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