extHostExtensionService.ts 27.5 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 7
import * as nls from 'vs/nls';
import * as path from '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 16
import { createApiFactory, initializeExtensionApi, IExtensionApiFactory } from 'vs/workbench/api/node/extHost.api.impl';
import { ExtHostExtensionServiceShape, IEnvironment, IInitData, IMainContext, IWorkspaceData, MainContext, MainThreadExtensionServiceShape, MainThreadTelemetryShape, MainThreadWorkspaceShape } from 'vs/workbench/api/node/extHost.protocol';
17
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
A
Alex Dima 已提交
18
import { ActivatedExtension, EmptyExtension, ExtensionActivatedByAPI, ExtensionActivatedByEvent, ExtensionActivationReason, ExtensionActivationTimes, ExtensionActivationTimesBuilder, ExtensionsActivator, IExtensionAPI, IExtensionContext, IExtensionMemento, IExtensionModule } from 'vs/workbench/api/node/extHostExtensionActivator';
19
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
A
Alex Dima 已提交
20 21
import { ExtHostStorage } from 'vs/workbench/api/node/extHostStorage';
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';
28
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
A
Alex Dima 已提交
29

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

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

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

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

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

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

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

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
class ExtensionStoragePath {

	private readonly _workspace: IWorkspaceData;
	private readonly _environment: IEnvironment;

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

	constructor(workspace: IWorkspaceData, environment: IEnvironment) {
		this._workspace = workspace;
		this._environment = environment;
		this._ready = this._getOrCreateWorkspaceStoragePath().then(value => this._value = value);
	}

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

99
	workspaceValue(extension: IExtensionDescription): string {
100
		if (this._value) {
101
			return path.join(this._value, extension.identifier.value);
102 103 104 105
		}
		return undefined;
	}

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

110 111 112 113 114 115
	private async _getOrCreateWorkspaceStoragePath(): Promise<string> {
		if (!this._workspace) {
			return Promise.resolve(undefined);
		}

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

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

		if (exists) {
			return storagePath;
		}

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

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

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

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

	private _started: boolean;

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

			actualActivateExtension: (extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> => {
				return this._activateExtension(extensionDescription, reason);
			}
		});
		this._extensionPathIndex = null;
216

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

A
Alex Dima 已提交
220 221
		this._started = false;

222
		this._initialize();
A
Alex Dima 已提交
223 224 225 226

		if (this._initData.autoStart) {
			this._startExtensionHost();
		}
227 228
	}

229 230 231 232 233 234 235 236 237 238 239 240
	private async _initialize(): Promise<void> {
		try {
			const configProvider = await this._extHostConfiguration.getConfigProvider();
			await initializeExtensionApi(this, this._extensionApiFactory, this._registry, configProvider);
			// Do this when extension service exists, but extensions are not being activated yet.
			await connectProxyResolver(this._extHostWorkspace, configProvider, this, this._extHostLogService, this._mainThreadTelemetryProxy);
			this._barrier.open();
		} catch (err) {
			errors.onUnexpectedError(err);
		}
	}

A
Alex Dima 已提交
241
	public async deactivateAll(): Promise<void> {
J
Johannes Rieken 已提交
242
		let allPromises: Promise<void>[] = [];
A
Alex Dima 已提交
243 244
		try {
			const allExtensions = this._registry.getAllExtensionDescriptions();
245
			const allExtensionsIds = allExtensions.map(ext => ext.identifier);
A
Alex Dima 已提交
246 247 248 249 250 251 252 253 254
			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;
255 256
	}

257
	public isActivated(extensionId: ExtensionIdentifier): boolean {
A
Alex Dima 已提交
258 259 260 261
		if (this._barrier.isOpen()) {
			return this._activator.isActivated(extensionId);
		}
		return false;
262 263
	}

J
Johannes Rieken 已提交
264
	private _activateByEvent(activationEvent: string, startup: boolean): Promise<void> {
A
Alex Dima 已提交
265
		const reason = new ExtensionActivatedByEvent(startup, activationEvent);
A
Alex Dima 已提交
266
		return this._activator.activateByEvent(activationEvent, reason);
267 268
	}

269
	private _activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
A
Alex Dima 已提交
270
		return this._activator.activateById(extensionId, reason);
271 272
	}

