forked from ocharles/micro-ci
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMicroCI.hs
390 lines (294 loc) · 9.5 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
381
382
383
384
385
386
387
388
389
390
{-# 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(..), fromJSON, Value(..), Object, withArray, eitherDecodeStrict)
import qualified Data.Aeson.Types as A
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
{ jobRepoOwner :: Text.Text
, jobRepoProject :: Text.Text
, jobCommit :: Text.Text
, jobAttr :: AttrPath
}
doJob :: Config -> Job -> IO ()
doJob config job = do
ensureRepository config (jobRepoOwner job) (jobRepoProject job)
checkoutRef config (jobRepoOwner job) (jobRepoProject job) (jobCommit job)
buildRes <-
buildAttribute config (jobRepoOwner job) (jobRepoProject job) (jobAttr job)
createStatus
(OAuth (fromString $ LT.unpack $ Config.oauth config))
(mkName (Proxy @Owner) (jobRepoOwner job))
(mkName (Proxy @Repo) (jobRepoProject 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 -> Text.Text -> Text.Text -> AttrPath -> IO BuildResult
buildAttribute config owner project path = do
(exitCode, stdout, stderr) <-
readCreateProcessWithExitCode
(inGitRepository config owner project
(Process.proc "nix-instantiate"
["ci.nix"
, "-A"
, encodeAttrPath path
]))
""
drv <-
case lines stdout of
[drv] ->
return drv
_ ->
fail $ unlines $
[ "Could not find .drv from nix-instantiate ci.nix:"
, ""
, stdout
, stderr
]
(exitCode, stdout, stderr) <-
readCreateProcessWithExitCode
(inGitRepository config owner project
(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 -> Text.Text -> Text.Text -> IO [AttrPath]
findJobAttrPaths config owner project = do
jobsNixPath <-
getDataFileName "jobs.nix"
(exitCode, jobs, stderr) <-
readCreateProcessWithExitCode
(inGitRepository config owner project
(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 -> Text.Text -> Text.Text -> FilePath
repoDir config owner project =
LT.unpack (Config.repoRoot config)
</> Text.unpack owner
</> Text.unpack project
-- ensureRepository
-- | Ensure that a repository has been cloned into the repoRoot directory, and that
-- it is up-to-date.
ensureRepository :: Config -> Text.Text -> Text.Text -> IO ()
ensureRepository cfg owner project = do
let
dir =
repoDir cfg owner project
exists <-
doesDirectoryExist dir
if exists then
void $
readCreateProcess
(inGitRepository cfg owner project
(proc "git" [ "fetch" ]))
""
else do
let cloneUrl = "https://github.com/" <> owner <> "/" <> project <> ".git"
void $ readCreateProcess (proc "git" [ "clone", Text.unpack cloneUrl, dir ]) ""
checkoutRef :: Config -> Text.Text -> Text.Text -> Text.Text -> IO ()
checkoutRef config owner project ref =
void $
readCreateProcess
(inGitRepository config owner project
(proc "git" [ "checkout", Text.unpack ref ]))
""
-- inGitRepository
inGitRepository :: Config -> Text.Text -> Text.Text -> CreateProcess -> CreateProcess
inGitRepository config owner project a =
a { cwd = Just (repoDir config owner project) }
-- HttpApi
type HttpApi =
"github"
:> "web-hook"
:> GitHubEvent '[ 'WebhookPingEvent
, 'WebhookPushEvent
, 'WebhookCreateEvent
, 'WebhookPullRequestEvent
]
:> GitHubSignedReqBody '[JSON] Object
:> Post '[JSON] ()
:<|>
Capture "drv" Text.Text
:> Get '[PlainText] Text.Text
httpEndpoints :: TQueue (Text.Text, Text.Text, Text.Text) -> 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 (Text.Text, Text.Text, Text.Text) -> RepoWebhookEvent -> ((), Object) -> Handler ()
gitHubWebHookHandler queue WebhookPullRequestEvent ((), obj)
| A.Success ev <- fromJSON (Object obj) = do
let prCommit = pullRequestHead (pullRequestEventPullRequest ev)
sha = pullRequestCommitSha prCommit
repo = pullRequestCommitRepo prCommit
liftIO $ atomically $
writeTQueue queue
( untagName $ simpleOwnerLogin (repoOwner repo)
, untagName $ repoName repo
, sha
)
gitHubWebHookHandler queue WebhookPushEvent ((), obj) = do
let mcommit = A.parse (flip A.parseField "head_commit" >=> flip A.parseField "id" . asObj) obj
mrepo = A.parse (flip A.parseField "repository" >=> parseRepo) obj
case (,) <$> mcommit <*> mrepo of
A.Error str -> liftIO . putStrLn $ "Error: " ++ str
A.Success (commitSha, (owner, project)) -> liftIO . atomically $
writeTQueue queue (owner, project, commitSha)
where asObj obj = obj :: Object
parseRepo o = (,) <$> (flip A.parseField "owner" >=> flip A.parseField "name" . asObj) o
<*> flip A.parseField "name" o
gitHubWebHookHandler _ _ _ = return ()
-- processCommit
processCommit :: Config -> TQueue Job -> (Text.Text, Text.Text, Text.Text) -> IO ()
processCommit config jobQueue (owner, project, commitsha) = do
ensureRepository config owner project
checkoutRef config owner project commitsha
paths <- findJobAttrPaths config owner project
for_ paths $ \path ->
atomically $
writeTQueue
jobQueue
Job
{ jobRepoOwner = owner
, jobRepoProject = project
, jobCommit = commitsha
, 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 commitData ->
processCommit config jobQueue commitData
Right job ->
doJob config job
Warp.run 8080
(serveWithContext
(Proxy @HttpApi)
(gitHubKey (return (fromString $ LT.unpack $ Config.secret config)) :. EmptyContext)
(httpEndpoints prQueue config))