-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.go
More file actions
205 lines (181 loc) · 4.85 KB
/
Copy pathloader.go
File metadata and controls
205 lines (181 loc) · 4.85 KB
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
package lamvms
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"maps"
"os"
"path/filepath"
"text/template"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
)
// DefaultMicrovmFiles is the list of default file names to search for.
var DefaultMicrovmFiles = []string{
"microvm.jsonnet",
"microvm.json",
}
// Loader loads and evaluates microvm definition files.
type Loader struct {
extStr map[string]string
extCode map[string]string
callerID *callerIdentity
}
// NewLoader creates a Loader with Jsonnet native functions and template functions.
func NewLoader(awsCfg aws.Config, extStr, extCode map[string]string) *Loader {
return &Loader{
extStr: extStr,
extCode: extCode,
callerID: newCallerIdentity(awsCfg),
}
}
// Load loads a MicrovmImage from the given path and returns the resolved path.
// If path is empty, it searches for default files.
func (l *Loader) Load(ctx context.Context, path string) (*MicrovmImage, string, error) {
var err error
if path == "" {
path, err = findMicrovmFile()
if err != nil {
return nil, "", err
}
}
expanded, err := l.loadAndExpand(ctx, path)
if err != nil {
return nil, "", err
}
var img MicrovmImage
if err := json.Unmarshal(expanded, &img); err != nil {
return nil, "", fmt.Errorf("failed to parse %s: %w", path, err)
}
return &img, path, nil
}
// LoadRunConfig loads a RunConfig from the given path.
func (l *Loader) LoadRunConfig(ctx context.Context, path string) (*RunConfig, error) {
expanded, err := l.loadAndExpand(ctx, path)
if err != nil {
return nil, err
}
var rc RunConfig
if err := json.Unmarshal(expanded, &rc); err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", path, err)
}
return &rc, nil
}
func (l *Loader) loadAndExpand(ctx context.Context, path string) ([]byte, error) {
slog.Info("loading definition", "path", path)
src, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %w", path, err)
}
if filepath.Ext(path) == ".jsonnet" {
slog.Debug("evaluating jsonnet")
vm := l.jsonnetVM(ctx)
evaluated, err := vm.EvaluateAnonymousSnippet(path, string(src))
if err != nil {
return nil, fmt.Errorf("failed to evaluate jsonnet %s: %w", path, err)
}
return []byte(evaluated), nil
}
return l.expandTemplate(ctx, src)
}
func findMicrovmFile() (string, error) {
for _, name := range DefaultMicrovmFiles {
if _, err := os.Stat(name); err == nil {
return name, nil
}
}
return "", fmt.Errorf("no microvm definition file found (searched: %v)", DefaultMicrovmFiles)
}
func (l *Loader) jsonnetVM(ctx context.Context) *jsonnet.VM {
vm := jsonnet.MakeVM()
for k, v := range l.extStr {
vm.ExtVar(k, v)
}
for k, v := range l.extCode {
vm.ExtCode(k, v)
}
nativeFuncs := []*jsonnet.NativeFunction{
nativeFuncEnv(),
nativeFuncMustEnv(),
}
nativeFuncs = append(nativeFuncs, l.callerID.jsonnetNativeFuncs(ctx)...)
for _, f := range nativeFuncs {
vm.NativeFunction(f)
}
return vm
}
func nativeFuncEnv() *jsonnet.NativeFunction {
return &jsonnet.NativeFunction{
Name: "env",
Params: ast.Identifiers{"name", "default"},
Func: func(args []any) (any, error) {
name, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("env: name must be a string")
}
if v, ok := os.LookupEnv(name); ok {
return v, nil
}
if args[1] == nil {
return "", nil
}
def, ok := args[1].(string)
if !ok {
return nil, fmt.Errorf("env: default must be a string")
}
return def, nil
},
}
}
func nativeFuncMustEnv() *jsonnet.NativeFunction {
return &jsonnet.NativeFunction{
Name: "must_env",
Params: ast.Identifiers{"name"},
Func: func(args []any) (any, error) {
name, ok := args[0].(string)
if !ok {
return nil, fmt.Errorf("must_env: name must be a string")
}
v, ok := os.LookupEnv(name)
if !ok {
return nil, fmt.Errorf("must_env: environment variable %q is not set", name)
}
return v, nil
},
}
}
func (l *Loader) expandTemplate(ctx context.Context, src []byte) ([]byte, error) {
funcMap := template.FuncMap{
"env": templateFuncEnv,
"must_env": templateFuncMustEnv,
}
maps.Copy(funcMap, l.callerID.templateFuncMap(ctx))
tmpl, err := template.New("microvm").Funcs(funcMap).Parse(string(src))
if err != nil {
return nil, fmt.Errorf("failed to parse template: %w", err)
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
return nil, fmt.Errorf("failed to execute template: %w", err)
}
return buf.Bytes(), nil
}
func templateFuncEnv(name string, defaultValues ...string) string {
if v, ok := os.LookupEnv(name); ok {
return v
}
if len(defaultValues) > 0 {
return defaultValues[0]
}
return ""
}
func templateFuncMustEnv(name string) (string, error) {
v, ok := os.LookupEnv(name)
if !ok {
return "", fmt.Errorf("environment variable %q is not set", name)
}
return v, nil
}