273
	public activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
A
Alex Dima 已提交
274
		return this._activateById(extensionId, reason).then(() => {
275 276 277
			const extension = this._activator.getActivatedExtension(extensionId);
			if (extension.activationFailed) {
				// activation failed => bubble up the error as the promise result
278
				return Promise.reject(extension.activationFailedError);
279
			}
R
Rob Lourens 已提交
280
			return undefined;
281 282 283
		});
	}

A
Alex Dima 已提交
284 285
	public getExtensionRegistry(): Promise<ExtensionDescriptionRegistry> {
		return this._barrier.wait().then(_ => this._registry);
286 287
	}

288
	public getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI {
A
Alex Dima 已提交
289 290 291 292
		if (this._barrier.isOpen()) {
			return this._activator.getActivatedExtension(extensionId).exports;
		} else {
			return null;
E
Erich Gamma 已提交
293 294 295
		}
	}

296
	// create trie to enable fast 'filename -> extension id' look up
297
	public getExtensionPathIndex(): Promise<TernarySearchTree<IExtensionDescription>> {
298
		if (!this._extensionPathIndex) {
299
			const tree = TernarySearchTree.forPaths<IExtensionDescription>();
A
Alex Dima 已提交
300
			const extensions = this._registry.getAllExtensionDescriptions().map(ext => {
301 302 303
				if (!ext.main) {
					return undefined;
				}
A
Alex Dima 已提交
304
				return pfs.realpath(ext.extensionLocation.fsPath).then(value => tree.set(URI.file(value).fsPath, ext));
305
			});
306
			this._extensionPathIndex = Promise.all(extensions).then(() => tree);
307 308 309 310
		}
		return this._extensionPathIndex;
	}

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

A
Alex Dima 已提交
314 315 316 317 318
		if (!this._barrier.isOpen()) {
			return result;
		}

		if (!this._activator.isActivated(extensionId)) {
A
Alex Dima 已提交
319 320 321
			return result;
		}

A
Alex Dima 已提交
322
		let extension = this._activator.getActivatedExtension(extensionId);
A
Alex Dima 已提交
323
		if (!extension) {
324
			return result;
325 326 327 328
		}

		// call deactivate if available
		try {
A
Alex Dima 已提交
329
			if (typeof extension.module.deactivate === 'function') {
R
Rob Lourens 已提交
330
				result = Promise.resolve(extension.module.deactivate()).then(undefined, (err) => {
331
					// TODO: Do something with err if this is not the shutdown case
R
Rob Lourens 已提交
332
					return Promise.resolve(undefined);
333
				});
334
			}
B
Benjamin Pasero 已提交
335
		} catch (err) {
336 337 338 339 340
			// TODO: Do something with err if this is not the shutdown case
		}

		// clean up subscriptions
		try {
J
Joao Moreno 已提交
341
			dispose(extension.subscriptions);
B
Benjamin Pasero 已提交
342
		} catch (err) {
343 344
			// TODO: Do something with err if this is not the shutdown case
		}
345 346

		return result;
347
	}
E
Erich Gamma 已提交
348

349
	public addMessage(extensionId: ExtensionIdentifier, severity: Severity, message: string): void {
A
Alex Dima 已提交
350
		this._mainThreadExtensionsProxy.$addMessage(extensionId, severity, message);
A
Alex Dima 已提交
351 352
	}

A
Alex Dima 已提交
353
	// --- impl
A
Alex Dima 已提交
354

355
	private _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
356
		this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
A
Alex Dima 已提交
357
		return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => {
358
			const activationTimes = activatedExtension.activationTimes;
A
Alex Dima 已提交
359
			let activationEvent = (reason instanceof ExtensionActivatedByEvent ? reason.activationEvent : null);
360
			this._mainThreadExtensionsProxy.$onDidActivateExtension(extensionDescription.identifier, activationTimes.startup, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, activationEvent);
361
			this._logExtensionActivationTimes(extensionDescription, reason, 'success', activationTimes);
A
Alex Dima 已提交
362 363
			return activatedExtension;
		}, (err) => {
364
			this._mainThreadExtensionsProxy.$onExtensionActivationFailed(extensionDescription.identifier);
365
			this._logExtensionActivationTimes(extensionDescription, reason, 'failure');
A
Alex Dima 已提交
366 367
			throw err;
		});
