github.com/scottwinkler/terraform@v0.11.6-0.20180329211809-05143987aea8/helper/schema/resource_diff.go (about)

     1  package schema
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"reflect"
     7  	"strings"
     8  	"sync"
     9  
    10  	"github.com/hashicorp/terraform/terraform"
    11  )
    12  
    13  // newValueWriter is a minor re-implementation of MapFieldWriter to include
    14  // keys that should be marked as computed, to represent the new part of a
    15  // pseudo-diff.
    16  type newValueWriter struct {
    17  	*MapFieldWriter
    18  
    19  	// A list of keys that should be marked as computed.
    20  	computedKeys map[string]bool
    21  
    22  	// A lock to prevent races on writes. The underlying writer will have one as
    23  	// well - this is for computed keys.
    24  	lock sync.Mutex
    25  
    26  	// To be used with init.
    27  	once sync.Once
    28  }
    29  
    30  // init performs any initialization tasks for the newValueWriter.
    31  func (w *newValueWriter) init() {
    32  	if w.computedKeys == nil {
    33  		w.computedKeys = make(map[string]bool)
    34  	}
    35  }
    36  
    37  // WriteField overrides MapValueWriter's WriteField, adding the ability to flag
    38  // the address as computed.
    39  func (w *newValueWriter) WriteField(address []string, value interface{}, computed bool) error {
    40  	// Fail the write if we have a non-nil value and computed is true.
    41  	// NewComputed values should not have a value when written.
    42  	if value != nil && computed {
    43  		return errors.New("Non-nil value with computed set")
    44  	}
    45  
    46  	if err := w.MapFieldWriter.WriteField(address, value); err != nil {
    47  		return err
    48  	}
    49  
    50  	w.once.Do(w.init)
    51  
    52  	w.lock.Lock()
    53  	defer w.lock.Unlock()
    54  	if computed {
    55  		w.computedKeys[strings.Join(address, ".")] = true
    56  	}
    57  	return nil
    58  }
    59  
    60  // ComputedKeysMap returns the underlying computed keys map.
    61  func (w *newValueWriter) ComputedKeysMap() map[string]bool {
    62  	w.once.Do(w.init)
    63  	return w.computedKeys
    64  }
    65  
    66  // newValueReader is a minor re-implementation of MapFieldReader and is the
    67  // read counterpart to MapValueWriter, allowing the read of keys flagged as
    68  // computed to accommodate the diff override logic in ResourceDiff.
    69  type newValueReader struct {
    70  	*MapFieldReader
    71  
    72  	// The list of computed keys from a newValueWriter.
    73  	computedKeys map[string]bool
    74  }
    75  
    76  // ReadField reads the values from the underlying writer, returning the
    77  // computed value if it is found as well.
    78  func (r *newValueReader) ReadField(address []string) (FieldReadResult, error) {
    79  	addrKey := strings.Join(address, ".")
    80  	v, err := r.MapFieldReader.ReadField(address)
    81  	if err != nil {
    82  		return FieldReadResult{}, err
    83  	}
    84  	for computedKey := range r.computedKeys {
    85  		if childAddrOf(addrKey, computedKey) {
    86  			if strings.HasSuffix(addrKey, ".#") {
    87  				// This is a count value for a list or set that has been marked as
    88  				// computed, or a sub-list/sub-set of a complex resource that has
    89  				// been marked as computed.  We need to pass through to other readers
    90  				// so that an accurate previous count can be fetched for the diff.
    91  				v.Exists = false
    92  			}
    93  			v.Computed = true
    94  		}
    95  	}
    96  
    97  	return v, nil
    98  }
    99  
   100  // ResourceDiff is used to query and make custom changes to an in-flight diff.
   101  // It can be used to veto particular changes in the diff, customize the diff
   102  // that has been created, or diff values not controlled by config.
   103  //
   104  // The object functions similar to ResourceData, however most notably lacks
   105  // Set, SetPartial, and Partial, as it should be used to change diff values
   106  // only.  Most other first-class ResourceData functions exist, namely Get,
   107  // GetOk, HasChange, and GetChange exist.
   108  //
   109  // All functions in ResourceDiff, save for ForceNew, can only be used on
   110  // computed fields.
   111  type ResourceDiff struct {
   112  	// The schema for the resource being worked on.
   113  	schema map[string]*Schema
   114  
   115  	// The current config for this resource.
   116  	config *terraform.ResourceConfig
   117  
   118  	// The state for this resource as it exists post-refresh, after the initial
   119  	// diff.
   120  	state *terraform.InstanceState
   121  
   122  	// The diff created by Terraform. This diff is used, along with state,
   123  	// config, and custom-set diff data, to provide a multi-level reader
   124  	// experience similar to ResourceData.
   125  	diff *terraform.InstanceDiff
   126  
   127  	// The internal reader structure that contains the state, config, the default
   128  	// diff, and the new diff.
   129  	multiReader *MultiLevelFieldReader
   130  
   131  	// A writer that writes overridden new fields.
   132  	newWriter *newValueWriter
   133  
   134  	// Tracks which keys have been updated by ResourceDiff to ensure that the
   135  	// diff does not get re-run on keys that were not touched, or diffs that were
   136  	// just removed (re-running on the latter would just roll back the removal).
   137  	updatedKeys map[string]bool
   138  }
   139  
   140  // newResourceDiff creates a new ResourceDiff instance.
   141  func newResourceDiff(schema map[string]*Schema, config *terraform.ResourceConfig, state *terraform.InstanceState, diff *terraform.InstanceDiff) *ResourceDiff {
   142  	d := &ResourceDiff{
   143  		config: config,
   144  		state:  state,
   145  		diff:   diff,
   146  		schema: schema,
   147  	}
   148  
   149  	d.newWriter = &newValueWriter{
   150  		MapFieldWriter: &MapFieldWriter{Schema: d.schema},
   151  	}
   152  	readers := make(map[string]FieldReader)
   153  	var stateAttributes map[string]string
   154  	if d.state != nil {
   155  		stateAttributes = d.state.Attributes
   156  		readers["state"] = &MapFieldReader{
   157  			Schema: d.schema,
   158  			Map:    BasicMapReader(stateAttributes),
   159  		}
   160  	}
   161  	if d.config != nil {
   162  		readers["config"] = &ConfigFieldReader{
   163  			Schema: d.schema,
   164  			Config: d.config,
   165  		}
   166  	}
   167  	if d.diff != nil {
   168  		readers["diff"] = &DiffFieldReader{
   169  			Schema: d.schema,
   170  			Diff:   d.diff,
   171  			Source: &MultiLevelFieldReader{
   172  				Levels:  []string{"state", "config"},
   173  				Readers: readers,
   174  			},
   175  		}
   176  	}
   177  	readers["newDiff"] = &newValueReader{
   178  		MapFieldReader: &MapFieldReader{
   179  			Schema: d.schema,
   180  			Map:    BasicMapReader(d.newWriter.Map()),
   181  		},
   182  		computedKeys: d.newWriter.ComputedKeysMap(),
   183  	}
   184  	d.multiReader = &MultiLevelFieldReader{
   185  		Levels: []string{
   186  			"state",
   187  			"config",
   188  			"diff",
   189  			"newDiff",
   190  		},
   191  
   192  		Readers: readers,
   193  	}
   194  
   195  	d.updatedKeys = make(map[string]bool)
   196  
   197  	return d
   198  }
   199  
   200  // UpdatedKeys returns the keys that were updated by this ResourceDiff run.
   201  // These are the only keys that a diff should be re-calculated for.
   202  func (d *ResourceDiff) UpdatedKeys() []string {
   203  	var s []string
   204  	for k := range d.updatedKeys {
   205  		s = append(s, k)
   206  	}
   207  	return s
   208  }
   209  
   210  // Clear wipes the diff for a particular key. It is called by ResourceDiff's
   211  // functionality to remove any possibility of conflicts, but can be called on
   212  // its own to just remove a specific key from the diff completely.
   213  //
   214  // Note that this does not wipe an override. This function is only allowed on
   215  // computed keys.
   216  func (d *ResourceDiff) Clear(key string) error {
   217  	if err := d.checkKey(key, "Clear"); err != nil {
   218  		return err
   219  	}
   220  
   221  	return d.clear(key)
   222  }
   223  
   224  func (d *ResourceDiff) clear(key string) error {
   225  	// Check the schema to make sure that this key exists first.
   226  	schemaL := addrToSchema(strings.Split(key, "."), d.schema)
   227  	if len(schemaL) == 0 {
   228  		return fmt.Errorf("%s is not a valid key", key)
   229  	}
   230  
   231  	for k := range d.diff.Attributes {
   232  		if strings.HasPrefix(k, key) {
   233  			delete(d.diff.Attributes, k)
   234  		}
   235  	}
   236  	return nil
   237  }
   238  
   239  // GetChangedKeysPrefix helps to implement Resource.CustomizeDiff
   240  // where we need to act on all nested fields
   241  // without calling out each one separately
   242  func (d *ResourceDiff) GetChangedKeysPrefix(prefix string) []string {
   243  	keys := make([]string, 0)
   244  	for k := range d.diff.Attributes {
   245  		if strings.HasPrefix(k, prefix) {
   246  			keys = append(keys, k)
   247  		}
   248  	}
   249  	return keys
   250  }
   251  
   252  // diffChange helps to implement resourceDiffer and derives its change values
   253  // from ResourceDiff's own change data, in addition to existing diff, config, and state.
   254  func (d *ResourceDiff) diffChange(key string) (interface{}, interface{}, bool, bool, bool) {
   255  	old, new, customized := d.getChange(key)
   256  
   257  	if !old.Exists {
   258  		old.Value = nil
   259  	}
   260  	if !new.Exists {
   261  		new.Value = nil
   262  	}
   263  
   264  	return old.Value, new.Value, !reflect.DeepEqual(old.Value, new.Value), new.Computed, customized
   265  }
   266  
   267  // SetNew is used to set a new diff value for the mentioned key. The value must
   268  // be correct for the attribute's schema (mostly relevant for maps, lists, and
   269  // sets). The original value from the state is used as the old value.
   270  //
   271  // This function is only allowed on computed attributes.
   272  func (d *ResourceDiff) SetNew(key string, value interface{}) error {
   273  	if err := d.checkKey(key, "SetNew"); err != nil {
   274  		return err
   275  	}
   276  
   277  	return d.setDiff(key, value, false)
   278  }
   279  
   280  // SetNewComputed functions like SetNew, except that it blanks out a new value
   281  // and marks it as computed.
   282  //
   283  // This function is only allowed on computed attributes.
   284  func (d *ResourceDiff) SetNewComputed(key string) error {
   285  	if err := d.checkKey(key, "SetNewComputed"); err != nil {
   286  		return err
   287  	}
   288  
   289  	return d.setDiff(key, nil, true)
   290  }
   291  
   292  // setDiff performs common diff setting behaviour.
   293  func (d *ResourceDiff) setDiff(key string, new interface{}, computed bool) error {
   294  	if err := d.clear(key); err != nil {
   295  		return err
   296  	}
   297  
   298  	if err := d.newWriter.WriteField(strings.Split(key, "."), new, computed); err != nil {
   299  		return fmt.Errorf("Cannot set new diff value for key %s: %s", key, err)
   300  	}
   301  
   302  	d.updatedKeys[key] = true
   303  
   304  	return nil
   305  }
   306  
   307  // ForceNew force-flags ForceNew in the schema for a specific key, and
   308  // re-calculates its diff, effectively causing this attribute to force a new
   309  // resource.
   310  //
   311  // Keep in mind that forcing a new resource will force a second run of the
   312  // resource's CustomizeDiff function (with a new ResourceDiff) once the current
   313  // one has completed. This second run is performed without state. This behavior
   314  // will be the same as if a new resource is being created and is performed to
   315  // ensure that the diff looks like the diff for a new resource as much as
   316  // possible. CustomizeDiff should expect such a scenario and act correctly.
   317  //
   318  // This function is a no-op/error if there is no diff.
   319  //
   320  // Note that the change to schema is permanent for the lifecycle of this
   321  // specific ResourceDiff instance.
   322  func (d *ResourceDiff) ForceNew(key string) error {
   323  	if !d.HasChange(key) {
   324  		return fmt.Errorf("ForceNew: No changes for %s", key)
   325  	}
   326  
   327  	keyParts := strings.Split(key, ".")
   328  	var schema *Schema
   329  	schemaL := addrToSchema(keyParts, d.schema)
   330  	if len(schemaL) > 0 {
   331  		schema = schemaL[len(schemaL)-1]
   332  	} else {
   333  		return fmt.Errorf("ForceNew: %s is not a valid key", key)
   334  	}
   335  
   336  	schema.ForceNew = true
   337  
   338  	// We need to set whole lists/sets/maps here
   339  	_, new := d.GetChange(keyParts[0])
   340  	return d.setDiff(keyParts[0], new, false)
   341  }
   342  
   343  // Get hands off to ResourceData.Get.
   344  func (d *ResourceDiff) Get(key string) interface{} {
   345  	r, _ := d.GetOk(key)
   346  	return r
   347  }
   348  
   349  // GetChange gets the change between the state and diff, checking first to see
   350  // if a overridden diff exists.
   351  //
   352  // This implementation differs from ResourceData's in the way that we first get
   353  // results from the exact levels for the new diff, then from state and diff as
   354  // per normal.
   355  func (d *ResourceDiff) GetChange(key string) (interface{}, interface{}) {
   356  	old, new, _ := d.getChange(key)
   357  	return old.Value, new.Value
   358  }
   359  
   360  // GetOk functions the same way as ResourceData.GetOk, but it also checks the
   361  // new diff levels to provide data consistent with the current state of the
   362  // customized diff.
   363  func (d *ResourceDiff) GetOk(key string) (interface{}, bool) {
   364  	r := d.get(strings.Split(key, "."), "newDiff")
   365  	exists := r.Exists && !r.Computed
   366  	if exists {
   367  		// If it exists, we also want to verify it is not the zero-value.
   368  		value := r.Value
   369  		zero := r.Schema.Type.Zero()
   370  
   371  		if eq, ok := value.(Equal); ok {
   372  			exists = !eq.Equal(zero)
   373  		} else {
   374  			exists = !reflect.DeepEqual(value, zero)
   375  		}
   376  	}
   377  
   378  	return r.Value, exists
   379  }
   380  
   381  // HasChange checks to see if there is a change between state and the diff, or
   382  // in the overridden diff.
   383  func (d *ResourceDiff) HasChange(key string) bool {
   384  	old, new := d.GetChange(key)
   385  
   386  	// If the type implements the Equal interface, then call that
   387  	// instead of just doing a reflect.DeepEqual. An example where this is
   388  	// needed is *Set
   389  	if eq, ok := old.(Equal); ok {
   390  		return !eq.Equal(new)
   391  	}
   392  
   393  	return !reflect.DeepEqual(old, new)
   394  }
   395  
   396  // Id returns the ID of this resource.
   397  //
   398  // Note that technically, ID does not change during diffs (it either has
   399  // already changed in the refresh, or will change on update), hence we do not
   400  // support updating the ID or fetching it from anything else other than state.
   401  func (d *ResourceDiff) Id() string {
   402  	var result string
   403  
   404  	if d.state != nil {
   405  		result = d.state.ID
   406  	}
   407  	return result
   408  }
   409  
   410  // getChange gets values from two different levels, designed for use in
   411  // diffChange, HasChange, and GetChange.
   412  //
   413  // This implementation differs from ResourceData's in the way that we first get
   414  // results from the exact levels for the new diff, then from state and diff as
   415  // per normal.
   416  func (d *ResourceDiff) getChange(key string) (getResult, getResult, bool) {
   417  	old := d.get(strings.Split(key, "."), "state")
   418  	var new getResult
   419  	for p := range d.updatedKeys {
   420  		if childAddrOf(key, p) {
   421  			new = d.getExact(strings.Split(key, "."), "newDiff")
   422  			return old, new, true
   423  		}
   424  	}
   425  	new = d.get(strings.Split(key, "."), "newDiff")
   426  	return old, new, false
   427  }
   428  
   429  // get performs the appropriate multi-level reader logic for ResourceDiff,
   430  // starting at source. Refer to newResourceDiff for the level order.
   431  func (d *ResourceDiff) get(addr []string, source string) getResult {
   432  	result, err := d.multiReader.ReadFieldMerge(addr, source)
   433  	if err != nil {
   434  		panic(err)
   435  	}
   436  
   437  	return d.finalizeResult(addr, result)
   438  }
   439  
   440  // getExact gets an attribute from the exact level referenced by source.
   441  func (d *ResourceDiff) getExact(addr []string, source string) getResult {
   442  	result, err := d.multiReader.ReadFieldExact(addr, source)
   443  	if err != nil {
   444  		panic(err)
   445  	}
   446  
   447  	return d.finalizeResult(addr, result)
   448  }
   449  
   450  // finalizeResult does some post-processing of the result produced by get and getExact.
   451  func (d *ResourceDiff) finalizeResult(addr []string, result FieldReadResult) getResult {
   452  	// If the result doesn't exist, then we set the value to the zero value
   453  	var schema *Schema
   454  	if schemaL := addrToSchema(addr, d.schema); len(schemaL) > 0 {
   455  		schema = schemaL[len(schemaL)-1]
   456  	}
   457  
   458  	if result.Value == nil && schema != nil {
   459  		result.Value = result.ValueOrZero(schema)
   460  	}
   461  
   462  	// Transform the FieldReadResult into a getResult. It might be worth
   463  	// merging these two structures one day.
   464  	return getResult{
   465  		Value:          result.Value,
   466  		ValueProcessed: result.ValueProcessed,
   467  		Computed:       result.Computed,
   468  		Exists:         result.Exists,
   469  		Schema:         schema,
   470  	}
   471  }
   472  
   473  // childAddrOf does a comparison of two addresses to see if one is the child of
   474  // the other.
   475  func childAddrOf(child, parent string) bool {
   476  	cs := strings.Split(child, ".")
   477  	ps := strings.Split(parent, ".")
   478  	if len(ps) > len(cs) {
   479  		return false
   480  	}
   481  	return reflect.DeepEqual(ps, cs[:len(ps)])
   482  }
   483  
   484  // checkKey checks the key to make sure it exists and is computed.
   485  func (d *ResourceDiff) checkKey(key, caller string) error {
   486  	s, ok := d.schema[key]
   487  	if !ok {
   488  		return fmt.Errorf("%s: invalid key: %s", caller, key)
   489  	}
   490  	if !s.Computed {
   491  		return fmt.Errorf("%s only operates on computed keys - %s is not one", caller, key)
   492  	}
   493  	return nil
   494  }