extensionService.ts 17.6 KB
Newer Older
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import * as nls from 'vs/nls';
A
Alex Dima 已提交
8
import * as errors from 'vs/base/common/errors';
9 10 11 12 13
import Severity from 'vs/base/common/severity';
import { TPromise } from 'vs/base/common/winjs.base';
import pkg from 'vs/platform/node/package';
import * as path from 'path';
import URI from 'vs/base/common/uri';
A
Alex Dima 已提交
14
import { ExtensionDescriptionRegistry } from "vs/workbench/services/extensions/node/extensionDescriptionRegistry";
A
Alex Dima 已提交
15
import { IMessage, IExtensionDescription, IExtensionsStatus, IExtensionService, ExtensionPointContribution } from 'vs/platform/extensions/common/extensions';
16 17
import { IExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionManagement';
import { areSameExtensions, getGloballyDisabledExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
A
Alex Dima 已提交
18
import { ExtensionsRegistry, ExtensionPoint, IExtensionPointUser, ExtensionMessageCollector, IExtensionPoint } from 'vs/platform/extensions/common/extensionsRegistry';
19
import { ExtensionScanner, ILog } from 'vs/workbench/services/extensions/electron-browser/extensionPoints';
20
import { IMessageService } from 'vs/platform/message/common/message';
21 22
import { ProxyIdentifier } from 'vs/workbench/services/thread/common/threadService';
import { ExtHostContext, ExtHostExtensionServiceShape, IExtHostContext, MainContext } from "vs/workbench/api/node/extHost.protocol";
23 24 25 26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IInstantiationService } from "vs/platform/instantiation/common/instantiation";
27
import { ExtensionHostProcessWorker } from "vs/workbench/services/extensions/electron-browser/extensionHost";
28
import { MainThreadService } from "vs/workbench/services/thread/electron-browser/threadService";
29
import { Barrier } from "vs/workbench/services/extensions/node/barrier";
30 31
import { IMessagePassingProtocol } from "vs/base/parts/ipc/common/ipc";
import { ExtHostCustomersRegistry } from "vs/workbench/api/electron-browser/extHostCustomers";
32 33
import { IWindowService } from "vs/platform/windows/common/windows";
import { Action } from "vs/base/common/actions";
A
Alex Dima 已提交
34
import { IDisposable } from "vs/base/common/lifecycle";
35 36 37

const SystemExtensionsRoot = path.normalize(path.join(URI.parse(require.toUrl('')).fsPath, '..', 'extensions'));

38
function messageWithSource(msg: IMessage): string {
39 40 41 42 43 44 45 46
	return messageWithSource2(msg.source, msg.message);
}

function messageWithSource2(source: string, message: string): string {
	if (source) {
		return `[${source}]: ${message}`;
	}
	return message;
47 48
}

49 50 51
const hasOwnProperty = Object.hasOwnProperty;
const NO_OP_VOID_PROMISE = TPromise.as<void>(void 0);

52
export class ExtensionService implements IExtensionService {
53
	public _serviceBrand: any;
54

55 56
	private _registry: ExtensionDescriptionRegistry;
	private readonly _barrier: Barrier;
57 58
	private readonly _isDev: boolean;
	private readonly _extensionsStatus: { [id: string]: IExtensionsStatus };
A
Alex Dima 已提交
59 60 61 62 63
	private _allRequestedActivateEvents: { [activationEvent: string]: boolean; };


	// --- Members used per extension host process

64
	/**
65
	 * A map of already activated events to speed things up if the same activation event is triggered multiple times.
66
	 */
A
Alex Dima 已提交
67 68 69 70 71 72 73 74
	private _extensionHostProcessFinishedActivateEvents: { [activationEvent: string]: boolean; };
	private _extensionHostProcessWorker: ExtensionHostProcessWorker;
	private _extensionHostProcessThreadService: MainThreadService;
	private _extensionHostProcessCustomers: IDisposable[];
	/**
	 * winjs believes a proxy is a promise because it has a `then` method, so wrap the result in an object.
	 */
	private _extensionHostProcessProxy: TPromise<{ value: ExtHostExtensionServiceShape; }>;
75

76 77 78
	constructor(
		@IInstantiationService private readonly _instantiationService: IInstantiationService,
		@IMessageService private readonly _messageService: IMessageService,
79
		@IEnvironmentService private readonly _environmentService: IEnvironmentService,
80
		@ITelemetryService private readonly _telemetryService: ITelemetryService,
81 82
		@IExtensionEnablementService private readonly _extensionEnablementService: IExtensionEnablementService,
		@IStorageService private readonly _storageService: IStorageService,
83
		@IWindowService private readonly _windowService: IWindowService
84
	) {
85 86
		this._registry = null;
		this._barrier = new Barrier();
87
		this._isDev = !this._environmentService.isBuilt || this._environmentService.isExtensionDevelopment;
88
		this._extensionsStatus = {};
A
Alex Dima 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
		this._allRequestedActivateEvents = Object.create(null);

		this._extensionHostProcessFinishedActivateEvents = Object.create(null);
		this._extensionHostProcessWorker = null;
		this._extensionHostProcessThreadService = null;
		this._extensionHostProcessCustomers = [];
		this._extensionHostProcessProxy = null;

		this._startExtensionHostProcess([]);
		this._scanAndHandleExtensions();
	}

	private _stopExtensionHostProcess(): void {
		this._extensionHostProcessFinishedActivateEvents = Object.create(null);
		if (this._extensionHostProcessWorker) {
			this._extensionHostProcessWorker.dispose();
			this._extensionHostProcessWorker = null;
		}
		if (this._extensionHostProcessThreadService) {
108
			this._extensionHostProcessThreadService.dispose();
A
Alex Dima 已提交
109 110 111 112 113 114 115 116
			this._extensionHostProcessThreadService = null;
		}
		for (let i = 0, len = this._extensionHostProcessCustomers.length; i < len; i++) {
			const customer = this._extensionHostProcessCustomers[i];
			try {
				customer.dispose();
			} catch (err) {
				errors.onUnexpectedError(err);
117
			}
A
Alex Dima 已提交
118 119 120 121 122 123 124 125 126 127 128
		}
		this._extensionHostProcessCustomers = [];
		this._extensionHostProcessProxy = null;
	}

	private _startExtensionHostProcess(initialActivationEvents: string[]): void {
		this._stopExtensionHostProcess();

		this._extensionHostProcessWorker = this._instantiationService.createInstance(ExtensionHostProcessWorker, this);
		this._extensionHostProcessWorker.onCrashed(([code, signal]) => this._onExtensionHostCrashed(code, signal));
		this._extensionHostProcessProxy = this._extensionHostProcessWorker.start().then(
129
			(protocol) => {
A
Alex Dima 已提交
130
				return { value: this._createExtensionHostCustomers(protocol) };
131 132 133 134
			},
			(err) => {
				console.error('Error received from starting extension host');
				console.error(err);
A
Alex Dima 已提交
135
				return null;
136 137
			}
		);
A
Alex Dima 已提交
138 139 140 141
		this._extensionHostProcessProxy.then(() => {
			initialActivationEvents.forEach((activationEvent) => this.activateByEvent(activationEvent));
		});
	}
142

A
Alex Dima 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
	private _onExtensionHostCrashed(code: number, signal: string): void {
		const openDevTools = new Action('openDevTools', nls.localize('devTools', "Developer Tools"), '', true, (): TPromise<boolean> => {
			return this._windowService.openDevTools().then(() => false);
		});

		const restart = new Action('restart', nls.localize('restart', "Restart Extension Host"), '', true, (): TPromise<boolean> => {
			this._startExtensionHostProcess(Object.keys(this._allRequestedActivateEvents));
			return TPromise.as(true);
		});

		console.error('Extension host terminated unexpectedly. Code: ', code, ' Signal: ', signal);
		this._stopExtensionHostProcess();

		let message = nls.localize('extensionHostProcess.crash', "Extension host terminated unexpectedly.");
		if (code === 87) {
			message = nls.localize('extensionHostProcess.unresponsiveCrash', "Extension host terminated because it was not responsive.");
		}
		this._messageService.show(Severity.Error, {
			message: message,
			actions: [
				openDevTools,
				restart
			]
		});
167 168
	}

A
Alex Dima 已提交
169
	private _createExtensionHostCustomers(protocol: IMessagePassingProtocol): ExtHostExtensionServiceShape {
170

A
Alex Dima 已提交
171 172
		this._extensionHostProcessThreadService = this._instantiationService.createInstance(MainThreadService, protocol);
		const extHostContext: IExtHostContext = this._extensionHostProcessThreadService;
173

174 175 176 177
		// Named customers
		const namedCustomers = ExtHostCustomersRegistry.getNamedCustomers();
		for (let i = 0, len = namedCustomers.length; i < len; i++) {
			const [id, ctor] = namedCustomers[i];
A
Alex Dima 已提交
178 179 180
			const instance = this._instantiationService.createInstance(ctor, extHostContext);
			this._extensionHostProcessCustomers.push(instance);
			this._extensionHostProcessThreadService.set(id, instance);
181
		}
182

183 184 185 186
		// Customers
		const customers = ExtHostCustomersRegistry.getCustomers();
		for (let i = 0, len = customers.length; i < len; i++) {
			const ctor = customers[i];
A
Alex Dima 已提交
187 188
			const instance = this._instantiationService.createInstance(ctor, extHostContext);
			this._extensionHostProcessCustomers.push(instance);
189
		}
190

191 192
		// Check that no named customers are missing
		const expected: ProxyIdentifier<any>[] = Object.keys(MainContext).map((key) => MainContext[key]);
A
Alex Dima 已提交
193
		this._extensionHostProcessThreadService.assertRegistered(expected);
194

A
Alex Dima 已提交
195
		return this._extensionHostProcessThreadService.get(ExtHostContext.ExtHostExtensionService);
196
	}
197

198
	// ---- begin IExtensionService
199

200
	public activateByEvent(activationEvent: string): TPromise<void> {
201
		if (this._barrier.isOpen()) {
A
Alex Dima 已提交
202 203 204 205 206 207 208 209 210 211
			// Extensions have been scanned and interpreted

			if (!this._registry.containsActivationEvent(activationEvent)) {
				// There is no extension that is interested in this activation event
				return NO_OP_VOID_PROMISE;
			}

			// Record the fact that this activationEvent was requested (in case of a restart)
			this._allRequestedActivateEvents[activationEvent] = true;

212 213
			return this._activateByEvent(activationEvent);
		} else {
A
Alex Dima 已提交
214 215 216 217 218
			// Extensions have not been scanned yet.

			// Record the fact that this activationEvent was requested (in case of a restart)
			this._allRequestedActivateEvents[activationEvent] = true;

219 220 221
			return this._barrier.wait().then(() => this._activateByEvent(activationEvent));
		}
	}
222

223
	protected _activateByEvent(activationEvent: string): TPromise<void> {
A
Alex Dima 已提交
224
		if (this._extensionHostProcessFinishedActivateEvents[activationEvent]) {
225
			return NO_OP_VOID_PROMISE;
226
		}
A
Alex Dima 已提交
227
		return this._extensionHostProcessProxy.then((proxy) => {
228 229
			return proxy.value.$activateByEvent(activationEvent);
		}).then(() => {
A
Alex Dima 已提交
230
			this._extensionHostProcessFinishedActivateEvents[activationEvent] = true;
231
		});
232 233
	}

234 235 236
	public onReady(): TPromise<boolean> {
		return this._barrier.wait();
	}
237

A
Alex Dima 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
	public getExtensions(): TPromise<IExtensionDescription[]> {
		return this.onReady().then(() => {
			return this._registry.getAllExtensionDescriptions();
		});
	}

	public readExtensionPointContributions<T>(extPoint: IExtensionPoint<T>): TPromise<ExtensionPointContribution<T>[]> {
		return this.onReady().then(() => {
			let availableExtensions = this._registry.getAllExtensionDescriptions();

			let result: ExtensionPointContribution<T>[] = [], resultLen = 0;
			for (let i = 0, len = availableExtensions.length; i < len; i++) {
				let desc = availableExtensions[i];

				if (desc.contributes && hasOwnProperty.call(desc.contributes, extPoint.name)) {
					result[resultLen++] = new ExtensionPointContribution<T>(desc, desc.contributes[extPoint.name]);
				}
			}

			return result;
		});
	}

261 262 263 264
	public getExtensionsStatus(): { [id: string]: IExtensionsStatus } {
		return this._extensionsStatus;
	}

265
	// ---- end IExtensionService
266

267 268
	// --- impl

269
	private _scanAndHandleExtensions(): void {
270

271 272 273
		const log = new Logger((severity, source, message) => {
			this._logOrShowMessage(severity, this._isDev ? messageWithSource2(source, message) : message);
		});
274

275
		ExtensionService._scanInstalledExtensions(this._environmentService, log).then((installedExtensions) => {
276 277 278 279 280 281 282 283 284
			const disabledExtensions = [
				...getGloballyDisabledExtensions(this._extensionEnablementService, this._storageService, installedExtensions),
				...this._extensionEnablementService.getWorkspaceDisabledExtensions()
			];

			this._telemetryService.publicLog('extensionsScanned', {
				totalCount: installedExtensions.length,
				disabledCount: disabledExtensions.length
			});
285

286 287 288 289 290 291
			if (disabledExtensions.length === 0) {
				return installedExtensions;
			}
			return installedExtensions.filter(e => disabledExtensions.every(id => !areSameExtensions({ id }, e)));

		}).then((extensionDescriptions) => {
A
Alex Dima 已提交
292
			this._registry = new ExtensionDescriptionRegistry(extensionDescriptions);
293 294 295 296 297 298 299 300 301 302 303

			let availableExtensions = this._registry.getAllExtensionDescriptions();
			let extensionPoints = ExtensionsRegistry.getExtensionPoints();

			let messageHandler = (msg: IMessage) => this._handleExtensionPointMessage(msg);

			for (let i = 0, len = extensionPoints.length; i < len; i++) {
				ExtensionService._handleExtensionPoint(extensionPoints[i], availableExtensions, messageHandler);
			}

			this._barrier.open();
304 305 306
		});
	}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
	private _handleExtensionPointMessage(msg: IMessage) {

		if (!this._extensionsStatus[msg.source]) {
			this._extensionsStatus[msg.source] = { messages: [] };
		}
		this._extensionsStatus[msg.source].messages.push(msg);

		if (msg.source === this._environmentService.extensionDevelopmentPath) {
			// This message is about the extension currently being developed
			this._showMessageToUser(msg.type, messageWithSource(msg));
		} else {
			this._logMessageInConsole(msg.type, messageWithSource(msg));
		}

		if (!this._isDev && msg.extensionId) {
			const { type, extensionId, extensionPointId, message } = msg;
			this._telemetryService.publicLog('extensionsMessage', {
				type, extensionId, extensionPointId, message
			});
		}
	}

	private static _scanInstalledExtensions(environmentService: IEnvironmentService, log: ILog): TPromise<IExtensionDescription[]> {
330
		const version = pkg.version;
331 332 333
		const builtinExtensions = ExtensionScanner.scanExtensions(version, log, SystemExtensionsRoot, true);
		const userExtensions = environmentService.disableExtensions || !environmentService.extensionsPath ? TPromise.as([]) : ExtensionScanner.scanExtensions(version, log, environmentService.extensionsPath, false);
		const developedExtensions = environmentService.disableExtensions || !environmentService.isExtensionDevelopment ? TPromise.as([]) : ExtensionScanner.scanOneOrMultipleExtensions(version, log, environmentService.extensionDevelopmentPath, false);
334 335 336 337 338 339 340 341 342 343 344 345

		return TPromise.join([builtinExtensions, userExtensions, developedExtensions]).then<IExtensionDescription[]>((extensionDescriptions: IExtensionDescription[][]) => {
			const builtinExtensions = extensionDescriptions[0];
			const userExtensions = extensionDescriptions[1];
			const developedExtensions = extensionDescriptions[2];

			let result: { [extensionId: string]: IExtensionDescription; } = {};
			builtinExtensions.forEach((builtinExtension) => {
				result[builtinExtension.id] = builtinExtension;
			});
			userExtensions.forEach((userExtension) => {
				if (result.hasOwnProperty(userExtension.id)) {
346
					log.warn(userExtension.extensionFolderPath, nls.localize('overwritingExtension', "Overwriting extension {0} with {1}.", result[userExtension.id].extensionFolderPath, userExtension.extensionFolderPath));
347 348 349 350
				}
				result[userExtension.id] = userExtension;
			});
			developedExtensions.forEach(developedExtension => {
351
				log.info('', nls.localize('extensionUnderDevelopment', "Loading development extension at {0}", developedExtension.extensionFolderPath));
352
				if (result.hasOwnProperty(developedExtension.id)) {
353
					log.warn(developedExtension.extensionFolderPath, nls.localize('overwritingExtension', "Overwriting extension {0} with {1}.", result[developedExtension.id].extensionFolderPath, developedExtension.extensionFolderPath));
354 355 356 357 358
				}
				result[developedExtension.id] = developedExtension;
			});

			return Object.keys(result).map(name => result[name]);
R
Ron Buckton 已提交
359
		}).then(null, err => {
360
			log.error('', err);
361 362 363
			return [];
		});
	}
364

365
	private static _handleExtensionPoint<T>(extensionPoint: ExtensionPoint<T>, availableExtensions: IExtensionDescription[], messageHandler: (msg: IMessage) => void): void {
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
		let users: IExtensionPointUser<T>[] = [], usersLen = 0;
		for (let i = 0, len = availableExtensions.length; i < len; i++) {
			let desc = availableExtensions[i];

			if (desc.contributes && hasOwnProperty.call(desc.contributes, extensionPoint.name)) {
				users[usersLen++] = {
					description: desc,
					value: desc.contributes[extensionPoint.name],
					collector: new ExtensionMessageCollector(messageHandler, desc, extensionPoint.name)
				};
			}
		}

		extensionPoint.acceptUsers(users);
	}

382 383
	private _showMessageToUser(severity: Severity, msg: string): void {
		if (severity === Severity.Error || severity === Severity.Warning) {
384
			this._messageService.show(severity, msg);
385 386 387 388 389 390 391
		} else {
			this._logMessageInConsole(severity, msg);
		}
	}

	private _logMessageInConsole(severity: Severity, msg: string): void {
		if (severity === Severity.Error) {
392 393 394 395 396 397
			console.error(msg);
		} else if (severity === Severity.Warning) {
			console.warn(msg);
		} else {
			console.log(msg);
		}
398
	}
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431

	// -- called by extension host

	public _logOrShowMessage(severity: Severity, msg: string): void {
		if (this._isDev) {
			this._showMessageToUser(severity, msg);
		} else {
			this._logMessageInConsole(severity, msg);
		}
	}
}

export class Logger implements ILog {

	private readonly _messageHandler: (severity: Severity, source: string, message: string) => void;

	constructor(
		messageHandler: (severity: Severity, source: string, message: string) => void
	) {
		this._messageHandler = messageHandler;
	}

	public error(source: string, message: string): void {
		this._messageHandler(Severity.Error, source, message);
	}

	public warn(source: string, message: string): void {
		this._messageHandler(Severity.Warning, source, message);
	}

	public info(source: string, message: string): void {
		this._messageHandler(Severity.Info, source, message);
	}
432
}