-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
hosted-plugin-process.ts
196 lines (164 loc) · 7.1 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
/********************************************************************************
* 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 path from 'path';
import * as cp from 'child_process';
import { injectable, inject, named } from 'inversify';
import { ILogger, ConnectionErrorHandler, ContributionProvider } from '@theia/core/lib/common';
import { Emitter } from '@theia/core/lib/common/event';
import { createIpcEnv } from '@theia/core/lib/node/messaging/ipc-protocol';
import { HostedPluginClient, ServerPluginRunner, PluginMetadata, PluginHostEnvironmentVariable } from '../../common/plugin-protocol';
import { RPCProtocolImpl } from '../../api/rpc-protocol';
import { MAIN_RPC_CONTEXT } from '../../api/plugin-api';
import { HostedPluginCliContribution } from './hosted-plugin-cli-contribution';
import {HostedPluginProcessesCache} from './hosted-plugin-processes-cache';
export interface IPCConnectionOptions {
readonly serverName: string;
readonly logger: ILogger;
readonly args: string[];
readonly errorHandler?: ConnectionErrorHandler;
}
@injectable()
export class HostedPluginProcess implements ServerPluginRunner {
@inject(ILogger)
protected readonly logger: ILogger;
@inject(HostedPluginCliContribution)
protected readonly cli: HostedPluginCliContribution;
@inject(HostedPluginProcessesCache)
protected readonly pluginProcessCache: HostedPluginProcessesCache;
@inject(ContributionProvider)
@named(PluginHostEnvironmentVariable)
protected readonly pluginHostEnvironmentVariables: ContributionProvider<PluginHostEnvironmentVariable>;
private childProcess: cp.ChildProcess | undefined;
private client: HostedPluginClient;
private async getClientId(): Promise<number> {
return await this.pluginProcessCache.getLazyClientId(this.client);
}
public setClient(client: HostedPluginClient): void {
if (this.client) {
if (this.childProcess) {
this.runPluginServer();
}
}
this.client = client;
this.getClientId().then(clientId => {
const childProcess = this.pluginProcessCache.retrieveClientChildProcess(clientId);
if (!this.childProcess && childProcess) {
this.childProcess = childProcess;
this.linkClientWithChildProcess(this.childProcess);
}
});
}
public clientClosed(): void {
}
public setDefault(defaultRunner: ServerPluginRunner): void {
}
// tslint:disable-next-line:no-any
public acceptMessage(jsonMessage: any): boolean {
return jsonMessage.type !== undefined && jsonMessage.id;
}
// tslint:disable-next-line:no-any
public onMessage(jsonMessage: any): void {
if (this.childProcess) {
this.childProcess.send(JSON.stringify(jsonMessage));
}
}
public markPluginServerTerminated() {
if (this.childProcess) {
this.pluginProcessCache.scheduleChildProcessTermination(this, this.childProcess);
}
}
public terminatePluginServer(): void {
if (this.childProcess === undefined) {
return;
}
// tslint:disable-next-line:no-shadowed-variable
const cp = this.childProcess;
this.childProcess = undefined;
const emitter = new Emitter();
cp.on('message', message => {
emitter.fire(JSON.parse(message));
});
const rpc = new RPCProtocolImpl({
onMessage: emitter.event,
send: (m: {}) => {
if (cp.send) {
cp.send(JSON.stringify(m));
}
}
});
const hostedPluginManager = rpc.getProxy(MAIN_RPC_CONTEXT.HOSTED_PLUGIN_MANAGER_EXT);
hostedPluginManager.$stopPlugin('').then(() => {
emitter.dispose();
cp.kill();
});
}
public runPluginServer(): void {
if (this.childProcess) {
this.terminatePluginServer();
}
this.childProcess = this.fork({
serverName: 'hosted-plugin',
logger: this.logger,
args: []
});
this.linkClientWithChildProcess(this.childProcess);
}
private linkClientWithChildProcess(childProcess: cp.ChildProcess) {
childProcess.on('message', message => {
if (this.client) {
this.client.postMessage(message);
}
});
this.getClientId().then(clientId => {
this.pluginProcessCache.linkLiveClientAndProcess(clientId, childProcess);
});
}
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(path.resolve(__dirname, 'plugin-host.js'), options.args, forkOptions);
childProcess.stdout.on('data', data => this.logger.info(`[${options.serverName}: ${childProcess.pid}] ${data.toString()}`));
childProcess.stderr.on('data', data => this.logger.error(`[${options.serverName}: ${childProcess.pid}] ${data.toString()}`));
this.logger.debug(`[${options.serverName}: ${childProcess.pid}] IPC started`);
childProcess.once('exit', () => this.logger.debug(`[${options.serverName}: ${childProcess.pid}] IPC exited`));
return childProcess;
}
async getExtraPluginMetadata(): Promise<PluginMetadata[]> {
return [];
}
}