• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
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 */
15
16import './sql-wasm.js'
17import {CpuStruct} from "../bean/CpuStruct.js";
18import {CpuFreqStruct} from "../bean/CpuFreqStruct.js";
19import {ThreadStruct} from "../bean/ThreadStruct.js";
20import {ProcessMemStruct} from "../bean/ProcessMemStruct.js";
21import {Counter, Fps, SelectionData} from "../bean/BoxSelection.js";
22import {FuncStruct} from "../bean/FuncStruct.js";
23import {WakeUpTimeBean} from "../bean/WakeUpTimeBean.js";
24import {WakeupBean} from "../bean/WakeupBean.js";
25import {BinderArgBean} from "../bean/BinderArgBean.js";
26import {FpsStruct} from "../bean/FpsStruct.js";
27import {HeapBean} from "../bean/HeapBean.js";
28import {SPTChild, StateProcessThread} from "../bean/StateProcessThread.js";
29import {CpuUsage, Freq} from "../bean/CpuUsage.js";
30import {HeapStruct} from "../bean/HeapStruct.js";
31
32class DbThread extends Worker {
33    busy: boolean = false;
34    isCancelled: boolean = false;
35    id: number = -1;
36    taskMap: any = {};
37    cacheArray: Array<any> = [];
38
39    uuid(): string {
40        // @ts-ignore
41        return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
42    }
43
44    queryFunc(name: string, sql: string, args: any, handler: Function) {
45        this.busy = true;
46        let id = this.uuid();
47        this.taskMap[id] = handler
48        this.postMessage({
49            id: id,
50            name: name,
51            action: "exec",
52            sql: sql,
53            params: args,
54        })
55    }
56
57    dbOpen = async (): Promise<{status:boolean,msg:string} > => {
58        return new Promise<any>((resolve, reject) => {
59            let id = this.uuid();
60            this.taskMap[id] = (res: any) => {
61                if(res.init) {
62                    resolve({status:res.init,msg: res.msg});
63                } else {
64                    resolve({status:res.init,msg: res.msg});
65                }
66            }
67            this.postMessage({
68                id: id,
69                action: "open",
70                buffer: DbPool.sharedBuffer!, /*Optional. An ArrayBuffer representing an SQLite Database file*/
71            }, [DbPool.sharedBuffer!]);
72        })
73    }
74}
75
76export class DbPool {
77    maxThreadNumber: number = 0;
78    works: Array<DbThread> = [];
79    static sharedBuffer: ArrayBuffer | null = null;
80    progress: Function | undefined | null;
81    init = async (type: string, threadBuild: (() => DbThread) | undefined = undefined) => { // wasm | server | sqlite
82        await this.close();
83        if (type === "wasm") {
84            this.maxThreadNumber = 1;
85        } else if (type === "server") {
86            this.maxThreadNumber = 1;
87        } else if (type === "sqlite") {
88            this.maxThreadNumber = 1;
89        }
90        for (let i = 0; i < this.maxThreadNumber; i++) {
91            let thread: DbThread
92            if (threadBuild) {
93                thread = threadBuild()
94            } else {
95                if (type === "wasm") {
96                    thread = new DbThread("trace/database/TraceWorker.js")
97                } else if (type === "server") {
98                    thread = new DbThread("trace/database/SqlLiteWorker.js")
99                } else if (type === "sqlite") {
100                    thread = new DbThread("trace/database/SqlLiteWorker.js")
101                }
102                // thread = new DbThread("trace/database/worker.sql-wasm.js")
103            }
104            thread!.onmessage = (event: MessageEvent) => {
105                thread.busy = false;
106                if (Reflect.has(thread.taskMap, event.data.id)) {
107                    if (event.data.results) {
108                        let fun = thread.taskMap[event.data.id];
109                        if (fun) {
110                            fun(event.data.results);
111                        }
112                        Reflect.deleteProperty(thread.taskMap, event.data.id);
113                    } else if (Reflect.has(event.data, 'ready')) {
114                        let num=Math.floor(Math.random()*10+1)+20;
115                        this.progress!("database opened", num + event.data.index)
116                    } else if (Reflect.has(event.data, 'init')) {
117                        this.progress!("database ready", 40)
118                        let fun = thread.taskMap[event.data.id];
119                        if (fun) {
120                            fun(event.data)
121                        }
122                        Reflect.deleteProperty(thread.taskMap, event.data.id)
123                    } else {
124                        let fun = thread.taskMap[event.data.id];
125                        if (fun) {
126                            fun([])
127                        }
128                        Reflect.deleteProperty(thread.taskMap, event.data.id)
129                    }
130                } else {
131                }
132            }
133            thread!.onmessageerror = e => {
134            }
135            thread!.onerror = e => {
136            }
137            thread!.id = i;
138            thread!.busy = false;
139            this.works?.push(thread!);
140        }
141    }
142
143    initServer = async (url: string, progress: Function) => {
144        this.progress = progress;
145        progress("database loaded", 15)
146        let buf = await fetch(url).then(res => res.arrayBuffer());
147        DbPool.sharedBuffer = buf;
148        progress("open database", 20)
149        for (let i = 0; i < this.works.length; i++) {
150            let thread = this.works[i];
151            let {status,msg} = await thread.dbOpen()
152            if(!status){
153                return {status,msg}
154            }
155        }
156        return {status:true,msg:"ok"};
157    }
158    initSqlite = async (buf: ArrayBuffer, progress: Function) =>{
159        this.progress = progress;
160        progress("database loaded", 15)
161        DbPool.sharedBuffer = buf;
162        progress("parse database", 20)
163        for (let i = 0; i < this.works.length; i++) {
164            let thread = this.works[i];
165            let {status,msg} = await thread.dbOpen()
166            if(!status){
167                return {status,msg}
168            }
169        }
170        return {status:true,msg:"ok"};
171    }
172
173    close = async () => {
174        for (let i = 0; i < this.works.length; i++) {
175            let thread = this.works[i];
176            thread.terminate();
177        }
178        this.works.length = 0;
179    }
180
181    submit(name: string, sql: string, args: any, handler: Function) {
182        let noBusyThreads = this.works.filter(it => !it.busy);
183        let thread: DbThread
184        if (noBusyThreads.length > 0) {
185            thread = noBusyThreads[0];
186            thread.queryFunc(name, sql, args, handler)
187        } else {
188            thread = this.works[Math.floor(Math.random() * this.works.length)]
189            thread.queryFunc(name, sql, args, handler)
190        }
191    }
192}
193
194export const threadPool = new DbPool()
195
196function query<T extends any>(name: string, sql: string, args: any = null): Promise<Array<T>> {
197    return new Promise<Array<T>>((resolve, reject) => {
198        threadPool.submit(name, sql, args, (res: any) => {
199            resolve(res)
200        })
201    })
202}
203
204
205/*-------------------------------------------------------------------------------------*/
206export const queryProcess = (): Promise<Array<{
207    pid: number | null
208    processName: string | null
209}>> =>
210    query("queryProcess", `SELECT pid,processName FROM temp_query_process`)
211/*-------------------------------------------------------------------------------------*/
212export const queryTotalTime = (): Promise<Array<{ total: number }>> =>
213    query("queryTotalTime", `select end_ts-start_ts as total from trace_section;`)
214/*-------------------------------------------------------------------------------------*/
215export const queryCpu = async (): Promise<Array<{ cpu: number }>> =>
216    query("queryCpu", `select cpu from cpu_measure_filter where name='cpu_idle' order by cpu;`)
217/*-------------------------------------------------------------------------------------*/
218export const getAsyncEvents = (): Promise<Array<any>> =>
219    query("getAsyncEvents", `select *,p.pid as pid,c.ts - t.start_ts as "startTime" from callstack c,trace_section t
220left join process p on c.callid = p.id where cookie is not null;`)
221
222export const getCpuUtilizationRate = (startNS: number, endNS: number): Promise<Array<{
223    cpu: number
224    ro: number
225    rate: number
226}>> =>
227    query("getCpuUtilizationRate", `select * from temp_get_cpu_rate;`, {})
228/*-------------------------------------------------------------------------------------*/
229export const getFps = () =>
230    query<FpsStruct>("getFps", `select distinct(ts-tb.start_ts) as startNS,fps
231from hidump c ,trace_section tb
232where startNS >= 0
233order by startNS;`, {})
234
235/*-------------------------------------------------------------------------------------*/
236export const getFunDataByTid = (tid: number): Promise<Array<FuncStruct>> =>
237    query("getFunDataByTid", `select * from temp_query_thread_function where tid = $tid`, {$tid: tid})
238/*-------------------------------------------------------------------------------------*/
239export const getTabStatesGroupByProcessThread = (leftNs: number, rightNs: number): Promise<Array<StateProcessThread>> =>
240    query<StateProcessThread>("getTabStatesGroupByProcessThread", `select IP.name as process,
241       IP.pid as processId,
242       A.name as thread,
243       a.tid as threadId,
244    sum(B.dur) as wallDuration,
245    round(avg(B.dur),2) as avgDuration,
246    min(B.dur) as minDuration,
247    max(B.dur) as maxDuration,
248    --round(stdev(B.dur),2) as stdDuration,
249    count(A.tid) as count
250from thread_state AS B
251    left join  thread as A on B.itid = A.id
252    left join process AS IP on A.ipid = IP.id
253    left join trace_section AS TR
254where pid not null and
255    B.dur > 0 and
256    not ((ts - TR.start_ts + dur < $leftNS) or (ts - TR.start_ts > $rightNS))
257group by IP.name, IP.pid,thread,threadId
258order by wallDuration`, {$leftNS: leftNs, $rightNS: rightNs})
259
260export const getTabStatesGroupByProcess = (leftNs: number, rightNs: number): Promise<Array<StateProcessThread>> =>
261    query<StateProcessThread>("getTabStatesGroupByProcess", `select IP.name as process,IP.pid as processId,
262       sum(dur) as wallDuration,
263       round(avg(dur),2) as avgDuration,
264       min(dur) as minDuration,
265       max(dur) as maxDuration,
266       --round(stdev(dur),2) as stdDuration,
267       count(Ip.id) as count
268from thread_state as A,trace_section as B
269    left join  thread as C on A.itid = C.id
270    left join process AS IP on C.ipid = IP.id
271where A.dur > 0 and processId not null and not ((ts - B.start_ts + dur < $leftNS) or (ts - B.start_ts > $rightNS))
272group by process,processId`, {$leftNS: leftNs, $rightNS: rightNs});
273
274export const getTabStatesGroupByState = (leftNs: number, rightNs: number): Promise<Array<StateProcessThread>> =>
275    query<StateProcessThread>("getTabStatesGroupByState", `select state,
276       sum(dur) as wallDuration,
277       round(avg(dur),2) as avgDuration,
278       min(dur) as minDuration,
279       max(dur) as maxDuration,
280       --round(stdev(dur),2) as stdDuration,
281       count(state) as count
282from thread_state as A,trace_section as B
283    left join  thread as C on A.itid = C.id
284    left join process AS IP on C.ipid = IP.id
285where A.dur > 0 and IP.pid not null and not ((ts - B.start_ts + dur < $leftNS) or (ts - B.start_ts > $rightNS))
286group by state`, {$leftNS: leftNs, $rightNS: rightNs});
287
288export const getTabStatesGroupByStatePid = (leftNs: number, rightNs: number): Promise<Array<StateProcessThread>> =>
289    query<StateProcessThread>("getTabStatesGroupByStatePid", `select IP.name as process,
290       IP.pid as processId,
291       B.state as state,
292    sum(B.dur) as wallDuration,
293    round(avg(B.dur),2) as avgDuration,
294    min(B.dur) as minDuration,
295    max(B.dur) as maxDuration,
296    --round(stdev(B.dur),2) as stdDuration,
297    count(A.tid) as count
298from thread_state AS B
299    left join  thread as A on B.itid = A.id
300    left join process AS IP on A.ipid = IP.id
301    left join trace_section AS TR
302where pid not null and
303    B.dur > 0 and
304    not ((ts - TR.start_ts + dur < $leftNS) or (ts - TR.start_ts > $rightNS))
305group by IP.name, IP.pid,state
306order by wallDuration`, {$leftNS: leftNs, $rightNS: rightNs});
307
308export const getTabStatesGroupByStatePidTid = (leftNs: number, rightNs: number): Promise<Array<StateProcessThread>> =>
309    query<StateProcessThread>("getTabStatesGroupByStatePidTid", `select  IP.name as process,
310    IP.pid as processId,
311    A.name as thread,
312    B.state as state,
313    A.tid as threadId,
314    sum(B.dur) as wallDuration,
315    round(avg(B.dur),2) as avgDuration,
316    min(B.dur) as minDuration,
317    max(B.dur) as maxDuration,
318    --round(stdev(B.dur),2) as stdDuration,
319    count(A.tid) as count
320from thread_state AS B
321    left join  thread as A on B.itid = A.id
322    left join process AS IP on A.ipid = IP.id
323    left join trace_section AS TR
324where
325    B.dur > 0 and IP.pid not null and
326    not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS))
327group by IP.name, IP.pid, A.name, A.tid,state
328order by wallDuration`, {$leftNS: leftNs, $rightNS: rightNs});
329
330export const getTabBoxChildData = (leftNs: number, rightNs: number, state: string | undefined, processId: number | undefined, threadId: number | undefined): Promise<Array<SPTChild>> =>
331    query<SPTChild>("getTabBoxChildData", `select  IP.name as process,
332    IP.pid as processId,
333    A.name as thread,
334    B.state as state,
335    A.tid as threadId,
336       B.dur as duration,
337       B.ts - TR.start_ts as startNs,
338       B.cpu,
339       C.priority,
340       '-' as note
341from thread_state AS B
342    left join  thread as A on B.itid = A.id
343    left join process AS IP on A.ipid = IP.id
344    left join trace_section AS TR
345    left join sched_slice as C on B.itid = C.itid and C.ts = B.ts
346where
347    B.dur > 0 and IP.pid not null
348    and not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS))
349    ${ state != undefined ? 'and B.state = $state':''}
350    ${ processId != undefined ? 'and IP.pid = $processID':''}
351    ${ threadId != undefined ? 'and A.tid = $threadID':''}
352    `, {$leftNS: leftNs, $rightNS: rightNs, $state: state, $processID: processId, $threadID: threadId})
353
354/*-------------------------------------------------------------------------------------*/
355export const getTabCpuUsage = (cpus: Array<number>, leftNs: number, rightNs: number): Promise<Array<CpuUsage>> =>
356    query<CpuUsage>("getTabCpuUsage", `select cpu,
357    sum(case
358        when (A.ts - B.start_ts) < $leftNS then (A.ts - B.start_ts + A.dur - $leftNS)
359        when (A.ts - B.start_ts) >= $leftNS and (A.ts - B.start_ts + A.dur) <= $rightNS then A.dur
360        when (A.ts - B.start_ts + A.dur) > $rightNS then ($rightNS - (A.ts - B.start_ts)) end) / cast($rightNS - $leftNS as float) as usage
361from thread_state A ,trace_section B
362where (A.ts - B.start_ts) > 0 and A.dur > 0
363  and cpu in (${cpus.join(",")})
364  and  (A.ts - B.start_ts + A.dur) > $leftNS and (A.ts - B.start_ts) < $rightNS
365group by cpu`, {$leftNS: leftNs, $rightNS: rightNs})
366
367export const getTabCpuFreq = (cpus: Array<number>, leftNs: number, rightNs: number): Promise<Array<Freq>> =>
368    query<Freq>("getTabCpuFreq", `select cpu,value,(ts - tb.start_ts) as startNs
369from measure c ,trace_section tb
370inner join cpu_measure_filter t on c.filter_id = t.id
371where (name = 'cpufreq' or name='cpu_frequency')
372  and cpu in (${cpus.join(",")})
373  and startNs > 0
374  and startNs < $rightNS
375  order by startNs`, {$leftNS: leftNs, $rightNS: rightNs})
376/*-------------------------------------------------------------------------------------*/
377export const getTabFps = (leftNs: number, rightNs: number): Promise<Array<Fps>> =>
378    query<Fps>("getTabFps", `select distinct(ts-tb.start_ts) as startNS,fps
379from hidump c ,trace_section tb
380where startNS <= $rightNS and startNS >= 0
381order by startNS;`, {$leftNS: leftNs, $rightNS: rightNs})
382/*-------------------------------------------------------------------------------------*/
383export const getTabCounters = (filterIds: Array<number>, startTime: number) =>
384    query<Counter>("getTabCounters", `select t1.filter_id as trackId,t2.name,value, t1.ts - t3.start_ts as startTime
385from measure t1
386left join process_measure_filter t2 on t1.filter_id = t2.id
387left join trace_section t3 where filter_id in (${filterIds.join(",")})
388and startTime <= $startTime
389order by startTime asc;`, {$startTime: startTime})
390/*-------------------------------------------------------------------------------------*/
391export const getTabCpuByProcess = (cpus: Array<number>, leftNS: number, rightNS: number) =>
392    query<SelectionData>("getTabCpuByProcess", `select  IP.name as process,
393    IP.pid as pid,
394    sum(B.dur) as wallDuration,
395    avg(B.dur) as avgDuration,
396    count(A.tid) as occurrences
397from thread_state AS B
398    left join  thread as A
399    left join trace_section AS TR
400    left join process AS IP
401where B.itid = A.id
402    and A.ipid = IP.id
403    and B.cpu in (${cpus.join(",")})
404    and not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS ))
405group by IP.name, IP.pid
406order by wallDuration desc;`, {$rightNS: rightNS, $leftNS: leftNS})
407/*-------------------------------------------------------------------------------------*/
408export const getTabCpuByThread = (cpus: Array<number>, leftNS: number, rightNS: number) =>
409    query<SelectionData>("getTabCpuByThread", `select  IP.name as process,
410    IP.pid as pid,
411    A.name as thread,
412    A.tid as tid,
413    sum(B.dur) as wallDuration,
414    avg(B.dur) as avgDuration,
415    count(A.tid) as occurrences
416from thread_state AS B
417    left join  thread as A
418    left join trace_section AS TR
419    left join process AS IP
420where B.itid = A.id
421    and A.ipid = IP.id
422    and B.cpu in (${cpus.join(",")})
423    and not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS))
424group by IP.name, IP.pid, A.name, A.tid
425order by wallDuration desc;`, {$rightNS: rightNS, $leftNS: leftNS})
426/*-------------------------------------------------------------------------------------*/
427export const getTabSlices = (funTids: Array<number>, leftNS: number, rightNS: number): Promise<Array<any>> =>
428    query<SelectionData>("getTabSlices", `select
429      c.name as name,
430      sum(c.dur) as wallDuration,
431      avg(c.dur) as avgDuration,
432      count(c.name) as occurrences
433from thread A,trace_section D
434left join callstack C on A.id = C.callid
435where C.ts not null
436      and c.dur >= 0
437      and A.tid in (${funTids.join(",")})
438      and c.name not like 'binder%'
439      and not ((C.ts - D.start_ts + C.dur < $leftNS) or (C.ts - D.start_ts > $rightNS))
440group by c.name
441order by wallDuration desc;`, {$leftNS: leftNS, $rightNS: rightNS})
442/*-------------------------------------------------------------------------------------*/
443export const getTabThreadStates = (tIds: Array<number>, leftNS: number, rightNS: number): Promise<Array<any>> =>
444    query<SelectionData>("getTabThreadStates", `select
445    IP.name as process,
446    IP.pid,
447    A.name as thread,
448    A.tid,
449    B.state,
450    sum(B.dur) as wallDuration,
451    avg(B.dur) as avgDuration,
452    count(A.tid) as occurrences
453from thread_state AS B
454left join thread as A on A.id = B.itid
455left join trace_section AS TR
456left join process AS IP on IP.id=ipid
457where A.tid in (${tIds.join(",")})
458and not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS))
459group by IP.name, IP.pid, A.name, A.tid, B.state
460order by wallDuration desc;`, {$leftNS: leftNS, $rightNS: rightNS})
461/*-------------------------------------------------------------------------------------*/
462export const getThreadFuncData = (tId: number): Promise<Array<any>> =>
463    query("getThreadFuncData", `select tid,
464    A.start_ts,
465    A.end_ts,
466    A.name as threadName,
467    is_main_thread,
468    c.callid as track_id,
469    c.ts-D.start_ts as startTs,
470    c.ts + c.dur as endTs,
471    c.dur,
472    c.name as funName,
473    c.depth,
474   c.parent_id,
475   c.id
476from thread A,trace_section D
477left join callstack C on A.id = C.callid
478where startTs not null and A.tid = $tid;`, {$tid: tId})
479/*-------------------------------------------------------------------------------------*/
480export const queryBinderArgsByArgset = (argset: number): Promise<Array<BinderArgBean>> =>
481    query("queryBinderArgsByArgset", `select * from args_view where argset = $argset;`, {$argset: argset})
482/*-------------------------------------------------------------------------------------*/
483export const queryClockFrequency = (): Promise<Array<any>> =>
484    query("queryClockFrequency", `with freq as (  select measure.filter_id, measure.ts, measure.type, measure.value from clock_event_filter
485left join measure
486where clock_event_filter.name = '%s' and clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id
487order by measure.ts)
488select freq.filter_id,freq.ts - r.start_ts as ts,freq.type,freq.value from freq,trace_section r;`, {})
489/*-------------------------------------------------------------------------------------*/
490export const queryClockList = (): Promise<Array<any>> =>
491    query("queryClockList", `with list as (
492    select distinct name from clock_event_filter
493    where  clock_event_filter.type = 'clock_set_rate' order by name
494),freq as(
495    select measure.filter_id, measure.ts, measure.type, measure.value , clock_event_filter.name from clock_event_filter
496    left join measure
497    where  clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id
498    order by measure.ts
499),state as (
500    select filter_id, ts, endts, endts-ts as dur, type, value,name from
501    (select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value,clock_event_filter.name from clock_event_filter,trace_section
502    left join measure
503    where clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id
504    order by measure.ts)
505),count_freq as (
506    select COUNT(*) num,name srcname from freq group by name
507),count_state as (
508    select COUNT(*) num,name srcname from state group by name
509)
510select count_freq.srcname||' Frequency' as name,* from count_freq union select count_state.srcname||' State' as name,* from count_state order by name;`)
511/*-------------------------------------------------------------------------------------*/
512export const queryClockState = (): Promise<Array<any>> =>
513    query("queryClockState", `with state as (
514select filter_id, ts, endts, endts-ts as dur, type, value from
515(select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value from clock_event_filter,trace_section
516left join measure
517where clock_event_filter.name = '%s' and clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id
518order by measure.ts))
519-- select * from state;
520select s.filter_id,s.ts-r.start_ts as ts,s.type,s.value,s.dur from state s,trace_section r;`)
521/*-------------------------------------------------------------------------------------*/
522export const queryCpuData = (cpu: number, startNS: number, endNS: number): Promise<Array<CpuStruct>> =>
523    query("queryCpuData", `select * from temp_query_cpu_data where cpu = $cpu and startTime between $startNS and $endNS;`, {
524        $cpu: cpu,
525        $startNS: startNS,
526        $endNS: endNS
527    })
528/*-------------------------------------------------------------------------------------*/
529export const queryCpuFreq = (): Promise<Array<{ cpu: number }>> =>
530    query("queryCpuFreq", `select cpu from temp_query_cpu_freq;`)
531/*-------------------------------------------------------------------------------------*/
532export const queryCpuFreqData = (cpu: number): Promise<Array<CpuFreqStruct>> =>
533    query("queryCpuFreqData", `select * from temp_query_freq_data where cpu = $cpu;`, {$cpu: cpu})
534/*-------------------------------------------------------------------------------------*/
535export const queryCpuMax = (): Promise<Array<any>> =>
536    query("queryCpuMax", `select cpu from sched_slice order by cpu desc limit 1;`)
537/*-------------------------------------------------------------------------------------*/
538export const queryCpuMaxFreq = (): Promise<Array<any>> =>
539    query("queryCpuMaxFreq", `select * from temp_query_cpu_max_freq;`)
540// /*-------------------------------------------------------------------------------------*/
541export const queryLogs = (): Promise<Array<any>> =>
542    query("queryLogs", `select l.*,l.ts-t.start_ts as "startTime" from log as l left join trace_section AS t
543 where "startTime" between %s and %s order by "startTime"
544 limit %s offset %s;`)
545/*-------------------------------------------------------------------------------------*/
546export const queryLogsCount = (): Promise<Array<any>> =>
547    query("queryLogsCount", `select l.*,l.ts-t.start_ts as "startTime" from log as l left join trace_section AS t
548 where "startTime" between %s and %s;`)
549/*-------------------------------------------------------------------------------------*/
550export const queryProcessData = (pid: number, startNS: number, endNS: number): Promise<Array<any>> =>
551    query("queryProcessData", `select * from temp_query_process_data where pid = $pid and startTime between $startNS and $endNS;`, {
552        $pid: pid,
553        $startNS: startNS,
554        $endNS: endNS
555    })
556/*-------------------------------------------------------------------------------------*/
557export const queryProcessDataCount = (): Promise<Array<any>> =>
558    query("queryProcessDataCount", `select ta.id,type, ts, dur, ta.cpu, itid as utid, state
559     ,ts-tb.start_ts as startTime,tc.tid,tc.pid,tc.process,tc.thread
560from thread_state ta,trace_section tb
561left join (
562    select it.id,tid,pid,ip.name as process,it.name as thread from thread as it left join process ip on it.ipid = ip.id
563    ) tc on ta.itid = tc.id
564where tc.pid = %d
565  and startTime between  %s and  %s
566and ta.cpu is not null
567order by startTime;`)
568/*-------------------------------------------------------------------------------------*/
569export const queryProcessDataLimit = (pid: number, startNS: number, endNS: number, limit: number): Promise<Array<any>> =>
570    query("queryProcessDataLimit", `with list as (select ta.id,type, ts, dur, ta.cpu, itid as utid, state
571     ,ts-tb.start_ts as startTime,tc.tid,tc.pid,tc.process,tc.thread
572from thread_state ta,trace_section tb
573left join (
574    select it.id,tid,pid,ip.name as process,it.name as thread from thread as it left join process ip on it.ipid = ip.id
575    ) tc on ta.itid = tc.id
576where tc.pid = $pid
577  and startTime between  $startNS and  $endNS
578and ta.cpu is not null
579order by startTime )
580select * from list order by random() limit $limit;`, {$pid: pid, $startNS: startNS, $endNS: endNS, $limit: limit})
581/*-------------------------------------------------------------------------------------*/
582export const queryProcessMem = (): Promise<Array<any>> =>
583    query("queryProcessMem", `select process_measure_filter.id   as trackId,
584       process_measure_filter.name as trackName,
585       ipid as upid,
586       process_view.pid,
587       process_view.name               as processName
588from process_measure_filter join process_view using (ipid)
589order by trackName;`)
590/*-------------------------------------------------------------------------------------*/
591export const queryProcessMemData = (trackId: number): Promise<Array<ProcessMemStruct>> =>
592    query("queryProcessMemData", `select c.type,
593    ts, value,
594    filter_id as track_id,
595    c.ts-tb.start_ts startTime
596from measure c,trace_section tb where filter_id = $id;`, {$id: trackId})
597/*-------------------------------------------------------------------------------------*/
598export const queryProcessNOrder = (): Promise<Array<any>> =>
599    query("queryProcessNOrder", `select pid,name as processName from process;`)
600/*-------------------------------------------------------------------------------------*/
601export const queryProcessThreads = (): Promise<Array<ThreadStruct>> =>
602    query("queryProcessThreads", `select
603  the_tracks.ipid as upid,
604  the_tracks.itid as utid,
605  total_dur as hasSched,
606  process_view.pid as pid,
607  thread_view.tid as tid,
608  process_view.name as processName,
609  thread_view.name as threadName
610from (
611  select ipid, itid from sched_view join thread_view using(itid) group by itid
612) the_tracks
613left join (select ipid, sum(dur) as total_dur
614  from sched_view join thread_view using(itid)
615  group by ipid
616) using(ipid)
617left join thread_view using(itid)
618left join process_view using(ipid)
619order by
620  total_dur desc,
621  the_tracks.ipid,
622  the_tracks.itid;`, {})
623/*-------------------------------------------------------------------------------------*/
624export const queryProcessThreadsNOrder = (): Promise<Array<any>> =>
625    query("queryProcessThreadsNOrder", `select p.id as upid,
626       t.id as utid,
627       p.pid,
628       t.tid,
629       p.name as processName,
630       t.name as threadName
631       from thread t left join process p on t.ipid = p.id;`)
632/*-------------------------------------------------------------------------------------*/
633export const queryScreenState = (): Promise<Array<any>> =>
634    query("queryScreenState", `select m.type, m.ts-r.start_ts as ts, value, filter_id from measure m,trace_section r where filter_id in (select id from process_measure_filter where name = 'ScreenState');`)
635/*-------------------------------------------------------------------------------------*/
636export const queryThreadData = (tid: number): Promise<Array<ThreadStruct>> =>
637    query("queryThreadData", `select * from temp_query_thread_data where tid = $tid;`, {$tid: tid})
638/*-------------------------------------------------------------------------------------*/
639export const queryWakeUpThread_Desc = (): Promise<Array<any>> =>
640    query("queryWakeUpThread_Desc", `This is the interval from when the task became eligible to run
641(e.g.because of notifying a wait queue it was a suspended on) to when it started running.`)
642/*-------------------------------------------------------------------------------------*/
643export const queryWakeUpThread_WakeThread = (wakets: number): Promise<Array<WakeupBean>> =>
644    query("queryWakeUpThread_WakeThread", `select TB.tid,TB.name as thread,TA.cpu,TC.pid,TC.name as process
645from sched_view TA
646left join thread TB on TA.itid = TB.id
647left join process TC on TB.ipid = TC.id
648where itid = (select itid from raw where name = 'sched_waking' and ts = $wakets )
649    and TA.ts < $wakets
650    and Ta.ts + Ta.dur >= $wakets`, {$wakets: wakets})
651/*-------------------------------------------------------------------------------------*/
652export const queryWakeUpThread_WakeTime = (tid: number, startTime: number): Promise<Array<WakeUpTimeBean>> =>
653    query("queryWakeUpThread_WakeTime", `select * from
654    ( select ts as wakeTs,start_ts as startTs from instants_view,trace_section
655       where name = 'sched_waking'
656       and ref = $tid
657       and ts < start_ts + $startTime
658       order by ts desc limit 1) TA
659       left join
660    (select ts as preRow from sched_view,trace_section
661       where itid = $tid
662       and ts < start_ts + $startTime
663       order by ts desc limit 1) TB`, {$tid: tid, $startTime: startTime})
664/*-------------------------------------------------------------------------------------*/
665export const queryThreadsByPid = (pid: number): Promise<Array<any>> =>
666    query("queryThreadsByPid", `select
667                the_tracks.ipid as upid,
668                the_tracks.itid as utid,
669                total_dur as hasSched,
670                process_view.pid as pid,
671                thread_view.tid as tid,
672                process_view.name as processName,
673                thread_view.name as threadName
674              from (
675                select ipid, itid from sched_view join thread_view using(itid) group by itid
676              ) the_tracks
677              left join (select ipid, sum(dur) as total_dur
678                from sched_view join thread_view using(itid)
679                group by ipid
680              ) using(ipid)
681              left join thread_view using(itid)
682              left join process_view using(ipid)
683              where  pid = $pid
684              order by
685                total_dur desc,
686                the_tracks.ipid,
687                the_tracks.itid`, {$pid: pid})
688/*-------------------------------------------------------------------------------------*/
689export const queryHeapByPid = (startTs: number, endTs: number, ipid: number): Promise<Array<HeapStruct>> =>
690    query("queryHeapByPid", `select a.maxheap maxHeapSize,current_size_dur as dur,h.all_heap_size heapsize,h.start_ts - t.start_ts as startTime,h.end_ts - t.start_ts as endTime
691from heap h left join trace_section t left join (select max(all_heap_size) maxheap from heap) a where  ipid = ${ipid} and startTime between ${startTs} and ${endTs};
692`, {$ipid: ipid, $startTs: startTs, $endTs: endTs})
693/*-------------------------------------------------------------------------------------*/
694export const queryHeapPid = (): Promise<Array<any>> =>
695    query("queryHeapPid", `select ipid,pid from heap h left join process p on h.ipid = p.id group by ipid,pid`, {})
696/*-------------------------------------------------------------------------------------*/
697export const queryHeapTable = (startTs: number, endTs: number, ipids: Array<number>): Promise<Array<HeapBean>> =>
698    query("queryHeapTable", `select *,Allocations - Deallocations Total,AllocationSize - DeAllocationSize RemainingSize from (select f.file_path MoudleName,
699       sum(case when h.event_type = 'AllocEvent' then 1 else 0 end) Allocations,
700       sum(case when h.event_type = 'FreeEvent' then 1 else 0 end) Deallocations,
701       sum(case when h.event_type = 'AllocEvent' then heap_size else 0 end) AllocationSize,
702       sum(case when h.event_type = 'FreeEvent' then heap_size else 0 end) DeAllocationSize,
703        f.symbol_name AllocationFunction
704 from (select heap.start_ts - t.start_ts as startTime,* from heap
705     left join trace_range t where ipid in (${ipids.join(",")}) and startTime between ${startTs} and ${endTs}) h
706     left join (select * from heap_frame where depth = 0) f
707     on f.eventId = h.eventId group by f.file_path)`,
708        {ipids: ipids, $startTs: startTs, $endTs: endTs})
709
710
711
712