/
main.go
263 lines (223 loc) · 7.13 KB
/
main.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
// Copyright 2020 Google LLC
//
// 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 main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/GoogleCloudPlatform/cloud-build-notifiers/lib/notifiers"
log "github.com/golang/glog"
chat "google.golang.org/api/chat/v1"
cbpb "cloud.google.com/go/cloudbuild/apiv1/v2/cloudbuildpb"
)
const (
webhookURLSecretName = "webhookUrl"
)
func main() {
if err := notifiers.Main(new(googlechatNotifier)); err != nil {
log.Fatalf("fatal error: %v", err)
}
}
type googlechatNotifier struct {
filter notifiers.EventFilter
webhookURL string
}
func (g *googlechatNotifier) SetUp(ctx context.Context, cfg *notifiers.Config, _ string, sg notifiers.SecretGetter, _ notifiers.BindingResolver) error {
prd, err := notifiers.MakeCELPredicate(cfg.Spec.Notification.Filter)
if err != nil {
return fmt.Errorf("failed to make a CEL predicate: %w", err)
}
g.filter = prd
wuRef, err := notifiers.GetSecretRef(cfg.Spec.Notification.Delivery, webhookURLSecretName)
if err != nil {
return fmt.Errorf("failed to get Secret ref from delivery config (%v) field %q: %w", cfg.Spec.Notification.Delivery, webhookURLSecretName, err)
}
wuResource, err := notifiers.FindSecretResourceName(cfg.Spec.Secrets, wuRef)
if err != nil {
return fmt.Errorf("failed to find Secret for ref %q: %w", wuRef, err)
}
wu, err := sg.GetSecret(ctx, wuResource)
if err != nil {
return fmt.Errorf("failed to get token secret: %w", err)
}
g.webhookURL = wu
return nil
}
func (g *googlechatNotifier) SendNotification(ctx context.Context, build *cbpb.Build) error {
if !g.filter.Apply(ctx, build) {
return nil
}
log.Infof("sending Google Chat webhook for Build %q (status: %q)", build.Id, build.Status)
msg, err := g.writeMessage(build)
if err != nil {
return fmt.Errorf("failed to write Google Chat message: %w", err)
}
payload := new(bytes.Buffer)
err = json.NewEncoder(payload).Encode(msg)
if err != nil {
return fmt.Errorf("failed to encode payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.webhookURL, payload)
if err != nil {
return fmt.Errorf("failed to create a new HTTP request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "GCB-Notifier/0.1 (http)")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to make HTTP request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Warningf("got a non-OK response status %q (%d) from %q", resp.Status, resp.StatusCode, g.webhookURL)
}
log.V(2).Infoln("send HTTP request successfully")
return nil
}
func (g *googlechatNotifier) writeMessage(build *cbpb.Build) (*chat.Message, error) {
var icon string
switch build.Status {
case cbpb.Build_SUCCESS:
icon = "https://www.gstatic.com/images/icons/material/system/2x/check_circle_googgreen_48dp.png"
case cbpb.Build_FAILURE, cbpb.Build_INTERNAL_ERROR:
icon = "https://www.gstatic.com/images/icons/material/system/2x/error_red_48dp.png"
case cbpb.Build_TIMEOUT:
icon = "https://www.gstatic.com/images/icons/material/system/2x/hourglass_empty_black_48dp.png"
default:
icon = "https://www.gstatic.com/images/icons/material/system/2x/question_mark_black_48dp.png"
}
logURL, err := notifiers.AddUTMParams(build.LogUrl, notifiers.ChatMedium)
if err != nil {
return nil, fmt.Errorf("failed to add UTM params: %w", err)
}
// Basic card setup
duration := build.GetFinishTime().AsTime().Sub(build.GetStartTime().AsTime())
duration_min, duration_sec := int(duration.Minutes()), int(duration.Seconds())-int(duration.Minutes())*60
duration_fmt := fmt.Sprintf("%d min %d sec", duration_min, duration_sec)
card := &chat.Card{
Header: &chat.CardHeader{
Title: fmt.Sprintf("Build %s Status: %s", build.Id[:8], build.Status),
Subtitle: build.ProjectId,
ImageUrl: icon,
},
Sections: []*chat.Section{
{
Widgets: []*chat.WidgetMarkup{
{
KeyValue: &chat.KeyValue{
TopLabel: "Duration",
Content: duration_fmt,
},
},
},
},
},
}
// Optional section: display trigger information
if build.BuildTriggerId != "" {
log.Infof("Detected a build trigger id: %s", build.BuildTriggerId)
/*
//TODO(glasnt): Get trigger information for Uri links.
// The repo name in `build` does not include the owner information
// You need to inspect the trigger object to get the full repo name and/or the git URI.
ctx := context.Background()
cbapi, _ := cloudbuild.NewClient(ctx)
trigger_info := cbapi.GetBuildTrigger(ctx, &cbpb.GetBuildTriggerRequest{ProjectId: build.ProjectId, TriggerId: build.BuildTriggerId,})
log.Infof("Trigger Repo URI: %s", trigger_info.??)
*/
repo_name := build.Substitutions["REPO_NAME"]
trigger_name := build.Substitutions["TRIGGER_NAME"]
commit := build.Substitutions["SHORT_SHA"]
// Branch, Tag, or None.
branch_tag_label := "Branch"
branch_tag_value := build.Substitutions["BRANCH_NAME"]
if branch_tag_value == "" {
branch_tag_label = "Tag"
branch_tag_value = build.Substitutions["TAG_NAME"]
if branch_tag_value == "" {
branch_tag_label = "Branch/Tag"
branch_tag_value = "[no branch or tag]"
}
}
card.Header.Subtitle = fmt.Sprintf("%s on %s", trigger_name, build.ProjectId)
build_info := &chat.Section{
Header: "Trigger information",
Widgets: []*chat.WidgetMarkup{
{
KeyValue: &chat.KeyValue{
TopLabel: "Trigger",
Content: trigger_name,
},
},
{
KeyValue: &chat.KeyValue{
TopLabel: "Repo",
Content: repo_name,
},
},
{
KeyValue: &chat.KeyValue{
TopLabel: branch_tag_label,
Content: branch_tag_value,
},
},
{
KeyValue: &chat.KeyValue{
TopLabel: "Commit",
Content: commit,
},
},
},
}
card.Sections = append(card.Sections, build_info)
}
// Optional section: display information about errors
if build.FailureInfo != nil {
failure_info := &chat.Section{
Header: "Error information",
Widgets: []*chat.WidgetMarkup{
{
TextParagraph: &chat.TextParagraph{
Text: build.FailureInfo.GetDetail(),
},
},
},
}
card.Sections = append(card.Sections, failure_info)
}
// Append action button
action_section := &chat.Section{
Widgets: []*chat.WidgetMarkup{
{
Buttons: []*chat.Button{
{
TextButton: &chat.TextButton{
Text: "open logs",
OnClick: &chat.OnClick{
OpenLink: &chat.OpenLink{
Url: logURL,
},
},
},
},
},
},
},
}
card.Sections = append(card.Sections, action_section)
msg := chat.Message{Cards: []*chat.Card{card}}
return &msg, nil
}