forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine_driver.go
388 lines (350 loc) · 11 KB
/
machine_driver.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
package nodedriver
import (
"context"
"fmt"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/controllers/management/drivers"
"reflect"
"strconv"
"strings"
"sync"
"github.com/rancher/norman/types"
errs "github.com/pkg/errors"
"github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
var (
SchemaLock = sync.Mutex{}
driverLock = sync.Mutex{}
)
const (
driverNameLabel = "io.cattle.node_driver.name"
)
func Register(ctx context.Context, management *config.ManagementContext) {
nodeDriverClient := management.Management.NodeDrivers("")
nodeDriverLifecycle := &Lifecycle{
nodeDriverClient: nodeDriverClient,
schemaClient: management.Management.DynamicSchemas(""),
schemaLister: management.Management.DynamicSchemas("").Controller().Lister(),
secretStore: management.Core.Secrets(""),
nsStore: management.Core.Namespaces(""),
schemas: management.Schemas,
}
nodeDriverClient.
AddLifecycle(ctx, "node-driver-controller", nodeDriverLifecycle)
}
type Lifecycle struct {
nodeDriverClient v3.NodeDriverInterface
schemaClient v3.DynamicSchemaInterface
schemaLister v3.DynamicSchemaLister
secretStore v1.SecretInterface
nsStore v1.NamespaceInterface
schemas *types.Schemas
}
func (m *Lifecycle) Create(obj *v3.NodeDriver) (runtime.Object, error) {
return m.download(obj)
}
func (m *Lifecycle) download(obj *v3.NodeDriver) (*v3.NodeDriver, error) {
driverLock.Lock()
defer driverLock.Unlock()
if !obj.Spec.Active {
return obj, nil
}
err := errs.New("not found")
// if node driver was created, we also activate the driver by default
driver := drivers.NewDynamicDriver(obj.Spec.Builtin, obj.Spec.DisplayName, obj.Spec.URL, obj.Spec.Checksum)
schemaName := obj.Spec.DisplayName + "config"
var existingSchema *v3.DynamicSchema
if obj.Spec.DisplayName != "" {
existingSchema, err = m.schemaLister.Get("", schemaName)
}
if driver.Exists() && err == nil {
// add credential schema
credFields := map[string]v3.Field{}
if err != nil {
logrus.Errorf("error getting schema %v", err)
}
userCredFields, pwdFields, defaults := getCredFields(obj.Annotations)
for name, field := range existingSchema.Spec.ResourceFields {
if pwdFields[name] {
field.Type = "password"
}
if field.Type == "password" || userCredFields[name] {
credField := field
credField.Required = true
if val, ok := defaults[name]; ok {
credField = updateDefault(credField, val, field.Type)
}
credFields[name] = credField
}
}
return m.createCredSchema(obj, credFields)
}
if !driver.Exists() {
v3.NodeDriverConditionDownloaded.Unknown(obj)
v3.NodeDriverConditionInstalled.Unknown(obj)
}
newObj, err := v3.NodeDriverConditionDownloaded.Once(obj, func() (runtime.Object, error) {
// update status
obj, err = m.nodeDriverClient.Update(obj)
if err != nil {
return nil, err
}
if err := driver.Stage(); err != nil {
return nil, err
}
return obj, nil
})
if err != nil {
return obj, err
}
obj = newObj.(*v3.NodeDriver)
newObj, err = v3.NodeDriverConditionInstalled.Once(obj, func() (runtime.Object, error) {
if err := driver.Install(); err != nil {
return nil, err
}
if err = driver.Excutable(); err != nil {
return nil, err
}
obj.Spec.DisplayName = strings.TrimPrefix(driver.Name(), drivers.DockerMachineDriverPrefix)
return obj, nil
})
if err != nil {
return newObj.(*v3.NodeDriver), err
}
obj = newObj.(*v3.NodeDriver)
driverName := strings.TrimPrefix(driver.Name(), drivers.DockerMachineDriverPrefix)
flags, err := getCreateFlagsForDriver(driverName)
if err != nil {
return nil, err
}
credFields := map[string]v3.Field{}
resourceFields := map[string]v3.Field{}
userCredFields, pwdFields, defaults := getCredFields(obj.Annotations)
for _, flag := range flags {
name, field, err := FlagToField(flag)
if err != nil {
return nil, err
}
if pwdFields[name] {
field.Type = "password"
}
if field.Type == "password" || userCredFields[name] {
credField := field
credField.Required = true
if val, ok := defaults[name]; ok {
credField = updateDefault(credField, val, field.Type)
}
credFields[name] = credField
}
resourceFields[name] = field
}
dynamicSchema := &v3.DynamicSchema{
Spec: v3.DynamicSchemaSpec{
ResourceFields: resourceFields,
},
}
dynamicSchema.Name = obj.Spec.DisplayName + "config"
dynamicSchema.OwnerReferences = []metav1.OwnerReference{
{
UID: obj.UID,
Kind: obj.Kind,
APIVersion: obj.APIVersion,
Name: obj.Name,
},
}
dynamicSchema.Labels = map[string]string{}
dynamicSchema.Labels[driverNameLabel] = obj.Spec.DisplayName
_, err = m.schemaClient.Create(dynamicSchema)
if err != nil && !errors.IsAlreadyExists(err) {
return obj, err
}
return m.createCredSchema(obj, credFields)
}
func (m *Lifecycle) createCredSchema(obj *v3.NodeDriver, credFields map[string]v3.Field) (*v3.NodeDriver, error) {
name := credentialConfigSchemaName(obj.Spec.DisplayName)
credSchema, err := m.schemaLister.Get("", name)
if err != nil {
if errors.IsNotFound(err) {
credentialSchema := &v3.DynamicSchema{
Spec: v3.DynamicSchemaSpec{
ResourceFields: credFields,
},
}
credentialSchema.Name = name
credentialSchema.OwnerReferences = []metav1.OwnerReference{
{
UID: obj.UID,
Kind: obj.Kind,
APIVersion: obj.APIVersion,
Name: obj.Name,
},
}
_, err := m.schemaClient.Create(credentialSchema)
return obj, err
}
return obj, err
} else if !reflect.DeepEqual(credSchema.Spec.ResourceFields, credFields) {
toUpdate := credSchema.DeepCopy()
toUpdate.Spec.ResourceFields = credFields
_, err := m.schemaClient.Update(toUpdate)
if err != nil {
return obj, err
}
}
return obj, nil
}
func (m *Lifecycle) Updated(obj *v3.NodeDriver) (runtime.Object, error) {
var err error
obj, err = m.download(obj)
if err != nil {
return obj, err
}
if err := m.createOrUpdateNodeForEmbeddedType(obj.Spec.DisplayName+"config", obj.Spec.DisplayName+"Config", obj.Spec.Active); err != nil {
return obj, err
}
if err := m.createOrUpdateNodeForEmbeddedTypeCredential(credentialConfigSchemaName(obj.Spec.DisplayName),
obj.Spec.DisplayName+"credentialConfig", obj.Spec.Active); err != nil {
return obj, err
}
v3.NodeDriverConditionActive.True(obj)
v3.NodeDriverConditionInactive.True(obj)
return obj, nil
}
func (m *Lifecycle) Remove(obj *v3.NodeDriver) (runtime.Object, error) {
schemas, err := m.schemaClient.List(metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s", driverNameLabel, obj.Spec.DisplayName),
})
if err != nil {
return obj, err
}
for _, schema := range schemas.Items {
logrus.Infof("Deleting schema %s", schema.Name)
if err := m.schemaClient.Delete(schema.Name, &metav1.DeleteOptions{}); err != nil {
return obj, err
}
logrus.Infof("Deleting schema %s done", schema.Name)
}
if err := m.createOrUpdateNodeForEmbeddedType(obj.Spec.DisplayName+"config", obj.Spec.DisplayName+"Config", false); err != nil {
return obj, err
}
return obj, nil
}
func (m *Lifecycle) createOrUpdateNodeForEmbeddedTypeCredential(embeddedType, fieldName string, embedded bool) error {
SchemaLock.Lock()
defer SchemaLock.Unlock()
return m.createOrUpdateNodeForEmbeddedTypeWithParents(embeddedType, fieldName, "credentialconfig", "cloudCredential", embedded, true)
}
func (m *Lifecycle) createOrUpdateNodeForEmbeddedType(embeddedType, fieldName string, embedded bool) error {
SchemaLock.Lock()
defer SchemaLock.Unlock()
if err := m.createOrUpdateNodeForEmbeddedTypeWithParents(embeddedType, fieldName, "nodeconfig", "node", embedded, false); err != nil {
return err
}
return m.createOrUpdateNodeForEmbeddedTypeWithParents(embeddedType, fieldName, "nodetemplateconfig", "nodeTemplate", embedded, true)
}
func (m *Lifecycle) createOrUpdateNodeForEmbeddedTypeWithParents(embeddedType, fieldName, schemaID, parentID string, embedded, update bool) error {
nodeSchema, err := m.schemaLister.Get("", schemaID)
if err != nil && !errors.IsNotFound(err) {
return err
} else if errors.IsNotFound(err) {
resourceField := map[string]v3.Field{}
if embedded {
resourceField[fieldName] = v3.Field{
Create: true,
Nullable: true,
Update: update,
Type: embeddedType,
}
}
dynamicSchema := &v3.DynamicSchema{}
dynamicSchema.Name = schemaID
dynamicSchema.Spec.ResourceFields = resourceField
dynamicSchema.Spec.Embed = true
dynamicSchema.Spec.EmbedType = parentID
_, err := m.schemaClient.Create(dynamicSchema)
if err != nil {
return err
}
return nil
}
shouldUpdate := false
if embedded {
if nodeSchema.Spec.ResourceFields == nil {
nodeSchema.Spec.ResourceFields = map[string]v3.Field{}
}
if _, ok := nodeSchema.Spec.ResourceFields[fieldName]; !ok {
// if embedded we add the type to schema
logrus.Infof("uploading %s to %s schema", fieldName, schemaID)
nodeSchema.Spec.ResourceFields[fieldName] = v3.Field{
Create: true,
Nullable: true,
Update: update,
Type: embeddedType,
}
shouldUpdate = true
}
} else {
// if not we delete it from schema
if _, ok := nodeSchema.Spec.ResourceFields[fieldName]; ok {
logrus.Infof("deleting %s from %s schema", fieldName, schemaID)
delete(nodeSchema.Spec.ResourceFields, fieldName)
shouldUpdate = true
}
}
if shouldUpdate {
_, err = m.schemaClient.Update(nodeSchema)
if err != nil {
return err
}
}
return nil
}
func getCredFields(annotations map[string]string) (map[string]bool, map[string]bool, map[string]string) {
getMap := func(fields string) map[string]bool {
data := map[string]bool{}
for _, field := range strings.Split(fields, ",") {
data[field] = true
}
return data
}
getDefaults := func(fields string) map[string]string {
data := map[string]string{}
for _, pattern := range strings.Split(fields, ",") {
split := strings.SplitN(pattern, ":", 2)
if len(split) == 2 {
data[split[0]] = split[1]
}
}
return data
}
return getMap(annotations["cred"]), getMap(annotations["password"]), getDefaults(annotations["defaults"])
}
func credentialConfigSchemaName(driverName string) string {
return fmt.Sprintf("%s%s", driverName, "credentialconfig")
}
func updateDefault(credField v3.Field, val, kind string) v3.Field {
switch kind {
case "int":
i, err := strconv.Atoi(val)
if err == nil {
credField.Default = v3.Values{IntValue: i}
} else {
logrus.Errorf("error converting %s to int %v", val, err)
}
case "boolean":
credField.Default = v3.Values{BoolValue: convert.ToBool(val)}
case "array[string]":
credField.Default = v3.Values{StringSliceValue: convert.ToStringSlice(val)}
case "password", "string":
credField.Default = v3.Values{StringValue: val}
default:
logrus.Errorf("unsupported kind for default val:%s kind:%s", val, kind)
}
return credField
}