-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
parser.go
1776 lines (1534 loc) · 43.5 KB
/
parser.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
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 pkger
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/influxdata/influxdb"
"github.com/influxdata/influxdb/pkg/jsonnet"
"gopkg.in/yaml.v3"
)
type (
// ReaderFn is used for functional inputs to abstract the individual
// entrypoints for the reader itself.
ReaderFn func() (io.Reader, error)
// Encoder is an encodes a type.
Encoder interface {
Encode(v interface{}) error
}
// Encoding describes the encoding for the raw package data. The
// encoding determines how the raw data is parsed.
Encoding int
)
// encoding types
const (
EncodingUnknown Encoding = iota
EncodingJSON
EncodingJsonnet
EncodingSource // EncodingSource draws the encoding type by inferring it from the source.
EncodingYAML
)
// String provides the string representation of the encoding.
func (e Encoding) String() string {
switch e {
case EncodingJSON:
return "json"
case EncodingJsonnet:
return "jsonnet"
case EncodingSource:
return "source"
case EncodingYAML:
return "yaml"
default:
return "unknown"
}
}
// ErrInvalidEncoding indicates the encoding is invalid type for the parser.
var ErrInvalidEncoding = errors.New("invalid encoding provided")
// Parse parses a pkg defined by the encoding and readerFns. As of writing this
// we can parse both a YAML, JSON, and Jsonnet formats of the Pkg model.
func Parse(encoding Encoding, readerFn ReaderFn, opts ...ValidateOptFn) (*Pkg, error) {
r, err := readerFn()
if err != nil {
return nil, err
}
switch encoding {
case EncodingJSON:
return parseJSON(r, opts...)
case EncodingJsonnet:
return parseJsonnet(r, opts...)
case EncodingSource:
return parseSource(r, opts...)
case EncodingYAML:
return parseYAML(r, opts...)
default:
return nil, ErrInvalidEncoding
}
}
// FromFile reads a file from disk and provides a reader from it.
func FromFile(filePath string) ReaderFn {
return func() (io.Reader, error) {
// not using os.Open to avoid having to deal with closing the file in here
b, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}
}
// FromReader simply passes the reader along. Useful when consuming
// this from an HTTP request body. There are a number of other useful
// places for this functional input.
func FromReader(r io.Reader) ReaderFn {
return func() (io.Reader, error) {
return r, nil
}
}
// FromString parses a pkg from a raw string value. This is very useful
// in tests.
func FromString(s string) ReaderFn {
return func() (io.Reader, error) {
return strings.NewReader(s), nil
}
}
// FromHTTPRequest parses a pkg from the request body of a HTTP request. This is
// very useful when using packages that are hosted..
func FromHTTPRequest(addr string) ReaderFn {
return func() (io.Reader, error) {
client := http.Client{Timeout: 5 * time.Minute}
resp, err := client.Get(addr)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, resp.Body); err != nil {
return nil, err
}
if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("bad response: status_code=%d body=%q", resp.StatusCode, strings.TrimSpace(buf.String()))
}
return &buf, nil
}
}
func parseJSON(r io.Reader, opts ...ValidateOptFn) (*Pkg, error) {
return parse(json.NewDecoder(r), opts...)
}
func parseJsonnet(r io.Reader, opts ...ValidateOptFn) (*Pkg, error) {
return parse(jsonnet.NewDecoder(r), opts...)
}
func parseSource(r io.Reader, opts ...ValidateOptFn) (*Pkg, error) {
var b []byte
if byter, ok := r.(interface{ Bytes() []byte }); ok {
b = byter.Bytes()
} else {
bb, err := ioutil.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("failed to decode pkg source: %s", err)
}
b = bb
}
contentType := http.DetectContentType(b[:512])
switch {
case strings.Contains(contentType, "jsonnet"):
// highly unlikely to fall in here with supported content type detection as is
return parseJsonnet(bytes.NewReader(b), opts...)
case strings.Contains(contentType, "json"):
return parseJSON(bytes.NewReader(b), opts...)
case strings.Contains(contentType, "yaml"),
strings.Contains(contentType, "yml"):
return parseYAML(bytes.NewReader(b), opts...)
default:
return parseYAML(bytes.NewReader(b), opts...)
}
}
func parseYAML(r io.Reader, opts ...ValidateOptFn) (*Pkg, error) {
dec := yaml.NewDecoder(r)
var pkg Pkg
for {
// forced to use this for loop b/c the yaml dependency does not
// decode multi documents.
var k Object
err := dec.Decode(&k)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
pkg.Objects = append(pkg.Objects, k)
}
if err := pkg.Validate(opts...); err != nil {
return nil, err
}
return &pkg, nil
}
type decoder interface {
Decode(interface{}) error
}
func parse(dec decoder, opts ...ValidateOptFn) (*Pkg, error) {
var pkg Pkg
if err := dec.Decode(&pkg.Objects); err != nil {
return nil, err
}
if err := pkg.Validate(opts...); err != nil {
return nil, err
}
return &pkg, nil
}
// Object describes the metadata and raw spec for an entity of a package kind.
type Object struct {
APIVersion string `json:"apiVersion" yaml:"apiVersion"`
Kind Kind `json:"kind" yaml:"kind"`
Metadata Resource `json:"metadata" yaml:"metadata"`
Spec Resource `json:"spec" yaml:"spec"`
}
// Name returns the name of the kind.
func (k Object) Name() string {
return k.Metadata.references(fieldName).String()
}
// Pkg is the model for a package. The resources are more generic that one might
// expect at first glance. This was done on purpose. The way json/yaml/toml or
// w/e scripting you want to use, can have very different ways of parsing. The
// different parsers are limited for the parsers that do not come from the std
// lib (looking at you yaml/v2). This allows us to parse it and leave the matching
// to another power, the graphing of the package is handled within itself.
type Pkg struct {
Objects []Object `json:"-" yaml:"-"`
mLabels map[string]*label
mBuckets map[string]*bucket
mChecks map[string]*check
mDashboards map[string]*dashboard
mNotificationEndpoints map[string]*notificationEndpoint
mNotificationRules map[string]*notificationRule
mTasks map[string]*task
mTelegrafs map[string]*telegraf
mVariables map[string]*variable
mEnv map[string]bool
mEnvVals map[string]string
mSecrets map[string]bool
isVerified bool // dry run has verified pkg resources with existing resources
isParsed bool // indicates the pkg has been parsed and all resources graphed accordingly
}
// Encode is a helper for encoding the pkg correctly.
func (p *Pkg) Encode(encoding Encoding) ([]byte, error) {
var (
buf bytes.Buffer
err error
)
switch encoding {
case EncodingJSON, EncodingJsonnet:
enc := json.NewEncoder(&buf)
enc.SetIndent("", "\t")
err = enc.Encode(p.Objects)
case EncodingYAML:
enc := yaml.NewEncoder(&buf)
for _, k := range p.Objects {
if err = enc.Encode(k); err != nil {
break
}
}
default:
return nil, ErrInvalidEncoding
}
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Summary returns a package Summary that describes all the resources and
// associations the pkg contains. It is very useful for informing users of
// the changes that will take place when this pkg would be applied.
func (p *Pkg) Summary() Summary {
// ensure zero values for arrays aren't returned, but instead
// we always returning an initialized slice.
sum := Summary{
Buckets: []SummaryBucket{},
Checks: []SummaryCheck{},
Dashboards: []SummaryDashboard{},
NotificationEndpoints: []SummaryNotificationEndpoint{},
NotificationRules: []SummaryNotificationRule{},
Labels: []SummaryLabel{},
MissingEnvs: p.missingEnvRefs(),
MissingSecrets: []string{},
Tasks: []SummaryTask{},
TelegrafConfigs: []SummaryTelegraf{},
Variables: []SummaryVariable{},
}
// only add this after dry run has been completed
if p.isVerified {
sum.MissingSecrets = p.missingSecrets()
}
for _, b := range p.buckets() {
sum.Buckets = append(sum.Buckets, b.summarize())
}
for _, c := range p.checks() {
sum.Checks = append(sum.Checks, c.summarize())
}
for _, d := range p.dashboards() {
sum.Dashboards = append(sum.Dashboards, d.summarize())
}
for _, l := range p.labels() {
sum.Labels = append(sum.Labels, l.summarize())
}
sum.LabelMappings = p.labelMappings()
for _, n := range p.notificationEndpoints() {
sum.NotificationEndpoints = append(sum.NotificationEndpoints, n.summarize())
}
for _, r := range p.notificationRules() {
sum.NotificationRules = append(sum.NotificationRules, r.summarize())
}
for _, t := range p.tasks() {
sum.Tasks = append(sum.Tasks, t.summarize())
}
for _, t := range p.telegrafs() {
sum.TelegrafConfigs = append(sum.TelegrafConfigs, t.summarize())
}
for _, v := range p.variables() {
sum.Variables = append(sum.Variables, v.summarize())
}
return sum
}
func (p *Pkg) applyEnvRefs(envRefs map[string]string) error {
if len(envRefs) == 0 {
return nil
}
if p.mEnvVals == nil {
p.mEnvVals = make(map[string]string)
}
for k, v := range envRefs {
p.mEnvVals[k] = v
}
return p.Validate()
}
func (p *Pkg) applySecrets(secrets map[string]string) {
for k := range secrets {
p.mSecrets[k] = true
}
}
// Combine combines pkgs together. Is useful when you want to take multiple disparate pkgs
// and compile them into one to take advantage of the parser and service guarantees.
func Combine(pkgs []*Pkg, validationOpts ...ValidateOptFn) (*Pkg, error) {
newPkg := new(Pkg)
for _, p := range pkgs {
newPkg.Objects = append(newPkg.Objects, p.Objects...)
}
return newPkg, newPkg.Validate(validationOpts...)
}
type (
validateOpt struct {
minResources bool
skipValidate bool
}
// ValidateOptFn provides a means to disable desired validation checks.
ValidateOptFn func(*validateOpt)
)
// ValidWithoutResources ignores the validation check for minimum number
// of resources. This is useful for the service Create to ignore this and
// allow the creation of a pkg without resources.
func ValidWithoutResources() ValidateOptFn {
return func(opt *validateOpt) {
opt.minResources = false
}
}
// ValidSkipParseError ignores the validation check from the of resources. This
// is useful for the service Create to ignore this and allow the creation of a
// pkg without resources.
func ValidSkipParseError() ValidateOptFn {
return func(opt *validateOpt) {
opt.skipValidate = true
}
}
// Validate will graph all resources and validate every thing is in a useful form.
func (p *Pkg) Validate(opts ...ValidateOptFn) error {
opt := &validateOpt{minResources: true}
for _, o := range opts {
o(opt)
}
var setupFns []func() error
if opt.minResources {
setupFns = append(setupFns, p.validResources)
}
setupFns = append(setupFns, p.graphResources)
var pErr parseErr
for _, fn := range setupFns {
if err := fn(); err != nil {
if IsParseErr(err) {
pErr.append(err.(*parseErr).Resources...)
continue
}
return err
}
}
if len(pErr.Resources) > 0 && !opt.skipValidate {
return &pErr
}
p.isParsed = true
return nil
}
func (p *Pkg) buckets() []*bucket {
buckets := make([]*bucket, 0, len(p.mBuckets))
for _, b := range p.mBuckets {
buckets = append(buckets, b)
}
sort.Slice(buckets, func(i, j int) bool { return buckets[i].Name() < buckets[j].Name() })
return buckets
}
func (p *Pkg) checks() []*check {
checks := make([]*check, 0, len(p.mChecks))
for _, c := range p.mChecks {
checks = append(checks, c)
}
sort.Slice(checks, func(i, j int) bool { return checks[i].Name() < checks[j].Name() })
return checks
}
func (p *Pkg) labels() []*label {
labels := make(sortedLabels, 0, len(p.mLabels))
for _, b := range p.mLabels {
labels = append(labels, b)
}
sort.Sort(labels)
return labels
}
func (p *Pkg) dashboards() []*dashboard {
dashes := make([]*dashboard, 0, len(p.mDashboards))
for _, d := range p.mDashboards {
dashes = append(dashes, d)
}
sort.Slice(dashes, func(i, j int) bool { return dashes[i].Name() < dashes[j].Name() })
return dashes
}
func (p *Pkg) notificationEndpoints() []*notificationEndpoint {
endpoints := make([]*notificationEndpoint, 0, len(p.mNotificationEndpoints))
for _, e := range p.mNotificationEndpoints {
endpoints = append(endpoints, e)
}
sort.Slice(endpoints, func(i, j int) bool {
ei, ej := endpoints[i], endpoints[j]
if ei.kind == ej.kind {
return ei.Name() < ej.Name()
}
return ei.kind < ej.kind
})
return endpoints
}
func (p *Pkg) notificationRules() []*notificationRule {
rules := make([]*notificationRule, 0, len(p.mNotificationRules))
for _, r := range p.mNotificationRules {
rules = append(rules, r)
}
sort.Slice(rules, func(i, j int) bool { return rules[i].Name() < rules[j].Name() })
return rules
}
func (p *Pkg) missingEnvRefs() []string {
envRefs := make([]string, 0)
for envRef, matching := range p.mEnv {
if !matching {
envRefs = append(envRefs, envRef)
}
}
sort.Strings(envRefs)
return envRefs
}
func (p *Pkg) missingSecrets() []string {
secrets := make([]string, 0, len(p.mSecrets))
for secret, foundInPlatform := range p.mSecrets {
if foundInPlatform {
continue
}
secrets = append(secrets, secret)
}
return secrets
}
func (p *Pkg) tasks() []*task {
tasks := make([]*task, 0, len(p.mTasks))
for _, t := range p.mTasks {
tasks = append(tasks, t)
}
sort.Slice(tasks, func(i, j int) bool { return tasks[i].Name() < tasks[j].Name() })
return tasks
}
func (p *Pkg) telegrafs() []*telegraf {
teles := make([]*telegraf, 0, len(p.mTelegrafs))
for _, t := range p.mTelegrafs {
t.config.Name = t.Name()
teles = append(teles, t)
}
sort.Slice(teles, func(i, j int) bool { return teles[i].Name() < teles[j].Name() })
return teles
}
func (p *Pkg) variables() []*variable {
vars := make([]*variable, 0, len(p.mVariables))
for _, v := range p.mVariables {
vars = append(vars, v)
}
sort.Slice(vars, func(i, j int) bool { return vars[i].Name() < vars[j].Name() })
return vars
}
// labelMappings returns the mappings that will be created for
// valid pairs of labels and resources of which all have IDs.
// If a resource does not exist yet, a label mapping will not
// be returned for it.
func (p *Pkg) labelMappings() []SummaryLabelMapping {
labels := p.mLabels
mappings := make([]SummaryLabelMapping, 0, len(labels))
for _, l := range labels {
mappings = append(mappings, l.mappingSummary()...)
}
// sort by res type ASC, then res name ASC, then label name ASC
sort.Slice(mappings, func(i, j int) bool {
n, m := mappings[i], mappings[j]
if n.ResourceType < m.ResourceType {
return true
}
if n.ResourceType > m.ResourceType {
return false
}
if n.ResourceName < m.ResourceName {
return true
}
if n.ResourceName > m.ResourceName {
return false
}
return n.LabelName < m.LabelName
})
return mappings
}
func (p *Pkg) validResources() error {
if len(p.Objects) > 0 {
return nil
}
res := resourceErr{
Kind: KindPackage.String(),
RootErrs: []validationErr{{
Field: "resources",
Msg: "at least 1 kind must be provided",
}},
}
var err parseErr
err.append(res)
return &err
}
func (p *Pkg) graphResources() error {
p.mEnv = make(map[string]bool)
p.mSecrets = make(map[string]bool)
graphFns := []func() *parseErr{
// labels are first, this is to validate associations with other resources
p.graphLabels,
p.graphVariables,
p.graphBuckets,
p.graphChecks,
p.graphDashboards,
p.graphNotificationEndpoints,
p.graphNotificationRules,
p.graphTasks,
p.graphTelegrafs,
}
var pErr parseErr
for _, fn := range graphFns {
if err := fn(); err != nil {
pErr.append(err.Resources...)
}
}
if len(pErr.Resources) > 0 {
sort.Slice(pErr.Resources, func(i, j int) bool {
ir, jr := pErr.Resources[i], pErr.Resources[j]
return *ir.Idx < *jr.Idx
})
return &pErr
}
return nil
}
func (p *Pkg) graphBuckets() *parseErr {
p.mBuckets = make(map[string]*bucket)
tracker := p.trackNames(true)
return p.eachResource(KindBucket, bucketNameMinLength, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
bkt := &bucket{
identity: ident,
Description: o.Spec.stringShort(fieldDescription),
}
if rules, ok := o.Spec[fieldBucketRetentionRules].(retentionRules); ok {
bkt.RetentionRules = rules
} else {
for _, r := range o.Spec.slcResource(fieldBucketRetentionRules) {
bkt.RetentionRules = append(bkt.RetentionRules, retentionRule{
Type: r.stringShort(fieldType),
Seconds: r.intShort(fieldRetentionRulesEverySeconds),
})
}
}
p.setRefs(bkt.name, bkt.displayName)
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
bkt.labels = append(bkt.labels, l)
p.mLabels[l.PkgName()].setMapping(bkt, false)
return nil
})
sort.Sort(bkt.labels)
p.mBuckets[bkt.PkgName()] = bkt
return append(failures, bkt.valid()...)
})
}
func (p *Pkg) graphLabels() *parseErr {
p.mLabels = make(map[string]*label)
tracker := p.trackNames(true)
return p.eachResource(KindLabel, labelNameMinLength, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
l := &label{
identity: ident,
Color: o.Spec.stringShort(fieldLabelColor),
Description: o.Spec.stringShort(fieldDescription),
}
p.mLabels[l.PkgName()] = l
p.setRefs(l.name, l.displayName)
return l.valid()
})
}
func (p *Pkg) graphChecks() *parseErr {
p.mChecks = make(map[string]*check)
tracker := p.trackNames(true)
checkKinds := []struct {
kind Kind
checkKind checkKind
}{
{kind: KindCheckThreshold, checkKind: checkKindThreshold},
{kind: KindCheckDeadman, checkKind: checkKindDeadman},
}
var pErr parseErr
for _, checkKind := range checkKinds {
err := p.eachResource(checkKind.kind, checkNameMinLength, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
ch := &check{
kind: checkKind.checkKind,
identity: ident,
description: o.Spec.stringShort(fieldDescription),
every: o.Spec.durationShort(fieldEvery),
level: o.Spec.stringShort(fieldLevel),
offset: o.Spec.durationShort(fieldOffset),
query: strings.TrimSpace(o.Spec.stringShort(fieldQuery)),
reportZero: o.Spec.boolShort(fieldCheckReportZero),
staleTime: o.Spec.durationShort(fieldCheckStaleTime),
status: normStr(o.Spec.stringShort(fieldStatus)),
statusMessage: o.Spec.stringShort(fieldCheckStatusMessageTemplate),
timeSince: o.Spec.durationShort(fieldCheckTimeSince),
}
for _, tagRes := range o.Spec.slcResource(fieldCheckTags) {
ch.tags = append(ch.tags, struct{ k, v string }{
k: tagRes.stringShort(fieldKey),
v: tagRes.stringShort(fieldValue),
})
}
for _, th := range o.Spec.slcResource(fieldCheckThresholds) {
ch.thresholds = append(ch.thresholds, threshold{
threshType: thresholdType(normStr(th.stringShort(fieldType))),
allVals: th.boolShort(fieldCheckAllValues),
level: strings.TrimSpace(strings.ToUpper(th.stringShort(fieldLevel))),
max: th.float64Short(fieldMax),
min: th.float64Short(fieldMin),
val: th.float64Short(fieldValue),
})
}
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
ch.labels = append(ch.labels, l)
p.mLabels[l.PkgName()].setMapping(ch, false)
return nil
})
sort.Sort(ch.labels)
p.mChecks[ch.PkgName()] = ch
p.setRefs(ch.name, ch.displayName)
return append(failures, ch.valid()...)
})
if err != nil {
pErr.append(err.Resources...)
}
}
if len(pErr.Resources) > 0 {
return &pErr
}
return nil
}
func (p *Pkg) graphDashboards() *parseErr {
p.mDashboards = make(map[string]*dashboard)
tracker := p.trackNames(false)
return p.eachResource(KindDashboard, dashboardNameMinLength, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
dash := &dashboard{
identity: ident,
Description: o.Spec.stringShort(fieldDescription),
}
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
dash.labels = append(dash.labels, l)
p.mLabels[l.PkgName()].setMapping(dash, false)
return nil
})
sort.Sort(dash.labels)
for i, cr := range o.Spec.slcResource(fieldDashCharts) {
ch, fails := parseChart(cr)
if fails != nil {
failures = append(failures,
objectValidationErr(fieldSpec, validationErr{
Field: fieldDashCharts,
Index: intPtr(i),
Nested: fails,
}),
)
continue
}
dash.Charts = append(dash.Charts, ch)
}
p.mDashboards[dash.PkgName()] = dash
p.setRefs(dash.name, dash.displayName)
return append(failures, dash.valid()...)
})
}
func (p *Pkg) graphNotificationEndpoints() *parseErr {
p.mNotificationEndpoints = make(map[string]*notificationEndpoint)
tracker := p.trackNames(true)
notificationKinds := []struct {
kind Kind
notificationKind notificationKind
}{
{
kind: KindNotificationEndpointHTTP,
notificationKind: notificationKindHTTP,
},
{
kind: KindNotificationEndpointPagerDuty,
notificationKind: notificationKindPagerDuty,
},
{
kind: KindNotificationEndpointSlack,
notificationKind: notificationKindSlack,
},
}
var pErr parseErr
for _, nk := range notificationKinds {
err := p.eachResource(nk.kind, 1, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
endpoint := ¬ificationEndpoint{
kind: nk.notificationKind,
identity: ident,
description: o.Spec.stringShort(fieldDescription),
method: strings.TrimSpace(strings.ToUpper(o.Spec.stringShort(fieldNotificationEndpointHTTPMethod))),
httpType: normStr(o.Spec.stringShort(fieldType)),
password: o.Spec.references(fieldNotificationEndpointPassword),
routingKey: o.Spec.references(fieldNotificationEndpointRoutingKey),
status: normStr(o.Spec.stringShort(fieldStatus)),
token: o.Spec.references(fieldNotificationEndpointToken),
url: o.Spec.stringShort(fieldNotificationEndpointURL),
username: o.Spec.references(fieldNotificationEndpointUsername),
}
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
endpoint.labels = append(endpoint.labels, l)
p.mLabels[l.PkgName()].setMapping(endpoint, false)
return nil
})
sort.Sort(endpoint.labels)
p.setRefs(
endpoint.name,
endpoint.displayName,
endpoint.password,
endpoint.routingKey,
endpoint.token,
endpoint.username,
)
p.mNotificationEndpoints[endpoint.PkgName()] = endpoint
return append(failures, endpoint.valid()...)
})
if err != nil {
pErr.append(err.Resources...)
}
}
if len(pErr.Resources) > 0 {
return &pErr
}
return nil
}
func (p *Pkg) graphNotificationRules() *parseErr {
p.mNotificationRules = make(map[string]*notificationRule)
tracker := p.trackNames(false)
return p.eachResource(KindNotificationRule, 1, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
rule := ¬ificationRule{
identity: ident,
endpointName: p.getRefWithKnownEnvs(o.Spec, fieldNotificationRuleEndpointName),
description: o.Spec.stringShort(fieldDescription),
channel: o.Spec.stringShort(fieldNotificationRuleChannel),
every: o.Spec.durationShort(fieldEvery),
msgTemplate: o.Spec.stringShort(fieldNotificationRuleMessageTemplate),
offset: o.Spec.durationShort(fieldOffset),
status: normStr(o.Spec.stringShort(fieldStatus)),
}
for _, sRule := range o.Spec.slcResource(fieldNotificationRuleStatusRules) {
rule.statusRules = append(rule.statusRules, struct{ curLvl, prevLvl string }{
curLvl: strings.TrimSpace(strings.ToUpper(sRule.stringShort(fieldNotificationRuleCurrentLevel))),
prevLvl: strings.TrimSpace(strings.ToUpper(sRule.stringShort(fieldNotificationRulePreviousLevel))),
})
}
for _, tRule := range o.Spec.slcResource(fieldNotificationRuleTagRules) {
rule.tagRules = append(rule.tagRules, struct{ k, v, op string }{
k: tRule.stringShort(fieldKey),
v: tRule.stringShort(fieldValue),
op: normStr(tRule.stringShort(fieldOperator)),
})
}
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
rule.labels = append(rule.labels, l)
p.mLabels[l.PkgName()].setMapping(rule, false)
return nil
})
sort.Sort(rule.labels)
p.mNotificationRules[rule.PkgName()] = rule
p.setRefs(rule.name, rule.displayName, rule.endpointName)
return append(failures, rule.valid()...)
})
}
func (p *Pkg) graphTasks() *parseErr {
p.mTasks = make(map[string]*task)
tracker := p.trackNames(false)
return p.eachResource(KindTask, 1, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
t := &task{
identity: ident,
cron: o.Spec.stringShort(fieldTaskCron),
description: o.Spec.stringShort(fieldDescription),
every: o.Spec.durationShort(fieldEvery),
offset: o.Spec.durationShort(fieldOffset),
query: strings.TrimSpace(o.Spec.stringShort(fieldQuery)),
status: normStr(o.Spec.stringShort(fieldStatus)),
}
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
t.labels = append(t.labels, l)
p.mLabels[l.PkgName()].setMapping(t, false)
return nil
})
sort.Sort(t.labels)
p.mTasks[t.PkgName()] = t
p.setRefs(t.name, t.displayName)
return append(failures, t.valid()...)
})
}
func (p *Pkg) graphTelegrafs() *parseErr {
p.mTelegrafs = make(map[string]*telegraf)
tracker := p.trackNames(false)
return p.eachResource(KindTelegraf, 0, func(o Object) []validationErr {
ident, errs := tracker(o)
if len(errs) > 0 {
return errs
}
tele := &telegraf{
identity: ident,
}
tele.config.Config = o.Spec.stringShort(fieldTelegrafConfig)
tele.config.Description = o.Spec.stringShort(fieldDescription)
failures := p.parseNestedLabels(o.Spec, func(l *label) error {
tele.labels = append(tele.labels, l)
p.mLabels[l.PkgName()].setMapping(tele, false)
return nil
})
sort.Sort(tele.labels)
p.mTelegrafs[tele.PkgName()] = tele
p.setRefs(tele.name, tele.displayName)
return append(failures, tele.valid()...)
})
}