/
addondeploymentconfig.go
466 lines (406 loc) · 17.3 KB
/
addondeploymentconfig.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
package addonfactory
import (
"context"
"encoding/json"
"fmt"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/klog/v2"
addonapiv1alpha1 "open-cluster-management.io/api/addon/v1alpha1"
addonv1alpha1client "open-cluster-management.io/api/client/addon/clientset/versioned"
clusterv1 "open-cluster-management.io/api/cluster/v1"
"open-cluster-management.io/addon-framework/pkg/utils"
)
// Deprecated: use AddOnDeploymentConfigGVR in package "open-cluster-management.io/addon-framework/pkg/utils" instead.
var AddOnDeploymentConfigGVR = schema.GroupVersionResource{
Group: "addon.open-cluster-management.io",
Version: "v1alpha1",
Resource: "addondeploymentconfigs",
}
// AddOnDeloymentConfigToValuesFunc transform the AddOnDeploymentConfig object into Values object
// The transformation logic depends on the definition of the addon template
// Deprecated: use AddOnDeploymentConfigToValuesFunc instead.
type AddOnDeloymentConfigToValuesFunc func(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error)
// NewAddOnDeloymentConfigGetter returns a AddOnDeloymentConfigGetter with addon client
// Deprecated: use NewAddOnDeploymentConfigGetter in pkg/utils package instead.
func NewAddOnDeloymentConfigGetter(addonClient addonv1alpha1client.Interface) utils.AddOnDeploymentConfigGetter {
return utils.NewAddOnDeploymentConfigGetter(addonClient)
}
// GetAddOnDeloymentConfigValues uses AddOnDeloymentConfigGetter to get the AddOnDeploymentConfig object, then
// uses AddOnDeloymentConfigToValuesFunc to transform the AddOnDeploymentConfig object to Values object
// If there are multiple AddOnDeploymentConfig objects in the AddOn ConfigReferences, the big index object will
// override the one from small index
// Deprecated: use GetAddOnDeploymentConfigValues instead.
func GetAddOnDeloymentConfigValues(
getter utils.AddOnDeploymentConfigGetter, toValuesFuncs ...AddOnDeloymentConfigToValuesFunc) GetValuesFunc {
return func(cluster *clusterv1.ManagedCluster, addon *addonapiv1alpha1.ManagedClusterAddOn) (Values, error) {
var lastValues = Values{}
for _, config := range addon.Status.ConfigReferences {
if config.ConfigGroupResource.Group != utils.AddOnDeploymentConfigGVR.Group ||
config.ConfigGroupResource.Resource != utils.AddOnDeploymentConfigGVR.Resource {
continue
}
addOnDeploymentConfig, err := getter.Get(context.Background(), config.Namespace, config.Name)
if err != nil {
return nil, err
}
for _, toValuesFunc := range toValuesFuncs {
values, err := toValuesFunc(*addOnDeploymentConfig)
if err != nil {
return nil, err
}
lastValues = MergeValues(lastValues, values)
}
}
return lastValues, nil
}
}
// ToAddOnDeloymentConfigValues transform the AddOnDeploymentConfig object into Values object that is a plain value map
// for example: the spec of one AddOnDeploymentConfig is:
//
// {
// customizedVariables: [{name: "Image", value: "img"}, {name: "ImagePullPolicy", value: "Always"}],
// nodePlacement: {nodeSelector: {"host": "ssd"}, tolerations: {"key": "test"}},
// }
//
// after transformed, the key set of Values object will be: {"Image", "ImagePullPolicy", "NodeSelector", "Tolerations"}
// Deprecated: use ToAddOnDeploymentConfigValues instead.
func ToAddOnDeloymentConfigValues(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error) {
values, err := ToAddOnCustomizedVariableValues(config)
if err != nil {
return nil, err
}
if config.Spec.NodePlacement != nil {
values["NodeSelector"] = config.Spec.NodePlacement.NodeSelector
values["Tolerations"] = config.Spec.NodePlacement.Tolerations
}
return values, nil
}
// ToAddOnNodePlacementValues only transform the AddOnDeploymentConfig NodePlacement part into Values object that has
// a specific for helm chart values
// for example: the spec of one AddOnDeploymentConfig is:
//
// {
// nodePlacement: {nodeSelector: {"host": "ssd"}, tolerations: {"key":"test"}},
// }
//
// after transformed, the Values will be:
// map[global:map[nodeSelector:map[host:ssd]] tolerations:[map[key:test]]]
func ToAddOnNodePlacementValues(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error) {
if config.Spec.NodePlacement == nil {
return nil, nil
}
type global struct {
NodeSelector map[string]string `json:"nodeSelector"`
}
jsonStruct := struct {
Tolerations []corev1.Toleration `json:"tolerations"`
Global global `json:"global"`
}{
Tolerations: config.Spec.NodePlacement.Tolerations,
Global: global{
NodeSelector: config.Spec.NodePlacement.NodeSelector,
},
}
values, err := JsonStructToValues(jsonStruct)
if err != nil {
return nil, err
}
return values, nil
}
// ToAddOnProxyConfigValues transform the spec.proxyConfig of AddOnDeploymentConfig into Values object that has
// a specific for helm chart values
// for example: the spec of one AddOnDeploymentConfig is:
//
// {
// proxyConfig: {"httpProxy": "http://10.11.12.13:3128", "httpsProxy": "https://10.11.12.13:3129", "noProxy": "example.com"},
// }
//
// after transformed, the Values will be:
// map[global:map[proxyConfig:map[httpProxy:http://10.11.12.13:3128 httpsProxy:https://10.11.12.13:3129 noProxy:example.com]]]
func ToAddOnProxyConfigValues(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error) {
proxyConfig := map[string]string{}
if len(config.Spec.ProxyConfig.HTTPProxy) > 0 {
proxyConfig["HTTP_PROXY"] = config.Spec.ProxyConfig.HTTPProxy
}
if len(config.Spec.ProxyConfig.HTTPSProxy) > 0 {
proxyConfig["HTTPS_PROXY"] = config.Spec.ProxyConfig.HTTPSProxy
}
if len(proxyConfig) == 0 {
return nil, nil
}
if len(config.Spec.ProxyConfig.NoProxy) > 0 {
proxyConfig["NO_PROXY"] = config.Spec.ProxyConfig.NoProxy
}
if len(config.Spec.ProxyConfig.CABundle) > 0 {
proxyConfig["PROXY_CA_BUNDLE"] = string(config.Spec.ProxyConfig.CABundle)
}
type global struct {
ProxyConfig map[string]string `json:"proxyConfig"`
}
jsonStruct := struct {
Global global `json:"global"`
}{
Global: global{
ProxyConfig: proxyConfig,
},
}
values, err := JsonStructToValues(jsonStruct)
if err != nil {
return nil, err
}
return values, nil
}
// ToAddOnCustomizedVariableValues only transform the CustomizedVariables in the spec of AddOnDeploymentConfig into Values object.
// for example: the spec of one AddOnDeploymentConfig is:
//
// {
// customizedVariables: [{name: "a", value: "x"}, {name: "b", value: "y"}],
// }
//
// after transformed, the Values will be:
// map[a:x b:y]
func ToAddOnCustomizedVariableValues(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error) {
values := Values{}
for _, variable := range config.Spec.CustomizedVariables {
values[variable.Name] = variable.Value
}
return values, nil
}
// AddOnDeploymentConfigToValuesFunc transform the AddOnDeploymentConfig object into Values object
// The transformation logic depends on the definition of the addon template
type AddOnDeploymentConfigToValuesFunc func(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error)
// NewAddOnDeploymentConfigGetter returns a AddOnDeploymentConfigGetter with addon client
// Deprecated: use NewAddOnDeploymentConfigGetter in pkg/utils package instead.
func NewAddOnDeploymentConfigGetter(addonClient addonv1alpha1client.Interface) utils.AddOnDeploymentConfigGetter {
return utils.NewAddOnDeploymentConfigGetter(addonClient)
}
// GetAddOnDeploymentConfigValues uses AddOnDeploymentConfigGetter to get the AddOnDeploymentConfig object, then
// uses AddOnDeploymentConfigToValuesFunc to transform the AddOnDeploymentConfig object to Values object
// If there are multiple AddOnDeploymentConfig objects in the AddOn ConfigReferences, the big index object will
// override the one from small index
func GetAddOnDeploymentConfigValues(
getter utils.AddOnDeploymentConfigGetter, toValuesFuncs ...AddOnDeploymentConfigToValuesFunc) GetValuesFunc {
return func(cluster *clusterv1.ManagedCluster, addon *addonapiv1alpha1.ManagedClusterAddOn) (Values, error) {
var lastValues = Values{}
for _, config := range addon.Status.ConfigReferences {
if config.ConfigGroupResource.Group != utils.AddOnDeploymentConfigGVR.Group ||
config.ConfigGroupResource.Resource != utils.AddOnDeploymentConfigGVR.Resource {
continue
}
addOnDeploymentConfig, err := getter.Get(context.Background(), config.Namespace, config.Name)
if err != nil {
return nil, err
}
for _, toValuesFunc := range toValuesFuncs {
values, err := toValuesFunc(*addOnDeploymentConfig)
if err != nil {
return nil, err
}
lastValues = MergeValues(lastValues, values)
}
}
return lastValues, nil
}
}
// ToAddOnDeploymentConfigValues transform the AddOnDeploymentConfig object into Values object that is a plain value map
// for example: the spec of one AddOnDeploymentConfig is:
//
// {
// customizedVariables: [{name: "Image", value: "img"}, {name: "ImagePullPolicy", value: "Always"}],
// nodePlacement: {nodeSelector: {"host": "ssd"}, tolerations: {"key": "test"}},
// }
//
// after transformed, the key set of Values object will be: {"Image", "ImagePullPolicy", "NodeSelector", "Tolerations"}
func ToAddOnDeploymentConfigValues(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error) {
values, err := ToAddOnCustomizedVariableValues(config)
if err != nil {
return nil, err
}
if config.Spec.NodePlacement != nil {
values["NodeSelector"] = config.Spec.NodePlacement.NodeSelector
values["Tolerations"] = config.Spec.NodePlacement.Tolerations
}
// load add-on proxy settings
if len(config.Spec.ProxyConfig.HTTPProxy) > 0 {
values["HTTPProxy"] = config.Spec.ProxyConfig.HTTPProxy
}
if len(config.Spec.ProxyConfig.HTTPSProxy) > 0 {
values["HTTPSProxy"] = config.Spec.ProxyConfig.HTTPSProxy
}
if len(config.Spec.ProxyConfig.NoProxy) > 0 {
values["NoProxy"] = config.Spec.ProxyConfig.NoProxy
}
if len(config.Spec.ProxyConfig.CABundle) > 0 {
values["ProxyCABundle"] = string(config.Spec.ProxyConfig.CABundle)
}
return values, nil
}
// ToImageOverrideValuesFunc return a func that can use the AddOnDeploymentConfig.spec.Registries to override image,
// then return the overridden value with key imageKey.
//
// for example: the spec of one AddOnDeploymentConfig is:
// { registries: [{source: "quay.io/open-cluster-management/addon-agent", mirror: "quay.io/ocm/addon-agent"}]}
// the imageKey is "helloWorldImage", the image is "quay.io/open-cluster-management/addon-agent:v1"
// after transformed, the Values object will be: {"helloWorldImage": "quay.io/ocm/addon-agent:v1"}
//
// Note:
// - the imageKey can support the nested key, for example: "global.imageOverrides.helloWorldImage", the output
// will be: {"global": {"imageOverrides": {"helloWorldImage": "quay.io/ocm/addon-agent:v1"}}}
// - If you want to override the image with the value from the AddOnDeploymentConfig.spec.Registries first, and
// if it is not changed, then override it with the value from the cluster annotation, you can use the function
// GetAgentImageValues instead.
func ToImageOverrideValuesFunc(imageKey, image string) AddOnDeploymentConfigToValuesFunc {
return func(config addonapiv1alpha1.AddOnDeploymentConfig) (Values, error) {
values, _, err := overrideImageWithKeyValue(imageKey, image, getRegistriesFromAddonDeploymentConfig(config))
return values, err
}
}
func getRegistriesFromAddonDeploymentConfig(
config addonapiv1alpha1.AddOnDeploymentConfig) func() ([]addonapiv1alpha1.ImageMirror, error) {
return func() ([]addonapiv1alpha1.ImageMirror, error) {
return config.Spec.Registries, nil
}
}
func getRegistriesFromClusterAnnotation(
cluster *clusterv1.ManagedCluster) func() ([]addonapiv1alpha1.ImageMirror, error) {
return func() ([]addonapiv1alpha1.ImageMirror, error) {
if cluster == nil {
return nil, nil
}
annotations := cluster.GetAnnotations()
klog.V(4).Infof("Try to get image registries from annotation %v", annotations[clusterv1.ClusterImageRegistriesAnnotationKey])
if len(annotations[clusterv1.ClusterImageRegistriesAnnotationKey]) == 0 {
return nil, nil
}
type ImageRegistries struct {
Registries []addonapiv1alpha1.ImageMirror `json:"registries"`
}
imageRegistries := ImageRegistries{}
err := json.Unmarshal([]byte(annotations[clusterv1.ClusterImageRegistriesAnnotationKey]), &imageRegistries)
if err != nil {
klog.Errorf("failed to unmarshal the annotation %v, err %v", annotations[clusterv1.ClusterImageRegistriesAnnotationKey], err)
return nil, err
}
return imageRegistries.Registries, nil
}
}
// GetAgentImageValues return a func that can use two ways, AddOnDeploymentConfig.spec.Registries and annotation on the
// ManagedCluster, to override image, then return the overridden value with key imageKey.
// For example:
//
// 1. configure the image registries with the spec of the AddOnDeploymentConfig, if the registries in the spec is:
// {...,"spec":{"registries":[{"mirror":"quay.io/ocm/addon-agent","source":"quay.io/open-cluster-management/addon-agent"}]}}
// the "imageKey" is "helloWorldImage", the "image" is "quay.io/open-cluster-management/addon-agent:v1"
// after transformed, the Values object will be: {"helloWorldImage": "quay.io/ocm/addon-agent:v1"}
//
// 2. configure the image registries with the annotation "open-cluster-management.io/image-registries" on the
// ManagedCluster, if the annotation on the managed cluster resource is:
// "open-cluster-management.io/image-registries": '{"registries":[{"mirror":"quay.io/ocm","source":"quay.io/open-cluster-management"}]}'
// the "imageKey" is "helloWorldImage", the "image" is "quay.io/open-cluster-management/addon-agent:v1"
// after transformed, the Values object will be: {"helloWorldImage": "quay.io/ocm/addon-agent:v1"}
//
// Note:
// - the imageKey can support the nested key, for example: "global.imageOverrides.helloWorldImage", the output
// will be: {"global": {"imageOverrides": {"helloWorldImage": "quay.io/ocm/addon-agent:v1"}}}
// - Image registries configured in the addonDeploymentConfig will take precedence over the managed cluster annotation
func GetAgentImageValues(getter utils.AddOnDeploymentConfigGetter, imageKey, image string) GetValuesFunc {
return func(cluster *clusterv1.ManagedCluster, addon *addonapiv1alpha1.ManagedClusterAddOn) (Values, error) {
// Get image from AddOnDeploymentConfig
for _, config := range addon.Status.ConfigReferences {
if config.ConfigGroupResource.Group != utils.AddOnDeploymentConfigGVR.Group ||
config.ConfigGroupResource.Resource != utils.AddOnDeploymentConfigGVR.Resource {
continue
}
addOnDeploymentConfig, err := getter.Get(context.Background(), config.Namespace, config.Name)
if err != nil {
return nil, err
}
values, overrode, err := overrideImageWithKeyValue(imageKey, image,
getRegistriesFromAddonDeploymentConfig(*addOnDeploymentConfig))
if err != nil {
return values, err
}
// if the image is overrode by AddOnDeploymentConfig, use the overrode value
if overrode {
klog.V(4).Infof("Overrode image %v with %v", image, values)
return values, nil
}
}
// If the image is not overrode by AddOnDeploymentConfig, try to get image from cluster annotation
values, _, err := overrideImageWithKeyValue(imageKey, image, getRegistriesFromClusterAnnotation(cluster))
if err != nil {
return values, err
}
return values, nil
}
}
func overrideImageWithKeyValue(imageKey, image string, getRegistries func() ([]addonapiv1alpha1.ImageMirror, error),
) (Values, bool, error) {
if len(imageKey) == 0 {
return nil, false, fmt.Errorf("imageKey is empty")
}
if len(image) == 0 {
return nil, false, fmt.Errorf("image is empty")
}
nestedMap := make(map[string]interface{})
keys := strings.Split(imageKey, ".")
currentMap := nestedMap
for i := 0; i < len(keys)-1; i++ {
key := keys[i]
nextMap := make(map[string]interface{})
currentMap[key] = nextMap
currentMap = nextMap
}
lastKey := keys[len(keys)-1]
currentMap[lastKey] = image
registries, err := getRegistries()
if err != nil {
klog.Errorf("failed to get image registries, err %v", err)
return nestedMap, false, err
}
overrode := false
klog.V(4).Infof("Image registries values %v", registries)
if registries != nil {
overrodeImage := OverrideImage(registries, image)
currentMap[lastKey] = overrodeImage
if overrodeImage != image {
overrode = true
}
}
return nestedMap, overrode, nil
}
// OverrideImage checks whether the source configured in registries can match the imagedName, if yes will use the
// mirror value in the registries to override the imageName
func OverrideImage(registries []addonapiv1alpha1.ImageMirror, imageName string) string {
if len(registries) == 0 {
return imageName
}
overrideImageName := imageName
for i := 0; i < len(registries); i++ {
registry := registries[i]
name := overrideImageDirectly(registry.Source, registry.Mirror, imageName)
if name != imageName {
overrideImageName = name
}
}
return overrideImageName
}
func overrideImageDirectly(source, mirror, imageName string) string {
source = strings.TrimSuffix(source, "/")
mirror = strings.TrimSuffix(mirror, "/")
imageSegments := strings.Split(imageName, "/")
imageNameTag := imageSegments[len(imageSegments)-1]
if source == "" {
if mirror == "" {
return imageNameTag
}
return fmt.Sprintf("%s/%s", mirror, imageNameTag)
}
if !strings.HasPrefix(imageName, source) {
return imageName
}
trimSegment := strings.TrimPrefix(imageName, source)
return fmt.Sprintf("%s%s", mirror, trimSegment)
}