processes.ts 16.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import path = require('path');
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import exec = cp.exec;
import spawn = cp.spawn;
B
Benjamin Pasero 已提交
12
import { PassThrough } from 'stream';
B
Benjamin Pasero 已提交
13
import { fork } from 'vs/base/node/stdFork';
E
Erich Gamma 已提交
14
import nls = require('vs/nls');
15
import { PPromise, TPromise, TValueCallback, TProgressCallback, ErrorCallback } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
16 17 18 19 20 21 22
import * as Types from 'vs/base/common/types';
import { IStringDictionary } from 'vs/base/common/collections';
import URI from 'vs/base/common/uri';
import * as Objects from 'vs/base/common/objects';
import * as TPath from 'vs/base/common/paths';
import * as Platform from 'vs/base/common/platform';
import { LineDecoder } from 'vs/base/node/decoder';
D
Dirk Baeumer 已提交
23 24
import { CommandOptions, ForkOptions, SuccessData, Source, TerminateResponse, TerminateResponseCode, Executable } from 'vs/base/common/processes';
export { CommandOptions, ForkOptions, SuccessData, Source, TerminateResponse, TerminateResponseCode };
E
Erich Gamma 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

export interface LineData {
	line: string;
	source: Source;
}

export interface BufferData {
	data: Buffer;
	source: Source;
}

export interface StreamData {
	stdin: NodeJS.WritableStream;
	stdout: NodeJS.ReadableStream;
	stderr: NodeJS.ReadableStream;
}

D
Dirk Baeumer 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
function getWindowsCode(status: number): TerminateResponseCode {
	switch (status) {
		case 0:
			return TerminateResponseCode.Success;
		case 1:
			return TerminateResponseCode.AccessDenied;
		case 128:
			return TerminateResponseCode.ProcessNotFound;
		default:
			return TerminateResponseCode.Unknown;
	}
}

