-
Notifications
You must be signed in to change notification settings - Fork 18
/
larker.go
306 lines (258 loc) · 7.38 KB
/
larker.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
package larker
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs/cachinglayer"
"github.com/cirruslabs/cirrus-cli/pkg/larker/fs/dummy"
"github.com/cirruslabs/cirrus-cli/pkg/larker/loader"
"github.com/cirruslabs/cirrus-cli/pkg/yamlhelper"
"go.starlark.net/resolve"
"go.starlark.net/starlark"
"gopkg.in/yaml.v3"
"time"
)
var (
ErrLoadFailed = errors.New("load failed")
ErrNotFound = errors.New("entrypoint not found")
ErrMainFailed = errors.New("failed to call main")
ErrHookFailed = errors.New("failed to call hook")
ErrMainUnexpectedResult = errors.New("main returned unexpected result")
ErrSanity = errors.New("sanity check failed")
)
type Larker struct {
fs fs.FileSystem
env map[string]string
affectedFiles []string
isTest bool
}
type HookResult struct {
ErrorMessage string
OutputLogs []byte
DurationNanos int64
Result interface{}
}
type MainResult struct {
OutputLogs []byte
YAMLConfig string
}
func New(opts ...Option) *Larker {
lrk := &Larker{
fs: dummy.New(),
env: make(map[string]string),
}
// weird global init by Starlark
// we need floats at least for configuring CPUs for containers
resolve.AllowFloat = true
// Apply options
for _, opt := range opts {
opt(lrk)
}
// Wrap the final file system in a caching layer
wrappedFS, err := cachinglayer.Wrap(lrk.fs)
if err != nil {
panic(err)
}
lrk.fs = wrappedFS
return lrk
}
func (larker *Larker) MainOptional(ctx context.Context, source string) (*MainResult, error) {
result, err := larker.Main(ctx, source)
if errors.Is(err, ErrNotFound) {
return &MainResult{
OutputLogs: nil,
YAMLConfig: "",
}, nil
}
return result, err
}
func (larker *Larker) Main(ctx context.Context, source string) (*MainResult, error) {
outputLogsBuffer := &bytes.Buffer{}
capture := func(thread *starlark.Thread, msg string) {
_, _ = fmt.Fprintln(outputLogsBuffer, msg)
}
thread := &starlark.Thread{
Load: loader.NewLoader(ctx, larker.fs, larker.env, larker.affectedFiles, larker.isTest).LoadFunc(larker.fs),
Print: capture,
}
resCh := make(chan starlark.Value)
errCh := make(chan error)
go func() {
// Execute the source code for the main() to be visible
globals, err := starlark.ExecFile(thread, ".cirrus.star", source, nil)
if err != nil {
errCh <- fmt.Errorf("%w: %v", ErrLoadFailed, err)
return
}
// Retrieve main()
main, ok := globals["main"]
if !ok {
errCh <- fmt.Errorf("%w: main()", ErrNotFound)
return
}
// Ensure that main() is a function
mainFunc, ok := main.(*starlark.Function)
if !ok {
errCh <- fmt.Errorf("%w: main is not a function", ErrMainFailed)
return
}
var args starlark.Tuple
// Prepare a context to pass to main() as it's first argument if needed
if mainFunc.NumParams() != 0 {
args = append(args, &Context{})
}
mainResult, err := starlark.Call(thread, main, args, nil)
if err != nil {
errCh <- &ErrExecFailed{err: err}
return
}
resCh <- mainResult
}()
var mainResult starlark.Value
select {
case mainResult = <-resCh:
case err := <-errCh:
return nil, &ExtendedError{err: err, logs: logsWithErrorAttached(outputLogsBuffer.Bytes(), err)}
case <-ctx.Done():
thread.Cancel(ctx.Err().Error())
return nil, ctx.Err()
}
var tasksNode *yaml.Node
var err error
// main() should return a list of tasks or a dict resembling a Cirrus YAML configuration
switch typedMainResult := mainResult.(type) {
case *starlark.List:
tasksNode, err = convertInstructions(typedMainResult)
if err != nil {
return nil, err
}
if tasksNode == nil {
return &MainResult{OutputLogs: outputLogsBuffer.Bytes()}, nil
}
case *starlark.Dict:
tasksNode = convertDict(typedMainResult)
if tasksNode == nil {
return &MainResult{OutputLogs: outputLogsBuffer.Bytes()}, nil
}
case starlark.String:
return &MainResult{
OutputLogs: outputLogsBuffer.Bytes(),
YAMLConfig: typedMainResult.GoString(),
}, nil
default:
return nil, fmt.Errorf("%w: result is not a list, dict or str: %T", ErrMainUnexpectedResult,
typedMainResult)
}
formattedYaml, err := yamlhelper.PrettyPrint(tasksNode)
if err != nil {
return nil, fmt.Errorf("%w: cannot marshal into YAML: %v", ErrMainUnexpectedResult, err)
}
return &MainResult{
OutputLogs: outputLogsBuffer.Bytes(),
YAMLConfig: formattedYaml,
}, nil
}
func (larker *Larker) Hook(
ctx context.Context,
source string,
name string,
arguments []interface{},
) (*HookResult, error) {
if name == "" {
return nil, fmt.Errorf("%w: empty hook name specified", ErrSanity)
}
outputLogsBuffer := &bytes.Buffer{}
capture := func(thread *starlark.Thread, msg string) {
_, _ = fmt.Fprintln(outputLogsBuffer, msg)
}
thread := &starlark.Thread{
Load: loader.NewLoader(ctx, larker.fs, larker.env, []string{}, larker.isTest).LoadFunc(larker.fs),
Print: capture,
}
resCh := make(chan *HookResult)
errCh := make(chan error)
go func() {
// Execute the source code for the hook to be visible
globals, err := starlark.ExecFile(thread, ".cirrus.star", source, nil)
if err != nil {
errCh <- fmt.Errorf("%w: %v", ErrLoadFailed, err)
return
}
// Retrieve hook
hook, ok := globals[name]
if !ok {
errCh <- fmt.Errorf("%w: %s()", ErrNotFound, name)
return
}
// Ensure that hook is a function
hookFunc, ok := hook.(*starlark.Function)
if !ok {
errCh <- fmt.Errorf("%w: %s is not a function", ErrHookFailed, name)
return
}
var args starlark.Tuple
if hookFunc.NumParams() != 0 {
for i, argument := range arguments {
argumentStarlark, err := interfaceAsStarlarkValue(argument)
if err != nil {
errCh <- fmt.Errorf("%w: %s()'s %d argument should be JSON-compatible: %v",
ErrHookFailed, name, i+1, err)
return
}
args = append(args, argumentStarlark)
}
}
// Run hook and measure time spent
//
// We could've used unix.Getrusage() here instead, however:
// * it's not clear if we even need such level of precision at the moment
// * precise time measurement requires:
// * usage of the Linux-specific RUSAGE_THREAD flag
// * guarding starlark.Call() with runtime.LockOSThread()/runtime.UnlockOSThread()
hookStartTime := time.Now()
hookResult, err := starlark.Call(thread, hook, args, nil)
if err != nil {
errCh <- &ErrExecFailed{err: err}
return
}
durationNanos := time.Since(hookStartTime).Nanoseconds()
// Convert Starlark-style value to interface{}-style value
hookResultStarlark, err := starlarkValueAsInterface(hookResult)
if err != nil {
errCh <- err
return
}
// All good
resCh <- &HookResult{
OutputLogs: outputLogsBuffer.Bytes(),
DurationNanos: durationNanos,
Result: hookResultStarlark,
}
}()
select {
case hookResult := <-resCh:
return hookResult, nil
case err := <-errCh:
return &HookResult{
ErrorMessage: err.Error(),
OutputLogs: logsWithErrorAttached(outputLogsBuffer.Bytes(), err),
}, nil
case <-ctx.Done():
thread.Cancel(ctx.Err().Error())
return nil, ctx.Err()
}
}
func logsWithErrorAttached(logs []byte, err error) []byte {
fmt.Printf("%T\n", err)
ee, ok := errors.Unwrap(err).(*starlark.EvalError)
if !ok {
return logs
}
if len(logs) != 0 && !bytes.HasSuffix(logs, []byte("\n")) {
logs = append(logs, byte('\n'))
}
logs = append(logs, []byte(ee.Backtrace())...)
return logs
}