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

A
Alex Dima 已提交
6
import * as nls from 'vs/nls';
7
import * as path from 'vs/base/common/path';
A
Alex Dima 已提交
8 9 10
import { Barrier } from 'vs/base/common/async';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { TernarySearchTree } from 'vs/base/common/map';
E
Erich Gamma 已提交
11
import Severity from 'vs/base/common/severity';
A
Alex Dima 已提交
12
import { URI } from 'vs/base/common/uri';
A
Alex Dima 已提交
13
import * as pfs from 'vs/base/node/pfs';
A
Alex Dima 已提交
14
import { ILogService } from 'vs/platform/log/common/log';
A
Alex Dima 已提交
15
import { createApiFactory, initializeExtensionApi, IExtensionApiFactory } from 'vs/workbench/api/node/extHost.api.impl';
16
import { ExtHostExtensionServiceShape, IEnvironment, IInitData, IMainContext, MainContext, MainThreadExtensionServiceShape, MainThreadTelemetryShape, MainThreadWorkspaceShape, IStaticWorkspaceData } from 'vs/workbench/api/node/extHost.protocol';
17
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
18
import { ActivatedExtension, EmptyExtension, ExtensionActivatedByAPI, ExtensionActivatedByEvent, ExtensionActivationReason, ExtensionActivationTimes, ExtensionActivationTimesBuilder, ExtensionsActivator, IExtensionAPI, IExtensionContext, IExtensionMemento, IExtensionModule, HostExtension } from 'vs/workbench/api/node/extHostExtensionActivator';
19
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
A
Alex Dima 已提交
20
import { ExtHostStorage } from 'vs/workbench/api/node/extHostStorage';
21
import { ExtHostWorkspace, ExtHostWorkspaceProvider } from 'vs/workbench/api/node/extHostWorkspace';
S
Sandeep Somavarapu 已提交
22
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
A
Alex Dima 已提交
23
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/node/extensionDescriptionRegistry';
24
import { connectProxyResolver } from 'vs/workbench/services/extensions/node/proxyResolver';
A
Alex Dima 已提交
25 26 27
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import * as errors from 'vs/base/common/errors';
import { ResolvedAuthority } from 'vs/platform/remote/common/remoteAuthorityResolver';
28
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
29
import { IWorkspace } from 'vs/platform/workspace/common/workspace';
A
Alex Dima 已提交
30

A
Alex Dima 已提交
31
class ExtensionMemento implements IExtensionMemento {
A
Alex Dima 已提交
32

33 34 35
	private readonly _id: string;
	private readonly _shared: boolean;
	private readonly _storage: ExtHostStorage;
A
Alex Dima 已提交
36

J
Johannes Rieken 已提交
37
	private readonly _init: Promise<ExtensionMemento>;
A
Alex Dima 已提交
38
	private _value: { [n: string]: any; };
39
	private readonly _storageListener: IDisposable;
A
Alex Dima 已提交
40

A
Alex Dima 已提交
41
	constructor(id: string, global: boolean, storage: ExtHostStorage) {
A
Alex Dima 已提交
42 43 44 45 46 47 48 49
		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;
		});
50 51 52 53 54 55

		this._storageListener = this._storage.onDidChangeStorage(e => {
			if (e.shared === this._shared && e.key === this._id) {
				this._value = e.value;
			}
		});
A
Alex Dima 已提交
56 57
	}

J
Johannes Rieken 已提交
58
	get whenReady(): Promise<ExtensionMemento> {
A
Alex Dima 已提交
59 60 61 62 63 64 65 66 67 68 69
		return this._init;
	}

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

J
Johannes Rieken 已提交
70
	update(key: string, value: any): Promise<boolean> {
A
Alex Dima 已提交
71 72 73 74 75
		this._value[key] = value;
		return this._storage
			.setValue(this._shared, this._id, this._value)
			.then(() => true);
	}
76 77 78 79

	dispose(): void {
		this._storageListener.dispose();
	}
A
Alex Dima 已提交
80 81
}

82 83
class ExtensionStoragePath {

M
Matt Bierner 已提交
84
	private readonly _workspace?: IStaticWorkspaceData;
85 86
	private readonly _environment: IEnvironment;

M
Matt Bierner 已提交
87 88
	private readonly _ready: Promise<string | undefined>;
	private _value?: string;
89

M
Matt Bierner 已提交
90
	constructor(workspace: IStaticWorkspaceData | undefined, environment: IEnvironment) {
91 92 93 94 95 96 97 98 99
		this._workspace = workspace;
		this._environment = environment;
		this._ready = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value);
	}

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

