github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/terraform/graph_config_node_resource.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/hashicorp/terraform/config"
     8  	"github.com/hashicorp/terraform/dag"
     9  	"github.com/hashicorp/terraform/dot"
    10  )
    11  
    12  // GraphNodeCountDependent is implemented by resources for giving only
    13  // the dependencies they have from the "count" field.
    14  type GraphNodeCountDependent interface {
    15  	CountDependentOn() []string
    16  }
    17  
    18  // GraphNodeConfigResource represents a resource within the config graph.
    19  type GraphNodeConfigResource struct {
    20  	Resource *config.Resource
    21  
    22  	// If this is set to anything other than destroyModeNone, then this
    23  	// resource represents a resource that will be destroyed in some way.
    24  	DestroyMode GraphNodeDestroyMode
    25  
    26  	// Used during DynamicExpand to target indexes
    27  	Targets []ResourceAddress
    28  
    29  	Path []string
    30  }
    31  
    32  func (n *GraphNodeConfigResource) ConfigType() GraphNodeConfigType {
    33  	return GraphNodeConfigTypeResource
    34  }
    35  
    36  func (n *GraphNodeConfigResource) DependableName() []string {
    37  	return []string{n.Resource.Id()}
    38  }
    39  
    40  // GraphNodeCountDependent impl.
    41  func (n *GraphNodeConfigResource) CountDependentOn() []string {
    42  	result := make([]string, 0, len(n.Resource.RawCount.Variables))
    43  	for _, v := range n.Resource.RawCount.Variables {
    44  		if vn := varNameForVar(v); vn != "" {
    45  			result = append(result, vn)
    46  		}
    47  	}
    48  
    49  	return result
    50  }
    51  
    52  // GraphNodeDependent impl.
    53  func (n *GraphNodeConfigResource) DependentOn() []string {
    54  	result := make([]string, len(n.Resource.DependsOn),
    55  		(len(n.Resource.RawCount.Variables)+
    56  			len(n.Resource.RawConfig.Variables)+
    57  			len(n.Resource.DependsOn))*2)
    58  	copy(result, n.Resource.DependsOn)
    59  
    60  	for _, v := range n.Resource.RawCount.Variables {
    61  		if vn := varNameForVar(v); vn != "" {
    62  			result = append(result, vn)
    63  		}
    64  	}
    65  	for _, v := range n.Resource.RawConfig.Variables {
    66  		if vn := varNameForVar(v); vn != "" {
    67  			result = append(result, vn)
    68  		}
    69  	}
    70  	for _, p := range n.Resource.Provisioners {
    71  		for _, v := range p.ConnInfo.Variables {
    72  			if vn := varNameForVar(v); vn != "" && vn != n.Resource.Id() {
    73  				result = append(result, vn)
    74  			}
    75  		}
    76  		for _, v := range p.RawConfig.Variables {
    77  			if vn := varNameForVar(v); vn != "" && vn != n.Resource.Id() {
    78  				result = append(result, vn)
    79  			}
    80  		}
    81  	}
    82  
    83  	return result
    84  }
    85  
    86  // VarWalk calls a callback for all the variables that this resource
    87  // depends on.
    88  func (n *GraphNodeConfigResource) VarWalk(fn func(config.InterpolatedVariable)) {
    89  	for _, v := range n.Resource.RawCount.Variables {
    90  		fn(v)
    91  	}
    92  	for _, v := range n.Resource.RawConfig.Variables {
    93  		fn(v)
    94  	}
    95  	for _, p := range n.Resource.Provisioners {
    96  		for _, v := range p.ConnInfo.Variables {
    97  			fn(v)
    98  		}
    99  		for _, v := range p.RawConfig.Variables {
   100  			fn(v)
   101  		}
   102  	}
   103  }
   104  
   105  func (n *GraphNodeConfigResource) Name() string {
   106  	result := n.Resource.Id()
   107  	switch n.DestroyMode {
   108  	case DestroyNone:
   109  	case DestroyPrimary:
   110  		result += " (destroy)"
   111  	case DestroyTainted:
   112  		result += " (destroy tainted)"
   113  	default:
   114  		result += " (unknown destroy type)"
   115  	}
   116  
   117  	return result
   118  }
   119  
   120  // GraphNodeDotter impl.
   121  func (n *GraphNodeConfigResource) DotNode(name string, opts *GraphDotOpts) *dot.Node {
   122  	if n.DestroyMode != DestroyNone && !opts.Verbose {
   123  		return nil
   124  	}
   125  	return dot.NewNode(name, map[string]string{
   126  		"label": n.Name(),
   127  		"shape": "box",
   128  	})
   129  }
   130  
   131  // GraphNodeFlattenable impl.
   132  func (n *GraphNodeConfigResource) Flatten(p []string) (dag.Vertex, error) {
   133  	return &GraphNodeConfigResourceFlat{
   134  		GraphNodeConfigResource: n,
   135  		PathValue:               p,
   136  	}, nil
   137  }
   138  
   139  // GraphNodeDynamicExpandable impl.
   140  func (n *GraphNodeConfigResource) DynamicExpand(ctx EvalContext) (*Graph, error) {
   141  	state, lock := ctx.State()
   142  	lock.RLock()
   143  	defer lock.RUnlock()
   144  
   145  	// Start creating the steps
   146  	steps := make([]GraphTransformer, 0, 5)
   147  
   148  	// Primary and non-destroy modes are responsible for creating/destroying
   149  	// all the nodes, expanding counts.
   150  	switch n.DestroyMode {
   151  	case DestroyNone, DestroyPrimary:
   152  		steps = append(steps, &ResourceCountTransformer{
   153  			Resource: n.Resource,
   154  			Destroy:  n.DestroyMode != DestroyNone,
   155  			Targets:  n.Targets,
   156  		})
   157  	}
   158  
   159  	// Additional destroy modifications.
   160  	switch n.DestroyMode {
   161  	case DestroyPrimary:
   162  		// If we're destroying the primary instance, then we want to
   163  		// expand orphans, which have all the same semantics in a destroy
   164  		// as a primary.
   165  		steps = append(steps, &OrphanTransformer{
   166  			State:   state,
   167  			View:    n.Resource.Id(),
   168  			Targets: n.Targets,
   169  		})
   170  
   171  		steps = append(steps, &DeposedTransformer{
   172  			State: state,
   173  			View:  n.Resource.Id(),
   174  		})
   175  	case DestroyTainted:
   176  		// If we're only destroying tainted resources, then we only
   177  		// want to find tainted resources and destroy them here.
   178  		steps = append(steps, &TaintedTransformer{
   179  			State: state,
   180  			View:  n.Resource.Id(),
   181  		})
   182  	}
   183  
   184  	// Always end with the root being added
   185  	steps = append(steps, &RootTransformer{})
   186  
   187  	// Build the graph
   188  	b := &BasicGraphBuilder{Steps: steps}
   189  	return b.Build(ctx.Path())
   190  }
   191  
   192  // GraphNodeAddressable impl.
   193  func (n *GraphNodeConfigResource) ResourceAddress() *ResourceAddress {
   194  	return &ResourceAddress{
   195  		Path:         n.Path[1:],
   196  		Index:        -1,
   197  		InstanceType: TypePrimary,
   198  		Name:         n.Resource.Name,
   199  		Type:         n.Resource.Type,
   200  	}
   201  }
   202  
   203  // GraphNodeTargetable impl.
   204  func (n *GraphNodeConfigResource) SetTargets(targets []ResourceAddress) {
   205  	n.Targets = targets
   206  }
   207  
   208  // GraphNodeEvalable impl.
   209  func (n *GraphNodeConfigResource) EvalTree() EvalNode {
   210  	return &EvalSequence{
   211  		Nodes: []EvalNode{
   212  			&EvalInterpolate{Config: n.Resource.RawCount},
   213  			&EvalOpFilter{
   214  				Ops:  []walkOperation{walkValidate},
   215  				Node: &EvalValidateCount{Resource: n.Resource},
   216  			},
   217  			&EvalCountFixZeroOneBoundary{Resource: n.Resource},
   218  		},
   219  	}
   220  }
   221  
   222  // GraphNodeProviderConsumer
   223  func (n *GraphNodeConfigResource) ProvidedBy() []string {
   224  	return []string{resourceProvider(n.Resource.Type, n.Resource.Provider)}
   225  }
   226  
   227  // GraphNodeProvisionerConsumer
   228  func (n *GraphNodeConfigResource) ProvisionedBy() []string {
   229  	result := make([]string, len(n.Resource.Provisioners))
   230  	for i, p := range n.Resource.Provisioners {
   231  		result[i] = p.Type
   232  	}
   233  
   234  	return result
   235  }
   236  
   237  // GraphNodeDestroyable
   238  func (n *GraphNodeConfigResource) DestroyNode(mode GraphNodeDestroyMode) GraphNodeDestroy {
   239  	// If we're already a destroy node, then don't do anything
   240  	if n.DestroyMode != DestroyNone {
   241  		return nil
   242  	}
   243  
   244  	result := &graphNodeResourceDestroy{
   245  		GraphNodeConfigResource: *n,
   246  		Original:                n,
   247  	}
   248  	result.DestroyMode = mode
   249  	return result
   250  }
   251  
   252  // GraphNodeNoopPrunable
   253  func (n *GraphNodeConfigResource) Noop(opts *NoopOpts) bool {
   254  	// We don't have any noop optimizations for destroy nodes yet
   255  	if n.DestroyMode != DestroyNone {
   256  		return false
   257  	}
   258  
   259  	// If there is no diff, then we aren't a noop since something needs to
   260  	// be done (such as a plan). We only check if we're a noop in a diff.
   261  	if opts.Diff == nil || opts.Diff.Empty() {
   262  		return false
   263  	}
   264  
   265  	// If we have no module diff, we're certainly a noop. This is because
   266  	// it means there is a diff, and that the module we're in just isn't
   267  	// in it, meaning we're not doing anything.
   268  	if opts.ModDiff == nil || opts.ModDiff.Empty() {
   269  		return true
   270  	}
   271  
   272  	// Grab the ID which is the prefix (in the case count > 0 at some point)
   273  	prefix := n.Resource.Id()
   274  
   275  	// Go through the diff and if there are any with our name on it, keep us
   276  	found := false
   277  	for k, _ := range opts.ModDiff.Resources {
   278  		if strings.HasPrefix(k, prefix) {
   279  			found = true
   280  			break
   281  		}
   282  	}
   283  
   284  	return !found
   285  }
   286  
   287  // Same as GraphNodeConfigResource, but for flattening
   288  type GraphNodeConfigResourceFlat struct {
   289  	*GraphNodeConfigResource
   290  
   291  	PathValue []string
   292  }
   293  
   294  func (n *GraphNodeConfigResourceFlat) Name() string {
   295  	return fmt.Sprintf(
   296  		"%s.%s", modulePrefixStr(n.PathValue), n.GraphNodeConfigResource.Name())
   297  }
   298  
   299  func (n *GraphNodeConfigResourceFlat) Path() []string {
   300  	return n.PathValue
   301  }
   302  
   303  func (n *GraphNodeConfigResourceFlat) DependableName() []string {
   304  	return modulePrefixList(
   305  		n.GraphNodeConfigResource.DependableName(),
   306  		modulePrefixStr(n.PathValue))
   307  }
   308  
   309  func (n *GraphNodeConfigResourceFlat) DependentOn() []string {
   310  	prefix := modulePrefixStr(n.PathValue)
   311  	return modulePrefixList(
   312  		n.GraphNodeConfigResource.DependentOn(),
   313  		prefix)
   314  }
   315  
   316  func (n *GraphNodeConfigResourceFlat) ProvidedBy() []string {
   317  	prefix := modulePrefixStr(n.PathValue)
   318  	return modulePrefixList(
   319  		n.GraphNodeConfigResource.ProvidedBy(),
   320  		prefix)
   321  }
   322  
   323  func (n *GraphNodeConfigResourceFlat) ProvisionedBy() []string {
   324  	prefix := modulePrefixStr(n.PathValue)
   325  	return modulePrefixList(
   326  		n.GraphNodeConfigResource.ProvisionedBy(),
   327  		prefix)
   328  }
   329  
   330  // GraphNodeDestroyable impl.
   331  func (n *GraphNodeConfigResourceFlat) DestroyNode(mode GraphNodeDestroyMode) GraphNodeDestroy {
   332  	// Get our parent destroy node. If we don't have any, just return
   333  	raw := n.GraphNodeConfigResource.DestroyNode(mode)
   334  	if raw == nil {
   335  		return nil
   336  	}
   337  
   338  	node, ok := raw.(*graphNodeResourceDestroy)
   339  	if !ok {
   340  		panic(fmt.Sprintf("unknown destroy node: %s %T", dag.VertexName(raw), raw))
   341  	}
   342  
   343  	// Otherwise, wrap it so that it gets the proper module treatment.
   344  	return &graphNodeResourceDestroyFlat{
   345  		graphNodeResourceDestroy: node,
   346  		PathValue:                n.PathValue,
   347  		FlatCreateNode:           n,
   348  	}
   349  }
   350  
   351  type graphNodeResourceDestroyFlat struct {
   352  	*graphNodeResourceDestroy
   353  
   354  	PathValue []string
   355  
   356  	// Needs to be able to properly yield back a flattened create node to prevent
   357  	FlatCreateNode *GraphNodeConfigResourceFlat
   358  }
   359  
   360  func (n *graphNodeResourceDestroyFlat) Name() string {
   361  	return fmt.Sprintf(
   362  		"%s.%s", modulePrefixStr(n.PathValue), n.graphNodeResourceDestroy.Name())
   363  }
   364  
   365  func (n *graphNodeResourceDestroyFlat) Path() []string {
   366  	return n.PathValue
   367  }
   368  
   369  func (n *graphNodeResourceDestroyFlat) CreateNode() dag.Vertex {
   370  	return n.FlatCreateNode
   371  }
   372  
   373  func (n *graphNodeResourceDestroyFlat) ProvidedBy() []string {
   374  	prefix := modulePrefixStr(n.PathValue)
   375  	return modulePrefixList(
   376  		n.GraphNodeConfigResource.ProvidedBy(),
   377  		prefix)
   378  }
   379  
   380  // graphNodeResourceDestroy represents the logical destruction of a
   381  // resource. This node doesn't mean it will be destroyed for sure, but
   382  // instead that if a destroy were to happen, it must happen at this point.
   383  type graphNodeResourceDestroy struct {
   384  	GraphNodeConfigResource
   385  	Original *GraphNodeConfigResource
   386  }
   387  
   388  func (n *graphNodeResourceDestroy) CreateBeforeDestroy() bool {
   389  	// CBD is enabled if the resource enables it in addition to us
   390  	// being responsible for destroying the primary state. The primary
   391  	// state destroy node is the only destroy node that needs to be
   392  	// "shuffled" according to the CBD rules, since tainted resources
   393  	// don't have the same inverse dependencies.
   394  	return n.Original.Resource.Lifecycle.CreateBeforeDestroy &&
   395  		n.DestroyMode == DestroyPrimary
   396  }
   397  
   398  func (n *graphNodeResourceDestroy) CreateNode() dag.Vertex {
   399  	return n.Original
   400  }
   401  
   402  func (n *graphNodeResourceDestroy) DestroyInclude(d *ModuleDiff, s *ModuleState) bool {
   403  	switch n.DestroyMode {
   404  	case DestroyPrimary:
   405  		return n.destroyIncludePrimary(d, s)
   406  	case DestroyTainted:
   407  		return n.destroyIncludeTainted(d, s)
   408  	default:
   409  		return true
   410  	}
   411  }
   412  
   413  func (n *graphNodeResourceDestroy) destroyIncludeTainted(
   414  	d *ModuleDiff, s *ModuleState) bool {
   415  	// If there is no state, there can't by any tainted.
   416  	if s == nil {
   417  		return false
   418  	}
   419  
   420  	// Grab the ID which is the prefix (in the case count > 0 at some point)
   421  	prefix := n.Original.Resource.Id()
   422  
   423  	// Go through the resources and find any with our prefix. If there
   424  	// are any tainted, we need to keep it.
   425  	for k, v := range s.Resources {
   426  		if !strings.HasPrefix(k, prefix) {
   427  			continue
   428  		}
   429  
   430  		if len(v.Tainted) > 0 {
   431  			return true
   432  		}
   433  	}
   434  
   435  	// We didn't find any tainted nodes, return
   436  	return false
   437  }
   438  
   439  func (n *graphNodeResourceDestroy) destroyIncludePrimary(
   440  	d *ModuleDiff, s *ModuleState) bool {
   441  	// Get the count, and specifically the raw value of the count
   442  	// (with interpolations and all). If the count is NOT a static "1",
   443  	// then we keep the destroy node no matter what.
   444  	//
   445  	// The reasoning for this is complicated and not intuitively obvious,
   446  	// but I attempt to explain it below.
   447  	//
   448  	// The destroy transform works by generating the worst case graph,
   449  	// with worst case being the case that every resource already exists
   450  	// and needs to be destroy/created (force-new). There is a single important
   451  	// edge case where this actually results in a real-life cycle: if a
   452  	// create-before-destroy (CBD) resource depends on a non-CBD resource.
   453  	// Imagine a EC2 instance "foo" with CBD depending on a security
   454  	// group "bar" without CBD, and conceptualize the worst case destroy
   455  	// order:
   456  	//
   457  	//   1.) SG must be destroyed (non-CBD)
   458  	//   2.) SG must be created/updated
   459  	//   3.) EC2 instance must be created (CBD, requires the SG be made)
   460  	//   4.) EC2 instance must be destroyed (requires SG be destroyed)
   461  	//
   462  	// Except, #1 depends on #4, since the SG can't be destroyed while
   463  	// an EC2 instance is using it (AWS API requirements). As you can see,
   464  	// this is a real life cycle that can't be automatically reconciled
   465  	// except under two conditions:
   466  	//
   467  	//   1.) SG is also CBD. This doesn't work 100% of the time though
   468  	//       since the non-CBD resource might not support CBD. To make matters
   469  	//       worse, the entire transitive closure of dependencies must be
   470  	//       CBD (if the SG depends on a VPC, you have the same problem).
   471  	//   2.) EC2 must not CBD. This can't happen automatically because CBD
   472  	//       is used as a way to ensure zero (or minimal) downtime Terraform
   473  	//       applies, and it isn't acceptable for TF to ignore this request,
   474  	//       since it can result in unexpected downtime.
   475  	//
   476  	// Therefore, we compromise with this edge case here: if there is
   477  	// a static count of "1", we prune the diff to remove cycles during a
   478  	// graph optimization path if we don't see the resource in the diff.
   479  	// If the count is set to ANYTHING other than a static "1" (variable,
   480  	// computed attribute, static number greater than 1), then we keep the
   481  	// destroy, since it is required for dynamic graph expansion to find
   482  	// orphan/tainted count objects.
   483  	//
   484  	// This isn't ideal logic, but its strictly better without introducing
   485  	// new impossibilities. It breaks the cycle in practical cases, and the
   486  	// cycle comes back in no cases we've found to be practical, but just
   487  	// as the cycle would already exist without this anyways.
   488  	count := n.Original.Resource.RawCount
   489  	if raw := count.Raw[count.Key]; raw != "1" {
   490  		return true
   491  	}
   492  
   493  	// Okay, we're dealing with a static count. There are a few ways
   494  	// to include this resource.
   495  	prefix := n.Original.Resource.Id()
   496  
   497  	// If we're present in the diff proper, then keep it. We're looking
   498  	// only for resources in the diff that match our resource or a count-index
   499  	// of our resource that are marked for destroy.
   500  	if d != nil {
   501  		for k, d := range d.Resources {
   502  			match := k == prefix || strings.HasPrefix(k, prefix+".")
   503  			if match && d.Destroy {
   504  				return true
   505  			}
   506  		}
   507  	}
   508  
   509  	// If we're in the state as a primary in any form, then keep it.
   510  	// This does a prefix check so it will also catch orphans on count
   511  	// decreases to "1".
   512  	if s != nil {
   513  		for k, v := range s.Resources {
   514  			// Ignore exact matches
   515  			if k == prefix {
   516  				continue
   517  			}
   518  
   519  			// Ignore anything that doesn't have a "." afterwards so that
   520  			// we only get our own resource and any counts on it.
   521  			if !strings.HasPrefix(k, prefix+".") {
   522  				continue
   523  			}
   524  
   525  			// Ignore exact matches and the 0'th index. We only care
   526  			// about if there is a decrease in count.
   527  			if k == prefix+".0" {
   528  				continue
   529  			}
   530  
   531  			if v.Primary != nil {
   532  				return true
   533  			}
   534  		}
   535  
   536  		// If we're in the state as _both_ "foo" and "foo.0", then
   537  		// keep it, since we treat the latter as an orphan.
   538  		_, okOne := s.Resources[prefix]
   539  		_, okTwo := s.Resources[prefix+".0"]
   540  		if okOne && okTwo {
   541  			return true
   542  		}
   543  	}
   544  
   545  	return false
   546  }