forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofiler-edit.ts
More file actions
487 lines (457 loc) · 15.8 KB
/
Copy pathprofiler-edit.ts
File metadata and controls
487 lines (457 loc) · 15.8 KB
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import fs from 'fs';
import {
Command,
CommanderError,
InvalidArgumentError,
Option,
} from 'commander';
import { parse as parseToml } from 'smol-toml';
import {
optimizeProfileForStorage,
serializeProfileToJsonSlabsFile,
serializeProfileToJsonString,
unserializeProfileOfArbitraryFormat,
} from 'firefox-profiler/profile-logic/process-profile';
import { computeCompactedProfile } from 'firefox-profiler/profile-logic/profile-compacting';
import { GOOGLE_STORAGE_BUCKET } from 'firefox-profiler/app-logic/constants';
import { compress } from 'firefox-profiler/utils/gz';
import { insertStackLabels } from 'firefox-profiler/profile-logic/insert-stack-labels';
import { SymbolStore } from 'firefox-profiler/profile-logic/symbol-store';
import {
symbolicateProfile,
applySymbolicationSteps,
} from 'firefox-profiler/profile-logic/symbolication';
import type { SymbolicationStepInfo } from 'firefox-profiler/profile-logic/symbolication';
import * as MozillaSymbolicationAPI from 'firefox-profiler/profile-logic/mozilla-symbolication-api';
import {
applyWasmSymbolication,
type WasmSymbolicationSpec,
} from 'firefox-profiler/profile-logic/wasm-symbolication';
import { getThreadsWithMarkersMatchingSearchFilter } from 'firefox-profiler/profile-logic/marker-data';
import type {
Profile,
RawThread,
ThreadIndex,
} from 'firefox-profiler/types/profile';
import { assertExhaustiveCheck } from 'firefox-profiler/utils/types';
import {
type AutoLabel,
type LabelDescription,
resolveAllLabels,
} from 'firefox-profiler/utils/label-templates';
import {
mergeNonOverlappingThreadsByName,
remapCountersAndProfilerOverhead,
} from 'firefox-profiler/profile-logic/merge-compare';
/**
* A CLI tool for editing profiles.
*
* To use it, first build:
* yarn build-node-tools
*
* Then run:
* node node-tools-dist/profiler-edit.js -i <profile> -o <output> [options]
*
* Examples:
* node node-tools-dist/profiler-edit.js -i samply-profile.json -o out.json \
* --symbolicate-with-server http://localhost:8001/abcdef/
*
* node node-tools-dist/profiler-edit.js -i input.json.gz -o out.json.gz \
* --symbolicate-wasm http://host/a.wasm=./a-unstripped.wasm \
* --symbolicate-wasm http://host/b.wasm=./b-unstripped.wasm
*
* node node-tools-dist/profiler-edit.js --from-hash w1spyw917hg... -o out.json.gz \
* --insert-label-frames known-functions.toml
*
* node node-tools-dist/profiler-edit.js -i big.json.gz -o small.json.gz \
* --only-keep-threads-with-markers-matching '-async,-sync' \
* --merge-non-overlapping-threads-by-name
*/
export type ProfileSource =
| { type: 'FILE'; path: string }
| { type: 'URL'; url: string }
| { type: 'HASH'; hash: string };
// Describes one --symbolicate-wasm argument: a local unstripped wasm file that
// supplies symbol names, plus (optionally) the URL of the stripped wasm in the
// profile to which those names should be applied. If `strippedWasmUrl` is
// omitted, the profile must contain exactly one .wasm source, which is used.
export interface WasmSymbolicationCliSpec {
// Path to the local unstripped .wasm file (with a "name" custom section).
unstrippedWasmPath: string;
// URL of the matching stripped wasm as it appears in the profile.
strippedWasmUrl?: string;
}
export interface CliOptions {
input: ProfileSource;
output: string;
symbolicateWithServer?: string;
symbolicateWasm: WasmSymbolicationCliSpec[];
insertLabelFrames?: string;
onlyKeepThreadsWithMarkersMatching?: string;
mergeNonOverlappingThreadsByName?: boolean;
setName?: string;
}
export function loadWasmSymbolicationSpecs(
cliSpecs: WasmSymbolicationCliSpec[]
): WasmSymbolicationSpec[] {
return cliSpecs.map((spec) => {
console.log(`Reading wasm symbols from ${spec.unstrippedWasmPath}`);
const buf = fs.readFileSync(spec.unstrippedWasmPath);
return {
bytes: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength),
url: spec.strippedWasmUrl,
label: spec.unstrippedWasmPath,
};
});
}
/**
* Reconstruct the func-name strings used by insertStackLabels' prefix matcher
* (mirrors getLabelIndexForFunc in insert-stack-labels.ts), so auto-discovery
* sees the same strings the labeler will compare against.
*/
export function collectFuncNames(profile: Profile): string[] {
const { funcTable, sources, stringArray } = profile.shared;
const result: string[] = [];
for (let i = 0; i < funcTable.length; i++) {
let name = stringArray[funcTable.name[i]];
const sourceIndex = funcTable.source[i];
if (sourceIndex !== null) {
const filename = stringArray[sources.filename[sourceIndex]];
name += ` (${filename})`;
}
result.push(name);
}
return result;
}
export type ParsedLabelToml = {
labels: LabelDescription[];
autoLabels: AutoLabel[];
};
export function parseLabelToml(tomlText: string): ParsedLabelToml {
const data = parseToml(tomlText) as unknown as {
labels?: LabelDescription[];
auto_labels?: AutoLabel[];
};
return {
labels: data.labels ?? [],
autoLabels: data.auto_labels ?? [],
};
}
async function loadProfile(source: ProfileSource): Promise<Profile> {
switch (source.type) {
case 'FILE': {
console.log(`Loading profile from file ${source.path}`);
const bytes = fs.readFileSync(source.path, null);
const profile = await unserializeProfileOfArbitraryFormat(bytes);
if (profile === undefined) {
throw new Error('Unable to parse the profile.');
}
return profile;
}
case 'URL': {
console.log(`Loading profile from URL ${source.url}`);
const response = await fetch(source.url);
if (!response.ok) {
throw new Error(
`Unexpected response code: ${response.status} / ${response.statusText}`
);
}
const bytes = await response.arrayBuffer();
const profile = await unserializeProfileOfArbitraryFormat(
new Uint8Array(bytes)
);
if (profile === undefined) {
throw new Error('Unable to parse the profile.');
}
return profile;
}
case 'HASH': {
const url = `https://storage.googleapis.com/${GOOGLE_STORAGE_BUCKET}/${source.hash}`;
console.log(`Loading profile from hash ${source.hash}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Unexpected response code: ${response.status} / ${response.statusText}`
);
}
const bytes = await response.arrayBuffer();
const profile = await unserializeProfileOfArbitraryFormat(
new Uint8Array(bytes)
);
if (profile === undefined) {
throw new Error('Unable to parse the profile.');
}
return profile;
}
default:
throw assertExhaustiveCheck(source);
}
}
async function encodeProfileWithFilename(
profile: Profile,
filename: string
): Promise<Uint8Array> {
if (filename.endsWith('.jslb') || filename.endsWith('.jslb.gz')) {
const bytes = serializeProfileToJsonSlabsFile(
optimizeProfileForStorage(profile)
);
if (filename.endsWith('.jslb.gz')) {
return compress(bytes);
}
return bytes;
}
const s = serializeProfileToJsonString(profile);
if (filename.endsWith('.gz')) {
return compress(s);
}
return new TextEncoder().encode(s);
}
export async function run(options: CliOptions) {
let profile = await loadProfile(options.input);
if (options.symbolicateWithServer !== undefined) {
const server = options.symbolicateWithServer;
const symbolStore = new SymbolStore({
requestSymbolsFromServer: async (requests) => {
for (const { lib } of requests) {
console.log(` Loading symbols for ${lib.debugName}`);
}
try {
return await MozillaSymbolicationAPI.requestSymbols(
'symbol server',
requests,
async (path, json) => {
const response = await fetch(server + path, {
body: json,
method: 'POST',
});
return response.json();
}
);
} catch (e) {
throw new Error(
`There was a problem with the symbolication API request to the symbol server: ${e.message}`
);
}
},
requestSymbolsFromBrowser: async () => [],
requestSymbolsViaSymbolTableFromBrowser: async () => {
throw new Error('Not supported in this context');
},
});
console.log('Symbolicating...');
const symbolicationSteps: SymbolicationStepInfo[] = [];
await symbolicateProfile(profile, symbolStore, (step) => {
symbolicationSteps.push(step);
});
console.log('Applying collected symbolication steps...');
const { shared, threads } = applySymbolicationSteps(
profile.threads,
profile.shared,
symbolicationSteps
);
profile.shared = shared;
profile.threads = threads;
profile.meta.symbolicated = true;
}
applyWasmSymbolication(
profile,
loadWasmSymbolicationSpecs(options.symbolicateWasm)
);
if (options.insertLabelFrames !== undefined) {
console.log('Inserting label frames...');
const tomlText = fs.readFileSync(options.insertLabelFrames, 'utf8');
const parsed = parseLabelToml(tomlText);
const funcNames = collectFuncNames(profile);
const labels = resolveAllLabels(
parsed.autoLabels,
parsed.labels,
funcNames
);
profile = insertStackLabels(profile, labels);
}
if (
options.onlyKeepThreadsWithMarkersMatching !== undefined &&
options.onlyKeepThreadsWithMarkersMatching !== ''
) {
const before = profile.threads.length;
const matchingThreadIndexes = getThreadsWithMarkersMatchingSearchFilter(
profile,
options.onlyKeepThreadsWithMarkersMatching
);
const oldThreadIndexToNew = new Map<ThreadIndex, ThreadIndex>();
const matchingThreads: RawThread[] = [];
profile.threads.forEach((thread, oldIndex) => {
if (matchingThreadIndexes.has(oldIndex)) {
oldThreadIndexToNew.set(oldIndex, matchingThreads.length);
matchingThreads.push(thread);
}
});
profile = {
...profile,
threads: matchingThreads,
...remapCountersAndProfilerOverhead(profile, oldThreadIndexToNew),
};
console.log(
`Kept ${profile.threads.length} of ${before} threads with markers matching ${JSON.stringify(options.onlyKeepThreadsWithMarkersMatching)}.`
);
}
if (options.mergeNonOverlappingThreadsByName) {
profile = mergeNonOverlappingThreadsByName(profile);
}
if (options.setName !== undefined) {
profile.meta.product = options.setName;
}
const { profile: compactedProfile } = computeCompactedProfile(profile);
const outputFilename = options.output;
console.log(`Saving profile to ${outputFilename}`);
const bytes = await encodeProfileWithFilename(
compactedProfile,
outputFilename
);
fs.writeFileSync(outputFilename, bytes);
console.log('Finished.');
}
function collectWasm(
value: string,
previous: WasmSymbolicationCliSpec[]
): WasmSymbolicationCliSpec[] {
// Accept "<url>=<path>" if the LHS looks like a URL, otherwise treat the
// whole string as a path and infer the URL from the profile. Split on
// the last `=` so URLs containing `=` (e.g. in query strings) survive
// intact; this assumes file paths don't contain `=`.
const eqIndex = value.lastIndexOf('=');
if (eqIndex !== -1 && /^[a-z]+:\/\//i.test(value.slice(0, eqIndex))) {
return [
...previous,
{
strippedWasmUrl: value.slice(0, eqIndex),
unstrippedWasmPath: value.slice(eqIndex + 1),
},
];
}
return [...previous, { unstrippedWasmPath: value }];
}
function requireNonEmpty(flagName: string): (value: string) => string {
return (value: string) => {
if (value === '') {
throw new InvalidArgumentError(`${flagName} requires a non-empty value`);
}
return value;
};
}
export function makeOptionsFromArgv(processArgv: string[]): CliOptions {
const program = new Command();
program
.name('profiler-edit')
.description('Edit and transform Firefox performance profiles')
.exitOverride()
.option(
'-i, --input <fileOrUrl>',
'Input profile (file path or http(s) URL)'
)
.option('-o, --output <path>', 'Output path (.json or .json.gz)')
.option('--from-file <path>', 'Load input from a file')
.option('--from-url <url>', 'Load input from a URL')
.option('--from-hash <hash>', 'Load input from a profile hash')
.option(
'--symbolicate-with-server <url>',
'Symbolicate frames using this symbol server URL'
)
.addOption(
new Option(
'--symbolicate-wasm <spec>',
'Apply wasm symbol info, as <url>=<path> or just <path>'
)
.argParser(collectWasm)
.default([] as WasmSymbolicationCliSpec[])
)
.option('--insert-label-frames <path>', 'TOML file with label definitions')
.option(
'--only-keep-threads-with-markers-matching <search>',
'Keep only threads with markers matching the given search string'
)
.option(
'--merge-non-overlapping-threads-by-name',
'Merge same-named threads across non-overlapping process runs'
)
.option(
'--set-name <name>',
'Override the profile product name',
requireNonEmpty('--set-name')
);
program.parse(processArgv);
const opts = program.opts();
const sources: ProfileSource[] = [];
if (typeof opts.input === 'string' && opts.input !== '') {
if (/^https?:\/\//i.test(opts.input)) {
sources.push({ type: 'URL', url: opts.input });
} else {
sources.push({ type: 'FILE', path: opts.input });
}
}
if (typeof opts.fromFile === 'string' && opts.fromFile !== '') {
sources.push({ type: 'FILE', path: opts.fromFile });
}
if (typeof opts.fromUrl === 'string' && opts.fromUrl !== '') {
sources.push({ type: 'URL', url: opts.fromUrl });
}
if (typeof opts.fromHash === 'string' && opts.fromHash !== '') {
sources.push({ type: 'HASH', hash: opts.fromHash });
}
if (sources.length === 0) {
throw new Error(
'An input must be supplied: use -i <FILE_OR_URL>, --from-file <path>, --from-url <url>, or --from-hash <hash>'
);
}
if (sources.length > 1) {
throw new Error(
'Only one input may be supplied (-i, --from-file, --from-url, --from-hash)'
);
}
if (!(typeof opts.output === 'string' && opts.output !== '')) {
throw new Error('An output path must be supplied with --output / -o');
}
return {
input: sources[0],
output: opts.output,
symbolicateWithServer:
typeof opts.symbolicateWithServer === 'string' &&
opts.symbolicateWithServer !== ''
? opts.symbolicateWithServer
: undefined,
symbolicateWasm: opts.symbolicateWasm,
insertLabelFrames:
typeof opts.insertLabelFrames === 'string' &&
opts.insertLabelFrames !== ''
? opts.insertLabelFrames
: undefined,
onlyKeepThreadsWithMarkersMatching:
typeof opts.onlyKeepThreadsWithMarkersMatching === 'string' &&
opts.onlyKeepThreadsWithMarkersMatching !== ''
? opts.onlyKeepThreadsWithMarkersMatching
: undefined,
mergeNonOverlappingThreadsByName:
opts.mergeNonOverlappingThreadsByName === true,
setName: typeof opts.setName === 'string' ? opts.setName : undefined,
};
}
if (require.main === module) {
try {
const options = makeOptionsFromArgv(process.argv);
run(options).catch((err) => {
console.error(err);
process.exit(1);
});
} catch (err) {
if (err instanceof CommanderError) {
// Commander already wrote its own output and chose the
// appropriate exit code.
process.exit(err.exitCode);
}
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
}