github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/helper/resource/state.go (about)

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