github.com/hooklift/terraform@v0.11.0-beta1.0.20171117000744-6786c1361ffe/config/module/tree.go (about)

     1  package module
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"log"
     8  	"path/filepath"
     9  	"strings"
    10  	"sync"
    11  
    12  	getter "github.com/hashicorp/go-getter"
    13  	"github.com/hashicorp/terraform/config"
    14  )
    15  
    16  // RootName is the name of the root tree.
    17  const RootName = "root"
    18  
    19  // Tree represents the module import tree of configurations.
    20  //
    21  // This Tree structure can be used to get (download) new modules, load
    22  // all the modules without getting, flatten the tree into something
    23  // Terraform can use, etc.
    24  type Tree struct {
    25  	name     string
    26  	config   *config.Config
    27  	children map[string]*Tree
    28  	path     []string
    29  	lock     sync.RWMutex
    30  
    31  	// version is the final version of the config loaded for the Tree's module
    32  	version string
    33  	// source is the "source" string used to load this module. It's possible
    34  	// for a module source to change, but the path remains the same, preventing
    35  	// it from being reloaded.
    36  	source string
    37  	// parent allows us to walk back up the tree and determine if there are any
    38  	// versioned ancestor modules which may effect the stored location of
    39  	// submodules
    40  	parent *Tree
    41  }
    42  
    43  // NewTree returns a new Tree for the given config structure.
    44  func NewTree(name string, c *config.Config) *Tree {
    45  	return &Tree{config: c, name: name}
    46  }
    47  
    48  // NewEmptyTree returns a new tree that is empty (contains no configuration).
    49  func NewEmptyTree() *Tree {
    50  	t := &Tree{config: &config.Config{}}
    51  
    52  	// We do this dummy load so that the tree is marked as "loaded". It
    53  	// should never fail because this is just about a no-op. If it does fail
    54  	// we panic so we can know its a bug.
    55  	if err := t.Load(&Storage{Mode: GetModeGet}); err != nil {
    56  		panic(err)
    57  	}
    58  
    59  	return t
    60  }
    61  
    62  // NewTreeModule is like NewTree except it parses the configuration in
    63  // the directory and gives it a specific name. Use a blank name "" to specify
    64  // the root module.
    65  func NewTreeModule(name, dir string) (*Tree, error) {
    66  	c, err := config.LoadDir(dir)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	return NewTree(name, c), nil
    72  }
    73  
    74  // Config returns the configuration for this module.
    75  func (t *Tree) Config() *config.Config {
    76  	return t.config
    77  }
    78  
    79  // Child returns the child with the given path (by name).
    80  func (t *Tree) Child(path []string) *Tree {
    81  	if t == nil {
    82  		return nil
    83  	}
    84  
    85  	if len(path) == 0 {
    86  		return t
    87  	}
    88  
    89  	c := t.Children()[path[0]]
    90  	if c == nil {
    91  		return nil
    92  	}
    93  
    94  	return c.Child(path[1:])
    95  }
    96  
    97  // Children returns the children of this tree (the modules that are
    98  // imported by this root).
    99  //
   100  // This will only return a non-nil value after Load is called.
   101  func (t *Tree) Children() map[string]*Tree {
   102  	t.lock.RLock()
   103  	defer t.lock.RUnlock()
   104  	return t.children
   105  }
   106  
   107  // DeepEach calls the provided callback for the receiver and then all of
   108  // its descendents in the tree, allowing an operation to be performed on
   109  // all modules in the tree.
   110  //
   111  // Parents will be visited before their children but otherwise the order is
   112  // not defined.
   113  func (t *Tree) DeepEach(cb func(*Tree)) {
   114  	t.lock.RLock()
   115  	defer t.lock.RUnlock()
   116  	t.deepEach(cb)
   117  }
   118  
   119  func (t *Tree) deepEach(cb func(*Tree)) {
   120  	cb(t)
   121  	for _, c := range t.children {
   122  		c.deepEach(cb)
   123  	}
   124  }
   125  
   126  // Loaded says whether or not this tree has been loaded or not yet.
   127  func (t *Tree) Loaded() bool {
   128  	t.lock.RLock()
   129  	defer t.lock.RUnlock()
   130  	return t.children != nil
   131  }
   132  
   133  // Modules returns the list of modules that this tree imports.
   134  //
   135  // This is only the imports of _this_ level of the tree. To retrieve the
   136  // full nested imports, you'll have to traverse the tree.
   137  func (t *Tree) Modules() []*Module {
   138  	result := make([]*Module, len(t.config.Modules))
   139  	for i, m := range t.config.Modules {
   140  		result[i] = &Module{
   141  			Name:      m.Name,
   142  			Version:   m.Version,
   143  			Source:    m.Source,
   144  			Providers: m.Providers,
   145  		}
   146  	}
   147  
   148  	return result
   149  }
   150  
   151  // Name returns the name of the tree. This will be "<root>" for the root
   152  // tree and then the module name given for any children.
   153  func (t *Tree) Name() string {
   154  	if t.name == "" {
   155  		return RootName
   156  	}
   157  
   158  	return t.name
   159  }
   160  
   161  // Load loads the configuration of the entire tree.
   162  //
   163  // The parameters are used to tell the tree where to find modules and
   164  // whether it can download/update modules along the way.
   165  //
   166  // Calling this multiple times will reload the tree.
   167  //
   168  // Various semantic-like checks are made along the way of loading since
   169  // module trees inherently require the configuration to be in a reasonably
   170  // sane state: no circular dependencies, proper module sources, etc. A full
   171  // suite of validations can be done by running Validate (after loading).
   172  func (t *Tree) Load(s *Storage) error {
   173  	t.lock.Lock()
   174  	defer t.lock.Unlock()
   175  
   176  	children, err := t.getChildren(s)
   177  	if err != nil {
   178  		return err
   179  	}
   180  
   181  	// Go through all the children and load them.
   182  	for _, c := range children {
   183  		if err := c.Load(s); err != nil {
   184  			return err
   185  		}
   186  	}
   187  
   188  	// Set our tree up
   189  	t.children = children
   190  
   191  	return nil
   192  }
   193  
   194  func (t *Tree) getChildren(s *Storage) (map[string]*Tree, error) {
   195  	children := make(map[string]*Tree)
   196  
   197  	// Go through all the modules and get the directory for them.
   198  	for _, m := range t.Modules() {
   199  		if _, ok := children[m.Name]; ok {
   200  			return nil, fmt.Errorf(
   201  				"module %s: duplicated. module names must be unique", m.Name)
   202  		}
   203  
   204  		// Determine the path to this child
   205  		modPath := make([]string, len(t.path), len(t.path)+1)
   206  		copy(modPath, t.path)
   207  		modPath = append(modPath, m.Name)
   208  
   209  		log.Printf("[TRACE] module source: %q", m.Source)
   210  
   211  		// add the module path to help indicate where modules with relative
   212  		// paths are being loaded from
   213  		s.output(fmt.Sprintf("- module.%s", strings.Join(modPath, ".")))
   214  
   215  		// Lookup the local location of the module.
   216  		// dir is the local directory where the module is stored
   217  		mod, err := s.findRegistryModule(m.Source, m.Version)
   218  		if err != nil {
   219  			return nil, err
   220  		}
   221  
   222  		// The key is the string that will be used to uniquely id the Source in
   223  		// the local storage.  The prefix digit can be incremented to
   224  		// invalidate the local module storage.
   225  		key := "1." + t.versionedPathKey(m)
   226  		if mod.Version != "" {
   227  			key += "." + mod.Version
   228  		}
   229  
   230  		// Check for the exact key if it's not a registry module
   231  		if !mod.registry {
   232  			mod.Dir, err = s.findModule(key)
   233  			if err != nil {
   234  				return nil, err
   235  			}
   236  		}
   237  
   238  		if mod.Dir != "" && s.Mode != GetModeUpdate {
   239  			// We found it locally, but in order to load the Tree we need to
   240  			// find out if there was another subDir stored from detection.
   241  			subDir, err := s.getModuleRoot(mod.Dir)
   242  			if err != nil {
   243  				// If there's a problem with the subdir record, we'll let the
   244  				// recordSubdir method fix it up.  Any other filesystem errors
   245  				// will turn up again below.
   246  				log.Println("[WARN] error reading subdir record:", err)
   247  			}
   248  
   249  			fullDir := filepath.Join(mod.Dir, subDir)
   250  
   251  			child, err := NewTreeModule(m.Name, fullDir)
   252  			if err != nil {
   253  				return nil, fmt.Errorf("module %s: %s", m.Name, err)
   254  			}
   255  			child.path = modPath
   256  			child.parent = t
   257  			child.version = mod.Version
   258  			child.source = m.Source
   259  			children[m.Name] = child
   260  			continue
   261  		}
   262  
   263  		// Split out the subdir if we have one.
   264  		// Terraform keeps the entire requested tree, so that modules can
   265  		// reference sibling modules from the same archive or repo.
   266  		rawSource, subDir := getter.SourceDirSubdir(m.Source)
   267  
   268  		// we haven't found a source, so fallback to the go-getter detectors
   269  		source := mod.url
   270  		if source == "" {
   271  			source, err = getter.Detect(rawSource, t.config.Dir, getter.Detectors)
   272  			if err != nil {
   273  				return nil, fmt.Errorf("module %s: %s", m.Name, err)
   274  			}
   275  		}
   276  
   277  		log.Printf("[TRACE] detected module source %q", source)
   278  
   279  		// Check if the detector introduced something new.
   280  		// For example, the registry always adds a subdir of `//*`,
   281  		// indicating that we need to strip off the first component from the
   282  		// tar archive, though we may not yet know what it is called.
   283  		source, detectedSubDir := getter.SourceDirSubdir(source)
   284  		if detectedSubDir != "" {
   285  			subDir = filepath.Join(detectedSubDir, subDir)
   286  		}
   287  
   288  		output := ""
   289  		switch s.Mode {
   290  		case GetModeUpdate:
   291  			output = fmt.Sprintf("  Updating source %q", m.Source)
   292  		default:
   293  			output = fmt.Sprintf("  Getting source %q", m.Source)
   294  		}
   295  		s.output(output)
   296  
   297  		dir, ok, err := s.getStorage(key, source)
   298  		if err != nil {
   299  			return nil, err
   300  		}
   301  		if !ok {
   302  			return nil, fmt.Errorf("module %s: not found, may need to run 'terraform init'", m.Name)
   303  		}
   304  
   305  		log.Printf("[TRACE] %q stored in %q", source, dir)
   306  
   307  		// expand and record the subDir for later
   308  		fullDir := dir
   309  		if subDir != "" {
   310  			fullDir, err = getter.SubdirGlob(dir, subDir)
   311  			if err != nil {
   312  				return nil, err
   313  			}
   314  
   315  			// +1 to account for the pathsep
   316  			if len(dir)+1 > len(fullDir) {
   317  				return nil, fmt.Errorf("invalid module storage path %q", fullDir)
   318  			}
   319  			subDir = fullDir[len(dir)+1:]
   320  		}
   321  
   322  		// add new info to the module record
   323  		mod.Key = key
   324  		mod.Dir = dir
   325  		mod.Root = subDir
   326  
   327  		// record the module in our manifest
   328  		if err := s.recordModule(mod); err != nil {
   329  			return nil, err
   330  		}
   331  
   332  		child, err := NewTreeModule(m.Name, fullDir)
   333  		if err != nil {
   334  			return nil, fmt.Errorf("module %s: %s", m.Name, err)
   335  		}
   336  		child.path = modPath
   337  		child.parent = t
   338  		child.version = mod.Version
   339  		child.source = m.Source
   340  		children[m.Name] = child
   341  	}
   342  
   343  	return children, nil
   344  }
   345  
   346  // Path is the full path to this tree.
   347  func (t *Tree) Path() []string {
   348  	return t.path
   349  }
   350  
   351  // String gives a nice output to describe the tree.
   352  func (t *Tree) String() string {
   353  	var result bytes.Buffer
   354  	path := strings.Join(t.path, ", ")
   355  	if path != "" {
   356  		path = fmt.Sprintf(" (path: %s)", path)
   357  	}
   358  	result.WriteString(t.Name() + path + "\n")
   359  
   360  	cs := t.Children()
   361  	if cs == nil {
   362  		result.WriteString("  not loaded")
   363  	} else {
   364  		// Go through each child and get its string value, then indent it
   365  		// by two.
   366  		for _, c := range cs {
   367  			r := strings.NewReader(c.String())
   368  			scanner := bufio.NewScanner(r)
   369  			for scanner.Scan() {
   370  				result.WriteString("  ")
   371  				result.WriteString(scanner.Text())
   372  				result.WriteString("\n")
   373  			}
   374  		}
   375  	}
   376  
   377  	return result.String()
   378  }
   379  
   380  // Validate does semantic checks on the entire tree of configurations.
   381  //
   382  // This will call the respective config.Config.Validate() functions as well
   383  // as verifying things such as parameters/outputs between the various modules.
   384  //
   385  // Load must be called prior to calling Validate or an error will be returned.
   386  func (t *Tree) Validate() error {
   387  	if !t.Loaded() {
   388  		return fmt.Errorf("tree must be loaded before calling Validate")
   389  	}
   390  
   391  	// If something goes wrong, here is our error template
   392  	newErr := &treeError{Name: []string{t.Name()}}
   393  
   394  	// Terraform core does not handle root module children named "root".
   395  	// We plan to fix this in the future but this bug was brought up in
   396  	// the middle of a release and we don't want to introduce wide-sweeping
   397  	// changes at that time.
   398  	if len(t.path) == 1 && t.name == "root" {
   399  		return fmt.Errorf("root module cannot contain module named 'root'")
   400  	}
   401  
   402  	// Validate our configuration first.
   403  	if err := t.config.Validate(); err != nil {
   404  		newErr.Add(err)
   405  	}
   406  
   407  	// If we're the root, we do extra validation. This validation usually
   408  	// requires the entire tree (since children don't have parent pointers).
   409  	if len(t.path) == 0 {
   410  		if err := t.validateProviderAlias(); err != nil {
   411  			newErr.Add(err)
   412  		}
   413  	}
   414  
   415  	// Get the child trees
   416  	children := t.Children()
   417  
   418  	// Validate all our children
   419  	for _, c := range children {
   420  		err := c.Validate()
   421  		if err == nil {
   422  			continue
   423  		}
   424  
   425  		verr, ok := err.(*treeError)
   426  		if !ok {
   427  			// Unknown error, just return...
   428  			return err
   429  		}
   430  
   431  		// Append ourselves to the error and then return
   432  		verr.Name = append(verr.Name, t.Name())
   433  		newErr.AddChild(verr)
   434  	}
   435  
   436  	// Go over all the modules and verify that any parameters are valid
   437  	// variables into the module in question.
   438  	for _, m := range t.config.Modules {
   439  		tree, ok := children[m.Name]
   440  		if !ok {
   441  			// This should never happen because Load watches us
   442  			panic("module not found in children: " + m.Name)
   443  		}
   444  
   445  		// Build the variables that the module defines
   446  		requiredMap := make(map[string]struct{})
   447  		varMap := make(map[string]struct{})
   448  		for _, v := range tree.config.Variables {
   449  			varMap[v.Name] = struct{}{}
   450  
   451  			if v.Required() {
   452  				requiredMap[v.Name] = struct{}{}
   453  			}
   454  		}
   455  
   456  		// Compare to the keys in our raw config for the module
   457  		for k, _ := range m.RawConfig.Raw {
   458  			if _, ok := varMap[k]; !ok {
   459  				newErr.Add(fmt.Errorf(
   460  					"module %s: %s is not a valid parameter",
   461  					m.Name, k))
   462  			}
   463  
   464  			// Remove the required
   465  			delete(requiredMap, k)
   466  		}
   467  
   468  		// If we have any required left over, they aren't set.
   469  		for k, _ := range requiredMap {
   470  			newErr.Add(fmt.Errorf(
   471  				"module %s: required variable %q not set",
   472  				m.Name, k))
   473  		}
   474  	}
   475  
   476  	// Go over all the variables used and make sure that any module
   477  	// variables represent outputs properly.
   478  	for source, vs := range t.config.InterpolatedVariables() {
   479  		for _, v := range vs {
   480  			mv, ok := v.(*config.ModuleVariable)
   481  			if !ok {
   482  				continue
   483  			}
   484  
   485  			tree, ok := children[mv.Name]
   486  			if !ok {
   487  				newErr.Add(fmt.Errorf(
   488  					"%s: undefined module referenced %s",
   489  					source, mv.Name))
   490  				continue
   491  			}
   492  
   493  			found := false
   494  			for _, o := range tree.config.Outputs {
   495  				if o.Name == mv.Field {
   496  					found = true
   497  					break
   498  				}
   499  			}
   500  			if !found {
   501  				newErr.Add(fmt.Errorf(
   502  					"%s: %s is not a valid output for module %s",
   503  					source, mv.Field, mv.Name))
   504  			}
   505  		}
   506  	}
   507  
   508  	return newErr.ErrOrNil()
   509  }
   510  
   511  // versionedPathKey returns a path string with every levels full name, version
   512  // and source encoded. This is to provide a unique key for our module storage,
   513  // since submodules need to know which versions of their ancestor modules they
   514  // are loaded from.
   515  // For example, if module A has a subdirectory B, if module A's source or
   516  // version is updated B's storage key must reflect this change in order for the
   517  // correct version of B's source to be loaded.
   518  func (t *Tree) versionedPathKey(m *Module) string {
   519  	path := make([]string, len(t.path)+1)
   520  	path[len(path)-1] = m.Name + ";" + m.Source
   521  	// We're going to load these in order for easier reading and debugging, but
   522  	// in practice they only need to be unique and consistent.
   523  
   524  	p := t
   525  	i := len(path) - 2
   526  	for ; i >= 0; i-- {
   527  		if p == nil {
   528  			break
   529  		}
   530  		// we may have been loaded under a blank Tree, so always check for a name
   531  		// too.
   532  		if p.name == "" {
   533  			break
   534  		}
   535  		seg := p.name
   536  		if p.version != "" {
   537  			seg += "#" + p.version
   538  		}
   539  
   540  		if p.source != "" {
   541  			seg += ";" + p.source
   542  		}
   543  
   544  		path[i] = seg
   545  		p = p.parent
   546  	}
   547  
   548  	key := strings.Join(path, "|")
   549  	return key
   550  }
   551  
   552  // treeError is an error use by Tree.Validate to accumulates all
   553  // validation errors.
   554  type treeError struct {
   555  	Name     []string
   556  	Errs     []error
   557  	Children []*treeError
   558  }
   559  
   560  func (e *treeError) Add(err error) {
   561  	e.Errs = append(e.Errs, err)
   562  }
   563  
   564  func (e *treeError) AddChild(err *treeError) {
   565  	e.Children = append(e.Children, err)
   566  }
   567  
   568  func (e *treeError) ErrOrNil() error {
   569  	if len(e.Errs) > 0 || len(e.Children) > 0 {
   570  		return e
   571  	}
   572  	return nil
   573  }
   574  
   575  func (e *treeError) Error() string {
   576  	name := strings.Join(e.Name, ".")
   577  	var out bytes.Buffer
   578  	fmt.Fprintf(&out, "module %s: ", name)
   579  
   580  	if len(e.Errs) == 1 {
   581  		// single like error
   582  		out.WriteString(e.Errs[0].Error())
   583  	} else {
   584  		// multi-line error
   585  		for _, err := range e.Errs {
   586  			fmt.Fprintf(&out, "\n    %s", err)
   587  		}
   588  	}
   589  
   590  	if len(e.Children) > 0 {
   591  		// start the next error on a new line
   592  		out.WriteString("\n  ")
   593  	}
   594  	for _, child := range e.Children {
   595  		out.WriteString(child.Error())
   596  	}
   597  
   598  	return out.String()
   599  }