E
Erich Gamma 已提交
55 56 57
export function terminateProcess(process: ChildProcess, cwd?: string): TerminateResponse {
	if (Platform.isWindows) {
		try {
J
Johannes Rieken 已提交
58
			let options: any = {
E
Erich Gamma 已提交
59 60 61
				stdio: ['pipe', 'pipe', 'ignore']
			};
			if (cwd) {
B
Benjamin Pasero 已提交
62
				options.cwd = cwd;
E
Erich Gamma 已提交
63
			}
D
Dirk Baeumer 已提交
64
			cp.execFileSync('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options);
E
Erich Gamma 已提交
65
		} catch (err) {
J
Johannes Rieken 已提交
66
			return { success: false, error: err, code: err.status ? getWindowsCode(err.status) : TerminateResponseCode.Unknown };
E
Erich Gamma 已提交
67 68 69
		}
	} else if (Platform.isLinux || Platform.isMacintosh) {
		try {
B
Benjamin Pasero 已提交
70
			let cmd = URI.parse(require.toUrl('vs/base/node/terminateProcess.sh')).fsPath;
D
Dirk Baeumer 已提交
71
			let result = cp.spawnSync(cmd, [process.pid.toString()]);
E
Erich Gamma 已提交
72 73 74 75 76 77 78 79 80 81 82 83
			if (result.error) {
				return { success: false, error: result.error };
			}
		} catch (err) {
			return { success: false, error: err };
		}
	} else {
		process.kill('SIGKILL');
	}
	return { success: true };
}

84 85 86 87
export function getWindowsShell(): string {
	return process.env['comspec'] || 'cmd.exe';
}

E
Erich Gamma 已提交
88 89 90 91 92 93 94 95 96
export abstract class AbstractProcess<TProgressData> {
	private cmd: string;
	private module: string;
	private args: string[];
	private options: CommandOptions | ForkOptions;
	protected shell: boolean;

	private childProcess: ChildProcess;
	protected childProcessPromise: TPromise<ChildProcess>;
J
Johannes Rieken 已提交
97
	protected terminateRequested: boolean;
E
Erich Gamma 已提交
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

	private static WellKnowCommands: IStringDictionary<boolean> = {
		'ant': true,
		'cmake': true,
		'eslint': true,
		'gradle': true,
		'grunt': true,
		'gulp': true,
		'jake': true,
		'jenkins': true,
		'jshint': true,
		'make': true,
		'maven': true,
		'msbuild': true,
		'msc': true,
		'nmake': true,
		'npm': true,
		'rake': true,
		'tsc': true,
		'xbuild': true
	};

	public constructor(executable: Executable);
	public constructor(cmd: string, args: string[], shell: boolean, options: CommandOptions);
	public constructor(module: string, args: string[], options: ForkOptions);
	public constructor(arg1: string | Executable, arg2?: string[], arg3?: boolean | ForkOptions, arg4?: CommandOptions) {
		if (arg4) {
			this.cmd = <string>arg1;
			this.args = arg2;
			this.shell = <boolean>arg3;
			this.options = arg4;
		} else if (arg3 && arg2) {
			this.module = <string>arg1;
			this.args = arg2;
			this.shell = false;
			this.options = <ForkOptions>arg3;
		} else {
P
Pascal Borreli 已提交
135 136 137 138 139
			let executable = <Executable>arg1;
			this.cmd = executable.command;
			this.shell = executable.isShellCommand;
			this.args = executable.args.slice(0);
			this.options = executable.options || {};
E
Erich Gamma 已提交
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
		}

		this.childProcess = null;
		this.terminateRequested = false;

		if (this.options.env) {
			let newEnv: IStringDictionary<string> = Object.create(null);
			Object.keys(process.env).forEach((key) => {
				newEnv[key] = process.env[key];
			});
			Object.keys(this.options.env).forEach((key) => {
				newEnv[key] = this.options.env[key];
			});
			this.options.env = newEnv;
		}
	}

	public getSanitizedCommand(): string {
		let result = this.cmd.toLowerCase();
		let index = result.lastIndexOf(path.sep);
		if (index !== -1) {
			result = result.substring(index + 1);
		}
		if (AbstractProcess.WellKnowCommands[result]) {
			return result;
		}
		return 'other';
	}

	public start(): PPromise<SuccessData, TProgressData> {
		if (Platform.isWindows && ((this.options && this.options.cwd && TPath.isUNC(this.options.cwd)) || !this.options && !this.options.cwd && TPath.isUNC(process.cwd()))) {
171
			return TPromise.wrapError(new Error(nls.localize('TaskRunner.UNC', 'Can\'t execute a shell command on an UNC drive.')));
E
Erich Gamma 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
		}
		return this.useExec().then((useExec) => {
			let cc: TValueCallback<SuccessData>;
			let ee: ErrorCallback;
			let pp: TProgressCallback<TProgressData>;
			let result = new PPromise<any, TProgressData>((c, e, p) => {
				cc = c;
				ee = e;
				pp = p;
			});

			if (useExec) {
				let cmd: string = this.cmd;
				if (this.args) {
					cmd = cmd + ' ' + this.args.join(' ');
				}
				this.childProcess = exec(cmd, this.options, (error, stdout, stderr) => {
					this.childProcess = null;
J
Johannes Rieken 已提交
190
					let err: any = error;
E
Erich Gamma 已提交
191 192 193 194 195 196
					// This is tricky since executing a command shell reports error back in case the executed command return an
					// error or the command didn't exist at all. So we can't blindly treat an error as a failed command. So we
					// always parse the output and report success unless the job got killed.
					if (err && err.killed) {
						ee({ killed: this.terminateRequested, stdout: stdout.toString(), stderr: stderr.toString() });
					} else {
J
Joao Moreno 已提交
197
						this.handleExec(cc, pp, error, stdout as any, stderr as any);
E
Erich Gamma 已提交
198 199 200 201 202 203 204 205 206 207 208
					}
				});
			} else {
				let childProcess: ChildProcess = null;
				let closeHandler = (data: any) => {
					this.childProcess = null;
					this.childProcessPromise = null;
					this.handleClose(data, cc, pp, ee);
					let result: SuccessData = {
						terminated: this.terminateRequested
					};
J
Johannes Rieken 已提交
209
					if (Types.isNumber(data)) {
E
Erich Gamma 已提交
210 211 212
						result.cmdCode = <number>data;
					}
					cc(result);
B
Benjamin Pasero 已提交
213
				};
E
Erich Gamma 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
				if (this.shell && Platform.isWindows) {
					let options: any = Objects.clone(this.options);
					options.windowsVerbatimArguments = true;
					options.detached = false;
					let quotedCommand: boolean = false;
					let quotedArg: boolean = false;
					let commandLine: string[] = [];
					let quoted = this.ensureQuotes(this.cmd);
					commandLine.push(quoted.value);
					quotedCommand = quoted.quoted;
					if (this.args) {
						this.args.forEach((elem) => {
							quoted = this.ensureQuotes(elem);
							commandLine.push(quoted.value);
							quotedArg = quotedArg && quoted.quoted;
						});
					}
					let args: string[] = [
						'/s',
						'/c',
					];
					if (quotedCommand) {
						if (quotedArg) {
B
Benjamin Pasero 已提交
237
							args.push('"' + commandLine.join(' ') + '"');
E
Erich Gamma 已提交
238 239 240 241 242 243 244 245
						} else if (commandLine.length > 1) {
							args.push('"' + commandLine[0] + '"' + ' ' + commandLine.slice(1).join(' '));
						} else {
							args.push('"' + commandLine[0] + '"');
						}
					} else {
						args.push(commandLine.join(' '));
					}
246
					childProcess = spawn(getWindowsShell(), args, options);
E
Erich Gamma 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
				} else {
					if (this.cmd) {
						childProcess = spawn(this.cmd, this.args, this.options);
					} else if (this.module) {
						this.childProcessPromise = new TPromise<ChildProcess>((c, e, p) => {
							fork(this.module, this.args, <ForkOptions>this.options, (error: any, childProcess: ChildProcess) => {
								if (error) {
									e(error);
									ee({ terminated: this.terminateRequested, error: error });
									return;
								}
								this.childProcess = childProcess;
								this.childProcess.on('close', closeHandler);
								this.handleSpawn(childProcess, cc, pp, ee, false);
								c(childProcess);
							});
						});
					}
				}
				if (childProcess) {
					this.childProcess = childProcess;
					this.childProcessPromise = TPromise.as(childProcess);
J
Johannes Rieken 已提交
269
					childProcess.on('error', (error: Error) => {
E
Erich Gamma 已提交
270
						this.childProcess = null;
J
Johannes Rieken 已提交
271
						ee({ terminated: this.terminateRequested, error: error });
E
Erich Gamma 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
					});
					if (childProcess.pid) {
						this.childProcess.on('close', closeHandler);
						this.handleSpawn(childProcess, cc, pp, ee, true);
					}
				}
			}
			return result;
		});
	}

	protected abstract handleExec(cc: TValueCallback<SuccessData>, pp: TProgressCallback<TProgressData>, error: Error, stdout: Buffer, stderr: Buffer): void;
	protected abstract handleSpawn(childProcess: ChildProcess, cc: TValueCallback<SuccessData>, pp: TProgressCallback<TProgressData>, ee: ErrorCallback, sync: boolean): void;

	protected handleClose(data: any, cc: TValueCallback<SuccessData>, pp: TProgressCallback<TProgressData>, ee: ErrorCallback): void {
		// Default is to do nothing.
	}

	private static regexp = /^[^"].* .*[^"]/;
	private ensureQuotes(value: string) {
J
Johannes Rieken 已提交
292 293 294 295 296 297 298 299 300 301 302
		if (AbstractProcess.regexp.test(value)) {
			return {
				value: '"' + value + '"', //`"${value}"`,
				quoted: true
			};
		} else {
			return {
				value: value,
				quoted: value.length > 0 && value[0] === '"' && value[value.length - 1] === '"'
			};
		}
E
Erich Gamma 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
	}

	public isRunning(): boolean {
		return this.childProcessPromise !== null;
	}

	public get pid(): TPromise<number> {
		return this.childProcessPromise.then(childProcess => childProcess.pid, err => -1);
	}

	public terminate(): TPromise<TerminateResponse> {
		if (!this.childProcessPromise) {
			return TPromise.as<TerminateResponse>({ success: true });
		}
		return this.childProcessPromise.then((childProcess) => {
			this.terminateRequested = true;
			let result = terminateProcess(childProcess, this.options.cwd);
			if (result.success) {
				this.childProcess = null;
			}
			return result;
		}, (err) => {
325
			return { success: true };
E
Erich Gamma 已提交
326 327 328 329 330 331 332 333
		});
	}

	private useExec(): TPromise<boolean> {
		return new TPromise<boolean>((c, e, p) => {
			if (!this.shell || !Platform.isWindows) {
				c(false);
			}
334
			let cmdShell = spawn(getWindowsShell(), ['/s', '/c']);
J
Johannes Rieken 已提交
335
			cmdShell.on('error', (error: Error) => {
E
Erich Gamma 已提交
336 337
				c(true);
			});
J
Johannes Rieken 已提交
338
			cmdShell.on('exit', (data: any) => {
E
Erich Gamma 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
				c(false);
			});
		});
	}
}

export class LineProcess extends AbstractProcess<LineData> {

	private stdoutLineDecoder: LineDecoder;
	private stderrLineDecoder: LineDecoder;

	public constructor(executable: Executable);
	public constructor(cmd: string, args: string[], shell: boolean, options: CommandOptions);
	public constructor(module: string, args: string[], options: ForkOptions);
	public constructor(arg1: string | Executable, arg2?: string[], arg3?: boolean | ForkOptions, arg4?: CommandOptions) {
		super(<any>arg1, arg2, <any>arg3, arg4);
	}

	protected handleExec(cc: TValueCallback<SuccessData>, pp: TProgressCallback<LineData>, error: Error, stdout: Buffer, stderr: Buffer) {
J
Johannes Rieken 已提交
358
		[stdout, stderr].forEach((buffer: Buffer, index: number) => {
E
Erich Gamma 已提交
359 360 361
			let lineDecoder = new LineDecoder();
			let lines = lineDecoder.write(buffer);
			lines.forEach((line) => {
J
Johannes Rieken 已提交
362
				pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr });
E
Erich Gamma 已提交
363 364 365
			});
			let line = lineDecoder.end();
			if (line) {
J
Johannes Rieken 已提交
366
				pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr });
E
Erich Gamma 已提交
367 368 369 370 371 372 373 374
			}
		});
		cc({ terminated: this.terminateRequested, error: error });
	}

	protected handleSpawn(childProcess: ChildProcess, cc: TValueCallback<SuccessData>, pp: TProgressCallback<LineData>, ee: ErrorCallback, sync: boolean): void {
		this.stdoutLineDecoder = new LineDecoder();
		this.stderrLineDecoder = new LineDecoder();
J
Johannes Rieken 已提交
375
		childProcess.stdout.on('data', (data: Buffer) => {
E
Erich Gamma 已提交
376 377 378
			let lines = this.stdoutLineDecoder.write(data);
			lines.forEach(line => pp({ line: line, source: Source.stdout }));
		});
J
Johannes Rieken 已提交
379
		childProcess.stderr.on('data', (data: Buffer) => {
E
Erich Gamma 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
			let lines = this.stderrLineDecoder.write(data);
			lines.forEach(line => pp({ line: line, source: Source.stderr }));
		});
	}

	protected handleClose(data: any, cc: TValueCallback<SuccessData>, pp: TProgressCallback<LineData>, ee: ErrorCallback): void {
		[this.stdoutLineDecoder.end(), this.stderrLineDecoder.end()].forEach((line, index) => {
			if (line) {
				pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr });
			}
		});
	}
}

