extHostExtensionService.ts 29.9 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
import { Barrier } from 'vs/base/common/async';
A
Alex Dima 已提交
9
import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
10
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 } 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';
A
Alex Dima 已提交
28
import * as vscode from 'vscode';
29
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
30
import { IWorkspace } from 'vs/platform/workspace/common/workspace';
A
Alex Dima 已提交
31

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

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

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

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

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

J
Johannes Rieken 已提交
59
	get whenReady(): Promise<ExtensionMemento> {
A
Alex Dima 已提交
60 61 62 63 64 65 66 67 68 69 70
		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 已提交
71
	update(key: string, value: any): Promise<boolean> {
A
Alex Dima 已提交
72 73 74 75 76
		this._value[key] = value;
		return this._storage
			.setValue(this._shared, this._id, this._value)
			.then(() => true);
	}
77 78 79 80

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

83 84
class ExtensionStoragePath {

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

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

M
Matt Bierner 已提交
91
	constructor(workspace: IStaticWorkspaceData | undefined, environment: IEnvironment) {
92 93 94 95 96 97 98 99 100
		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 已提交
101
	workspaceValue(extension: IExtensionDescription): string | undefined {
102
		if (this._value) {
103
			return path.join(this._value, extension.identifier.value);
104 105 106 107
		}
		return undefined;
	}

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

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

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

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

		if (exists) {
			return storagePath;
		}

		try {
A
Alex Dima 已提交
127 128 129
			await pfs.mkdirp(storagePath);
			await pfs.writeFile(
				path.join(storagePath, 'meta.json'),
130 131 132 133 134 135 136 137 138 139 140 141 142 143
				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 已提交
144 145 146 147 148

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

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

A
Alex Dima 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163
	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 已提交
164
	private readonly _almostReadyToRunExtensions: Barrier;
A
Alex Dima 已提交
165
	private readonly _readyToRunExtensions: Barrier;
A
Alex Dima 已提交
166 167
	private readonly _registry: ExtensionDescriptionRegistry;
	private readonly _storage: ExtHostStorage;
168
	private readonly _storagePath: ExtensionStoragePath;
A
Alex Dima 已提交
169
	private readonly _activator: ExtensionsActivator;
A
Alex Dima 已提交
170
	private _extensionPathIndex: Promise<TernarySearchTree<IExtensionDescription>> | null;
A
Alex Dima 已提交
171 172
	private readonly _extensionApiFactory: IExtensionApiFactory;

A
Alex Dima 已提交
173 174
	private readonly _resolvers: { [authorityPrefix: string]: vscode.RemoteAuthorityResolver; };

A
Alex Dima 已提交
175 176 177 178 179
	private _started: boolean;

	constructor(
		nativeExit: (code?: number) => void,
		initData: IInitData,
180
		extHostContext: IMainContext,
181
		extHostWorkspace: ExtHostWorkspace,
J
Joao Moreno 已提交
182
		extHostConfiguration: ExtHostConfiguration,
A
Alex Dima 已提交
183
		extHostLogService: ExtHostLogService
184
	) {
A
Alex Dima 已提交
185 186 187 188 189 190 191 192 193 194 195
		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 已提交
196
		this._almostReadyToRunExtensions = new Barrier();
A
Alex Dima 已提交
197
		this._readyToRunExtensions = new Barrier();
A
Alex Dima 已提交
198
		this._registry = new ExtensionDescriptionRegistry(initData.extensions);
A
Alex Dima 已提交
199
		this._storage = new ExtHostStorage(this._extHostContext);
200
		this._storagePath = new ExtensionStoragePath(initData.workspace, initData.environment);
201 202 203 204 205

		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 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
			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);
				}
			},

221 222 223 224 225 226
			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();
				}
A
Alex Dima 已提交
227
				const extensionDescription = this._registry.getExtensionDescription(extensionId)!;
A
Alex Dima 已提交
228 229 230 231
				return this._activateExtension(extensionDescription, reason);
			}
		});
		this._extensionPathIndex = null;
