-
Notifications
You must be signed in to change notification settings - Fork 28k
/
abstractExtensionService.ts
1592 lines (1344 loc) · 66.7 KB
/
abstractExtensionService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { Barrier } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import * as perf from 'vs/base/common/performance';
import { isEqualOrParent } from 'vs/base/common/resources';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IWorkbenchExtensionEnablementService, IWorkbenchExtensionManagementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ActivationTimes, ExtensionPointContribution, IExtensionService, IExtensionsStatus, IMessage, IWillActivateEvent, IResponsiveStateChangeEvent, toExtension, IExtensionHost, ActivationKind, ExtensionHostKind, ExtensionRunningLocation, extensionHostKindToString, ExtensionActivationReason, IInternalExtensionService, RemoteRunningLocation, LocalProcessRunningLocation, LocalWebWorkerRunningLocation } from 'vs/workbench/services/extensions/common/extensions';
import { ExtensionMessageCollector, ExtensionPoint, ExtensionsRegistry, IExtensionPoint, IExtensionPointUser } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
import { ResponsiveState } from 'vs/workbench/services/extensions/common/rpcProtocol';
import { createExtensionHostManager, IExtensionHostManager } from 'vs/workbench/services/extensions/common/extensionHostManager';
import { ExtensionIdentifier, IExtensionDescription, IExtension, IExtensionContributions } from 'vs/platform/extensions/common/extensions';
import { ExtensionKind } from 'vs/platform/environment/common/environment';
import { IFileService } from 'vs/platform/files/common/files';
import { parseExtensionDevOptions } from 'vs/workbench/services/extensions/common/extensionDevOptions';
import { IProductService } from 'vs/platform/product/common/productService';
import { InstallOperation } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IExtensionActivationHost as IWorkspaceContainsActivationHost, checkGlobFileExists, checkActivateWorkspaceContainsExtension } from 'vs/workbench/services/extensions/common/workspaceContains';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Schemas } from 'vs/base/common/network';
import { URI } from 'vs/base/common/uri';
import { IExtensionManifestPropertiesService } from 'vs/workbench/services/extensions/common/extensionManifestPropertiesService';
import { ApiProposalName, allApiProposals } from 'vs/workbench/services/extensions/common/extensionsApiProposals';
import { ILogService } from 'vs/platform/log/common/log';
import { IExtensionHostExitInfo, IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IUserDataProfileService } from 'vs/workbench/services/userDataProfile/common/userDataProfile';
const hasOwnProperty = Object.hasOwnProperty;
const NO_OP_VOID_PROMISE = Promise.resolve<void>(undefined);
class DeltaExtensionsQueueItem {
constructor(
public readonly toAdd: IExtension[],
public readonly toRemove: string[] | IExtension[]
) { }
}
export const enum ExtensionRunningPreference {
None,
Local,
Remote
}
export function extensionRunningPreferenceToString(preference: ExtensionRunningPreference) {
switch (preference) {
case ExtensionRunningPreference.None:
return 'None';
case ExtensionRunningPreference.Local:
return 'Local';
case ExtensionRunningPreference.Remote:
return 'Remote';
}
}
class LockCustomer {
public readonly promise: Promise<IDisposable>;
private _resolve!: (value: IDisposable) => void;
constructor(
public readonly name: string
) {
this.promise = new Promise<IDisposable>((resolve, reject) => {
this._resolve = resolve;
});
}
resolve(value: IDisposable): void {
this._resolve(value);
}
}
class Lock {
private readonly _pendingCustomers: LockCustomer[] = [];
private _isLocked = false;
public async acquire(customerName: string): Promise<IDisposable> {
const customer = new LockCustomer(customerName);
this._pendingCustomers.push(customer);
this._advance();
return customer.promise;
}
private _advance(): void {
if (this._isLocked) {
// cannot advance yet
return;
}
if (this._pendingCustomers.length === 0) {
// no more waiting customers
return;
}
const customer = this._pendingCustomers.shift()!;
this._isLocked = true;
let customerHoldsLock = true;
const logLongRunningCustomerTimeout = setTimeout(() => {
if (customerHoldsLock) {
console.warn(`The customer named ${customer.name} has been holding on to the lock for 30s. This might be a problem.`);
}
}, 30 * 1000 /* 30 seconds */);
const releaseLock = () => {
if (!customerHoldsLock) {
return;
}
clearTimeout(logLongRunningCustomerTimeout);
customerHoldsLock = false;
this._isLocked = false;
this._advance();
};
customer.resolve(toDisposable(releaseLock));
}
}
export abstract class AbstractExtensionService extends Disposable implements IExtensionService {
public _serviceBrand: undefined;
private readonly _onDidRegisterExtensions: Emitter<void> = this._register(new Emitter<void>());
public readonly onDidRegisterExtensions = this._onDidRegisterExtensions.event;
private readonly _onDidChangeExtensionsStatus: Emitter<ExtensionIdentifier[]> = this._register(new Emitter<ExtensionIdentifier[]>());
public readonly onDidChangeExtensionsStatus: Event<ExtensionIdentifier[]> = this._onDidChangeExtensionsStatus.event;
private readonly _onDidChangeExtensions: Emitter<void> = this._register(new Emitter<void>({ leakWarningThreshold: 400 }));
public readonly onDidChangeExtensions: Event<void> = this._onDidChangeExtensions.event;
private readonly _onWillActivateByEvent = this._register(new Emitter<IWillActivateEvent>());
public readonly onWillActivateByEvent: Event<IWillActivateEvent> = this._onWillActivateByEvent.event;
private readonly _onDidChangeResponsiveChange = this._register(new Emitter<IResponsiveStateChangeEvent>());
public readonly onDidChangeResponsiveChange: Event<IResponsiveStateChangeEvent> = this._onDidChangeResponsiveChange.event;
protected readonly _registry: ExtensionDescriptionRegistry;
private readonly _registryLock: Lock;
private readonly _installedExtensionsReady: Barrier;
private readonly _isDev: boolean;
private readonly _extensionsMessages: Map<string, IMessage[]>;
private readonly _allRequestedActivateEvents = new Set<string>();
private readonly _proposedApiController: ProposedApiController;
private readonly _isExtensionDevHost: boolean;
protected readonly _isExtensionDevTestFromCli: boolean;
private _deltaExtensionsQueue: DeltaExtensionsQueueItem[];
private _inHandleDeltaExtensions: boolean;
private _runningLocation: Map<string, ExtensionRunningLocation | null>;
private _lastExtensionHostId: number = 0;
private _maxLocalProcessAffinity: number = 0;
private readonly _remoteCrashTracker = new ExtensionHostCrashTracker();
// --- Members used per extension host process
private _extensionHostManagers: IExtensionHostManager[];
protected _extensionHostActiveExtensions: Map<string, ExtensionIdentifier>;
private _extensionHostActivationTimes: Map<string, ActivationTimes>;
private _extensionHostExtensionRuntimeErrors: Map<string, Error[]>;
constructor(
@IInstantiationService protected readonly _instantiationService: IInstantiationService,
@INotificationService protected readonly _notificationService: INotificationService,
@IWorkbenchEnvironmentService protected readonly _environmentService: IWorkbenchEnvironmentService,
@ITelemetryService protected readonly _telemetryService: ITelemetryService,
@IWorkbenchExtensionEnablementService protected readonly _extensionEnablementService: IWorkbenchExtensionEnablementService,
@IFileService protected readonly _fileService: IFileService,
@IProductService protected readonly _productService: IProductService,
@IWorkbenchExtensionManagementService protected readonly _extensionManagementService: IWorkbenchExtensionManagementService,
@IWorkspaceContextService private readonly _contextService: IWorkspaceContextService,
@IConfigurationService protected readonly _configurationService: IConfigurationService,
@IExtensionManifestPropertiesService protected readonly _extensionManifestPropertiesService: IExtensionManifestPropertiesService,
@ILogService protected readonly _logService: ILogService,
@IRemoteAgentService protected readonly _remoteAgentService: IRemoteAgentService,
@ILifecycleService private readonly _lifecycleService: ILifecycleService,
@IUserDataProfileService protected readonly _userDataProfileService: IUserDataProfileService,
) {
super();
// help the file service to activate providers by activating extensions by file system event
this._register(this._fileService.onWillActivateFileSystemProvider(e => {
if (e.scheme !== Schemas.vscodeRemote) {
e.join(this.activateByEvent(`onFileSystem:${e.scheme}`));
}
}));
this._registry = new ExtensionDescriptionRegistry([]);
this._registryLock = new Lock();
this._installedExtensionsReady = new Barrier();
this._isDev = !this._environmentService.isBuilt || this._environmentService.isExtensionDevelopment;
this._extensionsMessages = new Map<string, IMessage[]>();
this._proposedApiController = _instantiationService.createInstance(ProposedApiController);
this._extensionHostManagers = [];
this._extensionHostActiveExtensions = new Map<string, ExtensionIdentifier>();
this._extensionHostActivationTimes = new Map<string, ActivationTimes>();
this._extensionHostExtensionRuntimeErrors = new Map<string, Error[]>();
const devOpts = parseExtensionDevOptions(this._environmentService);
this._isExtensionDevHost = devOpts.isExtensionDevHost;
this._isExtensionDevTestFromCli = devOpts.isExtensionDevTestFromCli;
this._deltaExtensionsQueue = [];
this._inHandleDeltaExtensions = false;
this._runningLocation = new Map<string, ExtensionRunningLocation>();
this._register(this._extensionEnablementService.onEnablementChanged((extensions) => {
const toAdd: IExtension[] = [];
const toRemove: IExtension[] = [];
for (const extension of extensions) {
if (this._safeInvokeIsEnabled(extension)) {
// an extension has been enabled
toAdd.push(extension);
} else {
// an extension has been disabled
toRemove.push(extension);
}
}
this._handleDeltaExtensions(new DeltaExtensionsQueueItem(toAdd, toRemove));
}));
this._register(this._extensionManagementService.onDidChangeProfileExtensions(({ added, removed }) => this._handleDeltaExtensions(new DeltaExtensionsQueueItem(added, removed))));
this._register(this._extensionManagementService.onDidInstallExtensions((result) => {
const extensions: IExtension[] = [];
for (const { local, operation } of result) {
if (local && operation !== InstallOperation.Migrate && this._safeInvokeIsEnabled(local)) {
extensions.push(local);
}
}
if (extensions.length) {
this._handleDeltaExtensions(new DeltaExtensionsQueueItem(extensions, []));
}
}));
this._register(this._extensionManagementService.onDidUninstallExtension((event) => {
if (!event.error) {
// an extension has been uninstalled
this._handleDeltaExtensions(new DeltaExtensionsQueueItem([], [event.identifier.id]));
}
}));
this._register(this._lifecycleService.onDidShutdown(() => {
this.stopExtensionHosts();
}));
}
private _getExtensionKind(extensionDescription: IExtensionDescription): ExtensionKind[] {
if (extensionDescription.isUnderDevelopment && this._environmentService.extensionDevelopmentKind) {
return this._environmentService.extensionDevelopmentKind;
}
return this._extensionManifestPropertiesService.getExtensionKind(extensionDescription);
}
protected abstract _pickExtensionHostKind(extensionId: ExtensionIdentifier, extensionKinds: ExtensionKind[], isInstalledLocally: boolean, isInstalledRemotely: boolean, preference: ExtensionRunningPreference): ExtensionHostKind | null;
protected _getExtensionHostManagers(kind: ExtensionHostKind): IExtensionHostManager[] {
return this._extensionHostManagers.filter(extHostManager => extHostManager.kind === kind);
}
protected _getExtensionHostManagerByRunningLocation(runningLocation: ExtensionRunningLocation): IExtensionHostManager | null {
for (const extensionHostManager of this._extensionHostManagers) {
if (extensionHostManager.representsRunningLocation(runningLocation)) {
return extensionHostManager;
}
}
return null;
}
//#region running location
private _computeAffinity(inputExtensions: IExtensionDescription[], extensionHostKind: ExtensionHostKind, isInitialAllocation: boolean): { affinities: Map<string, number>; maxAffinity: number } {
// Only analyze extensions that can execute
const extensions = new Map<string, IExtensionDescription>();
for (const extension of inputExtensions) {
if (extension.main || extension.browser) {
extensions.set(ExtensionIdentifier.toKey(extension.identifier), extension);
}
}
// Also add existing extensions of the same kind that can execute
for (const extension of this._registry.getAllExtensionDescriptions()) {
if (extension.main || extension.browser) {
const runningLocation = this._runningLocation.get(ExtensionIdentifier.toKey(extension.identifier));
if (runningLocation && runningLocation.kind === extensionHostKind) {
extensions.set(ExtensionIdentifier.toKey(extension.identifier), extension);
}
}
}
// Initially, each extension belongs to its own group
const groups = new Map<string, number>();
let groupNumber = 0;
for (const [_, extension] of extensions) {
groups.set(ExtensionIdentifier.toKey(extension.identifier), ++groupNumber);
}
const changeGroup = (from: number, to: number) => {
for (const [key, group] of groups) {
if (group === from) {
groups.set(key, to);
}
}
};
// We will group things together when there are dependencies
for (const [_, extension] of extensions) {
if (!extension.extensionDependencies) {
continue;
}
const myGroup = groups.get(ExtensionIdentifier.toKey(extension.identifier))!;
for (const depId of extension.extensionDependencies) {
const depGroup = groups.get(ExtensionIdentifier.toKey(depId));
if (!depGroup) {
// probably can't execute, so it has no impact
continue;
}
if (depGroup === myGroup) {
// already in the same group
continue;
}
changeGroup(depGroup, myGroup);
}
}
// Initialize with existing affinities
const resultingAffinities = new Map<number, number>();
let lastAffinity = 0;
for (const [_, extension] of extensions) {
const runningLocation = this._runningLocation.get(ExtensionIdentifier.toKey(extension.identifier));
if (runningLocation) {
const group = groups.get(ExtensionIdentifier.toKey(extension.identifier))!;
resultingAffinities.set(group, runningLocation.affinity);
lastAffinity = Math.max(lastAffinity, runningLocation.affinity);
}
}
// When doing extension host debugging, we will ignore the configured affinity
// because we can currently debug a single extension host
if (!this._environmentService.isExtensionDevelopment) {
// Go through each configured affinity and try to accomodate it
const configuredAffinities = this._configurationService.getValue<{ [extensionId: string]: number } | undefined>('extensions.experimental.affinity') || {};
const configuredExtensionIds = Object.keys(configuredAffinities);
const configuredAffinityToResultingAffinity = new Map<number, number>();
for (const extensionId of configuredExtensionIds) {
const configuredAffinity = configuredAffinities[extensionId];
if (typeof configuredAffinity !== 'number' || configuredAffinity <= 0 || Math.floor(configuredAffinity) !== configuredAffinity) {
this._logService.info(`Ignoring configured affinity for '${extensionId}' because the value is not a positive integer.`);
continue;
}
const group = groups.get(ExtensionIdentifier.toKey(extensionId));
if (!group) {
this._logService.info(`Ignoring configured affinity for '${extensionId}' because the extension is unknown or cannot execute.`);
continue;
}
const affinity1 = resultingAffinities.get(group);
if (affinity1) {
// Affinity for this group is already established
configuredAffinityToResultingAffinity.set(configuredAffinity, affinity1);
continue;
}
const affinity2 = configuredAffinityToResultingAffinity.get(configuredAffinity);
if (affinity2) {
// Affinity for this configuration is already established
resultingAffinities.set(group, affinity2);
continue;
}
if (!isInitialAllocation) {
this._logService.info(`Ignoring configured affinity for '${extensionId}' because extension host(s) are already running. Reload window.`);
continue;
}
const affinity3 = ++lastAffinity;
configuredAffinityToResultingAffinity.set(configuredAffinity, affinity3);
resultingAffinities.set(group, affinity3);
}
}
const result = new Map<string, number>();
for (const extension of inputExtensions) {
const group = groups.get(ExtensionIdentifier.toKey(extension.identifier)) || 0;
const affinity = resultingAffinities.get(group) || 0;
result.set(ExtensionIdentifier.toKey(extension.identifier), affinity);
}
if (lastAffinity > 0 && isInitialAllocation) {
for (let affinity = 1; affinity <= lastAffinity; affinity++) {
const extensionIds: ExtensionIdentifier[] = [];
for (const extension of inputExtensions) {
if (result.get(ExtensionIdentifier.toKey(extension.identifier)) === affinity) {
extensionIds.push(extension.identifier);
}
}
this._logService.info(`Placing extension(s) ${extensionIds.map(e => e.value).join(', ')} on a separate extension host.`);
}
}
return { affinities: result, maxAffinity: lastAffinity };
}
private _computeRunningLocation(localExtensions: IExtensionDescription[], remoteExtensions: IExtensionDescription[], isInitialAllocation: boolean): { runningLocation: Map<string, ExtensionRunningLocation | null>; maxLocalProcessAffinity: number } {
const extensionHostKinds = ExtensionHostKindClassifier.determineExtensionHostKinds(
localExtensions,
remoteExtensions,
(extension) => this._getExtensionKind(extension),
(extensionId, extensionKinds, isInstalledLocally, isInstalledRemotely, preference) => this._pickExtensionHostKind(extensionId, extensionKinds, isInstalledLocally, isInstalledRemotely, preference)
);
const extensions = new Map<string, IExtensionDescription>();
for (const extension of localExtensions) {
extensions.set(ExtensionIdentifier.toKey(extension.identifier), extension);
}
for (const extension of remoteExtensions) {
extensions.set(ExtensionIdentifier.toKey(extension.identifier), extension);
}
const result = new Map<string, ExtensionRunningLocation | null>();
const localProcessExtensions: IExtensionDescription[] = [];
for (const [extensionIdKey, extensionHostKind] of extensionHostKinds) {
let runningLocation: ExtensionRunningLocation | null = null;
if (extensionHostKind === ExtensionHostKind.LocalProcess) {
const extensionDescription = extensions.get(ExtensionIdentifier.toKey(extensionIdKey));
if (extensionDescription) {
localProcessExtensions.push(extensionDescription);
}
} else if (extensionHostKind === ExtensionHostKind.LocalWebWorker) {
runningLocation = new LocalWebWorkerRunningLocation();
} else if (extensionHostKind === ExtensionHostKind.Remote) {
runningLocation = new RemoteRunningLocation();
}
result.set(extensionIdKey, runningLocation);
}
const { affinities, maxAffinity } = this._computeAffinity(localProcessExtensions, ExtensionHostKind.LocalProcess, isInitialAllocation);
for (const extension of localProcessExtensions) {
const affinity = affinities.get(ExtensionIdentifier.toKey(extension.identifier)) || 0;
result.set(ExtensionIdentifier.toKey(extension.identifier), new LocalProcessRunningLocation(affinity));
}
return { runningLocation: result, maxLocalProcessAffinity: maxAffinity };
}
protected _determineRunningLocation(localExtensions: IExtensionDescription[]): Map<string, ExtensionRunningLocation | null> {
return this._computeRunningLocation(localExtensions, [], false).runningLocation;
}
protected _initializeRunningLocation(localExtensions: IExtensionDescription[], remoteExtensions: IExtensionDescription[]): void {
const { runningLocation, maxLocalProcessAffinity } = this._computeRunningLocation(localExtensions, remoteExtensions, true);
this._runningLocation = runningLocation;
this._maxLocalProcessAffinity = maxLocalProcessAffinity;
this._startExtensionHostsIfNecessary(true, []);
}
/**
* Update `this._runningLocation` with running locations for newly enabled/installed extensions.
*/
private _updateRunningLocationForAddedExtensions(toAdd: IExtensionDescription[]): void {
// Determine new running location
const localProcessExtensions: IExtensionDescription[] = [];
for (const extension of toAdd) {
const extensionKind = this._getExtensionKind(extension);
const isRemote = extension.extensionLocation.scheme === Schemas.vscodeRemote;
const extensionHostKind = this._pickExtensionHostKind(extension.identifier, extensionKind, !isRemote, isRemote, ExtensionRunningPreference.None);
let runningLocation: ExtensionRunningLocation | null = null;
if (extensionHostKind === ExtensionHostKind.LocalProcess) {
localProcessExtensions.push(extension);
} else if (extensionHostKind === ExtensionHostKind.LocalWebWorker) {
runningLocation = new LocalWebWorkerRunningLocation();
} else if (extensionHostKind === ExtensionHostKind.Remote) {
runningLocation = new RemoteRunningLocation();
}
this._runningLocation.set(ExtensionIdentifier.toKey(extension.identifier), runningLocation);
}
const { affinities } = this._computeAffinity(localProcessExtensions, ExtensionHostKind.LocalProcess, false);
for (const extension of localProcessExtensions) {
const affinity = affinities.get(ExtensionIdentifier.toKey(extension.identifier)) || 0;
this._runningLocation.set(ExtensionIdentifier.toKey(extension.identifier), new LocalProcessRunningLocation(affinity));
}
}
protected _filterByRunningLocation(extensions: IExtensionDescription[], desiredRunningLocation: ExtensionRunningLocation): IExtensionDescription[] {
return filterByRunningLocation(extensions, this._runningLocation, desiredRunningLocation);
}
protected _filterByExtensionHostKind(extensions: IExtensionDescription[], desiredExtensionHostKind: ExtensionHostKind): IExtensionDescription[] {
return filterByExtensionHostKind(extensions, this._runningLocation, desiredExtensionHostKind);
}
protected _filterByExtensionHostManager(extensions: IExtensionDescription[], extensionHostManager: IExtensionHostManager): IExtensionDescription[] {
return filterByExtensionHostManager(extensions, this._runningLocation, extensionHostManager);
}
//#endregion
//#region deltaExtensions
private async _handleDeltaExtensions(item: DeltaExtensionsQueueItem): Promise<void> {
this._deltaExtensionsQueue.push(item);
if (this._inHandleDeltaExtensions) {
// Let the current item finish, the new one will be picked up
return;
}
let lock: IDisposable | null = null;
try {
this._inHandleDeltaExtensions = true;
// wait for _initialize to finish before hanlding any delta extension events
await this._installedExtensionsReady.wait();
lock = await this._registryLock.acquire('handleDeltaExtensions');
while (this._deltaExtensionsQueue.length > 0) {
const item = this._deltaExtensionsQueue.shift()!;
await this._deltaExtensions(item.toAdd, item.toRemove);
}
} finally {
this._inHandleDeltaExtensions = false;
if (lock) {
lock.dispose();
}
}
}
private async _deltaExtensions(_toAdd: IExtension[], _toRemove: string[] | IExtension[]): Promise<void> {
let toRemove: IExtensionDescription[] = [];
for (let i = 0, len = _toRemove.length; i < len; i++) {
const extensionOrId = _toRemove[i];
const extensionId = (typeof extensionOrId === 'string' ? extensionOrId : extensionOrId.identifier.id);
const extension = (typeof extensionOrId === 'string' ? null : extensionOrId);
const extensionDescription = this._registry.getExtensionDescription(extensionId);
if (!extensionDescription) {
// ignore disabling/uninstalling an extension which is not running
continue;
}
if (extension && extensionDescription.extensionLocation.scheme !== extension.location.scheme) {
// this event is for a different extension than mine (maybe for the local extension, while I have the remote extension)
continue;
}
if (!this.canRemoveExtension(extensionDescription)) {
// uses non-dynamic extension point or is activated
continue;
}
toRemove.push(extensionDescription);
}
const toAdd: IExtensionDescription[] = [];
for (let i = 0, len = _toAdd.length; i < len; i++) {
const extension = _toAdd[i];
const extensionDescription = await this._scanSingleExtension(extension);
if (!extensionDescription) {
// could not scan extension...
continue;
}
if (!this._canAddExtension(extensionDescription, toRemove)) {
continue;
}
toAdd.push(extensionDescription);
}
if (toAdd.length === 0 && toRemove.length === 0) {
return;
}
// Update the local registry
const result = this._registry.deltaExtensions(toAdd, toRemove.map(e => e.identifier));
this._onDidChangeExtensions.fire(undefined);
toRemove = toRemove.concat(result.removedDueToLooping);
if (result.removedDueToLooping.length > 0) {
this._notificationService.notify({
severity: Severity.Error,
message: nls.localize('looping', "The following extensions contain dependency loops and have been disabled: {0}", result.removedDueToLooping.map(e => `'${e.identifier.value}'`).join(', '))
});
}
// enable or disable proposed API per extension
this._checkEnableProposedApi(toAdd);
// Update extension points
this._doHandleExtensionPoints((<IExtensionDescription[]>[]).concat(toAdd).concat(toRemove));
// Update the extension host
await this._updateExtensionsOnExtHosts(toAdd, toRemove.map(e => e.identifier));
for (let i = 0; i < toAdd.length; i++) {
this._activateAddedExtensionIfNeeded(toAdd[i]);
}
}
private async _updateExtensionsOnExtHosts(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> {
// Remove old running location
const removedRunningLocation = new Map<string, ExtensionRunningLocation | null>();
for (const extensionId of toRemove) {
const extensionKey = ExtensionIdentifier.toKey(extensionId);
removedRunningLocation.set(extensionKey, this._runningLocation.get(extensionKey) || null);
this._runningLocation.delete(extensionKey);
}
// Determine new running location
this._updateRunningLocationForAddedExtensions(toAdd);
const promises = this._extensionHostManagers.map(
extHostManager => this._updateExtensionsOnExtHost(extHostManager, toAdd, toRemove, removedRunningLocation)
);
await Promise.all(promises);
}
private async _updateExtensionsOnExtHost(extensionHostManager: IExtensionHostManager, toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[], removedRunningLocation: Map<string, ExtensionRunningLocation | null>): Promise<void> {
const myToAdd = filterByExtensionHostManager(toAdd, this._runningLocation, extensionHostManager);
const myToRemove = _filterByExtensionHostManager(toRemove, extId => extId, removedRunningLocation, extensionHostManager);
await extensionHostManager.deltaExtensions({ toRemove, toAdd, myToRemove, myToAdd: myToAdd.map(extension => extension.identifier) });
}
public canAddExtension(extension: IExtensionDescription): boolean {
return this._canAddExtension(extension, []);
}
private _canAddExtension(extension: IExtensionDescription, extensionsBeingRemoved: IExtensionDescription[]): boolean {
// (Also check for renamed extensions)
const existing = this._registry.getExtensionDescriptionByIdOrUUID(extension.identifier, extension.id);
if (existing) {
// This extension is already known (most likely at a different version)
// so it cannot be added again unless it is removed first
const isBeingRemoved = extensionsBeingRemoved.some((extensionDescription) => ExtensionIdentifier.equals(extension.identifier, extensionDescription.identifier));
if (!isBeingRemoved) {
return false;
}
}
const extensionKind = this._getExtensionKind(extension);
const isRemote = extension.extensionLocation.scheme === Schemas.vscodeRemote;
const extensionHostKind = this._pickExtensionHostKind(extension.identifier, extensionKind, !isRemote, isRemote, ExtensionRunningPreference.None);
if (extensionHostKind === null) {
return false;
}
return true;
}
public canRemoveExtension(extension: IExtensionDescription): boolean {
const extensionDescription = this._registry.getExtensionDescription(extension.identifier);
if (!extensionDescription) {
// Can't remove an extension that is unknown!
return false;
}
if (this._extensionHostActiveExtensions.has(ExtensionIdentifier.toKey(extensionDescription.identifier))) {
// Extension is running, cannot remove it safely
return false;
}
return true;
}
private async _activateAddedExtensionIfNeeded(extensionDescription: IExtensionDescription): Promise<void> {
let shouldActivate = false;
let shouldActivateReason: string | null = null;
let hasWorkspaceContains = false;
if (Array.isArray(extensionDescription.activationEvents)) {
for (let activationEvent of extensionDescription.activationEvents) {
// TODO@joao: there's no easy way to contribute this
if (activationEvent === 'onUri') {
activationEvent = `onUri:${ExtensionIdentifier.toKey(extensionDescription.identifier)}`;
}
if (this._allRequestedActivateEvents.has(activationEvent)) {
// This activation event was fired before the extension was added
shouldActivate = true;
shouldActivateReason = activationEvent;
break;
}
if (activationEvent === '*') {
shouldActivate = true;
shouldActivateReason = activationEvent;
break;
}
if (/^workspaceContains/.test(activationEvent)) {
hasWorkspaceContains = true;
}
if (activationEvent === 'onStartupFinished') {
shouldActivate = true;
shouldActivateReason = activationEvent;
break;
}
}
}
if (shouldActivate) {
await Promise.all(
this._extensionHostManagers.map(extHostManager => extHostManager.activate(extensionDescription.identifier, { startup: false, extensionId: extensionDescription.identifier, activationEvent: shouldActivateReason! }))
).then(() => { });
} else if (hasWorkspaceContains) {
const workspace = await this._contextService.getCompleteWorkspace();
const forceUsingSearch = !!this._environmentService.remoteAuthority;
const host: IWorkspaceContainsActivationHost = {
logService: this._logService,
folders: workspace.folders.map(folder => folder.uri),
forceUsingSearch: forceUsingSearch,
exists: (uri) => this._fileService.exists(uri),
checkExists: (folders, includes, token) => this._instantiationService.invokeFunction((accessor) => checkGlobFileExists(accessor, folders, includes, token))
};
const result = await checkActivateWorkspaceContainsExtension(host, extensionDescription);
if (!result) {
return;
}
await Promise.all(
this._extensionHostManagers.map(extHostManager => extHostManager.activate(extensionDescription.identifier, { startup: false, extensionId: extensionDescription.identifier, activationEvent: result.activationEvent }))
).then(() => { });
}
}
//#endregion
protected async _initialize(): Promise<void> {
perf.mark('code/willLoadExtensions');
this._startExtensionHostsIfNecessary(true, []);
const lock = await this._registryLock.acquire('_initialize');
try {
await this._scanAndHandleExtensions();
} finally {
lock.dispose();
}
this._releaseBarrier();
perf.mark('code/didLoadExtensions');
await this._handleExtensionTests();
}
private async _handleExtensionTests(): Promise<void> {
if (!this._environmentService.isExtensionDevelopment || !this._environmentService.extensionTestsLocationURI) {
return;
}
const extensionHostManager = this.findTestExtensionHost(this._environmentService.extensionTestsLocationURI);
if (!extensionHostManager) {
const msg = nls.localize('extensionTestError', "No extension host found that can launch the test runner at {0}.", this._environmentService.extensionTestsLocationURI.toString());
console.error(msg);
this._notificationService.error(msg);
return;
}
let exitCode: number;
try {
exitCode = await extensionHostManager.extensionTestsExecute();
} catch (err) {
console.error(err);
exitCode = 1 /* ERROR */;
}
this._onExtensionHostExit(exitCode);
}
private findTestExtensionHost(testLocation: URI): IExtensionHostManager | null {
let runningLocation: ExtensionRunningLocation | null = null;
for (const extension of this._registry.getAllExtensionDescriptions()) {
if (isEqualOrParent(testLocation, extension.extensionLocation)) {
runningLocation = this._runningLocation.get(ExtensionIdentifier.toKey(extension.identifier)) || null;
break;
}
}
if (runningLocation === null) {
// not sure if we should support that, but it was possible to have an test outside an extension
if (testLocation.scheme === Schemas.vscodeRemote) {
runningLocation = new RemoteRunningLocation();
} else {
// When a debugger attaches to the extension host, it will surface all console.log messages from the extension host,
// but not necessarily from the window. So it would be best if any errors get printed to the console of the extension host.
// That is why here we use the local process extension host even for non-file URIs
runningLocation = new LocalProcessRunningLocation(0);
}
}
if (runningLocation !== null) {
return this._getExtensionHostManagerByRunningLocation(runningLocation);
}
return null;
}
private _releaseBarrier(): void {
this._installedExtensionsReady.open();
this._onDidRegisterExtensions.fire(undefined);
this._onDidChangeExtensionsStatus.fire(this._registry.getAllExtensionDescriptions().map(e => e.identifier));
}
//#region Stopping / Starting / Restarting
public stopExtensionHosts(): void {
const previouslyActivatedExtensionIds: ExtensionIdentifier[] = [];
this._extensionHostActiveExtensions.forEach((value) => {
previouslyActivatedExtensionIds.push(value);
});
// See https://github.com/microsoft/vscode/issues/152204
// Dispose extension hosts in reverse creation order because the local extension host
// might be critical in sustaining a connection to the remote extension host
for (let i = this._extensionHostManagers.length - 1; i >= 0; i--) {
this._extensionHostManagers[i].dispose();
}
this._extensionHostManagers = [];
this._extensionHostActiveExtensions = new Map<string, ExtensionIdentifier>();
this._extensionHostActivationTimes = new Map<string, ActivationTimes>();
this._extensionHostExtensionRuntimeErrors = new Map<string, Error[]>();
if (previouslyActivatedExtensionIds.length > 0) {
this._onDidChangeExtensionsStatus.fire(previouslyActivatedExtensionIds);
}
}
private _startExtensionHostsIfNecessary(isInitialStart: boolean, initialActivationEvents: string[]): void {
const locations: ExtensionRunningLocation[] = [];
for (let affinity = 0; affinity <= this._maxLocalProcessAffinity; affinity++) {
locations.push(new LocalProcessRunningLocation(affinity));
}
locations.push(new LocalWebWorkerRunningLocation());
locations.push(new RemoteRunningLocation());
for (const location of locations) {
if (this._getExtensionHostManagerByRunningLocation(location)) {
// already running
continue;
}
const extHostManager = this._createExtensionHostManager(location, isInitialStart, initialActivationEvents);
if (extHostManager) {
this._extensionHostManagers.push(extHostManager);
}
}
}
private _createExtensionHostManager(runningLocation: ExtensionRunningLocation, isInitialStart: boolean, initialActivationEvents: string[]): IExtensionHostManager | null {
const extensionHost = this._createExtensionHost(runningLocation, isInitialStart);
if (!extensionHost) {
return null;
}
const extensionHostId = String(++this._lastExtensionHostId);
const processManager: IExtensionHostManager = this._doCreateExtensionHostManager(extensionHostId, extensionHost, isInitialStart, initialActivationEvents);
processManager.onDidExit(([code, signal]) => this._onExtensionHostCrashOrExit(processManager, code, signal));
processManager.onDidChangeResponsiveState((responsiveState) => {
this._onDidChangeResponsiveChange.fire({
extensionHostId: extensionHostId,
extensionHostKind: processManager.kind,
isResponsive: responsiveState === ResponsiveState.Responsive
});
});
return processManager;
}
protected _doCreateExtensionHostManager(extensionHostId: string, extensionHost: IExtensionHost, isInitialStart: boolean, initialActivationEvents: string[]): IExtensionHostManager {
return createExtensionHostManager(this._instantiationService, extensionHostId, extensionHost, isInitialStart, initialActivationEvents, this._acquireInternalAPI());
}
private _onExtensionHostCrashOrExit(extensionHost: IExtensionHostManager, code: number, signal: string | null): void {
// Unexpected termination
if (!this._isExtensionDevHost) {
this._onExtensionHostCrashed(extensionHost, code, signal);
return;
}
this._onExtensionHostExit(code);
}
protected _onExtensionHostCrashed(extensionHost: IExtensionHostManager, code: number, signal: string | null): void {
console.error(`Extension host (${extensionHostKindToString(extensionHost.kind)}) terminated unexpectedly. Code: ${code}, Signal: ${signal}`);
if (extensionHost.kind === ExtensionHostKind.LocalProcess) {
this.stopExtensionHosts();
} else if (extensionHost.kind === ExtensionHostKind.Remote) {
if (signal) {
this._onRemoteExtensionHostCrashed(extensionHost, signal);
}
for (let i = 0; i < this._extensionHostManagers.length; i++) {
if (this._extensionHostManagers[i] === extensionHost) {
this._extensionHostManagers[i].dispose();
this._extensionHostManagers.splice(i, 1);
break;
}
}
}
}
private _getExtensionHostExitInfoWithTimeout(reconnectionToken: string): Promise<IExtensionHostExitInfo | null> {
return new Promise((resolve, reject) => {
const timeoutHandle = setTimeout(() => {
reject(new Error('getExtensionHostExitInfo timed out'));
}, 2000);
this._remoteAgentService.getExtensionHostExitInfo(reconnectionToken).then(
(r) => {
clearTimeout(timeoutHandle);
resolve(r);
},
reject
);
});
}
private async _onRemoteExtensionHostCrashed(extensionHost: IExtensionHostManager, reconnectionToken: string): Promise<void> {
try {
const info = await this._getExtensionHostExitInfoWithTimeout(reconnectionToken);
if (info) {
this._logService.error(`Extension host (${extensionHostKindToString(extensionHost.kind)}) terminated unexpectedly with code ${info.code}.`);
}
this._logExtensionHostCrash(extensionHost);
this._remoteCrashTracker.registerCrash();
if (this._remoteCrashTracker.shouldAutomaticallyRestart()) {
this._logService.info(`Automatically restarting the remote extension host.`);
this._notificationService.status(nls.localize('extensionService.autoRestart', "The remote extension host terminated unexpectedly. Restarting..."), { hideAfter: 5000 });
this._startExtensionHostsIfNecessary(false, Array.from(this._allRequestedActivateEvents.keys()));
} else {
this._notificationService.prompt(Severity.Error, nls.localize('extensionService.crash', "Remote Extension host terminated unexpectedly 3 times within the last 5 minutes."),
[{
label: nls.localize('restart', "Restart Remote Extension Host"),
run: () => {
this._startExtensionHostsIfNecessary(false, Array.from(this._allRequestedActivateEvents.keys()));
}
}]
);
}
} catch (err) {
// maybe this wasn't an extension host crash and it was a permanent disconnection
}
}
protected _logExtensionHostCrash(extensionHost: IExtensionHostManager): void {
const activatedExtensions = Array.from(this._extensionHostActiveExtensions.values()).filter(extensionId => extensionHost.containsExtension(extensionId));
if (activatedExtensions.length > 0) {
this._logService.error(`Extension host (${extensionHostKindToString(extensionHost.kind)}) terminated unexpectedly. The following extensions were running: ${activatedExtensions.map(id => id.value).join(', ')}`);
} else {
this._logService.error(`Extension host (${extensionHostKindToString(extensionHost.kind)}) terminated unexpectedly. No extensions were activated.`);
}
}
public async startExtensionHosts(): Promise<void> {
this.stopExtensionHosts();
const lock = await this._registryLock.acquire('startExtensionHosts');
try {
this._startExtensionHostsIfNecessary(false, Array.from(this._allRequestedActivateEvents.keys()));
const localProcessExtensionHosts = this._getExtensionHostManagers(ExtensionHostKind.LocalProcess);
await Promise.all(localProcessExtensionHosts.map(extHost => extHost.ready()));
} finally {
lock.dispose();
}
}
public async restartExtensionHost(): Promise<void> {
this.stopExtensionHosts();
await this.startExtensionHosts();
}
//#endregion
//#region IExtensionService
public activateByEvent(activationEvent: string, activationKind: ActivationKind = ActivationKind.Normal): Promise<void> {
if (this._installedExtensionsReady.isOpen()) {
// Extensions have been scanned and interpreted
// Record the fact that this activationEvent was requested (in case of a restart)
this._allRequestedActivateEvents.add(activationEvent);