forked from hashicorp/terraform
/
graph.go
2038 lines (1767 loc) · 52.1 KB
/
graph.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 terraform
import (
"errors"
"fmt"
"log"
"sort"
"strings"
"github.com/hashicorp/terraform/config"
"github.com/hashicorp/terraform/config/module"
"github.com/hashicorp/terraform/depgraph"
"github.com/hashicorp/terraform/helper/multierror"
)
// GraphOpts are options used to create the resource graph that Terraform
// walks to make changes to infrastructure.
//
// Depending on what options are set, the resulting graph will come in
// varying degrees of completeness.
type GraphOpts struct {
// Config is the configuration from which to build the basic graph.
// This is the only required item.
//Config *config.Config
// Module is the relative root of a module tree for this graph. This
// is the only required item. This should always be the absolute root
// of the tree. ModulePath below should be used to constrain the depth.
//
// ModulePath specifies the place in the tree where Module exists.
// This is used for State lookups.
Module *module.Tree
ModulePath []string
// Diff of changes that will be applied to the given state. This will
// associate a ResourceDiff with applicable resources. Additionally,
// new resource nodes representing resource destruction may be inserted
// into the graph.
Diff *Diff
// State, if present, will make the ResourceState available on each
// resource node. Additionally, any orphans will be added automatically
// to the graph.
//
// Note: the state will be modified so it is initialized with basic
// empty states for all modules/resources in this graph. If you call prune
// later, these will be removed, but the graph adds important metadata.
State *State
// Providers is a mapping of prefixes to a resource provider. If given,
// resource providers will be found, initialized, and associated to the
// resources in the graph.
//
// This will also potentially insert new nodes into the graph for
// the configuration of resource providers.
Providers map[string]ResourceProviderFactory
// Provisioners is a mapping of names to a resource provisioner.
// These must be provided to support resource provisioners.
Provisioners map[string]ResourceProvisionerFactory
// parent specifies the parent graph if there is one. This should not be
// set manually.
parent *depgraph.Graph
}
// GraphRootNode is the name of the root node in the Terraform resource
// graph. This node is just a placemarker and has no associated functionality.
const GraphRootNode = "root"
// GraphMeta is the metadata attached to the graph itself.
type GraphMeta struct {
// ModulePath is the path of the module that this graph represents.
ModulePath []string
}
// GraphNodeModule is a node type in the graph that represents a module
// that will be created/managed.
type GraphNodeModule struct {
Config *config.Module
Path []string
Graph *depgraph.Graph
State *ModuleState
Flags ResourceFlag
}
// GraphNodeResource is a node type in the graph that represents a resource
// that will be created or managed. Unlike the GraphNodeResourceMeta node,
// this represents a _single_, _resource_ to be managed, not a set of resources
// or a component of a resource.
type GraphNodeResource struct {
Index int
Config *config.Resource
Resource *Resource
ResourceProviderNode string
// All the fields below are related to expansion. These are set by
// the graph but aren't useful individually.
ExpandMode ResourceExpandMode
Diff *ModuleDiff
State *ModuleState
}
// GraphNodeResourceProvider is a node type in the graph that represents
// the configuration for a resource provider.
type GraphNodeResourceProvider struct {
ID string
Provider *graphSharedProvider
}
// graphSharedProvider is a structure that stores a configuration
// with initialized providers and might be shared across different
// graphs in order to have only one instance of a provider.
type graphSharedProvider struct {
Config *config.ProviderConfig
Providers map[string]ResourceProvider
ProviderKeys []string
Parent *graphSharedProvider
overrideConfig map[string]map[string]interface{}
parentNoun *depgraph.Noun
}
// ResourceExpandMode specifies the expand behavior of the GraphNodeResource
// node.
type ResourceExpandMode byte
const (
ResourceExpandNone ResourceExpandMode = iota
ResourceExpandApply
ResourceExpandDestroy
)
// Graph builds a dependency graph of all the resources for infrastructure
// change.
//
// This dependency graph shows the correct order that any resources need
// to be operated on.
//
// The Meta field of a graph Noun can contain one of the follow types. A
// description is next to each type to explain what it is.
//
// *GraphNodeResource - A resource. See the documentation of this
// struct for more details.
// *GraphNodeResourceProvider - A resource provider that needs to be
// configured at this point.
//
func Graph(opts *GraphOpts) (*depgraph.Graph, error) {
if opts.Module == nil {
return nil, errors.New("Module is required for Graph")
}
if opts.ModulePath == nil {
opts.ModulePath = rootModulePath
}
if !opts.Module.Loaded() {
return nil, errors.New("Module must be loaded")
}
// Get the correct module in the tree that we're looking for.
currentModule := opts.Module
for _, n := range opts.ModulePath[1:] {
children := currentModule.Children()
currentModule = children[n]
}
var conf *config.Config
if currentModule != nil {
conf = currentModule.Config()
} else {
conf = new(config.Config)
}
// Get the state and diff of the module that we're working with.
var modDiff *ModuleDiff
var modState *ModuleState
if opts.Diff != nil {
modDiff = opts.Diff.ModuleByPath(opts.ModulePath)
}
if opts.State != nil {
modState = opts.State.ModuleByPath(opts.ModulePath)
}
log.Printf("[DEBUG] Creating graph for path: %v", opts.ModulePath)
g := new(depgraph.Graph)
g.Meta = &GraphMeta{
ModulePath: opts.ModulePath,
}
// First, build the initial resource graph. This only has the resources
// and no dependencies. This only adds resources that are in the config
// and not "orphans" (that are in the state, but not in the config).
graphAddConfigResources(g, conf, modState)
if modState != nil {
// Next, add the state orphans if we have any
graphAddOrphans(g, conf, modState)
// Add tainted resources if we have any.
graphAddTainted(g, modState)
}
// Create the resource provider nodes for explicitly configured
// providers within our graph.
graphAddConfigProviderConfigs(g, conf)
if opts.parent != nil {
// Add/merge the provider configurations from the parent so that
// we properly "inherit" providers.
graphAddParentProviderConfigs(g, opts.parent)
}
// First pass matching resources to providers. This will allow us to
// determine what providers are missing.
graphMapResourceProviderId(g)
if opts.Providers != nil {
// Add missing providers from the mapping.
if err := graphAddMissingResourceProviders(g, opts.Providers); err != nil {
return nil, err
}
// Initialize all the providers
if err := graphInitResourceProviders(g, opts.Providers); err != nil {
return nil, err
}
// Map the providers to resources
if err := graphMapResourceProviders(g); err != nil {
return nil, err
}
}
// Add the modules that are in the configuration.
if err := graphAddConfigModules(g, conf, opts); err != nil {
return nil, err
}
if opts.State != nil {
// Add module orphans if we have any of those
if ms := opts.State.Children(opts.ModulePath); len(ms) > 0 {
if err := graphAddModuleOrphans(g, conf, ms, opts); err != nil {
return nil, err
}
}
}
// Add the orphan dependencies
graphAddOrphanDeps(g, modState)
// Add the orphan module dependencies
graphAddOrphanModuleDeps(g, modState)
// Add the provider dependencies
graphAddResourceProviderDeps(g)
// Now, prune the providers that we aren't using.
graphPruneResourceProviders(g)
// Add explicit dependsOn dependencies to the graph
graphAddExplicitDeps(g)
// Setup the provisioners. These may have variable dependencies,
// and must be done before dependency setup
if err := graphMapResourceProvisioners(g, opts.Provisioners); err != nil {
return nil, err
}
// Add all the variable dependencies
graphAddVariableDeps(g)
// Build the root so that we have a single valid root
graphAddRoot(g)
// If we have a diff, then make sure to add that in
if modDiff != nil {
if err := graphAddDiff(g, opts.Diff, modDiff); err != nil {
return nil, err
}
}
// Encode the dependencies
graphEncodeDependencies(g)
// Validate
if err := g.Validate(); err != nil {
return nil, err
}
log.Printf(
"[DEBUG] Graph %v created and valid. %d nouns.",
opts.ModulePath,
len(g.Nouns))
return g, nil
}
// graphEncodeDependencies is used to initialize a State with a ResourceState
// for every resource.
//
// This method is very important to call because it will properly setup
// the ResourceState dependency information with data from the graph. This
// allows orphaned resources to be destroyed in the proper order.
func graphEncodeDependencies(g *depgraph.Graph) {
for _, n := range g.Nouns {
switch rn := n.Meta.(type) {
case *GraphNodeResource:
// If we are using create-before-destroy, there
// are some special depedencies injected on the
// deposed node that would cause a circular depedency
// chain if persisted. We must only handle the new node,
// node the deposed node.
r := rn.Resource
if r.Flags&FlagDeposed != 0 {
continue
}
// Update the dependencies
var inject []string
for _, dep := range n.Deps {
switch target := dep.Target.Meta.(type) {
case *GraphNodeModule:
inject = append(inject, dep.Target.Name)
case *GraphNodeResource:
if target.Resource.Id == r.Id {
continue
}
inject = append(inject, target.Resource.Id)
case *GraphNodeResourceProvider:
// Do nothing
default:
panic(fmt.Sprintf("Unknown graph node: %#v", dep.Target))
}
}
// Update the dependencies
r.Dependencies = inject
case *GraphNodeModule:
// Update the dependencies
var inject []string
for _, dep := range n.Deps {
switch target := dep.Target.Meta.(type) {
case *GraphNodeModule:
if dep.Target.Name == n.Name {
continue
}
inject = append(inject, dep.Target.Name)
case *GraphNodeResource:
inject = append(inject, target.Resource.Id)
case *GraphNodeResourceProvider:
// Do nothing
default:
panic(fmt.Sprintf("Unknown graph node: %#v", dep.Target))
}
}
// Update the dependencies
if rn.State != nil {
rn.State.Dependencies = inject
}
}
}
}
// graphAddConfigModules adds the modules from a configuration structure
// into the graph, expanding each to their own sub-graph.
func graphAddConfigModules(
g *depgraph.Graph,
c *config.Config,
opts *GraphOpts) error {
// Just short-circuit the whole thing if we don't have modules
if len(c.Modules) == 0 {
return nil
}
// Build the list of nouns to add to the graph
nounsList := make([]*depgraph.Noun, 0, len(c.Modules))
for _, m := range c.Modules {
if n, err := graphModuleNoun(m.Name, m, g, opts); err != nil {
return err
} else {
// Attach the module state if any
if opts.State != nil {
module := n.Meta.(*GraphNodeModule)
module.State = opts.State.ModuleByPath(module.Path)
if module.State == nil {
module.State = opts.State.AddModule(module.Path)
}
}
nounsList = append(nounsList, n)
}
}
g.Nouns = append(g.Nouns, nounsList...)
return nil
}
// configGraph turns a configuration structure into a dependency graph.
func graphAddConfigResources(
g *depgraph.Graph, c *config.Config, mod *ModuleState) {
meta := g.Meta.(*GraphMeta)
// This tracks all the resource nouns
nounsList := make([]*depgraph.Noun, len(c.Resources))
for i, r := range c.Resources {
name := r.Id()
// Build the noun
nounsList[i] = &depgraph.Noun{
Name: name,
Meta: &GraphNodeResource{
Index: -1,
Config: r,
Resource: &Resource{
Id: name,
Info: &InstanceInfo{
Id: name,
ModulePath: meta.ModulePath,
Type: r.Type,
},
},
State: mod.View(name),
ExpandMode: ResourceExpandApply,
},
}
/*
TODO: probably did something important, bring it back somehow
resourceNouns := make([]*depgraph.Noun, r.Count)
for i := 0; i < r.Count; i++ {
name := r.Id()
index := -1
// If we have a count that is more than one, then make sure
// we suffix with the number of the resource that this is.
if r.Count > 1 {
name = fmt.Sprintf("%s.%d", name, i)
index = i
}
var state *ResourceState
if mod != nil {
// Lookup the resource state
state = mod.Resources[name]
if state == nil {
if r.Count == 1 {
// If the count is one, check the state for ".0"
// appended, which might exist if we go from
// count > 1 to count == 1.
state = mod.Resources[r.Id()+".0"]
} else if i == 0 {
// If count is greater than one, check for state
// with just the ID, which might exist if we go
// from count == 1 to count > 1
state = mod.Resources[r.Id()]
}
// TODO(mitchellh): If one of the above works, delete
// the old style and just copy it to the new style.
}
}
if state == nil {
state = &ResourceState{
Type: r.Type,
}
}
flags := FlagPrimary
if len(state.Tainted) > 0 {
flags |= FlagHasTainted
}
resourceNouns[i] = &depgraph.Noun{
Name: name,
Meta: &GraphNodeResource{
Index: index,
Config: r,
Resource: &Resource{
Id: name,
Info: &InstanceInfo{
Id: name,
ModulePath: meta.ModulePath,
Type: r.Type,
},
State: state.Primary,
Config: NewResourceConfig(r.RawConfig),
Flags: flags,
},
},
}
}
// If we have more than one, then create a meta node to track
// the resources.
if r.Count > 1 {
metaNoun := &depgraph.Noun{
Name: r.Id(),
Meta: &GraphNodeResourceMeta{
ID: r.Id(),
Name: r.Name,
Type: r.Type,
Count: r.Count,
},
}
// Create the dependencies on this noun
for _, n := range resourceNouns {
metaNoun.Deps = append(metaNoun.Deps, &depgraph.Dependency{
Name: n.Name,
Source: metaNoun,
Target: n,
})
}
// Assign it to the map so that we have it
nouns[metaNoun.Name] = metaNoun
}
for _, n := range resourceNouns {
nouns[n.Name] = n
}
*/
}
g.Name = "terraform"
g.Nouns = append(g.Nouns, nounsList...)
}
// graphAddDiff takes an already-built graph of resources and adds the
// diffs to the resource nodes themselves.
//
// This may also introduces new graph elements. If there are diffs that
// require a destroy, new elements may be introduced since destroy order
// is different than create order. For example, destroying a VPC requires
// destroying the VPC's subnets first, whereas creating a VPC requires
// doing it before the subnets are created. This function handles inserting
// these nodes for you.
func graphAddDiff(g *depgraph.Graph, gDiff *Diff, d *ModuleDiff) error {
var nlist []*depgraph.Noun
var modules []*depgraph.Noun
injected := make(map[*depgraph.Dependency]struct{})
for _, n := range g.Nouns {
// A module is being destroyed if all it's resources are being
// destroyed (via a destroy plan) or if it is orphaned. Only in
// those cases do we need to handle depedency inversion.
if mod, ok := n.Meta.(*GraphNodeModule); ok {
md := gDiff.ModuleByPath(mod.Path)
if mod.Flags&FlagOrphan != 0 || (md != nil && md.Destroy) {
modules = append(modules, n)
}
continue
}
rn, ok := n.Meta.(*GraphNodeResource)
if !ok {
continue
}
if rn.Resource.Flags&FlagTainted != 0 {
continue
}
change := false
destroy := false
diffs := d.Instances(rn.Resource.Id)
if len(diffs) == 0 {
continue
}
for _, d := range diffs {
if d.Destroy {
destroy = true
}
if len(d.Attributes) > 0 {
change = true
}
}
// If we're expanding, save the diff so we can add it on later
if rn.ExpandMode > ResourceExpandNone {
rn.Diff = d
}
// If we are not expanding, then we assign the
// instance diff to the resource.
var rd *InstanceDiff
if rn.ExpandMode == ResourceExpandNone {
rd = diffs[0]
}
if destroy {
// If we're destroying, we create a new destroy node with
// the proper dependencies. Perform a dirty copy operation.
newNode := new(GraphNodeResource)
*newNode = *rn
newNode.Resource = new(Resource)
*newNode.Resource = *rn.Resource
// Make the diff _just_ the destroy.
newNode.Resource.Diff = &InstanceDiff{Destroy: true}
// Make sure ExpandDestroy is set if Expand
if newNode.ExpandMode == ResourceExpandApply {
newNode.ExpandMode = ResourceExpandDestroy
}
// Create the new node
newN := &depgraph.Noun{
Name: fmt.Sprintf("%s (destroy)", newNode.Resource.Id),
Meta: newNode,
}
newN.Deps = make([]*depgraph.Dependency, len(n.Deps))
// Copy all the dependencies and do a fixup later
copy(newN.Deps, n.Deps)
// Append it to the list so we handle it later
nlist = append(nlist, newN)
if rd != nil {
// Mark the old diff to not destroy since we handle that in
// the dedicated node.
newDiff := new(InstanceDiff)
*newDiff = *rd
newDiff.Destroy = false
rd = newDiff
}
// The dependency ordering depends on if the CreateBeforeDestroy
// flag is enabled. If so, we must create the replacement first,
// and then destroy the old instance.
if rn.Config != nil && rn.Config.Lifecycle.CreateBeforeDestroy && change {
dep := &depgraph.Dependency{
Name: n.Name,
Source: newN,
Target: n,
}
// Add the old noun to the new noun dependencies so that
// the create happens before the destroy.
newN.Deps = append(newN.Deps, dep)
// Mark that this dependency has been injected so that
// we do not invert the direction below.
injected[dep] = struct{}{}
// Add a depedency from the root, since the create node
// does not depend on us
if g.Root != nil {
g.Root.Deps = append(g.Root.Deps, &depgraph.Dependency{
Name: newN.Name,
Source: g.Root,
Target: newN,
})
}
// Set the ReplacePrimary flag on the new instance so that
// it will become the new primary, and Diposed flag on the
// existing instance so that it will step down
rn.Resource.Flags |= FlagReplacePrimary
newNode.Resource.Flags |= FlagDeposed
// This logic is not intuitive, but we need to make the
// destroy depend upon any resources that depend on the
// create. The reason is suppose you have a LB depend on
// a web server. You need the order to be create, update LB,
// destroy. Without this, the update LB and destroy can
// be executed in an arbitrary order (likely in parallel).
incoming := g.DependsOn(n)
for _, inc := range incoming {
// Ignore the root...
if inc == g.Root {
continue
}
dep := &depgraph.Dependency{
Name: inc.Name,
Source: newN,
Target: inc,
}
injected[dep] = struct{}{}
newN.Deps = append(newN.Deps, dep)
}
} else {
dep := &depgraph.Dependency{
Name: newN.Name,
Source: n,
Target: newN,
}
// Add the new noun to our dependencies so that
// the destroy happens before the apply.
n.Deps = append(n.Deps, dep)
}
}
rn.Resource.Diff = rd
}
// Go through each resource and module and make sure we
// calculate all the dependencies properly.
invertDeps := [][]*depgraph.Noun{nlist, modules}
for _, list := range invertDeps {
for _, n := range list {
deps := n.Deps
num := len(deps)
for i := 0; i < num; i++ {
dep := deps[i]
// Check if this dependency was just injected, otherwise
// we will incorrectly flip the depedency twice.
if _, ok := injected[dep]; ok {
continue
}
switch target := dep.Target.Meta.(type) {
case *GraphNodeResource:
// If the other node is also being deleted,
// we must be deleted first. E.g. if A -> B,
// then when we create, B is created first then A.
// On teardown, A is destroyed first, then B.
// Thus we must flip our depedency and instead inject
// it on B.
for _, n2 := range nlist {
rn2 := n2.Meta.(*GraphNodeResource)
if target.Resource.Id == rn2.Resource.Id {
newDep := &depgraph.Dependency{
Name: n.Name,
Source: n2,
Target: n,
}
injected[newDep] = struct{}{}
n2.Deps = append(n2.Deps, newDep)
break
}
}
// Drop the dependency. We may have created
// an inverse depedency if the dependent resource
// is also being deleted, but this dependence is
// no longer required.
deps[i], deps[num-1] = deps[num-1], nil
num--
i--
case *GraphNodeModule:
// We invert any module dependencies so we're destroyed
// first, before any modules are applied.
newDep := &depgraph.Dependency{
Name: n.Name,
Source: dep.Target,
Target: n,
}
dep.Target.Deps = append(dep.Target.Deps, newDep)
// Drop the dependency. We may have created
// an inverse depedency if the dependent resource
// is also being deleted, but this dependence is
// no longer required.
deps[i], deps[num-1] = deps[num-1], nil
num--
i--
case *GraphNodeResourceProvider:
// Keep these around, but fix up the source to be ourselves
// rather than the old node.
newDep := *dep
newDep.Source = n
deps[i] = &newDep
default:
panic(fmt.Errorf("Unhandled depedency type: %#v", dep.Target.Meta))
}
}
n.Deps = deps[:num]
}
}
// Add the nouns to the graph
g.Nouns = append(g.Nouns, nlist...)
return nil
}
// graphAddExplicitDeps adds the dependencies to the graph for the explicit
// dependsOn configurations.
func graphAddExplicitDeps(g *depgraph.Graph) {
depends := false
rs := make(map[string]*depgraph.Noun)
for _, n := range g.Nouns {
rn, ok := n.Meta.(*GraphNodeResource)
if !ok {
continue
}
if rn.Config == nil {
// Orphan. It can't be depended on or have depends (explicit)
// anyways.
continue
}
rs[rn.Resource.Id] = n
if rn.Config != nil && len(rn.Config.DependsOn) > 0 {
depends = true
}
}
// If we didn't have any dependsOn, just return
if !depends {
return
}
for _, n1 := range rs {
rn1 := n1.Meta.(*GraphNodeResource)
for _, d := range rn1.Config.DependsOn {
for _, n2 := range rs {
rn2 := n2.Meta.(*GraphNodeResource)
if rn2.Config.Id() != d {
continue
}
n1.Deps = append(n1.Deps, &depgraph.Dependency{
Name: d,
Source: n1,
Target: n2,
})
}
}
}
}
// graphAddMissingResourceProviders adds GraphNodeResourceProvider nodes for
// the resources that do not have an explicit resource provider specified
// because no provider configuration was given.
func graphAddMissingResourceProviders(
g *depgraph.Graph,
ps map[string]ResourceProviderFactory) error {
var errs []error
for _, n := range g.Nouns {
rn, ok := n.Meta.(*GraphNodeResource)
if !ok {
continue
}
if rn.ResourceProviderNode != "" {
continue
}
prefixes := matchingPrefixes(rn.Resource.Info.Type, ps)
if len(prefixes) == 0 {
errs = append(errs, fmt.Errorf(
"No matching provider for type: %s",
rn.Resource.Info.Type))
continue
}
// The resource provider ID is simply the shortest matching
// prefix, since that'll give us the most resource providers
// to choose from.
id := prefixes[len(prefixes)-1]
rn.ResourceProviderNode = fmt.Sprintf("provider.%s", id)
// If we don't have a matching noun for this yet, insert it.
if g.Noun(rn.ResourceProviderNode) == nil {
pn := &depgraph.Noun{
Name: rn.ResourceProviderNode,
Meta: &GraphNodeResourceProvider{
ID: id,
Provider: new(graphSharedProvider),
},
}
g.Nouns = append(g.Nouns, pn)
}
}
if len(errs) > 0 {
return &multierror.Error{Errors: errs}
}
return nil
}
func graphAddModuleOrphans(
g *depgraph.Graph,
config *config.Config,
ms []*ModuleState,
opts *GraphOpts) error {
// Build a lookup map for the modules we do have defined
childrenKeys := make(map[string]struct{})
for _, m := range config.Modules {
childrenKeys[m.Name] = struct{}{}
}
// Go through each of the child modules. If we don't have it in our
// config, it is an orphan.
var nounsList []*depgraph.Noun
for _, m := range ms {
k := m.Path[len(m.Path)-1]
if _, ok := childrenKeys[k]; ok {
// We have this module configured
continue
}
if n, err := graphModuleNoun(k, nil, g, opts); err != nil {
return err
} else {
// Mark this module as being an orphan
module := n.Meta.(*GraphNodeModule)
module.Flags |= FlagOrphan
module.State = m
nounsList = append(nounsList, n)
}
}
g.Nouns = append(g.Nouns, nounsList...)
return nil
}
// graphAddOrphanDeps adds the dependencies to the orphans based on their
// explicit Dependencies state.
func graphAddOrphanDeps(g *depgraph.Graph, mod *ModuleState) {
for _, n := range g.Nouns {
rn, ok := n.Meta.(*GraphNodeResource)
if !ok {
continue
}
if rn.Resource.Flags&FlagOrphan == 0 {
continue
}
// If we have no dependencies, then just continue
rs := mod.Resources[n.Name]
if len(rs.Dependencies) == 0 {
continue
}
for _, n2 := range g.Nouns {
// Don't ever depend on ourselves
if n2.Meta == n.Meta {
continue
}
var compareName string
switch rn2 := n2.Meta.(type) {
case *GraphNodeModule:
compareName = n2.Name
case *GraphNodeResource:
compareName = rn2.Resource.Id
}
if compareName == "" {
continue
}
for _, depName := range rs.Dependencies {
if !strings.HasPrefix(depName, compareName) {
continue
}
dep := &depgraph.Dependency{
Name: depName,
Source: n,
Target: n2,
}
n.Deps = append(n.Deps, dep)
break
}
}
}
}
// graphAddOrphanModuleDeps adds the dependencies to the orphan
// modules based on their explicit Dependencies state.
func graphAddOrphanModuleDeps(g *depgraph.Graph, mod *ModuleState) {
for _, n := range g.Nouns {
module, ok := n.Meta.(*GraphNodeModule)
if !ok {
continue
}
if module.Flags&FlagOrphan == 0 {
continue
}
// If we have no dependencies, then just continue
if len(module.State.Dependencies) == 0 {
continue
}
for _, n2 := range g.Nouns {
// Don't ever depend on ourselves
if n2.Meta == n.Meta {
continue
}
var compareName string
switch rn2 := n2.Meta.(type) {