-
-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathsimpleperf.js
More file actions
221 lines (200 loc) · 6.62 KB
/
simpleperf.js
File metadata and controls
221 lines (200 loc) · 6.62 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
import { getLogger } from '@sitespeed.io/log';
import path from 'node:path';
const { join } = path;
import { execa } from 'execa';
import { existsSync, renameSync } from 'node:fs';
import { Android, isAndroidConfigured } from '../../../android/index.js';
// const delay = ms => new Promise(res => setTimeout(res, ms));
/**
* Manages the collection of perfetto traces on Android.
*
* @class
* @hideconstructor
*/
const log = getLogger('browsertime.command.simpleperf');
const defaultRecordOptions =
'--call-graph fp --duration 240 -f 1000 --trace-offcpu -e cpu-clock';
/**
* Timeout a promise after ms. Use promise.race to compete
* about the timeout and the promise.
* @param {promise} promise - the promise to wait for
* @param {int} ms - how long in ms to wait for the promise to fininsh
* @param {string} errorMessage - the error message in the Error if we timeouts
*/
async function timeout(promise, ms, errorMessage) {
let timer;
return Promise.race([
new Promise((resolve, reject) => {
timer = setTimeout(reject, ms, new Error(errorMessage));
return timer;
}),
promise.then(value => {
clearTimeout(timer);
return value;
})
]);
}
export class SimplePerfProfiler {
constructor(browser, index, storageManager, options) {
/**
* @private
*/
this.browser = browser;
/**
* @private
*/
this.storageManager = storageManager;
/**
* @private
*/
this.options = options;
/**
* @private
*/
this.index = index;
/**
* @private
*/
this.running = false;
}
/**
* Start Simpleperf profiling.
*
* @async
* @returns {Promise<void>} A promise that resolves when simpleperf has started profiling.
* @throws {Error} Throws an error if app_profiler.py fails to execute.
*/
async start(
profilerOptions = [],
recordOptions = defaultRecordOptions,
dirName = 'simpleperf'
) {
if (!isAndroidConfigured(this.options)) {
throw new Error('Simpleperf profiling is only available on Android.');
}
log.info('Starting simpleperf profiler.');
// Create empty subdirectory for simpleperf data.
let dirname = `${dirName}-${this.index}`;
let counter = 0;
this.profilerOptions = profilerOptions;
while (true) {
log.info(`Checking if ${dirname} exists...`);
if (existsSync(join(this.storageManager.directory, dirname))) {
dirname = `${dirName}-${this.index}.${counter}`;
counter++;
log.info(`Directory already exists.`);
} else {
this.dataDir = await this.storageManager.createSubDataDir(dirname);
log.info(`Creating subdir ${this.dataDir}.`);
break;
}
}
// Execute simpleperf.
this.packageName =
this.options.browser === 'firefox'
? this.options.firefox?.android?.package
: this.options.chrome?.android?.package;
let simpleperfPath = this.options.androidSimpleperf;
let cmd = join(simpleperfPath, 'app_profiler.py');
let args = [
...profilerOptions,
'-p',
this.packageName,
'-r',
recordOptions,
'--log',
'debug',
'-o',
join(this.dataDir, 'perf.data')
];
this.simpleperfProcess = execa(cmd, args);
// Waiting for simpleperf to start.
let simpleperfPromise = new Promise((resolve, reject) => {
let stderrStream = this.simpleperfProcess.stderr;
stderrStream.on('data', data => {
let dataStr = data.toString();
log.info(dataStr);
if (/command 'record' starts running/.test(dataStr)) {
this.running = true;
stderrStream.removeAllListeners('data');
return resolve();
}
if (/Failed to record profiling data./.test(dataStr)) {
this.running = false;
log.info(`Error starting simpleperf: ${dataStr}`);
throw new Error('Simpleperf failed to start.');
}
});
stderrStream.once('error', reject);
});
// Set a 30s timeout for starting simpleperf.
return timeout(simpleperfPromise, 30_000, 'Simpleperf timed out.');
}
/**
* Stop Simpleperf profiling.
*
* @async
* @returns {Promise<void>} A promise that resolves when simpleperf has stopped profiling
* and collected profile data.
* @throws {Error} Throws an error if app_profiler.py fails to execute.
*/
async stop() {
if (!isAndroidConfigured(this.options)) {
throw new Error('Simpleperf profiling is only available on Android.');
}
if (!this.running) {
throw new Error('Simpleperf profiling was not started.');
}
log.info('Stop simpleperf profiler.');
this.simpleperfProcess.kill('SIGINT');
const pullJitMarkerFiles = async () => {
const android = new Android(this.options);
const filesDir = `/storage/emulated/0/Android/data/${this.packageName}/files`;
const listing = await android._runCommandAndGet(
`ls ${filesDir}/jit-* ${filesDir}/marker-* 2>/dev/null`
);
if (listing) {
for (const file of listing.split('\n').filter(f => f.trim())) {
const fileName = file.trim().split('/').pop();
await android._downloadFile(
file.trim(),
join(this.dataDir, fileName)
);
}
}
};
// Return when "profiling is finished." is found, or an error.
return new Promise((resolve, reject) => {
let stderrStream = this.simpleperfProcess.stderr;
log.info('Reading stderr.');
stderrStream.on('data', data => {
const dataStr = data.toString();
log.info(dataStr);
// Resolve immediately if -nb or --skip_collect_binaries is passed
// into the app_profiler options as a binary cache will not be produced.
if (
this.profilerOptions.includes('-nb') ||
this.profilerOptions.includes('--skip_collect_binaries')
) {
stderrStream.removeAllListeners('data');
// Pull any JIT dumps and marker files if possible.
pullJitMarkerFiles().then(resolve).catch(resolve);
return;
}
if (/profiling is finished./.test(dataStr)) {
stderrStream.removeAllListeners('data');
// There is no way to specify the output of binary_cache,
// so manually move it (if it exists) into the data directory.
if (existsSync('binary_cache')) {
renameSync('binary_cache', join(this.dataDir, 'binary_cache'));
} else {
log.info('binary_cache does not exist.');
}
pullJitMarkerFiles().then(resolve).catch(resolve);
return;
}
});
stderrStream.once('error', reject);
});
}
}