-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
kpa.go
311 lines (269 loc) · 11.7 KB
/
kpa.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
/*
Copyright 2018 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 kpa
import (
"context"
"fmt"
"go.opencensus.io/stats"
"go.uber.org/zap"
nv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1"
"knative.dev/pkg/logging"
pkgmetrics "knative.dev/pkg/metrics"
"knative.dev/pkg/ptr"
pkgreconciler "knative.dev/pkg/reconciler"
pav1alpha1 "knative.dev/serving/pkg/apis/autoscaling/v1alpha1"
"knative.dev/serving/pkg/apis/serving"
"knative.dev/serving/pkg/autoscaler/scaling"
pareconciler "knative.dev/serving/pkg/client/injection/reconciler/autoscaling/v1alpha1/podautoscaler"
"knative.dev/serving/pkg/metrics"
areconciler "knative.dev/serving/pkg/reconciler/autoscaling"
"knative.dev/serving/pkg/reconciler/autoscaling/config"
"knative.dev/serving/pkg/reconciler/autoscaling/kpa/resources"
anames "knative.dev/serving/pkg/reconciler/autoscaling/resources/names"
resourceutil "knative.dev/serving/pkg/resources"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
corev1listers "k8s.io/client-go/listers/core/v1"
)
const (
noPrivateServiceName = "No Private Service Name"
noTrafficReason = "NoTraffic"
)
// podCounts keeps record of various numbers of pods
// for each revision.
type podCounts struct {
want int
ready int
notReady int
pending int
terminating int
}
// Reconciler tracks PAs and right sizes the ScaleTargetRef based on the
// information from Deciders.
type Reconciler struct {
*areconciler.Base
podsLister corev1listers.PodLister
deciders resources.Deciders
scaler *scaler
}
// Check that our Reconciler implements pareconciler.Interface
var _ pareconciler.Interface = (*Reconciler)(nil)
// ReconcileKind implements Interface.ReconcileKind.
func (c *Reconciler) ReconcileKind(ctx context.Context, pa *pav1alpha1.PodAutoscaler) pkgreconciler.Event {
logger := logging.FromContext(ctx)
// We need the SKS object in order to optimize scale to zero
// performance. It is OK if SKS is nil at this point.
sksName := anames.SKS(pa.Name)
sks, err := c.SKSLister.ServerlessServices(pa.Namespace).Get(sksName)
if err != nil && !errors.IsNotFound(err) {
logger.Warnw("Error retrieving SKS for Scaler", zap.Error(err))
}
// Having an SKS and its PrivateServiceName is a prerequisite for all upcoming steps.
if sks == nil || sks.Status.PrivateServiceName == "" {
// Before we can reconcile decider and get real number of activators
// we start with default of 2.
if _, err = c.ReconcileSKS(ctx, pa, nv1alpha1.SKSOperationModeServe, 0 /*numActivators == all*/); err != nil {
return fmt.Errorf("error reconciling SKS: %w", err)
}
pa.Status.MarkSKSNotReady(noPrivateServiceName) // In both cases this is true.
computeStatus(ctx, pa, podCounts{want: scaleUnknown}, logger)
return nil
}
pa.Status.MetricsServiceName = sks.Status.PrivateServiceName
decider, err := c.reconcileDecider(ctx, pa)
if err != nil {
return fmt.Errorf("error reconciling Decider: %w", err)
}
if err := c.ReconcileMetric(ctx, pa, resolveScrapeTarget(ctx, pa)); err != nil {
return fmt.Errorf("error reconciling Metric: %w", err)
}
// Get the appropriate current scale from the metric, and right size
// the scaleTargetRef based on it.
want, err := c.scaler.scale(ctx, pa, sks, decider.Status.DesiredScale)
if err != nil {
return fmt.Errorf("error scaling target: %w", err)
}
mode := nv1alpha1.SKSOperationModeServe
// We put activator in the serving path in the following cases:
// 1. The revision is scaled to 0:
// a. want == 0
// b. want == -1 && PA is inactive (Autoscaler has no previous knowledge of
// this revision, e.g. after a restart) but PA status is inactive (it was
// already scaled to 0).
// 2. The excess burst capacity is negative.
if want == 0 || decider.Status.ExcessBurstCapacity < 0 || want == scaleUnknown && pa.Status.IsInactive() {
mode = nv1alpha1.SKSOperationModeProxy
}
logger.Infof("SKS should be in %s mode: want = %d, ebc = %d, #act's = %d PA Inactive? = %v",
mode, want, decider.Status.ExcessBurstCapacity, decider.Status.NumActivators,
pa.Status.IsInactive())
// If we have not successfully reconciled Decider yet, NumActivators will be 0 and
// we'll use all activators to back this revision.
sks, err = c.ReconcileSKS(ctx, pa, mode, decider.Status.NumActivators)
if err != nil {
return fmt.Errorf("error reconciling SKS: %w", err)
}
// Propagate service name.
pa.Status.ServiceName = sks.Status.ServiceName
// Compare the desired and observed resources to determine our situation.
podCounter := resourceutil.NewPodAccessor(c.podsLister, pa.Namespace, pa.Labels[serving.RevisionLabelKey])
ready, notReady, pending, terminating, err := podCounter.PodCountsByState()
if err != nil {
return fmt.Errorf("error getting pod counts %s: %w", sks.Status.PrivateServiceName, err)
}
// If SKS is not ready — ensure we're not becoming ready.
if sks.IsReady() {
logger.Debug("SKS is ready, marking SKS status ready")
pa.Status.MarkSKSReady()
} else {
logger.Debug("SKS is not ready, marking SKS status not ready")
pa.Status.MarkSKSNotReady(sks.Status.GetCondition(nv1alpha1.ServerlessServiceConditionReady).GetMessage())
}
logger.Infof("PA scale got=%d, want=%d, desiredPods=%d ebc=%d", ready, want,
decider.Status.DesiredScale, decider.Status.ExcessBurstCapacity)
pc := podCounts{
want: int(want),
ready: ready,
notReady: notReady,
pending: pending,
terminating: terminating,
}
logger.Infof("Observed pod counts=%#v", pc)
computeStatus(ctx, pa, pc, logger)
return nil
}
func (c *Reconciler) reconcileDecider(ctx context.Context, pa *pav1alpha1.PodAutoscaler) (*scaling.Decider, error) {
desiredDecider := resources.MakeDecider(ctx, pa, config.FromContext(ctx).Autoscaler)
decider, err := c.deciders.Get(ctx, desiredDecider.Namespace, desiredDecider.Name)
if errors.IsNotFound(err) {
decider, err = c.deciders.Create(ctx, desiredDecider)
if err != nil {
return nil, fmt.Errorf("error creating Decider: %w", err)
}
} else if err != nil {
return nil, fmt.Errorf("error fetching Decider: %w", err)
}
// Ignore status when reconciling
desiredDecider.Status = decider.Status
if !equality.Semantic.DeepEqual(desiredDecider, decider) {
decider, err = c.deciders.Update(ctx, desiredDecider)
if err != nil {
return nil, fmt.Errorf("error updating decider: %w", err)
}
}
return decider, nil
}
func computeStatus(ctx context.Context, pa *pav1alpha1.PodAutoscaler, pc podCounts, logger *zap.SugaredLogger) {
pa.Status.DesiredScale, pa.Status.ActualScale = ptr.Int32(int32(pc.want)), ptr.Int32(int32(pc.ready))
reportMetrics(pa, pc)
computeActiveCondition(ctx, pa, pc)
logger.Debugf("PA Status after reconcile: %#v", pa.Status.Status)
}
func reportMetrics(pa *pav1alpha1.PodAutoscaler, pc podCounts) {
serviceLabel := pa.Labels[serving.ServiceLabelKey] // This might be empty.
configLabel := pa.Labels[serving.ConfigurationLabelKey]
ctx := metrics.RevisionContext(pa.Namespace, serviceLabel, configLabel, pa.Name)
stats := []stats.Measurement{
actualPodCountM.M(int64(pc.ready)), notReadyPodCountM.M(int64(pc.notReady)),
pendingPodCountM.M(int64(pc.pending)), terminatingPodCountM.M(int64(pc.terminating)),
}
// Negative "want" values represent an empty metrics pipeline and thus no specific request is being made.
if pc.want >= 0 {
stats = append(stats, requestedPodCountM.M(int64(pc.want)))
}
pkgmetrics.RecordBatch(ctx, stats...)
}
// computeActiveCondition updates the status of a PA given the current scale (got), desired scale (want)
// active threshold (min), and the current status, as per the following table:
//
// | Want | Got | min | Status | New status |
// | 0 | <any> | <any> | <any> | inactive |
// | >0 | < min | <any> | <any> | activating |
// | >0 | >= min | <any> | <any> | active |
// | -1 | < min | <any> | inactive | inactive |
// | -1 | < min | <any> | activating | activating |
// | -1 | < min | <any> | active | activating |
// | -1 | >= min | <any> | inactive | inactive |
// | -1 | >= min | 0 | activating | inactive |
// | -1 | >= min | 0 | active | inactive | <-- this case technically is impossible.
// | -1 | >= min | >0 | activating | active |
// | -1 | >= min | >0 | active | active |
func computeActiveCondition(ctx context.Context, pa *pav1alpha1.PodAutoscaler, pc podCounts) {
minReady := activeThreshold(ctx, pa)
// In pre-0.17 we could have scaled down normally without ever setting ScaleTargetInitialized.
// In this case we'll be in the NoTraffic/inactive state.
// TODO(taragu): remove after 0.19
alreadyScaledDownSuccessfully := minReady > 0 && pa.Status.GetCondition(pav1alpha1.PodAutoscalerConditionActive).GetReason() == noTrafficReason
if (pc.ready >= minReady || alreadyScaledDownSuccessfully) && pa.Status.ServiceName != "" {
pa.Status.MarkScaleTargetInitialized()
}
switch {
// Need to check for minReady = 0 because in the initialScale 0 case, pc.want will be -1.
case pc.want == 0 || minReady == 0:
if pa.Status.IsActivating() && minReady > 0 {
// We only ever scale to zero while activating if we fail to activate within the progress deadline.
pa.Status.MarkInactive("TimedOut", "The target could not be activated.")
} else {
pa.Status.MarkInactive(noTrafficReason, "The target is not receiving traffic.")
}
case pc.ready < minReady:
if pc.want > 0 || !pa.Status.IsInactive() {
pa.Status.MarkActivating(
"Queued", "Requests to the target are being buffered as resources are provisioned.")
} else {
// This is for the initialScale 0 case. In the first iteration, minReady is 0,
// but for the following iterations, minReady is 1. pc.want will continue being
// -1 until we start receiving metrics, so we will end up here.
// Even though PA is already been marked as inactive in the first iteration, we
// still need to set it again. Otherwise reconciliation will fail with NewObservedGenFailure
// because we cannot go through one iteration of reconciliation without setting
// some status.
pa.Status.MarkInactive(noTrafficReason, "The target is not receiving traffic.")
}
case pc.ready >= minReady:
if pc.want > 0 || !pa.Status.IsInactive() {
pa.Status.MarkActive()
}
}
}
// activeThreshold returns the scale required for the pa to be marked Active
func activeThreshold(ctx context.Context, pa *pav1alpha1.PodAutoscaler) int {
asConfig := config.FromContext(ctx).Autoscaler
min, _ := pa.ScaleBounds(asConfig)
if !pa.Status.IsScaleTargetInitialized() {
initialScale := resources.GetInitialScale(asConfig, pa)
return int(intMax(min, initialScale))
}
return int(intMax(min, 1))
}
// resolveScrapeTarget returns metric service name to be scraped based on TBC configuration
// TBC == -1 => activator in path, don't scrape the service
func resolveScrapeTarget(ctx context.Context, pa *pav1alpha1.PodAutoscaler) string {
tbc := resolveTBC(ctx, pa)
if tbc == -1 {
return ""
}
return pa.Status.MetricsServiceName
}
func resolveTBC(ctx context.Context, pa *pav1alpha1.PodAutoscaler) float64 {
if v, ok := pa.TargetBC(); ok {
return v
}
return config.FromContext(ctx).Autoscaler.TargetBurstCapacity
}
func intMax(a, b int32) int32 {
if a < b {
return b
}
return a
}