• 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 = async (itid: number, startTime: number): Promise<unknown> => {
333  let sql1 = `select wakeup_from from instant where ts = ${startTime} and ref = ${itid} limit 1`;
334  const result = await query('queryThreadWakeUpFrom', sql1, {}, { traceId: Utils.currentSelectTrace });
335  let res: unknown = [];
336  if (result && result.length > 0) { //@ts-ignore
337    let wakeupFromItid = result[0].wakeup_from; // 获取wakeup_from的值
338    let sql2 = `
339            select (A.ts - B.start_ts) as ts,
340                   A.tid,
341                   A.itid,
342                   A.pid,
343                   A.cpu,
344                   A.dur,
345                   A.arg_setid as argSetID
346            from thread_state A, trace_range B
347            where A.state = 'Running'
348            and A.itid = ${wakeupFromItid}
349            and (A.ts - B.start_ts) < (${startTime} - B.start_ts)
350            order by ts desc limit 1
351          `;
352    res = query('queryThreadWakeUpFrom', sql2, {}, { traceId: Utils.currentSelectTrace });
353  }
354  return res;
355};
356
357export const queryRWakeUpFrom = async (itid: number, startTime: number): Promise<unknown> => {
358  let sql1 = `select wakeup_from from instant where ts = ${startTime} and ref = ${itid} limit 1`;
359  const res = await query('queryRWakeUpFrom', sql1, {}, { traceId: Utils.currentSelectTrace });
360  let result: unknown = [];
361  if (res && res.length) {
362    //@ts-ignore
363    let wakeupFromItid = res[0].wakeup_from;
364    let sql2 = `
365      select
366        (A.ts - B.start_ts) as ts,
367        A.tid,
368        A.itid,
369        A.arg_setid as argSetID
370      from
371        thread_state A,
372        trace_range B
373      where
374        A.state = 'Running'
375        and A.itid = ${wakeupFromItid}
376        and A.ts < ${startTime}
377      order by
378        ts desc
379        limit 1
380    `;
381    result = query('queryRWakeUpFrom', sql2, {}, { traceId: Utils.currentSelectTrace });
382  }
383  return result;
384};
385export const queryRunnableTimeByRunning = (tid: number, startTime: number): Promise<Array<WakeupBean>> => {
386  let sql = `
387select ts from thread_state,trace_range where ts + dur -start_ts = ${startTime} and state = 'R' and tid=${tid} limit 1
388    `;
389  return query('queryRunnableTimeByRunning', sql, {}, { traceId: Utils.currentSelectTrace });
390};
391
392export const queryProcessByTable = (traceId?: string): Promise<
393  Array<{
394    pid: number | null;
395    processName: string | null;
396  }>
397> =>
398  query(
399    'queryProcessByTable',
400    `
401    SELECT
402      pid, name as processName
403    FROM
404      process where pid != 0`,
405    {},
406    { traceId: traceId }
407  );
408
409export const getTabStartups = (
410  ids: Array<number>,
411  leftNS: number,
412  rightNS: number
413): //@ts-ignore
414  Promise<Array<unknown>> => {
415  let sql = `
416select
417    P.pid,
418    P.name as process,
419    (A.start_time - B.start_ts) as startTs,
420    (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur,
421    A.start_name as startName
422from app_startup A,trace_range B
423left join process P on A.ipid = P.ipid
424where P.pid in (${ids.join(',')})
425and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS}))
426order by start_name;`;
427  return query('getTabStartups', sql, {});
428};
429
430export const getTabStaticInit = (
431  ids: Array<number>,
432  leftNS: number,
433  rightNS: number
434): //@ts-ignore
435  Promise<Array<unknown>> => {
436  let sql = `
437select
438    P.pid,
439    P.name as process,
440    (A.start_time - B.start_ts) as startTs,
441    (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur,
442    A.so_name as soName
443from static_initalize A,trace_range B
444left join process P on A.ipid = P.ipid
445where P.pid in (${ids.join(',')})
446and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS}))
447order by dur desc;`;
448  return query('getTabStaticInit', sql, {});
449};
450
451export const queryBinderArgsByArgset = (argset: number): Promise<Array<BinderArgBean>> =>
452  query(
453    'queryBinderArgsByArgset',
454    `
455    select
456      *
457    from
458      args_view
459    where
460      argset = $argset;`,
461    { $argset: argset },
462    { traceId: Utils.currentSelectTrace }
463  );
464
465export const queryProcessData = (
466  pid: number,
467  startNS: number,
468  endNS: number
469): //@ts-ignore
470  Promise<Array<unknown>> =>
471  query(
472    'queryProcessData',
473    `
474    select  ta.cpu,
475        dur,
476        ts-${window.recordStartNS} as startTime
477from thread_state ta
478where ta.cpu is not null and pid=$pid and startTime between $startNS and $endNS;`,
479    {
480      $pid: pid,
481      $startNS: startNS,
482      $endNS: endNS,
483    }
484  );
485
486export const queryProcessMem = (): //@ts-ignore
487  Promise<Array<unknown>> =>
488  query(
489    'queryProcessMem',
490    `
491    select
492      process_measure_filter.id as trackId,
493      process_measure_filter.name as trackName,
494      ipid as upid,
495      process.pid,
496      process.name as processName
497    from
498      process_measure_filter
499    join
500      process using (ipid)
501    order by trackName;`
502  );
503
504export const queryProcessThreadDataCount = (): //@ts-ignore
505  Promise<Array<unknown>> =>
506  query(
507    'queryProcessThreadDataCount',
508    `select pid,count(id) as count
509    from thread_state
510    where ts between ${window.recordStartNS} and ${window.recordEndNS} group by pid;`,
511    {}
512  );
513
514export const queryProcessFuncDataCount = (): //@ts-ignore
515  Promise<Array<unknown>> =>
516  query(
517    'queryProcessFuncDataCount',
518    `select
519        P.pid,
520        count(tid) as count
521    from callstack C
522    left join thread A on A.id = C.callid
523    left join process AS P on P.id = A.ipid
524    where  C.ts between ${window.recordStartNS} and ${window.recordEndNS}
525    group by pid;`,
526    {}
527  );
528
529export const queryProcessMemDataCount = (): //@ts-ignore
530  Promise<Array<unknown>> =>
531  query(
532    'queryProcessMemDataCount',
533    `select
534      p.pid as pid, count(value) count
535    from process_measure c
536    left join process_measure_filter f on f.id = c.filter_id
537    left join process p on p.ipid = f.ipid
538where f.id not NULL and value>0
539 and c.ts between ${window.recordStartNS} and ${window.recordEndNS}
540group by p.pid`,
541    {}
542  );
543
544export const queryProcessMemData = (trackId: number): Promise<Array<ProcessMemStruct>> =>
545  query(
546    'queryProcessMemData',
547    `
548    select
549      c.type,
550      ts,
551      value,
552      filter_id as track_id,
553      c.ts-tb.start_ts startTime
554    from
555      process_measure c,
556      trace_range tb
557    where
558      filter_id = $id;`,
559    { $id: trackId }
560  );
561
562export const queryThreads = ():
563  Promise<Array<{ id: number; tid: number; name: string; }>> =>
564  query('queryThreads', `select id,tid,(ifnull(name,'Thread') || '(' || tid || ')') name from thread where id != 0;`);
565
566export const queryDataDICT = async (): Promise<Array<unknown>> => {
567  let dataDictBuffer = await query(
568    'queryDataDICT',
569    'select * from data_dict;',
570    {},
571    { action: 'exec-buf' }
572  );
573  // @ts-ignore
574  return Utils.convertJSON(dataDictBuffer);
575};
576
577export const queryAppStartupProcessIds = (): Promise<Array<{ pid: number }>> =>
578  query(
579    'queryAppStartupProcessIds',
580    `
581  SELECT pid FROM process
582  WHERE ipid IN (
583    SELECT ipid FROM app_startup
584    UNION
585    SELECT t.ipid FROM app_startup a LEFT JOIN thread t ON a.call_id = t.itid
586);`
587  );
588
589export const queryTaskPoolProcessIds = (): Promise<Array<{ pid: number }>> =>
590  query(
591    'queryAppStartupProcessIds',
592    `SELECT pid
593FROM
594    process
595WHERE
596    ipid IN (
597    SELECT DISTINCT
598    ( ipid )
599    FROM
600    thread
601    WHERE
602    itid IN ( SELECT DISTINCT ( callid ) FROM callstack WHERE name LIKE 'H:Task%' )
603    AND name = 'TaskWorkThread'
604    )`
605  );
606
607export const querySysCallThreadIds = (traceId?: string): Promise<Array<{ pid: number, tid: number, itid: number, ipid: number }>> =>
608  query(
609    'querySysCallThreadIds',
610    `SELECT tid, pid, itid, thread.ipid
611FROM
612    thread left join process on thread.ipid = process.ipid
613WHERE
614    itid IN (SELECT DISTINCT( itid ) FROM syscall )
615    `,
616    {},
617    { traceId: traceId}
618  );
619
620export const querySysCallEventDetail =
621(itid: number, startTs: number, dur: number, traceId?: string): Promise<Array<{tid: number, pid: number,
622  tName: string, pName: string, args: string, ret: number}>> =>
623  query(
624    'querySysCallEventDetail',
625    `SELECT tid, thread.name as tName, pid, process.name as pName, args, ret
626FROM
627  (select * from syscall where itid= ${itid} and ts = ${startTs} and dur = ${dur}) A
628  left join thread on A.itid = thread.itid
629  left join process on thread.ipid = process.ipid
630    `,
631    {},
632    { traceId: traceId}
633  );
634
635export const querySysCallEventWithBoxSelect =
636(ipidArr: Array<number>, itidArr: Array<number>, leftNs: number, rightNs: number): Promise<Array<{
637  pName: string,
638  tName: string,
639  pid: number,
640  tid: number,
641  nameId: number,
642  sumDur: number,
643  totalCount: number
644}>> =>
645  query(
646    'querySysCallEventWithBoxSelect',
647    `select ifnull(process.name, 'Process') as pName,
648	   ifnull(thread.name, 'Thread') as tName,
649	   process.pid,
650	   thread.tid,
651	   A.nameId,
652	   A.sumDur,
653	   A.totalCount
654from (
655select itid, syscall_number as nameId, sum(dur) as sumDur, count(1) as totalCount
656from syscall
657where
658  ${itidArr.length > 0 ? 'itid in (' + itidArr.join(',') + ')' : '1 = 1'}
659  and not ((ts - ${window.recordStartNS} + ifnull(dur,0) < ${leftNs}) or (ts - ${window.recordStartNS} > ${rightNs}))
660group by itid, syscall_number
661) as A
662left join thread on A.itid = thread.itid
663left join process on thread.ipid = process.ipid
664where
665  ${ipidArr.length > 0 ? 'thread.ipid in (' + ipidArr.join(',') + ')' : '1 = 1'}
666    `,
667    {}
668  );
669
670  export const querySysCallEventWithRange =
671(ipidArr: Array<number>, itidArr: Array<number>, leftNs: number, rightNs: number, sysCallId?: number): Promise<Array<{
672  pName: string,
673  tName: string,
674  pid: number,
675  tid: number,
676  nameId: number,
677  startTs: number,
678  dur: number,
679  args: string,
680  ret: number,
681}>> =>
682  query(
683    'querySysCallEventWithRange',
684    `select ifnull(process.name, 'Process') as pName,
685	   ifnull(thread.name, 'Thread') as tName,
686	   process.pid,
687	   thread.tid,
688	   A.nameId,
689	   A.startTs,
690	   A.dur,
691	   A.args,
692	   A.ret
693from (
694	select itid, syscall_number as nameId, (ts - ${window.recordStartNS}) as startTs, dur, args, ret
695	from syscall
696	where
697		${itidArr.length > 0 ? 'itid in (' + itidArr.join(',') + ')' : '1 = 1'}
698		and ${sysCallId !== undefined ? 'syscall_number = ' + sysCallId : '1 = 1'  }
699		and not ((ts - ${window.recordStartNS} + ifnull(dur,0) < ${leftNs}) or (ts - ${window.recordStartNS} > ${rightNs}))
700	) as A
701	left join thread on A.itid = thread.itid
702	left join process on thread.ipid = process.ipid
703where
704  ${ipidArr.length > 0 ? 'thread.ipid in (' + ipidArr.join(',') + ')' : '1 = 1'}
705    `,
706    {}
707  );
708
709export const queryProcessContentCount = (traceId?: string): Promise<Array<unknown>> =>
710  query(
711    `queryProcessContentCount`,
712    `select
713    pid,
714    switch_count,
715    thread_count,
716    slice_count,
717    mem_count
718    from process;`,
719    {},
720    { traceId: traceId }
721  );
722
723export const queryProcessThreadsByTable = (traceId?: string): Promise<Array<ThreadStruct>> =>
724  query(
725    'queryProcessThreadsByTable',
726    `
727        select
728        p.pid as pid,
729        p.ipid as upid,
730        t.tid as tid,
731        p.name as processName,
732        t.name as threadName,
733        t.switch_count as switchCount,
734        t.itid as utid
735        from
736        thread t left join process  p on t.ipid = p.id where t.tid != 0`,
737    {},
738    { traceId: traceId }
739  );
740
741export const queryStartupPidArray = (): Promise<Array<{ pid: number }>> =>
742  query(
743    'queryStartupPidArray',
744    `
745    select distinct pid
746from app_startup A,trace_range B left join process P on A.ipid = p.ipid
747where A.start_time between B.start_ts and B.end_ts;`,
748    {}
749  );
750
751export const queryProcessStartup = (pid: number): Promise<Array<AppStartupStruct>> =>
752  query(
753    'queryProcessStartup',
754    `
755    select
756    P.pid,
757    A.tid,
758    A.call_id as itid,
759    (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs,
760    (case
761        when A.start_time < B.start_ts then (A.end_time - B.start_ts)
762        when A.end_time = -1 then 0
763        else (A.end_time - A.start_time) end) as dur,
764    A.start_name as startName
765from app_startup A,trace_range B
766left join process P on A.ipid = P.ipid
767where P.pid = $pid
768order by start_name;`,
769    { $pid: pid }
770  );
771
772export const queryProcessAllAppStartup = (pids: Array<number>): Promise<Array<AppStartupStruct>> =>
773  query(
774    'queryProcessStartup',
775    `
776    select
777    P.pid,
778    A.tid,
779    A.call_id as itid,
780    (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs,
781    (case
782        when A.start_time < B.start_ts then (A.end_time - B.start_ts)
783        when A.end_time = -1 then 0
784        else (A.end_time - A.start_time) end) as dur,
785    A.start_name as startName
786from app_startup A,trace_range B
787left join process P on A.ipid = P.ipid
788where P.pid in(${pids.join(',')})
789order by start_name;`,
790    { $pid: pids }
791  );
792
793export const querySingleAppStartupsName = (
794  pid: number
795): //@ts-ignore
796  Promise<Array<unknown>> =>
797  query(
798    'queryAllAppStartupsName',
799    `select name from process
800    where pid=$pid`,
801    { $pid: pid }
802  );
803
804export const queryProcessSoMaxDepth = (): Promise<Array<{ pid: number; maxDepth: number }>> =>
805  query(
806    'queryProcessSoMaxDepth',
807    `select p.pid,max(depth) maxDepth
808from static_initalize S,trace_range B left join process p on S.ipid = p.ipid
809where S.start_time between B.start_ts and B.end_ts
810group by p.pid;`,
811    {}
812  );
813export const queryAllThreadName = (): //@ts-ignore
814  Promise<Array<unknown>> => {
815  return query(
816    'queryAllThreadName',
817    `
818          select name,tid from thread;`
819  );
820};
821
822export const queryAllProcessNames = (): //@ts-ignore
823  Promise<Array<unknown>> => {
824  return query(
825    'queryAllProcessNames',
826    `
827        select id, name, pid from process;`
828  );
829};
830
831export const queryRsProcess = (): //@ts-ignore
832  Promise<Array<unknown>> => {
833  return query(
834    'queryRsProcess',
835    `
836        SELECT p.pid FROM process p WHERE p.ipid = (SELECT t.ipid FROM thread t WHERE t.itid IN
837        ( SELECT c.callid FROM callstack c WHERE name LIKE '%H:RSMainThread::DoComposition%' LIMIT 1 )
838      LIMIT 1
839      )`
840  );
841};
842
843export const queryProcessSoInitData = (pid: number): Promise<Array<SoStruct>> =>
844  query(
845    'queryProcessSoInitData',
846    `
847    select
848    P.pid,
849    T.tid,
850    A.call_id as itid,
851    (A.start_time - B.start_ts) as startTs,
852    (A.end_time - A.start_time) as dur,
853    A.so_name as soName,
854    A.depth
855from static_initalize A,trace_range B
856left join process P on A.ipid = P.ipid
857left join thread T on A.call_id = T.itid
858where P.pid = $pid;`,
859    { $pid: pid }
860  );
861
862export const queryThreadAndProcessName = (traceId?: string): //@ts-ignore
863  Promise<Array<unknown>> =>
864  query(
865    'queryThreadAndProcessName',
866    `
867    select tid id,name,'t' type from thread
868union all
869select pid id,name,'p' type from process;`,
870    {},
871    { traceId: traceId }
872  );
873
874export const queryThreadStateArgs = (argset: number): Promise<Array<BinderArgBean>> =>
875  query('queryThreadStateArgs',
876    `select args_view.* from args_view where argset = ${argset}`, {}, {
877    traceId: Utils.currentSelectTrace
878  });
879
880export const queryThreadStateArgsByName = (key: string, traceId?: string):
881  Promise<Array<{ argset: number; strValue: string }>> =>
882  query(
883    'queryThreadStateArgsByName',
884    `select
885    strValue,
886    argset
887    from args_view where keyName = $key`,
888    { $key: key },
889    { traceId: traceId }
890  );
891
892export const queryArgsById = (key: string, traceId?: string):
893  Promise<Array<{ id: number }>> =>
894  query(
895    'queryArgsById',
896    `select
897    id
898    from data_dict
899    WHERE data = $key`,
900    { $key: key },
901    { traceId: traceId }
902  );
903
904export const queryThreadStateArgsById = (id: number, traceId?: string):
905  Promise<Array<{ argset: number; strValue: string }>> =>
906  query(
907    'queryThreadStateArgsById',
908    `select
909    A.argset,
910    DD.data as strValue
911    from
912    (select argset,value
913    from args where key = $id) as A left join data_dict as DD
914    on DD.id = A.value
915    `,
916    { $id: id },
917    { traceId: traceId }
918  );
919
920export const queryThreadWakeUp = (itid: number, startTime: number, dur: number):
921  Promise<Array<WakeupBean>> =>
922  query(
923    'queryThreadWakeUp',
924    `
925select 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
926from
927  (select min(ts) as wakeTs,ref as itid from instant,trace_range
928       where name = 'sched_wakeup'
929       and wakeup_from = $itid
930       and ts > start_ts + $startTime
931       and ts < start_ts + $startTime + $dur
932      group by ref
933       ) TW
934left join thread_state TA on TW.itid = TA.itid
935left join trace_range TR
936where TA.ts > TW.wakeTs
937group by TA.tid,TA.pid;
938    `,
939    { $itid: itid, $startTime: startTime, $dur: dur },
940    { traceId: Utils.currentSelectTrace }
941  );
942
943export const getTabRunningPercent = (
944  tIds: Array<number>,
945  pIds: Array<number>,
946  leftNS: number,
947  rightNS: number
948): Promise<
949  Array<{
950    pid: number;
951    tid: number;
952    cpu: number;
953    dur: number;
954    ts: number;
955    process: string;
956    thread: string;
957  }>
958> =>
959  query(
960    'getTabRunningPercent',
961    `
962          select
963            B.pid,
964            B.tid,
965            B.cpu,
966            B.dur,
967            B.ts
968          from
969            thread_state AS B
970          left join
971            trace_range AS TR
972          where
973            B.tid in (${tIds.join(',')})
974          and
975            B.state='Running'
976          and
977            B.pid in (${pIds.join(',')})
978          and
979            not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS}))
980          order by ts
981       `,
982    {},
983    { traceId: Utils.currentSelectTrace }
984  );
985
986//VM  Purgeable 点选 tab页
987export const queryProcessPurgeableSelectionTab = (
988  startNs: number,
989  ipid: number,
990  isPin?: boolean
991): //@ts-ignore
992  Promise<Array<unknown>> => {
993  const condition = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'";
994  const pinSql = isPin ? ' AND ref_count > 0' : '';
995  return query(
996    'queryProcessPurgeableSelectionTab',
997    `SELECT
998        ( CASE WHEN f.name = 'mem.purg_pin' THEN 'PinedPurg' ELSE 'TotalPurg' END ) AS name,
999        SUM( m.value )  AS value
1000    FROM
1001        process_measure m,
1002        trace_range tr
1003        left join process_measure_filter f on f.id = m.filter_id
1004    WHERE
1005        f.name = ${condition}
1006        AND m.ts - tr.start_ts = ${startNs}
1007    AND f.ipid = ${ipid}
1008    GROUP BY m.ts
1009    UNION
1010    SELECT
1011        'ShmPurg' AS name,
1012        SUM( pss ) AS size
1013    FROM
1014        memory_ashmem,
1015        trace_range tr
1016    WHERE
1017        ipid = ${ipid}
1018        AND ts - tr.start_ts = ${startNs}
1019        AND flag = 0
1020        ${pinSql}
1021    GROUP BY ts`
1022  );
1023};
1024///////////////////////////////////////////////
1025//VM  Purgeable 框选 tab页
1026export const queryProcessPurgeableTab = (
1027  leftNs: number,
1028  rightNs: number,
1029  dur: number,
1030  ipid: number,
1031  isPin?: boolean
1032): //@ts-ignore
1033  Promise<Array<unknown>> => {
1034  const pinSql = isPin ? ' AND ref_count > 0' : '';
1035  let filterSql = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'";
1036  return query(
1037    'queryProcessPurgeableTab',
1038    `SELECT name, MAX(size) AS maxSize, MIN(size) AS minSize, AVG(size) AS avgSize
1039    FROM
1040      (SELECT
1041        'ShmPurg' AS name, ts - tr.start_ts AS startTs, SUM( pss ) AS size
1042      FROM
1043        memory_ashmem,
1044        trace_range tr
1045      WHERE
1046        ipid = ${ipid}
1047        AND flag = 0
1048        ${pinSql}
1049      GROUP BY ts
1050      UNION
1051      SELECT
1052      CASE
1053          WHEN f.name = 'mem.purg_pin' THEN
1054          'PinedPurg' ELSE 'TotalPurg'
1055        END AS name,
1056        m.ts - tr.start_ts AS startTs,
1057        sum( m.value ) AS size
1058      FROM
1059        process_measure m,
1060        trace_range tr
1061        LEFT JOIN process_measure_filter f ON f.id = m.filter_id
1062      WHERE f.name = ${filterSql}
1063        AND f.ipid = ${ipid}
1064      GROUP BY m.ts
1065    ) combined_data, trace_range tr
1066    WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs
1067    GROUP BY name`
1068  );
1069};
1070export const getTabPowerDetailsData = (
1071  leftNs: number,
1072  rightNs: number
1073): Promise<
1074  Array<{
1075    startNS: number;
1076    eventName: string;
1077    appKey: string;
1078    eventValue: string;
1079  }>
1080> =>
1081  query(
1082    'getTabPowerDetailsData',
1083    `SELECT
1084        ( S.ts - TR.start_ts ) AS startNS,
1085        D.data AS eventName,
1086        D2.data AS appKey,
1087        group_concat( ( CASE WHEN S.type = 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
1088        FROM
1089        trace_range AS TR,
1090        hisys_event_measure AS S
1091        LEFT JOIN data_dict AS D ON D.id = S.name_id
1092        LEFT JOIN app_name AS APP ON APP.id = S.key_id
1093        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
1094        where
1095        D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY',
1096        'POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO',
1097        'POWER_IDE_WIFISCAN')
1098        and
1099        D2.data in ('APPNAME')
1100        GROUP BY
1101        S.serial,
1102        APP.app_key,
1103        D.data,
1104        D2.data
1105        UNION
1106        SELECT
1107        ( S.ts - TR.start_ts ) AS startNS,
1108        D1.data AS eventName,
1109        D2.data AS appKey,
1110        group_concat( ( CASE WHEN S.type = 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
1111        FROM
1112        trace_range AS TR,
1113        hisys_event_measure AS S
1114        LEFT JOIN data_dict AS D1 ON D1.id = S.name_id
1115        LEFT JOIN app_name AS APP ON APP.id = S.key_id
1116        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
1117        where
1118        D1.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY',
1119        'POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO',
1120        'POWER_IDE_WIFISCAN')
1121        and
1122        D2.data in ('CHARGE','BACKGROUND_TIME','SCREEN_ON_TIME','SCREEN_OFF_TIME','LOAD','USAGE',
1123        'DURATION','CAMERA_ID','FOREGROUND_COUNT','BACKGROUND_COUNT','SCREEN_ON_COUNT',
1124        'SCREEN_OFF_COUNT','COUNT','UID','FOREGROUND_DURATION','FOREGROUND_ENERGY',
1125        'BACKGROUND_DURATION','BACKGROUND_ENERGY','SCREEN_ON_DURATION','SCREEN_ON_ENERGY',
1126        'SCREEN_OFF_DURATION','SCREEN_OFF_ENERGY','ENERGY')
1127        and
1128        (S.ts - TR.start_ts) >= $leftNS
1129        and (S.ts - TR.start_ts) <= $rightNS
1130        GROUP BY
1131        S.serial,
1132        APP.app_key,
1133        D1.data,
1134        D2.data
1135        ORDER BY
1136        eventName;`,
1137    { $leftNS: leftNs, $rightNS: rightNs }
1138  );
1139
1140export const getTabPowerBatteryData = (
1141  rightNs: number
1142): Promise<
1143  Array<{
1144    ts: number;
1145    eventName: string;
1146    appKey: string;
1147    eventValue: string;
1148  }>
1149> =>
1150  query(
1151    'getTabPowerBatteryData',
1152    `select
1153      MAX(S.ts) as ts,
1154      D.data as eventName,
1155      D2.data as appKey,
1156      group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as eventValue
1157      from
1158      trace_range AS TR,
1159      hisys_event_measure as S
1160      left join
1161      data_dict as D
1162      on
1163      D.id=S.name_id
1164      left join
1165      app_name as APP
1166      on
1167      APP.id=S.key_id
1168      left join
1169      data_dict as D2
1170      on
1171      D2.id=APP.app_key
1172      where
1173      D.data = 'POWER_IDE_BATTERY'
1174      and D2.data in ('GAS_GAUGE','CHARGE','SCREEN','LEVEL','CURRENT','CAPACITY','UID')
1175      and (S.ts - TR.start_ts) >= 0
1176      and (S.ts - TR.start_ts) <= $rightNS
1177      group by APP.app_key,D.data,D2.data;`,
1178    { $rightNS: rightNs }
1179  );
1180export const queryPowerData = (): Promise<
1181  Array<{
1182    id: number;
1183    startNS: number;
1184    eventName: string;
1185    appKey: string;
1186    eventValue: string;
1187  }>
1188> =>
1189  query(
1190    'queryPowerData',
1191    `SELECT
1192         S.id,
1193        ( S.ts - TR.start_ts ) AS startNS,
1194        D.data AS eventName,
1195        D2.data AS appKey,
1196        group_concat( ( CASE WHEN S.type = 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
1197        FROM
1198        trace_range AS TR,
1199        hisys_event_measure AS S
1200        LEFT JOIN data_dict AS D
1201        ON D.id = S.name_id
1202        LEFT JOIN app_name AS APP
1203        ON APP.id = S.key_id
1204        LEFT JOIN data_dict AS D2
1205        ON D2.id = APP.app_key
1206        where
1207        D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY',
1208        'POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO',
1209        'POWER_IDE_WIFISCAN')
1210        and
1211        D2.data in ('BACKGROUND_ENERGY','FOREGROUND_ENERGY','SCREEN_ON_ENERGY','SCREEN_OFF_ENERGY',
1212        'ENERGY','APPNAME')
1213        GROUP BY
1214        S.serial,
1215        APP.app_key,
1216        D.data,
1217        D2.data
1218        ORDER BY
1219        eventName;`,
1220    {}
1221  );
1222export const getTabLiveProcessData = (leftNs: number, rightNs: number): Promise<Array<LiveProcess>> =>
1223  query<LiveProcess>(
1224    'getTabLiveProcessData',
1225    `SELECT
1226        process.id as processId,
1227        process.name as processName,
1228        process.ppid as responsibleProcess,
1229        process.uud as userName,
1230        process.usag as cpu,
1231        process.threadN as threads,
1232        process.pss as memory,
1233        process.cpu_time as cpuTime,
1234        process.disk_reads as diskReads,
1235        process.disk_writes as diskWrite
1236        FROM
1237        (
1238        SELECT
1239        tt.process_id AS id,
1240        tt.process_name AS name,
1241        tt.parent_process_id AS ppid,
1242        tt.uid as uud,
1243        tt.cpu_usage as usag,
1244        tt.thread_num AS threadN,
1245        mt.maxTT - TR.start_ts as endTs,
1246        tt.pss_info as pss,
1247        tt.cpu_time,
1248        tt.disk_reads,
1249        tt.disk_writes
1250        FROM
1251        live_process tt
1252        LEFT JOIN trace_range AS TR
1253        LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT
1254        from live_process re GROUP BY re.process_name, re.process_id ) mt
1255        on mt.idd = tt.process_id where endTs >= $rightNS
1256        GROUP BY
1257        tt.process_name,
1258        tt.process_id
1259        ) process ;`,
1260    { $leftNS: leftNs, $rightNS: rightNs }
1261  );
1262
1263export const getTabProcessHistoryData = (
1264  leftNs: number,
1265  rightNs: number,
1266  processId: number | undefined,
1267  threadId: number | undefined
1268): Promise<Array<ProcessHistory>> =>
1269  query<ProcessHistory>(
1270    'getTabProcessHistoryData',
1271    `SELECT
1272        process.id as processId,
1273        process.isD as alive,
1274        process.startTS as firstSeen,
1275        process.endTs as lastSeen,
1276        process.name as processName,
1277        process.ppid as responsibleProcess,
1278        process.uuid as userName,
1279        process.cpu_time as cpuTime,
1280        0 as pss
1281        FROM
1282        (
1283        SELECT
1284        tt.process_id AS id,
1285        tt.process_name AS name,
1286        tt.parent_process_id AS ppid,
1287        tt.uid AS uuid,
1288        tt.cpu_time,
1289        (mt.minTT - TR.start_ts ) AS startTS,
1290        mt.maxTT - TR.start_ts as endTs,
1291        (mt.maxTT - TR.start_ts - $rightNS) > 0 as isD
1292        FROM
1293        live_process tt
1294        LEFT JOIN trace_range AS TR
1295        LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT
1296        from live_process re GROUP BY re.process_name, re.process_id ) mt
1297        on mt.idd = tt.process_id
1298        GROUP BY
1299        tt.process_name,
1300        tt.process_id
1301        ) process;`,
1302    {
1303      $leftNS: leftNs,
1304      $rightNS: rightNs,
1305      $processID: processId,
1306      $threadID: threadId,
1307    }
1308  );
1309export const getTabSlices = (
1310  funTids: Array<number>,
1311  pids: Array<number>,
1312  leftNS: number,
1313  rightNS: number
1314): Promise<Array<unknown>> =>
1315  query<SelectionData>(
1316    'getTabSlices',
1317    `
1318    select
1319      c.name as name,
1320      c.id,
1321      sum(c.dur) as wallDuration,
1322      count(c.name) as occurrences
1323    from
1324      thread T, trace_range TR
1325      left join process P on T.ipid = P.id
1326    left join
1327      callstack C
1328    on
1329      T.id = C.callid
1330    where
1331      C.ts > 0
1332      and
1333      c.dur >= 0
1334    and
1335      T.tid in (${funTids.join(',')})
1336    and
1337      P.pid in (${pids.join(',')})
1338    and
1339      c.cookie is null
1340    and
1341      not ((C.ts - TR.start_ts + C.dur < $leftNS) or (C.ts - TR.start_ts > $rightNS))
1342    group by
1343      c.name
1344    order by
1345      wallDuration desc;`,
1346    { $leftNS: leftNS, $rightNS: rightNS },
1347    { traceId: Utils.currentSelectTrace }
1348  );
1349
1350export const getTabThreadStates = (
1351  tIds: Array<number>,
1352  leftNS: number,
1353  rightNS: number
1354): //@ts-ignore
1355  Promise<Array<unknown>> =>
1356  query<SelectionData>(
1357    'getTabThreadStates',
1358    `
1359    select
1360      B.pid,
1361      B.tid,
1362      B.state,
1363      sum(B.dur) as wallDuration,
1364      avg(ifnull(B.dur,0)) as avgDuration,
1365      count(B.tid) as occurrences
1366    from
1367      thread_state AS B
1368    left join
1369      trace_range AS TR
1370    where
1371      B.tid in (${tIds.join(',')})
1372    and
1373      not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS))
1374    group by
1375      B.pid, B.tid, B.state
1376    order by
1377      wallDuration desc;`,
1378    { $leftNS: leftNS, $rightNS: rightNS }
1379  );
1380
1381export const queryAnomalyDetailedData = (leftNs: number, rightNs: number): Promise<Array<EnergyAnomalyStruct>> =>
1382  query<EnergyAnomalyStruct>(
1383    'queryAnomalyDetailedData',
1384    `select
1385  S.ts,
1386  D.data as eventName,
1387  D2.data as appKey,
1388  group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as Value
1389  from trace_range AS TR,hisys_event_measure as S
1390  left join data_dict as D on D.id=S.name_id
1391  left join app_name as APP on APP.id=S.key_id
1392  left join data_dict as D2 on D2.id=APP.app_key
1393  where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_ALARM_WAKEUP','ANOMALY_KERNEL_WAKELOCK',
1394  'ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_HIGH_FREQUENCY',
1395  'ANOMALY_CPU_ENERGY','ANOMALY_WAKEUP')
1396  and D2.data in ('APPNAME')
1397  and (S.ts - TR.start_ts) >= $leftNS
1398   and (S.ts - TR.start_ts) <= $rightNS
1399  group by S.serial,APP.app_key,D.data,D2.data
1400  union
1401  select
1402  S.ts,
1403  D.data as eventName,
1404  D2.data as appKey,
1405  group_concat((case when S.type = 1 then S.string_value else S.int_value end), ',') as Value
1406  from trace_range AS TR,hisys_event_measure as S
1407  left join data_dict as D on D.id = S.name_id
1408  left join app_name as APP on APP.id = S.key_id
1409  left join data_dict as D2 on D2.id = APP.app_key
1410  where D.data in ('ANOMALY_SCREEN_OFF_ENERGY', 'ANOMALY_ALARM_WAKEUP', 'ANOMALY_KERNEL_WAKELOCK',
1411  'ANOMALY_RUNNINGLOCK', 'ANORMALY_APP_ENERGY', 'ANOMALY_GNSS_ENERGY', 'ANOMALY_CPU_HIGH_FREQUENCY',
1412  'ANOMALY_CPU_ENERGY', 'ANOMALY_WAKEUP')
1413  and D2.data not in ('pid_', 'tid_', 'type_', 'tz_', 'uid_', 'domain_', 'id_', 'level_', 'info_', 'tag_', 'APPNAME')
1414  and (S.ts - TR.start_ts) >= $leftNS
1415  and (S.ts - TR.start_ts) <= $rightNS
1416  group by S.serial, APP.app_key, D.data, D2.data;`,
1417    { $leftNS: leftNs, $rightNS: rightNs }
1418  );
1419
1420export const queryBySelectExecute = (
1421  executeId: string,
1422  itid: number
1423): Promise<
1424  Array<{
1425    tid: number;
1426    allocation_task_row: number;
1427    execute_task_row: number;
1428    return_task_row: number;
1429    priority: number;
1430  }>
1431> => {
1432  let sqlStr = `SELECT thread.tid,
1433                       task_pool.allocation_task_row,
1434                       task_pool.execute_task_row,
1435                       task_pool.return_task_row,
1436                       task_pool.priority
1437                FROM task_pool
1438                  LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row
1439                  LEFT JOIN thread ON thread.id = callstack.callid
1440                WHERE task_pool.task_id = $executeId AND task_pool.execute_itid = $itid;
1441    `;
1442  return query('queryBySelectExecute', sqlStr, { $executeId: executeId, $itid: itid });
1443};
1444
1445export const queryDistributedRelationData = (traceId?: string): Promise<
1446  Array<{
1447    id: number;
1448    chainId: string;
1449    spanId: string;
1450    parentSpanId: string;
1451    chainFlag: string;
1452  }>
1453> => {
1454  let sqlStr = `SELECT
1455                      c.id,
1456                      c.chainId,
1457                      c.spanId,
1458                      c.parentSpanId,
1459                      c.flag as chainFlag
1460                      FROM
1461                      callstack c
1462                      WHERE
1463                      c.chainId IS NOT NULL
1464                      AND c.spanId IS NOT NULL
1465                      AND c.parentSpanId IS NOT NULL;`;
1466  return query('queryDistributedRelationData', sqlStr, {}, { traceId: traceId });
1467};
1468
1469export const queryDistributedRelationAllData = (
1470  chainId: string,
1471  traceId: string = ''
1472): Promise<
1473  Array<FuncStruct>
1474> => {
1475  let sqlStr = `SELECT
1476                      P.pid,
1477                      A.tid,
1478                      C.name as chainName,
1479                      C.chainId,
1480                      C.spanId,
1481                      C.parentSpanId,
1482                      C.flag as chainFlag,
1483                      C.depth,
1484                      (C.ts - r.start_ts) as ts,
1485                      c.dur,
1486                      $traceId as traceId
1487                  from callstack C, trace_range r
1488                      left join thread A on A.id = C.callid
1489                      left join process AS P on P.id = A.ipid
1490                      where C.chainId = $chainId;`;
1491  if (traceId === '') {
1492    return query('queryDistributedRelationAllData', sqlStr, { $chainId: chainId, $traceId: traceId });
1493  }
1494  return query('queryDistributedRelationAllData', sqlStr, { $chainId: chainId, $traceId: traceId }, { traceId: traceId });
1495};
1496
1497export const sqlPrioCount = (args: unknown): Promise<unknown> =>
1498  query(
1499    'prioCount',
1500    `select
1501      S.priority AS prio,
1502      COUNT(S.priority) as count
1503      from
1504      sched_slice AS S
1505      left join
1506      process P on S.ipid = P.ipid
1507      left join
1508      thread T on S.itid = T.itid
1509      where T.tid = ${//@ts-ignore
1510    args.tid}
1511      and P.pid = ${//@ts-ignore
1512    args.pid}
1513      GROUP BY S.priority;`
1514  );
1515
1516export const queryRunningThread = (
1517  pIds: Array<number>,
1518  tIds: Array<number>,
1519  leftStartNs: number,
1520  rightEndNs: number
1521): Promise<Array<unknown>> =>
1522  query(
1523    'getTabThread',
1524    `
1525            select
1526              P.pid,
1527              T.tid,
1528              S.itid,
1529              S.ts,
1530              P.name AS pName,
1531              ifnull(S.dur,0) + S.ts as endTs
1532            from
1533              sched_slice AS S
1534            left join
1535              process P on S.ipid = P.ipid
1536            left join
1537              thread T on S.itid = T.itid
1538            where
1539              T.tid in (${tIds.join(',')})
1540            and
1541              P.pid in (${pIds.join(',')})
1542            and
1543              not ((S.ts + ifnull(S.dur,0) < $leftStartNs) or (S.ts > $rightEndNs))
1544            order by
1545              S.ts;
1546            `,
1547    { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs }
1548  );
1549
1550export const queryCoreRunningThread = (
1551  pIds: Array<number>,
1552  tIds: Array<number>,
1553  cpu: Array<number>,
1554  leftStartNs: number,
1555  rightEndNs: number
1556): Promise<Array<unknown>> =>
1557  query(
1558    'getTabThread',
1559    `
1560            select
1561              P.pid,
1562              T.tid,
1563              S.cpu,
1564              S.itid,
1565              S.ts,
1566              P.name AS pName,
1567              ifnull(S.dur,0) + S.ts as endTs
1568            from
1569              sched_slice AS S
1570            left join
1571              process P on S.ipid = P.ipid
1572            left join
1573              thread T on S.itid = T.itid
1574            where
1575              T.tid in (${tIds.join(',')})
1576            and
1577              P.pid in (${pIds.join(',')})
1578            and
1579              S.cpu in (${cpu.join(',')})
1580            and
1581              not ((S.ts + ifnull(S.dur,0) < $leftStartNs) or (S.ts > $rightEndNs))
1582            order by
1583              S.ts;
1584            `,
1585    { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs }
1586  );
1587