export class BufferProcess extends AbstractProcess<BufferData> {

	public constructor(executable: Executable);
	public constructor(cmd: string, args: string[], shell: boolean, options: CommandOptions);
	public constructor(module: string, args: string[], options: ForkOptions);
	public constructor(arg1: string | Executable, arg2?: string[], arg3?: boolean | ForkOptions, arg4?: CommandOptions) {
		super(<any>arg1, arg2, <any>arg3, arg4);
	}

	protected handleExec(cc: TValueCallback<SuccessData>, pp: TProgressCallback<BufferData>, error: Error, stdout: Buffer, stderr: Buffer): void {
		pp({ data: stdout, source: Source.stdout });
		pp({ data: stderr, source: Source.stderr });
		cc({ terminated: this.terminateRequested, error: error });
	}

	protected handleSpawn(childProcess: ChildProcess, cc: TValueCallback<SuccessData>, pp: TProgressCallback<BufferData>, ee: ErrorCallback, sync: boolean): void {
J
Johannes Rieken 已提交
410
		childProcess.stdout.on('data', (data: Buffer) => {
E
Erich Gamma 已提交
411 412
			pp({ data: data, source: Source.stdout });
		});
J
Johannes Rieken 已提交
413
		childProcess.stderr.on('data', (data: Buffer) => {
E
Erich Gamma 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
			pp({ data: data, source: Source.stderr });
		});
	}
}

