-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathslack.go
251 lines (218 loc) · 6.82 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
// Copyright 2020 The PipeCD Authors.
//
// 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 notifier
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"go.uber.org/zap"
"github.com/pipe-cd/pipe/pkg/config"
"github.com/pipe-cd/pipe/pkg/model"
)
const (
slackUsername = "PipeCD"
slackInfoColor = "#212121"
slackSuccessColor = "#2E7D32"
slackErrorColor = "#AF3F52"
slackWarnColor = "#FFB74D"
)
type slack struct {
name string
config config.NotificationReceiverSlack
webURL string
httpClient *http.Client
eventCh chan model.Event
gracePeriod time.Duration
logger *zap.Logger
}
func newSlackSender(name string, cfg config.NotificationReceiverSlack, webURL string, logger *zap.Logger) *slack {
return &slack{
name: name,
config: cfg,
webURL: strings.TrimRight(webURL, "/"),
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
eventCh: make(chan model.Event, 100),
gracePeriod: 10 * time.Second,
logger: logger.Named("slack"),
}
}
func (s *slack) Run(ctx context.Context) error {
send := func(ctx context.Context, event model.Event) {
msg, ok := buildSlackMessage(event, s.webURL)
if !ok {
s.logger.Info(fmt.Sprintf("ignore event %s", event.Type.String()))
return
}
if err := s.sendMessage(ctx, msg); err != nil {
s.logger.Error(fmt.Sprintf("unable to send notification to slack: %v", err))
}
}
for {
select {
case event := <-s.eventCh:
send(ctx, event)
case <-ctx.Done():
// TODO: Send all remaining events before exiting.
return nil
}
}
}
func (s *slack) Notify(event model.Event) {
s.eventCh <- event
}
func buildSlackMessage(event model.Event, webURL string) (slackMessage, bool) {
var (
title, link, text string
color = slackInfoColor
timestamp = time.Now().Unix()
fields []slackField
)
generateDeploymentEventData := func(d *model.Deployment) {
link = webURL + "/deployments/" + d.Id
// TODO: Use environment name instead of id.
fields = []slackField{
{"Env", truncateText(d.EnvId, 8), true},
{"Application", makeSlackLink(d.ApplicationName, webURL+"/applications/"+d.ApplicationId), true},
{"Kind", strings.ToLower(d.Kind.String()), true},
{"Deployment", makeSlackLink(truncateText(d.Id, 8), link), true},
{"Triggered By", d.TriggeredBy(), true},
{"Started At", makeSlackDate(d.CreatedAt), true},
}
}
generatePipedEventData := func(id, version string) {
link = webURL + "/settings/piped"
fields = []slackField{
{"Id", id, true},
{"Version", version, true},
}
}
switch event.Type {
case model.EventType_EVENT_DEPLOYMENT_TRIGGERED:
md := event.Metadata.(*model.EventDeploymentTriggered)
title = fmt.Sprintf("Triggered a new deployment for %q", md.Deployment.ApplicationName)
generateDeploymentEventData(md.Deployment)
break
case model.EventType_EVENT_DEPLOYMENT_PLANNED:
md := event.Metadata.(*model.EventDeploymentPlanned)
title = fmt.Sprintf("Deployment for %q was planned", md.Deployment.ApplicationName)
text = md.Summary
generateDeploymentEventData(md.Deployment)
break
case model.EventType_EVENT_DEPLOYMENT_SUCCEEDED:
md := event.Metadata.(*model.EventDeploymentSucceeded)
title = fmt.Sprintf("Deployment for %q was completed successfully", md.Deployment.ApplicationName)
color = slackSuccessColor
generateDeploymentEventData(md.Deployment)
break
case model.EventType_EVENT_DEPLOYMENT_FAILED:
md := event.Metadata.(*model.EventDeploymentFailed)
title = fmt.Sprintf("Deployment for %q was failed", md.Deployment.ApplicationName)
text = md.Reason
color = slackErrorColor
generateDeploymentEventData(md.Deployment)
break
case model.EventType_EVENT_DEPLOYMENT_CANCELLED:
md := event.Metadata.(*model.EventDeploymentCancelled)
title = fmt.Sprintf("Deployment for %q was cancelled", md.Deployment.ApplicationName)
text = fmt.Sprintf("Cancelled by %s", md.Commander)
color = slackWarnColor
generateDeploymentEventData(md.Deployment)
break
case model.EventType_EVENT_PIPED_STARTED:
md := event.Metadata.(*model.EventPipedStarted)
title = "A piped has been started"
generatePipedEventData(md.Id, md.Version)
break
case model.EventType_EVENT_PIPED_STOPPED:
md := event.Metadata.(*model.EventPipedStarted)
title = "A piped has been stopped"
generatePipedEventData(md.Id, md.Version)
break
default:
return slackMessage{}, false
}
return makeSlackMessage(title, link, text, color, timestamp, fields...), true
}
type slackMessage struct {
Username string `json:"username"`
Attachments []slackAttachment `json:"attachments,omitempty"`
}
type slackAttachment struct {
Title string `json:"title"`
TitleLink string `json:"title_link"`
Text string `json:"text"`
Fields []slackField `json:"fields"`
Color string `json:"color,omitempty"`
Markdown []string `json:"mrkdwn_in,omitempty"`
Timestamp int64 `json:"ts,omitempty"`
}
type slackField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
func makeSlackLink(title, url string) string {
return fmt.Sprintf("<%s|%s>", url, title)
}
func makeSlackDate(unix int64) string {
return fmt.Sprintf("<!date^%d^{date_num} {time_secs}|date>", unix)
}
func truncateText(text string, max int) string {
if len(text) <= max {
return text
}
return text[:max] + "..."
}
func makeSlackMessage(title, titleLink, text, color string, timestamp int64, fields ...slackField) slackMessage {
return slackMessage{
Username: slackUsername,
Attachments: []slackAttachment{{
Title: title,
TitleLink: titleLink,
Text: text,
Fields: fields,
Color: color,
Markdown: []string{"text"},
Timestamp: timestamp,
}},
}
}
func (s *slack) sendMessage(ctx context.Context, msg slackMessage) error {
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(msg); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "POST", s.config.HookURL, buf)
if err != nil {
return err
}
resp, err := s.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1024*1024))
return fmt.Errorf("%s from Slack: %s", resp.Status, strings.TrimSpace(string(body)))
}
return nil
}