232

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

A
Alex Dima 已提交
236 237
		this._resolvers = Object.create(null);

A
Alex Dima 已提交
238 239
		this._started = false;

240
		this._initialize();
A
Alex Dima 已提交
241 242 243 244

		if (this._initData.autoStart) {
			this._startExtensionHost();
		}
245 246
	}

247 248 249
	private async _initialize(): Promise<void> {
		try {
			const configProvider = await this._extHostConfiguration.getConfigProvider();
250
			await initializeExtensionApi(this, this._extensionApiFactory, this._registry, configProvider);
251
			// Do this when extension service exists, but extensions are not being activated yet.
252
			await connectProxyResolver(this._extHostWorkspace, configProvider, this, this._extHostLogService, this._mainThreadTelemetryProxy);
A
Alex Dima 已提交
253 254 255
			this._almostReadyToRunExtensions.open();

			await this._extHostWorkspace.waitForInitializeCall();
A
Alex Dima 已提交
256
			this._readyToRunExtensions.open();
257 258 259 260 261
		} catch (err) {
			errors.onUnexpectedError(err);
		}
	}

A
Alex Dima 已提交
262
	public async deactivateAll(): Promise<void> {
J
Johannes Rieken 已提交
263
		let allPromises: Promise<void>[] = [];
A
Alex Dima 已提交
264 265
		try {
			const allExtensions = this._registry.getAllExtensionDescriptions();
266
			const allExtensionsIds = allExtensions.map(ext => ext.identifier);
A
Alex Dima 已提交
267 268 269 270 271 272 273 274 275
			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;
276 277
	}

278
	public isActivated(extensionId: ExtensionIdentifier): boolean {
A
Alex Dima 已提交
279
		if (this._readyToRunExtensions.isOpen()) {
A
Alex Dima 已提交
280 281 282
			return this._activator.isActivated(extensionId);
		}
		return false;
283 284
	}

J
Johannes Rieken 已提交
285
	private _activateByEvent(activationEvent: string, startup: boolean): Promise<void> {
A
Alex Dima 已提交
286
		const reason = new ExtensionActivatedByEvent(startup, activationEvent);
A
Alex Dima 已提交
287
		return this._activator.activateByEvent(activationEvent, reason);
288 289
	}

290
	private _activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
A
Alex Dima 已提交
291
		return this._activator.activateById(extensionId, reason);
292 293
	}

294
	public activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
A
Alex Dima 已提交
295
		return this._activateById(extensionId, reason).then(() => {
296 297 298
			const extension = this._activator.getActivatedExtension(extensionId);
			if (extension.activationFailed) {
				// activation failed => bubble up the error as the promise result
299
				return Promise.reject(extension.activationFailedError);
300
			}
R
Rob Lourens 已提交
301
			return undefined;
302 303 304
		});
	}

A
Alex Dima 已提交
305
	public getExtensionRegistry(): Promise<ExtensionDescriptionRegistry> {
A
Alex Dima 已提交
306
		return this._readyToRunExtensions.wait().then(_ => this._registry);
307 308
	}

A
Alex Dima 已提交
309
	public getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined {
A
Alex Dima 已提交
310
		if (this._readyToRunExtensions.isOpen()) {
A
Alex Dima 已提交
311 312 313
			return this._activator.getActivatedExtension(extensionId).exports;
		} else {
			return null;
E
Erich Gamma 已提交
314 315 316
		}
	}

317
	// create trie to enable fast 'filename -> extension id' look up