M
Matt Bierner 已提交
100
	workspaceValue(extension: IExtensionDescription): string | undefined {
101
		if (this._value) {
102
			return path.join(this._value, extension.identifier.value);
103 104 105 106
		}
		return undefined;
	}

107
	globalValue(extension: IExtensionDescription): string {
S
Sandeep Somavarapu 已提交
108
		return path.join(this._environment.globalStorageHome.fsPath, extension.identifier.value.toLowerCase());
109 110
	}

M
Matt Bierner 已提交
111
	private async _getOrCreateWorkspaceStoragePath(): Promise<string | undefined> {
112 113 114 115 116
		if (!this._workspace) {
			return Promise.resolve(undefined);
		}

		const storageName = this._workspace.id;
A
Alex Dima 已提交
117
		const storagePath = path.join(this._environment.appSettingsHome.fsPath, 'workspaceStorage', storageName);
118

A
Alex Dima 已提交
119
		const exists = await pfs.dirExists(storagePath);
120 121 122 123 124 125

		if (exists) {
			return storagePath;
		}

		try {
A
Alex Dima 已提交
126 127 128
			await pfs.mkdirp(storagePath);
			await pfs.writeFile(
				path.join(storagePath, 'meta.json'),
129 130 131 132 133 134 135 136 137 138 139 140 141 142
				JSON.stringify({
					id: this._workspace.id,
					configuration: this._workspace.configuration && URI.revive(this._workspace.configuration).toString(),
					name: this._workspace.name
				}, undefined, 2)
			);
			return storagePath;

		} catch (e) {
			console.error(e);
			return undefined;
		}
	}
}
A
Alex Dima 已提交
143 144 145 146 147

interface ITestRunner {
	run(testsRoot: string, clb: (error: Error, failures?: number) => void): void;
}

A
Alex Dima 已提交
148
export class ExtHostExtensionService implements ExtHostExtensionServiceShape {
A
Alex Dima 已提交
149

A
Alex Dima 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162
	private static readonly WORKSPACE_CONTAINS_TIMEOUT = 7000;

	private readonly _nativeExit: (code?: number) => void;
	private readonly _initData: IInitData;
	private readonly _extHostContext: IMainContext;
	private readonly _extHostWorkspace: ExtHostWorkspace;
	private readonly _extHostConfiguration: ExtHostConfiguration;
	private readonly _extHostLogService: ExtHostLogService;

	private readonly _mainThreadWorkspaceProxy: MainThreadWorkspaceShape;
	private readonly _mainThreadTelemetryProxy: MainThreadTelemetryShape;
	private readonly _mainThreadExtensionsProxy: MainThreadExtensionServiceShape;

A
Alex Dima 已提交
163 164 165
	private readonly _barrier: Barrier;
	private readonly _registry: ExtensionDescriptionRegistry;
	private readonly _storage: ExtHostStorage;
166
	private readonly _storagePath: ExtensionStoragePath;
A
Alex Dima 已提交
167
	private readonly _activator: ExtensionsActivator;
168
	private _extensionPathIndex: Promise<TernarySearchTree<IExtensionDescription>>;
A
Alex Dima 已提交
169 170 171 172 173 174 175
	private readonly _extensionApiFactory: IExtensionApiFactory;

	private _started: boolean;

