retry.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. waitTime = time.Second
  18. break
  19. }
  20. if strings.Contains(err.Error(), "transport") {
  21. hasErr = true
  22. glog.V(0).Infof("retry %s: err: %v", name, err)
  23. } else {
  24. break
  25. }
  26. time.Sleep(waitTime)
  27. waitTime += waitTime / 2
  28. }
  29. return err
  30. }
  31. func MultiRetry(name string, errList []string, job func() error) (err error) {
  32. waitTime := time.Second
  33. hasErr := false
  34. for waitTime < RetryWaitTime {
  35. err = job()
  36. if err == nil {
  37. if hasErr {
  38. glog.V(0).Infof("retry %s successfully", name)
  39. }
  40. waitTime = time.Second
  41. break
  42. }
  43. if containErr(err.Error(), errList) {
  44. hasErr = true
  45. glog.V(0).Infof("retry %s: err: %v", name, err)
  46. } else {
  47. break
  48. }
  49. time.Sleep(waitTime)
  50. waitTime += waitTime / 2
  51. }
  52. return err
  53. }
  54. func RetryForever(name string, job func() error, onErrFn func(err error) (shouldContinue bool)) {
  55. waitTime := time.Second
  56. for {
  57. err := job()
  58. if err == nil {
  59. waitTime = time.Second
  60. break
  61. }
  62. if onErrFn(err) {
  63. if strings.Contains(err.Error(), "transport") {
  64. glog.V(0).Infof("retry %s: err: %v", name, err)
  65. }
  66. time.Sleep(waitTime)
  67. if waitTime < RetryWaitTime {
  68. waitTime += waitTime / 2
  69. }
  70. continue
  71. }
  72. }
  73. }
  74. // return the first non empty string
  75. func Nvl(values ...string) string {
  76. for _, s := range values {
  77. if s != "" {
  78. return s
  79. }
  80. }
  81. return ""
  82. }
  83. func containErr(err string, errList []string) bool {
  84. for _, e := range errList {
  85. if strings.Contains(err, e) {
  86. return true
  87. }
  88. }
  89. return false
  90. }