export class StreamProcess extends AbstractProcess<StreamData> {

	public constructor(executable: Executable);
	public constructor(cmd: string, args: string[], shell: boolean, options: CommandOptions);
	public constructor(module: string, args: string[], options: ForkOptions);
	public constructor(arg1: string | Executable, arg2?: string[], arg3?: boolean | ForkOptions, arg4?: CommandOptions) {
		super(<any>arg1, arg2, <any>arg3, arg4);
	}

	protected handleExec(cc: TValueCallback<SuccessData>, pp: TProgressCallback<StreamData>, error: Error, stdout: Buffer, stderr: Buffer): void {
		let stdoutStream = new PassThrough();
		stdoutStream.end(stdout);
		let stderrStream = new PassThrough();
		stderrStream.end(stderr);
		pp({ stdin: null, stdout: stdoutStream, stderr: stderrStream });
		cc({ terminated: this.terminateRequested, error: error });
	}

	protected handleSpawn(childProcess: ChildProcess, cc: TValueCallback<SuccessData>, pp: TProgressCallback<StreamData>, ee: ErrorCallback, sync: boolean): void {
		if (sync) {
			process.nextTick(() => {
				pp({ stdin: childProcess.stdin, stdout: childProcess.stdout, stderr: childProcess.stderr });
			});
		} else {
			pp({ stdin: childProcess.stdin, stdout: childProcess.stdout, stderr: childProcess.stderr });
		}
	}
B
Benjamin Pasero 已提交
446 447
}

