blob: 9b85de67e667a1eb28f5d6fb26b0d64bab8edfbc [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 {
19 Action,
20 addChromeSliceTrack,
21 addTrack,
22 navigate,
23 setEngineReady,
24 setTraceTime,
25 setVisibleTraceTime,
26 updateStatus
27} from '../common/actions';
28import {TimeSpan} from '../common/time';
29import {QuantizedLoad, ThreadDesc} from '../frontend/globals';
30import {SLICE_TRACK_KIND} from '../tracks/chrome_slices/common';
31import {CPU_SLICE_TRACK_KIND} from '../tracks/cpu_slices/common';
32
33import {Child, Children, Controller} from './controller';
34import {Engine} from './engine';
35import {globals} from './globals';
36import {QueryController, QueryControllerArgs} from './query_controller';
37import {TrackControllerArgs, trackControllerRegistry} from './track_controller';
38
39type States = 'init'|'loading_trace'|'ready';
40
41
Primiano Tucci7e330292018-08-24 19:10:52 +020042declare interface FileReaderSync { readAsArrayBuffer(blob: Blob): ArrayBuffer; }
43
44declare var FileReaderSync:
45 {prototype: FileReaderSync; new (): FileReaderSync;};
46
Primiano Tuccie36ca632018-08-21 14:32:23 +020047// TraceController handles handshakes with the frontend for everything that
48// concerns a single trace. It owns the WASM trace processor engine, handles
49// tracks data and SQL queries. There is one TraceController instance for each
50// trace opened in the UI (for now only one trace is supported).
51export class TraceController extends Controller<States> {
52 private readonly engineId: string;
53 private engine?: Engine;
54
55 constructor(engineId: string) {
56 super('init');
57 this.engineId = engineId;
58 }
59
Primiano Tucci7e330292018-08-24 19:10:52 +020060 onDestroy() {
61 if (this.engine !== undefined) globals.destroyEngine(this.engine.id);
62 }
63
Primiano Tuccie36ca632018-08-21 14:32:23 +020064 run() {
65 const engineCfg = assertExists(globals.state.engines[this.engineId]);
66 switch (this.state) {
67 case 'init':
68 globals.dispatch(setEngineReady(this.engineId, false));
69 this.loadTrace().then(() => {
70 globals.dispatch(setEngineReady(this.engineId, true));
71 });
72 globals.dispatch(updateStatus('Opening trace'));
73 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() {
Primiano Tucci7e330292018-08-24 19:10:52 +0200114 globals.dispatch(updateStatus('Creating trace processor'));
Primiano Tuccie36ca632018-08-21 14:32:23 +0200115 const engineCfg = assertExists(globals.state.engines[this.engineId]);
Primiano Tucci7e330292018-08-24 19:10:52 +0200116 this.engine = await globals.createEngine();
117
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);
128 globals.dispatch(updateStatus(`${statusHeader} ${progress} %`));
129 }
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) {
133 globals.dispatch(updateStatus(`HTTP error ${resp.status}`));
134 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)`;
156 globals.dispatch(updateStatus(status));
157 }
158 if (readRes.done) break;
159 }
Primiano Tuccie36ca632018-08-21 14:32:23 +0200160 }
161
Primiano Tuccie36ca632018-08-21 14:32:23 +0200162 const traceTime = await this.engine.getTraceTimeBounds();
163 const actions = [
164 setTraceTime(traceTime),
165 navigate('/viewer'),
166 ];
167
168 if (globals.state.visibleTraceTime.lastUpdate === 0) {
169 actions.push(setVisibleTraceTime(traceTime));
170 }
171
172 globals.dispatchMultiple(actions);
173
174 await this.listTracks();
175 await this.listThreads();
176 await this.loadTimelineOverview(traceTime);
177 }
178
179 private async listTracks() {
180 globals.dispatch(updateStatus('Loading tracks'));
181 const engine = assertExists<Engine>(this.engine);
182 const addToTrackActions: Action[] = [];
183 const numCpus = await engine.getNumberOfCpus();
184 for (let cpu = 0; cpu < numCpus; cpu++) {
185 addToTrackActions.push(
186 addTrack(this.engineId, CPU_SLICE_TRACK_KIND, cpu));
187 }
188
189 const threadQuery = await engine.rawQuery({
190 sqlQuery: 'select upid, utid, tid, thread.name, max(slices.depth) ' +
191 'from thread inner join slices using(utid) group by utid'
192 });
193 for (let i = 0; i < threadQuery.numRecords; i++) {
194 const upid = threadQuery.columns[0].longValues![i];
195 const utid = threadQuery.columns[1].longValues![i];
196 const threadId = threadQuery.columns[2].longValues![i];
197 let threadName = threadQuery.columns[3].stringValues![i];
198 threadName += `[${threadId}]`;
199 const maxDepth = threadQuery.columns[4].longValues![i];
200 addToTrackActions.push(addChromeSliceTrack(
201 this.engineId,
202 SLICE_TRACK_KIND,
203 upid as number,
204 utid as number,
205 threadName,
206 maxDepth as number));
207 }
208 globals.dispatchMultiple(addToTrackActions);
209 }
210
211 private async listThreads() {
212 globals.dispatch(updateStatus('Reading thread list'));
213 const sqlQuery = 'select utid, tid, pid, thread.name, process.name ' +
214 'from thread inner join process using(upid)';
215 const threadRows = await assertExists(this.engine).rawQuery({sqlQuery});
216 const threads: ThreadDesc[] = [];
217 for (let i = 0; i < threadRows.numRecords; i++) {
218 const utid = threadRows.columns[0].longValues![i] as number;
219 const tid = threadRows.columns[1].longValues![i] as number;
220 const pid = threadRows.columns[2].longValues![i] as number;
221 const threadName = threadRows.columns[3].stringValues![i];
222 const procName = threadRows.columns[4].stringValues![i];
223 threads.push({utid, tid, threadName, pid, procName});
224 } // for (record ...)
225 globals.publish('Threads', threads);
226 }
227
228 private async loadTimelineOverview(traceTime: TimeSpan) {
229 const engine = assertExists<Engine>(this.engine);
230 const numSteps = 100;
231 const stepSec = traceTime.duration / numSteps;
232 for (let step = 0; step < numSteps; step++) {
233 globals.dispatch(updateStatus(
234 'Loading overview ' +
235 `${Math.round((step + 1) / numSteps * 1000) / 10}%`));
236 const startSec = traceTime.start + step * stepSec;
237 const startNs = Math.floor(startSec * 1e9);
238 const endSec = startSec + stepSec;
239 const endNs = Math.ceil(endSec * 1e9);
240
241 // Sched overview.
242 const schedRows = await engine.rawQuery({
243 sqlQuery: `select sum(dur)/${stepSec}/1e9, cpu from sched ` +
244 `where ts >= ${startNs} and ts < ${endNs} ` +
245 'group by cpu order by cpu'
246 });
247 const schedData: {[key: string]: QuantizedLoad} = {};
248 for (let i = 0; i < schedRows.numRecords; i++) {
249 const load = schedRows.columns[0].doubleValues![i];
250 const cpu = schedRows.columns[1].longValues![i] as number;
251 schedData[cpu] = {startSec, endSec, load};
252 } // for (record ...)
253 globals.publish('OverviewData', schedData);
254
255 // Slices overview.
256 const slicesRows = await engine.rawQuery({
257 sqlQuery:
258 `select sum(dur)/${stepSec}/1e9, process.name, process.pid, upid ` +
259 'from slices inner join thread using(utid) ' +
260 'inner join process using(upid) where depth = 0 ' +
261 `and ts >= ${startNs} and ts < ${endNs} ` +
262 'group by upid'
263 });
264 const slicesData: {[key: string]: QuantizedLoad} = {};
265 for (let i = 0; i < slicesRows.numRecords; i++) {
266 const load = slicesRows.columns[0].doubleValues![i];
267 let procName = slicesRows.columns[1].stringValues![i];
268 const pid = slicesRows.columns[2].longValues![i];
269 procName += ` [${pid}]`;
270 slicesData[procName] = {startSec, endSec, load};
271 }
272 globals.publish('OverviewData', slicesData);
273 } // for (step ...)
274 }
275}