-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
257 lines (219 loc) · 5.99 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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
)
var (
// BuildCommit contains the git sha of the commit built, defaults to empty
BuildCommit = "-"
// BuildTag contains the tag of the commit built, defaults to 'snapshot'
BuildTag = "snapshot"
)
// Config contains what's in the `settings` section of the config file
type Config struct {
APIKey string
DryRun bool
Region string
}
// Metric represents a point that'll be sent to Datadog
type Metric struct {
Name string
Type string
Value float32
Host string
Tags []string
}
// Metrics is a type alias for a slice of Metric
type Metrics []Metric
// Event represents an event that'll be sent to Datadog
// see https://docs.datadoghq.com/api/latest/events/
type Event struct {
Title string `json:"title"`
Text string `json:"text"`
AlertType string `json:"alert_type,omitempty"`
Host string `json:"host,omitempty"`
Tags []string `json:"tags,omitempty"`
AggregationKey string `json:"aggregation_key"` // limited to 100 chars
DateHappened int64 `json:"date_happened"`
DeviceName string `json:"device_name"`
Priority string `json:"priority"` // 'normal' or 'low'
RelatedEventID int64 `json:"related_event_id"`
SourceTypeName string `json:"source_type_name"`
}
// Events is a type alias for a slice ov Event
type Events []Event
// MarshalJSON provides custom serialization for the Metric object
func (m Metric) MarshalJSON() ([]byte, error) {
point := []float32{
float32(time.Now().Unix()),
m.Value,
}
return json.Marshal(&struct {
Name string `json:"metric"`
Type string `json:"type,omitempty"`
Host string `json:"host,omitempty"`
Tags []string `json:"tags,omitempty"`
Points [][]float32 `json:"points"`
}{
Name: m.Name,
Type: m.Type,
Host: m.Host,
Tags: m.Tags,
Points: [][]float32{point},
})
}
func isValidMetricType(t string) bool {
return map[string]bool{
"gauge": true,
"rate": true,
"count": true,
"": true, // will default to `gauge`
}[t]
}
func isValidAlertType(t string) bool {
return map[string]bool{
"info": true,
"success": true,
"warning": true,
"error": true,
"": true, // will default to `info`
}[t]
}
func isValidPriority(p string) bool {
return map[string]bool{
"normal": true,
"low": true,
"": true, // will default to `normal`
}[p]
}
func isValidAggregationKey(k string) bool {
return len(k) <= 100
}
func printVersion() {
log.Printf("Drone-Datadog Plugin version: %s - git commit: %s", BuildTag, BuildCommit)
}
func parseConfig() (*Config, error) {
cfg := &Config{
APIKey: os.Getenv("PLUGIN_API_KEY"),
DryRun: os.Getenv("PLUGIN_DRY_RUN") == "true",
Region: strings.ToLower(os.Getenv("PLUGIN_REGION")),
}
if cfg.APIKey == "" && !cfg.DryRun {
return nil, fmt.Errorf("Datadog API Key is missing")
}
if cfg.Region == "" && !cfg.DryRun {
cfg.Region = "com"
}
return cfg, nil
}
func parseMetrics() (Metrics, error) {
configData := []byte(os.Getenv("PLUGIN_METRICS"))
data := Metrics{}
if err := json.Unmarshal(configData, &data); err != nil {
return nil, fmt.Errorf("metrics configuration error: %v", err)
}
metrics := Metrics{}
for _, m := range data {
if !isValidMetricType(m.Type) {
log.Printf("invalid metric type: %s", m.Type)
continue
}
metrics = append(metrics, m)
}
return metrics, nil
}
func parseEvents() (Events, error) {
configData := []byte(os.Getenv("PLUGIN_EVENTS"))
data := Events{}
if err := json.Unmarshal(configData, &data); err != nil {
return nil, fmt.Errorf("events configuration error: %v", err)
}
// validate Event fields
events := Events{}
for _, ev := range data {
if !isValidAlertType(ev.AlertType) {
log.Printf("invalid alert type: %s", ev.AlertType)
} else if !isValidPriority(ev.Priority) {
log.Printf("invalid priority value: %s", ev.Priority)
} else if !isValidAggregationKey(ev.AggregationKey) {
log.Printf("invalid aggregation key value: %s", ev.AggregationKey)
} else {
// all good, add the event
ev.DateHappened = time.Now().Unix()
events = append(events, ev)
}
}
return events, nil
}
func send(url string, payload []byte, dryRun bool) error {
if dryRun {
log.Println("Dry run, logging payload:")
log.Println(string(payload))
return nil
}
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(payload))
req.Header.Set("Content-Type", "application/json")
if res, err := http.DefaultClient.Do(req); err == nil {
if res.StatusCode >= 300 {
return fmt.Errorf("server responded with: %s", res.Status)
}
} else {
return fmt.Errorf("unable to send data: %s", err)
}
return nil
}
func main() {
showVersion := flag.Bool("v", false, "print plugin version")
flag.Parse()
if *showVersion {
printVersion()
os.Exit(0)
}
cfg, err := parseConfig()
if err != nil {
log.Fatalf("parseConfig() err: %s", err)
}
if metrics, err := parseMetrics(); err == nil {
payload, err := json.Marshal(struct {
Series Metrics `json:"series"`
}{
Series: metrics,
})
if err != nil {
log.Printf("error encoding metrics: %v", err)
} else {
url := fmt.Sprintf("https://api.datadoghq.%s/api/v1/series?api_key=%s", cfg.Region, cfg.APIKey)
if err := send(url, payload, cfg.DryRun); err != nil {
log.Fatalf("unable to send metrics: %v", err)
}
log.Printf("%d metric(s) sent successfully", len(metrics))
}
} else {
log.Println(err)
}
if events, err := parseEvents(); err == nil {
url := fmt.Sprintf("https://api.datadoghq.%s/api/v1/events?api_key=%s", cfg.Region, cfg.APIKey)
successCount := 0
// events must be posted one at a time
for _, ev := range events {
payload, err := json.Marshal(ev)
if err != nil {
log.Printf("error encoding event: %v", err)
continue
}
if err := send(url, payload, cfg.DryRun); err != nil {
log.Printf("unable to send event: %v", err)
continue
}
successCount++
}
log.Printf("%d event(s) sent successfully", successCount)
}
}