E
Erich Gamma 已提交
368 369
	}

370 371 372 373 374 375 376 377 378 379 380
	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 已提交
381
		this._mainThreadTelemetryProxy.$publicLog('extensionActivationTimes', {
382 383 384 385 386 387
			...event,
			...(activationTimes || {}),
			outcome,
		});
	}

388
	private _doActivateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
R
Rob Lourens 已提交
389
		let event = getTelemetryActivationEvent(extensionDescription, reason);
K
kieferrm 已提交
390
		/* __GDPR__
K
kieferrm 已提交
391 392 393 394 395 396
			"activatePlugin" : {
				"${include}": [
					"${TelemetryActivationEvent}"
				]
			}
		*/
A
Alex Dima 已提交
397
		this._mainThreadTelemetryProxy.$publicLog('activatePlugin', event);
A
Alex Dima 已提交
398 399
		if (!extensionDescription.main) {
			// Treat the extension as being empty => NOT AN ERROR CASE
400
			return Promise.resolve(new EmptyExtension(ExtensionActivationTimes.NONE));
A
Alex Dima 已提交
401
		}
402

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

A
Alex Dima 已提交
405
		const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
406
		return Promise.all<any>([
407
			loadCommonJSModule(this._extHostLogService, extensionDescription.main, activationTimesBuilder),
A
Alex Dima 已提交
408 409
			this._loadExtensionContext(extensionDescription)
		]).then(values => {
410
			return ExtHostExtensionService._callActivate(this._extHostLogService, extensionDescription.identifier, <IExtensionModule>values[0], <IExtensionContext>values[1], activationTimesBuilder);
A
Alex Dima 已提交
411
		});
E
Erich Gamma 已提交
412 413
	}

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

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

419
		this._extHostLogService.trace(`ExtensionService#loadExtensionContext ${extensionDescription.identifier.value}`);
420
		return Promise.all([
421
			globalState.whenReady,
422 423
			workspaceState.whenReady,
			this._storagePath.whenReady
424
		]).then(() => {
425
			const that = this;
A
Alex Dima 已提交
426
			return Object.freeze(<IExtensionContext>{
E
Erich Gamma 已提交
427 428 429
				globalState,
				workspaceState,
				subscriptions: [],
430
				get extensionPath() { return extensionDescription.extensionLocation.fsPath; },
431
				storagePath: this._storagePath.workspaceValue(extensionDescription),
S
Sandeep Somavarapu 已提交
432
				globalStoragePath: this._storagePath.globalValue(extensionDescription),
A
Alex Dima 已提交
433
				asAbsolutePath: (relativePath: string) => { return path.join(extensionDescription.extensionLocation.fsPath, relativePath); },
434
				logPath: that._extHostLogService.getLogDirectory(extensionDescription.identifier)
E
Erich Gamma 已提交
435 436 437 438
			});
		});
	}

439
	private static _callActivate(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<ActivatedExtension> {
A
Alex Dima 已提交
440 441
		// Make sure the extension's surface is not undefined
		extensionModule = extensionModule || {
442 443 444 445
			activate: undefined,
			deactivate: undefined
		};

446
		return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
447
			return new ActivatedExtension(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions);
448 449 450
		});
	}

