• 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 */
15import { query } from '../SqlLite';
16import { SelectionData } from '../../bean/BoxSelection';
17import { ThreadStruct } from '../ui-worker/ProcedureWorkerThread';
18import { WakeupBean } from '../../bean/WakeupBean';
19import { SPTChild } from '../../bean/StateProcessThread';
20import { BinderArgBean } from '../../bean/BinderArgBean';
21import { ProcessMemStruct } from '../ui-worker/ProcedureWorkerMem';
22import { AppStartupStruct } from '../ui-worker/ProcedureWorkerAppStartup';
23import { SoStruct } from '../ui-worker/ProcedureWorkerSoInit';
24import { LiveProcess, ProcessHistory } from '../../bean/AbilityMonitor';
25import { EnergyAnomalyStruct } from '../ui-worker/ProcedureWorkerEnergyAnomaly';
26import { BinderItem } from '../../bean/BinderProcessThread';
27
28export const queryBinderByThreadId = (
29  pIds: number[],
30  tIds: Array<number>,
31  leftNS: number,
32  rightNS: number
33): Promise<Array<BinderItem>> =>
34  query<BinderItem>(
35    'queryBinderByThreadId',
36    `
37      SELECT
38            c.name,
39            c.ts - r.start_ts AS ts,
40            c.dur,
41            t.tid,
42            p.pid
43          FROM
44              callstack c, trace_range r
45          LEFT JOIN
46              thread t
47          ON
48              c.callid = t.id
49          LEFT JOIN
50              process p
51          ON
52              t.ipid = p.id
53          WHERE
54              c.name in ('binder transaction', 'binder async rcv', 'binder reply', 'binder transaction async')
55          AND
56              t.tid in (${tIds.join(',')})
57          AND
58              p.pid in (${pIds.join(',')})
59          AND NOT
60              (((c.ts - r.start_ts) < ${leftNS})
61          OR
62              ((c.ts - r.start_ts) > ${rightNS}))
63        `,
64    {
65      $pIds: pIds,
66      $tIds: tIds,
67      $leftNS: leftNS,
68      $rightNS: rightNS,
69    }
70  );
71export const getTabBindersCount = (
72  pIds: number[],
73  tIds: number[],
74  leftNS: number,
75  rightNS: number
76): Promise<Array<BinderItem>> =>
77  query<BinderItem>(
78    'getTabBindersCount',
79    `
80      SELECT
81          c.name,
82          c.dur,
83          1 AS count,
84          c.ts,
85          c.ts - r.start_ts AS startTime,
86          c.ts -r.start_ts + c.dur AS endTime,
87          t.tid,
88          p.pid
89        FROM
90            callstack c, trace_range r
91          LEFT JOIN
92            thread t
93          ON
94            c.callid = t.id
95          LEFT JOIN
96            process p
97          ON
98            t.ipid = p.id
99        WHERE
100            c.name in ('binder transaction', 'binder async rcv', 'binder reply', 'binder transaction async')
101          AND
102            t.tid in (${tIds.join(',')})
103          AND
104            p.pid in (${pIds.join(',')})
105          AND NOT
106            ((startTime < ${leftNS})
107          OR
108            (endTime > ${rightNS}));
109      `,
110    {
111      $pIds: pIds,
112      $tIds: tIds,
113      $leftNS: leftNS,
114      $rightNS: rightNS,
115    }
116  );
117
118export const querySchedThreadStates = (
119  pIds: Array<number>,
120  tIds: Array<number>,
121  leftStartNs: number,
122  rightEndNs: number
123): //@ts-ignore
124Promise<Array<unknown>> =>
125  query(
126    'getTabThreadStates',
127    `
128    select
129      B.pid,
130      B.tid,
131      B.state,
132      ifnull(B.dur,0) as dur,
133      B.ts,
134      ifnull(B.dur,0) + B.ts as endTs
135    from
136      thread_state AS B
137    where
138      B.tid in (${tIds.join(',')})
139    and
140      B.pid in (${pIds.join(',')})
141    and
142      B.state='Running'
143    and
144      not ((B.ts + ifnull(B.dur,0) < $leftStartNs) or (B.ts > $rightEndNs))
145    order by
146      B.pid;
147    `,
148    { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs }
149  );
150
151export const querySingleCutData = (
152  funcName: string,
153  tIds: string,
154  leftStartNs: number,
155  rightEndNs: number
156): //@ts-ignore
157Promise<Array<unknown>> =>
158  query(
159    'querySingleCutData',
160    `
161    select
162      c.ts as cycleStartTime,
163      c.ts + ifnull(c.dur, 0) as cycleEndTime,
164      t.tid,
165      p.pid
166      from
167      callstack c
168    left join
169      thread t on c.callid = t.id
170    left join
171      process p on t.ipid = p.id
172    left join
173      trace_range r
174    where
175      c.name like '${funcName}%'
176    and
177      t.tid = '${tIds}'
178    and
179      not ((c.ts < $leftStartNs) or (c.ts + ifnull(c.dur, 0) > $rightEndNs))
180    order by
181      c.ts
182    `,
183    { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs }
184  );
185
186export const queryLoopCutData = (
187  funcName: string,
188  tIds: string,
189  leftStartNs: number,
190  rightEndNs: number
191): //@ts-ignore
192Promise<Array<unknown>> =>
193  query(
194    'queryLoopCutData',
195    `
196    select
197      c.ts as cycleStartTime,
198      t.tid,
199      p.pid
200    from callstack c
201    left join
202      thread t on c.callid = t.id
203    left join
204      process p on t.ipid = p.id
205    where
206      c.name like '${funcName}%'
207    and
208      t.tid = '${tIds}'
209    and
210      not ((c.ts < $leftStartNs) or (c.ts > $rightEndNs))
211    order by
212      c.ts
213    `,
214    { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs }
215  );
216// 框选区域内sleeping的时间
217export const getTabSleepingTime = (
218  tIds: Array<number>,
219  leftNS: number,
220  rightNS: number
221): //@ts-ignore
222Promise<Array<unknown>> =>
223  query<SelectionData>(
224    'getTabRunningPersent',
225    `
226 select
227   B.pid,
228   B.tid,
229   B.state,
230   B.cpu,
231   B.dur,
232   B.ts
233 from
234   thread_state AS  B
235 left join
236   trace_range AS TR
237 where
238   B.tid in (${tIds.join(',')})
239 and
240   B.state='Sleeping'
241 and
242   not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS}))
243 order by
244   ts;`,
245    { $leftNS: leftNS, $rightNS: rightNS }
246  );
247export const getTabThreadStatesCpu = (
248  tIds: Array<number>,
249  leftNS: number,
250  rightNS: number
251): //@ts-ignore
252Promise<Array<unknown>> => {
253  let sql = `
254select
255       B.pid,
256       B.tid,
257       B.cpu,
258       sum( min(${rightNS},(B.ts - TR.start_ts + iif(B.dur = -1 or B.dur is null, 0, B.dur))) - max(${leftNS},B.ts - TR.start_ts)) wallDuration
259from thread_state as B
260left join trace_range as TR
261where cpu notnull
262    and B.tid in (${tIds.join(',')})
263    and not ((B.ts - TR.start_ts + iif(B.dur = -1 or B.dur is null, 0, B.dur) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS}))
264group by B.tid, B.pid, B.cpu;`;
265  return query<SelectionData>('getTabThreadStatesCpu', sql, {
266    $leftNS: leftNS,
267    $rightNS: rightNS,
268  });
269};
270
271// 框选区域内running的时间
272export const getTabRunningPersent = (
273  tIds: Array<number>,
274  leftNS: number,
275  rightNS: number
276): //@ts-ignore
277Promise<Array<unknown>> =>
278  query<SelectionData>(
279    'getTabRunningPersent',
280    `
281   select
282     B.pid,
283     B.tid,
284     B.state,
285     B.cpu,
286     iif(B.dur = -1 or B.dur is null, 0, B.dur) as dur,
287     B.ts
288   from
289     thread_state AS  B
290   left join
291     trace_range AS TR
292   where
293     B.tid in (${tIds.join(',')})
294   and
295     B.state='Running'
296   and
297     not ((B.ts - TR.start_ts + iif(B.dur = -1 or B.dur is null, 0, B.dur) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS}))
298   order by
299     ts;`,
300    { $leftNS: leftNS, $rightNS: rightNS }
301  );
302export const queryThreadData = (tid: number, pid: number): Promise<Array<ThreadStruct>> =>
303  query(
304    'queryThreadData',
305    `
306    select
307      B.itid as id
308     , B.tid
309     , B.cpu
310     , B.ts - TR.start_ts AS startTime
311     , B.dur
312     , B.state
313     , B.pid
314     , B.arg_setid as argSetID
315from thread_state AS B
316    left join trace_range AS TR
317where B.tid = $tid and B.pid = $pid;`,
318    { $tid: tid, $pid: pid }
319  );
320export const queryThreadNearData = (
321  itid: number,
322  startTime: number
323): //@ts-ignore
324Promise<Array<unknown>> =>
325  query(
326    'queryThreadNearData',
327    `
328select itid,tid,pid,cpu,state,arg_setid as argSetID,dur,max((A.ts - B.start_ts)) as startTime
329from thread_state A,trace_range B
330where itid = ${itid}
331and (A.ts - B.start_ts) < ${startTime} and A.ts > B.start_ts
332union
333select itid,tid,pid,cpu,state,arg_setid as argSetID,dur,min((A.ts - B.start_ts)) as startTime
334from thread_state A,trace_range B
335where itid = ${itid}
336and (A.ts - B.start_ts) > ${startTime} and A.ts < B.end_ts;
337    `,
338    {}
339  );
340export const queryThreadWakeUpFrom = (itid: number, startTime: number): Promise<Array<WakeupBean>> => {
341  let sql = `
342select (A.ts - B.start_ts) as ts,
343       A.tid,
344       A.itid,
345       A.pid,
346       A.cpu,
347       A.dur,
348       A.arg_setid as argSetID
349from thread_state A,trace_range B
350where A.state = 'Running'
351and A.itid = (select wakeup_from from instant where ts = ${startTime} and ref = ${itid} limit 1)
352and (A.ts - B.start_ts) < (${startTime} - B.start_ts)
353order by ts desc limit 1
354    `;
355  return query('queryThreadWakeUpFrom', sql, {});
356};
357
358export const queryRunnableTimeByRunning = (tid: number, startTime: number): Promise<Array<WakeupBean>> => {
359  let sql = `
360select ts from thread_state,trace_range where ts + dur -start_ts = ${startTime} and state = 'R' and tid=${tid} limit 1
361    `;
362  return query('queryRunnableTimeByRunning', sql, {});
363};
364
365export const queryProcess = (): Promise<
366  Array<{
367    pid: number | null;
368    processName: string | null;
369  }>
370> =>
371  query(
372    'queryProcess',
373    `
374    SELECT
375      pid, processName
376    FROM
377      temp_query_process where pid != 0`
378  );
379
380export const queryProcessByTable = (): Promise<
381  Array<{
382    pid: number | null;
383    processName: string | null;
384  }>
385> =>
386  query(
387    'queryProcessByTable',
388    `
389    SELECT
390      pid, name as processName
391    FROM
392      process where pid != 0`
393  );
394
395export const getTabBoxChildData = (
396  leftNs: number,
397  rightNs: number,
398  cpus: number[],
399  state: string | undefined,
400  processId: number | undefined,
401  threadId: number | undefined
402): Promise<Array<SPTChild>> => {
403  let condition = `
404      ${state !== undefined && state !== '' ? `and B.state = '${state}'` : ''}
405      ${processId !== undefined && processId !== -1 ? `and IP.pid = ${processId}` : ''}
406      ${threadId !== undefined && threadId !== -1 ? `and A.tid = ${threadId}` : ''}
407      ${cpus.length > 0 ? `and (B.cpu is null or B.cpu in (${cpus.join(',')}))` : ''}
408  `;
409  let sql = `select
410      IP.name as process,
411      IP.pid as processId,
412      A.name as thread,
413      B.state as state,
414      A.tid as threadId,
415      B.dur as duration,
416      B.ts - TR.start_ts as startNs,
417      B.cpu,
418      C.priority
419    from
420      thread_state AS B
421    left join
422      thread as A
423    on
424      B.itid = A.itid
425    left join
426      process AS IP
427    on
428      A.ipid = IP.ipid
429    left join
430      trace_range AS TR
431    left join
432      sched_slice as C
433    on
434      B.itid = C.itid
435    and
436      C.ts = B.ts
437    where
438      B.dur > 0
439    and
440      IP.pid not null
441    and
442      not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) ${condition};
443  `;
444  return query('getTabBoxChildData', sql, {});
445};
446export const getTabStartups = (
447  ids: Array<number>,
448  leftNS: number,
449  rightNS: number
450): //@ts-ignore
451Promise<Array<unknown>> => {
452  let sql = `
453select
454    P.pid,
455    P.name as process,
456    (A.start_time - B.start_ts) as startTs,
457    (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur,
458    A.start_name as startName
459from app_startup A,trace_range B
460left join process P on A.ipid = P.ipid
461where P.pid in (${ids.join(',')})
462and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS}))
463order by start_name;`;
464  return query('getTabStartups', sql, {});
465};
466
467export const getTabStaticInit = (
468  ids: Array<number>,
469  leftNS: number,
470  rightNS: number
471): //@ts-ignore
472Promise<Array<unknown>> => {
473  let sql = `
474select
475    P.pid,
476    P.name as process,
477    (A.start_time - B.start_ts) as startTs,
478    (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur,
479    A.so_name as soName
480from static_initalize A,trace_range B
481left join process P on A.ipid = P.ipid
482where P.pid in (${ids.join(',')})
483and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS}))
484order by dur desc;`;
485  return query('getTabStaticInit', sql, {});
486};
487
488export const queryBinderArgsByArgset = (argset: number): Promise<Array<BinderArgBean>> =>
489  query(
490    'queryBinderArgsByArgset',
491    `
492    select
493      *
494    from
495      args_view
496    where
497      argset = $argset;`,
498    { $argset: argset }
499  );
500
501export const queryProcessData = (
502  pid: number,
503  startNS: number,
504  endNS: number
505): //@ts-ignore
506Promise<Array<unknown>> =>
507  query(
508    'queryProcessData',
509    `
510    select  ta.cpu,
511        dur,
512        ts-${window.recordStartNS} as startTime
513from thread_state ta
514where ta.cpu is not null and pid=$pid and startTime between $startNS and $endNS;`,
515    {
516      $pid: pid,
517      $startNS: startNS,
518      $endNS: endNS,
519    }
520  );
521
522export const queryProcessMem = (): //@ts-ignore
523Promise<Array<unknown>> =>
524  query(
525    'queryProcessMem',
526    `
527    select
528      process_measure_filter.id as trackId,
529      process_measure_filter.name as trackName,
530      ipid as upid,
531      process.pid,
532      process.name as processName
533    from
534      process_measure_filter
535    join
536      process using (ipid)
537    order by trackName;`
538  );
539
540export const queryProcessThreadDataCount = (): //@ts-ignore
541Promise<Array<unknown>> =>
542  query(
543    `queryProcessThreadDataCount`,
544    `select pid,count(id) as count
545    from thread_state
546    where ts between ${window.recordStartNS} and ${window.recordEndNS} group by pid;`,
547    {}
548  );
549
550export const queryProcessFuncDataCount = (): //@ts-ignore
551Promise<Array<unknown>> =>
552  query(
553    `queryProcessFuncDataCount`,
554    `select
555        P.pid,
556        count(tid) as count
557    from callstack C
558    left join thread A on A.id = C.callid
559    left join process AS P on P.id = A.ipid
560    where  C.ts between ${window.recordStartNS} and ${window.recordEndNS}
561    group by pid;`,
562    {}
563  );
564
565export const queryProcessMemDataCount = (): //@ts-ignore
566Promise<Array<unknown>> =>
567  query(
568    `queryProcessMemDataCount`,
569    `select
570      p.pid as pid, count(value) count
571    from process_measure c
572    left join process_measure_filter f on f.id = c.filter_id
573    left join process p on p.ipid = f.ipid
574where f.id not NULL and value>0
575 and c.ts between ${window.recordStartNS} and ${window.recordEndNS}
576group by p.pid`,
577    {}
578  );
579
580export const queryProcessMemData = (trackId: number): Promise<Array<ProcessMemStruct>> =>
581  query(
582    'queryProcessMemData',
583    `
584    select
585      c.type,
586      ts,
587      value,
588      filter_id as track_id,
589      c.ts-tb.start_ts startTime
590    from
591      process_measure c,
592      trace_range tb
593    where
594      filter_id = $id;`,
595    { $id: trackId }
596  );
597
598export const queryThreads = (): //@ts-ignore
599Promise<Array<unknown>> =>
600  query('queryThreads', `select id,tid,(ifnull(name,'Thread') || '(' || tid || ')') name from thread where id != 0;`);
601
602export const queryDataDICT = (): //@ts-ignore
603Promise<Array<unknown>> => query('queryDataDICT', `select * from data_dict;`);
604
605export const queryAppStartupProcessIds = (): Promise<Array<{ pid: number }>> =>
606  query(
607    'queryAppStartupProcessIds',
608    `
609  SELECT pid FROM process
610  WHERE ipid IN (
611    SELECT ipid FROM app_startup
612    UNION
613    SELECT t.ipid FROM app_startup a LEFT JOIN thread t ON a.call_id = t.itid
614);`
615  );
616
617export const queryTaskPoolProcessIds = (): Promise<Array<{ pid: number }>> =>
618  query(
619    'queryAppStartupProcessIds',
620    `SELECT pid
621FROM
622    process
623WHERE
624    ipid IN (
625    SELECT DISTINCT
626    ( ipid )
627    FROM
628    thread
629    WHERE
630    itid IN ( SELECT DISTINCT ( callid ) FROM callstack WHERE name LIKE 'H:Task%' )
631    AND name = 'TaskWorkThread'
632    )`
633  );
634
635export const queryProcessContentCount = (): //@ts-ignore
636Promise<Array<unknown>> =>
637  query(`queryProcessContentCount`, `select pid,switch_count,thread_count,slice_count,mem_count from process;`);
638export const queryProcessThreadsByTable = (): Promise<Array<ThreadStruct>> =>
639  query(
640    'queryProcessThreadsByTable',
641    `
642        select p.pid as pid,p.ipid as upid,t.tid as tid,p.name as processName,t.name as threadName,t.switch_count as switchCount, t.itid as utid from thread t left join process  p on t.ipid = p.id where t.tid != 0;
643    `
644  );
645export const queryProcessThreads = (): Promise<Array<ThreadStruct>> =>
646  query(
647    'queryProcessThreads',
648    `
649    select
650      the_tracks.ipid as upid,
651      the_tracks.itid as utid,
652      total_dur as hasSched,
653      process.pid as pid,
654      thread.tid as tid,
655      process.name as processName,
656      thread.switch_count as switchCount,
657      thread.name as threadName
658    from (
659      select ipid,itid from sched_slice group by itid
660    ) the_tracks
661    left join (select itid,sum(dur) as total_dur from thread_state where state != 'S' group by itid) using(itid)
662    left join thread using(itid)
663    left join process using(ipid)
664    order by total_dur desc,the_tracks.ipid,the_tracks.itid;`,
665    {}
666  );
667export const queryStartupPidArray = (): Promise<Array<{ pid: number }>> =>
668  query(
669    'queryStartupPidArray',
670    `
671    select distinct pid
672from app_startup A,trace_range B left join process P on A.ipid = p.ipid
673where A.start_time between B.start_ts and B.end_ts;`,
674    {}
675  );
676
677export const queryProcessStartup = (pid: number): Promise<Array<AppStartupStruct>> =>
678  query(
679    'queryProcessStartup',
680    `
681    select
682    P.pid,
683    A.tid,
684    A.call_id as itid,
685    (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs,
686    (case
687        when A.start_time < B.start_ts then (A.end_time - B.start_ts)
688        when A.end_time = -1 then 0
689        else (A.end_time - A.start_time) end) as dur,
690    A.start_name as startName
691from app_startup A,trace_range B
692left join process P on A.ipid = P.ipid
693where P.pid = $pid
694order by start_name;`,
695    { $pid: pid }
696  );
697
698export const queryProcessAllAppStartup = (pids: Array<number>): Promise<Array<AppStartupStruct>> =>
699  query(
700    'queryProcessStartup',
701    `
702    select
703    P.pid,
704    A.tid,
705    A.call_id as itid,
706    (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs,
707    (case
708        when A.start_time < B.start_ts then (A.end_time - B.start_ts)
709        when A.end_time = -1 then 0
710        else (A.end_time - A.start_time) end) as dur,
711    A.start_name as startName
712from app_startup A,trace_range B
713left join process P on A.ipid = P.ipid
714where P.pid in(${pids.join(',')})
715order by start_name;`,
716    { $pid: pids }
717  );
718
719export const querySingleAppStartupsName = (
720  pid: number
721): //@ts-ignore
722Promise<Array<unknown>> =>
723  query(
724    'queryAllAppStartupsName',
725    `select name from process
726    where pid=$pid`,
727    { $pid: pid }
728  );
729
730export const queryProcessSoMaxDepth = (): Promise<Array<{ pid: number; maxDepth: number }>> =>
731  query(
732    'queryProcessSoMaxDepth',
733    `select p.pid,max(depth) maxDepth
734from static_initalize S,trace_range B left join process p on S.ipid = p.ipid
735where S.start_time between B.start_ts and B.end_ts
736group by p.pid;`,
737    {}
738  );
739export const queryAllThreadName = (): //@ts-ignore
740Promise<Array<unknown>> => {
741  return query(
742    'queryAllThreadName',
743    `
744          select name,tid from thread;`
745  );
746};
747
748export const queryAllProcessNames = (): //@ts-ignore
749Promise<Array<unknown>> => {
750  return query(
751    'queryAllProcessNames',
752    `
753        select id, name, pid from process;`
754  );
755};
756
757export const queryRsProcess = (): //@ts-ignore
758Promise<Array<unknown>> => {
759  return query(
760    'queryRsProcess',
761    `
762        SELECT p.pid FROM process p WHERE p.ipid = (SELECT t.ipid FROM thread t WHERE t.itid IN
763        ( SELECT c.callid FROM callstack c WHERE name LIKE '%H:RSMainThread::DoComposition%' LIMIT 1 )
764      LIMIT 1
765      )`
766  );
767};
768
769export const queryProcessSoInitData = (pid: number): Promise<Array<SoStruct>> =>
770  query(
771    'queryProcessSoInitData',
772    `
773    select
774    P.pid,
775    T.tid,
776    A.call_id as itid,
777    (A.start_time - B.start_ts) as startTs,
778    (A.end_time - A.start_time) as dur,
779    A.so_name as soName,
780    A.depth
781from static_initalize A,trace_range B
782left join process P on A.ipid = P.ipid
783left join thread T on A.call_id = T.itid
784where P.pid = $pid;`,
785    { $pid: pid }
786  );
787
788export const queryThreadAndProcessName = (): //@ts-ignore
789Promise<Array<unknown>> =>
790  query(
791    'queryThreadAndProcessName',
792    `
793    select tid id,name,'t' type from thread
794union all
795select pid id,name,'p' type from process;`,
796    {}
797  );
798
799export const queryThreadStateArgs = (argset: number): Promise<Array<BinderArgBean>> =>
800  query('queryThreadStateArgs', ` select args_view.* from args_view where argset = ${argset}`, {});
801
802export const queryThreadStateArgsByName = (key: string): Promise<Array<{ argset: number; strValue: string }>> =>
803  query('queryThreadStateArgsByName', ` select strValue, argset from args_view where keyName = $key`, { $key: key });
804
805export const queryThreadWakeUp = (itid: number, startTime: number, dur: number): Promise<Array<WakeupBean>> =>
806  query(
807    'queryThreadWakeUp',
808    `
809select TA.tid,min(TA.ts - TR.start_ts) as ts,TA.pid,TA.dur,TA.state,TA.cpu,TA.itid,TA.arg_setid as argSetID
810from
811  (select min(ts) as wakeTs,ref as itid from instant,trace_range
812       where name = 'sched_wakeup'
813       and wakeup_from = $itid
814       and ts > start_ts + $startTime
815       and ts < start_ts + $startTime + $dur
816      group by ref
817       ) TW
818left join thread_state TA on TW.itid = TA.itid
819left join trace_range TR
820where TA.ts > TW.wakeTs
821group by TA.tid,TA.pid;
822    `,
823    { $itid: itid, $startTime: startTime, $dur: dur }
824  );
825
826export const getTabRunningPercent = (
827  tIds: Array<number>,
828  leftNS: number,
829  rightNS: number
830): Promise<
831  Array<{
832    pid: number;
833    tid: number;
834    cpu: number;
835    dur: number;
836    ts: number;
837    process: string;
838    thread: string;
839  }>
840> =>
841  query(
842    'getTabRunningPercent',
843    `
844          select
845            B.pid,
846            B.tid,
847            B.cpu,
848            B.dur,
849            B.ts
850          from
851            thread_state AS B
852          left join
853            trace_range AS TR
854          where
855            B.tid in (${tIds.join(',')})
856          and
857            B.state='Running'
858          and
859            not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS}))
860          order by ts
861        `
862  );
863//VM  Purgeable 点选 tab页
864export const queryProcessPurgeableSelectionTab = (
865  startNs: number,
866  ipid: number,
867  isPin?: boolean
868): //@ts-ignore
869Promise<Array<unknown>> => {
870  const condition = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'";
871  const pinSql = isPin ? ' AND ref_count > 0' : '';
872  return query(
873    'queryProcessPurgeableSelectionTab',
874    `SELECT
875        ( CASE WHEN f.name = 'mem.purg_pin' THEN 'PinedPurg' ELSE 'TotalPurg' END ) AS name,
876        SUM( m.value )  AS value
877    FROM
878        process_measure m,
879        trace_range tr
880        left join process_measure_filter f on f.id = m.filter_id
881    WHERE
882        f.name = ${condition}
883        AND m.ts - tr.start_ts = ${startNs}
884    AND f.ipid = ${ipid}
885    GROUP BY m.ts
886    UNION
887    SELECT
888        'ShmPurg' AS name,
889        SUM( pss ) AS size
890    FROM
891        memory_ashmem,
892        trace_range tr
893    WHERE
894        ipid = ${ipid}
895        AND ts - tr.start_ts = ${startNs}
896        AND flag = 0
897        ${pinSql}
898    GROUP BY ts`
899  );
900};
901///////////////////////////////////////////////
902//VM  Purgeable 框选 tab页
903export const queryProcessPurgeableTab = (
904  leftNs: number,
905  rightNs: number,
906  dur: number,
907  ipid: number,
908  isPin?: boolean
909): //@ts-ignore
910Promise<Array<unknown>> => {
911  const pinSql = isPin ? ' AND ref_count > 0' : '';
912  let filterSql = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'";
913  return query(
914    'queryProcessPurgeableTab',
915    `SELECT name, MAX(size) AS maxSize, MIN(size) AS minSize, AVG(size) AS avgSize
916    FROM
917      (SELECT
918        'ShmPurg' AS name, ts - tr.start_ts AS startTs, SUM( pss ) AS size
919      FROM
920        memory_ashmem,
921        trace_range tr
922      WHERE
923        ipid = ${ipid}
924        AND flag = 0
925        ${pinSql}
926      GROUP BY ts
927      UNION
928      SELECT
929      CASE
930          WHEN f.name = 'mem.purg_pin' THEN
931          'PinedPurg' ELSE 'TotalPurg'
932        END AS name,
933        m.ts - tr.start_ts AS startTs,
934        sum( m.value ) AS size
935      FROM
936        process_measure m,
937        trace_range tr
938        LEFT JOIN process_measure_filter f ON f.id = m.filter_id
939      WHERE f.name = ${filterSql}
940        AND f.ipid = ${ipid}
941      GROUP BY m.ts
942    ) combined_data, trace_range tr
943    WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs
944    GROUP BY name`
945  );
946};
947export const getTabPowerDetailsData = (
948  leftNs: number,
949  rightNs: number
950): Promise<
951  Array<{
952    startNS: number;
953    eventName: string;
954    appKey: string;
955    eventValue: string;
956  }>
957> =>
958  query(
959    'getTabPowerDetailsData',
960    `SELECT
961        ( S.ts - TR.start_ts ) AS startNS,
962        D.data AS eventName,
963        D2.data AS appKey,
964        group_concat( ( CASE WHEN S.type = 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
965        FROM
966        trace_range AS TR,
967        hisys_event_measure AS S
968        LEFT JOIN data_dict AS D ON D.id = S.name_id
969        LEFT JOIN app_name AS APP ON APP.id = S.key_id
970        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
971        where
972        D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN')
973        and
974        D2.data in ('APPNAME')
975        GROUP BY
976        S.serial,
977        APP.app_key,
978        D.data,
979        D2.data
980        UNION
981        SELECT
982        ( S.ts - TR.start_ts ) AS startNS,
983        D1.data AS eventName,
984        D2.data AS appKey,
985        group_concat( ( CASE WHEN S.type = 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
986        FROM
987        trace_range AS TR,
988        hisys_event_measure AS S
989        LEFT JOIN data_dict AS D1 ON D1.id = S.name_id
990        LEFT JOIN app_name AS APP ON APP.id = S.key_id
991        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
992        where
993        D1.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN')
994        and
995        D2.data in ('CHARGE','BACKGROUND_TIME','SCREEN_ON_TIME','SCREEN_OFF_TIME','LOAD','USAGE','DURATION','CAMERA_ID',
996        'FOREGROUND_COUNT','BACKGROUND_COUNT','SCREEN_ON_COUNT','SCREEN_OFF_COUNT','COUNT','UID','FOREGROUND_DURATION',
997        'FOREGROUND_ENERGY','BACKGROUND_DURATION','BACKGROUND_ENERGY','SCREEN_ON_DURATION','SCREEN_ON_ENERGY',
998        'SCREEN_OFF_DURATION','SCREEN_OFF_ENERGY','ENERGY')
999        and
1000        (S.ts - TR.start_ts) >= $leftNS
1001        and (S.ts - TR.start_ts) <= $rightNS
1002        GROUP BY
1003        S.serial,
1004        APP.app_key,
1005        D1.data,
1006        D2.data
1007        ORDER BY
1008        eventName;`,
1009    { $leftNS: leftNs, $rightNS: rightNs }
1010  );
1011
1012export const getTabPowerBatteryData = (
1013  rightNs: number
1014): Promise<
1015  Array<{
1016    ts: number;
1017    eventName: string;
1018    appKey: string;
1019    eventValue: string;
1020  }>
1021> =>
1022  query(
1023    'getTabPowerBatteryData',
1024    `select
1025      MAX(S.ts) as ts,
1026      D.data as eventName,
1027      D2.data as appKey,
1028      group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as eventValue
1029      from
1030      trace_range AS TR,
1031      hisys_event_measure as S
1032      left join
1033      data_dict as D
1034      on
1035      D.id=S.name_id
1036      left join
1037      app_name as APP
1038      on
1039      APP.id=S.key_id
1040      left join
1041      data_dict as D2
1042      on
1043      D2.id=APP.app_key
1044      where
1045      D.data = 'POWER_IDE_BATTERY'
1046      and D2.data in ('GAS_GAUGE','CHARGE','SCREEN','LEVEL','CURRENT','CAPACITY','UID')
1047      and (S.ts - TR.start_ts) >= 0
1048      and (S.ts - TR.start_ts) <= $rightNS
1049      group by APP.app_key,D.data,D2.data;`,
1050    { $rightNS: rightNs }
1051  );
1052export const queryPowerData = (): Promise<
1053  Array<{
1054    id: number;
1055    startNS: number;
1056    eventName: string;
1057    appKey: string;
1058    eventValue: string;
1059  }>
1060> =>
1061  query(
1062    'queryPowerData',
1063    `SELECT
1064         S.id,
1065        ( S.ts - TR.start_ts ) AS startNS,
1066        D.data AS eventName,
1067        D2.data AS appKey,
1068        group_concat( ( CASE WHEN S.type = 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
1069        FROM
1070        trace_range AS TR,
1071        hisys_event_measure AS S
1072        LEFT JOIN data_dict AS D
1073        ON D.id = S.name_id
1074        LEFT JOIN app_name AS APP
1075        ON APP.id = S.key_id
1076        LEFT JOIN data_dict AS D2
1077        ON D2.id = APP.app_key
1078        where
1079        D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN')
1080        and
1081        D2.data in ('BACKGROUND_ENERGY','FOREGROUND_ENERGY','SCREEN_ON_ENERGY','SCREEN_OFF_ENERGY','ENERGY','APPNAME')
1082        GROUP BY
1083        S.serial,
1084        APP.app_key,
1085        D.data,
1086        D2.data
1087        ORDER BY
1088        eventName;`,
1089    {}
1090  );
1091export const getTabLiveProcessData = (leftNs: number, rightNs: number): Promise<Array<LiveProcess>> =>
1092  query<LiveProcess>(
1093    'getTabLiveProcessData',
1094    `SELECT
1095        process.id as processId,
1096        process.name as processName,
1097        process.ppid as responsibleProcess,
1098        process.uud as userName,
1099        process.usag as cpu,
1100        process.threadN as threads,
1101        process.pss as memory,
1102        process.cpu_time as cpuTime,
1103        process.disk_reads as diskReads,
1104        process.disk_writes as diskWrite
1105        FROM
1106        (
1107        SELECT
1108        tt.process_id AS id,
1109        tt.process_name AS name,
1110        tt.parent_process_id AS ppid,
1111        tt.uid as uud,
1112        tt.cpu_usage as usag,
1113        tt.thread_num AS threadN,
1114        mt.maxTT - TR.start_ts as endTs,
1115        tt.pss_info as pss,
1116        tt.cpu_time,
1117        tt.disk_reads,
1118        tt.disk_writes
1119        FROM
1120        live_process tt
1121        LEFT JOIN trace_range AS TR
1122        LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT
1123        from live_process re GROUP BY re.process_name, re.process_id ) mt
1124        on mt.idd = tt.process_id where endTs >= $rightNS
1125        GROUP BY
1126        tt.process_name,
1127        tt.process_id
1128        ) process ;`,
1129    { $leftNS: leftNs, $rightNS: rightNs }
1130  );
1131
1132export const getTabProcessHistoryData = (
1133  leftNs: number,
1134  rightNs: number,
1135  processId: number | undefined,
1136  threadId: number | undefined
1137): Promise<Array<ProcessHistory>> =>
1138  query<ProcessHistory>(
1139    'getTabProcessHistoryData',
1140    `SELECT
1141        process.id as processId,
1142        process.isD as alive,
1143        process.startTS as firstSeen,
1144        process.endTs as lastSeen,
1145        process.name as processName,
1146        process.ppid as responsibleProcess,
1147        process.uuid as userName,
1148        process.cpu_time as cpuTime,
1149        0 as pss
1150        FROM
1151        (
1152        SELECT
1153        tt.process_id AS id,
1154        tt.process_name AS name,
1155        tt.parent_process_id AS ppid,
1156        tt.uid AS uuid,
1157        tt.cpu_time,
1158        (mt.minTT - TR.start_ts ) AS startTS,
1159        mt.maxTT - TR.start_ts as endTs,
1160        (mt.maxTT - TR.start_ts - $rightNS) > 0 as isD
1161        FROM
1162        live_process tt
1163        LEFT JOIN trace_range AS TR
1164        LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT
1165        from live_process re GROUP BY re.process_name, re.process_id ) mt
1166        on mt.idd = tt.process_id
1167        GROUP BY
1168        tt.process_name,
1169        tt.process_id
1170        ) process;`,
1171    {
1172      $leftNS: leftNs,
1173      $rightNS: rightNs,
1174      $processID: processId,
1175      $threadID: threadId,
1176    }
1177  );
1178export const getTabSlices = (
1179  funTids: Array<number>,
1180  pids: Array<number>,
1181  leftNS: number,
1182  rightNS: number
1183): //@ts-ignore
1184Promise<Array<unknown>> =>
1185  query<SelectionData>(
1186    'getTabSlices',
1187    `
1188    select
1189      c.name as name,
1190      sum(c.dur) as wallDuration,
1191      avg(c.dur) as avgDuration,
1192      count(c.name) as occurrences
1193    from
1194      thread T, trace_range TR
1195      left join process P on T.ipid = P.id
1196    left join
1197      callstack C
1198    on
1199      T.id = C.callid
1200    where
1201      C.ts > 0
1202      and
1203      c.dur >= 0
1204    and
1205      T.tid in (${funTids.join(',')})
1206    and
1207      P.pid in (${pids.join(',')})
1208    and
1209      c.cookie is null
1210    and
1211      not ((C.ts - TR.start_ts + C.dur < $leftNS) or (C.ts - TR.start_ts > $rightNS))
1212    group by
1213      c.name
1214    order by
1215      wallDuration desc;`,
1216    { $leftNS: leftNS, $rightNS: rightNS }
1217  );
1218export const getTabThreadStates = (
1219  tIds: Array<number>,
1220  leftNS: number,
1221  rightNS: number
1222): //@ts-ignore
1223Promise<Array<unknown>> =>
1224  query<SelectionData>(
1225    'getTabThreadStates',
1226    `
1227    select
1228      B.pid,
1229      B.tid,
1230      B.state,
1231      sum(B.dur) as wallDuration,
1232      avg(ifnull(B.dur,0)) as avgDuration,
1233      count(B.tid) as occurrences
1234    from
1235      thread_state AS B
1236    left join
1237      trace_range AS TR
1238    where
1239      B.tid in (${tIds.join(',')})
1240    and
1241      not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS))
1242    group by
1243      B.pid, B.tid, B.state
1244    order by
1245      wallDuration desc;`,
1246    { $leftNS: leftNS, $rightNS: rightNS }
1247  );
1248
1249// 查询线程状态详细信息
1250export const getTabThreadStatesDetail = (
1251  tIds: Array<number>,
1252  leftNS: number,
1253  rightNS: number
1254): //@ts-ignore
1255Promise<Array<unknown>> =>
1256  query<SelectionData>(
1257    'getTabThreadStates',
1258    `select
1259        B.pid,
1260        B.tid,
1261        B.state,
1262        B.ts,
1263        B.dur
1264      from
1265        thread_state AS B
1266      left join
1267        trace_range AS TR
1268      where
1269        B.tid in (${tIds.join(',')})
1270      and
1271        not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS))
1272      order by ts;`,
1273    { $leftNS: leftNS, $rightNS: rightNS }
1274  );
1275export const queryAnomalyDetailedData = (leftNs: number, rightNs: number): Promise<Array<EnergyAnomalyStruct>> =>
1276  query<EnergyAnomalyStruct>(
1277    'queryAnomalyDetailedData',
1278    `select
1279  S.ts,
1280  D.data as eventName,
1281  D2.data as appKey,
1282  group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as Value
1283  from trace_range AS TR,hisys_event_measure as S
1284  left join data_dict as D on D.id=S.name_id
1285  left join app_name as APP on APP.id=S.key_id
1286  left join data_dict as D2 on D2.id=APP.app_key
1287  where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_ALARM_WAKEUP','ANOMALY_KERNEL_WAKELOCK',
1288  'ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_CPU_ENERGY','ANOMALY_WAKEUP')
1289  and D2.data in ('APPNAME')
1290  and (S.ts - TR.start_ts) >= $leftNS
1291   and (S.ts - TR.start_ts) <= $rightNS
1292  group by S.serial,APP.app_key,D.data,D2.data
1293  union
1294  select
1295  S.ts,
1296  D.data as eventName,
1297  D2.data as appKey,
1298  group_concat((case when S.type = 1 then S.string_value else S.int_value end), ',') as Value
1299  from trace_range AS TR,hisys_event_measure as S
1300  left join data_dict as D on D.id = S.name_id
1301  left join app_name as APP on APP.id = S.key_id
1302  left join data_dict as D2 on D2.id = APP.app_key
1303  where D.data in ('ANOMALY_SCREEN_OFF_ENERGY', 'ANOMALY_ALARM_WAKEUP', 'ANOMALY_KERNEL_WAKELOCK',
1304  'ANOMALY_RUNNINGLOCK', 'ANORMALY_APP_ENERGY', 'ANOMALY_GNSS_ENERGY', 'ANOMALY_CPU_HIGH_FREQUENCY', 'ANOMALY_CPU_ENERGY', 'ANOMALY_WAKEUP')
1305  and D2.data not in ('pid_', 'tid_', 'type_', 'tz_', 'uid_', 'domain_', 'id_', 'level_', 'info_', 'tag_', 'APPNAME')
1306  and (S.ts - TR.start_ts) >= $leftNS
1307  and (S.ts - TR.start_ts) <= $rightNS
1308  group by S.serial, APP.app_key, D.data, D2.data;`,
1309    { $leftNS: leftNs, $rightNS: rightNs }
1310  );
1311
1312export const queryBySelectExecute = (
1313  executeId: string,
1314  itid: number
1315): Promise<
1316  Array<{
1317    tid: number;
1318    allocation_task_row: number;
1319    execute_task_row: number;
1320    return_task_row: number;
1321    priority: number;
1322  }>
1323> => {
1324  let sqlStr = `SELECT thread.tid,
1325                       task_pool.allocation_task_row,
1326                       task_pool.execute_task_row,
1327                       task_pool.return_task_row,
1328                       task_pool.priority
1329                FROM task_pool
1330                       LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row
1331                       LEFT JOIN thread ON thread.id = callstack.callid
1332                WHERE task_pool.task_id = $executeId AND task_pool.execute_itid = $itid;
1333    `;
1334  return query('queryBySelectExecute', sqlStr, { $executeId: executeId, $itid: itid });
1335};
1336