-
Notifications
You must be signed in to change notification settings - Fork 13
/
starlark.go
239 lines (203 loc) · 5.85 KB
/
starlark.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
package starlark
import (
"errors"
"fmt"
"strings"
"github.com/circonus-labs/circonus-unified-agent/cua"
"github.com/circonus-labs/circonus-unified-agent/plugins/processors"
"go.starlark.net/resolve"
"go.starlark.net/starlark"
"go.starlark.net/starlarkjson"
)
const (
description = "Process metrics using a Starlark script"
sampleConfig = `
## The Starlark source can be set as a string in this configuration file, or
## by referencing a file containing the script. Only one source or script
## should be set at once.
##
## Source of the Starlark script.
source = '''
def apply(metric):
return metric
'''
## File containing a Starlark script.
# script = "/usr/local/bin/myscript.star"
`
)
type Starlark struct {
Source string `toml:"source"`
Script string `toml:"script"`
Log cua.Logger `toml:"-"`
thread *starlark.Thread
applyFunc *starlark.Function
args starlark.Tuple
results []cua.Metric
}
func (s *Starlark) Init() error {
if s.Source == "" && s.Script == "" {
return errors.New("one of source or script must be set")
}
if s.Source != "" && s.Script != "" {
return errors.New("both source or script cannot be set")
}
s.thread = &starlark.Thread{
Print: func(_ *starlark.Thread, msg string) { s.Log.Debug(msg) },
Load: func(thread *starlark.Thread, module string) (starlark.StringDict, error) {
return loadFunc(thread, module, s.Log)
},
}
builtins := starlark.StringDict{}
builtins["Metric"] = starlark.NewBuiltin("Metric", newMetric)
builtins["deepcopy"] = starlark.NewBuiltin("deepcopy", deepcopy)
builtins["catch"] = starlark.NewBuiltin("catch", catch)
program, err := s.sourceProgram(builtins)
if err != nil {
return err
}
// Execute source
globals, err := program.Init(s.thread, builtins)
if err != nil {
return fmt.Errorf("program init: %w", err)
}
// Make available a shared state to the apply function
globals["state"] = starlark.NewDict(0)
// Freeze the global state. This prevents modifications to the processor
// state and prevents scripts from containing errors storing tracking
// metrics. Tasks that require global state will not be possible due to
// this, so maybe we should relax this in the future.
globals.Freeze()
// The source should define an apply function.
apply := globals["apply"]
if apply == nil {
return errors.New("apply is not defined")
}
var ok bool
if s.applyFunc, ok = apply.(*starlark.Function); !ok {
return errors.New("apply is not a function")
}
if s.applyFunc.NumParams() != 1 {
return errors.New("apply function must take one parameter")
}
// Reusing the same metric wrapper to skip an allocation. This will cause
// any saved references to point to the new metric, but due to freezing the
// globals none should exist.
s.args = make(starlark.Tuple, 1)
s.args[0] = &Metric{}
// Preallocate a slice for return values.
s.results = make([]cua.Metric, 0, 10)
return nil
}
func (s *Starlark) sourceProgram(builtins starlark.StringDict) (*starlark.Program, error) {
if s.Source != "" {
_, program, err := starlark.SourceProgram("processor.starlark", s.Source, builtins.Has)
return program, fmt.Errorf("source program (source:%s): %w", s.Source, err)
}
_, program, err := starlark.SourceProgram(s.Script, nil, builtins.Has)
return program, fmt.Errorf("source program (script:%s): %w", s.Script, err)
}
func (s *Starlark) SampleConfig() string {
return sampleConfig
}
func (s *Starlark) Description() string {
return description
}
func (s *Starlark) Start(acc cua.Accumulator) error {
return nil
}
func (s *Starlark) Add(metric cua.Metric, acc cua.Accumulator) error {
s.args[0].(*Metric).Wrap(metric)
rv, err := starlark.Call(s.thread, s.applyFunc, s.args, nil)
if err != nil {
var eerr *starlark.EvalError
if errors.As(err, &eerr) {
for _, line := range strings.Split(eerr.Backtrace(), "\n") {
s.Log.Error(line)
}
}
metric.Reject()
return fmt.Errorf("starlark call: %w", err)
}
switch rv := rv.(type) {
case *starlark.List:
iter := rv.Iterate()
defer iter.Done()
var v starlark.Value
for iter.Next(&v) {
switch v := v.(type) {
case *Metric:
m := v.Unwrap()
if containsMetric(s.results, m) {
s.Log.Errorf("Duplicate metric reference detected")
continue
}
s.results = append(s.results, m)
acc.AddMetric(m)
default:
s.Log.Errorf("Invalid type returned in list: %s", v.Type())
}
}
// If the script didn't return the original metrics, mark it as
// successfully handled.
if !containsMetric(s.results, metric) {
metric.Accept()
}
// clear results
for i := range s.results {
s.results[i] = nil
}
s.results = s.results[:0]
case *Metric:
m := rv.Unwrap()
// If the script returned a different metric, mark this metric as
// successfully handled.
if m != metric {
metric.Accept()
}
acc.AddMetric(m)
case starlark.NoneType:
metric.Drop()
default:
return fmt.Errorf("Invalid type returned: %T", rv)
}
return nil
}
func (s *Starlark) Stop() error {
return nil
}
func containsMetric(metrics []cua.Metric, metric cua.Metric) bool {
for _, m := range metrics {
if m == metric {
return true
}
}
return false
}
func init() {
// https://github.com/bazelbuild/starlark/issues/20
resolve.AllowNestedDef = true
resolve.AllowLambda = true
resolve.AllowFloat = true
resolve.AllowSet = true
resolve.AllowGlobalReassign = true
resolve.AllowRecursion = true
}
func init() {
processors.AddStreaming("starlark", func() cua.StreamingProcessor {
return &Starlark{}
})
}
func loadFunc(thread *starlark.Thread, module string, logger cua.Logger) (starlark.StringDict, error) { //nolint:unparam
switch module {
case "json.star":
return starlark.StringDict{
"json": starlarkjson.Module,
}, nil
case "logging.star":
return starlark.StringDict{
"log": LogModule(logger),
}, nil
default:
return nil, errors.New("module " + module + " is not available")
}
}