This repository has been archived by the owner on Aug 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
handlers.go
471 lines (407 loc) · 11.2 KB
/
handlers.go
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/Sirupsen/logrus"
"github.com/crosbymichael/octokat"
"github.com/docker/leeroy/github"
"github.com/docker/leeroy/jenkins"
"github.com/pkg/errors"
)
func pingHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "pong")
return
}
func jenkinsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
logrus.Errorf("%q is not a valid method", r.Method)
w.WriteHeader(405)
return
}
// decode the body
decoder := json.NewDecoder(r.Body)
var j jenkins.Response
if err := decoder.Decode(&j); err != nil {
logrus.Errorf("decoding the jenkins request as json failed: %v", err)
return
}
logrus.Infof("Received Jenkins notification for %s %d (%s): %s", j.Name, j.Build.Number, j.Build.URL, j.Build.Phase)
// if the phase is not started or completed
// we don't care
if j.Build.Phase != "STARTED" && j.Build.Phase != "COMPLETED" {
return
}
// get the status for github
// and create a status description
desc := fmt.Sprintf("Jenkins build %s %d", j.Name, j.Build.Number)
var state string
if j.Build.Phase == "STARTED" {
state = "pending"
desc += " is running"
} else {
switch j.Build.Status {
case "SUCCESS":
state = "success"
desc += " has succeeded"
case "FAILURE":
state = "failure"
desc += " has failed"
case "UNSTABLE":
state = "failure"
desc += " was unstable"
case "ABORTED":
state = "error"
desc += " has encountered an error"
default:
logrus.Errorf("Did not understand %q build status. Aborting.", j.Build.Status)
return
}
}
// get the build
build, err := config.getBuildByJob(j.Name)
if err != nil {
logrus.Error(err)
return
}
// update the github status
if err := config.updateGithubStatus(j.Build.Parameters.GitBaseRepo, build.Context, j.Build.Parameters.GitSha, state, desc, j.Build.URL+"console"); err != nil {
logrus.Error(err)
return
}
/*
// if the build failed return get the build logs
if state == "failure" {
// setup the jenkins client
jc := &config.Jenkins
log, err := jc.GetBuildLog(j.Name, j.Build.Number)
if err != nil {
logrus.Errorf("requesting log for job %s and build %d failed: %v", j.Name, j.Build.Number, err)
return
}
// add comment to the PR
if err := config.addGithubComment(j.Build.Parameters.GitBaseRepo, j.Build.Parameters.PR, log); err != nil {
logrus.Error(err)
return
}
logrus.Infof("added comment to %s#%s", j.Build.Parameters.GitBaseRepo, j.Build.Parameters.PR)
}
if state == "success" {
// find the comments about failed builds and remove them
number, _ := strconv.Atoi(j.Build.Parameters.PR)
if err := config.removeFailedBuildComment(j.Build.Parameters.GitBaseRepo, j.Name, number); err != nil {
logrus.Error(err)
}
}
*/
return
}
func githubHandler(w http.ResponseWriter, r *http.Request) {
event := r.Header.Get("X-GitHub-Event")
switch event {
case "":
logrus.Error("Got GitHub notification without a type")
case "ping":
w.WriteHeader(200)
//case "issues", "issue_comment":
// handleIssue(w, r)
case "pull_request":
handlePullRequest(w, r)
//case "pull_request_review_comment":
// handlePullRequestReviewComment(w, r)
default:
logrus.Errorf("Got unknown GitHub notification event type: %s", event)
}
}
func handleIssue(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("Got an issue hook")
// parse the issue
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Errorf("Error reading github issue handler body: %v", err)
w.WriteHeader(500)
return
}
issueHook, err := octokat.ParseIssueHook(body)
if err != nil {
logrus.Errorf("Error parsing issue hook: %v", err)
w.WriteHeader(500)
return
}
// get the build
baseRepo := fmt.Sprintf("%s/%s", issueHook.Repo.Owner.Login, issueHook.Repo.Name)
logrus.Debugf("Issue is for repo: %s", baseRepo)
build, err := config.getBuildByContextAndRepo("janky", baseRepo)
if err != nil {
logrus.Warnf("could not find build for repo %s for issue handler, skipping: %v", baseRepo, err)
return
}
// if we do not handle issues for this build just return
if !build.HandleIssues {
logrus.Warnf("Not configured to handle issues for %s", baseRepo)
return
}
g := github.GitHub{
AuthToken: config.GHToken,
User: config.GHUser,
}
logrus.Infof("Received GitHub issue notification for %s %d (%s): %s", baseRepo, issueHook.Issue.Number, issueHook.Issue.URL, issueHook.Action)
// if it is not a comment or an opened issue
// return becuase we dont care
if !issueHook.IsComment() && !issueHook.IsOpened() {
logrus.Debugf("Ignoring issue hook action %q", issueHook.Action)
return
}
if issueHook.Issue.State != "open" {
return
}
if issueHook.Issue.PullRequest.HTMLURL != "" {
if err := g.MoveTriageForward(issueHook.Repo, issueHook.Issue.Number, issueHook.Comment); err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
w.WriteHeader(204)
return
}
// Try to label the issue with the version information it contains.
if err := g.IssueAddVersionLabel(issueHook); err != nil {
logrus.Errorf("Error applying version label to issue: %v", err)
w.WriteHeader(500)
return
}
// handle if it is an issue comment
// apply approproate labels
if err := g.LabelIssueComment(issueHook); err != nil {
logrus.Errorf("Error applying labels to issue comment: %v", err)
w.WriteHeader(500)
return
}
return
}
func handlePullRequest(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("Got a pull request hook")
// parse the pull request
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logrus.Errorf("Error reading github pull request handler body: %v", err)
w.WriteHeader(500)
return
}
prHook, err := octokat.ParsePullRequestHook(body)
if err != nil {
logrus.Errorf("Error parsing pull request hook: %v", err)
w.WriteHeader(500)
return
}
pr := prHook.PullRequest
baseRepo := fmt.Sprintf("%s/%s", pr.Base.Repo.Owner.Login, pr.Base.Repo.Name)
logrus.Infof("Received GitHub pull request notification for %s %d (%s): %s", baseRepo, pr.Number, pr.URL, prHook.Action)
// ignore everything we don't care about
if prHook.Action != "opened" && prHook.Action != "reopened" && prHook.Action != "synchronize" {
logrus.Debugf("Ignoring PR hook action %q", prHook.Action)
return
}
g := github.GitHub{
AuthToken: config.GHToken,
User: config.GHUser,
}
attempt, totalAttempts := 1, 5
delay := time.Second
retry:
pullRequest, err := g.LoadPullRequest(prHook)
if err != nil {
logrus.Errorf("Error loading the pull request (attempt %d/%d): %v", attempt, totalAttempts, err)
if attempt <= totalAttempts && errors.Cause(err).Error() == "Not Found" {
time.Sleep(delay)
attempt++
delay *= 2
goto retry
}
w.WriteHeader(500)
return
}
mergeable, err := g.IsMergeable(pullRequest)
if err != nil {
logrus.Errorf("Error checking if PR is mergeable: %v", err)
w.WriteHeader(500)
return
}
// PR is not mergeable, so don't start the build
if !mergeable {
logrus.Errorf("Unmergeable PR for %s #%d. Aborting build", baseRepo, pr.Number)
w.WriteHeader(200)
return
}
var builds []Build
// Only run full jobs if there are code related changes
if !pullRequest.Content.IsNonCodeOnly() {
// get the builds -- skip pipeline jobs though, they'll be scheduled automatically
var err error
builds, err = config.getBuilds(baseRepo, false, false)
if err != nil {
logrus.Warn(err)
}
}
// If there are doc-changes validate them
if pullRequest.Content.HasDocsChanges() {
build, err := config.getBuildByContextAndRepo("doc", baseRepo)
if err != nil {
logrus.Warnf("Adding doc build to %s for %d failed: %v", baseRepo, pr.Number, err)
} else {
builds = append(builds, build)
}
}
// If there are vendoring changes validate them
if pullRequest.Content.HasVendoringChanges() {
build, err := config.getBuildByContextAndRepo("vendor", baseRepo)
if err != nil {
logrus.Warnf("Adding vendor build to %s for %d failed: %v", baseRepo, pr.Number, err)
} else {
builds = append(builds, build)
}
}
// schedule the jenkins builds
for _, build := range builds {
// schedule the build
if err := config.scheduleJenkinsBuild(baseRepo, pr.Number, "", build); err != nil {
logrus.Error(err)
w.WriteHeader(500)
}
}
return
}
type requestBuild struct {
Number int `json:"number"`
Repo string `json:"repo"`
Context string `json:"context"`
Ref string `json:"ref"`
}
func customBuildHandler(w http.ResponseWriter, r *http.Request) {
// setup auth
user, pass, ok := r.BasicAuth()
if !ok {
w.WriteHeader(401)
return
}
if user != config.User && pass != config.Pass {
w.WriteHeader(401)
return
}
if r.Method != "POST" {
logrus.Errorf("%q is not a valid method", r.Method)
w.WriteHeader(405)
return
}
// decode the body
decoder := json.NewDecoder(r.Body)
var b requestBuild
if err := decoder.Decode(&b); err != nil {
logrus.Errorf("decoding the retry request as json failed: %v", err)
w.WriteHeader(500)
return
}
var (
builds []Build
err error
)
if b.Context == "all" || b.Context == "" {
// get all the builds
builds, err = config.getBuilds(b.Repo, false, true)
if err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
} else {
// get the build
build, err := config.getBuildByContextAndRepo(b.Context, b.Repo)
if err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
builds = append(builds, build)
}
// schedule the jenkins builds
for _, build := range builds {
if err := config.scheduleJenkinsBuild(b.Repo, b.Number, b.Ref, build); err != nil {
logrus.Error(err)
w.WriteHeader(500)
}
}
w.WriteHeader(204)
return
}
func cronBuildHandler(w http.ResponseWriter, r *http.Request) {
// setup auth
user, pass, ok := r.BasicAuth()
if !ok {
w.WriteHeader(401)
return
}
if user != config.User && pass != config.Pass {
w.WriteHeader(401)
return
}
if r.Method != "POST" {
logrus.Errorf("%q is not a valid method", r.Method)
w.WriteHeader(405)
return
}
// decode the body
decoder := json.NewDecoder(r.Body)
var b requestBuild
if err := decoder.Decode(&b); err != nil {
logrus.Errorf("decoding the retry request as json failed: %v", err)
w.WriteHeader(500)
return
}
// get the build
build, err := config.getBuildByContextAndRepo(b.Context, b.Repo)
if err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
// get PRs that have failed for the context
nums, err := config.getFailedPRs(b.Context, b.Repo)
if err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
for _, prNum := range nums {
// schedule the jenkins build
if err := config.scheduleJenkinsBuild(b.Repo, prNum, "", build); err != nil {
logrus.Error(err)
}
}
w.WriteHeader(204)
return
}
func handlePullRequestReviewComment(w http.ResponseWriter, r *http.Request) {
hook, err := github.ParsePullRequestReviewCommentHook(r.Body)
if err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
if !hook.IsOpen() {
w.WriteHeader(200)
return
}
g := github.GitHub{
AuthToken: config.GHToken,
User: config.GHUser,
}
if err := g.MoveTriageForward(hook.Repo, hook.PullRequest.Number, hook.Comment); err != nil {
logrus.Error(err)
w.WriteHeader(500)
return
}
w.WriteHeader(204)
return
}