-
Notifications
You must be signed in to change notification settings - Fork 33
/
gotemplate.go
361 lines (308 loc) · 10.8 KB
/
gotemplate.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
// SPDX-FileCopyrightText: 2020 SAP SE or an SAP affiliate company and Gardener contributors.
//
// SPDX-License-Identifier: Apache-2.0
package gotemplate
import (
"bytes"
"context"
"encoding/json"
"fmt"
gotmpl "text/template"
"github.com/mandelsoft/vfs/pkg/vfs"
"github.com/pkg/errors"
"sigs.k8s.io/yaml"
lsv1alpha1 "github.com/gardener/landscaper/apis/core/v1alpha1"
"github.com/gardener/landscaper/controller-utils/pkg/landscaper/targetresolver"
"github.com/gardener/landscaper/pkg/components/model"
lstmpl "github.com/gardener/landscaper/pkg/landscaper/installations/executions/template"
"github.com/gardener/landscaper/pkg/utils/blueprints"
)
const (
recursionMaxNums = 100
)
// Templater is the go template implementation for landscaper templating.
type Templater struct {
state lstmpl.GenericStateHandler
inputFormatter *lstmpl.TemplateInputFormatter
targetResolver targetresolver.TargetResolver
}
// New creates a new go template execution templater.
func New(state lstmpl.GenericStateHandler, targetResolver targetresolver.TargetResolver) *Templater {
return &Templater{
state: state,
inputFormatter: lstmpl.NewTemplateInputFormatter(false, "imports", "targets", "values", "state"),
targetResolver: targetResolver,
}
}
// WithInputFormatter ads a custom input formatter to this templater used for error messages.
func (t *Templater) WithInputFormatter(inputFormatter *lstmpl.TemplateInputFormatter) *Templater {
t.inputFormatter = inputFormatter
return t
}
type TemplateExecution struct {
funcMap map[string]interface{}
blueprint *blueprints.Blueprint
includedNames map[string]int
}
func NewTemplateExecution(blueprint *blueprints.Blueprint,
cd model.ComponentVersion,
cdList *model.ComponentVersionList,
targetResolver targetresolver.TargetResolver) (*TemplateExecution, error) {
funcs, err := LandscaperTplFuncMap(blueprint, cd, cdList, targetResolver)
if err != nil {
return nil, err
}
t := &TemplateExecution{
funcMap: funcs,
blueprint: blueprint,
includedNames: map[string]int{},
}
t.funcMap["include"] = t.include
return t, nil
}
func (te *TemplateExecution) include(name string, binding interface{}) (string, error) {
if v, ok := te.includedNames[name]; ok {
if v > recursionMaxNums {
return "", errors.Wrapf(fmt.Errorf("unable to execute template"), "rendering template has a nested reference name: %s", name)
}
te.includedNames[name]++
} else {
te.includedNames[name] = 1
}
data, err := vfs.ReadFile(te.blueprint.Fs, name)
if err != nil {
return "", errors.Wrapf(err, "unable to read include file %q", name)
}
res, err := te.Execute(string(data), binding)
te.includedNames[name]--
return string(res), err
}
func (te *TemplateExecution) Execute(template string, binding interface{}) ([]byte, error) {
tmpl, err := gotmpl.New("execution").
Funcs(LandscaperSprigFuncMap()).Funcs(te.funcMap).
Option("missingkey=zero").
Parse(template)
if err != nil {
parseError := TemplateErrorBuilder(err).WithSource(&template).Build()
return nil, parseError
}
data := bytes.NewBuffer([]byte{})
if err := tmpl.Execute(data, binding); err != nil {
return nil, err
}
return data.Bytes(), nil
}
// StateTemplateResult describes the result of go templating.
type StateTemplateResult struct {
State json.RawMessage `json:"state"`
}
func (t Templater) Type() lsv1alpha1.TemplateType {
return lsv1alpha1.GOTemplateType
}
func (t *Templater) TemplateExecution(rawTemplate string,
blueprint *blueprints.Blueprint,
cd model.ComponentVersion,
cdList *model.ComponentVersionList,
values map[string]interface{}) ([]byte, error) {
te, err := NewTemplateExecution(blueprint, cd, cdList, t.targetResolver)
if err != nil {
return nil, err
}
return te.Execute(rawTemplate, values)
}
func (t *Templater) TemplateSubinstallationExecutions(tmplExec lsv1alpha1.TemplateExecutor,
blueprint *blueprints.Blueprint,
cd model.ComponentVersion,
cdList *model.ComponentVersionList,
values map[string]interface{}) (*lstmpl.SubinstallationExecutorOutput, error) {
const templateName = "subinstallation execution"
rawTemplate, err := getTemplateFromExecution(tmplExec, blueprint)
if err != nil {
return nil, err
}
ctx := context.Background()
defer ctx.Done()
state, err := t.getDeployExecutionState(ctx, tmplExec)
if err != nil {
return nil, fmt.Errorf("unable to load state: %w", err)
}
values["state"] = state
data, err := t.TemplateExecution(rawTemplate, blueprint, cd, cdList, values)
if err != nil {
executeError := TemplateErrorBuilder(err).WithSource(&rawTemplate).
WithInput(values, t.inputFormatter).
Build()
return nil, executeError
}
if err := CreateErrorIfContainsNoValue(string(data), templateName, values, t.inputFormatter); err != nil {
return nil, err
}
if err := t.storeDeployExecutionState(ctx, tmplExec, data); err != nil {
return nil, fmt.Errorf("unable to store state: %w", err)
}
output := &lstmpl.SubinstallationExecutorOutput{}
if err := yaml.Unmarshal(data, output); err != nil {
return nil, fmt.Errorf("error while decoding templated execution: %w", err)
}
return output, nil
}
// TemplateImportExecutions is the GoTemplate executor for an import execution.
func (t *Templater) TemplateImportExecutions(tmplExec lsv1alpha1.TemplateExecutor,
blueprint *blueprints.Blueprint,
descriptor model.ComponentVersion,
cdList *model.ComponentVersionList,
values map[string]interface{}) (*lstmpl.ImportExecutorOutput, error) {
rawTemplate, err := getTemplateFromExecution(tmplExec, blueprint)
if err != nil {
return nil, err
}
ctx := context.Background()
defer ctx.Done()
data, err := t.TemplateExecution(rawTemplate, blueprint, descriptor, cdList, values)
if err != nil {
executeError := TemplateErrorBuilder(err).WithSource(&rawTemplate).
WithInput(values, t.inputFormatter).
Build()
return nil, executeError
}
output := &lstmpl.ImportExecutorOutput{}
if err := yaml.Unmarshal(data, output); err != nil {
return nil, fmt.Errorf("error while decoding templated execution: %w", err)
}
return output, nil
}
// TemplateDeployExecutions is the GoTemplate executor for a deploy execution.
func (t *Templater) TemplateDeployExecutions(tmplExec lsv1alpha1.TemplateExecutor,
blueprint *blueprints.Blueprint,
descriptor model.ComponentVersion,
cdList *model.ComponentVersionList,
values map[string]interface{}) (*lstmpl.DeployExecutorOutput, error) {
const templateName = "deploy execution"
rawTemplate, err := getTemplateFromExecution(tmplExec, blueprint)
if err != nil {
return nil, err
}
ctx := context.Background()
defer ctx.Done()
state, err := t.getDeployExecutionState(ctx, tmplExec)
if err != nil {
return nil, fmt.Errorf("unable to load state: %w", err)
}
values["state"] = state
data, err := t.TemplateExecution(rawTemplate, blueprint, descriptor, cdList, values)
if err != nil {
executeError := TemplateErrorBuilder(err).WithSource(&rawTemplate).
WithInput(values, t.inputFormatter).
Build()
return nil, executeError
}
if err := CreateErrorIfContainsNoValue(string(data), templateName, values, t.inputFormatter); err != nil {
return nil, err
}
if err := t.storeDeployExecutionState(ctx, tmplExec, data); err != nil {
return nil, fmt.Errorf("unable to store state: %w", err)
}
output := &lstmpl.DeployExecutorOutput{}
if err := yaml.Unmarshal(data, output); err != nil {
return nil, fmt.Errorf("error while decoding templated execution: %w", err)
}
return output, nil
}
func (t *Templater) TemplateExportExecutions(tmplExec lsv1alpha1.TemplateExecutor,
blueprint *blueprints.Blueprint,
descriptor model.ComponentVersion,
cdList *model.ComponentVersionList,
values map[string]interface{}) (*lstmpl.ExportExecutorOutput, error) {
const templateName = "export execution"
rawTemplate, err := getTemplateFromExecution(tmplExec, blueprint)
if err != nil {
return nil, err
}
ctx := context.Background()
defer ctx.Done()
state, err := t.getExportExecutionState(ctx, tmplExec)
if err != nil {
return nil, fmt.Errorf("unable to load state: %w", err)
}
values["state"] = state
data, err := t.TemplateExecution(rawTemplate, blueprint, descriptor, cdList, values)
if err != nil {
executeError := TemplateErrorBuilder(err).WithSource(&rawTemplate).
WithInput(values, t.inputFormatter).
Build()
return nil, executeError
}
if err := CreateErrorIfContainsNoValue(string(data), templateName, values, t.inputFormatter); err != nil {
return nil, err
}
if err != nil {
return nil, fmt.Errorf("unable to execute template: %w", err)
}
if err := t.storeExportExecutionState(ctx, tmplExec, data); err != nil {
return nil, fmt.Errorf("unable to store state: %w", err)
}
output := &lstmpl.ExportExecutorOutput{}
if err := yaml.Unmarshal(data, output); err != nil {
return nil, err
}
return output, nil
}
func (t *Templater) getDeployExecutionState(ctx context.Context, tmplExec lsv1alpha1.TemplateExecutor) (interface{}, error) {
return t.getState(ctx, "deploy", tmplExec)
}
func (t *Templater) storeDeployExecutionState(ctx context.Context, tmplExec lsv1alpha1.TemplateExecutor, data []byte) error {
return t.storeState(ctx, "deploy", tmplExec, data)
}
func (t *Templater) getExportExecutionState(ctx context.Context, tmplExec lsv1alpha1.TemplateExecutor) (interface{}, error) {
return t.getState(ctx, "export", tmplExec)
}
func (t *Templater) storeExportExecutionState(ctx context.Context, tmplExec lsv1alpha1.TemplateExecutor, data []byte) error {
return t.storeState(ctx, "export", tmplExec, data)
}
func (t *Templater) getState(ctx context.Context, prefix string, tmplExec lsv1alpha1.TemplateExecutor) (interface{}, error) {
if t.state == nil {
return map[string]interface{}{}, nil
}
data, err := t.state.Get(ctx, prefix+tmplExec.Name)
if err != nil {
if err == lstmpl.StateNotFoundErr {
return map[string]interface{}{}, nil
}
return nil, err
}
var state interface{}
if err := yaml.Unmarshal(data, &state); err != nil {
return nil, err
}
return state, nil
}
func (t *Templater) storeState(ctx context.Context, prefix string, tmplExec lsv1alpha1.TemplateExecutor, data []byte) error {
if t.state == nil {
return nil
}
res := &StateTemplateResult{}
if err := yaml.Unmarshal(data, res); err != nil {
return err
}
if len(res.State) == 0 {
return nil
}
return t.state.Store(ctx, prefix+tmplExec.Name, res.State)
}
func getTemplateFromExecution(tmplExec lsv1alpha1.TemplateExecutor, blueprint *blueprints.Blueprint) (string, error) {
if len(tmplExec.Template.RawMessage) != 0 {
var rawTemplate string
if err := json.Unmarshal(tmplExec.Template.RawMessage, &rawTemplate); err != nil {
return "", err
}
return rawTemplate, nil
}
if len(tmplExec.File) != 0 {
rawTemplateBytes, err := vfs.ReadFile(blueprint.Fs, tmplExec.File)
if err != nil {
return "", err
}
return string(rawTemplateBytes), nil
}
return "", fmt.Errorf("no template found")
}