blob: 565a2c6b5906c905132f71f5b24f37dd820a1f20 [file] [log] [blame]
Primiano Tuccie36ca632018-08-21 14:32:23 +02001// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import '../tracks/all_controller';
16
17import {assertExists, assertTrue} from '../base/logging';
18import {
Hector Dearman4d8d73d2018-10-04 13:16:29 +010019 Actions,
Hector Dearman5ae82472018-10-03 08:30:35 +010020 DeferredAction,
Primiano Tuccie36ca632018-08-21 14:32:23 +020021} from '../common/actions';
22import {TimeSpan} from '../common/time';
23import {QuantizedLoad, ThreadDesc} from '../frontend/globals';
24import {SLICE_TRACK_KIND} from '../tracks/chrome_slices/common';
25import {CPU_SLICE_TRACK_KIND} from '../tracks/cpu_slices/common';
26
27import {Child, Children, Controller} from './controller';
28import {Engine} from './engine';
29import {globals} from './globals';
30import {QueryController, QueryControllerArgs} from './query_controller';
31import {TrackControllerArgs, trackControllerRegistry} from './track_controller';
32
33type States = 'init'|'loading_trace'|'ready';
34
35
Primiano Tucci7e330292018-08-24 19:10:52 +020036declare interface FileReaderSync { readAsArrayBuffer(blob: Blob): ArrayBuffer; }
37
38declare var FileReaderSync:
39 {prototype: FileReaderSync; new (): FileReaderSync;};
40
Primiano Tuccie36ca632018-08-21 14:32:23 +020041// TraceController handles handshakes with the frontend for everything that
42// concerns a single trace. It owns the WASM trace processor engine, handles
43// tracks data and SQL queries. There is one TraceController instance for each
44// trace opened in the UI (for now only one trace is supported).
45export class TraceController extends Controller<States> {
46 private readonly engineId: string;
47 private engine?: Engine;
48
49 constructor(engineId: string) {
50 super('init');
51 this.engineId = engineId;
52 }
53
Primiano Tucci7e330292018-08-24 19:10:52 +020054 onDestroy() {
55 if (this.engine !== undefined) globals.destroyEngine(this.engine.id);
56 }
57
Primiano Tuccie36ca632018-08-21 14:32:23 +020058 run() {
59 const engineCfg = assertExists(globals.state.engines[this.engineId]);
60 switch (this.state) {
61 case 'init':
Hector Dearman4d8d73d2018-10-04 13:16:29 +010062 globals.dispatch(Actions.setEngineReady({
63 engineId: this.engineId,
64 ready: false,
65 }));
Primiano Tuccie36ca632018-08-21 14:32:23 +020066 this.loadTrace().then(() => {
Hector Dearman4d8d73d2018-10-04 13:16:29 +010067 globals.dispatch(Actions.setEngineReady({
68 engineId: this.engineId,
69 ready: true,
70 }));
Primiano Tuccie36ca632018-08-21 14:32:23 +020071 });
Hector Dearman4d8d73d2018-10-04 13:16:29 +010072 this.updateStatus('Opening trace');
Primiano Tuccie36ca632018-08-21 14:32:23 +020073 this.setState('loading_trace');
74 break;
75
76 case 'loading_trace':
77 // Stay in this state until loadTrace() returns and marks the engine as
78 // ready.
79 if (this.engine === undefined || !engineCfg.ready) return;
80 this.setState('ready');
81 break;
82
83 case 'ready':
84 // At this point we are ready to serve queries and handle tracks.
85 const engine = assertExists(this.engine);
86 assertTrue(engineCfg.ready);
87 const childControllers: Children = [];
88
89 // Create a TrackController for each track.
90 for (const trackId of Object.keys(globals.state.tracks)) {
91 const trackCfg = globals.state.tracks[trackId];
92 if (trackCfg.engineId !== this.engineId) continue;
93 if (!trackControllerRegistry.has(trackCfg.kind)) continue;
94 const trackCtlFactory = trackControllerRegistry.get(trackCfg.kind);
95 const trackArgs: TrackControllerArgs = {trackId, engine};
96 childControllers.push(Child(trackId, trackCtlFactory, trackArgs));
97 }
98
99 // Create a QueryController for each query.
100 for (const queryId of Object.keys(globals.state.queries)) {
101 const queryArgs: QueryControllerArgs = {queryId, engine};
102 childControllers.push(Child(queryId, QueryController, queryArgs));
103 }
104
105 return childControllers;
106
107 default:
108 throw new Error(`unknown state ${this.state}`);
109 }
110 return;
111 }
112
113 private async loadTrace() {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100114 this.updateStatus('Creating trace processor');
Primiano Tuccie36ca632018-08-21 14:32:23 +0200115 const engineCfg = assertExists(globals.state.engines[this.engineId]);
Hector Dearman03159542018-09-19 18:37:00 +0100116 this.engine = globals.createEngine();
Primiano Tucci7e330292018-08-24 19:10:52 +0200117
118 const statusHeader = 'Opening trace';
Primiano Tuccie36ca632018-08-21 14:32:23 +0200119 if (engineCfg.source instanceof File) {
Primiano Tucci7e330292018-08-24 19:10:52 +0200120 const blob = engineCfg.source as Blob;
121 const reader = new FileReaderSync();
122 const SLICE_SIZE = 1024 * 1024;
123 for (let off = 0; off < blob.size; off += SLICE_SIZE) {
124 const slice = blob.slice(off, off + SLICE_SIZE);
125 const arrBuf = reader.readAsArrayBuffer(slice);
126 await this.engine.parse(new Uint8Array(arrBuf));
127 const progress = Math.round((off + slice.size) / blob.size * 100);
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100128 this.updateStatus(`${statusHeader} ${progress} %`);
Primiano Tucci7e330292018-08-24 19:10:52 +0200129 }
Primiano Tuccie36ca632018-08-21 14:32:23 +0200130 } else {
Primiano Tucci7e330292018-08-24 19:10:52 +0200131 const resp = await fetch(engineCfg.source);
132 if (resp.status !== 200) {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100133 this.updateStatus(`HTTP error ${resp.status}`);
Primiano Tucci7e330292018-08-24 19:10:52 +0200134 throw new Error(`fetch() failed with HTTP error ${resp.status}`);
135 }
136 // tslint:disable-next-line no-any
137 const rd = (resp.body as any).getReader() as ReadableStreamReader;
138 const tStartMs = performance.now();
139 let tLastUpdateMs = 0;
140 for (let off = 0;;) {
141 const readRes = await rd.read() as {value: Uint8Array, done: boolean};
142 if (readRes.value !== undefined) {
143 off += readRes.value.length;
144 await this.engine.parse(readRes.value);
145 }
146 // For traces loaded from the network there doesn't seem to be a
147 // reliable way to compute the %. The content-length exposed by GCS is
148 // before compression (which is handled transparently by the browser).
149 const nowMs = performance.now();
150 if (nowMs - tLastUpdateMs > 100) {
151 tLastUpdateMs = nowMs;
152 const mb = off / 1e6;
153 const tElapsed = (nowMs - tStartMs) / 1e3;
154 let status = `${statusHeader} ${mb.toFixed(1)} MB `;
155 status += `(${(mb / tElapsed).toFixed(1)} MB/s)`;
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100156 this.updateStatus(status);
Primiano Tucci7e330292018-08-24 19:10:52 +0200157 }
158 if (readRes.done) break;
159 }
Primiano Tuccie36ca632018-08-21 14:32:23 +0200160 }
161
Hector Dearman1d289212018-09-05 14:05:29 +0100162 await this.engine.notifyEof();
163
Primiano Tuccie36ca632018-08-21 14:32:23 +0200164 const traceTime = await this.engine.getTraceTimeBounds();
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100165 const traceTimeState = {
166 startSec: traceTime.start,
167 endSec: traceTime.end,
168 lastUpdate: Date.now() / 1000,
169 };
Primiano Tuccie36ca632018-08-21 14:32:23 +0200170 const actions = [
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100171 Actions.setTraceTime(traceTimeState),
172 Actions.navigate({route: '/viewer'}),
Primiano Tuccie36ca632018-08-21 14:32:23 +0200173 ];
174
175 if (globals.state.visibleTraceTime.lastUpdate === 0) {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100176 actions.push(Actions.setVisibleTraceTime(traceTimeState));
Primiano Tuccie36ca632018-08-21 14:32:23 +0200177 }
178
179 globals.dispatchMultiple(actions);
180
181 await this.listTracks();
182 await this.listThreads();
183 await this.loadTimelineOverview(traceTime);
184 }
185
186 private async listTracks() {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100187 this.updateStatus('Loading tracks');
Primiano Tuccie36ca632018-08-21 14:32:23 +0200188 const engine = assertExists<Engine>(this.engine);
Hector Dearman5ae82472018-10-03 08:30:35 +0100189 const addToTrackActions: DeferredAction[] = [];
Primiano Tuccie36ca632018-08-21 14:32:23 +0200190 const numCpus = await engine.getNumberOfCpus();
Hector Dearmane27a9742018-10-12 09:31:34 +0100191
192 // TODO(hjd): Move this code out of TraceController.
193 for (const counterName of ['VSYNC-sf', 'VSYNC-app']) {
194 const hasVsync =
195 !!(await engine.query(
196 `select ts from counters where name like "${
197 counterName
198 }" limit 1`))
199 .numRecords;
200 if (!hasVsync) continue;
201 addToTrackActions.push(Actions.addTrack({
202 engineId: this.engineId,
203 kind: 'VsyncTrack',
204 name: `${counterName}`,
205 config: {
206 counterName,
207 }
208 }));
209 }
210
Primiano Tuccie36ca632018-08-21 14:32:23 +0200211 for (let cpu = 0; cpu < numCpus; cpu++) {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100212 addToTrackActions.push(Actions.addTrack({
213 engineId: this.engineId,
214 kind: CPU_SLICE_TRACK_KIND,
215 name: `Cpu ${cpu}`,
216 config: {
217 cpu,
218 }
219 }));
Primiano Tuccie36ca632018-08-21 14:32:23 +0200220 }
221
Hector Dearmandbf46342018-10-04 17:28:38 +0100222 const threadQuery = await engine.query(`
223 select upid, utid, tid, thread.name, depth
224 from thread inner join (
225 select utid, max(slices.depth) as depth
226 from slices
227 group by utid
228 ) using(utid)`);
Primiano Tuccie36ca632018-08-21 14:32:23 +0200229 for (let i = 0; i < threadQuery.numRecords; i++) {
230 const upid = threadQuery.columns[0].longValues![i];
231 const utid = threadQuery.columns[1].longValues![i];
232 const threadId = threadQuery.columns[2].longValues![i];
233 let threadName = threadQuery.columns[3].stringValues![i];
234 threadName += `[${threadId}]`;
235 const maxDepth = threadQuery.columns[4].longValues![i];
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100236 addToTrackActions.push(Actions.addTrack({
237 engineId: this.engineId,
238 kind: SLICE_TRACK_KIND,
239 name: threadName,
240 config: {
241 upid: upid as number,
242 utid: utid as number,
243 maxDepth: maxDepth as number,
244 }
245 }));
Primiano Tuccie36ca632018-08-21 14:32:23 +0200246 }
247 globals.dispatchMultiple(addToTrackActions);
248 }
249
250 private async listThreads() {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100251 this.updateStatus('Reading thread list');
Primiano Tuccie36ca632018-08-21 14:32:23 +0200252 const sqlQuery = 'select utid, tid, pid, thread.name, process.name ' +
253 'from thread inner join process using(upid)';
Hector Dearmane6dfe412018-09-20 14:12:13 +0100254 const threadRows = await assertExists(this.engine).query(sqlQuery);
Primiano Tuccie36ca632018-08-21 14:32:23 +0200255 const threads: ThreadDesc[] = [];
256 for (let i = 0; i < threadRows.numRecords; i++) {
257 const utid = threadRows.columns[0].longValues![i] as number;
258 const tid = threadRows.columns[1].longValues![i] as number;
259 const pid = threadRows.columns[2].longValues![i] as number;
260 const threadName = threadRows.columns[3].stringValues![i];
261 const procName = threadRows.columns[4].stringValues![i];
262 threads.push({utid, tid, threadName, pid, procName});
263 } // for (record ...)
264 globals.publish('Threads', threads);
265 }
266
267 private async loadTimelineOverview(traceTime: TimeSpan) {
268 const engine = assertExists<Engine>(this.engine);
269 const numSteps = 100;
270 const stepSec = traceTime.duration / numSteps;
271 for (let step = 0; step < numSteps; step++) {
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100272 this.updateStatus(
Primiano Tuccie36ca632018-08-21 14:32:23 +0200273 'Loading overview ' +
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100274 `${Math.round((step + 1) / numSteps * 1000) / 10}%`);
Primiano Tuccie36ca632018-08-21 14:32:23 +0200275 const startSec = traceTime.start + step * stepSec;
276 const startNs = Math.floor(startSec * 1e9);
277 const endSec = startSec + stepSec;
278 const endNs = Math.ceil(endSec * 1e9);
279
280 // Sched overview.
Hector Dearmane6dfe412018-09-20 14:12:13 +0100281 const schedRows = await engine.query(
282 `select sum(dur)/${stepSec}/1e9, cpu from sched ` +
283 `where ts >= ${startNs} and ts < ${endNs} and utid != 0 ` +
284 'group by cpu order by cpu');
Primiano Tuccie36ca632018-08-21 14:32:23 +0200285 const schedData: {[key: string]: QuantizedLoad} = {};
286 for (let i = 0; i < schedRows.numRecords; i++) {
287 const load = schedRows.columns[0].doubleValues![i];
288 const cpu = schedRows.columns[1].longValues![i] as number;
289 schedData[cpu] = {startSec, endSec, load};
290 } // for (record ...)
291 globals.publish('OverviewData', schedData);
292
293 // Slices overview.
Hector Dearmane6dfe412018-09-20 14:12:13 +0100294 const slicesRows = await engine.query(
295 `select sum(dur)/${stepSec}/1e9, process.name, process.pid, upid ` +
296 'from slices inner join thread using(utid) ' +
297 'inner join process using(upid) where depth = 0 ' +
298 `and ts >= ${startNs} and ts < ${endNs} ` +
299 'group by upid');
Primiano Tuccie36ca632018-08-21 14:32:23 +0200300 const slicesData: {[key: string]: QuantizedLoad} = {};
301 for (let i = 0; i < slicesRows.numRecords; i++) {
302 const load = slicesRows.columns[0].doubleValues![i];
303 let procName = slicesRows.columns[1].stringValues![i];
304 const pid = slicesRows.columns[2].longValues![i];
305 procName += ` [${pid}]`;
306 slicesData[procName] = {startSec, endSec, load};
307 }
308 globals.publish('OverviewData', slicesData);
309 } // for (step ...)
310 }
Hector Dearman4d8d73d2018-10-04 13:16:29 +0100311
312 private updateStatus(msg: string): void {
313 globals.dispatch(Actions.updateStatus({
314 msg,
315 timestamp: Date.now() / 1000,
316 }));
317 }
Primiano Tuccie36ca632018-08-21 14:32:23 +0200318}