forked from knative/serving
/
revision_types.go
463 lines (383 loc) · 16.6 KB
/
revision_types.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
/*
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 v1alpha1
import (
"fmt"
"strconv"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/knative/pkg/apis"
duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1"
"github.com/knative/pkg/kmeta"
"github.com/knative/serving/pkg/apis/serving"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Revision is an immutable snapshot of code and configuration. A revision
// references a container image, and optionally a build that is responsible for
// materializing that container image from source. Revisions are created by
// updates to a Configuration.
//
// See also: https://github.com/knative/serving/blob/master/docs/spec/overview.md#revision
type Revision struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec holds the desired state of the Revision (from the client).
// +optional
Spec RevisionSpec `json:"spec,omitempty"`
// Status communicates the observed state of the Revision (from the controller).
// +optional
Status RevisionStatus `json:"status,omitempty"`
}
// Check that Revision can be validated, can be defaulted, and has immutable fields.
var _ apis.Validatable = (*Revision)(nil)
var _ apis.Defaultable = (*Revision)(nil)
var _ apis.Immutable = (*Revision)(nil)
// Check that RevisionStatus may have its conditions managed.
var _ duckv1alpha1.ConditionsAccessor = (*RevisionStatus)(nil)
// Check that we can create OwnerReferences to a Revision.
var _ kmeta.OwnerRefable = (*Revision)(nil)
// RevisionTemplateSpec describes the data a revision should have when created from a template.
// Based on: https://github.com/kubernetes/api/blob/e771f807/core/v1/types.go#L3179-L3190
type RevisionTemplateSpec struct {
// +optional
metav1.ObjectMeta `json:"metadata,omitempty"`
// +optional
Spec RevisionSpec `json:"spec,omitempty"`
}
// DeprecatedRevisionServingStateType is an enumeration of the levels of serving readiness of the Revision.
// See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting
type DeprecatedRevisionServingStateType string
const (
// The revision is ready to serve traffic. It should have Kubernetes
// resources, and the Istio route should be pointed to the given resources.
DeprecatedRevisionServingStateActive DeprecatedRevisionServingStateType = "Active"
// The revision is not currently serving traffic, but could be made to serve
// traffic quickly. It should have Kubernetes resources, but the Istio route
// should be pointed to the activator.
DeprecatedRevisionServingStateReserve DeprecatedRevisionServingStateType = "Reserve"
// The revision has been decommissioned and is not needed to serve traffic
// anymore. It should not have any Istio routes or Kubernetes resources.
// A Revision may be brought out of retirement, but it may take longer than
// it would from a "Reserve" state.
// Note: currently not set anywhere. See https://github.com/knative/serving/issues/1203
DeprecatedRevisionServingStateRetired DeprecatedRevisionServingStateType = "Retired"
)
// RevisionRequestConcurrencyModelType is an enumeration of the
// concurrency models supported by a Revision.
// Deprecated in favor of RevisionContainerConcurrencyType.
type RevisionRequestConcurrencyModelType string
const (
// RevisionRequestConcurrencyModelSingle guarantees that only one
// request will be handled at a time (concurrently) per instance
// of Revision Container.
RevisionRequestConcurrencyModelSingle RevisionRequestConcurrencyModelType = "Single"
// RevisionRequestConcurencyModelMulti allows more than one request to
// be handled at a time (concurrently) per instance of Revision
// Container.
RevisionRequestConcurrencyModelMulti RevisionRequestConcurrencyModelType = "Multi"
)
// RevisionContainerConcurrencyType is an integer expressing a number of
// in-flight (concurrent) requests.
type RevisionContainerConcurrencyType int64
const (
// The maximum configurable container concurrency.
RevisionContainerConcurrencyMax RevisionContainerConcurrencyType = 1000
)
// RevisionSpec holds the desired state of the Revision (from the client).
type RevisionSpec struct {
// TODO: Generation does not work correctly with CRD. They are scrubbed
// by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778)
// So, we add Generation here. Once that gets fixed, remove this and use
// ObjectMeta.Generation instead.
// +optional
Generation int64 `json:"generation,omitempty"`
// DeprecatedServingState holds a value describing the desired state the Kubernetes
// resources should be in for this Revision.
// Users must not specify this when creating a revision. These values are no longer
// updated by the system.
// +optional
DeprecatedServingState DeprecatedRevisionServingStateType `json:"servingState,omitempty"`
// ConcurrencyModel specifies the desired concurrency model
// (Single or Multi) for the
// Revision. Defaults to Multi.
// Deprecated in favor of ContainerConcurrency.
// +optional
ConcurrencyModel RevisionRequestConcurrencyModelType `json:"concurrencyModel,omitempty"`
// ContainerConcurrency specifies the maximum allowed
// in-flight (concurrent) requests per container of the Revision.
// Defaults to `0` which means unlimited concurrency.
// This field replaces ConcurrencyModel. A value of `1`
// is equivalent to `Single` and `0` is equivalent to `Multi`.
// +optional
ContainerConcurrency RevisionContainerConcurrencyType `json:"containerConcurrency,omitempty"`
// ServiceAccountName holds the name of the Kubernetes service account
// as which the underlying K8s resources should be run. If unspecified
// this will default to the "default" service account for the namespace
// in which the Revision exists.
// This may be used to provide access to private container images by
// following: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#add-imagepullsecrets-to-a-service-account
// TODO(ZhiminXiang): verify the corresponding service account exists.
// +optional
ServiceAccountName string `json:"serviceAccountName,omitempty"`
// BuildName optionally holds the name of the Build responsible for
// producing the container image for its Revision.
// DEPRECATED: Use BuildRef instead.
// +optional
BuildName string `json:"buildName,omitempty"`
// BuildRef holds the reference to the build (if there is one) responsible
// for producing the container image for this Revision. Otherwise, nil
// +optional
BuildRef *corev1.ObjectReference `json:"buildRef,omitempty"`
// Container defines the unit of execution for this Revision.
// In the context of a Revision, we disallow a number of the fields of
// this Container, including: name, resources, ports, and volumeMounts.
// TODO(mattmoor): Link to the runtime contract tracked by:
// https://github.com/knative/serving/issues/627
// +optional
Container corev1.Container `json:"container,omitempty"`
}
const (
// RevisionConditionReady is set when the revision is starting to materialize
// runtime resources, and becomes true when those resources are ready.
RevisionConditionReady = duckv1alpha1.ConditionReady
// RevisionConditionBuildSucceeded is set when the revision has an associated build
// and is marked True if/once the Build has completed successfully.
RevisionConditionBuildSucceeded duckv1alpha1.ConditionType = "BuildSucceeded"
// RevisionConditionResourcesAvailable is set when underlying
// Kubernetes resources have been provisioned.
RevisionConditionResourcesAvailable duckv1alpha1.ConditionType = "ResourcesAvailable"
// RevisionConditionContainerHealthy is set when the revision readiness check completes.
RevisionConditionContainerHealthy duckv1alpha1.ConditionType = "ContainerHealthy"
// RevisionConditionActive is set when the revision is receiving traffic.
RevisionConditionActive duckv1alpha1.ConditionType = "Active"
)
var revCondSet = duckv1alpha1.NewLivingConditionSet(
RevisionConditionResourcesAvailable,
RevisionConditionContainerHealthy,
RevisionConditionActive,
)
var buildCondSet = duckv1alpha1.NewBatchConditionSet()
// RevisionStatus communicates the observed state of the Revision (from the controller).
type RevisionStatus struct {
// ServiceName holds the name of a core Kubernetes Service resource that
// load balances over the pods backing this Revision. When the Revision
// is Active, this service would be an appropriate ingress target for
// targeting the revision.
// +optional
ServiceName string `json:"serviceName,omitempty"`
// Conditions communicates information about ongoing/complete
// reconciliation processes that bring the "spec" inline with the observed
// state of the world.
// +optional
Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"`
// ObservedGeneration is the 'Generation' of the Configuration that
// was last processed by the controller. The observed generation is updated
// even if the controller failed to process the spec and create the Revision.
// +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// LogURL specifies the generated logging url for this particular revision
// based on the revision url template specified in the controller's config.
// +optional
LogURL string `json:"logUrl,omitempty"`
// ImageDigest holds the resolved digest for the image specified
// within .Spec.Container.Image. The digest is resolved during the creation
// of Revision. This field holds the digest value regardless of whether
// a tag or digest was originally specified in the Container object. It
// may be empty if the image comes from a registry listed to skip resolution.
// +optional
ImageDigest string `json:"imageDigest,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// RevisionList is a list of Revision resources
type RevisionList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata"`
Items []Revision `json:"items"`
}
func (r *Revision) GetGroupVersionKind() schema.GroupVersionKind {
return SchemeGroupVersion.WithKind("Revision")
}
func (r *Revision) BuildRef() *corev1.ObjectReference {
if r.Spec.BuildRef != nil {
buildRef := r.Spec.BuildRef.DeepCopy()
if buildRef.Namespace == "" {
buildRef.Namespace = r.Namespace
}
return buildRef
}
if r.Spec.BuildName != "" {
return &corev1.ObjectReference{
APIVersion: "build.knative.dev/v1alpha1",
Kind: "Build",
Namespace: r.Namespace,
Name: r.Spec.BuildName,
}
}
return nil
}
// IsReady looks at the conditions and if the Status has a condition
// RevisionConditionReady returns true if ConditionStatus is True
func (rs *RevisionStatus) IsReady() bool {
return revCondSet.Manage(rs).IsHappy()
}
func (rs *RevisionStatus) IsActivationRequired() bool {
if c := revCondSet.Manage(rs).GetCondition(RevisionConditionActive); c != nil {
return c.Status != corev1.ConditionTrue
}
return false
}
func (rs *RevisionStatus) IsRoutable() bool {
return rs.IsReady() || rs.IsActivationRequired()
}
func (rs *RevisionStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition {
return revCondSet.Manage(rs).GetCondition(t)
}
func (rs *RevisionStatus) InitializeConditions() {
revCondSet.Manage(rs).InitializeConditions()
// We don't include BuildSucceeded here because it could confuse users if
// no `buildName` was specified.
}
func (rs *RevisionStatus) InitializeBuildCondition() {
revCondSet.Manage(rs).InitializeCondition(RevisionConditionBuildSucceeded)
}
func (rs *RevisionStatus) PropagateBuildStatus(bs duckv1alpha1.KResourceStatus) {
bc := buildCondSet.Manage(&bs).GetCondition(duckv1alpha1.ConditionSucceeded)
if bc == nil {
return
}
switch {
case bc.Status == corev1.ConditionUnknown:
revCondSet.Manage(rs).MarkUnknown(RevisionConditionBuildSucceeded, "Building", bc.Message)
case bc.Status == corev1.ConditionTrue:
revCondSet.Manage(rs).MarkTrue(RevisionConditionBuildSucceeded)
case bc.Status == corev1.ConditionFalse:
revCondSet.Manage(rs).MarkFalse(RevisionConditionBuildSucceeded, bc.Reason, bc.Message)
}
}
func (rs *RevisionStatus) MarkDeploying(reason string) {
revCondSet.Manage(rs).MarkUnknown(RevisionConditionResourcesAvailable, reason, "")
revCondSet.Manage(rs).MarkUnknown(RevisionConditionContainerHealthy, reason, "")
}
func (rs *RevisionStatus) MarkServiceTimeout() {
revCondSet.Manage(rs).MarkFalse(RevisionConditionResourcesAvailable, "ServiceTimeout",
"Timed out waiting for a service endpoint to become ready")
}
func (rs *RevisionStatus) MarkProgressDeadlineExceeded(message string) {
revCondSet.Manage(rs).MarkFalse(RevisionConditionResourcesAvailable, "ProgressDeadlineExceeded", message)
}
func (rs *RevisionStatus) MarkContainerHealthy() {
revCondSet.Manage(rs).MarkTrue(RevisionConditionContainerHealthy)
}
func (rs *RevisionStatus) MarkResourcesAvailable() {
revCondSet.Manage(rs).MarkTrue(RevisionConditionResourcesAvailable)
}
func (rs *RevisionStatus) MarkActive() {
revCondSet.Manage(rs).MarkTrue(RevisionConditionActive)
}
func (rs *RevisionStatus) MarkActivating(reason, message string) {
revCondSet.Manage(rs).MarkUnknown(RevisionConditionActive, reason, message)
}
func (rs *RevisionStatus) MarkInactive(reason, message string) {
revCondSet.Manage(rs).MarkFalse(RevisionConditionActive, reason, message)
}
func (rs *RevisionStatus) MarkContainerMissing(message string) {
revCondSet.Manage(rs).MarkFalse(RevisionConditionContainerHealthy, "ContainerMissing", message)
}
// GetConditions returns the Conditions array. This enables generic handling of
// conditions by implementing the duckv1alpha1.Conditions interface.
func (rs *RevisionStatus) GetConditions() duckv1alpha1.Conditions {
return rs.Conditions
}
// SetConditions sets the Conditions array. This enables generic handling of
// conditions by implementing the duckv1alpha1.Conditions interface.
func (rs *RevisionStatus) SetConditions(conditions duckv1alpha1.Conditions) {
rs.Conditions = conditions
}
const (
AnnotationParseErrorTypeMissing = "Missing"
AnnotationParseErrorTypeInvalid = "Invalid"
)
// +k8s:deepcopy-gen=false
type AnnotationParseError struct {
Type string
Value string
Err error
}
// +k8s:deepcopy-gen=false
type LastPinnedParseError AnnotationParseError
func (e LastPinnedParseError) Error() string {
return fmt.Sprintf("%v lastPinned value: %q", e.Type, e.Value)
}
// +k8s:deepcopy-gen=false
type configurationGenerationParseError AnnotationParseError
func (e configurationGenerationParseError) Error() string {
return fmt.Sprintf("%v configurationGeneration value: %q", e.Type, e.Value)
}
func RevisionLastPinnedString(t time.Time) string {
return fmt.Sprintf("%d", t.Unix())
}
func (r *Revision) SetLastPinned(t time.Time) {
if r.ObjectMeta.Annotations == nil {
r.ObjectMeta.Annotations = make(map[string]string)
}
r.ObjectMeta.Annotations[serving.RevisionLastPinnedAnnotationKey] = RevisionLastPinnedString(t)
}
func (r *Revision) GetLastPinned() (time.Time, error) {
if r.Annotations == nil {
return time.Time{}, LastPinnedParseError{
Type: AnnotationParseErrorTypeMissing,
}
}
str, ok := r.ObjectMeta.Annotations[serving.RevisionLastPinnedAnnotationKey]
if !ok {
// If a revision is past the create delay without an annotation it is stale
return time.Time{}, LastPinnedParseError{
Type: AnnotationParseErrorTypeMissing,
}
}
secs, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return time.Time{}, LastPinnedParseError{
Type: AnnotationParseErrorTypeInvalid,
Value: str,
Err: err,
}
}
return time.Unix(secs, 0), nil
}
func (r *Revision) GetConfigurationGeneration() (int64, error) {
if r.Annotations == nil {
return 0, configurationGenerationParseError{
Type: AnnotationParseErrorTypeMissing,
}
}
str, ok := r.ObjectMeta.Annotations[serving.ConfigurationGenerationAnnotationKey]
if !ok {
return 0, configurationGenerationParseError{
Type: AnnotationParseErrorTypeMissing,
}
}
gen, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return 0, configurationGenerationParseError{
Type: AnnotationParseErrorTypeInvalid,
Value: str,
Err: err,
}
}
return gen, nil
}