github.com/pmcatominey/terraform@v0.7.0-rc2.0.20160708105029-1401a52a5cc5/terraform/state_filter.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  )
     7  
     8  // StateFilter is responsible for filtering and searching a state.
     9  //
    10  // This is a separate struct from State rather than a method on State
    11  // because StateFilter might create sidecar data structures to optimize
    12  // filtering on the state.
    13  //
    14  // If you change the State, the filter created is invalid and either
    15  // Reset should be called or a new one should be allocated. StateFilter
    16  // will not watch State for changes and do this for you. If you filter after
    17  // changing the State without calling Reset, the behavior is not defined.
    18  type StateFilter struct {
    19  	State *State
    20  }
    21  
    22  // Filter takes the addresses specified by fs and finds all the matches.
    23  // The values of fs are resource addressing syntax that can be parsed by
    24  // ParseResourceAddress.
    25  func (f *StateFilter) Filter(fs ...string) ([]*StateFilterResult, error) {
    26  	// Parse all the addresses
    27  	as := make([]*ResourceAddress, len(fs))
    28  	for i, v := range fs {
    29  		a, err := ParseResourceAddress(v)
    30  		if err != nil {
    31  			return nil, fmt.Errorf("Error parsing address '%s': %s", v, err)
    32  		}
    33  
    34  		as[i] = a
    35  	}
    36  
    37  	// If we werent given any filters, then we list all
    38  	if len(fs) == 0 {
    39  		as = append(as, &ResourceAddress{Index: -1})
    40  	}
    41  
    42  	// Filter each of the address. We keep track of this in a map to
    43  	// strip duplicates.
    44  	resultSet := make(map[string]*StateFilterResult)
    45  	for _, a := range as {
    46  		for _, r := range f.filterSingle(a) {
    47  			resultSet[r.String()] = r
    48  		}
    49  	}
    50  
    51  	// Make the result list
    52  	results := make([]*StateFilterResult, 0, len(resultSet))
    53  	for _, v := range resultSet {
    54  		results = append(results, v)
    55  	}
    56  
    57  	// Sort them and return
    58  	sort.Sort(StateFilterResultSlice(results))
    59  	return results, nil
    60  }
    61  
    62  func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult {
    63  	// The slice to keep track of results
    64  	var results []*StateFilterResult
    65  
    66  	// Go through modules first.
    67  	modules := make([]*ModuleState, 0, len(f.State.Modules))
    68  	for _, m := range f.State.Modules {
    69  		if f.relevant(a, m) {
    70  			modules = append(modules, m)
    71  
    72  			// Only add the module to the results if we haven't specified a type.
    73  			// We also ignore the root module.
    74  			if a.Type == "" && len(m.Path) > 1 {
    75  				results = append(results, &StateFilterResult{
    76  					Path:    m.Path[1:],
    77  					Address: (&ResourceAddress{Path: m.Path[1:]}).String(),
    78  					Value:   m,
    79  				})
    80  			}
    81  		}
    82  	}
    83  
    84  	// With the modules set, go through all the resources within
    85  	// the modules to find relevant resources.
    86  	for _, m := range modules {
    87  		for n, r := range m.Resources {
    88  			if f.relevant(a, r) {
    89  				// The name in the state contains valuable information. Parse.
    90  				key, err := ParseResourceStateKey(n)
    91  				if err != nil {
    92  					// If we get an error parsing, then just ignore it
    93  					// out of the state.
    94  					continue
    95  				}
    96  
    97  				if a.Index >= 0 && key.Index != a.Index {
    98  					// Index doesn't match
    99  					continue
   100  				}
   101  
   102  				if a.Name != "" && a.Name != key.Name {
   103  					continue
   104  				}
   105  
   106  				// Build the address for this resource
   107  				addr := &ResourceAddress{
   108  					Path:  m.Path[1:],
   109  					Name:  key.Name,
   110  					Type:  key.Type,
   111  					Index: key.Index,
   112  				}
   113  
   114  				// Add the resource level result
   115  				resourceResult := &StateFilterResult{
   116  					Path:    addr.Path,
   117  					Address: addr.String(),
   118  					Value:   r,
   119  				}
   120  				if !a.InstanceTypeSet {
   121  					results = append(results, resourceResult)
   122  				}
   123  
   124  				// Add the instances
   125  				if r.Primary != nil {
   126  					addr.InstanceType = TypePrimary
   127  					addr.InstanceTypeSet = false
   128  					results = append(results, &StateFilterResult{
   129  						Path:    addr.Path,
   130  						Address: addr.String(),
   131  						Parent:  resourceResult,
   132  						Value:   r.Primary,
   133  					})
   134  				}
   135  
   136  				for _, instance := range r.Deposed {
   137  					if f.relevant(a, instance) {
   138  						addr.InstanceType = TypeDeposed
   139  						addr.InstanceTypeSet = true
   140  						results = append(results, &StateFilterResult{
   141  							Path:    addr.Path,
   142  							Address: addr.String(),
   143  							Parent:  resourceResult,
   144  							Value:   instance,
   145  						})
   146  					}
   147  				}
   148  			}
   149  		}
   150  	}
   151  
   152  	return results
   153  }
   154  
   155  // relevant checks for relevance of this address against the given value.
   156  func (f *StateFilter) relevant(addr *ResourceAddress, raw interface{}) bool {
   157  	switch v := raw.(type) {
   158  	case *ModuleState:
   159  		path := v.Path[1:]
   160  
   161  		if len(addr.Path) > len(path) {
   162  			// Longer path in address means there is no way we match.
   163  			return false
   164  		}
   165  
   166  		// Check for a prefix match
   167  		for i, p := range addr.Path {
   168  			if path[i] != p {
   169  				// Any mismatches don't match.
   170  				return false
   171  			}
   172  		}
   173  
   174  		return true
   175  	case *ResourceState:
   176  		if addr.Type == "" {
   177  			// If we have no resource type, then we're interested in all!
   178  			return true
   179  		}
   180  
   181  		// If the type doesn't match we fail immediately
   182  		if v.Type != addr.Type {
   183  			return false
   184  		}
   185  
   186  		return true
   187  	default:
   188  		// If we don't know about it, let's just say no
   189  		return false
   190  	}
   191  }
   192  
   193  // StateFilterResult is a single result from a filter operation. Filter
   194  // can match multiple things within a state (module, resource, instance, etc.)
   195  // and this unifies that.
   196  type StateFilterResult struct {
   197  	// Module path of the result
   198  	Path []string
   199  
   200  	// Address is the address that can be used to reference this exact result.
   201  	Address string
   202  
   203  	// Parent, if non-nil, is a parent of this result. For instances, the
   204  	// parent would be a resource. For resources, the parent would be
   205  	// a module. For modules, this is currently nil.
   206  	Parent *StateFilterResult
   207  
   208  	// Value is the actual value. This must be type switched on. It can be
   209  	// any data structures that `State` can hold: `ModuleState`,
   210  	// `ResourceState`, `InstanceState`.
   211  	Value interface{}
   212  }
   213  
   214  func (r *StateFilterResult) String() string {
   215  	return fmt.Sprintf("%T: %s", r.Value, r.Address)
   216  }
   217  
   218  func (r *StateFilterResult) sortedType() int {
   219  	switch r.Value.(type) {
   220  	case *ModuleState:
   221  		return 0
   222  	case *ResourceState:
   223  		return 1
   224  	case *InstanceState:
   225  		return 2
   226  	default:
   227  		return 50
   228  	}
   229  }
   230  
   231  // StateFilterResultSlice is a slice of results that implements
   232  // sort.Interface. The sorting goal is what is most appealing to
   233  // human output.
   234  type StateFilterResultSlice []*StateFilterResult
   235  
   236  func (s StateFilterResultSlice) Len() int      { return len(s) }
   237  func (s StateFilterResultSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   238  func (s StateFilterResultSlice) Less(i, j int) bool {
   239  	a, b := s[i], s[j]
   240  
   241  	// If the addresses are different it is just lexographic sorting
   242  	if a.Address != b.Address {
   243  		return a.Address < b.Address
   244  	}
   245  
   246  	// Addresses are the same, which means it matters on the type
   247  	return a.sortedType() < b.sortedType()
   248  }