-
Notifications
You must be signed in to change notification settings - Fork 117
/
alerts.go
624 lines (540 loc) · 21.3 KB
/
alerts.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
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
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"path"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/rilldata/rill/admin/database"
"github.com/rilldata/rill/admin/server/auth"
adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime"
"github.com/rilldata/rill/runtime/drivers/slack"
"github.com/rilldata/rill/runtime/pkg/observability"
"github.com/rilldata/rill/runtime/pkg/pbutil"
"go.opentelemetry.io/otel/attribute"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/structpb"
"gopkg.in/yaml.v3"
)
func (s *Server) GetAlertMeta(ctx context.Context, req *adminv1.GetAlertMetaRequest) (*adminv1.GetAlertMetaResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.project_id", req.ProjectId),
attribute.String("args.branch", req.Branch),
attribute.String("args.alert", req.Alert),
attribute.Bool("args.query_for", req.GetQueryFor() != nil),
)
proj, err := s.admin.DB.FindProject(ctx, req.ProjectId)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "project not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
permissions := auth.GetClaims(ctx).ProjectPermissions(ctx, proj.OrganizationID, proj.ID)
if !permissions.ReadProdStatus {
return nil, status.Error(codes.PermissionDenied, "does not have permission to read alert meta")
}
if proj.ProdBranch != req.Branch {
return nil, status.Error(codes.InvalidArgument, "branch not found")
}
org, err := s.admin.DB.FindOrganization(ctx, proj.OrganizationID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
var attr map[string]any
if req.QueryFor != nil {
switch forVal := req.QueryFor.(type) {
case *adminv1.GetAlertMetaRequest_QueryForUserId:
attr, err = s.getAttributesForUser(ctx, proj.OrganizationID, proj.ID, forVal.QueryForUserId, "")
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
case *adminv1.GetAlertMetaRequest_QueryForUserEmail:
attr, err = s.getAttributesForUser(ctx, proj.OrganizationID, proj.ID, "", forVal.QueryForUserEmail)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
default:
return nil, status.Error(codes.InvalidArgument, "invalid 'for' type")
}
}
var attrPB *structpb.Struct
if attr != nil {
attrPB, err = structpb.NewStruct(attr)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}
return &adminv1.GetAlertMetaResponse{
OpenUrl: s.urls.alertOpen(org.Name, proj.Name, req.Alert),
EditUrl: s.urls.alertEdit(org.Name, proj.Name, req.Alert),
QueryForAttributes: attrPB,
}, nil
}
func (s *Server) CreateAlert(ctx context.Context, req *adminv1.CreateAlertRequest) (*adminv1.CreateAlertResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.organization", req.Organization),
attribute.String("args.project", req.Project),
)
proj, err := s.admin.DB.FindProjectByName(ctx, req.Organization, req.Project)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "project not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
permissions := claims.ProjectPermissions(ctx, proj.OrganizationID, proj.ID)
if !permissions.CreateAlerts {
return nil, status.Error(codes.PermissionDenied, "does not have permission to read project repo")
}
if claims.OwnerType() != auth.OwnerTypeUser {
return nil, status.Error(codes.PermissionDenied, "only users can create alerts")
}
if proj.ProdDeploymentID == nil {
return nil, status.Error(codes.FailedPrecondition, "project does not have a production deployment")
}
depl, err := s.admin.DB.FindDeployment(ctx, *proj.ProdDeploymentID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
name, err := s.generateAlertName(ctx, depl, req.Options.Title)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
data, err := s.yamlForManagedAlert(req.Options, claims.OwnerID())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to generate alert YAML: %s", err.Error())
}
err = s.admin.DB.UpsertVirtualFile(ctx, &database.InsertVirtualFileOptions{
ProjectID: proj.ID,
Branch: proj.ProdBranch,
Path: virtualFilePathForManagedAlert(name),
Data: data,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to insert virtual file: %s", err.Error())
}
err = s.admin.TriggerReconcileAndAwaitResource(ctx, depl, name, runtime.ResourceKindAlert)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be created")
}
return nil, status.Errorf(codes.Internal, "failed to reconcile alert: %s", err.Error())
}
return &adminv1.CreateAlertResponse{
Name: name,
}, nil
}
func (s *Server) EditAlert(ctx context.Context, req *adminv1.EditAlertRequest) (*adminv1.EditAlertResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.organization", req.Organization),
attribute.String("args.project", req.Project),
attribute.String("args.name", req.Name),
)
proj, err := s.admin.DB.FindProjectByName(ctx, req.Organization, req.Project)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "project not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
permissions := claims.ProjectPermissions(ctx, proj.OrganizationID, proj.ID)
if !permissions.ReadProd {
return nil, status.Error(codes.PermissionDenied, "does not have permission to read project repo")
}
if proj.ProdDeploymentID == nil {
return nil, status.Error(codes.FailedPrecondition, "project does not have a production deployment")
}
depl, err := s.admin.DB.FindDeployment(ctx, *proj.ProdDeploymentID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
spec, err := s.admin.LookupAlert(ctx, depl, req.Name)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "could not get alert: %s", err.Error())
}
annotations := parseAlertAnnotations(spec.Annotations)
if !annotations.AdminManaged {
return nil, status.Error(codes.FailedPrecondition, "can't edit alert because it was not created from the UI")
}
isOwner := claims.OwnerType() == auth.OwnerTypeUser && annotations.AdminOwnerUserID == claims.OwnerID()
if !permissions.ManageAlerts && !isOwner {
return nil, status.Error(codes.PermissionDenied, "does not have permission to edit alert")
}
data, err := s.yamlForManagedAlert(req.Options, annotations.AdminOwnerUserID)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to generate alert YAML: %s", err.Error())
}
err = s.admin.DB.UpsertVirtualFile(ctx, &database.InsertVirtualFileOptions{
ProjectID: proj.ID,
Branch: proj.ProdBranch,
Path: virtualFilePathForManagedAlert(req.Name),
Data: data,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to update virtual file: %s", err.Error())
}
err = s.admin.TriggerReconcileAndAwaitResource(ctx, depl, req.Name, runtime.ResourceKindAlert)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be updated")
}
return nil, status.Errorf(codes.Internal, "failed to reconcile alert: %s", err.Error())
}
return &adminv1.EditAlertResponse{}, nil
}
func (s *Server) UnsubscribeAlert(ctx context.Context, req *adminv1.UnsubscribeAlertRequest) (*adminv1.UnsubscribeAlertResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.organization", req.Organization),
attribute.String("args.project", req.Project),
attribute.String("args.name", req.Name),
)
proj, err := s.admin.DB.FindProjectByName(ctx, req.Organization, req.Project)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "project not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
permissions := claims.ProjectPermissions(ctx, proj.OrganizationID, proj.ID)
if !permissions.ReadProd {
return nil, status.Error(codes.PermissionDenied, "does not have permission to read project repo")
}
if proj.ProdDeploymentID == nil {
return nil, status.Error(codes.FailedPrecondition, "project does not have a production deployment")
}
depl, err := s.admin.DB.FindDeployment(ctx, *proj.ProdDeploymentID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
spec, err := s.admin.LookupAlert(ctx, depl, req.Name)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "could not get alert: %s", err.Error())
}
annotations := parseAlertAnnotations(spec.Annotations)
if !annotations.AdminManaged {
return nil, status.Error(codes.FailedPrecondition, "can't edit alert because it was not created from the UI")
}
if claims.OwnerType() != auth.OwnerTypeUser {
return nil, status.Error(codes.PermissionDenied, "only users can unsubscribe from alerts")
}
user, err := s.admin.DB.FindUser(ctx, claims.OwnerID())
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
opts, err := recreateAlertOptionsFromSpec(spec)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to recreate alert options: %s", err.Error())
}
found := false
for idx, email := range opts.EmailRecipients {
if strings.EqualFold(user.Email, email) {
opts.EmailRecipients = slices.Delete(opts.EmailRecipients, idx, idx+1)
found = true
break
}
}
for idx, email := range opts.SlackUsers {
if strings.EqualFold(user.Email, email) {
opts.SlackUsers = slices.Delete(opts.SlackUsers, idx, idx+1)
found = true
break
}
}
if !found {
return nil, status.Error(codes.InvalidArgument, "user is not subscribed to alert")
}
if len(opts.EmailRecipients) == 0 && len(opts.SlackUsers) == 0 && len(opts.SlackChannels) == 0 && len(opts.SlackWebhooks) == 0 {
err = s.admin.DB.UpdateVirtualFileDeleted(ctx, proj.ID, proj.ProdBranch, virtualFilePathForManagedAlert(req.Name))
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to update virtual file: %s", err.Error())
}
} else {
data, err := s.yamlForManagedAlert(opts, annotations.AdminOwnerUserID)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to generate alert YAML: %s", err.Error())
}
err = s.admin.DB.UpsertVirtualFile(ctx, &database.InsertVirtualFileOptions{
ProjectID: proj.ID,
Branch: proj.ProdBranch,
Path: virtualFilePathForManagedAlert(req.Name),
Data: data,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to update virtual file: %s", err.Error())
}
}
err = s.admin.TriggerReconcileAndAwaitResource(ctx, depl, req.Name, runtime.ResourceKindAlert)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be updated")
}
return nil, status.Errorf(codes.Internal, "failed to reconcile alert: %s", err.Error())
}
return &adminv1.UnsubscribeAlertResponse{}, nil
}
func (s *Server) DeleteAlert(ctx context.Context, req *adminv1.DeleteAlertRequest) (*adminv1.DeleteAlertResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.organization", req.Organization),
attribute.String("args.project", req.Project),
attribute.String("args.name", req.Name),
)
proj, err := s.admin.DB.FindProjectByName(ctx, req.Organization, req.Project)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "project not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
permissions := claims.ProjectPermissions(ctx, proj.OrganizationID, proj.ID)
if !permissions.ReadProd {
return nil, status.Error(codes.PermissionDenied, "does not have permission to read project repo")
}
if proj.ProdDeploymentID == nil {
return nil, status.Error(codes.FailedPrecondition, "project does not have a production deployment")
}
depl, err := s.admin.DB.FindDeployment(ctx, *proj.ProdDeploymentID)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
spec, err := s.admin.LookupAlert(ctx, depl, req.Name)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "could not get alert: %s", err.Error())
}
annotations := parseAlertAnnotations(spec.Annotations)
if !annotations.AdminManaged {
return nil, status.Error(codes.FailedPrecondition, "can't edit alert because it was not created from the UI")
}
isOwner := claims.OwnerType() == auth.OwnerTypeUser && annotations.AdminOwnerUserID == claims.OwnerID()
if !permissions.ManageAlerts && !isOwner {
return nil, status.Error(codes.PermissionDenied, "does not have permission to edit alert")
}
err = s.admin.DB.UpdateVirtualFileDeleted(ctx, proj.ID, proj.ProdBranch, virtualFilePathForManagedAlert(req.Name))
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete virtual file: %s", err.Error())
}
err = s.admin.TriggerReconcileAndAwaitResource(ctx, depl, req.Name, runtime.ResourceKindAlert)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return nil, status.Error(codes.DeadlineExceeded, "timed out waiting for alert to be deleted")
}
return nil, status.Errorf(codes.Internal, "failed to reconcile alert: %s", err.Error())
}
return &adminv1.DeleteAlertResponse{}, nil
}
func (s *Server) GenerateAlertYAML(ctx context.Context, req *adminv1.GenerateAlertYAMLRequest) (*adminv1.GenerateAlertYAMLResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.organization", req.Organization),
attribute.String("args.project", req.Project),
)
data, err := s.yamlForCommittedAlert(req.Options)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to generate alert YAML: %s", err.Error())
}
return &adminv1.GenerateAlertYAMLResponse{
Yaml: string(data),
}, nil
}
func (s *Server) GetAlertYAML(ctx context.Context, req *adminv1.GetAlertYAMLRequest) (*adminv1.GetAlertYAMLResponse, error) {
observability.AddRequestAttributes(ctx,
attribute.String("args.organization", req.Organization),
attribute.String("args.project", req.Project),
attribute.String("args.name", req.Name),
)
proj, err := s.admin.DB.FindProjectByName(ctx, req.Organization, req.Project)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, status.Error(codes.NotFound, "project not found")
}
return nil, status.Error(codes.InvalidArgument, err.Error())
}
claims := auth.GetClaims(ctx)
permissions := claims.ProjectPermissions(ctx, proj.OrganizationID, proj.ID)
if !permissions.ReadProd {
return nil, status.Error(codes.PermissionDenied, "does not have permission to read project repo")
}
if proj.ProdDeploymentID == nil {
return nil, status.Error(codes.FailedPrecondition, "project does not have a production deployment")
}
vf, err := s.admin.DB.FindVirtualFile(ctx, proj.ID, proj.ProdBranch, virtualFilePathForManagedAlert(req.Name))
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if vf == nil {
return nil, status.Error(codes.NotFound, fmt.Sprintf("failed to find file for alert %s", req.Name))
}
return &adminv1.GetAlertYAMLResponse{
Yaml: string(vf.Data),
}, nil
}
func (s *Server) yamlForManagedAlert(opts *adminv1.AlertOptions, ownerUserID string) ([]byte, error) {
res := alertYAML{}
res.Type = "alert"
// Trigger the alert when the metrics view refreshes.
res.Refs = []string{fmt.Sprintf("MetricsView/%s", opts.MetricsViewName)}
res.Title = opts.Title
res.Watermark = "inherit"
res.Intervals.Duration = opts.IntervalDuration
res.Query.Name = opts.QueryName
res.Query.ArgsJSON = opts.QueryArgsJson
// Hard code the user id to run for (to avoid exposing data through alert creation)
res.Query.For.UserID = ownerUserID
// Notification options
res.Renotify = opts.Renotify
res.RenotifyAfter = opts.RenotifyAfterSeconds
res.Notify.Email.Recipients = opts.EmailRecipients
res.Notify.Slack.Channels = opts.SlackChannels
res.Notify.Slack.Users = opts.SlackUsers
res.Notify.Slack.Webhooks = opts.SlackWebhooks
res.Annotations.AdminOwnerUserID = ownerUserID
res.Annotations.AdminManaged = true
res.Annotations.AdminNonce = time.Now().Format(time.RFC3339Nano)
return yaml.Marshal(res)
}
func (s *Server) yamlForCommittedAlert(opts *adminv1.AlertOptions) ([]byte, error) {
// Format args as pretty YAML
var args map[string]interface{}
if opts.QueryArgsJson != "" {
err := json.Unmarshal([]byte(opts.QueryArgsJson), &args)
if err != nil {
return nil, fmt.Errorf("failed to parse queryArgsJSON: %w", err)
}
}
res := alertYAML{}
res.Type = "alert"
// Trigger the alert when the metrics view refreshes.
res.Refs = []string{fmt.Sprintf("MetricsView/%s", opts.MetricsViewName)}
res.Title = opts.Title
res.Watermark = "inherit"
res.Intervals.Duration = opts.IntervalDuration
res.Query.Name = opts.QueryName
res.Query.Args = args
// Notification options
res.Renotify = opts.Renotify
res.RenotifyAfter = opts.RenotifyAfterSeconds
res.Notify.Email.Recipients = opts.EmailRecipients
res.Notify.Slack.Channels = opts.SlackChannels
res.Notify.Slack.Users = opts.SlackUsers
res.Notify.Slack.Webhooks = opts.SlackWebhooks
return yaml.Marshal(res)
}
// generateAlertName generates a random alert name with the title as a seed.
// Example: "My alert!" -> "my-alert-5b3f7e1a".
// It verifies that the name is not taken (the random component makes any collision unlikely, but we check to be sure).
func (s *Server) generateAlertName(ctx context.Context, depl *database.Deployment, title string) (string, error) {
for i := 0; i < 5; i++ {
name := randomAlertName(title)
_, err := s.admin.LookupAlert(ctx, depl, name)
if err != nil {
if s, ok := status.FromError(err); ok && s.Code() == codes.NotFound {
// Success! Name isn't taken
return name, nil
}
return "", fmt.Errorf("failed to check alert name: %w", err)
}
}
// Fail-safe in case all names we tried were taken
return uuid.New().String(), nil
}
var alertNameToDashCharsRegexp = regexp.MustCompile(`[ _]+`)
var alertNameExcludeCharsRegexp = regexp.MustCompile(`[^a-zA-Z0-9-]+`)
func randomAlertName(title string) string {
name := alertNameToDashCharsRegexp.ReplaceAllString(title, "-")
name = alertNameExcludeCharsRegexp.ReplaceAllString(name, "")
name = strings.ToLower(name)
name = strings.Trim(name, "-")
if name == "" {
name = uuid.New().String()
} else {
name = name + "-" + uuid.New().String()[0:8]
}
return name
}
func recreateAlertOptionsFromSpec(spec *runtimev1.AlertSpec) (*adminv1.AlertOptions, error) {
opts := &adminv1.AlertOptions{}
opts.Title = spec.Title
opts.IntervalDuration = spec.IntervalsIsoDuration
opts.QueryName = spec.QueryName
opts.QueryArgsJson = spec.QueryArgsJson
opts.Renotify = spec.Renotify
opts.RenotifyAfterSeconds = spec.RenotifyAfterSeconds
for _, notifier := range spec.Notifiers {
switch notifier.Connector {
case "email":
opts.EmailRecipients = pbutil.ToSliceString(notifier.Properties.AsMap()["recipients"])
case "slack":
props, err := slack.DecodeProps(notifier.Properties.AsMap())
if err != nil {
return nil, err
}
opts.SlackUsers = props.Users
opts.SlackChannels = props.Channels
opts.SlackWebhooks = props.Webhooks
default:
return nil, fmt.Errorf("unknown notifier connector: %s", notifier.Connector)
}
}
return opts, nil
}
// alertYAML is derived from rillv1.AlertYAML, but adapted for generating (as opposed to parsing) the alert YAML.
type alertYAML struct {
Type string `yaml:"type"`
Refs []string `yaml:"refs"`
Title string `yaml:"title"`
Watermark string `yaml:"watermark"`
Intervals struct {
Duration string `yaml:"duration"`
} `yaml:"intervals"`
Query struct {
Name string `yaml:"name"`
Args map[string]any `yaml:"args,omitempty"`
ArgsJSON string `yaml:"args_json,omitempty"`
For struct {
UserID string `yaml:"user_id"`
} `yaml:"for"`
} `yaml:"query"`
Renotify bool `yaml:"renotify"`
RenotifyAfter uint32 `yaml:"renotify_after"`
Notify struct {
Email struct {
Recipients []string `yaml:"recipients"`
}
Slack struct {
Users []string `yaml:"users"`
Channels []string `yaml:"channels"`
Webhooks []string `yaml:"webhooks"`
}
}
Annotations alertAnnotations `yaml:"annotations,omitempty"`
}
type alertAnnotations struct {
AdminOwnerUserID string `yaml:"admin_owner_user_id"`
AdminManaged bool `yaml:"admin_managed"`
AdminNonce string `yaml:"admin_nonce"` // To ensure spec version gets updated on writes, to enable polling in TriggerReconcileAndAwaitAlert
}
func parseAlertAnnotations(annotations map[string]string) alertAnnotations {
if annotations == nil {
return alertAnnotations{}
}
res := alertAnnotations{}
res.AdminOwnerUserID = annotations["admin_owner_user_id"]
res.AdminManaged, _ = strconv.ParseBool(annotations["admin_managed"])
res.AdminNonce = annotations["admin_nonce"]
return res
}
func virtualFilePathForManagedAlert(name string) string {
return path.Join("alerts", name+".yaml")
}