-
Notifications
You must be signed in to change notification settings - Fork 263
/
config_changes.go
275 lines (242 loc) · 9.07 KB
/
config_changes.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
// 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 serving
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
corev1 "k8s.io/api/core/v1"
"knative.dev/serving/pkg/apis/autoscaling"
servingv1alpha1 "knative.dev/serving/pkg/apis/serving/v1alpha1"
servingv1beta1 "knative.dev/serving/pkg/apis/serving/v1beta1"
)
var UserImageAnnotationKey = "client.knative.dev/user-image"
// UpdateEnvVars gives the configuration all the env var values listed in the given map of
// vars. Does not touch any environment variables not mentioned, but it can add
// new env vars and change the values of existing ones.
func UpdateEnvVars(template *servingv1alpha1.RevisionTemplateSpec, toUpdate []corev1.EnvVar, toRemove map[string]bool) error {
container, err := ContainerOfRevisionTemplate(template)
if err != nil {
return err
}
envVars := mergeEnvVarsWithStableOrder(container.Env, toUpdate, toRemove)
container.Env = envVars
return nil
}
// UpdateMinScale updates min scale annotation
func UpdateMinScale(template *servingv1alpha1.RevisionTemplateSpec, min int) error {
return UpdateAnnotation(template, autoscaling.MinScaleAnnotationKey, strconv.Itoa(min))
}
// UpdatMaxScale updates max scale annotation
func UpdateMaxScale(template *servingv1alpha1.RevisionTemplateSpec, max int) error {
return UpdateAnnotation(template, autoscaling.MaxScaleAnnotationKey, strconv.Itoa(max))
}
// UpdateConcurrencyTarget updates container concurrency annotation
func UpdateConcurrencyTarget(template *servingv1alpha1.RevisionTemplateSpec, target int) error {
// TODO(toVersus): Remove the following validation once serving library is updated to v0.8.0
// and just rely on ValidateAnnotations method.
if target < autoscaling.TargetMin {
return fmt.Errorf("invalid 'concurrency-target' value: must be an integer greater than 0: %s",
autoscaling.TargetAnnotationKey)
}
return UpdateAnnotation(template, autoscaling.TargetAnnotationKey, strconv.Itoa(target))
}
// UpdateConcurrencyLimit updates container concurrency limit
func UpdateConcurrencyLimit(template *servingv1alpha1.RevisionTemplateSpec, limit int) error {
cc := servingv1beta1.RevisionContainerConcurrencyType(limit)
// Validate input limit
ctx := context.Background()
if err := cc.Validate(ctx).ViaField("spec.containerConcurrency"); err != nil {
return fmt.Errorf("invalid 'concurrency-limit' value: %s", err)
}
template.Spec.ContainerConcurrency = cc
return nil
}
// UpdateAnnotation updates (or adds) an annotation to the given service
func UpdateAnnotation(template *servingv1alpha1.RevisionTemplateSpec, annotation string, value string) error {
annoMap := template.Annotations
if annoMap == nil {
annoMap = make(map[string]string)
template.Annotations = annoMap
}
// Validate autoscaling annotations and returns error if invalid input provided
// without changing the existing spec
in := make(map[string]string)
in[annotation] = value
if err := autoscaling.ValidateAnnotations(in); err != nil {
return err
}
annoMap[annotation] = value
return nil
}
var ApiTooOldError = errors.New("the service is using too old of an API format for the operation")
// UpdateName updates the revision name.
func UpdateName(template *servingv1alpha1.RevisionTemplateSpec, name string) error {
if template.Spec.DeprecatedContainer != nil {
return ApiTooOldError
}
template.Name = name
return nil
}
// EnvToMap is an utility function to translate between the API list form of env vars, and the
// more convenient map form.
func EnvToMap(vars []corev1.EnvVar) (map[string]string, error) {
result := map[string]string{}
for _, envVar := range vars {
_, present := result[envVar.Name]
if present {
return nil, fmt.Errorf("env var name present more than once: %v", envVar.Name)
}
result[envVar.Name] = envVar.Value
}
return result, nil
}
// UpdateImage a given image
func UpdateImage(template *servingv1alpha1.RevisionTemplateSpec, image string) error {
// When not setting the image to a digest, add the user image annotation.
container, err := ContainerOfRevisionTemplate(template)
if err != nil {
return err
}
container.Image = image
return nil
}
// UnsetUserImageAnnot removes the user image annotation
func UnsetUserImageAnnot(template *servingv1alpha1.RevisionTemplateSpec) {
delete(template.Annotations, UserImageAnnotationKey)
}
// SetUserImageAnnot sets the user image annotation if the image isn't by-digest already.
func SetUserImageAnnot(template *servingv1alpha1.RevisionTemplateSpec) {
// If the current image isn't by-digest, set the user-image annotation to it
// so we remember what it was.
currentContainer, _ := ContainerOfRevisionTemplate(template)
ui := currentContainer.Image
if strings.Contains(ui, "@") {
prev, ok := template.Annotations[UserImageAnnotationKey]
if ok {
ui = prev
}
}
if template.Annotations == nil {
template.Annotations = make(map[string]string)
}
template.Annotations[UserImageAnnotationKey] = ui
}
// FreezeImageToDigest sets the image on the template to the image digest of the base revision.
func FreezeImageToDigest(template *servingv1alpha1.RevisionTemplateSpec, baseRevision *servingv1alpha1.Revision) error {
currentContainer, err := ContainerOfRevisionTemplate(template)
if baseRevision == nil {
return nil
}
baseContainer, err := ContainerOfRevisionSpec(&baseRevision.Spec)
if err != nil {
return err
}
if currentContainer.Image != baseContainer.Image {
return fmt.Errorf("could not freeze image to digest since current revision contains unexpected image.")
}
if baseRevision.Status.ImageDigest != "" {
return UpdateImage(template, baseRevision.Status.ImageDigest)
}
return nil
}
// UpdateContainerPort updates container with a give port
func UpdateContainerPort(template *servingv1alpha1.RevisionTemplateSpec, port int32) error {
container, err := ContainerOfRevisionTemplate(template)
if err != nil {
return err
}
container.Ports = []corev1.ContainerPort{{
ContainerPort: port,
}}
return nil
}
// UpdateResources updates resources as requested
func UpdateResources(template *servingv1alpha1.RevisionTemplateSpec, requestsResourceList corev1.ResourceList, limitsResourceList corev1.ResourceList) error {
container, err := ContainerOfRevisionTemplate(template)
if err != nil {
return err
}
if container.Resources.Requests == nil {
container.Resources.Requests = corev1.ResourceList{}
}
for k, v := range requestsResourceList {
container.Resources.Requests[k] = v
}
if container.Resources.Limits == nil {
container.Resources.Limits = corev1.ResourceList{}
}
for k, v := range limitsResourceList {
container.Resources.Limits[k] = v
}
return nil
}
// UpdateLabels updates the labels identically on a service and template.
// Does not overwrite the entire Labels field, only makes the requested updates
func UpdateLabels(service *servingv1alpha1.Service, template *servingv1alpha1.RevisionTemplateSpec, toUpdate map[string]string, toRemove []string) error {
if service.ObjectMeta.Labels == nil {
service.ObjectMeta.Labels = make(map[string]string)
}
if template.ObjectMeta.Labels == nil {
template.ObjectMeta.Labels = make(map[string]string)
}
for key, value := range toUpdate {
service.ObjectMeta.Labels[key] = value
template.ObjectMeta.Labels[key] = value
}
for _, key := range toRemove {
delete(service.ObjectMeta.Labels, key)
delete(template.ObjectMeta.Labels, key)
}
return nil
}
// =======================================================================================
func mergeEnvVarsWithStableOrder(src []corev1.EnvVar, target []corev1.EnvVar, toRemove map[string]bool) []corev1.EnvVar {
// dict records all EnvVars with fixed capacity
dict := make(map[string]string, len(src)+len(target))
for _, v := range target {
dict[v.Name] = v.Value
}
srcUpdated := src[:0]
for _, v := range src {
// Register only non-duplicated EnvVars, which results in overwriting old EnvVars
if _, ok := dict[v.Name]; ok {
// Don't change the order of updated items
srcUpdated = append(srcUpdated, v)
continue
}
if _, ok := toRemove[v.Name]; !ok {
dict[v.Name] = v.Value
// Only append non-duplicated key-value pair
srcUpdated = append(srcUpdated, v)
}
}
// merged EnvVars keep the original order of equal elements
merged := []corev1.EnvVar{}
for _, v := range srcUpdated {
if _, ok := dict[v.Name]; ok {
merged = append(merged, corev1.EnvVar{Name: v.Name, Value: dict[v.Name]})
// Delete dict item for avoiding duplicated entries
delete(dict, v.Name)
}
}
for _, v := range target {
if _, ok := dict[v.Name]; ok {
merged = append(merged, corev1.EnvVar{Name: v.Name, Value: dict[v.Name]})
}
}
return merged
}