	constructor(
		nativeExit: (code?: number) => void,
		initData: IInitData,
176
		extHostContext: IMainContext,
177
		extHostWorkspace: ExtHostWorkspace,
J
Joao Moreno 已提交
178
		extHostConfiguration: ExtHostConfiguration,
A
Alex Dima 已提交
179
		extHostLogService: ExtHostLogService
180
	) {
A
Alex Dima 已提交
181 182 183 184 185 186 187 188 189 190 191
		this._nativeExit = nativeExit;
		this._initData = initData;
		this._extHostContext = extHostContext;
		this._extHostWorkspace = extHostWorkspace;
		this._extHostConfiguration = extHostConfiguration;
		this._extHostLogService = extHostLogService;

		this._mainThreadWorkspaceProxy = this._extHostContext.getProxy(MainContext.MainThreadWorkspace);
		this._mainThreadTelemetryProxy = this._extHostContext.getProxy(MainContext.MainThreadTelemetry);
		this._mainThreadExtensionsProxy = this._extHostContext.getProxy(MainContext.MainThreadExtensionService);

A
Alex Dima 已提交
192 193
		this._barrier = new Barrier();
		this._registry = new ExtensionDescriptionRegistry(initData.extensions);
A
Alex Dima 已提交
194
		this._storage = new ExtHostStorage(this._extHostContext);
195
		this._storagePath = new ExtensionStoragePath(initData.workspace, initData.environment);
196 197 198 199 200

		const hostExtensions = new Set<string>();
		initData.hostExtensions.forEach((extensionId) => hostExtensions.add(ExtensionIdentifier.toKey(extensionId)));

		this._activator = new ExtensionsActivator(this._registry, initData.resolvedExtensions, initData.hostExtensions, {
A
Alex Dima 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
			showMessage: (severity: Severity, message: string): void => {
				this._mainThreadExtensionsProxy.$localShowMessage(severity, message);

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

216 217 218 219 220 221 222
			actualActivateExtension: async (extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<ActivatedExtension> => {
				if (hostExtensions.has(ExtensionIdentifier.toKey(extensionId))) {
					let activationEvent = (reason instanceof ExtensionActivatedByEvent ? reason.activationEvent : null);
					await this._mainThreadExtensionsProxy.$activateExtension(extensionId, activationEvent);
					return new HostExtension();
				}
				const extensionDescription = this._registry.getExtensionDescription(extensionId);
A
Alex Dima 已提交
223 224 225 226
				return this._activateExtension(extensionDescription, reason);
			}
		});
		this._extensionPathIndex = null;
227

A
Alex Dima 已提交
228
		// initialize API first (i.e. do not release barrier until the API is initialized)
A
Alex Dima 已提交
229
		this._extensionApiFactory = createApiFactory(this._initData, this._extHostContext, this._extHostWorkspace, this._extHostConfiguration, this, this._extHostLogService, this._storage);
230

A
Alex Dima 已提交
231 232
		this._started = false;

233
		this._initialize();
A
Alex Dima 已提交
234 235 236 237

		if (this._initData.autoStart) {
			this._startExtensionHost();
		}
238 239
	}

240 241 242
	private async _initialize(): Promise<void> {
		try {
			const configProvider = await this._extHostConfiguration.getConfigProvider();
243 244
			const workspaceProvider = await this._extHostWorkspace.getWorkspaceProvider();
			await initializeExtensionApi(this, this._extensionApiFactory, this._registry, workspaceProvider, configProvider);
245
			// Do this when extension service exists, but extensions are not being activated yet.
246
			await connectProxyResolver(workspaceProvider, configProvider, this, this._extHostLogService, this._mainThreadTelemetryProxy);
247 248 249 250 251 252
			this._barrier.open();
		} catch (err) {
			errors.onUnexpectedError(err);
		}
	}

A
Alex Dima 已提交
253
	public async deactivateAll(): Promise<void> {
J
Johannes Rieken 已提交
254
		let allPromises: Promise<void>[] = [];
A
Alex Dima 已提交
255 256
		try {
			const allExtensions = this._registry.getAllExtensionDescriptions();
257
			const allExtensionsIds = allExtensions.map(ext => ext.identifier);
A
Alex Dima 已提交
258 259 260 261 262 263 264 265 266
			const activatedExtensions = allExtensionsIds.filter(id => this.isActivated(id));

			allPromises = activatedExtensions.map((extensionId) => {
				return this._deactivate(extensionId);
			});
		} catch (err) {
			// TODO: write to log once we have one
		}
		await allPromises;
267 268
	}

269
	public isActivated(extensionId: ExtensionIdentifier): boolean {
A
Alex Dima 已提交
270 271 272 273
		if (this._barrier.isOpen()) {
			return this._activator.isActivated(extensionId);
		}
		return false;
274 275
	}

J
Johannes Rieken 已提交
276
	private _activateByEvent(activationEvent: string, startup: boolean): Promise<void> {
A
Alex Dima 已提交
277
		const reason = new ExtensionActivatedByEvent(startup, activationEvent);
A
Alex Dima 已提交
278
		return this._activator.activateByEvent(activationEvent, reason);
279 280
	}

281
	private _activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
A
Alex Dima 已提交
282
		return this._activator.activateById(extensionId, reason);
283 284
	}

285
	public activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
A
Alex Dima 已提交
286
		return this._activateById(extensionId, reason).then(() => {
287 288 289
			const extension = this._activator.getActivatedExtension(extensionId);
			if (extension.activationFailed) {
				// activation failed => bubble up the error as the promise result
290
				return Promise.reject(extension.activationFailedError);
291
			}
R
Rob Lourens 已提交
292
			return undefined;
293 294 295
		});
	}

A
Alex Dima 已提交
296 297
	public getExtensionRegistry(): Promise<ExtensionDescriptionRegistry> {
		return this._barrier.wait().then(_ => this._registry);
298 299
	}

300
	public getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI {
A
Alex Dima 已提交
301 302 303 304
		if (this._barrier.isOpen()) {
			return this._activator.getActivatedExtension(extensionId).exports;
		} else {
			return null;
E
Erich Gamma 已提交
305 306 307
		}
	}

308
	// create trie to enable fast 'filename -> extension id' look up
309
	public getExtensionPathIndex(): Promise<TernarySearchTree<IExtensionDescription>> {
310
		if (!this._extensionPathIndex) {
311
			const tree = TernarySearchTree.forPaths<IExtensionDescription>();
A
Alex Dima 已提交
312
			const extensions = this._registry.getAllExtensionDescriptions().map(ext => {
313 314 315
				if (!ext.main) {
					return undefined;
				}
A
Alex Dima 已提交
316
				return pfs.realpath(ext.extensionLocation.fsPath).then(value => tree.set(URI.file(value).fsPath, ext));
317
			});
318
			this._extensionPathIndex = Promise.all(extensions).then(() => tree);
319 320 321 322
		}
		return this._extensionPathIndex;
	}

323
	private _deactivate(extensionId: ExtensionIdentifier): Promise<void> {
R
Rob Lourens 已提交
324
		let result = Promise.resolve(undefined);
325

A
Alex Dima 已提交
326 327 328 329 330
		if (!this._barrier.isOpen()) {
			return result;
		}

		if (!this._activator.isActivated(extensionId)) {
A
Alex Dima 已提交
331 332 333
			return result;
		}

A
Alex Dima 已提交
334
		let extension = this._activator.getActivatedExtension(extensionId);
A
Alex Dima 已提交
335
		if (!extension) {
336
			return result;
337 338 339 340
		}

		// call deactivate if available
		try {
A
Alex Dima 已提交
341
			if (typeof extension.module.deactivate === 'function') {
R
Rob Lourens 已提交
342
				result = Promise.resolve(extension.module.deactivate()).then(undefined, (err) => {
343
					// TODO: Do something with err if this is not the shutdown case
R
Rob Lourens 已提交
344
					return Promise.resolve(undefined);
345
				});
346
			}
B
Benjamin Pasero 已提交
347
		} catch (err) {
348 349 350 351 352
			// TODO: Do something with err if this is not the shutdown case
		}

		// clean up subscriptions
		try {
J
Joao Moreno 已提交
353
			dispose(extension.subscriptions);
B
Benjamin Pasero 已提交
354
		} catch (err) {
355 356
			// TODO: Do something with err if this is not the shutdown case
		}
357 358

		return result;
359
	}
E
Erich Gamma 已提交
360

361
	public addMessage(extensionId: ExtensionIdentifier, severity: Severity, message: string): void {
A
Alex Dima 已提交
362
		this._mainThreadExtensionsProxy.$addMessage(extensionId, severity, message);
A
Alex Dima 已提交
363 364
	}

A
Alex Dima 已提交
365
	// --- impl
A
Alex Dima 已提交
366

367
	private _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
368
		this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
A
Alex Dima 已提交
369
		return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => {
370
			const activationTimes = activatedExtension.activationTimes;
A
Alex Dima 已提交
371
			let activationEvent = (reason instanceof ExtensionActivatedByEvent ? reason.activationEvent : null);
372
			this._mainThreadExtensionsProxy.$onDidActivateExtension(extensionDescription.identifier, activationTimes.startup, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, activationEvent);
373
			this._logExtensionActivationTimes(extensionDescription, reason, 'success', activationTimes);
A
Alex Dima 已提交
374 375
			return activatedExtension;
		}, (err) => {
376
			this._mainThreadExtensionsProxy.$onExtensionActivationFailed(extensionDescription.identifier);
377
			this._logExtensionActivationTimes(extensionDescription, reason, 'failure');
A
Alex Dima 已提交
378 379
			throw err;
		});
