github.com/rhenning/terraform@v0.8.0-beta2/terraform/graph_config_node_resource.go (about)

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