-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapex.go
235 lines (203 loc) · 5.42 KB
/
apex.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
/*
Lambda function to alert the Cloudwatch Alarm to mackerel.
*/
package cwa2mkr
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/apex/go-apex/sns"
"github.com/aws/aws-lambda-go/lambda"
)
const (
checkReportEndpoint = "https://api.mackerelio.com/api/v0/monitoring/checks/report"
reportMsgFmt = "%s status is '%s', reason: %s, alarm_description: %s, state_change_time: %s, metrics: %s, namespace: %s"
StatusOK = "OK"
StatusWarning = "WARNING"
StatusCritical = "CRITICAL"
)
// https://mackerel.io/ja/api-docs/entry/check-monitoring
//
// json struct should be posted:
// {
// "reports": [
// {
// "source": {
// "type": "host",
// "hostId": "hostid"
// },
// "name": "Mycron Batch Failed",
// "status": "CRITICAL",
// "message": "alert message",
// "occurredAt": epoch_time
// }
// ]
// }
type Reports struct {
Reports []Report `json:"reports"`
}
type Report struct {
// source struct reference
Source Source `json:"source"`
// monitoring name
Name string `json:"name"`
// result of status: "OK", "CRITICAL", "WARNING", "UNKNOWN"
Status string `json:"status"` // OK, ALARM
// message memo, 1024 characters
Message string `json:"message"`
// monitor time (epoch sec)
OccurredAt int64 `json:"occurredAt"`
// [optional] alert resent interval(min). default is not resending, and if it is less than 10 min, it is set 10 min.
NotificationInterval int `json:"notificationInterval,omitempty"`
}
type Source struct {
// constant string "host"
Type string `json:"type"`
// mackerel host id
HostID string `json:"hostId"`
}
// a content of record sent to lambd by SNS:
// {
// "AlarmName": "test",
// "AlarmDescription": "test",
// "AWSAccountId": "***",
// "NewStateValue": "OK",
// "NewStateReason": "Threshold Crossed: no datapoints were received for 1 period and 1 missing datapoint was treated as [NonBreaching].",
// "StateChangeTime": "2018-02-16T08:42:33.109+0000",
// "Region": "Asia Pacific (Tokyo)",
// "OldStateValue": "ALARM",
// "Trigger": {
// "MetricName": "FailedInvocations",
// "Namespace": "AWS/Events",
// "StatisticType": "Statistic",
// "Statistic": "SUM",
// "Unit": null,
// "Dimensions": [
// {
// "name": "RuleName",
// "value": "cron_name",
// }
// ],
// "Period": 60,
// "EvaluationPeriods": 1,
// "ComparisonOperator": "GreaterThanOrEqualToThreshold",
// "Threshold": 0,
// "TreatMissingData": "- TreatMissingData: NonBreaching",
// "EvaluateLowSampleCountPercentile": ""
// }
// }
//
type snsMessage struct {
AlarmName string `json:"AlarmName"`
AlarmDescription string `json:"AlarmDescription"`
NewStateValue string `json:"NewStateValue"`
NewStateReason string `json:"NewStateReason"`
StateChangeTime string `json:"StateChangeTime"`
Trigger trigger `json:"Trigger"`
}
type trigger struct {
MetricName string `json:"MetricName"`
Namespace string `json:"NameSpace"`
}
func (m snsMessage) toMackerelStatus() string {
if m.NewStateValue == StatusOK {
return StatusOK
}
if strings.HasPrefix(m.AlarmDescription, "CRITICAL") {
return StatusCritical
}
return StatusWarning
}
func ApexRun() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
apiKey, hostID, err := parseEnvVars()
if err != nil {
return err
}
handler := func(ctx context.Context, event *sns.Event) error {
reps := Reports{
Reports: make([]Report, 0, len(event.Records)),
}
for _, record := range event.Records {
var msg snsMessage
if err := json.Unmarshal([]byte(record.SNS.Message), &msg); err != nil {
log.Println(err)
continue
}
// empty is not expected, so skip.
if msg.AlarmName == "" || msg.NewStateValue == "" {
log.Printf("got the unknown message: %#v", msg)
continue
}
reps.Reports = append(reps.Reports, Report{
Source: Source{
HostID: hostID,
Type: "host",
},
Name: msg.AlarmName,
Status: msg.toMackerelStatus(),
Message: fmt.Sprintf(reportMsgFmt,
msg.AlarmName,
msg.NewStateValue,
msg.NewStateReason,
msg.AlarmDescription,
msg.StateChangeTime,
msg.Trigger.MetricName,
msg.Trigger.Namespace,
),
OccurredAt: time.Now().Unix(),
})
}
return PostChecksReport(apiKey, reps)
}
lambda.Start(handler)
return nil
}
func parseEnvVars() (apiKey, hostID string, err error) {
if hostID = os.Getenv("HOST_ID"); hostID == "" {
err = errors.New("HOST_ID is required")
return
}
if apiKey = os.Getenv("MACKEREL_APIKEY"); apiKey == "" {
err = errors.New("MACKEREL_APIKEY is required")
return
}
return
}
func PostChecksReport(apiKey string, reps Reports) error {
body := new(bytes.Buffer)
if err := json.NewEncoder(body).Encode(reps); err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, checkReportEndpoint, body)
if err != nil {
return err
}
req.Header.Set("Content-type", "application/json")
req.Header.Set("X-Api-Key", apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if status := resp.StatusCode; status >= 400 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: status code %d %s", status, err)
}
return fmt.Errorf("failed to post: status code %d %s", status, string(body))
}
return nil
}