Repository navigation
Expand file tree
/
Copy pathinsights.go
More file actions
2027 lines (1811 loc) · 74.3 KB
/
Copy pathinsights.go
File metadata and controls
2027 lines (1811 loc) · 74.3 KB
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package godo
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/google/go-querystring/query"
)
const (
insightsNotificationChannelsPath = "/v2/insights/notification-channels"
insightsAlertRulesPath = "/v2/insights/alert-rules"
insightsAlertInstancesPath = "/v2/insights/alert-instances"
insightsResourcesPath = "/v2/insights/resources"
)
// Insights resource list sort fields.
const (
InsightsResourceSortResourceURN = "resource_urn"
InsightsResourceSortEffectiveAt = "effective_at"
)
// Insights resource list sort directions.
const (
InsightsResourceSortAscending = "asc"
InsightsResourceSortDescending = "desc"
)
// Insights notification channel types. These are the protobuf enum values the
// API returns on read; create and update select the type by which config
// object is set.
const (
InsightsChannelTypeEmail = "CHANNEL_TYPE_EMAIL"
InsightsChannelTypeSlack = "CHANNEL_TYPE_SLACK"
InsightsChannelTypeWebhook = "CHANNEL_TYPE_WEBHOOK"
)
// Insights alert rule statuses.
const (
InsightsAlertRuleStatusActive = "ALERT_RULE_STATUS_ACTIVE"
InsightsAlertRuleStatusPaused = "ALERT_RULE_STATUS_PAUSED"
)
// Insights alert evaluation windows.
const (
InsightsEvaluationWindow1m = "EVALUATION_WINDOW_1M"
InsightsEvaluationWindow5m = "EVALUATION_WINDOW_5M"
InsightsEvaluationWindow10m = "EVALUATION_WINDOW_10M"
InsightsEvaluationWindow15m = "EVALUATION_WINDOW_15M"
InsightsEvaluationWindow30m = "EVALUATION_WINDOW_30M"
InsightsEvaluationWindow1h = "EVALUATION_WINDOW_1H"
)
// Insights threshold operators.
const (
InsightsThresholdOperatorEqual = "THRESHOLD_OPERATOR_EQUAL"
InsightsThresholdOperatorLessThanOrEqual = "THRESHOLD_OPERATOR_LESS_THAN_OR_EQUAL"
InsightsThresholdOperatorLessThan = "THRESHOLD_OPERATOR_LESS_THAN"
InsightsThresholdOperatorGreaterThan = "THRESHOLD_OPERATOR_GREATER_THAN"
InsightsThresholdOperatorGreaterThanOrEqual = "THRESHOLD_OPERATOR_GREATER_THAN_OR_EQUAL"
InsightsThresholdOperatorNotEqual = "THRESHOLD_OPERATOR_NOT_EQUAL"
)
// Insights metrics-query filter operators.
const (
InsightsFilterOperatorEqual = "FILTER_OPERATOR_EQUAL"
InsightsFilterOperatorNotEqual = "FILTER_OPERATOR_NOT_EQUAL"
InsightsFilterOperatorLessThan = "FILTER_OPERATOR_LESS_THAN"
InsightsFilterOperatorLessThanOrEqual = "FILTER_OPERATOR_LESS_THAN_OR_EQUAL"
InsightsFilterOperatorGreaterThan = "FILTER_OPERATOR_GREATER_THAN"
InsightsFilterOperatorGreaterThanOrEqual = "FILTER_OPERATOR_GREATER_THAN_OR_EQUAL"
)
// Insights re-alert durations.
const (
InsightsReAlertDuration30m = "RE_ALERT_DURATION_30M"
InsightsReAlertDuration1h = "RE_ALERT_DURATION_1H"
InsightsReAlertDuration4h = "RE_ALERT_DURATION_4H"
InsightsReAlertDurationNever = "RE_ALERT_DURATION_NEVER"
)
// Insights severities used when binding a notification channel to an alert rule.
const (
InsightsSeverityWarning = "SEVERITY_WARNING"
InsightsSeverityCritical = "SEVERITY_CRITICAL"
)
// Insights alert instance statuses. These are lowercase, unlike the protobuf
// enums used by alert rules and notification channels.
const (
InsightsAlertInstanceStatusActive = "active"
InsightsAlertInstanceStatusResolved = "resolved"
)
// Insights alert instance severities.
const (
InsightsAlertInstanceSeverityWarning = "warning"
InsightsAlertInstanceSeverityCritical = "critical"
)
// Insights logs filter operators.
const (
InsightsLogsFilterOperatorEqual = "FILTER_OPERATOR_EQ"
InsightsLogsFilterOperatorNotEqual = "FILTER_OPERATOR_NEQ"
InsightsLogsFilterOperatorIn = "FILTER_OPERATOR_IN"
InsightsLogsFilterOperatorExists = "FILTER_OPERATOR_EXISTS"
InsightsLogsFilterOperatorGreaterThanOrEqual = "FILTER_OPERATOR_GTE"
InsightsLogsFilterOperatorLessThanOrEqual = "FILTER_OPERATOR_LTE"
)
// Insights logs field scopes.
const (
InsightsLogsFieldScopeResource = "FIELD_SCOPE_RESOURCE"
InsightsLogsFieldScopeAttributes = "FIELD_SCOPE_ATTRIBUTES"
)
// Insights logs sort directions.
const (
InsightsLogsSortDirectionAscending = "SORT_DIRECTION_ASC"
InsightsLogsSortDirectionDescending = "SORT_DIRECTION_DESC"
)
// Insights spans filter node types.
// Deprecated: filter nodes are selected by setting Condition, And, Or, Not, or
// TextSearch on SpansFilterExpression.
const (
InsightsSpansFilterTypeCondition = "condition"
InsightsSpansFilterTypeAnd = "and"
InsightsSpansFilterTypeOr = "or"
InsightsSpansFilterTypeNot = "not"
InsightsSpansFilterTypeTextSearch = "text_search"
)
// Insights spans filter condition operators.
const (
InsightsSpansFilterOperatorEqual = "FILTER_OPERATOR_EQ"
InsightsSpansFilterOperatorNotEqual = "FILTER_OPERATOR_NEQ"
InsightsSpansFilterOperatorGreaterThanOrEqual = "FILTER_OPERATOR_GTE"
InsightsSpansFilterOperatorLessThanOrEqual = "FILTER_OPERATOR_LTE"
InsightsSpansFilterOperatorIn = "FILTER_OPERATOR_IN"
InsightsSpansFilterOperatorExists = "FILTER_OPERATOR_EXISTS"
)
// InsightsSpansFilterOperatorGreaterThan is retained for source compatibility.
// Deprecated: the spans API does not support a strict greater-than operator.
const InsightsSpansFilterOperatorGreaterThan = "gt"
// InsightsSpansFilterOperatorLessThan is retained for source compatibility.
// Deprecated: the spans API does not support a strict less-than operator.
const InsightsSpansFilterOperatorLessThan = "lt"
// Insights spans field scopes. Omit the scope for well-known span fields or to
// search both attribute maps.
const (
InsightsSpansFieldScopeResource = "FIELD_SCOPE_RESOURCE"
InsightsSpansFieldScopeAttributes = "FIELD_SCOPE_ATTRIBUTES"
)
// Insights spans sort directions.
const (
InsightsSpansSortDirectionAscending = "asc"
InsightsSpansSortDirectionDescending = "desc"
)
// Insights spans filter value types.
// Deprecated: these identify the pre-COBS-1725 typed-wrapper representation
// accepted only by SpansFilterValue.UnmarshalJSON.
const (
InsightsSpansValueTypeString = "string"
InsightsSpansValueTypeNumber = "number"
InsightsSpansValueTypeBool = "bool"
InsightsSpansValueTypeStringArray = "string_array"
InsightsSpansValueTypeNumberArray = "number_array"
)
// Insights traces filter node types.
// Deprecated: filter nodes are selected by setting Condition, And, Or, Not, or
// TextSearch on TracesFilterExpression.
const (
InsightsTracesFilterTypeCondition = "condition"
InsightsTracesFilterTypeAnd = "and"
InsightsTracesFilterTypeOr = "or"
InsightsTracesFilterTypeNot = "not"
InsightsTracesFilterTypeTextSearch = "text_search"
)
// Insights traces filter condition operators.
const (
InsightsTracesFilterOperatorEqual = "FILTER_OPERATOR_EQ"
InsightsTracesFilterOperatorNotEqual = "FILTER_OPERATOR_NEQ"
InsightsTracesFilterOperatorGreaterThanOrEqual = "FILTER_OPERATOR_GTE"
InsightsTracesFilterOperatorLessThanOrEqual = "FILTER_OPERATOR_LTE"
InsightsTracesFilterOperatorIn = "FILTER_OPERATOR_IN"
InsightsTracesFilterOperatorExists = "FILTER_OPERATOR_EXISTS"
)
// InsightsTracesFilterOperatorGreaterThan is retained for source compatibility.
// Deprecated: the traces API does not support a strict greater-than operator.
const InsightsTracesFilterOperatorGreaterThan = "gt"
// InsightsTracesFilterOperatorLessThan is retained for source compatibility.
// Deprecated: the traces API does not support a strict less-than operator.
const InsightsTracesFilterOperatorLessThan = "lt"
// Insights traces field scopes. Omit the scope for well-known span fields or to
// look up a span attribute with a resource attribute fallback.
const (
InsightsTracesFieldScopeResource = "FIELD_SCOPE_RESOURCE"
InsightsTracesFieldScopeAttributes = "FIELD_SCOPE_ATTRIBUTES"
)
// Insights traces sort directions.
const (
InsightsTracesSortDirectionAscending = "asc"
InsightsTracesSortDirectionDescending = "desc"
)
// Insights traces filter value types.
// Deprecated: these identify the pre-COBS-1725 typed-wrapper representation
// accepted only by TracesFilterValue.UnmarshalJSON.
const (
InsightsTracesValueTypeString = "string"
InsightsTracesValueTypeNumber = "number"
InsightsTracesValueTypeBool = "bool"
InsightsTracesValueTypeStringArray = "string_array"
InsightsTracesValueTypeNumberArray = "number_array"
)
// Insights trace statuses, rolled up from the status codes of a trace's spans.
const (
InsightsTraceStatusOk = "Ok"
InsightsTraceStatusError = "Error"
)
// InsightsService manages Insights notification channels, alert rules, alert
// instances, PromQL queries, logs searches, spans searches, traces queries,
// and per-resource telemetry signal enablement.
type InsightsService interface {
ListNotificationChannels(context.Context, *ListOptions) ([]NotificationChannel, *Response, error)
GetNotificationChannel(context.Context, string) (*NotificationChannel, *Response, error)
CreateNotificationChannel(context.Context, *NotificationChannelRequest) (*NotificationChannel, *Response, error)
UpdateNotificationChannel(context.Context, string, *NotificationChannelRequest) (*NotificationChannel, *Response, error)
DeleteNotificationChannel(context.Context, string) (*Response, error)
ListAlertRules(context.Context, *AlertRuleListOptions) ([]AlertRule, *Response, error)
GetAlertRule(context.Context, string) (*AlertRule, *Response, error)
CreateAlertRule(context.Context, *AlertRuleRequest) (*AlertRule, *Response, error)
UpdateAlertRule(context.Context, string, *AlertRuleRequest) (*AlertRule, *Response, error)
DeleteAlertRule(context.Context, string) (*Response, error)
ListAlertInstances(context.Context, *AlertInstanceListOptions) ([]AlertInstance, *Response, error)
GetAlertInstance(context.Context, string) (*AlertInstance, *Response, error)
// Query evaluates a PromQL expression at one timestamp (GET).
Query(context.Context, string, *PromQueryOptions) (*PromQueryResponse, *Response, error)
// PostQuery is the form-encoded POST form of Query, for expressions that do not fit in a URL.
PostQuery(context.Context, string, *PromQueryOptions) (*PromQueryResponse, *Response, error)
QueryRange(context.Context, string, *PromQueryRangeOptions) (*PromQueryRangeResponse, *Response, error)
PostQueryRange(context.Context, string, *PromQueryRangeOptions) (*PromQueryRangeResponse, *Response, error)
Series(context.Context, string, *PromSelectorOptions) (*PromSeriesResponse, *Response, error)
PostSeries(context.Context, string, *PromSelectorOptions) (*PromSeriesResponse, *Response, error)
Labels(context.Context, string, *PromSelectorOptions) (*PromLabelsResponse, *Response, error)
PostLabels(context.Context, string, *PromSelectorOptions) (*PromLabelsResponse, *Response, error)
LabelValues(context.Context, string, string, *PromSelectorOptions) (*PromLabelsResponse, *Response, error)
SearchLogs(context.Context, string, *LogsSearchRequest) (*LogsSearchResponse, *Response, error)
SearchSpans(context.Context, string, *SpansSearchRequest) (*SpansSearchResponse, *Response, error)
SearchTraces(context.Context, string, *TracesSearchRequest) (*TracesSearchResponse, *Response, error)
GetTrace(context.Context, string, string, *TraceGetOptions) (*Trace, *Response, error)
ListResources(context.Context, *InsightsResourceListOptions) (*InsightsResourceList, *Response, error)
GetResource(context.Context, string) (*InsightsResource, *Response, error)
UpdateResourceSignals(context.Context, string, *InsightsResourceSignalsRequest) (*InsightsResource, *Response, error)
}
// InsightsServiceOp handles communication with Insights methods of the DigitalOcean API.
type InsightsServiceOp struct {
client *Client
}
var _ InsightsService = &InsightsServiceOp{}
// NotificationChannel is a reusable Insights notification destination.
type NotificationChannel struct {
ID string `json:"id"`
Name string `json:"name"`
ChannelType string `json:"channel_type"`
Email *EmailNotificationConfig `json:"email,omitempty"`
Slack *SlackNotificationConfig `json:"slack,omitempty"`
Webhook *WebhookNotificationConfig `json:"webhook,omitempty"`
Usage *NotificationChannelUsage `json:"usage,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// NotificationChannelRequest is the body for creating or updating a notification channel.
// Set exactly one of Email, Slack, or Webhook. Secret fields are write-only:
// send the full value to set or rotate one, and leave it empty on update to keep the current secret.
type NotificationChannelRequest struct {
Name string `json:"name"`
Email *EmailNotificationConfig `json:"email,omitempty"`
Slack *SlackNotificationConfig `json:"slack,omitempty"`
Webhook *WebhookNotificationConfig `json:"webhook,omitempty"`
}
// EmailNotificationConfig is an email notification channel.
// To is one or more verified team-member addresses separated by commas, semicolons, or spaces.
type EmailNotificationConfig struct {
To string `json:"to"`
}
// SlackNotificationConfig is a Slack notification channel.
// WebhookURL is write-only: reads return a masked value, and an empty WebhookURL on update keeps the existing URL.
type SlackNotificationConfig struct {
WebhookURL string `json:"webhook_url,omitempty"`
Channel string `json:"channel"`
}
// WebhookNotificationConfig is an HTTPS webhook notification channel.
// URL is returned in full on read. Credential fields are write-only and masked on read;
// leave a secret empty on update to keep the existing value. Set BasicAuth or BearerToken, not both.
type WebhookNotificationConfig struct {
URL string `json:"url"`
BasicAuth *WebhookBasicAuth `json:"basic_auth,omitempty"`
BearerToken *WebhookBearerToken `json:"bearer_token,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Signature *WebhookSignatureConfig `json:"signature,omitempty"`
}
// WebhookBasicAuth is HTTP basic auth for a webhook. Password is write-only.
type WebhookBasicAuth struct {
Username string `json:"username"`
Password string `json:"password,omitempty"`
}
// WebhookBearerToken is bearer auth for a webhook. Token is write-only.
type WebhookBearerToken struct {
Token string `json:"token,omitempty"`
}
// WebhookSignatureConfig is the HMAC signing secret for a webhook. Secret is write-only.
type WebhookSignatureConfig struct {
Secret string `json:"secret,omitempty"`
}
// NotificationChannelUsage counts alert rules that reference a channel.
type NotificationChannelUsage struct {
RuleCount int `json:"rule_count"`
}
type notificationChannelsRoot struct {
NotificationChannels []NotificationChannel `json:"notification_channels"`
Links *Links `json:"links"`
Meta *Meta `json:"meta"`
}
type notificationChannelRoot struct {
NotificationChannel *NotificationChannel `json:"notification_channel"`
}
// ListNotificationChannels lists notification channels.
func (s *InsightsServiceOp) ListNotificationChannels(ctx context.Context, opt *ListOptions) ([]NotificationChannel, *Response, error) {
path, err := addOptions(insightsNotificationChannelsPath, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, nil, err
}
root := new(notificationChannelsRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
setListPaging(resp, root.Links, root.Meta)
return root.NotificationChannels, resp, nil
}
// GetNotificationChannel retrieves a notification channel. Secret fields are masked.
func (s *InsightsServiceOp) GetNotificationChannel(ctx context.Context, id string) (*NotificationChannel, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodGet, insightsResourcePath(insightsNotificationChannelsPath, id), nil)
if err != nil {
return nil, nil, err
}
root := new(notificationChannelRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.NotificationChannel, resp, nil
}
// CreateNotificationChannel creates a notification channel.
func (s *InsightsServiceOp) CreateNotificationChannel(ctx context.Context, create *NotificationChannelRequest) (*NotificationChannel, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodPost, insightsNotificationChannelsPath, create)
if err != nil {
return nil, nil, err
}
root := new(notificationChannelRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.NotificationChannel, resp, nil
}
// UpdateNotificationChannel replaces a notification channel's name and config.
func (s *InsightsServiceOp) UpdateNotificationChannel(ctx context.Context, id string, update *NotificationChannelRequest) (*NotificationChannel, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodPut, insightsResourcePath(insightsNotificationChannelsPath, id), update)
if err != nil {
return nil, nil, err
}
root := new(notificationChannelRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.NotificationChannel, resp, nil
}
// DeleteNotificationChannel deletes a notification channel.
// Deleting a channel that alert rules still reference returns 409 Conflict.
func (s *InsightsServiceOp) DeleteNotificationChannel(ctx context.Context, id string) (*Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodDelete, insightsResourcePath(insightsNotificationChannelsPath, id), nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AlertRuleListOptions are filters for listing alert rules.
type AlertRuleListOptions struct {
Page int `url:"page,omitempty"`
PerPage int `url:"per_page,omitempty"`
ResourceURN string `url:"resource_urn,omitempty"`
}
// AlertRule is an Insights alert rule.
type AlertRule struct {
ID string `json:"id"`
Spec AlertRuleSpec `json:"spec"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// AlertRuleRequest is the body for creating or updating an alert rule.
// Status is optional: create defaults to active, and update keeps the current status when empty.
type AlertRuleRequest struct {
Spec AlertRuleSpec `json:"spec"`
Status string `json:"status,omitempty"`
}
// AlertRuleSpec is the configuration of an alert rule.
type AlertRuleSpec struct {
Name string `json:"name"`
Query AlertMetricsQuery `json:"query"`
Condition *AlertCondition `json:"condition,omitempty"`
Thresholds AlertThresholds `json:"thresholds"`
// NotificationChannels are notified when the rule fires.
// On create, set a non-empty list. On update, leave nil to keep existing bindings.
// A pointer to an empty slice is sent as [] and the API rejects it.
NotificationChannels *[]NotificationChannelBinding `json:"notification_channels,omitempty"`
ReAlertDuration string `json:"re_alert_duration,omitempty"`
}
// AlertCondition is the evaluation window for an alert rule.
type AlertCondition struct {
Window string `json:"window,omitempty"`
}
// AlertThresholds is the comparison applied to the aggregated metric.
// At least one of Warning or Critical must be set. Use a pointer so a threshold of 0 is sent.
type AlertThresholds struct {
Warning *float64 `json:"warning,omitempty"`
Critical *float64 `json:"critical,omitempty"`
Operator string `json:"operator"`
}
// AlertMetricsQuery is the metric an alert rule evaluates.
// Metric must be a dotted OpenTelemetry name such as do.droplets.cpu_utilization.
type AlertMetricsQuery struct {
Metric string `json:"metric"`
Filters []AlertQueryFilter `json:"filters,omitempty"`
ResourceURNs []string `json:"resource_urns,omitempty"`
Tags []string `json:"tags,omitempty"`
}
// AlertQueryFilter is a label filter on an alert metrics query.
type AlertQueryFilter struct {
Field string `json:"field"`
Operator string `json:"operator"`
Value string `json:"value"`
}
// NotificationChannelBinding attaches a notification channel to an alert rule.
// An empty NotifyOn list notifies on every severity.
type NotificationChannelBinding struct {
NotificationChannelID string `json:"notification_channel_id"`
NotifyOn []string `json:"notify_on,omitempty"`
}
type alertRulesRoot struct {
AlertRules []AlertRule `json:"alert_rules"`
Links *Links `json:"links"`
Meta *Meta `json:"meta"`
}
type alertRuleRoot struct {
AlertRule *AlertRule `json:"alert_rule"`
}
// ListAlertRules lists alert rules.
func (s *InsightsServiceOp) ListAlertRules(ctx context.Context, opt *AlertRuleListOptions) ([]AlertRule, *Response, error) {
path, err := addOptions(insightsAlertRulesPath, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, nil, err
}
root := new(alertRulesRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
setListPaging(resp, root.Links, root.Meta)
return root.AlertRules, resp, nil
}
// GetAlertRule retrieves an alert rule.
func (s *InsightsServiceOp) GetAlertRule(ctx context.Context, id string) (*AlertRule, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodGet, insightsResourcePath(insightsAlertRulesPath, id), nil)
if err != nil {
return nil, nil, err
}
root := new(alertRuleRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.AlertRule, resp, nil
}
// CreateAlertRule creates an alert rule.
func (s *InsightsServiceOp) CreateAlertRule(ctx context.Context, create *AlertRuleRequest) (*AlertRule, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodPost, insightsAlertRulesPath, create)
if err != nil {
return nil, nil, err
}
root := new(alertRuleRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.AlertRule, resp, nil
}
// UpdateAlertRule updates an alert rule. Omitted status, re-alert duration, and
// notification channel bindings are left unchanged.
func (s *InsightsServiceOp) UpdateAlertRule(ctx context.Context, id string, update *AlertRuleRequest) (*AlertRule, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodPut, insightsResourcePath(insightsAlertRulesPath, id), update)
if err != nil {
return nil, nil, err
}
root := new(alertRuleRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.AlertRule, resp, nil
}
// DeleteAlertRule deletes an alert rule.
func (s *InsightsServiceOp) DeleteAlertRule(ctx context.Context, id string) (*Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodDelete, insightsResourcePath(insightsAlertRulesPath, id), nil)
if err != nil {
return nil, err
}
return s.client.Do(ctx, req, nil)
}
// AlertInstanceListOptions are filters for listing alert instances.
type AlertInstanceListOptions struct {
Page int `url:"page,omitempty"`
PerPage int `url:"per_page,omitempty"`
Status string `url:"status,omitempty"`
RuleID string `url:"rule_id,omitempty"`
ResourceURN string `url:"resource_urn,omitempty"`
}
// AlertInstance is a read-only firing of an alert rule against a resource.
type AlertInstance struct {
ID string `json:"id"`
RuleID string `json:"rule_id"`
Severity string `json:"severity"`
Status string `json:"status"`
ResourceURN string `json:"resource_urn,omitempty"`
Value float64 `json:"value"`
TriggeredAt time.Time `json:"triggered_at"`
LastTriggeredAt time.Time `json:"last_triggered_at"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
LastNotifiedAt *time.Time `json:"last_notified_at,omitempty"`
}
type alertInstancesRoot struct {
AlertInstances []AlertInstance `json:"alert_instances"`
Links *Links `json:"links"`
Meta *Meta `json:"meta"`
}
type alertInstanceRoot struct {
AlertInstance *AlertInstance `json:"alert_instance"`
}
// ListAlertInstances lists alert instances, newest trigger first.
func (s *InsightsServiceOp) ListAlertInstances(ctx context.Context, opt *AlertInstanceListOptions) ([]AlertInstance, *Response, error) {
path, err := addOptions(insightsAlertInstancesPath, opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, nil, err
}
root := new(alertInstancesRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
setListPaging(resp, root.Links, root.Meta)
return root.AlertInstances, resp, nil
}
// GetAlertInstance retrieves an alert instance.
func (s *InsightsServiceOp) GetAlertInstance(ctx context.Context, id string) (*AlertInstance, *Response, error) {
req, err := s.client.NewRequest(ctx, http.MethodGet, insightsResourcePath(insightsAlertInstancesPath, id), nil)
if err != nil {
return nil, nil, err
}
root := new(alertInstanceRoot)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return nil, resp, err
}
return root.AlertInstance, resp, nil
}
// LogsSearchRequest describes an Insights logs search. TimeRange must not
// exceed seven days.
type LogsSearchRequest struct {
TimeRange LogsTimeRange `json:"time_range"`
Filter *LogsFilterExpression `json:"filter,omitempty"`
OrderBy []LogsOrderBy `json:"order_by,omitempty"`
Pagination *LogsPaginationRequest `json:"pagination,omitempty"`
}
// LogsTimeRange is an inclusive logs query time window.
type LogsTimeRange struct {
From LogsTimeInstant `json:"from"`
To LogsTimeInstant `json:"to"`
}
// LogsTimeInstant identifies a point in time. Set exactly one of Absolute,
// Relative, or UnixNano.
type LogsTimeInstant struct {
Absolute string `json:"absolute,omitempty"`
Relative string `json:"relative,omitempty"`
UnixNano string `json:"unix_nano,omitempty"`
}
// LogsFilterExpression is a boolean filter tree. Set exactly one expression
// node.
type LogsFilterExpression struct {
Condition *LogsFilterCondition `json:"condition,omitempty"`
And *LogsFilterGroup `json:"and,omitempty"`
Or *LogsFilterGroup `json:"or,omitempty"`
Not *LogsFilterExpression `json:"not,omitempty"`
TextSearch *LogsTextSearch `json:"text_search,omitempty"`
}
// LogsFilterGroup combines nested logs filter expressions.
type LogsFilterGroup struct {
Expressions []LogsFilterExpression `json:"expressions"`
}
// LogsTextSearch searches for a substring across the log body, service name,
// and resource URN.
type LogsTextSearch struct {
Query string `json:"query"`
}
// LogsFilterCondition is a single field comparison.
type LogsFilterCondition struct {
Field LogsFieldRef `json:"field"`
Operator string `json:"operator"`
Value *LogsFilterValue `json:"value,omitempty"`
}
// LogsFieldRef identifies an intrinsic field or an attribute.
type LogsFieldRef struct {
Name string `json:"name"`
Scope string `json:"scope,omitempty"`
}
// LogsFilterValue is a typed filter literal. Set exactly one value.
// Scalar fields use pointers so zero, false, and an empty string can be sent.
type LogsFilterValue struct {
StringValue *string `json:"string_value,omitempty"`
NumberValue *float64 `json:"number_value,omitempty"`
BoolValue *bool `json:"bool_value,omitempty"`
StringArrayValue *LogsStringArrayValue `json:"string_array_value,omitempty"`
NumberArrayValue *LogsNumberArrayValue `json:"number_array_value,omitempty"`
}
// LogsStringArrayValue is a string-list filter value.
type LogsStringArrayValue struct {
Values []string `json:"values"`
}
// LogsNumberArrayValue is a number-list filter value.
type LogsNumberArrayValue struct {
Values []float64 `json:"values"`
}
// LogsOrderBy is a logs search sort clause. Cursor pagination is available
// only when ordering by timestamp alone.
type LogsOrderBy struct {
Field LogsFieldRef `json:"field"`
Direction string `json:"direction,omitempty"`
}
// LogsPaginationRequest configures cursor pagination for a logs search.
type LogsPaginationRequest struct {
// Limit defaults to 100 and is clamped to 1000 by the API.
Limit int `json:"limit,omitempty"`
Cursor string `json:"cursor,omitempty"`
}
// LogsSearchResponse contains matching log records and pagination state.
type LogsSearchResponse struct {
Data []InsightsLogRecord `json:"data,omitempty"`
Pagination *LogsPaginationResponse `json:"pagination,omitempty"`
}
// LogsPaginationResponse describes the next page of logs search results.
type LogsPaginationResponse struct {
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor,omitempty"`
}
// InsightsLogRecord is a single log record returned by an Insights logs search.
type InsightsLogRecord struct {
Timestamp time.Time `json:"timestamp"`
SeverityNumber int32 `json:"severity_number,omitempty"`
SeverityText string `json:"severity_text,omitempty"`
Body string `json:"body,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
ServiceName string `json:"service_name,omitempty"`
Resource map[string]string `json:"resource,omitempty"`
Attributes map[string]string `json:"attributes,omitempty"`
}
// SearchLogs searches log records in a region. Cursor pagination requires
// ordering by timestamp alone; other sort orders return HasMore as false.
func (s *InsightsServiceOp) SearchLogs(ctx context.Context, region string, search *LogsSearchRequest) (*LogsSearchResponse, *Response, error) {
path := "/v2/insights/query/" + url.PathEscape(region) + "/logs/search"
req, err := s.client.NewRequest(ctx, http.MethodPost, path, search)
if err != nil {
return nil, nil, err
}
result := new(LogsSearchResponse)
resp, err := s.client.Do(ctx, req, result)
if err != nil {
return nil, resp, err
}
return result, resp, nil
}
// PromQueryOptions are parameters for an instant PromQL query.
// Time and Timeout accept Prometheus timestamps and duration strings.
type PromQueryOptions struct {
Query string `url:"query"`
Time string `url:"time,omitempty"`
Timeout string `url:"timeout,omitempty"`
}
// PromQueryRangeOptions are parameters for a range PromQL query.
type PromQueryRangeOptions struct {
Query string `url:"query"`
Start string `url:"start"`
End string `url:"end"`
Step string `url:"step"`
Timeout string `url:"timeout,omitempty"`
}
// PromSelectorOptions are parameters for series, label, and label-value lookups.
// Match is repeated as match[] selectors.
type PromSelectorOptions struct {
Match []string `url:"match,brackets,omitempty"`
Start string `url:"start,omitempty"`
End string `url:"end,omitempty"`
}
// PromQueryResponse is a successful instant PromQL query.
// ResultType is vector, matrix, scalar, or string. Exactly one of Vector, Matrix, or Sample is set.
type PromQueryResponse struct {
Status string
ResultType string
Vector []PromVectorSample
Matrix []PromMatrixSample
Sample *PromSample
}
// PromQueryRangeResponse is a successful range PromQL query. Data.ResultType is matrix.
type PromQueryRangeResponse struct {
Status string `json:"status"`
Data PromMatrixResult `json:"data"`
}
// PromMatrixResult is the data object of a range query.
type PromMatrixResult struct {
ResultType string `json:"resultType"`
Result []PromMatrixSample `json:"result"`
}
// PromVectorSample is one series from an instant vector result.
type PromVectorSample struct {
Metric map[string]string `json:"metric"`
Value PromSample `json:"value"`
}
// PromMatrixSample is one series from a range result.
type PromMatrixSample struct {
Metric map[string]string `json:"metric"`
Values []PromSample `json:"values"`
}
// PromSample is a Prometheus sample pair [timestamp_seconds, value].
// Value is the raw string from the API, including non-numeric string results.
type PromSample struct {
Timestamp float64
Value string
}
// PromSeriesResponse lists series matching one or more selectors.
type PromSeriesResponse struct {
Status string `json:"status"`
Data []map[string]string `json:"data"`
}
// PromLabelsResponse lists label names or the values of one label.
type PromLabelsResponse struct {
Status string `json:"status"`
Data []string `json:"data"`
}
// UnmarshalJSON decodes a Prometheus instant-query envelope.
func (r *PromQueryResponse) UnmarshalJSON(data []byte) error {
var raw struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result json.RawMessage `json:"result"`
} `json:"data"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
r.Status = raw.Status
r.ResultType = raw.Data.ResultType
if len(raw.Data.Result) == 0 || string(raw.Data.Result) == "null" {
return nil
}
switch raw.Data.ResultType {
case "vector":
return json.Unmarshal(raw.Data.Result, &r.Vector)
case "matrix":
return json.Unmarshal(raw.Data.Result, &r.Matrix)
case "scalar", "string":
r.Sample = &PromSample{}
return json.Unmarshal(raw.Data.Result, r.Sample)
default:
return fmt.Errorf("godo: unknown PromQL result type %q", raw.Data.ResultType)
}
}
// UnmarshalJSON decodes a Prometheus [timestamp, value] sample.
func (s *PromSample) UnmarshalJSON(data []byte) error {
var pair []json.RawMessage
if err := json.Unmarshal(data, &pair); err != nil {
return err
}
if len(pair) != 2 {
return fmt.Errorf("godo: prom sample has %d elements", len(pair))
}
if err := json.Unmarshal(pair[0], &s.Timestamp); err != nil {
return err
}
return json.Unmarshal(pair[1], &s.Value)
}
// Query evaluates a PromQL expression at a single timestamp.
func (s *InsightsServiceOp) Query(ctx context.Context, region string, opt *PromQueryOptions) (*PromQueryResponse, *Response, error) {
return s.promGet(ctx, insightsPromPath(region, "query"), opt)
}
// PostQuery evaluates a PromQL expression at a single timestamp using a form body.
func (s *InsightsServiceOp) PostQuery(ctx context.Context, region string, opt *PromQueryOptions) (*PromQueryResponse, *Response, error) {
return s.promPost(ctx, insightsPromPath(region, "query"), opt)
}
// QueryRange evaluates a PromQL expression over a time range.
func (s *InsightsServiceOp) QueryRange(ctx context.Context, region string, opt *PromQueryRangeOptions) (*PromQueryRangeResponse, *Response, error) {
out := new(PromQueryRangeResponse)
resp, err := s.promDo(ctx, http.MethodGet, insightsPromPath(region, "query_range"), opt, out)
if err != nil {
return nil, resp, err
}
return out, resp, nil
}
// PostQueryRange evaluates a PromQL expression over a time range using a form body.
func (s *InsightsServiceOp) PostQueryRange(ctx context.Context, region string, opt *PromQueryRangeOptions) (*PromQueryRangeResponse, *Response, error) {
out := new(PromQueryRangeResponse)
resp, err := s.promDo(ctx, http.MethodPost, insightsPromPath(region, "query_range"), opt, out)
if err != nil {
return nil, resp, err
}
return out, resp, nil
}
// Series finds series matching label selectors.
func (s *InsightsServiceOp) Series(ctx context.Context, region string, opt *PromSelectorOptions) (*PromSeriesResponse, *Response, error) {
out := new(PromSeriesResponse)
resp, err := s.promDo(ctx, http.MethodGet, insightsPromPath(region, "series"), opt, out)
if err != nil {
return nil, resp, err
}
return out, resp, nil
}
// PostSeries finds series matching label selectors using a form body.
func (s *InsightsServiceOp) PostSeries(ctx context.Context, region string, opt *PromSelectorOptions) (*PromSeriesResponse, *Response, error) {
out := new(PromSeriesResponse)
resp, err := s.promDo(ctx, http.MethodPost, insightsPromPath(region, "series"), opt, out)
if err != nil {
return nil, resp, err
}
return out, resp, nil
}
// Labels lists label names.
func (s *InsightsServiceOp) Labels(ctx context.Context, region string, opt *PromSelectorOptions) (*PromLabelsResponse, *Response, error) {
out := new(PromLabelsResponse)
resp, err := s.promDo(ctx, http.MethodGet, insightsPromPath(region, "labels"), opt, out)
if err != nil {
return nil, resp, err
}
return out, resp, nil
}
// PostLabels lists label names using a form body.
func (s *InsightsServiceOp) PostLabels(ctx context.Context, region string, opt *PromSelectorOptions) (*PromLabelsResponse, *Response, error) {
out := new(PromLabelsResponse)
resp, err := s.promDo(ctx, http.MethodPost, insightsPromPath(region, "labels"), opt, out)
if err != nil {
return nil, resp, err
}
return out, resp, nil
}
// LabelValues lists values for a label name.
func (s *InsightsServiceOp) LabelValues(ctx context.Context, region, name string, opt *PromSelectorOptions) (*PromLabelsResponse, *Response, error) {
out := new(PromLabelsResponse)