-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.go
543 lines (477 loc) · 14.4 KB
/
generator.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
package generator
import (
"bytes"
"context"
"fmt"
"os"
"path"
"sort"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/giantswarm/microerror"
"github.com/pkg/errors"
"go.mozilla.org/sops/v3/decrypt"
uberconfig "go.uber.org/config"
yaml3 "gopkg.in/yaml.v3"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
)
/*
- .yaml is a values source
- .yaml.patch overrides values source
- .yaml.template is a template
- .yaml.template.patch overrides template
Folder structure:
default/
config.yaml
apps/
aws-operator/
...
azure-operator/
configmap-values.yaml.template
secret-values.yaml.template
installations/
ghost/
...
godsmack/
config.yaml.patch
secret.yaml
apps/
azure-operator/
configmap-values.yaml.patch
secret-values.yaml.patch
*/
type Config struct {
Fs Filesystem
DecryptTraverser DecryptTraverser
Installation string
Verbose bool
}
type Generator struct {
fs Filesystem
decryptTraverser DecryptTraverser
installation string
verbose bool
}
func New(config Config) (*Generator, error) {
if config.Fs == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Fs must not be empty", config)
}
if config.DecryptTraverser == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.DecryptTraverser must not be empty", config)
}
if config.Installation == "" {
return nil, microerror.Maskf(invalidConfigError, "%T.Installation must not be empty", config)
}
g := Generator{
fs: config.Fs,
decryptTraverser: config.DecryptTraverser,
installation: config.Installation,
verbose: config.Verbose,
}
return &g, nil
}
func (g Generator) generateRawConfig(ctx context.Context, app string) (configmap string, secret string, err error) {
configmap, secret, err = g.generateRawConfigUnsorted(ctx, app)
if err != nil {
return "", "", microerror.Mask(err)
}
configmap, err = sortYAMLKeys(configmap)
if err != nil {
return "", "", microerror.Mask(err)
}
secret, err = sortYAMLKeys(secret)
if err != nil {
return "", "", microerror.Mask(err)
}
return
}
// generateRawConfigUnsorted creates final configmap values and secret values
// for helm to use by performing the following operations:
// 1. Get configmap template data and patch it with installation-specific
// overrides (if available)
// 2. Get global configmap template for the app and render it with template
// data (result of 1.)
// 3. Get installation-specific configmap patch for the app template (if available)
// 4. Patch global template (result of 2.) with installation-specific (result
// of 3.) app overrides
// 5. Get installation-specific secret template data and decrypt it
// 6. Merge config and secret values before templating app secret
// 7. Get global secret template for the app (if available) and render it with
// installation secret template data (result of 5.)
// 8. Get installation-specific secret template patch (if available) and
// decrypt it
// 9. Patch secret template (result of 6.) with decrypted patch values (result
// of 7.)
func (g Generator) generateRawConfigUnsorted(ctx context.Context, app string) (configmap string, secret string, err error) {
// Check if installation folder exists at all. If not, return a descriptive
// error.
if _, err := g.fs.ReadDir("installations/" + g.installation); err != nil {
if IsNotFound(err) {
return "", "", microerror.Maskf(
notFoundError,
"cannot generate config for installation %s, because \"installations/%s\" does not exist",
g.installation, g.installation,
)
} else {
return "", "", microerror.Mask(err)
}
}
// Check if app folder exists at all. If not, return a descriptive error.
if _, err := g.fs.ReadDir("default/apps/" + app); err != nil {
if IsNotFound(err) {
return "", "", microerror.Maskf(
notFoundError,
"cannot generate config for app %s, because \"default/apps/%s\" does not exist",
app, app,
)
} else {
return "", "", microerror.Mask(err)
}
}
// 1.
configmapContext, err := g.getWithPatchIfExists(
ctx,
"default/config.yaml",
"installations/"+g.installation+"/config.yaml.patch",
)
if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "loaded patched config values")
// 2.
g.logMessage(ctx, "rendering configmap-values")
configmapBase, err := g.getRenderedTemplate(
ctx,
"default/apps/"+app+"/configmap-values.yaml.template",
configmapContext,
)
if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "rendered configmap-values template")
// 3.
var configmapPatch string
{
g.logMessage(ctx, "rendering configmap-values patch (if it exists)")
filepath := "installations/" + g.installation + "/apps/" + app + "/configmap-values.yaml.patch"
patch, err := g.getRenderedTemplate(ctx, filepath, configmapContext)
if IsNotFound(err) {
configmapPatch = ""
} else if err != nil {
return "", "", microerror.Mask(err)
} else {
configmapPatch = patch
g.logMessage(ctx, "rendered configmap-values patch")
}
}
// 4.
configmap, err = applyPatch(
ctx,
[]byte(configmapBase),
[]byte(configmapPatch),
)
if err != nil {
return "", "", microerror.Mask(err)
}
if configmapPatch != "" {
g.logMessage(ctx, "patched configmap-values")
}
// 5.
installationSecretPath := "installations/" + g.installation + "/secret.yaml"
secretContext, err := g.getWithPatchIfExists(
ctx,
installationSecretPath,
"",
)
if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "loaded installation secret")
decryptedBytes, err := g.decryptSecret(ctx, []byte(secretContext))
if err != nil {
return "", "", microerror.Mask(errors.Errorf("failed to decrypt secret in %q: %s", installationSecretPath, err))
}
secretContext = string(decryptedBytes)
g.logMessage(ctx, "decrypted installation secret")
// 6.
secretContextFinal, err := applyPatch(
ctx,
[]byte(configmapContext),
[]byte(secretContext),
)
if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "merged config and secret values")
// 7.
secretTemplate, err := g.getWithPatchIfExists(
ctx,
"default/apps/"+app+"/secret-values.yaml.template",
"",
)
if IsNotFound(err) {
g.logMessage(ctx, "secret-values template not found, generated configmap")
return configmap, "", nil
} else if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "loaded secret-values template")
secret, err = g.renderTemplate(ctx, secretTemplate, secretContextFinal)
if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "rendered secret-values")
// 8.
var secretPatch string
{
filepath := "installations/" + g.installation + "/apps/" + app + "/secret-values.yaml.patch"
patch, err := g.getRenderedTemplate(ctx, filepath, secretContext)
if IsNotFound(err) {
secretPatch = ""
} else if err != nil {
return "", "", microerror.Mask(err)
} else {
g.logMessage(ctx, "loaded secret-values patch")
decryptedBytes, err := g.decryptSecret(ctx, []byte(patch))
if err != nil {
return "", "", microerror.Mask(errors.Errorf("failed to decrypt app secret in %q: %s", filepath, err))
}
secretPatch = string(decryptedBytes)
g.logMessage(ctx, "decrypted secret-values patch")
}
}
// 9.
if secretPatch == "" {
g.logMessage(ctx, "generated configmap and secret")
return configmap, secret, nil
}
secret, err = applyPatch(
ctx,
[]byte(secret),
[]byte(secretPatch),
)
if err != nil {
return "", "", microerror.Mask(err)
}
g.logMessage(ctx, "patched secret-values, generated configmap and secret")
return configmap, secret, nil
}
func sortYAMLKeys(yamlString string) (string, error) {
if yamlString == "" {
return yamlString, nil
}
n := new(yaml3.Node)
err := yaml3.Unmarshal([]byte(yamlString), n)
if err != nil {
return "", microerror.Mask(err)
}
sortYAMLKeysNode(n)
buf := new(bytes.Buffer)
enc := yaml3.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(n)
if err != nil {
return "", microerror.Mask(err)
}
return buf.String(), nil
}
// Coped (and adapted) from:
// https://github.com/mikefarah/yq/blob/fe12407c936cc4dacf7495a04b5881d14e7b0f47/pkg/yqlib/operator_sort_keys.go#L32
func sortYAMLKeysNode(node *yaml3.Node) {
if node.Kind == yaml3.DocumentNode || node.Kind == yaml3.SequenceNode {
for _, n := range node.Content {
sortYAMLKeysNode(n)
}
}
if node.Kind != yaml3.MappingNode {
return
}
keys := make([]string, len(node.Content)/2)
keyBucket := map[string]*yaml3.Node{}
valueBucket := map[string]*yaml3.Node{}
var contents = node.Content
for index := 0; index < len(contents); index = index + 2 {
key := contents[index]
value := contents[index+1]
keys[index/2] = key.Value
keyBucket[key.Value] = key
valueBucket[key.Value] = value
sortYAMLKeysNode(value)
}
sort.Strings(keys)
sortedContent := make([]*yaml3.Node, len(node.Content))
for index := 0; index < len(keys); index = index + 1 {
keyString := keys[index]
sortedContent[index*2] = keyBucket[keyString]
sortedContent[1+(index*2)] = valueBucket[keyString]
}
node.Content = sortedContent
}
// GenerateConfig generates ConfigMap and Secret for a given App. The generated
// CM and Secret metadata are configured with the provided value.
func (g Generator) GenerateConfig(ctx context.Context, app string, meta metav1.ObjectMeta) (*corev1.ConfigMap, *corev1.Secret, error) {
cm, s, err := g.generateRawConfig(ctx, app)
if err != nil {
return nil, nil, microerror.Mask(err)
}
configmap := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: meta,
Data: map[string]string{
"configmap-values.yaml": cm,
},
}
secret := &corev1.Secret{
TypeMeta: metav1.TypeMeta{
Kind: "Secret",
APIVersion: "v1",
},
ObjectMeta: meta,
Data: map[string][]byte{
"secret-values.yaml": []byte(s),
},
}
return configmap, secret, nil
}
// getWithPatchIfExists provides contents of filepath overwritten by patch at
// patchFilepath. File at patchFilepath may be non-existent, resulting in pure
// file at filepath being returned.
func (g Generator) getWithPatchIfExists(ctx context.Context, filepath, patchFilepath string) (string, error) {
var err error
var base []byte
{
base, err = g.fs.ReadFile(filepath)
if err != nil {
return "", microerror.Mask(err)
}
}
// patch is not obligatory
if patchFilepath == "" {
return string(base), nil
}
var patch []byte
{
patch, err = g.fs.ReadFile(patchFilepath)
if err != nil {
if IsNotFound(err) {
return string(base), nil
}
return "", microerror.Mask(err)
}
}
result, err := applyPatch(ctx, base, patch)
if err != nil {
return "", microerror.Mask(errors.Errorf("failed to apply patch from %q onto %q: %s", patchFilepath, filepath, err))
}
return result, nil
}
func (g Generator) getRenderedTemplate(ctx context.Context, filepath, templateData string) (string, error) {
templateBytes, err := g.fs.ReadFile(filepath)
if err != nil {
return "", microerror.Mask(err)
}
result, err := g.renderTemplate(ctx, string(templateBytes), templateData)
if err != nil {
return "", microerror.Mask(errors.Errorf("failed to render template from %q: %s", filepath, err))
}
return result, nil
}
func applyPatch(ctx context.Context, base, patch []byte) (string, error) {
patcher, err := uberconfig.NewYAML(
uberconfig.Permissive(),
uberconfig.Source(bytes.NewBuffer(base)),
uberconfig.Source(bytes.NewBuffer(patch)),
)
if err != nil {
return "", microerror.Mask(err)
}
value := patcher.Get(uberconfig.Root).Value() // nolint:staticcheck
output, err := yaml3.Marshal(value)
if err != nil {
return "", microerror.Mask(err)
}
return string(output), nil
}
func (g Generator) renderTemplate(ctx context.Context, templateText string, templateData string) (string, error) {
c := map[string]interface{}{}
err := yaml.Unmarshal([]byte(templateData), &c)
if err != nil {
return "", microerror.Mask(err)
}
funcMap := sprig.TxtFuncMap()
funcMap["include"] = g.include
t, err := template.New("main").Funcs(funcMap).Option("missingkey=error").Parse(templateText)
if err != nil {
return "", microerror.Mask(err)
}
// render final template
out := bytes.NewBuffer([]byte{})
err = t.Execute(out, c)
if err != nil {
return "", microerror.Mask(err)
}
return out.String(), nil
}
func (g Generator) include(templateName string, templateData interface{}) (string, error) {
templateFilePath := path.Join("include", templateName+".yaml.template")
contents, err := g.fs.ReadFile(templateFilePath)
if err != nil {
return "", microerror.Mask(err)
}
t, err := template.New(templateName).Funcs(sprig.TxtFuncMap()).Option("missingkey=error").Parse(string(contents))
if err != nil {
return "", microerror.Mask(errors.Errorf("failed to parse template in file %q: %s", templateFilePath, err))
}
out := bytes.NewBuffer([]byte{})
err = t.Execute(out, templateData)
if err != nil {
return "", microerror.Mask(errors.Errorf("failed to render template from %q: %s", templateFilePath, err))
}
return out.String(), nil
}
// TODO: get rid of the Vault decryption eventually. For now supporting both
//
// options doesn't feel like a bad idea, having both of them opens a door
// for less stressfull and coordinated migration, allowing us to migrate
// less-critical apps first, etc.
func (g *Generator) decryptSecret(ctx context.Context, data []byte) ([]byte, error) {
// Check if file is SOPS-encrypted
forSOPS, err := isSOPSEncrypted(ctx, data)
if err != nil {
return nil, microerror.Mask(err)
}
// If SOPS-encrypted decrypt with SOPS API, otherwise fallback to the
// Vault method
var decryptedBytes []byte
if forSOPS {
decryptedBytes, err = decrypt.Data(data, "yaml")
} else {
decryptedBytes, err = g.decryptTraverser.Traverse(ctx, data)
}
if err != nil {
return nil, microerror.Mask(err)
}
return decryptedBytes, nil
}
// Each SOPS-encrypted file carries the `sops` key, that in turn carries metadata
// necessary to decrypt it, hence this key is good for discovering files for SOPS
// decryption.
func isSOPSEncrypted(ctx context.Context, data []byte) (bool, error) {
values := make(map[interface{}]interface{})
err := yaml3.Unmarshal([]byte(data), &values)
if err != nil {
return false, microerror.Mask(err)
}
_, ok := values["sops"]
return ok, nil
}
func (g Generator) logMessage(ctx context.Context, format string, params ...interface{}) {
if g.verbose {
fmt.Fprintf(os.Stderr, "generator: "+format+"\n", params...)
}
}