-
Notifications
You must be signed in to change notification settings - Fork 15
/
StateMutationEngine.go
2127 lines (1972 loc) · 61.3 KB
/
StateMutationEngine.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
/* StateMutationEngine.go: In many ways, the heart of Kraken, this engine manages state mutations.
*
* Author: J. Lowell Wofford <lowell@lanl.gov>
*
* This software is open source software available under the BSD-3 license.
* Copyright (c) 2018, Triad National Security, LLC
* See LICENSE file for details.
*/
package core
import (
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"sync"
"time"
pb "github.com/kraken-hpc/kraken/core/proto"
ct "github.com/kraken-hpc/kraken/core/proto/customtypes"
"github.com/kraken-hpc/kraken/lib/types"
"github.com/kraken-hpc/kraken/lib/util"
)
///////////////////////
// Auxiliary Objects /
/////////////////////
const (
MutationEvent_MUTATE pb.MutationControl_Type = pb.MutationControl_MUTATE
MutationEvent_INTERRUPT pb.MutationControl_Type = pb.MutationControl_INTERRUPT
)
var MutationEventString = map[pb.MutationControl_Type]string{
MutationEvent_MUTATE: "MUTATE",
MutationEvent_INTERRUPT: "INTERRUPT",
}
type MutationEvent struct {
Type pb.MutationControl_Type
// strictly speaking, we may only need the Cfg
// but we generally have this info on hand anyway
NodeCfg types.Node
NodeDsc types.Node
Mutation [2]string // [0] = module, [1] = mutid
}
func (me *MutationEvent) String() string {
return fmt.Sprintf("(%s) %s : %s -> %s", MutationEventString[me.Type], me.NodeCfg.ID().String(), me.Mutation[0], me.Mutation[1])
}
type mutationEdge struct {
cost uint32
mut types.StateMutation
from *mutationNode
to *mutationNode
}
// consider equal if mut is the same (pointer), and to and from are the same
func (m *mutationEdge) Equal(b *mutationEdge) bool {
if m.to != b.to {
return false
}
if m.from != b.from {
return false
}
if m.mut != b.mut {
return false
}
return true
}
type mutationNode struct {
spec types.StateSpec // spec with aggregated require/excludes
in []*mutationEdge
out []*mutationEdge
}
type mutationPath struct {
mutex *sync.Mutex
cur int // where are we currently?
cmplt bool
// curSeen is a slice of URLs that we've seen (correct) changes in the current mut
// This is important to keep track of muts that change more than one URL
curSeen []string
start types.Node
end types.Node
gstart *mutationNode
gend *mutationNode
chain []*mutationEdge
timer *time.Timer
waitingFor string // the SI we're currently waiting for
}
// sme tests to see if a new path is really the same as an existing one
// same tests if one of the following is true:
// 1) these paths are the same
// 2) sub is a subpath of mp and:
// a) subpath starts at mp.cur
// b) subpath ends at mp.gend
func (mp *mutationPath) same(sub *mutationPath) bool {
mp.mutex.Lock()
defer mp.mutex.Unlock()
sub.mutex.Lock()
defer sub.mutex.Unlock()
if sub.gend != mp.gend {
// this must be true in either case
return false
}
if sub.gstart == mp.gstart {
return true
}
if mp.chain[mp.cur].from == sub.gstart {
return true
}
return false
}
// alreadyFired tests to see if the curren mp has already fired our first mutation for new mp
func (mp *mutationPath) alreadyFired(nmp *mutationPath) bool {
// generall nmp.cur == 0, but no reason not to make this more generic
return mp.chain[mp.cur].mut == nmp.chain[nmp.cur].mut
}
// DefaultRootSpec provides a sensible root StateSpec to build the mutation graph off of
func DefaultRootSpec() types.StateSpec {
return NewStateSpec(map[string]reflect.Value{"/PhysState": reflect.ValueOf(pb.Node_PHYS_UNKNOWN)}, map[string]reflect.Value{})
}
////////////////////////////////
// StateMutationEngine Object /
//////////////////////////////
var _ types.StateMutationEngine = (*StateMutationEngine)(nil)
// A StateMutationEngine listens for state change events and manages mutations to evolve Dsc state into Cfg state
type StateMutationEngine struct {
muts []types.StateMutation
mutResolver map[types.StateMutation][2]string // this allows us to lookup module/id pair from mutation
// stuff we can compute from muts
mutators map[string]uint32 // ref count, all URLs that mutate
requires map[string]uint32 // ref count, referenced (req/exc) urls that don't mutate
deps map[string]types.StateSpec
graph *mutationNode // graph start
graphMutex *sync.RWMutex
nodes []*mutationNode // so we can search for matches
edges []*mutationEdge
em *EventEmitter
qc chan types.Query
schan chan<- types.EventListener // subscription channel
echan chan types.Event
sichan chan types.Event
selist *EventListener
silist *EventListener
run bool // are we running?
active map[string]*mutationPath // active mutations
waiting map[string][]*mutationPath
activeMutex *sync.Mutex // active (and waiting) needs some synchronization, or we can get in bad places
query *QueryEngine
log types.Logger
self types.NodeID
root types.StateSpec
freeze bool
}
// NewStateMutationEngine creates an initialized StateMutationEngine
func NewStateMutationEngine(ctx Context, qc chan types.Query) *StateMutationEngine {
sme := &StateMutationEngine{
muts: []types.StateMutation{},
mutResolver: make(map[types.StateMutation][2]string),
active: make(map[string]*mutationPath),
waiting: make(map[string][]*mutationPath),
activeMutex: &sync.Mutex{},
mutators: make(map[string]uint32),
requires: make(map[string]uint32),
deps: make(map[string]types.StateSpec),
graph: &mutationNode{spec: ctx.SME.RootSpec},
graphMutex: &sync.RWMutex{},
nodes: []*mutationNode{},
edges: []*mutationEdge{},
em: NewEventEmitter(types.Event_STATE_MUTATION),
qc: qc,
run: false,
echan: make(chan types.Event),
sichan: make(chan types.Event),
query: &ctx.Query,
schan: ctx.SubChan,
log: &ctx.Logger,
self: ctx.Self,
root: ctx.SME.RootSpec,
freeze: true,
}
sme.log.SetModule("StateMutationEngine")
return sme
}
// RegisterMutation injects new mutaitons into the SME. muts[i] should match callback[i]
// We take a list so that we only call onUpdate once
// LOCKS: graphMutex (RW)
func (sme *StateMutationEngine) RegisterMutation(si, id string, mut types.StateMutation) (e error) {
sme.graphMutex.Lock()
sme.muts = append(sme.muts, mut)
sme.mutResolver[mut] = [2]string{si, id}
sme.graphMutex.Unlock()
sme.onUpdate()
return
}
// NodeMatch determines how many compatable StateSpecs this node has in the graph
func (sme *StateMutationEngine) NodeMatch(node types.Node) (i int) {
ns := sme.nodeSearch(node)
sme.Logf(DEBUG, "===\nNode:\n%v\n", string(node.JSON()))
sme.Log(DEBUG, "Matched:\n")
for _, m := range ns {
sme.Logf(DEBUG, "Spec:\nreq: %v\nexc: %v\n", m.spec.Requires(), m.spec.Excludes())
}
return len(sme.nodeSearch(node))
}
func (sme *StateMutationEngine) dumpMapOfValues(m map[string]reflect.Value) (s string) {
for k := range m {
s += fmt.Sprintf("%s: %s, ", k, util.ValueToString(m[k]))
}
return
}
func (sme *StateMutationEngine) dumpMutMap(m map[string][2]reflect.Value) (s string) {
for k := range m {
s += fmt.Sprintf("%s: %s -> %s, ", k, util.ValueToString(m[k][0]), util.ValueToString(m[k][1]))
}
return
}
// DumpGraph FIXME: REMOVE -- for debugging
// LOCKS: graphMutex (R)
func (sme *StateMutationEngine) DumpGraph() {
sme.graphMutex.RLock()
fmt.Printf("\n")
fmt.Printf("=== START: Mutators URLs ===\n")
for k, v := range sme.mutators {
fmt.Printf("%s: %d\n", k, v)
}
fmt.Printf("=== END: Mutators URLs ===\n")
fmt.Printf("=== START: Requires URLs ===\n")
for k, v := range sme.requires {
fmt.Printf("%s: %d\n", k, v)
}
fmt.Printf("=== END: Requires URLs ===\n")
fmt.Printf("\n=== START: Node list ===\n")
for _, m := range sme.nodes {
fmt.Printf(`
Node: %p
Spec: %p
req: %s
exc: %s
In: %v
Out: %v
`, m, m.spec, sme.dumpMapOfValues(m.spec.Requires()), sme.dumpMapOfValues(m.spec.Excludes()), m.in, m.out)
}
fmt.Printf("\n=== END: Node list ===\n")
fmt.Printf("\n=== START: Edge list ===\n")
for _, m := range sme.edges {
fmt.Printf(`
Edge: %p
Mutation: %p
mut: %s
req: %s
exc: %s
From: %p
To: %p
`, m, m.mut, sme.dumpMutMap(m.mut.Mutates()), sme.dumpMapOfValues(m.mut.Requires()), sme.dumpMapOfValues(m.mut.Excludes()), m.from, m.to)
}
fmt.Printf("\n=== END: Edge list ===\n")
sme.graphMutex.RUnlock()
}
// DumpJSONGraph for debugging the graph
// !!!IMPORTANT!!!
// DumpJSONGraph assumes you already hold a lock
func (sme *StateMutationEngine) DumpJSONGraph(nodes []*mutationNode, edges []*mutationEdge) {
nl := mutationNodesToProto(nodes)
el := mutationEdgesToProto(edges)
graph := struct {
Nodes []*pb.MutationNode `json:"nodes"`
Edges []*pb.MutationEdge `json:"edges"`
}{
Nodes: nl.MutationNodeList,
Edges: el.MutationEdgeList,
}
jsonGraph, e := json.Marshal(graph)
if e != nil {
fmt.Printf("error getting json graph\n")
return
}
fmt.Printf("JSON Graph: \n%v\n", string(jsonGraph))
}
// Converts a slice of sme mutation nodes to a protobuf MutationNodeList
func mutationNodesToProto(nodes []*mutationNode) (r pb.MutationNodeList) {
for _, mn := range nodes {
var nmn pb.MutationNode
nmn.Id = fmt.Sprintf("%p", mn)
label := ""
var reqKeys []string
var excKeys []string
var reqs = mn.spec.Requires()
for k := range reqs {
reqKeys = append(reqKeys, k)
}
sort.Strings(reqKeys)
var excs = mn.spec.Excludes()
for k := range excs {
excKeys = append(excKeys, k)
}
sort.Strings(excKeys)
for _, reqKey := range reqKeys {
reqValue := reqs[reqKey]
// Add req to label
trimKey := strings.Replace(reqKey, "type.googleapis.com", "", -1)
trimKey = strings.Replace(trimKey, "/", "", -1)
if label == "" {
label = fmt.Sprintf("%s: %s", trimKey, util.ValueToString(reqValue))
} else {
label = fmt.Sprintf("%s\n%s: %s", label, trimKey, util.ValueToString(reqValue))
}
}
for _, excKey := range excKeys {
excValue := excs[excKey]
// Add req to label
trimKey := strings.Replace(excKey, "type.googleapis.com", "", -1)
trimKey = strings.Replace(trimKey, "/", "", -1)
if label == "" {
label = fmt.Sprintf("%s: !%s", trimKey, util.ValueToString(excValue))
} else {
label = fmt.Sprintf("%s\n%s: !%s", label, trimKey, util.ValueToString(excValue))
}
}
nmn.Label = label
r.MutationNodeList = append(r.MutationNodeList, &nmn)
}
return
}
// Converts a slice of sme mutation edges to a protobuf MutationEdgeList
func mutationEdgesToProto(edges []*mutationEdge) (r pb.MutationEdgeList) {
for _, me := range edges {
var nme pb.MutationEdge
nme.From = fmt.Sprintf("%p", me.from)
nme.To = fmt.Sprintf("%p", me.to)
nme.Id = fmt.Sprintf("%p", me)
r.MutationEdgeList = append(r.MutationEdgeList, &nme)
}
return
}
// Converts an sme mutation path to a protobuf MutationPath
// LOCKS: path.mutex
func mutationPathToProto(path *mutationPath) (r pb.MutationPath, e error) {
path.mutex.Lock()
defer path.mutex.Unlock()
if path != nil {
r.Cur = int64(path.cur)
r.Cmplt = path.cmplt
for _, me := range path.chain {
var nme pb.MutationEdge
nme.From = fmt.Sprintf("%p", me.from)
nme.To = fmt.Sprintf("%p", me.to)
nme.Id = fmt.Sprintf("%p", me)
r.Chain = append(r.Chain, &nme)
}
} else {
e = fmt.Errorf("Mutation path is nil")
}
return
}
// Returns the mutation nodes that have correlating reqs and execs for a given nodeID
// LOCKS: activeMutex; path.mutex
func (sme *StateMutationEngine) filterMutNodesFromNode(n ct.NodeID) (r []*mutationNode, e error) {
// Get node from path
sme.activeMutex.Lock()
mp := sme.active[n.String()]
sme.activeMutex.Unlock()
if mp != nil {
mp.mutex.Lock()
node := mp.end
mp.mutex.Unlock()
// Combine discoverables and mutators into discoverables map
discoverables := make(map[string]string)
for _, siMap := range Registry.Discoverables {
for key := range siMap {
discoverables[key] = ""
}
}
sme.graphMutex.RLock()
for key := range sme.mutators {
discoverables[key] = ""
}
sme.graphMutex.RUnlock()
filteredNodes := make(map[*mutationNode]string)
for _, mn := range sme.nodes {
filteredNodes[mn] = ""
for reqKey, reqVal := range mn.spec.Requires() {
// if reqkey is not in discoverables
if _, ok := discoverables[reqKey]; !ok {
// if physical node has the reqkey as a value, check if it doesn't match
if nodeVal, err := node.GetValue(reqKey); err == nil {
// if it doesn't match, remove mn from final nodes
if nodeVal.String() != reqVal.String() {
delete(filteredNodes, mn)
}
}
}
}
for excKey, excVal := range mn.spec.Excludes() {
// if excKey is in discoverables, move on
if _, ok := discoverables[excKey]; ok {
break
}
// if physical node has the exckey as a value, check if it does match
if nodeVal, err := node.GetValue(excKey); err == nil {
// if it doesn't match, remove mn from final nodes
if nodeVal == excVal {
delete(filteredNodes, mn)
}
}
}
}
for mn := range filteredNodes {
r = append(r, mn)
}
sme.Logf(DDDEBUG, "Final filtered nodes from SME: %v", r)
} else {
e = fmt.Errorf("Can't get node info because mutation path is nil")
}
return
}
// Returns the mutation edges that match the filtered nodes from filterMutNodesFromNode
// LOCKS: activeMutex via filterMutNodesFromNode; path.mutex via filterMutNodesFromNode
func (sme *StateMutationEngine) filterMutEdgesFromNode(n ct.NodeID) (r []*mutationEdge, e error) {
nodes, e := sme.filterMutNodesFromNode(n)
filteredEdges := make(map[*mutationEdge]string)
for _, mn := range nodes {
for _, me := range mn.in {
filteredEdges[me] = ""
}
for _, me := range mn.out {
filteredEdges[me] = ""
}
}
for me := range filteredEdges {
r = append(r, me)
}
return
}
// PathExists returns a boolean indicating whether or not a path exists in the graph between two nodes.
// If the path doesn't exist, it also returns the error.
// LOCKS: graphMutex (R) via findPath
func (sme *StateMutationEngine) PathExists(start types.Node, end types.Node) (r bool, e error) {
p, e := sme.findPath(start, end)
if p != nil {
r = true
}
return
}
// goroutine
func (sme *StateMutationEngine) sendQueryResponse(qr types.QueryResponse, r chan<- types.QueryResponse) {
r <- qr
}
// QueryChan returns a chanel that Queries can be sent on
func (sme *StateMutationEngine) QueryChan() chan<- types.Query {
return sme.qc
}
// Run is a goroutine that listens for state changes and performs StateMutation magic
// LOCKS: all
func (sme *StateMutationEngine) Run(ready chan<- interface{}) {
// on run we import all mutations in the registry
sme.graphMutex.Lock()
for mod := range Registry.Mutations {
for id, mut := range Registry.Mutations[mod] {
sme.muts = append(sme.muts, mut)
sme.mutResolver[mut] = [2]string{mod, id}
}
}
sme.graphMutex.Unlock()
sme.onUpdate()
if sme.GetLoggerLevel() >= DDEBUG {
sme.DumpGraph() // Use this to debug your graph
sme.graphMutex.RLock()
sme.DumpJSONGraph(sme.nodes, sme.edges) // Use this to debug your graph
sme.graphMutex.RUnlock()
}
// create a listener for state change events we care about
sme.selist = NewEventListener(
"StateMutationEngine",
types.Event_STATE_CHANGE,
func(v types.Event) bool {
_, url := util.NodeURLSplit(v.URL())
sme.graphMutex.RLock()
defer sme.graphMutex.RUnlock()
for m := range sme.mutators {
if url == m {
return true
}
}
for m := range sme.requires {
if url == m {
return true
}
}
if url == "" { // this should mean we got CREATE/DELETE
return true
}
return false
},
func(v types.Event) error { return ChanSender(v, sme.echan) })
// subscribe our listener
sme.schan <- sme.selist
smurl := regexp.MustCompile(`^\/?Services\/`)
sme.silist = NewEventListener(
"StateMutationEngine-SI",
types.Event_STATE_CHANGE,
func(v types.Event) bool {
node, url := util.NodeURLSplit(v.URL())
if !ct.NewNodeID(node).EqualTo(sme.self) {
return false
}
if smurl.MatchString(url) {
return true
}
return false
},
func(v types.Event) error { return ChanSender(v, sme.sichan) },
)
sme.schan <- sme.silist
debugchan := make(chan interface{})
if sme.GetLoggerLevel() >= DDEBUG {
go func() {
for {
time.Sleep(10 * time.Second)
debugchan <- nil
}
}()
}
ready <- nil
for {
select {
case q := <-sme.qc:
switch q.Type() {
case types.Query_MUTATIONNODES:
_, u := util.NodeURLSplit(q.URL())
var e error
// If url is empty then assume we want all mutation nodes
if u == "" {
sme.graphMutex.RLock()
v := mutationNodesToProto(sme.nodes)
sme.graphMutex.RUnlock()
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{reflect.ValueOf(v)}, e), q.ResponseChan())
} else {
n := ct.NewNodeIDFromURL(q.URL())
sme.graphMutex.RLock()
fmn, e := sme.filterMutNodesFromNode(*n)
mnl := mutationNodesToProto(fmn)
sme.graphMutex.RUnlock()
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{reflect.ValueOf(mnl)}, e), q.ResponseChan())
}
break
case types.Query_MUTATIONEDGES:
_, u := util.NodeURLSplit(q.URL())
var e error
// If url is empty then assume we want all mutation edges
if u == "" {
sme.graphMutex.RLock()
v := mutationEdgesToProto(sme.edges)
sme.graphMutex.RUnlock()
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{reflect.ValueOf(v)}, e), q.ResponseChan())
} else {
n := ct.NewNodeIDFromURL(q.URL())
sme.graphMutex.RLock()
fme, e := sme.filterMutEdgesFromNode(*n)
mel := mutationEdgesToProto(fme)
sme.graphMutex.RUnlock()
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{reflect.ValueOf(mel)}, e), q.ResponseChan())
}
break
case types.Query_MUTATIONPATH:
n := ct.NewNodeIDFromURL(q.URL())
sme.activeMutex.Lock()
mp := sme.active[n.String()]
sme.activeMutex.Unlock()
pmp, e := mutationPathToProto(mp)
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{reflect.ValueOf(pmp)}, e), q.ResponseChan())
break
case types.Query_FREEZE:
sme.Freeze()
if sme.Frozen() {
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{}, nil), q.ResponseChan())
} else {
e := fmt.Errorf("sme failed to freeze")
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{}, e), q.ResponseChan())
}
break
case types.Query_THAW:
sme.Thaw()
if !sme.Frozen() {
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{}, nil), q.ResponseChan())
} else {
e := fmt.Errorf("sme failed to thaw")
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{}, e), q.ResponseChan())
}
break
case types.Query_FROZEN:
f := sme.Frozen()
go sme.sendQueryResponse(NewQueryResponse(
[]reflect.Value{reflect.ValueOf(f)}, nil), q.ResponseChan())
break
default:
sme.Logf(DEBUG, "unsupported query type: %d", q.Type())
}
break
case v := <-sme.echan:
// FIXME: event processing can be expensive;
// we should make them concurrent with a queue
if !sme.Frozen() {
sme.handleEvent(v)
}
break
case v := <-sme.sichan:
// Got a service change
sme.handleServiceEvent(v.Data().(*StateChangeEvent))
case <-debugchan:
sme.Logf(DDEBUG, "There are %d active mutations.", len(sme.active))
break
}
}
}
func (sme *StateMutationEngine) Frozen() bool {
sme.activeMutex.Lock()
defer sme.activeMutex.Unlock()
return sme.freeze
}
func (sme *StateMutationEngine) Freeze() {
sme.Log(INFO, "freezing")
sme.activeMutex.Lock()
sme.freeze = true
sme.activeMutex.Unlock()
}
func (sme *StateMutationEngine) Thaw() {
sme.Log(INFO, "thawing")
sme.activeMutex.Lock()
sme.active = make(map[string]*mutationPath)
sme.freeze = false
sme.activeMutex.Unlock()
ns, _ := sme.query.ReadAll()
for _, n := range ns {
sme.startNewMutation(n.ID().String())
}
}
////////////////////////
// Unexported methods /
//////////////////////
// !!!IMPORTANT!!!
// collectURLs assumes you already hold a lock
// currently only used in onUpdate
func (sme *StateMutationEngine) collectURLs() {
for _, m := range sme.muts {
for u := range m.Mutates() {
if _, ok := sme.mutators[u]; !ok {
sme.mutators[u] = 0
}
sme.mutators[u]++
}
}
// We do this as a separate loop because we don't want mutators in requires
for _, m := range sme.muts {
for u := range m.Requires() {
if _, ok := sme.mutators[u]; ok {
//skip if we've already registered as a mutator
continue
}
if _, ok := sme.requires[u]; !ok {
sme.requires[u] = 0
}
sme.requires[u]++
}
// sme.requires is a bit of a misnomer.
// really we're interested in any url we depend on to asses, including excludes.
for u := range m.Excludes() {
if _, ok := sme.mutators[u]; ok {
//skip if we've already registered as a mutator
continue
}
if _, ok := sme.requires[u]; !ok {
sme.requires[u] = 0
}
sme.requires[u]++
}
}
}
func (sme *StateMutationEngine) remapToNode(root *mutationNode, to *mutationNode, reqsOnly bool) []*mutationEdge {
var mutEqual func(*mutationEdge, *mutationEdge) bool
// if reqsOnly we consider nodes the same if they have the same requirements
if reqsOnly {
mutEqual = func(a *mutationEdge, b *mutationEdge) bool {
if a.mut != b.mut {
return false
}
if !a.from.spec.ReqsEqual(b.from.spec) {
return false
}
if !a.to.spec.ReqsEqual(b.to.spec) {
return false
}
return true
}
} else {
mutEqual = func(a *mutationEdge, b *mutationEdge) bool { return a.Equal(b) }
}
inSlice := func(s []*mutationEdge, n *mutationEdge) bool {
for _, mn := range s {
if mutEqual(mn, n) {
return true
}
}
return false
}
rmEdges := []*mutationEdge{}
// we perform a union on in/out
for _, in := range root.in {
in.to = to
if !inSlice(to.in, in) {
to.in = append(to.in, in)
} else {
rmEdges = append(rmEdges, in)
// make sure the tail is cleared
for i, v := range in.from.out {
if v == in {
in.from.out = append(in.from.out[:i], in.from.out[i+1:]...)
}
}
}
}
for _, out := range root.out {
out.from = to
if !inSlice(to.out, out) {
to.out = append(to.out, out)
} else {
// make sure the head is cleared
for i, v := range out.to.in {
if v == out {
out.to.in = append(out.to.in[:i], out.to.in[i+1:]...)
}
}
rmEdges = append(rmEdges, out)
}
}
return rmEdges
}
func nodeMerge(list []int, nodes []*mutationNode) (*mutationNode, []*mutationEdge) {
// build a new node from a merge of multiple nodes
// use least-common specification
// note: this will choke on a zero length list, but that shouldn't happen
node := nodes[list[0]] // build off of the first node
for i := 1; i < len(list); i++ {
// remap edges
inode := nodes[list[i]]
for _, e := range inode.in {
if !edgeInEdges(e, node.in) { // don't add if we already have this
e.to = node
node.in = append(node.in, e)
}
}
for _, e := range inode.out {
if !edgeInEdges(e, node.out) {
e.from = node
node.out = append(node.out, e)
}
}
// prune spec
node.spec.LeastCommon(inode.spec)
}
return node, node.out
}
// buildGraphStage1 builds a fully expanded set of paths branching from a starting root
// this will build a very verbose, probably unusable graph
// it is expected that later graph stages will clean it up and make it more sane
// root: current node, edge: edge that got us here (or nil), seenNodes: map of nodes we've seen
func (sme *StateMutationEngine) buildGraphStage1(root *mutationNode, edge *mutationEdge, seenNodes map[types.StateSpec]*mutationNode) ([]*mutationNode, []*mutationEdge) {
// for this algorithm, it just complicates things to track nodes & edges at the same time. We build the edge list at the end
nodes := []*mutationNode{}
edges := []*mutationEdge{}
// is this node equal to one we've already seen?
for sp, n := range seenNodes {
if sp.Equal(root.spec) {
// yes, we've seen this node, so we're done processing this chain. Merge the nodes.
dead := sme.remapToNode(root, n, false)
if len(dead) != 0 {
fmt.Printf("dead edges was %d, expected 0!", len(dead))
}
return nodes, edges
}
}
nodes = append(nodes, root)
seenNodes[root.spec] = root
// find connecting mutations
OUTER:
for _, m := range sme.muts {
// do we have a valid out arrow?
if m.SpecCompatOut(root.spec, sme.mutators) {
// m is a valid out arrow, create an edge for the out arrow
// first, do we already know about this one?
for _, edge := range root.out {
if m == edge.mut {
continue OUTER
}
}
newEdge := &mutationEdge{
cost: 1,
mut: m,
from: root,
}
// ...and construct the new node that it connects to
newNode := &mutationNode{
spec: root.spec.SpecMergeMust(m.After()), // a combination of the current spec + the changes the mation creates
in: []*mutationEdge{newEdge}, // we know we have this in at least
out: []*mutationEdge{}, // for now, out is empty
}
newNode.spec.StripZeros()
newEdge.to = newNode
root.out = append(root.out, newEdge)
// ready to recurse
ns, _ := sme.buildGraphStage1(newNode, newEdge, seenNodes)
nodes = append(nodes, ns...)
} else if m.SpecCompatIn(root.spec, sme.mutators) {
// note: it doesn't make sense for the same mutator to be both in/out. This would be a meaningless nop.
// m is a valid in arrow, similar to out with some subtle differences
for _, edge := range root.in {
if m == edge.mut {
continue OUTER
}
}
newEdge := &mutationEdge{
cost: 1,
mut: m,
to: root,
}
newNode := &mutationNode{
spec: root.spec.SpecMergeMust(m.Before()),
in: []*mutationEdge{},
out: []*mutationEdge{newEdge},
}
newNode.spec.StripZeros()
newEdge.from = newNode
root.in = append(root.in, newEdge)
ns, _ := sme.buildGraphStage1(newNode, newEdge, seenNodes)
nodes = append(nodes, ns...)
}
}
// build edges list
for _, n := range nodes {
edges = append(edges, n.out...)
}
return nodes, edges
}
// some useful util functions for graph building
func edgeInEdges(m *mutationEdge, es []*mutationEdge) bool {
for _, e := range es {
if m.Equal(e) {
return true
}
}
return false
}
func mutInEdges(m *mutationEdge, es []*mutationEdge) bool {
for _, e := range es {
if m.mut == e.mut {
return true
}
}
return false
}
// buildGraphReduceNodes remaps any nodes with identical edges to be the same node
// This is currently unused but may be used as a component of subgraph creation in the future
func (sme *StateMutationEngine) buildGraphReduceNodes(nodes []*mutationNode, edges []*mutationEdge) ([]*mutationNode, []*mutationEdge) {
// some tests we'll use
nodeEqual := func(a *mutationNode, b *mutationNode) bool {
if len(a.in) != len(b.in) || len(a.out) != len(b.out) {
return false
}
for _, e := range a.in {
if !mutInEdges(e, b.in) {
return false
}
}
for _, e := range a.out {
if !mutInEdges(e, b.out) {
return false
}
}
return true
}
mergeList := [][]int{}
merged := map[int]bool{}
for i := range nodes {
if _, ok := merged[i]; ok { // skip if already merged
continue
}
list := []int{i}
for j := i + 1; j < len(nodes); j++ {
if _, ok := merged[j]; ok { // skip if already merged
continue
}
if nodeEqual(nodes[i], nodes[j]) {
list = append(list, j)
merged[j] = true
}
}
mergeList = append(mergeList, list)
}
newNodes := []*mutationNode{}
newEdges := []*mutationEdge{}
for _, list := range mergeList {
n, e := nodeMerge(list, nodes)
newNodes = append(newNodes, n)
newEdges = append(newEdges, e...)
}
return newNodes, newEdges
}
// buildGraphDiscoverDepends calculates the dependencies of discoveries (any mutation that goes from zero to non-zero)
// it returns a map[state_url]spec_of_dependencies
func (sme *StateMutationEngine) buildGraphDiscoverDepends(edges []*mutationEdge) map[string]types.StateSpec {
clone := func(from map[string]reflect.Value) (to map[string]reflect.Value) {
to = make(map[string]reflect.Value)
for k, v := range from {
to[k] = v
}
return
}