E
Erich Gamma 已提交
380 381
	}

382 383 384 385 386 387 388 389 390 391 392
	private _logExtensionActivationTimes(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason, outcome: string, activationTimes?: ExtensionActivationTimes) {
		let event = getTelemetryActivationEvent(extensionDescription, reason);
		/* __GDPR__
			"extensionActivationTimes" : {
				"${include}": [
					"${TelemetryActivationEvent}",
					"${ExtensionActivationTimes}"
				],
				"outcome" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
A
Alex Dima 已提交
393
		this._mainThreadTelemetryProxy.$publicLog('extensionActivationTimes', {
394 395 396 397 398 399
			...event,
			...(activationTimes || {}),
			outcome,
		});
	}

400
	private _doActivateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
R
Rob Lourens 已提交
401
		let event = getTelemetryActivationEvent(extensionDescription, reason);
K
kieferrm 已提交
402
		/* __GDPR__
K
kieferrm 已提交
403 404 405 406 407 408
			"activatePlugin" : {
				"${include}": [
					"${TelemetryActivationEvent}"
				]
			}
		*/
A
Alex Dima 已提交
409
		this._mainThreadTelemetryProxy.$publicLog('activatePlugin', event);
A
Alex Dima 已提交
410 411
		if (!extensionDescription.main) {
			// Treat the extension as being empty => NOT AN ERROR CASE
412
			return Promise.resolve(new EmptyExtension(ExtensionActivationTimes.NONE));
A
Alex Dima 已提交
413
		}
414

415
		this._extHostLogService.info(`ExtensionService#_doActivateExtension ${extensionDescription.identifier.value} ${JSON.stringify(reason)}`);
416

A
Alex Dima 已提交
417
		const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
418
		return Promise.all<any>([
419
			loadCommonJSModule(this._extHostLogService, extensionDescription.main, activationTimesBuilder),
A
Alex Dima 已提交
420 421
			this._loadExtensionContext(extensionDescription)
		]).then(values => {
422
			return ExtHostExtensionService._callActivate(this._extHostLogService, extensionDescription.identifier, <IExtensionModule>values[0], <IExtensionContext>values[1], activationTimesBuilder);
A
Alex Dima 已提交
423
		});
E
Erich Gamma 已提交
424 425
	}

