-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
module_builder.go
366 lines (304 loc) · 10.3 KB
/
module_builder.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
/*
Copyright 2023 Stefan Prodan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package engine
import (
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/load"
apiv1 "github.com/stefanprodan/timoni/api/v1alpha1"
)
const (
defaultPackage = "main"
defaultValuesFile = "values.cue"
defaultSchemaFile = "timoni.schema.cue"
defaultDevelVersion = "0.0.0-devel"
// The default Kubernetes version must be kept in sync with go.mod.
defaultKubeVersion = "1.27.5"
)
// ModuleBuilder compiles CUE definitions to Kubernetes objects.
type ModuleBuilder struct {
ctx *cue.Context
moduleRoot string
pkgName string
pkgPath string
name string
namespace string
moduleVersion string
kubeVersion string
}
// NewModuleBuilder creates a ModuleBuilder for the given module and package.
func NewModuleBuilder(ctx *cue.Context, name, namespace, moduleRoot, pkgName string) *ModuleBuilder {
if ctx == nil {
ctx = cuecontext.New()
}
b := &ModuleBuilder{
ctx: ctx,
moduleRoot: moduleRoot,
pkgName: pkgName,
pkgPath: moduleRoot,
name: name,
namespace: namespace,
moduleVersion: defaultDevelVersion,
kubeVersion: defaultKubeVersion,
}
if kv := os.Getenv("TIMONI_KUBE_VERSION"); kv != "" {
b.kubeVersion = kv
}
if pkgName != defaultPackage {
b.pkgPath = filepath.Join(moduleRoot, pkgName)
}
return b
}
// MergeValuesFile merges the given values overlays into the module's root values.cue.
func (b *ModuleBuilder) MergeValuesFile(overlays [][]byte) error {
vb := NewValuesBuilder(b.ctx)
defaultFile := filepath.Join(b.pkgPath, defaultValuesFile)
finalVal, err := vb.MergeValues(overlays, defaultFile)
if err != nil {
return err
}
cueGen := fmt.Sprintf("package %s\n%s: %v", b.pkgName, apiv1.ValuesSelector, finalVal)
// overwrite the values.cue file with the merged values
if err := os.MkdirAll(b.moduleRoot, os.ModePerm); err != nil {
return err
}
return os.WriteFile(defaultFile, []byte(cueGen), 0644)
}
// WriteValuesFileWithDefaults merges the module's root values.cue with the supplied value.
func (b *ModuleBuilder) WriteValuesFileWithDefaults(val cue.Value) error {
valData := []byte(fmt.Sprintf("%s: %v", apiv1.ValuesSelector.String(), val))
vb := NewValuesBuilder(b.ctx)
defaultFile := filepath.Join(b.pkgPath, defaultValuesFile)
finalVal, err := vb.MergeValues([][]byte{valData}, defaultFile)
if err != nil {
return err
}
cueGen := fmt.Sprintf("package %s\n%s: %v", b.pkgName, apiv1.ValuesSelector, finalVal)
// overwrite the values.cue file with the merged values
if err := os.MkdirAll(b.moduleRoot, os.ModePerm); err != nil {
return err
}
return os.WriteFile(defaultFile, []byte(cueGen), 0644)
}
// WriteSchemaFile generates the module's instance schema.
func (b *ModuleBuilder) WriteSchemaFile() error {
if fs, err := os.Stat(b.pkgPath); err != nil || !fs.IsDir() {
return fmt.Errorf("cannot find package %s", b.pkgPath)
}
cueGen := fmt.Sprintf("package %s\n%v", b.pkgName, apiv1.InstanceSchema)
return os.WriteFile(filepath.Join(b.pkgPath, defaultSchemaFile), []byte(cueGen), 0644)
}
// SetVersionInfo allows setting the Timoni module version and Kubernetes version,
// which are injected at build time as optional CUE tags.
func (b *ModuleBuilder) SetVersionInfo(moduleVersion, kubeVersion string) {
if moduleVersion != "" {
b.moduleVersion = moduleVersion
}
if kubeVersion != "" {
b.kubeVersion = kubeVersion
}
}
// Build builds the Timoni instance for the specified module and returns its CUE value.
// If the instance validation fails, the returned error may represent more than one error,
// retrievable with errors.Errors.
func (b *ModuleBuilder) Build(tags ...string) (cue.Value, error) {
var value cue.Value
cfg := &load.Config{
ModuleRoot: b.moduleRoot,
Package: b.pkgName,
Dir: b.pkgPath,
DataFiles: true,
Tags: []string{
"name=" + b.name,
"namespace=" + b.namespace,
},
TagVars: map[string]load.TagVar{
"moduleVersion": {
Func: func() (ast.Expr, error) {
return ast.NewString(b.moduleVersion), nil
},
},
"kubeVersion": {
Func: func() (ast.Expr, error) {
return ast.NewString(b.kubeVersion), nil
},
},
},
}
if len(tags) > 0 {
cfg.Tags = append(cfg.Tags, tags...)
}
modInstances := load.Instances([]string{}, cfg)
if len(modInstances) == 0 {
return value, errors.New("no instances found")
}
modInstance := modInstances[0]
if modInstance.Err != nil {
return value, fmt.Errorf("instance error: %w", modInstance.Err)
}
modValue := b.ctx.BuildInstance(modInstance)
if modValue.Err() != nil {
return value, modValue.Err()
}
// Extract the Timoni instance from the build value.
instance := modValue.LookupPath(cue.ParsePath(apiv1.InstanceSelector.String()))
if instance.Err() != nil {
return modValue, fmt.Errorf("lookup %s failed: %w", apiv1.InstanceSelector, instance.Err())
}
// Validate the Timoni instance which should be concrete and final.
if err := instance.Validate(cue.Concrete(true), cue.Final()); err != nil {
return modValue, err
}
return modValue, nil
}
// GetAPIVersion returns the list of API version of the Timoni's CUE definition.
func (b *ModuleBuilder) GetAPIVersion(value cue.Value) (string, error) {
ver := value.LookupPath(cue.ParsePath(apiv1.APIVersionSelector.String()))
if ver.Err() != nil {
return "", fmt.Errorf("lookup %s failed: %w", apiv1.APIVersionSelector, ver.Err())
}
return ver.String()
}
// GetApplySets returns the list of Kubernetes unstructured objects to be applied in steps.
func (b *ModuleBuilder) GetApplySets(value cue.Value) ([]ResourceSet, error) {
steps := value.LookupPath(cue.ParsePath(apiv1.ApplySelector.String()))
if steps.Err() != nil {
return nil, fmt.Errorf("lookup %s failed: %w", apiv1.ApplySelector, steps.Err())
}
return GetResources(steps)
}
// GetDefaultValues extracts the default values from the module.
func (b *ModuleBuilder) GetDefaultValues() (string, error) {
filePath := filepath.Join(b.pkgPath, defaultValuesFile)
var value cue.Value
vData, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
value = b.ctx.CompileBytes(vData)
if value.Err() != nil {
return "", value.Err()
}
expr := value.LookupPath(cue.ParsePath(apiv1.ValuesSelector.String()))
if expr.Err() != nil {
return "", fmt.Errorf("lookup %s failed: %w", apiv1.ValuesSelector, expr.Err())
}
return fmt.Sprintf("%v", expr.Eval()), nil
}
// GetModuleName returns the module name as defined in 'cue.mod/module.cue'.
func (b *ModuleBuilder) GetModuleName() (string, error) {
filePath := filepath.Join(b.moduleRoot, "cue.mod", "module.cue")
var value cue.Value
vData, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
value = b.ctx.CompileBytes(vData)
if value.Err() != nil {
return "", value.Err()
}
expr := value.LookupPath(cue.ParsePath("module"))
if expr.Err() != nil {
return "", fmt.Errorf("lookup module name failed: %w", expr.Err())
}
mod, err := expr.String()
if err != nil {
return "", fmt.Errorf("lookup module name failed: %w", err)
}
return mod, nil
}
// GetContainerImages extracts the container images referenced in the instance config values.
func (b *ModuleBuilder) GetContainerImages(value cue.Value) ([]string, error) {
cfgValues := value.LookupPath(cue.ParsePath(apiv1.ConfigValuesSelector.String()))
if cfgValues.Err() != nil {
return nil, fmt.Errorf("lookup %s failed: %w", apiv1.ConfigValuesSelector, cfgValues.Err())
}
var images []string
imgExtract := func(v cue.Value) bool {
switch v.IncompleteKind() {
case cue.StructKind:
var img apiv1.ImageReference
imgVal := reflect.ValueOf(img)
for i := 0; i < imgVal.Type().NumField(); i++ {
if tag, ok := imgVal.Type().Field(i).Tag.Lookup("json"); ok {
if !v.LookupPath(cue.ParsePath(tag)).Exists() {
return true
}
}
}
if err := v.Decode(&img); err == nil {
images = append(images, img.Reference)
}
}
return true
}
cfgValues.Walk(imgExtract, nil)
images = slices.Compact(images)
slices.Sort(images)
return images, nil
}
// GetConfigDoc extracts the config structure from the module.
func (b *ModuleBuilder) GetConfigDoc(value cue.Value) ([][]string, error) {
cfgValues := value.LookupPath(cue.ParsePath(apiv1.ConfigValuesSelector.String()))
if cfgValues.Err() != nil {
return nil, fmt.Errorf("lookup %s failed: %w", apiv1.ConfigValuesSelector, cfgValues.Err())
}
labelDomain := regexp.MustCompile(`^([a-zA-Z0-9-_.]+)?(".+")?$`)
var rows [][]string
configDataInfo := func(v cue.Value) bool {
var row []string
var noDoc bool
var doc string
for _, d := range v.Doc() {
if line := len(d.List) - 1; line >= 0 {
switch d.List[line].Text {
case "// +nodoc":
noDoc = true
break
}
}
doc += d.Text()
doc = strings.ReplaceAll(doc, "\n", " ")
doc = strings.ReplaceAll(doc, "+required", "")
doc = strings.ReplaceAll(doc, "+optional", "")
}
if !noDoc {
defaultVal, _ := v.Default()
valueBytes, _ := defaultVal.MarshalJSON()
valueType := strings.ReplaceAll(v.IncompleteKind().String(), "|", "\\|")
value := strings.ReplaceAll(string(valueBytes), "\":", "\": ")
value = strings.ReplaceAll(value, "\":[", "\": [")
value = strings.ReplaceAll(value, "},", "}, ")
value = strings.ReplaceAll(value, "|", "\\|")
field := strings.Replace(v.Path().String(), "timoni.instance.config.", "", 1)
match := labelDomain.FindStringSubmatch(field)
row = append(row, fmt.Sprintf("`%s:`", strings.ReplaceAll(match[1], ".", ": ")+match[2]))
row = append(row, fmt.Sprintf("`%s`", valueType))
row = append(row, fmt.Sprintf("`%s`", value))
row = append(row, fmt.Sprintf("%s", doc))
rows = append(rows, row)
}
return true
}
cfgValues.Walk(configDataInfo, nil)
return rows, nil
}