timeout.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ipam
  14. import (
  15. "time"
  16. )
  17. // Timeout manages the resync loop timing for a given node sync operation. The
  18. // timeout changes depending on whether or not there was an error reported for
  19. // the operation. Consecutive errors will result in exponential backoff to a
  20. // maxBackoff timeout.
  21. type Timeout struct {
  22. // Resync is the default timeout duration when there are no errors.
  23. Resync time.Duration
  24. // MaxBackoff is the maximum timeout when in a error backoff state.
  25. MaxBackoff time.Duration
  26. // InitialRetry is the initial retry interval when an error is reported.
  27. InitialRetry time.Duration
  28. // errs is the count of consecutive errors that have occurred.
  29. errs int
  30. // current is the current backoff timeout.
  31. current time.Duration
  32. }
  33. // Update the timeout with the current error state.
  34. func (b *Timeout) Update(ok bool) {
  35. if ok {
  36. b.errs = 0
  37. b.current = b.Resync
  38. return
  39. }
  40. b.errs++
  41. if b.errs == 1 {
  42. b.current = b.InitialRetry
  43. return
  44. }
  45. b.current *= 2
  46. if b.current >= b.MaxBackoff {
  47. b.current = b.MaxBackoff
  48. }
  49. }
  50. // Next returns the next operation timeout given the disposition of err.
  51. func (b *Timeout) Next() time.Duration {
  52. if b.errs == 0 {
  53. return b.Resync
  54. }
  55. return b.current
  56. }