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

     1  package resource
     2  
     3  import (
     4  	"log"
     5  	"math"
     6  	"time"
     7  )
     8  
     9  // StateRefreshFunc is a function type used for StateChangeConf that is
    10  // responsible for refreshing the item being watched for a state change.
    11  //
    12  // It returns three results. `result` is any object that will be returned
    13  // as the final object after waiting for state change. This allows you to
    14  // return the final updated object, for example an EC2 instance after refreshing
    15  // it.
    16  //
    17  // `state` is the latest state of that object. And `err` is any error that
    18  // may have happened while refreshing the state.
    19  type StateRefreshFunc func() (result interface{}, state string, err error)
    20  
    21  // StateChangeConf is the configuration struct used for `WaitForState`.
    22  type StateChangeConf struct {
    23  	Delay          time.Duration    // Wait this time before starting checks
    24  	Pending        []string         // States that are "allowed" and will continue trying
    25  	Refresh        StateRefreshFunc // Refreshes the current state
    26  	Target         []string         // Target state
    27  	Timeout        time.Duration    // The amount of time to wait before timeout
    28  	MinTimeout     time.Duration    // Smallest time to wait before refreshes
    29  	NotFoundChecks int              // Number of times to allow not found
    30  
    31  	// This is to work around inconsistent APIs
    32  	ContinuousTargetOccurence int // Number of times the Target state has to occur continuously
    33  }
    34  
    35  // WaitForState watches an object and waits for it to achieve the state
    36  // specified in the configuration using the specified Refresh() func,
    37  // waiting the number of seconds specified in the timeout configuration.
    38  //
    39  // If the Refresh function returns a error, exit immediately with that error.
    40  //
    41  // If the Refresh function returns a state other than the Target state or one
    42  // listed in Pending, return immediately with an error.
    43  //
    44  // If the Timeout is exceeded before reaching the Target state, return an
    45  // error.
    46  //
    47  // Otherwise, result the result of the first call to the Refresh function to
    48  // reach the target state.
    49  func (conf *StateChangeConf) WaitForState() (interface{}, error) {
    50  	log.Printf("[DEBUG] Waiting for state to become: %s", conf.Target)
    51  
    52  	notfoundTick := 0
    53  	targetOccurence := 0
    54  
    55  	// Set a default for times to check for not found
    56  	if conf.NotFoundChecks == 0 {
    57  		conf.NotFoundChecks = 20
    58  	}
    59  
    60  	if conf.ContinuousTargetOccurence == 0 {
    61  		conf.ContinuousTargetOccurence = 1
    62  	}
    63  
    64  	var result interface{}
    65  	var resulterr error
    66  
    67  	doneCh := make(chan struct{})
    68  	go func() {
    69  		defer close(doneCh)
    70  
    71  		// Wait for the delay
    72  		time.Sleep(conf.Delay)
    73  
    74  		var err error
    75  		for tries := 0; ; tries++ {
    76  			// Wait between refreshes using an exponential backoff
    77  			wait := time.Duration(math.Pow(2, float64(tries))) *
    78  				100 * time.Millisecond
    79  			if wait < conf.MinTimeout {
    80  				wait = conf.MinTimeout
    81  			} else if wait > 10*time.Second {
    82  				wait = 10 * time.Second
    83  			}
    84  
    85  			log.Printf("[TRACE] Waiting %s before next try", wait)
    86  			time.Sleep(wait)
    87  
    88  			var currentState string
    89  			result, currentState, err = conf.Refresh()
    90  			if err != nil {
    91  				resulterr = err
    92  				return
    93  			}
    94  
    95  			// If we're waiting for the absence of a thing, then return
    96  			if result == nil && len(conf.Target) == 0 {
    97  				targetOccurence += 1
    98  				if conf.ContinuousTargetOccurence == targetOccurence {
    99  					return
   100  				} else {
   101  					continue
   102  				}
   103  			}
   104  
   105  			if result == nil {
   106  				// If we didn't find the resource, check if we have been
   107  				// not finding it for awhile, and if so, report an error.
   108  				notfoundTick += 1
   109  				if notfoundTick > conf.NotFoundChecks {
   110  					resulterr = &NotFoundError{
   111  						LastError: resulterr,
   112  					}
   113  					return
   114  				}
   115  			} else {
   116  				// Reset the counter for when a resource isn't found
   117  				notfoundTick = 0
   118  				found := false
   119  
   120  				for _, allowed := range conf.Target {
   121  					if currentState == allowed {
   122  						found = true
   123  						targetOccurence += 1
   124  						if conf.ContinuousTargetOccurence == targetOccurence {
   125  							return
   126  						} else {
   127  							continue
   128  						}
   129  					}
   130  				}
   131  
   132  				for _, allowed := range conf.Pending {
   133  					if currentState == allowed {
   134  						found = true
   135  						targetOccurence = 0
   136  						break
   137  					}
   138  				}
   139  
   140  				if !found {
   141  					resulterr = &UnexpectedStateError{
   142  						LastError:     resulterr,
   143  						State:         currentState,
   144  						ExpectedState: conf.Target,
   145  					}
   146  					return
   147  				}
   148  			}
   149  		}
   150  	}()
   151  
   152  	select {
   153  	case <-doneCh:
   154  		return result, resulterr
   155  	case <-time.After(conf.Timeout):
   156  		return nil, &TimeoutError{
   157  			LastError:     resulterr,
   158  			ExpectedState: conf.Target,
   159  		}
   160  	}
   161  }