-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpythonExecutor.ts
291 lines (255 loc) · 7.52 KB
/
pythonExecutor.ts
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
import { PythonShell, Options, NewlineTransformer } from 'python-shell'
import { EOL } from 'os'
import { randomBytes } from 'crypto'
export interface FrameSummary {
_line: string
filename: string
lineno: number
locals: {}
name: string
}
export interface UserError {
__cause__: UserError
__context__: UserError
_str: string
cause: UserError
context: UserError
exc_traceback: {}
exc_type: {
"py/type": string
}
stack: {
"py/seq": FrameSummary[]
}
/* following for syntax errors only */
filename?: string
lineno?: string
msg?: string
offset?: number
text?: string
}
export interface ExecArgs {
evalCode: string,
filePath: string,
usePreviousVariables?: boolean,
show_global_vars?: boolean,
default_filter_vars: string[],
default_filter_types: string[]
}
export interface PythonResult {
userError: UserError,
userErrorMsg?: string,
userVariables: object,
execTime: number,
totalPyTime: number,
totalTime: number,
internalError: string,
caller: string,
lineno: number,
done: boolean,
startResult: boolean,
evaluatorName: string,
}
/**
* Starting = Starting or restarting.
* Ending = Process is exiting.
* Executing = Executing inputted code.
* DirtyFree = evaluator may have been polluted by side-effects from previous code, but is free for more code.
* FreshFree = evaluator is ready for the first run of code
*/
export enum PythonState {
Starting,
Ending,
Executing,
DirtyFree,
FreshFree
}
export class PythonExecutor {
private static readonly areplPythonBackendFolderPath = __dirname + '/python/'
// how long between SIGTERM and SIGKILL, in ms
static GRACE_PERIOD = 50
state: PythonState = PythonState.Starting
finishedStartingCallback: Function
evaluatorName: string
private startTime: number
/**
* an instance of python-shell. See https://github.com/extrabacon/python-shell
*/
pyshell: PythonShell
/**
* starts python_evaluator.py
* @param options Process / Python options. If not specified sensible defaults are inferred.
*/
constructor(private options: Options = {}) {
if (!options.env) options.env = {}
if (process.platform == "darwin") {
// needed for Mac to prevent ENOENT
options.env.PATH = ["/usr/local/bin", process.env.PATH].join(":")
}
else if (process.platform == "win32") {
// needed for windows for encoding to match what it would be in terminal
// https://docs.python.org/3/library/sys.html#sys.stdin
options.env.PYTHONIOENCODING = "utf8"
}
// python-shell buffers untill newline is reached in text mode
// so we use binary instead to skip python-shell buffering
// this lets user flush without newline
this.options.mode = 'binary'
this.options.stdio = ['pipe', 'pipe', 'pipe', 'pipe']
if (!options.pythonPath) this.options.pythonPath = PythonShell.defaultPythonPath
if (!options.scriptPath) this.options.scriptPath = PythonExecutor.areplPythonBackendFolderPath
this.evaluatorName = randomBytes(16).toString('hex')
}
/**
* does not do anything if program is currently executing code
*/
execCode(code: ExecArgs) {
if (this.state == PythonState.Executing){
console.error('Incoming code detected while process is still executing. \
This should never happen')
}
this.state = PythonState.Executing
this.startTime = Date.now()
this.pyshell.send(JSON.stringify(code) + EOL)
}
/**
* @param {string} message
*/
sendStdin(message: string) {
this.pyshell.send(message)
}
/**
* kills python process and restarts. Force-kills if necessary after 50ms.
* After process restarts the callback passed in is invoked
*/
restart(callback = () => { }) {
this.state = PythonState.Ending
// register callback for restart
// using childProcess callback instead of pyshell callback
// (pyshell callback only happens when process exits voluntarily)
this.pyshell.childProcess.on('exit', () => {
this.start(callback)
})
this.stop()
}
/**
* Kills python process. Force-kills if necessary after 50ms.
* You can check python_evaluator.running to see if process is dead yet
*/
stop(kill_immediately=false) {
this.state = PythonState.Ending
const kill_signal = kill_immediately ? 'SIGKILL' : 'SIGTERM'
this.pyshell.childProcess.kill(kill_signal)
if(!kill_immediately){
// pyshell has 50 ms to die gracefully
setTimeout(() => {
if (this.state == PythonState.Ending) {
// python didn't respect the SIGTERM, force-kill it
this.pyshell.childProcess.kill('SIGKILL')
}
}, PythonExecutor.GRACE_PERIOD)
}
}
/**
* starts python_evaluator.py.
*/
start(finishedStartingCallback) {
this.state = PythonState.Starting
console.log("Starting Python...")
this.finishedStartingCallback = finishedStartingCallback
this.startTime = Date.now()
this.pyshell = new PythonShell('arepl_python_evaluator.py', this.options)
const resultPipe = this.pyshell.childProcess.stdio[3]
const newlineTransformer = new NewlineTransformer()
resultPipe.pipe(newlineTransformer).on('data', this.handleResult.bind(this))
this.pyshell.stdout.on('data', (message: Buffer) => {
this.onPrint(message.toString())
})
this.pyshell.stderr.on('data', (log: Buffer) => {
this.onStderr(log.toString())
})
}
/**
* Overwrite this with your own handler.
* is called when program fails or completes
*/
onResult(foo: PythonResult) { }
/**
* Overwrite this with your own handler.
* Is called when program prints
* @param {string} foo
*/
onPrint(foo: string) { }
/**
* Overwrite this with your own handler.
* Is called when program logs stderr
* @param {string} foo
*/
onStderr(foo: string) { }
/**
* handles pyshell results and calls onResult / onPrint
* @param {string} results
*/
handleResult(results: string) {
let pyResult: PythonResult = {
userError: null,
userErrorMsg: "",
userVariables: {},
execTime: 0,
totalTime: 0,
totalPyTime: 0,
internalError: "",
caller: "",
lineno: -1,
done: true,
startResult: false,
evaluatorName: this.evaluatorName
}
try {
pyResult = JSON.parse(results)
if(pyResult.startResult){
console.log(`Finished starting in ${Date.now() - this.startTime}`)
this.state = PythonState.FreshFree
this.finishedStartingCallback()
return
}
if(pyResult['done'] == true){
this.state = PythonState.DirtyFree
}
pyResult.execTime = pyResult.execTime * 1000 // convert into ms
pyResult.totalPyTime = pyResult.totalPyTime * 1000
//@ts-ignore pyResult.userVariables is sent to as string, we convert to object
pyResult.userVariables = JSON.parse(pyResult.userVariables)
//@ts-ignore pyResult.userError is sent to as string, we convert to object
pyResult.userError = pyResult.userError ? JSON.parse(pyResult.userError) : {}
if (pyResult.userErrorMsg) {
pyResult.userErrorMsg = this.formatPythonException(pyResult.userErrorMsg)
}
pyResult.totalTime = Date.now() - this.startTime
this.onResult(pyResult)
} catch (err) {
if (err instanceof Error) {
err.message = err.message + "\nresults: " + results
}
throw err
}
}
/**
* checks syntax without executing code
* @param {string} code
* @returns {Promise} rejects w/ stderr if syntax failure
*/
async checkSyntax(code: string) {
return PythonShell.checkSyntax(code);
}
/**
* gets rid of unnecessary File "<string>" message in exception
* @example err:
* Traceback (most recent call last):\n File "<string>", line 1, in <module>\nNameError: name \'x\' is not defined\n
*/
private formatPythonException(err: string) {
//replace File "<string>" (pointless)
err = err.replace(/File \"<string>\", /g, "")
return err
}
}