Debian Codegraph @

tools/watch/retrywatcher.go

raw symbols SCIP
1 /*
2 Copyright 2017 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 watch
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "io"
24 "net/http"
25 "time"
26
27 apierrors "k8s.io/apimachinery/pkg/api/errors"
28 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
29 "k8s.io/apimachinery/pkg/util/dump"
30 "k8s.io/apimachinery/pkg/util/net"
31 "k8s.io/apimachinery/pkg/util/wait"
32 "k8s.io/apimachinery/pkg/watch"
33 "k8s.io/client-go/tools/cache"
34 "k8s.io/klog/v2"
35 )
36
37 // resourceVersionGetter is an interface used to get resource version from events.
38 // We can't reuse an interface from meta otherwise it would be a cyclic dependency and we need just this one method
39 type resourceVersionGetter interface {
40 GetResourceVersion() string
41 }
42
43 // RetryWatcher will make sure that in case the underlying watcher is closed (e.g. due to API timeout or etcd timeout)
44 // it will get restarted from the last point without the consumer even knowing about it.
45 // RetryWatcher does that by inspecting events and keeping track of resourceVersion.
46 // Especially useful when using watch.UntilWithoutRetry where premature termination is causing issues and flakes.
47 // Please note that this is not resilient to etcd cache not having the resource version anymore - you would need to
48 // use Informers for that.
49 type RetryWatcher struct {
50 cancel func(error)
51 lastResourceVersion string
52 watcherClient cache.WatcherWithContext
53 resultChan chan watch.Event
54 doneChan chan struct{}
55 minRestartDelay time.Duration
56 }
57
58 // NewRetryWatcher creates a new RetryWatcher.
59 // It will make sure that watches gets restarted in case of recoverable errors.
60 // The initialResourceVersion will be given to watch method when first called.
61 //
62 // Deprecated: use NewRetryWatcherWithContext instead.
63 func NewRetryWatcher(initialResourceVersion string, watcherClient cache.Watcher) (*RetryWatcher, error) {
64 return NewRetryWatcherWithContext(context.Background(), initialResourceVersion, cache.ToWatcherWithContext(watcherClient))
65 }
66
67 // NewRetryWatcherWithContext creates a new RetryWatcher.
68 // It will make sure that watches gets restarted in case of recoverable errors.
69 // The initialResourceVersion will be given to watch method when first called.
70 func NewRetryWatcherWithContext(ctx context.Context, initialResourceVersion string, watcherClient cache.WatcherWithContext) (*RetryWatcher, error) {
71 return newRetryWatcher(ctx, initialResourceVersion, watcherClient, 1*time.Second)
72 }
73
74 func newRetryWatcher(ctx context.Context, initialResourceVersion string, watcherClient cache.WatcherWithContext, minRestartDelay time.Duration) (*RetryWatcher, error) {
75 switch initialResourceVersion {
76 case "", "0":
77 // TODO: revisit this if we ever get WATCH v2 where it means start "now"
78 // without doing the synthetic list of objects at the beginning (see #74022)
79 return nil, fmt.Errorf("initial RV %q is not supported due to issues with underlying WATCH", initialResourceVersion)
80 default:
81 break
82 }
83
84 ctx, cancel := context.WithCancelCause(ctx)
85
86 rw := &RetryWatcher{
87 cancel: cancel,
88 lastResourceVersion: initialResourceVersion,
89 watcherClient: watcherClient,
90 doneChan: make(chan struct{}),
91 resultChan: make(chan watch.Event, 0),
92 minRestartDelay: minRestartDelay,
93 }
94
95 go rw.receive(ctx)
96 return rw, nil
97 }
98
99 func (rw *RetryWatcher) send(ctx context.Context, event watch.Event) bool {
100 // Writing to an unbuffered channel is blocking operation
101 // and we need to check if stop wasn't requested while doing so.
102 select {
103 case rw.resultChan <- event:
104 return true
105 case <-ctx.Done():
106 return false
107 }
108 }
109
110 // doReceive returns true when it is done, false otherwise.
111 // If it is not done the second return value holds the time to wait before calling it again.
112 func (rw *RetryWatcher) doReceive(ctx context.Context) (bool, time.Duration) {
113 watcher, err := rw.watcherClient.WatchWithContext(ctx, metav1.ListOptions{
114 ResourceVersion: rw.lastResourceVersion,
115 AllowWatchBookmarks: true,
116 })
117 // We are very unlikely to hit EOF here since we are just establishing the call,
118 // but it may happen that the apiserver is just shutting down (e.g. being restarted)
119 // This is consistent with how it is handled for informers
120 switch err {
121 case nil:
122 break
123
124 case io.EOF:
125 // watch closed normally
126 return false, 0
127
128 case io.ErrUnexpectedEOF:
129 klog.FromContext(ctx).V(1).Info("Watch closed with unexpected EOF", "err", err)
130 return false, 0
131
132 default:
133 msg := "Watch failed"
134 if net.IsProbableEOF(err) || net.IsTimeout(err) {
135 klog.FromContext(ctx).V(5).Info(msg, "err", err)
136 // Retry
137 return false, 0
138 }
139
140 // Check if the watch failed due to the client not having permission to watch the resource or the credentials
141 // being invalid (e.g. expired token).
142 if apierrors.IsForbidden(err) || apierrors.IsUnauthorized(err) {
143 // Add more detail since the forbidden message returned by the Kubernetes API is just "unknown".
144 klog.FromContext(ctx).Error(err, msg+": ensure the client has valid credentials and watch permissions on the resource")
145
146 if apiStatus, ok := err.(apierrors.APIStatus); ok {
147 statusErr := apiStatus.Status()
148
149 sent := rw.send(ctx, watch.Event{
150 Type: watch.Error,
151 Object: &statusErr,
152 })
153 if !sent {
154 // This likely means the RetryWatcher is stopping but return false so the caller to doReceive can
155 // verify this and potentially retry.
156 klog.FromContext(ctx).Error(nil, "Failed to send the Unauthorized or Forbidden watch event")
157
158 return false, 0
159 }
160 } else {
161 // This should never happen since apierrors only handles apierrors.APIStatus. Still, this is an
162 // unrecoverable error, so still allow it to return true below.
163 klog.FromContext(ctx).Error(err, msg+": encountered an unexpected Unauthorized or Forbidden error type")
164 }
165
166 return true, 0
167 }
168
169 klog.FromContext(ctx).Error(err, msg)
170 // Retry
171 return false, 0
172 }
173
174 if watcher == nil {
175 klog.FromContext(ctx).Error(nil, "Watch returned nil watcher")
176 // Retry
177 return false, 0
178 }
179
180 ch := watcher.ResultChan()
181 defer watcher.Stop()
182
183 for {
184 select {
185 case <-ctx.Done():
186 klog.FromContext(ctx).V(4).Info("Stopping RetryWatcher")
187 return true, 0
188 case event, ok := <-ch:
189 if !ok {
190 klog.FromContext(ctx).V(4).Info("Failed to get event - re-creating the watcher", "resourceVersion", rw.lastResourceVersion)
191 return false, 0
192 }
193
194 // We need to inspect the event and get ResourceVersion out of it
195 switch event.Type {
196 case watch.Added, watch.Modified, watch.Deleted, watch.Bookmark:
197 metaObject, ok := event.Object.(resourceVersionGetter)
198 if !ok {
199 _ = rw.send(ctx, watch.Event{
200 Type: watch.Error,
201 Object: &apierrors.NewInternalError(errors.New("retryWatcher: doesn't support resourceVersion")).ErrStatus,
202 })
203 // We have to abort here because this might cause lastResourceVersion inconsistency by skipping a potential RV with valid data!
204 return true, 0
205 }
206
207 resourceVersion := metaObject.GetResourceVersion()
208 if resourceVersion == "" {
209 _ = rw.send(ctx, watch.Event{
210 Type: watch.Error,
211 Object: &apierrors.NewInternalError(fmt.Errorf("retryWatcher: object %#v doesn't support resourceVersion", event.Object)).ErrStatus,
212 })
213 // We have to abort here because this might cause lastResourceVersion inconsistency by skipping a potential RV with valid data!
214 return true, 0
215 }
216
217 // All is fine; send the non-bookmark events and update resource version.
218 if event.Type != watch.Bookmark {
219 ok = rw.send(ctx, event)
220 if !ok {
221 return true, 0
222 }
223 }
224 rw.lastResourceVersion = resourceVersion
225
226 continue
227
228 case watch.Error:
229 // This round trip allows us to handle unstructured status
230 errObject := apierrors.FromObject(event.Object)
231 statusErr, ok := errObject.(*apierrors.StatusError)
232 if !ok {
233 klog.FromContext(ctx).Error(nil, "Received an error which is not *metav1.Status", "errorObject", dump.Pretty(event.Object))
234 // Retry unknown errors
235 return false, 0
236 }
237
238 status := statusErr.ErrStatus
239
240 statusDelay := time.Duration(0)
241 if status.Details != nil {
242 statusDelay = time.Duration(status.Details.RetryAfterSeconds) * time.Second
243 }
244
245 switch status.Code {
246 case http.StatusGone:
247 // Never retry RV too old errors
248 _ = rw.send(ctx, event)
249 return true, 0
250
251 case http.StatusGatewayTimeout, http.StatusInternalServerError:
252 // Retry
253 return false, statusDelay
254
255 default:
256 // We retry by default. RetryWatcher is meant to proceed unless it is certain
257 // that it can't. If we are not certain, we proceed with retry and leave it
258 // up to the user to timeout if needed.
259
260 // Log here so we have a record of hitting the unexpected error
261 // and we can whitelist some error codes if we missed any that are expected.
262 klog.FromContext(ctx).V(5).Info("Retrying after unexpected error", "errorObject", dump.Pretty(event.Object))
263
264 // Retry
265 return false, statusDelay
266 }
267
268 default:
269 klog.FromContext(ctx).Error(nil, "Failed to recognize event", "type", event.Type)
270 _ = rw.send(ctx, watch.Event{
271 Type: watch.Error,
272 Object: &apierrors.NewInternalError(fmt.Errorf("retryWatcher failed to recognize Event type %q", event.Type)).ErrStatus,
273 })
274 // We are unable to restart the watch and have to stop the loop or this might cause lastResourceVersion inconsistency by skipping a potential RV with valid data!
275 return true, 0
276 }
277 }
278 }
279 }
280
281 // receive reads the result from a watcher, restarting it if necessary.
282 func (rw *RetryWatcher) receive(ctx context.Context) {
283 defer close(rw.doneChan)
284 defer close(rw.resultChan)
285
286 logger := klog.FromContext(ctx)
287 logger.V(4).Info("Starting RetryWatcher")
288 defer logger.V(4).Info("Stopping RetryWatcher")
289
290 ctx, cancel := context.WithCancel(ctx)
291 defer cancel()
292
293 // We use non sliding until so we don't introduce delays on happy path when WATCH call
294 // timeouts or gets closed and we need to reestablish it while also avoiding hot loops.
295 wait.NonSlidingUntilWithContext(ctx, func(ctx context.Context) {
296 done, retryAfter := rw.doReceive(ctx)
297 if done {
298 cancel()
299 return
300 }
301
302 timer := time.NewTimer(retryAfter)
303 select {
304 case <-ctx.Done():
305 timer.Stop()
306 return
307 case <-timer.C:
308 }
309
310 logger.V(4).Info("Restarting RetryWatcher", "resourceVersion", rw.lastResourceVersion)
311 }, rw.minRestartDelay)
312 }
313
314 // ResultChan implements Interface.
315 func (rw *RetryWatcher) ResultChan() <-chan watch.Event {
316 return rw.resultChan
317 }
318
319 // Stop implements Interface.
320 func (rw *RetryWatcher) Stop() {
321 rw.cancel(errors.New("asked to stop"))
322 }
323
324 // Done allows the caller to be notified when Retry watcher stops.
325 func (rw *RetryWatcher) Done() <-chan struct{} {
326 return rw.doneChan
327 }