-
Notifications
You must be signed in to change notification settings - Fork 0
/
notification_policies.gen.go
583 lines (517 loc) · 17.7 KB
/
notification_policies.gen.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
// Code generated by chronogen; DO NOT EDIT
package configv1
import (
"context"
"fmt"
"github.com/chronosphereio/chronoctl-core/src/cmd/cli"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/client"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/clienterror"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/dry"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/file"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/groups"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/output"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/pagination"
"github.com/chronosphereio/chronoctl-core/src/cmd/pkg/ptr"
config_v1 "github.com/chronosphereio/chronoctl-core/src/generated/swagger/configv1/client/operations"
"github.com/chronosphereio/chronoctl-core/src/generated/swagger/configv1/models"
"github.com/chronosphereio/chronoctl-core/src/types"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
)
func init() { types.MustRegisterObject(NotificationPolicyTypeMeta, &NotificationPolicy{}) }
var _ types.Object = &NotificationPolicy{}
var NotificationPolicyTypeMeta = types.TypeMeta{
APIVersion: "v1/config",
Kind: "NotificationPolicy",
}
type NotificationPolicy struct {
types.TypeMeta `json:",inline"`
Spec *models.Configv1NotificationPolicy `json:"spec"`
}
func NewNotificationPolicy(spec *models.Configv1NotificationPolicy) *NotificationPolicy {
return &NotificationPolicy{
TypeMeta: NotificationPolicyTypeMeta,
Spec: spec,
}
}
func (e *NotificationPolicy) Description() string {
return types.TypeDescription(e, "name", e.Spec.Name, "slug", e.Spec.Slug)
}
func (e *NotificationPolicy) Identifier() string {
return e.Spec.Slug
}
func CreateNotificationPolicy(
ctx context.Context,
client config_v1.ClientService,
entity *NotificationPolicy,
dryRun bool,
) (*NotificationPolicy, error) {
res, err := client.CreateNotificationPolicy(&config_v1.CreateNotificationPolicyParams{
Context: ctx,
Body: &models.Configv1CreateNotificationPolicyRequest{
DryRun: dryRun,
NotificationPolicy: entity.Spec,
},
})
if err != nil {
return nil, clienterror.Wrap(err)
}
return NewNotificationPolicy(res.Payload.NotificationPolicy), nil
}
func newNotificationPolicyCreateCmd() *cobra.Command {
var (
permissiveParsing bool
dryRunFlags = dry.NewFlags()
clientFlags = client.NewClientFlags()
outputFlags = output.NewFlags(output.WithoutOutputDirectory(), output.WithoutCreateFilePerObject())
fileFlags = file.NewFlags(true /* required */)
)
var (
use string
short string
)
use = "create -f <file>"
short = "Creates a single NotificationPolicy."
cmd := &cobra.Command{
Use: use,
GroupID: groups.Commands.ID,
Short: short,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(cmd.Context(), clientFlags.Timeout())
defer cancel()
if err := outputFlags.Validate(); err != nil {
return err
}
defer outputFlags.Close(cmd.OutOrStdout())
stderr := output.NewStderrPrinter(cmd)
client, err := clientFlags.ConfigV1Client()
if err != nil {
return err
}
var notificationPolicy *NotificationPolicy
file, err := fileFlags.File()
if err != nil {
return err
}
defer file.Close() //nolint:errcheck
notificationPolicy, err = types.MustDecodeSingleObject[*NotificationPolicy](file, permissiveParsing)
if err != nil {
return err
}
if dryRunFlags.DryRun {
stderr.Println("--dry-run is set")
}
fullNotificationPolicy, err := CreateNotificationPolicy(ctx, client, notificationPolicy, dryRunFlags.DryRun)
if err != nil {
return err
}
if dryRunFlags.DryRun {
stderr.Println("NotificationPolicy is valid and can be created")
return nil
}
stderr.Printf("NotificationPolicy with slug %q created successfully\n", fullNotificationPolicy.Spec.Slug)
if err := outputFlags.WriteObject(fullNotificationPolicy, cmd.OutOrStdout()); err != nil {
return err
}
return nil
},
}
dryRunFlags.AddFlags(cmd)
clientFlags.AddFlags(cmd)
outputFlags.AddFlags(cmd)
fileFlags.AddFlags(cmd)
cmd.Flags().BoolVar(&permissiveParsing, "no-strict", false, "If set, manifests with unknown fields are not rejected. Defaults to false.")
return cmd
}
func GetNotificationPolicy(
ctx context.Context,
client config_v1.ClientService,
slug string,
) (*NotificationPolicy, error) {
res, err := client.ReadNotificationPolicy(&config_v1.ReadNotificationPolicyParams{
Context: ctx,
Slug: slug,
})
if err != nil {
return nil, clienterror.Wrap(err)
}
return NewNotificationPolicy(res.GetPayload().NotificationPolicy), nil
}
func newNotificationPolicyReadCmd() *cobra.Command {
clientFlags := client.NewClientFlags()
outputFlags := output.NewFlags(output.WithoutOutputDirectory(), output.WithoutCreateFilePerObject())
var (
short string
use string
args cobra.PositionalArgs
)
short = "Reads a single NotificationPolicy by slug"
use = "read <slug>"
args = cobra.ExactArgs(1)
cmd := &cobra.Command{
Use: use,
GroupID: groups.Commands.ID,
Short: short,
Args: args,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(cmd.Context(), clientFlags.Timeout())
defer cancel()
if err := outputFlags.Validate(); err != nil {
return err
}
defer outputFlags.Close(cmd.OutOrStdout())
client, err := clientFlags.ConfigV1Client()
if err != nil {
return err
}
entity, err := GetNotificationPolicy(ctx, client, args[0])
if err != nil {
return err
}
if err := outputFlags.WriteObject(entity, cmd.OutOrStdout()); err != nil {
return err
}
return nil
},
}
clientFlags.AddFlags(cmd)
outputFlags.AddFlags(cmd)
return cmd
}
func UpdateNotificationPolicy(
ctx context.Context,
client config_v1.ClientService,
entity *NotificationPolicy,
opts UpdateOptions,
) (*NotificationPolicy, error) {
res, err := client.UpdateNotificationPolicy(&config_v1.UpdateNotificationPolicyParams{
Context: ctx,
Slug: entity.Spec.Slug,
Body: config_v1.UpdateNotificationPolicyBody{
CreateIfMissing: opts.CreateIfMissing,
DryRun: opts.DryRun,
NotificationPolicy: entity.Spec,
},
})
if err != nil {
return nil, clienterror.Wrap(err)
}
return NewNotificationPolicy(res.Payload.NotificationPolicy), nil
}
func newNotificationPolicyUpdateCmd() *cobra.Command {
var (
permissiveParsing bool
createIfMissing bool
dryRunFlags = dry.NewFlags()
clientFlags = client.NewClientFlags()
outputFlags = output.NewFlags(output.WithoutOutputDirectory(), output.WithoutCreateFilePerObject())
fileFlags = file.NewFlags(true /* required */)
)
cmd := &cobra.Command{
Use: "update -f <filename>",
GroupID: groups.Commands.ID,
Short: "Updates an existing NotificationPolicy.",
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(cmd.Context(), clientFlags.Timeout())
defer cancel()
if err := outputFlags.Validate(); err != nil {
return err
}
defer outputFlags.Close(cmd.OutOrStdout())
stderr := output.NewStderrPrinter(cmd)
client, err := clientFlags.ConfigV1Client()
if err != nil {
return err
}
file, err := fileFlags.File()
if err != nil {
return err
}
defer file.Close() //nolint:errcheck
notificationPolicy, err := types.MustDecodeSingleObject[*NotificationPolicy](file, permissiveParsing)
if err != nil {
return err
}
updateOpts := UpdateOptions{
DryRun: dryRunFlags.DryRun,
CreateIfMissing: createIfMissing,
}
if dryRunFlags.DryRun {
stderr.Println("--dry-run is set, update not persisted")
}
fullNotificationPolicy, err := UpdateNotificationPolicy(ctx, client, notificationPolicy, updateOpts)
if err != nil {
return err
}
if dryRunFlags.DryRun {
stderr.Println("NotificationPolicy is valid and can be updated")
return nil
}
stderr.Printf("NotificationPolicy with slug %q applied successfully\n", fullNotificationPolicy.Spec.Slug)
if err := outputFlags.WriteObject(fullNotificationPolicy, cmd.OutOrStdout()); err != nil {
return err
}
return nil
},
}
dryRunFlags.AddFlags(cmd)
clientFlags.AddFlags(cmd)
outputFlags.AddFlags(cmd)
fileFlags.AddFlags(cmd)
cmd.Flags().BoolVar(&permissiveParsing, "no-strict", false, "If set, manifests with unknown fields are allowed. Defaults to false.")
cmd.Flags().BoolVar(&createIfMissing, "create-if-missing", false, "If set, creates the NotificationPolicy if it does not already exist. Defaults to false.")
return cmd
}
func DeleteNotificationPolicy(
ctx context.Context,
client config_v1.ClientService,
slug string,
) error {
_, err := client.DeleteNotificationPolicy(&config_v1.DeleteNotificationPolicyParams{
Context: ctx,
Slug: slug,
})
if err != nil {
return clienterror.Wrap(err)
}
return nil
}
func newNotificationPolicyDeleteCmd() *cobra.Command {
clientFlags := client.NewClientFlags()
outputFlags := output.NewFlags(output.WithoutOutputDirectory(), output.WithoutCreateFilePerObject())
cmd := &cobra.Command{
Use: "delete <slug>",
GroupID: groups.Commands.ID,
Short: "Deletes a single NotificationPolicy by slug",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(cmd.Context(), clientFlags.Timeout())
defer cancel()
if err := outputFlags.Validate(); err != nil {
return err
}
defer outputFlags.Close(cmd.OutOrStdout())
client, err := clientFlags.ConfigV1Client()
if err != nil {
return err
}
res, err := client.DeleteNotificationPolicy(&config_v1.DeleteNotificationPolicyParams{
Context: ctx,
Slug: args[0],
})
if err != nil {
return clienterror.Wrap(err)
}
_ = res
fmt.Fprintf(cmd.OutOrStdout(), "deleted NotificationPolicy with slug %q\n", args[0])
return nil
},
}
clientFlags.AddFlags(cmd)
outputFlags.AddFlags(cmd)
return cmd
}
type NotificationPolicyListOpts struct {
// Limit represents that maximum number of items we wish to return.
Limit int
// PageToken is the pagination token we want to start our request at.
PageToken string
// PageMaxSize is the maximum page size to use when making List calls.
PageMaxSize int
BucketSlugs []string
Names []string
Slugs []string
TeamSlugs []string
}
func (r *NotificationPolicyListOpts) registerFlags(flags *flag.FlagSet) {
var emptyBucketSlugs []string
flags.StringSliceVar(&r.BucketSlugs, "bucket-slugs", emptyBucketSlugs, "Filters results by bucket_slug, where any NotificationPolicy with a matching bucket_slug in the given list (and matches all other filters) is returned.")
var emptyNames []string
flags.StringSliceVar(&r.Names, "names", emptyNames, "Filters results by name, where any NotificationPolicy with a matching name in the given list (and matches all other filters) is returned.")
var emptySlugs []string
flags.StringSliceVar(&r.Slugs, "slugs", emptySlugs, "Filters results by slug, where any NotificationPolicy with a matching slug in the given list (and matches all other filters) is returned.")
var emptyTeamSlugs []string
flags.StringSliceVar(&r.TeamSlugs, "team-slugs", emptyTeamSlugs, "Filters results by team_slug, where any NotificationPolicy with a matching team_slug in the given list (and matches all other filters) is returned.")
flags.IntVar(&r.Limit, "limit", 0, "maximum number of items to return")
flags.IntVar(&r.PageMaxSize, "page-max-size", 0, "maximum page size")
flags.StringVar(&r.PageToken, "page-token", "", "begins listing items at the start of the pagination token")
}
func ListNotificationPolicies(
ctx context.Context,
client config_v1.ClientService,
streamer output.Streamer[*NotificationPolicy],
opts NotificationPolicyListOpts,
) (pagination.Token, error) {
var (
gotItems = 0
nextToken = opts.PageToken
pageMaxSize = opts.PageMaxSize
)
// Use the limit if it's set, and smaller than a set page size.
if opts.Limit > 0 && (opts.Limit < pageMaxSize || pageMaxSize == 0) {
pageMaxSize = opts.Limit
}
for {
res, err := client.ListNotificationPolicies(&config_v1.ListNotificationPoliciesParams{
Context: ctx,
PageToken: &nextToken,
PageMaxSize: ptr.Int64(int64(pageMaxSize)),
BucketSlugs: opts.BucketSlugs,
Names: opts.Names,
Slugs: opts.Slugs,
TeamSlugs: opts.TeamSlugs,
})
if err != nil {
return pagination.Token(""), clienterror.Wrap(err)
}
for _, v := range res.Payload.NotificationPolicies {
if err := streamer(NewNotificationPolicy(v)); err != nil {
return pagination.Token(""), err
}
gotItems++
}
nextToken = res.Payload.Page.NextToken
if nextToken == "" {
return pagination.Token(""), nil
}
if opts.Limit > 0 && gotItems >= opts.Limit {
return pagination.Token(nextToken), nil
}
pageMaxSize = pagination.CalculatePageSize(pagination.Calculation{
GotItems: gotItems,
MaxItems: opts.Limit,
MaxPageSize: len(res.Payload.NotificationPolicies),
})
}
}
func newNotificationPolicyListCmd() *cobra.Command {
var listOptions NotificationPolicyListOpts
clientFlags := client.NewClientFlags()
outputFlags := output.NewFlags()
cmd := &cobra.Command{
Use: "list",
Short: "Lists all NotificationPolicies and applies optional filters",
GroupID: groups.Commands.ID,
RunE: func(cmd *cobra.Command, args []string) error {
ctx, cancel := context.WithTimeout(cmd.Context(), clientFlags.Timeout())
defer cancel()
if err := outputFlags.Validate(); err != nil {
return err
}
writer, err := outputFlags.NewWriterManager(cmd.OutOrStdout())
if err != nil {
return err
}
defer writer.Close()
client, err := clientFlags.ConfigV1Client()
if err != nil {
return err
}
streamer := output.NewWriteObjectStreamer[*NotificationPolicy](writer)
nextToken, err := ListNotificationPolicies(ctx, client, streamer, listOptions)
if err != nil {
return err
}
if nextToken != "" {
nextPage := pagination.Result{
Kind: pagination.ResultKind,
Message: "There are additional notificationPolicies. To view more, use the next page token or run the full command.",
NextPageToken: nextToken,
FullCommand: fmt.Sprintf("%s --page-token %q",
cli.BuildCommandString(cmd, []string{"page-token"}),
nextToken),
}
if err := outputFlags.WriteObject(nextPage, cmd.OutOrStdout()); err != nil {
return err
}
}
return nil
},
}
listOptions.registerFlags(cmd.Flags())
clientFlags.AddFlags(cmd)
outputFlags.AddFlags(cmd)
return cmd
}
const NotificationPolicyScaffoldYAML = `api_version: v1/config
kind: NotificationPolicy
spec:
# Unique identifier of the NotificationPolicy. If slug is not provided, one will be generated based of the name field. Cannot be modified after the NotificationPolicy is created.
slug: <string>
# Required name of the NotificationPolicy. May be modified after the NotificationPolicy is created.
name: <string>
# Slug of the bucket the notification policy belongs to. Required if
# team_slug is not set.
bucket_slug: <string>
# Slug of the team the notification policy belongs to. Required if
# bucket_slug is not set.
team_slug: <string>
routes:
# Optional list of overrides to use for alerts having matching labels.
# Each override defines labels that potentially match an alert's labels.
# If one or more overrides match an alert, the notifiers of the first matching
# override are used instead of the defaults.
overrides:
- # Set of matchers on an alert's labels.
# If all labels match then the override notifiers apply.
alert_label_matchers:
- # name always matches against an exact label name.
name: <string>
# value matches against a label value based on the configured type.
value: <string>
type: <EXACT|REGEX>
notifiers:
critical:
# Slugs of notifiers that will receive the alerts.
notifier_slugs:
- <string>
# Frequency at which to resend alerts.
repeat_interval_secs: <integer>
warn:
# Slugs of notifiers that will receive the alerts.
notifier_slugs:
- <string>
# Frequency at which to resend alerts.
repeat_interval_secs: <integer>
defaults:
critical:
# Slugs of notifiers that will receive the alerts.
notifier_slugs:
- <string>
# Frequency at which to resend alerts.
repeat_interval_secs: <integer>
warn:
# Slugs of notifiers that will receive the alerts.
notifier_slugs:
- <string>
# Frequency at which to resend alerts.
repeat_interval_secs: <integer>
`
func newNotificationPolicyScaffoldCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "scaffold",
GroupID: groups.Commands.ID,
Short: "Scaffolds a complete object with placeholder values",
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprint(cmd.OutOrStdout(), NotificationPolicyScaffoldYAML)
},
}
return cmd
}
func NewNotificationPolicyCmd() *cobra.Command {
root := &cobra.Command{
Use: "notification-policies",
GroupID: groups.Config.ID,
Short: "All commands for NotificationPolicies",
}
root.AddGroup(groups.Commands)
root.AddCommand(
newNotificationPolicyCreateCmd(),
newNotificationPolicyReadCmd(),
newNotificationPolicyUpdateCmd(),
newNotificationPolicyDeleteCmd(),
newNotificationPolicyListCmd(),
newNotificationPolicyScaffoldCmd(),
)
return root
}