extHostExtensionService.ts 15.7 KB
Newer Older
E
Erich Gamma 已提交
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';

A
Alex Dima 已提交
7
import { dispose } from 'vs/base/common/lifecycle';
8
import { join } from 'path';
J
Johannes Rieken 已提交
9
import { mkdirp, dirExists, realpath } from 'vs/base/node/pfs';
E
Erich Gamma 已提交
10
import Severity from 'vs/base/common/severity';
J
Johannes Rieken 已提交
11
import { TPromise } from 'vs/base/common/winjs.base';
B
Benjamin Pasero 已提交
12
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/node/extensionDescriptionRegistry';
A
Alex Dima 已提交
13
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
J
Johannes Rieken 已提交
14
import { ExtHostStorage } from 'vs/workbench/api/node/extHostStorage';
15
import { createApiFactory, initializeExtensionApi, checkProposedApiEnabled } from 'vs/workbench/api/node/extHost.api.impl';
16
import { MainContext, MainThreadExtensionServiceShape, IWorkspaceData, IEnvironment, IInitData, ExtHostExtensionServiceShape, MainThreadTelemetryShape, IExtHostContext } from './extHost.protocol';
A
Alex Dima 已提交
17
import { IExtensionMemento, ExtensionsActivator, ActivatedExtension, IExtensionAPI, IExtensionContext, EmptyExtension, IExtensionModule, ExtensionActivationTimesBuilder, ExtensionActivationTimes, ExtensionActivationReason, ExtensionActivatedByEvent } from 'vs/workbench/api/node/extHostExtensionActivator';
18 19
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
20
import { TernarySearchTree } from 'vs/base/common/map';
J
Joao Moreno 已提交
21
import { Barrier } from 'vs/base/common/async';
J
Joao Moreno 已提交
22
import { ILogService } from 'vs/platform/log/common/log';
23
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
24
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
A
Alex Dima 已提交
25

A
Alex Dima 已提交
26
class ExtensionMemento implements IExtensionMemento {
A
Alex Dima 已提交
27 28 29

	private _id: string;
	private _shared: boolean;
A
Alex Dima 已提交
30
	private _storage: ExtHostStorage;
A
Alex Dima 已提交
31

A
Alex Dima 已提交
32
	private _init: TPromise<ExtensionMemento>;
A
Alex Dima 已提交
33 34
	private _value: { [n: string]: any; };

A
Alex Dima 已提交
35
	constructor(id: string, global: boolean, storage: ExtHostStorage) {
A
Alex Dima 已提交
36 37 38 39 40 41 42 43 44 45
		this._id = id;
		this._shared = global;
		this._storage = storage;

		this._init = this._storage.getValue(this._shared, this._id, Object.create(null)).then(value => {
			this._value = value;
			return this;
		});
	}

A
Alex Dima 已提交
46
	get whenReady(): TPromise<ExtensionMemento> {
A
Alex Dima 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
		return this._init;
	}

	get<T>(key: string, defaultValue: T): T {
		let value = this._value[key];
		if (typeof value === 'undefined') {
			value = defaultValue;
		}
		return value;
	}

	update(key: string, value: any): Thenable<boolean> {
		this._value[key] = value;
		return this._storage
			.setValue(this._shared, this._id, this._value)
			.then(() => true);
	}
}

66 67
class ExtensionStoragePath {

68
	private readonly _workspace: IWorkspaceData;
69 70 71 72 73
	private readonly _environment: IEnvironment;

	private readonly _ready: TPromise<string>;
	private _value: string;

74
	constructor(workspace: IWorkspaceData, environment: IEnvironment) {
75
		this._workspace = workspace;
76 77 78 79 80 81 82 83
		this._environment = environment;
		this._ready = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value);
	}

	get whenReady(): TPromise<any> {
		return this._ready;
	}

