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