forked from openfaas/openfaas-cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
306 lines (252 loc) · 8.77 KB
/
handler.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
package function
import (
"context"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/alexellis/derek/auth"
"github.com/alexellis/derek/factory"
"github.com/alexellis/hmac"
"github.com/google/go-github/github"
"github.com/openfaas/openfaas-cloud/sdk"
)
const (
defaultPrivateKeyName = "private-key"
defaultSecretMountPath = "/var/openfaas/secrets"
githubCheckCompleted = "completed"
githubCheckQueued = "queued"
githubConclusionFailure = "failure"
githubConclusionSuccess = "success"
githubConclusionNeutral = "neutral"
)
var (
token = ""
)
// Handle reports the building process of the
// function along with the function stack by sending
// commit statuses to GitHub on pending, failure or success
func Handle(req []byte) string {
if sdk.HmacEnabled() {
key, keyErr := sdk.ReadSecret("payload-secret")
if keyErr != nil {
fmt.Fprintf(os.Stderr, keyErr.Error())
os.Exit(-1)
}
digest := os.Getenv("Http_X_Cloud_Signature")
validated := hmac.Validate(req, digest, key)
if validated != nil {
fmt.Fprintf(os.Stderr, validated.Error())
os.Exit(-1)
}
fmt.Fprintf(os.Stderr, "hash for HMAC validated successfully\n")
}
status, marshalErr := sdk.UnmarshalStatus(req)
if marshalErr != nil {
log.Fatal("failed to parse status request json, error: ", marshalErr.Error())
}
if len(status.CommitStatuses) == 0 {
log.Fatal("failed commit statuses are empty: ", status.CommitStatuses)
}
// use auth token if provided
if status.AuthToken != sdk.EmptyAuthToken && sdk.ValidToken(status.AuthToken) {
token = status.AuthToken
log.Printf("reusing provided auth token")
} else {
var tokenErr error
privateKeyPath := sdk.GetPrivateKeyPath()
token, tokenErr = auth.MakeAccessTokenForInstallation(os.Getenv("github_app_id"), status.EventInfo.InstallationID, privateKeyPath)
if tokenErr != nil {
log.Fatalf("failed to report status %v, error: %s\n", status, tokenErr.Error())
}
if token == "" {
log.Fatalf("failed to report status %v, error: authentication failed Invalid token\n", status)
}
log.Printf("auth token is created")
}
for _, commitStatus := range status.CommitStatuses {
err := reportToGithub(&commitStatus, &status.EventInfo)
if err != nil {
log.Fatalf("failed to report status %v, error: %s", status, err.Error())
}
}
// marshal token
token = sdk.MarshalToken(token)
// return auth token so that it can be reused form a same function
return token
}
func getLogs(status *sdk.CommitStatus, event *sdk.Event) (string, error) {
client := &http.Client{}
var err error
gatewayURL := os.Getenv("gateway_url")
// TODO: support logs for different commit status contexts
url := fmt.Sprintf("%s/function/pipeline-log?repoPath=%s/%s&commitSHA=%s&function=%s", gatewayURL, event.Owner, event.Repository, event.SHA, event.Service)
log.Println(url)
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
response, err := client.Do(request)
if err != nil {
return "", err
}
defer response.Body.Close()
responsePayload, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
return string(responsePayload), nil
}
func reportToGithub(commitStatus *sdk.CommitStatus, event *sdk.Event) error {
if os.Getenv("use_checks") == "false" {
return reportStatus(commitStatus.Status, commitStatus.Description, commitStatus.Context, event)
}
return reportCheck(commitStatus, event)
}
func reportStatus(status string, desc string, statusContext string, event *sdk.Event) error {
ctx := context.Background()
url := buildPublicStatusURL(status, statusContext, event)
repoStatus := buildStatus(status, desc, statusContext, url)
log.Printf("Status: %s, Context: %s, GitHub AppID: %d, Repo: %s, Owner: %s", status, statusContext, event.InstallationID, event.Repository, event.Owner)
client := factory.MakeClient(ctx, token)
_, _, apiErr := client.Repositories.CreateStatus(ctx, event.Owner, event.Repository, event.SHA, repoStatus)
if apiErr != nil {
return fmt.Errorf("failed to report status %v, error: %s", repoStatus, apiErr.Error())
}
return nil
}
func reportCheck(commitStatus *sdk.CommitStatus, event *sdk.Event) error {
ctx := context.Background()
status := commitStatus.Status
url := buildPublicStatusURL(commitStatus.Status, commitStatus.Context, event)
log.Printf("Check: %s, Context: %s, GitHub AppID: %d, Repo: %s, Owner: %s", status, commitStatus.Context, event.InstallationID, event.Repository, event.Owner)
client := factory.MakeClient(ctx, token)
now := github.Timestamp{time.Now()}
logs, err := getLogs(commitStatus, event)
if err != nil {
return err
}
var logValue string
if len(logs) > 0 {
const maxCheckMessageLength = 65535
logValue = formatLog(logs, maxCheckMessageLength)
}
checks, _, _ := client.Checks.ListCheckRunsForRef(ctx, event.Owner, event.Repository, event.SHA, &github.ListCheckRunsOptions{CheckName: &commitStatus.Context})
checkRunStatus := getCheckRunStatus(&status)
conclusion := getCheckRunConclusion(&status)
summary := getCheckRunDescription(commitStatus, &url)
log.Printf("Check run status: %s", checkRunStatus)
var apiErr error
if *checks.Total == 0 {
check := github.CreateCheckRunOptions{
StartedAt: &now,
Name: commitStatus.Context,
HeadSHA: event.SHA,
Status: &checkRunStatus,
Output: &github.CheckRunOutput{
Text: &logValue,
Title: getCheckRunTitle(commitStatus),
Summary: summary,
},
}
if checkRunStatus == githubCheckCompleted {
check.Conclusion = &conclusion
check.CompletedAt = &now
}
log.Printf("Creating check run %s", check.Name)
_, _, apiErr = client.Checks.CreateCheckRun(ctx, event.Owner, event.Repository, check)
} else {
check := github.UpdateCheckRunOptions{
Name: *checks.CheckRuns[0].Name,
DetailsURL: &url,
Output: &github.CheckRunOutput{
Text: &logValue,
Title: getCheckRunTitle(commitStatus),
Summary: summary,
},
}
if checkRunStatus == "completed" {
check.Conclusion = &conclusion
check.CompletedAt = &now
}
_, _, apiErr = client.Checks.UpdateCheckRun(ctx, event.Owner, event.Repository, *checks.CheckRuns[0].ID, check)
log.Printf("Creating check run %s", check.Name)
}
if apiErr != nil {
return fmt.Errorf("Failed to report status %s, error: %s", status, apiErr.Error())
}
return nil
}
// getCheckRunStatus returns the check run status matching the sdk status
func getCheckRunStatus(status *string) string {
switch *status {
case sdk.StatusFailure:
return githubCheckCompleted
case sdk.StatusSuccess:
return githubCheckCompleted
}
return githubCheckQueued
}
// getCheckRunConclusion returns the conclusion matching the sdk status
func getCheckRunConclusion(status *string) string {
switch *status {
case sdk.StatusFailure:
return githubConclusionFailure
case sdk.StatusSuccess:
return githubConclusionSuccess
}
return githubConclusionNeutral
}
// getCheckRunTitle returns a title for the given status to be displayed in Github Checks UI
func getCheckRunTitle(status *sdk.CommitStatus) *string {
title := status.Description
switch status.Context {
case sdk.StackContext:
title = "Deploy to OpenFaaS"
default: // Assuming status is either a function name (building) or stack deploy
title = fmt.Sprintf("Build %s", status.Context)
}
return &title
}
// getCheckRunDescription returns a formatted summary for the Check Run page
func getCheckRunDescription(status *sdk.CommitStatus, url *string) *string {
if status.Status == sdk.StatusSuccess || status.Status == sdk.StatusFailure {
s := fmt.Sprintf("[%s](%s)", status.Description, *url)
return &s
}
return &status.Description
}
func buildStatus(status string, desc string, context string, url string) *github.RepoStatus {
return &github.RepoStatus{State: &status, TargetURL: &url, Description: &desc, Context: &context}
}
func truncate(maxLength int, message string) string {
if len(message) > maxLength {
message = message[len(message)-maxLength:]
}
return message
}
// formatLog formats the logs for the GitHub Checks API including truncating
// to maxCheckMessageLength using the tail of the message.
func formatLog(logs string, maxCheckMessageLength int) string {
frame := "\n```shell\n%s\n```\n"
// Remove 2 for the %s
log.Printf("formatLog: %d bytes", len(logs))
var logValue string
if len(logs)+len(frame)-2 > maxCheckMessageLength {
warning := fmt.Sprintf("Warning: log size (%d) bytes exceeded (%d) bytes so was truncated. See dashboard for full logs.\n\n", len(logs), maxCheckMessageLength)
newLength := maxCheckMessageLength - len(warning) - len(frame) - 2
if newLength <= 0 {
tailVal := truncate(maxCheckMessageLength, logs)
logValue = tailVal
} else {
tailVal := truncate(newLength, logs)
logValue = warning + tailVal
}
} else {
logValue = logs
}
logValue = fmt.Sprintf(frame, logValue)
return logValue
}