451
	private static _callActivateOptional(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: IExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<IExtensionAPI> {
A
Alex Dima 已提交
452
		if (typeof extensionModule.activate === 'function') {
453
			try {
454
				activationTimesBuilder.activateCallStart();
455
				logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`);
J
Johannes Rieken 已提交
456
				const activateResult: Promise<IExtensionAPI> = extensionModule.activate.apply(global, [context]);
457 458 459
				activationTimesBuilder.activateCallStop();

				activationTimesBuilder.activateResolveStart();
460
				return Promise.resolve(activateResult).then((value) => {
461 462 463
					activationTimesBuilder.activateResolveStop();
					return value;
				});
464
			} catch (err) {
465
				return Promise.reject(err);
466 467
			}
		} else {
A
Alex Dima 已提交
468
			// No activate found => the module is the extension's exports
469
			return Promise.resolve<IExtensionAPI>(extensionModule);
470 471 472
		}
	}

A
Alex Dima 已提交
473 474 475 476
	// -- eager activation

	// Handle "eager" activation extensions
	private _handleEagerExtensions(): Promise<void> {
R
Rob Lourens 已提交
477
		this._activateByEvent('*', true).then(undefined, (err) => {
A
Alex Dima 已提交
478 479 480 481 482 483 484 485
			console.error(err);
		});

		return this._handleWorkspaceContainsEagerExtensions(this._initData.workspace);
	}

	private _handleWorkspaceContainsEagerExtensions(workspace: IWorkspaceData): Promise<void> {
		if (!workspace || workspace.folders.length === 0) {
R
Rob Lourens 已提交
486
			return Promise.resolve(undefined);
A
Alex Dima 已提交
487 488 489 490 491 492 493 494 495 496 497 498
		}

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

	private _handleWorkspaceContainsEagerExtension(workspace: IWorkspaceData, desc: IExtensionDescription): Promise<void> {
		const activationEvents = desc.activationEvents;
		if (!activationEvents) {
R
Rob Lourens 已提交
499
			return Promise.resolve(undefined);
A
Alex Dima 已提交
500 501 502 503 504
		}

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

505 506 507
		for (const activationEvent of activationEvents) {
			if (/^workspaceContains:/.test(activationEvent)) {
				const fileNameOrGlob = activationEvent.substr('workspaceContains:'.length);
A
Alex Dima 已提交
508 509 510 511 512 513 514 515 516
				if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
					globPatterns.push(fileNameOrGlob);
				} else {
					fileNames.push(fileNameOrGlob);
				}
			}
		}

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

520 521
		const fileNamePromise = Promise.all(fileNames.map((fileName) => this._activateIfFileName(workspace, desc.identifier, fileName))).then(() => { });
		const globPatternPromise = this._activateIfGlobPatterns(desc.identifier, globPatterns);
A
Alex Dima 已提交
522 523 524 525

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

526
	private async _activateIfFileName(workspace: IWorkspaceData, extensionId: ExtensionIdentifier, fileName: string): Promise<void> {
A
Alex Dima 已提交
527 528 529 530 531 532 533

		// 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 已提交
534
						.then(undefined, err => console.error(err))
A
Alex Dima 已提交
535 536 537 538 539 540 541
				);
			}
		}

		return undefined;
	}

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

		if (globPatterns.length === 0) {
R
Rob Lourens 已提交
546
			return Promise.resolve(undefined);
A
Alex Dima 已提交
547 548 549 550 551 552 553 554
		}

		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 已提交
555
				.then(undefined, err => console.error(err));
A
Alex Dima 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
		}, ExtHostExtensionService.WORKSPACE_CONTAINS_TIMEOUT);

		let exists: boolean;
		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 已提交
574
					.then(undefined, err => console.error(err))
A
Alex Dima 已提交
575 576 577
			);
		}

R
Rob Lourens 已提交
578
		return Promise.resolve(undefined);
A
Alex Dima 已提交
579 580 581
	}

	private _handleExtensionTests(): Promise<void> {
582 583 584 585 586 587 588 589
		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 已提交
590
		if (!this._initData.environment.extensionTestsPath || !this._initData.environment.extensionDevelopmentLocationURI) {
R
Rob Lourens 已提交
591
			return Promise.resolve(undefined);
A
Alex Dima 已提交
592 593
		}

B
Benjamin Pasero 已提交
594 595 596 597
		if (this._initData.autoStart) {
			return Promise.resolve(undefined); // https://github.com/Microsoft/vscode/issues/66936
		}

A
Alex Dima 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
		// Require the test runner via node require from the provided path
		let testRunner: ITestRunner;
		let requireError: Error;
		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) => {
				testRunner.run(this._initData.environment.extensionTestsPath, (error, failures) => {
					if (error) {
						e(error.toString());
					} else {
R
Rob Lourens 已提交
614
						c(undefined);
A
Alex Dima 已提交
615 616 617
					}

					// after tests have run, we shutdown the host
618
					this._gracefulExit(error || (typeof failures === 'number' && failures > 0) ? 1 /* ERROR */ : 0 /* OK */);
A
Alex Dima 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
				});
			});
		}

		// 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 已提交
637
	private _startExtensionHost(): Promise<void> {
A
Alex Dima 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650
		if (this._started) {
			throw new Error(`Extension host is already started!`);
		}
		this._started = true;

		return this._barrier.wait()
			.then(() => this._handleEagerExtensions())
			.then(() => this._handleExtensionTests())
			.then(() => {
				this._extHostLogService.info(`eager extensions activated`);
			});
	}

E
Erich Gamma 已提交
651 652
	// -- called by main thread

A
Alex Dima 已提交
653 654 655 656
	public async $resolveAuthority(remoteAuthority: string): Promise<ResolvedAuthority> {
		throw new Error(`Not implemented`);
	}

657
	public $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void> {
A
Alex Dima 已提交
658 659 660 661
		this._registry.keepOnly(enabledExtensionIds);
		return this._startExtensionHost();
	}

J
Johannes Rieken 已提交
662
	public $activateByEvent(activationEvent: string): Promise<void> {
A
Alex Dima 已提交
663 664 665 666
		return (
			this._barrier.wait()
				.then(_ => this._activateByEvent(activationEvent, false))
		);
667
	}
668

669 670 671 672 673 674 675
	public $activate(extensionId: ExtensionIdentifier, activationEvent: string): Promise<void> {
		return (
			this._barrier.wait()
				.then(_ => this._activateById(extensionId, new ExtensionActivatedByEvent(false, activationEvent)))
		);
	}

676
	public async $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> {
677
		toAdd.forEach((extension) => (<any>extension).extensionLocation = URI.revive(extension.extensionLocation));
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694

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

695
		this._registry.deltaExtensions(toAdd, toRemove);
696 697 698
		return Promise.resolve(undefined);
	}

699 700 701 702 703 704 705 706 707 708 709 710 711
	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;
	}

712 713
}

714
function loadCommonJSModule<T>(logService: ILogService, modulePath: string, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T> {
715
	let r: T | null = null;
716
	activationTimesBuilder.codeLoadingStart();
717
	logService.info(`ExtensionService#loadCommonJSModule ${modulePath}`);
E
Erich Gamma 已提交
718 719
	try {
		r = require.__$__nodeRequire<T>(modulePath);
B
Benjamin Pasero 已提交
720
	} catch (e) {
721
		return Promise.reject(e);
722 723
	} finally {
		activationTimesBuilder.codeLoadingStop();
E
Erich Gamma 已提交
724
	}
725
	return Promise.resolve(r);
E
Erich Gamma 已提交
726
}
A
Alex Dima 已提交
727

R
Rob Lourens 已提交
728 729 730 731 732
function getTelemetryActivationEvent(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): any {
	const reasonStr = reason instanceof ExtensionActivatedByEvent ? reason.activationEvent :
		reason instanceof ExtensionActivatedByAPI ? 'api' :
			'';

K
kieferrm 已提交
733
	/* __GDPR__FRAGMENT__
K
kieferrm 已提交
734 735 736
		"TelemetryActivationEvent" : {
			"id": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
			"name": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
C
Christof Marti 已提交
737
			"extensionVersion": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
738
			"publisherDisplayName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
K
kieferrm 已提交
739
			"activationEvents": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
R
Rob Lourens 已提交
740 741
			"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
			"reason": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
K
kieferrm 已提交
742 743
		}
	*/
A
Alex Dima 已提交
744
	let event = {
745
		id: extensionDescription.identifier.value,
A
Alex Dima 已提交
746
		name: extensionDescription.name,
C
Christof Marti 已提交
747
		extensionVersion: extensionDescription.version,
748
		publisherDisplayName: extensionDescription.publisher,
749
		activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
R
Rob Lourens 已提交
750 751
		isBuiltin: extensionDescription.isBuiltin,
		reason: reasonStr
A
Alex Dima 已提交
752 753 754
	};

	return event;
755
}