-
Notifications
You must be signed in to change notification settings - Fork 1
/
coprocess_lua.go
213 lines (171 loc) · 5.73 KB
/
coprocess_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
// +build coprocess
// +build lua
package main
/*
#cgo pkg-config: luajit
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "coprocess/api.h"
#include "coprocess/lua/binding.h"
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
static void LoadMiddleware(char* middleware_file, char* middleware_contents) {
}
static void LoadMiddlewareIntoState(lua_State* L, char* middleware_name, char* middleware_contents) {
luaL_dostring(L, middleware_contents);
}
static int LuaDispatchHook(struct CoProcessMessage* object, struct CoProcessMessage* outputObject) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// luaL_dofile(L, "coprocess/lua/tyk/core.lua");
LoadCachedModules(L);
LoadCachedMiddleware(L);
lua_getglobal(L, "dispatch");
lua_pushlstring(L, object->p_data, object->length);
int call_result = lua_pcall(L, 1, 2, 0);
size_t lua_output_length = lua_tointeger(L, -1);
const char* lua_output_data = lua_tolstring(L, 0, &lua_output_length);
char* output = malloc(lua_output_length);
memmove(output, lua_output_data, lua_output_length);
lua_close(L);
outputObject->p_data = (void*)output;
outputObject->length = lua_output_length;
return 0;
}
static void LuaDispatchEvent(char* event_json) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_dofile(L, "coprocess/lua/tyk/core.lua");
lua_getglobal(L, "dispatch_event");
// lua_pushlstring(L, object->p_data, object->length);
int call_result = lua_pcall(L, 1, 1, 0);
lua_close(L);
}
*/
import "C"
import (
"errors"
"io/ioutil"
"path/filepath"
"unsafe"
"github.com/Sirupsen/logrus"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/coprocess"
)
// CoProcessName specifies the driver name.
const CoProcessName = apidef.LuaDriver
const (
// ModuleBasePath points to the Tyk modules path.
ModuleBasePath = "coprocess/lua"
// MiddlewareBasePath points to the custom middleware path.
MiddlewareBasePath = "middleware/lua"
)
// MessageType sets the default message type.
var MessageType = coprocess.JsonMessage
// gMiddlewareCache will hold LuaDispatcher.gMiddlewareCache.
var gMiddlewareCache map[string]string
var gModuleCache map[string]string
// LuaDispatcher implements a coprocess.Dispatcher
type LuaDispatcher struct {
// LuaDispatcher implements the coprocess.Dispatcher interface.
coprocess.Dispatcher
// MiddlewareCache will keep the middleware file name and contents in memory, the contents will be accessed when a Lua state is initialized.
MiddlewareCache map[string]string
ModuleCache map[string]string
}
// Dispatch takes a CoProcessMessage and sends it to the CP.
func (d *LuaDispatcher) Dispatch(objectPtr unsafe.Pointer, newObjectPtr unsafe.Pointer) error {
object := (*C.struct_CoProcessMessage)(objectPtr)
newObject := (*C.struct_CoProcessMessage)(newObjectPtr)
if result := C.LuaDispatchHook(object, newObject); result != 0 {
return errors.New("Dispatch error")
}
return nil
}
// Reload will perform a middleware reload when a hot reload is triggered.
func (d *LuaDispatcher) Reload() {
files, _ := ioutil.ReadDir(MiddlewareBasePath)
if d.MiddlewareCache == nil {
d.MiddlewareCache = make(map[string]string, len(files))
gMiddlewareCache = d.MiddlewareCache
} else {
for k := range d.MiddlewareCache {
delete(d.MiddlewareCache, k)
}
}
for _, f := range files {
middlewarePath := filepath.Join(MiddlewareBasePath, f.Name())
contents, err := ioutil.ReadFile(middlewarePath)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Error("Failed to read middleware file: ", err)
}
d.MiddlewareCache[f.Name()] = string(contents)
}
}
func (d *LuaDispatcher) HandleMiddlewareCache(b *apidef.BundleManifest, basePath string) {
for _, f := range b.FileList {
fullPath := filepath.Join(basePath, f)
contents, err := ioutil.ReadFile(fullPath)
if err == nil {
d.ModuleCache[f] = string(contents)
} else {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Error("Failed to read bundle file: ", err)
}
}
}
func (d *LuaDispatcher) LoadModules() {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Info("Loading Tyk/Lua modules.")
if d.ModuleCache == nil {
d.ModuleCache = make(map[string]string, 0)
gModuleCache = d.ModuleCache
}
middlewarePath := filepath.Join(ModuleBasePath, "bundle.lua")
contents, err := ioutil.ReadFile(middlewarePath)
if err == nil {
d.ModuleCache["bundle.lua"] = string(contents)
} else {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Error("Failed to read bundle file: ", err)
}
}
//export LoadCachedModules
func LoadCachedModules(luaState unsafe.Pointer) {
for moduleName, moduleContents := range gModuleCache {
cModuleName := C.CString(moduleName)
cModuleContents := C.CString(moduleContents)
C.LoadMiddlewareIntoState((*C.struct_lua_State)(luaState), cModuleName, cModuleContents)
C.free(unsafe.Pointer(cModuleName))
C.free(unsafe.Pointer(cModuleContents))
}
}
//export LoadCachedMiddleware
func LoadCachedMiddleware(luaState unsafe.Pointer) {
for middlewareName, middlewareContents := range gMiddlewareCache {
cMiddlewareName := C.CString(middlewareName)
cMiddlewareContents := C.CString(middlewareContents)
C.LoadMiddlewareIntoState((*C.struct_lua_State)(luaState), cMiddlewareName, cMiddlewareContents)
C.free(unsafe.Pointer(cMiddlewareName))
C.free(unsafe.Pointer(cMiddlewareContents))
}
}
func (d *LuaDispatcher) DispatchEvent(eventJSON []byte) {
CEventJSON := C.CString(string(eventJSON))
C.LuaDispatchEvent(CEventJSON)
C.free(unsafe.Pointer(CEventJSON))
}
// NewCoProcessDispatcher wraps all the actions needed for this CP.
func NewCoProcessDispatcher() (coprocess.Dispatcher, error) {
dispatcher := &LuaDispatcher{}
dispatcher.LoadModules()
dispatcher.Reload()
return dispatcher, nil
}