318
	public getExtensionPathIndex(): Promise<TernarySearchTree<IExtensionDescription>> {
319
		if (!this._extensionPathIndex) {
320
			const tree = TernarySearchTree.forPaths<IExtensionDescription>();
A
Alex Dima 已提交
321
			const extensions = this._registry.getAllExtensionDescriptions().map(ext => {
322 323 324
				if (!ext.main) {
					return undefined;
				}
A
Alex Dima 已提交
325
				return pfs.realpath(ext.extensionLocation.fsPath).then(value => tree.set(URI.file(value).fsPath, ext));
326
			});
327
			this._extensionPathIndex = Promise.all(extensions).then(() => tree);
328 329 330 331
		}
		return this._extensionPathIndex;
	}

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

A
Alex Dima 已提交
335
		if (!this._readyToRunExtensions.isOpen()) {
A
Alex Dima 已提交
336 337 338 339
			return result;
		}

		if (!this._activator.isActivated(extensionId)) {
A
Alex Dima 已提交
340 341 342
			return result;
		}

A
Alex Dima 已提交
343
		let extension = this._activator.getActivatedExtension(extensionId);
A
Alex Dima 已提交
344
		if (!extension) {
345
			return result;
346 347 348 349
		}

		// call deactivate if available
		try {
A
Alex Dima 已提交
350
			if (typeof extension.module.deactivate === 'function') {
R
Rob Lourens 已提交
351
				result = Promise.resolve(extension.module.deactivate()).then(undefined, (err) => {
352
					// TODO: Do something with err if this is not the shutdown case
R
Rob Lourens 已提交
353
					return Promise.resolve(undefined);
354
				});
355
			}
B
Benjamin Pasero 已提交
356
		} catch (err) {
357 358 359 360 361
			// TODO: Do something with err if this is not the shutdown case
		}

		// clean up subscriptions
		try {
J
Joao Moreno 已提交
362
			dispose(extension.subscriptions);
B
Benjamin Pasero 已提交
363
		} catch (err) {
364 365
			// TODO: Do something with err if this is not the shutdown case
		}
366 367

		return result;
368
	}
E
Erich Gamma 已提交
369

370
	public addMessage(extensionId: ExtensionIdentifier, severity: Severity, message: string): void {
A
Alex Dima 已提交
371
		this._mainThreadExtensionsProxy.$addMessage(extensionId, severity, message);
A
Alex Dima 已提交
372 373
	}

A
Alex Dima 已提交
374
	// --- impl
A
Alex Dima 已提交
375

376
	private _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
377
		this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
A
Alex Dima 已提交
378
		return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => {
379
			const activationTimes = activatedExtension.activationTimes;
A
Alex Dima 已提交
380
			let activationEvent = (reason instanceof ExtensionActivatedByEvent ? reason.activationEvent : null);
381
			this._mainThreadExtensionsProxy.$onDidActivateExtension(extensionDescription.identifier, activationTimes.startup, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, activationEvent);
382
			this._logExtensionActivationTimes(extensionDescription, reason, 'success', activationTimes);
A
Alex Dima 已提交
383 384
			return activatedExtension;
		}, (err) => {
385
			this._mainThreadExtensionsProxy.$onExtensionActivationFailed(extensionDescription.identifier);
386
			this._logExtensionActivationTimes(extensionDescription, reason, 'failure');
A
Alex Dima 已提交
387 388
			throw err;
		});
E
Erich Gamma 已提交
389 390
	}

391 392 393 394 395 396 397 398 399 400 401
	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 已提交
402
		this._mainThreadTelemetryProxy.$publicLog('extensionActivationTimes', {
403 404 405 406 407 408
			...event,
			...(activationTimes || {}),
			outcome,
		});
	}

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

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

A
Alex Dima 已提交
426
		const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
427
		return Promise.all<any>([
428
			loadCommonJSModule(this._extHostLogService, extensionDescription.main, activationTimesBuilder),
A
Alex Dima 已提交
429 430
			this._loadExtensionContext(extensionDescription)
		]).then(values => {
431
			return ExtHostExtensionService._callActivate(this._extHostLogService, extensionDescription.identifier, <IExtensionModule>values[0], <IExtensionContext>values[1], activationTimesBuilder);
A
Alex Dima 已提交
432
		});
