util.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2016 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 unversioned
  14. import (
  15. "time"
  16. "k8s.io/kubernetes/pkg/api/errors"
  17. "k8s.io/kubernetes/pkg/util/wait"
  18. )
  19. // DefaultRetry is the recommended retry for a conflict where multiple clients
  20. // are making changes to the same resource.
  21. var DefaultRetry = wait.Backoff{
  22. Steps: 5,
  23. Duration: 10 * time.Millisecond,
  24. Factor: 1.0,
  25. Jitter: 0.1,
  26. }
  27. // DefaultBackoff is the recommended backoff for a conflict where a client
  28. // may be attempting to make an unrelated modification to a resource under
  29. // active management by one or more controllers.
  30. var DefaultBackoff = wait.Backoff{
  31. Steps: 4,
  32. Duration: 10 * time.Millisecond,
  33. Factor: 5.0,
  34. Jitter: 0.1,
  35. }
  36. // RetryConflict executes the provided function repeatedly, retrying if the server returns a conflicting
  37. // write. Callers should preserve previous executions if they wish to retry changes. It performs an
  38. // exponential backoff.
  39. //
  40. // var pod *api.Pod
  41. // err := RetryOnConflict(DefaultBackoff, func() (err error) {
  42. // pod, err = c.Pods("mynamespace").UpdateStatus(podStatus)
  43. // return
  44. // })
  45. // if err != nil {
  46. // // may be conflict if max retries were hit
  47. // return err
  48. // }
  49. // ...
  50. //
  51. // TODO: Make Backoff an interface?
  52. func RetryOnConflict(backoff wait.Backoff, fn func() error) error {
  53. var lastConflictErr error
  54. err := wait.ExponentialBackoff(backoff, func() (bool, error) {
  55. err := fn()
  56. switch {
  57. case err == nil:
  58. return true, nil
  59. case errors.IsConflict(err):
  60. lastConflictErr = err
  61. return false, nil
  62. default:
  63. return false, err
  64. }
  65. })
  66. if err == wait.ErrWaitTimeout {
  67. err = lastConflictErr
  68. }
  69. return err
  70. }