forked from knative/serving
/
throttler.go
683 lines (595 loc) · 22 KB
/
throttler.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/*
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"
"errors"
"math"
"math/rand"
"sort"
"sync"
"sync/atomic"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
endpointsinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/endpoints"
"knative.dev/pkg/controller"
"knative.dev/pkg/logging"
"knative.dev/pkg/logging/logkey"
"knative.dev/pkg/network"
"knative.dev/pkg/reconciler"
"knative.dev/pkg/system"
"knative.dev/serving/pkg/activator/util"
"knative.dev/serving/pkg/apis/networking"
v1 "knative.dev/serving/pkg/apis/serving/v1"
revisioninformer "knative.dev/serving/pkg/client/injection/informers/serving/v1/revision"
servinglisters "knative.dev/serving/pkg/client/listers/serving/v1"
"knative.dev/serving/pkg/queue"
"knative.dev/serving/pkg/resources"
)
type podTracker struct {
dest string
b breaker
}
func (p *podTracker) Capacity() int {
if p.b == nil {
return 1
}
return p.b.Capacity()
}
func (p *podTracker) UpdateConcurrency(c int) error {
if p.b == nil {
return nil
}
return p.b.UpdateConcurrency(c)
}
func (p *podTracker) Reserve(ctx context.Context) (func(), bool) {
if p.b == nil {
return noop, true
}
return p.b.Reserve(ctx)
}
type breaker interface {
Capacity() int
Maybe(ctx context.Context, thunk func()) error
UpdateConcurrency(int) error
Reserve(ctx context.Context) (func(), bool)
}
var ErrActivatorOverload = errors.New("activator overload")
type revisionThrottler struct {
revID types.NamespacedName
containerConcurrency int
// Holds the current number of backends. This is used for when we get an activatorCount update and
// therefore need to recalculate capacity
backendCount int
// This is a breaker for the revision as a whole. try calls first pass through
// this breaker and are either called with clusterIPDest or go through selecting
// a podIPTracker and are then called.
breaker breaker
// This will be non empty when we're able to use pod addressing.
podTrackers []*podTracker
// Effective trackers that are assigned to this Activator.
// This is a subset of podIPTrackers.
assignedTrackers []*podTracker
// If we dont have a healthy clusterIPTracker this is set to nil, otherwise
// it is the l4dest for this revision's private clusterIP.
clusterIPTracker *podTracker
// mux guards "throttle state" which is the state we use during the request path. This
// is trackers, clusterIPDest.
mux sync.RWMutex
// used to atomically calculate and set capacity
capacityMux sync.Mutex
logger *zap.SugaredLogger
}
func newRevisionThrottler(revID types.NamespacedName,
containerConcurrency int,
breakerParams queue.BreakerParams,
logger *zap.SugaredLogger) *revisionThrottler {
logger = logger.With(zap.String(logkey.Key, revID.String()))
var revBreaker breaker
if containerConcurrency == 0 {
revBreaker = newInfiniteBreaker(logger)
} else {
revBreaker = queue.NewBreaker(breakerParams)
}
return &revisionThrottler{
revID: revID,
containerConcurrency: containerConcurrency,
breaker: revBreaker,
logger: logger,
}
}
func noop() {}
// pickPod picks the first tracker that has open capacity if container concurrency
// if limited, random pod otherwise.
func pickPod(ctx context.Context, tgs []*podTracker, cc int) (func(), *podTracker) {
// Infinite capacity, pick random. We have to do this
// otherwise _all_ the requests will go to the first pod
// since it has unlimited capacity.
if cc == 0 {
return noop, tgs[rand.Intn(len(tgs))]
}
for _, t := range tgs {
if cb, ok := t.Reserve(ctx); ok {
return cb, t
}
}
// NB: as currently written this can never happen.
return noop, nil
}
// Returns a dest that at the moment of choosing had an open slot
// for request.
func (rt *revisionThrottler) acquireDest(ctx context.Context) (func(), *podTracker) {
rt.mux.RLock()
defer rt.mux.RUnlock()
if rt.clusterIPTracker != nil {
return noop, rt.clusterIPTracker
}
return pickPod(ctx, rt.assignedTrackers, rt.containerConcurrency)
}
func (rt *revisionThrottler) try(ctx context.Context, function func(string) error) error {
var ret error
if err := rt.breaker.Maybe(ctx, func() {
cb, tracker := rt.acquireDest(ctx)
if tracker == nil {
ret = errors.New("made it through breaker but we have no clusterIP or podIPs. This should" +
" never happen" + rt.revID.String())
return
}
defer cb()
// We already reserved a guaranteed spot. So just execute the passed functor.
ret = function(tracker.dest)
}); err != nil {
return err
}
return ret
}
func (rt *revisionThrottler) calculateCapacity(size, activatorCount, maxConcurrency int) int {
targetCapacity := rt.containerConcurrency * size
if size > 0 && (rt.containerConcurrency == 0 || targetCapacity > maxConcurrency) {
// If cc==0, we need to pick a number, but it does not matter, since
// infinite breaker will dole out as many tokens as it can.
targetCapacity = maxConcurrency
} else if targetCapacity > 0 {
targetCapacity = minOneOrValue(targetCapacity / minOneOrValue(activatorCount))
}
return targetCapacity
}
// This makes sure we reset the capacity to the CC, since the pod
// might be reassigned to be exclusively used.
func (rt *revisionThrottler) resetTrackers() {
if rt.containerConcurrency <= 0 {
return
}
for _, t := range rt.podTrackers {
// Reset to default.
t.UpdateConcurrency(rt.containerConcurrency)
}
}
func (rt *revisionThrottler) updateCapacity(throttler *Throttler, backendCount int) {
ac := throttler.activatorCount()
// We have to make assignments on each updateCapacity, since if number
// of activators changes, then we need to rebalance the assignedTrackers.
numTrackers := func() int {
rt.mux.Lock()
defer rt.mux.Unlock()
// We're using cluster IP.
if rt.clusterIPTracker != nil {
return 0
}
// Infinite capacity, assign all.
if rt.containerConcurrency == 0 {
rt.assignedTrackers = rt.podTrackers
} else {
rt.resetTrackers()
rt.assignedTrackers = assignSlice(rt.podTrackers, throttler.index(), ac, rt.containerConcurrency)
}
rt.logger.Debugf("Trackers %d/%d %v", throttler.index(), ac, rt.assignedTrackers)
return len(rt.assignedTrackers)
}()
capacity := 0
if numTrackers > 0 {
// Capacity is computed based off of number of trackers,
// when using pod direct routing.
capacity = rt.calculateCapacity(len(rt.podTrackers), ac, throttler.breakerParams.MaxConcurrency)
} else {
// Capacity is computed off of number of ready backends,
// when we are using clusterIP routing.
capacity = rt.calculateCapacity(backendCount, ac, throttler.breakerParams.MaxConcurrency)
}
rt.logger.Infof("Set capacity to %d (backends: %d, index: %d/%d)",
capacity, backendCount, throttler.index(), ac)
// TODO(vagababov): analyze to see if we need this mutex at all?
rt.capacityMux.Lock()
defer rt.capacityMux.Unlock()
rt.backendCount = backendCount
rt.breaker.UpdateConcurrency(capacity)
}
func (rt *revisionThrottler) updateThrottlerState(
throttler *Throttler, backendCount int,
trackers []*podTracker, clusterIPDest *podTracker) {
rt.logger.Infof("Updating Revision Throttler with: clusterIP = %v, trackers = %d, backends = %d activator pos %d/%d",
clusterIPDest, len(trackers), backendCount, throttler.index(), throttler.activatorCount())
// Update trackers / clusterIP before capacity. Otherwise we can race updating our breaker when
// we increase capacity, causing a request to fall through before a tracker is added, causing an
// incorrect LB decision.
if func() bool {
rt.mux.Lock()
defer rt.mux.Unlock()
rt.podTrackers = trackers
rt.clusterIPTracker = clusterIPDest
return clusterIPDest != nil || len(trackers) > 0
}() {
// If we have an address to target, then pass through an accurate
// accounting of the number of backends.
rt.updateCapacity(throttler, backendCount)
} else {
// If we do not have an address to target, then we should treat it
// as though we have zero backends.
rt.updateCapacity(throttler, 0)
}
}
// pickIndices picks the indices for the slicing.
func pickIndices(numTrackers, selfIndex, numActivators int) (beginIndex, endIndex, remnants int) {
if numActivators > numTrackers {
// 1. We have fewer pods than than activators. Assign the pod in round robin fashion.
// NB: when we implement subsetting this will be less of a problem.
// e.g. lt=3, #ac = 5; for selfIdx = 3 => 3 % 3 = 0, or for si = 5 => 5%3 = 2
beginIndex = selfIndex % numTrackers
endIndex = beginIndex + 1
return
}
// 2. distribute equally and share the remnants
// among all the activators, but with reduced capacity, if finite.
sliceSize := numTrackers / numActivators
remnants = numTrackers % numActivators
beginIndex = selfIndex * sliceSize
endIndex = beginIndex + sliceSize
return
}
// assignSlice picks a subset of the individual pods to send requests to
// for this Activator instance. This only matters in case of direct
// to pod IP routing, and is irrelevant, when ClusterIP is used.
func assignSlice(trackers []*podTracker, selfIndex, numActivators, cc int) []*podTracker {
// When we're unassigned, doesn't matter what we return.
lt := len(trackers)
if selfIndex == -1 || lt <= 1 {
return trackers
}
// Sort, so we get more or less stable results.
sort.Slice(trackers, func(i, j int) bool {
return trackers[i].dest < trackers[j].dest
})
bi, ei, remnants := pickIndices(lt, selfIndex, numActivators)
x := append(trackers[:0:0], trackers[bi:ei]...)
if remnants > 0 {
tail := trackers[len(trackers)-remnants:]
// We shuffle the tail, to ensure that pods in the tail get better
// load distribution, since we sort the pods above, this puts more requests
// on the very first tail pod, than on the others.
rand.Shuffle(remnants, func(i, j int) {
tail[i], tail[j] = tail[j], tail[i]
})
// We need minOneOrValue in order for cc==0 to work.
dcc := minOneOrValue(int(math.Ceil(float64(cc) / float64(numActivators))))
// This is basically: x = append(x, trackers[len(trackers)-remnants:]...)
// But we need to update the capacity.
for _, t := range tail {
t.UpdateConcurrency(dcc)
x = append(x, t)
}
}
return x
}
// This function will never be called in parallel but try can be called in parallel to this so we need
// to lock on updating concurrency / trackers
func (rt *revisionThrottler) handleUpdate(throttler *Throttler, update revisionDestsUpdate) {
rt.logger.Debugf("Handling update w/ ClusterIP=%q, %d ready and dests: %v",
update.ClusterIPDest, len(update.Dests), update.Dests)
// ClusterIP is not yet ready, so we want to send requests directly to the pods.
// NB: this will not be called in parallel, thus we can build a new podIPTrackers
// array before taking out a lock.
if update.ClusterIPDest == "" {
// Create a map for fast lookup of existing trackers.
trackersMap := make(map[string]*podTracker, len(rt.podTrackers))
for _, tracker := range rt.podTrackers {
trackersMap[tracker.dest] = tracker
}
trackers := make([]*podTracker, 0, len(update.Dests))
// Loop over dests, reuse existing tracker if we have one, otherwise create
// a new one.
for newDest := range update.Dests {
tracker, ok := trackersMap[newDest]
if !ok {
if rt.containerConcurrency == 0 {
tracker = &podTracker{dest: newDest}
} else {
tracker = &podTracker{
dest: newDest,
b: queue.NewBreaker(queue.BreakerParams{
QueueDepth: throttler.breakerParams.QueueDepth,
MaxConcurrency: rt.containerConcurrency,
InitialCapacity: rt.containerConcurrency, // Presume full unused capacity.
}),
}
}
}
trackers = append(trackers, tracker)
}
rt.updateThrottlerState(throttler, len(update.Dests), trackers, nil /*clusterIP*/)
return
}
rt.updateThrottlerState(throttler, len(update.Dests), nil /*trackers*/, &podTracker{
dest: update.ClusterIPDest,
})
}
// Throttler load balances requests to revisions based on capacity. When `Run` is called it listens for
// updates to revision backends and decides when and when and where to forward a request.
type Throttler struct {
revisionThrottlers map[types.NamespacedName]*revisionThrottler
revisionThrottlersMutex sync.RWMutex
breakerParams queue.BreakerParams
revisionLister servinglisters.RevisionLister
numActivators int32 // Total number of activators.
activatorIndex int32 // The assigned index of this activator, -1 is Activator is not expected to receive traffic.
ipAddress string // The IP address of this activator.
logger *zap.SugaredLogger
}
// NewThrottler creates a new Throttler
func NewThrottler(ctx context.Context,
breakerParams queue.BreakerParams,
ipAddr string) *Throttler {
revisionInformer := revisioninformer.Get(ctx)
t := &Throttler{
revisionThrottlers: make(map[types.NamespacedName]*revisionThrottler),
breakerParams: breakerParams,
revisionLister: revisionInformer.Lister(),
ipAddress: ipAddr,
activatorIndex: -1, // Unset yet.
logger: logging.FromContext(ctx),
}
// Watch revisions to create throttler with backlog immediately and delete
// throttlers on revision delete
revisionInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: t.revisionUpdated,
UpdateFunc: controller.PassNew(t.revisionUpdated),
DeleteFunc: t.revisionDeleted,
})
// Watch activator endpoint to maintain activator count
endpointsInformer := endpointsinformer.Get(ctx)
endpointsInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: reconciler.ChainFilterFuncs(
reconciler.NameFilterFunc(networking.ActivatorServiceName),
reconciler.NamespaceFilterFunc(system.Namespace()),
),
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: t.activatorEndpointsUpdated,
UpdateFunc: controller.PassNew(t.activatorEndpointsUpdated),
},
})
return t
}
// Run starts the throttler and blocks until the context is done.
func (t *Throttler) Run(ctx context.Context) {
rbm := newRevisionBackendsManager(ctx, network.AutoTransport)
// Update channel is closed when ctx is done.
t.run(rbm.updates())
}
func (t *Throttler) run(updateCh <-chan revisionDestsUpdate) {
for update := range updateCh {
t.handleUpdate(update)
}
t.logger.Info("The Throttler has stopped.")
}
// Try waits for capacity and then executes function, passing in a l4 dest to send a request
func (t *Throttler) Try(ctx context.Context, function func(string) error) error {
rt, err := t.getOrCreateRevisionThrottler(util.RevIDFrom(ctx))
if err != nil {
return err
}
return rt.try(ctx, function)
}
func (t *Throttler) getOrCreateRevisionThrottler(revID types.NamespacedName) (*revisionThrottler, error) {
// First, see if we can succeed with just an RLock. This is in the request path so optimizing
// for this case is important
t.revisionThrottlersMutex.RLock()
revThrottler, ok := t.revisionThrottlers[revID]
t.revisionThrottlersMutex.RUnlock()
if ok {
return revThrottler, nil
}
// Redo with a write lock since we failed the first time and may need to create
t.revisionThrottlersMutex.Lock()
defer t.revisionThrottlersMutex.Unlock()
revThrottler, ok = t.revisionThrottlers[revID]
if !ok {
rev, err := t.revisionLister.Revisions(revID.Namespace).Get(revID.Name)
if err != nil {
return nil, err
}
revThrottler = newRevisionThrottler(revID, int(rev.Spec.GetContainerConcurrency()), t.breakerParams, t.logger)
t.revisionThrottlers[revID] = revThrottler
}
return revThrottler, nil
}
// revisionUpdated is used to ensure we have a backlog set up for a revision as soon as it is created
// rather than erroring with revision not found until a networking probe succeeds
func (t *Throttler) revisionUpdated(obj interface{}) {
rev := obj.(*v1.Revision)
revID := types.NamespacedName{Namespace: rev.Namespace, Name: rev.Name}
logger := t.logger.With(zap.String(logkey.Key, revID.String()))
logger.Debug("Revision update")
if _, err := t.getOrCreateRevisionThrottler(revID); err != nil {
logger.Errorw("Failed to get revision throttler for revision "+revID.String(), zap.Error(err))
}
}
// revisionDeleted is to clean up revision throttlers after a revision is deleted to prevent unbounded
// memory growth
func (t *Throttler) revisionDeleted(obj interface{}) {
rev := obj.(*v1.Revision)
revID := types.NamespacedName{Namespace: rev.Namespace, Name: rev.Name}
logger := t.logger.With(zap.String(logkey.Key, revID.String()))
logger.Debug("Revision delete")
t.revisionThrottlersMutex.Lock()
defer t.revisionThrottlersMutex.Unlock()
delete(t.revisionThrottlers, revID)
}
func (t *Throttler) handleUpdate(update revisionDestsUpdate) {
if rt, err := t.getOrCreateRevisionThrottler(update.Rev); err != nil {
logger := t.logger.With(zap.String(logkey.Key, update.Rev.String()))
if k8serrors.IsNotFound(err) {
logger.Debug("Revision not found. It was probably removed")
} else {
logger.With(zap.Error(err)).Error("Failed to get revision throttler")
}
} else {
rt.handleUpdate(t, update)
}
}
// inferIndex returns the index of this activator slice.
// If inferIndex returns -1, it means that this activator will not receive
// any traffic just yet so, do not participate in slicing, this happens after
// startup, but before this activator is threaded into the endpoints
// (which is up to 10s after reporting healthy).
// For now we are just sorting the IP addresses of all activators
// and finding our index in that list.
func inferIndex(eps []string, ipAddress string) int {
// `eps` will contain port, so binary search of the insertion point would be fine.
idx := sort.SearchStrings(eps, ipAddress)
// Check if this activator is part of the endpoints slice?
if idx == len(eps) || eps[idx] != ipAddress {
idx = -1
}
return idx
}
func (t *Throttler) updateAllThrottlerCapacity() {
t.revisionThrottlersMutex.RLock()
defer t.revisionThrottlersMutex.RUnlock()
for _, rt := range t.revisionThrottlers {
rt.updateCapacity(t, rt.backendCount)
}
}
func (t *Throttler) activatorEndpointsUpdated(newObj interface{}) {
endpoints := newObj.(*corev1.Endpoints)
// We want to pass sorted list, so that we get _some_ stability in the results.
epSet, _ := endpointsToDests(endpoints, networking.ServicePortNameHTTP1)
eps := epSet.List()
t.logger.Debugf("All Activator IPS: %v, my IP: %s", eps, t.ipAddress)
idx := inferIndex(eps, t.ipAddress)
activatorCount := resources.ReadyAddressCount(endpoints)
t.logger.Infof("Got %d ready activator endpoints, our position is: %d", activatorCount, idx)
atomic.StoreInt32(&t.numActivators, int32(activatorCount))
atomic.StoreInt32(&t.activatorIndex, int32(idx))
t.updateAllThrottlerCapacity()
}
func (t *Throttler) index() int {
return int(atomic.LoadInt32(&t.activatorIndex))
}
func (t *Throttler) activatorCount() int {
return int(atomic.LoadInt32(&t.numActivators))
}
// minOneOrValue function returns num if its greater than 1
// else the function returns 1
func minOneOrValue(num int) int {
if num > 1 {
return num
}
return 1
}
// infiniteBreaker is basically a short circuit.
// infiniteBreaker provides us capability to send unlimited number
// of requests to the downstream system.
// This is to be used only when the container concurrency is unset
// (i.e. infinity).
// The infiniteBreaker will, though, block the requests when
// downstream capacity is 0.
type infiniteBreaker struct {
// mu guards `broadcast` channel.
mu sync.RWMutex
// broadcast channel is used notify the waiting requests that
// downstream capacity showed up.
// When the downstream capacity switches from 0 to 1, the channel is closed.
// When the downstream capacity disappears, the a new channel is created.
// Reads/Writes to the `broadcast` must be guarded by `mu`.
broadcast chan struct{}
// concurrency in the infinite breaker takes only two values
// 0 (no downstream capacity) and 1 (infinite downstream capacity).
// `Maybe` checks this value to determine whether to proxy the request
// immediately or wait for capacity to appear.
// `concurrency` should only be manipulated by `sync/atomic` methods.
concurrency int32
logger *zap.SugaredLogger
}
// newInfiniteBreaker creates an infiniteBreaker
func newInfiniteBreaker(logger *zap.SugaredLogger) *infiniteBreaker {
return &infiniteBreaker{
broadcast: make(chan struct{}),
logger: logger,
}
}
// Capacity returns the current capacity of the breaker
func (ib *infiniteBreaker) Capacity() int {
return int(atomic.LoadInt32(&ib.concurrency))
}
func zeroOrOne(x int) int32 {
if x == 0 {
return 0
}
return 1
}
// UpdateConcurrency sets the concurrency of the breaker
func (ib *infiniteBreaker) UpdateConcurrency(cc int) error {
rcc := zeroOrOne(cc)
// We lock here to make sure two scale up events don't
// stomp on each other's feet.
ib.mu.Lock()
defer ib.mu.Unlock()
old := atomic.SwapInt32(&ib.concurrency, rcc)
// Scale up/down event.
if old != rcc {
if rcc == 0 {
// Scaled to 0.
ib.broadcast = make(chan struct{})
} else {
close(ib.broadcast)
}
}
return nil
}
// Maybe executes thunk when capacity is available
func (ib *infiniteBreaker) Maybe(ctx context.Context, thunk func()) error {
has := ib.Capacity()
// We're scaled to serve.
if has > 0 {
thunk()
return nil
}
// Make sure we lock to get the channel, to avoid
// race between Maybe and UpdateConcurrency.
var ch chan struct{}
ib.mu.RLock()
ch = ib.broadcast
ib.mu.RUnlock()
select {
case <-ch:
// Scaled up.
thunk()
return nil
case <-ctx.Done():
ib.logger.Infof("Context is closed: %v", ctx.Err())
return ctx.Err()
}
}
func (ib *infiniteBreaker) Reserve(context.Context) (func(), bool) { return noop, true }