github.com/coreos/mantle@v0.13.0/util/retry.go (about)

     1  // Copyright 2015 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"fmt"
    19  	"time"
    20  )
    21  
    22  // Retry calls function f until it has been called attemps times, or succeeds.
    23  // Retry delays for delay between calls of f. If f does not succeed after
    24  // attempts calls, the error from the last call is returned.
    25  func Retry(attempts int, delay time.Duration, f func() error) error {
    26  	return RetryConditional(attempts, delay, func(_ error) bool { return true }, f)
    27  }
    28  
    29  // RetryConditional calls function f until it has been called attemps times, or succeeds.
    30  // Retry delays for delay between calls of f. If f does not succeed after
    31  // attempts calls, the error from the last call is returned.
    32  // If shouldRetry returns false on the error generated, RetryConditional stops immediately
    33  // and returns the error
    34  func RetryConditional(attempts int, delay time.Duration, shouldRetry func(err error) bool, f func() error) error {
    35  	var err error
    36  
    37  	for i := 0; i < attempts; i++ {
    38  		err = f()
    39  		if err == nil || !shouldRetry(err) {
    40  			break
    41  		}
    42  
    43  		if i < attempts-1 {
    44  			time.Sleep(delay)
    45  		}
    46  	}
    47  
    48  	return err
    49  }
    50  
    51  func WaitUntilReady(timeout, delay time.Duration, checkFunction func() (bool, error)) error {
    52  	after := time.After(timeout)
    53  	for {
    54  		select {
    55  		case <-after:
    56  			return fmt.Errorf("time limit exceeded")
    57  		default:
    58  		}
    59  
    60  		time.Sleep(delay)
    61  
    62  		done, err := checkFunction()
    63  		if err != nil {
    64  			return err
    65  		}
    66  
    67  		if done {
    68  			break
    69  		}
    70  	}
    71  	return nil
    72  }