github.com/tomaszheflik/terraform@v0.7.3-0.20160827060421-32f990b41594/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.Name != "" && a.Name != key.Name {
    98  					// Name doesn't match
    99  					continue
   100  				}
   101  
   102  				if a.Index >= 0 && key.Index != a.Index {
   103  					// Index doesn't match
   104  					continue
   105  				}
   106  
   107  				if a.Name != "" && a.Name != key.Name {
   108  					continue
   109  				}
   110  
   111  				// Build the address for this resource
   112  				addr := &ResourceAddress{
   113  					Path:  m.Path[1:],
   114  					Name:  key.Name,
   115  					Type:  key.Type,
   116  					Index: key.Index,
   117  				}
   118  
   119  				// Add the resource level result
   120  				resourceResult := &StateFilterResult{
   121  					Path:    addr.Path,
   122  					Address: addr.String(),
   123  					Value:   r,
   124  				}
   125  				if !a.InstanceTypeSet {
   126  					results = append(results, resourceResult)
   127  				}
   128  
   129  				// Add the instances
   130  				if r.Primary != nil {
   131  					addr.InstanceType = TypePrimary
   132  					addr.InstanceTypeSet = false
   133  					results = append(results, &StateFilterResult{
   134  						Path:    addr.Path,
   135  						Address: addr.String(),
   136  						Parent:  resourceResult,
   137  						Value:   r.Primary,
   138  					})
   139  				}
   140  
   141  				for _, instance := range r.Deposed {
   142  					if f.relevant(a, instance) {
   143  						addr.InstanceType = TypeDeposed
   144  						addr.InstanceTypeSet = true
   145  						results = append(results, &StateFilterResult{
   146  							Path:    addr.Path,
   147  							Address: addr.String(),
   148  							Parent:  resourceResult,
   149  							Value:   instance,
   150  						})
   151  					}
   152  				}
   153  			}
   154  		}
   155  	}
   156  
   157  	return results
   158  }
   159  
   160  // relevant checks for relevance of this address against the given value.
   161  func (f *StateFilter) relevant(addr *ResourceAddress, raw interface{}) bool {
   162  	switch v := raw.(type) {
   163  	case *ModuleState:
   164  		path := v.Path[1:]
   165  
   166  		if len(addr.Path) > len(path) {
   167  			// Longer path in address means there is no way we match.
   168  			return false
   169  		}
   170  
   171  		// Check for a prefix match
   172  		for i, p := range addr.Path {
   173  			if path[i] != p {
   174  				// Any mismatches don't match.
   175  				return false
   176  			}
   177  		}
   178  
   179  		return true
   180  	case *ResourceState:
   181  		if addr.Type == "" {
   182  			// If we have no resource type, then we're interested in all!
   183  			return true
   184  		}
   185  
   186  		// If the type doesn't match we fail immediately
   187  		if v.Type != addr.Type {
   188  			return false
   189  		}
   190  
   191  		return true
   192  	default:
   193  		// If we don't know about it, let's just say no
   194  		return false
   195  	}
   196  }
   197  
   198  // StateFilterResult is a single result from a filter operation. Filter
   199  // can match multiple things within a state (module, resource, instance, etc.)
   200  // and this unifies that.
   201  type StateFilterResult struct {
   202  	// Module path of the result
   203  	Path []string
   204  
   205  	// Address is the address that can be used to reference this exact result.
   206  	Address string
   207  
   208  	// Parent, if non-nil, is a parent of this result. For instances, the
   209  	// parent would be a resource. For resources, the parent would be
   210  	// a module. For modules, this is currently nil.
   211  	Parent *StateFilterResult
   212  
   213  	// Value is the actual value. This must be type switched on. It can be
   214  	// any data structures that `State` can hold: `ModuleState`,
   215  	// `ResourceState`, `InstanceState`.
   216  	Value interface{}
   217  }
   218  
   219  func (r *StateFilterResult) String() string {
   220  	return fmt.Sprintf("%T: %s", r.Value, r.Address)
   221  }
   222  
   223  func (r *StateFilterResult) sortedType() int {
   224  	switch r.Value.(type) {
   225  	case *ModuleState:
   226  		return 0
   227  	case *ResourceState:
   228  		return 1
   229  	case *InstanceState:
   230  		return 2
   231  	default:
   232  		return 50
   233  	}
   234  }
   235  
   236  // StateFilterResultSlice is a slice of results that implements
   237  // sort.Interface. The sorting goal is what is most appealing to
   238  // human output.
   239  type StateFilterResultSlice []*StateFilterResult
   240  
   241  func (s StateFilterResultSlice) Len() int      { return len(s) }
   242  func (s StateFilterResultSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
   243  func (s StateFilterResultSlice) Less(i, j int) bool {
   244  	a, b := s[i], s[j]
   245  
   246  	// If the addresses are different it is just lexographic sorting
   247  	if a.Address != b.Address {
   248  		return a.Address < b.Address
   249  	}
   250  
   251  	// Addresses are the same, which means it matters on the type
   252  	return a.sortedType() < b.sortedType()
   253  }