-
Notifications
You must be signed in to change notification settings - Fork 877
/
lua.go
395 lines (349 loc) · 11 KB
/
lua.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
/*
Copyright 2022 The Karmada Authors.
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 luavm
import (
"context"
"encoding/json"
"fmt"
"reflect"
"time"
lua "github.com/yuin/gopher-lua"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/klog/v2"
luajson "layeh.com/gopher-json"
configv1alpha1 "github.com/karmada-io/karmada/pkg/apis/config/v1alpha1"
workv1alpha2 "github.com/karmada-io/karmada/pkg/apis/work/v1alpha2"
"github.com/karmada-io/karmada/pkg/util/fixedpool"
lualifted "github.com/karmada-io/karmada/pkg/util/lifted/lua"
)
// VM Defines a struct that implements the luaVM.
type VM struct {
// UseOpenLibs flag to enable open libraries. Libraries are disabled by default while running, but enabled during testing to allow the use of print statements.
UseOpenLibs bool
Pool *fixedpool.FixedPool
}
// New creates a manager for lua VM
func New(useOpenLibs bool, poolSize int) *VM {
vm := &VM{
UseOpenLibs: useOpenLibs,
}
vm.Pool = fixedpool.New(
"luavm",
func() (any, error) { return vm.NewLuaState() },
func(a any) { a.(*lua.LState).Close() },
poolSize)
return vm
}
// NewLuaState creates a new lua state.
func (vm *VM) NewLuaState() (*lua.LState, error) {
l := lua.NewState(lua.Options{
SkipOpenLibs: !vm.UseOpenLibs,
})
// Opens table library to allow access to functions to manipulate tables
err := vm.setLib(l)
if err != nil {
return nil, err
}
// preload kube library. Allows the 'local kube = require("kube")' to work
l.PreloadModule(KubeLibName, KubeLoader)
return l, err
}
// RunScript got a lua vm from pool, and execute script with given arguments.
func (vm *VM) RunScript(script string, fnName string, nRets int, args ...interface{}) ([]lua.LValue, error) {
a, err := vm.Pool.Get()
if err != nil {
return nil, err
}
defer vm.Pool.Put(a)
l := a.(*lua.LState)
l.Pop(l.GetTop())
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
l.SetContext(ctx)
err = l.DoString(script)
if err != nil {
return nil, err
}
vArgs := make([]lua.LValue, len(args))
for i, arg := range args {
vArgs[i], err = decodeValue(l, arg)
if err != nil {
return nil, err
}
}
f := l.GetGlobal(fnName)
if f.Type() == lua.LTNil {
return nil, fmt.Errorf("not found function %v", fnName)
}
if f.Type() != lua.LTFunction {
return nil, fmt.Errorf("%s is not a function: %s", fnName, f.Type())
}
err = l.CallByParam(lua.P{
Fn: f,
NRet: nRets,
Protect: true,
}, vArgs...)
if err != nil {
return nil, err
}
// get rets from stack: [ret1, ret2, ret3 ...]
rets := make([]lua.LValue, nRets)
for i := range rets {
rets[i] = l.Get(i + 1)
}
// pop all the values in stack
l.Pop(l.GetTop())
return rets, nil
}
// GetReplicas returns the desired replicas of the object as well as the requirements of each replica by lua script.
func (vm *VM) GetReplicas(obj *unstructured.Unstructured, script string) (replica int32, requires *workv1alpha2.ReplicaRequirements, err error) {
results, err := vm.RunScript(script, "GetReplicas", 2, obj)
if err != nil {
return 0, nil, err
}
replica, err = ConvertLuaResultToInt(results[0])
if err != nil {
return 0, nil, err
}
replicaRequirementResult := results[1]
requires = &workv1alpha2.ReplicaRequirements{}
if replicaRequirementResult.Type() == lua.LTTable {
err = ConvertLuaResultInto(replicaRequirementResult, requires)
if err != nil {
klog.Errorf("ConvertLuaResultToReplicaRequirements err %v", err.Error())
return 0, nil, err
}
} else if replicaRequirementResult.Type() == lua.LTNil {
requires = nil
} else {
return 0, nil, fmt.Errorf("expect the returned requires type is table but got %s", replicaRequirementResult.Type())
}
return
}
// ReviseReplica revises the replica of the given object by lua.
func (vm *VM) ReviseReplica(object *unstructured.Unstructured, replica int64, script string) (*unstructured.Unstructured, error) {
results, err := vm.RunScript(script, "ReviseReplica", 1, object, replica)
if err != nil {
return nil, err
}
luaResult := results[0]
reviseReplicaResult := &unstructured.Unstructured{}
if luaResult.Type() == lua.LTTable {
err := ConvertLuaResultInto(luaResult, reviseReplicaResult)
if err != nil {
return nil, err
}
return reviseReplicaResult, nil
}
return nil, fmt.Errorf("expect the returned requires type is table but got %s", luaResult.Type())
}
func (vm *VM) setLib(l *lua.LState) error {
for _, pair := range []struct {
n string
f lua.LGFunction
}{
{lua.LoadLibName, lualifted.OpenPackage},
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
{lua.StringLibName, lua.OpenString},
{lua.MathLibName, lua.OpenMath},
// load our 'safe' version of the OS library
{lua.OsLibName, lualifted.OpenSafeOs},
} {
if err := l.CallByParam(lua.P{
Fn: l.NewFunction(pair.f),
NRet: 0,
Protect: true,
}, lua.LString(pair.n)); err != nil {
return err
}
}
// Set potentially unsafe basic functions to nil, prohibiting users from
// calling these functions in custom Lua scripts.
// For the safety analysis of Sandbox in Lua, please refer to http://lua-users.org/wiki/SandBoxes
// For users, these functions are not needed for parsing resource templates,
// so disabling these functions has no impact on functionality.
for _, value := range []string{
"collectgarbage",
"dofile",
"getfenv",
"getmetatable",
"load",
"loadfile",
"loadstring",
"rawequal",
"rawget",
"rawset",
"setfenv",
"setmetatable",
"module",
"newproxy",
} {
overrideFunc := "function %s() error('call function %s is not supported in karmada customized resourceinterpreter.') end"
err := l.DoString(fmt.Sprintf(overrideFunc, value, value))
if err != nil {
return err
}
}
return nil
}
// Retain returns the objects that based on the "desired" object but with values retained from the "observed" object by lua.
func (vm *VM) Retain(desired *unstructured.Unstructured, observed *unstructured.Unstructured, script string) (retained *unstructured.Unstructured, err error) {
results, err := vm.RunScript(script, "Retain", 1, desired, observed)
if err != nil {
return nil, err
}
luaResult := results[0]
retainResult := &unstructured.Unstructured{}
if luaResult.Type() == lua.LTTable {
err := ConvertLuaResultInto(luaResult, retainResult)
if err != nil {
return nil, err
}
return retainResult, nil
}
return nil, fmt.Errorf("expect the returned requires type is table but got %s", luaResult.Type())
}
// AggregateStatus returns the objects that based on the 'object' but with status aggregated by lua.
func (vm *VM) AggregateStatus(object *unstructured.Unstructured, items []workv1alpha2.AggregatedStatusItem, script string) (*unstructured.Unstructured, error) {
results, err := vm.RunScript(script, "AggregateStatus", 1, object, items)
if err != nil {
return nil, err
}
luaResult := results[0]
aggregateStatus := &unstructured.Unstructured{}
if luaResult.Type() == lua.LTTable {
err := ConvertLuaResultInto(luaResult, aggregateStatus)
if err != nil {
return nil, err
}
return aggregateStatus, nil
}
return nil, fmt.Errorf("expect the returned requires type is table but got %s", luaResult.Type())
}
// InterpretHealth returns the health state of the object by lua.
func (vm *VM) InterpretHealth(object *unstructured.Unstructured, script string) (bool, error) {
results, err := vm.RunScript(script, "InterpretHealth", 1, object)
if err != nil {
return false, err
}
var health bool
health, err = ConvertLuaResultToBool(results[0])
if err != nil {
return false, err
}
return health, nil
}
// ReflectStatus returns the status of the object by lua.
func (vm *VM) ReflectStatus(object *unstructured.Unstructured, script string) (status *runtime.RawExtension, err error) {
results, err := vm.RunScript(script, "ReflectStatus", 1, object)
if err != nil {
return nil, err
}
luaStatusResult := results[0]
if luaStatusResult.Type() != lua.LTTable {
return nil, fmt.Errorf("expect the returned replica type is table but got %s", luaStatusResult.Type())
}
status = &runtime.RawExtension{}
err = ConvertLuaResultInto(luaStatusResult, status)
return status, err
}
// GetDependencies returns the dependent resources of the given object by lua.
func (vm *VM) GetDependencies(object *unstructured.Unstructured, script string) (dependencies []configv1alpha1.DependentObjectReference, err error) {
results, err := vm.RunScript(script, "GetDependencies", 1, object)
if err != nil {
return nil, err
}
luaResult := results[0]
if luaResult.Type() != lua.LTTable {
return nil, fmt.Errorf("expect the returned requires type is table but got %s", luaResult.Type())
}
err = ConvertLuaResultInto(luaResult, &dependencies)
return
}
// NewWithContext creates a lua VM with the given context.
func NewWithContext(ctx context.Context) (*lua.LState, error) {
vm := VM{}
l := lua.NewState(lua.Options{
SkipOpenLibs: !vm.UseOpenLibs,
})
// Opens table library to allow access to functions to manipulate tables
err := vm.setLib(l)
if err != nil {
return nil, err
}
// preload kube library. Allows the 'local kube = require("kube")' to work
l.PreloadModule(KubeLibName, KubeLoader)
if ctx != nil {
l.SetContext(ctx)
}
return l, nil
}
// nolint:gocyclo
func decodeValue(L *lua.LState, value interface{}) (lua.LValue, error) {
// We handle simple type without json for better performance.
switch converted := value.(type) {
case []interface{}:
arr := L.CreateTable(len(converted), 0)
for _, item := range converted {
v, err := decodeValue(L, item)
if err != nil {
return nil, err
}
arr.Append(v)
}
return arr, nil
case map[string]interface{}:
tbl := L.CreateTable(0, len(converted))
for key, item := range converted {
v, err := decodeValue(L, item)
if err != nil {
return nil, err
}
tbl.RawSetString(key, v)
}
return tbl, nil
case nil:
return lua.LNil, nil
}
v := reflect.ValueOf(value)
switch {
case v.CanInt():
return lua.LNumber(v.Int()), nil
case v.CanUint():
return lua.LNumber(v.Uint()), nil
case v.CanFloat():
return lua.LNumber(v.Float()), nil
}
switch t := v.Type(); t.Kind() {
case reflect.String:
return lua.LString(v.String()), nil
case reflect.Bool:
return lua.LBool(v.Bool()), nil
case reflect.Pointer:
if v.IsNil() {
return lua.LNil, nil
}
}
// Other types can't be handled, ask for help from json
data, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("json Marshal obj %#v error: %v", value, err)
}
lv, err := luajson.Decode(L, data)
if err != nil {
return nil, fmt.Errorf("lua Decode obj %#v error: %v", value, err)
}
return lv, nil
}