1/*
2Copyright 2016 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package retry
18
19import (
20	"time"
21
22	"k8s.io/apimachinery/pkg/api/errors"
23	"k8s.io/apimachinery/pkg/util/wait"
24)
25
26// DefaultRetry is the recommended retry for a conflict where multiple clients
27// are making changes to the same resource.
28var DefaultRetry = wait.Backoff{
29	Steps:    5,
30	Duration: 10 * time.Millisecond,
31	Factor:   1.0,
32	Jitter:   0.1,
33}
34
35// DefaultBackoff is the recommended backoff for a conflict where a client
36// may be attempting to make an unrelated modification to a resource under
37// active management by one or more controllers.
38var DefaultBackoff = wait.Backoff{
39	Steps:    4,
40	Duration: 10 * time.Millisecond,
41	Factor:   5.0,
42	Jitter:   0.1,
43}
44
45// RetryConflict executes the provided function repeatedly, retrying if the server returns a conflicting
46// write. Callers should preserve previous executions if they wish to retry changes. It performs an
47// exponential backoff.
48//
49//     var pod *api.Pod
50//     err := RetryOnConflict(DefaultBackoff, func() (err error) {
51//       pod, err = c.Pods("mynamespace").UpdateStatus(podStatus)
52//       return
53//     })
54//     if err != nil {
55//       // may be conflict if max retries were hit
56//       return err
57//     }
58//     ...
59//
60// TODO: Make Backoff an interface?
61func RetryOnConflict(backoff wait.Backoff, fn func() error) error {
62	var lastConflictErr error
63	err := wait.ExponentialBackoff(backoff, func() (bool, error) {
64		err := fn()
65		switch {
66		case err == nil:
67			return true, nil
68		case errors.IsConflict(err):
69			lastConflictErr = err
70			return false, nil
71		default:
72			return false, err
73		}
74	})
75	if err == wait.ErrWaitTimeout {
76		err = lastConflictErr
77	}
78	return err
79}
80