84 85
	value(extension: IExtensionDescription): string {
		if (this._value) {
86
			return join(this._value, extension.id);
87
		}
M
Matt Bierner 已提交
88
		return undefined;
89 90 91
	}

	private _getOrCreateWorkspaceStoragePath(): TPromise<string> {
92
		if (!this._workspace) {
93 94
			return TPromise.as(undefined);
		}
95
		const storageName = this._workspace.id;
96
		const storagePath = join(this._environment.appSettingsHome, 'workspaceStorage', storageName);
97 98 99 100 101 102

		return dirExists(storagePath).then(exists => {
			if (exists) {
				return storagePath;
			}

J
Johannes Rieken 已提交
103
			return mkdirp(storagePath).then(success => {
104 105 106 107 108 109 110 111
				return storagePath;
			}, err => {
				return undefined;
			});
		});
	}
}

A
Alex Dima 已提交
112
export class ExtHostExtensionService implements ExtHostExtensionServiceShape {
A
Alex Dima 已提交
113 114 115

	private readonly _barrier: Barrier;
	private readonly _registry: ExtensionDescriptionRegistry;
116
	private readonly _threadService: IExtHostContext;
117
	private readonly _mainThreadTelemetry: MainThreadTelemetryShape;
A
Alex Dima 已提交
118 119
	private readonly _storage: ExtHostStorage;
	private readonly _storagePath: ExtensionStoragePath;
120
	private readonly _proxy: MainThreadExtensionServiceShape;
121
	private readonly _logService: ILogService;
122
	private readonly _extHostLogService: ExtHostLogService;
A
Alex Dima 已提交
123
	private _activator: ExtensionsActivator;
124
	private _extensionPathIndex: TPromise<TernarySearchTree<IExtensionDescription>>;
A
Alex Dima 已提交
125 126 127
	/**
	 * This class is constructed manually because it is a service, so it doesn't use any ctor injection
	 */
128
	constructor(initData: IInitData,
129
		threadService: IExtHostContext,
130
		extHostWorkspace: ExtHostWorkspace,
J
Joao Moreno 已提交
131
		extHostConfiguration: ExtHostConfiguration,
132 133
		logService: ILogService,
		environmentService: IEnvironmentService
134
	) {
A
Alex Dima 已提交
135 136 137
		this._barrier = new Barrier();
		this._registry = new ExtensionDescriptionRegistry(initData.extensions);
		this._threadService = threadService;
138
		this._logService = logService;
139
		this._mainThreadTelemetry = threadService.getProxy(MainContext.MainThreadTelemetry);
A
Alex Dima 已提交
140 141
		this._storage = new ExtHostStorage(threadService);
		this._storagePath = new ExtensionStoragePath(initData.workspace, initData.environment);
142
		this._proxy = this._threadService.getProxy(MainContext.MainThreadExtensionService);
A
Alex Dima 已提交
143
		this._activator = null;
144
		this._extHostLogService = new ExtHostLogService(environmentService);
145

A
Alex Dima 已提交
146
		// initialize API first (i.e. do not release barrier until the API is initialized)
147
		const apiFactory = createApiFactory(initData, threadService, extHostWorkspace, extHostConfiguration, this, logService);
148

A
Alex Dima 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
		initializeExtensionApi(this, apiFactory).then(() => {

			this._activator = new ExtensionsActivator(this._registry, {
				showMessage: (severity: Severity, message: string): void => {
					this._proxy.$localShowMessage(severity, message);

					switch (severity) {
						case Severity.Error:
							console.error(message);
							break;
						case Severity.Warning:
							console.warn(message);
							break;
						default:
							console.log(message);
					}
				},

A
Alex Dima 已提交
167 168
				actualActivateExtension: (extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): TPromise<ActivatedExtension> => {
					return this._activateExtension(extensionDescription, reason);
A
Alex Dima 已提交
169
				}
170 171
			});

A
Alex Dima 已提交
172 173
			this._barrier.open();
		});
174 175
	}

A
Alex Dima 已提交
176 177
	public onExtensionAPIReady(): TPromise<boolean> {
		return this._barrier.wait();
178 179 180
	}

