-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
revision_backends.go
494 lines (430 loc) · 15.7 KB
/
revision_backends.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
corev1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
endpointsinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/endpoints"
serviceinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/service"
"knative.dev/pkg/controller"
"knative.dev/pkg/logging"
"knative.dev/pkg/logging/logkey"
"knative.dev/pkg/network/prober"
"knative.dev/pkg/reconciler"
"knative.dev/serving/pkg/apis/networking"
"knative.dev/serving/pkg/apis/serving"
revisioninformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/revision"
servinglisters "knative.dev/serving/pkg/client/listers/serving/v1"
"knative.dev/serving/pkg/network"
"knative.dev/serving/pkg/queue"
)
// revisionDestsUpdate contains the state of healthy l4 dests for talking to a revision and is the
// primary output from the RevisionBackendsManager system. If a healthy ClusterIP is found then
// ClusterIPDest will be set to non empty string and Dests will be nil. Otherwise Dests will be set
// to a slice of healthy l4 dests for reaching the revision.
type revisionDestsUpdate struct {
Rev types.NamespacedName
ClusterIPDest string
Dests sets.String
}
type dests struct {
ready sets.String
notReady sets.String
}
const (
probeTimeout time.Duration = 300 * time.Millisecond
defaultProbeFrequency time.Duration = 200 * time.Millisecond
probePath = "/healthz"
)
// revisionWatcher watches the podIPs and ClusterIP of the service for a revision. It implements the logic
// to supply revisionDestsUpdate events on updateCh
type revisionWatcher struct {
stopCh <-chan struct{}
cancel context.CancelFunc
rev types.NamespacedName
protocol networking.ProtocolType
updateCh chan<- revisionDestsUpdate
done chan struct{}
// Stores the list of pods that have been successfully probed.
healthyPods sets.String
// Stores whether the service ClusterIP has been seen as healthy
clusterIPHealthy bool
transport http.RoundTripper
destsCh chan dests
serviceLister corev1listers.ServiceLister
logger *zap.SugaredLogger
// podsAddressable will be set to false if we cannot
// probe a pod directly, but its cluster IP has beeen successfully probed.
podsAddressable bool
}
func newRevisionWatcher(ctx context.Context, rev types.NamespacedName, protocol networking.ProtocolType,
updateCh chan<- revisionDestsUpdate, destsCh chan dests,
transport http.RoundTripper, serviceLister corev1listers.ServiceLister,
logger *zap.SugaredLogger) *revisionWatcher {
ctx, cancel := context.WithCancel(ctx)
return &revisionWatcher{
stopCh: ctx.Done(),
cancel: cancel,
rev: rev,
protocol: protocol,
updateCh: updateCh,
done: make(chan struct{}),
healthyPods: sets.NewString(),
transport: transport,
destsCh: destsCh,
serviceLister: serviceLister,
podsAddressable: true, // By default we presume we can talk to pods directly.
logger: logger.With(zap.String(logkey.Key, rev.String())),
}
}
func (rw *revisionWatcher) getK8sPrivateService() (*corev1.Service, error) {
selector := labels.SelectorFromSet(labels.Set{
serving.RevisionLabelKey: rw.rev.Name,
networking.ServiceTypeKey: string(networking.ServiceTypePrivate),
})
svcList, err := rw.serviceLister.Services(rw.rev.Namespace).List(selector)
if err != nil {
return nil, err
}
switch len(svcList) {
case 0:
return nil, fmt.Errorf("found no private services for revision %q", rw.rev.String())
case 1:
return svcList[0], nil
default:
return nil, fmt.Errorf("found multiple private services matching revision %v", rw.rev)
}
}
func (rw *revisionWatcher) probe(ctx context.Context, dest string) (bool, error) {
httpDest := url.URL{
Scheme: "http",
Host: dest,
Path: probePath,
}
// NOTE: changes below may require changes to testing/roundtripper.go to make unit tests passing.
return prober.Do(ctx, rw.transport, httpDest.String(),
prober.WithHeader(network.ProbeHeaderName, queue.Name),
prober.WithHeader(network.UserAgentKey, network.ActivatorUserAgent),
prober.ExpectsBody(queue.Name),
prober.ExpectsStatusCodes([]int{http.StatusOK}))
}
func (rw *revisionWatcher) getDest() (string, error) {
svc, err := rw.getK8sPrivateService()
if err != nil {
return "", err
}
if svc.Spec.ClusterIP == "" {
return "", fmt.Errorf("private service %s/%s clusterIP is nil, this should never happen", svc.ObjectMeta.Namespace, svc.ObjectMeta.Name)
}
svcPort, ok := getServicePort(rw.protocol, svc)
if !ok {
return "", fmt.Errorf("unable to find port in service %s/%s", svc.Namespace, svc.Name)
}
return net.JoinHostPort(svc.Spec.ClusterIP, strconv.Itoa(svcPort)), nil
}
func (rw *revisionWatcher) probeClusterIP(dest string) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
defer cancel()
return rw.probe(ctx, dest)
}
// probePodIPs will probe the given target Pod IPs and will return
// the ones that are successfully probed, whether the update was a no-op, or an error.
func (rw *revisionWatcher) probePodIPs(dests sets.String) (sets.String, bool, error) {
// Short circuit case where dests == healthyPods
if rw.healthyPods.Equal(dests) {
return rw.healthyPods, true /*no-op*/, nil
}
toProbe := sets.NewString()
healthy := sets.NewString()
for dest := range dests {
if rw.healthyPods.Has(dest) {
healthy.Insert(dest)
} else {
toProbe.Insert(dest)
}
}
// Short circuit case where the healthy list got effectively smaller.
if toProbe.Len() == 0 {
return healthy, false, nil
}
// Context used for our probe requests
ctx, cancel := context.WithTimeout(context.Background(), probeTimeout)
defer cancel()
var probeGroup errgroup.Group
healthyDests := make(chan string, toProbe.Len())
for dest := range toProbe {
dest := dest // Standard Go concurrency pattern.
probeGroup.Go(func() error {
ok, err := rw.probe(ctx, dest)
if ok {
healthyDests <- dest
}
return err
})
}
err := probeGroup.Wait()
close(healthyDests)
unchanged := len(healthyDests) == 0
for d := range healthyDests {
healthy.Insert(d)
}
return healthy, unchanged, err
}
func (rw *revisionWatcher) sendUpdate(clusterIP string, dests sets.String) {
select {
case <-rw.stopCh:
return
default:
rw.updateCh <- revisionDestsUpdate{Rev: rw.rev, ClusterIPDest: clusterIP, Dests: dests}
}
}
// checkDests performs probing and potentially sends a dests update. It is
// assumed this method is not called concurrently.
func (rw *revisionWatcher) checkDests(dests dests) {
if len(dests.ready) == 0 && len(dests.notReady) == 0 {
// We must have scaled down.
rw.clusterIPHealthy = false
rw.healthyPods = sets.NewString()
rw.logger.Debug("ClusterIP is no longer healthy.")
// Send update that we are now inactive (both params invalid).
rw.sendUpdate("", nil)
return
}
// If we have discovered that this revision cannot be probed directly
// do not spend time trying.
if rw.podsAddressable {
// First check the pod IPs. If we can individually address
// the Pods we should go that route, since it permits us to do
// precise load balancing in the throttler.
hs, noop, err := rw.probePodIPs(dests.ready.Union(dests.notReady))
if err != nil {
rw.logger.With(zap.Error(err)).Warnf("Failed probing: %+v", dests)
// We dont want to return here as an error still affects health states.
}
rw.logger.Debugf("Done probing, got %d healthy pods", len(hs))
if !noop {
rw.healthyPods = hs
rw.sendUpdate("" /*clusterIP*/, hs)
return
}
// no-op, and we have successfully probed at least one pod.
if len(hs) > 0 {
return
}
}
// If we failed to probe even a single pod, check the clusterIP.
// NB: We can't cache the IP address, since user might go rogue
// and delete the K8s service. We'll fix it, but the cluster IP will be different.
dest, err := rw.getDest()
if err != nil {
rw.logger.Errorw("Failed to determine service destination", zap.Error(err))
return
}
// If cluster IP is healthy and we haven't scaled down, short circuit.
if rw.clusterIPHealthy {
rw.logger.Debugf("ClusterIP %s already probed (ready backends: %d)", dest, len(dests.ready))
rw.sendUpdate(dest, dests.ready)
return
}
// If clusterIP is healthy send this update and we are done.
if ok, err := rw.probeClusterIP(dest); err != nil {
rw.logger.Errorw("Failed to probe clusterIP "+dest, zap.Error(err))
} else if ok {
// We can reach here only iff pods are not successfully individually probed
// but ClusterIP conversely has been successfully probed.
rw.podsAddressable = false
rw.logger.Debugf("ClusterIP is successfully probed: %s (ready backends: %d)", dest, len(dests.ready))
rw.clusterIPHealthy = true
rw.healthyPods = nil
rw.sendUpdate(dest, dests.ready)
}
}
func (rw *revisionWatcher) run(probeFrequency time.Duration) {
defer close(rw.done)
var dests dests
timer := time.NewTicker(probeFrequency)
defer timer.Stop()
var tickCh <-chan time.Time
for {
// If we have at least one pod and either there are pods that have not been
// successfully probed or clusterIP has not been probed (no pod addressability),
// then we want to probe on timer.
rw.logger.Debugf("Dests: %+v, healthy dests: %+v, clusterIP: %v", dests, rw.healthyPods, rw.clusterIPHealthy)
if len(dests.ready)+len(dests.notReady) > 0 && !(rw.clusterIPHealthy ||
dests.ready.Union(dests.notReady).Equal(rw.healthyPods)) {
rw.logger.Debug("Probing on timer")
tickCh = timer.C
} else {
rw.logger.Debug("Not Probing on timer")
tickCh = nil
}
select {
case <-rw.stopCh:
return
case x := <-rw.destsCh:
dests = x
case <-tickCh:
}
rw.checkDests(dests)
}
}
// revisionBackendsManager listens to revision endpoints and keeps track of healthy
// l4 dests which can be used to reach a revision
type revisionBackendsManager struct {
ctx context.Context
revisionLister servinglisters.RevisionLister
serviceLister corev1listers.ServiceLister
revisionWatchers map[types.NamespacedName]*revisionWatcher
revisionWatchersMux sync.RWMutex
updateCh chan revisionDestsUpdate
transport http.RoundTripper
logger *zap.SugaredLogger
probeFrequency time.Duration
}
// NewRevisionBackendsManager returns a new RevisionBackendsManager with default
// probe time out.
func newRevisionBackendsManager(ctx context.Context, tr http.RoundTripper) *revisionBackendsManager {
return newRevisionBackendsManagerWithProbeFrequency(ctx, tr, defaultProbeFrequency)
}
// newRevisionBackendsManagerWithProbeFrequency creates a fully spec'd RevisionBackendsManager.
func newRevisionBackendsManagerWithProbeFrequency(ctx context.Context, tr http.RoundTripper,
probeFreq time.Duration) *revisionBackendsManager {
rbm := &revisionBackendsManager{
ctx: ctx,
revisionLister: revisioninformer.Get(ctx).Lister(),
serviceLister: serviceinformer.Get(ctx).Lister(),
revisionWatchers: make(map[types.NamespacedName]*revisionWatcher),
updateCh: make(chan revisionDestsUpdate),
transport: tr,
logger: logging.FromContext(ctx),
probeFrequency: probeFreq,
}
endpointsInformer := endpointsinformer.Get(ctx)
endpointsInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: reconciler.ChainFilterFuncs(
reconciler.LabelExistsFilterFunc(serving.RevisionUID),
// We are only interested in the private services, since that is
// what is populated by the actual revision backends.
reconciler.LabelFilterFunc(networking.ServiceTypeKey, string(networking.ServiceTypePrivate), false),
),
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: rbm.endpointsUpdated,
UpdateFunc: controller.PassNew(rbm.endpointsUpdated),
DeleteFunc: rbm.endpointsDeleted,
},
})
go func() {
// updateCh can only be closed after revisionWatchers are done running
defer close(rbm.updateCh)
// Wait for cancellation
<-rbm.ctx.Done()
// Wait for all revisionWatchers to be done
rbm.revisionWatchersMux.Lock()
defer rbm.revisionWatchersMux.Unlock()
for _, rw := range rbm.revisionWatchers {
<-rw.done
}
}()
return rbm
}
// Returns channel where destination updates are sent to.
func (rbm *revisionBackendsManager) updates() <-chan revisionDestsUpdate {
return rbm.updateCh
}
func (rbm *revisionBackendsManager) getRevisionProtocol(revID types.NamespacedName) (networking.ProtocolType, error) {
revision, err := rbm.revisionLister.Revisions(revID.Namespace).Get(revID.Name)
if err != nil {
return "", err
}
return revision.GetProtocol(), nil
}
func (rbm *revisionBackendsManager) getOrCreateRevisionWatcher(rev types.NamespacedName) (*revisionWatcher, error) {
rbm.revisionWatchersMux.Lock()
defer rbm.revisionWatchersMux.Unlock()
rwCh, ok := rbm.revisionWatchers[rev]
if !ok {
proto, err := rbm.getRevisionProtocol(rev)
if err != nil {
return nil, err
}
destsCh := make(chan dests)
rw := newRevisionWatcher(rbm.ctx, rev, proto, rbm.updateCh, destsCh, rbm.transport, rbm.serviceLister, rbm.logger)
rbm.revisionWatchers[rev] = rw
go rw.run(rbm.probeFrequency)
return rw, nil
}
return rwCh, nil
}
// endpointsUpdated is a handler function to be used by the Endpoints informer.
// It updates the endpoints in the RevisionBackendsManager if the hosts changed
func (rbm *revisionBackendsManager) endpointsUpdated(newObj interface{}) {
// Ignore the updates when we've terminated.
select {
case <-rbm.ctx.Done():
return
default:
}
endpoints := newObj.(*corev1.Endpoints)
revID := types.NamespacedName{Namespace: endpoints.Namespace, Name: endpoints.Labels[serving.RevisionLabelKey]}
logger := rbm.logger.With(zap.String(logkey.Key, revID.String()))
logger.Debugf("Endpoints updated: %#v", newObj)
rw, err := rbm.getOrCreateRevisionWatcher(revID)
if err != nil {
logger.With(zap.Error(err)).Error("Failed to get revision watcher")
return
}
ready, notReady := endpointsToDests(endpoints, networking.ServicePortName(rw.protocol))
logger.Debugf("Updating Endpoints: ready backends: %d, not-ready backends: %d", len(ready), len(notReady))
select {
case <-rbm.ctx.Done():
return
case rw.destsCh <- dests{ready: ready, notReady: notReady}:
}
}
// deleteRevisionWatcher deletes the revision watcher for rev if it exists. It expects
// a write lock is held on revisionWatchersMux when calling.
func (rbm *revisionBackendsManager) deleteRevisionWatcher(rev types.NamespacedName) {
if rw, ok := rbm.revisionWatchers[rev]; ok {
rw.cancel()
delete(rbm.revisionWatchers, rev)
}
}
func (rbm *revisionBackendsManager) endpointsDeleted(obj interface{}) {
// Ignore the updates when we've terminated.
select {
case <-rbm.ctx.Done():
return
default:
}
ep := obj.(*corev1.Endpoints)
revID := types.NamespacedName{Namespace: ep.Namespace, Name: ep.Labels[serving.RevisionLabelKey]}
logger := rbm.logger.With(zap.String(logkey.Key, revID.String()))
logger.Debug("Deleting endpoint")
rbm.revisionWatchersMux.Lock()
defer rbm.revisionWatchersMux.Unlock()
rbm.deleteRevisionWatcher(revID)
}