2014-07-01 03:03:27 +02:00
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2014-10-08 06:44:51 +02:00
|
|
|
// RetryFunc is the function retried until it succeeds.
|
|
|
|
type RetryFunc func() error
|
|
|
|
|
|
|
|
// Retry is a basic wrapper around StateChangeConf that will just retry
|
|
|
|
// a function until it no longer returns an error.
|
|
|
|
func Retry(timeout time.Duration, f RetryFunc) error {
|
|
|
|
var err error
|
|
|
|
c := &StateChangeConf{
|
|
|
|
Pending: []string{"error"},
|
|
|
|
Target: "success",
|
|
|
|
Timeout: timeout,
|
|
|
|
MinTimeout: 500 * time.Millisecond,
|
|
|
|
Refresh: func() (interface{}, string, error) {
|
|
|
|
err = f()
|
2014-10-18 03:28:03 +02:00
|
|
|
if err == nil {
|
|
|
|
return 42, "success", nil
|
2014-07-08 00:21:54 +02:00
|
|
|
}
|
|
|
|
|
2014-10-18 03:28:03 +02:00
|
|
|
if rerr, ok := err.(RetryError); ok {
|
|
|
|
err = rerr.Err
|
|
|
|
return nil, "quit", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return 42, "error", nil
|
2014-10-08 06:44:51 +02:00
|
|
|
},
|
2014-07-01 03:03:27 +02:00
|
|
|
}
|
2014-10-08 06:44:51 +02:00
|
|
|
|
|
|
|
c.WaitForState()
|
|
|
|
return err
|
2014-07-01 03:03:27 +02:00
|
|
|
}
|
2014-10-18 03:28:03 +02:00
|
|
|
|
|
|
|
// RetryError, if returned, will quit the retry immediately with the
|
|
|
|
// Err.
|
|
|
|
type RetryError struct {
|
|
|
|
Err error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e RetryError) Error() string {
|
|
|
|
return e.Err.Error()
|
|
|
|
}
|