1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NoFieldSelectors #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module Main where
import Control.Arrow ((***))
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.ByteString.Lazy qualified as LB
import Data.ByteString.UTF8 qualified as B (fromString, toString)
import Data.List
import Data.List.Split
import Data.Map.Merge.Strict qualified as M
import Data.Map.Strict qualified as M
import Data.Maybe
import Data.String
import Data.String.Interpolate (i)
import Data.Tagged
import Data.Text qualified as T
import Debug.Trace
import Git
import Git.Libgit2
import Prettyprinter
import Prettyprinter.Render.Terminal
import System.Directory
import System.Environment
import System.FilePath
import System.INotify
import System.IO
import System.IO.Temp
import System.IO.Unsafe
import System.Process (CmdSpec (..))
import System.Process.Typed
import System.Process.Typed.Internal
import Text.Printf
stateDirectory :: FilePath
stateDirectory = unsafePerformIO (getEnv "ABUILDER_STATE")
ref :: String
ref = fromMaybe "main" (unsafePerformIO (lookupEnv "ABUILDER_BRANCH"))
type JobName = String
type Url = FilePath
urls :: M.Map JobName Url
urls =
M.fromList . map ((,) <$> takeBaseName <*> id) $
splitOn ":" (unsafePerformIO (getEnv "ABUILDER_URLS"))
concurrentBuilders :: Int
concurrentBuilders = 2
logLevel :: Importance
logLevel =
maybe Info (toEnum . read) $
unsafePerformIO (lookupEnv "ABUILDER_LOG_LEVEL")
type DesiredOutputs = M.Map JobName CommitHash
type CommitHash = String
type ActualOutputs = M.Map JobName CommitHash
data BuildJobs = BuildJobs
{ pendingBuilds :: M.Map JobName CommitHash,
runningBuilds :: M.Map JobName CommitHash
}
deriving (Show)
diff :: DesiredOutputs -> ActualOutputs -> BuildJobs
diff desiredOutputs actualOutputs =
BuildJobs
{ pendingBuilds =
M.merge
M.preserveMissing
M.dropMissing
( M.zipWithMaybeMatched
( \_ actualCommit desiredCommit ->
if desiredCommit /= actualCommit
then Just desiredCommit
else Nothing
)
)
desiredOutputs
actualOutputs,
runningBuilds = M.empty
}
replaceBuildJobs :: BuildJobs -> BuildJobs -> BuildJobs
replaceBuildJobs oldBuildJobs newBuildJobs =
BuildJobs
{ pendingBuilds =
M.differenceWithKey
( \_ pendingCommit runningCommit ->
if pendingCommit /= runningCommit
then Just pendingCommit
else Nothing
)
newBuildJobs.pendingBuilds
oldBuildJobs.runningBuilds,
runningBuilds = oldBuildJobs.runningBuilds
}
data BuildJob = BuildJob
{ jobName :: JobName,
commitHash :: CommitHash
}
deriving (Show)
obtainBuildJob :: BuildJobs -> (Maybe BuildJob, BuildJobs)
obtainBuildJob buildJobs = do
case uncurry BuildJob <$> M.lookupMin buildJobs.pendingBuilds of
Just buildJob@(BuildJob {jobName, commitHash}) ->
( Just buildJob,
buildJobs
{ pendingBuilds = M.delete jobName buildJobs.pendingBuilds,
runningBuilds = M.insert jobName commitHash buildJobs.runningBuilds
}
)
Nothing ->
(Nothing, buildJobs)
completeBuildJob :: BuildJob -> BuildJobs -> BuildJobs
completeBuildJob (BuildJob {jobName, commitHash}) buildJobs =
buildJobs
{ runningBuilds =
M.filterWithKey
( \jobName' commitHash' ->
jobName' /= jobName || commitHash' /= commitHash
)
buildJobs.runningBuilds
}
data Builder = Builder Int
deriving (Show)
data LogEntry = LogEntry
{ component :: String,
importance :: Importance,
message :: Doc AnsiStyle
}
deriving (Show)
data Importance
= Error
| Info
| Warning
| Debug
deriving (Show, Eq, Ord, Enum)
main :: IO ()
main = do
hSetBuffering stderr LineBuffering
hSetBuffering stdout LineBuffering
inotify <- initINotify
desiredOutputsT <- newTVarIO M.empty
actualOutputsT <- newTVarIO M.empty
buildJobsT <- newTVarIO (BuildJobs M.empty M.empty)
logs <- newTQueueIO
createDirectoryIfMissing True stateDirectory
setCurrentDirectory stateDirectory
mapM_
(\_ -> forkIO (builder logs buildJobsT))
(map Builder [1 .. concurrentBuilders])
mapM_ (uncurry (watch inotify logs desiredOutputsT)) (M.toList urls)
_ <- forkIO (scheduler desiredOutputsT actualOutputsT buildJobsT)
forever do
log <- atomically $ readTQueue logs
case log of
LogEntry {component, message, importance} ->
when (importance <= logLevel) do
let c = case importance of
Error -> Red
Info -> White
Warning -> Yellow
Debug -> Black
putDoc . annotate (color c) $
annotate bold (brackets (pretty component))
<+> message <> hardline
scheduler ::
TVar DesiredOutputs ->
TVar ActualOutputs ->
TVar BuildJobs ->
IO ()
scheduler desiredOutputsT actualOutputsT buildJobsT = do
lastDesiredOutputsT <- newTVarIO Nothing
forever $ atomically do
lastDesiredOutputs <- readTVar lastDesiredOutputsT
desiredOutputs <- readTVar desiredOutputsT
check (Just desiredOutputs /= lastDesiredOutputs)
actualOutputs <- readTVar actualOutputsT
let buildJobs' = diff desiredOutputs actualOutputs
buildJobs <- readTVar buildJobsT
writeTVar buildJobsT (replaceBuildJobs buildJobs buildJobs')
writeTVar lastDesiredOutputsT (Just desiredOutputs)
builder :: TQueue LogEntry -> TVar BuildJobs -> IO ()
builder logs buildJobsT =
forever
( do
buildJob <- atomically do
buildJobs <- readTVar buildJobsT
let (maybeBuildJob, buildJobs') = obtainBuildJob buildJobs
check (isJust maybeBuildJob)
writeTVar buildJobsT buildJobs'
pure (fromJust maybeBuildJob)
build logs buildJob
`catch` ( \(e :: SomeException) -> do
print e
)
)
build :: TQueue LogEntry -> BuildJob -> IO ()
build logs (BuildJob {jobName, commitHash}) = do
let url = urls M.! jobName
rev = commitHash
refDir = jobName </> ref
tmpDir = jobName <> "-" <> rev
log_ logs jobName Info [printf "building commit %s" rev]
exitCodeT <- newEmptyTMVarIO
_ <-
flip forkFinally (atomically . putTMVar exitCodeT) do
withSystemTempDirectory tmpDir $ \tmpDir -> do
writeFile (tmpDir </> "default.nix") $
[i|
import
(fetchGit {
url = "#{url}";
ref = "#{ref}";
rev = "#{rev}";
})
|]
drv <- sh logs jobName (setWorkingDir tmpDir "nix-instantiate")
res <-
sh logs jobName . setWorkingDir tmpDir $
fromString (printf "nix-store --realise '%s'" drv)
pure res
exitCode <- atomically $ takeTMVar exitCodeT
case exitCode of
Left e -> do
log_ logs jobName Error [printf "failed to build commit %s" rev]
throw e
Right nixDir -> do
log_ logs jobName Info [printf "built commit %s" rev]
createDirectoryIfMissing True jobName
runProcess_ (fromString (printf ">/dev/null nix-store --add-root '%s' --realise '%s'" refDir nixDir))
watch ::
INotify ->
TQueue LogEntry ->
TVar DesiredOutputs ->
JobName ->
Url ->
IO ()
watch inotify logs desiredOutputsT jobName url = do
let bareFp = url </> "refs/heads"
nonBareFp = url </> ".git/refs/heads"
isBare <- doesDirectoryExist bareFp
_ <- addWatch
inotify
[ Modify,
MoveIn
]
(B.fromString (if isBare then bareFp else nonBareFp))
$ \e -> do
let isChange =
case e of
System.INotify.Modified _ (Just (B.toString -> filePath)) -> filePath == ref
System.INotify.MovedIn False (B.toString -> filePath) _ -> filePath == ref
_ -> False
when isChange do
updateDesiredOutputs
log_ logs jobName Info [printf "watching %s" url]
updateDesiredOutputs
where
updateDesiredOutputs = do
rev <- withRepository lgFactory url do
Just cid <- resolveReference ("refs/heads/" <> T.pack ref)
show . untag . (.commitOid) <$> lookupCommit (Tagged cid)
atomically do
desiredOutputs <- readTVar desiredOutputsT
writeTVar desiredOutputsT (M.insert jobName rev desiredOutputs)
log_ logs jobName Info [printf "queueing commit %s" rev]
log_ :: TQueue LogEntry -> String -> Importance -> [String] -> IO ()
log_ logs component importance messages = atomically do
mapM_
( writeTQueue logs
. LogEntry component importance
. pretty
)
messages
sh ::
TQueue LogEntry ->
String ->
ProcessConfig stdin stdoutIgnored stderrIgnored ->
IO String
sh logs component proc = do
log_ logs component Debug $
[ printf
"+ %s"
( case proc.pcCmdSpec of
RawCommand bin args -> intercalate " " (bin : args)
ShellCommand s -> s
)
]
(out, err) <-
( B.toString . B.strip . LB.toStrict
*** map (B.toString . B.strip) . B.lines . LB.toStrict
)
<$> readProcess_ proc
log_ logs component Warning err
pure out
debug :: Show a => String -> a -> a
debug s x =
trace (printf "%s: %s\n" s (show x)) x
|