forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cluster_store.go
486 lines (416 loc) · 16.2 KB
/
cluster_store.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
package cluster
import (
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/store/transform"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/norman/types/values"
ccluster "github.com/rancher/rancher/pkg/api/customization/cluster"
"github.com/rancher/rancher/pkg/clustermanager"
"github.com/rancher/rancher/pkg/controllers/management/clusterprovisioner"
"github.com/rancher/rancher/pkg/controllers/management/clusterstatus"
"github.com/rancher/rancher/pkg/settings"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
managementv3 "github.com/rancher/types/client/management/v3"
"github.com/rancher/types/config"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/labels"
)
const (
DefaultBackupIntervalHours = 12
DefaultBackupRetention = 6
)
type Store struct {
types.Store
ShellHandler types.RequestHandler
mu sync.Mutex
KontainerDriverLister v3.KontainerDriverLister
}
type transformer struct {
KontainerDriverLister v3.KontainerDriverLister
}
func (t *transformer) TransformerFunc(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}, opt *types.QueryOptions) (map[string]interface{}, error) {
data = transformSetNilSnapshotFalse(data)
return t.transposeGenericConfigToDynamicField(data)
}
//transposeGenericConfigToDynamicField converts a genericConfig to one usable by rancher and maps a kontainer id to a kontainer name
func (t *transformer) transposeGenericConfigToDynamicField(data map[string]interface{}) (map[string]interface{}, error) {
if data["genericEngineConfig"] != nil {
drivers, err := t.KontainerDriverLister.List("", labels.Everything())
if err != nil {
return nil, err
}
var driver *v3.KontainerDriver
driverName := data["genericEngineConfig"].(map[string]interface{})[clusterprovisioner.DriverNameField].(string)
// iterate over kontainer drivers to find the one that maps to the genericEngineConfig DriverName ("kd-**") -> "example"
for _, candidate := range drivers {
if driverName == candidate.Name {
driver = candidate
break
}
}
if driver == nil {
logrus.Warnf("unable to find the kontainer driver %v that maps to %v", driverName, data[clusterprovisioner.DriverNameField])
return data, nil
}
var driverTypeName string
if driver.Spec.BuiltIn {
driverTypeName = driver.Status.DisplayName + "Config"
} else {
driverTypeName = driver.Status.DisplayName + "EngineConfig"
}
data[driverTypeName] = data["genericEngineConfig"]
delete(data, "genericEngineConfig")
}
return data, nil
}
func SetClusterStore(schema *types.Schema, mgmt *config.ScaledContext, clusterManager *clustermanager.Manager, k8sProxy http.Handler) {
transformer := transformer{
KontainerDriverLister: mgmt.Management.KontainerDrivers("").Controller().Lister(),
}
t := &transform.Store{
Store: schema.Store,
Transformer: transformer.TransformerFunc,
}
linkHandler := &ccluster.ShellLinkHandler{
Proxy: k8sProxy,
ClusterManager: clusterManager,
}
s := &Store{
Store: t,
KontainerDriverLister: mgmt.Management.KontainerDrivers("").Controller().Lister(),
ShellHandler: linkHandler.LinkHandler,
}
schema.Store = s
}
func transformSetNilSnapshotFalse(data map[string]interface{}) map[string]interface{} {
var (
etcd interface{}
found bool
)
etcd, found = values.GetValue(data, "appliedSpec", "rancherKubernetesEngineConfig", "services", "etcd")
if found {
etcd := convert.ToMapInterface(etcd)
val, found := values.GetValue(etcd, "snapshot")
if !found || val == nil {
values.PutValue(data, false, "appliedSpec", "rancherKubernetesEngineConfig", "services", "etcd", "snapshot")
}
}
etcd, found = values.GetValue(data, "rancherKubernetesEngineConfig", "services", "etcd")
if found {
etcd := convert.ToMapInterface(etcd)
val, found := values.GetValue(etcd, "snapshot")
if !found || val == nil {
values.PutValue(data, false, "rancherKubernetesEngineConfig", "services", "etcd", "snapshot")
}
}
return data
}
func (r *Store) ByID(apiContext *types.APIContext, schema *types.Schema, id string) (map[string]interface{}, error) {
// Really we want a link handler but the URL parse makes it impossible to add links to clusters for now. So this
// is basically a hack
if apiContext.Query.Get("shell") == "true" {
return nil, r.ShellHandler(apiContext, nil)
}
return r.Store.ByID(apiContext, schema, id)
}
func (r *Store) Create(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}) (map[string]interface{}, error) {
name := convert.ToString(data["name"])
if name == "" {
return nil, httperror.NewFieldAPIError(httperror.MissingRequired, "Cluster name", "")
}
r.mu.Lock()
defer r.mu.Unlock()
if err := canUseClusterName(apiContext, name); err != nil {
return nil, err
}
setKubernetesVersion(data)
// enable local backups for rke clusters by default
enableLocalBackup(data)
data, err := r.transposeDynamicFieldToGenericConfig(data)
if err != nil {
return nil, err
}
if err := validateNetworkFlag(data, true); err != nil {
return nil, httperror.NewFieldAPIError(httperror.InvalidOption, "enableNetworkPolicy", err.Error())
}
if driverName, _ := values.GetValue(data, "genericEngineConfig", "driverName"); driverName == "amazonelasticcontainerservice" {
sessionToken, _ := values.GetValue(data, "genericEngineConfig", "sessionToken")
annotation, _ := values.GetValue(data, managementv3.ClusterFieldAnnotations)
m := toMap(annotation)
m[clusterstatus.TemporaryCredentialsAnnotationKey] = strconv.FormatBool(
sessionToken != "" && sessionToken != nil)
values.PutValue(data, m, managementv3.ClusterFieldAnnotations)
}
if err = setInitialConditions(data); err != nil {
return nil, err
}
return r.Store.Create(apiContext, schema, data)
}
func setInitialConditions(data map[string]interface{}) error {
if data[managementv3.ClusterStatusFieldConditions] == nil {
data[managementv3.ClusterStatusFieldConditions] = []map[string]interface{}{}
}
conditions, ok := data[managementv3.ClusterStatusFieldConditions].([]map[string]interface{})
if !ok {
return fmt.Errorf("unable to parse field \"%v\" type \"%v\" as \"[]map[string]interface{}\"",
managementv3.ClusterStatusFieldConditions, reflect.TypeOf(data[managementv3.ClusterStatusFieldConditions]))
}
for key := range data {
if strings.Index(key, "Config") == len(key)-6 {
data[managementv3.ClusterStatusFieldConditions] =
append(
conditions,
[]map[string]interface{}{
{
"status": "True",
"type": string(v3.ClusterConditionPending),
},
{
"status": "Unknown",
"type": string(v3.ClusterConditionProvisioned),
},
{
"status": "Unknown",
"type": string(v3.ClusterConditionWaiting),
},
}...,
)
}
}
return nil
}
func toMap(rawMap interface{}) map[string]interface{} {
if theMap, ok := rawMap.(map[string]interface{}); ok {
return theMap
}
return make(map[string]interface{})
}
func (r *Store) Update(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}, id string) (map[string]interface{}, error) {
updatedName := convert.ToString(data["name"])
if updatedName == "" {
return nil, httperror.NewFieldAPIError(httperror.MissingRequired, "Cluster name", "")
}
existingCluster, err := r.ByID(apiContext, schema, id)
if err != nil {
return nil, err
}
clusterName, ok := existingCluster["name"].(string)
if !ok {
clusterName = ""
}
if !strings.EqualFold(updatedName, clusterName) {
r.mu.Lock()
defer r.mu.Unlock()
if err := canUseClusterName(apiContext, updatedName); err != nil {
return nil, err
}
}
setKubernetesVersion(data)
data, err = r.transposeDynamicFieldToGenericConfig(data)
if err != nil {
return nil, err
}
if err := validateNetworkFlag(data, false); err != nil {
return nil, httperror.NewFieldAPIError(httperror.InvalidOption, "enableNetworkPolicy", err.Error())
}
setBackupConfigSecretKeyIfNotExists(existingCluster, data)
setPrivateRegistryPasswordIfNotExists(existingCluster, data)
setCloudProviderPasswordFieldsIfNotExists(existingCluster, data)
return r.Store.Update(apiContext, schema, data, id)
}
// this method moves the cluster config to and from the genericEngineConfig field so that
// the kontainer drivers behave similarly to the existing machine drivers
func (r *Store) transposeDynamicFieldToGenericConfig(data map[string]interface{}) (map[string]interface{}, error) {
dynamicField, err := r.getDynamicField(data)
if err != nil {
return nil, fmt.Errorf("error getting kontainer drivers: %v", err)
}
// No dynamic schema field exists on this cluster so return immediately
if dynamicField == "" {
return data, nil
}
// overwrite generic engine config so it gets saved
data["genericEngineConfig"] = data[dynamicField]
delete(data, dynamicField)
return data, nil
}
func (r *Store) getDynamicField(data map[string]interface{}) (string, error) {
drivers, err := r.KontainerDriverLister.List("", labels.Everything())
if err != nil {
return "", err
}
for _, driver := range drivers {
var driverName string
if driver.Spec.BuiltIn {
driverName = driver.Status.DisplayName + "Config"
} else {
driverName = driver.Status.DisplayName + "EngineConfig"
}
if data[driverName] != nil {
if !(driver.Status.DisplayName == "rancherKubernetesEngine" || driver.Status.DisplayName == "import") {
return driverName, nil
}
}
}
return "", nil
}
func canUseClusterName(apiContext *types.APIContext, requestedName string) error {
var clusters []managementv3.Cluster
if err := access.List(apiContext, apiContext.Version, managementv3.ClusterType, &types.QueryOptions{}, &clusters); err != nil {
return err
}
for _, c := range clusters {
if c.Removed == "" && strings.EqualFold(c.Name, requestedName) {
//cluster exists by this name
return httperror.NewFieldAPIError(httperror.NotUnique, "Cluster name", "")
}
}
return nil
}
func setKubernetesVersion(data map[string]interface{}) {
rkeConfig, ok := values.GetValue(data, "rancherKubernetesEngineConfig")
if ok && rkeConfig != nil {
k8sVersion := values.GetValueN(data, "rancherKubernetesEngineConfig", "kubernetesVersion")
if k8sVersion == nil || k8sVersion == "" {
//set k8s version to system default on the spec
defaultVersion := settings.KubernetesVersion.Get()
values.PutValue(data, defaultVersion, "rancherKubernetesEngineConfig", "kubernetesVersion")
}
}
}
func validateNetworkFlag(data map[string]interface{}, create bool) error {
enableNetworkPolicy := values.GetValueN(data, "enableNetworkPolicy")
rkeConfig := values.GetValueN(data, "rancherKubernetesEngineConfig")
plugin := convert.ToString(values.GetValueN(convert.ToMapInterface(rkeConfig), "network", "plugin"))
if enableNetworkPolicy == nil {
// setting default values for new clusters if value not passed
values.PutValue(data, false, "enableNetworkPolicy")
} else if value := convert.ToBool(enableNetworkPolicy); value {
if rkeConfig == nil {
if create {
values.PutValue(data, false, "enableNetworkPolicy")
return nil
}
return fmt.Errorf("enableNetworkPolicy should be false for non-RKE clusters")
}
if plugin != "canal" {
return fmt.Errorf("plugin %s should have enableNetworkPolicy %v", plugin, !value)
}
}
return nil
}
func enableLocalBackup(data map[string]interface{}) {
rkeConfig, ok := values.GetValue(data, "rancherKubernetesEngineConfig")
if ok && rkeConfig != nil {
legacyConfig := values.GetValueN(data, "rancherKubernetesEngineConfig", "services", "etcd", "snapshot")
if legacyConfig != nil && legacyConfig.(bool) { // don't enable rancher backup if legacy is enabled.
return
}
backupConfig := values.GetValueN(data, "rancherKubernetesEngineConfig", "services", "etcd", "backupConfig")
if backupConfig == nil {
enabled := true
backupConfig = &v3.BackupConfig{
Enabled: &enabled,
IntervalHours: DefaultBackupIntervalHours,
Retention: DefaultBackupRetention,
}
// enable rancher etcd backup
values.PutValue(data, backupConfig, "rancherKubernetesEngineConfig", "services", "etcd", "backupConfig")
}
}
}
func setBackupConfigSecretKeyIfNotExists(oldData, newData map[string]interface{}) {
s3BackupConfig := values.GetValueN(newData, "rancherKubernetesEngineConfig", "services", "etcd", "backupConfig", "s3BackupConfig")
if s3BackupConfig == nil {
return
}
val := convert.ToMapInterface(s3BackupConfig)
if val["secretKey"] != nil {
return
}
oldSecretKey := convert.ToString(values.GetValueN(oldData, "rancherKubernetesEngineConfig", "services", "etcd", "backupConfig", "s3BackupConfig", "secretKey"))
if oldSecretKey != "" {
values.PutValue(newData, oldSecretKey, "rancherKubernetesEngineConfig", "services", "etcd", "backupConfig", "s3BackupConfig", "secretKey")
}
}
func setPrivateRegistryPasswordIfNotExists(oldData, newData map[string]interface{}) {
newSlice, ok := values.GetSlice(newData, "rancherKubernetesEngineConfig", "privateRegistries")
if !ok || newSlice == nil {
return
}
oldSlice, ok := values.GetSlice(oldData, "rancherKubernetesEngineConfig", "privateRegistries")
if !ok || oldSlice == nil {
return
}
var updatedConfig []map[string]interface{}
for _, newConfig := range newSlice {
if newConfig["password"] != nil {
updatedConfig = append(updatedConfig, newConfig)
continue
}
for _, oldConfig := range oldSlice {
if newConfig["url"] == oldConfig["url"] && newConfig["user"] == oldConfig["user"] &&
oldConfig["password"] != nil {
newConfig["password"] = oldConfig["password"]
break
}
}
updatedConfig = append(updatedConfig, newConfig)
}
values.PutValue(newData, updatedConfig, "rancherKubernetesEngineConfig", "privateRegistries")
}
func setCloudProviderPasswordFieldsIfNotExists(oldData, newData map[string]interface{}) {
replaceWithOldSecretIfNotExists(oldData, newData, "openstackCloudProvider", "rancherKubernetesEngineConfig", "cloudProvider", "openstackCloudProvider", "global", "password")
replaceWithOldSecretIfNotExists(oldData, newData, "vsphereCloudProvider", "rancherKubernetesEngineConfig", "cloudProvider", "vsphereCloudProvider", "global", "password")
azureCloudProviderPasswordFields := []string{"aadClientSecret", "aadClientCertPassword"}
for _, secretField := range azureCloudProviderPasswordFields {
replaceWithOldSecretIfNotExists(oldData, newData, "azureCloudProvider", "rancherKubernetesEngineConfig", "cloudProvider", "azureCloudProvider", secretField)
}
vSphereCloudProviderConfig := values.GetValueN(newData, "rancherKubernetesEngineConfig", "cloudProvider", "vsphereCloudProvider")
if vSphereCloudProviderConfig == nil {
return
}
newVCenter := values.GetValueN(newData, "rancherKubernetesEngineConfig", "cloudProvider", "vsphereCloudProvider", "virtualCenter")
if newVCenter != nil {
oldVCenter := values.GetValueN(oldData, "rancherKubernetesEngineConfig", "cloudProvider", "vsphereCloudProvider", "virtualCenter")
newVCenterMap := convert.ToMapInterface(newVCenter)
oldVCenterMap := convert.ToMapInterface(oldVCenter)
for vCenterName, vCenterConfigInterface := range newVCenterMap {
vCenterConfig := convert.ToMapInterface(vCenterConfigInterface)
if vCenterConfig["password"] != nil {
continue
}
// new vcenter has no password provided
// see if this vcenter exists in oldData
if oldVCenterConfigInterface, ok := oldVCenterMap[vCenterName]; ok {
oldVCenterConfig := convert.ToMapInterface(oldVCenterConfigInterface)
if oldVCenterConfig["password"] != nil {
vCenterConfig["password"] = oldVCenterConfig["password"]
newVCenterMap[vCenterName] = vCenterConfig
}
}
}
}
}
func replaceWithOldSecretIfNotExists(oldData, newData map[string]interface{}, cloudProviderName string, keys ...string) {
cloudProviderConfig := values.GetValueN(newData, "rancherKubernetesEngineConfig", "cloudProvider", cloudProviderName)
if cloudProviderConfig == nil {
return
}
newSecret := convert.ToString(values.GetValueN(newData, keys...))
if newSecret != "" {
return
}
oldSecret := convert.ToString(values.GetValueN(oldData, keys...))
if oldSecret != "" {
values.PutValue(newData, oldSecret, keys...)
}
}