B
Benjamin Pasero 已提交
448
export interface IQueuedSender {
B
Benjamin Pasero 已提交
449 450 451
	send: (msg: any) => void;
}

B
Benjamin Pasero 已提交
452 453 454 455 456 457
// Wrapper around process.send() that will queue any messages if the internal node.js
// queue is filled with messages and only continue sending messages when the internal
// queue is free again to consume messages.
// On Windows we always wait for the send() method to return before sending the next message
// to workaround https://github.com/nodejs/node/issues/7657 (IPC can freeze process)
export function createQueuedSender(childProcess: ChildProcess | NodeJS.Process): IQueuedSender {
458
	let msgQueue: string[] = [];
B
Benjamin Pasero 已提交
459
	let useQueue = false;
B
Benjamin Pasero 已提交
460 461

	const send = function (msg: any): void {
B
Benjamin Pasero 已提交
462 463
		if (useQueue) {
			msgQueue.push(msg); // add to the queue if the process cannot handle more messages
B
Benjamin Pasero 已提交
464 465 466
			return;
		}

467
		let result = childProcess.send(msg, (error: Error) => {
B
Benjamin Pasero 已提交
468 469 470 471
			if (error) {
				console.error(error); // unlikely to happen, best we can do is log this error
			}

B
Benjamin Pasero 已提交
472
			useQueue = false; // we are good again to send directly without queue
B
Benjamin Pasero 已提交
473

B
Benjamin Pasero 已提交
474 475 476 477 478
			// now send all the messages that we have in our queue and did not send yet
			if (msgQueue.length > 0) {
				const msgQueueCopy = msgQueue.slice(0);
				msgQueue = [];
				msgQueueCopy.forEach(entry => send(entry));
B
Benjamin Pasero 已提交
479 480 481
			}
		});

B
Benjamin Pasero 已提交
482 483
		if (!result || Platform.isWindows /* workaround https://github.com/nodejs/node/issues/7657 */) {
			useQueue = true;
B
Benjamin Pasero 已提交
484 485 486 487
		}
	};

	return { send };
488
}