main.ts 12.3 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

8
import { app, dialog } from 'electron';
J
Joao Moreno 已提交
9 10
import { assign } from 'vs/base/common/objects';
import * as platform from 'vs/base/common/platform';
11
import product from 'vs/platform/node/product';
12
import * as path from 'path';
J
Joao Moreno 已提交
13
import { parseMainProcessArgv } from 'vs/platform/environment/node/argv';
14
import { mkdirp, readdir, rimraf } from 'vs/base/node/pfs';
B
Benjamin Pasero 已提交
15
import { validatePaths } from 'vs/code/node/paths';
16
import { LifecycleService, ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';
J
Joao Moreno 已提交
17 18
import { Server, serve, connect } from 'vs/base/parts/ipc/node/ipc.net';
import { TPromise } from 'vs/base/common/winjs.base';
B
Benjamin Pasero 已提交
19
import { ILaunchChannel, LaunchChannelClient } from 'vs/code/electron-main/launch';
J
Joao Moreno 已提交
20 21 22 23
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
J
Joao Moreno 已提交
24
import { ILogService, ConsoleLogMainService, MultiplexLogService } from 'vs/platform/log/common/log';
B
Benjamin Pasero 已提交
25 26
import { StateService } from 'vs/platform/state/node/stateService';
import { IStateService } from 'vs/platform/state/common/state';
D
Daniel Imms 已提交
27
import { IBackupMainService } from 'vs/platform/backup/common/backup';
D
Daniel Imms 已提交
28
import { BackupMainService } from 'vs/platform/backup/electron-main/backupMainService';
J
Joao Moreno 已提交
29
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
J
Joao Moreno 已提交
30 31
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
32
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
J
Joao Moreno 已提交
33
import { IRequestService } from 'vs/platform/request/node/request';
J
Joao Moreno 已提交
34
import { RequestService } from 'vs/platform/request/electron-main/requestService';
J
Joao Moreno 已提交
35
import { IURLService } from 'vs/platform/url/common/url';
J
Joao Moreno 已提交
36
import { URLService } from 'vs/platform/url/electron-main/urlService';
B
Benjamin Pasero 已提交
37
import * as fs from 'original-fs';
38 39
import { CodeApplication } from 'vs/code/electron-main/app';
import { HistoryMainService } from 'vs/platform/history/electron-main/historyMainService';
B
Benjamin Pasero 已提交
40
import { IHistoryMainService } from 'vs/platform/history/common/history';
41
import { WorkspacesMainService } from 'vs/platform/workspaces/electron-main/workspacesMainService';
B
Benjamin Pasero 已提交
42
import { IWorkspacesMainService } from 'vs/platform/workspaces/common/workspaces';
43 44
import { localize } from 'vs/nls';
import { mnemonicButtonLabel } from 'vs/base/common/labels';
45
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
B
Benjamin Pasero 已提交
46
import { printDiagnostics } from 'vs/code/electron-main/diagnostics';
47
import { BufferLogService } from 'vs/platform/log/common/bufferLog';
B
Benjamin Pasero 已提交
48

49
function createServices(args: ParsedArgs, bufferLogService: BufferLogService): IInstantiationService {
B
Benjamin Pasero 已提交
50 51
	const services = new ServiceCollection();

52
	const environmentService = new EnvironmentService(args, process.execPath);
53
	const consoleLogService = new ConsoleLogMainService(environmentService);
54
	const logService = new MultiplexLogService([consoleLogService, bufferLogService]);
55 56

	process.once('exit', () => logService.dispose());
57

J
Joao Moreno 已提交
58
	// Eventually cleanup
59
	setTimeout(() => cleanupOlderLogs(environmentService).then(null, err => console.error(err)), 10000);
J
Joao Moreno 已提交
60

61 62
	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
63
	services.set(IWorkspacesMainService, new SyncDescriptor(WorkspacesMainService));
64
	services.set(IHistoryMainService, new SyncDescriptor(HistoryMainService));
B
Benjamin Pasero 已提交
65
	services.set(ILifecycleService, new SyncDescriptor(LifecycleService));
B
Benjamin Pasero 已提交
66
	services.set(IStateService, new SyncDescriptor(StateService));
B
Benjamin Pasero 已提交
67 68
	services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
	services.set(IRequestService, new SyncDescriptor(RequestService));
J
Joao Moreno 已提交
69
	services.set(IURLService, new SyncDescriptor(URLService, args['open-url'] ? args._urls : []));
B
Benjamin Pasero 已提交
70 71 72 73 74
	services.set(IBackupMainService, new SyncDescriptor(BackupMainService));

	return new InstantiationService(services, true);
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88
/**
 * Cleans up older logs, while keeping the 10 most recent ones.
*/
async function cleanupOlderLogs(environmentService: EnvironmentService): TPromise<void> {
	const currentLog = path.basename(environmentService.logsPath);
	const logsRoot = path.dirname(environmentService.logsPath);
	const children = await readdir(logsRoot);
	const allSessions = children.filter(name => /^\d{8}T\d{6}$/.test(name));
	const oldSessions = allSessions.sort().filter((d, i) => d !== currentLog);
	const toDelete = oldSessions.slice(0, Math.max(0, oldSessions.length - 9));

	await TPromise.join(toDelete.map(name => rimraf(path.join(logsRoot, name))));
}

B
Benjamin Pasero 已提交
89 90 91 92
function createPaths(environmentService: IEnvironmentService): TPromise<any> {
	const paths = [
		environmentService.appSettingsHome,
		environmentService.extensionsPath,
J
Joao Moreno 已提交
93 94
		environmentService.nodeCachedDataDir,
		environmentService.logsPath
B
Benjamin Pasero 已提交
95
	];
B
Benjamin Pasero 已提交
96

B
Benjamin Pasero 已提交
97 98 99
	return TPromise.join(paths.map(p => p && mkdirp(p))) as TPromise<any>;
}

J
Joao Moreno 已提交
100 101 102 103
class ExpectedError extends Error {
	public readonly isExpected = true;
}

J
Joao Moreno 已提交
104 105
function setupIPC(accessor: ServicesAccessor): TPromise<Server> {
	const logService = accessor.get(ILogService);
106
	const environmentService = accessor.get(IEnvironmentService);
J
Joao Moreno 已提交
107

B
Benjamin Pasero 已提交
108
	function allowSetForegroundWindow(service: LaunchChannelClient): TPromise<void> {
109
		let promise = TPromise.wrap<void>(void 0);
B
Benjamin Pasero 已提交
110 111 112
		if (platform.isWindows) {
			promise = service.getMainProcessId()
				.then(processId => {
J
Joao Moreno 已提交
113
					logService.trace('Sending some foreground love to the running instance:', processId);
J
Johannes Rieken 已提交
114

B
Benjamin Pasero 已提交
115 116 117 118 119 120 121 122 123 124 125 126
					try {
						const { allowSetForegroundWindow } = <any>require.__$__nodeRequire('windows-foreground-love');
						allowSetForegroundWindow(processId);
					} catch (e) {
						// noop
					}
				});
		}

		return promise;
	}

E
Erich Gamma 已提交
127
	function setup(retry: boolean): TPromise<Server> {
128
		return serve(environmentService.mainIPCHandle).then(server => {
129

130 131
			// Print --status usage info
			if (environmentService.args.status) {
B
Benjamin Pasero 已提交
132
				logService.warn('Warning: The --status argument can only be used if Code is already running. Please run it again after Code has started.');
B
Benjamin Pasero 已提交
133 134 135 136 137 138
				throw new ExpectedError('Terminating...');
			}

			// dock might be hidden at this case due to a retry
			if (platform.isMacintosh) {
				app.dock.show();
B
Benjamin Pasero 已提交
139 140
			}

141 142 143 144
			// Set the VSCODE_PID variable here when we are sure we are the first
			// instance to startup. Otherwise we would wrongly overwrite the PID
			process.env['VSCODE_PID'] = String(process.pid);

145 146
			return server;
		}, err => {
E
Erich Gamma 已提交
147
			if (err.code !== 'EADDRINUSE') {
148
				return TPromise.wrapError<Server>(err);
E
Erich Gamma 已提交
149 150
			}

151 152 153 154
			// Since we are the second instance, we do not want to show the dock
			if (platform.isMacintosh) {
				app.dock.hide();
			}
B
Benjamin Pasero 已提交
155

156
			// there's a running instance, let's connect to it
157
			return connect(environmentService.mainIPCHandle, 'main').then(
158
				client => {
J
Joao Moreno 已提交
159

B
Benjamin Pasero 已提交
160
					// Tests from CLI require to be the only instance currently
J
Joao Moreno 已提交
161
					if (environmentService.extensionTestsPath && !environmentService.debugExtensionHost.break) {
J
Joao Moreno 已提交
162
						const msg = 'Running extension tests from the command line is currently only supported if no other instance of Code is running.';
B
Benjamin Pasero 已提交
163
						logService.error(msg);
J
Joao Moreno 已提交
164
						client.dispose();
B
Benjamin Pasero 已提交
165

166
						return TPromise.wrapError<Server>(new Error(msg));
J
Joao Moreno 已提交
167 168
					}

169
					// Show a warning dialog after some timeout if it takes long to talk to the other instance
B
Benjamin Pasero 已提交
170 171
					// Skip this if we are running with --wait where it is expected that we wait for a while.
					// Also skip when gathering diagnostics (--status) which can take a longer time.
172
					let startupWarningDialogHandle: number;
B
Benjamin Pasero 已提交
173
					if (!environmentService.wait && !environmentService.status) {
174 175 176 177 178 179 180 181
						startupWarningDialogHandle = setTimeout(() => {
							showStartupWarningDialog(
								localize('secondInstanceNoResponse', "Another instance of {0} is running but not responding", product.nameShort),
								localize('secondInstanceNoResponseDetail', "Please close all other instances and try again.")
							);
						}, 10000);
					}

J
Joao Moreno 已提交
182 183
					const channel = client.getChannel<ILaunchChannel>('launch');
					const service = new LaunchChannelClient(channel);
E
Erich Gamma 已提交
184

B
Benjamin Pasero 已提交
185
					// Process Info
186
					if (environmentService.args.status) {
B
Benjamin Pasero 已提交
187
						return service.getMainProcessInfo().then(info => {
B
Benjamin Pasero 已提交
188
							return printDiagnostics(info).then(() => TPromise.wrapError(new ExpectedError()));
B
Benjamin Pasero 已提交
189 190 191
						});
					}

J
Joao Moreno 已提交
192
					logService.trace('Sending env to running instance...');
B
Benjamin Pasero 已提交
193

B
Benjamin Pasero 已提交
194
					return allowSetForegroundWindow(service)
195
						.then(() => service.start(environmentService.args, process.env))
E
Erich Gamma 已提交
196
						.then(() => client.dispose())
197 198 199 200 201 202 203 204 205
						.then(() => {

							// Now that we started, make sure the warning dialog is prevented
							if (startupWarningDialogHandle) {
								clearTimeout(startupWarningDialogHandle);
							}

							return TPromise.wrapError(new ExpectedError('Sent env to running instance. Terminating...'));
						});
E
Erich Gamma 已提交
206 207 208
				},
				err => {
					if (!retry || platform.isWindows || err.code !== 'ECONNREFUSED') {
209 210 211 212 213 214 215
						if (err.code === 'EPERM') {
							showStartupWarningDialog(
								localize('secondInstanceAdmin', "A second instance of {0} is already running as administrator.", product.nameShort),
								localize('secondInstanceAdminDetail', "Please close the other instance and try again.")
							);
						}

216
						return TPromise.wrapError<Server>(err);
E
Erich Gamma 已提交
217 218 219 220
					}

					// it happens on Linux and OS X that the pipe is left behind
					// let's delete it, since we can't connect to it
S
Shreya Dahal 已提交
221
					// and then retry the whole thing
E
Erich Gamma 已提交
222
					try {
223
						fs.unlinkSync(environmentService.mainIPCHandle);
E
Erich Gamma 已提交
224
					} catch (e) {
J
Joao Moreno 已提交
225
						logService.warn('Could not delete obsolete instance handle', e);
226
						return TPromise.wrapError<Server>(e);
E
Erich Gamma 已提交
227 228 229 230 231 232 233 234 235 236 237
					}

					return setup(false);
				}
			);
		});
	}

	return setup(true);
}

238
function showStartupWarningDialog(message: string, detail: string): void {
239
	dialog.showMessageBox({
240 241 242 243 244 245 246 247 248
		title: product.nameLong,
		type: 'warning',
		buttons: [mnemonicButtonLabel(localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close"))],
		message,
		detail,
		noLink: true
	});
}

B
Benjamin Pasero 已提交
249
function quit(accessor: ServicesAccessor, reason?: ExpectedError | Error): void {
250 251
	const logService = accessor.get(ILogService);
	const lifecycleService = accessor.get(ILifecycleService);
252

253
	let exitCode = 0;
J
Joao Moreno 已提交
254

B
Benjamin Pasero 已提交
255 256
	if (reason) {
		if ((reason as ExpectedError).isExpected) {
B
Benjamin Pasero 已提交
257 258 259
			if (reason.message) {
				logService.trace(reason.message);
			}
260
		} else {
J
Joao Moreno 已提交
261 262
			exitCode = 1; // signal error to the outside

B
Benjamin Pasero 已提交
263
			if (reason.stack) {
B
Benjamin Pasero 已提交
264
				logService.error(reason.stack);
J
Joao Moreno 已提交
265
			} else {
B
Benjamin Pasero 已提交
266
				logService.error(`Startup error: ${reason.toString()}`);
J
Joao Moreno 已提交
267
			}
268
		}
J
Joao Moreno 已提交
269 270
	}

271
	lifecycleService.kill(exitCode);
J
Joao Moreno 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
}

function main() {
	let args: ParsedArgs;

	try {
		args = parseMainProcessArgv(process.argv);
		args = validatePaths(args);
	} catch (err) {
		console.error(err.message);
		app.exit(1);

		return;
	}

287 288 289 290 291 292
	// We need to buffer the spdlog logs until we are sure
	// we are the only instance running, otherwise we'll have concurrent
	// log file access on Windows
	// https://github.com/Microsoft/vscode/issues/41218
	const bufferLogService = new BufferLogService();
	const instantiationService = createServices(args, bufferLogService);
J
Joao Moreno 已提交
293 294 295 296 297 298 299

	return instantiationService.invokeFunction(accessor => {

		// Patch `process.env` with the instance's environment
		const environmentService = accessor.get(IEnvironmentService);
		const instanceEnv: typeof process.env = {
			VSCODE_IPC_HOOK: environmentService.mainIPCHandle,
J
Joao Moreno 已提交
300 301
			VSCODE_NLS_CONFIG: process.env['VSCODE_NLS_CONFIG'],
			VSCODE_LOGS: process.env['VSCODE_LOGS']
J
Joao Moreno 已提交
302 303 304 305 306 307
		};
		assign(process.env, instanceEnv);

		// Startup
		return instantiationService.invokeFunction(a => createPaths(a.get(IEnvironmentService)))
			.then(() => instantiationService.invokeFunction(setupIPC))
308 309 310 311
			.then(mainIpcServer => {
				bufferLogService.logger = createSpdLogService('main', environmentService);
				return instantiationService.createInstance(CodeApplication, mainIpcServer, instanceEnv).startup();
			});
J
Joao Moreno 已提交
312 313 314
	}).done(null, err => instantiationService.invokeFunction(quit, err));
}

S
Shreya Dahal 已提交
315
main();