426
	private _loadExtensionContext(extensionDescription: IExtensionDescription): Promise<IExtensionContext> {
E
Erich Gamma 已提交
427

428 429
		let globalState = new ExtensionMemento(extensionDescription.identifier.value, true, this._storage);
		let workspaceState = new ExtensionMemento(extensionDescription.identifier.value, false, this._storage);
E
Erich Gamma 已提交
430

431
		this._extHostLogService.trace(`ExtensionService#loadExtensionContext ${extensionDescription.identifier.value}`);
432
		return Promise.all([
433
			globalState.whenReady,
434 435
			workspaceState.whenReady,
			this._storagePath.whenReady
436
		]).then(() => {
437
			const that = this;
A
Alex Dima 已提交
438
			return Object.freeze(<IExtensionContext>{
E
Erich Gamma 已提交
439 440 441
				globalState,
				workspaceState,
				subscriptions: [],
442
				get extensionPath() { return extensionDescription.extensionLocation.fsPath; },
443
				storagePath: this._storagePath.workspaceValue(extensionDescription),
S
Sandeep Somavarapu 已提交
444
				globalStoragePath: this._storagePath.globalValue(extensionDescription),
A
Alex Dima 已提交
445
				asAbsolutePath: (relativePath: string) => { return path.join(extensionDescription.extensionLocation.fsPath, relativePath); },
446
				logPath: that._extHostLogService.getLogDirectory(extensionDescription.identifier)
E
Erich Gamma 已提交
447 448 449 450
			});
		});
	}

451
	private static _callActivate(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<ActivatedExtension> {
A
Alex Dima 已提交
452 453
		// Make sure the extension's surface is not undefined
		extensionModule = extensionModule || {
454 455 456 457
			activate: undefined,
			deactivate: undefined
		};

458
		return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
459
			return new ActivatedExtension(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions);
460 461 462
		});
	}

