forked from zorkian/go-datadog-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice_level_objectives.go
443 lines (372 loc) · 14.2 KB
/
service_level_objectives.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
* Datadog API for Go
*
* Please see the included LICENSE file for licensing information.
*
* Copyright 2017 by authors and contributors.
*/
package datadog
import (
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
"time"
)
// Define the available machine-readable SLO types
const (
ServiceLevelObjectiveTypeMonitorID int = 0
ServiceLevelObjectiveTypeMetricID int = 1
)
// Define the available human-readable SLO types
var (
ServiceLevelObjectiveTypeMonitor = "monitor"
ServiceLevelObjectiveTypeMetric = "metric"
)
// ServiceLevelObjectiveTypeFromID maps machine-readable type to human-readable type
var ServiceLevelObjectiveTypeFromID = map[int]string{
ServiceLevelObjectiveTypeMonitorID: ServiceLevelObjectiveTypeMonitor,
ServiceLevelObjectiveTypeMetricID: ServiceLevelObjectiveTypeMetric,
}
// ServiceLevelObjectiveTypeToID maps human-readable type to machine-readable type
var ServiceLevelObjectiveTypeToID = map[string]int{
ServiceLevelObjectiveTypeMonitor: ServiceLevelObjectiveTypeMonitorID,
ServiceLevelObjectiveTypeMetric: ServiceLevelObjectiveTypeMetricID,
}
// ServiceLevelObjectiveThreshold defines an SLO threshold and timeframe
// For example it's the `<SLO: ex 99.999%> of <SLI> within <TimeFrame: ex 7d>
type ServiceLevelObjectiveThreshold struct {
TimeFrame *string `json:"timeframe,omitempty"`
Target *float64 `json:"target,omitempty"`
TargetDisplay *string `json:"target_display,omitempty"` // Read-Only for monitor type
Warning *float64 `json:"warning,omitempty"`
WarningDisplay *string `json:"warning_display,omitempty"` // Read-Only for monitor type
}
const thresholdTolerance float64 = 1e-8
// Equal check if one threshold is equal to another.
func (s *ServiceLevelObjectiveThreshold) Equal(o interface{}) bool {
other, ok := o.(*ServiceLevelObjectiveThreshold)
if !ok {
return false
}
return s.GetTimeFrame() == other.GetTimeFrame() &&
Float64AlmostEqual(s.GetTarget(), other.GetTarget(), thresholdTolerance) &&
Float64AlmostEqual(s.GetWarning(), other.GetWarning(), thresholdTolerance)
}
// String implements Stringer
func (s ServiceLevelObjectiveThreshold) String() string {
return fmt.Sprintf("Threshold{timeframe=%s target=%f target_display=%s warning=%f warning_display=%s",
s.GetTimeFrame(), s.GetTarget(), s.GetTargetDisplay(), s.GetWarning(), s.GetWarningDisplay())
}
// ServiceLevelObjectiveMetricQuery represents a metric-based SLO definition query
// Numerator is the sum of the `good` events
// Denominator is the sum of the `total` events
type ServiceLevelObjectiveMetricQuery struct {
Numerator *string `json:"numerator,omitempty"`
Denominator *string `json:"denominator,omitempty"`
}
// ServiceLevelObjectiveThresholds is a sortable array of ServiceLevelObjectiveThreshold(s)
type ServiceLevelObjectiveThresholds []*ServiceLevelObjectiveThreshold
// Len implements sort.Interface length
func (s ServiceLevelObjectiveThresholds) Len() int {
return len(s)
}
// Less implements sort.Interface less comparator
func (s ServiceLevelObjectiveThresholds) Less(i, j int) bool {
iDur, _ := ServiceLevelObjectiveTimeFrameToDuration(s[i].GetTimeFrame())
jDur, _ := ServiceLevelObjectiveTimeFrameToDuration(s[j].GetTimeFrame())
return iDur < jDur
}
// Swap implements sort.Interface swap method
func (s ServiceLevelObjectiveThresholds) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Equal check if one set of thresholds is equal to another.
func (s ServiceLevelObjectiveThresholds) Equal(o interface{}) bool {
other, ok := o.(ServiceLevelObjectiveThresholds)
if !ok {
return false
}
if len(s) != len(other) {
// easy case
return false
}
// compare one set from another
sSet := make(map[string]*ServiceLevelObjectiveThreshold, 0)
for _, t := range s {
sSet[t.GetTimeFrame()] = t
}
oSet := make(map[string]*ServiceLevelObjectiveThreshold, 0)
for _, t := range other {
oSet[t.GetTimeFrame()] = t
}
for timeframe, t := range oSet {
threshold, ok := sSet[timeframe]
if !ok {
// other contains more
return false
}
if !threshold.Equal(t) {
// they differ
return false
}
// drop from sSet for efficiency
delete(sSet, timeframe)
}
// if there are any remaining then they differ
if len(sSet) > 0 {
return false
}
return true
}
// ServiceLevelObjective defines the Service Level Objective entity
type ServiceLevelObjective struct {
// Common
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
Thresholds ServiceLevelObjectiveThresholds `json:"thresholds,omitempty"`
Type *string `json:"type,omitempty"`
TypeID *int `json:"type_id,omitempty"` // Read-Only
// SLI definition
Query *ServiceLevelObjectiveMetricQuery `json:"query,omitempty"`
MonitorIDs []int `json:"monitor_ids,omitempty"`
MonitorSearch *string `json:"monitor_search,omitempty"`
Groups []string `json:"groups,omitempty"`
// Informational
MonitorTags []string `json:"monitor_tags,omitempty"` // Read-Only
Creator *Creator `json:"creator,omitempty"` // Read-Only
CreatedAt *int `json:"created_at,omitempty"` // Read-Only
ModifiedAt *int `json:"modified_at,omitempty"` // Read-Only
}
// implements custom marshaler to ignore some fields
func (s *ServiceLevelObjective) MarshalJSON() ([]byte, error) {
var output struct {
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
Thresholds ServiceLevelObjectiveThresholds `json:"thresholds,omitempty"`
Type *string `json:"type,omitempty"`
// SLI definition
Query *ServiceLevelObjectiveMetricQuery `json:"query,omitempty"`
MonitorIDs []int `json:"monitor_ids,omitempty"`
MonitorSearch *string `json:"monitor_search,omitempty"`
Groups []string `json:"groups,omitempty"`
}
output.ID = s.ID
output.Name = s.Name
output.Description = s.Description
output.Tags = s.Tags
output.Thresholds = s.Thresholds
output.Type = s.Type
output.Query = s.Query
output.MonitorIDs = s.MonitorIDs
output.MonitorSearch = s.MonitorSearch
output.Groups = s.Groups
return json.Marshal(&output)
}
var sloTimeFrameToDurationRegex = regexp.MustCompile(`(?P<quantity>\d+)(?P<unit>(d))`)
// ServiceLevelObjectiveTimeFrameToDuration will convert a timeframe into a duration
func ServiceLevelObjectiveTimeFrameToDuration(timeframe string) (time.Duration, error) {
match := sloTimeFrameToDurationRegex.FindStringSubmatch(timeframe)
result := make(map[string]string)
for i, name := range sloTimeFrameToDurationRegex.SubexpNames() {
if i != 0 && name != "" {
result[name] = match[i]
}
}
if len(result) != 2 {
return 0, fmt.Errorf("invalid timeframe specified: '%s'", timeframe)
}
qty, err := json.Number(result["quantity"]).Int64()
if err != nil {
return 0, fmt.Errorf("invalid timeframe specified, could not convert quantity to number")
}
if qty <= 0 {
return 0, fmt.Errorf("invalid timeframe specified, quantity must be a positive number")
}
switch result["unit"] {
// FUTURE: will support more time frames, hence the switch here.
default:
// only matches on `d` currently, so this is simple
return time.Hour * 24 * time.Duration(qty), nil
}
}
// CreateServiceLevelObjective adds a new service level objective to the system. This returns a pointer
// to the service level objective so you can pass that to UpdateServiceLevelObjective or DeleteServiceLevelObjective
// later if needed.
func (client *Client) CreateServiceLevelObjective(slo *ServiceLevelObjective) (*ServiceLevelObjective, error) {
var out reqServiceLevelObjectives
if slo == nil {
return nil, fmt.Errorf("no SLO specified")
}
if err := client.doJsonRequest("POST", "/v1/slo", slo, &out); err != nil {
return nil, err
}
if out.Error != "" {
return nil, fmt.Errorf(out.Error)
}
return out.Data[0], nil
}
// UpdateServiceLevelObjective takes a service level objective that was previously retrieved through some method
// and sends it back to the server.
func (client *Client) UpdateServiceLevelObjective(slo *ServiceLevelObjective) (*ServiceLevelObjective, error) {
var out reqServiceLevelObjectives
if slo == nil {
return nil, fmt.Errorf("no SLO specified")
}
if _, ok := slo.GetIDOk(); !ok {
return nil, fmt.Errorf("SLO must be created first")
}
if err := client.doJsonRequest("PUT", fmt.Sprintf("/v1/slo/%s", slo.GetID()), slo, &out); err != nil {
return nil, err
}
if out.Error != "" {
return nil, fmt.Errorf(out.Error)
}
return out.Data[0], nil
}
type reqServiceLevelObjectives struct {
Data []*ServiceLevelObjective `json:"data"`
Error string `json:"error"`
}
// SearchServiceLevelObjectives searches for service level objectives by search criteria.
// limit will limit the amount of SLO's returned, the API will enforce a maximum and default to a minimum if not specified
func (client *Client) SearchServiceLevelObjectives(limit int, offset int, query string, ids []string) ([]*ServiceLevelObjective, error) {
var out reqServiceLevelObjectives
uriValues := make(url.Values, 0)
if limit > 0 {
uriValues.Set("limit", fmt.Sprintf("%d", limit))
}
if offset >= 0 {
uriValues.Set("offset", fmt.Sprintf("%d", offset))
}
// Either use `query` or use `ids`
hasQuery := strings.TrimSpace(query) != ""
hasIDs := len(ids) > 0
if hasQuery && hasIDs {
return nil, fmt.Errorf("invalid search: must specify either ids OR query, not both")
}
// specify by query
if hasQuery {
uriValues.Set("query", query)
}
// specify by `ids`
if hasIDs {
uriValues.Set("ids", strings.Join(ids, ","))
}
uri := "/v1/slo"
encodedQuery := uriValues.Encode()
if encodedQuery != "" {
uri += "?" + encodedQuery
}
if err := client.doJsonRequest("GET", uri, nil, &out); err != nil {
return nil, err
}
if out.Error != "" {
return nil, fmt.Errorf(out.Error)
}
return out.Data, nil
}
type reqSingleServiceLevelObjective struct {
Data *ServiceLevelObjective `json:"data"`
Error string `json:"error"`
}
// GetServiceLevelObjective retrieves an service level objective by identifier.
func (client *Client) GetServiceLevelObjective(id string) (*ServiceLevelObjective, error) {
var out reqSingleServiceLevelObjective
if id == "" {
return nil, fmt.Errorf("no SLO specified")
}
if err := client.doJsonRequest("GET", fmt.Sprintf("/v1/slo/%s", id), nil, &out); err != nil {
return nil, err
}
if out.Error != "" {
return nil, fmt.Errorf(out.Error)
}
return out.Data, nil
}
type reqDeleteResp struct {
Data []string `json:"data"`
Error string `json:"error"`
}
// DeleteServiceLevelObjective removes an service level objective from the system.
func (client *Client) DeleteServiceLevelObjective(id string) error {
var out reqDeleteResp
if id == "" {
return fmt.Errorf("no SLO specified")
}
if err := client.doJsonRequest("DELETE", fmt.Sprintf("/v1/slo/%s", id), nil, &out); err != nil {
return err
}
if out.Error != "" {
return fmt.Errorf(out.Error)
}
return nil
}
// DeleteServiceLevelObjectives removes multiple service level objective from the system by id.
func (client *Client) DeleteServiceLevelObjectives(ids []string) error {
var out reqDeleteResp
if len(ids) == 0 {
return fmt.Errorf("no SLOs specified")
}
if err := client.doJsonRequest("DELETE", "/v1/slo", ids, &out); err != nil {
return err
}
if out.Error != "" {
return fmt.Errorf(out.Error)
}
return nil
}
// ServiceLevelObjectiveDeleteTimeFramesResponse is the response unique to the delete individual time-frames request
// this is read-only
type ServiceLevelObjectiveDeleteTimeFramesResponse struct {
DeletedIDs []string `json:"deleted"`
UpdatedIDs []string `json:"updated"`
}
// ServiceLevelObjectiveDeleteTimeFramesError is the error specific to deleting individual time frames.
// It contains more detailed information than the standard error.
type ServiceLevelObjectiveDeleteTimeFramesError struct {
ID *string `json:"id"`
TimeFrame *string `json:"timeframe"`
Message *string `json:"message"`
}
// Error computes the human readable error
func (e ServiceLevelObjectiveDeleteTimeFramesError) Error() string {
return fmt.Sprintf("error=%s id=%s for timeframe=%s", e.GetMessage(), e.GetID(), e.GetTimeFrame())
}
type timeframesDeleteResp struct {
Data *ServiceLevelObjectiveDeleteTimeFramesResponse `json:"data"`
Errors []*ServiceLevelObjectiveDeleteTimeFramesError `json:"errors"`
}
// DeleteServiceLevelObjectiveTimeFrames will delete SLO timeframes individually.
// This is useful if you have a SLO with 3 time windows and only need to delete some of the time windows.
// It will do a full delete if all time windows are removed as a result.
//
// Example:
// SLO `12345678901234567890123456789012` was defined with 2 time frames: "7d" and "30d"
// SLO `abcdefabcdefabcdefabcdefabcdefab` was defined with 2 time frames: "30d" and "90d"
//
// When we delete `7d` from `12345678901234567890123456789012` we still have `30d` timeframe remaining, hence this is "updated"
// When we delete `30d` and `90d` from `abcdefabcdefabcdefabcdefabcdefab` we are left with 0 time frames, hence this is "deleted"
// and the entire SLO config is deleted
func (client *Client) DeleteServiceLevelObjectiveTimeFrames(timeframeByID map[string][]string) (*ServiceLevelObjectiveDeleteTimeFramesResponse, error) {
var out timeframesDeleteResp
if len(timeframeByID) == 0 {
return nil, fmt.Errorf("nothing specified")
}
if err := client.doJsonRequest("POST", "/v1/slo/bulk_delete", &timeframeByID, &out); err != nil {
return nil, err
}
if out.Errors != nil && len(out.Errors) > 0 {
errMsgs := make([]string, 0)
for _, e := range out.Errors {
errMsgs = append(errMsgs, e.Error())
}
return nil, fmt.Errorf("errors deleting timeframes: %s", strings.Join(errMsgs, ","))
}
return out.Data, nil
}