-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
hosted-plugin-process.ts
234 lines (196 loc) · 8.54 KB
/
hosted-plugin-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
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
/********************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
import * as cp from 'child_process';
import { injectable, inject, named } from 'inversify';
import { ILogger, ConnectionErrorHandler, ContributionProvider, MessageService } from '@theia/core/lib/common';
import { createIpcEnv } from '@theia/core/lib/node/messaging/ipc-protocol';
import { HostedPluginClient, ServerPluginRunner, PluginHostEnvironmentVariable, DeployedPlugin } from '../../common/plugin-protocol';
import { MessageType } from '../../common/rpc-protocol';
import { HostedPluginCliContribution } from './hosted-plugin-cli-contribution';
import * as psTree from 'ps-tree';
import { Deferred } from '@theia/core/lib/common/promise-util';
export interface IPCConnectionOptions {
readonly serverName: string;
readonly logger: ILogger;
readonly args: string[];
readonly errorHandler?: ConnectionErrorHandler;
}
export const HostedPluginProcessConfiguration = Symbol('HostedPluginProcessConfiguration');
export interface HostedPluginProcessConfiguration {
readonly path: string
}
@injectable()
export class HostedPluginProcess implements ServerPluginRunner {
@inject(HostedPluginProcessConfiguration)
protected configuration: HostedPluginProcessConfiguration;
@inject(ILogger)
protected readonly logger: ILogger;
@inject(HostedPluginCliContribution)
protected readonly cli: HostedPluginCliContribution;
@inject(ContributionProvider)
@named(PluginHostEnvironmentVariable)
protected readonly pluginHostEnvironmentVariables: ContributionProvider<PluginHostEnvironmentVariable>;
@inject(MessageService)
protected readonly messageService: MessageService;
private childProcess: cp.ChildProcess | undefined;
private client: HostedPluginClient;
private terminatingPluginServer = false;
public setClient(client: HostedPluginClient): void {
if (this.client) {
if (this.childProcess) {
this.runPluginServer();
}
}
this.client = client;
}
public clientClosed(): void {
}
public setDefault(defaultRunner: ServerPluginRunner): void {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public acceptMessage(jsonMessage: any): boolean {
return jsonMessage.type !== undefined && jsonMessage.id;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public onMessage(jsonMessage: any): void {
if (this.childProcess) {
this.childProcess.send(JSON.stringify(jsonMessage));
}
}
async terminatePluginServer(): Promise<void> {
if (this.childProcess === undefined) {
return;
}
this.terminatingPluginServer = true;
// eslint-disable-next-line @typescript-eslint/no-shadow
const cp = this.childProcess;
this.childProcess = undefined;
const waitForTerminated = new Deferred<void>();
cp.on('message', message => {
const msg = JSON.parse(message);
if ('type' in msg && msg.type === MessageType.Terminated) {
waitForTerminated.resolve();
}
});
const stopTimeout = this.cli.pluginHostStopTimeout;
cp.send(JSON.stringify({ type: MessageType.Terminate, stopTimeout }));
const terminateTimeout = this.cli.pluginHostTerminateTimeout;
if (terminateTimeout) {
await Promise.race([
waitForTerminated.promise,
new Promise(resolve => setTimeout(resolve, terminateTimeout))
]);
} else {
await waitForTerminated.promise;
}
this.killProcessTree(cp.pid);
}
killProcessTree(parentPid: number): void {
psTree(parentPid, (_, childProcesses) => {
childProcesses.forEach(childProcess =>
this.killProcess(parseInt(childProcess.PID))
);
this.killProcess(parentPid);
});
}
protected killProcess(pid: number): void {
try {
process.kill(pid);
} catch (e) {
if (e && 'code' in e && e.code === 'ESRCH') {
return;
}
this.logger.error(`[${pid}] failed to kill`, e);
}
}
public runPluginServer(): void {
if (this.childProcess) {
this.terminatePluginServer();
}
this.terminatingPluginServer = false;
this.childProcess = this.fork({
serverName: 'hosted-plugin',
logger: this.logger,
args: []
});
this.childProcess.on('message', message => {
if (this.client) {
this.client.postMessage(message);
}
});
}
readonly HOSTED_PLUGIN_ENV_REGEXP_EXCLUSION = new RegExp('HOSTED_PLUGIN*');
private fork(options: IPCConnectionOptions): cp.ChildProcess {
// create env and add PATH to it so any executable from root process is available
const env = createIpcEnv({ env: process.env });
for (const key of Object.keys(env)) {
if (this.HOSTED_PLUGIN_ENV_REGEXP_EXCLUSION.test(key)) {
delete env[key];
}
}
// apply external env variables
this.pluginHostEnvironmentVariables.getContributions().forEach(envVar => envVar.process(env));
if (this.cli.extensionTestsPath) {
env.extensionTestsPath = this.cli.extensionTestsPath;
}
const forkOptions: cp.ForkOptions = {
silent: true,
env: env,
execArgv: [],
stdio: ['pipe', 'pipe', 'pipe', 'ipc']
};
const inspectArgPrefix = `--${options.serverName}-inspect`;
const inspectArg = process.argv.find(v => v.startsWith(inspectArgPrefix));
if (inspectArg !== undefined) {
forkOptions.execArgv = ['--nolazy', `--inspect${inspectArg.substr(inspectArgPrefix.length)}`];
}
const childProcess = cp.fork(this.configuration.path, options.args, forkOptions);
childProcess.stdout!.on('data', data => this.logger.info(`[${options.serverName}: ${childProcess.pid}] ${data.toString().trim()}`));
childProcess.stderr!.on('data', data => this.logger.error(`[${options.serverName}: ${childProcess.pid}] ${data.toString().trim()}`));
this.logger.debug(`[${options.serverName}: ${childProcess.pid}] IPC started`);
childProcess.once('exit', (code: number, signal: string) => this.onChildProcessExit(options.serverName, childProcess.pid, code, signal));
childProcess.on('error', err => this.onChildProcessError(err));
return childProcess;
}
private onChildProcessExit(serverName: string, pid: number, code: number, signal: string): void {
if (this.terminatingPluginServer) {
return;
}
this.logger.error(`[${serverName}: ${pid}] IPC exited, with signal: ${signal}, and exit code: ${code}`);
const message = 'Plugin runtime crashed unexpectedly, all plugins are not working, please reload the page.';
let hintMessage: string = 'If it doesn\'t help, please check Theia server logs.';
if (signal && signal.toUpperCase() === 'SIGKILL') {
// May happen in case of OOM or manual force stop.
hintMessage = 'Probably there is not enough memory for the plugins. ' + hintMessage;
}
this.messageService.error(message + ' ' + hintMessage, { timeout: 15 * 60 * 1000 });
}
private onChildProcessError(err: Error): void {
this.logger.error(`Error from plugin host: ${err.message}`);
}
/**
* Provides additional plugin ids.
*/
public async getExtraDeployedPluginIds(): Promise<string[]> {
return [];
}
/**
* Provides additional deployed plugins.
*/
public async getExtraDeployedPlugins(): Promise<DeployedPlugin[]> {
return [];
}
}