retry.go 1.4 KB

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