github.com/hobbeswalsh/terraform@v0.3.7-0.20150619183303-ad17cf55a0fa/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  			Targeting: (len(n.Targets) > 0),
   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  // Same as GraphNodeConfigResource, but for flattening
   253  type GraphNodeConfigResourceFlat struct {
   254  	*GraphNodeConfigResource
   255  
   256  	PathValue []string
   257  }
   258  
   259  func (n *GraphNodeConfigResourceFlat) Name() string {
   260  	return fmt.Sprintf(
   261  		"%s.%s", modulePrefixStr(n.PathValue), n.GraphNodeConfigResource.Name())
   262  }
   263  
   264  func (n *GraphNodeConfigResourceFlat) Path() []string {
   265  	return n.PathValue
   266  }
   267  
   268  func (n *GraphNodeConfigResourceFlat) DependableName() []string {
   269  	return modulePrefixList(
   270  		n.GraphNodeConfigResource.DependableName(),
   271  		modulePrefixStr(n.PathValue))
   272  }
   273  
   274  func (n *GraphNodeConfigResourceFlat) DependentOn() []string {
   275  	prefix := modulePrefixStr(n.PathValue)
   276  	return modulePrefixList(
   277  		n.GraphNodeConfigResource.DependentOn(),
   278  		prefix)
   279  }
   280  
   281  func (n *GraphNodeConfigResourceFlat) ProvidedBy() []string {
   282  	prefix := modulePrefixStr(n.PathValue)
   283  	return modulePrefixList(
   284  		n.GraphNodeConfigResource.ProvidedBy(),
   285  		prefix)
   286  }
   287  
   288  func (n *GraphNodeConfigResourceFlat) ProvisionedBy() []string {
   289  	prefix := modulePrefixStr(n.PathValue)
   290  	return modulePrefixList(
   291  		n.GraphNodeConfigResource.ProvisionedBy(),
   292  		prefix)
   293  }
   294  
   295  // GraphNodeDestroyable impl.
   296  func (n *GraphNodeConfigResourceFlat) DestroyNode(mode GraphNodeDestroyMode) GraphNodeDestroy {
   297  	// Get our parent destroy node. If we don't have any, just return
   298  	raw := n.GraphNodeConfigResource.DestroyNode(mode)
   299  	if raw == nil {
   300  		return nil
   301  	}
   302  
   303  	node, ok := raw.(*graphNodeResourceDestroy)
   304  	if !ok {
   305  		panic(fmt.Sprintf("unknown destroy node: %s %T", dag.VertexName(raw), raw))
   306  	}
   307  
   308  	// Otherwise, wrap it so that it gets the proper module treatment.
   309  	return &graphNodeResourceDestroyFlat{
   310  		graphNodeResourceDestroy: node,
   311  		PathValue:                n.PathValue,
   312  		FlatCreateNode:           n,
   313  	}
   314  }
   315  
   316  type graphNodeResourceDestroyFlat struct {
   317  	*graphNodeResourceDestroy
   318  
   319  	PathValue []string
   320  
   321  	// Needs to be able to properly yield back a flattened create node to prevent
   322  	FlatCreateNode *GraphNodeConfigResourceFlat
   323  }
   324  
   325  func (n *graphNodeResourceDestroyFlat) Name() string {
   326  	return fmt.Sprintf(
   327  		"%s.%s", modulePrefixStr(n.PathValue), n.graphNodeResourceDestroy.Name())
   328  }
   329  
   330  func (n *graphNodeResourceDestroyFlat) Path() []string {
   331  	return n.PathValue
   332  }
   333  
   334  func (n *graphNodeResourceDestroyFlat) CreateNode() dag.Vertex {
   335  	return n.FlatCreateNode
   336  }
   337  
   338  // graphNodeResourceDestroy represents the logical destruction of a
   339  // resource. This node doesn't mean it will be destroyed for sure, but
   340  // instead that if a destroy were to happen, it must happen at this point.
   341  type graphNodeResourceDestroy struct {
   342  	GraphNodeConfigResource
   343  	Original *GraphNodeConfigResource
   344  }
   345  
   346  func (n *graphNodeResourceDestroy) CreateBeforeDestroy() bool {
   347  	// CBD is enabled if the resource enables it in addition to us
   348  	// being responsible for destroying the primary state. The primary
   349  	// state destroy node is the only destroy node that needs to be
   350  	// "shuffled" according to the CBD rules, since tainted resources
   351  	// don't have the same inverse dependencies.
   352  	return n.Original.Resource.Lifecycle.CreateBeforeDestroy &&
   353  		n.DestroyMode == DestroyPrimary
   354  }
   355  
   356  func (n *graphNodeResourceDestroy) CreateNode() dag.Vertex {
   357  	return n.Original
   358  }
   359  
   360  func (n *graphNodeResourceDestroy) DestroyInclude(d *ModuleDiff, s *ModuleState) bool {
   361  	switch n.DestroyMode {
   362  	case DestroyPrimary:
   363  		return n.destroyIncludePrimary(d, s)
   364  	case DestroyTainted:
   365  		return n.destroyIncludeTainted(d, s)
   366  	default:
   367  		return true
   368  	}
   369  }
   370  
   371  func (n *graphNodeResourceDestroy) destroyIncludeTainted(
   372  	d *ModuleDiff, s *ModuleState) bool {
   373  	// If there is no state, there can't by any tainted.
   374  	if s == nil {
   375  		return false
   376  	}
   377  
   378  	// Grab the ID which is the prefix (in the case count > 0 at some point)
   379  	prefix := n.Original.Resource.Id()
   380  
   381  	// Go through the resources and find any with our prefix. If there
   382  	// are any tainted, we need to keep it.
   383  	for k, v := range s.Resources {
   384  		if !strings.HasPrefix(k, prefix) {
   385  			continue
   386  		}
   387  
   388  		if len(v.Tainted) > 0 {
   389  			return true
   390  		}
   391  	}
   392  
   393  	// We didn't find any tainted nodes, return
   394  	return false
   395  }
   396  
   397  func (n *graphNodeResourceDestroy) destroyIncludePrimary(
   398  	d *ModuleDiff, s *ModuleState) bool {
   399  	// Get the count, and specifically the raw value of the count
   400  	// (with interpolations and all). If the count is NOT a static "1",
   401  	// then we keep the destroy node no matter what.
   402  	//
   403  	// The reasoning for this is complicated and not intuitively obvious,
   404  	// but I attempt to explain it below.
   405  	//
   406  	// The destroy transform works by generating the worst case graph,
   407  	// with worst case being the case that every resource already exists
   408  	// and needs to be destroy/created (force-new). There is a single important
   409  	// edge case where this actually results in a real-life cycle: if a
   410  	// create-before-destroy (CBD) resource depends on a non-CBD resource.
   411  	// Imagine a EC2 instance "foo" with CBD depending on a security
   412  	// group "bar" without CBD, and conceptualize the worst case destroy
   413  	// order:
   414  	//
   415  	//   1.) SG must be destroyed (non-CBD)
   416  	//   2.) SG must be created/updated
   417  	//   3.) EC2 instance must be created (CBD, requires the SG be made)
   418  	//   4.) EC2 instance must be destroyed (requires SG be destroyed)
   419  	//
   420  	// Except, #1 depends on #4, since the SG can't be destroyed while
   421  	// an EC2 instance is using it (AWS API requirements). As you can see,
   422  	// this is a real life cycle that can't be automatically reconciled
   423  	// except under two conditions:
   424  	//
   425  	//   1.) SG is also CBD. This doesn't work 100% of the time though
   426  	//       since the non-CBD resource might not support CBD. To make matters
   427  	//       worse, the entire transitive closure of dependencies must be
   428  	//       CBD (if the SG depends on a VPC, you have the same problem).
   429  	//   2.) EC2 must not CBD. This can't happen automatically because CBD
   430  	//       is used as a way to ensure zero (or minimal) downtime Terraform
   431  	//       applies, and it isn't acceptable for TF to ignore this request,
   432  	//       since it can result in unexpected downtime.
   433  	//
   434  	// Therefore, we compromise with this edge case here: if there is
   435  	// a static count of "1", we prune the diff to remove cycles during a
   436  	// graph optimization path if we don't see the resource in the diff.
   437  	// If the count is set to ANYTHING other than a static "1" (variable,
   438  	// computed attribute, static number greater than 1), then we keep the
   439  	// destroy, since it is required for dynamic graph expansion to find
   440  	// orphan/tainted count objects.
   441  	//
   442  	// This isn't ideal logic, but its strictly better without introducing
   443  	// new impossibilities. It breaks the cycle in practical cases, and the
   444  	// cycle comes back in no cases we've found to be practical, but just
   445  	// as the cycle would already exist without this anyways.
   446  	count := n.Original.Resource.RawCount
   447  	if raw := count.Raw[count.Key]; raw != "1" {
   448  		return true
   449  	}
   450  
   451  	// Okay, we're dealing with a static count. There are a few ways
   452  	// to include this resource.
   453  	prefix := n.Original.Resource.Id()
   454  
   455  	// If we're present in the diff proper, then keep it. We're looking
   456  	// only for resources in the diff that match our resource or a count-index
   457  	// of our resource that are marked for destroy.
   458  	if d != nil {
   459  		for k, d := range d.Resources {
   460  			match := k == prefix || strings.HasPrefix(k, prefix+".")
   461  			if match && d.Destroy {
   462  				return true
   463  			}
   464  		}
   465  	}
   466  
   467  	// If we're in the state as a primary in any form, then keep it.
   468  	// This does a prefix check so it will also catch orphans on count
   469  	// decreases to "1".
   470  	if s != nil {
   471  		for k, v := range s.Resources {
   472  			// Ignore exact matches
   473  			if k == prefix {
   474  				continue
   475  			}
   476  
   477  			// Ignore anything that doesn't have a "." afterwards so that
   478  			// we only get our own resource and any counts on it.
   479  			if !strings.HasPrefix(k, prefix+".") {
   480  				continue
   481  			}
   482  
   483  			// Ignore exact matches and the 0'th index. We only care
   484  			// about if there is a decrease in count.
   485  			if k == prefix+".0" {
   486  				continue
   487  			}
   488  
   489  			if v.Primary != nil {
   490  				return true
   491  			}
   492  		}
   493  
   494  		// If we're in the state as _both_ "foo" and "foo.0", then
   495  		// keep it, since we treat the latter as an orphan.
   496  		_, okOne := s.Resources[prefix]
   497  		_, okTwo := s.Resources[prefix+".0"]
   498  		if okOne && okTwo {
   499  			return true
   500  		}
   501  	}
   502  
   503  	return false
   504  }