extHostExtensionService.ts 30.0 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';
8
import { originalFSPath } from 'vs/base/common/resources';
A
Alex Dima 已提交
9
import { Barrier } from 'vs/base/common/async';
A
Alex Dima 已提交
10
import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
11
import { TernarySearchTree } from 'vs/base/common/map';
E
Erich Gamma 已提交
12
import Severity from 'vs/base/common/severity';
A
Alex Dima 已提交
13
import { URI } from 'vs/base/common/uri';
A
Alex Dima 已提交
14
import * as pfs from 'vs/base/node/pfs';
A
Alex Dima 已提交
15
import { ILogService } from 'vs/platform/log/common/log';
A
Alex Dima 已提交
16
import { createApiFactory, initializeExtensionApi, IExtensionApiFactory } from 'vs/workbench/api/node/extHost.api.impl';
17
import { ExtHostExtensionServiceShape, IEnvironment, IInitData, IMainContext, MainContext, MainThreadExtensionServiceShape, MainThreadTelemetryShape, MainThreadWorkspaceShape, IStaticWorkspaceData } from 'vs/workbench/api/node/extHost.protocol';
18
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
19
import { ActivatedExtension, EmptyExtension, ExtensionActivatedByAPI, ExtensionActivatedByEvent, ExtensionActivationReason, ExtensionActivationTimes, ExtensionActivationTimesBuilder, ExtensionsActivator, IExtensionAPI, IExtensionContext, IExtensionMemento, IExtensionModule, HostExtension } from 'vs/workbench/api/node/extHostExtensionActivator';
20
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
A
Alex Dima 已提交
21
import { ExtHostStorage } from 'vs/workbench/api/node/extHostStorage';
22
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
S
Sandeep Somavarapu 已提交
23
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
A
Alex Dima 已提交
24
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/node/extensionDescriptionRegistry';
25
import { connectProxyResolver } from 'vs/workbench/services/extensions/node/proxyResolver';
A
Alex Dima 已提交
26 27 28
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 已提交
29
import * as vscode from 'vscode';
30
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
31
import { IWorkspace } from 'vs/platform/workspace/common/workspace';
32
import { Schemas } from 'vs/base/common/network';
A
Alex Dima 已提交
33

A
Alex Dima 已提交
34
class ExtensionMemento implements IExtensionMemento {
A
Alex Dima 已提交
35

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

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

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

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

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

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

85 86
class ExtensionStoragePath {

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

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

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

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

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

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

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

		if (exists) {
			return storagePath;
		}

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

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

A
Alex Dima 已提交
151
export class ExtHostExtensionService implements ExtHostExtensionServiceShape {
A
Alex Dima 已提交
152

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

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

A
Alex Dima 已提交
177 178 179 180 181
	private _started: boolean;

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

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

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

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

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

A
Alex Dima 已提交
240 241
		this._started = false;

242
		this._initialize();
A
Alex Dima 已提交
243 244 245 246

		if (this._initData.autoStart) {
			this._startExtensionHost();
		}
247 248
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return result;
370
	}
E
Erich Gamma 已提交
371

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

A
Alex Dima 已提交
376
	// --- impl
A
Alex Dima 已提交
377

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

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

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

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

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

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

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

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

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

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

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

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

A
Alex Dima 已提交
496 497 498
	// -- eager activation

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

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

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

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

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

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

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

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

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

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

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

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

		return undefined;
	}

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

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

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

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

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

	private _handleExtensionTests(): Promise<void> {
605 606 607 608 609 610 611 612
		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> {
613 614
		const { extensionDevelopmentLocationURI, extensionTestsLocationURI } = this._initData.environment;
		if (!(extensionDevelopmentLocationURI && extensionTestsLocationURI && extensionTestsLocationURI.scheme === Schemas.file)) {
R
Rob Lourens 已提交
615
			return Promise.resolve(undefined);
A
Alex Dima 已提交
616 617
		}

618
		const extensionTestsPath = originalFSPath(extensionTestsLocationURI);
B
Benjamin Pasero 已提交
619

A
Alex Dima 已提交
620
		// Require the test runner via node require from the provided path
M
Matt Bierner 已提交
621 622
		let testRunner: ITestRunner | undefined;
		let requireError: Error | undefined;
A
Alex Dima 已提交
623
		try {
624
			testRunner = <any>require.__$__nodeRequire(extensionTestsPath);
A
Alex Dima 已提交
625 626 627 628 629 630 631
		} catch (error) {
			requireError = error;
		}

		// Execute the runner if it follows our spec
		if (testRunner && typeof testRunner.run === 'function') {
			return new Promise<void>((c, e) => {
632
				testRunner!.run(extensionTestsPath, (error, failures) => {
A
Alex Dima 已提交
633 634 635
					if (error) {
						e(error.toString());
					} else {
R
Rob Lourens 已提交
636
						c(undefined);
A
Alex Dima 已提交
637 638 639
					}

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

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

650
		return Promise.reject(new Error(requireError ? requireError.toString() : nls.localize('extensionTestError', "Path {0} does not point to a valid extension test runner.", extensionTestsPath)));
A
Alex Dima 已提交
651 652 653 654 655 656 657 658
	}

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

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

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

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

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

A
Alex Dima 已提交
684
	public async $resolveAuthority(remoteAuthority: string): Promise<ResolvedAuthority> {
A
Alex Dima 已提交
685 686 687 688 689 690
		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 已提交
691
		await this._almostReadyToRunExtensions.wait();
A
Alex Dima 已提交
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
		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 已提交
707 708
	}

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

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

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

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

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

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

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

767 768
}

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

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

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

	return event;
810
}