E
Erich Gamma 已提交
433 434
	}

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

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

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

460
	private static _callActivate(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<ActivatedExtension> {
A
Alex Dima 已提交
461 462
		// Make sure the extension's surface is not undefined
		extensionModule = extensionModule || {
463 464 465 466
			activate: undefined,
			deactivate: undefined
		};

467
		return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
468
			return new ActivatedExtension(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions);
469 470 471
		});
	}

472
	private static _callActivateOptional(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<IExtensionAPI> {
A
Alex Dima 已提交
473
		if (typeof extensionModule.activate === 'function') {
474
			try {
475
				activationTimesBuilder.activateCallStart();
476
				logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`);
J
Johannes Rieken 已提交
477
				const activateResult: Promise<IExtensionAPI> = extensionModule.activate.apply(global, [context]);
478 479 480
				activationTimesBuilder.activateCallStop();

				activationTimesBuilder.activateResolveStart();
481
				return Promise.resolve(activateResult).then((value) => {
482 483 484
					activationTimesBuilder.activateResolveStop();
					return value;
				});
485
			} catch (err) {
486
				return Promise.reject(err);
487 488
			}
		} else {
A
Alex Dima 已提交
489
			// No activate found => the module is the extension's exports
490
			return Promise.resolve<IExtensionAPI>(extensionModule);
491 492 493
		}
	}

A
Alex Dima 已提交
494 495 496
	// -- eager activation

	// Handle "eager" activation extensions
497
	private _handleEagerExtensions(): Promise<void> {
R
Rob Lourens 已提交
498
		this._activateByEvent('*', true).then(undefined, (err) => {
A
Alex Dima 已提交
499 500 501
			console.error(err);
		});

502
		return this._handleWorkspaceContainsEagerExtensions(this._extHostWorkspace.workspace);
A
Alex Dima 已提交
503 504
	}

M
Matt Bierner 已提交
505
	private _handleWorkspaceContainsEagerExtensions(workspace: IWorkspace | undefined): Promise<void> {
A
Alex Dima 已提交
506
		if (!workspace || workspace.folders.length === 0) {
R
Rob Lourens 已提交
507
			return Promise.resolve(undefined);
A
Alex Dima 已提交
508 509 510 511 512 513 514 515 516
		}

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

517
	private _handleWorkspaceContainsEagerExtension(workspace: IWorkspace, desc: IExtensionDescription): Promise<void> {
A
Alex Dima 已提交
518 519
		const activationEvents = desc.activationEvents;
		if (!activationEvents) {
R
Rob Lourens 已提交
520
			return Promise.resolve(undefined);
A
Alex Dima 已提交
521 522 523 524 525
		}

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

526 527 528
		for (const activationEvent of activationEvents) {
			if (/^workspaceContains:/.test(activationEvent)) {
				const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
A
Alex Dima 已提交
529 530 531 532 533 534 535 536 537
				if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
					globPatterns.push(fileNameOrGlob);
				} else {
					fileNames.push(fileNameOrGlob);
				}
			}
		}

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

541 542
		const fileNamePromise = Promise.all(fileNames.map((fileName) => this._activateIfFileName(workspace, desc.identifier, fileName))).then(() => { });
		const globPatternPromise = this._activateIfGlobPatterns(desc.identifier, globPatterns);
A
Alex Dima 已提交
543 544 545 546

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

547
	private async _activateIfFileName(workspace: IWorkspace, extensionId: ExtensionIdentifier, fileName: string): Promise<void> {
A
Alex Dima 已提交
548 549 550 551 552 553 554

		// 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 已提交
555
						.then(undefined, err => console.error(err))
A
Alex Dima 已提交
556 557 558 559 560 561 562
				);
			}
		}

		return undefined;
	}

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

		if (globPatterns.length === 0) {
R
Rob Lourens 已提交
567
			return Promise.resolve(undefined);
A
Alex Dima 已提交
568 569 570 571 572 573 574 575
		}

		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 已提交
576
				.then(undefined, err => console.error(err));
A
Alex Dima 已提交
577 578
		}, ExtHostExtensionService.WORKSPACE_CONTAINS_TIMEOUT);

M
Matt Bierner 已提交
579
		let exists: boolean = false;
A
Alex Dima 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
		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 已提交
595
					.then(undefined, err => console.error(err))
A
Alex Dima 已提交
596 597 598
			);
		}

R
Rob Lourens 已提交
599
		return Promise.resolve(undefined);
A
Alex Dima 已提交
600 601 602
	}

	private _handleExtensionTests(): Promise<void> {
603 604 605 606 607 608 609 610
		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 已提交
611
		if (!this._initData.environment.extensionTestsPath || !this._initData.environment.extensionDevelopmentLocationURI) {
R
Rob Lourens 已提交
612
			return Promise.resolve(undefined);
A
Alex Dima 已提交
613 614
		}

B
Benjamin Pasero 已提交
615 616 617 618
		if (this._initData.autoStart) {
			return Promise.resolve(undefined); // https://github.com/Microsoft/vscode/issues/66936
		}

A
Alex Dima 已提交
619
		// Require the test runner via node require from the provided path
M
Matt Bierner 已提交
620 621
		let testRunner: ITestRunner | undefined;
		let requireError: Error | undefined;
A
Alex Dima 已提交
622 623 624 625 626 627 628 629 630
		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) => {
A
Alex Dima 已提交
631
				testRunner!.run(this._initData.environment.extensionTestsPath!, (error, failures) => {
A
Alex Dima 已提交
632 633 634
					if (error) {
						e(error.toString());
					} else {
R
Rob Lourens 已提交
635
						c(undefined);
A
Alex Dima 已提交
636 637 638
					}

					// after tests have run, we shutdown the host
639
					this._gracefulExit(error || (typeof failures === 'number' && failures > 0) ? 1 /* ERROR */ : 0 /* OK */);
A
Alex Dima 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
				});
			});
		}

		// 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 已提交
658
	private _startExtensionHost(): Promise<void> {
A
Alex Dima 已提交
659 660 661 662 663
		if (this._started) {
			throw new Error(`Extension host is already started!`);
		}
		this._started = true;

A
Alex Dima 已提交
664
		return this._readyToRunExtensions.wait()
665
			.then(() => this._handleEagerExtensions())
A
Alex Dima 已提交
666 667 668 669 670 671
			.then(() => this._handleExtensionTests())
			.then(() => {
				this._extHostLogService.info(`eager extensions activated`);
			});
	}

A
Alex Dima 已提交
672 673 674 675 676
	// -- called by extensions

	public registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable {
		this._resolvers[authorityPrefix] = resolver;
		return toDisposable(() => {
A
Alex Dima 已提交
677
			delete this._resolvers[authorityPrefix];
A
Alex Dima 已提交
678 679 680
		});
	}

E
Erich Gamma 已提交
681 682
	// -- called by main thread

A
Alex Dima 已提交
683
	public async $resolveAuthority(remoteAuthority: string): Promise<ResolvedAuthority> {
A
Alex Dima 已提交
684 685 686 687 688 689
		const authorityPlusIndex = remoteAuthority.indexOf('+');
		if (authorityPlusIndex === -1) {
			throw new Error(`Not an authority that can be resolved!`);
		}
		const authorityPrefix = remoteAuthority.substr(0, authorityPlusIndex);

A
Alex Dima 已提交
690
		await this._almostReadyToRunExtensions.wait();
A
Alex Dima 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
		await this._activateByEvent(`onResolveRemoteAuthority:${authorityPrefix}`, false);

		const resolver = this._resolvers[authorityPrefix];
		if (!resolver) {
			throw new Error(`No resolver available for ${authorityPrefix}`);
		}

		const result = await resolver.resolve(remoteAuthority);
		return {
			authority: remoteAuthority,
			host: result.host,
			port: result.port,
			debugListenPort: result.debugListenPort,
			debugConnectPort: result.debugConnectPort,
		};
A
Alex Dima 已提交
706 707
	}

708
	public $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void> {
A
Alex Dima 已提交
709 710 711 712
		this._registry.keepOnly(enabledExtensionIds);
		return this._startExtensionHost();
	}

J
Johannes Rieken 已提交
713
	public $activateByEvent(activationEvent: string): Promise<void> {
A
Alex Dima 已提交
714
		return (
A
Alex Dima 已提交
715
			this._readyToRunExtensions.wait()
A
Alex Dima 已提交
716 717
				.then(_ => this._activateByEvent(activationEvent, false))
		);
718
	}
719

720
	public async $activate(extensionId: ExtensionIdentifier, activationEvent: string): Promise<boolean> {
A
Alex Dima 已提交
721
		await this._readyToRunExtensions.wait();
722 723 724 725 726 727
		if (!this._registry.getExtensionDescription(extensionId)) {
			// unknown extension => ignore
			return false;
		}
		await this._activateById(extensionId, new ExtensionActivatedByEvent(false, activationEvent));
		return true;
728 729
	}

730
	public async $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> {
731
		toAdd.forEach((extension) => (<any>extension).extensionLocation = URI.revive(extension.extensionLocation));
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

		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);
		}));

749
		this._registry.deltaExtensions(toAdd, toRemove);
750 751 752
		return Promise.resolve(undefined);
	}

753 754 755 756 757 758 759 760 761 762 763 764 765
	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;
	}

766 767
}

768
function loadCommonJSModule<T>(logService: ILogService, modulePath: string, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
769
	let r: T | null = null;
770
	activationTimesBuilder.codeLoadingStart();
771
	logService.info(`ExtensionService#loadCommonJSModule ${modulePath}`);
E
Erich Gamma 已提交
772 773
	try {
		r = require.__$__nodeRequire<T>(modulePath);
B
Benjamin Pasero 已提交
774
	} catch (e) {
775
		return Promise.reject(e);
776 777
	} finally {
		activationTimesBuilder.codeLoadingStop();
E
Erich Gamma 已提交
778
	}
779
	return Promise.resolve(r);
E
Erich Gamma 已提交
780
}
A
Alex Dima 已提交
781

R
Rob Lourens 已提交
782 783 784 785 786
function getTelemetryActivationEvent(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): any {
	const reasonStr = reason instanceof ExtensionActivatedByEvent ? reason.activationEvent :
		reason instanceof ExtensionActivatedByAPI ? 'api' :
			'';

K
kieferrm 已提交
787
	/* __GDPR__FRAGMENT__
K
kieferrm 已提交
788 789 790
		"TelemetryActivationEvent" : {
			"id": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
			"name": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
C
Christof Marti 已提交
791
			"extensionVersion": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
792
			"publisherDisplayName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
K
kieferrm 已提交
793
			"activationEvents": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
R
Rob Lourens 已提交
794 795
			"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
			"reason": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
K
kieferrm 已提交
796 797
		}
	*/
A
Alex Dima 已提交
798
	let event = {
799
		id: extensionDescription.identifier.value,
A
Alex Dima 已提交
800
		name: extensionDescription.name,
C
Christof Marti 已提交
801
		extensionVersion: extensionDescription.version,
802
		publisherDisplayName: extensionDescription.publisher,
803
		activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
R
Rob Lourens 已提交
804 805
		isBuiltin: extensionDescription.isBuiltin,
		reason: reasonStr
A
Alex Dima 已提交
806 807 808
	};

	return event;
809
}