	public isActivated(extensionId: string): boolean {
A
Alex Dima 已提交
181 182 183 184
		if (this._barrier.isOpen()) {
			return this._activator.isActivated(extensionId);
		}
		return false;
185 186
	}

187
	public activateByEvent(activationEvent: string, startup: boolean): TPromise<void> {
A
Alex Dima 已提交
188
		const reason = new ExtensionActivatedByEvent(startup, activationEvent);
A
Alex Dima 已提交
189
		if (this._barrier.isOpen()) {
A
Alex Dima 已提交
190
			return this._activator.activateByEvent(activationEvent, reason);
191
		} else {
A
Alex Dima 已提交
192
			return this._barrier.wait().then(() => this._activator.activateByEvent(activationEvent, reason));
193 194 195
		}
	}

A
Alex Dima 已提交
196
	public activateById(extensionId: string, reason: ExtensionActivationReason): TPromise<void> {
A
Alex Dima 已提交
197
		if (this._barrier.isOpen()) {
A
Alex Dima 已提交
198
			return this._activator.activateById(extensionId, reason);
199
		} else {
A
Alex Dima 已提交
200
			return this._barrier.wait().then(() => this._activator.activateById(extensionId, reason));
201 202 203
		}
	}

204 205 206 207 208 209 210 211
	public getAllExtensionDescriptions(): IExtensionDescription[] {
		return this._registry.getAllExtensionDescriptions();
	}

	public getExtensionDescription(extensionId: string): IExtensionDescription {
		return this._registry.getExtensionDescription(extensionId);
	}

A
Alex Dima 已提交
212 213 214 215 216
	public getExtensionExports(extensionId: string): IExtensionAPI {
		if (this._barrier.isOpen()) {
			return this._activator.getActivatedExtension(extensionId).exports;
		} else {
			return null;
E
Erich Gamma 已提交
217 218 219
		}
	}

220
	// create trie to enable fast 'filename -> extension id' look up
221
	public getExtensionPathIndex(): TPromise<TernarySearchTree<IExtensionDescription>> {
222
		if (!this._extensionPathIndex) {
223
			const tree = TernarySearchTree.forPaths<IExtensionDescription>();
224 225 226 227
			const extensions = this.getAllExtensionDescriptions().map(ext => {
				if (!ext.main) {
					return undefined;
				}
J
Johannes Rieken 已提交
228 229
				return realpath(ext.extensionFolderPath).then(value => tree.set(value, ext));

230
			});
231
			this._extensionPathIndex = TPromise.join(extensions).then(() => tree);
232 233 234 235 236
		}
		return this._extensionPathIndex;
	}


237
	public deactivate(extensionId: string): TPromise<void> {
J
Johannes Rieken 已提交
238
		let result: TPromise<void> = TPromise.as(void 0);
239

A
Alex Dima 已提交
240 241 242 243 244
		if (!this._barrier.isOpen()) {
			return result;
		}

		if (!this._activator.isActivated(extensionId)) {
A
Alex Dima 已提交
245 246 247
			return result;
		}

A
Alex Dima 已提交
248
		let extension = this._activator.getActivatedExtension(extensionId);
A
Alex Dima 已提交
249
		if (!extension) {
250
			return result;
251 252 253 254
		}

		// call deactivate if available
		try {
A
Alex Dima 已提交
255
			if (typeof extension.module.deactivate === 'function') {
256 257 258 259
				result = TPromise.wrap(extension.module.deactivate()).then(null, (err) => {
					// TODO: Do something with err if this is not the shutdown case
					return TPromise.as(void 0);
				});
260
			}
B
Benjamin Pasero 已提交
261
		} catch (err) {
262 263 264 265 266
			// TODO: Do something with err if this is not the shutdown case
		}

		// clean up subscriptions
		try {
J
Joao Moreno 已提交
267
			dispose(extension.subscriptions);
B
Benjamin Pasero 已提交
268
		} catch (err) {
269 270
			// TODO: Do something with err if this is not the shutdown case
		}
271 272

		return result;
273
	}
E
Erich Gamma 已提交
274

A
Alex Dima 已提交
275 276 277 278
	public addMessage(extensionId: string, severity: Severity, message: string): void {
		this._proxy.$addMessage(extensionId, severity, message);
	}

A
Alex Dima 已提交
279
	// --- impl
A
Alex Dima 已提交
280

A
Alex Dima 已提交
281 282
	private _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): TPromise<ActivatedExtension> {
		return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => {
283
			const activationTimes = activatedExtension.activationTimes;
A
Alex Dima 已提交
284 285
			let activationEvent = (reason instanceof ExtensionActivatedByEvent ? reason.activationEvent : null);
			this._proxy.$onExtensionActivated(extensionDescription.id, activationTimes.startup, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, activationEvent);
A
Alex Dima 已提交
286 287 288 289 290
			return activatedExtension;
		}, (err) => {
			this._proxy.$onExtensionActivationFailed(extensionDescription.id);
			throw err;
		});
