github.com/ndarilek/terraform@v0.3.8-0.20150320140257-d3135c1b2bac/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  func (conf *StateChangeConf) WaitForState() (interface{}, error) {
    38  	log.Printf("[DEBUG] Waiting for state to become: %s", conf.Target)
    39  
    40  	notfoundTick := 0
    41  
    42  	// Set a default for times to check for not found
    43  	if conf.NotFoundChecks == 0 {
    44  		conf.NotFoundChecks = 20
    45  	}
    46  
    47  	var result interface{}
    48  	var resulterr error
    49  
    50  	doneCh := make(chan struct{})
    51  	go func() {
    52  		defer close(doneCh)
    53  
    54  		// Wait for the delay
    55  		time.Sleep(conf.Delay)
    56  
    57  		var err error
    58  		for tries := 0; ; tries++ {
    59  			// Wait between refreshes using an exponential backoff
    60  			wait := time.Duration(math.Pow(2, float64(tries))) *
    61  				100 * time.Millisecond
    62  			if wait < conf.MinTimeout {
    63  				wait = conf.MinTimeout
    64  			} else if wait > 10*time.Second {
    65  				wait = 10 * time.Second
    66  			}
    67  
    68  			log.Printf("[TRACE] Waiting %s before next try", wait)
    69  			time.Sleep(wait)
    70  
    71  			var currentState string
    72  			result, currentState, err = conf.Refresh()
    73  			if err != nil {
    74  				resulterr = err
    75  				return
    76  			}
    77  
    78  			// If we're waiting for the absence of a thing, then return
    79  			if result == nil && conf.Target == "" {
    80  				return
    81  			}
    82  
    83  			if result == nil {
    84  				// If we didn't find the resource, check if we have been
    85  				// not finding it for awhile, and if so, report an error.
    86  				notfoundTick += 1
    87  				if notfoundTick > conf.NotFoundChecks {
    88  					resulterr = errors.New("couldn't find resource")
    89  					return
    90  				}
    91  			} else {
    92  				// Reset the counter for when a resource isn't found
    93  				notfoundTick = 0
    94  
    95  				if currentState == conf.Target {
    96  					return
    97  				}
    98  
    99  				found := false
   100  				for _, allowed := range conf.Pending {
   101  					if currentState == allowed {
   102  						found = true
   103  						break
   104  					}
   105  				}
   106  
   107  				if !found {
   108  					resulterr = fmt.Errorf(
   109  						"unexpected state '%s', wanted target '%s'",
   110  						currentState,
   111  						conf.Target)
   112  					return
   113  				}
   114  			}
   115  		}
   116  	}()
   117  
   118  	select {
   119  	case <-doneCh:
   120  		return result, resulterr
   121  	case <-time.After(conf.Timeout):
   122  		return nil, fmt.Errorf(
   123  			"timeout while waiting for state to become '%s'",
   124  			conf.Target)
   125  	}
   126  }