forked from cybozu-go/kkok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.go
167 lines (146 loc) · 3.33 KB
/
send.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
package slack
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
"github.com/cybozu-go/cmd"
"github.com/cybozu-go/log"
)
const (
queueSize = 100
// See https://api.slack.com/docs/rate-limits
slackAPIDuration = 1100 * time.Millisecond
slackAPITimeout = 5 * time.Second
)
var (
sendCh = make(chan *slackMessage, queueSize)
httpClient = &cmd.HTTPClient{
Client: &http.Client{},
Severity: log.LvDebug,
}
)
func enqueue(m *slackMessage) bool {
select {
case sendCh <- m:
return true
default:
return false
}
}
type slackMessage struct {
url *url.URL
maxRetry int
payload []byte
}
func (m *slackMessage) wait(ctx context.Context, duration time.Duration) bool {
select {
case <-ctx.Done():
return false
case <-time.After(duration):
return true
}
}
func (m *slackMessage) do(ctx context.Context) (*http.Response, []byte, error) {
header := make(http.Header)
header.Set("Content-Type", "application/json")
req := &http.Request{
Method: "POST",
URL: m.url,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: header,
Body: ioutil.NopCloser(bytes.NewReader(m.payload)),
ContentLength: int64(len(m.payload)),
Host: m.url.Host,
}
// use context.Background to send alerts gracefully.
ctx, cancel := context.WithTimeout(context.Background(), slackAPITimeout)
defer cancel()
resp, err := httpClient.Do(req.WithContext(ctx))
if err != nil {
return nil, nil, err
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, nil, err
}
return resp, data, nil
}
func (m *slackMessage) send(ctx context.Context) bool {
var retries int
RETRY:
resp, body, err := m.do(ctx)
if err != nil {
log.Error("[slack] do", map[string]interface{}{
log.FnError: err.Error(),
log.FnURL: m.url.String(),
})
if retries < m.maxRetry {
retries++
if m.wait(ctx, slackAPIDuration) {
goto RETRY
}
}
log.Error("[slack] gave up", nil)
return false
}
sleepDuration := slackAPIDuration
switch {
case (200 <= resp.StatusCode) && (resp.StatusCode < 300):
log.Info("[slack] sent alerts", nil)
return true
case resp.StatusCode == 429:
// rate limit exceeded
log.Warn("[slack] rate limit exceeds", nil)
ssec := resp.Header.Get("Retry-After")
if len(ssec) > 0 {
sec, err := strconv.Atoi(ssec)
if err == nil {
sleepDuration = time.Duration(sec) * time.Second
}
}
case resp.StatusCode >= 500:
// temporary server failure, hopefully.
log.Error("[slack] failed to send", map[string]interface{}{
log.FnURL: m.url.String(),
log.FnHTTPStatusCode: resp.StatusCode,
})
default:
// mainly because the request was bad.
fields := map[string]interface{}{
log.FnURL: m.url,
log.FnHTTPStatusCode: resp.StatusCode,
}
if len(body) > 0 {
fields[log.FnError] = string(body)
}
log.Error("[slack] request failed", fields)
return false
}
if retries < m.maxRetry {
retries++
if m.wait(ctx, sleepDuration) {
goto RETRY
}
}
log.Error("[slack] gave up", nil)
return false
}
// A goroutine to send messages to slack complying its rate limits.
func dequeueAndSend(ctx context.Context) error {
for {
select {
case m := <-sendCh:
m.send(ctx)
m.wait(ctx, slackAPIDuration)
case <-ctx.Done():
return nil
}
}
}