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