github.com/ojongerius/terraform@v0.7.1-0.20160811111335-97fcd5f4cc90/config/raw_config.go (about)

     1  package config
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/gob"
     6  	"sync"
     7  
     8  	"github.com/hashicorp/hil"
     9  	"github.com/hashicorp/hil/ast"
    10  	"github.com/mitchellh/copystructure"
    11  	"github.com/mitchellh/reflectwalk"
    12  )
    13  
    14  // UnknownVariableValue is a sentinel value that can be used
    15  // to denote that the value of a variable is unknown at this time.
    16  // RawConfig uses this information to build up data about
    17  // unknown keys.
    18  const UnknownVariableValue = "74D93920-ED26-11E3-AC10-0800200C9A66"
    19  
    20  // RawConfig is a structure that holds a piece of configuration
    21  // where te overall structure is unknown since it will be used
    22  // to configure a plugin or some other similar external component.
    23  //
    24  // RawConfigs can be interpolated with variables that come from
    25  // other resources, user variables, etc.
    26  //
    27  // RawConfig supports a query-like interface to request
    28  // information from deep within the structure.
    29  type RawConfig struct {
    30  	Key            string
    31  	Raw            map[string]interface{}
    32  	Interpolations []ast.Node
    33  	Variables      map[string]InterpolatedVariable
    34  
    35  	lock        sync.Mutex
    36  	config      map[string]interface{}
    37  	unknownKeys []string
    38  }
    39  
    40  // NewRawConfig creates a new RawConfig structure and populates the
    41  // publicly readable struct fields.
    42  func NewRawConfig(raw map[string]interface{}) (*RawConfig, error) {
    43  	result := &RawConfig{Raw: raw}
    44  	if err := result.init(); err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	return result, nil
    49  }
    50  
    51  // Copy returns a copy of this RawConfig, uninterpolated.
    52  func (r *RawConfig) Copy() *RawConfig {
    53  	r.lock.Lock()
    54  	defer r.lock.Unlock()
    55  
    56  	newRaw := make(map[string]interface{})
    57  	for k, v := range r.Raw {
    58  		newRaw[k] = v
    59  	}
    60  
    61  	result, err := NewRawConfig(newRaw)
    62  	if err != nil {
    63  		panic("copy failed: " + err.Error())
    64  	}
    65  
    66  	result.Key = r.Key
    67  	return result
    68  }
    69  
    70  // Value returns the value of the configuration if this configuration
    71  // has a Key set. If this does not have a Key set, nil will be returned.
    72  func (r *RawConfig) Value() interface{} {
    73  	if c := r.Config(); c != nil {
    74  		if v, ok := c[r.Key]; ok {
    75  			return v
    76  		}
    77  	}
    78  
    79  	r.lock.Lock()
    80  	defer r.lock.Unlock()
    81  	return r.Raw[r.Key]
    82  }
    83  
    84  // Config returns the entire configuration with the variables
    85  // interpolated from any call to Interpolate.
    86  //
    87  // If any interpolated variables are unknown (value set to
    88  // UnknownVariableValue), the first non-container (map, slice, etc.) element
    89  // will be removed from the config. The keys of unknown variables
    90  // can be found using the UnknownKeys function.
    91  //
    92  // By pruning out unknown keys from the configuration, the raw
    93  // structure will always successfully decode into its ultimate
    94  // structure using something like mapstructure.
    95  func (r *RawConfig) Config() map[string]interface{} {
    96  	r.lock.Lock()
    97  	defer r.lock.Unlock()
    98  	return r.config
    99  }
   100  
   101  // Interpolate uses the given mapping of variable values and uses
   102  // those as the values to replace any variables in this raw
   103  // configuration.
   104  //
   105  // Any prior calls to Interpolate are replaced with this one.
   106  //
   107  // If a variable key is missing, this will panic.
   108  func (r *RawConfig) Interpolate(vs map[string]ast.Variable) error {
   109  	r.lock.Lock()
   110  	defer r.lock.Unlock()
   111  
   112  	config := langEvalConfig(vs)
   113  	return r.interpolate(func(root ast.Node) (interface{}, error) {
   114  		// We detect the variables again and check if the value of any
   115  		// of the variables is the computed value. If it is, then we
   116  		// treat this entire value as computed.
   117  		//
   118  		// We have to do this here before the `lang.Eval` because
   119  		// if any of the variables it depends on are computed, then
   120  		// the interpolation can fail at runtime for other reasons. Example:
   121  		// `${count.index+1}`: in a world where `count.index` is computed,
   122  		// this would fail a type check since the computed placeholder is
   123  		// a string, but realistically the whole value is just computed.
   124  		vars, err := DetectVariables(root)
   125  		if err != nil {
   126  			return "", err
   127  		}
   128  		for _, v := range vars {
   129  			varVal, ok := vs[v.FullKey()]
   130  			if ok && varVal.Value == UnknownVariableValue {
   131  				return UnknownVariableValue, nil
   132  			}
   133  		}
   134  
   135  		// None of the variables we need are computed, meaning we should
   136  		// be able to properly evaluate.
   137  		result, err := hil.Eval(root, config)
   138  		if err != nil {
   139  			return "", err
   140  		}
   141  
   142  		return result.Value, nil
   143  	})
   144  }
   145  
   146  // Merge merges another RawConfig into this one (overriding any conflicting
   147  // values in this config) and returns a new config. The original config
   148  // is not modified.
   149  func (r *RawConfig) Merge(other *RawConfig) *RawConfig {
   150  	r.lock.Lock()
   151  	defer r.lock.Unlock()
   152  
   153  	// Merge the raw configurations
   154  	raw := make(map[string]interface{})
   155  	for k, v := range r.Raw {
   156  		raw[k] = v
   157  	}
   158  	for k, v := range other.Raw {
   159  		raw[k] = v
   160  	}
   161  
   162  	// Create the result
   163  	result, err := NewRawConfig(raw)
   164  	if err != nil {
   165  		panic(err)
   166  	}
   167  
   168  	// Merge the interpolated results
   169  	result.config = make(map[string]interface{})
   170  	for k, v := range r.config {
   171  		result.config[k] = v
   172  	}
   173  	for k, v := range other.config {
   174  		result.config[k] = v
   175  	}
   176  
   177  	// Build the unknown keys
   178  	unknownKeys := make(map[string]struct{})
   179  	for _, k := range r.unknownKeys {
   180  		unknownKeys[k] = struct{}{}
   181  	}
   182  	for _, k := range other.unknownKeys {
   183  		unknownKeys[k] = struct{}{}
   184  	}
   185  
   186  	result.unknownKeys = make([]string, 0, len(unknownKeys))
   187  	for k, _ := range unknownKeys {
   188  		result.unknownKeys = append(result.unknownKeys, k)
   189  	}
   190  
   191  	return result
   192  }
   193  
   194  func (r *RawConfig) init() error {
   195  	r.config = r.Raw
   196  	r.Interpolations = nil
   197  	r.Variables = nil
   198  
   199  	fn := func(node ast.Node) (interface{}, error) {
   200  		r.Interpolations = append(r.Interpolations, node)
   201  		vars, err := DetectVariables(node)
   202  		if err != nil {
   203  			return "", err
   204  		}
   205  
   206  		for _, v := range vars {
   207  			if r.Variables == nil {
   208  				r.Variables = make(map[string]InterpolatedVariable)
   209  			}
   210  
   211  			r.Variables[v.FullKey()] = v
   212  		}
   213  
   214  		return "", nil
   215  	}
   216  
   217  	walker := &interpolationWalker{F: fn}
   218  	if err := reflectwalk.Walk(r.Raw, walker); err != nil {
   219  		return err
   220  	}
   221  
   222  	return nil
   223  }
   224  
   225  func (r *RawConfig) interpolate(fn interpolationWalkerFunc) error {
   226  	config, err := copystructure.Copy(r.Raw)
   227  	if err != nil {
   228  		return err
   229  	}
   230  	r.config = config.(map[string]interface{})
   231  
   232  	w := &interpolationWalker{F: fn, Replace: true}
   233  	err = reflectwalk.Walk(r.config, w)
   234  	if err != nil {
   235  		return err
   236  	}
   237  
   238  	r.unknownKeys = w.unknownKeys
   239  	return nil
   240  }
   241  
   242  func (r *RawConfig) merge(r2 *RawConfig) *RawConfig {
   243  	rawRaw, err := copystructure.Copy(r.Raw)
   244  	if err != nil {
   245  		panic(err)
   246  	}
   247  
   248  	raw := rawRaw.(map[string]interface{})
   249  	for k, v := range r2.Raw {
   250  		raw[k] = v
   251  	}
   252  
   253  	result, err := NewRawConfig(raw)
   254  	if err != nil {
   255  		panic(err)
   256  	}
   257  
   258  	return result
   259  }
   260  
   261  // UnknownKeys returns the keys of the configuration that are unknown
   262  // because they had interpolated variables that must be computed.
   263  func (r *RawConfig) UnknownKeys() []string {
   264  	return r.unknownKeys
   265  }
   266  
   267  // See GobEncode
   268  func (r *RawConfig) GobDecode(b []byte) error {
   269  	var data gobRawConfig
   270  	err := gob.NewDecoder(bytes.NewReader(b)).Decode(&data)
   271  	if err != nil {
   272  		return err
   273  	}
   274  
   275  	r.Key = data.Key
   276  	r.Raw = data.Raw
   277  
   278  	return r.init()
   279  }
   280  
   281  // GobEncode is a custom Gob encoder to use so that we only include the
   282  // raw configuration. Interpolated variables and such are lost and the
   283  // tree of interpolated variables is recomputed on decode, since it is
   284  // referentially transparent.
   285  func (r *RawConfig) GobEncode() ([]byte, error) {
   286  	r.lock.Lock()
   287  	defer r.lock.Unlock()
   288  
   289  	data := gobRawConfig{
   290  		Key: r.Key,
   291  		Raw: r.Raw,
   292  	}
   293  
   294  	var buf bytes.Buffer
   295  	if err := gob.NewEncoder(&buf).Encode(data); err != nil {
   296  		return nil, err
   297  	}
   298  
   299  	return buf.Bytes(), nil
   300  }
   301  
   302  type gobRawConfig struct {
   303  	Key string
   304  	Raw map[string]interface{}
   305  }
   306  
   307  // langEvalConfig returns the evaluation configuration we use to execute.
   308  func langEvalConfig(vs map[string]ast.Variable) *hil.EvalConfig {
   309  	funcMap := make(map[string]ast.Function)
   310  	for k, v := range Funcs() {
   311  		funcMap[k] = v
   312  	}
   313  	funcMap["lookup"] = interpolationFuncLookup(vs)
   314  	funcMap["keys"] = interpolationFuncKeys(vs)
   315  	funcMap["values"] = interpolationFuncValues(vs)
   316  
   317  	return &hil.EvalConfig{
   318  		GlobalScope: &ast.BasicScope{
   319  			VarMap:  vs,
   320  			FuncMap: funcMap,
   321  		},
   322  	}
   323  }