-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
extensionsAutoProfiler.ts
196 lines (165 loc) · 6.84 KB
/
extensionsAutoProfiler.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IExtensionService, IResponsiveStateChangeEvent, IExtensionHostProfile, ProfileSession } from 'vs/workbench/services/extensions/common/extensions';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Disposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { onUnexpectedError } from 'vs/base/common/errors';
import * as os from 'os';
import { join } from 'vs/base/common/path';
import { writeFile } from 'vs/base/node/pfs';
import { IExtensionHostProfileService } from 'vs/workbench/contrib/extensions/electron-browser/runtimeExtensionsEditor';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { localize } from 'vs/nls';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { RuntimeExtensionsInput } from 'vs/workbench/contrib/extensions/electron-browser/runtimeExtensionsInput';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { createSlowExtensionAction } from 'vs/workbench/contrib/extensions/electron-browser/extensionsSlowActions';
import { ExtensionHostProfiler } from 'vs/workbench/services/extensions/electron-browser/extensionHostProfiler';
export class ExtensionsAutoProfiler extends Disposable implements IWorkbenchContribution {
private readonly _blame = new Set<string>();
private _session: CancellationTokenSource | undefined;
constructor(
@IExtensionService private readonly _extensionService: IExtensionService,
@IExtensionHostProfileService private readonly _extensionProfileService: IExtensionHostProfileService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@ILogService private readonly _logService: ILogService,
@INotificationService private readonly _notificationService: INotificationService,
@IEditorService private readonly _editorService: IEditorService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
super();
this._register(_extensionService.onDidChangeResponsiveChange(this._onDidChangeResponsiveChange, this));
}
private async _onDidChangeResponsiveChange(event: IResponsiveStateChangeEvent): Promise<void> {
const port = await this._extensionService.getInspectPort(true);
if (!port) {
return;
}
if (event.isResponsive && this._session) {
// stop profiling when responsive again
this._session.cancel();
} else if (!event.isResponsive && !this._session) {
// start profiling if not yet profiling
const cts = new CancellationTokenSource();
this._session = cts;
let session: ProfileSession;
try {
session = await this._instantiationService.createInstance(ExtensionHostProfiler, port).start();
} catch (err) {
this._session = undefined;
// fail silent as this is often
// caused by another party being
// connected already
return;
}
// wait 5 seconds or until responsive again
await new Promise(resolve => {
cts.token.onCancellationRequested(resolve);
setTimeout(resolve, 5e3);
});
try {
// stop profiling and analyse results
this._processCpuProfile(await session.stop());
} catch (err) {
onUnexpectedError(err);
} finally {
this._session = undefined;
}
}
}
private async _processCpuProfile(profile: IExtensionHostProfile) {
interface NamedSlice {
id: string;
total: number;
percentage: number;
}
let data: NamedSlice[] = [];
for (let i = 0; i < profile.ids.length; i++) {
let id = profile.ids[i];
let total = profile.deltas[i];
data.push({ id, total, percentage: 0 });
}
// merge data by identifier
let anchor = 0;
data.sort((a, b) => a.id.localeCompare(b.id));
for (let i = 1; i < data.length; i++) {
if (data[anchor].id === data[i].id) {
data[anchor].total += data[i].total;
} else {
anchor += 1;
data[anchor] = data[i];
}
}
data = data.slice(0, anchor + 1);
const duration = profile.endTime - profile.startTime;
const percentage = duration / 100;
let top: NamedSlice | undefined;
for (const slice of data) {
slice.percentage = Math.round(slice.total / percentage);
if (!top || top.percentage < slice.percentage) {
top = slice;
}
}
if (!top) {
return;
}
const extension = await this._extensionService.getExtension(top.id);
if (!extension) {
// not an extension => idle, gc, self?
return;
}
// print message to log
const path = join(os.tmpdir(), `exthost-${Math.random().toString(16).slice(2, 8)}.cpuprofile`);
await writeFile(path, JSON.stringify(profile.data));
this._logService.warn(`UNRESPONSIVE extension host, '${top.id}' took ${top!.percentage}% of ${duration / 1e3}ms, saved PROFILE here: '${path}'`, data);
/* __GDPR__
"exthostunresponsive" : {
"id" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" },
"duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
"data": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }
}
*/
this._telemetryService.publicLog('exthostunresponsive', {
duration,
data,
});
// add to running extensions view
this._extensionProfileService.setUnresponsiveProfile(extension.identifier, profile);
// prompt: when really slow/greedy
if (!(top.percentage >= 99 && top.total >= 5e6)) {
return;
}
const action = await this._instantiationService.invokeFunction(createSlowExtensionAction, extension, profile);
if (!action) {
// cannot report issues against this extension...
return;
}
// only blame once per extension, don't blame too often
if (this._blame.has(ExtensionIdentifier.toKey(extension.identifier)) || this._blame.size >= 3) {
return;
}
this._blame.add(ExtensionIdentifier.toKey(extension.identifier));
// user-facing message when very bad...
this._notificationService.prompt(
Severity.Warning,
localize(
'unresponsive-exthost',
"The extension '{0}' took a very long time to complete its last operation and it has prevented other extensions from running.",
extension.displayName || extension.name
),
[{
label: localize('show', 'Show Extensions'),
run: () => this._editorService.openEditor(new RuntimeExtensionsInput())
},
action
],
{ silent: true }
);
}
}