Debian Codegraph @

apimachinery/lease/controller.go

raw symbols SCIP
1 /*
2 Copyright 2018 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package lease
18
19 import (
20 "context"
21 "fmt"
22 "time"
23
24 coordinationv1 "k8s.io/api/coordination/v1"
25 apierrors "k8s.io/apimachinery/pkg/api/errors"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/util/wait"
28 clientset "k8s.io/client-go/kubernetes"
29 coordclientset "k8s.io/client-go/kubernetes/typed/coordination/v1"
30 "k8s.io/utils/clock"
31 "k8s.io/utils/pointer"
32
33 "k8s.io/klog/v2"
34 )
35
36 const (
37 // maxUpdateRetries is the number of immediate, successive retries the controller will attempt
38 // when renewing the lease before it waits for the renewal interval before trying again,
39 // similar to what we do for node status retries
40 maxUpdateRetries = 5
41 // maxBackoff is the maximum sleep time during backoff (e.g. in backoffEnsureLease)
42 maxBackoff = 7 * time.Second
43 )
44
45 // Controller manages creating and renewing the lease for this component (kube-apiserver, kubelet, etc.)
46 type Controller interface {
47 Run(ctx context.Context)
48 }
49
50 // ProcessLeaseFunc processes the given lease in-place
51 type ProcessLeaseFunc func(*coordinationv1.Lease) error
52
53 type controller struct {
54 client clientset.Interface
55 leaseClient coordclientset.LeaseInterface
56 holderIdentity string
57 leaseName string
58 leaseNamespace string
59 leaseDurationSeconds int32
60 renewInterval time.Duration
61 clock clock.Clock
62 onRepeatedHeartbeatFailure func()
63
64 // latestLease is the latest lease which the controller updated or created
65 latestLease *coordinationv1.Lease
66
67 // newLeasePostProcessFunc allows customizing a lease object (e.g. setting OwnerReference)
68 // before every time the lease is created/refreshed(updated).
69 // Note that an error will block the lease operation.
70 newLeasePostProcessFunc ProcessLeaseFunc
71 }
72
73 // NewController constructs and returns a controller
74 func NewController(clock clock.Clock, client clientset.Interface, holderIdentity string, leaseDurationSeconds int32, onRepeatedHeartbeatFailure func(), renewInterval time.Duration, leaseName, leaseNamespace string, newLeasePostProcessFunc ProcessLeaseFunc) Controller {
75 var leaseClient coordclientset.LeaseInterface
76 if client != nil {
77 leaseClient = client.CoordinationV1().Leases(leaseNamespace)
78 }
79 return &controller{
80 client: client,
81 leaseClient: leaseClient,
82 holderIdentity: holderIdentity,
83 leaseName: leaseName,
84 leaseNamespace: leaseNamespace,
85 leaseDurationSeconds: leaseDurationSeconds,
86 renewInterval: renewInterval,
87 clock: clock,
88 onRepeatedHeartbeatFailure: onRepeatedHeartbeatFailure,
89 newLeasePostProcessFunc: newLeasePostProcessFunc,
90 }
91 }
92
93 // Run runs the controller
94 func (c *controller) Run(ctx context.Context) {
95 if c.leaseClient == nil {
96 klog.FromContext(ctx).Info("lease controller has nil lease client, will not claim or renew leases")
97 return
98 }
99 wait.JitterUntilWithContext(ctx, c.sync, c.renewInterval, 0.04, true)
100 }
101
102 func (c *controller) sync(ctx context.Context) {
103 if c.latestLease != nil {
104 // As long as the lease is not (or very rarely) updated by any other agent than the component itself,
105 // we can optimistically assume it didn't change since our last update and try updating
106 // based on the version from that time. Thanks to it we avoid GET call and reduce load
107 // on etcd and kube-apiserver.
108 // If at some point other agents will also be frequently updating the Lease object, this
109 // can result in performance degradation, because we will end up with calling additional
110 // GET/PUT - at this point this whole "if" should be removed.
111 err := c.retryUpdateLease(ctx, c.latestLease)
112 if err == nil {
113 return
114 }
115 klog.FromContext(ctx).Info("failed to update lease using latest lease, fallback to ensure lease", "err", err)
116 }
117
118 lease, created := c.backoffEnsureLease(ctx)
119 c.latestLease = lease
120 // we don't need to update the lease if we just created it
121 if !created && lease != nil {
122 if err := c.retryUpdateLease(ctx, lease); err != nil {
123 klog.FromContext(ctx).Error(err, "Will retry updating lease", "interval", c.renewInterval)
124 }
125 }
126 }
127
128 // backoffEnsureLease attempts to create the lease if it does not exist,
129 // and uses exponentially increasing waits to prevent overloading the API server
130 // with retries. Returns the lease, and true if this call created the lease,
131 // false otherwise.
132 func (c *controller) backoffEnsureLease(ctx context.Context) (*coordinationv1.Lease, bool) {
133 var (
134 lease *coordinationv1.Lease
135 created bool
136 err error
137 )
138 sleep := 100 * time.Millisecond
139 for {
140 lease, created, err = c.ensureLease(ctx)
141 if err == nil {
142 break
143 }
144 sleep = minDuration(2*sleep, maxBackoff)
145 klog.FromContext(ctx).Error(err, "Failed to ensure lease exists, will retry", "interval", sleep)
146 // backoff wait with early return if the context gets canceled
147 select {
148 case <-ctx.Done():
149 return nil, false
150 case <-time.After(sleep):
151 }
152 }
153 return lease, created
154 }
155
156 // ensureLease creates the lease if it does not exist. Returns the lease and
157 // a bool (true if this call created the lease), or any error that occurs.
158 func (c *controller) ensureLease(ctx context.Context) (*coordinationv1.Lease, bool, error) {
159 lease, err := c.leaseClient.Get(ctx, c.leaseName, metav1.GetOptions{})
160 if apierrors.IsNotFound(err) {
161 // lease does not exist, create it.
162 leaseToCreate, err := c.newLease(nil)
163 // An error occurred during allocating the new lease (likely from newLeasePostProcessFunc).
164 // Given that we weren't able to set the lease correctly, we simply
165 // not create it this time - we will retry in the next iteration.
166 if err != nil {
167 return nil, false, nil
168 }
169 lease, err := c.leaseClient.Create(ctx, leaseToCreate, metav1.CreateOptions{})
170 if err != nil {
171 return nil, false, err
172 }
173 return lease, true, nil
174 } else if err != nil {
175 // unexpected error getting lease
176 return nil, false, err
177 }
178 // lease already existed
179 return lease, false, nil
180 }
181
182 // retryUpdateLease attempts to update the lease for maxUpdateRetries,
183 // call this once you're sure the lease has been created
184 func (c *controller) retryUpdateLease(ctx context.Context, base *coordinationv1.Lease) error {
185 for i := 0; i < maxUpdateRetries; i++ {
186 leaseToUpdate, err := c.newLease(base)
187 if err != nil {
188 klog.FromContext(ctx).Error(err, "Failed to prepare lease")
189 } else {
190 lease, err := c.leaseClient.Update(ctx, leaseToUpdate, metav1.UpdateOptions{})
191 if err == nil {
192 c.latestLease = lease
193 return nil
194 }
195 klog.FromContext(ctx).Error(err, "Failed to update lease")
196 // OptimisticLockError requires getting the newer version of lease to proceed.
197 if apierrors.IsConflict(err) {
198 base, _ = c.backoffEnsureLease(ctx)
199 continue
200 }
201 }
202 if i > 0 && c.onRepeatedHeartbeatFailure != nil {
203 c.onRepeatedHeartbeatFailure()
204 }
205 }
206 return fmt.Errorf("failed %d attempts to update lease", maxUpdateRetries)
207 }
208
209 // newLease constructs a new lease if base is nil, or returns a copy of base
210 // with desired state asserted on the copy.
211 // Note that an error will block lease CREATE, causing the CREATE to be retried in
212 // the next iteration; but the error won't block lease refresh (UPDATE).
213 func (c *controller) newLease(base *coordinationv1.Lease) (*coordinationv1.Lease, error) {
214 // Use the bare minimum set of fields; other fields exist for debugging/legacy,
215 // but we don't need to make component heartbeats more complicated by using them.
216 var lease *coordinationv1.Lease
217 if base == nil {
218 lease = &coordinationv1.Lease{
219 ObjectMeta: metav1.ObjectMeta{
220 Name: c.leaseName,
221 Namespace: c.leaseNamespace,
222 },
223 Spec: coordinationv1.LeaseSpec{
224 HolderIdentity: pointer.StringPtr(c.holderIdentity),
225 LeaseDurationSeconds: pointer.Int32Ptr(c.leaseDurationSeconds),
226 },
227 }
228 } else {
229 lease = base.DeepCopy()
230 }
231 lease.Spec.RenewTime = &metav1.MicroTime{Time: c.clock.Now()}
232
233 if c.newLeasePostProcessFunc != nil {
234 err := c.newLeasePostProcessFunc(lease)
235 return lease, err
236 }
237
238 return lease, nil
239 }
240
241 func minDuration(a, b time.Duration) time.Duration {
242 if a < b {
243 return a
244 }
245 return b
246 }