463
	private static _callActivateOptional(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<IExtensionAPI> {
A
Alex Dima 已提交
464
		if (typeof extensionModule.activate === 'function') {
465
			try {
466
				activationTimesBuilder.activateCallStart();
467
				logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`);
J
Johannes Rieken 已提交
468
				const activateResult: Promise<IExtensionAPI> = extensionModule.activate.apply(global, [context]);
469 470 471
				activationTimesBuilder.activateCallStop();

				activationTimesBuilder.activateResolveStart();
472
				return Promise.resolve(activateResult).then((value) => {
473 474 475
					activationTimesBuilder.activateResolveStop();
					return value;
				});
476
			} catch (err) {
477
				return Promise.reject(err);
478 479
			}
		} else {
A
Alex Dima 已提交
480
			// No activate found => the module is the extension's exports
481
			return Promise.resolve<IExtensionAPI>(extensionModule);
482 483 484
		}
	}

A
Alex Dima 已提交
485 486 487
	// -- eager activation

	// Handle "eager" activation extensions
488
	private _handleEagerExtensions(workspaceProvider: ExtHostWorkspaceProvider): Promise<void> {
R
Rob Lourens 已提交
489
		this._activateByEvent('*', true).then(undefined, (err) => {
A
Alex Dima 已提交
490 491 492
			console.error(err);
		});

493
		return this._handleWorkspaceContainsEagerExtensions(workspaceProvider.workspace);
A
Alex Dima 已提交
494 495
	}

M
Matt Bierner 已提交
496
	private _handleWorkspaceContainsEagerExtensions(workspace: IWorkspace | undefined): Promise<void> {
A
Alex Dima 已提交
497
		if (!workspace || workspace.folders.length === 0) {
R
Rob Lourens 已提交
498
			return Promise.resolve(undefined);
A
Alex Dima 已提交
499 500 501 502 503 504 505 506 507
		}

		return Promise.all(
			this._registry.getAllExtensionDescriptions().map((desc) => {
				return this._handleWorkspaceContainsEagerExtension(workspace, desc);
			})
		).then(() => { });
	}

508
	private _handleWorkspaceContainsEagerExtension(workspace: IWorkspace, desc: IExtensionDescription): Promise<void> {
A
Alex Dima 已提交
509 510
		const activationEvents = desc.activationEvents;
		if (!activationEvents) {
R
Rob Lourens 已提交
511
			return Promise.resolve(undefined);
A
Alex Dima 已提交
512 513 514 515 516
		}

		const fileNames: string[] = [];
		const globPatterns: string[] = [];

517 518 519
		for (const activationEvent of activationEvents) {
			if (/^workspaceContains:/.test(activationEvent)) {
				const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
A
Alex Dima 已提交
520 521 522 523 524 525 526 527 528
				if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
					globPatterns.push(fileNameOrGlob);
				} else {
					fileNames.push(fileNameOrGlob);
				}
			}
		}

		if (fileNames.length === 0 && globPatterns.length === 0) {
R
Rob Lourens 已提交
529
			return Promise.resolve(undefined);
A
Alex Dima 已提交
530 531
		}

532 533
		const fileNamePromise = Promise.all(fileNames.map((fileName) => this._activateIfFileName(workspace, desc.identifier, fileName))).then(() => { });
		const globPatternPromise = this._activateIfGlobPatterns(desc.identifier, globPatterns);
A
Alex Dima 已提交
534 535 536 537

		return Promise.all([fileNamePromise, globPatternPromise]).then(() => { });
	}

538
	private async _activateIfFileName(workspace: IWorkspace, extensionId: ExtensionIdentifier, fileName: string): Promise<void> {
A
Alex Dima 已提交
539 540 541 542 543 544 545

		// find exact path
		for (const { uri } of workspace.folders) {
			if (await pfs.exists(path.join(URI.revive(uri).fsPath, fileName))) {
				// the file was found
				return (
					this._activateById(extensionId, new ExtensionActivatedByEvent(true, `workspaceContains:${fileName}`))
R
Rob Lourens 已提交
546
						.then(undefined, err => console.error(err))
A
Alex Dima 已提交
547 548 549 550 551 552 553
				);
			}
		}

		return undefined;
	}

554
	private async _activateIfGlobPatterns(extensionId: ExtensionIdentifier, globPatterns: string[]): Promise<void> {
555
		this._extHostLogService.trace(`extensionHostMain#activateIfGlobPatterns: fileSearch, extension: ${extensionId.value}, entryPoint: workspaceContains`);
A
Alex Dima 已提交
556 557

		if (globPatterns.length === 0) {
R
Rob Lourens 已提交
558
			return Promise.resolve(undefined);
A
Alex Dima 已提交
559 560 561 562 563 564 565 566
		}

		const tokenSource = new CancellationTokenSource();
		const searchP = this._mainThreadWorkspaceProxy.$checkExists(globPatterns, tokenSource.token);

		const timer = setTimeout(async () => {
			tokenSource.cancel();
			this._activateById(extensionId, new ExtensionActivatedByEvent(true, `workspaceContainsTimeout:${globPatterns.join(',')}`))
R
Rob Lourens 已提交
567
				.then(undefined, err => console.error(err));
A
Alex Dima 已提交
568 569
		}, ExtHostExtensionService.WORKSPACE_CONTAINS_TIMEOUT);

M
Matt Bierner 已提交
570
		let exists: boolean = false;
A
Alex Dima 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
		try {
			exists = await searchP;
		} catch (err) {
			if (!errors.isPromiseCanceledError(err)) {
				console.error(err);
			}
		}

		tokenSource.dispose();
		clearTimeout(timer);

		if (exists) {
			// a file was found matching one of the glob patterns
			return (
				this._activateById(extensionId, new ExtensionActivatedByEvent(true, `workspaceContains:${globPatterns.join(',')}`))
R
Rob Lourens 已提交
586
					.then(undefined, err => console.error(err))
A
Alex Dima 已提交
587 588 589
			);
		}

R
Rob Lourens 已提交
590
		return Promise.resolve(undefined);
A
Alex Dima 已提交
591 592 593
	}

	private _handleExtensionTests(): Promise<void> {
594 595 596 597 598 599 600 601
		return this._doHandleExtensionTests().then(undefined, error => {
			console.error(error); // ensure any error message makes it onto the console

			return Promise.reject(error);
		});
	}

	private _doHandleExtensionTests(): Promise<void> {
A
Alex Dima 已提交
602
		if (!this._initData.environment.extensionTestsPath || !this._initData.environment.extensionDevelopmentLocationURI) {
R
Rob Lourens 已提交
603
			return Promise.resolve(undefined);
A
Alex Dima 已提交
604 605
		}

B
Benjamin Pasero 已提交
606 607 608 609
		if (this._initData.autoStart) {
			return Promise.resolve(undefined); // https://github.com/Microsoft/vscode/issues/66936
		}

A
Alex Dima 已提交
610
		// Require the test runner via node require from the provided path
M
Matt Bierner 已提交
611 612
		let testRunner: ITestRunner | undefined;
		let requireError: Error | undefined;
A
Alex Dima 已提交
613 614 615 616 617 618 619 620 621
		try {
			testRunner = <any>require.__$__nodeRequire(this._initData.environment.extensionTestsPath);
		} catch (error) {
			requireError = error;
		}

		// Execute the runner if it follows our spec
		if (testRunner && typeof testRunner.run === 'function') {
			return new Promise<void>((c, e) => {
M
Matt Bierner 已提交
622
				testRunner!.run(this._initData.environment.extensionTestsPath, (error, failures) => {
A
Alex Dima 已提交
623 624 625
					if (error) {
						e(error.toString());
					} else {
R
Rob Lourens 已提交
626
						c(undefined);
A
Alex Dima 已提交
627 628 629
					}

					// after tests have run, we shutdown the host
630
					this._gracefulExit(error || (typeof failures === 'number' && failures > 0) ? 1 /* ERROR */ : 0 /* OK */);
A
Alex Dima 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
				});
			});
		}

		// Otherwise make sure to shutdown anyway even in case of an error
		else {
			this._gracefulExit(1 /* ERROR */);
		}

		return Promise.reject(new Error(requireError ? requireError.toString() : nls.localize('extensionTestError', "Path {0} does not point to a valid extension test runner.", this._initData.environment.extensionTestsPath)));
	}

	private _gracefulExit(code: number): void {
		// to give the PH process a chance to flush any outstanding console
		// messages to the main process, we delay the exit() by some time
		setTimeout(() => this._nativeExit(code), 500);
	}

J
Johannes Rieken 已提交
649
	private _startExtensionHost(): Promise<void> {
A
Alex Dima 已提交
650 651 652 653 654 655
		if (this._started) {
			throw new Error(`Extension host is already started!`);
		}
		this._started = true;

		return this._barrier.wait()
656 657
			.then(() => this._extHostWorkspace.getWorkspaceProvider())
			.then(workspaceProvider => this._handleEagerExtensions(workspaceProvider))
A
Alex Dima 已提交
658 659 660 661 662 663
			.then(() => this._handleExtensionTests())
			.then(() => {
				this._extHostLogService.info(`eager extensions activated`);
			});
	}

E
Erich Gamma 已提交
664 665
	// -- called by main thread

A
Alex Dima 已提交
666 667 668 669
	public async $resolveAuthority(remoteAuthority: string): Promise<ResolvedAuthority> {
		throw new Error(`Not implemented`);
	}

670
	public $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void> {
A
Alex Dima 已提交
671 672 673 674
		this._registry.keepOnly(enabledExtensionIds);
		return this._startExtensionHost();
	}

J
Johannes Rieken 已提交
675
	public $activateByEvent(activationEvent: string): Promise<void> {
A
Alex Dima 已提交
676 677 678 679
		return (
			this._barrier.wait()
				.then(_ => this._activateByEvent(activationEvent, false))
		);
680
	}
681

682 683 684 685 686 687 688 689
	public async $activate(extensionId: ExtensionIdentifier, activationEvent: string): Promise<boolean> {
		await this._barrier.wait();
		if (!this._registry.getExtensionDescription(extensionId)) {
			// unknown extension => ignore
			return false;
		}
		await this._activateById(extensionId, new ExtensionActivatedByEvent(false, activationEvent));
		return true;
690 691
	}

692
	public async $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> {
693
		toAdd.forEach((extension) => (<any>extension).extensionLocation = URI.revive(extension.extensionLocation));
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

		const trie = await this.getExtensionPathIndex();

		await Promise.all(toRemove.map(async (extensionId) => {
			const extensionDescription = this._registry.getExtensionDescription(extensionId);
			if (!extensionDescription) {
				return;
			}
			const realpath = await pfs.realpath(extensionDescription.extensionLocation.fsPath);
			trie.delete(URI.file(realpath).fsPath);
		}));

		await Promise.all(toAdd.map(async (extensionDescription) => {
			const realpath = await pfs.realpath(extensionDescription.extensionLocation.fsPath);
			trie.set(URI.file(realpath).fsPath, extensionDescription);
		}));

711
		this._registry.deltaExtensions(toAdd, toRemove);
712 713 714
		return Promise.resolve(undefined);
	}

715 716 717 718 719 720 721 722 723 724 725 726 727
	public async $test_latency(n: number): Promise<number> {
		return n;
	}

	public async $test_up(b: Buffer): Promise<number> {
		return b.length;
	}

	public async $test_down(size: number): Promise<Buffer> {
		let b = Buffer.alloc(size, Math.random() % 256);
		return b;
	}

728 729
}

730
function loadCommonJSModule<T>(logService: ILogService, modulePath: string, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
731
	let r: T | null = null;
732
	activationTimesBuilder.codeLoadingStart();
733
	logService.info(`ExtensionService#loadCommonJSModule ${modulePath}`);
E
Erich Gamma 已提交
734 735
	try {
		r = require.__$__nodeRequire<T>(modulePath);
B
Benjamin Pasero 已提交
736
	} catch (e) {
737
		return Promise.reject(e);
738 739
	} finally {
		activationTimesBuilder.codeLoadingStop();
E
Erich Gamma 已提交
740
	}
741
	return Promise.resolve(r);
E
Erich Gamma 已提交
742
}
A
Alex Dima 已提交
743

R
Rob Lourens 已提交
744 745 746 747 748
function getTelemetryActivationEvent(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): any {
	const reasonStr = reason instanceof ExtensionActivatedByEvent ? reason.activationEvent :
		reason instanceof ExtensionActivatedByAPI ? 'api' :
			'';

K
kieferrm 已提交
749
	/* __GDPR__FRAGMENT__
K
kieferrm 已提交
750 751 752
		"TelemetryActivationEvent" : {
			"id": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
			"name": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
C
Christof Marti 已提交
753
			"extensionVersion": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
754
			"publisherDisplayName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
K
kieferrm 已提交
755
			"activationEvents": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
R
Rob Lourens 已提交
756 757
			"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
			"reason": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
K
kieferrm 已提交
758 759
		}
	*/
A
Alex Dima 已提交
760
	let event = {
761
		id: extensionDescription.identifier.value,
A
Alex Dima 已提交
762
		name: extensionDescription.name,
C
Christof Marti 已提交
763
		extensionVersion: extensionDescription.version,
764
		publisherDisplayName: extensionDescription.publisher,
765
		activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
R
Rob Lourens 已提交
766 767
		isBuiltin: extensionDescription.isBuiltin,
		reason: reasonStr
A
Alex Dima 已提交
768 769 770
	};

	return event;
771
}