/
python-rpc-server-process.ts
86 lines (72 loc) · 2.66 KB
/
python-rpc-server-process.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
import { ChildProcess, spawn } from "child_process";
import * as path from "path";
import { log } from "@batch-flask/utils";
import { Constants } from "../client-constants";
import { pythonLogger } from "../logger";
import { getPythonPath } from "./python-executable";
const asarPath = path.join(Constants.root, "../python-rpc/main");
const localPath = path.join(Constants.root, "python/main.py");
const portPromise = process.env.HOT ? Constants.pythonServerPort.dev : Constants.pythonServerPort.prod;
export class PythonRpcServerProcess {
public port: Promise<number> = portPromise;
private _spawedProcess: ChildProcess;
private _askForKill: boolean;
/**
* Start the python server
* @returns Promise when the process has spawned
*/
public async start(): Promise<void> {
this._askForKill = false;
const data = await this._getCommandLine();
if (!data) {
log.info("Couldn't start the python server!");
return;
}
log.info(`Python path is: '${data.cmd}', Args: ${data.args}`);
const child = this._spawedProcess = spawn(data.cmd, ["-u", ...data.args], {
});
pythonLogger.info("========================= STARTING PYTHON RPC SERVER PROCESS =========================");
child.stdout.on("data", (data) => {
pythonLogger.info(data.toString());
});
child.stderr.on("data", (data) => {
pythonLogger.info(data.toString());
});
child.on("exit", (code) => {
if (this._askForKill) {
log.info("Python rpc server has stopped!");
} else {
log.error("Python Rpc server has exited unexpectedly with code!", code);
}
});
child.on("error", (e) => {
log.error("Error with python server", e);
});
log.info("Python Rpc server started!");
}
public stop() {
if (this._spawedProcess) {
this._askForKill = true;
log.info("Stopping python rpc server!");
this._spawedProcess.kill();
}
}
public async restart() {
this.stop();
return this.start();
}
private async _getCommandLine(): Promise<{ cmd: string, args: string[] } | null> {
const port = await portPromise;
const portStr = port.toString();
if (Constants.isAsar) {
return { cmd: asarPath, args: [portStr] };
} else {
const pythonPath = await getPythonPath();
if (!pythonPath) { return null; }
return {
cmd: pythonPath,
args: [localPath, portStr],
};
}
}
}