E
Erich Gamma 已提交
291 292
	}

A
Alex Dima 已提交
293
	private _doActivateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): TPromise<ActivatedExtension> {
A
Alex Dima 已提交
294
		let event = getTelemetryActivationEvent(extensionDescription);
K
kieferrm 已提交
295
		/* __GDPR__
K
kieferrm 已提交
296 297 298 299 300 301
			"activatePlugin" : {
				"${include}": [
					"${TelemetryActivationEvent}"
				]
			}
		*/
302
		this._mainThreadTelemetry.$publicLog('activatePlugin', event);
A
Alex Dima 已提交
303 304
		if (!extensionDescription.main) {
			// Treat the extension as being empty => NOT AN ERROR CASE
305
			return TPromise.as(new EmptyExtension(ExtensionActivationTimes.NONE));
A
Alex Dima 已提交
306
		}
307

308 309
		this._logService.info(`ExtensionService#_doActivateExtension ${extensionDescription.id} ${JSON.stringify(reason)}`);

A
Alex Dima 已提交
310
		const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
A
Alex Dima 已提交
311
		return TPromise.join<any>([
312
			loadCommonJSModule(this._logService, extensionDescription.main, activationTimesBuilder),
A
Alex Dima 已提交
313 314
			this._loadExtensionContext(extensionDescription)
		]).then(values => {
315
			return ExtHostExtensionService._callActivate(this._logService, extensionDescription.id, <IExtensionModule>values[0], <IExtensionContext>values[1], activationTimesBuilder);
A
Alex Dima 已提交
316 317 318 319 320 321 322 323 324 325
		}, (errors: any[]) => {
			// Avoid failing with an array of errors, fail with a single error
			if (errors[0]) {
				return TPromise.wrapError<ActivatedExtension>(errors[0]);
			}
			if (errors[1]) {
				return TPromise.wrapError<ActivatedExtension>(errors[1]);
			}
			return undefined;
		});
E
Erich Gamma 已提交
326 327
	}

A
Alex Dima 已提交
328
	private _loadExtensionContext(extensionDescription: IExtensionDescription): TPromise<IExtensionContext> {
E
Erich Gamma 已提交
329

A
Alex Dima 已提交
330 331
		let globalState = new ExtensionMemento(extensionDescription.id, true, this._storage);
		let workspaceState = new ExtensionMemento(extensionDescription.id, false, this._storage);
E
Erich Gamma 已提交
332

333
		this._logService.trace(`ExtensionService#loadExtensionContext ${extensionDescription.id}`);
334 335 336 337 338
		return TPromise.join([
			globalState.whenReady,
			workspaceState.whenReady,
			this._storagePath.whenReady
		]).then(() => {
339
			const that = this;
A
Alex Dima 已提交
340
			return Object.freeze(<IExtensionContext>{
E
Erich Gamma 已提交
341 342 343
				globalState,
				workspaceState,
				subscriptions: [],
A
Alex Dima 已提交
344
				get extensionPath() { return extensionDescription.extensionFolderPath; },
345
				storagePath: this._storagePath.value(extensionDescription),
346
				asAbsolutePath: (relativePath: string) => { return join(extensionDescription.extensionFolderPath, relativePath); },
347 348 349 350
				get logger() {
					checkProposedApiEnabled(extensionDescription);
					return that._extHostLogService.getExtLogger(extensionDescription.id);
				}
E
Erich Gamma 已提交
351 352 353 354
			});
		});
	}

