-
-
Notifications
You must be signed in to change notification settings - Fork 306
/
structs.go
9033 lines (7967 loc) · 283 KB
/
structs.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
// Mgmt
// Copyright (C) 2013-2021+ James Shubin and the project contributors
// Written by James Shubin <james@shubin.ca> and the project contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package lang // TODO: move this into a sub package of lang/$name?
import (
"bytes"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"github.com/purpleidea/mgmt/engine"
engineUtil "github.com/purpleidea/mgmt/engine/util"
"github.com/purpleidea/mgmt/lang/funcs"
"github.com/purpleidea/mgmt/lang/funcs/bindata"
"github.com/purpleidea/mgmt/lang/funcs/structs"
"github.com/purpleidea/mgmt/lang/interfaces"
"github.com/purpleidea/mgmt/lang/types"
langutil "github.com/purpleidea/mgmt/lang/util"
"github.com/purpleidea/mgmt/pgraph"
"github.com/purpleidea/mgmt/util"
"github.com/purpleidea/mgmt/util/errwrap"
"golang.org/x/time/rate"
)
const (
// EdgeNotify declares an edge a -> b, such that a notification occurs.
// This is most similar to "notify" in Puppet.
EdgeNotify = "notify"
// EdgeBefore declares an edge a -> b, such that no notification occurs.
// This is most similar to "before" in Puppet.
EdgeBefore = "before"
// EdgeListen declares an edge a <- b, such that a notification occurs.
// This is most similar to "subscribe" in Puppet.
EdgeListen = "listen"
// EdgeDepend declares an edge a <- b, such that no notification occurs.
// This is most similar to "require" in Puppet.
EdgeDepend = "depend"
// MetaField is the prefix used to specify a meta parameter for the res.
MetaField = "meta"
// AllowUserDefinedPolyFunc specifies if we allow user-defined
// polymorphic functions or not. At the moment this is not implemented.
// XXX: not implemented
AllowUserDefinedPolyFunc = false
// RequireStrictModulePath can be set to true if you wish to ignore any
// of the metadata parent path searching. By default that is allowed,
// unless it is disabled per module with ParentPathBlock. This option is
// here in case we decide that the parent module searching is confusing.
RequireStrictModulePath = false
// RequireTopologicalOrdering specifies if the code *must* be written in
// a topologically correct order. This prevents "out-of-order" code that
// is valid, but possibly confusing to the read. The main author
// (purpleidea) believes that this is better of as false. This is
// because occasionally code might be more logical when out-of-order,
// and hiding the fundamental structure of the language isn't elegant.
RequireTopologicalOrdering = false
// TopologicalOrderingWarning specifies whether a warning is emitted if
// the code is not in a topologically correct order. If this warning is
// seen too often, then we should consider disabling this by default.
TopologicalOrderingWarning = true
// varOrderingPrefix is a magic prefix used for the Ordering graph.
varOrderingPrefix = "var:"
// funcOrderingPrefix is a magic prefix used for the Ordering graph.
funcOrderingPrefix = "func:"
// classOrderingPrefix is a magic prefix used for the Ordering graph.
classOrderingPrefix = "class:"
// legacyProgSetScope enables an old version of the SetScope function
// in StmtProg. Use it for experimentation if you don't want to use the
// Ordering function for some reason. In general, this should be false!
legacyProgSetScope = false
// ErrNoStoredScope is an error that tells us we can't get a scope here.
ErrNoStoredScope = interfaces.Error("scope is not stored in this node")
)
var (
// orderingGraphSingleton is used for debugging the ordering graph.
orderingGraphSingleton = true
)
// StmtBind is a representation of an assignment, which binds a variable to an
// expression.
type StmtBind struct {
Ident string
Value interfaces.Expr
}
// String returns a short representation of this statement.
func (obj *StmtBind) String() string {
return fmt.Sprintf("bind(%s)", obj.Ident)
}
// Apply is a general purpose iterator method that operates on any AST node. It
// is not used as the primary AST traversal function because it is less readable
// and easy to reason about than manually implementing traversal for each node.
// Nevertheless, it is a useful facility for operations that might only apply to
// a select number of node types, since they won't need extra noop iterators...
func (obj *StmtBind) Apply(fn func(interfaces.Node) error) error {
if err := obj.Value.Apply(fn); err != nil {
return err
}
return fn(obj)
}
// Init initializes this branch of the AST, and returns an error if it fails to
// validate.
func (obj *StmtBind) Init(data *interfaces.Data) error {
return obj.Value.Init(data)
}
// Interpolate returns a new node (aka a copy) once it has been expanded. This
// generally increases the size of the AST when it is used. It calls Interpolate
// on any child elements and builds the new node with those new node contents.
func (obj *StmtBind) Interpolate() (interfaces.Stmt, error) {
interpolated, err := obj.Value.Interpolate()
if err != nil {
return nil, err
}
return &StmtBind{
Ident: obj.Ident,
Value: interpolated,
}, nil
}
// Copy returns a light copy of this struct. Anything static will not be copied.
func (obj *StmtBind) Copy() (interfaces.Stmt, error) {
copied := false
value, err := obj.Value.Copy()
if err != nil {
return nil, err
}
if value != obj.Value { // must have been copied, or pointer would be same
copied = true
}
if !copied { // it's static
return obj, nil
}
return &StmtBind{
Ident: obj.Ident,
Value: value,
}, nil
}
// Ordering returns a graph of the scope ordering that represents the data flow.
// This can be used in SetScope so that it knows the correct order to run it in.
// We only really care about the consumers here, because the "produces" aspect
// of this resource is handled by the StmtProg Ordering function. This is
// because the "prog" allows out-of-order statements, therefore it solves this
// by running an early (second) loop through the program and peering into this
// Stmt and extracting the produced name.
func (obj *StmtBind) Ordering(produces map[string]interfaces.Node) (*pgraph.Graph, map[interfaces.Node]string, error) {
graph, err := pgraph.NewGraph("ordering")
if err != nil {
return nil, nil, errwrap.Wrapf(err, "could not create graph")
}
graph.AddVertex(obj)
// additional constraint...
edge := &pgraph.SimpleEdge{Name: "stmtbindvalue"}
graph.AddEdge(obj.Value, obj, edge) // prod -> cons
cons := make(map[interfaces.Node]string)
g, c, err := obj.Value.Ordering(produces)
if err != nil {
return nil, nil, err
}
graph.AddGraph(g) // add in the child graph
for k, v := range c { // c is consumes
x, exists := cons[k]
if exists && v != x {
return nil, nil, fmt.Errorf("consumed value is different, got `%+v`, expected `%+v`", x, v)
}
cons[k] = v // add to map
n, exists := produces[v]
if !exists {
continue
}
edge := &pgraph.SimpleEdge{Name: "stmtbind"}
graph.AddEdge(n, k, edge)
}
return graph, cons, nil
}
// SetScope sets the scope of the child expression bound to it. It seems this is
// necessary in order to reach this, in particular in situations when a bound
// expression points to a previously bound expression.
func (obj *StmtBind) SetScope(scope *interfaces.Scope) error {
return obj.Value.SetScope(scope)
}
// Unify returns the list of invariants that this node produces. It recursively
// calls Unify on any children elements that exist in the AST, and returns the
// collection to the caller.
func (obj *StmtBind) Unify() ([]interfaces.Invariant, error) {
// Invariants from an ExprFunc come in from the copy of it in ExprCall.
// We could exclude *all* recursion here, however when multiple ExprVar
// expressions use a bound variable from here, they'd end up calling it
// multiple times so it's better to do it here even if it's not elegant
// symmetrically.
// FIXME: There must be a way to keep this symmetrical, isn't there?
// FIXME: Keep it symmetrical and inefficient for now...
//if _, ok := obj.Value.(*ExprFunc); !ok {
// return obj.Value.Unify()
//}
return []interfaces.Invariant{}, nil
}
// Graph returns the reactive function graph which is expressed by this node. It
// includes any vertices produced by this node, and the appropriate edges to any
// vertices that are produced by its children. Nodes which fulfill the Expr
// interface directly produce vertices (and possible children) where as nodes
// that fulfill the Stmt interface do not produces vertices, where as their
// children might. This particular bind statement adds its linked expression to
// the graph. It is not logically done in the ExprVar since that could exist
// multiple times for the single binding operation done here.
func (obj *StmtBind) Graph() (*pgraph.Graph, error) {
// It seems that adding this to the graph will end up including an
// expression in the case of an ExprFunc lambda, since we copy it and
// build a new ExprFunc when it's used by ExprCall.
//return obj.Value.Graph() // nope!
return pgraph.NewGraph("stmtbind") // empty graph!
}
// Output for the bind statement produces no output. Any values of interest come
// from the use of the var which this binds the expression to.
func (obj *StmtBind) Output() (*interfaces.Output, error) {
return interfaces.EmptyOutput(), nil
}
// StmtRes is a representation of a resource and possibly some edges. The `Name`
// value can be a single string or a list of strings. The former will produce a
// single resource, the latter produces a list of resources. Using this list
// mechanism is a safe alternative to traditional flow control like `for` loops.
// TODO: Consider expanding Name to have this return a list of Res's in the
// Output function if it is a map[name]struct{}, or even a map[[]name]struct{}.
type StmtRes struct {
data *interfaces.Data
Kind string // kind of resource, eg: pkg, file, svc, etc...
Name interfaces.Expr // unique name for the res of this kind
Contents []StmtResContents // list of fields/edges in parsed order
}
// String returns a short representation of this statement.
func (obj *StmtRes) String() string {
// TODO: add .String() for Contents and Name
return fmt.Sprintf("res(%s)", obj.Kind)
}
// Apply is a general purpose iterator method that operates on any AST node. It
// is not used as the primary AST traversal function because it is less readable
// and easy to reason about than manually implementing traversal for each node.
// Nevertheless, it is a useful facility for operations that might only apply to
// a select number of node types, since they won't need extra noop iterators...
func (obj *StmtRes) Apply(fn func(interfaces.Node) error) error {
if err := obj.Name.Apply(fn); err != nil {
return err
}
for _, x := range obj.Contents {
if err := x.Apply(fn); err != nil {
return err
}
}
return fn(obj)
}
// Init initializes this branch of the AST, and returns an error if it fails to
// validate.
func (obj *StmtRes) Init(data *interfaces.Data) error {
if strings.Contains(obj.Kind, "_") {
return fmt.Errorf("kind must not contain underscores")
}
obj.data = data
if err := obj.Name.Init(data); err != nil {
return err
}
fieldNames := make(map[string]struct{})
metaNames := make(map[string]struct{})
for _, x := range obj.Contents {
// Duplicate checking for identical field names.
if line, ok := x.(*StmtResField); ok {
// Was the field already seen in this resource?
if _, exists := fieldNames[line.Field]; exists {
return fmt.Errorf("resource has duplicate field of: %s", line.Field)
}
fieldNames[line.Field] = struct{}{}
}
// NOTE: you can have as many *StmtResEdge lines as you want =D
if line, ok := x.(*StmtResMeta); ok {
// Was the meta entry already seen in this resource?
// Ignore the generic MetaField struct field for now.
// You're allowed to have more than one Meta field, but
// they can't contain the same field twice.
if _, exists := metaNames[line.Property]; exists && line.Property != MetaField {
return fmt.Errorf("resource has duplicate meta entry of: %s", line.Property)
}
metaNames[line.Property] = struct{}{}
}
if err := x.Init(data); err != nil {
return err
}
}
return nil
}
// Interpolate returns a new node (aka a copy) once it has been expanded. This
// generally increases the size of the AST when it is used. It calls Interpolate
// on any child elements and builds the new node with those new node contents.
func (obj *StmtRes) Interpolate() (interfaces.Stmt, error) {
name, err := obj.Name.Interpolate()
if err != nil {
return nil, err
}
contents := []StmtResContents{}
for _, x := range obj.Contents { // make sure we preserve ordering...
interpolated, err := x.Interpolate()
if err != nil {
return nil, err
}
contents = append(contents, interpolated)
}
return &StmtRes{
data: obj.data,
Kind: obj.Kind,
Name: name,
Contents: contents,
}, nil
}
// Copy returns a light copy of this struct. Anything static will not be copied.
func (obj *StmtRes) Copy() (interfaces.Stmt, error) {
copied := false
name, err := obj.Name.Copy()
if err != nil {
return nil, err
}
if name != obj.Name { // must have been copied, or pointer would be same
copied = true
}
copiedContents := false
contents := []StmtResContents{}
for _, x := range obj.Contents { // make sure we preserve ordering...
cp, err := x.Copy()
if err != nil {
return nil, err
}
if cp != x {
copiedContents = true
}
contents = append(contents, cp)
}
if copiedContents {
copied = true
} else {
contents = obj.Contents // don't re-package it unnecessarily!
}
if !copied { // it's static
return obj, nil
}
return &StmtRes{
data: obj.data,
Kind: obj.Kind,
Name: name,
Contents: contents,
}, nil
}
// Ordering returns a graph of the scope ordering that represents the data flow.
// This can be used in SetScope so that it knows the correct order to run it in.
func (obj *StmtRes) Ordering(produces map[string]interfaces.Node) (*pgraph.Graph, map[interfaces.Node]string, error) {
graph, err := pgraph.NewGraph("ordering")
if err != nil {
return nil, nil, errwrap.Wrapf(err, "could not create graph")
}
graph.AddVertex(obj)
// Additional constraints: We know the name has to be satisfied before
// this res statement itself can be used, since we depend on that value.
edge := &pgraph.SimpleEdge{Name: "stmtresname"}
graph.AddEdge(obj.Name, obj, edge) // prod -> cons
cons := make(map[interfaces.Node]string)
g, c, err := obj.Name.Ordering(produces)
if err != nil {
return nil, nil, err
}
graph.AddGraph(g) // add in the child graph
for k, v := range c { // c is consumes
x, exists := cons[k]
if exists && v != x {
return nil, nil, fmt.Errorf("consumed value is different, got `%+v`, expected `%+v`", x, v)
}
cons[k] = v // add to map
n, exists := produces[v]
if !exists {
continue
}
edge := &pgraph.SimpleEdge{Name: "stmtres"}
graph.AddEdge(n, k, edge)
}
for _, node := range obj.Contents {
g, c, err := node.Ordering(produces)
if err != nil {
return nil, nil, err
}
graph.AddGraph(g) // add in the child graph
// additional constraint...
edge := &pgraph.SimpleEdge{Name: "stmtrescontents1"}
graph.AddEdge(node, obj, edge) // prod -> cons
for k, v := range c { // c is consumes
x, exists := cons[k]
if exists && v != x {
return nil, nil, fmt.Errorf("consumed value is different, got `%+v`, expected `%+v`", x, v)
}
cons[k] = v // add to map
n, exists := produces[v]
if !exists {
continue
}
edge := &pgraph.SimpleEdge{Name: "stmtrescontents2"}
graph.AddEdge(n, k, edge)
}
}
return graph, cons, nil
}
// SetScope stores the scope for later use in this resource and its children,
// which it propagates this downwards to.
func (obj *StmtRes) SetScope(scope *interfaces.Scope) error {
if err := obj.Name.SetScope(scope); err != nil {
return err
}
for _, x := range obj.Contents {
if err := x.SetScope(scope); err != nil {
return err
}
}
return nil
}
// Unify returns the list of invariants that this node produces. It recursively
// calls Unify on any children elements that exist in the AST, and returns the
// collection to the caller.
func (obj *StmtRes) Unify() ([]interfaces.Invariant, error) {
var invariants []interfaces.Invariant
invars, err := obj.Name.Unify()
if err != nil {
return nil, err
}
invariants = append(invariants, invars...)
// name must be a string or a list
ors := []interfaces.Invariant{}
invarStr := &interfaces.EqualsInvariant{
Expr: obj.Name,
Type: types.TypeStr,
}
ors = append(ors, invarStr)
invarListStr := &interfaces.EqualsInvariant{
Expr: obj.Name,
Type: types.NewType("[]str"),
}
ors = append(ors, invarListStr)
invar := &interfaces.ExclusiveInvariant{
Invariants: ors, // one and only one of these should be true
}
invariants = append(invariants, invar)
// collect all the invariants of each field and edge
for _, x := range obj.Contents {
invars, err := x.Unify(obj.Kind) // pass in the resource kind
if err != nil {
return nil, err
}
invariants = append(invariants, invars...)
}
return invariants, nil
}
// Graph returns the reactive function graph which is expressed by this node. It
// includes any vertices produced by this node, and the appropriate edges to any
// vertices that are produced by its children. Nodes which fulfill the Expr
// interface directly produce vertices (and possible children) where as nodes
// that fulfill the Stmt interface do not produces vertices, where as their
// children might. It is interesting to note that nothing directly adds an edge
// to the resources created, but rather, once all the values (expressions) with
// no outgoing edges have produced at least a single value, then the resources
// know they're able to be built.
//
// This runs right after type unification. For this particular resource, we can
// do some additional static analysis, but only after unification has been done.
// Since I don't think it's worth extending the Stmt API for this, we can do the
// checks here at the beginning, and error out if something was invalid. In this
// particular case, the issue is one of catching duplicate meta fields.
func (obj *StmtRes) Graph() (*pgraph.Graph, error) {
metaNames := make(map[string]struct{})
for _, x := range obj.Contents {
line, ok := x.(*StmtResMeta)
if !ok {
continue
}
properties := []string{line.Property} // "noop" or "Meta" or...
if line.Property == MetaField {
// If this is the generic MetaField struct field, then
// we lookup the type signature to see which fields are
// defined. You're allowed to have more than one Meta
// field, but they can't contain the same field twice.
typ, err := line.MetaExpr.Type() // must be known now
if err != nil {
// programming error in type unification
return nil, errwrap.Wrapf(err, "unknown resource meta type")
}
if t := typ.Kind; t != types.KindStruct {
return nil, fmt.Errorf("unexpected resource meta kind of: %s", t)
}
properties = typ.Ord // list of field names in this struct
}
for _, property := range properties {
// Was the meta entry already seen in this resource?
if _, exists := metaNames[property]; exists {
return nil, fmt.Errorf("resource has duplicate meta entry of: %s", property)
}
metaNames[property] = struct{}{}
}
}
graph, err := pgraph.NewGraph("res")
if err != nil {
return nil, errwrap.Wrapf(err, "could not create graph")
}
g, err := obj.Name.Graph()
if err != nil {
return nil, err
}
graph.AddGraph(g)
for _, x := range obj.Contents {
g, err := x.Graph()
if err != nil {
return nil, err
}
graph.AddGraph(g)
}
return graph, nil
}
// Output returns the output that this "program" produces. This output is what
// is used to build the output graph. This only exists for statements. The
// analogous function for expressions is Value. Those Value functions might get
// called by this Output function if they are needed to produce the output. In
// the case of this resource statement, this is definitely the case.
func (obj *StmtRes) Output() (*interfaces.Output, error) {
nameValue, err := obj.Name.Value()
if err != nil {
return nil, err
}
names := []string{} // list of names to build
switch {
case types.TypeStr.Cmp(nameValue.Type()) == nil:
name := nameValue.Str() // must not panic
names = append(names, name)
case types.NewType("[]str").Cmp(nameValue.Type()) == nil:
for _, x := range nameValue.List() { // must not panic
name := x.Str() // must not panic
names = append(names, name)
}
default:
// programming error
return nil, fmt.Errorf("unhandled resource name type: %+v", nameValue.Type())
}
resources := []engine.Res{}
edges := []*interfaces.Edge{}
for _, name := range names {
res, err := obj.resource(name)
if err != nil {
return nil, errwrap.Wrapf(err, "error building resource")
}
edgeList, err := obj.edges(name)
if err != nil {
return nil, errwrap.Wrapf(err, "error building edges")
}
edges = append(edges, edgeList...)
if err := obj.metaparams(res); err != nil { // set metaparams
return nil, errwrap.Wrapf(err, "error building meta params")
}
resources = append(resources, res)
}
return &interfaces.Output{
Resources: resources,
Edges: edges,
}, nil
}
// resource is a helper function to generate the res that comes from this.
// TODO: it could memoize some of the work to avoid re-computation when looped
func (obj *StmtRes) resource(resName string) (engine.Res, error) {
res, err := engine.NewNamedResource(obj.Kind, resName)
if err != nil {
return nil, errwrap.Wrapf(err, "cannot create resource kind `%s` with named `%s`", obj.Kind, resName)
}
sv := reflect.ValueOf(res).Elem() // pointer to struct, then struct
if k := sv.Kind(); k != reflect.Struct {
panic(fmt.Sprintf("expected struct, got: %s", k))
}
mapping, err := engineUtil.LangFieldNameToStructFieldName(obj.Kind)
if err != nil {
return nil, err
}
st := reflect.TypeOf(res).Elem() // pointer to struct, then struct
// FIXME: we could probably simplify this code...
for _, line := range obj.Contents {
x, ok := line.(*StmtResField)
if !ok {
continue
}
if x.Condition != nil {
b, err := x.Condition.Value()
if err != nil {
return nil, err
}
if !b.Bool() { // if value exists, and is false, skip it
continue
}
}
typ, err := x.Value.Type()
if err != nil {
return nil, errwrap.Wrapf(err, "resource field `%s` did not return a type", x.Field)
}
name, exists := mapping[x.Field] // lookup recommended field name
if !exists { // this should be caught during unification.
return nil, fmt.Errorf("field `%s` does not exist", x.Field) // user made a typo?
}
tf, exists := st.FieldByName(name) // exported field type
if !exists {
return nil, fmt.Errorf("field `%s` type does not exist", x.Field)
}
f := sv.FieldByName(name) // exported field
if !f.IsValid() || !f.CanSet() {
return nil, fmt.Errorf("field `%s` cannot be set", name) // field is broken?
}
// is expr type compatible with expected field type?
t, err := types.TypeOf(tf.Type)
if err != nil {
return nil, errwrap.Wrapf(err, "resource field `%s` has no compatible type", x.Field)
}
if err := t.Cmp(typ); err != nil {
return nil, errwrap.Wrapf(err, "resource field `%s` of type `%+v`, cannot take type `%+v", x.Field, t, typ)
}
fv, err := x.Value.Value() // Value method on Expr
if err != nil {
return nil, err
}
// mutate the struct field f with the mcl data in fv
if err := types.Into(fv, f); err != nil {
return nil, err
}
}
return res, nil
}
// edges is a helper function to generate the edges that come from the resource.
func (obj *StmtRes) edges(resName string) ([]*interfaces.Edge, error) {
edges := []*interfaces.Edge{}
// to and from self, map of kind, name, notify
var to = make(map[string]map[string]bool) // to this from self
var from = make(map[string]map[string]bool) // from this to self
for _, line := range obj.Contents {
x, ok := line.(*StmtResEdge)
if !ok {
continue
}
if x.Condition != nil {
b, err := x.Condition.Value()
if err != nil {
return nil, err
}
if !b.Bool() { // if value exists, and is false, skip it
continue
}
}
nameValue, err := x.EdgeHalf.Name.Value()
if err != nil {
return nil, err
}
// the edge name can be a single string or a list of strings...
names := []string{} // list of names to build
switch {
case types.TypeStr.Cmp(nameValue.Type()) == nil:
name := nameValue.Str() // must not panic
names = append(names, name)
case types.NewType("[]str").Cmp(nameValue.Type()) == nil:
for _, x := range nameValue.List() { // must not panic
name := x.Str() // must not panic
names = append(names, name)
}
default:
// programming error
return nil, fmt.Errorf("unhandled resource name type: %+v", nameValue.Type())
}
kind := x.EdgeHalf.Kind
for _, name := range names {
var notify bool
switch p := x.Property; p {
// a -> b
// a notify b
// a before b
case EdgeNotify:
notify = true
fallthrough
case EdgeBefore:
if m, exists := to[kind]; !exists {
to[kind] = make(map[string]bool)
} else if n, exists := m[name]; exists {
notify = notify || n // collate
}
to[kind][name] = notify // to this from self
// b -> a
// b listen a
// b depend a
case EdgeListen:
notify = true
fallthrough
case EdgeDepend:
if m, exists := from[kind]; !exists {
from[kind] = make(map[string]bool)
} else if n, exists := m[name]; exists {
notify = notify || n // collate
}
from[kind][name] = notify // from this to self
default:
return nil, fmt.Errorf("unknown property: %s", p)
}
}
}
// TODO: we could detect simple loops here (if `from` and `to` have the
// same entry) but we can leave this to the proper dag checker later on
for kind, x := range to { // to this from self
for name, notify := range x {
edge := &interfaces.Edge{
Kind1: obj.Kind,
Name1: resName, // self
//Send: "",
Kind2: kind,
Name2: name,
//Recv: "",
Notify: notify,
}
edges = append(edges, edge)
}
}
for kind, x := range from { // from this to self
for name, notify := range x {
edge := &interfaces.Edge{
Kind1: kind,
Name1: name,
//Send: "",
Kind2: obj.Kind,
Name2: resName, // self
//Recv: "",
Notify: notify,
}
edges = append(edges, edge)
}
}
return edges, nil
}
// metaparams is a helper function to set the metaparams that come from the
// resource on to the individual resource we're working on.
func (obj *StmtRes) metaparams(res engine.Res) error {
meta := engine.DefaultMetaParams.Copy() // defaults
var rm *engine.ReversibleMeta
if r, ok := res.(engine.ReversibleRes); ok {
rm = r.ReversibleMeta() // get a struct with the defaults
}
var aem *engine.AutoEdgeMeta
if r, ok := res.(engine.EdgeableRes); ok {
aem = r.AutoEdgeMeta() // get a struct with the defaults
}
var agm *engine.AutoGroupMeta
if r, ok := res.(engine.GroupableRes); ok {
agm = r.AutoGroupMeta() // get a struct with the defaults
}
for _, line := range obj.Contents {
x, ok := line.(*StmtResMeta)
if !ok {
continue
}
if x.Condition != nil {
b, err := x.Condition.Value()
if err != nil {
return err
}
if !b.Bool() { // if value exists, and is false, skip it
continue
}
}
v, err := x.MetaExpr.Value()
if err != nil {
return err
}
switch p := strings.ToLower(x.Property); p {
// TODO: we could add these fields dynamically if we were fancy!
case "noop":
meta.Noop = v.Bool() // must not panic
case "retry":
x := v.Int() // must not panic
// TODO: check that it doesn't overflow
meta.Retry = int16(x)
case "delay":
x := v.Int() // must not panic
// TODO: check that it isn't signed
meta.Delay = uint64(x)
case "poll":
x := v.Int() // must not panic
// TODO: check that it doesn't overflow and isn't signed
meta.Poll = uint32(x)
case "limit": // rate.Limit
x := v.Float() // must not panic
meta.Limit = rate.Limit(x)
case "burst":
x := v.Int() // must not panic
// TODO: check that it doesn't overflow
meta.Burst = int(x)
case "sema": // []string
values := []string{}
for _, x := range v.List() { // must not panic
s := x.Str() // must not panic
values = append(values, s)
}
meta.Sema = values
case "rewatch":
meta.Rewatch = v.Bool() // must not panic
case "realize":
meta.Realize = v.Bool() // must not panic
case "reverse":
if v.Type().Cmp(types.TypeBool) == nil {
if rm != nil {
rm.Disabled = !v.Bool() // must not panic
}
} else {
// TODO: read values from struct into rm.XXX
}
case "autoedge":
if aem != nil {
aem.Disabled = !v.Bool() // must not panic
}
case "autogroup":
if agm != nil {
agm.Disabled = !v.Bool() // must not panic
}
case MetaField:
if val, exists := v.Struct()["noop"]; exists {
meta.Noop = val.Bool() // must not panic
}
if val, exists := v.Struct()["retry"]; exists {
x := val.Int() // must not panic
// TODO: check that it doesn't overflow
meta.Retry = int16(x)
}
if val, exists := v.Struct()["delay"]; exists {
x := val.Int() // must not panic
// TODO: check that it isn't signed
meta.Delay = uint64(x)
}
if val, exists := v.Struct()["poll"]; exists {
x := val.Int() // must not panic
// TODO: check that it doesn't overflow and isn't signed
meta.Poll = uint32(x)
}
if val, exists := v.Struct()["limit"]; exists {
x := val.Float() // must not panic
meta.Limit = rate.Limit(x)
}
if val, exists := v.Struct()["burst"]; exists {
x := val.Int() // must not panic
// TODO: check that it doesn't overflow
meta.Burst = int(x)
}
if val, exists := v.Struct()["sema"]; exists {