Merge pull request #5460 from hashicorp/phinze/resource-retry-retval

helper/resource: restore retval of resource.Retry on timeout
This commit is contained in:
Paul Hinze 2016-03-07 15:27:36 -06:00
commit d8a072cfa2
1 changed files with 18 additions and 4 deletions

View File

@ -1,6 +1,7 @@
package resource package resource
import ( import (
"sync"
"time" "time"
) )
@ -10,6 +11,11 @@ type RetryFunc func() error
// Retry is a basic wrapper around StateChangeConf that will just retry // Retry is a basic wrapper around StateChangeConf that will just retry
// a function until it no longer returns an error. // a function until it no longer returns an error.
func Retry(timeout time.Duration, f RetryFunc) error { func Retry(timeout time.Duration, f RetryFunc) error {
// These are used to pull the error out of the function; need a mutex to
// avoid a data race.
var resultErr error
var resultErrMu sync.Mutex
c := &StateChangeConf{ c := &StateChangeConf{
Pending: []string{"error"}, Pending: []string{"error"},
Target: []string{"success"}, Target: []string{"success"},
@ -21,17 +27,25 @@ func Retry(timeout time.Duration, f RetryFunc) error {
return 42, "success", nil return 42, "success", nil
} }
resultErrMu.Lock()
defer resultErrMu.Unlock()
resultErr = err
if rerr, ok := err.(RetryError); ok { if rerr, ok := err.(RetryError); ok {
err = rerr.Err resultErr = rerr.Err
return nil, "quit", err return nil, "quit", rerr.Err
} }
return 42, "error", nil return 42, "error", nil
}, },
} }
_, err := c.WaitForState() c.WaitForState()
return err
// Need to acquire the lock here to be able to avoid race using resultErr as
// the return value
resultErrMu.Lock()
defer resultErrMu.Unlock()
return resultErr
} }
// RetryError, if returned, will quit the retry immediately with the // RetryError, if returned, will quit the retry immediately with the