/
webhook.go
326 lines (281 loc) · 10.2 KB
/
webhook.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
/*
Copyright 2017 caicloud authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package router
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
restful "github.com/emicklei/go-restful"
log "github.com/golang/glog"
"github.com/google/go-github/github"
"github.com/xanzy/go-gitlab"
"github.com/caicloud/cyclone/pkg/api"
gitlabuitl "github.com/caicloud/cyclone/pkg/util/gitlab"
httputil "github.com/caicloud/cyclone/pkg/util/http"
)
const (
// branchRefTemplate represents reference template for branches.
branchRefTemplate = "refs/heads/%s"
// tagRefTemplate represents reference template for tags.
tagRefTemplate = "refs/tags/%s"
// githubPullRefTemplate represents reference template for Github pull request.
githubPullRefTemplate = "refs/pull/%d/merge"
// gitlabMergeRefTemplate represents reference template for Gitlab merge request.
gitlabMergeRefTemplate = "refs/merge-requests/%d/head"
// gitlabEventTypeHeader represents the Gitlab header key used to pass the event type.
gitlabEventTypeHeader = "X-Gitlab-Event"
)
// handleGithubWebhook handles the webhook request from Github.
// 1. Parse the pipeline id from request path;
// 2. Get the pipeline by id;
// 3. Parse the payload from request header;
// 4. Parse the payload from request body;
// 5. First get the event type, and handle it according to its type.
func (router *router) handleGithubWebhook(request *restful.Request, response *restful.Response) {
pipelineID := request.PathParameter(pipelineIDPathParameterName)
pipeline, err := router.pipelineManager.GetPipelineByID(pipelineID)
if err != nil {
httputil.ResponseWithError(response, err)
return
}
if pipeline.AutoTrigger == nil || pipeline.AutoTrigger.SCMTrigger == nil {
httputil.ResponseWithError(response, fmt.Errorf("SCM auto trigger is not set"))
return
}
scmTrigger := pipeline.AutoTrigger.SCMTrigger
// TODO (robin) Validate the payload.
// Ref: https://github.com/google/go-github/blob/df47db1628185875602e66d3356ae7337b52bba3/github/messages.go#L213-L233
// github.ValidatePayload(request.Request, secretKey)
payload, err := ioutil.ReadAll(request.Request.Body)
if err != nil {
httputil.ResponseWithError(response, fmt.Errorf("Fail to read the request body"))
return
}
event, err := github.ParseWebHook(github.WebHookType(request.Request), payload)
if err != nil {
httputil.ResponseWithError(response, err)
return
}
log.Infof("Github webhook event: %v", event)
// Handle the event.
var performParams *api.PipelinePerformParams
switch event := event.(type) {
case *github.ReleaseEvent:
if scmTrigger.TagRelease == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Release trigger is not enabled")
return
}
performParams = &api.PipelinePerformParams{
Name: *event.Release.TagName,
Ref: fmt.Sprintf(tagRefTemplate, *event.Release.TagName),
Description: "Triggered by tag release",
Stages: scmTrigger.TagRelease.Stages,
}
log.Info("Triggered by Github release event")
case *github.PullRequestEvent:
// Only handle when the pull request are created.
if *event.Action != "opened" {
response.WriteHeaderAndEntity(http.StatusOK, "Only handle when pull request is created")
return
}
if scmTrigger.PullRequest == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Pull request trigger is not enabled")
return
}
performParams = &api.PipelinePerformParams{
Ref: fmt.Sprintf(githubPullRefTemplate, *event.PullRequest.Number),
Description: "Triggered by pull request",
Stages: scmTrigger.PullRequest.Stages,
}
log.Info("Triggered by Github pull request event")
case *github.IssueCommentEvent:
if event.Issue.PullRequestLinks == nil {
log.Infof("Only handle when issues type is pull request")
response.WriteHeaderAndEntity(http.StatusOK, "Only handle when issues type is pull request")
return
}
// Only handle when the pull request comments are created.
if *event.Action != "created" {
response.WriteHeaderAndEntity(http.StatusOK, "Only handle when pull request comment is created")
return
}
if scmTrigger.PullRequestComment == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Pull request comment trigger is not enabled")
return
}
comment := event.Comment
trigger := false
if comment != nil {
for _, c := range scmTrigger.PullRequestComment.Comments {
if *comment.Body == c {
trigger = true
break
}
}
}
if trigger {
performParams = &api.PipelinePerformParams{
Ref: fmt.Sprintf(githubPullRefTemplate, *event.Issue.Number),
Description: "Triggered by pull request comments",
Stages: scmTrigger.PullRequestComment.Stages,
}
log.Info("Triggered by Github pull request review comment event")
}
case *github.PushEvent:
if scmTrigger.Push == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Push trigger is not enabled")
return
}
performParams = &api.PipelinePerformParams{
Ref: fmt.Sprintf(*event.Ref),
Description: "Triggered by push",
Stages: scmTrigger.Push.Stages,
}
log.Info("Triggered by Github push event")
default:
log.Errorf("event type not support.")
}
if performParams != nil {
pipelineRecord := &api.PipelineRecord{
Name: performParams.Name,
PipelineID: pipeline.ID,
PerformParams: performParams,
Trigger: api.TriggerSCM,
}
if _, err = router.pipelineRecordManager.CreatePipelineRecord(pipelineRecord); err != nil {
httputil.ResponseWithError(response, err)
return
}
response.WriteHeaderAndEntity(http.StatusOK, "Successfully triggered")
} else {
response.WriteHeaderAndEntity(http.StatusOK, "Is ignored")
}
}
// handleGitlabWebhook handles the webhook request from Gitlab.
// 1. Parse the pipeline id from request path;
// 2. Get the pipeline by id;
// 3. Parse the payload from request header;
// 4. Parse the payload from request body;
// 5. First get the event type, and handle it according to its type.
func (router *router) handleGitlabWebhook(request *restful.Request, response *restful.Response) {
pipelineID := request.PathParameter(pipelineIDPathParameterName)
pipeline, err := router.pipelineManager.GetPipelineByID(pipelineID)
if err != nil {
httputil.ResponseWithError(response, err)
return
}
if pipeline.AutoTrigger == nil || pipeline.AutoTrigger.SCMTrigger == nil {
httputil.ResponseWithError(response, fmt.Errorf("SCM auto trigger is not set"))
return
}
scmTrigger := pipeline.AutoTrigger.SCMTrigger
// TODO (robin) Validate the payload.
// Ref: https://github.com/google/go-github/blob/df47db1628185875602e66d3356ae7337b52bba3/github/messages.go#L213-L233
// github.ValidatePayload(request.Request, secretKey)
event, err := gitlabuitl.ParseWebHook(request.Request)
if err != nil {
httputil.ResponseWithError(response, err)
return
}
log.Infof("Gitlab webhook event: %v", event)
// Handle the event.
var performParams *api.PipelinePerformParams
switch event := event.(type) {
case *gitlab.TagEvent:
if scmTrigger.TagRelease == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Release trigger is not enabled")
return
}
performParams = &api.PipelinePerformParams{
Name: strings.Split(event.Ref, "/")[2],
Ref: event.Ref,
Description: "Triggered by tag release",
Stages: scmTrigger.TagRelease.Stages,
}
log.Info("Triggered by Gitlab tag event")
case *gitlab.MergeEvent:
// Only handle when the pull request are created.
objectAttributes := event.ObjectAttributes
if objectAttributes.Action != "open" {
response.WriteHeaderAndEntity(http.StatusOK, "Only handle when merge request is created")
return
}
if scmTrigger.PullRequest == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Pull request trigger is not enabled")
return
}
performParams = &api.PipelinePerformParams{
Ref: fmt.Sprintf(gitlabMergeRefTemplate, objectAttributes.Iid),
Description: objectAttributes.Title,
Stages: scmTrigger.PullRequest.Stages,
}
log.Info("Triggered by Gitlab merge event")
case *gitlabuitl.MergeCommentEvent:
if event.MergeRequest == nil {
log.Infof("Only handle comments on merge request")
response.WriteHeaderAndEntity(http.StatusOK, "Only handle comments on merge request")
return
}
if scmTrigger.PullRequestComment == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Pull request comment trigger is not enabled")
return
}
objectAttributes := event.ObjectAttributes
trigger := false
if objectAttributes.Note != "" {
for _, c := range scmTrigger.PullRequestComment.Comments {
if objectAttributes.Note == c {
trigger = true
break
}
}
}
if trigger {
performParams = &api.PipelinePerformParams{
Ref: fmt.Sprintf(gitlabMergeRefTemplate, event.MergeRequest.IID),
Description: "Triggered by pull request comments",
Stages: scmTrigger.PullRequestComment.Stages,
}
log.Info("Triggered by Gitlab merge comment event")
}
case *gitlab.PushEvent:
if scmTrigger.Push == nil {
response.WriteHeaderAndEntity(http.StatusOK, "Push trigger is not enabled")
return
}
performParams = &api.PipelinePerformParams{
Ref: event.Ref,
Description: "Triggered by push",
Stages: scmTrigger.Push.Stages,
}
log.Info("Triggered by Gitlab push event")
default:
log.Errorf("event type not support.")
}
if performParams != nil {
pipelineRecord := &api.PipelineRecord{
Name: performParams.Name,
PipelineID: pipeline.ID,
PerformParams: performParams,
Trigger: api.TriggerSCM,
}
if _, err = router.pipelineRecordManager.CreatePipelineRecord(pipelineRecord); err != nil {
httputil.ResponseWithError(response, err)
return
}
response.WriteHeaderAndEntity(http.StatusOK, "Successfully triggered")
} else {
response.WriteHeaderAndEntity(http.StatusOK, "Is ignored")
}
}