github.com/ggriffiths/terraform@v0.9.0-beta1.0.20170222213024-79c4935604cb/terraform/context.go (about)

     1  package terraform
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  	"sort"
     8  	"strings"
     9  	"sync"
    10  
    11  	"github.com/hashicorp/go-multierror"
    12  	"github.com/hashicorp/hcl"
    13  	"github.com/hashicorp/terraform/config"
    14  	"github.com/hashicorp/terraform/config/module"
    15  	"github.com/hashicorp/terraform/helper/experiment"
    16  )
    17  
    18  // InputMode defines what sort of input will be asked for when Input
    19  // is called on Context.
    20  type InputMode byte
    21  
    22  const (
    23  	// InputModeVar asks for all variables
    24  	InputModeVar InputMode = 1 << iota
    25  
    26  	// InputModeVarUnset asks for variables which are not set yet.
    27  	// InputModeVar must be set for this to have an effect.
    28  	InputModeVarUnset
    29  
    30  	// InputModeProvider asks for provider variables
    31  	InputModeProvider
    32  
    33  	// InputModeStd is the standard operating mode and asks for both variables
    34  	// and providers.
    35  	InputModeStd = InputModeVar | InputModeProvider
    36  )
    37  
    38  var (
    39  	// contextFailOnShadowError will cause Context operations to return
    40  	// errors when shadow operations fail. This is only used for testing.
    41  	contextFailOnShadowError = false
    42  
    43  	// contextTestDeepCopyOnPlan will perform a Diff DeepCopy on every
    44  	// Plan operation, effectively testing the Diff DeepCopy whenever
    45  	// a Plan occurs. This is enabled for tests.
    46  	contextTestDeepCopyOnPlan = false
    47  )
    48  
    49  // ContextOpts are the user-configurable options to create a context with
    50  // NewContext.
    51  type ContextOpts struct {
    52  	Destroy            bool
    53  	Diff               *Diff
    54  	Hooks              []Hook
    55  	Module             *module.Tree
    56  	Parallelism        int
    57  	State              *State
    58  	StateFutureAllowed bool
    59  	Providers          map[string]ResourceProviderFactory
    60  	Provisioners       map[string]ResourceProvisionerFactory
    61  	Shadow             bool
    62  	Targets            []string
    63  	Variables          map[string]interface{}
    64  
    65  	UIInput UIInput
    66  }
    67  
    68  // Context represents all the context that Terraform needs in order to
    69  // perform operations on infrastructure. This structure is built using
    70  // NewContext. See the documentation for that.
    71  //
    72  // Extra functions on Context can be found in context_*.go files.
    73  type Context struct {
    74  	// Maintainer note: Anytime this struct is changed, please verify
    75  	// that newShadowContext still does the right thing. Tests should
    76  	// fail regardless but putting this note here as well.
    77  
    78  	components contextComponentFactory
    79  	destroy    bool
    80  	diff       *Diff
    81  	diffLock   sync.RWMutex
    82  	hooks      []Hook
    83  	module     *module.Tree
    84  	sh         *stopHook
    85  	shadow     bool
    86  	state      *State
    87  	stateLock  sync.RWMutex
    88  	targets    []string
    89  	uiInput    UIInput
    90  	variables  map[string]interface{}
    91  
    92  	l                   sync.Mutex // Lock acquired during any task
    93  	parallelSem         Semaphore
    94  	providerInputConfig map[string]map[string]interface{}
    95  	runLock             sync.Mutex
    96  	runCond             *sync.Cond
    97  	runContext          context.Context
    98  	runContextCancel    context.CancelFunc
    99  	shadowErr           error
   100  }
   101  
   102  // NewContext creates a new Context structure.
   103  //
   104  // Once a Context is creator, the pointer values within ContextOpts
   105  // should not be mutated in any way, since the pointers are copied, not
   106  // the values themselves.
   107  func NewContext(opts *ContextOpts) (*Context, error) {
   108  	// Validate the version requirement if it is given
   109  	if opts.Module != nil {
   110  		if err := checkRequiredVersion(opts.Module); err != nil {
   111  			return nil, err
   112  		}
   113  	}
   114  
   115  	// Copy all the hooks and add our stop hook. We don't append directly
   116  	// to the Config so that we're not modifying that in-place.
   117  	sh := new(stopHook)
   118  	hooks := make([]Hook, len(opts.Hooks)+1)
   119  	copy(hooks, opts.Hooks)
   120  	hooks[len(opts.Hooks)] = sh
   121  
   122  	state := opts.State
   123  	if state == nil {
   124  		state = new(State)
   125  		state.init()
   126  	}
   127  
   128  	// If our state is from the future, then error. Callers can avoid
   129  	// this error by explicitly setting `StateFutureAllowed`.
   130  	if !opts.StateFutureAllowed && state.FromFutureTerraform() {
   131  		return nil, fmt.Errorf(
   132  			"Terraform doesn't allow running any operations against a state\n"+
   133  				"that was written by a future Terraform version. The state is\n"+
   134  				"reporting it is written by Terraform '%s'.\n\n"+
   135  				"Please run at least that version of Terraform to continue.",
   136  			state.TFVersion)
   137  	}
   138  
   139  	// Explicitly reset our state version to our current version so that
   140  	// any operations we do will write out that our latest version
   141  	// has run.
   142  	state.TFVersion = Version
   143  
   144  	// Determine parallelism, default to 10. We do this both to limit
   145  	// CPU pressure but also to have an extra guard against rate throttling
   146  	// from providers.
   147  	par := opts.Parallelism
   148  	if par == 0 {
   149  		par = 10
   150  	}
   151  
   152  	// Set up the variables in the following sequence:
   153  	//    0 - Take default values from the configuration
   154  	//    1 - Take values from TF_VAR_x environment variables
   155  	//    2 - Take values specified in -var flags, overriding values
   156  	//        set by environment variables if necessary. This includes
   157  	//        values taken from -var-file in addition.
   158  	variables := make(map[string]interface{})
   159  
   160  	if opts.Module != nil {
   161  		var err error
   162  		variables, err = Variables(opts.Module, opts.Variables)
   163  		if err != nil {
   164  			return nil, err
   165  		}
   166  	}
   167  
   168  	diff := opts.Diff
   169  	if diff == nil {
   170  		diff = &Diff{}
   171  	}
   172  
   173  	return &Context{
   174  		components: &basicComponentFactory{
   175  			providers:    opts.Providers,
   176  			provisioners: opts.Provisioners,
   177  		},
   178  		destroy:   opts.Destroy,
   179  		diff:      diff,
   180  		hooks:     hooks,
   181  		module:    opts.Module,
   182  		shadow:    opts.Shadow,
   183  		state:     state,
   184  		targets:   opts.Targets,
   185  		uiInput:   opts.UIInput,
   186  		variables: variables,
   187  
   188  		parallelSem:         NewSemaphore(par),
   189  		providerInputConfig: make(map[string]map[string]interface{}),
   190  		sh:                  sh,
   191  	}, nil
   192  }
   193  
   194  type ContextGraphOpts struct {
   195  	// If true, validates the graph structure (checks for cycles).
   196  	Validate bool
   197  
   198  	// Legacy graphs only: won't prune the graph
   199  	Verbose bool
   200  }
   201  
   202  // Graph returns the graph used for the given operation type.
   203  //
   204  // The most extensive or complex graph type is GraphTypePlan.
   205  func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, error) {
   206  	if opts == nil {
   207  		opts = &ContextGraphOpts{Validate: true}
   208  	}
   209  
   210  	switch typ {
   211  	case GraphTypeApply:
   212  		return (&ApplyGraphBuilder{
   213  			Module:       c.module,
   214  			Diff:         c.diff,
   215  			State:        c.state,
   216  			Providers:    c.components.ResourceProviders(),
   217  			Provisioners: c.components.ResourceProvisioners(),
   218  			Targets:      c.targets,
   219  			Destroy:      c.destroy,
   220  			Validate:     opts.Validate,
   221  		}).Build(RootModulePath)
   222  
   223  	case GraphTypeInput:
   224  		// The input graph is just a slightly modified plan graph
   225  		fallthrough
   226  	case GraphTypeValidate:
   227  		// The validate graph is just a slightly modified plan graph
   228  		fallthrough
   229  	case GraphTypePlan:
   230  		// Create the plan graph builder
   231  		p := &PlanGraphBuilder{
   232  			Module:    c.module,
   233  			State:     c.state,
   234  			Providers: c.components.ResourceProviders(),
   235  			Targets:   c.targets,
   236  			Validate:  opts.Validate,
   237  		}
   238  
   239  		// Some special cases for other graph types shared with plan currently
   240  		var b GraphBuilder = p
   241  		switch typ {
   242  		case GraphTypeInput:
   243  			b = InputGraphBuilder(p)
   244  		case GraphTypeValidate:
   245  			// We need to set the provisioners so those can be validated
   246  			p.Provisioners = c.components.ResourceProvisioners()
   247  
   248  			b = ValidateGraphBuilder(p)
   249  		}
   250  
   251  		return b.Build(RootModulePath)
   252  
   253  	case GraphTypePlanDestroy:
   254  		return (&DestroyPlanGraphBuilder{
   255  			Module:   c.module,
   256  			State:    c.state,
   257  			Targets:  c.targets,
   258  			Validate: opts.Validate,
   259  		}).Build(RootModulePath)
   260  
   261  	case GraphTypeRefresh:
   262  		return (&RefreshGraphBuilder{
   263  			Module:    c.module,
   264  			State:     c.state,
   265  			Providers: c.components.ResourceProviders(),
   266  			Targets:   c.targets,
   267  			Validate:  opts.Validate,
   268  		}).Build(RootModulePath)
   269  	}
   270  
   271  	return nil, fmt.Errorf("unknown graph type: %s", typ)
   272  }
   273  
   274  // ShadowError returns any errors caught during a shadow operation.
   275  //
   276  // A shadow operation is an operation run in parallel to a real operation
   277  // that performs the same tasks using new logic on copied state. The results
   278  // are compared to ensure that the new logic works the same as the old logic.
   279  // The shadow never affects the real operation or return values.
   280  //
   281  // The result of the shadow operation are only available through this function
   282  // call after a real operation is complete.
   283  //
   284  // For API consumers of Context, you can safely ignore this function
   285  // completely if you have no interest in helping report experimental feature
   286  // errors to Terraform maintainers. Otherwise, please call this function
   287  // after every operation and report this to the user.
   288  //
   289  // IMPORTANT: Shadow errors are _never_ critical: they _never_ affect
   290  // the real state or result of a real operation. They are purely informational
   291  // to assist in future Terraform versions being more stable. Please message
   292  // this effectively to the end user.
   293  //
   294  // This must be called only when no other operation is running (refresh,
   295  // plan, etc.). The result can be used in parallel to any other operation
   296  // running.
   297  func (c *Context) ShadowError() error {
   298  	return c.shadowErr
   299  }
   300  
   301  // State returns a copy of the current state associated with this context.
   302  //
   303  // This cannot safely be called in parallel with any other Context function.
   304  func (c *Context) State() *State {
   305  	return c.state.DeepCopy()
   306  }
   307  
   308  // Interpolater returns an Interpolater built on a copy of the state
   309  // that can be used to test interpolation values.
   310  func (c *Context) Interpolater() *Interpolater {
   311  	var varLock sync.Mutex
   312  	var stateLock sync.RWMutex
   313  	return &Interpolater{
   314  		Operation:          walkApply,
   315  		Module:             c.module,
   316  		State:              c.state.DeepCopy(),
   317  		StateLock:          &stateLock,
   318  		VariableValues:     c.variables,
   319  		VariableValuesLock: &varLock,
   320  	}
   321  }
   322  
   323  // Input asks for input to fill variables and provider configurations.
   324  // This modifies the configuration in-place, so asking for Input twice
   325  // may result in different UI output showing different current values.
   326  func (c *Context) Input(mode InputMode) error {
   327  	defer c.acquireRun("input")()
   328  
   329  	if mode&InputModeVar != 0 {
   330  		// Walk the variables first for the root module. We walk them in
   331  		// alphabetical order for UX reasons.
   332  		rootConf := c.module.Config()
   333  		names := make([]string, len(rootConf.Variables))
   334  		m := make(map[string]*config.Variable)
   335  		for i, v := range rootConf.Variables {
   336  			names[i] = v.Name
   337  			m[v.Name] = v
   338  		}
   339  		sort.Strings(names)
   340  		for _, n := range names {
   341  			// If we only care about unset variables, then if the variable
   342  			// is set, continue on.
   343  			if mode&InputModeVarUnset != 0 {
   344  				if _, ok := c.variables[n]; ok {
   345  					continue
   346  				}
   347  			}
   348  
   349  			var valueType config.VariableType
   350  
   351  			v := m[n]
   352  			switch valueType = v.Type(); valueType {
   353  			case config.VariableTypeUnknown:
   354  				continue
   355  			case config.VariableTypeMap:
   356  				// OK
   357  			case config.VariableTypeList:
   358  				// OK
   359  			case config.VariableTypeString:
   360  				// OK
   361  			default:
   362  				panic(fmt.Sprintf("Unknown variable type: %#v", v.Type()))
   363  			}
   364  
   365  			// If the variable is not already set, and the variable defines a
   366  			// default, use that for the value.
   367  			if _, ok := c.variables[n]; !ok {
   368  				if v.Default != nil {
   369  					c.variables[n] = v.Default.(string)
   370  					continue
   371  				}
   372  			}
   373  
   374  			// this should only happen during tests
   375  			if c.uiInput == nil {
   376  				log.Println("[WARN] Content.uiInput is nil")
   377  				continue
   378  			}
   379  
   380  			// Ask the user for a value for this variable
   381  			var value string
   382  			retry := 0
   383  			for {
   384  				var err error
   385  				value, err = c.uiInput.Input(&InputOpts{
   386  					Id:          fmt.Sprintf("var.%s", n),
   387  					Query:       fmt.Sprintf("var.%s", n),
   388  					Description: v.Description,
   389  				})
   390  				if err != nil {
   391  					return fmt.Errorf(
   392  						"Error asking for %s: %s", n, err)
   393  				}
   394  
   395  				if value == "" && v.Required() {
   396  					// Redo if it is required, but abort if we keep getting
   397  					// blank entries
   398  					if retry > 2 {
   399  						return fmt.Errorf("missing required value for %q", n)
   400  					}
   401  					retry++
   402  					continue
   403  				}
   404  
   405  				break
   406  			}
   407  
   408  			// no value provided, so don't set the variable at all
   409  			if value == "" {
   410  				continue
   411  			}
   412  
   413  			decoded, err := parseVariableAsHCL(n, value, valueType)
   414  			if err != nil {
   415  				return err
   416  			}
   417  
   418  			if decoded != nil {
   419  				c.variables[n] = decoded
   420  			}
   421  		}
   422  	}
   423  
   424  	if mode&InputModeProvider != 0 {
   425  		// Build the graph
   426  		graph, err := c.Graph(GraphTypeInput, nil)
   427  		if err != nil {
   428  			return err
   429  		}
   430  
   431  		// Do the walk
   432  		if _, err := c.walk(graph, nil, walkInput); err != nil {
   433  			return err
   434  		}
   435  	}
   436  
   437  	return nil
   438  }
   439  
   440  // Apply applies the changes represented by this context and returns
   441  // the resulting state.
   442  //
   443  // In addition to returning the resulting state, this context is updated
   444  // with the latest state.
   445  func (c *Context) Apply() (*State, error) {
   446  	defer c.acquireRun("apply")()
   447  
   448  	// Copy our own state
   449  	c.state = c.state.DeepCopy()
   450  
   451  	// Build the graph.
   452  	graph, err := c.Graph(GraphTypeApply, nil)
   453  	if err != nil {
   454  		return nil, err
   455  	}
   456  
   457  	// Determine the operation
   458  	operation := walkApply
   459  	if c.destroy {
   460  		operation = walkDestroy
   461  	}
   462  
   463  	// Walk the graph
   464  	walker, err := c.walk(graph, graph, operation)
   465  	if len(walker.ValidationErrors) > 0 {
   466  		err = multierror.Append(err, walker.ValidationErrors...)
   467  	}
   468  
   469  	// Clean out any unused things
   470  	c.state.prune()
   471  
   472  	return c.state, err
   473  }
   474  
   475  // Plan generates an execution plan for the given context.
   476  //
   477  // The execution plan encapsulates the context and can be stored
   478  // in order to reinstantiate a context later for Apply.
   479  //
   480  // Plan also updates the diff of this context to be the diff generated
   481  // by the plan, so Apply can be called after.
   482  func (c *Context) Plan() (*Plan, error) {
   483  	defer c.acquireRun("plan")()
   484  
   485  	p := &Plan{
   486  		Module:  c.module,
   487  		Vars:    c.variables,
   488  		State:   c.state,
   489  		Targets: c.targets,
   490  	}
   491  
   492  	var operation walkOperation
   493  	if c.destroy {
   494  		operation = walkPlanDestroy
   495  	} else {
   496  		// Set our state to be something temporary. We do this so that
   497  		// the plan can update a fake state so that variables work, then
   498  		// we replace it back with our old state.
   499  		old := c.state
   500  		if old == nil {
   501  			c.state = &State{}
   502  			c.state.init()
   503  		} else {
   504  			c.state = old.DeepCopy()
   505  		}
   506  		defer func() {
   507  			c.state = old
   508  		}()
   509  
   510  		operation = walkPlan
   511  	}
   512  
   513  	// Setup our diff
   514  	c.diffLock.Lock()
   515  	c.diff = new(Diff)
   516  	c.diff.init()
   517  	c.diffLock.Unlock()
   518  
   519  	// Build the graph.
   520  	graphType := GraphTypePlan
   521  	if c.destroy {
   522  		graphType = GraphTypePlanDestroy
   523  	}
   524  	graph, err := c.Graph(graphType, nil)
   525  	if err != nil {
   526  		return nil, err
   527  	}
   528  
   529  	// Do the walk
   530  	walker, err := c.walk(graph, graph, operation)
   531  	if err != nil {
   532  		return nil, err
   533  	}
   534  	p.Diff = c.diff
   535  
   536  	// If this is true, it means we're running unit tests. In this case,
   537  	// we perform a deep copy just to ensure that all context tests also
   538  	// test that a diff is copy-able. This will panic if it fails. This
   539  	// is enabled during unit tests.
   540  	//
   541  	// This should never be true during production usage, but even if it is,
   542  	// it can't do any real harm.
   543  	if contextTestDeepCopyOnPlan {
   544  		p.Diff.DeepCopy()
   545  	}
   546  
   547  	/*
   548  		// We don't do the reverification during the new destroy plan because
   549  		// it will use a different apply process.
   550  		if X_legacyGraph {
   551  			// Now that we have a diff, we can build the exact graph that Apply will use
   552  			// and catch any possible cycles during the Plan phase.
   553  			if _, err := c.Graph(GraphTypeLegacy, nil); err != nil {
   554  				return nil, err
   555  			}
   556  		}
   557  	*/
   558  
   559  	var errs error
   560  	if len(walker.ValidationErrors) > 0 {
   561  		errs = multierror.Append(errs, walker.ValidationErrors...)
   562  	}
   563  	return p, errs
   564  }
   565  
   566  // Refresh goes through all the resources in the state and refreshes them
   567  // to their latest state. This will update the state that this context
   568  // works with, along with returning it.
   569  //
   570  // Even in the case an error is returned, the state will be returned and
   571  // will potentially be partially updated.
   572  func (c *Context) Refresh() (*State, error) {
   573  	defer c.acquireRun("refresh")()
   574  
   575  	// Copy our own state
   576  	c.state = c.state.DeepCopy()
   577  
   578  	// Build the graph.
   579  	graph, err := c.Graph(GraphTypeRefresh, nil)
   580  	if err != nil {
   581  		return nil, err
   582  	}
   583  
   584  	// Do the walk
   585  	if _, err := c.walk(graph, graph, walkRefresh); err != nil {
   586  		return nil, err
   587  	}
   588  
   589  	// Clean out any unused things
   590  	c.state.prune()
   591  
   592  	return c.state, nil
   593  }
   594  
   595  // Stop stops the running task.
   596  //
   597  // Stop will block until the task completes.
   598  func (c *Context) Stop() {
   599  	log.Printf("[WARN] terraform: Stop called, initiating interrupt sequence")
   600  
   601  	c.l.Lock()
   602  	defer c.l.Unlock()
   603  
   604  	// If we're running, then stop
   605  	if c.runContextCancel != nil {
   606  		log.Printf("[WARN] terraform: run context exists, stopping")
   607  
   608  		// Tell the hook we want to stop
   609  		c.sh.Stop()
   610  
   611  		// Stop the context
   612  		c.runContextCancel()
   613  		c.runContextCancel = nil
   614  	}
   615  
   616  	// Grab the condition var before we exit
   617  	if cond := c.runCond; cond != nil {
   618  		cond.Wait()
   619  	}
   620  
   621  	log.Printf("[WARN] terraform: stop complete")
   622  }
   623  
   624  // Validate validates the configuration and returns any warnings or errors.
   625  func (c *Context) Validate() ([]string, []error) {
   626  	defer c.acquireRun("validate")()
   627  
   628  	var errs error
   629  
   630  	// Validate the configuration itself
   631  	if err := c.module.Validate(); err != nil {
   632  		errs = multierror.Append(errs, err)
   633  	}
   634  
   635  	// This only needs to be done for the root module, since inter-module
   636  	// variables are validated in the module tree.
   637  	if config := c.module.Config(); config != nil {
   638  		// Validate the user variables
   639  		if err := smcUserVariables(config, c.variables); len(err) > 0 {
   640  			errs = multierror.Append(errs, err...)
   641  		}
   642  	}
   643  
   644  	// If we have errors at this point, the graphing has no chance,
   645  	// so just bail early.
   646  	if errs != nil {
   647  		return nil, []error{errs}
   648  	}
   649  
   650  	// Build the graph so we can walk it and run Validate on nodes.
   651  	// We also validate the graph generated here, but this graph doesn't
   652  	// necessarily match the graph that Plan will generate, so we'll validate the
   653  	// graph again later after Planning.
   654  	graph, err := c.Graph(GraphTypeValidate, nil)
   655  	if err != nil {
   656  		return nil, []error{err}
   657  	}
   658  
   659  	// Walk
   660  	walker, err := c.walk(graph, graph, walkValidate)
   661  	if err != nil {
   662  		return nil, multierror.Append(errs, err).Errors
   663  	}
   664  
   665  	// Return the result
   666  	rerrs := multierror.Append(errs, walker.ValidationErrors...)
   667  	return walker.ValidationWarnings, rerrs.Errors
   668  }
   669  
   670  // Module returns the module tree associated with this context.
   671  func (c *Context) Module() *module.Tree {
   672  	return c.module
   673  }
   674  
   675  // Variables will return the mapping of variables that were defined
   676  // for this Context. If Input was called, this mapping may be different
   677  // than what was given.
   678  func (c *Context) Variables() map[string]interface{} {
   679  	return c.variables
   680  }
   681  
   682  // SetVariable sets a variable after a context has already been built.
   683  func (c *Context) SetVariable(k string, v interface{}) {
   684  	c.variables[k] = v
   685  }
   686  
   687  func (c *Context) acquireRun(phase string) func() {
   688  	// With the run lock held, grab the context lock to make changes
   689  	// to the run context.
   690  	c.l.Lock()
   691  	defer c.l.Unlock()
   692  
   693  	// Wait until we're no longer running
   694  	for c.runCond != nil {
   695  		c.runCond.Wait()
   696  	}
   697  
   698  	// Build our lock
   699  	c.runCond = sync.NewCond(&c.l)
   700  
   701  	// Setup debugging
   702  	dbug.SetPhase(phase)
   703  
   704  	// Create a new run context
   705  	c.runContext, c.runContextCancel = context.WithCancel(context.Background())
   706  
   707  	// Reset the stop hook so we're not stopped
   708  	c.sh.Reset()
   709  
   710  	// Reset the shadow errors
   711  	c.shadowErr = nil
   712  
   713  	return c.releaseRun
   714  }
   715  
   716  func (c *Context) releaseRun() {
   717  	// Grab the context lock so that we can make modifications to fields
   718  	c.l.Lock()
   719  	defer c.l.Unlock()
   720  
   721  	// setting the phase to "INVALID" lets us easily detect if we have
   722  	// operations happening outside of a run, or we missed setting the proper
   723  	// phase
   724  	dbug.SetPhase("INVALID")
   725  
   726  	// End our run. We check if runContext is non-nil because it can be
   727  	// set to nil if it was cancelled via Stop()
   728  	if c.runContextCancel != nil {
   729  		c.runContextCancel()
   730  	}
   731  
   732  	// Unlock all waiting our condition
   733  	cond := c.runCond
   734  	c.runCond = nil
   735  	cond.Broadcast()
   736  
   737  	// Unset the context
   738  	c.runContext = nil
   739  }
   740  
   741  func (c *Context) walk(
   742  	graph, shadow *Graph, operation walkOperation) (*ContextGraphWalker, error) {
   743  	// Keep track of the "real" context which is the context that does
   744  	// the real work: talking to real providers, modifying real state, etc.
   745  	realCtx := c
   746  
   747  	// If we don't want shadowing, remove it
   748  	if !experiment.Enabled(experiment.X_shadow) {
   749  		shadow = nil
   750  	}
   751  
   752  	// Just log this so we can see it in a debug log
   753  	if !c.shadow {
   754  		log.Printf("[WARN] terraform: shadow graph disabled")
   755  		shadow = nil
   756  	}
   757  
   758  	// If we have a shadow graph, walk that as well
   759  	var shadowCtx *Context
   760  	var shadowCloser Shadow
   761  	if shadow != nil {
   762  		// Build the shadow context. In the process, override the real context
   763  		// with the one that is wrapped so that the shadow context can verify
   764  		// the results of the real.
   765  		realCtx, shadowCtx, shadowCloser = newShadowContext(c)
   766  	}
   767  
   768  	log.Printf("[DEBUG] Starting graph walk: %s", operation.String())
   769  
   770  	walker := &ContextGraphWalker{
   771  		Context:     realCtx,
   772  		Operation:   operation,
   773  		StopContext: c.runContext,
   774  	}
   775  
   776  	// Watch for a stop so we can call the provider Stop() API.
   777  	doneCh := make(chan struct{})
   778  	stopCh := c.runContext.Done()
   779  	go c.watchStop(walker, doneCh, stopCh)
   780  
   781  	// Walk the real graph, this will block until it completes
   782  	realErr := graph.Walk(walker)
   783  
   784  	// Close the done channel so the watcher stops
   785  	close(doneCh)
   786  
   787  	// If we have a shadow graph and we interrupted the real graph, then
   788  	// we just close the shadow and never verify it. It is non-trivial to
   789  	// recreate the exact execution state up until an interruption so this
   790  	// isn't supported with shadows at the moment.
   791  	if shadowCloser != nil && c.sh.Stopped() {
   792  		// Ignore the error result, there is nothing we could care about
   793  		shadowCloser.CloseShadow()
   794  
   795  		// Set it to nil so we don't do anything
   796  		shadowCloser = nil
   797  	}
   798  
   799  	// If we have a shadow graph, wait for that to complete.
   800  	if shadowCloser != nil {
   801  		// Build the graph walker for the shadow. We also wrap this in
   802  		// a panicwrap so that panics are captured. For the shadow graph,
   803  		// we just want panics to be normal errors rather than to crash
   804  		// Terraform.
   805  		shadowWalker := GraphWalkerPanicwrap(&ContextGraphWalker{
   806  			Context:   shadowCtx,
   807  			Operation: operation,
   808  		})
   809  
   810  		// Kick off the shadow walk. This will block on any operations
   811  		// on the real walk so it is fine to start first.
   812  		log.Printf("[INFO] Starting shadow graph walk: %s", operation.String())
   813  		shadowCh := make(chan error)
   814  		go func() {
   815  			shadowCh <- shadow.Walk(shadowWalker)
   816  		}()
   817  
   818  		// Notify the shadow that we're done
   819  		if err := shadowCloser.CloseShadow(); err != nil {
   820  			c.shadowErr = multierror.Append(c.shadowErr, err)
   821  		}
   822  
   823  		// Wait for the walk to end
   824  		log.Printf("[DEBUG] Waiting for shadow graph to complete...")
   825  		shadowWalkErr := <-shadowCh
   826  
   827  		// Get any shadow errors
   828  		if err := shadowCloser.ShadowError(); err != nil {
   829  			c.shadowErr = multierror.Append(c.shadowErr, err)
   830  		}
   831  
   832  		// Verify the contexts (compare)
   833  		if err := shadowContextVerify(realCtx, shadowCtx); err != nil {
   834  			c.shadowErr = multierror.Append(c.shadowErr, err)
   835  		}
   836  
   837  		// At this point, if we're supposed to fail on error, then
   838  		// we PANIC. Some tests just verify that there is an error,
   839  		// so simply appending it to realErr and returning could hide
   840  		// shadow problems.
   841  		//
   842  		// This must be done BEFORE appending shadowWalkErr since the
   843  		// shadowWalkErr may include expected errors.
   844  		//
   845  		// We only do this if we don't have a real error. In the case of
   846  		// a real error, we can't guarantee what nodes were and weren't
   847  		// traversed in parallel scenarios so we can't guarantee no
   848  		// shadow errors.
   849  		if c.shadowErr != nil && contextFailOnShadowError && realErr == nil {
   850  			panic(multierror.Prefix(c.shadowErr, "shadow graph:"))
   851  		}
   852  
   853  		// Now, if we have a walk error, we append that through
   854  		if shadowWalkErr != nil {
   855  			c.shadowErr = multierror.Append(c.shadowErr, shadowWalkErr)
   856  		}
   857  
   858  		if c.shadowErr == nil {
   859  			log.Printf("[INFO] Shadow graph success!")
   860  		} else {
   861  			log.Printf("[ERROR] Shadow graph error: %s", c.shadowErr)
   862  
   863  			// If we're supposed to fail on shadow errors, then report it
   864  			if contextFailOnShadowError {
   865  				realErr = multierror.Append(realErr, multierror.Prefix(
   866  					c.shadowErr, "shadow graph:"))
   867  			}
   868  		}
   869  	}
   870  
   871  	return walker, realErr
   872  }
   873  
   874  func (c *Context) watchStop(walker *ContextGraphWalker, doneCh, stopCh <-chan struct{}) {
   875  	// Wait for a stop or completion
   876  	select {
   877  	case <-stopCh:
   878  		// Stop was triggered. Fall out of the select
   879  	case <-doneCh:
   880  		// Done, just exit completely
   881  		return
   882  	}
   883  
   884  	// If we're here, we're stopped, trigger the call.
   885  
   886  	{
   887  		// Copy the providers so that a misbehaved blocking Stop doesn't
   888  		// completely hang Terraform.
   889  		walker.providerLock.Lock()
   890  		ps := make([]ResourceProvider, 0, len(walker.providerCache))
   891  		for _, p := range walker.providerCache {
   892  			ps = append(ps, p)
   893  		}
   894  		defer walker.providerLock.Unlock()
   895  
   896  		for _, p := range ps {
   897  			// We ignore the error for now since there isn't any reasonable
   898  			// action to take if there is an error here, since the stop is still
   899  			// advisory: Terraform will exit once the graph node completes.
   900  			p.Stop()
   901  		}
   902  	}
   903  
   904  	{
   905  		// Call stop on all the provisioners
   906  		walker.provisionerLock.Lock()
   907  		ps := make([]ResourceProvisioner, 0, len(walker.provisionerCache))
   908  		for _, p := range walker.provisionerCache {
   909  			ps = append(ps, p)
   910  		}
   911  		defer walker.provisionerLock.Unlock()
   912  
   913  		for _, p := range ps {
   914  			// We ignore the error for now since there isn't any reasonable
   915  			// action to take if there is an error here, since the stop is still
   916  			// advisory: Terraform will exit once the graph node completes.
   917  			p.Stop()
   918  		}
   919  	}
   920  }
   921  
   922  // parseVariableAsHCL parses the value of a single variable as would have been specified
   923  // on the command line via -var or in an environment variable named TF_VAR_x, where x is
   924  // the name of the variable. In order to get around the restriction of HCL requiring a
   925  // top level object, we prepend a sentinel key, decode the user-specified value as its
   926  // value and pull the value back out of the resulting map.
   927  func parseVariableAsHCL(name string, input string, targetType config.VariableType) (interface{}, error) {
   928  	// expecting a string so don't decode anything, just strip quotes
   929  	if targetType == config.VariableTypeString {
   930  		return strings.Trim(input, `"`), nil
   931  	}
   932  
   933  	// return empty types
   934  	if strings.TrimSpace(input) == "" {
   935  		switch targetType {
   936  		case config.VariableTypeList:
   937  			return []interface{}{}, nil
   938  		case config.VariableTypeMap:
   939  			return make(map[string]interface{}), nil
   940  		}
   941  	}
   942  
   943  	const sentinelValue = "SENTINEL_TERRAFORM_VAR_OVERRIDE_KEY"
   944  	inputWithSentinal := fmt.Sprintf("%s = %s", sentinelValue, input)
   945  
   946  	var decoded map[string]interface{}
   947  	err := hcl.Decode(&decoded, inputWithSentinal)
   948  	if err != nil {
   949  		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL: %s", name, input, err)
   950  	}
   951  
   952  	if len(decoded) != 1 {
   953  		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. Only one value may be specified.", name, input)
   954  	}
   955  
   956  	parsedValue, ok := decoded[sentinelValue]
   957  	if !ok {
   958  		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.", name, input)
   959  	}
   960  
   961  	switch targetType {
   962  	case config.VariableTypeList:
   963  		return parsedValue, nil
   964  	case config.VariableTypeMap:
   965  		if list, ok := parsedValue.([]map[string]interface{}); ok {
   966  			return list[0], nil
   967  		}
   968  
   969  		return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.", name, input)
   970  	default:
   971  		panic(fmt.Errorf("unknown type %s", targetType.Printable()))
   972  	}
   973  }