-
Notifications
You must be signed in to change notification settings - Fork 7
/
slack.go
462 lines (424 loc) · 14.3 KB
/
slack.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
package slack
import (
"context"
"fmt"
"strings"
"github.com/lunarway/release-manager/internal/http"
"github.com/lunarway/release-manager/internal/log"
"github.com/nlopes/slack"
"github.com/pkg/errors"
)
type SlackClient interface {
GetUserByEmailContext(ctx context.Context, email string) (*slack.User, error)
UpdateMessage(channelID, timestamp string, options ...slack.MsgOption) (string, string, string, error)
PostMessage(channelID string, options ...slack.MsgOption) (string, string, error)
PostMessageContext(ctx context.Context, channelID string, options ...slack.MsgOption) (string, string, error)
}
type Client struct {
client SlackClient
emailMappings map[string]string
muteOptions MuteOptions
emailSuffix string
}
type MuteOptions struct {
Kubernetes bool
Policy bool
ReleaseProcessed bool
Releases bool
BuildStatus bool
ReleaseManagerError bool
}
var (
// ErrUnknownEmail indicates that an email is not from the specified domain
// and no email mapping exists
ErrUnknownEmail = errors.New("not an accepted email domain")
)
func NewClient(slackClient SlackClient, emailMappings map[string]string, emailSuffix string) (*Client, error) {
if slackClient == nil {
log.Infof("slack: skipping: no token, so no slack notification")
return &Client{
muteOptions: MuteOptions{
Kubernetes: true,
Policy: true,
ReleaseProcessed: true,
Releases: true,
BuildStatus: true,
ReleaseManagerError: true,
},
}, nil
}
log.Infof("slack: new client: initialized with emailMappings: %+v", emailMappings)
client := Client{
client: slackClient,
emailMappings: emailMappings,
muteOptions: MuteOptions{},
emailSuffix: emailSuffix,
}
return &client, nil
}
func NewMuteableClient(slackClient SlackClient, emailMappings map[string]string, emailSuffix string, muteOptions MuteOptions) (*Client, error) {
client, err := NewClient(slackClient, emailMappings, emailSuffix)
if err != nil {
return nil, err
}
client.muteOptions = muteOptions
return client, nil
}
func (c *Client) getIdByEmail(ctx context.Context, email string) (string, error) {
if !strings.HasSuffix(email, c.emailSuffix) {
// check for fallback emails
companyEmail, ok := c.emailMappings[email]
if !ok {
// we log this error up front as it is a signal to operators that emails
// cannot be mapped to slack IDs. This should be fixed by either user
// using a valid email for commits for the slack space or by adding a
// mapping to a valid email. We still return the error to let the caller
// take appropriate action, eg. retries.
log.WithContext(ctx).Errorf("%s is not a %s email and no mapping exist", email, c.emailSuffix)
return "", ErrUnknownEmail
}
email = companyEmail
}
user, err := c.client.GetUserByEmailContext(ctx, email)
if err != nil {
return "", err
}
return user.ID, nil
}
func (c *Client) UpdateSlackBuildStatus(channel, title, titleLink, text, color, timestamp string) (string, string, error) {
if c.muteOptions.BuildStatus {
return "", "", nil
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: title,
TitleLink: titleLink,
Color: color,
Text: text,
MarkdownIn: []string{"text", "fields"},
})
respChannel, timestamp, _, err := c.client.UpdateMessage(channel, timestamp, asUser, attachments)
if err != nil {
return "", "", err
}
return respChannel, timestamp, nil
}
func (c *Client) PostSlackBuildStarted(email, title, titleLink, text, color string) (string, string, error) {
if c.muteOptions.BuildStatus {
return "", "", nil
}
userID, err := c.getIdByEmail(context.Background(), email)
if err != nil {
return "", "", err
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: title,
TitleLink: titleLink,
Color: color,
Text: text,
MarkdownIn: []string{"text", "fields"},
})
respChannel, timestamp, err := c.client.PostMessage(userID, asUser, attachments)
if err != nil {
return "", "", err
}
return respChannel, timestamp, err
}
type ReleaseOptions struct {
Service string
ArtifactID string
CommitSHA string
CommitLink string
CommitMessage string
CommitAuthor string
CommitAuthorEmail string
Releaser string
Environment string
}
func (c *Client) NotifyRelease(ctx context.Context, releaseOptions ReleaseOptions) {
err := c.notifySlackReleasesChannel(ctx, releaseOptions)
if err != nil {
log.WithContext(ctx).Errorf("flow.NotifyReleaseHook: failed to post releases slack message: %v", err)
}
err = c.notifyAuthorEventProcessed(ctx, releaseOptions)
if err != nil {
log.WithContext(ctx).Errorf("flow.NotifyReleaseHook: failed to post slack event processed message to author: %v", err)
}
}
func (c *Client) notifySlackReleasesChannel(ctx context.Context, options ReleaseOptions) error {
if c.muteOptions.Releases {
return nil
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: fmt.Sprintf("%s (%s)", options.Service, options.ArtifactID),
TitleLink: options.CommitLink,
Color: MsgColorGreen,
Text: fmt.Sprintf("*Author:* %s, *Releaser:* %s\n*Message:* _%s_", options.CommitAuthor, options.Releaser, options.CommitMessage),
MarkdownIn: []string{"text", "fields"},
})
_, _, err := c.client.PostMessageContext(ctx, fmt.Sprintf("#releases-%s", options.Environment), asUser, attachments)
if err != nil {
return err
}
return err
}
type BuildsOptions struct {
Service string
ArtifactID string
Branch string
CommitSHA string
CommitLink string
CommitMessage string
CommitAuthor string
CIJobURL string
Color string
}
func (c *Client) NotifySlackBuildsChannel(options BuildsOptions) error {
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: fmt.Sprintf("%s (%s)", options.Service, options.ArtifactID),
TitleLink: options.CIJobURL,
Color: options.Color,
Text: fmt.Sprintf("*Author:* %s (<%s|%s>)\n*Message:* _%s_", options.CommitAuthor, options.CommitLink, options.CommitSHA[0:10], options.CommitMessage),
MarkdownIn: []string{"text", "fields"},
})
_, _, err := c.client.PostMessage("#builds", asUser, attachments)
if err != nil {
return err
}
return err
}
func (c *Client) NotifySlackPolicyFailed(ctx context.Context, email, title, errorMessage string) error {
if c.muteOptions.Policy {
return nil
}
userID, err := c.getIdByEmail(ctx, email)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: title,
Color: MsgColorRed,
Text: formatErrorMessage(errorMessage),
MarkdownIn: []string{"text", "fields"},
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return nil
}
func (c *Client) NotifySlackPolicySucceeded(ctx context.Context, email, title, message string) error {
if c.muteOptions.Policy {
return nil
}
userID, err := c.getIdByEmail(ctx, email)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: title,
Color: MsgColorGreen,
Text: message,
MarkdownIn: []string{"text", "fields"},
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return nil
}
func (c *Client) notifyAuthorEventProcessed(ctx context.Context, options ReleaseOptions) error {
if c.muteOptions.ReleaseProcessed {
return nil
}
userID, err := c.getIdByEmail(ctx, options.CommitAuthorEmail)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: ":rocket: Release Manager :white_check_mark:",
Color: MsgColorGreen,
Text: fmt.Sprintf("Release for *%s* in %s processed\nArtifact: <%s|*%s*>", options.Service, options.Environment, options.CommitLink, options.ArtifactID),
MarkdownIn: []string{"text", "fields"},
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return err
}
type NotifyK8sDeployOptions struct {
AuthorEmail string
Environment string
Name string
AvailablePods int32
DesiredPods int32
ResourceType string
ArtifactID string
}
func (c *Client) NotifyK8SDeployEvent(ctx context.Context, event NotifyK8sDeployOptions) error {
if c.muteOptions.Kubernetes {
return nil
}
userID, err := c.getIdByEmail(ctx, event.AuthorEmail)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: fmt.Sprintf(":kubernetes: k8s (%s) :white_check_mark:", event.Environment),
Color: MsgColorGreen,
Text: fmt.Sprintf("%s deployed\n%d/%d pods are running (%s)\nArtifact: *%s*", event.Name, event.AvailablePods, event.DesiredPods, event.ResourceType, event.ArtifactID),
MarkdownIn: []string{"text", "fields"},
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return err
}
type NotifyReleaseFailedOptions struct {
PodName string
Namespace string
Errors []string
AuthorEmail string
Environment string
ArtifactID string
Squad string
AlertSquad string
}
func (c *Client) NotifyReleaseFailedEvent(ctx context.Context, event NotifyReleaseFailedOptions) error {
userID, err := c.getIdByEmail(ctx, event.AuthorEmail)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
fields := make([]slack.AttachmentField, 0)
for _, errMsg := range event.Errors {
fields = append(fields, slack.AttachmentField{
Title: fmt.Sprintf("Fail reason"),
Value: formatErrorMessage(errMsg),
Short: false,
})
}
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: fmt.Sprintf("release (%s) :no_entry:", event.Environment),
Color: MsgColorRed,
Text: fmt.Sprintf("artifact: %s", event.ArtifactID),
MarkdownIn: []string{"text", "fields"},
Fields: fields,
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return nil
}
func (c *Client) NotifyK8SPodErrorEvent(ctx context.Context, event *http.PodErrorEvent) error {
if c.muteOptions.Kubernetes {
return nil
}
userID, err := c.getIdByEmail(ctx, event.AuthorEmail)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
var fields []slack.AttachmentField
for _, container := range event.Errors {
fields = append(fields, slack.AttachmentField{
Title: fmt.Sprintf("Container: %s (%s)", container.Name, container.Type),
Value: formatErrorMessage(container.ErrorMessage),
Short: false,
})
}
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: fmt.Sprintf(":kubernetes: k8s (%s) :no_entry:", event.Environment),
Text: fmt.Sprintf("Pod Error: %s\nArtifact: *%s*", event.PodName, event.ArtifactID),
Color: "#e24d42",
MarkdownIn: []string{"text", "fields"},
Fields: fields,
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
if event.AlertSquad != "" {
_, _, err = c.client.PostMessageContext(ctx, event.AlertSquad, asUser, attachments)
}
return err
}
func (c *Client) NotifyK8SJobErrorEvent(ctx context.Context, event *http.JobErrorEvent) error {
if c.muteOptions.Kubernetes {
return nil
}
userID, err := c.getIdByEmail(ctx, event.AuthorEmail)
if err != nil {
return err
}
asUser := slack.MsgOptionAsUser(true)
var fields []slack.AttachmentField
for _, condition := range event.Errors {
fields = append(fields, slack.AttachmentField{
Title: fmt.Sprintf("Reason: %s", condition.Reason),
Value: formatErrorMessage(condition.Message),
Short: false,
})
}
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: fmt.Sprintf(":kubernetes: k8s (%s) :no_entry:", event.Environment),
Text: fmt.Sprintf("Job Error: %s\nArtifact: *%s*", event.JobName, event.ArtifactID),
Color: "#e24d42",
MarkdownIn: []string{"text", "fields"},
Fields: fields,
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return err
}
func (c *Client) NotifyReleaseManagerError(ctx context.Context, msgType, service, environment, branch, namespace, actorEmail string, inputErr error) error {
if c.muteOptions.ReleaseManagerError {
return nil
}
userID, err := c.getIdByEmail(ctx, actorEmail)
if err != nil {
// If user id somehow couldn't be found, post the message to fallback channel
log.With("actorEmail", actorEmail).Infof("slack: skipping: no user id found, so no slack notification")
return nil
}
asUser := slack.MsgOptionAsUser(true)
attachments := slack.MsgOptionAttachments(slack.Attachment{
Title: ":boom: Release Manager failed :x:",
Color: MsgColorRed,
Text: generateSlackMessage(msgType, service, environment, branch, namespace, inputErr),
MarkdownIn: []string{"text", "fields"},
})
_, _, err = c.client.PostMessageContext(ctx, userID, asUser, attachments)
if err != nil {
return err
}
return nil
}
func generateSlackMessage(msgType, service, environment, branch, namespace string, err error) string {
switch {
case msgType == "promote" && service != "" && environment != "" && branch != "":
return fmt.Sprintf("Failed promoting %s #%s in %s. Validate the options you used and try promoting again.\nError: %s", service, branch, environment, err)
case msgType == "release.branch" && service != "" && environment != "" && branch != "":
return fmt.Sprintf("Failed releasing %s #%s to %s. Validate the options you used and try releasing again.\nError: %s", service, branch, environment, err)
default:
return fmt.Sprintf("Failed handling event in release manager for:\nEvent: %s\nService: %s\nEnvironment: %s\nBranch: %s\nNamespace: %s\nError: %s", msgType, service, environment, branch, namespace, err)
}
}
func formatErrorMessage(errorMessage string) string {
if errorMessage == "" { //error message is only formatted if there is one
return errorMessage
}
return fmt.Sprintf("```%s```", errorMessage)
}