You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.1 KiB

4 years ago
2 years ago
3 years ago
4 years ago
  1. package util
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/seaweedfs/seaweedfs/weed/glog"
  6. )
  7. var RetryWaitTime = 6 * time.Second
  8. func Retry(name string, job func() error) (err error) {
  9. waitTime := time.Second
  10. hasErr := false
  11. for waitTime < RetryWaitTime {
  12. err = job()
  13. if err == nil {
  14. if hasErr {
  15. glog.V(0).Infof("retry %s successfully", name)
  16. }
  17. break
  18. }
  19. if strings.Contains(err.Error(), "transport") {
  20. hasErr = true
  21. glog.V(0).Infof("retry %s: err: %v", name, err)
  22. } else {
  23. break
  24. }
  25. time.Sleep(waitTime)
  26. waitTime += waitTime / 2
  27. }
  28. return err
  29. }
  30. func RetryForever(name string, job func() error, onErrFn func(err error) (shouldContinue bool)) {
  31. waitTime := time.Second
  32. for {
  33. err := job()
  34. if err == nil {
  35. waitTime = time.Second
  36. break
  37. }
  38. if onErrFn(err) {
  39. if strings.Contains(err.Error(), "transport") {
  40. glog.V(0).Infof("retry %s: err: %v", name, err)
  41. }
  42. time.Sleep(waitTime)
  43. if waitTime < RetryWaitTime {
  44. waitTime += waitTime / 2
  45. }
  46. continue
  47. }
  48. }
  49. }
  50. // return the first non empty string
  51. func Nvl(values ...string) string {
  52. for _, s := range values {
  53. if s != "" {
  54. return s
  55. }
  56. }
  57. return ""
  58. }