355
	private static _callActivate(logService: ILogService, extensionId: string, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Thenable<ActivatedExtension> {
A
Alex Dima 已提交
356 357
		// Make sure the extension's surface is not undefined
		extensionModule = extensionModule || {
358 359 360 361
			activate: undefined,
			deactivate: undefined
		};

362
		return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
363
			return new ActivatedExtension(false, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions);
364 365 366
		});
	}

367
	private static _callActivateOptional(logService: ILogService, extensionId: string, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Thenable<IExtensionAPI> {
A
Alex Dima 已提交
368
		if (typeof extensionModule.activate === 'function') {
369
			try {
370
				activationTimesBuilder.activateCallStart();
371
				logService.trace(`ExtensionService#_callActivateOptional ${extensionId}`);
372
				const activateResult: TPromise<IExtensionAPI> = extensionModule.activate.apply(global, [context]);
373 374 375 376 377 378 379
				activationTimesBuilder.activateCallStop();

				activationTimesBuilder.activateResolveStart();
				return TPromise.as(activateResult).then((value) => {
					activationTimesBuilder.activateResolveStop();
					return value;
				});
380
			} catch (err) {
A
Alex Dima 已提交
381
				return TPromise.wrapError(err);
382 383
			}
		} else {
A
Alex Dima 已提交
384 385
			// No activate found => the module is the extension's exports
			return TPromise.as<IExtensionAPI>(extensionModule);
386 387 388
		}
	}

E
Erich Gamma 已提交
389 390
	// -- called by main thread

391
	public $activateByEvent(activationEvent: string): TPromise<void> {
392
		return this.activateByEvent(activationEvent, false);
393 394 395
	}
}

396
function loadCommonJSModule<T>(logService: ILogService, modulePath: string, activationTimesBuilder: ExtensionActivationTimesBuilder): TPromise<T> {
B
Benjamin Pasero 已提交
397
	let r: T = null;
398
	activationTimesBuilder.codeLoadingStart();
399
	logService.info(`ExtensionService#loadCommonJSModule ${modulePath}`);
E
Erich Gamma 已提交
400 401
	try {
		r = require.__$__nodeRequire<T>(modulePath);
B
Benjamin Pasero 已提交
402
	} catch (e) {
403
		return TPromise.wrapError<T>(e);
404 405
	} finally {
		activationTimesBuilder.codeLoadingStop();
E
Erich Gamma 已提交
406
	}
A
Alex Dima 已提交
407
	return TPromise.as(r);
E
Erich Gamma 已提交
408
}
A
Alex Dima 已提交
409 410

function getTelemetryActivationEvent(extensionDescription: IExtensionDescription): any {
K
kieferrm 已提交
411
	/* __GDPR__FRAGMENT__
K
kieferrm 已提交
412 413 414 415 416
		"TelemetryActivationEvent" : {
			"id": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
			"name": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
			"publisherDisplayName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
			"activationEvents": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
A
Alex Dima 已提交
417
			"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
K
kieferrm 已提交
418 419
		}
	*/
A
Alex Dima 已提交
420 421 422 423
	let event = {
		id: extensionDescription.id,
		name: extensionDescription.name,
		publisherDisplayName: extensionDescription.publisher,
424 425
		activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
		isBuiltin: extensionDescription.isBuiltin
A
Alex Dima 已提交
426 427 428
	};

	return event;
429
}