-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
327 lines (280 loc) · 9.32 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
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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/getsentry/sentry-go"
"github.com/go-playground/validator/v10"
"github.com/gorilla/mux"
"github.com/patrickmn/go-cache"
"github.com/prometheus/alertmanager/template"
"golang.org/x/net/context"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
)
const readRange = "A2:D"
var regexpPhone = regexp.MustCompile("^\\+[1-9]\\d{1,14}$")
var regexpTwilioSid = regexp.MustCompile("^[A-Z]{2}[0-9a-f]{32}$")
var regexpSheetId = regexp.MustCompile("^[a-zA-Z0-9-_]+$")
var regexpPort = regexp.MustCompile("^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$")
var useSentry = false
type Config struct {
TwilioAccountSid string `validate:"required,twiliosid"`
TwilioAuthSid string `validate:"required,twiliosid"`
TwilioAuthToken string `validate:"required,min=1"`
TwilioFromNumber string `validate:"required,phone"`
GoogleSheetId string `validate:"required,sheetid"`
GoogleTokenPath string `validate:"required,file"`
ListenPort string `validate:"omitempty,port"`
SentryDsn string `validate:"omitempty,min=1"`
}
type Server struct {
mux http.Handler
twilio TwilioCredentials
google GoogleCredentials
shortCache *cache.Cache
longCache *cache.Cache
}
type TwilioCredentials struct {
AccountSid string
AuthSid string
AuthToken string
FromNumber string
}
type GoogleCredentials struct {
SpreadsheetId string
TokenPath string
}
func logMessage(message string) {
log.Println(message)
if useSentry {
sentry.CaptureMessage(message)
}
}
func asJson(w http.ResponseWriter, statusCode int, message interface{}) {
js, err := json.Marshal(message)
if err != nil {
logMessage(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write(js)
}
func newServer(config Config) *Server {
serv := &Server{
twilio: TwilioCredentials{config.TwilioAccountSid, config.TwilioAuthSid, config.TwilioAuthToken, config.TwilioFromNumber},
google: GoogleCredentials{config.GoogleSheetId, config.GoogleTokenPath},
}
// Init router and routes
router := mux.NewRouter()
router.HandleFunc("/webhook", serv.webhook)
serv.mux = router
serv.shortCache = cache.New(10*time.Minute, 10*time.Minute)
serv.longCache = cache.New(cache.NoExpiration, 0)
return serv
}
func (serv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
serv.mux.ServeHTTP(w, r)
}
func (serv *Server) webhook(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != http.MethodPost {
asJson(w, http.StatusMethodNotAllowed, "unsupported HTTP method")
return
}
var alerts template.Data
err := json.NewDecoder(r.Body).Decode(&alerts)
if err != nil {
logMessage(fmt.Sprintf("Error parsing alerts content: %s", err.Error()))
asJson(w, http.StatusBadRequest, err.Error())
return
}
for _, alert := range alerts.Alerts {
team := alert.Labels["team"]
message := fmt.Sprintf("%s: %s", alert.Status, alert.Annotations["summary"])
recipients, err := getPhonesFromLabel(alert.Labels["phone_numbers"])
if err != nil {
logMessage(fmt.Sprintf("Cannot use label-provided phone numbers %s: %s", alert.Labels["phone_numbers"], err.Error()))
}
if recipients == nil {
recipients, err = serv.getTeamNumbers(team)
if err != nil {
logMessage(err.Error())
asJson(w, http.StatusInternalServerError, err.Error())
return
}
}
for _, recipient := range recipients {
err := sendSms(serv.twilio, fmt.Sprintf("+%v", recipient), message)
if err != nil {
logMessage(err.Error())
asJson(w, http.StatusInternalServerError, err.Error())
return
}
}
}
asJson(w, http.StatusOK, "success")
}
func getPhonesFromLabel(phoneNumbers string) ([]interface{}, error) {
if phoneNumbers == "" {
return nil, nil
}
phonesPattern := "^[1-9]\\d{1,14}(,[1-9]\\d{1,14})*$"
res, err := regexp.MatchString(phonesPattern, phoneNumbers)
if err != nil {
return nil, err
}
if !res {
return nil, errors.New("Wrong comma-separated phone numbers syntax")
}
split := strings.Split(phoneNumbers, ",")
phonesList := make([]interface{}, len(split))
for i, v := range split {
phonesList[i] = v
}
return phonesList, nil
}
// Get team on-call phone number present on google sheet, use fallback cache if googleapi down
func (serv *Server) getTeamNumbers(team string) ([]interface{}, error) {
phoneNumbers, found := serv.shortCache.Get(team)
if found {
return phoneNumbers.([]interface{}), nil
}
log.Printf("Getting numbers for team \"%s\" from Sheet", team)
sheets, err := NewSpreadsheetService(serv.google.TokenPath)
if err != nil {
logMessage(fmt.Sprintf("Cannot create Sheets service, reading from fallback cache - %s", err.Error()))
phoneNumbers, found := serv.longCache.Get(team)
if found {
return phoneNumbers.([]interface{}), nil
} else {
return nil, errors.New(fmt.Sprintf("No numbers found in fallback cache for team %s", team))
}
}
resp, err := sheets.Spreadsheets.Values.Get(serv.google.SpreadsheetId, readRange).Do()
if err != nil {
logMessage(fmt.Sprintf("Cannot read Sheet, reading from fallback cache - %s", err.Error()))
phoneNumbers, found := serv.longCache.Get(team)
if found {
return phoneNumbers.([]interface{}), nil
} else {
return nil, errors.New(fmt.Sprintf("No numbers found in fallback cache for team %s", team))
}
return nil, err
}
if len(resp.Values) == 0 {
return nil, errors.New("Sheet appears to be empty :(")
}
for _, row := range resp.Values {
if len(row) > 0 {
serv.longCache.Set(row[0].(string), row[1:], cache.DefaultExpiration)
serv.shortCache.Set(row[0].(string), row[1:], cache.DefaultExpiration)
if row[0] == team {
return row[1:], nil
}
}
}
return nil, errors.New(fmt.Sprintf("No row found in Sheet for team %s", team))
}
func NewSpreadsheetService(client_secret_path string) (*sheets.Service, error) {
ctx := context.Background()
srv, err := sheets.NewService(ctx, option.WithCredentialsFile(client_secret_path), option.WithScopes(sheets.SpreadsheetsScope))
if err != nil {
return nil, errors.New(fmt.Sprintf("Unable to establish Sheets Client: %s", err.Error()))
}
return srv, nil
}
// Send message to recipient through twilio API
func sendSms(twilio TwilioCredentials, recipient string, message string) error {
log.Printf("Sending SMS to %s: %s", recipient, message)
urlStr := fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", twilio.AccountSid)
msgData := url.Values{}
msgData.Set("To", recipient)
msgData.Set("From", twilio.FromNumber)
msgData.Set("Body", message)
msgDataReader := *strings.NewReader(msgData.Encode())
client := &http.Client{}
req, _ := http.NewRequest("POST", urlStr, &msgDataReader)
req.SetBasicAuth(twilio.AuthSid, twilio.AuthToken)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
log.Printf("Error querying twilio API: %s", err.Error())
return err
} else if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(resp.Body)
return errors.New(fmt.Sprintf("Non-200 response from twilio API: %s - %s", resp.Status, body))
}
var data map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
log.Printf("Error in twilio response body: %s", err.Error())
return err
}
log.Printf("Successfully sent SMS - SID %s", data["sid"])
return nil
}
func main() {
validate := validator.New()
_ = validate.RegisterValidation("phone", func(fl validator.FieldLevel) bool {
return regexpPhone.MatchString(fl.Field().String())
})
_ = validate.RegisterValidation("twiliosid", func(fl validator.FieldLevel) bool {
return regexpTwilioSid.MatchString(fl.Field().String())
})
_ = validate.RegisterValidation("sheetid", func(fl validator.FieldLevel) bool {
return regexpSheetId.MatchString(fl.Field().String())
})
_ = validate.RegisterValidation("port", func(fl validator.FieldLevel) bool {
return regexpPort.MatchString(fl.Field().String())
})
config := Config{
TwilioAccountSid: os.Getenv("TWILIO_ACCOUNT_SID"),
TwilioAuthSid: os.Getenv("TWILIO_AUTH_SID"),
TwilioAuthToken: os.Getenv("TWILIO_AUTH_TOKEN"),
TwilioFromNumber: os.Getenv("TWILIO_FROM_NUMBER"),
GoogleSheetId: os.Getenv("GOOGLE_SHEET_ID"),
GoogleTokenPath: os.Getenv("GOOGLE_TOKEN_PATH"),
ListenPort: os.Getenv("PORT"),
SentryDsn: os.Getenv("SENTRY_DSN"),
}
err := validate.Struct(config)
if err != nil {
for _, e := range err.(validator.ValidationErrors) {
log.Println(e)
}
log.Fatal("Parameters validation failed")
}
if config.SentryDsn != "" {
err := sentry.Init(sentry.ClientOptions{
Dsn: config.SentryDsn,
})
if err != nil {
log.Fatal(fmt.Sprintf("Sentry initialization failed DSN %s", config.SentryDsn))
}
log.Printf("Sentry initialized with DSN %s", config.SentryDsn)
defer sentry.Flush(time.Second * 5)
defer sentry.Recover()
useSentry = true
} else {
log.Println("Not using Sentry")
}
serv := newServer(config)
listenAddress := ":9080"
if config.ListenPort != "" {
listenAddress = fmt.Sprintf(":%s", config.ListenPort)
}
log.Printf("listening on: %s", listenAddress)
log.Fatal(http.ListenAndServe(listenAddress, serv))
}