forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
405 lines (337 loc) · 9.37 KB
/
loader.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
package cloudup
import (
"bytes"
"encoding/json"
"fmt"
"github.com/golang/glog"
"io"
"k8s.io/kops/upup/pkg/api"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/loader"
"k8s.io/kops/upup/pkg/fi/utils"
"k8s.io/kops/util/pkg/vfs"
"os"
"reflect"
"strings"
"text/template"
)
const (
KEY_NAME = "name"
KEY_TYPE = "_type"
)
type Loader struct {
Cluster *api.Cluster
WorkDir string
ModelStore vfs.Path
Tags map[string]struct{}
TemplateFunctions template.FuncMap
typeMap map[string]reflect.Type
templates []*template.Template
Resources map[string]fi.Resource
tasks map[string]fi.Task
}
type templateResource struct {
key string
loader *Loader
template string
args []string
}
var _ fi.Resource = &templateResource{}
var _ fi.TemplateResource = &templateResource{}
func (a *templateResource) Open() (io.Reader, error) {
var err error
result, err := a.loader.executeTemplate(a.key, a.template, a.args)
if err != nil {
return nil, fmt.Errorf("error executing resource template %q: %v", a.key, err)
}
reader := bytes.NewReader([]byte(result))
return reader, nil
}
func (a *templateResource) Curry(args []string) fi.TemplateResource {
curried := &templateResource{}
*curried = *a
curried.args = append(curried.args, args...)
return curried
}
func (l *Loader) Init() {
l.tasks = make(map[string]fi.Task)
l.typeMap = make(map[string]reflect.Type)
l.Resources = make(map[string]fi.Resource)
l.TemplateFunctions = make(template.FuncMap)
}
func (l *Loader) AddTypes(types map[string]interface{}) {
for key, proto := range types {
_, exists := l.typeMap[key]
if exists {
glog.Fatalf("duplicate type key: %q", key)
}
t := reflect.TypeOf(proto)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
l.typeMap[key] = t
}
}
func (l *Loader) executeTemplate(key string, d string, args []string) (string, error) {
t := template.New(key)
funcMap := make(template.FuncMap)
funcMap["Args"] = func() []string {
return args
}
funcMap["RenderResource"] = func(resourceName string, args []string) (string, error) {
return l.renderResource(resourceName, args)
}
for k, fn := range l.TemplateFunctions {
funcMap[k] = fn
}
t.Funcs(funcMap)
t.Option("missingkey=zero")
spec := l.Cluster.Spec
_, err := t.Parse(d)
if err != nil {
return "", fmt.Errorf("error parsing template %q: %v", key, err)
}
var buffer bytes.Buffer
err = t.ExecuteTemplate(&buffer, key, spec)
if err != nil {
return "", fmt.Errorf("error executing template %q: %v", key, err)
}
return buffer.String(), nil
}
func ignoreHandler(i *loader.TreeWalkItem) error {
return nil
}
func (l *Loader) BuildTasks(modelStore vfs.Path, models []string) (map[string]fi.Task, error) {
// Second pass: load everything else
tw := &loader.TreeWalker{
DefaultHandler: l.objectHandler,
Contexts: map[string]loader.Handler{
"resources": l.resourceHandler,
},
Extensions: map[string]loader.Handler{
".options": ignoreHandler,
},
Tags: l.Tags,
}
for _, model := range models {
modelDir := modelStore.Join(model)
err := tw.Walk(modelDir)
if err != nil {
return nil, err
}
}
err := l.processDeferrals()
if err != nil {
return nil, err
}
return l.tasks, nil
}
func (l *Loader) processDeferrals() error {
for taskKey, task := range l.tasks {
taskValue := reflect.ValueOf(task)
err := utils.ReflectRecursive(taskValue, func(path string, f *reflect.StructField, v reflect.Value) error {
if utils.IsPrimitiveValue(v) {
return nil
}
if path == "" {
// Don't process top-level value
return nil
}
switch v.Kind() {
case reflect.Interface, reflect.Ptr:
if v.CanInterface() && !v.IsNil() {
// TODO: Can we / should we use a type-switch statement
intf := v.Interface()
if hn, ok := intf.(fi.HasName); ok {
name := hn.GetName()
if name != nil {
primary := l.tasks[*name]
if primary == nil {
glog.Infof("Known tasks:")
for k := range l.tasks {
glog.Infof(" %s", k)
}
return fmt.Errorf("Unable to find task %q, referenced from %s:%s", *name, taskKey, path)
}
glog.V(11).Infof("Replacing task %q at %s:%s", *name, taskKey, path)
v.Set(reflect.ValueOf(primary))
}
return utils.SkipReflection
} else if rh, ok := intf.(*fi.ResourceHolder); ok {
//Resources can contain template 'arguments', separated by spaces
// <resourcename> <arg1> <arg2>
tokens := strings.Split(rh.Name, " ")
match := tokens[0]
args := tokens[1:]
match = strings.TrimPrefix(match, "resources/")
resource := l.Resources[match]
if resource == nil {
glog.Infof("Known resources:")
for k := range l.Resources {
glog.Infof(" %s", k)
}
return fmt.Errorf("Unable to find resource %q, referenced from %s:%s", rh.Name, taskKey, path)
}
err := l.populateResource(rh, resource, args)
if err != nil {
return fmt.Errorf("error setting resource value: %v", err)
}
return utils.SkipReflection
}
}
}
return nil
})
if err != nil {
return fmt.Errorf("unexpected error resolving task %q: %v", taskKey, err)
}
}
return nil
}
func (l *Loader) resourceHandler(i *loader.TreeWalkItem) error {
contents, err := i.ReadBytes()
if err != nil {
return err
}
var a fi.Resource
key := i.RelativePath
if strings.HasSuffix(key, ".template") {
key = strings.TrimSuffix(key, ".template")
glog.V(2).Infof("loading (templated) resource %q", key)
a = &templateResource{
template: string(contents),
loader: l,
key: key,
}
} else {
glog.V(2).Infof("loading resource %q", key)
a = fi.NewBytesResource(contents)
}
l.Resources[key] = a
return nil
}
func (l *Loader) objectHandler(i *loader.TreeWalkItem) error {
glog.V(8).Infof("Reading %s", i.Path)
contents, err := i.ReadString()
if err != nil {
return err
}
data, err := l.executeTemplate(i.RelativePath, contents, nil)
if err != nil {
return err
}
objects, err := l.loadYamlObjects(i.RelativePath, data)
if err != nil {
return err
}
for k, v := range objects {
_, found := l.tasks[k]
if found {
return fmt.Errorf("found duplicate object: %q", k)
}
l.tasks[k] = v.(fi.Task)
}
return nil
}
func (l *Loader) loadYamlObjects(key string, data string) (map[string]interface{}, error) {
var o map[string]interface{}
if strings.TrimSpace(data) != "" {
err := utils.YamlUnmarshal([]byte(data), &o)
if err != nil {
// TODO: It would be nice if yaml returned us the line number here
glog.Infof("error parsing yaml. yaml follows:")
for i, line := range strings.Split(string(data), "\n") {
fmt.Fprintf(os.Stderr, "%3d: %s\n", i, line)
}
return nil, fmt.Errorf("error parsing yaml %q: %v", key, err)
}
}
return l.loadObjectMap(key, o)
}
func (l *Loader) loadObjectMap(key string, data map[string]interface{}) (map[string]interface{}, error) {
loaded := make(map[string]interface{})
for k, v := range data {
typeId := ""
name := ""
// If the name & type are not specified in the values,
// we infer them from the key (first component -> typeid, last component -> name)
if vMap, ok := v.(map[string]interface{}); ok {
if s, ok := vMap[KEY_TYPE]; ok {
typeId = s.(string)
}
if s, ok := vMap[KEY_NAME]; ok {
name = s.(string)
}
}
inferredName := false
if name == "" {
firstSlash := strings.Index(k, "/")
name = k[firstSlash+1:]
inferredName = true
}
if typeId == "" {
firstSlash := strings.Index(k, "/")
if firstSlash != -1 {
typeId = k[:firstSlash]
}
if typeId == "" {
return nil, fmt.Errorf("cannot determine type for %q", k)
}
}
t, found := l.typeMap[typeId]
if !found {
return nil, fmt.Errorf("unknown type %q (in %q)", typeId, key)
}
o := reflect.New(t)
// TODO replace with partial unmarshal...
jsonValue, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("error marshalling to json: %v", err)
}
err = json.Unmarshal(jsonValue, o.Interface())
if err != nil {
return nil, fmt.Errorf("error parsing %q: %v", key, err)
}
glog.V(4).Infof("Built %s:%s => %v", key, k, o.Interface())
if inferredName {
hn, ok := o.Interface().(fi.HasName)
if ok {
hn.SetName(name)
}
}
loaded[k] = o.Interface()
}
return loaded, nil
}
func (l *Loader) populateResource(rh *fi.ResourceHolder, resource fi.Resource, args []string) error {
if resource == nil {
return nil
}
if len(args) != 0 {
templateResource, ok := resource.(fi.TemplateResource)
if !ok {
return fmt.Errorf("cannot have arguments with resources of type %T", resource)
}
resource = templateResource.Curry(args)
}
rh.Resource = resource
return nil
}
func (l *Loader) renderResource(resourceName string, args []string) (string, error) {
resourceKey := strings.TrimSuffix(resourceName, ".template")
resourceKey = strings.TrimPrefix(resourceKey, "resources/")
configResource := l.Resources[resourceKey]
if configResource == nil {
return "", fmt.Errorf("cannot find resource %q", resourceName)
}
if tr, ok := configResource.(fi.TemplateResource); ok {
configResource = tr.Curry(args)
} else if len(args) != 0 {
return "", fmt.Errorf("args passed when building node config, but config was not a template %q", resourceName)
}
data, err := fi.ResourceAsBytes(configResource)
if err != nil {
return "", fmt.Errorf("error reading resource %q: %v", resourceName, err)
}
return string(data), nil
}