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.

96 lines
1.8 KiB

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