-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.go
More file actions
405 lines (385 loc) · 16.2 KB
/
Copy pathmain.go
File metadata and controls
405 lines (385 loc) · 16.2 KB
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
package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
lmbda "github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/sqs"
)
// AutoGenerated is the github webhook event payload
type AutoGenerated struct {
Action string `json:"action"`
CheckRun struct {
ID int `json:"id"`
NodeID string `json:"node_id"`
HeadSha string `json:"head_sha"`
ExternalID string `json:"external_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
DetailsURL string `json:"details_url"`
Status string `json:"status"`
Conclusion interface{} `json:"conclusion"`
StartedAt time.Time `json:"started_at"`
CompletedAt interface{} `json:"completed_at"`
Output struct {
Title interface{} `json:"title"`
Summary interface{} `json:"summary"`
Text interface{} `json:"text"`
AnnotationsCount int `json:"annotations_count"`
AnnotationsURL string `json:"annotations_url"`
} `json:"output"`
Name string `json:"name"`
CheckSuite struct {
ID int `json:"id"`
NodeID string `json:"node_id"`
HeadBranch string `json:"head_branch"`
HeadSha string `json:"head_sha"`
Status string `json:"status"`
Conclusion interface{} `json:"conclusion"`
URL string `json:"url"`
Before string `json:"before"`
After string `json:"after"`
PullRequests []interface{} `json:"pull_requests"`
App struct {
ID int `json:"id"`
Slug string `json:"slug"`
NodeID string `json:"node_id"`
Owner struct {
Login string `json:"login"`
ID int `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"owner"`
Name string `json:"name"`
Description string `json:"description"`
ExternalURL string `json:"external_url"`
HTMLURL string `json:"html_url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Permissions struct {
Actions string `json:"actions"`
Checks string `json:"checks"`
Contents string `json:"contents"`
Deployments string `json:"deployments"`
Issues string `json:"issues"`
Metadata string `json:"metadata"`
Packages string `json:"packages"`
Pages string `json:"pages"`
PullRequests string `json:"pull_requests"`
RepositoryHooks string `json:"repository_hooks"`
RepositoryProjects string `json:"repository_projects"`
SecurityEvents string `json:"security_events"`
Statuses string `json:"statuses"`
VulnerabilityAlerts string `json:"vulnerability_alerts"`
} `json:"permissions"`
Events []string `json:"events"`
} `json:"app"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
} `json:"check_suite"`
App struct {
ID int `json:"id"`
Slug string `json:"slug"`
NodeID string `json:"node_id"`
Owner struct {
Login string `json:"login"`
ID int `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"owner"`
Name string `json:"name"`
Description string `json:"description"`
ExternalURL string `json:"external_url"`
HTMLURL string `json:"html_url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Permissions struct {
Actions string `json:"actions"`
Checks string `json:"checks"`
Contents string `json:"contents"`
Deployments string `json:"deployments"`
Issues string `json:"issues"`
Metadata string `json:"metadata"`
Packages string `json:"packages"`
Pages string `json:"pages"`
PullRequests string `json:"pull_requests"`
RepositoryHooks string `json:"repository_hooks"`
RepositoryProjects string `json:"repository_projects"`
SecurityEvents string `json:"security_events"`
Statuses string `json:"statuses"`
VulnerabilityAlerts string `json:"vulnerability_alerts"`
} `json:"permissions"`
Events []string `json:"events"`
} `json:"app"`
PullRequests []interface{} `json:"pull_requests"`
} `json:"check_run"`
Repository struct {
ID int `json:"id"`
NodeID string `json:"node_id"`
Name string `json:"name"`
FullName string `json:"full_name"`
Private bool `json:"private"`
Owner struct {
Login string `json:"login"`
ID int `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"owner"`
HTMLURL string `json:"html_url"`
Description string `json:"description"`
Fork bool `json:"fork"`
URL string `json:"url"`
ForksURL string `json:"forks_url"`
KeysURL string `json:"keys_url"`
CollaboratorsURL string `json:"collaborators_url"`
TeamsURL string `json:"teams_url"`
HooksURL string `json:"hooks_url"`
IssueEventsURL string `json:"issue_events_url"`
EventsURL string `json:"events_url"`
AssigneesURL string `json:"assignees_url"`
BranchesURL string `json:"branches_url"`
TagsURL string `json:"tags_url"`
BlobsURL string `json:"blobs_url"`
GitTagsURL string `json:"git_tags_url"`
GitRefsURL string `json:"git_refs_url"`
TreesURL string `json:"trees_url"`
StatusesURL string `json:"statuses_url"`
LanguagesURL string `json:"languages_url"`
StargazersURL string `json:"stargazers_url"`
ContributorsURL string `json:"contributors_url"`
SubscribersURL string `json:"subscribers_url"`
SubscriptionURL string `json:"subscription_url"`
CommitsURL string `json:"commits_url"`
GitCommitsURL string `json:"git_commits_url"`
CommentsURL string `json:"comments_url"`
IssueCommentURL string `json:"issue_comment_url"`
ContentsURL string `json:"contents_url"`
CompareURL string `json:"compare_url"`
MergesURL string `json:"merges_url"`
ArchiveURL string `json:"archive_url"`
DownloadsURL string `json:"downloads_url"`
IssuesURL string `json:"issues_url"`
PullsURL string `json:"pulls_url"`
MilestonesURL string `json:"milestones_url"`
NotificationsURL string `json:"notifications_url"`
LabelsURL string `json:"labels_url"`
ReleasesURL string `json:"releases_url"`
DeploymentsURL string `json:"deployments_url"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
PushedAt time.Time `json:"pushed_at"`
GitURL string `json:"git_url"`
SSHURL string `json:"ssh_url"`
CloneURL string `json:"clone_url"`
SvnURL string `json:"svn_url"`
Homepage interface{} `json:"homepage"`
Size int `json:"size"`
StargazersCount int `json:"stargazers_count"`
WatchersCount int `json:"watchers_count"`
Language string `json:"language"`
HasIssues bool `json:"has_issues"`
HasProjects bool `json:"has_projects"`
HasDownloads bool `json:"has_downloads"`
HasWiki bool `json:"has_wiki"`
HasPages bool `json:"has_pages"`
ForksCount int `json:"forks_count"`
MirrorURL interface{} `json:"mirror_url"`
Archived bool `json:"archived"`
Disabled bool `json:"disabled"`
OpenIssuesCount int `json:"open_issues_count"`
License interface{} `json:"license"`
Forks int `json:"forks"`
OpenIssues int `json:"open_issues"`
Watchers int `json:"watchers"`
DefaultBranch string `json:"default_branch"`
} `json:"repository"`
Sender struct {
Login string `json:"login"`
ID int `json:"id"`
NodeID string `json:"node_id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"sender"`
}
// RunnerEvent is the event passed to the lambda-github-runner
type RunnerEvent struct {
QueueURL string `json:"queue_url"`
RepoURL string `json:"repo_url"`
RepoFullName string `json:"repo_fullname"`
Token string `json:"token"`
VirtualID string `json:"virtual_id"`
Event string `json:"event"`
}
func TriggerRunner(payloadEvent RunnerEvent) error {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
payload, _ := json.Marshal(&payloadEvent)
client := lmbda.New(sess, &aws.Config{Region: aws.String("us-east-1")})
_, err := client.Invoke(&lmbda.InvokeInput{FunctionName: aws.String("lambda-github-runner"), InvocationType: aws.String("Event"), Payload: payload})
return err
}
// HandleRequest handles Lambda Request
func HandleRequest(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fmt.Println(req.Body)
deliveryID := req.Headers["X-GitHub-Delivery"]
fmt.Printf("Delivery ID - %s\n", deliveryID)
fmt.Printf("Event - %s\n", req.Headers["X-GitHub-Event"])
// Only care about "check_run"/"ping" events
if req.Headers["X-GitHub-Event"] != "check_run" && req.Headers["X-GitHub-Event"] != "ping" {
return events.APIGatewayProxyResponse{StatusCode: 404}, nil
}
// if a github webhook secret it provided, require the check
if os.Getenv("GITHUB_WEBHOOK_SECRET") != "" {
secretKey := []byte(os.Getenv("GITHUB_WEBHOOK_SECRET"))
sha256Header := req.Headers["X-Hub-Signature-256"]
sha256HeaderParts := strings.SplitN(sha256Header, "=", 2)
buf, err := hex.DecodeString(sha256HeaderParts[1])
if err != nil {
fmt.Errorf("Error decoding signature %q: %w", sha256Header, err)
return events.APIGatewayProxyResponse{StatusCode: 400, Body: "Error decoding signature"}, nil
}
hashFunc := sha256.New
mac := hmac.New(hashFunc, secretKey)
mac.Write([]byte(req.Body))
ms := mac.Sum(nil)
if !hmac.Equal(buf, ms) {
fmt.Errorf("Payload signature check failed")
return events.APIGatewayProxyResponse{StatusCode: 417, Body: "Payload signature check failed"}, nil
}
}
data := AutoGenerated{}
json.Unmarshal([]byte(req.Body), &data)
virtualQueue := data.Repository.Name + strconv.Itoa(data.CheckRun.ID)
queueURL := os.Getenv("SQS_QUEUE_URL")
if queueURL == "" {
fmt.Println("No SQS Queue URL is configured")
return events.APIGatewayProxyResponse{StatusCode: 400, Body: "No SQS Queue URL is configured"}, nil
}
// If ping, send different event
if req.Headers["X-GitHub-Event"] == "ping" {
// Create new lambda
payloadEvent := RunnerEvent{
QueueURL: queueURL + "#" + virtualQueue,
RepoURL: data.Repository.HTMLURL,
RepoFullName: data.Repository.FullName,
Token: os.Getenv("GITHUB_TOKEN"),
VirtualID: virtualQueue,
Event: "create",
}
err := TriggerRunner(payloadEvent)
if err != nil {
fmt.Println("Error calling lambda-github-runner", err)
return events.APIGatewayProxyResponse{StatusCode: 400, Body: "Unable to start runner"}, nil
}
fmt.Println("lambda-github-runner triggered")
return events.APIGatewayProxyResponse{StatusCode: 200, Body: "Setting up default runner"}, nil
}
if data.Action == "created" || data.Action == "rerequested" {
// Create new lambda
payloadEvent := RunnerEvent{
QueueURL: queueURL + "#" + virtualQueue,
RepoURL: data.Repository.HTMLURL,
RepoFullName: data.Repository.FullName,
Token: os.Getenv("GITHUB_TOKEN"),
VirtualID: virtualQueue,
Event: "default",
}
err := TriggerRunner(payloadEvent)
if err != nil {
fmt.Println("Error calling lambda-github-runner", err)
return events.APIGatewayProxyResponse{StatusCode: 400, Body: "Unable to start runner"}, nil
}
fmt.Println("lambda-github-runner triggered")
} else if data.Action == "completed" {
// Stop lambda
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := sqs.New(sess)
sr, err := svc.SendMessage(&sqs.SendMessageInput{
DelaySeconds: aws.Int64(0),
MessageBody: aws.String(virtualQueue),
QueueUrl: aws.String(queueURL + "#" + virtualQueue),
})
if err != nil {
fmt.Println("Error sending message to virtual queue", err)
return events.APIGatewayProxyResponse{StatusCode: 400, Body: "Error sending message to virtual queue"}, nil
}
fmt.Println("Message send to SQS")
fmt.Println(sr)
} else {
fmt.Printf("Unknown action - %s\n", data.Action)
return events.APIGatewayProxyResponse{StatusCode: 412, Body: "Unknown action"}, nil
}
return events.APIGatewayProxyResponse{StatusCode: 204}, nil
}
func main() {
lambda.Start(HandleRequest)
}