-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
runtime.go
365 lines (319 loc) · 11.3 KB
/
runtime.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
// Copyright 2018 The Nakama 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 server
import (
"database/sql"
"bytes"
"sync"
"context"
"github.com/heroiclabs/nakama/social"
"github.com/yuin/gopher-lua"
"go.opencensus.io/stats"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
)
const LTSentinel = lua.LValueType(-1)
type LSentinelType struct {
lua.LNilType
}
func (s *LSentinelType) String() string { return "" }
func (s *LSentinelType) Type() lua.LValueType { return LTSentinel }
var LSentinel = lua.LValue(&LSentinelType{})
type RuntimeModule struct {
Name string
Path string
Content []byte
}
type RuntimePool struct {
sync.Mutex
logger *zap.Logger
regCallbacks *RegCallbacks
moduleCache *ModuleCache
poolCh chan *Runtime
maxCount int
currentCount int
newFn func() *Runtime
statsCtx context.Context
statsRuntimeCount *stats.Int64Measure
}
func NewRuntimePool(logger, startupLogger *zap.Logger, db *sql.DB, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, sessionRegistry *SessionRegistry, matchRegistry MatchRegistry, tracker Tracker, router MessageRouter, stdLibs map[string]lua.LGFunction, moduleCache *ModuleCache, regCallbacks *RegCallbacks, once *sync.Once) *RuntimePool {
statsRuntimeCount, err := stats.Int64("nakama.runtime.count", "Number of pooled runtime instances.", stats.UnitNone)
if err != nil {
startupLogger.Fatal("Error creating stats entry for runtime count", zap.Error(err))
}
rp := &RuntimePool{
logger: logger,
regCallbacks: regCallbacks,
moduleCache: moduleCache,
poolCh: make(chan *Runtime, config.GetRuntime().MaxCount),
maxCount: config.GetRuntime().MaxCount,
// Set the current count assuming we'll warm up the pool in a moment.
currentCount: config.GetRuntime().MinCount,
newFn: func() *Runtime {
r, err := newVM(logger, db, config, socialClient, leaderboardCache, sessionRegistry, matchRegistry, tracker, router, stdLibs, moduleCache, once, nil)
if err != nil {
logger.Fatal("Failed initializing runtime.", zap.Error(err))
}
return r
},
statsCtx: context.Background(),
statsRuntimeCount: statsRuntimeCount,
}
// Warm up the pool.
startupLogger.Info("Allocating minimum runtime pool", zap.Int("count", rp.currentCount))
if len(moduleCache.Names) > 0 {
// Only if there are runtime modules to load.
for i := 0; i < config.GetRuntime().MinCount; i++ {
rp.poolCh <- rp.newFn()
}
stats.Record(rp.statsCtx, rp.statsRuntimeCount.M(int64(config.GetRuntime().MinCount)))
}
startupLogger.Info("Allocated minimum runtime pool")
return rp
}
func (rp *RuntimePool) HasCallback(mode ExecutionMode, id string) bool {
ok := false
switch mode {
case ExecutionModeRPC:
_, ok = rp.regCallbacks.RPC[id]
case ExecutionModeBefore:
_, ok = rp.regCallbacks.Before[id]
case ExecutionModeAfter:
_, ok = rp.regCallbacks.After[id]
case ExecutionModeMatchmaker:
ok = rp.regCallbacks.Matchmaker != nil
}
return ok
}
func (rp *RuntimePool) Get() *Runtime {
select {
case r := <-rp.poolCh:
// Ideally use an available idle runtime.
return r
default:
// If there was no idle runtime, see if we can allocate a new one.
rp.Lock()
if rp.currentCount >= rp.maxCount {
rp.Unlock()
// If we've reached the max allowed allocation block on an available runtime.
return <-rp.poolCh
}
// Inside the locked region now, last chance to use an available idle runtime.
// Note: useful in case a runtime becomes available while waiting to acquire lock.
select {
case r := <-rp.poolCh:
rp.Unlock()
return r
default:
// Allocate a new runtime.
rp.currentCount++
rp.Unlock()
stats.Record(rp.statsCtx, rp.statsRuntimeCount.M(1))
return rp.newFn()
}
}
}
func (rp *RuntimePool) Put(r *Runtime) {
select {
case rp.poolCh <- r:
// Runtime is successfully returned to the pool.
default:
// The pool is over capacity. Should never happen but guard anyway.
// Safe to continue processing, the runtime is just discarded.
rp.logger.Warn("Runtime pool full, discarding runtime")
}
}
func newVM(logger *zap.Logger, db *sql.DB, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, sessionRegistry *SessionRegistry, matchRegistry MatchRegistry, tracker Tracker, router MessageRouter, stdLibs map[string]lua.LGFunction, moduleCache *ModuleCache, once *sync.Once, announceCallback func(ExecutionMode, string)) (*Runtime, error) {
// Initialize a one-off runtime to ensure startup code runs and modules are valid.
vm := lua.NewState(lua.Options{
CallStackSize: config.GetRuntime().CallStackSize,
RegistrySize: config.GetRuntime().RegistrySize,
SkipOpenLibs: true,
IncludeGoStackTrace: true,
})
for name, lib := range stdLibs {
vm.Push(vm.NewFunction(lib))
vm.Push(lua.LString(name))
vm.Call(1, 0)
}
nakamaModule := NewNakamaModule(logger, db, config, socialClient, leaderboardCache, vm, sessionRegistry, matchRegistry, tracker, router, once, announceCallback)
vm.PreloadModule("nakama", nakamaModule.Loader)
r := &Runtime{
logger: logger,
vm: vm,
luaEnv: ConvertMap(vm, config.GetRuntime().Environment),
}
return r, r.loadModules(moduleCache)
}
type Runtime struct {
logger *zap.Logger
vm *lua.LState
luaEnv *lua.LTable
}
func (r *Runtime) loadModules(moduleCache *ModuleCache) error {
// `DoFile(..)` only parses and evaluates modules. Calling it multiple times, will load and eval the file multiple times.
// So to make sure that we only load and evaluate modules once, regardless of whether there is dependency between files, we load them all into `preload`.
// This is to make sure that modules are only loaded and evaluated once as `doFile()` does not (always) update _LOADED table.
// Bear in mind two separate thoughts around the script runtime design choice:
//
// 1) This is only a problem if one module is dependent on another module.
// This means that the global functions are evaluated once at system startup and then later on when the module is required through `require`.
// We circumvent this by checking the _LOADED table to check if `require` had evaluated the module and avoiding double-eval.
//
// 2) Second item is that modules must be pre-loaded into the state for callback-func eval to work properly (in case of HTTP/RPC/etc invokes)
// So we need to always load the modules into the system via `preload` so that they are always available in the LState.
// We can't rely on `require` to have seen the module in case there is no dependency between the modules.
//for _, mod := range r.modules {
// relPath, _ := filepath.Rel(r.luaPath, mod)
// moduleName := strings.TrimSuffix(relPath, filepath.Ext(relPath))
//
// // check to see if this module was loaded by `require` before executing it
// loaded := l.GetField(l.Get(lua.RegistryIndex), "_LOADED")
// lv := l.GetField(loaded, moduleName)
// if lua.LVAsBool(lv) {
// // Already evaluated module via `require(..)`
// continue
// }
//
// if err = l.DoFile(mod); err != nil {
// failedModules++
// r.logger.Error("Failed to evaluate module - skipping", zap.String("path", mod), zap.Error(err))
// }
//}
preload := r.vm.GetField(r.vm.GetField(r.vm.Get(lua.EnvironIndex), "package"), "preload")
fns := make(map[string]*lua.LFunction)
for _, name := range moduleCache.Names {
module, ok := moduleCache.Modules[name]
if !ok {
r.logger.Fatal("Failed to find named module in cache", zap.String("name", name))
}
f, err := r.vm.Load(bytes.NewReader(module.Content), module.Path)
if err != nil {
r.logger.Error("Could not load module", zap.String("name", module.Path), zap.Error(err))
return err
} else {
r.vm.SetField(preload, module.Name, f)
fns[module.Name] = f
}
}
for _, name := range moduleCache.Names {
fn, ok := fns[name]
if !ok {
r.logger.Fatal("Failed to find named module in prepared functions", zap.String("name", name))
}
loaded := r.vm.GetField(r.vm.Get(lua.RegistryIndex), "_LOADED")
lv := r.vm.GetField(loaded, name)
if lua.LVAsBool(lv) {
// Already evaluated module via `require(..)`
continue
}
r.vm.Push(fn)
fnErr := r.vm.PCall(0, -1, nil)
if fnErr != nil {
r.logger.Error("Could not complete runtime invocation", zap.Error(fnErr))
return fnErr
}
}
return nil
}
func (r *Runtime) NewStateThread() (*lua.LState, context.CancelFunc) {
return r.vm, nil
}
func (r *Runtime) GetCallback(e ExecutionMode, key string) *lua.LFunction {
cp := r.vm.Context().Value(CALLBACKS).(*Callbacks)
switch e {
case ExecutionModeRPC:
return cp.RPC[key]
case ExecutionModeBefore:
return cp.Before[key]
case ExecutionModeAfter:
return cp.After[key]
case ExecutionModeMatchmaker:
return cp.Matchmaker
}
return nil
}
func (r *Runtime) InvokeFunction(execMode ExecutionMode, fn *lua.LFunction, queryParams map[string][]string, uid string, username string, sessionExpiry int64, sid string, payload interface{}) (interface{}, error, codes.Code) {
ctx := NewLuaContext(r.vm, r.luaEnv, execMode, queryParams, uid, username, sessionExpiry, sid)
var lv lua.LValue
if payload != nil {
lv = ConvertValue(r.vm, payload)
}
retValue, err, code := r.invokeFunction(r.vm, fn, ctx, lv)
if err != nil {
return nil, err, code
}
if retValue == nil || retValue == lua.LNil {
return nil, nil, 0
}
return ConvertLuaValue(retValue), nil, 0
}
func (r *Runtime) invokeFunction(l *lua.LState, fn *lua.LFunction, ctx *lua.LTable, payload lua.LValue) (lua.LValue, error, codes.Code) {
l.Push(LSentinel)
l.Push(fn)
nargs := 1
l.Push(ctx)
if payload != nil {
nargs = 2
l.Push(payload)
}
err := l.PCall(nargs, lua.MultRet, nil)
if err != nil {
// Unwind the stack up to and including our sentinel value, effectively discarding any other returned parameters.
for {
v := l.Get(-1)
l.Pop(1)
if v.Type() == LTSentinel {
break
}
}
if apiError, ok := err.(*lua.ApiError); ok && apiError.Object.Type() == lua.LTTable {
t := apiError.Object.(*lua.LTable)
switch t.Len() {
case 0:
return nil, err, codes.Internal
case 1:
apiError.Object = t.RawGetInt(1)
return nil, err, codes.Internal
default:
// Ignore everything beyond the first 2 params, if there are more.
apiError.Object = t.RawGetInt(1)
code := codes.Internal
if c := t.RawGetInt(2); c.Type() == lua.LTNumber {
code = codes.Code(c.(lua.LNumber))
}
return nil, err, code
}
}
return nil, err, codes.Internal
}
retValue := l.Get(-1)
l.Pop(1)
if retValue.Type() == LTSentinel {
return nil, nil, 0
}
// Unwind the stack up to and including our sentinel value, effectively discarding any other returned parameters.
for {
v := l.Get(-1)
l.Pop(1)
if v.Type() == LTSentinel {
break
}
}
return retValue, nil, 0
}
func (r *Runtime) Stop() {
// Not necessarily required as it only does OS temp files cleanup, which we don't expose in the runtime.
r.vm.Close()
}