-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathMicroCI.hs
380 lines (279 loc) · 8.2 KB
/
MicroCI.hs
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Paths_micro_ci
import qualified Config
import Config (Config)
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.STM.TQueue
import Control.Exception (try)
import Control.Monad
import Control.Monad.IO.Class
import Data.Aeson (FromJSON(..), withArray, eitherDecodeStrict)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Monoid
import Data.String
import qualified Data.Text as Text
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.IO as LT
import qualified Dhall
import GitHub.Data
import GitHub.Endpoints.Repos.Status
import Network.Wai.Handler.Warp as Warp
import Servant
import Servant.GitHub.Webhook
import Servant.Server
import System.Directory
import System.Exit
import System.FilePath
import System.Process
import qualified System.Process as Process
-- Job
data Job = Job
{ jobRepo :: Repo
, jobCommit :: Text.Text
, jobAttr :: AttrPath
}
doJob :: Config -> Job -> IO ()
doJob config job = do
ensureRepository config (jobRepo job)
checkoutRef config (jobRepo job) (jobCommit job)
buildRes <-
buildAttribute config (jobRepo job) (jobAttr job)
createStatus
(OAuth (fromString $ LT.unpack $ Config.oauth config))
(simpleOwnerLogin $ repoOwner (jobRepo job))
(repoName (jobRepo job))
(mkName (Proxy @Commit)
(jobCommit job))
NewStatus { newStatusState =
if buildSuccess buildRes then
Success
else
Failure
, newStatusTargetUrl =
Just $ URL $ Text.pack $
LT.unpack (Config.httpRoot config) ++ "/" ++ takeFileName (buildDerivation buildRes)
, newStatusDescription =
Just $
if buildSuccess buildRes then
"nix-build successful"
else
"nix-build failed"
, newStatusContext =
"ci.nix: " <> fromString (encodeAttrPath (jobAttr job))
}
return ()
-- buildAttribute
data BuildResult = BuildResult
{ buildSuccess :: Bool
, buildDerivation :: String
}
buildAttribute :: Config -> Repo -> AttrPath -> IO BuildResult
buildAttribute config repo path = do
(exitCode, stdout, stderr) <-
readCreateProcessWithExitCode
(inGitRepository config repo
(Process.proc "nix-instantiate"
["ci.nix"
, "-A"
, encodeAttrPath path
]))
""
drv <-
case lines stdout of
[drv] ->
return drv
_ ->
fail $ unlines $
[ "Colud not find .drv from nix-instantiate ci.nix:"
, ""
, stdout
, stderr
]
(exitCode, stdout, stderr) <-
readCreateProcessWithExitCode
(inGitRepository config repo
(Process.proc "nix-store" [ "--realise", drv ]))
""
createDirectoryIfMissing
True
(LT.unpack $ Config.logs config)
writeFile (LT.unpack (Config.logs config) </> takeFileName drv <.> "stdout") stdout
writeFile (LT.unpack (Config.logs config) </> takeFileName drv <.> "stderr") stderr
return BuildResult
{ buildSuccess =
case exitCode of
ExitSuccess ->
True
ExitFailure{} ->
False
, buildDerivation = drv
}
-- findJobAttrPaths
findJobAttrPaths :: Config -> Repo -> IO [AttrPath]
findJobAttrPaths config repo = do
jobsNixPath <-
getDataFileName "jobs.nix"
(exitCode, jobs, stderr) <-
readCreateProcessWithExitCode
(inGitRepository config repo
(Process.proc
"nix-instantiate"
[ "--eval"
, "--strict"
, "--json"
, "-E"
, "import " ++ jobsNixPath ++ " (import ./ci.nix)"
]))
""
unless (exitCode == ExitSuccess) $
fail $ unlines
[ "Could not identify jobs in ci.nix:"
, ""
, stderr
]
case eitherDecodeStrict (fromString jobs) of
Left e ->
fail $ unlines $
[ "Could not parse jobs JSON"
, ""
, "Aeson reported:"
, ""
, show e
, ""
, "I'm trying to parse:"
, ""
, jobs
]
Right paths ->
return paths
-- repoDir
repoDir :: Config -> Repo -> FilePath
repoDir config repo =
LT.unpack (Config.repoRoot config)
</> Text.unpack (untagName (simpleOwnerLogin (repoOwner repo)))
</> Text.unpack (untagName (repoName repo))
-- ensureRepository
-- | Ensure that a repository has been cloned into the repoRoot directory, and that
-- it is up-to-date.
ensureRepository :: Config -> Repo -> IO ()
ensureRepository cfg repo = do
let
dir =
repoDir cfg repo
exists <-
doesDirectoryExist dir
if exists then
void $
readCreateProcess
(inGitRepository cfg repo
(proc "git" [ "fetch" ]))
""
else do
URL cloneUrl <-
maybe
(fail (Text.unpack (untagName (repoName repo)) ++ " does not have a clone URL."))
return
(repoCloneUrl repo)
void $ readCreateProcess (proc "git" [ "clone", Text.unpack cloneUrl, dir ]) ""
checkoutRef :: Config -> Repo -> Text.Text -> IO ()
checkoutRef config repo ref =
void $
readCreateProcess
(inGitRepository config repo
(proc "git" [ "checkout", Text.unpack ref ]))
""
-- inGitRepository
inGitRepository :: Config -> Repo -> CreateProcess -> CreateProcess
inGitRepository config repo a =
a { cwd = Just (repoDir config repo) }
-- HttpApi
type HttpApi =
"github"
:> "web-hook"
:> GitHubEvent '[ 'WebhookPullRequestEvent ]
:> GitHubSignedReqBody '[JSON] PullRequestEvent
:> Post '[JSON] ()
:<|>
Capture "drv" Text.Text
:> Get '[PlainText] Text.Text
httpEndpoints :: TQueue PullRequestCommit -> Config -> Server HttpApi
httpEndpoints q config =
gitHubWebHookHandler q :<|> detailsHandler config
-- detailsHandler
detailsHandler :: Config-> Text.Text -> Handler Text.Text
detailsHandler config drvName = do
stdout <-
liftIO
$ readFile (LT.unpack (Config.logs config) </> Text.unpack drvName <.> "stdout")
stderr <-
liftIO
$ readFile (LT.unpack (Config.logs config) </> Text.unpack drvName <.> "stderr")
return (Text.pack $ unlines [ stdout, "", stderr ])
-- AttrPath
-- | An attribute path.
newtype AttrPath =
AttrPath [String]
deriving (FromJSON)
encodeAttrPath :: AttrPath -> String
encodeAttrPath (AttrPath parts) =
intercalate "." parts
-- gitHubWebHookHandler
-- | Top-level GitHub web hook handler. Ensures that a build is scheduled.
gitHubWebHookHandler :: TQueue PullRequestCommit -> RepoWebhookEvent -> ((), PullRequestEvent) -> Handler ()
gitHubWebHookHandler queue WebhookPullRequestEvent ((), ev) = do
liftIO $ atomically $
writeTQueue queue (pullRequestHead $ pullRequestEventPullRequest ev)
gitHubWebHookHandler _ _ _ =
return ()
-- processPullRequest
processPullRequest :: Config -> TQueue Job -> PullRequestCommit -> IO ()
processPullRequest config jobQueue pr = do
let
headRepo =
pullRequestCommitRepo pr
ensureRepository config headRepo
checkoutRef config headRepo (pullRequestCommitSha pr)
paths <-
findJobAttrPaths config headRepo
for_ paths $ \path ->
atomically $
writeTQueue
jobQueue
Job
{ jobRepo = headRepo
, jobCommit = pullRequestCommitSha pr
, jobAttr = path
}
-- main
main :: IO ()
main = do
config <-
LT.readFile "config.dhall"
>>= Dhall.input Dhall.auto
jobQueue <-
newTQueueIO
prQueue <-
newTQueueIO
forkIO $ forever $ do
job <-
atomically $ fmap Left (readTQueue prQueue) <|> fmap Right (readTQueue jobQueue)
--try $
case job of
Left pr ->
processPullRequest config jobQueue pr
Right job ->
doJob config job
Warp.run 8080
(serveWithContext
(Proxy @HttpApi)
(gitHubKey (return (fromString $ LT.unpack $ Config.secret config)) :. EmptyContext)
(httpEndpoints prQueue config))