forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoprocess_python.go
315 lines (283 loc) · 7.66 KB
/
coprocess_python.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
// +build cgo
package gateway
import (
"C"
"io/ioutil"
"path/filepath"
"runtime"
"unsafe"
"github.com/sirupsen/logrus"
"fmt"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/coprocess"
python "github.com/TykTechnologies/tyk/dlpython"
"github.com/golang/protobuf/proto"
)
import (
"os"
"sync"
)
var (
dispatcherClass unsafe.Pointer
dispatcherInstance unsafe.Pointer
pythonLock = sync.Mutex{}
)
// PythonDispatcher implements a coprocess.Dispatcher
type PythonDispatcher struct {
coprocess.Dispatcher
}
// Dispatch takes a CoProcessMessage and sends it to the CP.
func (d *PythonDispatcher) Dispatch(object *coprocess.Object) (*coprocess.Object, error) {
// Prepare the PB object:
objectMsg, err := proto.Marshal(object)
if err != nil {
return nil, err
}
pythonLock.Lock()
// Find the dispatch_hook:
dispatchHookFunc, err := python.PyObjectGetAttr(dispatcherInstance, "dispatch_hook")
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Fatal(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
objectBytes, err := python.PyBytesFromString(objectMsg)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Fatal(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
args, err := python.PyTupleNew(1)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Fatal(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
python.PyTupleSetItem(args, 0, objectBytes)
result, err := python.PyObjectCallObject(dispatchHookFunc, args)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
python.PyDecRef(args)
python.PyDecRef(dispatchHookFunc)
newObjectPtr, err := python.PyTupleGetItem(result, 0)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
newObjectLen, err := python.PyTupleGetItem(result, 1)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
newObjectBytes, err := python.PyBytesAsString(newObjectPtr, python.PyLongAsLong(newObjectLen))
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
pythonLock.Unlock()
return nil, err
}
python.PyDecRef(result)
pythonLock.Unlock()
newObject := &coprocess.Object{}
err = proto.Unmarshal(newObjectBytes, newObject)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
return nil, err
}
return newObject, nil
}
// DispatchEvent dispatches a Tyk event.
func (d *PythonDispatcher) DispatchEvent(eventJSON []byte) {
/*
CEventJSON := C.CString(string(eventJSON))
defer C.free(unsafe.Pointer(CEventJSON))
C.Python_DispatchEvent(CEventJSON)
*/
}
// Reload triggers a reload affecting CP middlewares and event handlers.
func (d *PythonDispatcher) Reload() {
// C.Python_ReloadDispatcher()
}
// HandleMiddlewareCache isn't used by Python.
func (d *PythonDispatcher) HandleMiddlewareCache(b *apidef.BundleManifest, basePath string) {
pythonLock.Lock()
defer pythonLock.Unlock()
dispatcherLoadBundle, err := python.PyObjectGetAttr(dispatcherInstance, "load_bundle")
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
return
}
args, err := python.PyTupleNew(1)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
return
}
python.PyTupleSetItem(args, 0, basePath)
_, err = python.PyObjectCallObject(dispatcherLoadBundle, args)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
}
}
// PythonInit initializes the Python interpreter.
func PythonInit() error {
ver, err := python.FindPythonConfig(config.Global().CoProcessOptions.PythonVersion)
if err != nil {
log.WithError(err).Errorf("Python version '%s' doesn't exist", ver)
return fmt.Errorf("python version '%s' doesn't exist", ver)
}
err = python.Init()
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Fatal("Couldn't initialize Python")
}
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Infof("Python version '%s' loaded", ver)
return nil
}
// PythonLoadDispatcher creates reference to the dispatcher class.
func PythonLoadDispatcher() error {
pythonLock.Lock()
defer pythonLock.Unlock()
moduleDict, err := python.LoadModuleDict("dispatcher")
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Fatalf("Couldn't initialize Python dispatcher")
python.PyErr_Print()
return err
}
dispatcherClass, err = python.GetItem(moduleDict, "TykDispatcher")
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Fatalf("Couldn't initialize Python dispatcher")
python.PyErr_Print()
return err
}
return nil
}
// PythonNewDispatcher creates an instance of TykDispatcher.
func PythonNewDispatcher(bundleRootPath string) (coprocess.Dispatcher, error) {
pythonLock.Lock()
defer pythonLock.Unlock()
args, err := python.PyTupleNew(1)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Fatal(err)
return nil, err
}
if err := python.PyTupleSetItem(args, 0, bundleRootPath); err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
return nil, err
}
dispatcherInstance, err = python.PyObjectCallObject(dispatcherClass, args)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "python",
}).Error(err)
python.PyErr_Print()
return nil, err
}
dispatcher := &PythonDispatcher{}
return dispatcher, nil
}
// PythonSetEnv sets PYTHONPATH, it's called before initializing the interpreter.
func PythonSetEnv(pythonPaths ...string) {
python.SetPythonPath(pythonPaths)
}
// getBundlePaths will return an array of the available bundle directories:
func getBundlePaths() []string {
bundlePath := filepath.Join(config.Global().MiddlewarePath, "bundles")
directories := make([]string, 0)
bundles, _ := ioutil.ReadDir(bundlePath)
for _, f := range bundles {
if f.IsDir() {
fullPath := filepath.Join(bundlePath, f.Name())
directories = append(directories, fullPath)
}
}
return directories
}
// NewPythonDispatcher wraps all the actions needed for this CP.
func NewPythonDispatcher() (dispatcher coprocess.Dispatcher, err error) {
workDir := config.Global().CoProcessOptions.PythonPathPrefix
if workDir == "" {
tykBin, _ := os.Executable()
workDir = filepath.Dir(tykBin)
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Debugf("Python path prefix isn't set, using '%s'", workDir)
}
dispatcherPath := filepath.Join(workDir, "coprocess", "python")
tykPath := filepath.Join(dispatcherPath, "tyk")
protoPath := filepath.Join(workDir, "coprocess", "python", "proto")
bundleRootPath := filepath.Join(config.Global().MiddlewarePath, "bundles")
paths := []string{dispatcherPath, tykPath, protoPath, bundleRootPath}
// initDone is used to signal the end of Python initialization step:
initDone := make(chan error)
go func() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
PythonSetEnv(paths...)
err := PythonInit()
if err != nil {
initDone <- err
return
}
if err := PythonLoadDispatcher(); err != nil {
initDone <- err
return
}
dispatcher, err = PythonNewDispatcher(bundleRootPath)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
}).Error(err)
}
initDone <- err
}()
err = <-initDone
return dispatcher, err
}