github.com/interconnectedcloud/qdr-operator@v0.0.0-20210826174505-576d2b33dac7/test/e2e/framework/retry_util.go (about)

     1  // Copyright 2019 The Interconnectedcloud Authors
     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 framework
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"time"
    21  )
    22  
    23  type RetryError struct {
    24  	n int
    25  }
    26  
    27  func (e *RetryError) Error() string {
    28  	return fmt.Sprintf("still failing after %d retries", e.n)
    29  }
    30  
    31  func IsRetryFailure(err error) bool {
    32  	_, ok := err.(*RetryError)
    33  	return ok
    34  }
    35  
    36  type ConditionFunc func() (bool, error)
    37  
    38  // Retry retries f every interval until after maxRetries.
    39  // The interval won't be affected by how long f takes.
    40  // For example, if interval is 3s, f takes 1s, another f will be called 2s later.
    41  // However, if f takes longer than interval, it will be delayed.
    42  func Retry(interval time.Duration, maxRetries int, f ConditionFunc) error {
    43  	if maxRetries <= 0 {
    44  		return fmt.Errorf("maxRetries (%d) should be > 0", maxRetries)
    45  	}
    46  	tick := time.NewTicker(interval)
    47  	defer tick.Stop()
    48  
    49  	for i := 0; ; i++ {
    50  		ok, err := f()
    51  		if err != nil {
    52  			return err
    53  		}
    54  		if ok {
    55  			return nil
    56  		}
    57  		if i == maxRetries {
    58  			break
    59  		}
    60  		<-tick.C
    61  	}
    62  	return &RetryError{maxRetries}
    63  }
    64  
    65  // RetryWithContext retries f every interval until the specified context times out.
    66  func RetryWithContext(ctx context.Context, interval time.Duration, f ConditionFunc) error {
    67  	tick := time.NewTicker(interval)
    68  	defer tick.Stop()
    69  
    70  	for {
    71  		select {
    72  		case <-ctx.Done():
    73  			return fmt.Errorf("the context timeout has been reached")
    74  		case <-tick.C:
    75  			r, err := f()
    76  			if err != nil {
    77  				return err
    78  			}
    79  			if r {
    80  				return nil
    81  			}
    82  		}
    83  	}
    84  }