yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/cloudprovider/retry.go (about)

     1  // Copyright 2019 Yunion
     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 cloudprovider
    16  
    17  import (
    18  	"strings"
    19  	"time"
    20  )
    21  
    22  func IsError(err error, errs []string) bool {
    23  	for i := range errs {
    24  		if strings.Index(err.Error(), errs[i]) >= 0 {
    25  			return true
    26  		}
    27  	}
    28  	return false
    29  }
    30  
    31  func RetryOnError(tryFunc func() error, errs []string, maxTries int) error {
    32  	tried := 0
    33  	for tried < maxTries {
    34  		err := tryFunc()
    35  		if err == nil {
    36  			return nil
    37  		}
    38  		if err != nil && !IsError(err, errs) {
    39  			return err
    40  		}
    41  		tried += 1
    42  		time.Sleep(10 * time.Duration(tried) * time.Second)
    43  	}
    44  	return ErrTimeout
    45  }
    46  
    47  func RetryUntil(tryFunc func() (bool, error), maxTries int) error {
    48  	tried := 0
    49  	for tried < maxTries {
    50  		stop, err := tryFunc()
    51  		if stop {
    52  			return nil
    53  		}
    54  		if err != nil {
    55  			return err
    56  		}
    57  		tried += 1
    58  		time.Sleep(10 * time.Duration(tried) * time.Second)
    59  	}
    60  	return ErrTimeout
    61  }