From db02abcf3141a666db661f500d7b84e08e2b26af Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:07:45 +0800 Subject: [PATCH 01/18] =?UTF-8?q?=E2=80=99Feat:1.hiprofiler=5Fcmd=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E4=B8=AD=E6=97=B6=E9=97=B4=E5=8F=82=E6=95=B0=E8=BF=87?= =?UTF-8?q?=E5=A4=9A,=E7=BB=9F=E4=B8=80=E7=94=B1-t=E6=8E=A7=E5=88=B62.?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E6=A8=A1=E6=9D=BF=E5=BD=95=E5=88=B6trace?= =?UTF-8?q?=E6=97=B6=E6=8F=90=E9=86=92=E7=94=A8=E6=88=B7=E6=89=93=E5=BC=80?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E7=9A=84flag=E2=80=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- ide/src/base-ui/select/LitSelectV.ts | 33 ++++++----- ide/src/trace/SpApplication.ts | 1 + ide/src/trace/component/SpFlags.ts | 5 -- ide/src/trace/component/SpRecordTrace.ts | 57 +++++++++++++++++-- .../component/setting/SpRecordTemplate.ts | 27 +++++---- .../setting/bean/ProfilerServiceTypes.ts | 3 - ide/src/trace/component/trace/base/Utils.ts | 3 - 7 files changed, 86 insertions(+), 43 deletions(-) diff --git a/ide/src/base-ui/select/LitSelectV.ts b/ide/src/base-ui/select/LitSelectV.ts index dc032a07..76a89ce8 100644 --- a/ide/src/base-ui/select/LitSelectV.ts +++ b/ide/src/base-ui/select/LitSelectV.ts @@ -303,6 +303,23 @@ export class LitSelectV extends BaseElement { } initOptions() { + this.selectVOptions!.addEventListener('click', (ev) => { + let items = this.selectVInputEl!.value.split(','); + this.customItem = []; + items.forEach((item: string) => { + if (item.trim() != '') { + let indexItem = this.itemValue.indexOf(item.trim()); + if (indexItem == -1) { + this.customItem.push(item.trim()); + } + } + }); + if (this.customItem.length > 0) { + this.selectVInputEl.value = this.customItem.concat(this.showItems); + } else { + this.selectVInputEl.value = this.showItems; + } + }); this.shadowRoot?.querySelectorAll('lit-select-option').forEach((a) => { a.setAttribute('check', ''); a.addEventListener('onSelected', (e: any) => { @@ -312,6 +329,7 @@ export class LitSelectV extends BaseElement { this.showItems.splice(number, 1); } a.removeAttribute('selected'); + return; } else { let index = this.itemValue.indexOf(a.textContent!); if (index > -1) { @@ -319,21 +337,6 @@ export class LitSelectV extends BaseElement { } a.setAttribute('selected', ''); } - let items = this.selectVInputEl!.value.split(','); - this.customItem = []; - items.forEach((item: string) => { - if (item.trim() != '') { - let indexItem = this.itemValue.indexOf(item.trim()); - if (indexItem == -1) { - this.customItem.push(item.trim()); - } - } - }); - if (this.customItem.length > 0) { - this.selectVInputEl.value = this.customItem.concat(this.showItems); - } else { - this.selectVInputEl.value = this.showItems; - } }); }); } diff --git a/ide/src/trace/SpApplication.ts b/ide/src/trace/SpApplication.ts index 17ab0331..0e522c67 100644 --- a/ide/src/trace/SpApplication.ts +++ b/ide/src/trace/SpApplication.ts @@ -1086,6 +1086,7 @@ export class SpApplication extends BaseElement { spRecordTemplate!.vs = true; spRecordTemplate!.startRefreshDeviceList(); } + spRecordTemplate!.refreshHint(); spRecordTemplate!.synchronizeDeviceList(); showContent(spRecordTemplate!); }, diff --git a/ide/src/trace/component/SpFlags.ts b/ide/src/trace/component/SpFlags.ts index 7e1cb955..41294fa1 100644 --- a/ide/src/trace/component/SpFlags.ts +++ b/ide/src/trace/component/SpFlags.ts @@ -249,11 +249,6 @@ export class FlagsConfig { switchOptions: [{ option: 'Enabled' }, { option: 'Disabled', selected: true }], describeContent: 'Scheduling analysis templates', }, - { - title: 'BinderRunnable', - switchOptions: [{ option: 'Enabled' }, { option: 'Disabled', selected: true }], - describeContent: 'support Cpu State Binder-Runnable', - }, ]; static getAllFlagConfig(): Array { diff --git a/ide/src/trace/component/SpRecordTrace.ts b/ide/src/trace/component/SpRecordTrace.ts index 8c6553a7..ab1f7cf3 100644 --- a/ide/src/trace/component/SpRecordTrace.ts +++ b/ide/src/trace/component/SpRecordTrace.ts @@ -22,6 +22,7 @@ import { SpRecordSetting } from './setting/SpRecordSetting.js'; import { LitMainMenu, MenuGroup, MenuItem } from '../../base-ui/menu/LitMainMenu.js'; import { SpProbesConfig } from './setting/SpProbesConfig.js'; import { SpTraceCommand } from './setting/SpTraceCommand.js'; +import { FlagsConfig } from './SpFlags.js'; import { CpuConfig, @@ -509,22 +510,50 @@ export class SpRecordTrace extends BaseElement { mainMenu.menus = mainMenu.menus; } + refreshHint() { + let flags = FlagsConfig.getAllFlagConfig(); + let showHint = false; + for (let i = 0 ; i < flags.length ; i++) { + let flag = flags[i]; + if (this.selectedTemplate.has(flag.title)) { + let selectedOption = flag.switchOptions.filter((option) => { + return option.selected; + }); + if (selectedOption[0].option === 'Disabled') { + showHint = true; + break; + } + } + } + this.showHint = showHint; + } + get showHint(): boolean { + return this.hasAttribute('show_hint'); + } + private hintTimeOut: number = -1; + set showHint(bool: boolean) { if (bool) { if (this.hasAttribute('show_hint')) { this.removeAttribute('show_hint'); - setTimeout(() => { + this.hintTimeOut = window.setTimeout(() => { this.setAttribute('show_hint', ''); }, 200); } else { this.setAttribute('show_hint', ''); } } else { + if (this.hintTimeOut !== -1) { + window.clearTimeout(this.hintTimeOut); + this.hintTimeOut = -1; + } this.removeAttribute('show_hint'); } } private refreshDeviceTimer: number | undefined; + private hintEl: HTMLSpanElement | undefined; + private selectedTemplate: Map = new Map(); initElements(): void { let parentElement = this.parentNode as HTMLElement; @@ -540,6 +569,8 @@ export class SpRecordTrace extends BaseElement { this.spHisysEvent = new SpHisysEvent(); this.spArkTs = new SpArkTs(); this.spRecordTemplate = new SpRecordTemplate(this); + this.hintEl = this.shadowRoot?.querySelector('#hint') as HTMLSpanElement; + this.addButton = this.shadowRoot?.querySelector('.add'); this.addButton!.addEventListener('click', () => { if (this.vs) { @@ -676,8 +707,25 @@ export class SpRecordTrace extends BaseElement { this.probesConfig!.addEventListener('addProbe', () => { this.showHint = false; }); - this.spRecordTemplate!.addEventListener('addProbe', () => { - this.showHint = false; + this.spRecordTemplate!.addEventListener('addProbe', (ev: CustomEventInit<{ 'elementId': string }>) => { + if (FlagsConfig.DEFAULT_CONFIG.find(flagItem => { return flagItem.title === ev.detail!.elementId;})) { + this.selectedTemplate.set(ev.detail!.elementId, 1); + let flagConfig = FlagsConfig.getFlagsConfig(ev.detail!.elementId); + if (flagConfig![ev.detail!.elementId] !== 'Enabled') { + this.hintEl!.textContent = 'Please open the corresponding Flags tag when parsing'; + if (!this.showHint) { + this.showHint = true; + } + } + } + }); + this.spRecordTemplate!.addEventListener('delProbe', (ev: CustomEventInit<{ 'elementId': string }>) => { + if (FlagsConfig.DEFAULT_CONFIG.find(flagItem => { return flagItem.title === ev.detail!.elementId;})) { + this.selectedTemplate.delete(ev.detail!.elementId); + if (this.selectedTemplate.size === 0) { + this.showHint = false; + } + } }); this.menuGroup = this.shadowRoot?.querySelector('#menu-group') as LitMainMenuGroup; this.appContent = this.shadowRoot?.querySelector('#app-content') as HTMLElement; @@ -975,6 +1023,7 @@ export class SpRecordTrace extends BaseElement { SpRecordTrace.stopRecord = false; let request = this.makeRequest(); if (request.pluginConfigs.length == 0) { + this.hintEl!.textContent = 'It looks like you didn\'t add any probes. Please add at least one'; this.showHint = true; return; } else { @@ -1260,7 +1309,6 @@ export class SpRecordTrace extends BaseElement { sessionMode: ProfilerSessionConfigMode.OFFLINE, resultFile: this.recordSetting!.output, resultMaxSize: 0, - sampleDuration: this.recordSetting!.maxDur * 1000, keepAliveTime: 0, }; let request: CreateSessionRequest = { @@ -1868,7 +1916,6 @@ export class SpRecordTrace extends BaseElement { rawDataPrefix: '', traceDurationMs: 0, debugOn: false, - hitraceTime: this.recordSetting!.maxDur, }; if (this.probesConfig!.traceEvents.length > 0) { tracePluginConfig.hitraceCategories = this.probesConfig!.traceEvents; diff --git a/ide/src/trace/component/setting/SpRecordTemplate.ts b/ide/src/trace/component/setting/SpRecordTemplate.ts index d0cacc4c..775eca58 100644 --- a/ide/src/trace/component/setting/SpRecordTemplate.ts +++ b/ide/src/trace/component/setting/SpRecordTemplate.ts @@ -98,7 +98,10 @@ export class SpRecordTemplate extends BaseElement { element.addEventListener('change', (event: CustomEventInit) => { let detail = event.detail; if (detail!.checked) { - this.dispatchEvent(new CustomEvent('addProbe', {})); + this.dispatchEvent(new CustomEvent('addProbe', + { detail: { 'elementId': element.getAttribute('name') } })); } else { + this.dispatchEvent(new CustomEvent('delProbe', + {detail: {'elementId': element.getAttribute('name')}})); } }); }); @@ -151,7 +154,6 @@ export class SpRecordTemplate extends BaseElement { parseKsyms: true, rawDataPrefix: '', traceDurationMs: 0, - hitraceTime: this.args.recordSetting!.maxDur, }; let htraceProfilerPluginConfig: ProfilerPluginConfig = { pluginName: 'ftrace-plugin', @@ -177,6 +179,7 @@ export class SpRecordTemplate extends BaseElement { }; return htraceProfilerPluginConfig; } + initHtml(): string { return ` + + + +
+ +
+
+
+
+
+
+
+
+
上一页
+
1
+ +
GO
+
下一页
+
+
+ `; + } + + move1px() { + this.tableElement!.scrollTop = this.tableElement!.scrollTop + 1; + } + + dataExportInit() { + let exportDiv = this.shadowRoot!.querySelector('.export'); + exportDiv && + (exportDiv.onclick = () => { + this.exportData(); + }); + } + + exportData() { + if (this.exportLoading || this.ds.length === 0) { + return; + } + this.exportLoading = true; + this.exportProgress!.loading = true; + let date = new Date(); + JSONToCSV.csvExport({ + columns: this.columns as any[], + tables: this.ds, + fileName: date.getTime() + '', + }).then((res) => { + this.exportLoading = false; + this.exportProgress!.loading = false; + }); + } + + formatExportData(dataSource: any[]): any[] { + if (dataSource == undefined || dataSource.length == 0) { + return []; + } + if (this.columns == undefined) { + return []; + } + return dataSource.map((item) => { + let formatData: any = {}; + this.columns!.forEach((column) => { + let dataIndex = column.getAttribute('data-index'); + let columnName = column.getAttribute('title'); + if (columnName == '') { + columnName = dataIndex; + } + if (dataIndex && columnName && item[dataIndex] != undefined) { + formatData[columnName] = item[dataIndex]; + } + }); + if (item.children != undefined) { + formatData.children = this.formatExportData(item.children); + } + return formatData; + }); + } + + recursionExportTableData(columns: any[], dataSource: any[]): string { + let concatStr = '\r\n'; + dataSource.forEach((item, index) => { + concatStr += columns + .map((column) => { + let dataIndex = column.getAttribute('data-index'); + return `"${item[dataIndex] || ''}" `; + }) + .join(','); + if (item.children != undefined) { + concatStr += this.recursionExportTableData(columns, item.children); + } + if (index != dataSource.length - 1) { + concatStr += '\r\n'; + } + }); + return concatStr; + } + + //当 custom element首次被插入文档DOM时,被调用。 + connectedCallback() { + this.colCount = this.tableColumns!.length; + this.dataExportInit(); + this.tableElement?.addEventListener('copy', (e) => { + // @ts-ignore + let clipboardData = e.clipboardData || window.clipboardData; + if (!clipboardData) return; + // @ts-ignore + let text = window.getSelection().toString(); + if (text) { + e.preventDefault(); + let length = this.tableColumns?.length || 1; + let strings = text.split('\n'); + let formatStr = ''; + for (let i = 0; i < strings.length; i++) { + if (i % length != 0) { + formatStr += ' '; + } + formatStr += strings[i]; + if (i != 0 && i % length == length - 1) { + formatStr += '\n'; + } + } + clipboardData.setData('text/plain', formatStr); + } + }); + this.st?.addEventListener('slotchange', () => { + this.theadElement!.innerHTML = ''; + setTimeout(() => { + this.columns = this.st!.assignedElements(); + let rowElement = document.createElement('div'); + rowElement.classList.add('th'); + if (this.selectable) { + let box = document.createElement('div'); + box.style.display = 'flex'; + box.style.justifyContent = 'center'; + box.style.alignItems = 'center'; + box.style.gridArea = '_checkbox_'; + box.classList.add('td'); + box.style.backgroundColor = '#ffffff66'; + let checkbox = document.createElement('lit-checkbox'); + checkbox.classList.add('row-checkbox-all'); + checkbox.onchange = (e: any) => { + this.shadowRoot!.querySelectorAll('.row-checkbox').forEach((a: any) => (a.checked = e.detail.checked)); + if (e.detail.checked) { + this.shadowRoot!.querySelectorAll('.tr').forEach((a) => a.setAttribute('checked', '')); + } else { + this.shadowRoot!.querySelectorAll('.tr').forEach((a) => a.removeAttribute('checked')); + } + }; + box.appendChild(checkbox); + rowElement.appendChild(box); + } + let area: Array = [], + gridTemplateColumns: Array = []; + let resolvingArea = (columns: any, x: any, y: any) => { + columns.forEach((a: any, i: any) => { + if (!area[y]) area[y] = []; + let key = a.getAttribute('key') || a.getAttribute('title'); + if (a.tagName === 'LIT-TABLE-GROUP') { + let len = a.querySelectorAll('lit-table-column').length; + let children = [...a.children].filter((a) => a.tagName !== 'TEMPLATE'); + if (children.length > 0) { + resolvingArea(children, x, y + 1); + } + for (let j = 0; j < len; j++) { + area[y][x] = { x, y, t: key }; + x++; + } + let h = document.createElement('div'); + h.classList.add('td'); + h.style.justifyContent = a.getAttribute('align'); + h.style.borderBottom = '1px solid #f0f0f0'; + h.style.gridArea = key; + h.innerText = a.title; + if (a.hasAttribute('fixed')) { + this.fixed(h, a.getAttribute('fixed'), '#42b983'); + } + rowElement.append(h); + } else if (a.tagName === 'LIT-TABLE-COLUMN') { + area[y][x] = { x, y, t: key }; + x++; + let h: any = document.createElement('div'); + h.classList.add('td'); + if (a.hasAttribute('order')) { + h.sortType = 0; + h.classList.add('td-order'); + h.style.position = 'relative'; + let NS = 'http://www.w3.org/2000/svg'; + let upSvg: any = document.createElementNS(NS, 'svg'); + let upPath: any = document.createElementNS(NS, 'path'); + upSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + upSvg.setAttribute('viewBox', '0 0 1024 1024'); + upSvg.setAttribute('stroke', 'let(--dark-color1,#212121)'); + upSvg.classList.add('up-svg'); + upPath.setAttribute( + 'd', + 'M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z' + ); + upSvg.appendChild(upPath); + let downSvg: any = document.createElementNS(NS, 'svg'); + let downPath: any = document.createElementNS(NS, 'path'); + downSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + downSvg.setAttribute('viewBox', '0 0 1024 1024'); + downSvg.setAttribute('stroke', 'let(--dark-color1,#212121)'); + downSvg.classList.add('down-svg'); + downPath.setAttribute( + 'd', + 'M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z' + ); + downSvg.appendChild(downPath); + if (i == 0) { + h.sortType = 0; // 默认以第一列 降序排序 作为默认排序 + upSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + downSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + } + upSvg.style.display = 'none'; + downSvg.style.display = 'none'; + h.appendChild(upSvg); + h.appendChild(downSvg); + h.onclick = () => { + this?.shadowRoot?.querySelectorAll('.td-order svg').forEach((it: any) => { + it.setAttribute('fill', 'let(--dark-color1,#212121)'); + it.sortType = 0; + it.style.display = 'none'; + }); + if (h.sortType == undefined || h.sortType == null) { + h.sortType = 0; + } else if (h.sortType === 2) { + h.sortType = 0; + } else { + h.sortType += 1; + } + switch (h.sortType) { + case 1: + this.theadElement!.setAttribute('sort', ''); + upSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + downSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + upSvg.style.display = 'block'; + downSvg.style.display = 'none'; + break; + case 2: + upSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + downSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + upSvg.style.display = 'none'; + downSvg.style.display = 'block'; + break; + default: + upSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + downSvg.setAttribute('fill', 'let(--dark-color1,#212121)'); + upSvg.style.display = 'none'; + downSvg.style.display = 'none'; + this.theadElement!.removeAttribute('sort'); + break; + } + this.dispatchEvent( + new CustomEvent('column-click', { + detail: { + sort: h.sortType, + key: key, + }, + composed: true, + }) + ); + }; + } + h.style.justifyContent = a.getAttribute('align'); + gridTemplateColumns.push(a.getAttribute('width') || '1fr'); + h.style.gridArea = key; + let titleLabel = document.createElement('label'); + titleLabel.textContent = a.title; + h.appendChild(titleLabel); + if (a.hasAttribute('fixed')) { + this.fixed(h, a.getAttribute('fixed'), '#42b983'); + } + rowElement.append(h); + } + }); + }; + resolvingArea(this.columns, 0, 0); + area.forEach((rows, j, array) => { + for (let i = 0; i < this.colCount; i++) { + if (!rows[i]) rows[i] = array[j - 1][i]; + } + }); + this.gridTemplateColumns = gridTemplateColumns.join(' '); + if (this.selectable) { + let s = area.map((a) => '"_checkbox_ ' + a.map((aa: any) => aa.t).join(' ') + '"').join(' '); + rowElement.style.gridTemplateColumns = '60px ' + gridTemplateColumns.join(' '); + rowElement.style.gridTemplateRows = `repeat(${area.length},1fr)`; + rowElement.style.gridTemplateAreas = s; + } else { + let s = area.map((a) => '"' + a.map((aa: any) => aa.t).join(' ') + '"').join(' '); + rowElement.style.gridTemplateColumns = gridTemplateColumns.join(' '); + rowElement.style.gridTemplateRows = `repeat(${area.length},1fr)`; + rowElement.style.gridTemplateAreas = s; + } + this.theadElement!.innerHTML = ''; + this.theadElement!.append(rowElement); + this.treeElement!.style.top = this.theadElement?.clientHeight + 'px'; + }); + }); + + this.shadowRoot!.addEventListener('load', function (event) {}); + this.tableElement!.addEventListener('mouseout', (ev) => this.mouseOut()); + } + + // Is called when the custom element is removed from the document DOM. + disconnectedCallback() {} + + // It is called when the custom element is moved to a new document. + adoptedCallback() {} + + // It is called when a custom element adds, deletes, or modifies its own properties. + attributeChangedCallback(name: string, oldValue: string, newValue: string) {} + + fixed(td: HTMLElement, placement: string, bgColor: string) { + td.style.position = 'sticky'; + if (placement === 'left') { + td.style.left = '0px'; + td.style.boxShadow = '3px 0px 5px #33333333'; + } else if (placement === 'right') { + td.style.right = '0px'; + td.style.boxShadow = '-3px 0px 5px #33333333'; + } + } + + getCheckRows() { + // @ts-ignore + return [...this.shadowRoot!.querySelectorAll('div[class=tr][checked]')] + .map((a) => (a as any).data) + .map((a) => { + delete a['children']; + return a; + }); + } + + deleteRowsCondition(fn: any) { + this.shadowRoot!.querySelectorAll('div[class=tr]').forEach((tr) => { + // @ts-ignore + if (fn(tr.data)) { + tr.remove(); + } + }); + } + + meauseElementHeight(rowData: any) { + return 27; + } + + meauseTreeElementHeight(rowData: any, depth: number) { + return 27; + } + + meauseAllRowHeight(list: any[]): TableRowObject[] { + this.tbodyElement!.innerHTML = ''; + this.meauseRowElement = undefined; + let head = this.shadowRoot!.querySelector('.th'); + this.tbodyElement && (this.tbodyElement.style.width = head?.clientWidth + 'px'); + this.currentRecycleList = []; + let headHeight = 0; + let totalHeight = headHeight; + let visibleObjects: TableRowObject[] = []; + let itemHandler = (rowData: any, index: number) => { + let height = this.meauseElementHeight(rowData); + let tableRowObject = new TableRowObject(); + tableRowObject.height = height; + tableRowObject.top = totalHeight; + tableRowObject.data = rowData; + tableRowObject.rowIndex = index; + if ( + Math.max(totalHeight, this.tableElement!.scrollTop + headHeight) <= + Math.min(totalHeight + height, this.tableElement!.scrollTop + this.tableElement!.clientHeight + headHeight) + ) { + let newTableElement = this.createNewTableElement(tableRowObject); + newTableElement.style.transform = `translateY(${totalHeight}px)`; + this.tbodyElement?.append(newTableElement); + this.currentRecycleList.push(newTableElement); + } + totalHeight += height; + visibleObjects.push(tableRowObject); + } + let realIndex = 0; + list.forEach((item, index) => { + if (Array.isArray(item)) { + item.forEach((rowData, childIndex) => { + itemHandler(rowData, realIndex); + realIndex++; + }); + } else { + itemHandler(item, index); + } + }); + this.tbodyElement && (this.tbodyElement.style.height = totalHeight + (this.isScrollXOutSide ? 0 : 0) + 'px'); + this.tableElement && + (this.tableElement.onscroll = (event) => { + let tblScrollTop = this.tableElement!.scrollTop; + let skip = 0; + for (let i = 0; i < visibleObjects.length; i++) { + if ( + visibleObjects[i].top <= tblScrollTop && + visibleObjects[i].top + visibleObjects[i].height >= tblScrollTop + ) { + skip = i; + break; + } + } + let reduce = this.currentRecycleList.map((item) => item.clientHeight).reduce((a, b) => a + b, 0); + if (reduce == 0) { + return; + } + while (reduce <= this.tableElement!.clientHeight) { + let newTableElement = this.createNewTableElement(visibleObjects[skip]); + this.tbodyElement?.append(newTableElement); + this.currentRecycleList.push(newTableElement); + reduce += newTableElement.clientHeight; + } + for (let i = 0; i < this.currentRecycleList.length; i++) { + this.freshCurrentLine(this.currentRecycleList[i], visibleObjects[i + skip]); + } + }); + return visibleObjects; + } + + meauseTreeRowElement(list: any[]): TableRowObject[] { + this.meauseRowElement = undefined; + this.tbodyElement!.innerHTML = ''; + this.treeElement!.innerHTML = ''; + let headHeight = this.theadElement?.clientHeight || 0; + let totalHeight = 0; + let visibleObjects: TableRowObject[] = []; + this.currentRecycleList = []; + this.currentTreeDivList = []; + let resetAllHeight = (list: any[], depth: number, parentNode?: TableRowObject) => { + list.forEach((item) => { + let tableRowObject = new TableRowObject(); + tableRowObject.depth = depth; + tableRowObject.data = item; + tableRowObject.top = totalHeight; + tableRowObject.height = this.meauseTreeElementHeight(tableRowObject, depth); + if (parentNode != undefined) { + parentNode.children.push(tableRowObject); + } + if ( + Math.max(totalHeight, this.tableElement!.scrollTop) <= + Math.min( + totalHeight + tableRowObject.height, + this.tableElement!.scrollTop + this.tableElement!.clientHeight - headHeight + ) + ) { + let newTableElement = this.createNewTreeTableElement(tableRowObject); + newTableElement.style.transform = `translateY(${totalHeight}px)`; + this.tbodyElement?.append(newTableElement); + if (this.treeElement?.lastChild) { + (this.treeElement?.lastChild as HTMLElement).style.height = tableRowObject.height + 'px'; + } + this.currentRecycleList.push(newTableElement); + } + totalHeight += tableRowObject.height; + visibleObjects.push(tableRowObject); + if (item.hasNext) { + if (item.parents != undefined && item.parents.length > 0 && item.status) { + resetAllHeight(item.parents, depth + 1, tableRowObject); + } else if (item.children != undefined && item.children.length > 0 && item.status) { + resetAllHeight(item.children, depth + 1, tableRowObject); + } + } else { + if (item.children != undefined && item.children.length > 0) { + resetAllHeight(item.children, depth + 1, tableRowObject); + } + } + }); + }; + resetAllHeight(list, 0); + this.tbodyElement && (this.tbodyElement.style.height = totalHeight + 'px'); + this.treeElement!.style.height = this.tableElement!.clientHeight - this.theadElement!.clientHeight + 'px'; + this.tableElement && + (this.tableElement.onscroll = (event) => { + let visibleObjects = this.recycleDs.filter((item) => { + return !item.rowHidden; + }); + let top = this.tableElement!.scrollTop; + this.treeElement!.style.transform = `translateY(${top}px)`; + let skip = 0; + for (let index = 0; index < visibleObjects.length; index++) { + if (visibleObjects[index].top <= top && visibleObjects[index].top + visibleObjects[index].height >= top) { + skip = index; + break; + } + } + let reduce = this.currentRecycleList.map((item) => item.clientHeight).reduce((a, b) => a + b, 0); + if (reduce == 0) { + return; + } + while (reduce <= this.tableElement!.clientHeight) { + let newTableElement = this.createNewTreeTableElement(visibleObjects[skip]); + this.tbodyElement?.append(newTableElement); + if (this.treeElement?.lastChild) { + (this.treeElement?.lastChild as HTMLElement).style.height = visibleObjects[skip].height + 'px'; + } + this.currentRecycleList.push(newTableElement); + reduce += newTableElement.clientHeight; + } + for (let i = 0; i < this.currentRecycleList.length; i++) { + this.freshCurrentLine( + this.currentRecycleList[i], + visibleObjects[i + skip], + this.treeElement?.children[i] as HTMLElement + ); + } + }); + return visibleObjects; + } + + createNewTreeTableElement(rowData: TableRowObject): any { + let newTableElement = document.createElement('div'); + newTableElement.classList.add('tr'); + let gridTemplateColumns: Array = []; + let treeTop = 0; + if (this.treeElement!.children?.length > 0) { + let transX = Number((this.treeElement?.lastChild as HTMLElement).style.transform.replace(/[^0-9]/gi, '')); + treeTop += transX + rowData.height; + } + this?.columns?.forEach((column: any, index) => { + let dataIndex = column.getAttribute('data-index') || '1'; + let td: any; + if (index === 0) { + if (column.template) { + td = column.template.render(rowData.data).content.cloneNode(true); + td.template = column.template; + td.title = rowData.data[dataIndex]; + } else { + td = document.createElement('div'); + td.innerHTML = this.formatName(dataIndex, rowData.data[dataIndex]); + td.dataIndex = dataIndex; + td.title = rowData.data[dataIndex]; + } + if (rowData.data.children && rowData.data.children.length > 0 && !rowData.data.hasNext) { + let btn = this.createExpandBtn(rowData); + td.insertBefore(btn, td.firstChild); + } + if (rowData.data.hasNext) { + td.title = rowData.data.objectName; + let btn = this.createBtn(rowData); + td.insertBefore(btn, td.firstChild); + } + td.style.paddingLeft = rowData.depth * 15 + 'px'; + if (!rowData.data.children || rowData.data.children.length === 0) { + td.style.paddingLeft = (15 * rowData.depth + 16) + 'px'; + } + (td as any).data = rowData.data; + td.classList.add('tree-first-body'); + td.style.position = 'absolute'; + td.style.top = '0px'; + td.style.left = '0px'; + td.onmouseenter = () => { + let indexOf = this.currentTreeDivList.indexOf(td); + this.currentRecycleList.forEach((row) => { + row.classList.remove('mouse-in'); + }); + if (indexOf >= 0 && indexOf < this.currentRecycleList.length && td.innerHTML != '') { + this.setMouseIn(true, [newTableElement]); + } + }; + td.onmouseleave = () => { + let indexOf = this.currentTreeDivList.indexOf(td); + if (indexOf >= 0 && indexOf < this.currentRecycleList.length) { + this.setMouseIn(false, [newTableElement]); + } + }; + td.onclick = () => { + let indexOf = this.currentTreeDivList.indexOf(td); + this.dispatchRowClickEvent(rowData, [td, newTableElement]); + }; + this.setHighLight(rowData.data.isSearch, td); + this.treeElement!.style.width = column.getAttribute('width'); + this.treeElement?.append(td); + this.currentTreeDivList.push(td); + } else { + gridTemplateColumns.push(column.getAttribute('width') || '1fr'); + td = document.createElement('div'); + td.classList.add('td'); + td.style.overflow = 'hidden'; + td.style.textOverflow = 'ellipsis'; + td.style.whiteSpace = 'nowrap'; + td.title = rowData.data[dataIndex]; + td.dataIndex = dataIndex; + td.style.justifyContent = column.getAttribute('align') || 'flex-start'; + if (column.template) { + td.appendChild(column.template.render(rowData.data).content.cloneNode(true)); + td.template = column.template; + } else { + td.innerHTML = this.formatName(dataIndex, rowData.data[dataIndex]); + } + newTableElement.append(td); + } + }); + let lastChild = this.treeElement?.lastChild as HTMLElement; + if (lastChild) { + lastChild.style.transform = `translateY(${treeTop}px)`; + } + (newTableElement as any).data = rowData.data; + newTableElement.style.gridTemplateColumns = gridTemplateColumns.join(' '); + newTableElement.style.position = 'absolute'; + newTableElement.style.top = '0px'; + newTableElement.style.left = '0px'; + newTableElement.style.cursor = 'pointer'; + this.setHighLight(rowData.data.isSearch, newTableElement); + newTableElement.onmouseenter = () => { + if ((newTableElement as any).data.isSelected) return; + let indexOf = this.currentRecycleList.indexOf(newTableElement); + this.currentTreeDivList.forEach((row) => { + row.classList.remove('mouse-in'); + }); + if (indexOf >= 0 && indexOf < this.treeElement!.children.length) { + this.setMouseIn(true, [this.treeElement?.children[indexOf] as HTMLElement]); + } + }; + newTableElement.onmouseleave = () => { + if ((newTableElement as any).data.isSelected) return; + let indexOf = this.currentRecycleList.indexOf(newTableElement); + if (indexOf >= 0 && indexOf < this.treeElement!.children.length) { + this.setMouseIn(false, [this.treeElement?.children[indexOf] as HTMLElement]); + } + }; + newTableElement.onclick = (e) => { + let indexOf = this.currentRecycleList.indexOf(newTableElement); + this.dispatchRowClickEvent(rowData, [this.treeElement?.children[indexOf] as HTMLElement, newTableElement]); + }; + return newTableElement; + } + + createBtn(rowData: any) { + let btn: any = document.createElement('lit-icon'); + btn.classList.add('tree-icon'); + if (rowData.data.expanded) { + btn.name = 'plus-square'; + } else { + btn.name = 'minus-square'; + } + btn.addEventListener('click', (e: any) => { + rowData.data.status = false; + const resetNodeHidden = (hidden: boolean, rowData: any) => { + if (hidden) { + rowData.children.forEach((child: any) => { + child.rowHidden = false; + }); + } else { + rowData.children.forEach((child: any) => { + child.rowHidden = true; + resetNodeHidden(hidden, child); + }); + } + }; + + if (rowData.data.expanded) { + rowData.data.status = true; + this.dispatchRowClickEventIcon(rowData, [btn]); + rowData.data.expanded = false; + resetNodeHidden(true, rowData); + } else { + rowData.data.expanded = true; + rowData.data.status = false; + resetNodeHidden(false, rowData); + } + this.reMeauseHeight(); + }); + return btn; + } + + createExpandBtn(rowData: any) { + let btn: any = document.createElement('lit-icon'); + btn.classList.add('tree-icon'); + // @ts-ignore + if (rowData.expanded) { + btn.name = 'minus-square'; + } else { + btn.name = 'plus-square'; + } + btn.onclick = (e: Event) => { + const resetNodeHidden = (hidden: boolean, rowData: any) => { + if (rowData.children.length > 0) { + if (hidden) { + rowData.children.forEach((child: any) => { + child.rowHidden = true; + resetNodeHidden(hidden, child); + }); + } else { + rowData.children.forEach((child: any) => { + child.rowHidden = !rowData.expanded; + if (rowData.expanded) { + resetNodeHidden(hidden, child); + } + }); + } + } + }; + + if (rowData.expanded) { + rowData.expanded = false; + resetNodeHidden(true, rowData); + } else { + rowData.expanded = true; + resetNodeHidden(false, rowData); + } + this.reMeauseHeight(); + e.stopPropagation(); + }; + return btn; + } + + reMeauseHeight() { + if (this.currentRecycleList.length == 0) { + return; + } + let totalHeight = 0; + this.recycleDs.forEach((it) => { + if (!it.rowHidden) { + it.top = totalHeight; + totalHeight += it.height; + } + }); + this.tbodyElement && (this.tbodyElement.style.height = totalHeight + (this.isScrollXOutSide ? 0 : 0) + 'px'); + this.treeElement!.style.height = this.tableElement!.clientHeight - this.theadElement!.clientHeight + 'px'; + let visibleObjects = this.recycleDs.filter((item) => { + return !item.rowHidden; + }); + let top = this.tableElement!.scrollTop; + let skip = 0; + for (let i = 0; i < visibleObjects.length; i++) { + if (visibleObjects[i].top <= top && visibleObjects[i].top + visibleObjects[i].height >= top) { + skip = i; + break; + } + } + let reduce = this.currentRecycleList.map((item) => item.clientHeight).reduce((a, b) => a + b, 0); + if (reduce == 0) { + return; + } + while (reduce <= this.tableElement!.clientHeight) { + let newTableElement; + if (this.hasAttribute('tree')) { + newTableElement = this.createNewTreeTableElement(visibleObjects[skip]); + } else { + newTableElement = this.createNewTableElement(visibleObjects[skip]); + } + this.tbodyElement?.append(newTableElement); + if (this.hasAttribute('tree')) { + if (this.treeElement?.lastChild) { + (this.treeElement?.lastChild as HTMLElement).style.height = visibleObjects[skip].height + 'px'; + } + } + this.currentRecycleList.push(newTableElement); + reduce += newTableElement.clientHeight; + } + for (let i = 0; i < this.currentRecycleList.length; i++) { + if (this.hasAttribute('tree')) { + this.freshCurrentLine( + this.currentRecycleList[i], + visibleObjects[i + skip], + this.treeElement?.children[i] as HTMLElement + ); + } else { + this.freshCurrentLine(this.currentRecycleList[i], visibleObjects[i + skip]); + } + } + } + + createNewTableElement(rowData: any): any { + let newTableElement = document.createElement('div'); + newTableElement.classList.add('tr'); + let gridTemplateColumns: Array = []; + this?.columns?.forEach((column: any) => { + let dataIndex = column.getAttribute('data-index') || '1'; + gridTemplateColumns.push(column.getAttribute('width') || '1fr'); + let td: any; + td = document.createElement('div'); + td.classList.add('td'); + td.style.overflow = 'hidden'; + td.style.textOverflow = 'ellipsis'; + td.style.whiteSpace = 'nowrap'; + td.dataIndex = dataIndex; + td.style.justifyContent = column.getAttribute('align') || 'flex-start'; + td.title = rowData.data[dataIndex]; + if (column.template) { + td.appendChild(column.template.render(rowData.data).content.cloneNode(true)); + td.template = column.template; + } else { + td.innerHTML = this.formatName(dataIndex, rowData.data[dataIndex]); + } + newTableElement.append(td); + }); + newTableElement.onclick = () => { + this.dispatchRowClickEvent(rowData, [newTableElement]); + }; + newTableElement.onmouseenter = () => { + this.dispatchRowHoverEvent(rowData, [newTableElement]); + }; + if (rowData.data.isSelected != undefined) { + this.setSelectedRow(rowData.data.isSelected, [newTableElement]); + } + (newTableElement as any).data = rowData.data; + newTableElement.style.cursor = 'pointer'; + newTableElement.style.gridTemplateColumns = gridTemplateColumns.join(' '); + newTableElement.style.position = 'absolute'; + newTableElement.style.top = '0px'; + newTableElement.style.left = '0px'; + if (this.getItemTextColor) { + newTableElement.style.color = this.getItemTextColor(rowData.data); + } + return newTableElement; + } + + freshCurrentLine(element: HTMLElement, rowObject: TableRowObject, firstElement?: HTMLElement) { + if (!rowObject) { + if (firstElement) { + firstElement.style.display = 'none'; + } + element.style.display = 'none'; + return; + } + let childIndex = -1; + this.setHighLight(rowObject.data.isSearch, element); + element.childNodes.forEach((child) => { + if (child.nodeType != 1) return; + childIndex++; + let idx = firstElement != undefined ? childIndex + 1 : childIndex; + if (firstElement != undefined && childIndex == 0) { + this.setHighLight(rowObject.data.isSearch, firstElement); + (firstElement as any).data = rowObject.data; + if ((this.columns![0] as any).template) { + firstElement.innerHTML = (this.columns![0] as any).template + .render(rowObject.data) + .content.cloneNode(true).innerHTML; + } else { + let dataIndex = this.columns![0].getAttribute('data-index') || '1'; + firstElement.innerHTML = this.formatName(dataIndex, rowObject.data[dataIndex]); + firstElement.title = rowObject.data[dataIndex]; + } + if (rowObject.children && rowObject.children.length > 0 && !rowObject.data.hasNext) { + let btn = this.createExpandBtn(rowObject); + firstElement.insertBefore(btn, firstElement.firstChild); + } + firstElement.style.paddingLeft = 15 * rowObject.depth + 'px'; + if (!rowObject.children || rowObject.children.length === 0) { + firstElement.style.paddingLeft = 15 * rowObject.depth + 16 + 'px'; + } + if (rowObject.data.hasNext) { + let btn = this.createBtn(rowObject); + firstElement.title = rowObject.data.objectName; + firstElement.insertBefore(btn, firstElement.firstChild); + firstElement.style.paddingLeft = 15 * rowObject.depth + 'px'; + } + firstElement.onclick = () => { + this.dispatchRowClickEvent(rowObject, [firstElement, element]); + }; + firstElement.style.transform = `translateY(${rowObject.top - this.tableElement!.scrollTop}px)`; + if (rowObject.data.isSelected != undefined) { + this.setSelectedRow(rowObject.data.isSelected, [firstElement]); + } else { + this.setSelectedRow(false, [firstElement]); + } + } + let dataIndex = this.columns![idx].getAttribute('data-index') || '1'; + if ((this.columns![idx] as any).template) { + (child as HTMLElement).innerHTML = ''; + (child as HTMLElement).appendChild( + (this.columns![idx] as any).template.render(rowObject.data).content.cloneNode(true) + ); + (child as HTMLElement).title = rowObject.data[dataIndex]; + } else { + (child as HTMLElement).innerHTML = this.formatName(dataIndex, rowObject.data[dataIndex]); + (child as HTMLElement).title = rowObject.data[dataIndex]; + } + }); + if (element.style.display == 'none') { + element.style.display = 'grid'; + } + element.style.transform = `translateY(${rowObject.top}px)`; + if (firstElement && firstElement.style.display == 'none') { + firstElement.style.display = 'flex'; + } + element.onclick = (e) => { + if (firstElement != undefined) { + this.dispatchRowClickEvent(rowObject, [firstElement, element]); + } else { + this.dispatchRowClickEvent(rowObject, [element]); + } + }; + element.onmouseenter = () => { + this.dispatchRowHoverEvent(rowObject, [element]); + }; + (element as any).data = rowObject.data; + if (rowObject.data.isSelected != undefined) { + this.setSelectedRow(rowObject.data.isSelected, [element]); + } else { + this.setSelectedRow(false, [element]); + } + if (rowObject.data.isHover != undefined) { + this.setMouseIn(rowObject.data.isHover, [element]); + } else { + this.setMouseIn(false, [element]); + } + if (this.getItemTextColor) { + element.style.color = this.getItemTextColor((element as any).data); + } + } + + setSelectedRow(isSelected: boolean, rows: any[]) { + if (isSelected) { + rows.forEach((row) => { + if (row.classList.contains('mouse-in')) row.classList.remove('mouse-in'); + row.classList.add('mouse-select'); + }); + } else { + rows.forEach((row) => { + row.classList.remove('mouse-select'); + }); + } + } + + setMouseIn(isMouseIn: boolean, rows: any[]) { + if (isMouseIn) { + rows.forEach((row) => { + row.classList.add('mouse-in'); + }); + } else { + rows.forEach((row) => { + row.classList.remove('mouse-in'); + }); + } + } + + scrollToData(data: any) { + if (this.recycleDs.length > 0) { + let filter = this.recycleDs.filter((item) => { + return item.data == data; + }); + if (filter.length > 0) { + this.tableElement!.scrollTop = filter[0].top; + } + this.setCurrentSelection(data); + } + } + + expandList(datasource: any[]) { + let filter = this.recycleDs.filter((item) => { + return datasource.indexOf(item.data) != -1; + }); + if (filter.length > 0) { + filter.forEach((item) => { + item.expanded = true; + item.rowHidden = false; + }); + } + this.reMeauseHeight(); + } + + clearAllSelection(rowObjectData: any) { + this.recycleDs.forEach((item) => { + if (item.data != rowObjectData && item.data.isSelected) { + item.data.isSelected = false; + } + }); + this.setSelectedRow(false, this.currentTreeDivList); + this.setSelectedRow(false, this.currentRecycleList); + } + + clearAllHover(rowObjectData: any) { + this.recycleDs.forEach((item) => { + if (item.data != rowObjectData && item.data.isHover) { + item.data.isHover = false; + } + }); + this.setMouseIn(false, this.currentTreeDivList); + this.setMouseIn(false, this.currentRecycleList); + } + + mouseOut() { + this.recycleDs.forEach((item) => (item.data.isHover = false)); + this.setMouseIn(false, this.currentTreeDivList); + this.setMouseIn(false, this.currentRecycleList); + this.dispatchEvent( + new CustomEvent('row-hover', { + detail: { + data: undefined, + }, + composed: true, + }) + ); + } + + setCurrentSelection(data: any) { + if (data.isSelected != undefined) { + this.currentTreeDivList.forEach((item) => { + if ((item as any).data == data) { + this.setSelectedRow(data.isSelected, [item]); + } + }); + this.currentRecycleList.forEach((item) => { + if ((item as any).data == data) { + this.setSelectedRow(data.isSelected, [item]); + } + }); + } + } + + setCurrentHover(data: any) { + this.setMouseIn(false, this.currentTreeDivList); + this.setMouseIn(false, this.currentRecycleList); + if (data.isHover != undefined) { + this.currentTreeDivList.forEach((item) => { + if ((item as any).data == data) { + this.setMouseIn(data.isHover, [item]); + } + }); + this.currentRecycleList.forEach((item) => { + if ((item as any).data == data) { + this.setMouseIn(data.isHover, [item]); + } + }); + } + } + + dispatchRowClickEventIcon(rowObject: any, elements: any[]) { + this.dispatchEvent( + new CustomEvent('icon-click', { + detail: { + ...rowObject.data, + data: rowObject.data, + callBack: (isSelected: boolean) => { + //是否爲单选 + if (isSelected) { + this.clearAllSelection(rowObject.data); + } + this.setSelectedRow(rowObject.data.isSelected, elements); + }, + }, + composed: true, + }) + ); + } + + dispatchRowClickEvent(rowObject: any, elements: any[]) { + this.dispatchEvent( + new CustomEvent('row-click', { + detail: { + ...rowObject.data, + data: rowObject.data, + callBack: (isSelected: boolean) => { + //是否爲单选 + if (isSelected) { + this.clearAllSelection(rowObject.data); + } + this.setSelectedRow(rowObject.data.isSelected, elements); + }, + }, + composed: true, + }) + ); + } + + dispatchRowHoverEvent(rowObject: any, elements: any[]) { + this.dispatchEvent( + new CustomEvent('row-hover', { + detail: { + data: rowObject.data, + callBack: () => { + this.clearAllHover(rowObject.data); + this.setMouseIn(rowObject.data.isHover, elements); + }, + }, + composed: true, + }) + ); + } + + formatName(key: string, name: any) { + let content = name; + if (this.itemTextHandleMap.has(key)) { + content = this.itemTextHandleMap.get(key)?.(name) || ''; + } + if (content !== undefined && content !== null) { + return content.toString().replace(//g, '>'); + } + return ''; + } + + setHighLight(isSearch: boolean, element: any) { + if (isSearch) { + element.setAttribute('high-light', ''); + } else { + element.removeAttribute('high-light'); + } + } +} + +if (!customElements.get('lit-page-table')) { + customElements.define('lit-page-table', LitPageTable); +} \ No newline at end of file diff --git a/ide/src/trace/bean/StateProcessThread.ts b/ide/src/trace/bean/StateProcessThread.ts index 51fb0065..eb54cfbf 100644 --- a/ide/src/trace/bean/StateProcessThread.ts +++ b/ide/src/trace/bean/StateProcessThread.ts @@ -13,22 +13,17 @@ * limitations under the License. */ -export class StateProcessThread { - id: string = ''; - pid: string = ''; +export class SliceGroup { title: string | null | undefined = ''; - children: Array = []; - process: string = ''; - processId: number = -1; - thread: string = ''; - threadId: number = -1; - state: string = ''; - wallDuration: number = 0; - avgDuration: string = ''; count: number = 0; + state?: string; + tid?: number; + pid?: number; minDuration: number = 0; maxDuration: number = 0; - stdDuration: string = ''; + wallDuration: number = 0; + avgDuration: string = ''; + children?: Array } export class SPTChild { @@ -49,17 +44,3 @@ export class SPTChild { prior: string = ''; note: string = '-'; } - -export class SPT { - start_ts: number = 0; - end_ts: number = 0; - state: string = ''; - dur: number = 0; - cpu: number = 0; - priority: string = '-'; - note: string = '-'; - process: string = ''; - processId: number = 0; - thread: string = ''; - threadId: number = 0; -} diff --git a/ide/src/trace/component/SpFlags.ts b/ide/src/trace/component/SpFlags.ts index 41294fa1..7e1cb955 100644 --- a/ide/src/trace/component/SpFlags.ts +++ b/ide/src/trace/component/SpFlags.ts @@ -249,6 +249,11 @@ export class FlagsConfig { switchOptions: [{ option: 'Enabled' }, { option: 'Disabled', selected: true }], describeContent: 'Scheduling analysis templates', }, + { + title: 'BinderRunnable', + switchOptions: [{ option: 'Enabled' }, { option: 'Disabled', selected: true }], + describeContent: 'support Cpu State Binder-Runnable', + }, ]; static getAllFlagConfig(): Array { diff --git a/ide/src/trace/component/trace/base/TraceSheet.ts b/ide/src/trace/component/trace/base/TraceSheet.ts index 615ff7d2..4a7c1541 100644 --- a/ide/src/trace/component/trace/base/TraceSheet.ts +++ b/ide/src/trace/component/trace/base/TraceSheet.ts @@ -76,6 +76,7 @@ import { TabPaneGpuMemoryVmTrackerComparison } from '../sheet/vmtracker/TabPaneG import { TabPaneVmTrackerShmComparison } from '../sheet/vmtracker/TabPaneVmTrackerShmComparison.js'; import { TabPaneJsCpuStatistics } from '../sheet/ark-ts/TabPaneJsCpuStatistics.js'; import { TabPaneGpuClickSelectComparison } from '../sheet/gpu/TabPaneGpuClickSelectComparison.js'; +import { Utils } from './Utils.js'; @element('trace-sheet') export class TraceSheet extends BaseElement { @@ -703,13 +704,13 @@ export class TraceSheet extends BaseElement { pane.closeable = true; pane.hidden = false; this.litTabs!.activeByKey(pane.key); - pane.tab = e.detail.title; + pane.tab = Utils.transferPTSTitle(e.detail.title); let param = new BoxJumpParam(); param.leftNs = this.selection!.leftNs; param.rightNs = this.selection!.rightNs; param.state = e.detail.state; - param.threadId = e.detail.threadId; - param.processId = e.detail.processId; + param.processId = e.detail.pid; + param.threadId = e.detail.tid; (pane.children.item(0) as TabPaneBoxChild).data = param; } diff --git a/ide/src/trace/component/trace/base/Utils.ts b/ide/src/trace/component/trace/base/Utils.ts index 0eb1ce7c..1e207b26 100644 --- a/ide/src/trace/component/trace/base/Utils.ts +++ b/ide/src/trace/component/trace/base/Utils.ts @@ -43,8 +43,9 @@ export class Utils { Utils.statusMap.set('R', 'Runnable'); Utils.statusMap.set('Running', 'Running'); Utils.statusMap.set('R+', 'Runnable (Preempted)'); + Utils.statusMap.set('R-B', 'Runnable (Binder)'); Utils.statusMap.set('I', 'Task Dead'); - Utils.statusMap.set('T', 'Traced'); + Utils.statusMap.set('T', 'Stopped'); Utils.statusMap.set('t', 'Traced'); Utils.statusMap.set('X', 'Exit (Dead)'); Utils.statusMap.set('Z', 'Exit (Zombie)'); @@ -78,6 +79,22 @@ export class Utils { } } + public static transferPTSTitle(value: any) { + if (value.startsWith('S-')) { + return Utils.getEndState(value.replace('S-','')); + } else if (value.startsWith('P-')) { + let pid = value.replace('P-',''); + let process = Utils.PROCESS_MAP.get(parseInt(pid)) || 'Process'; + return `${process} [${pid}]`; + } else if (value.startsWith('T-')) { + let tid = value.replace('T-',''); + let thread = Utils.THREAD_MAP.get(parseInt(tid)) || 'Thread'; + return `${thread} [${tid}]`; + } else { + return ''; + } + } + public static getStateColor(state: string): string { if (state == 'D-NIO' || state == 'DK-NIO') { return '#795548'; @@ -85,6 +102,8 @@ export class Utils { return '#f19b38'; } else if (state == 'R' || state == 'R+') { return '#a0b84d'; + } else if (state == 'R-B') { + return '#87CEFA'; } else if (state == 'I') { return '#673ab7'; } else if (state == 'Running') { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts index 0c5b3f4f..45ae110f 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts @@ -32,15 +32,8 @@ export class TabPaneBoxChild extends BaseElement { this.boxChildTbl?.shadowRoot?.querySelector('.table')?.style?.height = this.parentElement!.clientHeight - 45 + 'px'; this.boxChildRange!.textContent = 'Selected range: ' + parseFloat(((boxChildValue.rightNs - boxChildValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; - if ( - boxChildValue.state != null && - boxChildValue.state != undefined && - boxChildValue.processId && - boxChildValue.threadId - ) { - this.boxChildTbl!.recycleDataSource = []; - this.getDataByDB(boxChildValue); - } + this.boxChildTbl!.recycleDataSource = []; + this.getDataByDB(boxChildValue); } initElements(): void { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts b/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts index 830417ac..75ca4443 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts @@ -16,16 +16,15 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement.js'; import { LitTable } from '../../../../../base-ui/table/lit-table.js'; import { SelectionParam } from '../../../../bean/BoxSelection.js'; -import { getStatesProcessThreadDataByRange } from '../../../../database/SqlLite.js'; -import { SPT, StateProcessThread } from '../../../../bean/StateProcessThread.js'; import { resizeObserver } from '../SheetUtils.js'; import { procedurePool } from '../../../../database/Procedure.js'; +import { Utils } from '../../base/Utils.js'; +import { SliceGroup } from '../../../../bean/StateProcessThread.js'; @element('tabpane-pts') export class TabPanePTS extends BaseElement { private ptsTbl: LitTable | null | undefined; private ptsRange: HTMLLabelElement | null | undefined; - private loadDataInCache: boolean = true; private selectionParam: SelectionParam | null | undefined; set data(ptsValue: SelectionParam | any) { @@ -35,28 +34,19 @@ export class TabPanePTS extends BaseElement { this.selectionParam = ptsValue; this.ptsRange!.textContent = 'Selected range: ' + parseFloat(((ptsValue.rightNs - ptsValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; - if (this.loadDataInCache) { - this.getDataByPTS(ptsValue.leftNs, ptsValue.rightNs, []); - } else { - this.queryDataByDB(ptsValue); - } + this.getDataByPTS(ptsValue.leftNs, ptsValue.rightNs); } initElements(): void { this.ptsTbl = this.shadowRoot?.querySelector('#pts-tbl'); this.ptsRange = this.shadowRoot?.querySelector('#pts-time-range'); + this.ptsTbl!.itemTextHandleMap.set('title', Utils.transferPTSTitle); } - queryDataByDB(ptsVal: SelectionParam | any) { - getStatesProcessThreadDataByRange(ptsVal.leftNs, ptsVal.rightNs).then((result) => { - this.getDataByPTS(ptsVal.leftNs, ptsVal.rightNs, result); - }); - } - - getDataByPTS(ptsLeftNs: number, ptsRightNs: number, ptsSource: Array) { + getDataByPTS(ptsLeftNs: number, ptsRightNs: number) { this.ptsTbl!.loading = true; procedurePool.submitWithName('logic1', 'spt-getPTS', {leftNs:ptsLeftNs,rightNs: ptsRightNs}, undefined, - (res: Array) => { + (res: Array) => { this.ptsTbl!.loading = false; this.ptsTbl!.recycleDataSource = res; }); diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts index cf039c66..7d4303ff 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts @@ -16,16 +16,16 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement.js'; import { LitTable } from '../../../../../base-ui/table/lit-table.js'; import { SelectionParam } from '../../../../bean/BoxSelection.js'; -import { getStatesProcessThreadDataByRange } from '../../../../database/SqlLite.js'; -import { SPT, StateProcessThread } from '../../../../bean/StateProcessThread.js'; +import { SliceGroup } from '../../../../bean/StateProcessThread.js'; import { resizeObserver } from '../SheetUtils.js'; import { procedurePool } from '../../../../database/Procedure.js'; +import { Utils } from '../../base/Utils.js'; + @element('tabpane-spt') export class TabPaneSPT extends BaseElement { private sptTbl: LitTable | null | undefined; private range: HTMLLabelElement | null | undefined; - private loadDataInCache: boolean = true; private selectionParam: SelectionParam | null | undefined; set data(sptValue: SelectionParam | any) { @@ -37,16 +37,13 @@ export class TabPaneSPT extends BaseElement { this.sptTbl?.shadowRoot?.querySelector('.table').style.height = this.parentElement!.clientHeight - 45 + 'px'; this.range!.textContent = 'Selected range: ' + parseFloat(((sptValue.rightNs - sptValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; - if (this.loadDataInCache) { - this.getDataBySPT(sptValue.leftNs, sptValue.rightNs, []); - } else { - this.queryDataByDB(sptValue); - } + this.getDataBySPT(sptValue.leftNs, sptValue.rightNs); } initElements(): void { this.sptTbl = this.shadowRoot?.querySelector('#spt-tbl'); this.range = this.shadowRoot?.querySelector('#spt-time-range'); + this.sptTbl!.itemTextHandleMap.set('title', Utils.transferPTSTitle); } connectedCallback() { @@ -54,26 +51,20 @@ export class TabPaneSPT extends BaseElement { resizeObserver(this.parentElement!, this.sptTbl!); } - getDataBySPT(leftNs: number, rightNs: number, source: Array) { + getDataBySPT(leftNs: number, rightNs: number) { this.sptTbl!.loading = true; procedurePool.submitWithName( 'logic1', 'spt-getSPT', { leftNs: leftNs, rightNs: rightNs }, undefined, - (res: Array) => { + (res: Array) => { this.sptTbl!.loading = false; this.sptTbl!.recycleDataSource = res; } ); } - queryDataByDB(sptParam: SelectionParam | any) { - getStatesProcessThreadDataByRange(sptParam.leftNs, sptParam.rightNs).then((result) => { - this.getDataBySPT(sptParam.leftNs, sptParam.rightNs, result); - }); - } - initHtml(): string { return `
@@ -1612,8 +1675,10 @@ export class SpRecordTrace extends BaseElement {
Disconnect - Record + Cancel
@@ -1630,13 +1695,10 @@ export class SpRecordTrace extends BaseElement { `; } - private createHilogConfig( - probesConfig: SpProbesConfig, - reportingFrequency: number - ): ProfilerPluginConfig { + private createHilogConfig(probesConfig: SpProbesConfig, reportingFrequency: number): ProfilerPluginConfig { let hilogConfig: HilogConfig = { deviceType: Type.HI3516, - logLevel: levelFromJSON(probesConfig.hilogConfig[0]), + logLevel: levelFromJSON(3), needClear: true, }; let hilogConfigProfilerPluginConfig: ProfilerPluginConfig = { @@ -1644,7 +1706,6 @@ export class SpRecordTrace extends BaseElement { sampleInterval: reportingFrequency * 1000, configData: hilogConfig, }; - SpRecordTrace.appendSerialize(hilogConfigProfilerPluginConfig); return hilogConfigProfilerPluginConfig; } @@ -1655,65 +1716,65 @@ export class SpRecordTrace extends BaseElement { private createHiperConfig(reportingFrequency: number): ProfilerPluginConfig { let perfConfig = this.spRecordPerf!.getPerfConfig(); let recordArgs = ''; - recordArgs = recordArgs + '-f ' + perfConfig?.frequency; + recordArgs = `${ recordArgs }-f ${ perfConfig?.frequency }`; if (perfConfig?.process && !perfConfig?.process.includes('ALL') && perfConfig?.process.length > 0) { let process = perfConfig.process; if (process.indexOf(',') != -1) { let processIdOrName = process.split(','); if (this.isNumber(processIdOrName[0])) { - recordArgs = recordArgs + ' -p ' + perfConfig?.process; + recordArgs = `${ recordArgs } -p ${ perfConfig?.process }`; } else { - recordArgs = recordArgs + ' --app ' + perfConfig?.process; + recordArgs = `${ recordArgs } --app ${ perfConfig?.process }`; } } else { if (this.isNumber(process)) { - recordArgs = recordArgs + ' -p ' + perfConfig?.process; + recordArgs = `${ recordArgs } -p ${ perfConfig?.process }`; } else { - recordArgs = recordArgs + ' --app ' + perfConfig?.process; + recordArgs = `${ recordArgs } --app ${ perfConfig?.process }`; } } } else { - recordArgs = recordArgs + ' -a '; + recordArgs = `${ recordArgs } -a `; } if (perfConfig?.cpu && !perfConfig?.cpu.includes('ALL') && perfConfig?.cpu.length > 0) { - recordArgs = recordArgs + ' -c ' + perfConfig?.cpu; + recordArgs = `${ recordArgs } -c ${ perfConfig?.cpu }`; } if (perfConfig?.cpuPercent != 0) { - recordArgs = recordArgs + ' --cpu-limit ' + perfConfig?.cpuPercent; + recordArgs = `${ recordArgs } --cpu-limit ${ perfConfig?.cpuPercent }`; } if (perfConfig?.eventList && !perfConfig?.eventList.includes('NONE') && perfConfig?.eventList.length > 0) { - recordArgs = recordArgs + ' -e ' + perfConfig?.eventList; + recordArgs = `${ recordArgs } -e ${ perfConfig?.eventList }`; if (perfConfig?.isOffCpu) { - recordArgs = recordArgs + ',sched:sched_waking'; + recordArgs = `${ recordArgs },sched:sched_waking`; } } else { - recordArgs = recordArgs + ' -e hw-cpu-cycles'; + recordArgs = `${ recordArgs } -e hw-cpu-cycles`; if (perfConfig?.isOffCpu) { - recordArgs = recordArgs + ',sched:sched_waking'; + recordArgs = `${ recordArgs },sched:sched_waking`; } } if (perfConfig?.callStack != 'none') { - recordArgs = recordArgs + ' --call-stack ' + perfConfig?.callStack; + recordArgs = `${ recordArgs } --call-stack ${ perfConfig?.callStack }`; } if (perfConfig?.branch != 'none') { - recordArgs = recordArgs + ' -j ' + perfConfig?.branch; + recordArgs = `${ recordArgs } -j ${ perfConfig?.branch }`; } if (perfConfig?.clockType) { - recordArgs = recordArgs + ' --clockid ' + perfConfig?.clockType; + recordArgs = `${ recordArgs } --clockid ${ perfConfig?.clockType }`; } if (perfConfig?.isOffCpu) { - recordArgs = recordArgs + ' --offcpu'; + recordArgs = `${ recordArgs } --offcpu`; } if (perfConfig?.noInherit) { - recordArgs = recordArgs + ' --no-inherit'; + recordArgs = `${ recordArgs } --no-inherit`; } if (perfConfig?.mmap) { - recordArgs = recordArgs + ' -m ' + perfConfig.mmap; + recordArgs = `${ recordArgs } -m ${ perfConfig.mmap }`; } info('record config Args is: ', recordArgs); let hiPerf: HiperfPluginConfig = { @@ -1743,13 +1804,13 @@ export class SpRecordTrace extends BaseElement { recordEvent.push('bio'); } if (recordEvent.length > 0) { - recordArgs += ' --events ' + recordEvent.toString(); + recordArgs += ` --events ${ recordEvent.toString() }`; } recordArgs += ' --duration ' + this.recordSetting?.maxDur; if (systemConfig?.process && !systemConfig?.process.includes('ALL') && systemConfig?.process.length > 0) { - recordArgs = recordArgs + ' --pids ' + systemConfig?.process; + recordArgs = `${ recordArgs } --pids ${ systemConfig?.process }`; } - recordArgs += ' --max_stack_depth ' + systemConfig?.unWindLevel; + recordArgs += ` --max_stack_depth ${ systemConfig?.unWindLevel }`; let systemPluginConfig: FileSystemConfig = { cmdLine: recordArgs, outfileName: '/data/local/tmp/ebpf.data', @@ -1876,7 +1937,6 @@ export class SpRecordTrace extends BaseElement { sampleInterval: reportingFrequency * 1000, configData: memoryconfig, }; - SpRecordTrace.appendSerialize(profilerPluginConfig); return profilerPluginConfig; } @@ -1920,7 +1980,6 @@ export class SpRecordTrace extends BaseElement { sampleInterval: 1000, configData: fpsConfig, }; - SpRecordTrace.appendSerialize(fpsPlugin); return fpsPlugin; } @@ -1933,7 +1992,6 @@ export class SpRecordTrace extends BaseElement { pluginName: 'hisysevent-plugin', configData: hiSystemEventConfig, }; - SpRecordTrace.appendSerialize(hiSystemEventPlugin); return hiSystemEventPlugin; } @@ -1960,15 +2018,9 @@ export class SpRecordTrace extends BaseElement { sampleInterval: 1000, configData: tracePluginConfig, }; - SpRecordTrace.appendSerialize(htraceProfilerPluginConfig); return htraceProfilerPluginConfig; } - static appendSerialize(profilerPluginConfig: ProfilerPluginConfig<{}>): void { - if (Number(SpRecordTrace.selectVersion) >= 4.0) { - } - } - private createSdkConfig(): ProfilerPluginConfig<{}> { let gpuConfig = this.spSdkConfig!.getGpuConfig(); let gpuPluginConfig: ProfilerPluginConfig<{}> = { @@ -1976,19 +2028,20 @@ export class SpRecordTrace extends BaseElement { sampleInterval: this.spSdkConfig!.getSampleInterval(), configData: gpuConfig, }; - SpRecordTrace.appendSerialize(gpuPluginConfig); return gpuPluginConfig; } freshConfigMenuDisable(disable: boolean): void { let querySelectors = this.shadowRoot?.querySelectorAll('lit-main-menu-item'); querySelectors!.forEach((item) => { - if (disable) { - item.style.pointerEvents = 'none'; - } else { - item.style.pointerEvents = 'auto'; + if (item.title !== 'Hdc Shell') { + if (disable) { + item.style.pointerEvents = 'none'; + } else { + item.style.pointerEvents = 'auto'; + } + item.disabled = disable; } - item.disabled = disable; }); } @@ -2004,11 +2057,13 @@ export class SpRecordTrace extends BaseElement { if (disable) { this.disconnectButton!.style.pointerEvents = 'none'; this.recordButtonText!.textContent = this.stop; + this.cancelButtonShow(true); this.addButton!.style.pointerEvents = 'none'; this.deviceSelect!.style.pointerEvents = 'none'; this.deviceVersion!.style.pointerEvents = 'none'; } else { this.recordButtonText!.textContent = this.record; + this.cancelButtonShow(false); this.disconnectButton!.style.pointerEvents = 'auto'; this.addButton!.style.pointerEvents = 'auto'; this.deviceSelect!.style.pointerEvents = 'auto'; @@ -2026,7 +2081,7 @@ export class SpRecordTrace extends BaseElement { synchronizeDeviceList(): void { this.deviceSelect!.innerHTML = ''; - if (SpRecordTrace.serialNumber != '') { + if (SpRecordTrace.serialNumber !== '') { let option = document.createElement('option'); option.className = 'select'; option.selected = true; @@ -2035,7 +2090,7 @@ export class SpRecordTrace extends BaseElement { this.deviceSelect!.appendChild(option); this.recordButton!.hidden = false; this.disconnectButton!.hidden = false; - if (SpRecordTrace.selectVersion && SpRecordTrace.selectVersion != '') { + if (SpRecordTrace.selectVersion && SpRecordTrace.selectVersion !== '') { this.setDeviceVersionSelect(SpRecordTrace.selectVersion); } } diff --git a/ide/src/trace/component/setting/SpRecordTemplate.ts b/ide/src/trace/component/setting/SpRecordTemplate.ts index 775eca58..72893e42 100644 --- a/ide/src/trace/component/setting/SpRecordTemplate.ts +++ b/ide/src/trace/component/setting/SpRecordTemplate.ts @@ -123,7 +123,7 @@ export class SpRecordTemplate extends BaseElement { config.push(this.createHiperfDefaultConfig()); } SpRecordTemplate.FRAME_TIMELINE_EVENTS.forEach((ev) => { - if (traceEventSet.indexOf(ev) == -1) { + if (traceEventSet.indexOf(ev) === -1) { traceEventSet.push(ev); } }); @@ -160,13 +160,12 @@ export class SpRecordTemplate extends BaseElement { sampleInterval: 1000, configData: tracePluginConfig, }; - SpRecordTrace.appendSerialize(htraceProfilerPluginConfig); config.push(htraceProfilerPluginConfig); } return config; } - private createHiperfDefaultConfig() { + private createHiperfDefaultConfig(): ProfilerPluginConfig { let hiPerf: HiperfPluginConfig = { isRoot: false, outfileName: '/data/local/tmp/perf.data', diff --git a/ide/src/trace/component/setting/SpWebHdcShell.ts b/ide/src/trace/component/setting/SpWebHdcShell.ts new file mode 100644 index 00000000..f05a2e73 --- /dev/null +++ b/ide/src/trace/component/setting/SpWebHdcShell.ts @@ -0,0 +1,504 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseElement, element } from '../../../base-ui/BaseElement.js'; +import { HdcDeviceManager } from '../../../hdc/HdcDeviceManager.js'; +import { SpRecordTrace } from '../SpRecordTrace.js'; +import { DataMessage } from '../../../hdc/message/DataMessage.js'; + +@element('sp-web-hdc-shell') +export class SpWebHdcShell extends BaseElement { + private static MAX_DISPLAY_ROWS = 1000; + private static MAX_SAVE_SIZE = 2097152; + private shellDiv: HTMLDivElement | null | undefined; + private shellCanvas: HTMLCanvasElement | null | undefined; + private shellCanvasCtx: CanvasRenderingContext2D | null | undefined; + private resultStr = ''; + private sendCallBack: ((keyboardEvent: KeyboardEvent | string) => void | undefined) | undefined; + private startShellDevice = ''; + private intervalId: number | undefined; + private skipFlag: number[] = [7]; + private clearFlag: number[] = [27, 91, 50, 74, 27, 91, 72]; + private CRLFFlag: number[] = [13, 13, 10]; + private points: Point | undefined; + private forwardFlag: boolean = false; + private cursorIndex: number = 3; + private cursorRow: string = ''; + private textDecoder: TextDecoder = new TextDecoder(); + private isDragging: boolean = false; + private static TOP_OFFSET = 48; + private static TEXT_TOP_OFFSET = 32; + + private static LEFT_OFFSET = 48; + + public initElements(): void { + this.shellCanvas = this.shadowRoot!.querySelector('#shell_cmd'); + this.shellCanvasCtx = this.shellCanvas!.getContext('2d'); + this.shellCanvasCtx!.fillStyle = '#000'; + + this.shellCanvasCtx!.fillRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); + this.shellDiv = this.shadowRoot!.querySelector('.shell_cmd_div'); + this.shellCanvasAddMouseListener(); + this.shellCanvas!.addEventListener('contextmenu', event => { + event.preventDefault(); + event.stopPropagation(); + }); + let listenerThis = this; + this.shellCanvas!.addEventListener('keydown', async (keyboardEvent) => { + keyboardEvent.preventDefault(); + if (keyboardEvent.ctrlKey && keyboardEvent.code === 'KeyC' && listenerThis.points) { + let rowText: string = listenerThis.getSelectedText(); + listenerThis.points = undefined; + await navigator.clipboard.writeText(rowText); + } else { + if (this.sendCallBack) { + this.sendCallBack(keyboardEvent); + } + } + }); + window.subscribe(window.SmartEvent.UI.DeviceConnect, (deviceName: string) => { + if (deviceName) { + this.focus(); + } + }); + window.subscribe(window.SmartEvent.UI.DeviceDisConnect, (deviceName: string) => { + this.clear(); + }); + new ResizeObserver(() => { + this.resizeCanvas(); + this.refreshShellPage(true); + }).observe(this); + } + + resizeCanvas(): void { + if (this.shellCanvas !== null && this.shellCanvas !== undefined) { + this.shellCanvas.width = this.shellCanvas.clientWidth; + this.shellCanvas.height = this.shellCanvas.clientHeight; + } + } + + clear(): void { + this.sendCallBack = undefined; + this.resultStr = ''; + this.cursorRow = ''; + this.shellCanvasCtx!.clearRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); + this.shellCanvasCtx!.fillStyle = '#000'; + this.shellCanvasCtx!.fillRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); + window.clearInterval(this.intervalId); + } + + public focus(): void { + HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((connected) => { + if (connected) { + if (this.sendCallBack && this.startShellDevice === SpRecordTrace.serialNumber) { + this.shellCanvas!.focus(); + } else { + this.clear(); + this.sendCallBack = HdcDeviceManager.startShell((result: DataMessage) => { + if (result.channelClose) { + this.clear(); + return; + } + this.startShellDevice = SpRecordTrace.serialNumber; + this.handleHdcRecvData(result); + }); + this.shellCanvas!.focus(); + } + } else { + this.clear(); + } + }); + } + + arrayBufferCompare(compareA: ArrayBuffer, compareB: number[]): boolean { + const arrayA = new Uint8Array(compareA); + if (arrayA.length === compareB.length) { + for (let i = 0 ; i < arrayA.length ; i++) { + const dd = arrayA[i]; + if (dd !== compareB[i]) { + return false; + } + } + return true; + } + return false; + } + + getSelectedText(): string { + let selectedText = ''; + let textLines = [...this.finalArr]; + textLines.push(this.cursorRow); + let startX = this.points!.startX!; + let startY = this.points!.startY!; + let endX = this.points!.endX!; + let endY = this.points!.endY!; + let depth = Math.ceil((endY - startY) / 16); + let index = 0; + for (let i = 0 ; i < textLines.length ; i++) { + let line = textLines[i]; + let x = SpWebHdcShell.LEFT_OFFSET; + let textStartY = 16 * i + SpWebHdcShell.TEXT_TOP_OFFSET; + let textEndY = 16 * i + SpWebHdcShell.TOP_OFFSET; + let w = this.shellCanvasCtx!.measureText(line).width; + if ((startY < textEndY && endY >= textEndY) || (startY > textStartY && startY < textEndY)) { + index++; + if(index == 1){ + if (startX > x && startX < x + w && depth > 1) { + selectedText += line.substring(Math.floor((startX - x) / 8)) + ((endX < x + w) ? '\n' : ''); + } else { + selectedText += `${ line.substring(Math.floor((startX - x) / 8), endX / 8) }\n`; + } + } else if (index == depth) { + selectedText += `${ line.substring(0, Math.ceil((endX - x) / 8)) }\n`; + } else { + selectedText += `${ line }\n`; + } + } + } + return selectedText.trim(); + } + + forwardSelected(startX: number, startY: number, endX: number, endY: number): void { + //左边界x为SpWebHdcShell.LEFT_OFFSET,右边界为this.shellCanvas!.width + let depth = Math.ceil((endY - startY) / 16); + let startPointX = 0; + let startPointY = 0; + let endPointX = 0; + let endPointY = 0; + if (depth <= 1) { + this.shellCanvasCtx!.fillRect(startX, startY, endX - startX, endY - startY); + startPointX = startX; + startPointY = startY; + endPointX = endX; + endPointY = endY; + } else { + //绘制多行 + for (let index = 1 ; index <= depth ; index++) { + //第一行,绘起始点到canvas右边界矩形 + if (index === 1) { + this.shellCanvasCtx!.fillRect(startX, startY, this.shellCanvas!.width - startX, index * 16); + startPointX = startX; + startPointY = startY; + } else if (index === depth) { + //最后一行,canvas左边界到结束点矩形 + this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY + (index - 1) * 16, endX - SpWebHdcShell.LEFT_OFFSET, endY - (startY + (index - 1) * 16)); + endPointX = endX; + endPointY = endY; + } else { + //中间行,canvas的左边界到右边界的矩形 + this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY + (index - 1) * 16, this.shellCanvas!.width, 16); + } + } + } + this.points = { startX: startPointX, startY: startPointY, endX: endPointX, endY: endPointY }; + } + + reverseSelected(startX: number, startY: number, endX: number, endY: number): void { + //左边界x为SpWebHdcShell.LEFT_OFFSET,右边界为this.shellCanvas!.width + let depth = Math.ceil((startY - endY) / 16); + let startPointX = 0; + let startPointY = 0; + let endPointX = 0; + let endPointY = 0; + if (depth <= 1) { + this.shellCanvasCtx!.fillRect(endX, endY, startX - endX, startY - endY); + startPointX = endX; + startPointY = endY; + endPointX = startX; + endPointY = startY; + } else { + //绘制多行 + for (let index = 1 ; index <= depth ; index++) { + //第一行,绘起始点到canvas左边界矩形 + if (index === 1) { + this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY - 16, startX - SpWebHdcShell.LEFT_OFFSET, 16); + endPointX = startX; + endPointY = startY; + } else if (index === depth) { + //最后一行,canvas右边界到结束点矩形 + this.shellCanvasCtx!.fillRect(endX, endY, this.shellCanvas!.width - endX, startY - (index - 1) * 16 - endY); + startPointX = endX; + startPointY = endY; + } else { + this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY - index * 16, this.shellCanvas!.width, 16); + } + } + } + this.points = { startX: startPointX, startY: startPointY, endX: endPointX, endY: endPointY }; + } + + private singleLineToMultiLine(shellStr: string, foundationWidth: number, maxWidth: number): string[] { + let result = []; + while (shellStr.length * foundationWidth > maxWidth) { + let bfb = maxWidth / (shellStr.length * foundationWidth); + let cutIndex = Math.floor(shellStr.length * bfb); + let ss = shellStr.substring(0, cutIndex); + result.push(ss); + shellStr = shellStr.substring(cutIndex); + } + if (shellStr.length > 0) { + result.push(shellStr); + } + return result; + } + + private finalArr: Array = []; + refreshShellPage(scroller: boolean): void { + try { + if (this.resultStr.length === 0 && this.cursorRow.length === 0) { + return; + } + this.shellCanvasCtx!.clearRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); + this.shellCanvasCtx!.fillStyle = '#000'; + this.shellCanvasCtx!.fillRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); + + let resultStrArr = this.resultStr.split('\n'); + this.finalArr = []; + if (this.shellCanvas!.width > 0) { + let maxWidth = this.shellCanvas!.width; + let foundationWidth = this.shellCanvasCtx!.measureText(' ').width; + for (let i = 0 ; i < resultStrArr.length - 1 ; i++) { + let shellStr = resultStrArr[i]; + let strWidth = this.shellCanvasCtx!.measureText(shellStr).width; + if (strWidth > maxWidth) { + let lines = this.singleLineToMultiLine(shellStr, foundationWidth, maxWidth - SpWebHdcShell.LEFT_OFFSET); + this.finalArr.push(...lines); + } else { + this.finalArr.push(shellStr); + } + } + let shellStrLength = 0; + if (this.finalArr.length > SpWebHdcShell.MAX_DISPLAY_ROWS) { + this.finalArr.splice(0, this.finalArr.length - SpWebHdcShell.MAX_DISPLAY_ROWS + 1); + } + let unitWidth: number = this.shellCanvasCtx!.measureText(' ').width; + this.shellCanvasCtx!.fillStyle = '#fff'; + this.shellCanvasCtx!.font = '16px serif'; + let textY = SpWebHdcShell.TOP_OFFSET; + for (let index: number = 0 ; index < this.finalArr.length ; index++) { + let shellStr: string = this.finalArr[index]; + textY = SpWebHdcShell.TOP_OFFSET + index * 16; + this.shellCanvasCtx!.fillText(shellStr, SpWebHdcShell.LEFT_OFFSET, textY); + } + if (textY !== SpWebHdcShell.TOP_OFFSET) { + textY += 16; + } + shellStrLength = this.cursorIndex * unitWidth + SpWebHdcShell.LEFT_OFFSET; + this.shellCanvasCtx!.fillText(this.cursorRow, SpWebHdcShell.LEFT_OFFSET, textY); + if (scroller) { + if (this.finalArr.length < SpWebHdcShell.MAX_DISPLAY_ROWS && textY > this.shellDiv!.clientHeight) { + this.shellDiv!.scrollTop = textY - this.shellDiv!.clientHeight + (16 + 3); + } + } + if (this.intervalId) { + window.clearInterval(this.intervalId); + } + let needClear = false; + this.intervalId = window.setInterval(() => { + if (needClear) { + needClear = false; + this.shellCanvasCtx!.fillStyle = '#000'; + this.shellCanvasCtx!.fillRect(shellStrLength, textY, 12, 3); + } else { + needClear = true; + this.shellCanvasCtx!.fillStyle = '#fff'; + this.shellCanvasCtx!.fillRect(shellStrLength, textY, 12, 3); + } + }, 500); + } + } catch (e) { + } + } + + public initHtml(): string { + return ` + +
+ +
+ `; + } + + private refreshCurrentRow(): void { + let lastRow: string = this.resultStr; + if (this.resultStr.lastIndexOf('\r\n') !== -1) { + lastRow = this.resultStr.substring(this.resultStr.lastIndexOf('\r\n') + 2); + } + let currentRow: string[] = [...lastRow]; + let result: string[] = []; + this.cursorIndex = 0; + for (let index: number = 0 ; index < currentRow.length ; index++) { + let currentResult: string = currentRow[index]; + if (currentResult === '\b') { + this.cursorIndex--; + } else { + result[this.cursorIndex] = currentResult; + this.cursorIndex++; + } + } + this.cursorRow = result.join(''); + } + + private handleHdcRecvData(result: DataMessage): void { + const resData = result.getData(); + if (resData) { + if (this.arrayBufferCompare(resData, this.skipFlag)) { + return; + } else if (this.arrayBufferCompare(resData, this.clearFlag)) { + this.resultStr = ''; + this.shellDiv!.scrollTop = 0; + this.cursorIndex = 3; + } else if (this.arrayBufferCompare(resData, this.CRLFFlag)) { + if (this.resultStr.lastIndexOf('\r\n') !== -1) { + this.resultStr = this.resultStr.substring(0, this.resultStr.lastIndexOf('\r\n') + 2) + this.cursorRow; + } else { + this.resultStr = this.cursorRow; + } + this.resultStr += result.getDataToString(); + this.cursorIndex = 3; + } else { + if (this.resultStr.length > SpWebHdcShell.MAX_SAVE_SIZE) { + this.resultStr = this.resultStr.substring(this.resultStr.length / 2); + } + const arrayA = new Uint8Array(resData); + if (arrayA[0] === 13 && arrayA[1] !== 10 && arrayA[1] !== 13) { + const index = this.resultStr.lastIndexOf('\n'); + const resultStrLength = this.resultStr.length; + if (index > -1 && resultStrLength > index) { + this.resultStr = + this.resultStr.substring(0, index + 1) + this.textDecoder.decode(arrayA.slice(1, arrayA.length)); + } else { + if (this.resultStr.split('\n').length === 1) { + const index = this.cursorRow.lastIndexOf('\n'); + this.cursorRow = + this.cursorRow.substring(0, index + 1) + this.textDecoder.decode(arrayA.slice(1, arrayA.length)); + this.resultStr = this.cursorRow; + } else { + this.resultStr += result.getDataToString(); + } + } + } else { + this.resultStr += result.getDataToString(); + } + } + this.refreshCurrentRow(); + this.refreshShellPage(true); + } + } + + private shellCanvasAddMouseListener(): void { + let startX: number; + let startY: number; + let endX: number; + let endY: number; + let that = this; + this.shellCanvas!.addEventListener('mousedown', function (event) { + if (that.resultStr.length === 0 && that.cursorRow.length === 0) { + return; + } + that.isDragging = true; + startX = event.offsetX; + startY = event.offsetY; + that.refreshShellPage(false); + }); + this.shellCanvas!.addEventListener('mousemove', function (event) { + if (!that.isDragging) { + return; + } + if (that.resultStr.length === 0 && that.cursorRow.length === 0) { + return; + } + endX = event.offsetX; + endY = event.offsetY; + that.refreshShellPage(false); + that.points = undefined; + that.shellCanvasCtx!.fillStyle = 'rgba(128, 128, 128, 0.5)'; + if (endY > startY) { + that.forwardFlag = true; + that.forwardSelected(startX, startY, endX, endY); + } else { + that.forwardFlag = false; + that.reverseSelected(startX, startY, endX, endY); + } + }); + this.shellCanvasAddMouseUpListener(); + } + + private shellCanvasAddMouseUpListener(): void { + let that = this; + this.shellCanvas!.addEventListener('mouseup', async function (event) { + if (!that.isDragging) { + return; + } + if (that.resultStr.length === 0 && that.cursorRow.length === 0) { + return; + } + that.isDragging = false; + //右键 + if (event.button === 2) { + let text: string = await navigator.clipboard.readText(); + if (text) { + if (that.sendCallBack) { + that.sendCallBack(text); + } + return; + } + } + }); + } +} + +export class Point { + startX: number | undefined; + startY: number | undefined; + endX: number | undefined; + endY: number | undefined; +} diff --git a/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts b/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts index 163e027a..b2516e13 100644 --- a/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts +++ b/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts @@ -27,8 +27,7 @@ export enum ProfilerSessionConfigBufferConfigPolicy { export interface ProfilerSessionConfig { buffers: ProfilerSessionConfigBufferConfig[]; sessionMode: ProfilerSessionConfigMode; - /** for OFFLINE mode, result file path */ - resultFile: string; + /** for OFFLINE mode, result file max size in KB */ resultMaxSize: number; /** if set to non-zero value, session will auto-destroyed after CreateSession in ms */ diff --git a/ide/src/trace/component/trace/base/Extension.ts b/ide/src/trace/component/trace/base/Extension.ts index f91edc78..a4a8996b 100644 --- a/ide/src/trace/component/trace/base/Extension.ts +++ b/ide/src/trace/component/trace/base/Extension.ts @@ -51,7 +51,9 @@ declare global { UploadSOFile: string; // Upload so file Loading: string; // Upload so file Error: string; // load error - CheckALL: string; // Check all child chart + CheckALL: string; // Check all child chart, + DeviceConnect: string; + DeviceDisConnect: string; }; }; @@ -101,6 +103,8 @@ window.SmartEvent = { Loading: 'SmartEvent-UI-Loading', Error: 'SmartEvent-UI-Error', CheckALL: 'SmartEvent-UI-CheckALL', + DeviceConnect: 'SmartEvent-DEVICE_CONNECT', + DeviceDisConnect: 'SmartEvent-DEVICE_DISCONNECT', }, }; Window.prototype.subscribe = (ev, fn) => EventCenter.subscribe(ev, fn); -- Gitee From 6280a7f75040e97b7f559498d9d1f7dcc6ada123 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:16:21 +0800 Subject: [PATCH 05/18] =?UTF-8?q?=E2=80=99Fix:=E8=A7=A3=E5=86=B3hdcshell?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E2=80=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- .../trace/component/setting/SpWebHdcShell.ts | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/ide/src/trace/component/setting/SpWebHdcShell.ts b/ide/src/trace/component/setting/SpWebHdcShell.ts index f05a2e73..2791a0e1 100644 --- a/ide/src/trace/component/setting/SpWebHdcShell.ts +++ b/ide/src/trace/component/setting/SpWebHdcShell.ts @@ -39,7 +39,8 @@ export class SpWebHdcShell extends BaseElement { private textDecoder: TextDecoder = new TextDecoder(); private isDragging: boolean = false; private static TOP_OFFSET = 48; - private static TEXT_TOP_OFFSET = 32; + private static FIRST_ROW_OFFSET = 32; + private static LAST_ROW_OFFSET = 40; private static LEFT_OFFSET = 48; @@ -139,7 +140,6 @@ export class SpWebHdcShell extends BaseElement { getSelectedText(): string { let selectedText = ''; let textLines = [...this.finalArr]; - textLines.push(this.cursorRow); let startX = this.points!.startX!; let startY = this.points!.startY!; let endX = this.points!.endX!; @@ -149,16 +149,18 @@ export class SpWebHdcShell extends BaseElement { for (let i = 0 ; i < textLines.length ; i++) { let line = textLines[i]; let x = SpWebHdcShell.LEFT_OFFSET; - let textStartY = 16 * i + SpWebHdcShell.TEXT_TOP_OFFSET; + let textFirstRowY = 16 * i + SpWebHdcShell.FIRST_ROW_OFFSET; + let textLastRowY = 16 * i + SpWebHdcShell.LAST_ROW_OFFSET; let textEndY = 16 * i + SpWebHdcShell.TOP_OFFSET; let w = this.shellCanvasCtx!.measureText(line).width; - if ((startY < textEndY && endY >= textEndY) || (startY > textStartY && startY < textEndY)) { + if ((startY < textEndY && endY >= textEndY) || (startY > textFirstRowY && startY < textEndY) + || (endY > textLastRowY && endY < textEndY)) { index++; if(index == 1){ - if (startX > x && startX < x + w && depth > 1) { + if (depth > 1) { selectedText += line.substring(Math.floor((startX - x) / 8)) + ((endX < x + w) ? '\n' : ''); } else { - selectedText += `${ line.substring(Math.floor((startX - x) / 8), endX / 8) }\n`; + selectedText += `${ line.substring(Math.floor((startX - x) / 8), Math.ceil((endX - x) / 8)) }\n`; } } else if (index == depth) { selectedText += `${ line.substring(0, Math.ceil((endX - x) / 8)) }\n`; @@ -287,16 +289,13 @@ export class SpWebHdcShell extends BaseElement { this.shellCanvasCtx!.fillStyle = '#fff'; this.shellCanvasCtx!.font = '16px serif'; let textY = SpWebHdcShell.TOP_OFFSET; + this.finalArr.push(this.cursorRow) for (let index: number = 0 ; index < this.finalArr.length ; index++) { let shellStr: string = this.finalArr[index]; textY = SpWebHdcShell.TOP_OFFSET + index * 16; this.shellCanvasCtx!.fillText(shellStr, SpWebHdcShell.LEFT_OFFSET, textY); } - if (textY !== SpWebHdcShell.TOP_OFFSET) { - textY += 16; - } shellStrLength = this.cursorIndex * unitWidth + SpWebHdcShell.LEFT_OFFSET; - this.shellCanvasCtx!.fillText(this.cursorRow, SpWebHdcShell.LEFT_OFFSET, textY); if (scroller) { if (this.finalArr.length < SpWebHdcShell.MAX_DISPLAY_ROWS && textY > this.shellDiv!.clientHeight) { this.shellDiv!.scrollTop = textY - this.shellDiv!.clientHeight + (16 + 3); -- Gitee From ed2da244f0cf64b037900720d4725ae9ffeeb3a3 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:17:18 +0800 Subject: [PATCH 06/18] =?UTF-8?q?=E2=80=99Feat:Hilog=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=8F=8A=E4=BC=98=E5=8C=96=E2=80=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- ide/src/base-ui/icon.svg | 6 + ide/src/command/CmdConstant.ts | 4 +- ide/src/trace/bean/BoxSelection.ts | 7 +- ide/src/trace/component/SpRecordTrace.ts | 112 ++-- ide/src/trace/component/SpSystemTrace.ts | 41 +- .../trace/component/chart/SpChartManager.ts | 7 +- ide/src/trace/component/chart/SpLogChart.ts | 68 +++ .../component/metrics/MetaDataStrategy.ts | 2 +- .../component/metrics/SysCallsStrategy.ts | 12 +- .../trace/component/setting/SpHilogRecord.ts | 86 +++ .../trace/component/setting/SpProbesConfig.ts | 14 +- .../trace/component/setting/SpWebHdcShell.ts | 81 ++- .../setting/bean/ProfilerServiceTypes.ts | 5 +- .../trace/component/trace/base/ColorUtils.ts | 48 +- .../trace/component/trace/base/TraceRow.ts | 1 + .../trace/component/trace/base/TraceSheet.ts | 14 + .../component/trace/base/TraceSheetConfig.ts | 12 + .../trace/component/trace/sheet/SheetUtils.ts | 16 +- .../sheet/ark-ts/TabPaneJsCpuStatistics.ts | 29 +- .../trace/sheet/hilog/TabPaneHiLogSummary.ts | 231 ++++++++ .../trace/sheet/hilog/TabPaneHiLogs.ts | 498 ++++++++++++++++++ .../TabPaneGpuMemoryVmTrackerComparison.ts | 2 +- ide/src/trace/database/SqlLite.ts | 79 ++- .../ProcedureLogicWorkerJsCpuProfiler.ts | 8 +- .../database/ui-worker/ProcedureWorker.ts | 2 + .../ui-worker/ProcedureWorkerCommon.ts | 70 ++- .../database/ui-worker/ProcedureWorkerLog.ts | 148 ++++++ 27 files changed, 1474 insertions(+), 129 deletions(-) create mode 100644 ide/src/trace/component/chart/SpLogChart.ts create mode 100644 ide/src/trace/component/setting/SpHilogRecord.ts create mode 100644 ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogSummary.ts create mode 100644 ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts create mode 100644 ide/src/trace/database/ui-worker/ProcedureWorkerLog.ts diff --git a/ide/src/base-ui/icon.svg b/ide/src/base-ui/icon.svg index 87156b88..569a0aea 100644 --- a/ide/src/base-ui/icon.svg +++ b/ide/src/base-ui/icon.svg @@ -107,6 +107,12 @@ + + + + + + diff --git a/ide/src/command/CmdConstant.ts b/ide/src/command/CmdConstant.ts index acdc84ce..ca7aa347 100644 --- a/ide/src/command/CmdConstant.ts +++ b/ide/src/command/CmdConstant.ts @@ -22,8 +22,8 @@ export class CmdConstant { static CMD_GET_CPU_COUNT = 'hdc_std shell grep -c \'processor\' /proc/cpuinfo'; static CMD_GET_HIPERF_EVENTS = 'hdc_std shell hiperf list'; static CMD_GET_VERSION = 'hdc_std shell param get const.product.software.version'; - static CMD_GET_DEBUG_PROCESS = `hdc_std shell netstat -anp - |grep Panda |grep -v grep | sed \'s/.* \\([0-9]*\\)\\/.*/\\1/\' |xargs -r ps -A -opid,cmd`; + static CMD_GET_DEBUG_PROCESS = + `hdc shell netstat -anp |grep Panda |grep -v grep | sed \'s/.* \\([0-9]*\\)\\/.*/\\1/\' |xargs -r ps -A -opid,cmd`; static CMD_HDC_DEVICES = 'hdc_std list targets'; static CMD_MOUNT_DEVICES = 'hdc_std -t {0} shell mount -o remount,rw /'; static CMD_GET_PROCESS_DEVICES = 'hdc_std -t {0} shell ps -A -opid,cmd'; diff --git a/ide/src/trace/bean/BoxSelection.ts b/ide/src/trace/bean/BoxSelection.ts index 530ff16f..550154bb 100644 --- a/ide/src/trace/bean/BoxSelection.ts +++ b/ide/src/trace/bean/BoxSelection.ts @@ -21,6 +21,7 @@ import { FrameDynamicStruct } from '../database/ui-worker/ProcedureWorkerFrameDy import { FrameAnimationStruct } from '../database/ui-worker/ProcedureWorkerFrameAnimation.js'; import { FrameSpacingStruct } from '../database/ui-worker/ProcedureWorkerFrameSpacing.js'; import { JsCpuProfilerChartFrame } from './JsStruct.js'; +import { LogStruct } from '../database/ui-worker/ProcedureWorkerLog.js'; export class SelectionParam { recordStartNs: number = 0; @@ -82,12 +83,12 @@ export class SelectionParam { frameSpacing: Array = []; jsCpuProfilerData: Array = []; gpu: { - gl:boolean, + gl: boolean, gpuTotal: boolean, gpuWindow: boolean } = { gl: false, - gpuWindow:false, + gpuWindow: false, gpuTotal: false } purgeableTotalAbility: Array = []; @@ -100,6 +101,8 @@ export class SelectionParam { gpuMemoryAbilityData: Array = []; dmaVmTrackerData: Array = []; gpuMemoryTrackerData: Array = []; + hiLogs: Array = []; + hiLogSummary: Array = []; } export class BoxJumpParam { diff --git a/ide/src/trace/component/SpRecordTrace.ts b/ide/src/trace/component/SpRecordTrace.ts index e3de0e99..846743ef 100644 --- a/ide/src/trace/component/SpRecordTrace.ts +++ b/ide/src/trace/component/SpRecordTrace.ts @@ -68,6 +68,7 @@ import { SpRecordTemplate } from './setting/SpRecordTemplate.js'; import { SpStatisticsHttpUtil } from '../../statistics/util/SpStatisticsHttpUtil.js'; import { SpArkTs } from './setting/SpArkTs.js'; import { SpWebHdcShell } from './setting/SpWebHdcShell.js'; +import { SpHilogRecord } from './setting/SpHilogRecord.js'; @element('sp-record-trace') export class SpRecordTrace extends BaseElement { @@ -391,6 +392,8 @@ export class SpRecordTrace extends BaseElement { private spHisysEvent: SpHisysEvent | undefined; private spRecordTemplate: SpRecordTemplate | undefined; private spArkTs: SpArkTs | undefined; + private spHilog: SpHilogRecord | undefined; + private spWebShell: SpWebHdcShell | undefined; private menuGroup: LitMainMenuGroup | undefined | null; private appContent: HTMLElement | undefined | null; @@ -403,7 +406,7 @@ export class SpRecordTrace extends BaseElement { clearFlag = true; } else { let optionArray = new Array(); - for (let i = 0 ; i < this.deviceSelect!.options.length ; i++) { + for (let i = 0; i < this.deviceSelect!.options.length; i++) { optionArray.push(this.deviceSelect!.options[i].value); } devs.forEach((value) => { @@ -430,7 +433,7 @@ export class SpRecordTrace extends BaseElement { this.recordButton!.hidden = true; this.disconnectButton!.hidden = true; } - for (let i = 0 ; i < devs.length ; i++) { + for (let i = 0; i < devs.length; i++) { let dev = devs[i]; let option = document.createElement('option'); option.className = 'select'; @@ -453,7 +456,7 @@ export class SpRecordTrace extends BaseElement { this.recordButton!.hidden = true; this.disconnectButton!.hidden = true; } - for (let len = 0 ; len < devs.length ; len++) { + for (let len = 0; len < devs.length; len++) { let dev = devs[len]; let option = document.createElement('option'); option.className = 'select'; @@ -520,7 +523,7 @@ export class SpRecordTrace extends BaseElement { refreshHint() { let flags = FlagsConfig.getAllFlagConfig(); let showHint = false; - for (let i = 0 ; i < flags.length ; i++) { + for (let i = 0; i < flags.length; i++) { let flag = flags[i]; if (this.selectedTemplate.has(flag.title)) { let selectedOption = flag.switchOptions.filter((option) => { @@ -534,9 +537,11 @@ export class SpRecordTrace extends BaseElement { } this.showHint = showHint; } + get showHint(): boolean { return this.hasAttribute('show_hint'); } + private hintTimeOut: number = -1; set showHint(bool: boolean) { @@ -575,6 +580,7 @@ export class SpRecordTrace extends BaseElement { this.spVmTracker = new SpVmTracker(); this.spHisysEvent = new SpHisysEvent(); this.spArkTs = new SpArkTs(); + this.spHilog = new SpHilogRecord(); this.spRecordTemplate = new SpRecordTemplate(this); this.spWebShell = new SpWebHdcShell(); this.hintEl = this.shadowRoot?.querySelector('#hint') as HTMLSpanElement; @@ -748,7 +754,7 @@ export class SpRecordTrace extends BaseElement { return flagItem.title === ev.detail!.elementId; }) ) { - this.selectedTemplate.delete(ev.detail!.elementId); + this.selectedTemplate['delete'](ev.detail!.elementId); if (this.selectedTemplate.size === 0) { this.showHint = false; } @@ -793,7 +799,7 @@ export class SpRecordTrace extends BaseElement { SpRecordTrace.supportVersions.forEach((supportVersion) => { let option = document.createElement('option'); option.className = 'select'; - option.textContent = `OpenHarmony-${ supportVersion }`; + option.textContent = `OpenHarmony-${supportVersion}`; option.setAttribute('device-version', supportVersion); this.deviceVersion!.append(option); }); @@ -801,7 +807,7 @@ export class SpRecordTrace extends BaseElement { private setDeviceVersionSelect(selected: string): void { let children = this.deviceVersion!.children; - for (let i = 0 ; i < children.length ; i++) { + for (let i = 0; i < children.length; i++) { let child = children[i] as HTMLOptionElement; if (child.getAttribute('device-version') === selected) { child.selected = true; @@ -812,6 +818,7 @@ export class SpRecordTrace extends BaseElement { stopRecordListener(): void { this.recordButtonText!.textContent = this.record; + this.recordButtonDisable(true); this.cancelButtonShow(false); if (this.vs) { let cmd = Cmd.formatString(CmdConstant.CMS_HDC_STOP, [SpRecordTrace.serialNumber]); @@ -823,6 +830,7 @@ export class SpRecordTrace extends BaseElement { try { HdcDeviceManager.shellResultAsString(CmdConstant.CMS_STOP, true).then((result) => {}); } catch (exception) { + this.recordButtonDisable(false); log(exception); } } @@ -877,6 +885,7 @@ export class SpRecordTrace extends BaseElement { this.cancelButton!.style.visibility = 'hidden'; } } + private initMenuItems(): void { let that = this; if (this.record_template) { @@ -951,7 +960,9 @@ export class SpRecordTrace extends BaseElement { clickHandler: function (ev: InputEvent) { that.appContent!.innerHTML = ''; that.appContent!.append(that.spWebShell!); - that.spWebShell!.focus(); + setTimeout(() => { + that.spWebShell!.hdcShellFocus(); + }, 100); that.nowChildItem = that.spWebShell!; that.freshMenuItemsStatus('Hdc Shell'); }, @@ -1032,6 +1043,16 @@ export class SpRecordTrace extends BaseElement { that.freshMenuItemsStatus('Ark Ts'); }, }, + { + title: 'Hilog', + icon: 'realIntentionBulb', + fileChoose: false, + clickHandler: function (ev: InputEvent): void { + that.appContent!.innerHTML = ''; + that.appContent!.append(that.spHilog!); + that.freshMenuItemsStatus('Hilog'); + }, + }, { title: 'SDK Config', icon: 'file-config', @@ -1063,6 +1084,7 @@ export class SpRecordTrace extends BaseElement { this.menuGroup!.appendChild(th); }); } + // @ts-ignore usbConnectionListener(event: USBConnectionEvent): void { if (event.isTrusted) { @@ -1089,7 +1111,7 @@ export class SpRecordTrace extends BaseElement { usbDisConnectionListener(event: USBConnectionEvent): void { // @ts-ignore let disConnectDevice: USBDevice = event.device; - for (let index = 0 ; index < this.deviceSelect!.children.length ; index++) { + for (let index = 0; index < this.deviceSelect!.children.length; index++) { let option = this.deviceSelect!.children[index] as HTMLOptionElement; if (option.value == disConnectDevice.serialNumber) { let optValue = option.value; @@ -1117,7 +1139,7 @@ export class SpRecordTrace extends BaseElement { SpRecordTrace.cancelRecord = false; let request = this.makeRequest(); if (request.pluginConfigs.length == 0) { - this.hintEl!.textContent = 'It looks like you didn\'t add any probes. Please add at least one'; + this.hintEl!.textContent = "It looks like you didn't add any probes. Please add at least one"; this.showHint = true; return; } else { @@ -1164,7 +1186,7 @@ export class SpRecordTrace extends BaseElement { this.sp!.search = true; this.progressEL!.loading = true; this.litSearch!.clear(); - this.litSearch!.setPercent(`tracing ${ this.recordSetting!.maxDur * 1000 }ms`, -1); + this.litSearch!.setPercent(`tracing ${this.recordSetting!.maxDur * 1000}ms`, -1); this.initRecordUIState(); this.recordButtonText!.textContent = this.stop; this.cancelButtonShow(true); @@ -1206,7 +1228,7 @@ export class SpRecordTrace extends BaseElement { }); } else { HdcDeviceManager.connect(selectedOption.value).then((result) => { - log(`result is ${ result }`); + log(`result is ${result}`); if (result) { this.appContent!.innerHTML = ''; this.appContent!.append(this.traceCommand!); @@ -1223,7 +1245,7 @@ export class SpRecordTrace extends BaseElement { this.sp!.search = true; this.progressEL!.loading = true; this.litSearch!.clear(); - this.litSearch!.setPercent(`tracing ${ this.recordSetting!.maxDur * 1000 }ms`, -1); + this.litSearch!.setPercent(`tracing ${this.recordSetting!.maxDur * 1000}ms`, -1); this.buttonDisable(true); this.freshMenuDisable(true); this.freshConfigMenuDisable(true); @@ -1259,6 +1281,7 @@ export class SpRecordTrace extends BaseElement { this.freshConfigMenuDisable(false); this.freshMenuDisable(false); this.buttonDisable(false); + this.recordButtonDisable(false); fileHandler({ detail: file, }); @@ -1269,6 +1292,7 @@ export class SpRecordTrace extends BaseElement { }); } else { this.recordButtonText!.textContent = this.record; + this.recordButtonDisable(false); this.litSearch!.setPercent('htrace file is too big', -2); this.buttonDisable(false); this.freshConfigMenuDisable(false); @@ -1276,17 +1300,20 @@ export class SpRecordTrace extends BaseElement { } }); } else if (re == 2) { + this.recordButtonDisable(false); this.litSearch!.setPercent('stop tracing htrace ', -1); this.freshConfigMenuDisable(false); this.freshMenuDisable(false); this.buttonDisable(false); } else if (re == -1) { + this.recordButtonDisable(false); this.litSearch!.setPercent('The device is abnormal', -2); this.progressEL!.loading = false; this.freshConfigMenuDisable(false); this.freshMenuDisable(false); this.buttonDisable(false); } else { + this.recordButtonDisable(false); this.litSearch!.setPercent('tracing htrace failed, please check your config ', -2); this.freshConfigMenuDisable(false); this.freshMenuDisable(false); @@ -1375,6 +1402,7 @@ export class SpRecordTrace extends BaseElement { ) ); } + if (this.spAllocations!.appProcess != '') { request.pluginConfigs.push(this.createNativePluginConfig(reportingFrequency)); } @@ -1393,6 +1421,9 @@ export class SpRecordTrace extends BaseElement { if (this.spArkTs!.process != '' && this.spArkTs!.startSamp) { request.pluginConfigs.push(this.createArkTsConfig()); } + if (this.spHilog!.recordHilog) { + request.pluginConfigs.push(this.createHilogConfig(reportingFrequency)); + } } return request; }; @@ -1695,10 +1726,8 @@ export class SpRecordTrace extends BaseElement { `; } - private createHilogConfig(probesConfig: SpProbesConfig, reportingFrequency: number): ProfilerPluginConfig { + private createHilogConfig(reportingFrequency: number): ProfilerPluginConfig { let hilogConfig: HilogConfig = { - deviceType: Type.HI3516, - logLevel: levelFromJSON(3), needClear: true, }; let hilogConfigProfilerPluginConfig: ProfilerPluginConfig = { @@ -1716,65 +1745,65 @@ export class SpRecordTrace extends BaseElement { private createHiperConfig(reportingFrequency: number): ProfilerPluginConfig { let perfConfig = this.spRecordPerf!.getPerfConfig(); let recordArgs = ''; - recordArgs = `${ recordArgs }-f ${ perfConfig?.frequency }`; + recordArgs = `${recordArgs}-f ${perfConfig?.frequency}`; if (perfConfig?.process && !perfConfig?.process.includes('ALL') && perfConfig?.process.length > 0) { let process = perfConfig.process; if (process.indexOf(',') != -1) { let processIdOrName = process.split(','); if (this.isNumber(processIdOrName[0])) { - recordArgs = `${ recordArgs } -p ${ perfConfig?.process }`; + recordArgs = `${recordArgs} -p ${perfConfig?.process}`; } else { - recordArgs = `${ recordArgs } --app ${ perfConfig?.process }`; + recordArgs = `${recordArgs} --app ${perfConfig?.process}`; } } else { if (this.isNumber(process)) { - recordArgs = `${ recordArgs } -p ${ perfConfig?.process }`; + recordArgs = `${recordArgs} -p ${perfConfig?.process}`; } else { - recordArgs = `${ recordArgs } --app ${ perfConfig?.process }`; + recordArgs = `${recordArgs} --app ${perfConfig?.process}`; } } } else { - recordArgs = `${ recordArgs } -a `; + recordArgs = `${recordArgs} -a `; } if (perfConfig?.cpu && !perfConfig?.cpu.includes('ALL') && perfConfig?.cpu.length > 0) { - recordArgs = `${ recordArgs } -c ${ perfConfig?.cpu }`; + recordArgs = `${recordArgs} -c ${perfConfig?.cpu}`; } if (perfConfig?.cpuPercent != 0) { - recordArgs = `${ recordArgs } --cpu-limit ${ perfConfig?.cpuPercent }`; + recordArgs = `${recordArgs} --cpu-limit ${perfConfig?.cpuPercent}`; } if (perfConfig?.eventList && !perfConfig?.eventList.includes('NONE') && perfConfig?.eventList.length > 0) { - recordArgs = `${ recordArgs } -e ${ perfConfig?.eventList }`; + recordArgs = `${recordArgs} -e ${perfConfig?.eventList}`; if (perfConfig?.isOffCpu) { - recordArgs = `${ recordArgs },sched:sched_waking`; + recordArgs = `${recordArgs},sched:sched_waking`; } } else { - recordArgs = `${ recordArgs } -e hw-cpu-cycles`; + recordArgs = `${recordArgs} -e hw-cpu-cycles`; if (perfConfig?.isOffCpu) { - recordArgs = `${ recordArgs },sched:sched_waking`; + recordArgs = `${recordArgs},sched:sched_waking`; } } if (perfConfig?.callStack != 'none') { - recordArgs = `${ recordArgs } --call-stack ${ perfConfig?.callStack }`; + recordArgs = `${recordArgs} --call-stack ${perfConfig?.callStack}`; } if (perfConfig?.branch != 'none') { - recordArgs = `${ recordArgs } -j ${ perfConfig?.branch }`; + recordArgs = `${recordArgs} -j ${perfConfig?.branch}`; } if (perfConfig?.clockType) { - recordArgs = `${ recordArgs } --clockid ${ perfConfig?.clockType }`; + recordArgs = `${recordArgs} --clockid ${perfConfig?.clockType}`; } if (perfConfig?.isOffCpu) { - recordArgs = `${ recordArgs } --offcpu`; + recordArgs = `${recordArgs} --offcpu`; } if (perfConfig?.noInherit) { - recordArgs = `${ recordArgs } --no-inherit`; + recordArgs = `${recordArgs} --no-inherit`; } if (perfConfig?.mmap) { - recordArgs = `${ recordArgs } -m ${ perfConfig.mmap }`; + recordArgs = `${recordArgs} -m ${perfConfig.mmap}`; } info('record config Args is: ', recordArgs); let hiPerf: HiperfPluginConfig = { @@ -1804,13 +1833,13 @@ export class SpRecordTrace extends BaseElement { recordEvent.push('bio'); } if (recordEvent.length > 0) { - recordArgs += ` --events ${ recordEvent.toString() }`; + recordArgs += ` --events ${recordEvent.toString()}`; } - recordArgs += ' --duration ' + this.recordSetting?.maxDur; + recordArgs += ` --duration ${this.recordSetting?.maxDur}`; if (systemConfig?.process && !systemConfig?.process.includes('ALL') && systemConfig?.process.length > 0) { - recordArgs = `${ recordArgs } --pids ${ systemConfig?.process }`; + recordArgs = `${recordArgs} --pids ${systemConfig?.process}`; } - recordArgs += ` --max_stack_depth ${ systemConfig?.unWindLevel }`; + recordArgs += ` --max_stack_depth ${systemConfig?.unWindLevel}`; let systemPluginConfig: FileSystemConfig = { cmdLine: recordArgs, outfileName: '/data/local/tmp/ebpf.data', @@ -2053,6 +2082,13 @@ export class SpRecordTrace extends BaseElement { } } + recordButtonDisable(disable: boolean): void { + if (disable) { + this.recordButton!.style.pointerEvents = 'none'; + } else { + this.recordButton!.style.pointerEvents = 'auto'; + } + } buttonDisable(disable: boolean): void { if (disable) { this.disconnectButton!.style.pointerEvents = 'none'; diff --git a/ide/src/trace/component/SpSystemTrace.ts b/ide/src/trace/component/SpSystemTrace.ts index be2b0eb1..08eb37c4 100644 --- a/ide/src/trace/component/SpSystemTrace.ts +++ b/ide/src/trace/component/SpSystemTrace.ts @@ -41,6 +41,7 @@ import { drawFlagLineSegment, drawLines, drawLinkLines, + drawLogsLineSegment, drawWakeUp, drawWakeUpList, isFrameContainPoint, @@ -94,6 +95,7 @@ import { JsCpuProfilerChartFrame } from '../bean/JsStruct.js'; import { FileInfo } from '../../js-heap/model/UiStruct.js'; import { SnapshotStruct } from '../database/ui-worker/ProcedureWorkerSnapshot.js'; import { setSelectState, intersectData } from './Utils.js'; +import { LogStruct } from '../database/ui-worker/ProcedureWorkerLog.js'; function dpr() { return window.devicePixelRatio || 1; @@ -1108,6 +1110,14 @@ export class SpSystemTrace extends BaseElement { selection.purgeableTotalVM.push(...intersectData(it)); } else if (it.rowType == TraceRow.ROW_TYPE_PURGEABLE_PIN_VM) { selection.purgeablePinVM.push(...intersectData(it)); + } else if (it.rowType === TraceRow.ROW_TYPE_LOGS) { + let systemLogs: LogStruct[] = it.dataList.filter( + (logStruct: LogStruct) => + (logStruct.startTs ?? 0) >= TraceRow.rangeSelectObject!.startNS! && + (logStruct.startTs ?? 0) <= TraceRow.rangeSelectObject!.endNS! + ); + selection.hiLogs.push(...systemLogs); + selection.hiLogSummary.push(...systemLogs); } if (this.rangeTraceRow!.length !== rows.length) { let event = this.createPointEvent(it); @@ -1593,6 +1603,31 @@ export class SpSystemTrace extends BaseElement { } as Rect ); } + //draw system logs line segment for canvas + drawLogsLineSegment( + this.canvasPanelCtx, + this.traceSheetEL?.systemLogFlag, + { + x: 0, + y: 0, + width: this.timerShaftEL?.canvas?.clientWidth, + height: this.canvasPanel?.clientHeight, + }, + this.timerShaftEL! + ); + //draw system logs line segment for favorite canvas + drawLogsLineSegment( + this.canvasFavoritePanelCtx, + this.traceSheetEL?.systemLogFlag, + { + x: 0, + y: 0, + width: this.timerShaftEL?.canvas?.clientWidth, + height: this.canvasFavoritePanel?.clientHeight, + }, + this.timerShaftEL! + ); + // Draw the connection curve if (this.linkNodes) { drawLinkLines(this.canvasPanelCtx!, this.linkNodes, this.timerShaftEL!, false); @@ -2220,6 +2255,7 @@ export class SpSystemTrace extends BaseElement { TraceRow.ROW_TYPE_VM_TRACKER_SMAPS, () => SnapshotStruct.hoverSnapshotStruct !== null && SnapshotStruct.hoverSnapshotStruct !== undefined, ], + [TraceRow.ROW_TYPE_LOGS, () => LogStruct.hoverLogStruct !== null && LogStruct.hoverLogStruct !== undefined], ]); onClickHandler(clickRowType: string, row?: TraceRow) { @@ -2370,7 +2406,7 @@ export class SpSystemTrace extends BaseElement { this.observerScrollHeightEnable = true; let jankRowParent: any; if (d.rowId === 'actual frameTime') { - jankRowParent = this.shadowRoot?.querySelector>(`trace-row[row-id='frameTime']`); + jankRowParent = this.shadowRoot?.querySelector>("trace-row[row-id='frameTime']"); } else { jankRowParent = this.shadowRoot?.querySelector>(`trace-row[row-id='${d.pid}']`); } @@ -4045,6 +4081,9 @@ export class SpSystemTrace extends BaseElement { }, 360); }); } + if (this.loadTraceCompleted) { + this.traceSheetEL?.displaySystemLogsData(); + } this.intersectionObserver?.observe(it); }); return { status: true, msg: 'success' }; diff --git a/ide/src/trace/component/chart/SpChartManager.ts b/ide/src/trace/component/chart/SpChartManager.ts index b1eed8e3..cf5b22a5 100644 --- a/ide/src/trace/component/chart/SpChartManager.ts +++ b/ide/src/trace/component/chart/SpChartManager.ts @@ -19,7 +19,8 @@ import { SpCpuChart } from './SpCpuChart.js'; import { SpFreqChart } from './SpFreqChart.js'; import { SpFpsChart } from './SpFpsChart.js'; import { - getCpuUtilizationRate, queryAppStartupProcessIds, + getCpuUtilizationRate, + queryAppStartupProcessIds, queryDataDICT, queryMemoryConfig, queryTaskPoolCallStack, @@ -46,6 +47,7 @@ import { Utils } from '../trace/base/Utils.js'; import { SpArkTsChart } from './SpArkTsChart.js'; import { MemoryConfig } from '../../bean/MemoryConfig.js'; import { FlagsConfig } from '../SpFlags.js'; +import { SpLogChart } from './SpLogChart.js'; export class SpChartManager { static APP_STARTUP_PID_ARR: Array = []; @@ -67,6 +69,7 @@ export class SpChartManager { private irqChart: SpIrqChart; frameTimeChart: SpFrameTimeChart; public arkTsChart: SpArkTsChart; + private logChart: SpLogChart; constructor(trace: SpSystemTrace) { this.trace = trace; @@ -86,6 +89,7 @@ export class SpChartManager { this.irqChart = new SpIrqChart(trace); this.frameTimeChart = new SpFrameTimeChart(trace); this.arkTsChart = new SpArkTsChart(trace); + this.logChart = new SpLogChart(trace); } async init(progress: Function) { @@ -123,6 +127,7 @@ export class SpChartManager { info('Cpu Rate Data initialized'); progress('cpu freq', 80); await this.freq.init(); + await this.logChart.init(); progress('Clock init', 82); await this.clockChart.init(); progress('Irq init', 84); diff --git a/ide/src/trace/component/chart/SpLogChart.ts b/ide/src/trace/component/chart/SpLogChart.ts new file mode 100644 index 00000000..89a94f4a --- /dev/null +++ b/ide/src/trace/component/chart/SpLogChart.ts @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { SpSystemTrace } from '../SpSystemTrace.js'; +import { TraceRow } from '../trace/base/TraceRow.js'; +import { queryLogData } from '../../database/SqlLite.js'; +import { renders } from '../../database/ui-worker/ProcedureWorker.js'; +import { LogRender, LogStruct } from '../../database/ui-worker/ProcedureWorkerLog.js'; + +export class SpLogChart { + private trace: SpSystemTrace; + + constructor(trace: SpSystemTrace) { + this.trace = trace; + } + + async init() { + let dataArray = await queryLogData(); + if (dataArray.length === 0) { + return; + } + let folder = await this.initFolder(dataArray); + this.trace.rowsEL?.appendChild(folder); + } + + async initFolder(dataArray: LogStruct[]): Promise> { + let logsRow = TraceRow.skeleton(); + logsRow.rowId = 'logs'; + logsRow.index = 0; + logsRow.rowType = TraceRow.ROW_TYPE_LOGS; + logsRow.rowParentId = ''; + logsRow.style.height = '42px'; + logsRow.folder = false; + logsRow.name = 'Logs'; + logsRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; + logsRow.selectChangeHandler = this.trace.selectChangeHandler; + logsRow.supplier = () => + new Promise((resolve): void => { + resolve(dataArray); + }); + logsRow.onThreadHandler = (useCache) => { + let context = logsRow.collect ? this.trace.canvasFavoritePanelCtx! : this.trace.canvasPanelCtx!; + logsRow.canvasSave(context); + (renders.logs as LogRender).renderMainThread( + { + context: context, + useCache: useCache, + type: 'logs', + }, + logsRow + ); + logsRow.canvasRestore(context); + }; + return logsRow; + } +} diff --git a/ide/src/trace/component/metrics/MetaDataStrategy.ts b/ide/src/trace/component/metrics/MetaDataStrategy.ts index 3f2fb177..f29c035c 100644 --- a/ide/src/trace/component/metrics/MetaDataStrategy.ts +++ b/ide/src/trace/component/metrics/MetaDataStrategy.ts @@ -39,7 +39,7 @@ export const initMetaDataStrategy = (metricData: Array<{ let name = metricData[sqlIndex].name; let value = metricData[sqlIndex].valueText; if (!value.match('^-?\\d+$')) { - value = `"${ value.replace('\r|\n', '') }"`; + value = `${ value.replace('\r|\n', '') }`; } let traceMetaData = { name: name, diff --git a/ide/src/trace/component/metrics/SysCallsStrategy.ts b/ide/src/trace/component/metrics/SysCallsStrategy.ts index 4483113d..5b2a0564 100644 --- a/ide/src/trace/component/metrics/SysCallsStrategy.ts +++ b/ide/src/trace/component/metrics/SysCallsStrategy.ts @@ -17,8 +17,8 @@ import { info } from '../../../log/Log.js'; export const initSysCallsStrategy = (metricData: Array<{ frequency: string; - minDur: string; - maxDur: string; + minDur: number; + maxDur: number; avgDur: number; funName: string; }>): FunctionListItem => { @@ -28,7 +28,7 @@ export const initSysCallsStrategy = (metricData: Array<{ let functionNames = metricData[sqlIndex].funName; let durMaxes = metricData[sqlIndex].maxDur; let durMines = metricData[sqlIndex].minDur; - let durAvgs = Math.floor(metricData[sqlIndex].avgDur).toString(); + let durAvgs = Math.floor(metricData[sqlIndex].avgDur); let functionItem: FunctionItem = { functionName: functionNames, durMax: durMaxes, @@ -48,7 +48,7 @@ export interface FunctionListItem { export interface FunctionItem { functionName: string; - durMax: string; - durMin: string; - durAvg: string; + durMax: number; + durMin: number; + durAvg: number; } diff --git a/ide/src/trace/component/setting/SpHilogRecord.ts b/ide/src/trace/component/setting/SpHilogRecord.ts new file mode 100644 index 00000000..c18badb3 --- /dev/null +++ b/ide/src/trace/component/setting/SpHilogRecord.ts @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {BaseElement, element} from '../../../base-ui/BaseElement.js'; +import LitSwitch from '../../../base-ui/switch/lit-switch.js'; +import '../../../base-ui/select/LitAllocationSelect.js'; + +import '../../../base-ui/switch/lit-switch.js'; + +@element('sp-hi-log') +export class SpHilogRecord extends BaseElement { + private vmTrackerSwitch: LitSwitch | undefined | null; + + get recordHilog(): boolean { + return this.vmTrackerSwitch!.checked; + } + + initElements(): void { + this.vmTrackerSwitch = this.shadowRoot?.querySelector('.hilog-switch') as LitSwitch; + } + + initHtml(): string { + return ` + +
+
+
+ Start Hilog Record + +
+
+
+ `; + } +} diff --git a/ide/src/trace/component/setting/SpProbesConfig.ts b/ide/src/trace/component/setting/SpProbesConfig.ts index 07c0c297..e97a2862 100644 --- a/ide/src/trace/component/setting/SpProbesConfig.ts +++ b/ide/src/trace/component/setting/SpProbesConfig.ts @@ -56,18 +56,18 @@ export class SpProbesConfig extends BaseElement { get memoryConfig() { let values = []; let selectedMemory = this._memoryConfig?.querySelectorAll( - `check-des-box[checked]` + 'check-des-box[checked]' ) as NodeListOf; for (const litCheckBoxElement of selectedMemory) { values.push(litCheckBoxElement.value); } - log('memoryConfig size is :' + values.length); + log(`memoryConfig size is :${values.length}`); return values; } get recordAbility() { let selectedMemory = this._abilityConfig?.querySelectorAll( - `check-des-box[checked]` + 'check-des-box[checked]' ) as NodeListOf; return selectedMemory.length > 0; } @@ -76,12 +76,12 @@ export class SpProbesConfig extends BaseElement { let values = []; if (this.hitrace && this.hitrace.checked) { let parent = this.shadowRoot?.querySelector('.user-events') as Element; - const siblingNode = parent?.querySelectorAll(`lit-check-box[name=userEvents][checked]`); + const siblingNode = parent?.querySelectorAll('lit-check-box[name=userEvents][checked]'); for (const litCheckBoxElement of siblingNode) { values.push(litCheckBoxElement.value); } } - log('traceEvents size is :' + values.length); + log(`traceEvents size is :${values.length}`); return values; } @@ -254,7 +254,7 @@ export class SpProbesConfig extends BaseElement { } if (detail!.checked === false && this.hitrace?.checked === true) { let hasChecked = false; - const nodes = parent?.querySelectorAll(`lit-check-box[name=userEvents]`); + const nodes = parent?.querySelectorAll('lit-check-box[name=userEvents]'); nodes.forEach((vv) => { if (vv.checked) { hasChecked = true; @@ -513,7 +513,7 @@ export class SpProbesConfig extends BaseElement { //当 custom element首次被插入文档DOM时,被调用。 public connectedCallback() { let parent = this.shadowRoot?.querySelector('.user-events') as Element; - const siblingNode = parent?.querySelectorAll(`lit-check-box[name=userEvents]`); + const siblingNode = parent?.querySelectorAll('lit-check-box[name=userEvents]'); this.hitrace!.addEventListener('onchange', (ev: CustomEventInit) => { let detail = ev.detail; siblingNode.forEach((node) => { diff --git a/ide/src/trace/component/setting/SpWebHdcShell.ts b/ide/src/trace/component/setting/SpWebHdcShell.ts index 2791a0e1..ae7b55e7 100644 --- a/ide/src/trace/component/setting/SpWebHdcShell.ts +++ b/ide/src/trace/component/setting/SpWebHdcShell.ts @@ -41,7 +41,8 @@ export class SpWebHdcShell extends BaseElement { private static TOP_OFFSET = 48; private static FIRST_ROW_OFFSET = 32; private static LAST_ROW_OFFSET = 40; - + private static MULTI_LINE_FLAG = '<\b'; + private static LINE_BREAK_LENGTH = 2; private static LEFT_OFFSET = 48; public initElements(): void { @@ -52,7 +53,7 @@ export class SpWebHdcShell extends BaseElement { this.shellCanvasCtx!.fillRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); this.shellDiv = this.shadowRoot!.querySelector('.shell_cmd_div'); this.shellCanvasAddMouseListener(); - this.shellCanvas!.addEventListener('contextmenu', event => { + this.shellCanvas!.addEventListener('contextmenu', (event) => { event.preventDefault(); event.stopPropagation(); }); @@ -71,7 +72,7 @@ export class SpWebHdcShell extends BaseElement { }); window.subscribe(window.SmartEvent.UI.DeviceConnect, (deviceName: string) => { if (deviceName) { - this.focus(); + this.hdcShellFocus(); } }); window.subscribe(window.SmartEvent.UI.DeviceDisConnect, (deviceName: string) => { @@ -100,11 +101,12 @@ export class SpWebHdcShell extends BaseElement { window.clearInterval(this.intervalId); } - public focus(): void { + public hdcShellFocus(): void { HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((connected) => { if (connected) { if (this.sendCallBack && this.startShellDevice === SpRecordTrace.serialNumber) { this.shellCanvas!.focus(); + this.refreshShellPage(true); } else { this.clear(); this.sendCallBack = HdcDeviceManager.startShell((result: DataMessage) => { @@ -116,6 +118,7 @@ export class SpWebHdcShell extends BaseElement { this.handleHdcRecvData(result); }); this.shellCanvas!.focus(); + this.refreshShellPage(true); } } else { this.clear(); @@ -126,7 +129,7 @@ export class SpWebHdcShell extends BaseElement { arrayBufferCompare(compareA: ArrayBuffer, compareB: number[]): boolean { const arrayA = new Uint8Array(compareA); if (arrayA.length === compareB.length) { - for (let i = 0 ; i < arrayA.length ; i++) { + for (let i = 0; i < arrayA.length; i++) { const dd = arrayA[i]; if (dd !== compareB[i]) { return false; @@ -146,26 +149,29 @@ export class SpWebHdcShell extends BaseElement { let endY = this.points!.endY!; let depth = Math.ceil((endY - startY) / 16); let index = 0; - for (let i = 0 ; i < textLines.length ; i++) { + for (let i = 0; i < textLines.length; i++) { let line = textLines[i]; let x = SpWebHdcShell.LEFT_OFFSET; let textFirstRowY = 16 * i + SpWebHdcShell.FIRST_ROW_OFFSET; let textLastRowY = 16 * i + SpWebHdcShell.LAST_ROW_OFFSET; let textEndY = 16 * i + SpWebHdcShell.TOP_OFFSET; let w = this.shellCanvasCtx!.measureText(line).width; - if ((startY < textEndY && endY >= textEndY) || (startY > textFirstRowY && startY < textEndY) - || (endY > textLastRowY && endY < textEndY)) { + if ( + (startY < textEndY && endY >= textEndY) || + (startY > textFirstRowY && startY < textEndY) || + (endY > textLastRowY && endY < textEndY) + ) { index++; - if(index == 1){ + if (index == 1) { if (depth > 1) { - selectedText += line.substring(Math.floor((startX - x) / 8)) + ((endX < x + w) ? '\n' : ''); + selectedText += line.substring(Math.floor((startX - x) / 8)) + (endX < x + w ? '\n' : ''); } else { - selectedText += `${ line.substring(Math.floor((startX - x) / 8), Math.ceil((endX - x) / 8)) }\n`; + selectedText += `${line.substring(Math.floor((startX - x) / 8), Math.ceil((endX - x) / 8))}\n`; } } else if (index == depth) { - selectedText += `${ line.substring(0, Math.ceil((endX - x) / 8)) }\n`; + selectedText += `${line.substring(0, Math.ceil((endX - x) / 8))}\n`; } else { - selectedText += `${ line }\n`; + selectedText += `${line}\n`; } } } @@ -187,7 +193,7 @@ export class SpWebHdcShell extends BaseElement { endPointY = endY; } else { //绘制多行 - for (let index = 1 ; index <= depth ; index++) { + for (let index = 1; index <= depth; index++) { //第一行,绘起始点到canvas右边界矩形 if (index === 1) { this.shellCanvasCtx!.fillRect(startX, startY, this.shellCanvas!.width - startX, index * 16); @@ -195,12 +201,22 @@ export class SpWebHdcShell extends BaseElement { startPointY = startY; } else if (index === depth) { //最后一行,canvas左边界到结束点矩形 - this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY + (index - 1) * 16, endX - SpWebHdcShell.LEFT_OFFSET, endY - (startY + (index - 1) * 16)); + this.shellCanvasCtx!.fillRect( + SpWebHdcShell.LEFT_OFFSET, + startY + (index - 1) * 16, + endX - SpWebHdcShell.LEFT_OFFSET, + endY - (startY + (index - 1) * 16) + ); endPointX = endX; endPointY = endY; } else { //中间行,canvas的左边界到右边界的矩形 - this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY + (index - 1) * 16, this.shellCanvas!.width, 16); + this.shellCanvasCtx!.fillRect( + SpWebHdcShell.LEFT_OFFSET, + startY + (index - 1) * 16, + this.shellCanvas!.width, + 16 + ); } } } @@ -222,7 +238,7 @@ export class SpWebHdcShell extends BaseElement { endPointY = startY; } else { //绘制多行 - for (let index = 1 ; index <= depth ; index++) { + for (let index = 1; index <= depth; index++) { //第一行,绘起始点到canvas左边界矩形 if (index === 1) { this.shellCanvasCtx!.fillRect(SpWebHdcShell.LEFT_OFFSET, startY - 16, startX - SpWebHdcShell.LEFT_OFFSET, 16); @@ -265,13 +281,12 @@ export class SpWebHdcShell extends BaseElement { this.shellCanvasCtx!.clearRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); this.shellCanvasCtx!.fillStyle = '#000'; this.shellCanvasCtx!.fillRect(0, 0, this.shellCanvas!.width, this.shellCanvas!.height); - - let resultStrArr = this.resultStr.split('\n'); + let resultStrArr = this.resultStr.split('\r\n'); this.finalArr = []; if (this.shellCanvas!.width > 0) { let maxWidth = this.shellCanvas!.width; - let foundationWidth = this.shellCanvasCtx!.measureText(' ').width; - for (let i = 0 ; i < resultStrArr.length - 1 ; i++) { + let foundationWidth = Math.ceil(this.shellCanvasCtx!.measureText(' ').width); + for (let i = 0; i < resultStrArr.length - 1; i++) { let shellStr = resultStrArr[i]; let strWidth = this.shellCanvasCtx!.measureText(shellStr).width; if (strWidth > maxWidth) { @@ -289,16 +304,16 @@ export class SpWebHdcShell extends BaseElement { this.shellCanvasCtx!.fillStyle = '#fff'; this.shellCanvasCtx!.font = '16px serif'; let textY = SpWebHdcShell.TOP_OFFSET; - this.finalArr.push(this.cursorRow) - for (let index: number = 0 ; index < this.finalArr.length ; index++) { + this.finalArr.push(this.cursorRow); + for (let index: number = 0; index < this.finalArr.length; index++) { let shellStr: string = this.finalArr[index]; textY = SpWebHdcShell.TOP_OFFSET + index * 16; this.shellCanvasCtx!.fillText(shellStr, SpWebHdcShell.LEFT_OFFSET, textY); } shellStrLength = this.cursorIndex * unitWidth + SpWebHdcShell.LEFT_OFFSET; if (scroller) { - if (this.finalArr.length < SpWebHdcShell.MAX_DISPLAY_ROWS && textY > this.shellDiv!.clientHeight) { - this.shellDiv!.scrollTop = textY - this.shellDiv!.clientHeight + (16 + 3); + if (textY > this.shellDiv!.clientHeight) { + this.shellDiv!.scrollTop = textY - this.shellDiv!.clientHeight + 3; } } if (this.intervalId) { @@ -361,7 +376,7 @@ export class SpWebHdcShell extends BaseElement {
- +
`; } @@ -374,7 +389,7 @@ export class SpWebHdcShell extends BaseElement { let currentRow: string[] = [...lastRow]; let result: string[] = []; this.cursorIndex = 0; - for (let index: number = 0 ; index < currentRow.length ; index++) { + for (let index: number = 0; index < currentRow.length; index++) { let currentResult: string = currentRow[index]; if (currentResult === '\b') { this.cursorIndex--; @@ -425,7 +440,17 @@ export class SpWebHdcShell extends BaseElement { } } } else { - this.resultStr += result.getDataToString(); + if (result.getDataToString().includes(SpWebHdcShell.MULTI_LINE_FLAG)) { + // 获取所有内容,不包括最后一行数据 + this.resultStr = this.resultStr.substring( + 0, + this.resultStr.lastIndexOf('\r\n') + SpWebHdcShell.LINE_BREAK_LENGTH + ); + // 多行情况不能直接拼接返回数据 + this.resultStr += result.getDataToString().substring(result.getDataToString().indexOf('\r')); + } else { + this.resultStr += result.getDataToString(); + } } } this.refreshCurrentRow(); diff --git a/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts b/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts index b2516e13..f2bf3a27 100644 --- a/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts +++ b/ide/src/trace/component/setting/bean/ProfilerServiceTypes.ts @@ -811,8 +811,6 @@ export enum Type { } export interface HilogConfig { - deviceType: Type; - logLevel: Level; needClear: boolean; } @@ -893,8 +891,7 @@ export interface DiskioConfig { reportIoStats: string; } -export interface NetworkConfig { -} +export interface NetworkConfig {} export interface HiperfPluginConfig { isRoot: boolean; diff --git a/ide/src/trace/component/trace/base/ColorUtils.ts b/ide/src/trace/component/trace/base/ColorUtils.ts index d79ed5fe..74e59470 100644 --- a/ide/src/trace/component/trace/base/ColorUtils.ts +++ b/ide/src/trace/component/trace/base/ColorUtils.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CpuStruct } from '../../../database/ui-worker/ProcedureWorkerCPU.js'; +import {CpuStruct} from '../../../database/ui-worker/ProcedureWorkerCPU.js'; export class ColorUtils { public static GREY_COLOR: string = '#f0f0f0'; @@ -65,9 +65,45 @@ export class ColorUtils { '#FFFFFF' ]; - public static JANK_COLOR: Array = ['#42A14D', '#C0CE85', '#FF651D', '#E8BE44', '#009DFA', '#E97978', '#A8D1F4']; + public static JANK_COLOR: Array = [ + '#42A14D', + '#C0CE85', + '#FF651D', + '#E8BE44', + '#009DFA', + '#E97978', + '#A8D1F4', + ]; public static MD_PALETTE: Array = ColorUtils.FUNC_COLOR_B; public static FUNC_COLOR: Array = ColorUtils.FUNC_COLOR_B; + public static getHilogColor(loglevel: string): string { + let logColor: string = '#00000'; + switch (loglevel) { + case 'D': + case 'Debug': + logColor = '#00BFBF'; + break; + case 'I': + case 'Info': + logColor = '#00BF00'; + break; + case 'W': + case 'Warn': + logColor = '#BFBF00'; + break; + case 'E': + case 'Error': + logColor = '#FF4040'; + break; + case 'F': + case 'Fatal': + logColor = '#BF00A4'; + break; + default: + break; + } + return logColor; + } public static hash(str: string, max: number): number { let colorA: number = 0x811c9dc5; @@ -102,7 +138,9 @@ export class ColorUtils { } public static formatNumberComma(str: number): string { - if (str === undefined || str === null) return ''; + if (str === undefined || str === null) { + return ''; + } let unit = str >= 0 ? '' : '-'; let l = Math.abs(str).toString().split('').reverse(); let t: string = ''; @@ -126,7 +164,7 @@ export class ColorUtils { return (Math.abs(hash) + depth) % max; } - public static funcTextColor(val: string) { + public static funcTextColor(val: string): string { var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // 把颜色值变成小写 var color = val.toLowerCase(); @@ -141,7 +179,7 @@ export class ColorUtils { } var colorChange = []; for (var i = 1; i < 7; i += 2) { - colorChange.push(parseInt('0x' + color.slice(i, i + 2))); + colorChange.push(parseInt(`0x${color.slice(i, i + 2)}`)); } var grayLevel = colorChange[0] * 0.299 + colorChange[1] * 0.587 + colorChange[2] * 0.114; if (grayLevel >= 150) { diff --git a/ide/src/trace/component/trace/base/TraceRow.ts b/ide/src/trace/component/trace/base/TraceRow.ts index 2176757f..53ffc1da 100644 --- a/ide/src/trace/component/trace/base/TraceRow.ts +++ b/ide/src/trace/component/trace/base/TraceRow.ts @@ -109,6 +109,7 @@ export class TraceRow extends HTMLElement { static ROW_TYPE_PURGEABLE_PIN_ABILITY = 'purgeable-pin-ability'; static ROW_TYPE_PURGEABLE_TOTAL_VM = 'purgeable-total-vm'; static ROW_TYPE_PURGEABLE_PIN_VM = 'purgeable-pin-vm'; + static ROW_TYPE_LOGS = 'logs'; static FRAME_WIDTH: number = 0; static range: TimeRange | undefined | null; static rangeSelectObject: RangeSelectStruct | undefined; diff --git a/ide/src/trace/component/trace/base/TraceSheet.ts b/ide/src/trace/component/trace/base/TraceSheet.ts index 4a7c1541..74467ab3 100644 --- a/ide/src/trace/component/trace/base/TraceSheet.ts +++ b/ide/src/trace/component/trace/base/TraceSheet.ts @@ -77,9 +77,11 @@ import { TabPaneVmTrackerShmComparison } from '../sheet/vmtracker/TabPaneVmTrack import { TabPaneJsCpuStatistics } from '../sheet/ark-ts/TabPaneJsCpuStatistics.js'; import { TabPaneGpuClickSelectComparison } from '../sheet/gpu/TabPaneGpuClickSelectComparison.js'; import { Utils } from './Utils.js'; +import { TabPaneHiLogs } from '../sheet/hilog/TabPaneHiLogs.js'; @element('trace-sheet') export class TraceSheet extends BaseElement { + systemLogFlag: Flag | undefined | null; private litTabs: LitTabs | undefined | null; private importDiv: HTMLDivElement | undefined | null; private nav: HTMLDivElement | undefined | null; @@ -181,6 +183,7 @@ export class TraceSheet extends BaseElement { } }); } + connectedCallback(): void { this.nav = this.shadowRoot?.querySelector('#tabs')?.shadowRoot?.querySelector('.tab-nav-container'); let tabs: HTMLDivElement | undefined | null = this.shadowRoot?.querySelector('#tabs'); @@ -589,6 +592,17 @@ export class TraceSheet extends BaseElement { } }; + displaySystemLogsData = (): void => { + let tblHiLogPanel = this.shadowRoot?.querySelector('lit-tabpane[id=\'box-hilogs\']'); + if (tblHiLogPanel) { + let tblHiLog = tblHiLogPanel.querySelector('tab-hi-log'); + if (tblHiLog) { + tblHiLog.parentElement!.style.overflow = 'hidden'; + tblHiLog.initTabSheetEl(tblHiLog.parentElement!, this); + } + } + }; + rangeSelect(selection: SelectionParam, restore = false): boolean { this.selection = selection; this.showUploadSoBt(selection); diff --git a/ide/src/trace/component/trace/base/TraceSheetConfig.ts b/ide/src/trace/component/trace/base/TraceSheetConfig.ts index 1c640411..857fb071 100644 --- a/ide/src/trace/component/trace/base/TraceSheetConfig.ts +++ b/ide/src/trace/component/trace/base/TraceSheetConfig.ts @@ -113,6 +113,8 @@ import { TabPaneGpuMemoryVmTrackerComparison } from '../sheet/vmtracker/TabPaneG import { TabPaneVmTrackerShmComparison } from '../sheet/vmtracker/TabPaneVmTrackerShmComparison.js'; import { TabPaneSmapsComparison } from '../sheet/smaps/TabPaneSmapsComparison.js'; import { TabPaneGpuClickSelectComparison } from '../sheet/gpu/TabPaneGpuClickSelectComparison.js'; +import { TabPaneHiLogs } from '../sheet/hilog/TabPaneHiLogs.js'; +import { TabPaneHiLogSummary } from '../sheet/hilog/TabPaneHiLogSummary.js'; export let tabConfig: any = { 'tabpane-current': { @@ -598,4 +600,14 @@ export let tabConfig: any = { title: 'Gpu Dump Comparison', type: TabPaneGpuClickSelectComparison, }, + 'box-hilogs': { + title: 'Hilogs', + type: TabPaneHiLogs, + require: (param: SelectionParam) => param.hiLogs.length > 0, + }, + 'box-hilogs-summary': { + title: 'Summary', + type: TabPaneHiLogSummary, + require: (param: SelectionParam) => param.hiLogSummary.length > 0, + }, }; diff --git a/ide/src/trace/component/trace/sheet/SheetUtils.ts b/ide/src/trace/component/trace/sheet/SheetUtils.ts index 93ccda5f..7acca319 100644 --- a/ide/src/trace/component/trace/sheet/SheetUtils.ts +++ b/ide/src/trace/component/trace/sheet/SheetUtils.ts @@ -46,14 +46,14 @@ export function resizeObserverFromMemory( // @ts-ignore tableEl?.shadowRoot.querySelector('.table').style.height = parentElement.clientHeight - tblOffsetHeight + 'px'; tableEl?.reMeauseHeight(); - if (filterEl!.clientHeight > 0) { - filterHeight = filterEl!.clientHeight; - } - if (parentElement!.clientHeight > filterHeight) { - filterEl!.style.display = 'flex'; - } else { - filterEl!.style.display = 'none'; - } + } + if (filterEl!.clientHeight > 0) { + filterHeight = filterEl!.clientHeight; + } + if (parentElement!.clientHeight > filterHeight) { + filterEl!.style.display = 'flex'; + } else { + filterEl!.style.display = 'none'; } }).observe(parentElement); } diff --git a/ide/src/trace/component/trace/sheet/ark-ts/TabPaneJsCpuStatistics.ts b/ide/src/trace/component/trace/sheet/ark-ts/TabPaneJsCpuStatistics.ts index 7fb7177f..cc6a42ef 100644 --- a/ide/src/trace/component/trace/sheet/ark-ts/TabPaneJsCpuStatistics.ts +++ b/ide/src/trace/component/trace/sheet/ark-ts/TabPaneJsCpuStatistics.ts @@ -41,8 +41,7 @@ export class TabPaneJsCpuStatistics extends BaseElement { this.getDataByWorker(data, (results: Map) => { this.progress!.loading = false; - - this.statisticsSource = this.setStatisticsData(results); + this.statisticsSource = results.size > 0 ? this.setStatisticsData(results) : []; this.queryPieChartDataByType(this.statisticsSource || []); }); } @@ -126,11 +125,14 @@ export class TabPaneJsCpuStatistics extends BaseElement { this.statisticsPie?.showHover(); this.statisticsPie?.hideTip(); }); - this.sortByColumn({ key: this.sortKey, sort: this.sortType }); - let total = this.totalData(this.statisticsSource); - this.statisticsSource.unshift(total); - this.statisticsTable!.recycleDataSource = this.statisticsSource; - this.statisticsSource.shift(); + + if (this.statisticsSource.length > 0) { + this.sortByColumn({ key: this.sortKey, sort: this.sortType }); + let total = this.totalData(this.statisticsSource); + this.statisticsSource.unshift(total); + this.statisticsTable!.recycleDataSource = this.statisticsSource; + this.statisticsSource.shift(); + } this.statisticsTable?.reMeauseHeight(); } @@ -170,7 +172,7 @@ export class TabPaneJsCpuStatistics extends BaseElement { type, time, ns2s(time), - ((time / percentage) * 100).toFixed(1) + ((time / percentage || 0) * 100).toFixed(1) ); return statisticsStruct; } @@ -202,11 +204,12 @@ export class TabPaneJsCpuStatistics extends BaseElement { } else if (detail.key === 'type') { this.statisticsSource.sort(compare(detail.key, detail.sort, 'string')); } - - let total = this.totalData(this.statisticsSource); - this.statisticsSource.unshift(total); - this.statisticsTable!.recycleDataSource = this.statisticsSource; - this.statisticsSource.shift(); + if (this.statisticsSource.length > 0) { + let total = this.totalData(this.statisticsSource); + this.statisticsSource.unshift(total); + this.statisticsTable!.recycleDataSource = this.statisticsSource; + this.statisticsSource.shift(); + } } public connectedCallback(): void { diff --git a/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogSummary.ts b/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogSummary.ts new file mode 100644 index 00000000..4f162b94 --- /dev/null +++ b/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogSummary.ts @@ -0,0 +1,231 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseElement, element } from '../../../../../base-ui/BaseElement.js'; +import { SelectionParam } from '../../../../bean/BoxSelection.js'; +import { LogStruct } from '../../../../database/ui-worker/ProcedureWorkerLog.js'; +import { ColorUtils } from '../../base/ColorUtils.js'; +import { LitTable } from '../../../../../base-ui/table/lit-table.js'; + +@element('tab-hi-log-summary') +export class TabPaneHiLogSummary extends BaseElement { + private logSummaryTable: HTMLDivElement | undefined | null; + private summaryDownLoadTbl: LitTable | undefined | null; + private systemLogSource: LogStruct[] = []; + private expandedNodeList: Set = new Set(); + private logLevel: string[] = ['Debug', 'Info', 'Warn', 'Error','Fatal']; + + set data(systemLogDetailParam: SelectionParam) { + this.systemLogSource = []; + this.expandedNodeList.clear(); + this.logSummaryTable!.innerHTML = ''; + this.summaryDownLoadTbl!.recycleDataSource = []; + if (this.summaryDownLoadTbl) { + this.summaryDownLoadTbl.recycleDataSource = []; + } + this.systemLogSource = systemLogDetailParam.hiLogSummary; + if (this.systemLogSource?.length !== 0 && systemLogDetailParam) { + this.refreshRowNodeTable(); + } + } + + initElements(): void { + this.logSummaryTable = this.shadowRoot?.querySelector('#tab-summary'); + this.summaryDownLoadTbl = this.shadowRoot?.querySelector('#tb-hilog-summary'); + } + + initHtml(): string { + return ` +
+ + +
+
+ + `; + } + + private getLevelName(level: string): string { + switch (level) { + case 'D': + return 'Debug'; + case 'I': + return 'Info'; + case 'W': + return 'Warn'; + case 'E': + return 'Error'; + case 'F': + return 'Fatal'; + default: + return 'Other'; + } + } + + private createRowNodeTableEL(rowNodeList: LogTreeNode[], rowColor: string = ''): DocumentFragment { + let unitPadding: number = 20; + let leftPadding: number = 5; + let tableFragmentEl: DocumentFragment = document.createDocumentFragment(); + rowNodeList.forEach((rowNode) => { + let tableRowEl: HTMLElement = document.createElement('tr'); + tableRowEl.className = 'tree-row-tr'; + let leftSpacingEl: HTMLElement = document.createElement('td'); + leftSpacingEl.style.paddingLeft = `${rowNode.depth * unitPadding + leftPadding}px`; + tableRowEl.appendChild(leftSpacingEl); + this.addToggleIconEl(rowNode, tableRowEl); + let rowNodeTextEL: HTMLElement = document.createElement('td'); + rowNodeTextEL.textContent = rowNode.logName!; + rowNodeTextEL.className = 'row-name-td'; + tableRowEl.appendChild(rowNodeTextEL); + let countEL: HTMLElement = document.createElement('td'); + countEL.textContent = rowNode.count.toString(); + countEL.className = 'count-column-td'; + if (rowNode.depth === 0) { + rowNodeTextEL.style.color = ColorUtils.getHilogColor(rowNode.logName!); + countEL.style.color = ColorUtils.getHilogColor(rowNode.logName!); + } else { + rowNodeTextEL.style.color = rowColor; + countEL.style.color = rowColor; + } + tableRowEl.appendChild(countEL); + tableFragmentEl.appendChild(tableRowEl); + if (this.expandedNodeList.has(rowNode.id) && rowNode.children) { + tableFragmentEl.appendChild(this.createRowNodeTableEL(rowNode.children, countEL.style.color)); + } + }); + return tableFragmentEl; + } + + private addToggleIconEl(rowNode: LogTreeNode, tableRowEl: HTMLElement): void { + let toggleIconEl: HTMLElement = document.createElement('td'); + let expandIcon = document.createElement('lit-icon'); + expandIcon.classList.add('tree-icon'); + if (rowNode.children && rowNode.children.length > 0) { + toggleIconEl.appendChild(expandIcon); + // @ts-ignore + expandIcon.name = this.expandedNodeList.has(rowNode.id) ? 'minus-square' : 'plus-square'; + toggleIconEl.classList.add('expand-icon'); + toggleIconEl.addEventListener('click', () => { + this.changeNode(rowNode.id); + }); + } + tableRowEl.appendChild(toggleIconEl); + } + + private changeNode(currentNode: number): void { + if (this.expandedNodeList.has(currentNode)) { + this.expandedNodeList['delete'](currentNode); + } else { + this.expandedNodeList.add(currentNode); + } + this.refreshRowNodeTable(); + } + + private refreshRowNodeTable(): void { + this.logSummaryTable!.innerHTML = ''; + let logTreeNodes = this.buildTreeTblNodes(this.systemLogSource); + if (logTreeNodes.length > 0) { + this.summaryDownLoadTbl!.recycleDataSource = logTreeNodes; + } else { + this.summaryDownLoadTbl!.recycleDataSource = []; + } + let fragment = this.createRowNodeTableEL(logTreeNodes); + this.logSummaryTable!.appendChild(fragment); + } + + private buildTreeTblNodes(logTreeNodes: LogStruct[]): LogTreeNode[] { + let id = 0; + let root: LogTreeNode = { id: id, depth: 0, children: [], logName: 'All', count: 0 }; + logTreeNodes.forEach((item) => { + id++; + let levelName = this.getLevelName(item.level!); + let levelNode = root.children.find((node) => node.logName === levelName); + if (!levelNode) { + id++; + levelNode = { id: id, depth: 0, children: [], logName: levelName, count: 0 }; + root.children.push(levelNode); + } + let processNode = levelNode.children.find((node) => node.logName === item.processName); + if (!processNode) { + id++; + processNode = { id: id, depth: 1, children: [], logName: item.processName, count: 0 }; + levelNode.children.push(processNode); + } + let tagNode = processNode.children.find((node) => node.logName === item.tag); + if (!tagNode) { + id++; + tagNode = { id: id, depth: 2, children: [], logName: item.tag, count: 0 }; + processNode.children.push(tagNode); + } + id++; + tagNode.children.push({ id: id, depth: 3, children: [], logName: item.context, count: 1 }); + tagNode.count++; + processNode.count++; + levelNode.count++; + root.count++; + }); + return root.children.sort((leftData, rightData) => { + return this.logLevel.indexOf(leftData.logName!) - this.logLevel.indexOf(rightData.logName!); + }); + } +} + +export interface LogTreeNode { + id: number; + depth: number; + children: LogTreeNode[]; + logName: string | undefined; + count: number; +} diff --git a/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts b/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts new file mode 100644 index 00000000..4d4ff37e --- /dev/null +++ b/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts @@ -0,0 +1,498 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseElement, element } from '../../../../../base-ui/BaseElement.js'; +import { SelectionParam } from '../../../../bean/BoxSelection.js'; +import { TraceRow } from '../../base/TraceRow.js'; +import { TraceSheet } from '../../base/TraceSheet.js'; +import { Flag } from '../../timer-shaft/Flag.js'; +import { SpSystemTrace } from '../../../SpSystemTrace.js'; +import { ns2Timestamp, ns2x, Rect } from '../../../../database/ui-worker/ProcedureWorkerCommon.js'; +import { LogStruct } from '../../../../database/ui-worker/ProcedureWorkerLog.js'; +import { ColorUtils } from '../../base/ColorUtils.js'; +import { LitTable } from '../../../../../base-ui/table/lit-table.js'; + +@element('tab-hi-log') +export class TabPaneHiLogs extends BaseElement { + tableTimeHandle: (() => void) | undefined; + private systemLogSource: LogStruct[] = []; + private spSystemTrace: SpSystemTrace | undefined | null; + private traceSheetEl: TraceSheet | undefined | null; + private parentTabEl: HTMLElement | undefined | null; + private levelFilterInput: HTMLSelectElement | undefined | null; + private tagFilterInput: HTMLInputElement | undefined | null; + private searchFilterInput: HTMLInputElement | undefined | null; + private processFilter: HTMLInputElement | undefined | null; + private logTitle: HTMLDivElement | undefined | null; + private logTableTitle: HTMLDivElement | undefined | null; + private logTable: HTMLDivElement | undefined | null; + private scrollContainer: HTMLDivElement | undefined | null; + private tagFilterDiv: HTMLDivElement | undefined | null; + private hiLogDownLoadTbl: LitTable | undefined | null; + private filterData: LogStruct[] = []; + private visibleData: LogStruct[] = []; + private optionLevel: string[] = ['D', 'I', 'W', 'E', 'F']; + private tableColumnHead: string[] = ['Timestamp', 'Level', 'Tag', 'Process name', 'Message']; + private allowTag: Set = new Set(); + private startDataIndex: number = 0; + private endDataIndex: number = 0; + private containerClientHeight: number = 0; + + set data(systemLogParam: SelectionParam) { + if (this.hiLogDownLoadTbl) { + this.hiLogDownLoadTbl.recycleDataSource = []; + } + this.systemLogSource = systemLogParam.hiLogs; + if (systemLogParam && systemLogParam.hiLogs.length > 0) { + this.tableTimeHandle?.(); + } + } + + initElements(): void { + this.logTitle = this.shadowRoot?.querySelector('.logs-title-content'); + this.logTableTitle = this.shadowRoot?.querySelector('#log-title'); + this.scrollContainer = this.shadowRoot?.querySelector('.tbl-logs'); + this.logTable = this.shadowRoot?.querySelector('#logs-data-content'); + this.levelFilterInput = this.shadowRoot?.querySelector('#level-filter'); + this.tagFilterInput = this.shadowRoot?.querySelector('#tag-filter'); + this.searchFilterInput = this.shadowRoot?.querySelector('#search-filter'); + this.processFilter = this.shadowRoot?.querySelector('#process-filter'); + this.spSystemTrace = document.querySelector('body > sp-application')!. + shadowRoot!.querySelector('#sp-system-trace'); + this.tableTimeHandle = this.delayedRefresh(this.refreshTable); + this.tagFilterDiv = this.shadowRoot!.querySelector('#tagFilter'); + this.hiLogDownLoadTbl = this.shadowRoot!.querySelector('#tb-hilogs'); + } + + connectedCallback(): void { + super.connectedCallback(); + this.tagFilterInput?.addEventListener('input', this.tagFilterInputEvent); + this.tagFilterInput?.addEventListener('keydown', this.tagFilterKeyEvent); + this.tagFilterDiv?.addEventListener('click', this.tagFilterDivClickEvent); + this.searchFilterInput?.addEventListener('input', this.searchFilterInputEvent); + this.processFilter?.addEventListener('input', this.processFilterEvent); + this.levelFilterInput?.addEventListener('change', this.levelFilterInputEvent); + this.scrollContainer?.addEventListener('scroll', this.logTableScrollEvent); + new ResizeObserver(() => { + this.updateVisibleData(); + }).observe(this.parentElement!); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.tagFilterInput?.removeEventListener('input', this.tagFilterInputEvent); + this.tagFilterInput?.removeEventListener('keydown', this.tagFilterKeyEvent); + this.tagFilterDiv?.removeEventListener('click', this.tagFilterDivClickEvent); + this.searchFilterInput?.removeEventListener('input', this.searchFilterInputEvent); + this.processFilter?.removeEventListener('input', this.processFilterEvent); + this.levelFilterInput?.removeEventListener('change', this.levelFilterInputEvent); + this.scrollContainer?.removeEventListener('scroll', this.logTableScrollEvent); + } + + initHtml(): string { + return `${this.initTitleCssStyle()} + ${this.initTableCssStyle()} +
+ +
+ + +
+
+
+ +
+ + +
+
+
+
+ + `; + } + + initTabSheetEl(parentTabEl: HTMLElement, traceSheet: TraceSheet): void { + this.traceSheetEl = traceSheet; + if (parentTabEl) { + this.parentTabEl = parentTabEl; + this.containerClientHeight = parentTabEl.clientHeight; + } + this.levelFilterInput!.selectedIndex = 0; + this.tagFilterInput!.value = ''; + this.tagFilterInput!.placeholder = 'Filter by tag...'; + this.tagFilterDiv!.innerHTML = ''; + this.allowTag.clear(); + this.processFilter!.value = ''; + this.processFilter!.placeholder = 'Search process name...'; + this.searchFilterInput!.value = ''; + this.searchFilterInput!.placeholder = 'Search logs...'; + } + + tagFilterInputEvent = (): void => { + if (this.tagFilterInput) { + if (this.tagFilterInput.value === '') { + this.tagFilterInput.placeholder = 'Filter by tag...'; + } else { + this.tagFilterInput.placeholder = ''; + } + } + }; + + tagFilterKeyEvent = (e: KeyboardEvent): void => { + let inputValue = this.tagFilterInput!.value.trim(); + if (e.code === 'Enter') { + if (inputValue !== '' && !this.allowTag.has(inputValue.toLowerCase())) { + let tagElement = document.createElement('div'); + tagElement.className = 'tagElement'; + tagElement.id = inputValue; + let tag = document.createElement('div'); + tag.className = 'tag'; + tag.innerHTML = inputValue; + this.allowTag.add(inputValue.toLowerCase()); + let closeButton = document.createElement('lit-icon'); + closeButton.setAttribute('name', 'close-light'); + closeButton.style.color = '#FFFFFF'; + tagElement.append(tag); + tagElement.append(closeButton); + this.tagFilterDiv!.append(tagElement); + this.tagFilterInput!.value = ''; + this.tagFilterInput!.placeholder = 'Filter by tag...'; + } + } else if (e.code === 'Backspace') { + let index = this.tagFilterDiv!.childNodes.length - defaultIndex; + if (index >= 0 && inputValue === '') { + let childNode = this.tagFilterDiv!.childNodes[index]; + this.tagFilterDiv!.removeChild(childNode); + this.allowTag['delete'](childNode.textContent!.trim().toLowerCase()); + } + } + this.tableTimeHandle?.(); + }; + + tagFilterDivClickEvent = (ev: Event): void => { + // @ts-ignore + let parentNode = ev.target.parentNode; + if (parentNode && this.tagFilterDiv!.contains(parentNode)) { + this.tagFilterDiv!.removeChild(parentNode); + this.allowTag['delete'](parentNode.textContent.trim().toLowerCase()); + } + this.tableTimeHandle?.(); + }; + + searchFilterInputEvent = (): void => { + if (this.searchFilterInput) { + if (this.searchFilterInput.value === '') { + this.searchFilterInput.placeholder = 'Search logs...'; + } else { + this.searchFilterInput.placeholder = ''; + } + } + this.tableTimeHandle?.(); + }; + + processFilterEvent = (): void => { + if (this.processFilter) { + if (this.processFilter.value === '') { + this.processFilter.placeholder = 'Search process name...'; + } else { + this.processFilter.placeholder = ''; + } + } + this.tableTimeHandle?.(); + }; + + levelFilterInputEvent = (): void => { + this.tableTimeHandle?.(); + }; + + logTableScrollEvent = (): void => { + let newIndex = Math.floor((this.scrollContainer?.scrollTop || 0) / tableRowHeight); + if (newIndex !== this.startDataIndex) { + this.startDataIndex = newIndex; + this.updateVisibleData(); + } + }; + + private updateFilterData(): void { + if (this.systemLogSource?.length > 0) { + this.filterData = this.systemLogSource.filter((data) => this.isFilterLog(data)); + } + if (this.filterData.length > 0) { + this.hiLogDownLoadTbl!.recycleDataSource = this.filterData; + } else { + this.hiLogDownLoadTbl!.recycleDataSource = []; + } + } + + private updateVisibleData(): void { + this.visibleData = []; + this.logTable!.innerHTML = ''; + if (this.systemLogSource?.length === 0 || this.parentTabEl?.clientHeight === 0) { + return; + } + if (this.parentTabEl) { + this.containerClientHeight = this.parentTabEl.clientHeight; + } + if (this.systemLogSource.length > 0 && this.logTable) { + let tableHeight = this.containerClientHeight - (this.logTitle?.clientHeight || 0) - tableRowHeight; + this.scrollContainer!.style.height = `${tableHeight}px`; + if (this.filterData.length === 0) { + this.logTable.style.height = this.scrollContainer!.style.height; + this.logTableTitle!.textContent = 'Hilogs [0, 0] / 0'; + } else { + this.logTable.style.height = `${this.filterData.length * tableRowHeight}px`; + let totalLength = Math.floor(tableHeight / tableRowHeight); + this.endDataIndex = this.startDataIndex + totalLength; + if (this.filterData.length > this.endDataIndex - this.startDataIndex) { + this.visibleData = this.filterData.slice(this.startDataIndex, this.endDataIndex); + } else { + this.visibleData = this.filterData; + } + let maxLength = this.endDataIndex > this.filterData.length ? this.filterData.length : this.endDataIndex; + this.logTableTitle!.textContent = `Hilogs [${this.startDataIndex || 0}, + ${maxLength}] / ${this.filterData.length || 0}`; + let tableFragment = document.createDocumentFragment(); + this.buildTableHead(tableFragment); + this.createVirtualDOM(tableFragment); + this.logTable.append(tableFragment); + } + } + } + + private isFilterLog(data: LogStruct): boolean { + let level = this.levelFilterInput?.selectedIndex || 0; + let search = this.searchFilterInput?.value.toLowerCase() || ''; + let processSearch = this.processFilter?.value.toLowerCase() || ''; + return (data.startTs || 0) >= TraceRow.range!.startNS && (data.startTs || 0) <= TraceRow.range!.endNS && + (level === 0 || this.optionLevel.indexOf(data.level!) >= level) && + (this.allowTag.size === 0 || this.allowTag.has(data.tag!.toLowerCase())) && + (search === '' || data.context!.toLowerCase().indexOf(search) >= 0) && + (processSearch === '' || (data.processName !== null && + data.processName!.toLowerCase().indexOf(processSearch) >= 0)); + } + + private refreshTable(): void { + this.traceSheetEl!.systemLogFlag = undefined; + this.spSystemTrace?.refreshCanvas(false); + this.updateFilterData(); + this.updateVisibleData(); + } + + private delayedRefresh(optionFn: Function, dur: number = tableTimeOut): () => void { + let timeOutId: number; + return (...args: []): void => { + window.clearTimeout(timeOutId); + timeOutId = window.setTimeout((): void => { + optionFn.apply(this, ...args); + }, dur); + }; + } + + private createVirtualDOM(tableFragment: DocumentFragment): void { + if (this.visibleData) { + this.visibleData.forEach((row) => { + let trEL = document.createElement('tr'); + let timeStampEl = document.createElement('td'); + let levelEl = document.createElement('td'); + let tagEl = document.createElement('td'); + let processNameEl = document.createElement('td'); + let messageEl = document.createElement('td'); + let colorIndex = this.optionLevel.indexOf(row.level!) - defaultIndex; + if (colorIndex >= 0) { + trEL.style.color = ColorUtils.getHilogColor(row.level!); + } + timeStampEl.classList.add('time-td'); + timeStampEl.textContent = `${ns2Timestamp(row.startTs!)}`; + levelEl.textContent = `${row.level}`; + tagEl.textContent = `${row.tag}`; + processNameEl.textContent = `${row.processName}`; + messageEl.textContent = `${row.context}`; + trEL.addEventListener('mouseover', () => { + let pointX: number = ns2x( + row.startTs || 0, + TraceRow.range!.startNS, + TraceRow.range!.endNS, + TraceRow.range!.totalNS, + new Rect(0, 0, TraceRow.FRAME_WIDTH, 0) + ); + this.traceSheetEl!.systemLogFlag = new Flag(Math.floor(pointX), 0, 0, 0, row.startTs!, '#999999', true, ''); + this.spSystemTrace?.refreshCanvas(false); + }); + trEL.addEventListener('mouseout', () => { + this.traceSheetEl!.systemLogFlag = undefined; + this.spSystemTrace?.refreshCanvas(false); + }); + trEL.appendChild(timeStampEl); + trEL.appendChild(levelEl); + trEL.appendChild(tagEl); + trEL.appendChild(processNameEl); + trEL.appendChild(messageEl); + tableFragment.appendChild(trEL); + }); + } + } + + private buildTableHead(tableFragment: DocumentFragment): void { + let trEL = document.createElement('tr'); + this.tableColumnHead.forEach((columnText) => { + let columnEl = document.createElement('div'); + columnEl.textContent = columnText; + columnEl.className = 'head-column'; + trEL.appendChild(columnEl); + }); + let height = + (this.scrollContainer!.scrollTop <= tableRowHeight ? 0 : this.scrollContainer!.scrollTop) + tableRowHeight; + trEL.style.height = `${height}px`; + tableFragment.appendChild(trEL); + } + + private initTitleCssStyle(): string { + return ``; + } + + private initTableCssStyle(): string { + return ``; + } +} + +let defaultIndex: number = 1; +let tableRowHeight: number = 23; +let tableTimeOut: number = 50; diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts index 6d61d100..9bb0bad9 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts @@ -37,8 +37,8 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { initElements(): void { this.gpuMemoryClickTable = this.shadowRoot?.querySelector('#gpuMemoryClickTable'); - this.selectEl = this.comparisonSelect?.shadowRoot?.querySelector('lit-select'); this.comparisonSelect = this.shadowRoot?.querySelector('#filter') as TabPaneJsMemoryFilter; + this.selectEl = this.comparisonSelect?.shadowRoot?.querySelector('lit-select'); this.gpuMemoryClickTable!.addEventListener('column-click', (e) => { // @ts-ignore this.sortGpuMemoryByColumn(e.detail.key, e.detail.sort); diff --git a/ide/src/trace/database/SqlLite.ts b/ide/src/trace/database/SqlLite.ts index ef21ea2e..587414c1 100644 --- a/ide/src/trace/database/SqlLite.ts +++ b/ide/src/trace/database/SqlLite.ts @@ -90,6 +90,7 @@ import { FrameDynamicStruct } from './ui-worker/ProcedureWorkerFrameDynamic.js'; import { FrameAnimationStruct } from './ui-worker/ProcedureWorkerFrameAnimation.js'; import { SnapshotStruct } from './ui-worker/ProcedureWorkerSnapshot.js'; import { MemoryConfig } from '../bean/MemoryConfig.js'; +import { LogStruct } from './ui-worker/ProcedureWorkerLog.js'; class DataWorkerThread extends Worker { taskMap: any = {}; @@ -616,7 +617,7 @@ export const getTabBoxChildData = ( not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) ${condition}; ` return query('getTabBoxChildData', sql, {}); -} +}; export const getTabCpuUsage = (cpus: Array, leftNs: number, rightNs: number): Promise> => query( @@ -2042,9 +2043,9 @@ export const queryTraceMetaData = (): Promise< export const querySystemCalls = (): Promise< Array<{ frequency: string; - minDur: string; - maxDur: string; - avgDur: string; + minDur: number; + maxDur: number; + avgDur: number; funName: string; }> > => @@ -5279,3 +5280,73 @@ export const getTabGpuMemoryVmTrackerComparisonData = ( `, { $startNs: startNs, $pid: processId } ); + +export const getSystemLogsData = (): Promise< + Array<{ + id: number; + ts: number; + processName: string; + tid: number; + level: string; + tag: string; + message: string; + des: number; + }> +> => + query( + 'getSystemLogsData', + `SELECT + ROW_NUMBER() OVER (ORDER BY l.ts) AS processName, + l.seq AS id, + (l.ts - TR.start_ts) AS ts, + l.pid AS indexs, + l.tid, + l.level, + l.tag, + l.context AS message, + l.origints AS des + FROM trace_range AS TR, + log AS l + ORDER BY ts` + ); + +export const queryLogData = (): Promise> => + query( + 'queryLogData', + ` + SELECT l.seq AS id, + (l.ts - TR.start_ts) AS startTs, + l.level AS level, + CASE + WHEN l.level = 'D' THEN + 0 + WHEN l.level = 'I' THEN + 1 + WHEN l.level = 'W' THEN + 2 + WHEN l.level = 'E' THEN + 3 + WHEN l.level = 'F' THEN + 4 + END AS depth, + l.tag AS tag, + l.context AS context, + l.origints AS time, + l.pid, + l.tid, + CASE + WHEN p.name is null THEN + 'Process ' || l.pid + else p.name + END AS processName, + 1 AS dur + FROM + trace_range AS TR, + log AS l + LEFT JOIN + process p + ON p.pid = l.pid + ORDER BY + l.ts;`, + {} + ); diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.ts index 8d0c0623..aceb8a95 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.ts @@ -95,13 +95,13 @@ export class ProcedureLogicWorkerJsCpuProfiler extends LogicHandler { const samplesIds = this.findSamplesIds(chartData, [], []); for (const id of samplesIds) { const sample = this.samples[id]; - if (!sample) { + if (!sample || sample.type === undefined) { continue; } let sampleTotalTime = sample.dur; if (leftNs && rightNs) { // 不在框选范围内的不做处理 - if (sample.startTime > rightNs || sample.endTime < leftNs){ + if (sample.startTime > rightNs || sample.endTime < leftNs) { continue; } // 在框选范围内的被只框选到一部分的根据框选范围调整时间 @@ -207,7 +207,9 @@ export class ProcedureLogicWorkerJsCpuProfiler extends LogicHandler { sample.type = SampleType.RUNTIME; break; default: - sample.type = SampleType.OTHER; + if (stackTopSymbol.name !== '(program)') { + sample.type = SampleType.OTHER; + } break; } } diff --git a/ide/src/trace/database/ui-worker/ProcedureWorker.ts b/ide/src/trace/database/ui-worker/ProcedureWorker.ts index 50e478a5..577b6294 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorker.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorker.ts @@ -55,6 +55,7 @@ import { FrameAnimationRender } from './ProcedureWorkerFrameAnimation.js'; import { FrameSpacingRender } from './ProcedureWorkerFrameSpacing.js'; import { JsCpuProfilerRender } from './ProcedureWorkerCpuProfiler.js'; import { SnapshotRender } from './ProcedureWorkerSnapshot.js'; +import { LogRender } from './ProcedureWorkerLog.js'; let dataList: any = {}; let dataList2: any = {}; @@ -107,6 +108,7 @@ export let renders: any = { frameSpacing: new FrameSpacingRender(), 'js-cpu-profiler': new JsCpuProfilerRender(), snapshot: new SnapshotRender(), + logs: new LogRender(), }; function match(type: string, req: RequestMessage) { diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts index 4d61add7..0e897305 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts @@ -16,6 +16,7 @@ import { CpuStruct, WakeupBean } from './ProcedureWorkerCPU.js'; import { TraceRow } from '../../component/trace/base/TraceRow.js'; import { TimerShaftElement } from '../../component/trace/TimerShaftElement'; +import { Flag } from '../../component/trace/timer-shaft/Flag.js'; export abstract class Render { abstract renderMainThread(req: any, row: TraceRow): void; @@ -75,19 +76,33 @@ export function ns2s(ns: number): string { let microsecond = 1_000; // 1 microsecond let res; if (ns >= second1) { - res = (ns / 1000 / 1000 / 1000).toFixed(1) + ' s'; + res = `${(ns / 1000 / 1000 / 1000).toFixed(1)} s`; } else if (ns >= millisecond) { - res = (ns / 1000 / 1000).toFixed(1) + ' ms'; + res = `${(ns / 1000 / 1000).toFixed(1)} ms`; } else if (ns >= microsecond) { - res = (ns / 1000).toFixed(1) + ' μs'; + res = `${(ns / 1000).toFixed(1)} μs`; } else if (ns > 0) { - res = ns.toFixed(1) + ' ns'; + res = `${ns.toFixed(1)} ns`; } else { - res = ns.toFixed(1) + ' s'; + res = `${ns.toFixed(1)} s`; } return res; } +export function ns2Timestamp(ns: number): string { + let hour = Math.floor(ns / 3600000000000); + let minute = Math.floor((ns % 3600000000000) / 60000000000); + let second = Math.floor((ns % 60000000000) / 1000000000); + let millisecond = Math.floor((ns % 1000000000) / 1000000); + let microsecond = Math.floor((ns % 1000000) / 1000); + let nanosecond = ns % 1000; + return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second + .toString() + .padStart(2, '0')}:${millisecond.toString().padStart(3, '0')}:${microsecond + .toString() + .padStart(3, '0')}:${nanosecond.toString().padStart(3, '0')}`; +} + export function isFrameContainPoint(frame: Rect, x: number, y: number): boolean { return x >= frame.x && x <= frame.x + frame.width && y >= frame.y && y <= frame.y + frame.height; } @@ -537,6 +552,51 @@ export function drawFlagLineSegment(ctx: any, hoverFlag: any, selectFlag: any, f } } +export function drawLogsLineSegment( + ctx: CanvasRenderingContext2D | undefined | null, + systemLogFlag: Flag | undefined | null, + frame: { + x: number; + y: number; + width: number | undefined; + height: number | undefined; + }, + timerShaftEl: TimerShaftElement +): void { + timerShaftEl.sportRuler?.draw(); + if (systemLogFlag) { + if (ctx) { + ctx.beginPath(); + ctx.lineWidth = 2; + ctx.strokeStyle = systemLogFlag?.color || '#dadada'; + ctx.moveTo(Math.floor(systemLogFlag.x), 0); + ctx.lineTo(Math.floor(systemLogFlag.x), frame.height || 0); + ctx.stroke(); + ctx.closePath(); + } + if (timerShaftEl.ctx) { + let timeText = `| ${ns2Timestamp(systemLogFlag.time)}`; + let textPointX = systemLogFlag.x; + let textMetrics = timerShaftEl.ctx.measureText(timeText); + if (timerShaftEl.ctx.canvas.width - systemLogFlag.x <= textMetrics.width) { + textPointX = systemLogFlag.x - textMetrics.width; + timeText = `${ns2Timestamp(systemLogFlag.time)} |`; + } + let locationY = 120; + timerShaftEl.ctx.beginPath(); + timerShaftEl.ctx.lineWidth = 0; + timerShaftEl.ctx.fillStyle = '#FFFFFF'; + let textHeight = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent; + timerShaftEl.ctx.fillRect(textPointX, locationY - textHeight, textMetrics.width, textHeight); + timerShaftEl.ctx.lineWidth = 2; + timerShaftEl.ctx.fillStyle = systemLogFlag?.color || '#dadada'; + timerShaftEl.ctx.fillText(timeText, textPointX, locationY); + timerShaftEl.ctx.stroke(); + timerShaftEl.ctx.closePath(); + } + } +} + export function drawSelection(ctx: any, params: any) { if (params.isRangeSelect && params.rangeSelectObject) { params.rangeSelectObject!.startX = Math.floor( diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerLog.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerLog.ts new file mode 100644 index 00000000..f60dd96a --- /dev/null +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerLog.ts @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {TraceRow} from '../../component/trace/base/TraceRow.js'; +import {isFrameContainPoint, ns2x, Rect, Render} from './ProcedureWorkerCommon.js'; + +import {BaseStruct} from '../../bean/BaseStruct.js'; +import {ColorUtils} from "../../component/trace/base/ColorUtils.js"; + +const LOG_STRUCT_HEIGHT = 7; +const X_PADDING = 5; +const Y_PADDING = 2; + +export class LogRender extends Render { + renderMainThread( + req: { + useCache: boolean; + context: CanvasRenderingContext2D; + type: string; + }, + row: TraceRow + ): void { + let logList = row.dataList; + let logFilter = row.dataListCache; + filterLogData( + logList, + logFilter, + TraceRow.range!.startNS, + TraceRow.range!.endNS, + TraceRow.range!.totalNS, + row.frame, + req.useCache || !TraceRow.range!.refresh + ); + req.context.beginPath(); + for (let re of logFilter) { + LogStruct.draw(req.context, re); + } + req.context.closePath(); + } +} + +export function filterLogData( + logList: Array, + logFilter: Array, + startNS: number, + endNS: number, + totalNS: number, + frame: any, + use: boolean +): void { + if (use && logFilter.length > 0) { + for (let i = 0, len = logFilter.length; i < len; i++) { + if ((logFilter[i].startTs || 0) + (logFilter[i].dur || 0) >= startNS && (logFilter[i].startTs || 0) <= endNS) { + LogStruct.setLogFrame(logFilter[i], 0, startNS, endNS, totalNS, frame); + } else { + logFilter[i].frame = undefined; + } + } + return; + } + logFilter.length = 0; + if (logList) { + for (let index: number = 0; index < logList.length; index++) { + let itemLog: LogStruct = logList[index]; + if ((itemLog.startTs ?? 0) + (itemLog.dur ?? 0) >= startNS && (itemLog.startTs ?? 0) <= endNS) { + LogStruct.setLogFrame(itemLog, 0, startNS, endNS, totalNS, frame); + logFilter.push(itemLog); + } + } + } +} + +export class LogStruct extends BaseStruct { + static hoverLogStruct: LogStruct | undefined; + static selectLogStruct: LogStruct | undefined; + //日志等级对应颜色,debug、info、warn、error、fatal + id: number | undefined; + pid: number | undefined; + tid: number | undefined; + processName: string | undefined; + startTs: number | undefined; + level: string | undefined; + tag: string | undefined; + context: string | undefined; + time: number | undefined; + depth: number | undefined; + dur: number | undefined; + + static setLogFrame( + logNode: LogStruct, + padding: number, + startNS: number, + endNS: number, + totalNS: number, + frame: any + ): void { + let x1: number, x2: number; + if ((logNode.startTs || 0) > startNS && (logNode.startTs || 0) <= endNS) { + x1 = ns2x(logNode.startTs || 0, startNS, endNS, totalNS, frame); + } else { + x1 = 0; + } + if ((logNode.startTs || 0) + (logNode.dur || 0) > startNS && (logNode.startTs || 0) + (logNode.dur || 0) <= endNS) { + x2 = ns2x((logNode.startTs || 0) + (logNode.dur || 0), startNS, endNS, totalNS, frame); + } else { + x2 = frame.width; + } + if (!logNode.frame) { + logNode.frame! = new Rect(0, 0, 0, 0); + } + let getV: number = x2 - x1 < 1 ? 1 : x2 - x1; + logNode.frame!.x = Math.floor(x1); + logNode.frame!.y = logNode.depth! * LOG_STRUCT_HEIGHT; + logNode.frame!.width = Math.ceil(getV); + logNode.frame!.height = LOG_STRUCT_HEIGHT; + } + + static draw(ctx: CanvasRenderingContext2D, logData: LogStruct): void { + if (logData.depth === undefined || logData.depth === null) { + return; + } + if (logData.frame) { + ctx.globalAlpha = 1; + ctx.fillStyle = ColorUtils.getHilogColor(logData.level!); + ctx.fillRect(logData.frame.x, logData.frame.y, logData.frame.width, LOG_STRUCT_HEIGHT - Y_PADDING); + } + } + + static isSelected(data: LogStruct): boolean { + return ( + LogStruct.selectLogStruct !== undefined && + LogStruct.selectLogStruct.startTs === data.startTs && + LogStruct.selectLogStruct.depth === data.depth + ); + } +} -- Gitee From 8c2f3e6dc77e7dde2505216cf54d3a9863b04581 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:20:43 +0800 Subject: [PATCH 07/18] =?UTF-8?q?=E2=80=99Feat:=E7=81=AB=E7=84=B0=E5=9B=BE?= =?UTF-8?q?=E7=82=B9=E5=87=BB=E9=80=BB=E8=BE=91=E8=B0=83=E6=95=B4=EF=BC=8C?= =?UTF-8?q?=E8=AF=A6=E6=83=85=E5=B1=95=E5=BC=80=E6=98=BE=E7=A4=BA=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E6=A0=88=E5=8A=9F=E8=83=BD=E2=80=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- ide/src/trace/bean/FrameChartStruct.ts | 160 +-- ide/src/trace/bean/PerfProfile.ts | 1 - ide/src/trace/component/chart/FrameChart.ts | 930 ++++++++++-------- .../sheet/file-system/TabPaneCallTree.ts | 7 +- .../trace/sheet/hiperf/TabPerfProfile.ts | 10 +- .../sheet/native-memory/TabPaneNMCallTree.ts | 4 +- .../ProcedureLogicWorkerCommon.ts | 12 +- .../logic-worker/ProcedureLogicWorkerPerf.ts | 11 +- 8 files changed, 606 insertions(+), 529 deletions(-) diff --git a/ide/src/trace/bean/FrameChartStruct.ts b/ide/src/trace/bean/FrameChartStruct.ts index 336f8b4f..507e32d7 100644 --- a/ide/src/trace/bean/FrameChartStruct.ts +++ b/ide/src/trace/bean/FrameChartStruct.ts @@ -16,10 +16,11 @@ import { SpApplication } from '../SpApplication.js'; import { BaseStruct } from './BaseStruct.js'; import { Rect } from '../component/trace/timer-shaft/Rect.js'; -import { info, warn } from '../../log/Log.js'; +import { warn } from '../../log/Log.js'; import { drawString } from '../database/ui-worker/ProcedureWorkerCommon.js'; const padding: number = 1; +const rectHeight = 20; const lightBlue = { r: 82, g: 145, @@ -31,23 +32,30 @@ export class ChartStruct extends BaseStruct { static hoverFuncStruct: ChartStruct | undefined; static selectFuncStruct: ChartStruct | undefined; static lastSelectFuncStruct: ChartStruct | undefined; - needShow = false; - isDraw = false; + isDraw = false; // 是否绘制,太小的不绘制 depth: number = 0; symbol: string = ''; lib: string = ''; - size: number = 0; - count: number = 0; - dur: number = 0; + + size: number = 0; // 实际size + count: number = 0; // 实际count + dur: number = 0; // 实际dur + //搜索后会根据搜索匹配的函数的值赋值给parent + searchSize: number = 0; // + searchCount: number = 0; + searchDur: number = 0; + //点击绘制的size在搜索的基础上,赋值给parent drawSize: number = 0; drawCount: number = 0; drawDur: number = 0; + parent: ChartStruct | undefined; children: Array = []; - percent: number = 0; + percent: number = 0; // 0 - 1 该node所占整体的百分比 addr: string = ''; isSearch: boolean = false; - textMetricsWidth: number | undefined; + isChartSelect: boolean = false; // 是否为点选的调用链 + isChartSelectParent: boolean = false; // 用来显示灰色 } export enum ChartMode { @@ -56,106 +64,106 @@ export enum ChartMode { Duration, // eBpf } -export function setFuncFrame(node: ChartStruct, canvas_frame: Rect, total: number, mode: ChartMode) { +export function setFuncFrame(node: ChartStruct, canvasFrame: Rect, total: number, mode: ChartMode): void { if (!node.frame) { node.frame = new Rect(0, 0, 0, 0); } // filter depth is 0 if (node.parent) { let idx = node.parent.children.indexOf(node); - if (idx == 0) { + if (idx === 0) { node.frame!.x = node.parent.frame!.x; } else { // set x by left frame. left frame is parent.children[idx - 1] node.frame.x = node.parent.children[idx - 1].frame!.x + node.parent.children[idx - 1].frame!.width; } - switch (mode) { - case ChartMode.Byte: - node.frame!.width = Math.floor(((node.drawSize || node.size) / total) * canvas_frame.width); - break; - case ChartMode.Count: - node.frame!.width = Math.floor(((node.drawCount || node.count) / total) * canvas_frame.width); - break; - case ChartMode.Duration: - node.frame!.width = Math.floor(((node.drawDur || node.dur) / total) * canvas_frame.width); - break; - default: - warn('not match ChartMode'); + if (node.parent?.isChartSelect && !node.isChartSelect) { + node.frame!.width = 0; + } else { + switch (mode) { + case ChartMode.Byte: + node.frame!.width = Math.floor(((node.drawSize || node.size) / total) * canvasFrame.width); + break; + case ChartMode.Count: + node.frame!.width = Math.floor(((node.drawCount || node.count) / total) * canvasFrame.width); + break; + case ChartMode.Duration: + node.frame!.width = Math.floor(((node.drawDur || node.dur) / total) * canvasFrame.width); + break; + default: + warn('not match ChartMode'); + } } - node.frame!.y = node.parent.frame!.y + 20; - node.frame!.height = 20; + + node.frame!.y = node.parent.frame!.y + rectHeight; + node.frame!.height = rectHeight; } } /** * draw rect - * @param frameChartBeanCanvasCtx CanvasRenderingContext2D - * @param frameChartBeanData rect which is need draw + * @param canvasCtx CanvasRenderingContext2D + * @param node rect which is need draw * @param percent function size or count / total size or count */ -export function draw(frameChartBeanCanvasCtx: CanvasRenderingContext2D, frameChartBeanData: ChartStruct) { +export function draw(canvasCtx: CanvasRenderingContext2D, node: ChartStruct): void { let spApplication = document.getElementsByTagName('sp-application')[0]; - if (frameChartBeanData.frame) { - // draw rect - let frameChartMiniHeight = 20; - if (isSelected(frameChartBeanData)) { - frameChartBeanCanvasCtx.fillStyle = `rgba(${lightBlue.r}, ${lightBlue.g}, ${lightBlue.b}, ${lightBlue.a})`; + if (!node.frame) { + return; + } + //主体 + const drawHeight = rectHeight - padding * 2; //绘制方块上下留一个像素 + if (node.depth === 0 || (node.isChartSelectParent && node !== ChartStruct.selectFuncStruct)) { + canvasCtx.fillStyle = `rgba(${lightBlue.g}, ${lightBlue.g}, ${lightBlue.g}, ${lightBlue.a})`; + } else { + if (node.isSearch) { + canvasCtx.fillStyle = `rgba(${lightBlue.r}, ${lightBlue.g}, ${lightBlue.b}, ${lightBlue.a})`; } else { - let color = getHeatColor(frameChartBeanData.percent); - frameChartBeanCanvasCtx.fillStyle = `rgba(${color.r}, ${color.g}, ${color.b}, 0.9)`; + canvasCtx.fillStyle = getHeatColor(node.percent); } - frameChartBeanCanvasCtx.fillRect(frameChartBeanData.frame.x, frameChartBeanData.frame.y, frameChartBeanData.frame.width, frameChartMiniHeight - padding * 2); - //draw border - frameChartBeanCanvasCtx.lineWidth = 0.4; - if (isHover(frameChartBeanData)) { - if (spApplication.dark) { - frameChartBeanCanvasCtx.strokeStyle = '#fff'; - } else { - frameChartBeanCanvasCtx.strokeStyle = '#000'; - } + } + canvasCtx.fillRect(node.frame.x, node.frame.y, node.frame.width, drawHeight); + //边框 + canvasCtx.lineWidth = 0.4; + if (isHover(node)) { + if (spApplication.dark) { + canvasCtx.strokeStyle = '#fff'; } else { - if (spApplication.dark) { - frameChartBeanCanvasCtx.strokeStyle = '#000'; - } else { - frameChartBeanCanvasCtx.strokeStyle = '#fff'; - } - if (frameChartBeanData.isSearch) { - frameChartBeanCanvasCtx.strokeStyle = `rgb(${lightBlue.r}, ${lightBlue.g}, ${lightBlue.b})`; - frameChartBeanCanvasCtx.lineWidth = 1; - } + canvasCtx.strokeStyle = '#000'; } - frameChartBeanCanvasCtx.strokeRect(frameChartBeanData.frame.x, frameChartBeanData.frame.y, frameChartBeanData.frame.width, frameChartMiniHeight - padding * 2); - - //draw symbol name - if (frameChartBeanData.frame.width > 10) { - if (frameChartBeanData.percent > 0.6 || isSelected(frameChartBeanData)) { - frameChartBeanCanvasCtx.fillStyle = '#fff'; - } else { - frameChartBeanCanvasCtx.fillStyle = '#000'; - } - drawString(frameChartBeanCanvasCtx, frameChartBeanData.symbol || '', 5, frameChartBeanData.frame, frameChartBeanData); + } else { + if (spApplication.dark) { + canvasCtx.strokeStyle = '#000'; + } else { + canvasCtx.strokeStyle = '#fff'; } - frameChartBeanData.isDraw = true; } + canvasCtx.strokeRect(node.frame.x, node.frame.y, node.frame.width, drawHeight); + //文字 + if (node.frame.width > 10) { + if (node.percent > 0.6 || node.isSearch) { + canvasCtx.fillStyle = '#fff'; + } else { + canvasCtx.fillStyle = '#000'; + } + drawString(canvasCtx, node.symbol || '', 5, node.frame, node); + } + node.isDraw = true; } /** - * get frame chart color by percent - * @param widthPercentage proportion of function + * 火焰图颜色计算,根据每个node占总大小的百分比调整 + * @param widthPercentage 百分比 * @returns rbg */ -function getHeatColor(widthPercentage: number) { - return { - r: Math.floor(245 + 10 * (1 - widthPercentage)), - g: Math.floor(110 + 105 * (1 - widthPercentage)), - b: 100, - }; +function getHeatColor(widthPercentage: number): string { + return `rgba( + ${Math.floor(245 + 10 * (1 - widthPercentage))}, + ${Math.floor(110 + 105 * (1 - widthPercentage))}, + ${100}, + 0.9)`; } function isHover(data: ChartStruct): boolean { - return ChartStruct.hoverFuncStruct == data; -} - -function isSelected(data: ChartStruct): boolean { - return ChartStruct.lastSelectFuncStruct == data; + return ChartStruct.hoverFuncStruct === data; } diff --git a/ide/src/trace/bean/PerfProfile.ts b/ide/src/trace/bean/PerfProfile.ts index 4cb49d2e..c2482bfb 100644 --- a/ide/src/trace/bean/PerfProfile.ts +++ b/ide/src/trace/bean/PerfProfile.ts @@ -78,7 +78,6 @@ export class PerfCallChainMerageData extends ChartStruct { tid: number = 0; pid: number = 0; currentTreeParentNode: PerfCallChainMerageData | undefined = undefined; - symbolName: string = ''; libName: string = ''; symbol: string = ''; path: string = ''; diff --git a/ide/src/trace/component/chart/FrameChart.ts b/ide/src/trace/component/chart/FrameChart.ts index f2e1a6c3..6ac93f86 100644 --- a/ide/src/trace/component/chart/FrameChart.ts +++ b/ide/src/trace/component/chart/FrameChart.ts @@ -20,16 +20,18 @@ import { SpApplication } from '../../SpApplication.js'; import { Utils } from '../trace/base/Utils.js'; import { SpHiPerf } from './SpHiPerf.js'; -const TAG: string = 'FrameChart'; -const scaleHeight = 30; -const depthHeight = 20; -const filterPixel = 2; -const sideLength = 8; - -class Module { +const scaleHeight = 30; // 刻度尺高度 +const depthHeight = 20; // 调用栈高度 +const filterPixel = 2; // 过滤像素 +const textMaxWidth = 50; +const scaleRatio = 0.2; // 缩放比例 +const ms10 = 10_000_000; + +class NodeValue { size: number; count: number; dur: number; + constructor() { this.size = 0; this.count = 0; @@ -39,34 +41,26 @@ class Module { @element('tab-framechart') export class FrameChart extends BaseElement { - private canvas: HTMLCanvasElement | undefined | null; - private canvasContext: CanvasRenderingContext2D | undefined | null; - private floatHint: HTMLDivElement | undefined | null; + private canvas!: HTMLCanvasElement; + private canvasContext!: CanvasRenderingContext2D; + private floatHint!: HTMLDivElement | undefined | null; // 悬浮框 private rect: Rect = new Rect(0, 0, 0, 0); private _mode = ChartMode.Byte; - private startX = 0; // canvas start x coord - private startY = 0; // canvas start y coord - private canvasX = -1; // canvas current x - private canvasY = -1; // canvas current y - private hintContent = ''; // float hint inner html content - - private historyList: Array> = []; - private currentSize = 0; - private currentCount = 0; - private currentDuration = 0; - + private startX = 0; // 画布相对于整个界面的x坐标 + private startY = 0; // 画布相对于整个界面的y坐标 + private canvasX = -1; // 鼠标当前所在画布位置x坐标 + private canvasY = -1; // 鼠标当前所在画布位置y坐标 + private hintContent = ''; // 悬浮框内容。 html格式字符串 + private rootNode!: ChartStruct; private currentData: Array = []; private xPoint = 0; // x in rect - private isFocusing = false; - private canvasScrollTop = 0; + private isFocusing = false; // 鼠标是否在画布范围内 + private canvasScrollTop = 0; // Tab页上下滚动位置 private _maxDepth = 0; private chartClickListenerList: Array = []; private isUpdateCanvas = false; - - static get observedAttributes() { - return []; - } + private isClickMode = false; //是否为点选模式 /** * set chart mode @@ -76,27 +70,41 @@ export class FrameChart extends BaseElement { this._mode = mode; } - set data(val: Array | any) { - this.historyList = []; + set data(val: Array) { ChartStruct.lastSelectFuncStruct = undefined; + this.setSelectStatusRecursive(ChartStruct.selectFuncStruct, true); + ChartStruct.selectFuncStruct = undefined; + this.currentData = val; this.resetTrans(); this.calDrawArgs(true); - for (let callback of this.chartClickListenerList) { - callback(true); - } } set tabPaneScrollTop(scrollTop: number) { this.canvasScrollTop = scrollTop; - this.hideFloatHint(); + this.hideTip(); + } + + private get total(): number { + return this.getNodeValue(this.rootNode); + } + + private getNodeValue(node: ChartStruct): number { + switch (this._mode) { + case ChartMode.Byte: + return node.drawSize || node.size; + case ChartMode.Count: + return node.drawCount || node.count; + case ChartMode.Duration: + return node.drawDur || node.dur; + } } /** * add callback of chart click * @param callback function of chart click */ - public addChartClickListener(callback: Function) { + public addChartClickListener(callback: Function): void { if (this.chartClickListenerList.indexOf(callback) < 0) { this.chartClickListenerList.push(callback); } @@ -106,82 +114,164 @@ export class FrameChart extends BaseElement { * remove callback of chart click * @param callback function of chart click */ - public removeChartClickListener(callback: Function) { - let index = this.chartClickListenerList.indexOf(callback); + public removeChartClickListener(callback: Function): void { + const index = this.chartClickListenerList.indexOf(callback); if (index > -1) { this.chartClickListenerList.splice(index, 1); } } + private createRootNode(): void { + // 初始化root + this.rootNode = new ChartStruct(); + this.rootNode.symbol = 'root'; + this.rootNode.depth = 0; + this.rootNode.percent = 1; + this.rootNode.frame = new Rect(0, scaleHeight, this.canvas!.width, depthHeight); + for (const node of this.currentData!) { + this.rootNode.children.push(node); + this.rootNode.count += node.drawCount || node.count; + this.rootNode.size += node.drawSize || node.size; + this.rootNode.dur += node.drawDur || node.dur; + node.parent = this.rootNode; + } + } + /** - * cal total count size and max Depth - * @param isCalRoot use depth 1 node to cal depth 0 node size/count/dur + * 1.计算调用栈最大深度 + * 2.计算搜索情况下每个函数块显示的大小(非实际大小) + * 3.计算点选情况下每个函数块的显示大小(非实际大小) + * @param initRoot 是否初始化root节点 */ - private calDrawArgs(isCalRoot: boolean): void { - this.currentCount = 0; - this.currentSize = 0; - this.currentDuration = 0; + private calDrawArgs(initRoot: boolean): void { this._maxDepth = 0; - for (let rootNode of this.currentData!) { - let depth = 0; - this.calMaxDepth(rootNode, depth, isCalRoot, true); - this.currentCount += rootNode.drawCount || rootNode.count; - this.currentSize += rootNode.drawSize || rootNode.size; - this.currentDuration += rootNode.drawDur || rootNode.dur; + if (initRoot) { + this.createRootNode(); } + this.initData(this.rootNode, 0, true); + this.selectInit(); + this.setRootValue(); this.rect.width = this.canvas!.width; - this.rect.height = (this._maxDepth + 1) * 20 + scaleHeight; // 20px/depth and 30 is scale height - this.canvas!.style.height = this.rect!.height + 'px'; + this.rect.height = (this._maxDepth + 1) * depthHeight + scaleHeight; + this.canvas!.style.height = `${this.rect!.height}px`; this.canvas!.height = Math.ceil(this.rect!.height); } /** - * cal max Depth - * @param node every child node - * @param depth current depth - * @param isCalRoot use depth 1 node to cal depth 0 node size/count/dur + * 点选情况下由点选来设置每个函数的显示Size + */ + private selectInit(): void { + const node = ChartStruct.selectFuncStruct; + if (node) { + const module = new NodeValue(); + node.drawCount = 0; + node.drawDur = 0; + node.drawSize = 0; + for (let child of node.children) { + node.drawCount += child.searchCount; + node.drawDur += child.searchDur; + node.drawSize += child.searchSize; + } + module.count = node.drawCount = node.drawCount || node.count; + module.dur = node.drawDur = node.drawDur || node.dur; + module.size = node.drawSize = node.drawSize || node.size; + + this.setParentDisplayInfo(node, module, true); + this.setChildrenDisplayInfo(node); + } + } + + // 设置root显示区域value 以及占真实value的百分比 + private setRootValue(): void { + let currentValue = ''; + let currentValuePercent = 1; + switch (this._mode) { + case ChartMode.Byte: + currentValue = Utils.getBinaryByteWithUnit(this.total); + currentValuePercent = this.total / this.rootNode.size; + break; + case ChartMode.Count: + currentValue = Utils.timeMsFormat2p(this.total * (SpHiPerf.stringResult?.fValue || 1)); + currentValuePercent = this.total / this.rootNode.count; + break; + case ChartMode.Duration: + currentValue = Utils.getProbablyTime(this.total); + currentValuePercent = this.total / this.rootNode.dur; + break; + } + this.rootNode.symbol = `Root : ${currentValue} (${(currentValuePercent * 100).toFixed(2)}%)`; + } + + /** + * 计算调用栈最大深度,计算每个node显示大小 + * @param node 函数块 + * @param depth 当前递归深度 + * @param calDisplay 该层深度是否需要计算显示大小 */ - private calMaxDepth(node: ChartStruct, depth: number, isCalRoot: boolean, isCalDisplay: boolean): void { + private initData(node: ChartStruct, depth: number, calDisplay: boolean): void { node.depth = depth; + depth++; + //设置搜索以及点选的显示值,将点击/搜索的值设置为父节点的显示值 this.clearDisplayInfo(node); - if (node.isSearch && isCalDisplay) { - let module = new Module(); - module.count = node.drawCount = node.count; - module.dur = node.drawDur = node.dur; - module.size = node.drawSize = node.size; - this.setParentDisplayInfo(node, module); - isCalDisplay = false; + if (node.isSearch && calDisplay) { + const module = new NodeValue(); + module.size = node.drawSize = node.searchSize = node.size; + module.count = node.drawCount = node.searchCount = node.count; + module.dur = node.drawDur = node.searchDur = node.dur; + this.setParentDisplayInfo(node, module, false); + calDisplay = false; } - depth++; + // 设置parent以及计算最大的深度 if (node.children && node.children.length > 0) { - let parentSize, parentCount, parentDuration; - parentSize = parentCount = parentDuration = 0; - for (let children of node.children) { + for (const children of node.children) { children.parent = node; - if (node.depth == 0 && isCalRoot) { - parentSize += children.size; - parentCount += children.count; - parentDuration += children.dur; - } - this.calMaxDepth(children, depth, isCalRoot, isCalDisplay); - } - if (node.depth == 0 && isCalRoot) { - node.size = parentSize; - node.count = parentCount; - node.dur = parentDuration; + this.initData(children, depth, calDisplay); } } else { this._maxDepth = Math.max(depth, this._maxDepth); } } - private setParentDisplayInfo(node: ChartStruct, module: Module): void { - if (node.parent) { - node.parent.drawCount += module.count; - node.parent.drawDur += module.dur; - node.parent.drawSize += module.size; - this.setParentDisplayInfo(node.parent, module); + // 递归设置node parent的显示大小 + private setParentDisplayInfo(node: ChartStruct, module: NodeValue, isSelect?: boolean): void { + const parent = node.parent; + if (parent) { + if (isSelect) { + parent.isChartSelect = true; + parent.isChartSelectParent = true; + parent.drawCount = module.count; + parent.drawDur = module.dur; + parent.drawSize = module.size; + } else { + parent.searchCount += module.count; + parent.searchDur += module.dur; + parent.searchSize += module.size; + // 点击模式下不需要赋值draw value,由点击去 + if (!this.isClickMode) { + parent.drawDur = parent.searchDur; + parent.drawCount = parent.searchCount; + parent.drawSize = parent.searchSize; + } + } + this.setParentDisplayInfo(parent, module, isSelect); + } + } + + /** + * 点击与搜索同时触发情况下,由点击去设置绘制大小 + * @param node 当前点选的函数 + * @returns void + */ + private setChildrenDisplayInfo(node: ChartStruct): void { + if (node.children.length < 0) { + return; + } + for (const children of node.children) { + children.drawCount = children.searchCount || children.count; + children.drawDur = children.searchDur || children.dur; + children.drawSize = children.searchSize || children.size; + this.setChildrenDisplayInfo(children); } } @@ -189,127 +279,44 @@ export class FrameChart extends BaseElement { node.drawCount = 0; node.drawDur = 0; node.drawSize = 0; + node.searchCount = 0; + node.searchDur = 0; + node.searchSize = 0; } /** - * calculate Data and draw chart + * 计算每个函数块的坐标信息以及绘制火焰图 */ - public async calculateChartData() { + public async calculateChartData(): Promise { this.clearCanvas(); this.canvasContext?.beginPath(); - this.drawScale(); - let x = this.xPoint; - switch (this._mode) { - case ChartMode.Byte: - for (let node of this.currentData!) { - let nodeSize = node.drawSize || node.size; - let width = Math.round((nodeSize / this.currentSize) * this.rect!.width); - let nmHeight = depthHeight; // 20px / depth - // ensure the data for first depth frame - if (!node.frame) { - node.frame = new Rect(x, scaleHeight, width, nmHeight); - } else { - node.frame!.x = x; - node.frame!.y = scaleHeight; - node.frame!.width = width; - node.frame!.height = nmHeight; - } - // not draw when rect not in canvas - if (x + width >= 0 && x < this.canvas!.width) { - node.percent = nodeSize / this.currentSize; - draw(this.canvasContext!, node); - } - this.setStructFuncFrame(node); - this.drawFrameChart(node); - x += width; - } - break; - case ChartMode.Count: - for (let node of this.currentData!) { - let nodeCount = node.drawCount || node.count; - let width = Math.round((nodeCount / this.currentCount) * this.rect!.width); - let perfHeight = depthHeight; // 20px / depth - // ensure the data for first depth frame - if (!node.frame) { - node.frame = new Rect(x, scaleHeight, width, perfHeight); - } else { - node.frame!.x = x; - node.frame!.y = scaleHeight; - node.frame!.width = width; - node.frame!.height = perfHeight; - } - // not draw when rect not in canvas - if (x + width >= 0 && x < this.canvas!.width) { - node.percent = nodeCount / this.currentCount; - draw(this.canvasContext!, node); - } - this.setStructFuncFrame(node); - this.drawFrameChart(node); - x += width; - } - break; - case ChartMode.Duration: - for (let node of this.currentData!) { - let nodeDur = node.drawDur || node.dur; - let width = Math.round((nodeDur / this.currentDuration) * this.rect!.width); - let ebpfHeight = depthHeight; // 20px / depth - // ensure the data for first depth frame - if (!node.frame) { - node.frame = new Rect(x, scaleHeight, width, ebpfHeight); - } else { - node.frame!.x = x; - node.frame!.y = scaleHeight; - node.frame!.width = width; - node.frame!.height = ebpfHeight; - } - // not draw when rect not in canvas - if (x + width >= 0 && x < this.canvas!.width) { - node.percent = nodeDur / this.currentDuration; - draw(this.canvasContext!, node); - } - this.setStructFuncFrame(node); - this.drawFrameChart(node); - x += width; - } - break; - } - this.drawTriangleOnScale(); + // 绘制刻度线 + this.drawCalibrationTails(); + // 绘制root节点 + draw(this.canvasContext, this.rootNode); + // 设置子节点的位置以及宽高 + this.setFrameData(this.rootNode); + // 绘制子节点 + this.drawFrameChart(this.rootNode); this.canvasContext?.closePath(); } /** - * draw last selected reset position on scale - */ - private drawTriangleOnScale(): void { - if (ChartStruct.lastSelectFuncStruct) { - this.canvasContext!.fillStyle = `rgba(${82}, ${145}, ${255})`; - let x = Math.ceil(ChartStruct.lastSelectFuncStruct.frame!.x + ChartStruct.lastSelectFuncStruct.frame!.width / 2); - if (x < 0) x = sideLength / 2; - if (x > this.canvas!.width) x = this.canvas!.width - sideLength; - this.canvasContext!.moveTo(x - sideLength / 2, scaleHeight - sideLength); - this.canvasContext!.lineTo(x + sideLength / 2, scaleHeight - sideLength); - this.canvasContext!.lineTo(x, scaleHeight); - this.canvasContext!.lineTo(x - sideLength / 2, scaleHeight - sideLength); - this.canvasContext?.fill(); - } - } - - /** - * clear canvas all data + * 清空画布 */ public clearCanvas(): void { this.canvasContext?.clearRect(0, 0, this.canvas!.width, this.canvas!.height); } /** - * update canvas size + * 在窗口大小变化时调整画布大小 */ public updateCanvas(updateWidth: boolean, newWidth?: number): void { if (this.canvas instanceof HTMLCanvasElement) { - this.canvas.style.width = 100 + '%'; - this.canvas.style.height = this.rect!.height + 'px'; - if (this.canvas.clientWidth == 0 && newWidth) { - this.canvas.width = newWidth - 40; + this.canvas.style.width = `${100}%`; + this.canvas.style.height = `${this.rect!.height}px`; + if (this.canvas.clientWidth === 0 && newWidth) { + this.canvas.width = newWidth - depthHeight * 2; } else { this.canvas.width = this.canvas.clientWidth; } @@ -317,9 +324,9 @@ export class FrameChart extends BaseElement { this.updateCanvasCoord(); } if ( - this.rect.width == 0 || + this.rect.width === 0 || updateWidth || - Math.round(newWidth!) != this.canvas!.width + 40 || + Math.round(newWidth!) !== this.canvas!.width + depthHeight * 2 || newWidth! > this.rect.width ) { this.rect.width = this.canvas!.width; @@ -327,14 +334,14 @@ export class FrameChart extends BaseElement { } /** - * updateCanvasCoord + * 更新画布坐标 */ private updateCanvasCoord(): void { if (this.canvas instanceof HTMLCanvasElement) { - this.isUpdateCanvas = this.canvas.clientWidth != 0; + this.isUpdateCanvas = this.canvas.clientWidth !== 0; if (this.canvas.getBoundingClientRect()) { - let box = this.canvas.getBoundingClientRect(); - let D = document.documentElement; + const box = this.canvas.getBoundingClientRect(); + const D = document.documentElement; this.startX = box.left + Math.max(D.scrollLeft, document.body.scrollLeft) - D.clientLeft; this.startY = box.top + Math.max(D.scrollTop, document.body.scrollTop) - D.clientTop + this.canvasScrollTop; } @@ -342,28 +349,26 @@ export class FrameChart extends BaseElement { } /** - * draw top Scale Into 100 piece + * 绘制刻度尺,分为100段,每10段画一条长线 */ - private drawScale(): void { - let spApplication = document.getElementsByTagName('sp-application')[0]; - // line + private drawCalibrationTails(): void { + const spApplication = document.getElementsByTagName('sp-application')[0]; this.canvasContext!.lineWidth = 0.5; this.canvasContext?.moveTo(0, 0); this.canvasContext?.lineTo(this.canvas!.width, 0); - for (let i = 0; i <= 10; i++) { let startX = Math.floor((this.canvas!.width / 10) * i); for (let j = 0; j < 10; j++) { - // children scale this.canvasContext!.lineWidth = 0.5; - let startItemX = startX + Math.floor((this.canvas!.width / 100) * j); + const startItemX = startX + Math.floor((this.canvas!.width / 100) * j); this.canvasContext?.moveTo(startItemX, 0); this.canvasContext?.lineTo(startItemX, 10); } - if (i == 0) continue; // skip first Size is 0 - // long line every 10 count + if (i === 0) { + continue; + } this.canvasContext!.lineWidth = 1; - let sizeRatio = this.canvas!.width / this.rect.width; // scale ratio + const sizeRatio = this.canvas!.width / this.rect.width; // scale ratio if (spApplication.dark) { this.canvasContext!.strokeStyle = '#888'; } else { @@ -376,108 +381,119 @@ export class FrameChart extends BaseElement { } else { this.canvasContext!.fillStyle = '#000'; } - let scale = ''; + let calibration = ''; switch (this._mode) { case ChartMode.Byte: - scale = Utils.getByteWithUnit(((this.currentSize * sizeRatio) / 10) * i); + calibration = Utils.getByteWithUnit(((this.total * sizeRatio) / 10) * i); break; case ChartMode.Count: - scale = Utils.timeMsFormat2p( - (((this.currentCount * (SpHiPerf.stringResult?.fValue || 1)) * sizeRatio) / 10) * i + //count 转化为时间 + calibration = Utils.timeMsFormat2p( + ((this.total * (SpHiPerf.stringResult?.fValue || 1) * sizeRatio) / 10) * i ); break; case ChartMode.Duration: - scale = Utils.getProbablyTime(((this.currentDuration * sizeRatio) / 10) * i); + calibration = Utils.getProbablyTime(((this.total * sizeRatio) / 10) * i); break; } - let size = this.canvasContext!.measureText(scale).width; - this.canvasContext?.fillText(scale, startX - size - 5, depthHeight, 50); // 50 is Text max Length + const size = this.canvasContext!.measureText(calibration).width; + this.canvasContext?.fillText(calibration, startX - size - 5, depthHeight, textMaxWidth); this.canvasContext?.stroke(); } } - private setStructFuncFrame(node: ChartStruct) { - if (node.children && node.children.length > 0) { - for (let children of node.children) { + /** + * 设置每个node的宽高,开始坐标 + * @param node 函数块 + */ + private setFrameData(node: ChartStruct): void { + if (node.children.length > 0) { + for (const children of node.children) { node.isDraw = false; - children.parent = node; - switch (this._mode) { - case ChartMode.Byte: - let childrenSize = children.drawSize || children.size; - setFuncFrame(children, this.rect, this.currentSize, this._mode); - children.percent = childrenSize / this.currentSize; - break; - case ChartMode.Count: - let childrenCount = children.drawCount || children.count; - setFuncFrame(children, this.rect, this.currentCount, this._mode); - children.percent = childrenCount / this.currentCount; - break; - case ChartMode.Duration: - let childrenDur = children.drawDur || children.dur; - setFuncFrame(children, this.rect, this.currentDuration, this._mode); - children.percent = childrenDur / this.currentDuration; - break; + if (this.isClickMode && ChartStruct.selectFuncStruct) { + //处理点击逻辑,当前node为点选调用栈,children不是点选调用栈,width置为0 + if (!children.isChartSelect) { + if (children.frame) { + children.frame.x = this.rootNode.frame?.x || 0; + children.frame.width = 0; + children.percent = 0; + } else { + children.frame = new Rect(0, 0, 0, 0); + } + this.setFrameData(children); + continue; + } } - this.setStructFuncFrame(children); + const childrenValue = this.getNodeValue(children); + setFuncFrame(children, this.rect, this.total, this._mode); + children.percent = childrenValue / this.total; + this.setFrameData(children); } } } /** - * draw chart - * @param node draw chart by every piece + * 计算有效数据,当node的宽度太小不足以绘制时 + * 计算忽略node的size + * 忽略的size将转换成width,按照比例平摊到显示的node上 + * @param node 当前node + * @param effectChildList 生效的node */ - private drawFrameChart(node: ChartStruct) { - let effectChildList = []; - let nodeSize = node.drawSize || node.size; - let nodeCount = node.drawCount || node.count; - let nodeDur = node.drawDur || node.dur; - let ignoreSize, ignoreCount, ignoreDur; - ignoreSize = ignoreCount = ignoreDur = 0; - - if (node.children && node.children.length > 0) { - for (let children of node.children) { - // not draw when rect not in canvas - if ( - (children.frame!.x + children.frame!.width >= 0 && //less than canvas left - children.frame!.x < this.canvas!.width && // more than canvas right - children.frame!.width > filterPixel) || // filter px - children.needShow - ) { - // click and back - effectChildList.push(children); + private calEffectNode(node: ChartStruct, effectChildList: Array): number { + const ignore = new NodeValue(); + for (const children of node.children) { + // 小于1px的不绘制,并将其size平均赋值给>1px的 + if (children.frame!.width >= filterPixel) { + effectChildList.push(children); + } else { + if (node.isChartSelect || node.isSearch) { + ignore.size += children.drawSize; + ignore.count += children.drawCount; + ignore.dur += children.drawDur; } else { - ignoreSize += children.drawSize || children.size; - ignoreCount += children.drawCount || children.count; - ignoreDur += children.drawDur || children.dur; + ignore.size += children.size; + ignore.count += children.count; + ignore.dur += children.dur; } } + } + switch (this._mode) { + case ChartMode.Byte: + return ignore.size; + case ChartMode.Count: + return ignore.count; + case ChartMode.Duration: + return ignore.dur; + } + } + + /** + * 绘制每个函数色块 + * @param node 函数块 + */ + private drawFrameChart(node: ChartStruct): void { + const effectChildList: Array = []; + const nodeValue = this.getNodeValue(node); + + if (node.children && node.children.length > 0) { + const ignoreValue = this.calEffectNode(node, effectChildList); let x = node.frame!.x; if (effectChildList.length > 0) { for (let children of effectChildList) { children.frame!.x = x; - switch (this._mode) { - case ChartMode.Byte: - let childSize = children.drawSize || children.size; - children.frame!.width = (childSize / (nodeSize - ignoreSize)) * node.frame!.width; - break; - case ChartMode.Count: - let childCount = children.drawCount || children.count; - children.frame!.width = (childCount / (nodeCount - ignoreCount)) * node.frame!.width; - break; - case ChartMode.Duration: - let childDur = children.drawDur || children.dur; - children.frame!.width = (childDur / (nodeDur - ignoreDur)) * node.frame!.width; - break; - } + const childrenValue = this.getNodeValue(children); + children.frame!.width = (childrenValue / (nodeValue - ignoreValue)) * node.frame!.width; x += children.frame!.width; - draw(this.canvasContext!, children); - this.drawFrameChart(children); + if (this.nodeInCanvas(children)) { + draw(this.canvasContext!, children); + this.drawFrameChart(children); + } } } else { - let firstChildren = node.children[0]; + const firstChildren = node.children[0]; firstChildren.frame!.x = node.frame!.x; - firstChildren.frame!.width = node.frame!.width; + // perf parent有selfTime 需要所有children的count跟 + firstChildren.frame!.width = node.frame!.width * (ignoreValue / nodeValue); draw(this.canvasContext!, firstChildren); this.drawFrameChart(firstChildren); } @@ -485,20 +501,23 @@ export class FrameChart extends BaseElement { } /** - * find target node from tree by mouse position + * 根据鼠标当前的坐标递归查找对应的函数块 * - * @param nodes tree nodes - * @param canvasX x coord of canvas - * @param canvasY y coord of canvas - * @returns target node + * @param nodes + * @param canvasX 鼠标相对于画布开始点的x坐标 + * @param canvasY 鼠标相对于画布开始点的y坐标 + * @returns 当前鼠标位置的函数块 */ - private searchData(nodes: Array, canvasX: number, canvasY: number): any { - for (let node of nodes) { + private searchDataByCoord(nodes: Array, canvasX: number, canvasY: number): ChartStruct | null { + for (const node of nodes) { if (node.frame?.contains(canvasX, canvasY)) { return node; } else { - let result = this.searchData(node.children, canvasX, canvasY); - if (!result) continue; // if not found in this branch;search another branch + const result = this.searchDataByCoord(node.children, canvasX, canvasY); + // if not found in this branch;search another branch + if (!result) { + continue; + } return result; } } @@ -506,74 +525,125 @@ export class FrameChart extends BaseElement { } /** - * show float hint and update position + * 显示悬浮框信息,更新位置 */ - private updateFloatHint(): void { + private showTip(): void { this.floatHint!.innerHTML = this.hintContent; this.floatHint!.style.display = 'block'; let x = this.canvasX; let y = this.canvasY - this.canvasScrollTop; - //right rect hint show left + //右边的函数块悬浮框显示在函数左边 if (this.canvasX + this.floatHint!.clientWidth > (this.canvas?.clientWidth || 0)) { x -= this.floatHint!.clientWidth - 1; } else { x += scaleHeight; } - //bottom rect hint show top + //最下边函数块悬浮框显示在函数上边 y -= this.floatHint!.clientHeight - 1; this.floatHint!.style.transform = `translate(${x}px,${y}px)`; } /** - * redraw Chart while click to scale chart - * @param selectData select Rect data as array + * 递归设置传入node的parent以及children的isSelect + * 将上次点选的整条树的isSelect置为false + * 将本次点击的整条树的isSelect置为true + * @param node 点击的node + * @param isSelect 点选 */ - private redrawChart(selectData: Array): void { - this.currentData = selectData; - if (selectData.length == 0) return; + private setSelectStatusRecursive(node: ChartStruct | undefined, isSelect: boolean): void { + if (!node) { + return; + } + node.isChartSelect = isSelect; + + // 处理子节点及其子节点的子节点 + const stack: ChartStruct[] = [node]; // 使用栈来实现循环处理 + while (stack.length > 0) { + const currentNode = stack.pop(); + if (currentNode) { + currentNode.children.forEach((child) => { + child.isChartSelect = isSelect; + stack.push(child); + }); + } + } + + // 处理父节点 + while (node?.parent) { + node.parent.isChartSelect = isSelect; + node.parent.isChartSelectParent = isSelect; + node = node.parent; + } + } + + /** + * 判断当前node的整条调用栈都与之前点击node的相同 + * 则认为是上次选择的node + * @param data 每一个函数node + * @returns 是否为点选的那个node + */ + private isSelectedNode(data: ChartStruct): boolean { + let select = ChartStruct.selectFuncStruct; + while (data?.parent && select?.parent) { + if ( + select?.depth === data.depth && + select.symbol === data.symbol && + select.lib === data.lib && + select.addr === data.addr + ) { + data = data.parent; + select = select.parent; + } else { + return false; + } + } + return !data.parent && !select?.parent; + } + + /** + * 点选后重绘火焰图 + */ + private clickRedraw(): void { + //将上次点选的isSelect置为false + if (ChartStruct.lastSelectFuncStruct) { + this.setSelectStatusRecursive(ChartStruct.lastSelectFuncStruct!, false); + } + // 递归设置点选的parent,children为点选状态 + this.setSelectStatusRecursive(ChartStruct.selectFuncStruct!, true); + this.calDrawArgs(false); this.calculateChartData(); } /** - * press w to zoom in, s to zoom out - * @param index < 0 zoom out , > 0 zoom in + * 点击w s的放缩算法 + * @param index < 0 缩小 , > 0 放大 */ private scale(index: number): void { let newWidth = 0; - // zoom in - let deltaWidth = this.rect!.width * 0.2; + let deltaWidth = this.rect!.width * scaleRatio; + const ratio = 1 + scaleRatio; if (index > 0) { + // zoom in newWidth = this.rect!.width + deltaWidth; - // max scale - let sizeRatio = this.canvas!.width / this.rect.width; + const sizeRatio = this.canvas!.width / this.rect.width; // max scale switch (this._mode) { case ChartMode.Byte: - //limit 10 byte - if (Math.round((this.currentSize * sizeRatio) / 1.2) <= 10) { - if (this.xPoint == 0) { - return; - } - newWidth = this.canvas!.width / (10 / this.currentSize); - } - break; case ChartMode.Count: - //limit 10 counts - if (Math.round((this.currentCount * sizeRatio) / 1.2) <= 10) { - if (this.xPoint == 0) { + if (Math.round((this.total * sizeRatio) / ratio) <= 10) { + if (this.xPoint === 0) { return; } - newWidth = this.canvas!.width / (10 / this.currentCount); + newWidth = this.canvas!.width / (10 / this.total); } break; case ChartMode.Duration: - //limit 10ms - if (Math.round((this.currentDuration * sizeRatio) / 1.2) <= 10_000_000) { - if (this.xPoint == 0) { + if (Math.round((this.total * sizeRatio) / ratio) <= ms10) { + if (this.xPoint === 0) { return; } - newWidth = this.canvas!.width / (10_000_000 / this.currentDuration); + newWidth = this.canvas!.width / (ms10 / this.total); } break; } @@ -581,7 +651,6 @@ export class FrameChart extends BaseElement { } else { // zoom out newWidth = this.rect!.width - deltaWidth; - // min scale if (newWidth < this.canvas!.width) { newWidth = this.canvas!.width; this.resetTrans(); @@ -589,37 +658,40 @@ export class FrameChart extends BaseElement { deltaWidth = this.rect!.width - newWidth; } // width not change - if (newWidth == this.rect.width) return; + if (newWidth === this.rect.width) { + return; + } this.translationByScale(index, deltaWidth, newWidth); } - private resetTrans() { + private resetTrans(): void { this.xPoint = 0; } /** - * translation after scale - * @param index is zoom in - * @param deltaWidth scale delta width - * @param newWidth rect width after scale + * 放缩之后的平移算法 + * @param index < 0 缩小 , > 0 放大 + * @param deltaWidth 放缩增量 + * @param newWidth 放缩后的宽度 */ private translationByScale(index: number, deltaWidth: number, newWidth: number): void { - let translationValue = (deltaWidth * (this.canvasX - this.xPoint)) / this.rect.width; + const translationValue = (deltaWidth * (this.canvasX - this.xPoint)) / this.rect.width; if (index > 0) { this.xPoint -= translationValue; } else { this.xPoint += translationValue; } this.rect!.width = newWidth; + this.translationDraw(); } /** - * press a/d to translate rect - * @param index left or right + * 点击a d 平移 + * @param index < 0 左移; >0 右移 */ private translation(index: number): void { - let offset = this.canvas!.width / 10; + const offset = this.canvas!.width / 10; if (index < 0) { this.xPoint += offset; } else { @@ -640,71 +712,86 @@ export class FrameChart extends BaseElement { if (this.rect.width + this.xPoint < this.canvas!.width) { this.xPoint = this.canvas!.width - this.rect.width; } + this.rootNode.frame!.width = this.rect.width; + this.rootNode.frame!.x = this.xPoint; this.calculateChartData(); } - /** - * canvas click - * @param e MouseEvent - */ + private nodeInCanvas(node: ChartStruct): boolean { + if (!node.frame) { + return false; + } + return node.frame.x + node.frame.width >= 0 && node.frame.x < this.canvas.clientWidth; + } private onMouseClick(e: MouseEvent): void { - if (e.button == 0) { + if (e.button === 0) { // mouse left button - if (ChartStruct.hoverFuncStruct && ChartStruct.hoverFuncStruct != ChartStruct.selectFuncStruct) { - this.drawDataSet(ChartStruct.lastSelectFuncStruct!, false); - ChartStruct.lastSelectFuncStruct = undefined; + if (ChartStruct.hoverFuncStruct && ChartStruct.hoverFuncStruct !== ChartStruct.selectFuncStruct) { + ChartStruct.lastSelectFuncStruct = ChartStruct.selectFuncStruct; ChartStruct.selectFuncStruct = ChartStruct.hoverFuncStruct; - this.historyList.push(this.currentData!); - let selectData = new Array(); - selectData.push(ChartStruct.selectFuncStruct!); - // reset scale and translation - this.rect.width = this.canvas!.clientWidth; - this.resetTrans(); - this.redrawChart(selectData); - for (let callback of this.chartClickListenerList) { - callback(false); - } - } - } else if (e.button == 2) { - // mouse right button - ChartStruct.selectFuncStruct = undefined; - ChartStruct.hoverFuncStruct = undefined; - if (this.currentData.length == 1 && this.historyList.length > 0) { - ChartStruct.lastSelectFuncStruct = this.currentData[0]; - this.drawDataSet(ChartStruct.lastSelectFuncStruct, true); - } - if (this.historyList.length > 0) { - // reset scale and translation + this.isClickMode = ChartStruct.selectFuncStruct !== this.rootNode; this.rect.width = this.canvas!.clientWidth; + // 重置缩放 this.resetTrans(); - this.redrawChart(this.historyList.pop()!); - } - if (this.historyList.length === 0) { - for (let callback of this.chartClickListenerList) { - callback(true); - } + this.rootNode.frame!.x = this.xPoint; + this.rootNode.frame!.width = this.rect.width = this.canvas.clientWidth; + // 重新绘图 + this.clickRedraw(); } + } else if (e.button === 2) { } - this.hideFloatHint(); + this.hideTip(); } - private hideFloatHint() { + private hideTip(): void { if (this.floatHint) { this.floatHint.style.display = 'none'; } } /** - * set current select rect parents will show - * @param data current node - * @param isShow is show in chart + * 更新悬浮框内容 */ - private drawDataSet(data: ChartStruct, isShow: boolean): void { - if (data) { - data.needShow = isShow; - if (data.parent) { - this.drawDataSet(data.parent, isShow); - } + private updateTipContent(): void { + const hoverNode = ChartStruct.hoverFuncStruct; + if (!hoverNode) { + return; + } + const name = hoverNode?.symbol.replace(//g, '>'); + const percent = ((hoverNode?.percent || 0) * 100).toFixed(2); + switch (this._mode) { + case ChartMode.Byte: + const size = Utils.getByteWithUnit(this.getNodeValue(hoverNode)); + const countPercent = ((this.getNodeValue(hoverNode) / this.total) * 100).toFixed(2); + this.hintContent = ` + Symbol: ${name}
+ Lib: ${hoverNode?.lib}
+ Addr: ${hoverNode?.addr}
+ Size: ${size} (${percent}%)
+ Count: ${hoverNode?.count} (${countPercent}%)`; + break; + case ChartMode.Count: + const count = this.getNodeValue(hoverNode); + const dur = Utils.timeMsFormat2p(count * (SpHiPerf.stringResult?.fValue || 1)); + this.hintContent = ` + Name: ${name}
+ Lib: ${hoverNode?.lib} +
+ Addr: ${hoverNode?.addr} +
+ Dur: ${dur} (${percent}%) +
+ Count: ${count} (${percent}%)`; + break; + case ChartMode.Duration: + const duration = Utils.getProbablyTime(this.getNodeValue(hoverNode)); + this.hintContent = ` + Name: ${name}
+ Lib: ${hoverNode?.lib} +
+ Addr: ${hoverNode?.addr}
+ Duration: ${duration} (${percent}%)<`; + break; } } @@ -712,71 +799,57 @@ export class FrameChart extends BaseElement { * mouse on canvas move event */ private onMouseMove(): void { - let lastNode = ChartStruct.hoverFuncStruct; - let searchResult = this.searchData(this.currentData!, this.canvasX, this.canvasY); - if (searchResult && (searchResult.isDraw || searchResult.needShow || searchResult.depth == 0)) { + const lastNode = ChartStruct.hoverFuncStruct; + // 鼠标移动到root节点不作显示 + const hoverRootNode = this.rootNode.frame?.contains(this.canvasX, this.canvasY); + if (hoverRootNode) { + ChartStruct.hoverFuncStruct = this.rootNode; + return; + } + // 查找鼠标所在那个node上 + const searchResult = this.searchDataByCoord(this.currentData!, this.canvasX, this.canvasY); + if (searchResult && (searchResult.isDraw || searchResult.depth === 0)) { ChartStruct.hoverFuncStruct = searchResult; - // judge current node is hover redraw chart - if (searchResult != lastNode) { - let name = ChartStruct.hoverFuncStruct?.symbol; - switch (this._mode) { - case ChartMode.Byte: - let size = Utils.getByteWithUnit( - ChartStruct.hoverFuncStruct!.drawSize || ChartStruct.hoverFuncStruct!.size - ); - this.hintContent = ` - Symbol: ${name}
- Lib: ${ChartStruct.hoverFuncStruct?.lib}
- Addr: ${ChartStruct.hoverFuncStruct?.addr}
- Size: ${size}
- Count: ${ChartStruct.hoverFuncStruct?.count}`; - break; - case ChartMode.Count: - let count = ChartStruct.hoverFuncStruct!.count; - const dur = Utils.timeMsFormat2p(count * (SpHiPerf.stringResult?.fValue || 1)); - this.hintContent = ` - Name: ${name}
- Lib: ${ChartStruct.hoverFuncStruct?.lib} -
- Addr: ${ChartStruct.hoverFuncStruct?.addr} -
- Dur: ${dur} -
- Count: ${count}`; - break; - case ChartMode.Duration: - let duration = Utils.getProbablyTime(ChartStruct.hoverFuncStruct!.dur); - this.hintContent = ` - Name: ${name}
- Lib: ${ChartStruct.hoverFuncStruct?.lib} -
- Addr: ${ChartStruct.hoverFuncStruct?.addr}
- Duration: ${duration}`; - break; - } + // 悬浮的node未改变,不需要更新悬浮框文字信息,不绘图 + if (searchResult !== lastNode) { + this.updateTipContent(); this.calculateChartData(); } - // prevent float hint trigger onmousemove event - this.updateFloatHint(); + this.showTip(); } else { - this.hideFloatHint(); + this.hideTip(); ChartStruct.hoverFuncStruct = undefined; } } - initElements(): void { - this.canvas = this.shadowRoot?.querySelector('#canvas'); - this.canvasContext = this.canvas?.getContext('2d'); + /** + * 监听页面Size变化 + */ + private listenerResize(): void { + new ResizeObserver(() => { + if (this.canvas!.getBoundingClientRect()) { + const box = this.canvas!.getBoundingClientRect(); + const element = document.documentElement; + this.startX = box.left + Math.max(element.scrollLeft, document.body.scrollLeft) - element.clientLeft; + this.startY = + box.top + Math.max(element.scrollTop, document.body.scrollTop) - element.clientTop + this.canvasScrollTop; + } + }).observe(document.documentElement); + } + + public initElements(): void { + this.canvas = this.shadowRoot!.querySelector('#canvas')!; + this.canvasContext = this.canvas.getContext('2d')!; this.floatHint = this.shadowRoot?.querySelector('#float_hint'); - this.canvas!.oncontextmenu = () => { + this.canvas!.oncontextmenu = (): boolean => { return false; }; - this.canvas!.onmouseup = (e) => { + this.canvas!.onmouseup = (e): void => { this.onMouseClick(e); }; - this.canvas!.onmousemove = (e) => { + this.canvas!.onmousemove = (e): void => { if (!this.isUpdateCanvas) { this.updateCanvasCoord(); } @@ -786,14 +859,15 @@ export class FrameChart extends BaseElement { this.onMouseMove(); }; - this.canvas!.onmouseleave = () => { - ChartStruct.selectFuncStruct = undefined; + this.canvas!.onmouseleave = (): void => { this.isFocusing = false; - this.hideFloatHint(); + this.hideTip(); }; document.addEventListener('keydown', (e) => { - if (!this.isFocusing) return; + if (!this.isFocusing) { + return; + } switch (e.key.toLocaleLowerCase()) { case 'w': this.scale(1); @@ -809,18 +883,10 @@ export class FrameChart extends BaseElement { break; } }); - new ResizeObserver((entries) => { - if (this.canvas!.getBoundingClientRect()) { - let box = this.canvas!.getBoundingClientRect(); - let element = document.documentElement; - this.startX = box.left + Math.max(element.scrollLeft, document.body.scrollLeft) - element.clientLeft; - this.startY = - box.top + Math.max(element.scrollTop, document.body.scrollTop) - element.clientTop + this.canvasScrollTop; - } - }).observe(document.documentElement); + this.listenerResize(); } - initHtml(): string { + public initHtml(): string { return ` - + diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts index 7d4303ff..36e071e2 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts @@ -21,7 +21,6 @@ import { resizeObserver } from '../SheetUtils.js'; import { procedurePool } from '../../../../database/Procedure.js'; import { Utils } from '../../base/Utils.js'; - @element('tabpane-spt') export class TabPaneSPT extends BaseElement { private sptTbl: LitTable | null | undefined; @@ -76,7 +75,7 @@ export class TabPaneSPT extends BaseElement { - + diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneCallTree.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneCallTree.ts index 6e6ea3ee..6b9faaf4 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneCallTree.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneCallTree.ts @@ -599,7 +599,7 @@ export class TabPaneCallTree extends BaseElement {
- + diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts index 20486ddf..32240ede 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts @@ -588,7 +588,7 @@ export class TabpaneFilesystemCalltree extends BaseElement {
- + diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.ts index 642c66dc..8b72134e 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.ts @@ -215,7 +215,7 @@ export class TabPaneFileStatistics extends BaseElement { } - + diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.ts index c70841bf..7ddeae68 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.ts @@ -276,7 +276,7 @@ export class TabPaneIOTierStatistics extends BaseElement { } - + diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatistics.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatistics.ts index 1ae5406f..661d35b7 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatistics.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatistics.ts @@ -291,7 +291,7 @@ export class TabPaneVirtualMemoryStatistics extends BaseElement { } - + diff --git a/ide/src/trace/component/trace/sheet/hiperf/TabPerfBottomUp.ts b/ide/src/trace/component/trace/sheet/hiperf/TabPerfBottomUp.ts index 950d4949..9664e318 100644 --- a/ide/src/trace/component/trace/sheet/hiperf/TabPerfBottomUp.ts +++ b/ide/src/trace/component/trace/sheet/hiperf/TabPerfBottomUp.ts @@ -273,7 +273,7 @@ export class TabpanePerfBottomUp extends BaseElement {
+ align="flex-start" order isExpand> - + diff --git a/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.ts b/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.ts index 348bb197..020bc90c 100644 --- a/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.ts +++ b/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.ts @@ -796,7 +796,7 @@ export class TabpaneNMCalltree extends BaseElement {
- + diff --git a/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.ts b/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.ts index a9725ac7..761ac6da 100644 --- a/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.ts +++ b/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.ts @@ -371,7 +371,7 @@ export class TabPaneNMSampleList extends BaseElement {
- + diff --git a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsComparison.ts b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsComparison.ts index 1f60c930..2b58537d 100644 --- a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsComparison.ts +++ b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsComparison.ts @@ -174,7 +174,7 @@ export class TabPaneSmapsComparison extends TabPaneSmapsStatistics {
- + diff --git a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts index 47a3088c..6bd43e26 100644 --- a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts +++ b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts @@ -420,7 +420,7 @@ export class TabPaneSmapsStatistics extends BaseElement {
- + -- Gitee From 8f17e1e85eb71c216fc3054e284f9f45ffd0a41c Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:24:05 +0800 Subject: [PATCH 09/18] =?UTF-8?q?=E2=80=99Feat:=E6=B7=BB=E5=8A=A0=E4=BC=98?= =?UTF-8?q?=E5=85=88=E7=BA=A7=E7=9A=84=E7=BA=BF=E7=A8=8B=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E5=B1=95=E7=A4=BATab=E9=A1=B5=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- ide/src/base-ui/table/lit-table.ts | 12 +- ide/src/trace/bean/StateProcessThread.ts | 8 + .../component/trace/base/TraceSheetConfig.ts | 6 + .../trace/sheet/cpu/TabPaneSchedPriority.ts | 186 ++++++++++++++++++ .../trace/sheet/hilog/TabPaneHiLogs.ts | 10 +- .../trace/sheet/hiperf/TabPerfSampleList.ts | 2 +- ide/src/trace/database/SqlLite.ts | 5 +- .../logic-worker/ProcedureLogicWorkerSPT.ts | 16 ++ 8 files changed, 235 insertions(+), 10 deletions(-) create mode 100644 ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts diff --git a/ide/src/base-ui/table/lit-table.ts b/ide/src/base-ui/table/lit-table.ts index d5b4b12d..504dce0e 100644 --- a/ide/src/base-ui/table/lit-table.ts +++ b/ide/src/base-ui/table/lit-table.ts @@ -88,7 +88,7 @@ export class LitTable extends HTMLElement { } .td{ box-sizing: border-box; - padding: 3px; + padding: 4.5px; display: flex; justify-content: flex-start; align-items: center; @@ -1198,11 +1198,13 @@ export class LitTable extends HTMLElement { if ( Math.max(totalHeight, this.tableElement!.scrollTop) <= - Math.min( - totalHeight + tableRowObject.height, - this.tableElement!.scrollTop + this.tableElement!.clientHeight - headHeight - ) + Math.min( + totalHeight + tableRowObject.height, + this.tableElement!.scrollTop + this.tableElement!.clientHeight - headHeight + ) || + this.tableElement!.scrollTop >= this.value.length * 27 ) { + this.tableElement!.scrollTop = 0; let newTableElement = this.createNewTreeTableElement(tableRowObject); newTableElement.style.transform = `translateY(${totalHeight}px)`; this.tbodyElement?.append(newTableElement); diff --git a/ide/src/trace/bean/StateProcessThread.ts b/ide/src/trace/bean/StateProcessThread.ts index eb54cfbf..29a8f533 100644 --- a/ide/src/trace/bean/StateProcessThread.ts +++ b/ide/src/trace/bean/StateProcessThread.ts @@ -44,3 +44,11 @@ export class SPTChild { prior: string = ''; note: string = '-'; } + +export class Priority extends SliceGroup { + iTid: number = 0; + priorityType: string = '-'; + endState: string = ''; + dur: number = 0; + priority: number = 0; +} diff --git a/ide/src/trace/component/trace/base/TraceSheetConfig.ts b/ide/src/trace/component/trace/base/TraceSheetConfig.ts index 857fb071..60a6e59e 100644 --- a/ide/src/trace/component/trace/base/TraceSheetConfig.ts +++ b/ide/src/trace/component/trace/base/TraceSheetConfig.ts @@ -115,6 +115,7 @@ import { TabPaneSmapsComparison } from '../sheet/smaps/TabPaneSmapsComparison.js import { TabPaneGpuClickSelectComparison } from '../sheet/gpu/TabPaneGpuClickSelectComparison.js'; import { TabPaneHiLogs } from '../sheet/hilog/TabPaneHiLogs.js'; import { TabPaneHiLogSummary } from '../sheet/hilog/TabPaneHiLogSummary.js'; +import { TabPaneSchedPriority } from '../sheet/cpu/TabPaneSchedPriority.js'; export let tabConfig: any = { 'tabpane-current': { @@ -610,4 +611,9 @@ export let tabConfig: any = { type: TabPaneHiLogSummary, require: (param: SelectionParam) => param.hiLogSummary.length > 0, }, + 'box-sched-priority': { + title: 'Sched Priority', + type: TabPaneSchedPriority, + require: (param: SelectionParam) => param.cpus.length > 0, + }, }; diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts new file mode 100644 index 00000000..1bced89a --- /dev/null +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BaseElement, element } from '../../../../../base-ui/BaseElement.js'; +import { LitTable } from '../../../../../base-ui/table/lit-table.js'; +import { SelectionParam } from '../../../../bean/BoxSelection.js'; +import { resizeObserver } from '../SheetUtils.js'; +import { procedurePool } from '../../../../database/Procedure.js'; +import { Utils } from '../../base/Utils.js'; +import { queryThreadStateArgsByName } from '../../../../database/SqlLite.js'; +import { Priority } from '../../../../bean/StateProcessThread.js'; + +@element('tabpane-sched-priority') +export class TabPaneSchedPriority extends BaseElement { + private priorityTbl: LitTable | null | undefined; + private range: HTMLLabelElement | null | undefined; + private selectionParam: SelectionParam | null | undefined; + + set data(sptValue: SelectionParam) { + if (sptValue == this.selectionParam) { + return; + } + this.selectionParam = sptValue; + // @ts-ignore + this.sptTbl?.shadowRoot?.querySelector('.table').style.height = this.parentElement!.clientHeight - 45 + 'px'; + this.range!.textContent = + 'Selected range: ' + parseFloat(((sptValue.rightNs - sptValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; + this.queryDataByDB(sptValue); + } + + public initElements(): void { + this.priorityTbl = this.shadowRoot?.querySelector('#priority-tbl'); + this.range = this.shadowRoot?.querySelector('#priority-time-range'); + } + + public connectedCallback(): void { + super.connectedCallback(); + resizeObserver(this.parentElement!, this.priorityTbl!); + } + + private async queryDataByDB(sptParam: SelectionParam | any): Promise { + this.priorityTbl!.loading = true; + const resultData: Array = []; + const strValueMap: Map = new Map(); + await queryThreadStateArgsByName('next_info').then((value) => { + for (const item of value) { + strValueMap.set(item.argset, item.strValue); + } + }); + procedurePool.submitWithName('logic1', 'spt-getCpuPriority', {}, undefined, async (res: Array) => { + for (const item of res) { + if (item.cpu && !this.selectionParam?.cpus.includes(item.cpu)) { + continue; + } + if (!(item.endTs < sptParam.leftNs || item.startTs > sptParam.rightNs)) { + let strArg: string[] = []; + const args = strValueMap.get(item.argSetID); + if (args) { + strArg = args!.split(','); + } + const slice = Utils.SCHED_SLICE_MAP.get(`${item.itId}-${item.startTs}`); + if (slice) { + item.priority = slice!.priority; + item.endState = slice.endState; + if (item.priority >= 0 && item.priority <= 88) { + item.priorityType = 'RT'; + } else if (item.priority >= 89 && item.priority <= 99) { + item.priorityType = 'VIP2.0'; + } else if (item.priority >= 100 && strArg.length > 1 && (strArg[1] !== '0' || strArg[2] !== '0')) { + item.priorityType = 'STATIC_VIP'; + } else { + item.priorityType = 'CFS'; + } + resultData.push(item); + } + } else { + continue; + } + } + this.getDataByPriority(resultData); + }); + } + + private getDataByPriority(source: Array): void { + const priorityMap: Map = new Map(); + const stateMap: Map = new Map(); + source.map((d) => { + if (priorityMap.has(d.priorityType + '')) { + const priorityMapObj = priorityMap.get(d.priorityType + ''); + priorityMapObj!.count++; + priorityMapObj!.wallDuration += d.dur; + priorityMapObj!.avgDuration = (priorityMapObj!.wallDuration / priorityMapObj!.count).toFixed(2); + if (d.dur > priorityMapObj!.maxDuration) { + priorityMapObj!.maxDuration = d.dur; + } + if (d.dur < priorityMapObj!.minDuration) { + priorityMapObj!.minDuration = d.dur; + } + } else { + const stateMapObj = new Priority(); + stateMapObj.title = d.priorityType; + stateMapObj.minDuration = d.dur; + stateMapObj.maxDuration = d.dur; + stateMapObj.count = 1; + stateMapObj.avgDuration = d.dur + ''; + stateMapObj.wallDuration = d.dur; + priorityMap.set(d.priorityType + '', stateMapObj); + } + if (stateMap.has(d.priorityType + '_' + d.endState)) { + const ptsPtMapObj = stateMap.get(d.priorityType + '_' + d.endState); + ptsPtMapObj!.count++; + ptsPtMapObj!.wallDuration += d.dur; + ptsPtMapObj!.avgDuration = (ptsPtMapObj!.wallDuration / ptsPtMapObj!.count).toFixed(2); + if (d.dur > ptsPtMapObj!.maxDuration) { + ptsPtMapObj!.maxDuration = d.dur; + } + if (d.dur < ptsPtMapObj!.minDuration) { + ptsPtMapObj!.minDuration = d.dur; + } + } else { + const ptsPtMapObj = new Priority(); + ptsPtMapObj.title = Utils.getEndState(d.endState); + ptsPtMapObj.minDuration = d.dur; + ptsPtMapObj.maxDuration = d.dur; + ptsPtMapObj.count = 1; + ptsPtMapObj.avgDuration = d.dur + ''; + ptsPtMapObj.wallDuration = d.dur; + stateMap.set(d.priorityType + '_' + d.endState, ptsPtMapObj); + } + }); + + const priorityArr: Array = []; + for (const key of priorityMap.keys()) { + const ptsValues = priorityMap.get(key); + ptsValues!.children = []; + for (const itemKey of stateMap.keys()) { + if (itemKey.startsWith(key + '_')) { + const sp = stateMap.get(itemKey); + ptsValues!.children.push(sp!); + } + } + priorityArr.push(ptsValues!); + } + this.priorityTbl!.loading = false; + this.priorityTbl!.recycleDataSource = priorityArr; + } + + public initHtml(): string { + return ` + + + + + + + + + + + + + + + + + `; + } +} diff --git a/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts b/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts index 4d4ff37e..3cb89038 100644 --- a/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts +++ b/ide/src/trace/component/trace/sheet/hilog/TabPaneHiLogs.ts @@ -271,10 +271,14 @@ export class TabPaneHiLogs extends BaseElement { this.logTableTitle!.textContent = 'Hilogs [0, 0] / 0'; } else { this.logTable.style.height = `${this.filterData.length * tableRowHeight}px`; - let totalLength = Math.floor(tableHeight / tableRowHeight); + let totalLength = Math.ceil(tableHeight / tableRowHeight); this.endDataIndex = this.startDataIndex + totalLength; - if (this.filterData.length > this.endDataIndex - this.startDataIndex) { - this.visibleData = this.filterData.slice(this.startDataIndex, this.endDataIndex); + if (this.filterData.length >= this.endDataIndex - this.startDataIndex) { + if (this.endDataIndex >= this.filterData.length) { + this.visibleData = this.filterData.slice(this.filterData.length - totalLength, this.filterData.length); + } else { + this.visibleData = this.filterData.slice(this.startDataIndex, this.endDataIndex); + } } else { this.visibleData = this.filterData; } diff --git a/ide/src/trace/component/trace/sheet/hiperf/TabPerfSampleList.ts b/ide/src/trace/component/trace/sheet/hiperf/TabPerfSampleList.ts index ebbb470a..fd79ee38 100644 --- a/ide/src/trace/component/trace/sheet/hiperf/TabPerfSampleList.ts +++ b/ide/src/trace/component/trace/sheet/hiperf/TabPerfSampleList.ts @@ -103,7 +103,7 @@ export class TabPanePerfSample extends BaseElement { queryPerfSampleCallChain(sample.sampleId).then((result) => { for (let stack of result) { let files = (perfDataQuery.filesData[stack.fileId] ?? []) as Array; - stack.path = files[stack.symbolId].path; + stack.path = files[stack.symbolId]?.path || ''; stack.type = stack.path.endsWith('.so.1') || stack.path.endsWith('.dll') || stack.path.endsWith('.so') ? 0 : 1; } this.tblData!.dataSource = result; diff --git a/ide/src/trace/database/SqlLite.ts b/ide/src/trace/database/SqlLite.ts index 587414c1..a88f0da6 100644 --- a/ide/src/trace/database/SqlLite.ts +++ b/ide/src/trace/database/SqlLite.ts @@ -1359,6 +1359,9 @@ select pid id,name,'p' type from process;`, export const queryThreadStateArgs = (argset: number): Promise> => query('queryThreadStateArgs', ` select args_view.* from args_view where argset = ${argset}`, {}); +export const queryThreadStateArgsByName = (key: string): Promise> => +query('queryThreadStateArgsByName', ` select strValue, argset from args_view where keyName = $key`, {$key: key}); + export const queryWakeUpThread_Desc = (): Promise> => query( 'queryWakeUpThread_Desc', @@ -2672,7 +2675,7 @@ export const queryPerfSampleCallChain = (sampleId: number): Promise 0 and (ts - start_ts) >= 0; `, @@ -253,7 +263,13 @@ export class ThreadSlice { state?: string; dur?: number; startTs?: number; + endTs?: number; cpu?: number | null; tid?: number; pid?: number; + itId?: number; + priorityType?: string; + end_state?: string; + priority?: number; + argSetID?: number; } -- Gitee From d638ae8cc1f028dbd67575e1bfa6a54ac5044598 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:25:42 +0800 Subject: [PATCH 10/18] =?UTF-8?q?=E2=80=99Fix:1.metric=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E6=BA=90=E8=B0=83=E6=95=B4=E7=94=B1=E6=9F=A5=E8=AF=A2db?= =?UTF-8?q?=E6=94=B9=E4=B8=BATS=E6=8E=A5=E5=8F=A3=E5=90=8E=E5=8E=BB2.?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=98=BE=E7=A4=BA=E9=97=AE=E9=A2=98=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- ide/src/base-ui/table/lit-table.ts | 32 +++- ide/src/trace/SpApplication.ts | 3 + ide/src/trace/component/SpMetrics.ts | 162 ++---------------- ide/src/trace/component/SpRecordTrace.ts | 3 +- .../trace/component/SpRecyclerSystemTrace.ts | 2 - ide/src/trace/component/SpSystemTrace.ts | 10 +- .../trace/component/chart/SpProcessChart.ts | 4 - .../trace/component/metrics/CpuStrategy.ts | 85 --------- .../metrics/DistributeTermStrategy.ts | 50 ------ .../trace/component/metrics/MemAggStrategy.ts | 97 ----------- .../trace/component/metrics/MemStrategy.ts | 66 ------- .../component/metrics/MetaDataStrategy.ts | 62 ------- .../component/metrics/SysCallsStrategy.ts | 54 ------ .../component/metrics/SysCallsTopStrategy.ts | 76 -------- .../component/metrics/TraceStatsStrategy.ts | 54 ------ .../component/metrics/TraceTaskStrategy.ts | 57 ------ .../component/trace/base/TraceRowConfig.ts | 19 +- .../trace/component/trace/search/Search.ts | 1 - .../trace/sheet/hilog/TabPaneHiLogs.ts | 4 +- .../trace/sheet/process/TabPaneSlices.ts | 27 +++ ide/src/trace/database/SqlLite.ts | 21 +-- ide/src/trace/database/SqlLiteWorker.ts | 2 +- ide/src/trace/database/TraceWorker.ts | 32 +++- 23 files changed, 127 insertions(+), 796 deletions(-) delete mode 100644 ide/src/trace/component/metrics/CpuStrategy.ts delete mode 100644 ide/src/trace/component/metrics/DistributeTermStrategy.ts delete mode 100644 ide/src/trace/component/metrics/MemAggStrategy.ts delete mode 100644 ide/src/trace/component/metrics/MemStrategy.ts delete mode 100644 ide/src/trace/component/metrics/MetaDataStrategy.ts delete mode 100644 ide/src/trace/component/metrics/SysCallsStrategy.ts delete mode 100644 ide/src/trace/component/metrics/SysCallsTopStrategy.ts delete mode 100644 ide/src/trace/component/metrics/TraceStatsStrategy.ts delete mode 100644 ide/src/trace/component/metrics/TraceTaskStrategy.ts diff --git a/ide/src/base-ui/table/lit-table.ts b/ide/src/base-ui/table/lit-table.ts index 504dce0e..62b3bde0 100644 --- a/ide/src/base-ui/table/lit-table.ts +++ b/ide/src/base-ui/table/lit-table.ts @@ -1195,16 +1195,13 @@ export class LitTable extends HTMLElement { this.newTableRowObject(item, totalHeight, depth, tableRowObject); } } - if ( Math.max(totalHeight, this.tableElement!.scrollTop) <= - Math.min( - totalHeight + tableRowObject.height, - this.tableElement!.scrollTop + this.tableElement!.clientHeight - headHeight - ) || - this.tableElement!.scrollTop >= this.value.length * 27 + Math.min( + totalHeight + tableRowObject.height, + this.tableElement!.scrollTop + this.tableElement!.clientHeight - headHeight + ) ) { - this.tableElement!.scrollTop = 0; let newTableElement = this.createNewTreeTableElement(tableRowObject); newTableElement.style.transform = `translateY(${totalHeight}px)`; this.tbodyElement?.append(newTableElement); @@ -1213,6 +1210,14 @@ export class LitTable extends HTMLElement { } this.currentRecycleList.push(newTableElement); } + // 当滚动高度大于数据全部收起的高度时点击一键收起,滚动条位置偏下,需要向上滚动才能看到数据, + // 为了查看数据方便,直接将滚动条滚动到最上面 + if ( + this.tableElement!.scrollTop >= this.value.length * tableRowObject.height && + this.currentRecycleList.length === 0 + ) { + this.tableElement!.scrollTop = 0; + } totalHeight += tableRowObject.height; visibleObjects.push(tableRowObject); if (item.hasNext) { @@ -1255,6 +1260,19 @@ export class LitTable extends HTMLElement { break; } } + // 如果滚动高度大于数据全部收起的高度,并且this.currentRecycleList数组长度为0要给this.currentRecycleList赋值,不然tab页没有数据 + if ( + visibleObjects[0] && + this.tableElement!.scrollTop >= this.value.length * visibleObjects[0].height && + this.currentRecycleList.length === 0 + ) { + let newTableElement = this.createNewTreeTableElement(visibleObjects[skip]); + this.tbodyElement?.append(newTableElement); + if (this.treeElement?.lastChild) { + (this.treeElement?.lastChild as HTMLElement).style.height = visibleObjects[skip].height + 'px'; + } + this.currentRecycleList.push(newTableElement); + } let reduce = this.currentRecycleList.map((item) => item.clientHeight).reduce((a, b) => a + b, 0); if (reduce == 0) { return; diff --git a/ide/src/trace/SpApplication.ts b/ide/src/trace/SpApplication.ts index 0e522c67..185e98f6 100644 --- a/ide/src/trace/SpApplication.ts +++ b/ide/src/trace/SpApplication.ts @@ -486,6 +486,7 @@ export class SpApplication extends BaseElement { window.subscribe(window.SmartEvent.UI.Error, (err) => { litSearch.setPercent(err, -1); progressEL.loading = false; + that.freshMenuDisable(false); }); window.subscribe(window.SmartEvent.UI.Loading, (loading) => { litSearch.setPercent(loading ? 'Import So File' : '', loading ? -1 : 101); @@ -521,6 +522,8 @@ export class SpApplication extends BaseElement { } }); } else { + let indexEL = litSearch.shadowRoot!.querySelector('#index'); + indexEL!.textContent = '0'; litSearch.list = []; spSystemTrace?.visibleRows.forEach((it) => { it.highlight = false; diff --git a/ide/src/trace/component/SpMetrics.ts b/ide/src/trace/component/SpMetrics.ts index 4383f0e3..f630a2eb 100644 --- a/ide/src/trace/component/SpMetrics.ts +++ b/ide/src/trace/component/SpMetrics.ts @@ -16,57 +16,20 @@ import { BaseElement, element } from '../../base-ui/BaseElement.js'; import { - querySelectTraceStats, querySystemCalls, - queryTraceMemory, - queryTraceMemoryTop, - queryTraceMemoryUnAgg, - queryTraceMetaData, - queryTraceTaskName, + queryMetric, } from '../database/SqlLite.js'; import '../../base-ui/table/lit-table.js'; -import { initMemoryAggStrategy } from './metrics/MemAggStrategy.js'; -import { initMemoryStrategy } from './metrics/MemStrategy.js'; -import { initTraceStateStrategy } from './metrics/TraceStatsStrategy.js'; -import { initTraceTaskStrategy } from './metrics/TraceTaskStrategy.js'; -import { initMetaDataStrategy } from './metrics/MetaDataStrategy.js'; -import { PluginConvertUtils } from './setting/utils/PluginConvertUtils.js'; -import { info } from '../../log/Log.js'; import { LitProgressBar } from '../../base-ui/progress-bar/LitProgressBar.js'; import { SpStatisticsHttpUtil } from '../../statistics/util/SpStatisticsHttpUtil.js'; -import { initSysCallsStrategy } from './metrics/SysCallsStrategy.js'; @element('sp-metrics') export class SpMetrics extends BaseElement { - private _metric?: string; - private _metricResult?: string; private selectMetricEl: HTMLSelectElement | undefined; private runButtonEl: HTMLButtonElement | undefined | null; private responseJson: HTMLPreElement | undefined | null; - private metricOptionalSelects: Array | undefined; private metricProgressLoad: LitProgressBar | undefined; - static get observedAttributes(): string[] { - return ['metric', 'metricResult']; - } - - get metric(): string { - return this.getAttribute('metric') || ''; - } - - set metric(value: string) { - this._metric = value; - } - - get metricResult(): string { - return this.getAttribute('metricResult') || ''; - } - - set metricResult(value: string) { - this._metricResult = value; - this.setAttribute('metricResult', value); - } - reset(): void { this.selectMetricEl!.selectedIndex = 0; this.responseJson!.textContent = ''; @@ -77,47 +40,6 @@ export class SpMetrics extends BaseElement { this.selectMetricEl = this.shadowRoot?.querySelector('.sql-select') as HTMLSelectElement; this.runButtonEl = this.shadowRoot?.querySelector('.sql-select-button') as HTMLButtonElement; this.responseJson = this.shadowRoot?.querySelector('.response-json') as HTMLPreElement; - if (this.selectMetricEl) { - this.selectMetricEl.addEventListener('selectionchange', () => { - if (this.selectMetricEl) { - this.selectMetricEl.textContent = ''; - } - }); - } - this.initMetricDataHandle(); - this.initMetricSelectOption(); - } - - initMetric(queryItem: MetricQueryItem): void { - this.initMetricData(queryItem).then(() => { - this.metricProgressLoad!.loading = false; - }); - } - - async initMetricData(queryItem: MetricQueryItem): Promise { - let spacesNumber = 4; - let metricQuery = queryItem.metricQuery; - let queryList = await metricQuery(); - info('current Metric Data size is: ', queryList!.length); - let metric = queryItem.metricResultHandle; - let resultData = metric(queryList); - this.responseJson!.textContent = PluginConvertUtils.BeanToCmdTxtWithObjName(resultData, true, - queryItem.metricName, spacesNumber); - } - - attributeChangedCallback(name: string, oldValue: string, newValue: string): void { - switch (name) { - case 'metric': - if (this.selectMetricEl) { - this.selectMetricEl.textContent = newValue; - } - break; - case 'metricResult': - if (this.selectMetricEl) { - this.selectMetricEl.textContent = newValue; - } - break; - } } runClickListener = (): void => { @@ -125,20 +47,21 @@ export class SpMetrics extends BaseElement { event: 'metrics', action: 'metrics', }); + this.responseJson!.textContent = ''; this.metricProgressLoad!.loading = true; - let selectedIndex = this.selectMetricEl!.selectedIndex; - let value = this.selectMetricEl!.options[selectedIndex].value; - let resultQuery = this.metricOptionalSelects?.filter((item) => { - return item.metricName === value; - }); - if (!resultQuery || resultQuery.length === 0) { - return; + let index = this.selectMetricEl!.selectedIndex; + let optionEl = this.selectMetricEl?.querySelectorAll('option')[index]; + if (optionEl && optionEl.value !== '') { + queryMetric(optionEl.value).then((result)=>{ + this.metricProgressLoad!.loading = false; + this.responseJson!.textContent = result.toString(); + }); + } else { + this.metricProgressLoad!.loading = false; } - this.initMetric(resultQuery[0]); }; connectedCallback(): void { - // Run metric button to add listener this.runButtonEl?.addEventListener('click', this.runClickListener); } @@ -146,56 +69,6 @@ export class SpMetrics extends BaseElement { this.runButtonEl?.removeEventListener('click', this.runClickListener); } - initMetricSelectOption(): void { - for (let index = 0 ; index < this.metricOptionalSelects!.length ; index++) { - let htmlElement = document.createElement('option'); - if (this.metricOptionalSelects) { - htmlElement.textContent = this.metricOptionalSelects[index].metricName; - this.selectMetricEl?.appendChild(htmlElement); - } - } - } - - initMetricDataHandle(): void { - this.metricOptionalSelects = [ - { - metricName: 'trace_mem', - metricQuery: queryTraceMemory, - metricResultHandle: initMemoryStrategy, - }, - { - metricName: 'trace_mem_top10', - metricQuery: queryTraceMemoryTop, - metricResultHandle: initMemoryStrategy, - }, - { - metricName: 'trace_mem_unagg', - metricQuery: queryTraceMemoryUnAgg, - metricResultHandle: initMemoryAggStrategy, - }, - { - metricName: 'trace_task_names', - metricQuery: queryTraceTaskName, - metricResultHandle: initTraceTaskStrategy, - }, - { - metricName: 'trace_stats', - metricQuery: querySelectTraceStats, - metricResultHandle: initTraceStateStrategy, - }, - { - metricName: 'trace_metadata', - metricQuery: queryTraceMetaData, - metricResultHandle: initMetaDataStrategy, - }, - { - metricName: 'sys_calls', - metricQuery: querySystemCalls, - metricResultHandle: initSysCallsStrategy, - }, - ]; - } - initHtml(): string { return `
@@ -1310,7 +1351,19 @@ export class TabPaneCurrentSelection extends BaseElement {
- + +
diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts index 45ae110f..b726a4f6 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts @@ -52,7 +52,7 @@ export class TabPaneBoxChild extends BaseElement { getDataByDB(val: BoxJumpParam) { this.boxChildTbl!.loading = true; - getTabBoxChildData(val.leftNs, val.rightNs, val.state, val.processId, val.threadId).then((result) => { + getTabBoxChildData(val.leftNs, val.rightNs, val.cpus, val.state, val.processId, val.threadId).then((result) => { this.boxChildTbl!.loading = false; if (result.length != null && result.length > 0) { result.map((e) => { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts index ef31dcc1..cbb95db7 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts @@ -39,7 +39,7 @@ export class TabPaneCpuByProcess extends BaseElement { ' ms'; // @ts-ignore this.cpuByProcessTbl!.shadowRoot!.querySelector('.table')?.style?.height = - this.parentElement!.clientHeight - 45 + 'px'; + this.parentElement!.clientHeight - 50 + 'px'; this.cpuByProcessTbl!.recycleDataSource = []; this.cpuByProcessTbl!.loading = true; getTabCpuByProcess(cpuByProcessValue.cpus, cpuByProcessValue.leftNs, cpuByProcessValue.rightNs).then((result) => { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts index b2e3b345..8b862774 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts @@ -51,6 +51,7 @@ export class TabPaneCpuByThread extends BaseElement { } this.currentSelectionParam = cpuByThreadValue; this.cpuByThreadTbl!.innerHTML = this.getTableColumns(cpuByThreadValue.cpus); + this.cpuByThreadTbl!.injectColumns(); this.range!.textContent = 'Selected range: ' + parseFloat(((cpuByThreadValue.rightNs - cpuByThreadValue.leftNs) / 1000000.0).toFixed(5)) + diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts index 7e8826ff..2d99bd6e 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts @@ -32,8 +32,6 @@ export class TabPaneCpuUsage extends BaseElement { return; } this.currentSelectionParam = cpuUsageValue; - // @ts-ignore - this.cpuUsageTbl?.shadowRoot.querySelector('.table').style.height = this.parentElement.clientHeight - 45 + 'px'; this.range!.textContent = 'Selected range: ' + parseFloat(((cpuUsageValue.rightNs - cpuUsageValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; this.cpuUsageTbl!.loading = true; diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts b/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts index aa1b8945..d74e081c 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPanePTS.ts @@ -34,7 +34,7 @@ export class TabPanePTS extends BaseElement { this.selectionParam = ptsValue; this.ptsRange!.textContent = 'Selected range: ' + parseFloat(((ptsValue.rightNs - ptsValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; - this.getDataByPTS(ptsValue.leftNs, ptsValue.rightNs); + this.getDataByPTS(ptsValue.leftNs, ptsValue.rightNs, ptsValue.cpus); } initElements(): void { @@ -43,12 +43,12 @@ export class TabPanePTS extends BaseElement { this.ptsTbl!.itemTextHandleMap.set('title', Utils.transferPTSTitle); } - getDataByPTS(ptsLeftNs: number, ptsRightNs: number) { + getDataByPTS(ptsLeftNs: number, ptsRightNs: number, cpus: Array) { this.ptsTbl!.loading = true; procedurePool.submitWithName( 'logic1', 'spt-getPTS', - { leftNs: ptsLeftNs, rightNs: ptsRightNs }, + { leftNs: ptsLeftNs, rightNs: ptsRightNs, cpus: cpus}, undefined, (res: Array) => { this.ptsTbl!.loading = false; diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts index 36e071e2..8e958ba6 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneSPT.ts @@ -36,7 +36,7 @@ export class TabPaneSPT extends BaseElement { this.sptTbl?.shadowRoot?.querySelector('.table').style.height = this.parentElement!.clientHeight - 45 + 'px'; this.range!.textContent = 'Selected range: ' + parseFloat(((sptValue.rightNs - sptValue.leftNs) / 1000000.0).toFixed(5)) + ' ms'; - this.getDataBySPT(sptValue.leftNs, sptValue.rightNs); + this.getDataBySPT(sptValue.leftNs, sptValue.rightNs, sptValue.cpus); } initElements(): void { @@ -50,12 +50,12 @@ export class TabPaneSPT extends BaseElement { resizeObserver(this.parentElement!, this.sptTbl!); } - getDataBySPT(leftNs: number, rightNs: number) { + getDataBySPT(leftNs: number, rightNs: number, cpus: Array) { this.sptTbl!.loading = true; procedurePool.submitWithName( 'logic1', 'spt-getSPT', - { leftNs: leftNs, rightNs: rightNs }, + { leftNs: leftNs, rightNs: rightNs, cpus: cpus }, undefined, (res: Array) => { this.sptTbl!.loading = false; diff --git a/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMStatstics.ts b/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMStatstics.ts index fdb2076c..47c31e03 100644 --- a/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMStatstics.ts +++ b/ide/src/trace/component/trace/sheet/native-memory/TabPaneNMStatstics.ts @@ -51,7 +51,7 @@ export class TabPaneNMStatstics extends BaseElement { }); this.initResponseTypeList(nativeStatisticsParam); // @ts-ignore - this.nativeStatisticsTbl?.shadowRoot.querySelector('.table').style.height = this.parentElement.clientHeight - 20 + 'px'; + this.nativeStatisticsTbl?.shadowRoot.querySelector('.table').style.height = this.parentElement.clientHeight - 25 + 'px'; // @ts-ignore this.nativeStatisticsTbl?.recycleDataSource = []; this.nativeStatisticsTbl!.loading = true; @@ -240,7 +240,7 @@ export class TabPaneNMStatstics extends BaseElement { connectedCallback() { super.connectedCallback(); - resizeObserver(this.parentElement!, this.nativeStatisticsTbl!, 20); + resizeObserver(this.parentElement!, this.nativeStatisticsTbl!, 25); } sortByColumn(nmStatColumn: string, nmStatSort: number) { diff --git a/ide/src/trace/database/SqlLite.ts b/ide/src/trace/database/SqlLite.ts index df175a0a..4afe95f7 100644 --- a/ide/src/trace/database/SqlLite.ts +++ b/ide/src/trace/database/SqlLite.ts @@ -554,6 +554,7 @@ where c.ts not null and c.cookie is null group by tid,ipid`, export const getTabBoxChildData = ( leftNs: number, rightNs: number, + cpus: number[], state: string | undefined, processId: number | undefined, threadId: number | undefined @@ -562,6 +563,7 @@ export const getTabBoxChildData = ( ${state != undefined && state != '' ? `and B.state = '${state}'` : ''} ${processId != undefined && processId != -1 ? `and IP.pid = ${processId}` : ''} ${threadId != undefined && threadId != -1 ? `and A.tid = ${threadId}` : ''} + ${cpus.length > 0 ? `and (B.cpu is null or B.cpu in (${cpus.join(',')}))` : ''} `; let sql = `select IP.name as process, @@ -597,7 +599,8 @@ export const getTabBoxChildData = ( IP.pid not null and not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) ${condition}; - ` + `; + console.log(sql); return query('getTabBoxChildData', sql, {}); }; @@ -2727,6 +2730,18 @@ where itid = $itid and c.ts = $ts;`, { $itid: itid, $ts: ts } ); +export const queryWakeupListPriority = (itid: number[], ts: number[], cpus: number[]): Promise> => + query( + 'queryWakeupListPriority', + ` + select itid, priority, (ts - start_ts) as ts, dur, cpu + from sched_slice,trace_range where cpu in (${cpus.join(',')}) + and itid in (${itid.join(',')}) + and ts - start_ts in (${ts.join(',')}) + `, + { } + ); + export const queryBinderByArgsId = (id: number, startTime: number, isNext: boolean): Promise> => { let sql = `select c.ts - D.start_ts as startTime, c.dur, diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts index c96c967e..b13d9e58 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts @@ -44,21 +44,14 @@ export class ProcedureLogicWorkerSPT extends LogicHandler { self.postMessage({ id: this.currentEventId, action: 'spt-getPTS', - results: this.getPTSData(data.params.leftNs, data.params.rightNs), + results: this.getPTSData(data.params.leftNs, data.params.rightNs, data.params.cpus), }); break; case 'spt-getSPT': self.postMessage({ id: this.currentEventId, action: 'spt-getSPT', - results: this.getSPTData(data.params.leftNs, data.params.rightNs), - }); - break; - case 'spt-getGroupData': - self.postMessage({ - id: this.currentEventId, - action: 'spt-getSPT', - results: this.getSPTData(data.params.leftNs, data.params.rightNs), + results: this.getSPTData(data.params.leftNs, data.params.rightNs, data.params.cpus), }); break; case 'spt-getCpuPriority': @@ -102,8 +95,11 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; ); } - getPTSData(ptsLeftNs: number, ptsRightNs: number) { - let ptsFilter = this.threadSlice.filter(it => Math.max(ptsLeftNs, it.startTs!) < Math.min(ptsRightNs, it.startTs! + it.dur!)); + getPTSData(ptsLeftNs: number, ptsRightNs: number, cpus: Array) { + let ptsFilter = this.threadSlice.filter(it => + Math.max(ptsLeftNs, it.startTs!) < Math.min(ptsRightNs, it.startTs! + it.dur!) && + (it.cpu === null || it.cpu === undefined || cpus.includes(it.cpu)) + ); let group: any = {}; ptsFilter.forEach((slice) => { let item: SliceGroup = { @@ -180,8 +176,11 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; return Object.values(group); } - getSPTData(ptsLeftNs: number, ptsRightNs: number) { - let sptFilter = this.threadSlice.filter(it => Math.max(ptsLeftNs, it.startTs!) < Math.min(ptsRightNs, it.startTs! + it.dur!)); + getSPTData(sptLeftNs: number, sptRightNs: number, cpus: Array) { + let sptFilter = this.threadSlice.filter(it => + Math.max(sptLeftNs, it.startTs!) < Math.min(sptRightNs, it.startTs! + it.dur!) && + (it.cpu === null || it.cpu === undefined || cpus.includes(it.cpu)) + ); let group: any = {}; sptFilter.forEach((slice) => { let item: SliceGroup = { diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerCPU.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerCPU.ts index 9699f755..ed5d6054 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerCPU.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerCPU.ts @@ -424,6 +424,7 @@ export class WakeupBean { process: string | undefined; pid: number | undefined; thread: string | undefined; + dur: number | null | undefined; tid: number | undefined; schedulingLatency: number | undefined; ts: number | undefined; -- Gitee From f9eed4b70530d950752870f0030a0650d09c122a Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:29:46 +0800 Subject: [PATCH 12/18] =?UTF-8?q?=E2=80=99Fix:=E8=A7=A3=E5=86=B3=E7=81=AB?= =?UTF-8?q?=E7=84=B0=E5=9B=BE=EF=BC=8CTab=E9=A1=B5=E9=9D=A2=E5=92=8CNative?= =?UTF-8?q?memory=E6=98=BE=E7=A4=BA=E9=97=AE=E9=A2=98=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- ide/src/base-ui/select/LitAllocationSelect.ts | 11 ++++ ide/src/base-ui/table/LitPageTable.ts | 5 +- ide/src/base-ui/table/lit-table.ts | 11 ++-- ide/src/trace/component/SpSystemTrace.ts | 10 +--- ide/src/trace/component/chart/FrameChart.ts | 16 ++++-- .../trace/component/setting/SpAllocations.ts | 13 +++++ .../component/trace/TimerShaftElement.ts | 5 +- .../trace/sheet/TabPaneCurrentSelection.ts | 3 +- .../file-system/TabPaneFileSystemCalltree.ts | 4 +- .../trace/sheet/hiperf/TabPerfProfile.ts | 10 ++-- .../component/trace/timer-shaft/RangeRuler.ts | 6 ++- .../ProcedureLogicWorkerNativeNemory.ts | 51 +++++++++++-------- .../logic-worker/ProcedureLogicWorkerPerf.ts | 9 +++- 13 files changed, 96 insertions(+), 58 deletions(-) diff --git a/ide/src/base-ui/select/LitAllocationSelect.ts b/ide/src/base-ui/select/LitAllocationSelect.ts index 71f4b77d..1d595873 100644 --- a/ide/src/base-ui/select/LitAllocationSelect.ts +++ b/ide/src/base-ui/select/LitAllocationSelect.ts @@ -77,6 +77,17 @@ export class LitAllocationSelect extends BaseElement { this.setAttribute('list-height', value); } + attributeChangedCallback(name: any, oldValue: any, newValue: any) { + switch (name) { + case 'value': + this.selectAllocationInputEl!.value = newValue; + break; + case 'placeholder': + this.selectAllocationInputEl!.placeholder = newValue; + break; + } + } + initElements(): void { this.selectAllocationInputContent = this.shadowRoot!.querySelector('.multipleSelect') as HTMLDivElement; this.addEventListener('click', () => { diff --git a/ide/src/base-ui/table/LitPageTable.ts b/ide/src/base-ui/table/LitPageTable.ts index 79275af2..084a1694 100644 --- a/ide/src/base-ui/table/LitPageTable.ts +++ b/ide/src/base-ui/table/LitPageTable.ts @@ -151,9 +151,10 @@ export class LitPageTable extends BaseElement { } } this.jumpDiv!.onclick= () => { + let value = this.targetPageInput!.value; let reg = /^[0-9]*$/; - if (reg.test(this.targetPageInput!.value)) { - let target = parseInt(this.targetPageInput!.value); + if (value.length > 0 && reg.test(value)) { + let target = parseInt(value); if (target < 1) { target = 1; } diff --git a/ide/src/base-ui/table/lit-table.ts b/ide/src/base-ui/table/lit-table.ts index dc3bd189..c471d382 100644 --- a/ide/src/base-ui/table/lit-table.ts +++ b/ide/src/base-ui/table/lit-table.ts @@ -483,6 +483,9 @@ export class LitTable extends HTMLElement { } setStatus(list: any, status: boolean) { + if (!status) { + this.tableElement!.scrollTop = 0; + } for (let item of list) { item.status = status; if (item.children != undefined && item.children.length > 0) { @@ -1214,14 +1217,6 @@ export class LitTable extends HTMLElement { } this.currentRecycleList.push(newTableElement); } - // 当滚动高度大于数据全部收起的高度时点击一键收起,滚动条位置偏下,需要向上滚动才能看到数据, - // 为了查看数据方便,直接将滚动条滚动到最上面 - if ( - this.tableElement!.scrollTop >= this.value.length * tableRowObject.height && - this.currentRecycleList.length === 0 - ) { - this.tableElement!.scrollTop = 0; - } totalHeight += tableRowObject.height; visibleObjects.push(tableRowObject); if (item.hasNext) { diff --git a/ide/src/trace/component/SpSystemTrace.ts b/ide/src/trace/component/SpSystemTrace.ts index efcb1e7d..a6949004 100644 --- a/ide/src/trace/component/SpSystemTrace.ts +++ b/ide/src/trace/component/SpSystemTrace.ts @@ -1980,7 +1980,7 @@ export class SpSystemTrace extends BaseElement { if (this.timerShaftEL?.isScaling()) { return; } - this.timerShaftEL?.documentOnMouseMove(ev); + this.timerShaftEL?.documentOnMouseMove(ev, this); if (isMouseInTimeShaft) { return; } @@ -3266,10 +3266,6 @@ export class SpSystemTrace extends BaseElement { (e) => { if (e.ctrlKey) { e.preventDefault(); - this.removeEventListener('mousemove', this.documentOnMouseMove); - this.removeEventListener('click', this.documentOnClick); - this.removeEventListener('mousedown', this.documentOnMouseDown); - this.removeEventListener('mouseup', this.documentOnMouseUp); this.style.cursor = 'move'; SpSystemTrace.moveable = true; SpSystemTrace.mouseCurrentPosition = e.clientX; @@ -3291,10 +3287,6 @@ export class SpSystemTrace extends BaseElement { SpSystemTrace.mouseCurrentPosition = 0; SpSystemTrace.moveable = false; this.style.cursor = 'default'; - this.addEventListener('mousemove', this.documentOnMouseMove); - this.addEventListener('click', this.documentOnClick); - this.addEventListener('mousedown', this.documentOnMouseDown); - this.addEventListener('mouseup', this.documentOnMouseUp); } }, { passive: false } diff --git a/ide/src/trace/component/chart/FrameChart.ts b/ide/src/trace/component/chart/FrameChart.ts index 6ac93f86..016d6d86 100644 --- a/ide/src/trace/component/chart/FrameChart.ts +++ b/ide/src/trace/component/chart/FrameChart.ts @@ -74,7 +74,7 @@ export class FrameChart extends BaseElement { ChartStruct.lastSelectFuncStruct = undefined; this.setSelectStatusRecursive(ChartStruct.selectFuncStruct, true); ChartStruct.selectFuncStruct = undefined; - + this.isClickMode = false; this.currentData = val; this.resetTrans(); this.calDrawArgs(true); @@ -446,7 +446,7 @@ export class FrameChart extends BaseElement { if (children.frame!.width >= filterPixel) { effectChildList.push(children); } else { - if (node.isChartSelect || node.isSearch) { + if (node.isChartSelect || this.isSearch(node)) { ignore.size += children.drawSize; ignore.count += children.drawCount; ignore.dur += children.drawDur; @@ -467,6 +467,16 @@ export class FrameChart extends BaseElement { } } + private isSearch(node: ChartStruct): boolean { + switch (this._mode) { + case ChartMode.Byte: + return node.searchSize > 0; + case ChartMode.Count: + return node.searchCount > 0; + case ChartMode.Duration: + return node.searchDur > 0; + } + } /** * 绘制每个函数色块 * @param node 函数块 @@ -790,7 +800,7 @@ export class FrameChart extends BaseElement { Lib: ${hoverNode?.lib}
Addr: ${hoverNode?.addr}
- Duration: ${duration} (${percent}%)<`; + Duration: ${duration} (${percent}%)`; break; } } diff --git a/ide/src/trace/component/setting/SpAllocations.ts b/ide/src/trace/component/setting/SpAllocations.ts index 516aacd3..59bd8f79 100644 --- a/ide/src/trace/component/setting/SpAllocations.ts +++ b/ide/src/trace/component/setting/SpAllocations.ts @@ -132,6 +132,10 @@ export class SpAllocations extends BaseElement { }); input.addEventListener('inputClick', () => { allocationProcessData = []; + if (this.startup_mode) { + this.processId!.processData = []; + return; + } if (SpRecordTrace.serialNumber != '') { Cmd.getProcess().then((processList) => { this.processId!.processData = processList; @@ -240,6 +244,15 @@ export class SpAllocations extends BaseElement { this.recordStatisticsResult!.setAttribute('percentValue', stepValue[index] + ''); }); }); + this.startupMode.addEventListener('change', (evt) => { + if (this.startup_mode) { + this.processId!.value = ''; + this.processId!.placeholder = 'please input process'; + } else { + this.processId!.value = ''; + this.processId!.placeholder = 'please select process'; + } + }); } initHtml(): string { diff --git a/ide/src/trace/component/trace/TimerShaftElement.ts b/ide/src/trace/component/trace/TimerShaftElement.ts index 6891860a..72787075 100644 --- a/ide/src/trace/component/trace/TimerShaftElement.ts +++ b/ide/src/trace/component/trace/TimerShaftElement.ts @@ -327,13 +327,14 @@ export class TimerShaftElement extends BaseElement { this.sportRuler?.mouseUp(ev); }; - documentOnMouseMove = (ev: MouseEvent) => { + documentOnMouseMove = (ev: MouseEvent, trace: SpSystemTrace) => { + trace.style.cursor = 'default'; let x = ev.offsetX - (this.canvas?.offsetLeft || 0); // 鼠标的x轴坐标 let y = ev.offsetY; // 鼠标的y轴坐标 let findSlicestime = this.sportRuler?.findSlicesTime(x, y); // 查找帽子 if (!findSlicestime) { // 如果在该位置没有找到一个“帽子”,则可以显示一个旗子。 this.sportRuler?.showHoverFlag(); - this.rangeRuler?.mouseMove(ev); + this.rangeRuler?.mouseMove(ev, trace); if (this.sportRuler?.edgeDetection(ev)) { this.sportRuler?.mouseMove(ev); } else { diff --git a/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts b/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts index 2c0033b5..68abb324 100644 --- a/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts +++ b/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts @@ -227,7 +227,7 @@ export class TabPaneCurrentSelection extends BaseElement { let isBinder = FuncStruct.isBinder(data); let isAsyncBinder = isBinder && FuncStruct.isBinderAsync(data); if (data.argsetid !== undefined && data.argsetid !== null) { - this.setTableHeight('550px'); + this.setTableHeight('700px'); if (isAsyncBinder) { Promise.all([ queryBinderByArgsId(data.argsetid!, data.startTs!, !data.funName!.endsWith('rcv')), @@ -995,7 +995,6 @@ export class TabPaneCurrentSelection extends BaseElement { name: 'StartTime(Absolute)', value: ((data.ts || 0) + (window as any).recordStartNS) / 1000000000, }); - list.push({ name: 'Absolute Time', value: ((window as any).recordStartNS + data.ts) / 1000000000 }); list.push({ name: 'Duration', value: data.dur ? getTimeString(data.dur) : ' ' }); if (data.frame_type !== 'frameTime') { list.push({ name: 'Process', value: data.cmdline + ' ' + data.pid }); diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts index 32240ede..0e511cb8 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts @@ -441,7 +441,9 @@ export class TabpaneFilesystemCalltree extends BaseElement { this.isChartShow = true; this.fsCallTreeFilter!.disabledMining = true; showButtonMenu(this.fsCallTreeFilter, this.needShowMenu); - this.frameChart!.data = this.fsCallTreeDataSource; + if (!data){ + this.frameChart!.data = this.fsCallTreeDataSource; + } this.frameChart?.calculateChartData(); } else if (data.icon == 'tree') { fsCallTreePageChart?.setAttribute('class', ''); diff --git a/ide/src/trace/component/trace/sheet/hiperf/TabPerfProfile.ts b/ide/src/trace/component/trace/sheet/hiperf/TabPerfProfile.ts index 5daa3e96..ff22b6bf 100644 --- a/ide/src/trace/component/trace/sheet/hiperf/TabPerfProfile.ts +++ b/ide/src/trace/component/trace/sheet/hiperf/TabPerfProfile.ts @@ -495,7 +495,7 @@ export class TabpanePerfProfile extends BaseElement { this.isChartShow = true; this.perfProfilerFilter!.disabledMining = true; showButtonMenu(this.perfProfilerFilter, this.needShowMenu); - if (!data){ + if (!data) { this.perfProfileFrameChart!.data = this.perfProfilerDataSource; } this.perfProfileFrameChart?.calculateChartData(); @@ -579,16 +579,12 @@ export class TabpanePerfProfile extends BaseElement { } getDataByWorker(args: any[], handler: Function) { - this.perfProfileLoadingList.push(1); this.perfProfileProgressEL!.loading = true; this.perfProfileLoadingPage.style.visibility = 'visible'; procedurePool.submitWithName('logic0', 'perf-action', args, undefined, (results: any) => { handler(results); - this.perfProfileLoadingList.splice(0, 1); - if (this.perfProfileLoadingList.length == 0) { - this.perfProfileProgressEL!.loading = false; - this.perfProfileLoadingPage.style.visibility = 'hidden'; - } + this.perfProfileProgressEL!.loading = false; + this.perfProfileLoadingPage.style.visibility = 'hidden'; }); } diff --git a/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts b/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts index 48447d67..d6446a75 100644 --- a/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts +++ b/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts @@ -18,7 +18,7 @@ import { Rect } from './Rect.js'; import { ns2s, ns2UnitS, TimerShaftElement } from '../TimerShaftElement.js'; import { ColorUtils } from '../base/ColorUtils.js'; import { CpuStruct } from '../../../database/ui-worker/ProcedureWorkerCPU.js'; -import { CurrentSlicesTime } from '../../SpSystemTrace.js'; +import {CurrentSlicesTime, SpSystemTrace} from '../../SpSystemTrace.js'; const MarkPadding = 5; const FIT_TOTALX_MIN: number = 280; @@ -306,7 +306,7 @@ export class RangeRuler extends Graph { this.movingMark = null; } - mouseMove(ev: MouseEvent) { + mouseMove(ev: MouseEvent, trace: SpSystemTrace) { this.range.refresh = false; let move_x = ev.offsetX - (this.canvas?.offsetLeft || 0); let move_y = ev.offsetY - (this.canvas?.offsetTop || 0); @@ -342,11 +342,13 @@ export class RangeRuler extends Graph { this.delayDraw(); }); } else if (this.rangeRect.containsWithPadding(move_x, move_y, MarkPadding, 0)) { + trace.style.cursor = 'move'; document.body.style.cursor = 'move'; } else if ( this.frame.containsWithMargin(move_x, move_y, 20, 0, 0, 0) && !this.rangeRect.containsWithMargin(move_x, move_y, 0, MarkPadding, 0, MarkPadding) ) { + trace.style.cursor = 'crosshair'; document.body.style.cursor = 'crosshair'; } if (this.isMovingRange && this.isMouseDown) { diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts index a6cbbd51..6b059cbd 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts @@ -45,7 +45,7 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { isStatistic: boolean = false; boxRangeNativeHook: Array = []; clearBoxSelectionData: boolean = false; - nativeMemoryArgs?: Map + nativeMemoryArgs?: Map; private dataCache = DataCache.getInstance(); handle(data: any): void { @@ -277,12 +277,15 @@ where ts between start_ts and end_ts ${condition}; } queryNativeHookEvent(leftNs: number, rightNs: number, types: Array) { - let condition = types.length === 1 ? `and A.event_type = ${types[0]}` : `and (A.event_type = 'AllocEvent' or A.event_type = 'MmapEvent')`; + let condition = + types.length === 1 + ? `and A.event_type = ${types[0]}` + : `and (A.event_type = 'AllocEvent' or A.event_type = 'MmapEvent')`; let libId = this.nativeMemoryArgs?.get('filterResponseType'); let allocType = this.nativeMemoryArgs?.get('filterAllocType'); let eventType = this.nativeMemoryArgs?.get('filterEventType'); if (libId !== undefined && libId !== -1) { - condition = `${condition} and last_lib_id = ${libId}`;// filter lib + condition = `${condition} and last_lib_id = ${libId}`; // filter lib } if (eventType === '1') { condition = `${condition} and event_type = 'AllocEvent'`; @@ -322,7 +325,7 @@ where ts between start_ts and end_ts ${condition}; supplementNativeHoodData() { let len = this.boxRangeNativeHook.length; - for(let i = 0, j = len -1; i <= j; i++, j--){ + for (let i = 0, j = len - 1; i <= j; i++, j--) { this.fillNativeHook(this.boxRangeNativeHook[i], i); if (i !== j) { this.fillNativeHook(this.boxRangeNativeHook[j], j); @@ -349,10 +352,7 @@ where ts between start_ts and end_ts ${condition}; } if (frame !== null && frame !== undefined) { memory.symbol = this.groupCutFilePath(frame.symbolId, this.dataCache.dataDict.get(frame.symbolId) || ''); - memory.library = this.groupCutFilePath( - frame.fileId, - this.dataCache.dataDict.get(frame.fileId) || 'Unknown Path' - ); + memory.library = this.groupCutFilePath(frame.fileId, this.dataCache.dataDict.get(frame.fileId) || 'Unknown Path'); } else { memory.symbol = '-'; memory.library = '-'; @@ -622,16 +622,14 @@ where ts between start_ts and end_ts ${condition}; let sortType = paramMap.get('sortType'); let statisticsSelection = paramMap.get('statisticsSelection'); let filter = this.boxRangeNativeHook; - if ((filterAllocType !== undefined && filterAllocType !== 0) || + if ( + (filterAllocType !== undefined && filterAllocType !== 0) || (filterEventType !== undefined && filterEventType !== 0) || (filterResponseType !== undefined && filterResponseType !== -1) ) { filter = this.boxRangeNativeHook.filter((item) => { let filterAllocation = true; - let freed = item.endTs > leftNs && - item.endTs <= rightNs && - item.endTs !== 0 && - item.endTs !== null; + let freed = item.endTs > leftNs && item.endTs <= rightNs && item.endTs !== 0 && item.endTs !== null; if (filterAllocType === '1') { filterAllocation = !freed; } else if (filterAllocType == '2') { @@ -836,11 +834,11 @@ where ts between start_ts and end_ts ${condition}; ); } - combineStatisticAndCallChain(samples: NativeHookStatistics[]) { + combineStatisticAndCallChain(samples: NativeHookStatistics[]): Array { samples.sort((a, b) => a.id - b.id); - const analysisSampleList = new Array(); - const applyAllocSamples = new Array(); - const applyMmapSamples = new Array(); + const analysisSampleList: Array = []; + const applyAllocSamples: Array = []; + const applyMmapSamples: Array = []; for (const sample of samples) { const count = this.isStatistic ? sample.count : 1; @@ -890,7 +888,12 @@ where ts between start_ts and end_ts ${condition}; const callChains = this.dataCache.nmHeapFrameMap.get(sample.eventId) || []; if (!callChains || callChains.length === 0) { - return; + analysisSample.libId = -1; + analysisSample.libName = 'Unknown'; + analysisSample.symbolId = -1; + analysisSample.symbolName = 'Unknown'; + analysisSampleList.push(analysisSample); + continue; } let index = callChains.length - 1; let lastFilterCallChain: HeapTreeDataBean | undefined | null; @@ -959,13 +962,21 @@ where ts between start_ts and end_ts ${condition}; if (callChains.length > 0) { let root = this.currentTreeMapData[ - nativeHookSample.tid + '-' + (callChains[topIndex].symbolId || '') + '-' + (callChains[topIndex].fileId || '') + nativeHookSample.tid + + '-' + + (callChains[topIndex].symbolId || '') + + '-' + + (callChains[topIndex].fileId || '') ]; if (root == undefined) { root = new NativeHookCallInfo(); root.threadName = nativeHookSample.threadName; this.currentTreeMapData[ - nativeHookSample.tid + '-' + (callChains[topIndex].symbolId || '') + '-' + (callChains[topIndex].fileId || '') + nativeHookSample.tid + + '-' + + (callChains[topIndex].symbolId || '') + + '-' + + (callChains[topIndex].fileId || '') ] = root; this.currentTreeList.push(root); } diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts index 8e1c9271..d81148f0 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts @@ -18,6 +18,7 @@ import { PerfBottomUpStruct } from '../../bean/PerfBottomUpStruct.js'; const systemRuleName = '/system/'; const numRuleName = '/max/min/'; +const maxDepth = 128; export class ProcedureLogicWorkerPerf extends LogicHandler { filesData: any = {}; @@ -309,8 +310,12 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { } addPerfGroupData(callChain: PerfCallChain) { - this.callChainData[callChain.sampleId] = this.callChainData[callChain.sampleId] || []; - this.callChainData[callChain.sampleId].push(callChain); + const currentCallChain = this.callChainData[callChain.sampleId] || []; + this.callChainData[callChain.sampleId] = currentCallChain; + if (currentCallChain.length > maxDepth){ + currentCallChain.splice(0,1); + } + currentCallChain.push(callChain); } getPerfCallChainsBySampleIds(sampleIds: string[], isTopDown: boolean) { -- Gitee From 9e7d6bbbb824c2a8d82217bc3a216a747bbd7bf7 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:30:50 +0800 Subject: [PATCH 13/18] =?UTF-8?q?=E2=80=99Feat:=E6=96=B0=E5=A2=9EUT?= =?UTF-8?q?=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- .../chart/column/LitChartColumn.test.ts | 33 +- .../base-ui/chart/pie/LitChartPie.test.ts | 12 +- ide/test/base-ui/modal/LitModal.test.ts | 61 +++- ide/test/base-ui/select/LitSelect.test.ts | 7 + ide/test/base-ui/table/LitTable.test.ts | 18 + ide/test/base-ui/tree/LitTree.test.ts | 187 +++++++--- ide/test/hdc/hdcclient/HdcClient.test.ts | 4 - ide/test/js-heap/logic/HeapLoader.test.ts | 8 + .../trace/bean/StateProcessThread.test.ts | 102 +----- .../trace/component/SpInfoAndStas.test.ts | 40 ++- ide/test/trace/component/SpMetrics.test.ts | 42 --- .../trace/component/SpRecordTrace.test.ts | 289 ++++++++------- .../trace/component/chart/FrameChart.test.ts | 332 +++++++++--------- .../component/chart/SpAbilityMonitor.test.ts | 6 + .../component/chart/SpFileSystemChart.test.ts | 10 +- .../component/chart/SpFrameTimeChart.test.ts | 30 ++ .../trace/component/chart/SpHiPerf.test.ts | 4 + .../trace/component/chart/SpLogChart.test.ts | 98 ++++++ .../chart/SpNativeMemoryChart.test.ts | 6 + .../component/chart/SpProcessChart.test.ts | 54 +-- .../component/metrics/CpuStrategy.test.ts | 40 --- .../component/metrics/MemAggStrategy.test.ts | 92 ----- .../component/metrics/MemStrategy.test.ts | 32 -- .../metrics/SysCallsStrategy.test.ts | 32 -- .../metrics/SysCallsTopStrategy.test.ts | 35 -- .../metrics/TraceStatsStrategy.test.ts | 31 -- .../metrics/TraceTaskStrategy.test.ts | 30 -- .../Top20ProcessSwitchCount.test.ts | 7 + .../Top20ProcessThreadCount.test.ts | 7 + .../Top20ThreadRunTime.test.ts | 3 +- .../component/setting/SpAllocations.test.ts | 20 ++ .../SpHisysEvent.test.ts} | 25 +- .../component/setting/SpProbesConfig.test.ts | 4 + .../component/setting/SpRecordPerf.test.ts | 6 + .../component/setting/SpWebHdcShell.test.ts | 112 ++++++ .../component/trace/base/RangeSelect.test.ts | 78 ++++ .../component/trace/base/TraceRow.test.ts | 82 +++++ .../trace/base/TraceRowRecyclerView.test.ts | 6 + .../component/trace/base/TraceSheet.test.ts | 23 ++ .../sheet/TabPaneCurrentSelection.test.ts | 12 + .../trace/sheet/TabPaneFilter.test.ts | 27 ++ .../ability/TabPanePurgPinSelection.test.ts | 203 +++++------ .../sheet/ability/TabPanePurgTotal.test.ts | 212 ++++++----- .../ability/TabPanePurgTotalSelection.test.ts | 6 + .../trace/sheet/ark-ts/TabPaneJsCpu.test.ts | 72 ++++ .../trace/sheet/cpu/TabPaneBoxChild.test.ts | 43 ++- .../sheet/cpu/TabPaneCpuByProcess.test.ts | 4 + .../sheet/cpu/TabPaneCpuByThread.test.ts | 1 + .../trace/sheet/cpu/TabPaneCpuUsage.test.ts | 28 ++ .../trace/sheet/cpu/TabPanePTS.test.ts | 33 -- .../trace/sheet/cpu/TabPaneSPT.test.ts | 26 +- .../sheet/file-system/TabPaneCallTree.test.ts | 52 +++ .../TabPaneFileSystemCalltree.test.ts | 41 ++- .../TabPaneFileSystemDescTimeSlice.test.ts | 2 +- .../TabPaneFilesystemStatistics.test.ts | 65 +++- ...abPaneFilesystemStatisticsAnalysis.test.ts | 113 +++++- .../TabPaneIOTierStatistics.test.ts | 28 +- .../TabPaneIOTierStatisticsAnalysis.test.ts | 131 ++++++- ...aneVirtualMemoryStatisticsAnalysis.test.ts | 132 ++++++- .../TabPaneGpuClickSelectComparison.test.ts | 12 + .../sheet/hiperf/TabPanePerfAnalysis.test.ts | 43 ++- .../sheet/hiperf/TabPerfBottomUp.test.ts | 3 + .../trace/sheet/hiperf/TabPerfProfile.test.ts | 12 + .../native-memory/TabPaneNMCallTree.test.ts | 74 +--- .../TabPaneNMStatisticAnalysis.test.ts | 64 ++++ .../native-memory/TabPaneNMemory.test.ts | 6 + ...abPaneGpuMemoryVmTrackerComparison.test.ts | 10 +- .../trace/timer-shaft/RangeRuler.test.ts | 9 +- .../ProcedureLogicWorkerCommon.test.ts | 134 ++++--- .../ProcedureLogicWorkerFileSystem.test.ts | 71 ++++ .../ProcedureLogicWorkerJsCpuProfiler.test.ts | 41 ++- .../ProcedureLogicWorkerNativeNemory.test.ts | 320 +++++++++++++++++ .../ProcedureLogicWorkerPerf.test.ts | 214 ++++++++++- .../ProcedureLogicWorkerSPT.test.ts | 34 +- ...edureLogicWorkerSchedulingAnalysis.test.ts | 15 + .../ProcedureWorkerAppStartup.test.ts | 2 +- .../ui-worker/ProcedureWorkerCPU.test.ts | 9 +- .../ui-worker/ProcedureWorkerCommon.test.ts | 35 ++ .../ProcedureWorkerEnergyState.test.ts | 6 +- .../ui-worker/ProcedureWorkerLog.test.ts | 115 ++++++ 80 files changed, 3109 insertions(+), 1359 deletions(-) create mode 100644 ide/test/trace/component/chart/SpLogChart.test.ts delete mode 100644 ide/test/trace/component/metrics/CpuStrategy.test.ts delete mode 100644 ide/test/trace/component/metrics/MemAggStrategy.test.ts delete mode 100644 ide/test/trace/component/metrics/MemStrategy.test.ts delete mode 100644 ide/test/trace/component/metrics/SysCallsStrategy.test.ts delete mode 100644 ide/test/trace/component/metrics/SysCallsTopStrategy.test.ts delete mode 100644 ide/test/trace/component/metrics/TraceStatsStrategy.test.ts delete mode 100644 ide/test/trace/component/metrics/TraceTaskStrategy.test.ts rename ide/test/trace/component/{metrics/MetaDataStrategy.test.ts => setting/SpHisysEvent.test.ts} (62%) create mode 100644 ide/test/trace/component/setting/SpWebHdcShell.test.ts create mode 100644 ide/test/trace/component/trace/sheet/ark-ts/TabPaneJsCpu.test.ts create mode 100644 ide/test/trace/database/ui-worker/ProcedureWorkerLog.test.ts diff --git a/ide/test/base-ui/chart/column/LitChartColumn.test.ts b/ide/test/base-ui/chart/column/LitChartColumn.test.ts index 6f2667b9..5940983a 100644 --- a/ide/test/base-ui/chart/column/LitChartColumn.test.ts +++ b/ide/test/base-ui/chart/column/LitChartColumn.test.ts @@ -15,11 +15,10 @@ // @ts-ignore import { LitChartColumn } from '../../../../dist/base-ui/chart/column/LitChartColumn.js'; +import '../../../../dist/base-ui/chart/column/LitChartColumn.js'; // @ts-ignore import { getProbablyTime } from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerCommon.js'; -// @ts-ignore -jest.mock('../../../../dist/base-ui/chart/column/LitChartColumn.js'); window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ @@ -119,4 +118,34 @@ describe('litChartColumn Test', () => { ]; expect(clo.data[0].obj.pid).toBe(2); }); + it('litChartColumnTest04', function () { + let litChartColumn = new LitChartColumn(); + litChartColumn.litChartColumnTipEL = jest.fn(() => true); + litChartColumn.litChartColumnTipEL.style = jest.fn(() => true); + expect(litChartColumn.showTip(14, 5, 't')).toBeUndefined(); + }); + it('litChartColumnTest05', function () { + let litChartColumn = new LitChartColumn(); + litChartColumn.litChartColumnTipEL = jest.fn(() => true); + litChartColumn.litChartColumnTipEL.style = jest.fn(() => true); + expect(litChartColumn.hideTip()).toBeUndefined(); + }); + it('litChartColumnTest06', function () { + document.body.innerHTML = ` +
+ 小按钮 +
`; + let clo = document.getElementById('chart-cloumn') as LitChartColumn; + let mouseOutEvent: MouseEvent = new MouseEvent('mouseout', { clientX: 1, clientY: 2 }); + clo.litChartColumnCanvas.dispatchEvent(mouseOutEvent); + }); + it('litChartColumnTest07', function () { + document.body.innerHTML = ` +
+ 小按钮 +
`; + let clo = document.getElementById('chart-cloumn') as LitChartColumn; + let mouseOutEvent: MouseEvent = new MouseEvent('mousemove', { clientX: 1, clientY: 2 }); + clo.litChartColumnCanvas.dispatchEvent(mouseOutEvent); + }); }); diff --git a/ide/test/base-ui/chart/pie/LitChartPie.test.ts b/ide/test/base-ui/chart/pie/LitChartPie.test.ts index 44b2b364..c102a3c8 100644 --- a/ide/test/base-ui/chart/pie/LitChartPie.test.ts +++ b/ide/test/base-ui/chart/pie/LitChartPie.test.ts @@ -34,9 +34,9 @@ beforeAll(() => { jest.spyOn(document.documentElement, 'scrollTop', 'get').mockImplementation(() => fakeWindow.scrollTop); }); -window.ResizeObserver - = window.ResizeObserver - || jest.fn().mockImplementation(() => ({ +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), @@ -536,4 +536,10 @@ describe('litChartPie Test', () => { let mouseMoveEvent: MouseEvent = new MouseEvent('click', { movementX: 1, movementY: 2 }); clo.canvas.dispatchEvent(mouseMoveEvent); }); + it('litChartPieTest06', function () { + let litChartPie = new LitChartPie(); + litChartPie.pieTipEL = jest.fn(() => true); + litChartPie.pieTipEL.style = jest.fn(() => true); + expect(litChartPie.showTip(1, 4, 'ab')).toBeUndefined(); + }); }); diff --git a/ide/test/base-ui/modal/LitModal.test.ts b/ide/test/base-ui/modal/LitModal.test.ts index 86c159e8..16035dfa 100644 --- a/ide/test/base-ui/modal/LitModal.test.ts +++ b/ide/test/base-ui/modal/LitModal.test.ts @@ -60,14 +60,15 @@ describe('LitModal Test', () => {
`; let litmode = document.getElementById('lit-modal') as LitModal; + litmode.resizing = true; let mouseOutEvent: MouseEvent = new MouseEvent('mousemove', { movementX: 1, movementY: 2 }); litmode.dispatchEvent(mouseOutEvent); }); - it('LitModalTest06', function () { + it('LitModalTest19', function () { document.body.innerHTML = `
- +
`; let litmode = document.getElementById('lit-modal') as LitModal; @@ -112,7 +113,7 @@ describe('LitModal Test', () => { }); it('LitModalTest11', function () { let litModal = new LitModal(); - litModal.visible = false; + litModal.visible = 'visible'; expect(litModal).not.toBeUndefined(); }); it('LitModalTest12', function () { @@ -120,6 +121,11 @@ describe('LitModal Test', () => { litModal.visible = true; expect(litModal).not.toBeUndefined(); }); + it('LitModalTest17', function () { + let litModal = new LitModal(); + litModal.visible = false; + expect(litModal).not.toBeUndefined(); + }); it('LitModalTest13', function () { let litModal = new LitModal(); litModal.width = 'width'; @@ -129,4 +135,53 @@ describe('LitModal Test', () => { let litModal = new LitModal(); expect(litModal.adoptedCallback()).toBeUndefined(); }); + it('LitModalTest15', function () { + let litModal = new LitModal(); + litModal.addEventListener = jest.fn(() => true); + litModal.onOk = true; + expect(litModal).toBeTruthy(); + }); + it('LitModalTest18', function () { + let litModal = new LitModal(); + litModal.addEventListener = jest.fn(() => true); + litModal.onCancel = true; + expect(litModal).toBeTruthy(); + }); + it('LitModalTest19', function () { + document.body.innerHTML = ` +
+ +
`; + let litmode = document.getElementById('lit-modal') as LitModal; + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + litmode.resizeable = false; + litmode.dispatchEvent(mouseClickEvent); + }); + it('LitModalTest20', function () { + document.body.innerHTML = ` +
+ +
`; + let litmode = document.getElementById('lit-modal') as LitModal; + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + litmode.cancelElement.dispatchEvent(mouseClickEvent); + }); + it('LitModalTest21', function () { + document.body.innerHTML = ` +
+ +
`; + let litmode = document.getElementById('lit-modal') as LitModal; + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + litmode.okElement.dispatchEvent(mouseClickEvent); + }); + it('LitModalTest22', function () { + document.body.innerHTML = ` +
+ +
`; + let litmode = document.getElementById('lit-modal') as LitModal; + let mouseDownEvent: MouseEvent = new MouseEvent('mousedown', { clientX: 1, clientY: 2 }); + litmode.dispatchEvent(mouseDownEvent); + }); }); diff --git a/ide/test/base-ui/select/LitSelect.test.ts b/ide/test/base-ui/select/LitSelect.test.ts index 81b65c1e..7b7c0f8b 100644 --- a/ide/test/base-ui/select/LitSelect.test.ts +++ b/ide/test/base-ui/select/LitSelect.test.ts @@ -193,4 +193,11 @@ describe('LitSelect Test', () => { let select = document.querySelector('#litSelect') as LitSelect; expect(select.reset()).toBeUndefined(); }); + it('LitSelectTest31', function () { + document.body.innerHTML = ``; + let select = document.querySelector('#litSelect') as LitSelect; + let mouseClickEvent: MouseEvent = new MouseEvent('click', { movementX: 1, movementY: 2 }); + select.isMultiple = jest.fn(() => true); + select.selectClearEl.dispatchEvent(mouseClickEvent); + }); }); diff --git a/ide/test/base-ui/table/LitTable.test.ts b/ide/test/base-ui/table/LitTable.test.ts index 85ba8a50..aefc33a4 100644 --- a/ide/test/base-ui/table/LitTable.test.ts +++ b/ide/test/base-ui/table/LitTable.test.ts @@ -21,6 +21,7 @@ import { LitTableColumn } from '../../../dist/base-ui/table/lit-table-column.js' import { TableRowObject } from '../../../dist/base-ui/table/TableRowObject.js'; // @ts-ignore import { LitProgressBar } from '../../../dist/base-ui/progress-bar/LitProgressBar.js'; +import { LitIcon } from '../../../src/base-ui/icon/LitIcon.js'; describe('LitTable Test', () => { window.ResizeObserver = window.ResizeObserver || @@ -480,6 +481,17 @@ describe('LitTable Test', () => { litTable.treeElement = document.createElement('div'); litTable.tableElement = document.createElement('div'); litTable.setAttribute('selectable', '123'); + litTable.setAttribute('tree', ''); + litTable.recycleDataSource = [ + { + id: 1, + name: 'name', + }, + { + id: 2, + name: 'nameValue', + }, + ]; let tableColmn = document.createElement('lit-table-column') as LitTableColumn; tableColmn.setAttribute('title', '6'); tableColmn.setAttribute('data-index', '22'); @@ -621,9 +633,15 @@ describe('LitTable Test', () => { expect(litTable.mouseOut()).toBeUndefined(); }); it('LitTableTest49', () => { + litTable.isRecycleList = true; expect(litTable.setCurrentHover({})).toBeUndefined(); }); it('LitTableTest50', () => { expect(litTable.clearAllHover({})).toBeUndefined(); }); + it('LitTableTest52', () => { + let tableIcon = document.createElement('lit-icon') as LitIcon; + let mouseClickEvent: MouseEvent = new MouseEvent('click', { movementX: 1, movementY: 2 }); + tableIcon.dispatchEvent(mouseClickEvent); + }); }); diff --git a/ide/test/base-ui/tree/LitTree.test.ts b/ide/test/base-ui/tree/LitTree.test.ts index 7721bf18..a8ef798d 100644 --- a/ide/test/base-ui/tree/LitTree.test.ts +++ b/ide/test/base-ui/tree/LitTree.test.ts @@ -17,55 +17,142 @@ import { LitTree } from '../../../dist/base-ui/tree/LitTree.js'; describe('LitTree Test', () => { - let litTree = new LitTree(); - litTree.treeData = []; - litTree.multiple = true; - litTree.foldable = true; + let litTree = new LitTree(); + litTree.treeData = []; + litTree.multiple = true; + litTree.foldable = true; - it('litTreeTest01', () => { - expect(litTree.treeData).toStrictEqual([]); - }); - it('litTreeTest02', () => { - expect(litTree.multiple).toStrictEqual(true); - }); - it('litTreeTest03', () => { - expect(litTree.foldable).toBeUndefined(); - }); - it('litTreeTest04', () => { - expect(litTree.getCheckdKeys()).toStrictEqual([]); - }); - it('litTreeTest05', () => { - expect(litTree.getCheckdNodes()).toStrictEqual([]); - }); - it('litTreeTest06', () => { - expect(litTree.expandKeys(['c','a'])).toBeUndefined(); - }); - it('litTreeTest07', () => { - expect(litTree.collapseKeys(['cq','a'])).toBeUndefined(); - }); - it('litTreeTest08', () => { - expect(litTree.checkedKeys(['a'])).toBeUndefined(); - }); - it('litTreeTest09', () => { - expect(litTree.uncheckedKeys(['abc'])).toBeUndefined(); - }); - it('litTreeTest10', () => { - document.body.innerHTML = `
    `; - let ul = document.querySelector('#ul') as HTMLDivElement; - expect(litTree.drawTree(ul,[{},{}],true)).toBeUndefined(); - }); - it('litTreeTest11', () => { - expect(litTree.selectedNode([{},{}])).toBeUndefined(); - }); - it('litTreeTest12', () => { - expect(litTree.closeContextMenu()).toBeUndefined(); - }); - it('litTreeTest13', () => { - expect(litTree.insert([])).toBeUndefined(); - }); - it('litTreeTest14', () => { - document.body.innerHTML = `
      `; - let ul = document.querySelector('#ul') as HTMLDivElement; - expect(litTree._insertNode(ul,[])).toBeUndefined(); - }); + it('litTreeTest01', () => { + expect(litTree.treeData).toStrictEqual([]); + }); + it('litTreeTest02', () => { + expect(litTree.multiple).toStrictEqual(true); + }); + it('litTreeTest03', () => { + expect(litTree.foldable).toBeUndefined(); + }); + it('litTreeTest04', () => { + expect(litTree.getCheckdKeys()).toStrictEqual([]); + }); + it('litTreeTest05', () => { + expect(litTree.getCheckdNodes()).toStrictEqual([]); + }); + it('litTreeTest06', () => { + expect(litTree.expandKeys(['c', 'a'])).toBeUndefined(); + }); + it('litTreeTest07', () => { + expect(litTree.collapseKeys(['cq', 'a'])).toBeUndefined(); + }); + it('litTreeTest08', () => { + expect(litTree.checkedKeys(['a'])).toBeUndefined(); + }); + it('litTreeTest09', () => { + expect(litTree.uncheckedKeys(['abc'])).toBeUndefined(); + }); + it('litTreeTest10', () => { + document.body.innerHTML = `
        `; + let ul = document.querySelector('#ul') as HTMLDivElement; + expect(litTree.drawTree(ul, [{}, {}], true)).toBeUndefined(); + }); + it('litTreeTest11', () => { + expect(litTree.selectedNode([{}, {}])).toBeUndefined(); + }); + it('litTreeTest12', () => { + expect(litTree.closeContextMenu()).toBeUndefined(); + }); + it('litTreeTest13', () => { + expect(litTree.insert([])).toBeUndefined(); + }); + it('litTreeTest14', () => { + document.body.innerHTML = `
          `; + let ul = document.querySelector('#ul') as HTMLDivElement; + expect(litTree._insertNode(ul, [])).toBeUndefined(); + }); + it('litTreeTest15', () => { + expect(litTree.connectedCallback()).toBeUndefined(); + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + litTree.dispatchEvent(mouseClickEvent); + }); + it('litTreeTest16', () => { + expect(litTree.onDrag()).toBeUndefined(); + }); + it('litTreeTest17', () => { + expect(litTree.onDragEnd()).toBeUndefined(); + }); + it('litTreeTest18', () => { + let ev = { + target:{ + open:true, + autoExpand:jest.fn(()=>true), + }, + } + expect(litTree.onDragStart(ev)).toBeUndefined(); + }); + it('litTreeTest19', () => { + let ev = { + target:{ + style:{ + backgroundColor:'#ffffff', + } + }, + } + expect(litTree.onDragEnter(ev)).toBeUndefined(); + }); + it('litTreeTest20', () => { + let ev = { + target:{ + data:{ + key:1, + }, + }, + currentTarget:{ + getBoundingClientRect:jest.fn(()=>true), + }, + } + litTree.srcDragElement = jest.fn(()=>true); + litTree.srcDragElement.data = jest.fn(()=>true); + litTree.srcDragElement.data.key = jest.fn(()=>true); + expect(litTree.onDragOver(ev)).toBeUndefined(); + }); + it('litTreeTest21', () => { + let ev = { + target:{ + style:{ + backgroundColor:'#ffffff', + }, + drawLine:jest.fn(()=>true), + }, + } + expect(litTree.onDragLeave(ev)).toBeUndefined(); + }); + it('litTreeTest22', () => { + let ev = { + target:{ + style:{ + backgroundColor:'#ffffff', + }, + data:1, + drawLine:jest.fn(()=>true), + }, + }; + litTree.srcDragElement = jest.fn(()=>true); + litTree.srcDragElement.data = jest.fn(()=>true); + expect(litTree.onDrop(ev)).toBeUndefined(); + }); + it('litTreeTest23', () => { + let arr = { + findIndex:jest.fn(()=>true), + splice:jest.fn(()=>true), + }; + let d = {}; + expect(litTree.removeDataNode(arr, d)).toBeUndefined(); + }); + it('litTreeTest24', () => { + let arr = { + findIndex:jest.fn(()=>true), + splice:jest.fn(()=>true), + }; + let d = {}; + expect(litTree.addDataNode(arr, d,[],[])).toBeUndefined(); + }); }); diff --git a/ide/test/hdc/hdcclient/HdcClient.test.ts b/ide/test/hdc/hdcclient/HdcClient.test.ts index 6f35a723..fa54f82d 100644 --- a/ide/test/hdc/hdcclient/HdcClient.test.ts +++ b/ide/test/hdc/hdcclient/HdcClient.test.ts @@ -25,10 +25,6 @@ describe('HdcClient Test', () => { let hdcClient = new HdcClient(); expect(hdcClient.bindStream()).toBeUndefined(); }); - it('HdcClientTest03', function () { - let hdcClient = new HdcClient(); - expect(hdcClient.bindStopStream()).toBeUndefined(); - }); it('HdcClientTest04', function () { let hdcClient = new HdcClient(); expect(hdcClient.unbindStream()).toBeTruthy(); diff --git a/ide/test/js-heap/logic/HeapLoader.test.ts b/ide/test/js-heap/logic/HeapLoader.test.ts index e8060c1e..0c904f47 100644 --- a/ide/test/js-heap/logic/HeapLoader.test.ts +++ b/ide/test/js-heap/logic/HeapLoader.test.ts @@ -357,4 +357,12 @@ describe('HeapLoader Test', () => { } expect(heapLoader.processNode(datas,node,1)).toBeUndefined(); }); + it('HeapLoaderTest22', () => { + let heapLoader = new HeapLoader(data); + expect(heapLoader.allocation).toBeTruthy(); + }); + it('HeapLoaderTest23', () => { + let heapLoader = new HeapLoader(data); + expect(heapLoader.getAllocation()).toBeTruthy(); + }); }); \ No newline at end of file diff --git a/ide/test/trace/bean/StateProcessThread.test.ts b/ide/test/trace/bean/StateProcessThread.test.ts index 3789e70c..f8cae2c4 100644 --- a/ide/test/trace/bean/StateProcessThread.test.ts +++ b/ide/test/trace/bean/StateProcessThread.test.ts @@ -14,62 +14,32 @@ */ // @ts-ignore -import { - StateProcessThread, - SPTChild, - SPT, -} from '../../../dist/trace/bean/StateProcessThread.js'; +import { SliceGroup, SPTChild } from '../../../dist/trace/bean/StateProcessThread.js'; describe('StateProcessThread Test', () => { it('StateProcessThreadTest01', function () { - let stateProcessThread = new StateProcessThread(); - stateProcessThread = { - id: 'id', - pid: 'pid', - title: 'title', - process: 'process', - processId: -1, - thread: 'thread', - threadId: -1, - state: 'state', - wallDuration: 0, - avgDuration: 'avgDuration', + let sliceGroup = new SliceGroup(); + sliceGroup = { + title: 'id', count: 0, minDuration: 0, maxDuration: 0, - stdDuration: 'stdDuration', + avgDuration: 'stdDuration', }; - expect(stateProcessThread).not.toBeUndefined(); - expect(stateProcessThread).toMatchInlineSnapshot( -{ - id: expect.any(String), - pid: expect.any(String), - title: expect.any(String), - process: expect.any(String), - processId: expect.any(Number), - thread: expect.any(String), - threadId: expect.any(Number), - wallDuration: expect.any(Number), - avgDuration: expect.any(String), - count: expect.any(Number), - minDuration: expect.any(Number), - maxDuration: expect.any(Number), - stdDuration: expect.any(String) }, ` + expect(sliceGroup).not.toBeUndefined(); + expect(sliceGroup).toMatchInlineSnapshot( + { + title: expect.any(String), + count: expect.any(Number), + minDuration: expect.any(Number), + maxDuration: expect.any(Number), + avgDuration: expect.any(String) }, ` { "avgDuration": Any, "count": Any, - "id": Any, "maxDuration": Any, "minDuration": Any, - "pid": Any, - "process": Any, - "processId": Any, - "state": "state", - "stdDuration": Any, - "thread": Any, - "threadId": Any, "title": Any, - "wallDuration": Any, } `); }); @@ -128,52 +98,6 @@ describe('StateProcessThread Test', () => { "threadId": Any, "threadName": Any, } -` - ); - }); - - it('SPTTest03', function () { - let spt = new SPT(); - spt = { - process: 'process', - processId: 0, - thread: 'thread', - threadId: 0, - state: 'state', - dur: 0, - start_ts: 0, - end_ts: 0, - cpu: 0, - priority: 'priority', - note: 'note', - }; - expect(spt).not.toBeUndefined(); - expect(spt).toMatchInlineSnapshot( -{ - process: expect.any(String), - processId: expect.any(Number), - thread: expect.any(String), - threadId: expect.any(Number), - state: expect.any(String), - dur: expect.any(Number), - start_ts: expect.any(Number), - end_ts: expect.any(Number), - cpu: expect.any(Number), - priority: expect.any(String), - note: expect.any(String) }, ` -{ - "cpu": Any, - "dur": Any, - "end_ts": Any, - "note": Any, - "priority": Any, - "process": Any, - "processId": Any, - "start_ts": Any, - "state": Any, - "thread": Any, - "threadId": Any, -} ` ); }); diff --git a/ide/test/trace/component/SpInfoAndStas.test.ts b/ide/test/trace/component/SpInfoAndStas.test.ts index 9b962834..720a73fc 100644 --- a/ide/test/trace/component/SpInfoAndStas.test.ts +++ b/ide/test/trace/component/SpInfoAndStas.test.ts @@ -15,6 +15,15 @@ // @ts-ignore import { SpInfoAndStats } from '../../../dist/trace/component/SpInfoAndStas.js'; +const sqlit = require('../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../dist/trace/database/SqlLite.js'); +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); describe('SpInfoAndStasTest', () => { document.body.innerHTML = ``; @@ -24,11 +33,6 @@ describe('SpInfoAndStasTest', () => { expect(spInfoAndStats.initElements()).toBeUndefined(); }); - it('SpInfoAndStasTest03', function () { - spInfoAndStats.initMetricItemData = jest.fn(() => true); - expect(spInfoAndStats.initMetricItemData()).toBeTruthy(); - }); - it('SpInfoAndStasTest04', function () { let spInfoAndStats = new SpInfoAndStats(); expect( @@ -57,10 +61,30 @@ describe('SpInfoAndStasTest', () => { expect(spInfoAndStats.attributeChangedCallback([], [], [])).toBeUndefined(); }); - it('SpInfoAndStasTest9', function () { - expect(spInfoAndStats.initMetricItemData()).toBeTruthy(); - }); it('SpInfoAndStasTest10', function () { + let traceMetaData = sqlit.queryTraceMetaData; + let data = [ + { + name: 'a', + valueText: '', + }, + ]; + traceMetaData.mockResolvedValue(data); + let selectTraceMetaData = sqlit.querySelectTraceStats; + let selectData = [ + { + event_name: '', + stat_type: '', + count: 1, + source: 10, + serverity: 23, + }, + ]; + selectTraceMetaData.mockResolvedValue(selectData); + let spInfoAndStats = new SpInfoAndStats(); expect(spInfoAndStats.initMetricItemData()).toBeTruthy(); }); + it('SpInfoAndStasTest11', function () { + expect(spInfoAndStats.initInfoAndStatsData()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/SpMetrics.test.ts b/ide/test/trace/component/SpMetrics.test.ts index 5037d562..c5e916d6 100644 --- a/ide/test/trace/component/SpMetrics.test.ts +++ b/ide/test/trace/component/SpMetrics.test.ts @@ -21,46 +21,4 @@ describe('SpMetrics Test', () => { it('SpMetricsTest01', function () { expect(SpMetrics.initElements).toBeUndefined(); }); - it('SpMetricsTest02', function () { - expect(spMetrics.metric).toBe(''); - }); - it('SpMetricsTest03', function () { - spMetrics.metric = true; - expect(spMetrics.metric).toBe(''); - }); - it('SpMetricsTest04', function () { - expect(spMetrics.metricResult).toBe(''); - }); - it('SpMetricsTest05', function () { - spMetrics.metricResult = true; - expect(spMetrics.metricResult).toBeTruthy(); - }); - - it('SpMetricsTest06', function () { - expect(spMetrics.attributeChangedCallback('metric')).toBeUndefined(); - }); - - it('SpMetricsTest07', function () { - expect(spMetrics.attributeChangedCallback('metricResult')).toBeUndefined(); - }); - - it('SpMetricsTest09', function () { - expect(spMetrics.reset()).toBeUndefined(); - }); - - it('SpMetricsTest10', function () { - expect(spMetrics.connectedCallback()).toBeUndefined(); - }); - - it('SpMetricsTest11', function () { - expect(spMetrics.disconnectedCallback()).toBeUndefined(); - }); - - it('SpMetricsTest12', function () { - expect(spMetrics.initMetricSelectOption()).toBeUndefined(); - }); - - it('SpMetricsTest13', function () { - expect(spMetrics.initMetricDataHandle()).toBeUndefined(); - }); }); diff --git a/ide/test/trace/component/SpRecordTrace.test.ts b/ide/test/trace/component/SpRecordTrace.test.ts index 6c7906c9..81187de1 100644 --- a/ide/test/trace/component/SpRecordTrace.test.ts +++ b/ide/test/trace/component/SpRecordTrace.test.ts @@ -14,10 +14,40 @@ */ // @ts-ignore -import {SpRecordTrace} from '../../../dist/trace/component/SpRecordTrace.js'; +import { SpRecordTrace } from '../../../dist/trace/component/SpRecordTrace.js'; +// @ts-ignore +import { EventCenter } from '../../../dist/trace/component/trace/base/EventCenter.js'; +declare global { + interface Window { + SmartEvent: { + UI: { + DeviceConnect: string; + DeviceDisConnect: string; + }; + }; + subscribe(evt: string, fn: (b: any) => void): void; + unsubscribe(evt: string, fn: (b: any) => void): void; + subscribeOnce(evt: string, fn: (b: any) => void): void; + publish(evt: string, data: any): void; + clearTraceRowComplete(): void; + } +} + +window.SmartEvent = { + UI: { + DeviceConnect: 'SmartEvent-DEVICE_CONNECT', + DeviceDisConnect: 'SmartEvent-DEVICE_DISCONNECT', + }, +}; +Window.prototype.subscribe = (ev, fn) => EventCenter.subscribe(ev, fn); +Window.prototype.unsubscribe = (ev, fn) => EventCenter.unsubscribe(ev, fn); +Window.prototype.publish = (ev, data) => EventCenter.publish(ev, data); +Window.prototype.subscribeOnce = (ev, data) => EventCenter.subscribeOnce(ev, data); +Window.prototype.clearTraceRowComplete = () => EventCenter.clearTraceRowComplete(); // @ts-ignore -window.ResizeObserver = window.ResizeObserver || +window.ResizeObserver = + window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), @@ -87,8 +117,11 @@ describe('SpRecordTrace Test', () => { it('SpRecordTraceTest10', function () { let devs = { - length: 1, + length: 0, }; + spRecordTrace.deviceSelect = document.createElement('select'); + let option = document.createElement('option'); + spRecordTrace.deviceSelect.add(option) expect(spRecordTrace.compareArray(devs)).toBeTruthy(); }); it('SpRecordTraceTest09', function () { @@ -103,11 +136,11 @@ describe('SpRecordTrace Test', () => { }); it('SpRecordTraceTest12', function () { spRecordTrace.showHint = true; - expect(spRecordTrace.showHint).toBeUndefined(); + expect(spRecordTrace.showHint).toBeTruthy(); }); it('SpRecordTraceTest13', function () { spRecordTrace.showHint = false; - expect(spRecordTrace.showHint).toBeUndefined(); + expect(spRecordTrace.showHint).toBeFalsy(); }); it('SpRecordTraceTest14', function () { let event = { @@ -132,9 +165,7 @@ describe('SpRecordTrace Test', () => { sessionConfig: { buffers: [{ pages: 16384, policy: 0 }], keepAliveTime: 0, - resultFile: '/data/local/tmp/hiprofiler_data.htrace', resultMaxSize: 0, - sampleDuration: 30000, sessionMode: 0, }, }); @@ -233,135 +264,139 @@ describe('SpRecordTrace Test', () => { expect(spRecordTrace.freshConfigMenuDisable(true)).toBeUndefined(); }); it('SpRecordTraceTest31', function () { - expect(spRecordTrace.createSdkConfig()).toStrictEqual( - {"configData": {}, "pluginName": "", "sampleInterval": 5000} - ); + expect(spRecordTrace.createSdkConfig()).toStrictEqual({ configData: {}, pluginName: '', sampleInterval: 5000 }); }); it('SpRecordTraceTest32', function () { - expect(spRecordTrace.createHtracePluginConfig()).toStrictEqual( - { - "configData": { - "bufferSizeKb": 20480, - "clock": "boot", - "debugOn": false, - "flushIntervalMs": 1000, - "flushThresholdKb": 4096, - "ftraceEvents": [ - "sched/sched_switch", - "power/suspend_resume", - "sched/sched_wakeup", - "sched/sched_wakeup_new", - "sched/sched_waking", - "sched/sched_process_exit", - "sched/sched_process_free", - "task/task_newtask", - "task/task_rename", - "power/cpu_frequency", - "power/cpu_idle", - ], - "hitraceApps": [], - "hitraceCategories": [ - "ability", - "ace", - "app", - "ark", - "binder", - "disk", - "freq", - "graphic", - "idle", - "irq", - "memreclaim", - "mmc", - "multimodalinput", - "ohos", - "pagecache", - "rpc", - "sched", - "sync", - "window", - "workq", - "zaudio", - "zcamera", - "zimage", - "zmedia", - ], - "hitraceTime": 30, - "parseKsyms": true, - "rawDataPrefix": "", - "traceDurationMs": 0, - "tracePeriodMs": 200, - }, - "pluginName": "ftrace-plugin", - "sampleInterval": 1000, - } - ); + expect(spRecordTrace.createHtracePluginConfig()).toStrictEqual({ + configData: { + bufferSizeKb: 20480, + clock: 'boot', + debugOn: false, + flushIntervalMs: 1000, + flushThresholdKb: 4096, + ftraceEvents: [ + 'sched/sched_switch', + 'power/suspend_resume', + 'sched/sched_wakeup', + 'sched/sched_wakeup_new', + 'sched/sched_waking', + 'sched/sched_process_exit', + 'sched/sched_process_free', + 'task/task_newtask', + 'task/task_rename', + 'power/cpu_frequency', + 'power/cpu_idle', + ], + hitraceApps: [], + hitraceCategories: [ + 'ability', + 'ace', + 'app', + 'ark', + 'binder', + 'disk', + 'freq', + 'graphic', + 'idle', + 'irq', + 'memreclaim', + 'mmc', + 'multimodalinput', + 'ohos', + 'pagecache', + 'rpc', + 'sched', + 'sync', + 'window', + 'workq', + 'zaudio', + 'zcamera', + 'zimage', + 'zmedia', + ], + parseKsyms: true, + rawDataPrefix: '', + traceDurationMs: 0, + tracePeriodMs: 200, + }, + pluginName: 'ftrace-plugin', + sampleInterval: 1000, + }); }); it('SpRecordTraceTest33', function () { - expect(spRecordTrace.createArkTsConfig()).toStrictEqual( - {"configData": {"capture_numeric_value": false,'cpu_profiler_interval':1000, - "interval": 0,'enable_cpu_profiler': false, "pid": 0, "track_allocations": false, "type": -1}, - "pluginName": "arkts-plugin", "sampleInterval": 5000} - ); + expect(spRecordTrace.createArkTsConfig()).toStrictEqual({ + configData: { + capture_numeric_value: false, + cpu_profiler_interval: 1000, + interval: 0, + enable_cpu_profiler: false, + pid: 0, + track_allocations: false, + type: -1, + }, + pluginName: 'arkts-plugin', + sampleInterval: 5000, + }); }); it('SpRecordTraceTest34', function () { - expect(spRecordTrace.createMemoryPluginConfig(1,true,true,true)).toStrictEqual( - { - "configData": { - "pid": [ - 0, - ], - "reportAppMemByMemoryService": false, - "reportAppMemInfo": false, - "reportProcessMemInfo": true, - "reportProcessTree": true, - "reportSmapsMemInfo": true, - "reportSysmemMemInfo": true, - "reportDmaMemInfo": true, - "reportGpuDumpInfo": true, - "reportGpuMemInfo": true, - "reportSysmemVmemInfo": true, - "reportPurgeableAshmemInfo": true, - "sysMeminfoCounters": [ - "PMEM_MEM_TOTAL", - "PMEM_MEM_FREE", - "PMEM_BUFFERS", - "PMEM_CACHED", - "PMEM_SHMEM", - "PMEM_SLAB", - "PMEM_SWAP_TOTAL", - "PMEM_SWAP_FREE", - "PMEM_MAPPED", - "PMEM_VMALLOC_USED", - "PMEM_PAGE_TABLES", - "PMEM_KERNEL_STACK", - "PMEM_ACTIVE", - "PMEM_INACTIVE", - "PMEM_UNEVICTABLE", - "PMEM_VMALLOC_TOTAL", - "PMEM_SLAB_UNRECLAIMABLE", - "PMEM_CMA_TOTAL", - "PMEM_CMA_FREE", - "PMEM_KERNEL_RECLAIMABLE", - ], - "sysVmeminfoCounters": [], - }, - "pluginName": "memory-plugin", - "sampleInterval": 1000, - } - ); + expect(spRecordTrace.createMemoryPluginConfig(1, true, true, true)).toStrictEqual({ + configData: { + pid: [0], + reportAppMemByMemoryService: false, + reportAppMemInfo: false, + reportProcessMemInfo: true, + reportProcessTree: true, + reportSmapsMemInfo: true, + reportSysmemMemInfo: true, + reportDmaMemInfo: true, + reportGpuDumpInfo: true, + reportGpuMemInfo: true, + reportSysmemVmemInfo: true, + reportPurgeableAshmemInfo: true, + sysMeminfoCounters: [ + 'PMEM_MEM_TOTAL', + 'PMEM_MEM_FREE', + 'PMEM_BUFFERS', + 'PMEM_CACHED', + 'PMEM_SHMEM', + 'PMEM_SLAB', + 'PMEM_SWAP_TOTAL', + 'PMEM_SWAP_FREE', + 'PMEM_MAPPED', + 'PMEM_VMALLOC_USED', + 'PMEM_PAGE_TABLES', + 'PMEM_KERNEL_STACK', + 'PMEM_ACTIVE', + 'PMEM_INACTIVE', + 'PMEM_UNEVICTABLE', + 'PMEM_VMALLOC_TOTAL', + 'PMEM_SLAB_UNRECLAIMABLE', + 'PMEM_CMA_TOTAL', + 'PMEM_CMA_FREE', + 'PMEM_KERNEL_RECLAIMABLE', + ], + sysVmeminfoCounters: [], + }, + pluginName: 'memory-plugin', + sampleInterval: 1000, + }); }); it('SpRecordTraceTest35', function () { - expect(spRecordTrace.createSystemConfig()).toStrictEqual( - {"configData": {"cmdLine": "hiebpf --duration 30 --max_stack_depth 10", "outfileName": "/data/local/tmp/ebpf.data"}, "pluginName": "hiebpf-plugin", "sampleInterval": 1000} - ); + expect(spRecordTrace.createSystemConfig()).toStrictEqual({ + configData: { cmdLine: 'hiebpf --duration 30 --max_stack_depth 10', outfileName: '/data/local/tmp/ebpf.data' }, + pluginName: 'hiebpf-plugin', + sampleInterval: 1000, + }); }); it('SpRecordTraceTest36', function () { - expect(spRecordTrace.createSystemConfig({},1)).toStrictEqual( - {"configData": {"cmdLine": "hiebpf --duration 30 --max_stack_depth 10", "outfileName": "/data/local/tmp/ebpf.data"}, "pluginName": "hiebpf-plugin", "sampleInterval": 1000}); - }); - it('SpRecordTraceTest37', function () { - spRecordTrace.record_template = 'record_template'; - expect(spRecordTrace.record_template).toBeTruthy(); + expect(spRecordTrace.createSystemConfig({}, 1)).toStrictEqual({ + configData: { cmdLine: 'hiebpf --duration 30 --max_stack_depth 10', outfileName: '/data/local/tmp/ebpf.data' }, + pluginName: 'hiebpf-plugin', + sampleInterval: 1000, }); + }); + it('SpRecordTraceTest37', function () { + spRecordTrace.record_template = 'record_template'; + expect(spRecordTrace.record_template).toBeTruthy(); + }); }); diff --git a/ide/test/trace/component/chart/FrameChart.test.ts b/ide/test/trace/component/chart/FrameChart.test.ts index 2597a9b8..c34cf996 100644 --- a/ide/test/trace/component/chart/FrameChart.test.ts +++ b/ide/test/trace/component/chart/FrameChart.test.ts @@ -14,19 +14,19 @@ */ // @ts-ignore -import { FrameChart } from '../../../../dist/trace/component/chart/FrameChart.js'; +import { FrameChart, Module } from '../../../../dist/trace/component/chart/FrameChart.js'; // @ts-ignore -import {TraceRow} from '../../../../dist/trace/component/trace/base/TraceRow.js'; +import { TraceRow } from '../../../../dist/trace/component/trace/base/TraceRow.js'; // @ts-ignore -import {ChartMode} from "../../../../dist/trace/bean/FrameChartStruct.js"; +import { ChartMode, ChartStruct } from '../../../../dist/trace/bean/FrameChartStruct.js'; jest.mock('../../../../dist/trace/component/SpSystemTrace.js', () => { - return {}; + return {}; }); jest.mock('../../../../dist/js-heap/model/DatabaseStruct.js', () => {}); const intersectionObserverMock = () => ({ - observe: () => null, + observe: () => null, }); window.IntersectionObserver = jest.fn().mockImplementation(intersectionObserverMock); @@ -39,221 +39,231 @@ window.ResizeObserver = })); jest.mock('../../../../dist/trace/component/trace/base/TraceRow.js', () => { - return {} + return {}; }); describe('FrameChart Test', () => { - let node = [{ children: '' }, { children: { length: 0 } }]; - let node1 = [{ children: '' }, { children: { length: 10 } }]; - let selectData = [(length = 1)]; - document.body.innerHTML = ''; - let frameChart = document.querySelector('#ccc') as FrameChart; - it('FrameChartTest01', function () { - frameChart.tabPaneScrollTop = false; - expect(frameChart.tabPaneScrollTop).toBeFalsy(); - }); - - it('FrameChartTest02', function () { - expect(frameChart.updateFloatHint()).toBeUndefined(); - }); - - it('FrameChartTest03', function () { - frameChart.calculateChartData = jest.fn(() => true); - frameChart.calMaxDepth = jest.fn(() => true); - expect(frameChart.redrawChart(selectData)).toBeUndefined(); - }); - - it('FrameChartTest05', function () { - let index = frameChart.scale(2); - expect(index).toBe(undefined); - }); - - it('FrameChartTest08', function () { - frameChart.translationDraw = jest.fn(() => true); - expect(frameChart.translation()).toBeUndefined(); - }); - - it('FrameChartTest14', function () { - let frameChart = new FrameChart(); - frameChart.translationDraw = jest.fn(() => true); - expect(frameChart.translation(-1)).toBeUndefined(); - }); - - it('FrameChartTest09', function () { - frameChart.selectTotalCount = false; - expect(frameChart.selectTotalCount).toBeFalsy(); - }); - - it('FrameChartTest11', function () { - let frameChart = new FrameChart(); - frameChart._mode = 1; - frameChart.drawScale = jest.fn(() => true); - expect(frameChart.calculateChartData()).not.toBeUndefined(); - }); - - it('FrameChartTest12', function () { - expect(frameChart.updateCanvas()).toBeUndefined(); - }); - - it('FrameChartTest13', function () { - let frameChart = new FrameChart(); - frameChart.translationDraw = jest.fn(() => true); - frameChart.lastCanvasXInScale = 0; - expect(frameChart.translationByScale()).toBe(undefined); - }); - - it('FrameChartTest21', function () { - let frameChart = new FrameChart(); - frameChart.translationDraw = jest.fn(() => true); - frameChart.canvasX = 4; - frameChart.lastCanvasXInScale = 1; - expect(frameChart.translationByScale()).toBe(undefined); - }); - - it('FrameChartTest22', function () { - let frameChart = new FrameChart(); - frameChart.translationDraw = jest.fn(() => true); - expect(frameChart.translationByScale(1)).toBe(undefined); - }); - it('FrameChartTest23', function () { - expect(frameChart.searchData([], 2, 2)).toBeNull(); - }); - - it('FrameChartTest15', function () { - let frameChart = new FrameChart(); - frameChart.calculateChartData = jest.fn(() => true); - frameChart.xPoint = 1; - expect(frameChart.translationDraw()).toBe(undefined); - }); - - it('FrameChartTest16', function () { - expect(frameChart.onMouseClick({ button: 0 })).toBeUndefined(); - }); + let node = [{ children: '' }, { children: { length: 0 } }]; + let node1 = [{ children: '' }, { children: { length: 10 } }]; + let selectData = [(length = 1)]; + document.body.innerHTML = ''; + let frameChart = new FrameChart(); + frameChart.data = [{ + isDraw : false, + depth: 0, + symbol: '', + lib: '', + size: 0, + count: 0, + dur: 0, + searchSize: 0, + searchCount: 0, + searchDur: 0, + drawSize: 0, + drawCount: 0, + drawDur: 0, + parent: undefined, + children: [], + percent: 0, + addr: '', + isSearch: false, + isChartSelect: false, + isChartSelectParent: false + }] + it('FrameChartTest01', function () { + frameChart.tabPaneScrollTop = false; + expect(frameChart.tabPaneScrollTop).toBeFalsy(); + }); + it('FrameChartTest02', function () { + frameChart.createRootNode(); + let index = frameChart.scale(2); + expect(index).toBe(undefined); + }); - it('FrameChartTest18', function () { - let frameChart = new FrameChart(); - expect(frameChart.drawFrameChart(node)).toBeUndefined(); + it('FrameChartTest03', function () { + frameChart.translationDraw = jest.fn(() => true); + expect(frameChart.translation()).toBeUndefined(); }); - it('FrameChartTest20', function () { - expect(frameChart.searchData([], 1, 1)).toBeNull(); + it('FrameChartTest04', function () { + frameChart.translationDraw = jest.fn(() => true); + expect(frameChart.translation(-1)).toBeUndefined(); }); - it('FrameChartTest23', function () { - expect(frameChart.onMouseClick({ button: 2 })).toBeUndefined(); + it('FrameChartTest05', function () { + frameChart.selectTotalCount = false; + expect(frameChart.selectTotalCount).toBeFalsy(); }); - it('FrameChartTest24', function () { - document.body.innerHTML = ``; - expect(frameChart.drawScale()).toBeUndefined(); + it('FrameChartTest06', function () { + frameChart._mode = 1; + frameChart.drawScale = jest.fn(() => true); + expect(frameChart.calculateChartData()).not.toBeUndefined(); }); - it('FrameChartTest25', function () { - let frameChart = new FrameChart(); - frameChart.selectTotalSize = false; - expect(frameChart.selectTotalSize).toBeFalsy(); + it('FrameChartTest07', function () { + expect(frameChart.updateCanvas()).toBeUndefined(); }); - it('FrameChartTest26', function () { - let frameChart = new FrameChart(); - frameChart.maxDepth = false; - expect(frameChart.maxDepth).toBeFalsy(); + it('FrameChartTest08', function () { + frameChart.translationDraw = jest.fn(() => true); + frameChart.lastCanvasXInScale = 0; + expect(frameChart.translationByScale()).toBe(undefined); + }); + + it('FrameChartTest09', function () { + frameChart.translationDraw = jest.fn(() => true); + frameChart.canvasX = 4; + frameChart.lastCanvasXInScale = 1; + expect(frameChart.translationByScale()).toBe(undefined); + }); + + it('FrameChartTest10', function () { + frameChart.translationDraw = jest.fn(() => true); + expect(frameChart.translationByScale(1)).toBe(undefined); }); - it('FrameChartTest27 ', function () { - let frameChart = new FrameChart(); - expect(frameChart.calMaxDepth(node, 1)).toBeUndefined(); + it('FrameChartTest11', function () { + frameChart.calculateChartData = jest.fn(() => true); + frameChart.xPoint = 1; + frameChart.createRootNode(); + expect(frameChart.translationDraw()).toBeTruthy(); + }); + + it('FrameChartTest12', function () { + expect(frameChart.onMouseClick({ button: 0 })).toBeUndefined(); + }); + + it('FrameChartTest13', function () { + expect(frameChart.drawFrameChart(node)).toBeUndefined(); }); - it('FrameChartTest28 ', function () { - let frameChart = new FrameChart(); + + it('FrameChartTest14', function () { + expect(frameChart.onMouseClick({ button: 2 })).toBeUndefined(); + }); + + it('FrameChartTest15 ', function () { expect(frameChart.mode).toBeUndefined(); }); - it('FrameChartTest29', function () { - let frameChart = new FrameChart(); + it('FrameChartTest16', function () { frameChart.mode = false; expect(frameChart.mode).toBeFalsy(); }); - it('FrameChartTest30', function () { + it('FrameChartTest17', function () { frameChart.caldrawArgs = jest.fn(() => true); expect(frameChart.caldrawArgs()).toBeTruthy(); }); - it('FrameChartTest31', function () { - let frameChart = new FrameChart(); - frameChart.data = []; + it('FrameChartTest18', function () { expect(frameChart.data).toBeFalsy(); }); - it('FrameChartTest32', function () { - let frameChart = new FrameChart(); + it('FrameChartTest19', function () { expect(frameChart.addChartClickListener(() => {})).toBeUndefined(); }); - it('FrameChartTest33', function () { - let frameChart = new FrameChart(); + it('FrameChartTest20', function () { expect(frameChart.removeChartClickListener(() => {})).toBeUndefined(); }); - it('FrameChartTest34', function () { - let frameChart = new FrameChart(); - expect(frameChart.calMaxDepth(node1, 10)).toBeUndefined(); - }); - - it('FrameChartTest35', function () { - let frameChart = new FrameChart(); - frameChart.drawTriangleOnScale = jest.fn(() => true); - expect(frameChart.drawTriangleOnScale()).toBeTruthy(); - }); - - it('FrameChartTest36', function () { + it('FrameChartTest21', function () { frameChart._mode = 1; frameChart.drawScale = jest.fn(() => true); expect(frameChart.drawScale()).toBeTruthy(); }); - it('FrameChartTest37', function () { + it('FrameChartTest22', function () { frameChart._mode = 2; frameChart.drawScale = jest.fn(() => true); expect(frameChart.drawScale()).toBeTruthy(); }); - it('FrameChartTest38', function () { + it('FrameChartTest23', function () { frameChart._mode = 3; frameChart.drawScale = jest.fn(() => true); expect(frameChart.drawScale()).toBeTruthy(); }); - it('FrameChartTest39', function () { + it('FrameChartTest24', function () { expect(frameChart.resetTrans()).toBeUndefined(); }); - it('FrameChartTest40', function () { + it('FrameChartTest25', function () { expect(frameChart.onMouseClick({ button: 2 })).toBeUndefined(); }); - it('FrameChartTest41', function () { - expect(frameChart.drawDataSet(node, true)).toBeUndefined(); + it('FrameChartTest26', function () { + frameChart._mode = ChartMode.Byte; + frameChart.drawScale = jest.fn(() => true); + frameChart.currentData = [ + { + drawSize: 10, + size: 20, + frame: { + x: 10, + y: 40, + width: 9, + height: 3, + }, + }, + ]; + expect(frameChart.calculateChartData()).not.toBeUndefined(); + }); + it('FrameChartTest27', function () { + frameChart._mode = ChartMode.Count; + frameChart.drawScale = jest.fn(() => true); + frameChart.currentData = [ + { + drawSize: 23, + size: 12, + frame: { + x: 29, + y: 40, + width: 56, + height: 3, + }, + }, + ]; + expect(frameChart.calculateChartData()).not.toBeUndefined(); + }); + it('FrameChartTest28', function () { + frameChart._mode = ChartMode.Duration; + frameChart.drawScale = jest.fn(() => true); + frameChart.currentData = [ + { + drawSize: 78, + size: 12, + frame: { + x: 29, + y: 50, + width: 56, + height: 12, + }, + }, + ]; + expect(frameChart.calculateChartData()).not.toBeUndefined(); + }); + it('FrameChartTest29 ', function () { + let node = [ + { + parent: [ + { + drawCount: 23, + drawDur: 12, + drawSize: 45, + }, + ], + }, + ]; + let module = [{ + drawCount: 0, + drawDur: 78, + drawSize: 9, + }] + expect(frameChart.setParentDisplayInfo(node, module)).toBeUndefined(); }); - it('FrameChartTest42', function () { - let frameChart = new FrameChart(); - frameChart._mode = ChartMode.Byte; - frameChart.drawScale = jest.fn(() => true); - expect(frameChart.calculateChartData()).not.toBeUndefined(); - }); - it('FrameChartTest44', function () { - let frameChart = new FrameChart(); - frameChart._mode = ChartMode.Count; - frameChart.drawScale = jest.fn(() => true); - expect(frameChart.calculateChartData()).not.toBeUndefined(); - }); - it('FrameChartTest45', function () { - let frameChart = new FrameChart(); - frameChart._mode = ChartMode.Duration; - frameChart.drawScale = jest.fn(() => true); - expect(frameChart.calculateChartData()).not.toBeUndefined(); - }); }); diff --git a/ide/test/trace/component/chart/SpAbilityMonitor.test.ts b/ide/test/trace/component/chart/SpAbilityMonitor.test.ts index 0a3ce49e..e7688c02 100644 --- a/ide/test/trace/component/chart/SpAbilityMonitor.test.ts +++ b/ide/test/trace/component/chart/SpAbilityMonitor.test.ts @@ -23,6 +23,8 @@ jest.mock('../../../../dist/trace/database/ui-worker/ProcedureWorker.js', () => }); const sqlit = require('../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../dist/trace/database/SqlLite.js'); +// @ts-ignore +import { TraceRow } from '../../../../dist/trace/component/trace/base/TraceRow.js'; const intersectionObserverMock = () => ({ observe: () => null, }); @@ -153,4 +155,8 @@ describe('SpAbilityMonitorChart Test', () => { trace.init(); expect(trace).toBeDefined(); }); + it('SpAbilityMonitorChart02', function () { + let traceRow = new TraceRow(); + expect(trace.initNetworkAbility(traceRow)).toBeDefined(); + }); }); diff --git a/ide/test/trace/component/chart/SpFileSystemChart.test.ts b/ide/test/trace/component/chart/SpFileSystemChart.test.ts index dc537cba..9ad2cbf4 100644 --- a/ide/test/trace/component/chart/SpFileSystemChart.test.ts +++ b/ide/test/trace/component/chart/SpFileSystemChart.test.ts @@ -19,7 +19,11 @@ import { SpFileSystemChart } from '../../../../dist/trace/component/chart/SpFile import { SpChartManager } from '../../../../dist/trace/component/chart/SpChartManager.js'; const sqlit = require('../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../dist/trace/database/SqlLite.js'); - +// @ts-ignore +import { TraceRow } from '../../../../dist/trace/component/trace/base/TraceRow.js'; +// @ts-ignore +import { SpSystemTrace } from '../../../../dist/trace/component/SpSystemTrace.js'; +jest.mock('../../../../dist/js-heap/model/DatabaseStruct.js', () => {}); window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ @@ -45,4 +49,8 @@ describe('SpFileSystemChart Test', () => { spFileSystemChart.init(); expect(spFileSystemChart).toBeDefined(); }); + it('SpMpsChart02', function () { + ss.displayTip = jest.fn(() => true); + expect(spFileSystemChart.focusHandler(TraceRow)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/chart/SpFrameTimeChart.test.ts b/ide/test/trace/component/chart/SpFrameTimeChart.test.ts index f391b7b1..64461cc8 100644 --- a/ide/test/trace/component/chart/SpFrameTimeChart.test.ts +++ b/ide/test/trace/component/chart/SpFrameTimeChart.test.ts @@ -174,4 +174,34 @@ describe('SpFrameTimeChart Test', () => { ); expect(spFrameTimeChart.flagConfig?.AnimationAnalysis).toEqual('Enabled'); }); + it('TabPaneFramesTest03', function () { + expect(spFrameTimeChart.frameNoExpandTimeOut()).toBeTruthy(); + }); + it('TabPaneFramesTest04', function () { + expect(spFrameTimeChart.frameExpandTimeOut()).toBeTruthy(); + }); + it('TabPaneFramesTest05', function () { + let frameData = [{ + currentTs:23, + currentFrameWidth:9, + currentFrameHeight:5, + x:2, + y:78, + }, + { + currentTs:12, + currentFrameWidth:9, + currentFrameHeight:5, + x:21, + y:78, + }, + ]; + let deviceStruct = [{ + physicalWidth:40, + physicalHeight:41, + }]; + spFrameTimeChart.flagConfig = jest.fn(()=>true); + spFrameTimeChart.flagConfig.physicalWidth = jest.fn(()=>true); + expect(spFrameTimeChart.dataProcessing(frameData,deviceStruct)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/chart/SpHiPerf.test.ts b/ide/test/trace/component/chart/SpHiPerf.test.ts index 21d54e6e..72e2949c 100644 --- a/ide/test/trace/component/chart/SpHiPerf.test.ts +++ b/ide/test/trace/component/chart/SpHiPerf.test.ts @@ -130,4 +130,8 @@ describe('SpHiPerf Test', () => { spHiPerf.init(); expect(spHiPerf).toBeDefined(); }); + it('SpHiPerf02', function () { + ss.displayTip = jest.fn(()=>true); + expect(spHiPerf.hoverTip()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/chart/SpLogChart.test.ts b/ide/test/trace/component/chart/SpLogChart.test.ts new file mode 100644 index 00000000..ebd985d1 --- /dev/null +++ b/ide/test/trace/component/chart/SpLogChart.test.ts @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// @ts-ignore +import { SpChartManager } from '../../../../dist/trace/component/chart/SpChartManager.js'; +// @ts-ignore +import { SpLogChart } from '../../../../dist/trace/component/chart/SpLogChart.js'; + +const sqlite = require('../../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../../dist/trace/database/SqlLite.js'); + +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); + +describe('SpLogChart Test', () => { + let logChart = new SpLogChart(new SpChartManager()); + let queryLog = sqlite.queryLogData; + let queryLogData = [ + { + id: 2, + startTs: 0, + level: 'I', + depth: 1, + tag: 'C02d0c/Hiprofiler', + context: 'ParseTimeExtend: update ts with 0 to 33727453411', + time: 1502029274737385200, + pid: 1119, + tid: 1172, + processName: 'hiprofiler_plug', + dur: 1, + frame: { + x: 0, + y: 7, + width: 1, + height: 7, + }, + }, + { + id: 37, + startTs: 76402674, + level: 'W', + depth: 2, + tag: 'C01300/AbilityManagerService', + context: '[ability_manager_service.cpp(UpdateCallerInfo:6178)]UpdateCallerInfo caller abilityRecord is null.', + time: 1502029274813788000, + pid: 558, + tid: 558, + processName: 'foundation', + dur: 1, + frame: { + x: 3, + y: 14, + width: 1, + height: 7, + }, + }, + { + id: 99, + startTs: 579581683, + level: 'E', + depth: 3, + tag: 'C01300/AbilityManagerService', + context: '[ability_interceptor.cpp(CheckCrowdtest:104)]GetApplicaionInfo from bms failed.', + time: 1502029275316967000, + pid: 558, + tid: 558, + processName: 'foundation', + dur: 1, + frame: { + x: 29, + y: 21, + width: 1, + height: 7, + }, + }, + ]; + queryLog.mockResolvedValue(queryLogData); + it('SpLogChart01', function () { + expect(logChart.init()).toBeDefined(); + }); +}); diff --git a/ide/test/trace/component/chart/SpNativeMemoryChart.test.ts b/ide/test/trace/component/chart/SpNativeMemoryChart.test.ts index b84fe247..d24d8e7a 100644 --- a/ide/test/trace/component/chart/SpNativeMemoryChart.test.ts +++ b/ide/test/trace/component/chart/SpNativeMemoryChart.test.ts @@ -79,4 +79,10 @@ describe('SpNativeMemoryChart Test', () => { it('SpNativeMemoryChart01', function () { expect(spNativeMemoryChart.initChart()).toBeDefined(); }); + it('SpNativeMemoryChart02', function () { + expect(spNativeMemoryChart.getNativeMemoryStatisticByChartType()).toBeDefined(); + }); + it('SpNativeMemoryChart03', function () { + expect(spNativeMemoryChart.getNativeMemoryDataByChartType()).toBeDefined(); + }); }); diff --git a/ide/test/trace/component/chart/SpProcessChart.test.ts b/ide/test/trace/component/chart/SpProcessChart.test.ts index 46a329ec..328a1f9a 100644 --- a/ide/test/trace/component/chart/SpProcessChart.test.ts +++ b/ide/test/trace/component/chart/SpProcessChart.test.ts @@ -26,13 +26,14 @@ const intersectionObserverMock = () => ({ observe: () => null, }); window.IntersectionObserver = jest.fn().mockImplementation(intersectionObserverMock); +// @ts-ignore import { SpChartManager } from '../../../../dist/trace/component/chart/SpChartManager.js'; // @ts-ignore window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ - observe: jest.fn(), - unobserve: jest.fn(), - disconnect: jest.fn(), - })); + observe: jest.fn(), + unobserve: jest.fn(), + disconnect: jest.fn(), +})); describe('SpProcessChart Test', () => { let manager = new SpChartManager(); @@ -66,16 +67,7 @@ describe('SpProcessChart Test', () => { }, ]); let queryProcessThreads = sqlit.queryProcessThreads; - queryProcessThreads.mockResolvedValue([ - { - utid: 1, - hasSched: 0, - pid: 1, - tid: 4, - processName: 'process', - threadName: 'thread', - }, - ]); + queryProcessThreads.mockResolvedValue([]); let queryProcessThreadsByTable = sqlit.queryProcessThreadsByTable; queryProcessThreadsByTable.mockResolvedValue([ { @@ -85,13 +77,6 @@ describe('SpProcessChart Test', () => { threadName: 'thread', }, ]); - let getAsyncEvents = sqlit.getAsyncEvents; - getAsyncEvents.mockResolvedValue([ - { - pid: 1, - startTime: 100000, - }, - ]); let queryProcessMem = sqlit.queryProcessMem; queryProcessMem.mockResolvedValue([ { @@ -524,11 +509,36 @@ describe('SpProcessChart Test', () => { } } ]); + let processData = sqlit.queryProcessData; + processData.mockResolvedValue([ + { + cpu: 0, dur: 199000, startTime: 259730000 + }, + { + cpu: 2, dur: 147000, startTime: 307742000 + } + ]); + let processMemData = sqlit.queryProcessMemData; + processMemData.mockResolvedValue([ + { + startTime: 593015789, + track_id : 153, + ts : 30150767408970, + type : "measure", + value : 0 + }, + { + startTime: 593360060, + track_id : 153, + ts : 30150767753241, + type : "measure", + value : 1 + } + ]); spProcessChart.setAttribute = jest.fn(); spProcessChart.addChildTraceRow = jest.fn(); it('SpProcessChart01', function () { - spProcessChart.initAsyncFuncData(); spProcessChart.init(); expect(spProcessChart).toBeDefined(); }); diff --git a/ide/test/trace/component/metrics/CpuStrategy.test.ts b/ide/test/trace/component/metrics/CpuStrategy.test.ts deleted file mode 100644 index b908481c..00000000 --- a/ide/test/trace/component/metrics/CpuStrategy.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initTest, initCpuStrategyData } from '../../../../dist/trace/component/metrics/CpuStrategy.js'; - -describe('CpuStrategy Test', () => { - const metricData = [ - { - length: 1, - event_name: 'name', - stat_type: 1, - count: 1, - source: 1, - serverity: 0, - avg_frequency: null, - cpu: 1, - min_freq: '', - max_freq: '', - duration: 1, - process_name: '', - thread_name: '', - }, - ]; - - it('initCpuStrategyDataTest01', () => { - expect(initCpuStrategyData(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/metrics/MemAggStrategy.test.ts b/ide/test/trace/component/metrics/MemAggStrategy.test.ts deleted file mode 100644 index 7f567100..00000000 --- a/ide/test/trace/component/metrics/MemAggStrategy.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initMemoryAggStrategy } from '../../../../dist/trace/component/metrics/MemAggStrategy.js'; - -describe('MemAggStrategy Test', () => { - let metricData = [ - { - length: 1, - processName: 'name', - name: 'oom_score_adj', - value: '', - ts: '', - }, - ]; - it('initMemoryAggStrategyTest01', () => { - const metricData = [ - { - length: 11, - processName: 'name', - name: 'oom_score_adj', - value: '', - ts: '', - }, - ]; - expect(initMemoryAggStrategy(metricData)).toBeTruthy(); - }); - - it('initMemoryAggStrategyTest02', () => { - const metricData = [ - { - length: 12, - processName: 'name', - name: 'mem.rss.anon', - value: '', - ts: '', - }, - ]; - expect(initMemoryAggStrategy(metricData)).toBeTruthy(); - }); - - it('initMemoryAggStrategyTest03', () => { - const metricData = [ - { - length: 13, - processName: 'name', - name: 'mem.swap', - value: '', - ts: '', - }, - ]; - expect(initMemoryAggStrategy(metricData)).toBeTruthy(); - }); - - it('initMemoryAggStrategyTest04', () => { - const metricData = [ - { - length: 14, - processName: 'name', - name: 'mem.rss.file', - value: '', - ts: '', - }, - ]; - expect(initMemoryAggStrategy(metricData)).toBeTruthy(); - }); - - it('initMemoryAggStrategyTest05', () => { - const metricData = [ - { - length: 15, - processName: 'name', - name: 'oom_score_adj', - value: '', - ts: '', - }, - ]; - expect(initMemoryAggStrategy(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/metrics/MemStrategy.test.ts b/ide/test/trace/component/metrics/MemStrategy.test.ts deleted file mode 100644 index e5559fb2..00000000 --- a/ide/test/trace/component/metrics/MemStrategy.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initMemoryStrategy } from '../../../../dist/trace/component/metrics/MemStrategy.js'; - -describe('MemStrategy Test', () => { - const metricData = [ - { - length: 1, - minNum: 'name', - maxNum: '', - avgNum: '', - processName: '', - }, - ]; - - it('initMemoryStrategyTest01', () => { - expect(initMemoryStrategy(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/metrics/SysCallsStrategy.test.ts b/ide/test/trace/component/metrics/SysCallsStrategy.test.ts deleted file mode 100644 index 5c4f3e60..00000000 --- a/ide/test/trace/component/metrics/SysCallsStrategy.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initSysCallsStrategy } from '../../../../dist/trace/component/metrics/SysCallsStrategy.js'; - -describe('SysCallsStrategy Test', () => { - const metricData = [ - { - length: 1, - funName: 'name', - maxDur: '', - minDur: '', - avgDur: '', - }, - ]; - - it('initMetaDataStrategyTest01', () => { - expect(initSysCallsStrategy(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/metrics/SysCallsTopStrategy.test.ts b/ide/test/trace/component/metrics/SysCallsTopStrategy.test.ts deleted file mode 100644 index 43cea5bf..00000000 --- a/ide/test/trace/component/metrics/SysCallsTopStrategy.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initSysCallsTopStrategy } from '../../../../dist/trace/component/metrics/SysCallsTopStrategy.js'; - -describe('SysCallsTopStrategy Test', () => { - const metricData = [ - { - length: 1, - pid: 'pi', - tid: 'ti', - process_name: '', - maxDur: 'name', - minDur: '', - avgDur: '', - funName: '', - }, - ]; - - it('initSysCallsTopStrategyTest01', () => { - expect(initSysCallsTopStrategy(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/metrics/TraceStatsStrategy.test.ts b/ide/test/trace/component/metrics/TraceStatsStrategy.test.ts deleted file mode 100644 index f63abbf5..00000000 --- a/ide/test/trace/component/metrics/TraceStatsStrategy.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initTraceStateStrategy } from '../../../../dist/trace/component/metrics/TraceStatsStrategy.js'; - -describe('TraceTaskStrategy Test', () => { - let metricData = [ - { - length: 1, - event_name: 'name', - count: 1, - source: 1, - serverity: 0, - }, - ]; - it('initTraceStateStrategyTest01', () => { - expect(initTraceStateStrategy(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/metrics/TraceTaskStrategy.test.ts b/ide/test/trace/component/metrics/TraceTaskStrategy.test.ts deleted file mode 100644 index 5c47e34a..00000000 --- a/ide/test/trace/component/metrics/TraceTaskStrategy.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// @ts-ignore -import { initTraceTaskStrategy } from '../../../../dist/trace/component/metrics/TraceTaskStrategy.js'; - -describe('TraceTaskStrategy Test', () => { - let metricData = [ - { - length: 1, - process_name: '', - thread_name: '', - pid: 3, - }, - ]; - it('initTraceTaskStrategyTest01', () => { - expect(initTraceTaskStrategy(metricData)).toBeTruthy(); - }); -}); diff --git a/ide/test/trace/component/schedulingAnalysis/Top20ProcessSwitchCount.test.ts b/ide/test/trace/component/schedulingAnalysis/Top20ProcessSwitchCount.test.ts index aa764223..330f5a50 100644 --- a/ide/test/trace/component/schedulingAnalysis/Top20ProcessSwitchCount.test.ts +++ b/ide/test/trace/component/schedulingAnalysis/Top20ProcessSwitchCount.test.ts @@ -41,4 +41,11 @@ describe('Top20ProcessSwitchCount Test', () => { top20ProcessSwitchCount.queryLogicWorker = jest.fn(); expect(top20ProcessSwitchCount.queryLogicWorker('', '', {})).toBeUndefined(); }); + it('Top20ProcessSwitchCountTest04', () => { + let top20ProcessSwitchCount = new Top20ProcessSwitchCount(); + top20ProcessSwitchCount.queryLogicWorker = jest.fn(); + top20ProcessSwitchCount.processSwitchCountTbl = jest.fn(); + top20ProcessSwitchCount.processSwitchCountTbl.recycleDataSource = jest.fn(); + expect(top20ProcessSwitchCount.init()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/schedulingAnalysis/Top20ProcessThreadCount.test.ts b/ide/test/trace/component/schedulingAnalysis/Top20ProcessThreadCount.test.ts index e80515d9..3cdecd16 100644 --- a/ide/test/trace/component/schedulingAnalysis/Top20ProcessThreadCount.test.ts +++ b/ide/test/trace/component/schedulingAnalysis/Top20ProcessThreadCount.test.ts @@ -41,4 +41,11 @@ describe('Top20ProcessSwitchCount Test', () => { top20ProcessThreadCount.queryLogicWorker = jest.fn(); expect(top20ProcessThreadCount.queryLogicWorker('', '', {})).toBeUndefined(); }); + it('Top20ProcessSwitchCountTest04', () => { + let top20ProcessThreadCount = new Top20ProcessThreadCount(); + top20ProcessThreadCount.queryLogicWorker = jest.fn(); + top20ProcessThreadCount.processThreadCountTbl = jest.fn(); + top20ProcessThreadCount.processThreadCountTbl.recycleDataSource = jest.fn(); + expect(top20ProcessThreadCount.init()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/schedulingAnalysis/Top20ThreadRunTime.test.ts b/ide/test/trace/component/schedulingAnalysis/Top20ThreadRunTime.test.ts index 1a0e34d2..9076b30e 100644 --- a/ide/test/trace/component/schedulingAnalysis/Top20ThreadRunTime.test.ts +++ b/ide/test/trace/component/schedulingAnalysis/Top20ThreadRunTime.test.ts @@ -44,7 +44,8 @@ describe('Top20ThreadRunTime Test', () => { it('Top20ThreadRunTimeTest04', () => { let top20ThreadRunTime = new Top20ThreadRunTime(); top20ThreadRunTime.queryLogicWorker = jest.fn(); - top20ThreadRunTime.init = jest.fn(); + top20ThreadRunTime.threadRunTimeTbl = jest.fn(); + top20ThreadRunTime.threadRunTimeTbl.recycleDataSource = jest.fn(); expect(top20ThreadRunTime.init()).toBeUndefined(); }); }); diff --git a/ide/test/trace/component/setting/SpAllocations.test.ts b/ide/test/trace/component/setting/SpAllocations.test.ts index 974402d7..d22d6549 100644 --- a/ide/test/trace/component/setting/SpAllocations.test.ts +++ b/ide/test/trace/component/setting/SpAllocations.test.ts @@ -104,4 +104,24 @@ describe('SpAllocations Test', () => { let spAllocations = document.querySelector('#sp') as SpAllocations; expect(spAllocations.fp_unwind).toBeTruthy(); }); + it('SpAllocations test10', function () { + let spAllocations = document.querySelector('#sp') as SpAllocations; + expect(spAllocations.record_accurately).toBeTruthy(); + }); + it('SpAllocations test11', function () { + let spAllocations = document.querySelector('#sp') as SpAllocations; + expect(spAllocations.offline_symbolization).toBeTruthy(); + }); + it('SpAllocations test12', function () { + let spAllocations = document.querySelector('#sp') as SpAllocations; + expect(spAllocations.record_statistics).toBeTruthy(); + }); + it('SpAllocations test13', function () { + let spAllocations = document.querySelector('#sp') as SpAllocations; + expect(spAllocations.statistics_interval).toBeTruthy(); + }); + it('SpAllocations test14', function () { + let spAllocations = document.querySelector('#sp') as SpAllocations; + expect(spAllocations.startup_mode).toBeFalsy(); + }); }); diff --git a/ide/test/trace/component/metrics/MetaDataStrategy.test.ts b/ide/test/trace/component/setting/SpHisysEvent.test.ts similarity index 62% rename from ide/test/trace/component/metrics/MetaDataStrategy.test.ts rename to ide/test/trace/component/setting/SpHisysEvent.test.ts index f4aeb459..3633c87b 100644 --- a/ide/test/trace/component/metrics/MetaDataStrategy.test.ts +++ b/ide/test/trace/component/setting/SpHisysEvent.test.ts @@ -12,19 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// @ts-ignore -import { initMetaDataStrategy } from '../../../../dist/trace/component/metrics/MetaDataStrategy.js'; -describe('MetaDataStrategy Test', () => { - const metricData = [ - { - length: 1, - name: 'name', - valueText: '', - }, - ]; +// @ts-ignore +import { SpHisysEvent } from '../../../../dist/trace/component/setting/SpHisysEvent.js'; - it('initMetaDataStrategyTest01', () => { - expect(initMetaDataStrategy(metricData)).toBeTruthy(); - }); -}); +describe('SpHisysEvent Test', () => { + let spHisysEvent = new SpHisysEvent(); + it('SpHisysEventTest01', function () { + expect(spHisysEvent.startSamp).toBeFalsy(); + }); + it('SpHisysEventTest02', function () { + expect(spHisysEvent.process).toBeFalsy(); + }); +}) \ No newline at end of file diff --git a/ide/test/trace/component/setting/SpProbesConfig.test.ts b/ide/test/trace/component/setting/SpProbesConfig.test.ts index d34eba50..3fb263d1 100644 --- a/ide/test/trace/component/setting/SpProbesConfig.test.ts +++ b/ide/test/trace/component/setting/SpProbesConfig.test.ts @@ -32,4 +32,8 @@ describe('SpProbesConfig Test', () => { expect(spEle.traceEvents.length).toEqual(24); expect(spEle.memoryConfig).toEqual([]); }); + it('new SpProbesConfig02', function () { + let spEle = document.querySelector('#spconfig') as SpProbesConfig; + expect(spEle.recordAbility).toBeFalsy(); + }); }); diff --git a/ide/test/trace/component/setting/SpRecordPerf.test.ts b/ide/test/trace/component/setting/SpRecordPerf.test.ts index 800a0243..1bcc76db 100644 --- a/ide/test/trace/component/setting/SpRecordPerf.test.ts +++ b/ide/test/trace/component/setting/SpRecordPerf.test.ts @@ -62,4 +62,10 @@ describe('SpRecordPerf Test', () => { spRecordPerf.startSamp = true; expect(spRecordPerf.startSamp).toBeTruthy(); }); + it('SpRecordPerfTest011', function () { + expect(spRecordPerf.getPerfConfig()).toBeTruthy(); + }); + it('SpRecordPerfTest012', function () { + expect(spRecordPerf.parseEvent('adfger')).toBeTruthy(); + }); }); diff --git a/ide/test/trace/component/setting/SpWebHdcShell.test.ts b/ide/test/trace/component/setting/SpWebHdcShell.test.ts new file mode 100644 index 00000000..94e85fc8 --- /dev/null +++ b/ide/test/trace/component/setting/SpWebHdcShell.test.ts @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// @ts-ignore +import { DataMessage } from '../../../../dist/hdc/message/DataMessage.js'; + +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); + +// @ts-ignore +import { SpWebHdcShell } from '../../../../dist/trace/component/setting/SpWebHdcShell.js'; +// @ts-ignore +import { EventCenter } from '../../../../dist/trace/component/trace/base/EventCenter.js'; +// @ts-ignore +import { USBHead } from '../../../../dist/hdc/message/USBHead.js'; + +declare global { + interface Window { + SmartEvent: { + UI: { + DeviceConnect: string; + DeviceDisConnect: string; + }; + }; + subscribe(evt: string, fn: (b: any) => void): void; + unsubscribe(evt: string, fn: (b: any) => void): void; + subscribeOnce(evt: string, fn: (b: any) => void): void; + publish(evt: string, data: any): void; + clearTraceRowComplete(): void; + } +} + +window.SmartEvent = { + UI: { + DeviceConnect: 'SmartEvent-DEVICE_CONNECT', + DeviceDisConnect: 'SmartEvent-DEVICE_DISCONNECT', + }, +}; + +Window.prototype.subscribe = (ev, fn) => EventCenter.subscribe(ev, fn); +Window.prototype.unsubscribe = (ev, fn) => EventCenter.unsubscribe(ev, fn); +Window.prototype.publish = (ev, data) => EventCenter.publish(ev, data); +Window.prototype.subscribeOnce = (ev, data) => EventCenter.subscribeOnce(ev, data); +Window.prototype.clearTraceRowComplete = () => EventCenter.clearTraceRowComplete(); +describe('SpWebHdcShell Test', () => { + let spWebHdcShell = new SpWebHdcShell(); + it('SpWebHdcShell Test01', function () { + expect(spWebHdcShell.initElements()).toBeUndefined(); + }); + + it('SpWebHdcShell Test02', function () { + expect(spWebHdcShell.initHtml()).not.toBeNull(); + }); + + it('SpWebHdcShell Test03', function () { + let arrayBufferA = new Uint8Array(1); + arrayBufferA.set([1]); + let arrayBufferB = new Uint8Array(1); + arrayBufferB.set([1]); + expect(spWebHdcShell.arrayBufferCompare(arrayBufferA, arrayBufferB)).toBeTruthy(); + }); + + it('SpWebHdcShell Test05', function () { + let arrayBufferA = new Uint8Array(1); + arrayBufferA.set([2]); + let arrayBufferB = new Uint8Array(1); + arrayBufferB.set([1]); + expect(spWebHdcShell.arrayBufferCompare(arrayBufferA, arrayBufferB)).toBeFalsy(); + }); + + it('SpWebHdcShell Test06', function () { + let dataHead = new USBHead([85, 66], 1, 77777, 0); + let dataMessage = new DataMessage(dataHead); + expect(spWebHdcShell.handleHdcRecvData(dataMessage)).toBeUndefined(); + }); + + it('SpWebHdcShell Test07', function () { + let dataHead = new USBHead([85, 66], 1, 77777, 21); + let arrayBuffer = new Uint8Array(21); + arrayBuffer.set([72,87,0,0,2,0,8,0,0,0,2,8,2,16,10,24,0,32,9,35,32]); + let body = new DataView(arrayBuffer.buffer); + let dataMessage = new DataMessage(dataHead, body); + expect(spWebHdcShell.handleHdcRecvData(dataMessage)).toBeUndefined(); + }); + it('SpWebHdcShell Test011', function () { + expect(spWebHdcShell.clear()).toBeUndefined(); + }); + it('SpWebHdcShell Test012', function () { + let shellStr = '111111111111111111111111111111'; + let res = spWebHdcShell.singleLineToMultiLine(shellStr,1,10) + expect(res).toEqual(["1111111111","1111111111","1111111111"]) + }); + it('SpWebHdcShell Test013', function () { + expect(spWebHdcShell.forwardSelected(0,1120,0,1111)).toBeUndefined(); + }); +}); diff --git a/ide/test/trace/component/trace/base/RangeSelect.test.ts b/ide/test/trace/component/trace/base/RangeSelect.test.ts index ef9ec046..f9182b93 100644 --- a/ide/test/trace/component/trace/base/RangeSelect.test.ts +++ b/ide/test/trace/component/trace/base/RangeSelect.test.ts @@ -117,6 +117,13 @@ describe('RangeSelect Test', () => { }); rangeSelect.spacerEL = jest.fn(() => true); rangeSelect.spacerEL.offsetTop = jest.fn(() => 1); + rangeSelect.drag = true; + rangeSelect.rowsEL = jest.fn(() => true); + rangeSelect.rowsEL.getBoundingClientRect = jest.fn(() => true); + rangeSelect.spacerEL.containPoint = jest.fn(() => true); + rangeSelect.spacerEL.getBoundingClientRect = jest.fn(() => true); + rangeSelect.rowsPaneEL = jest.fn(() => true); + rangeSelect.rowsPaneEL.scrollTop = jest.fn(() => true); expect(rangeSelect.mouseUp(mouseEvent)).toBeUndefined(); }); @@ -125,6 +132,7 @@ describe('RangeSelect Test', () => { rangeSelect.isInRowsEl = jest.fn(() => true); rangeSelect.isDrag = jest.fn(() => true); rangeSelect.isMouseDown = true; + rangeSelect.isHover = true; let rowsELDiv = document.createElement('div'); rangeSelect.rowsEL = rowsELDiv; let rows = [ @@ -218,4 +226,74 @@ describe('RangeSelect Test', () => { }); expect(rangeSelect.mouseDown(mouseEvent)).toBeUndefined(); }); + it('Utils Test11', () => { + let rangeSelect = new RangeSelect(); + rangeSelect.isInRowsEl = jest.fn(() => true); + rangeSelect.isDrag = jest.fn(() => true); + + rangeSelect.rowsEL = { + offsetTop: 113, + offsetHeight: 540, + offsetLeft: 146, + offsetWidth: 1102, + }; + let mouseEvent = new MouseEvent('mouseout', { + // @ts-ignore + offsetY: 1, + offsetX: 3, + button: 4, + buttons: 0, + clientX: 8, + clientY: 99, + screenX: 45, + screenY: 78, + }); + rangeSelect.spacerEL = jest.fn(() => true); + rangeSelect.rowsEL = jest.fn(() => true); + rangeSelect.rowsEL.getBoundingClientRect = jest.fn(() => true); + rangeSelect.spacerEL.containPoint = jest.fn(() => true); + rangeSelect.spacerEL.getBoundingClientRect = jest.fn(() => true); + rangeSelect.rowsPaneEL = jest.fn(() => true); + rangeSelect.rowsPaneEL.scrollTop = jest.fn(() => true); + rangeSelect.spacerEL.offsetTop = jest.fn(() => 1); + rangeSelect.drag = true; + expect(rangeSelect.mouseOut(mouseEvent)).toBeUndefined(); + }); + it('Utils Test12', () => { + let rangeSelect = new RangeSelect(); + rangeSelect.isInRowsEl = jest.fn(() => true); + rangeSelect.isDrag = jest.fn(() => true); + rangeSelect.isMouseDown = false; + let rowsELDiv = document.createElement('div'); + rangeSelect.rowsEL = rowsELDiv; + let mouseEvent = new MouseEvent('mousedown', { + // @ts-ignore + offsetY: 12, + offsetX: 1, + button: 74, + buttons: 0, + clientX: 12, + clientY: 100, + screenX: 9, + screenY: 325, + }); + rangeSelect.timerShaftEL = jest.fn(() => true); + rangeSelect.timerShaftEL.sportRuler = jest.fn(() => true); + rangeSelect.timerShaftEL.sportRuler.isRangeSelect = jest.fn(() => true); + rangeSelect.timerShaftEL.sportRuler.draw = jest.fn(() => true); + rangeSelect.timerShaftDragEL = jest.fn(() => true); + rangeSelect.timerShaftDragEL.timerShaftDragEL = jest.fn(() => 0); + rangeSelect.spacerEL = jest.fn(() => true); + let htmlElement = document.createElement('div'); + rangeSelect.spacerEL = htmlElement; + let rowElement = document.createElement('div'); + rangeSelect.rowsPaneEL = rowElement; + rangeSelect.favoriteRowsEL = rowElement; + let traceRowElement = document.createElement('trace-row') as TraceRow; + rangeSelect.ns2x = jest.fn(() => 1); + rangeSelect.mouseX = jest.fn(() => 10); + rangeSelect.markA = jest.fn(() => 8); + rangeSelect.markB = jest.fn(() => 9); + expect(rangeSelect.mouseMove([traceRowElement], mouseEvent)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/base/TraceRow.test.ts b/ide/test/trace/component/trace/base/TraceRow.test.ts index 49d7f492..5f1a5803 100644 --- a/ide/test/trace/component/trace/base/TraceRow.test.ts +++ b/ide/test/trace/component/trace/base/TraceRow.test.ts @@ -197,6 +197,7 @@ describe('TraceRow Test', () => { it('TraceRow Test27', () => { traceRow.tip = true; + traceRow.tipEL = true; expect(traceRow.tip).toBeUndefined(); }); @@ -247,6 +248,8 @@ describe('TraceRow Test', () => { }); it('TraceRow Test36', () => { + traceRow.tipEL = jest.fn(()=>true); + traceRow.tipEL.style = jest.fn(()=>true); expect(traceRow.onMouseHover()).toBeFalsy(); }); @@ -365,4 +368,83 @@ describe('TraceRow Test', () => { it('TraceRow Test67', () => { expect(traceRow.clearMemory()).toBeUndefined(); }); + it('TraceRow Test68', () => { + expect(traceRow.rowSetting).toBeTruthy(); + }); + it('TraceRow Test69', () => { + expect(traceRow.rowSettingPopoverDirection).toBeTruthy(); + }); + it('TraceRow Test71', () => { + traceRow.rowSettingPopoverDirection = true; + expect(traceRow.rowSettingPopoverDirection).toBeTruthy(); + }); + it('TraceRow Test70', () => { + expect(traceRow.rowSettingList).toBeUndefined(); + }); + it('TraceRow Test72', () => { + traceRow.expansion = false; + expect(traceRow.expansion).toBeFalsy(); + }); + it('TraceRow Test73', () => { + expect(traceRow.replaceTraceRow([],[])).toBeUndefined(); + }); + it('TraceRow Test74', () => { + let child = [{ + parentRowEl:[], + }]; + // @ts-ignore + child.setAttribute = jest.fn(); + expect(traceRow.addChildTraceRowSpecifyLocation(child,[])).toBeUndefined(); + }); + it('TraceRow Test75', () => { + expect(traceRow.drawLine(false,'top')).toBeUndefined(); + }); + it('TraceRow Test76', () => { + let mouseChangeEvent: MouseEvent = new MouseEvent('change', { clientX: 1, clientY: 2 }); + traceRow.setCheckBox = jest.fn(()=>true); + traceRow.checkBoxEL.dispatchEvent(mouseChangeEvent); + }); + it('TraceRow Test77', () => { + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + traceRow.isComplete = true; + traceRow.collectEL.dispatchEvent(mouseClickEvent); + }); + it('TraceRow Test78', () => { + let mouseChangeEvent: MouseEvent = new MouseEvent('change', { clientX: 1, clientY: 2 }); + traceRow.rowSettingTree.dispatchEvent(mouseChangeEvent); + }); + it('TraceRow Test80', () => { + let mouseDragOverEvent: MouseEvent = new MouseEvent('dragover', { clientX: 1, clientY: 2 }); + traceRow.describeEl.dispatchEvent(mouseDragOverEvent); + }); + it('TraceRow Test81', () => { + let mouseDragendEvent: MouseEvent = new MouseEvent('dragend', { clientX: 1, clientY: 2 }); + traceRow.describeEl.dispatchEvent(mouseDragendEvent); + }); + it('TraceRow Test82', () => { + let mouseDragLeaveEvent: MouseEvent = new MouseEvent('dragleave', { clientX: 1, clientY: 2 }); + traceRow.describeEl.dispatchEvent(mouseDragLeaveEvent); + }); + it('TraceRow Test83', () => { + let mouseDragStartEvent: MouseEvent = new MouseEvent('dragstart', { clientX: 1, clientY: 2 }); + traceRow.describeEl.dispatchEvent(mouseDragStartEvent); + }); + it('TraceRow Test84', () => { + traceRow.online = true; + expect(traceRow.draw(false)).toBeFalsy(); + }); + it('TraceRow Test85', () => { + const canvas = document.createElement('canvas'); + canvas.width = 34; + canvas.height = 1; + const ctx = canvas.getContext('2d'); + expect(traceRow.canvasSave(ctx)).toBeUndefined(); + }); + it('TraceRow Test86', () => { + const canvas = document.createElement('canvas'); + canvas.width = 8; + canvas.height = 1; + const ctx = canvas.getContext('2d'); + expect(traceRow.canvasRestore(ctx)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/base/TraceRowRecyclerView.test.ts b/ide/test/trace/component/trace/base/TraceRowRecyclerView.test.ts index c74d9810..3b4aba29 100644 --- a/ide/test/trace/component/trace/base/TraceRowRecyclerView.test.ts +++ b/ide/test/trace/component/trace/base/TraceRowRecyclerView.test.ts @@ -90,4 +90,10 @@ describe('TraceRow Test', () => { let traceRow = new TraceRowRecyclerView(); expect(traceRow.initUI()).toBeUndefined(); }); + it('Test10', function () { + let traceRow = new TraceRowRecyclerView(); + let mouseScrollEvent: MouseEvent = new MouseEvent('scroll', { clientX: 1, clientY: 2 }); + traceRow.container.dispatchEvent(mouseScrollEvent); + }); + }); diff --git a/ide/test/trace/component/trace/base/TraceSheet.test.ts b/ide/test/trace/component/trace/base/TraceSheet.test.ts index 91b05df0..90ec415f 100644 --- a/ide/test/trace/component/trace/base/TraceSheet.test.ts +++ b/ide/test/trace/component/trace/base/TraceSheet.test.ts @@ -15,6 +15,8 @@ // @ts-ignore import { TraceSheet } from '../../../../../dist/trace/component/trace/base/TraceSheet.js'; +const sqlit = require('../../../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../../../dist/trace/database/SqlLite.js'); window.ResizeObserver = window.ResizeObserver || @@ -92,4 +94,25 @@ describe('TraceSheet Test', () => { let traceSheet = new TraceSheet(); expect(traceSheet.updateRangeSelect()).toBeFalsy(); }); + it('TraceSheet Test11', () => { + let traceSheet = new TraceSheet(); + expect(traceSheet.constructor()).toBeTruthy(); + }); + it('TraceSheet Test13', () => { + let nativeHookResponseTypes = sqlit.queryNativeHookResponseTypes; + let hookTypeData = [ + { + lastLibId:33, + value:'bc' + }, + ]; + nativeHookResponseTypes.mockResolvedValue(hookTypeData); + let traceSheet = new TraceSheet(); + let param = { + leftNs: 0, + rightNs: 1000, + nativeMemory: ['All Heap & Anonymous VM', 'All Heap', 'Heap'], + }; + expect(traceSheet.initFilterLibList(param)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/TabPaneCurrentSelection.test.ts b/ide/test/trace/component/trace/sheet/TabPaneCurrentSelection.test.ts index b8f56511..e2eae1f2 100644 --- a/ide/test/trace/component/trace/sheet/TabPaneCurrentSelection.test.ts +++ b/ide/test/trace/component/trace/sheet/TabPaneCurrentSelection.test.ts @@ -410,4 +410,16 @@ describe('TabPaneCurrentSelection Test', () => { let result = tabPaneCurrentSelection.setJankType(data, list); expect(result).toBeUndefined(); }); + it('TabPaneCurrentSelectionTest21', function () { + let data = [{ + startTime:22, + }] + let result = tabPaneCurrentSelection.setFrameAnimationData(data) + expect(result).toBeTruthy(); + }); + it('TabPaneCurrentSelectionTest22', function () { + let data = [{}] + let result = tabPaneCurrentSelection.queryCPUWakeUpFromData(data) + expect(result).toBeTruthy(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/TabPaneFilter.test.ts b/ide/test/trace/component/trace/sheet/TabPaneFilter.test.ts index 53eb61b2..76ec79db 100644 --- a/ide/test/trace/component/trace/sheet/TabPaneFilter.test.ts +++ b/ide/test/trace/component/trace/sheet/TabPaneFilter.test.ts @@ -85,4 +85,31 @@ describe('TabPaneFilter Test', () => { tabPaneFilter.disabledMining = true; expect(tabPaneFilter.disabledMining).toBeTruthy(); }); + it('TabPaneFilterTest15', function () { + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + tabPaneFilter.iconEL.name = 'statistics'; + tabPaneFilter.iconEL.dispatchEvent(mouseClickEvent); + }); + it('TabPaneFilterTest16', function () { + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + tabPaneFilter.iconEL.name = 'menu'; + tabPaneFilter.iconEL.dispatchEvent(mouseClickEvent); + }); + it('TabPaneFilterTest17', function () { + let mouseClickEvent: MouseEvent = new MouseEvent('click', { clientX: 1, clientY: 2 }); + tabPaneFilter.getFilter = jest.fn(()=>true); + tabPaneFilter.markButtonEL.dispatchEvent(mouseClickEvent); + }); + it('TabPaneFilterTest18', function () { + let mouseChangeEvent: MouseEvent = new MouseEvent('change', { clientX: 1, clientY: 2 }); + tabPaneFilter.firstSelectEL.dispatchEvent(mouseChangeEvent); + }); + it('TabPaneFilterTest19', function () { + let mouseChangeEvent: MouseEvent = new MouseEvent('change', { clientX: 1, clientY: 2 }); + tabPaneFilter.secondSelectEL.dispatchEvent(mouseChangeEvent); + }); + it('TabPaneFilterTest20', function () { + let mouseChangeEvent: MouseEvent = new MouseEvent('change', { clientX: 1, clientY: 2 }); + tabPaneFilter.thirdSelectEL.dispatchEvent(mouseChangeEvent); + }); }); diff --git a/ide/test/trace/component/trace/sheet/ability/TabPanePurgPinSelection.test.ts b/ide/test/trace/component/trace/sheet/ability/TabPanePurgPinSelection.test.ts index 7dda282c..2892d047 100644 --- a/ide/test/trace/component/trace/sheet/ability/TabPanePurgPinSelection.test.ts +++ b/ide/test/trace/component/trace/sheet/ability/TabPanePurgPinSelection.test.ts @@ -18,106 +18,113 @@ import { TabPanePurgPinSelection } from '../../../../../../dist/trace/component/ const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../../../dist/trace/component/trace/base/TraceRow.js', () => { - return {}; + return {}; }); // @ts-ignore -window.ResizeObserver = window.ResizeObserver || - jest.fn().mockImplementation(() => ({ - disconnect: jest.fn(), - observe: jest.fn(), - unobserve: jest.fn(), - })); +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); describe('TabPanePurgPin Test', () => { - let tabPanePurgPinSelection = new TabPanePurgPinSelection(); - let querySysPurgeableSelectionTab = sqlit.querySysPurgeableSelectionTab; - querySysPurgeableSelectionTab.mockResolvedValue([ - { - value: 25165824, - name: "24.00MB", - }, - { - value: 25165824, - name: "24.00MB", - }, - { - value: 25165824, - name: "24.00MB", - }, - ]); - let queryProcessPurgeableSelectionTab = sqlit.queryProcessPurgeableSelectionTab; - queryProcessPurgeableSelectionTab.mockResolvedValue([ - { - value: 25165824, - name: "24.00MB", - }, - { - value: 25165824, - name: "24.00MB", - }, - { - value: 25165824, - name: "24.00MB", - }, - ]); - tabPanePurgPinSelection.data = { - anomalyEnergy: [], - clockMapData:{size: 120}, - cpuAbilityIds: [], - cpuFreqFilterIds: [], - cpuFreqLimitDatas: [], - cpuStateFilterIds: [], - cpus: [], - gpu: {gl: false, gpuWindow: false, gpuTotal: false}, - gpuMemoryAbilityData: [], - gpuMemoryTrackerData: [], - hasFps: false, - irqMapData:{size: 965}, - diskAbilityIds: [], - diskIOLatency: false, - diskIOReadIds: [], - diskIOWriteIds: [], - diskIOipids: [], - dmaAbilityData: [], - dmaVmTrackerData: [], - fsCount: 410, - funAsync: [], - funTids: [], - isCurrentPane: false, - jankFramesData: [], - jsCpuProfilerData: [], - jsMemory: [], - leftNs: 2199973, - memoryAbilityIds: [], - nativeMemory: [], - nativeMemoryStatistic: [], - networkAbilityIds: [], - perfAll: false, - perfCpus: [], - perfProcess: [], - perfSampleIds: [], - perfThread: [], - powerEnergy: [], - purgeablePinVM: [], - purgeableTotalAbility: [], - purgeableTotalSelection: [], - purgeableTotalVM: [], - recordStartNs: 3546410021149, - rightNs: 2698537796280, - sdkCounterIds: [], - sdkSliceIds: [], - smapsType: [], - startup: false, - staticInit: false, - statisticsSelectData: undefined, - processIds: [], - processTrackIds: [], - promiseList: [], - purgeablePinAbility: [], - purgeablePinSelection: [], - }; + let tabPanePurgPinSelection = new TabPanePurgPinSelection(); + let querySysPurgeableSelectionTab = sqlit.querySysPurgeableSelectionTab; + querySysPurgeableSelectionTab.mockResolvedValue([ + { + value: 25165824, + name: '24.00MB', + }, + { + value: 25165824, + name: '24.00MB', + }, + { + value: 25165824, + name: '24.00MB', + }, + ]); + let queryProcessPurgeableSelectionTab = sqlit.queryProcessPurgeableSelectionTab; + queryProcessPurgeableSelectionTab.mockResolvedValue([ + { + value: 25165824, + name: '24.00MB', + }, + { + value: 25165824, + name: '24.00MB', + }, + { + value: 25165824, + name: '24.00MB', + }, + ]); + tabPanePurgPinSelection.data = { + anomalyEnergy: [], + clockMapData: { size: 120 }, + cpuAbilityIds: [], + cpuFreqFilterIds: [], + cpuFreqLimitDatas: [], + cpuStateFilterIds: [], + cpus: [], + gpu: { gl: false, gpuWindow: false, gpuTotal: false }, + gpuMemoryAbilityData: [], + gpuMemoryTrackerData: [], + hasFps: false, + irqMapData: { size: 965 }, + diskAbilityIds: [], + diskIOLatency: false, + diskIOReadIds: [], + diskIOWriteIds: [], + diskIOipids: [], + dmaAbilityData: [], + dmaVmTrackerData: [], + fsCount: 410, + funAsync: [], + funTids: [], + isCurrentPane: false, + jankFramesData: [], + jsCpuProfilerData: [], + jsMemory: [], + leftNs: 2199973, + memoryAbilityIds: [], + nativeMemory: [], + nativeMemoryStatistic: [], + networkAbilityIds: [], + perfAll: false, + perfCpus: [], + perfProcess: [], + perfSampleIds: [], + perfThread: [], + powerEnergy: [], + purgeablePinVM: [], + purgeableTotalAbility: [], + purgeableTotalSelection: [], + purgeableTotalVM: [], + recordStartNs: 3546410021149, + rightNs: 2698537796280, + sdkCounterIds: [], + sdkSliceIds: [], + smapsType: [], + startup: false, + staticInit: false, + statisticsSelectData: undefined, + processIds: [], + processTrackIds: [], + promiseList: [], + purgeablePinAbility: [], + purgeablePinSelection: [], + }; - it('tabPanePurgPinSelectionTest01', function () { - expect(tabPanePurgPinSelection.data).toBeUndefined(); - }); -}) \ No newline at end of file + it('tabPanePurgPinSelectionTest01', function () { + expect(tabPanePurgPinSelection.data).toBeUndefined(); + }); + it('tabPanePurgPinSelectionTest02', function () { + expect(tabPanePurgPinSelection.queryTableData('ability', 10)).toBeTruthy(); + }); + it('tabPanePurgPinSelectionTest03', function () { + expect(tabPanePurgPinSelection.queryTableData('VM', 10)).toBeTruthy(); + }); +}); diff --git a/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotal.test.ts b/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotal.test.ts index 4e80ccb8..d83d3607 100644 --- a/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotal.test.ts +++ b/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotal.test.ts @@ -18,115 +18,109 @@ import { TabPanePurgTotal } from '../../../../../../dist/trace/component/trace/s const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../../../dist/trace/database/SqlLite.js'); // @ts-ignore -window.ResizeObserver = window.ResizeObserver || - jest.fn().mockImplementation(() => ({ - disconnect: jest.fn(), - observe: jest.fn(), - unobserve: jest.fn(), - })); +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); describe('TabPanePurgTotal Test', () => { - let tabPanePurgTotal = new TabPanePurgTotal(); - let querySysPurgeableTab = sqlit.querySysPurgeableTab; - querySysPurgeableTab.mockResolvedValue([ - { - avgSize: 21025824, - avgSizes: "321.00MB", - type: "allocator_host", - maxSize: 9165822, - maxSizes: "233.00MB", - minSize: 35145824, - minSizes: "12.00MB", - }, - { - avgSize: 32133321, - avgSizes: "320.00MB", - type: "11allocator_host", - maxSize: 23265824, - maxSizes: "4.00MB", - minSize: 32365824, - minSizes: "321.00MB", - }, - { - avgSize: 98525824, - avgSizes: "3.00MB", - type: "alloca11tor_host", - maxSize: 12155824, - maxSizes: "6.00MB", - minSize: 36545824, - minSizes: "66.00MB", - }, - ]); - tabPanePurgTotal.init = jest.fn(() => true); - tabPanePurgTotal.data = { - anomalyEnergy: [], - clockMapData:{size: 321}, - cpuAbilityIds: [], - cpuFreqFilterIds: [], - cpuFreqLimitDatas: [], - diskIOReadIds: [], - diskIOWriteIds: [], - diskIOipids: [], - dmaAbilityData: [], - dmaVmTrackerData: [], - fsCount: 90, - funAsync: [], - funTids: [], - gpu: {gl: false, gpuWindow: false, gpuTotal: false}, - gpuMemoryAbilityData: [], - gpuMemoryTrackerData: [], - hasFps: false, - irqMapData:{size: 630}, - isCurrentPane: false, - jankFramesData: [], - jsCpuProfilerData: [], - jsMemory: [], - leftNs: 12120099973, - memoryAbilityIds: [], - nativeMemory: [], - nativeMemoryStatistic: [], - networkAbilityIds: [], - perfAll: false, - cpuStateFilterIds: [], - cpus: [], - diskAbilityIds: [], - diskIOLatency: false, - perfCpus: [], - perfProcess: [], - perfSampleIds: [], - perfThread: [], - purgeableTotalAbility: [], - purgeableTotalSelection: [], - purgeableTotalVM: [], - recordStartNs: 396522210669149, - rightNs: 21021096280, - sdkCounterIds: [], - sdkSliceIds: [], - smapsType: [], - startup: false, - staticInit: false, - statisticsSelectData: undefined, - powerEnergy: [], - processIds: [], - processTrackIds: [], - promiseList: [], - purgeablePinAbility: [], - purgeablePinSelection: [], - purgeablePinVM: [], - }; + let tabPanePurgTotal = new TabPanePurgTotal(); + let querySysPurgeableTab = sqlit.querySysPurgeableTab; + querySysPurgeableTab.mockResolvedValue([ + { + avgSize: 21025824, + avgSizes: '321.00MB', + type: 'allocator_host', + maxSize: 9165822, + maxSizes: '233.00MB', + minSize: 35145824, + minSizes: '12.00MB', + }, + { + avgSize: 32133321, + avgSizes: '320.00MB', + type: '11allocator_host', + maxSize: 23265824, + maxSizes: '4.00MB', + minSize: 32365824, + minSizes: '321.00MB', + }, + { + avgSize: 98525824, + avgSizes: '3.00MB', + type: 'alloca11tor_host', + maxSize: 12155824, + maxSizes: '6.00MB', + minSize: 36545824, + minSizes: '66.00MB', + }, + ]); + tabPanePurgTotal.init = jest.fn(() => true); + tabPanePurgTotal.data = { + anomalyEnergy: [], + clockMapData: { size: 321 }, + cpuAbilityIds: [], + cpuFreqFilterIds: [], + cpuFreqLimitDatas: [], + diskIOReadIds: [], + diskIOWriteIds: [], + diskIOipids: [], + dmaAbilityData: [], + dmaVmTrackerData: [], + fsCount: 90, + funAsync: [], + funTids: [], + gpu: { gl: false, gpuWindow: false, gpuTotal: false }, + gpuMemoryAbilityData: [], + gpuMemoryTrackerData: [], + hasFps: false, + irqMapData: { size: 630 }, + isCurrentPane: false, + jankFramesData: [], + jsCpuProfilerData: [], + jsMemory: [], + leftNs: 12120099973, + memoryAbilityIds: [], + nativeMemory: [], + nativeMemoryStatistic: [], + networkAbilityIds: [], + perfAll: false, + cpuStateFilterIds: [], + cpus: [], + diskAbilityIds: [], + diskIOLatency: false, + perfCpus: [], + perfProcess: [], + perfSampleIds: [], + perfThread: [], + purgeableTotalAbility: [1, 2], + purgeableTotalSelection: [], + purgeableTotalVM: [4, 1], + recordStartNs: 396522210669149, + rightNs: 21021096280, + sdkCounterIds: [], + sdkSliceIds: [], + smapsType: [], + startup: false, + staticInit: false, + statisticsSelectData: undefined, + powerEnergy: [], + processIds: [], + processTrackIds: [], + promiseList: [], + purgeablePinAbility: [], + purgeablePinSelection: [], + purgeablePinVM: [], + }; - it('TabPanePurgTotalTest01', function () { - expect( - tabPanePurgTotal.sortByColumn({ - key: 'avgSize', - }) - ).toBeUndefined(); - }); - it('TabPanePurgTotalTest02', function () { - expect( - tabPanePurgTotal.sortByColumn({ - key: 'type', - }) - ).toBeUndefined(); - }); -}) \ No newline at end of file + it('TabPanePurgTotalTest01', function () { + expect( + tabPanePurgTotal.sortByColumn({ + key: 'avgSize', + }) + ).toBeUndefined(); + }); +}); diff --git a/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.test.ts b/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.test.ts index 1c95de00..9a0df7fe 100644 --- a/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.test.ts +++ b/ide/test/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.test.ts @@ -120,4 +120,10 @@ describe('TabPanePurgTotalSelection Test', () => { it('TabPanePurgTotalSelectionTest01', function () { expect(tabPanePurgTotalSelection.data).toBeUndefined(); }); + it('TabPanePurgTotalSelectionTest02', function () { + expect(tabPanePurgTotalSelection.queryTableData('ability',21)).toBeTruthy(); + }); + it('TabPanePurgTotalSelectionTest03', function () { + expect(tabPanePurgTotalSelection.queryTableData('VM',21)).toBeTruthy(); + }); }) \ No newline at end of file diff --git a/ide/test/trace/component/trace/sheet/ark-ts/TabPaneJsCpu.test.ts b/ide/test/trace/component/trace/sheet/ark-ts/TabPaneJsCpu.test.ts new file mode 100644 index 00000000..23557dcb --- /dev/null +++ b/ide/test/trace/component/trace/sheet/ark-ts/TabPaneJsCpu.test.ts @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +//@ts-ignore +import { TabPaneJsCpuCallTree } from '../../../../../../dist/trace/component/trace/sheet/ark-ts/TabPaneJsCpu.js'; +import '../../../../../../dist/trace/component/trace/sheet/ark-ts/TabPaneJsCpu.js'; +import { JsCpuProfilerStatisticsStruct } from '../../../../../../dist/trace/bean/JsStruct.js'; + +const sqlite = require('../../../../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../../../../dist/base-ui/table/lit-table.js', () => { + return { + recycleDataSource: () => {}, + removeAttribute: () => {}, + reMeauseHeight: () => {}, + addEventListener: () => {}, + }; +}); +jest.mock('../../../../../../dist/trace/component/trace/base/TraceRow.js', () => { + return {}; +}); +// @ts-ignore +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); +describe('TabPaneJsCpuCallTree Test', () => { + document.body.innerHTML = ``; + let tabPaneJsCpu = document.querySelector('#statistics'); + it('TabPaneJsCpuCallTree01', () => { + tabPaneJsCpu.init = jest.fn(() => true); + tabPaneJsCpu.data = { + rightNs: 5, + leftNs: 1, + cpus: [], + threadIds: [], + trackIds: [6], + funTids: [111, 4, 43], + heapIds: [5, 67, 0], + nativeMemory: [], + cpuAbilityIds: [], + memoryAbilityIds: [], + diskAbilityIds: [88, 7], + networkAbilityIds: [], + hasFps: false, + statisticsSelectData: undefined, + perfSampleIds: [], + perfCpus: [], + perfProcess: [], + perfThread: [], + perfAll: true, + }; + expect(tabPaneJsCpu).toBeTruthy(); + }); + it('TabPaneJsCpuCallTree02', () => { + expect(tabPaneJsCpu.setCallTreeTableData).toBeUndefined(); + }); +}); diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPaneBoxChild.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPaneBoxChild.test.ts index f26e761e..1ee94f22 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPaneBoxChild.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPaneBoxChild.test.ts @@ -16,7 +16,8 @@ // @ts-ignore // import { it } from "mocha" import { TabPaneBoxChild } from '../../../../../../dist/trace/component/trace/sheet/cpu/TabPaneBoxChild.js'; -import { getTabBoxChildData } from '../../../../../../src/trace/database/SqlLite'; +const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../../../../dist/trace/database/SqlLite.js'); window.ResizeObserver = window.ResizeObserver || @@ -32,6 +33,21 @@ describe('TabPaneBoxChild Test', () => { let tabPaneBoxChild = new TabPaneBoxChild(); element.appendChild(tabPaneBoxChild); tabPaneBoxChild.loadDataInCache = true; + let getTabBox = sqlit.getTabBoxChildData; + let data = [ + { + process: '', + processId: 12, + thread: '', + state: 2, + threadId: 3, + duration: 1, + startNs: 17, + cpu: 2, + priority: 1, + }, + ]; + getTabBox.mockResolvedValue(data); tabPaneBoxChild.data = { cpus: [], threadIds: [], @@ -39,16 +55,13 @@ describe('TabPaneBoxChild Test', () => { funTids: [], heapIds: [], leftNs: 0, - rightNs: 0, + rightNs: 233, hasFps: false, + state:'', + processId:0, + threadId: 0 }; - let val = { - leftNs: 2, - rightNs: 1, - state: '1', - processId: 0, - threadId: 1, - }; + it('TabPaneBoxChildTest01', function () { expect( @@ -65,4 +78,16 @@ describe('TabPaneBoxChild Test', () => { }) ).toBeUndefined(); }); + it('TabPaneCounterTest03', function () { + let val = [ + { + leftNs: 11, + rightNs: 34, + state: true, + processId: 3, + threadId: 1, + }, + ]; + expect(tabPaneBoxChild.getDataByDB(val)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.test.ts index 8a7a1545..1c3ee397 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.test.ts @@ -15,6 +15,10 @@ // @ts-ignore import { TabPaneCpuByProcess } from '../../../../../../dist/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.js'; +// @ts-ignore +import { SpSystemTrace } from '../../../../../../dist/trace/component/SpSystemTrace.js'; +// @ts-ignore +import { LitTable } from '../../../../../../dist/base-ui/table/lit-table.js'; window.ResizeObserver = window.ResizeObserver || diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByThread.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByThread.test.ts index 2fa878bc..46800524 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByThread.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuByThread.test.ts @@ -29,6 +29,7 @@ jest.mock('../../../../../../dist/trace/database/SqlLite.js'); describe('TabPaneCpuByThread Test', () => { let tabPaneCpuByThread = new TabPaneCpuByThread(); + tabPaneCpuByThread.cpuByThreadTbl.injectColumns = jest.fn(()=> true) it('TabPaneCpuByThreadTest01', function () { expect( diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuUsage.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuUsage.test.ts index fdd17e3f..fb077a14 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuUsage.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPaneCpuUsage.test.ts @@ -185,4 +185,32 @@ describe('TabPaneCpuUsage Test', () => { let tabPaneCpuUsage = document.querySelector('#CpuUsage') as TabPaneCpuUsage; expect(tabPaneCpuUsage.sortFreq).toBe(undefined); }); + it('TabPaneCpuUsageTest12', function () { + document.body.innerHTML = `
          `; + let tabPaneCpuUsage = document.querySelector('#CpuUsage') as TabPaneCpuUsage; + tabPaneCpuUsage.data = [ + { + cpus: [2], + threadIds: [], + trackIds: [12, 4], + funTids: [56, 345], + heapIds: [], + nativeMemory: [], + cpuAbilityIds: [10, 32, 1], + memoryAbilityIds: [], + diskAbilityIds: [12, 76], + networkAbilityIds: [], + leftNs: 77, + rightNs: 987, + hasFps: false, + statisticsSelectData: undefined, + perfSampleIds: [], + perfCpus: [0, 9], + perfProcess: [], + perfThread: [], + perfAll: true, + }, + ]; + expect(tabPaneCpuUsage).toBeTruthy(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPanePTS.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPanePTS.test.ts index be5e953b..da2221cf 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPanePTS.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPanePTS.test.ts @@ -19,13 +19,6 @@ import { TabPanePTS } from '../../../../../../dist/trace/component/trace/sheet/c import { SpSystemTrace } from '../../../../../../dist/trace/component/SpSystemTrace.js'; // @ts-ignore import { LitTable } from '../../../../../../dist/base-ui/table/lit-table.js'; -jest.mock('../../../../../../dist/base-ui/table/lit-table.js', () => { - return { - meauseAllRowHeight: () => {}, - }; -}); -const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); -jest.mock('../../../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../../../dist/js-heap/model/DatabaseStruct.js', () => {}); window.ResizeObserver = @@ -36,14 +29,8 @@ window.ResizeObserver = observe: jest.fn(), })); describe('TabPanePTS Test', () => { - document.body.innerHTML = ``; - let tab = document.querySelector('#tb-states') as LitTable; - document.body.innerHTML = `
          `; let tabPane = document.querySelector('.pts') as TabPanePTS; - let tabPanePTS = new TabPanePTS(); - - tabPanePTS.tbl = jest.fn(() => tab); SpSystemTrace.SPT_DATA = [ { @@ -129,24 +116,4 @@ describe('TabPanePTS Test', () => { ]; expect(tabPane.getDataByPTS(10, 100_000, source)).toBeUndefined(); }); - - it('TabPaneSPTTest03', function () { - let mockgetProcessThreadDataByRange = sqlit.getStatesProcessThreadDataByRange; - mockgetProcessThreadDataByRange.mockResolvedValue([ - { - process: 'process', - processId: 11, - thread: 'thread', - state: 'state', - threadId: 11, - dur: 1000, - end_ts: 2000, - start_ts: 2000, - cpu: 1111, - }, - ]); - tab.recycleDataSource = jest.fn(() => []); - tabPanePTS.tbl.recycleDataSource = jest.fn(() => dataArray); - expect((tabPanePTS.data = dataArray)).toBeTruthy(); - }); }); diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPaneSPT.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPaneSPT.test.ts index 3d705403..12512a33 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPaneSPT.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPaneSPT.test.ts @@ -19,11 +19,7 @@ import { TabPaneSPT } from '../../../../../../dist/trace/component/trace/sheet/c import { SpSystemTrace } from '../../../../../../dist/trace/component/SpSystemTrace.js'; // @ts-ignore import { LitTable } from '../../../../../../dist/base-ui/table/lit-table.js'; -jest.mock('../../../../../../dist/base-ui/table/lit-table.js', () => { - return { - meauseTreeRowElement: () => {}, - }; -}); + jest.mock('../../../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../../../dist/js-heap/model/DatabaseStruct.js', () => {}); const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); @@ -148,24 +144,4 @@ describe('TabPaneSPT Test', () => { ]; expect(tabPane.getDataBySPT(10, 100_000, source)).toBeUndefined(); }); - - it('TabPaneSPTTest03', function () { - let mockgetProcessThreadDataByRange = sqlit.getStatesProcessThreadDataByRange; - mockgetProcessThreadDataByRange.mockResolvedValue([ - { - process: 'process', - processId: 13, - thread: 'thread', - state: 'state', - threadId: 12, - dur: 1000, - end_ts: 2000, - start_ts: 2000, - cpu: 1111, - }, - ]); - tabPane.tbl = jest.fn(() => tab); - tabPane.tbl.recycleDataSource = jest.fn(() => []); - expect((tabPane.data = dataList)).toBeTruthy(); - }); }); diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneCallTree.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneCallTree.test.ts index 4f51db70..55cae941 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneCallTree.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneCallTree.test.ts @@ -175,4 +175,56 @@ describe('TabPaneCallTree Test', () => { calltree.setLTableData(resultData); expect(calltree.callTreeDataSource.length).toEqual(1); }); + it('TabPaneCallTreeTest05', function () { + document.body.innerHTML = ``; + let calltree = document.querySelector('#calltree'); + let switchData = { + firstSelect: '', + icon: 'tree', + inputValue: 'kk', + mark: false, + secondSelect: '', + thirdSelect: '', + type: 'inputValue', + }; + expect(calltree.switchFlameChart(switchData)).toBeUndefined(); + }); + it('TabPaneCallTreeTest06', function () { + document.body.innerHTML = ``; + let calltree = document.querySelector('#calltree'); + let filterData = { + callTree: [{}, {}], + dataMining: { + concat: jest.fn(() => true), + }, + callTreeConstraints: { + checked: false, + }, + }; + expect(calltree.refreshAllNode(filterData)).toBeUndefined(); + }); + it('TabPaneCallTreeTest07', function () { + document.body.innerHTML = ``; + let calltree = document.querySelector('#calltree'); + let call = { + id: '3', + children: [], + }; + let target = { + id: '3', + }; + expect(calltree.getParentTree([call], { target }, [])).toBeFalsy(); + }); + it('TabPaneCallTreeTest08', function () { + document.body.innerHTML = ``; + let calltree = document.querySelector('#calltree'); + let call = { + id: '4', + children: [], + }; + let target = { + id: '4', + }; + expect(calltree.getChildTree([call], { target }, [])).toBeFalsy(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.test.ts index aeb7c9de..2c0493ff 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.test.ts @@ -44,7 +44,8 @@ window.IntersectionObserver = jest.fn().mockImplementation(intersectionObserverM import crypto from 'crypto'; // @ts-ignore -window.ResizeObserver = window.ResizeObserver || +window.ResizeObserver = + window.ResizeObserver || jest.fn().mockImplementation(() => ({ observe: jest.fn(), })); @@ -60,21 +61,21 @@ describe('TabpaneFilesystemCalltree Test', () => { let val = { anomalyEnergy: [], clockMapData: { size: 16 }, - cpuAbilityIds: [12,155,223], - cpuFreqFilterIds: [52,122,22], + cpuAbilityIds: [12, 155, 223], + cpuFreqFilterIds: [52, 122, 22], cpuFreqLimitDatas: [], - cpuStateFilterIds: [52,566,115], - cpus: [1,2], - diskAbilityIds: [451,22], + cpuStateFilterIds: [52, 566, 115], + cpus: [1, 2], + diskAbilityIds: [451, 22], diskIOLatency: false, diskIOReadIds: [522, 4, 5, 6], diskIOWriteIds: [2, 5621, 5, 6], - diskIOipids: [2,120, 5, 6], + diskIOipids: [2, 120, 5, 6], fileSysVirtualMemory: true, fileSystemType: [], fsCount: 32, funAsync: [], - funTids: [120,55], + funTids: [120, 55], hasFps: false, irqMapData: { size: 85 }, jsMemory: [], @@ -84,21 +85,21 @@ describe('TabpaneFilesystemCalltree Test', () => { nativeMemoryStatistic: [], networkAbilityIds: [], perfAll: true, - perfCpus: [1,2], + perfCpus: [1, 2], perfProcess: [], perfSampleIds: [], - perfThread: ['hiprofiler_cmd',''], + perfThread: ['hiprofiler_cmd', ''], powerEnergy: [], - processTrackIds: [552,123], + processTrackIds: [552, 123], promiseList: [], recordStartNs: 780423789228, rightNs: 966666666, - sdkCounterIds: [120,451,52], + sdkCounterIds: [120, 451, 52], sdkSliceIds: [154], smapsType: [], systemEnergy: [], - threadIds: [101,2122,4], - virtualTrackIds: [412,85], + threadIds: [101, 2122, 4], + virtualTrackIds: [412, 85], vmCount: 3, }; @@ -221,4 +222,16 @@ describe('TabpaneFilesystemCalltree Test', () => { }; expect(tabpaneFilesystemCalltree.setRightTableData(call)).toBeUndefined(); }); + it('TabpaneFilesystemCalltreeTest11', function () { + let filterData = { + callTree: [{}, {}], + dataMining: { + concat: jest.fn(() => true), + }, + callTreeConstraints: { + checked: false, + }, + }; + expect(tabpaneFilesystemCalltree.refreshAllNode(filterData)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemDescTimeSlice.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemDescTimeSlice.test.ts index e5163127..6f1d82f3 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemDescTimeSlice.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneFileSystemDescTimeSlice.test.ts @@ -140,7 +140,7 @@ describe('TabPaneFileSystemDescTimeSlice Test', () => { tabPane.loadingList = []; tabPane.data = param; tabPane.source = filterSource; - expect(tabPane.sortFsDescTimeSliceTable('startTsStr', 1)).toBeUndefined(); + expect(tabPane.sortFsDescTimeSliceTable('startTsStr', 0)).toBeUndefined(); }); it('descTimeSliceTest03', function () { diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.test.ts index 2d4b9885..38a8230a 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.test.ts @@ -28,7 +28,8 @@ import '../../../../../../dist/base-ui/table/lit-table.js'; // @ts-ignore import { TabPaneFilter } from '../../../../../../dist/trace/component/trace/sheet/TabPaneFilter.js'; import '../../../../../../dist/trace/component/trace/sheet/TabPaneFilter.js'; - +const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); +jest.mock('../../../../../../dist/trace/database/SqlLite.js'); Object.defineProperty(global.self, 'crypto', { value: { getRandomValues: (arr: string | any[]) => crypto.randomBytes(arr.length), @@ -36,10 +37,12 @@ Object.defineProperty(global.self, 'crypto', { }); // @ts-ignore window.ResizeObserver = - window.ResizeObserver || - jest.fn().mockImplementation(() => ({ - disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), - })); + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); describe('TabPaneFileStatistics Test', () => { document.body.innerHTML = `
          `; @@ -47,45 +50,45 @@ describe('TabPaneFileStatistics Test', () => { let param = { anomalyEnergy: [], clockMapData: { size: 50 }, - cpuAbilityIds: [23,25], - cpuFreqFilterIds: [34,66], + cpuAbilityIds: [23, 25], + cpuFreqFilterIds: [34, 66], cpuFreqLimitDatas: [], - cpuStateFilterIds: [77,96], + cpuStateFilterIds: [77, 96], cpus: [0], - diskAbilityIds: [10,34], + diskAbilityIds: [10, 34], diskIOLatency: false, - diskIOReadIds: [2,11, 4, 12], + diskIOReadIds: [2, 11, 4, 12], diskIOWriteIds: [2, 54, 64], diskIOipids: [25, 7, 58, 6], fileSysVirtualMemory: true, fileSystemType: [], fsCount: 30, funAsync: [], - funTids: [45,22], + funTids: [45, 22], hasFps: false, irqMapData: { size: 32 }, jsMemory: [], leftNs: 964667689, - memoryAbilityIds: [23,78,9], + memoryAbilityIds: [23, 78, 9], nativeMemory: [], nativeMemoryStatistic: [], - networkAbilityIds: [10,154,55], + networkAbilityIds: [10, 154, 55], perfAll: false, perfCpus: [1], perfProcess: [], - perfSampleIds: [233,120,4], + perfSampleIds: [233, 120, 4], perfThread: [], powerEnergy: [], - processTrackIds: [34,21], + processTrackIds: [34, 21], promiseList: [], recordStartNs: 780423722428, rightNs: 33236556624, - sdkCounterIds: [12,56], - sdkSliceIds: [45,98], + sdkCounterIds: [12, 56], + sdkSliceIds: [45, 98], smapsType: [], systemEnergy: [], - threadIds: [88,12], - virtualTrackIds: [34,87], + threadIds: [88, 12], + virtualTrackIds: [34, 87], vmCount: 31, }; @@ -168,4 +171,28 @@ describe('TabPaneFileStatistics Test', () => { }; expect(FileStatistics.sortTable(node, '')).toBeUndefined(); }); + it('TabPaneFileStatisticsTest10', function () { + let FileStatistics = new TabPaneFileStatistics(); + let tabPaneFilesystemStatistics = sqlit.getTabPaneFilesystemStatistics; + let result = [ + { + pid: 1, + name: '', + type: 1, + count: 34, + size: 22, + logicalReads: 32, + logicalWrites: 12, + otherFile: 55, + allDuration: 12, + minDuration: 1, + maxDuration: 7, + avgDuration: 2, + }, + ]; + FileStatistics.fileStatisticsTbl = jest.fn(() => true); + FileStatistics.fileStatisticsTbl.recycleDataSource = jest.fn(() => true); + tabPaneFilesystemStatistics.mockResolvedValue(result); + expect(FileStatistics.queryDataByDB(param)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.test.ts index b3c4ba2f..a2634b15 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.test.ts @@ -22,7 +22,8 @@ import crypto from 'crypto'; // @ts-ignore import { TabPaneFilter } from '../../../../../../dist/trace/component/trace/sheet/TabPaneFilter.js'; // @ts-ignore -window.ResizeObserver = window.ResizeObserver || +window.ResizeObserver = + window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), unobserve: jest.fn(), @@ -41,14 +42,14 @@ describe('TabPaneFilesystemStatisticsAnalysis Test', () => { let param = { anomalyEnergy: [], clockMapData: { size: 193 }, - cpuAbilityIds: [10,8], + cpuAbilityIds: [10, 8], cpuFreqFilterIds: [56], cpuFreqLimitDatas: [], - cpuStateFilterIds: [12,98], + cpuStateFilterIds: [12, 98], cpus: [], diskAbilityIds: [], diskIOLatency: false, - diskIOReadIds: [2,33], + diskIOReadIds: [2, 33], diskIOWriteIds: [54, 4, 54, 6], diskIOipids: [2, 17, 45, 5, 16], fileSysVirtualMemory: false, @@ -60,25 +61,25 @@ describe('TabPaneFilesystemStatisticsAnalysis Test', () => { irqMapData: { size: 996 }, jsMemory: [], leftNs: 964699125, - memoryAbilityIds: [12,34], + memoryAbilityIds: [12, 34], nativeMemory: [], nativeMemoryStatistic: [], - networkAbilityIds: [34,87], + networkAbilityIds: [34, 87], perfAll: false, perfCpus: [], perfProcess: [], - perfSampleIds: [67,33], + perfSampleIds: [67, 33], perfThread: [], powerEnergy: [], - processTrackIds: [122,34], + processTrackIds: [122, 34], promiseList: [], recordStartNs: 780423788588, rightNs: 69267555654, - sdkCounterIds: [34,22,12], + sdkCounterIds: [34, 22, 12], sdkSliceIds: [221], smapsType: [], systemEnergy: [], - threadIds: [12,45], + threadIds: [12, 45], virtualTrackIds: [], vmCount: 850, }; @@ -272,4 +273,96 @@ describe('TabPaneFilesystemStatisticsAnalysis Test', () => { tabPane.currentLevel = 4; expect(tabPane.sortByColumn('durFormat', 1)).toBeUndefined(); }); + it('systemStatisticsAnalysis13', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.fileProcessLevelClickEvent(it)).toBeUndefined(); + }); + it('systemStatisticsAnalysis14', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.fileTypeLevelClickEvent(it)).toBeUndefined(); + }); + it('systemStatisticsAnalysis15', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.fileThreadLevelClickEvent(it)).toBeUndefined(); + }); + it('systemStatisticsAnalysis16', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.fileSoLevelClickEvent(it)).toBeUndefined(); + }); + it('TabPanePerfAnalysisTest17 ', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By type AllDuration'; + tabPane.processStatisticsData = jest.fn(() => true); + tabPane.processStatisticsData.allDuration = jest.fn(() => true); + tabPane.fileStatisticsAnalysisPidData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('TabPanePerfAnalysisTest18 ', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Library AllDuration'; + tabPane.threadStatisticsData = jest.fn(() => true); + tabPane.threadStatisticsData.allDuration = jest.fn(() => true); + tabPane.fileStatisticsAnalysisThreadData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('TabPanePerfAnalysisTest19 ', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Function AllDuration'; + tabPane.libStatisticsData = jest.fn(() => true); + tabPane.libStatisticsData.allDuration = jest.fn(() => true); + tabPane.fileStatisticsAnalysisSoData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('TabPanePerfAnalysisTest20 ', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Thread AllDuration'; + tabPane.typeStatisticsData = jest.fn(() => true); + tabPane.typeStatisticsData.allDuration = jest.fn(() => true); + tabPane.fileStatisticsAnalysisTypeData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.test.ts index 8c2100ab..7f0f3186 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.test.ts @@ -48,12 +48,12 @@ describe('TabPaneIOTierStatistics Test', () => { let param = { anomalyEnergy: [], clockMapData: { size: 66 }, - cpuAbilityIds: [12,4,56,76], - cpuFreqFilterIds: [5,78,8], + cpuAbilityIds: [12, 4, 56, 76], + cpuFreqFilterIds: [5, 78, 8], cpuFreqLimitDatas: [], - cpuStateFilterIds: [67,22], - cpus: [1,0], - diskAbilityIds: [56,31], + cpuStateFilterIds: [67, 22], + cpus: [1, 0], + diskAbilityIds: [56, 31], diskIOLatency: false, diskIOReadIds: [12, 9], diskIOWriteIds: [2, 51, 6], @@ -62,31 +62,31 @@ describe('TabPaneIOTierStatistics Test', () => { fileSystemType: [], fsCount: 80, funAsync: [], - funTids: [1,65], + funTids: [1, 65], hasFps: false, irqMapData: { size: 98 }, jsMemory: [], leftNs: 921599689, - memoryAbilityIds: [12,45], + memoryAbilityIds: [12, 45], nativeMemory: [], - nativeMemoryStatistic: [45,10,11], - networkAbilityIds: [14,10], + nativeMemoryStatistic: [45, 10, 11], + networkAbilityIds: [14, 10], perfAll: false, perfCpus: [], perfProcess: [], perfSampleIds: [32], perfThread: [], powerEnergy: [], - processTrackIds: [34,6], + processTrackIds: [34, 6], promiseList: [], recordStartNs: 780663789228, rightNs: 24952556624, - sdkCounterIds: [22,6], - sdkSliceIds: [66,9], + sdkCounterIds: [22, 6], + sdkSliceIds: [66, 9], smapsType: [], systemEnergy: [], - threadIds: [3,76], - virtualTrackIds: [77,90], + threadIds: [3, 76], + virtualTrackIds: [77, 90], vmCount: 56, }; it('ioTierStatistics01', function () { diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.test.ts index 4c39ccbc..87d1ce1b 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.test.ts @@ -13,12 +13,13 @@ * limitations under the License. */ // @ts-ignore -window.ResizeObserver = window.ResizeObserver || - jest.fn().mockImplementation(() => ({ - disconnect: jest.fn(), - observe: jest.fn(), - unobserve: jest.fn(), - })); +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); // @ts-ignore import { TabPaneIOTierStatisticsAnalysis } from '../../../../../../dist/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.js'; import '../../../../../../dist/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.js'; @@ -39,12 +40,12 @@ describe('TabPaneIOTierStatisticsAnalysis Test', () => { let param = { anomalyEnergy: [], clockMapData: { size: 985 }, - cpuAbilityIds: [12,45,7], - cpuFreqFilterIds: [10,67,9], + cpuAbilityIds: [12, 45, 7], + cpuFreqFilterIds: [10, 67, 9], cpuFreqLimitDatas: [], - cpuStateFilterIds: [23,4], + cpuStateFilterIds: [23, 4], cpus: [], - diskAbilityIds: [43,45,4], + diskAbilityIds: [43, 45, 4], diskIOLatency: false, diskIOReadIds: [24, 17, 71], diskIOWriteIds: [2, 14, 5, 36], @@ -53,30 +54,30 @@ describe('TabPaneIOTierStatisticsAnalysis Test', () => { fileSystemType: [], fsCount: 44, funAsync: [], - funTids: [23,78], + funTids: [23, 78], hasFps: false, irqMapData: { size: 966 }, jsMemory: [], leftNs: 964696659, - memoryAbilityIds: [65,67,89,11], + memoryAbilityIds: [65, 67, 89, 11], nativeMemory: [], nativeMemoryStatistic: [], - networkAbilityIds: [12,56,88], + networkAbilityIds: [12, 56, 88], perfAll: false, - perfCpus: [0,2], + perfCpus: [0, 2], perfProcess: [], - perfSampleIds: [11,53,110], + perfSampleIds: [11, 53, 110], perfThread: [], powerEnergy: [], - processTrackIds: [12,110,889], + processTrackIds: [12, 110, 889], promiseList: [], recordStartNs: 780423782222, rightNs: 24267332224, - sdkCounterIds: [12,4,55,1], - sdkSliceIds: [45,12], + sdkCounterIds: [12, 4, 55, 1], + sdkSliceIds: [45, 12], smapsType: [], systemEnergy: [], - threadIds: [66,3,10], + threadIds: [66, 3, 10], virtualTrackIds: [], vmCount: 17, }; @@ -264,4 +265,96 @@ describe('TabPaneIOTierStatisticsAnalysis Test', () => { tabPane.currentLevel = 4; expect(tabPane.sortByColumn('durFormat', 1)).toBeUndefined(); }); + it('tabPaneIOTierStatisticsAnalysis14', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.ioTierProcessLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis15', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.ioTierTypeLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis16', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.ioTierThreadLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis17', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.ioTierSoLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis18', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By type AllDuration'; + tabPane.processStatisticsData = jest.fn(() => true); + tabPane.processStatisticsData.allDuration = jest.fn(() => true); + tabPane.pidData = [{}, {}]; + tabPane.iOTierStatisticsAnalysisBack!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis19', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Thread AllDuration'; + tabPane.typeStatisticsData = jest.fn(() => true); + tabPane.typeStatisticsData.allDuration = jest.fn(() => true); + tabPane.typeData = [{}, {}]; + tabPane.iOTierStatisticsAnalysisBack!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis20', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Library AllDuration'; + tabPane.threadStatisticsData = jest.fn(() => true); + tabPane.threadStatisticsData.allDuration = jest.fn(() => true); + tabPane.threadData = [{}, {}]; + tabPane.iOTierStatisticsAnalysisBack!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('tabPaneIOTierStatisticsAnalysis21', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Function AllDuration'; + tabPane.libStatisticsData = jest.fn(() => true); + tabPane.libStatisticsData.allDuration = jest.fn(() => true); + tabPane.soData = [{}, {}]; + tabPane.iOTierStatisticsAnalysisBack!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.test.ts b/ide/test/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.test.ts index 84977099..6fffff93 100644 --- a/ide/test/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.test.ts +++ b/ide/test/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.test.ts @@ -23,12 +23,14 @@ import crypto from 'crypto'; import { TabPaneFilter } from '../../../../../../dist/trace/component/trace/sheet/TabPaneFilter.js'; // @ts-ignore window.ResizeObserver = - window.ResizeObserver || jest.fn().mockImplementation(() => ({ + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), - unobserve: jest.fn(), observe: jest.fn(), - })); + unobserve: jest.fn(), + observe: jest.fn(), + })); Object.defineProperty(global.self, 'crypto', { - value: { getRandomValues: (arr: string | any[]) => crypto.randomBytes(arr.length)}, + value: { getRandomValues: (arr: string | any[]) => crypto.randomBytes(arr.length) }, }); describe('TabPaneVirtualMemoryStatisticsAnalysis Test', () => { @@ -37,44 +39,44 @@ describe('TabPaneVirtualMemoryStatisticsAnalysis Test', () => { let param = { anomalyEnergy: [], clockMapData: { size: 623 }, - cpuAbilityIds: [234,56], - cpuFreqFilterIds: [46,87,9], + cpuAbilityIds: [234, 56], + cpuFreqFilterIds: [46, 87, 9], cpuFreqLimitDatas: [], - cpuStateFilterIds: [77,97,3], - cpus: [2,1], - diskAbilityIds: [43,98], + cpuStateFilterIds: [77, 97, 3], + cpus: [2, 1], + diskAbilityIds: [43, 98], diskIOLatency: false, diskIOReadIds: [1], - diskIOWriteIds: [12, 4 ,55, 6], - diskIOipids: [6,88, 3, 551, 6], + diskIOWriteIds: [12, 4, 55, 6], + diskIOipids: [6, 88, 3, 551, 6], fileSysVirtualMemory: true, fileSystemType: [], fsCount: 56, funAsync: [], - funTids: [6,87,2], + funTids: [6, 87, 2], hasFps: false, irqMapData: { size: 158 }, jsMemory: [], leftNs: 964699699, - memoryAbilityIds: [25,87,8], + memoryAbilityIds: [25, 87, 8], nativeMemory: [], nativeMemoryStatistic: [], - networkAbilityIds: [67,12,9], + networkAbilityIds: [67, 12, 9], perfAll: false, perfCpus: [], perfProcess: [], - perfSampleIds: [12,66,6], + perfSampleIds: [12, 66, 6], perfThread: [], powerEnergy: [], - processTrackIds: [42,87,43], + processTrackIds: [42, 87, 43], promiseList: [], recordStartNs: 780621789228, rightNs: 24269616624, - sdkCounterIds: [33,87,21], - sdkSliceIds: [2,7,2], + sdkCounterIds: [33, 87, 21], + sdkSliceIds: [2, 7, 2], smapsType: [], systemEnergy: [], - threadIds: [2,9,1], + threadIds: [2, 9, 1], virtualTrackIds: [], vmCount: 450, }; @@ -247,4 +249,96 @@ describe('TabPaneVirtualMemoryStatisticsAnalysis Test', () => { tabPane.currentLevel = 4; expect(tabPane.sortByColumn('durFormat', 1)).toBeUndefined(); }); + it('tabPaneVirtualMemoryStatisticsAnalysis12', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.vmProcessLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis13', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.vmTypeLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis14', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.vmThreadLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis15', function () { + let it = [ + { + tabName: '', + }, + ]; + expect(tabPane.vmSoLevelClickEvent(it)).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis16', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By type AllDuration'; + tabPane.processStatisticsData = jest.fn(() => true); + tabPane.processStatisticsData.allDuration = jest.fn(() => true); + tabPane.vmStatisticsAnalysisPidData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis17', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Thread AllDuration'; + tabPane.typeStatisticsData = jest.fn(() => true); + tabPane.typeStatisticsData.allDuration = jest.fn(() => true); + tabPane.vmStatisticsAnalysisTypeData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis18', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Library AllDuration'; + tabPane.threadStatisticsData = jest.fn(() => true); + tabPane.threadStatisticsData.allDuration = jest.fn(() => true); + tabPane.vmStatisticsAnalysisThreadData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); + it('tabPaneVirtualMemoryStatisticsAnalysis19', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabPane.tabName!.textContent = 'Statistic By Function AllDuration'; + tabPane.libStatisticsData = jest.fn(() => true); + tabPane.libStatisticsData.allDuration = jest.fn(() => true); + tabPane.vmStatisticsAnalysisSoData = [{}, {}]; + tabPane.back!.dispatchEvent(itemClick); + expect(tabPane.goBack()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/gpu/TabPaneGpuClickSelectComparison.test.ts b/ide/test/trace/component/trace/sheet/gpu/TabPaneGpuClickSelectComparison.test.ts index a936929d..e98b9dd4 100644 --- a/ide/test/trace/component/trace/sheet/gpu/TabPaneGpuClickSelectComparison.test.ts +++ b/ide/test/trace/component/trace/sheet/gpu/TabPaneGpuClickSelectComparison.test.ts @@ -86,4 +86,16 @@ describe('TabPaneGpuClickSelectComparison Test', () => { let tabPaneGpuClickSelectComparison = new TabPaneGpuClickSelectComparison(); expect(tabPaneGpuClickSelectComparison.selectStamps(dataList, type)).toBeUndefined(); }); + it('TabPaneGpuClickSelectComparisonTest04', () => { + let tabPaneGpuClickSelectComparison = new TabPaneGpuClickSelectComparison(); + expect(tabPaneGpuClickSelectComparison.sortGpuByColumn(0, '')).toBeUndefined(); + }); + it('TabPaneGpuClickSelectComparisonTest05', () => { + let tabPaneGpuClickSelectComparison = new TabPaneGpuClickSelectComparison(); + expect(tabPaneGpuClickSelectComparison.sortGpuByColumn(1, 'name')).toBeUndefined(); + }); + it('TabPaneGpuClickSelectComparisonTest06', () => { + let tabPaneGpuClickSelectComparison = new TabPaneGpuClickSelectComparison(); + expect(tabPaneGpuClickSelectComparison.sortGpuByColumn(1, 'sizeDelta')).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/hiperf/TabPanePerfAnalysis.test.ts b/ide/test/trace/component/trace/sheet/hiperf/TabPanePerfAnalysis.test.ts index 909b6655..d97fabb0 100644 --- a/ide/test/trace/component/trace/sheet/hiperf/TabPanePerfAnalysis.test.ts +++ b/ide/test/trace/component/trace/sheet/hiperf/TabPanePerfAnalysis.test.ts @@ -20,7 +20,9 @@ import crypto from 'crypto'; import { queryHiPerfProcessCount } from '../../../../../../dist/trace/database/SqlLite.js'; // @ts-ignore -window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), @@ -543,4 +545,43 @@ describe('TabPanePerfAnalysis Test', () => { tabPanePerfAnalysis.data = jest.fn(() => true); expect(tabPanePerfAnalysis).toBeTruthy(); }); + it('TabPanePerfAnalysisTest14', function () { + document.body.innerHTML = ` + `; + let tabPanePerfAnalysis = document.getElementById('slc') as TabPanePerfAnalysis; + let it = [ + { + tabName: '', + }, + ]; + tabPanePerfAnalysis.perfAnalysisPie = jest.fn(() => true); + tabPanePerfAnalysis.perfAnalysisPie.hideTip = jest.fn(() => true); + expect(tabPanePerfAnalysis.perfProcessLevelClickEvent(it, [])).toBeUndefined(); + }); + it('TabPanePerfAnalysisTest15', function () { + document.body.innerHTML = ` + `; + let tabPanePerfAnalysis = document.getElementById('slc') as TabPanePerfAnalysis; + let it = [ + { + tabName: '', + }, + ]; + tabPanePerfAnalysis.perfAnalysisPie = jest.fn(() => true); + tabPanePerfAnalysis.perfAnalysisPie.hideTip = jest.fn(() => true); + expect(tabPanePerfAnalysis.perfThreadLevelClickEvent(it, [])).toBeUndefined(); + }); + it('TabPanePerfAnalysisTest16', function () { + document.body.innerHTML = ` + `; + let tabPanePerfAnalysis = document.getElementById('slc') as TabPanePerfAnalysis; + let it = [ + { + tabName: '', + }, + ]; + tabPanePerfAnalysis.perfAnalysisPie = jest.fn(() => true); + tabPanePerfAnalysis.perfAnalysisPie.hideTip = jest.fn(() => true); + expect(tabPanePerfAnalysis.perfSoLevelClickEvent(it, [])).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/hiperf/TabPerfBottomUp.test.ts b/ide/test/trace/component/trace/sheet/hiperf/TabPerfBottomUp.test.ts index dae6ba37..76c047a9 100644 --- a/ide/test/trace/component/trace/sheet/hiperf/TabPerfBottomUp.test.ts +++ b/ide/test/trace/component/trace/sheet/hiperf/TabPerfBottomUp.test.ts @@ -45,4 +45,7 @@ describe('TabPanePerfBottomUp Test', () => { tabPanePerfBottomUp.data = data; expect(tabPanePerfBottomUp.data).toBeUndefined(); }); + it('TabPanePerfBottomUp03 ', function () { + expect(tabPanePerfBottomUp.setBottomUpTableData([])).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/hiperf/TabPerfProfile.test.ts b/ide/test/trace/component/trace/sheet/hiperf/TabPerfProfile.test.ts index 45029d5c..901f9fcc 100644 --- a/ide/test/trace/component/trace/sheet/hiperf/TabPerfProfile.test.ts +++ b/ide/test/trace/component/trace/sheet/hiperf/TabPerfProfile.test.ts @@ -108,4 +108,16 @@ describe('TabPerfProfile Test', () => { ]; expect(tabpanePerfProfile.data).toBeUndefined(); }); + it('TabpanePerfProfileTest12 ', function () { + let filterData = { + callTree: [{}, {}], + dataMining: { + concat: jest.fn(() => true), + }, + callTreeConstraints: { + checked: false, + }, + }; + expect(tabpanePerfProfile.refreshAllNode(filterData)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.test.ts b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.test.ts index 974fb4fe..25a8dbdc 100644 --- a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.test.ts +++ b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMCallTree.test.ts @@ -28,7 +28,9 @@ jest.mock('../../../../../../dist/trace/component/trace/base/TraceRow.js', () => const sqlit = require('../../../../../../dist/trace/database/SqlLite.js'); // @ts-ignore -window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), @@ -53,9 +55,8 @@ describe('TabPaneNMCallTree Test', () => { children: [], }; tabPaneNMCallTree.dataSource = []; - tabPaneNMCallTree.setRightTableData = jest.fn(() => true); let groupByWithTid = tabPaneNMCallTree.setRightTableData(hookLeft); - expect(groupByWithTid).toBeTruthy(); + expect(groupByWithTid).toBeUndefined(); }); it('TabPaneNMCallTreeTest02', function () { @@ -128,46 +129,9 @@ describe('TabPaneNMCallTree Test', () => { ]; expect(tabPaneNMCallTree.setLTableData(data)).toBeUndefined(); }); - it('TabPaneNMCallTreeTest11', function () { - let data = [ - { - callTreeConstraints: { - inputs: [1], - }, - dataMining: 20, - callTree: [], - icon: 'block', - }, - { - callTreeConstraints: { - inputs: [1], - }, - dataMining: 21, - callTree: [], - icon: 'block', - }, - { - callTreeConstraints: { - inputs: [1], - }, - dataMining: 31, - callTree: [], - icon: 'block', - }, - ]; - expect(tabPaneNMCallTree.switchFlameChart(data)).toBeUndefined(); - }); it('TabPaneNMCallTreeTest12', function () { expect(tabPaneNMCallTree.initFilterTypes()).toBeUndefined(); }); - it('TabPaneNMCallTreeTest13', function () { - let data = [ - { id: 0, count: 20, children: [] }, - { id: 1, count: 21, children: [] }, - { id: 2, count: 31, children: [] }, - ]; - expect(tabPaneNMCallTree.setRightTableData(data)).toBeTruthy(); - }); it('TabPaneNMCallTreeTest14', function () { expect(tabPaneNMCallTree.getDataByWorkerQuery({}, {})).toBeUndefined(); }); @@ -182,23 +146,21 @@ describe('TabPaneNMCallTree Test', () => { callTree: [], icon: 'tree', }, - { - callTreeConstraints: { - inputs: [1], - }, - dataMining: 21, - callTree: [], - icon: 'tree', - }, - { - callTreeConstraints: { - inputs: [1], - }, - dataMining: 31, - callTree: [], - icon: 'tree', - }, ]; expect(tabPaneNMCallTree.switchFlameChart(data)).toBeUndefined(); }); + it('TabPaneNMCallTreeTest16', function () { + let filterData = { + callTree: [{}, {}], + dataMining: { + concat: jest.fn(() => true), + }, + callTreeConstraints: { + checked: false, + }, + }; + tabPaneNMCallTree.currentSelection = jest.fn(() => true); + tabPaneNMCallTree.currentSelection.nativeMemory = jest.fn(() => true); + expect(tabPaneNMCallTree.refreshAllNode(filterData)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMStatisticAnalysis.test.ts b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMStatisticAnalysis.test.ts index 002e7cb0..0df9d863 100644 --- a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMStatisticAnalysis.test.ts +++ b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMStatisticAnalysis.test.ts @@ -377,4 +377,68 @@ describe('TabPaneNMStatisticAnalysis Test', () => { }; expect(tabStatisticAnalysis.getNMEventTypeSize(val)).toBeUndefined(); }); + it('statisticAnalysis18', function () { + let it = [ + { + tabName: '', + }, + ]; + tabStatisticAnalysis.totalData = jest.fn(() => true); + tabStatisticAnalysis.pie = jest.fn(() => true); + tabStatisticAnalysis.pie.hideTip = jest.fn(() => true); + expect(tabStatisticAnalysis.nativeProcessLevelClickEvent(it)).toBeUndefined(); + }); + it('statisticAnalysis19', function () { + let it = [ + { + tabName: '', + }, + ]; + tabStatisticAnalysis.totalData = jest.fn(() => true); + tabStatisticAnalysis.pie = jest.fn(() => true); + tabStatisticAnalysis.pie.hideTip = jest.fn(() => true); + expect(tabStatisticAnalysis.nativeSoLevelClickEvent(it)).toBeUndefined(); + }); + it('statisticAnalysis20', function () { + expect(tabStatisticAnalysis.calPercent([])).toBeUndefined(); + }); + it('statisticAnalysis21', function () { + expect(tabStatisticAnalysis.calSizeObj([])).toBeTruthy(); + }); + it('statisticAnalysis23', function () { + tabStatisticAnalysis.threadUsageTbl = jest.fn(() => true); + tabStatisticAnalysis.threadUsageTbl.reMeauseHeight = jest.fn(() => true); + tabStatisticAnalysis.threadUsageTbl.addEventListener = jest.fn(() => true); + expect(tabStatisticAnalysis.getNMThreadSize(dataArray, select)).toBeUndefined(); + }); + it('statisticAnalysis24', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabStatisticAnalysis.tabName!.textContent = 'Statistic By Library Existing'; + tabStatisticAnalysis.typeStatisticsData = jest.fn(() => true); + tabStatisticAnalysis.typeStatisticsData.allDuration = jest.fn(() => true); + tabStatisticAnalysis.eventTypeData = [{}, {}]; + tabStatisticAnalysis.back!.dispatchEvent(itemClick); + expect(tabStatisticAnalysis.getBack()).toBeUndefined(); + }); + it('statisticAnalysis25', function () { + let itemClick = new CustomEvent('click', { + detail: { + ...{}, + data: {}, + }, + composed: true, + }); + tabStatisticAnalysis.tabName!.textContent = 'Statistic By Function Existing'; + tabStatisticAnalysis.libStatisticsData = jest.fn(() => true); + tabStatisticAnalysis.libStatisticsData.allDuration = jest.fn(() => true); + tabStatisticAnalysis.soData = [{}, {}]; + tabStatisticAnalysis.back!.dispatchEvent(itemClick); + expect(tabStatisticAnalysis.getBack()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMemory.test.ts b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMemory.test.ts index 806451dc..fce54635 100644 --- a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMemory.test.ts +++ b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMemory.test.ts @@ -94,4 +94,10 @@ describe('TabPaneNMemory Test', () => { it('TabPaneNMemoryTest20', function () { expect(tabPaneNMemory.startWorker({}, {})).toBeTruthy(); }); + it('TabPaneNMemoryTest21', function () { + expect(tabPaneNMemory.getDataByNativeMemoryWorker([], false)).toBeUndefined(); + }); + it('TabPaneNMemoryTest22', function () { + expect(tabPaneNMemory.resetFilter()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.test.ts b/ide/test/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.test.ts index 1e51f2ca..fb2b473f 100644 --- a/ide/test/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.test.ts +++ b/ide/test/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.test.ts @@ -18,6 +18,7 @@ jest.mock('../../../../../../dist/trace/database/SqlLite.js'); jest.mock('../../../../../../dist/base-ui/select/LitSelect.js', () => { return {}; }); +jest.mock('../../../../../../dist/js-heap/model/DatabaseStruct.js', () => {}); jest.mock('../../../../../../dist/base-ui/table/lit-table.js', () => { return { snapshotDataSource: () => {}, @@ -25,11 +26,12 @@ jest.mock('../../../../../../dist/base-ui/table/lit-table.js', () => { }; }); // @ts-ignore -window.ResizeObserver = window.ResizeObserver || +window.ResizeObserver = + window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), - observe: jest.fn(), unobserve: jest.fn(), + observe: jest.fn(), })); describe('TabPaneGpuMemoryVmTrackerComparison Test', () => { @@ -64,9 +66,9 @@ describe('TabPaneGpuMemoryVmTrackerComparison Test', () => { expect(tabPaneGpuMemoryVmTrackerComparison.getComparisonData(10)).toBeTruthy(); }); it('TabPaneGpuMemoryVmTrackerComparison03', function () { - expect(tabPaneGpuMemoryVmTrackerComparison.comparisonDataByDB(10, datalist)).toBeTruthy(); + expect(tabPaneGpuMemoryVmTrackerComparison.sortGpuMemoryByColumn(0, '')).toBeUndefined(); }); it('TabPaneGpuMemoryVmTrackerComparison04', function () { - expect(tabPaneGpuMemoryVmTrackerComparison.selectStamps(datalist)).toBeUndefined(); + expect(tabPaneGpuMemoryVmTrackerComparison.sortGpuMemoryByColumn(1, 'thread')).toBeUndefined(); }); }); diff --git a/ide/test/trace/component/trace/timer-shaft/RangeRuler.test.ts b/ide/test/trace/component/trace/timer-shaft/RangeRuler.test.ts index 7e2d9f20..db06e38e 100644 --- a/ide/test/trace/component/trace/timer-shaft/RangeRuler.test.ts +++ b/ide/test/trace/component/trace/timer-shaft/RangeRuler.test.ts @@ -23,7 +23,6 @@ jest.mock('../../../../../dist/trace/database/ui-worker/ProcedureWorker.js', () return {}; }); - describe('RangeRuler Test', () => { const canvas = document.createElement('canvas'); canvas.width = 1; @@ -283,6 +282,12 @@ describe('RangeRuler Test', () => { expect(rangeRuler.keyPressF()).toBeUndefined(); }); it('RangeRulerTest27', function () { - expect(rangeRuler.zoomFit('100','200')).toBeUndefined(); + expect(rangeRuler.zoomFit('100', '200')).toBeUndefined(); + }); + it('RangeRulerTest28', function () { + expect(Mark.draw).toBeUndefined(); + }); + it('RangeRulerTest29', function () { + expect(rangeRuler.drawSelectionRange()).toBeUndefined(); }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerCommon.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerCommon.test.ts index 43bb9e4d..c4eb532b 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerCommon.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerCommon.test.ts @@ -24,6 +24,8 @@ import { timeMsFormat2p, getProbablyTime, convertJSON, + JsProfilerSymbol, + DataCache, //@ts-ignore } from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerCommon.js'; describe('ProcedureLogicWorkerCommon Test', () => { @@ -77,28 +79,6 @@ describe('ProcedureLogicWorkerCommon Test', () => { expect(merageBeanDataSplit.splitTree('', [{ children: [] }], '', false, [''], '')).toBeUndefined(); }); - it('MerageBeanTest07', function () { - merageBeanDataSplit.recursionChargeInitTree = jest.fn(() => true); - let node = { - symbolName: '', - libName: '', - }; - expect(merageBeanDataSplit.recursionChargeInitTree('', node, '', true)).toBeTruthy(); - }); - - it('MerageBeanTest47', function () { - merageBeanDataSplit.recursionChargeInitTree = jest.fn(() => undefined); - merageBeanDataSplit.resetAllNode = jest.fn(() => true); - let node = { - symbolName: '', - libName: '', - initChildren: { - length: 1, - }, - }; - expect(merageBeanDataSplit.recursionChargeInitTree('', node, [], true)).toBeUndefined(); - }); - it('MerageBeanTest30', function () { expect(getByteWithUnit(-1_000_000_001)).toBe('-953.67 Mb'); }); @@ -203,54 +183,6 @@ describe('ProcedureLogicWorkerCommon Test', () => { expect(merageBeanDataSplit.recursionChargeTree(node, '', true)).toBeTruthy(); }); - it('MerageBeanTest18', function () { - merageBeanDataSplit.recursionPruneInitTree = jest.fn(() => true); - let node = [ - { - initChildren: { - length: 1, - }, - }, - ]; - expect(merageBeanDataSplit.recursionPruneInitTree('', node, '', true)).toBeTruthy(); - }); - - it('MerageBeanTest19', function () { - merageBeanDataSplit.recursionPruneTree = jest.fn(() => true); - let node = [ - { - initChildren: { - length: 1, - }, - }, - ]; - expect(merageBeanDataSplit.recursionPruneTree(node, '', true)).toBeTruthy(); - }); - - it('MerageBeanTest20', function () { - merageBeanDataSplit.recursionChargeByRule = jest.fn(() => true); - let node = [ - { - initChildren: { - length: 1, - }, - }, - ]; - expect(merageBeanDataSplit.recursionChargeByRule('', node, '', true)).toBeTruthy(); - }); - - it('MerageBeanTest21', function () { - merageBeanDataSplit.pruneChildren = jest.fn(() => true); - let node = [ - { - initChildren: { - length: 1, - }, - }, - ]; - expect(merageBeanDataSplit.pruneChildren('', node, '')).toBeTruthy(); - }); - it('MerageBeanTest22', function () { merageBeanDataSplit.hideSystemLibrary = jest.fn(() => true); expect(merageBeanDataSplit.hideSystemLibrary('', '')).toBeTruthy(); @@ -290,4 +222,66 @@ describe('ProcedureLogicWorkerCommon Test', () => { merageBeanDataSplit.splitAllProcess = jest.fn(() => true); expect(merageBeanDataSplit.splitAllProcess('', '', [])).toBeTruthy(); }); + it('MerageBeanTest32', function () { + let node = { + initChildren: { + length: 10, + forEach: jest.fn(() => true), + }, + }; + expect(merageBeanDataSplit.recursionChargeInitTree([], node, [], true)).toBeTruthy(); + }); + it('MerageBeanTest3', function () { + let node = { + initChildren: { + length: 10, + forEach: jest.fn(() => true), + }, + }; + expect(merageBeanDataSplit.recursionPruneInitTree([], node, [], true)).toBeTruthy(); + }); + it('MerageBeanTest45', function () { + let node = { + initChildren: { + length: 10, + forEach: jest.fn(() => true), + }, + }; + expect(merageBeanDataSplit.recursionChargeByRule([], node, [], true)).toBeUndefined(); + }); + it('MerageBeanTest46', function () { + let node = { + children: { + forEach: jest.fn(() => true), + }, + }; + expect(merageBeanDataSplit.recursionPruneTree(node, [], true)).toBeUndefined(); + }); + it('MerageBeanTest48', function () { + let node = { + initChildren: { + length: 10, + forEach: jest.fn(() => true), + }, + }; + expect(merageBeanDataSplit.pruneChildren([], node, true)).toBeUndefined(); + }); + it('MerageBeanTest49', function () { + let search = { + toLocaleLowerCase: jest.fn(() => true), + }; + expect(merageBeanDataSplit.findSearchNode([], search, [])).toBeUndefined(); + }); + it('MerageBeanTest50', function () { + let jsProfilerSymbol = new JsProfilerSymbol(); + expect(jsProfilerSymbol).not.toBeUndefined(); + }); + it('MerageBeanTest51', function () { + let jsProfilerSymbol = new JsProfilerSymbol(); + expect(jsProfilerSymbol.clone()).not.toBeUndefined(); + }); + it('MerageBeanTest52', function () { + let dataCache = new DataCache(); + expect(dataCache.clearAll()).toBeUndefined(); + }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.test.ts index 87813452..85c743b3 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.test.ts @@ -497,4 +497,75 @@ describe('ProcedureLogicWorkerFileSystem Test', () => { window.postMessage = jest.fn(() => true); expect(handlerMap.queryPageFaultSamples(selectionParam)).toBeUndefined(); }); + it('procedureLogicWorkerFileSystemTest60', function () { + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerF.fileSystemAnalysis([], [])).toEqual([]); + }); + it('procedureLogicWorkerFileSystemTest61', function () { + let handlerMap = procedureLogicWorkerF.handlerMap.get('fileSystem'); + window.postMessage = jest.fn(() => true); + expect(handlerMap.setEventId([])).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest62', function () { + let handlerMap = procedureLogicWorkerF.handlerMap.get('fileSystem'); + window.postMessage = jest.fn(() => true); + expect(handlerMap.setEventId([])).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest63', function () { + let handlerMap = procedureLogicWorkerF.handlerMap.get('io'); + let selectionParam = { + diskIOipids: { + length: 2, + join: jest.fn(() => true), + }, + diskIOReadIds: { + length: 2, + join: jest.fn(() => true), + }, + diskIOWriteIds: { + length: 2, + join: jest.fn(() => true), + }, + }; + window.postMessage = jest.fn(() => true); + expect(handlerMap.queryCallChainsSamples(selectionParam)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest64', function () { + let handlerMap = procedureLogicWorkerF.handlerMap.get('virtualMemory'); + let selectionParam = { + diskIOipids: { + length: 3, + join: jest.fn(() => true), + }, + diskIOReadIds: { + length: 3, + join: jest.fn(() => true), + }, + diskIOWriteIds: { + length: 3, + join: jest.fn(() => true), + }, + }; + window.postMessage = jest.fn(() => true); + expect(handlerMap.queryCallChainsSamples(selectionParam)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest65', function () { + let handlerMap = procedureLogicWorkerF.handlerMap.get('io'); + let selectionParam = { + diskIOipids: { + length: 3, + join: jest.fn(() => true), + }, + diskIOReadIds: { + length: 3, + join: jest.fn(() => true), + }, + diskIOWriteIds: { + length: 3, + join: jest.fn(() => true), + }, + }; + window.postMessage = jest.fn(() => true); + expect(handlerMap.queryIOSamples(selectionParam)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.test.ts index 459e93db..c95ab1f9 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.test.ts @@ -14,7 +14,10 @@ */ //@ts-ignore -import { ProcedureLogicWorkerJsCpuProfiler } from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.js'; +import { + ProcedureLogicWorkerJsCpuProfiler, + JsCpuProfilerSample, +} from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerJsCpuProfiler.js'; describe('ProcedureLogicWorkerJsCpuProfiler Test', () => { it('ProcedureLogicWorkerJsCpuProfiler01', function () { @@ -114,4 +117,40 @@ describe('ProcedureLogicWorkerJsCpuProfiler Test', () => { window.postMessage = jest.fn(() => true); expect(procedureLogicWorkerJsCpuProfiler.handle(data)).toBeUndefined(); }); + it('ProcedureLogicWorkerJsCpuProfiler09', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + let chartFrame = { + parent: true, + }; + expect(procedureLogicWorkerJsCpuProfiler.copyParent([], chartFrame)).toBeUndefined(); + }); + it('ProcedureLogicWorkerJsCpuProfiler10', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + expect(procedureLogicWorkerJsCpuProfiler.calStatistic([], 11, 43)).toBeTruthy(); + }); + it('ProcedureLogicWorkerJsCpuProfiler11', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + procedureLogicWorkerJsCpuProfiler.dataCache = jest.fn(() => true); + procedureLogicWorkerJsCpuProfiler.dataCache.clearAll = jest.fn(() => true); + expect(procedureLogicWorkerJsCpuProfiler.clearAll()).toBeUndefined(); + }); + it('ProcedureLogicWorkerJsCpuProfiler12', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + expect(procedureLogicWorkerJsCpuProfiler.getFullCallChainOfNode([])).toBeTruthy(); + }); + it('ProcedureLogicWorkerJsCpuProfiler13', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + expect(procedureLogicWorkerJsCpuProfiler.symbolToChartFrame([], [])).toBeTruthy(); + }); + it('ProcedureLogicWorkerJsCpuProfiler14', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + expect(procedureLogicWorkerJsCpuProfiler.chartFrameToTabStruct([], [])).toBeTruthy(); + }); + it('ProcedureLogicWorkerJsCpuProfiler15', function () { + let procedureLogicWorkerJsCpuProfiler = new ProcedureLogicWorkerJsCpuProfiler(); + expect(procedureLogicWorkerJsCpuProfiler.isSymbolEqual([], [])).toBeTruthy(); + }); + it('ProcedureLogicWorkerJsCpuProfiler16', function () { + expect(JsCpuProfilerSample).toBeUndefined(); + }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.test.ts index 681ab400..b7b20440 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.test.ts @@ -493,4 +493,324 @@ describe('ProcedureLogicWorkerNativeNemory Test', () => { }, ]); }); + it('procedureLogicWorkerFileSystemTest56', function () { + window.postMessage = jest.fn(() => true); + let data = { + params: { + list: '', + get: jest.fn(() => true), + }, + action: '', + id: 2, + type: 'native-memory-queryNativeHookEvent', + }; + procedureLogicWorkerNativeMemory.clearAll = jest.fn(() => true); + procedureLogicWorkerNativeMemory.initDataDict = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.handle(data)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest57', function () { + window.postMessage = jest.fn(() => true); + let data = { + params: { + list: '', + types: { + join: jest.fn(() => true), + }, + }, + action: '', + id: 4, + type: 'native-memory-queryAnalysis', + }; + procedureLogicWorkerNativeMemory.clearAll = jest.fn(() => true); + procedureLogicWorkerNativeMemory.initDataDict = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.handle(data)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest58', function () { + window.postMessage = jest.fn(() => true); + let data = { + params: { + list: '', + types: { + join: jest.fn(() => true), + }, + }, + action: 'c', + id: 4, + type: 'native-memory-queryStatisticCallchainsSamples', + }; + procedureLogicWorkerNativeMemory.clearAll = jest.fn(() => true); + procedureLogicWorkerNativeMemory.initDataDict = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.handle(data)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest59', function () { + window.postMessage = jest.fn(() => true); + let data = { + params: { + types: { + join: jest.fn(() => true), + }, + list: '', + }, + action: '', + id: 4, + type: 'native-memory-queryCallchainsSamples', + }; + procedureLogicWorkerNativeMemory.clearAll = jest.fn(() => true); + procedureLogicWorkerNativeMemory.initDataDict = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.handle(data)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest60', function () { + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.supplementNativeHoodData()).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest61', function () { + window.postMessage = jest.fn(() => true); + let memory = { + subTypeId: '', + }; + expect(procedureLogicWorkerNativeMemory.fillNativeHook(memory)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest62', function () { + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.initNMFrameData()).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest63', function () { + window.postMessage = jest.fn(() => true); + let paramMap = { + get: jest.fn(() => true), + }; + expect(procedureLogicWorkerNativeMemory.resolvingAction(paramMap)).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest64', function () { + window.postMessage = jest.fn(() => true); + let paramMap = { + get: jest.fn(() => true), + }; + expect(procedureLogicWorkerNativeMemory.resolvingActionNativeMemoryStack(paramMap)).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest65', function () { + window.postMessage = jest.fn(() => true); + let paramMap = { + get: jest.fn(() => true), + }; + expect(procedureLogicWorkerNativeMemory.resolvingActionNativeMemory(paramMap)).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest66', function () { + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.sortByNativeMemoryColumn('', 0, [])).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest67', function () { + window.postMessage = jest.fn(() => true); + let arr = { + isRelease: true, + startTs: 31, + endTs: 61, + addr: '', + }; + expect(procedureLogicWorkerNativeMemory.setApplyIsRelease([], arr)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest68', function () { + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.freshCurrentCallchains([], true)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest69', function () { + window.postMessage = jest.fn(() => true); + let paramMap = { + get: jest.fn(() => true), + }; + expect(procedureLogicWorkerNativeMemory.groupCallchainSample(paramMap)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest70', function () { + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerNativeMemory.createThreadSample([])).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest71', function () { + window.postMessage = jest.fn(() => true); + let currentNode = { + initChildren: { + filter: jest.fn(() => true), + }, + }; + expect(procedureLogicWorkerNativeMemory.merageChildrenByIndex(currentNode, [], 21, [], true)).toBeUndefined(); + }); + it('procedureLogicWorkerFileSystemTest72', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 1, + funcName: 'groupCallchainSample', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest73', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 1, + funcName: 'getCallChainsBySampleIds', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest74', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 1, + funcName: 'hideSystemLibrary', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest75', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 1, + funcName: 'hideNumMaxAndMin', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest76', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 1, + funcName: 'splitAllProcess', + funcArgs: [ + { + get: jest.fn(() => true), + forEach: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest77', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 2, + funcName: 'resetAllNode', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest78', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 2, + funcName: 'resotreAllNode', + funcArgs: [ + { + get: jest.fn(() => true), + forEach: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest79', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 2, + funcName: 'splitTree', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest80', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 2, + funcName: 'setSearchValue', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest81', function () { + window.postMessage = jest.fn(() => true); + let params = [ + { + length: 2, + funcName: 'clearSplitMapData', + funcArgs: [ + { + get: jest.fn(() => true), + }, + ], + }, + ]; + expect(procedureLogicWorkerNativeMemory.resolvingNMCallAction(params)).toStrictEqual([]); + }); + it('procedureLogicWorkerFileSystemTest83', function () { + window.postMessage = jest.fn(() => true); + let nativeHookCallInfo = new NativeHookCallInfo(); + expect(nativeHookCallInfo.totalCount).toEqual(0); + }); + it('procedureLogicWorkerFileSystemTest84', function () { + window.postMessage = jest.fn(() => true); + let nativeHookCallInfo = new NativeHookCallInfo(); + expect(nativeHookCallInfo.totalSize).toEqual(0); + }); + it('procedureLogicWorkerFileSystemTest85', function () { + window.postMessage = jest.fn(() => true); + let nativeHookCallInfo = new NativeHookCallInfo(); + nativeHookCallInfo.totalCount = true; + expect(nativeHookCallInfo).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest86', function () { + window.postMessage = jest.fn(() => true); + let nativeHookCallInfo = new NativeHookCallInfo(); + nativeHookCallInfo.totalSize = true; + expect(nativeHookCallInfo).toBeTruthy(); + }); + it('procedureLogicWorkerFileSystemTest87', function () { + let currentNode = { + symbol: '', + }; + expect(NativeHookCallInfo.merageCallChainSample(currentNode, [], [])); + }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerPerf.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerPerf.test.ts index 469a8c04..671e3284 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerPerf.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerPerf.test.ts @@ -24,6 +24,7 @@ import { PerfFile, PerfThread, PerfCallChain, + PerfAnalysisSample, } from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerPerf.js'; //@ts-ignore import { PerfCall } from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerCommon.js'; @@ -399,8 +400,10 @@ describe('ProcedureLogicWorkerPerf Test', () => { }); it('PerfFileTest02', function () { let perfFile = new PerfFile(); - let path = true; - expect(perfFile.setFileName(path)).toBeUndefined(); + perfFile.path = jest.fn(() => true); + perfFile.path.lastIndexOf = jest.fn(() => true); + perfFile.path.substring = jest.fn(() => true); + expect(perfFile.setFileName()).toBeUndefined(); }); it('PerfThreadTest01', function () { let perfThread = new PerfThread(); @@ -586,4 +589,211 @@ describe('ProcedureLogicWorkerPerf Test', () => { ]; expect(procedureLogicWorkerPerf.addPerfGroupData(callChains)).toBeUndefined(); }); + it('ProcedureLogicWorkerPerfTest60', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + expect(procedureLogicWorkerPerf.getPerfCallChainsBySampleIds([], true)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest61', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let currentNode = { + initChildren: { + filter: jest.fn(() => true), + }, + }; + expect(procedureLogicWorkerPerf.mergeChildrenByIndex(currentNode, [], 9, [], true)).toBeUndefined(); + }); + it('ProcedureLogicWorkerPerfTest62', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let sample = { + symbolName: '', + initChildren: { + length: 2, + forEach: jest.fn(() => true), + }, + }; + expect(procedureLogicWorkerPerf.recursionPerfChargeInitTree(sample, [], true)).toBeUndefined(); + }); + it('ProcedureLogicWorkerPerfTest63', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let sample = { + symbolName: '', + initChildren: { + length: 2, + forEach: jest.fn(() => true), + }, + }; + expect(procedureLogicWorkerPerf.recursionPerfPruneInitTree(sample, [], true)).toBeUndefined(); + }); + it('ProcedureLogicWorkerPerfTest64', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'hideSystemLibrary', + funcArgs: [{}], + }, + ]; + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest65', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'hideNumMaxAndMin', + funcArgs: [{}], + }, + ]; + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest66', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'getCurrentDataFromDb', + funcArgs: [ + { + perfAll: 1, + }, + ], + }, + ]; + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest67', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'splitAllProcess', + funcArgs: [ + { + perfAll: 1, + forEach: jest.fn(() => true), + }, + ], + }, + ]; + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest68', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'resetAllNode', + funcArgs: [{}], + }, + ]; + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest69', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'resotreAllNode', + funcArgs: [ + { + forEach: jest.fn(() => true), + }, + ], + }, + ]; + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest70', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'clearSplitMapData', + funcArgs: [ + { + forEach: jest.fn(() => true), + }, + ], + }, + ]; + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest71', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + let params = [ + { + length: 2, + funcName: 'splitTree', + funcArgs: [ + { + forEach: jest.fn(() => true), + }, + ], + }, + ]; + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.resolvingAction(params)).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest72', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.topUpDataToBottomUpData([])).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest73', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerPerf.mergeTreeBifurcation([], [])).toBeTruthy(); + }); + it('ProcedureLogicWorkerPerfTest74', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + window.postMessage = jest.fn(() => true); + let perfBottomUpStruct = { + addChildren: jest.fn(() => true), + }; + expect(procedureLogicWorkerPerf.copyParentNode(perfBottomUpStruct, { parentNode: 1 })).toBeUndefined(); + }); + it('ProcedureLogicWorkerPerfTest75', function () { + let procedureLogicWorkerPerf = new ProcedureLogicWorkerPerf(); + window.postMessage = jest.fn(() => true); + let perfBottomUpStruct = { + addChildren: jest.fn(() => true), + }; + expect(procedureLogicWorkerPerf.copyParentNode(perfBottomUpStruct, { parentNode: 1 })).toBeUndefined(); + }); + it('PerfCallChainTest76', function () { + expect(PerfCallChain.setNextNode([], [])); + }); + it('PerfCallChainTest77', function () { + expect(PerfCallChain.setPreviousNode([], [])); + }); + it('PerfCallChainTest78', function () { + expect(PerfCallChain.merageCallChain([], [])); + }); + it('PerfCallChainTest79', function () { + let currentNode = { + symbolName: '', + }; + let callChain = { + vaddrInFile: { + toString: jest.fn(() => true), + }, + }; + expect(PerfCallChainMerageData.merageCallChain(currentNode, callChain, true)); + }); + it('PerfCallChainTest80', function () { + let currentNode = { + symbolName: '', + }; + let callChain = { + vaddrInFile: { + toString: jest.fn(() => true), + }, + }; + expect(PerfCallChainMerageData.merageCallChainSample(currentNode, callChain, [], true)); + }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSPT.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSPT.test.ts index 62f8d2ec..58422b61 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSPT.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSPT.test.ts @@ -14,12 +14,7 @@ */ //@ts-ignore -import { - ProcedureLogicWorkerSPT, - ThreadState, - ThreadProcess, - SPT, -} from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerSPT.js'; +import { ProcedureLogicWorkerSPT, SPT,} from '../../../../dist/trace/database/logic-worker/ProcedureLogicWorkerSPT.js'; describe('ProcedureLogicWorkerSPT Test', () => { it('ProcedureLogicWorkerSPTTest01', function () { @@ -27,21 +22,6 @@ describe('ProcedureLogicWorkerSPT Test', () => { expect(procedureLogicWorkerSPT).not.toBeUndefined(); }); - it('ProcedureLogicWorkerSPTTest03', function () { - let threadState = new ThreadState(); - expect(threadState).not.toBeUndefined(); - }); - - it('ProcedureLogicWorkerSPTTest04', function () { - let threadProcess = new ThreadProcess(); - expect(threadProcess).not.toBeUndefined(); - }); - - it('ProcedureLogicWorkerSPTTest05', function () { - let sPT = new SPT(); - expect(sPT).not.toBeUndefined(); - }); - it('ProcedureLogicWorkerSPTTest06', function () { let procedureLogicWorkerSPT = new ProcedureLogicWorkerSPT(); let data = { @@ -96,19 +76,19 @@ describe('ProcedureLogicWorkerSPT Test', () => { window.postMessage = jest.fn(() => true); expect(procedureLogicWorkerSPT.getThreadState()).toBeUndefined(); }); - it('ProcedureLogicWorkerSPTTest11', function () { + it('ProcedureLogicWorkerSPTTest12', function () { let procedureLogicWorkerSPT = new ProcedureLogicWorkerSPT(); window.postMessage = jest.fn(() => true); - expect(procedureLogicWorkerSPT.getThreadProcessData()).toBeUndefined(); + expect(procedureLogicWorkerSPT.getSPTData()).toBeTruthy(); }); - it('ProcedureLogicWorkerSPTTest12', function () { + it('ProcedureLogicWorkerSPTTest14', function () { let procedureLogicWorkerSPT = new ProcedureLogicWorkerSPT(); window.postMessage = jest.fn(() => true); - expect(procedureLogicWorkerSPT.getSPTData()).toBeTruthy(); + expect(procedureLogicWorkerSPT.clearAll()).toBeUndefined(); }); - it('ProcedureLogicWorkerSPTTest13', function () { + it('ProcedureLogicWorkerSPTTest15', function () { let procedureLogicWorkerSPT = new ProcedureLogicWorkerSPT(); window.postMessage = jest.fn(() => true); - expect(procedureLogicWorkerSPT.initProcessThreadStateData()).toBeUndefined(); + expect(procedureLogicWorkerSPT.getPTSData()).toBeTruthy(); }); }); diff --git a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.test.ts b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.test.ts index fb4b0aa0..54a75fc8 100644 --- a/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.test.ts +++ b/ide/test/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.test.ts @@ -445,4 +445,19 @@ describe('ProcedureLogicWorkerSchedulingAnalysis Test', () => { window.postMessage = jest.fn(() => true); expect(procedureLogicWorkerSchedulingAnalysis.handle(data)).toBeUndefined(); }); + it('ProcedureLogicWorkerSchedulingAnalysisTest43', function () { + let procedureLogicWorkerSchedulingAnalysis = new ProcedureLogicWorkerSchedulingAnalysis(); + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerSchedulingAnalysis.groupIrgDataByCpu([])).toBeTruthy(); + }); + it('ProcedureLogicWorkerSchedulingAnalysisTest44', function () { + let procedureLogicWorkerSchedulingAnalysis = new ProcedureLogicWorkerSchedulingAnalysis(); + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerSchedulingAnalysis.computeCpuMeasureDur([], 1)).toBeTruthy(); + }); + it('ProcedureLogicWorkerSchedulingAnalysisTest45', function () { + let procedureLogicWorkerSchedulingAnalysis = new ProcedureLogicWorkerSchedulingAnalysis(); + window.postMessage = jest.fn(() => true); + expect(procedureLogicWorkerSchedulingAnalysis.handlerThreadCpuUsageData([])).toBeTruthy(); + }); }); diff --git a/ide/test/trace/database/ui-worker/ProcedureWorkerAppStartup.test.ts b/ide/test/trace/database/ui-worker/ProcedureWorkerAppStartup.test.ts index e86636ca..072ea725 100644 --- a/ide/test/trace/database/ui-worker/ProcedureWorkerAppStartup.test.ts +++ b/ide/test/trace/database/ui-worker/ProcedureWorkerAppStartup.test.ts @@ -31,7 +31,7 @@ describe('ProcedureWorkerAppStartup Test', () => { frame: { x: 20, y: 20, - width: 6, + width: 9, height: 3, }, dur: 1, diff --git a/ide/test/trace/database/ui-worker/ProcedureWorkerCPU.test.ts b/ide/test/trace/database/ui-worker/ProcedureWorkerCPU.test.ts index 56cfaa75..316d2350 100644 --- a/ide/test/trace/database/ui-worker/ProcedureWorkerCPU.test.ts +++ b/ide/test/trace/database/ui-worker/ProcedureWorkerCPU.test.ts @@ -14,8 +14,7 @@ */ // @ts-ignore -import {TraceRow} from "../../../../dist/trace/component/trace/base/TraceRow.js"; - +import { TraceRow } from '../../../../dist/trace/component/trace/base/TraceRow.js'; // @ts-ignore import { @@ -27,10 +26,10 @@ import { } from '../../../../dist/trace/database/ui-worker/ProcedureWorkerCPU.js'; // @ts-ignore import { Rect } from '../../../../dist/trace/component/trace/timer-shaft/Rect.js'; +import { drawWakeUp } from '../../../../dist/trace/database/ui-worker/ProcedureWorkerCommon'; jest.mock('../../../../dist/trace/component/trace/timer-shaft/RangeRuler.js', () => { - return { - }; + return {}; }); jest.mock('../../../../dist/trace/database/ui-worker/ProcedureWorker.js', () => { return {}; @@ -215,7 +214,7 @@ describe(' Test', () => { width: 75, height: 90, }, - canvas: '', + canvas: 'abc', context: { measureText: jest.fn(() => true), clearRect: jest.fn(() => true), diff --git a/ide/test/trace/database/ui-worker/ProcedureWorkerCommon.test.ts b/ide/test/trace/database/ui-worker/ProcedureWorkerCommon.test.ts index e8c5ca7e..e7d3da6e 100644 --- a/ide/test/trace/database/ui-worker/ProcedureWorkerCommon.test.ts +++ b/ide/test/trace/database/ui-worker/ProcedureWorkerCommon.test.ts @@ -40,6 +40,9 @@ import { drawFlagLineSegment, drawSelectionRange, drawLinkLines, + drawBezierCurve, + drawString2Line, + drawWakeUpList, // @ts-ignore } from '../../../../dist/trace/database/ui-worker/ProcedureWorkerCommon.js'; // @ts-ignore @@ -460,4 +463,36 @@ describe('ProcedureWorkerCommon Test', () => { }; expect(drawSelectionRange(context, params)).toBeUndefined(); }); + it('ProcedureWorkerCommon36', function () { + expect(FilterConfig).toBeUndefined(); + }); + it('ProcedureWorkerCommon37', function () { + const canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + const context = canvas.getContext('2d'); + let tm = { + getRange:jest.fn(()=>true), + getBoundingClientRect:jest.fn(()=>true), + }; + expect(drawLinkLines(context,[],tm,true)).toBeUndefined(); + }); + it('ProcedureWorkerCommon38', function () { + const canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + const context = canvas.getContext('2d'); + expect(drawString2Line(context,[],[],2,[],[])).toBeUndefined(); + }); + it('ProcedureWorkerCommon39', function () { + const canvas = document.createElement('canvas'); + canvas.width = 1; + canvas.height = 1; + const context = canvas.getContext('2d'); + let wake = { + wakeupTime:23, + }; + let frame = new Rect(20, 30, 10, 30); + expect(drawWakeUpList(context,wake,0,1000,1000,frame,true,undefined,false)).toBeUndefined(); + }); }); diff --git a/ide/test/trace/database/ui-worker/ProcedureWorkerEnergyState.test.ts b/ide/test/trace/database/ui-worker/ProcedureWorkerEnergyState.test.ts index 5cd8cf64..625180b3 100644 --- a/ide/test/trace/database/ui-worker/ProcedureWorkerEnergyState.test.ts +++ b/ide/test/trace/database/ui-worker/ProcedureWorkerEnergyState.test.ts @@ -131,7 +131,7 @@ describe('ProcedureWorkerEnergyState Test', () => { range: { refresh: '', }, - canvas: '', + canvas: 'bc', context: { font: '14px sans-serif', fillStyle: '#151212', @@ -148,6 +148,10 @@ describe('ProcedureWorkerEnergyState Test', () => { stroke: jest.fn(() => true), closePath: jest.fn(() => true), beginPath: jest.fn(() => true), + arc:jest.fn(() => true), + fill:jest.fn(() => true), + moveTo:jest.fn(() => true), + lineTo:jest.fn(() => true), }, lineColor: '#1a4dff', isHover: '', diff --git a/ide/test/trace/database/ui-worker/ProcedureWorkerLog.test.ts b/ide/test/trace/database/ui-worker/ProcedureWorkerLog.test.ts new file mode 100644 index 00000000..fe3feb8b --- /dev/null +++ b/ide/test/trace/database/ui-worker/ProcedureWorkerLog.test.ts @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// @ts-ignore +import { TraceRow } from '../../../../dist/trace/component/trace/base/TraceRow.js'; + +jest.mock('../../../../dist/trace/database/ui-worker/ProcedureWorker.js', () => { + return {}; +}); +// @ts-ignore +import { LogStruct, LogRender } from '../../../../dist/trace/database/ui-worker/ProcedureWorkerLog.js'; + +describe('ProcedureWorkerLog Test', () => { + let canvas = document.createElement('canvas'); + canvas.width = 12; + canvas.height = 12; + const ctx = canvas.getContext('2d'); + it('ProcedureWorkerLog01', () => { + let data = { + id: 5230, + startTs: 27351020209, + level: 'E', + depth: 3, + tag: 'C01510/BinderInvoker1', + context: '124: SendRequest: handle=0 result = 2', + time: 15020293020884055, + pid: 577, + tid: 967, + processName: 'distributeddata', + dur: 1, + frame: { + x: 1385, + y: 22, + width: 1, + height: 7, + }, + }; + expect(LogStruct.draw(ctx!, data)).toBeUndefined(); + }); + + it('ProcedureWorkerLog02', () => { + let data = { + id: 36, + startTs: 76402676, + level: 'W', + depth: 2, + tag: 'C01300/AbilityManagerService2', + context: '[ability_manager_service.cpp(UpdateCallerInfo:6178)]UpdateCallerInfo.', + time: 15020292748137880, + pid: 559, + tid: 559, + processName: 'foundation', + dur: 1, + frame: { + x: 3, + y: 16, + width: 1, + height: 7, + }, + }; + expect(LogStruct.draw(ctx!, data)).toBeUndefined(); + }); + + it('ProcedureWorkerLog03', () => { + let data = { + id: 3, + startTs: 1, + level: 'I', + depth: 1, + tag: 'C02d0c/Hiprofiler1', + context: 'ParseTimeExtend: update ts with 0 to 337274', + time: 15020292747373852, + pid: 1119, + tid: 1172, + processName: 'hiprofiler_plug', + dur: 1, + frame: { + x: 0, + y: 8, + width: 1, + height: 7, + }, + }; + expect(LogStruct.draw(ctx!, data)).toBeUndefined(); + }); + + it('ProcedureWorkerLog04', () => { + let canvas = document.createElement('canvas') as HTMLCanvasElement; + let context = canvas.getContext('2d'); + let data = { + context: context!, + useCache: true, + type: 'logs', + traceRange: [], + }; + TraceRow.range = jest.fn(() => true); + TraceRow.range!.startNS = jest.fn(() => 0); + TraceRow.range!.endNS = jest.fn(() => 27763331331); + TraceRow.range!.totalNS = jest.fn(() => 27763331331); + let logRender = new LogRender(); + expect(logRender.renderMainThread(data, new TraceRow())).toBeUndefined(); + }); +}); -- Gitee From abf8fe82b6184528ee9b22cd242c79485aa03dea Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:31:57 +0800 Subject: [PATCH 14/18] =?UTF-8?q?=E2=80=99support.parse.hilog=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- trace_streamer/src/base/ts_common.h | 1 + trace_streamer/src/include/BUILD.gn | 31 ++++ .../src/include/dummy/musl/include/elf.h | 0 trace_streamer/src/parser/BUILD.gn | 1 + .../bytrace_parser/bytrace_hilog_parser.cpp | 155 ++++++++++++++++++ .../bytrace_parser/bytrace_hilog_parser.h | 56 +++++++ .../parser/bytrace_parser/bytrace_parser.cpp | 12 +- .../parser/bytrace_parser/bytrace_parser.h | 8 +- trace_streamer/src/parser/common_types.h | 9 + .../parser/htrace_pbreader_parser/BUILD.gn | 2 +- .../trace_streamer_selector.cpp | 16 +- 11 files changed, 282 insertions(+), 9 deletions(-) create mode 100644 trace_streamer/src/include/BUILD.gn create mode 100644 trace_streamer/src/include/dummy/musl/include/elf.h create mode 100644 trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp create mode 100644 trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h diff --git a/trace_streamer/src/base/ts_common.h b/trace_streamer/src/base/ts_common.h index 1464210c..cd0ac26e 100644 --- a/trace_streamer/src/base/ts_common.h +++ b/trace_streamer/src/base/ts_common.h @@ -64,6 +64,7 @@ enum TraceFileType { TRACE_FILETYPE_H_TRACE, TRACE_FILETYPE_SYSEVENT, TRACE_FILETYPE_PERF, + TRACE_FILETYPE_HILOG, TRACE_FILETYPE_UN_KNOW }; diff --git a/trace_streamer/src/include/BUILD.gn b/trace_streamer/src/include/BUILD.gn new file mode 100644 index 00000000..e0981553 --- /dev/null +++ b/trace_streamer/src/include/BUILD.gn @@ -0,0 +1,31 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +ohos_source_set("ibase") { + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + part_name = "${OHOS_PROFILER_PART_NAME}" + sources = [ + "codec_cov.h", + "file.h", + "log.h", + "numerical_to_string.h", + "parting_string.h", + "string_to_numerical.h", + ] + include_dirs = [] + public_deps = [] + deps = [] + if (!is_independent_compile) { + configs = [ "${TS_DIR}/gn:ts_config" ] + } +} diff --git a/trace_streamer/src/include/dummy/musl/include/elf.h b/trace_streamer/src/include/dummy/musl/include/elf.h new file mode 100644 index 00000000..e69de29b diff --git a/trace_streamer/src/parser/BUILD.gn b/trace_streamer/src/parser/BUILD.gn index 05038b77..fb8093ea 100644 --- a/trace_streamer/src/parser/BUILD.gn +++ b/trace_streamer/src/parser/BUILD.gn @@ -19,6 +19,7 @@ ohos_source_set("parser") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "bytrace_parser/bytrace_event_parser.cpp", + "bytrace_parser/bytrace_hilog_parser.cpp", "bytrace_parser/bytrace_parser.cpp", "event_parser_base.cpp", "print_event_parser.cpp", diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp new file mode 100644 index 00000000..5ac5582c --- /dev/null +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "bytrace_hilog_parser.h" +#include "process_filter.h" +#include "stat_filter.h" + +namespace SysTuning { +namespace TraceStreamer { +BytraceHilogParser::BytraceHilogParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters) + : EventParserBase(dataCache, filters) +{ +} + +BytraceHilogParser::~BytraceHilogParser() = default; + +bool BytraceHilogParser::HilogTimeStrToTimestamp(std::string& timeStr, uint64_t& timeStamp) const +{ + const uint64_t S_TO_NS = 1e9; + const uint64_t MS_TO_NS = 1e6; + const uint64_t US_TO_NS = 1e3; + uint64_t sec; + uint64_t usec; + std::string usecStr; + std::smatch matcheLine; + if (std::regex_search(timeStr, matcheLine, std::regex(R"(^\d+\.(\d+)$)"))) { + size_t index = 0; + usecStr = matcheLine[++index].str(); + sscanf_s(timeStr.c_str(), "%lu.%lu", &sec, &usec); + } else if (std::regex_search(timeStr, matcheLine, + std::regex(R"(^(\d{4})?\-?(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.(\d+))$)"))) { + size_t index = 0; + std::string yearStr = matcheLine[++index].str(); + std::string timeStrTmp = matcheLine[++index].str(); + usecStr = matcheLine[++index].str(); + struct tm timeInfo = {0}; + sscanf_s(timeStrTmp.c_str(), "%d-%d %d:%d:%d.%lu", &timeInfo.tm_mon, &timeInfo.tm_mday, &timeInfo.tm_hour, + &timeInfo.tm_min, &timeInfo.tm_sec, &usec); + std::optional optionalYear = base::StrToInt(yearStr); + if (optionalYear.has_value()) { + timeInfo.tm_year = optionalYear.value() - 1900; + } else { + time_t tmNow; + tmNow = time(nullptr); + tm* ptmNow = localtime(&tmNow); + timeInfo.tm_year = ptmNow->tm_year; + } + timeInfo.tm_mon -= 1; + sec = std::mktime(&timeInfo); + } else { + return false; + } + + if (usecStr.length() == 3) { + usec *= MS_TO_NS; + } else if (usecStr.length() == 6) { + usec *= US_TO_NS; + } + + timeStamp = usec + sec * SEC_TO_NS; + return true; +} + +void BytraceHilogParser::ParseHilogDataItem(const std::string& buffer, const uint64_t lineSeq) +{ + std::smatch matcheLine; + if (!std::regex_search(buffer, matcheLine, hilogMatcher_)) { + TS_LOGD("Not support this hilog format (line: %s)", buffer.c_str()); + return; + } + + auto bufLine = std::make_unique(); + bufLine->lineSeq = lineSeq; + + std::string timeStr = matcheLine[HILOG_MATCH_SEQ_TIME].str(); + HilogTimeStrToTimestamp(timeStr, bufLine->timeStamp); + + std::string pidStr = matcheLine[HILOG_MATCH_SEQ_PID].str(); + std::optional optionalPid = base::StrToInt(pidStr); + if (!optionalPid.has_value()) { + TS_LOGD("Illegal pid: %s", pidStr.c_str()); + return; + } + bufLine->pid = optionalPid.value(); + + std::string tidStr = matcheLine[HILOG_MATCH_SEQ_TID].str(); + std::optional optionalTid = base::StrToInt(tidStr); + if (!optionalTid.has_value()) { + TS_LOGD("Illegal tid: %s", tidStr.c_str()); + return; + } + bufLine->tid = optionalTid.value(); + + streamFilters_->processFilter_->GetOrCreateThreadWithPid(bufLine->tid, bufLine->pid); + + bufLine->level = matcheLine[HILOG_MATCH_SEQ_LEVEL].str(); + bufLine->tag = matcheLine[HILOG_MATCH_SEQ_TAG].str(); + bufLine->context = matcheLine[HILOG_MATCH_SEQ_CONTENT].str(); + + FilterHilogData(std::move(bufLine)); + return; +} + +void BytraceHilogParser::FilterHilogData(std::unique_ptr bufLine) +{ + hilogList_.push_back(std::move(bufLine)); + return; +} + +void BytraceHilogParser::FilterAllHilogData() +{ + auto cmp = [](const std::unique_ptr& a, const std::unique_ptr& b) { + return a->timeStamp < b->timeStamp; + }; +#ifdef IS_WASM + std::sort(hilogList_.begin(), hilogList_.end(), cmp); +#else + std::stable_sort(hilogList_.begin(), hilogList_.end(), cmp); +#endif + + for (auto& item : hilogList_) { + HilogLine* hilogData = item.get(); + BeginFilterHilogData(hilogData); + } + + hilogList_.clear(); +} + +void BytraceHilogParser::BeginFilterHilogData(HilogLine* hilogData) +{ + streamFilters_->statFilter_->IncreaseStat(TRACE_HILOG, STAT_EVENT_RECEIVED); + auto curLineSeq = hilogData->lineSeq; + auto newTimeStamp = hilogData->timeStamp; + auto levelData = traceDataCache_->dataDict_.GetStringIndex(hilogData->level); + auto logTag = traceDataCache_->dataDict_.GetStringIndex(hilogData->tag); + auto logData = traceDataCache_->dataDict_.GetStringIndex(hilogData->context); + traceDataCache_->GetHilogData()->AppendNewLogInfo(curLineSeq, newTimeStamp, hilogData->pid, hilogData->tid, + levelData, logTag, logData, hilogData->timeStamp); + return; +} + +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h new file mode 100644 index 00000000..a5021e93 --- /dev/null +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BYTRACE_HILOG_PARSER_H +#define BYTRACE_HILOG_PARSER_H + +#include "common_types.h" +#include "string_help.h" +#include "log.h" +#include "string_to_numerical.h" +#include "parser_base.h" +#include "event_parser_base.h" +#include "trace_data_cache.h" + +namespace SysTuning { +namespace TraceStreamer { +class BytraceHilogParser : public EventParserBase { +public: + BytraceHilogParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters); + ~BytraceHilogParser(); + void ParseHilogDataItem(const std::string& buffer, const uint64_t lineSeq); + void FilterAllHilogData(); + +private: + bool HilogTimeStrToTimestamp(std::string& timeStr, uint64_t& timeStamp) const; + void FilterHilogData(std::unique_ptr bufLine); + void BeginFilterHilogData(HilogLine* hilogData); + + const std::regex hilogMatcher_ = std::regex(R"( *(\w+ )?([\-\d: ]+\.\d+) +(\d+) +(\d+) +([FEWID]) +(.+?): +(.+))"); + enum HILOG_MATCH_SEQ { + HILOG_MATCH_SEQ_ZONE = 1, + HILOG_MATCH_SEQ_TIME = 2, + HILOG_MATCH_SEQ_PID = 3, + HILOG_MATCH_SEQ_TID = 4, + HILOG_MATCH_SEQ_LEVEL = 5, + HILOG_MATCH_SEQ_TAG = 6, + HILOG_MATCH_SEQ_CONTENT = 7, + }; + + std::vector> hilogList_ = {}; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // BYTRACE_HILOG_PARSER_H diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp index 88cb9563..a48c7a12 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp @@ -26,9 +26,11 @@ #include "system_event_measure_filter.h" namespace SysTuning { namespace TraceStreamer { -BytraceParser::BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters) - : ParserBase(filters), +BytraceParser::BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters, TraceFileType fileType) + : fileType_(fileType), + ParserBase(filters), eventParser_(std::make_unique(dataCache, filters)), + hilogParser_(std::make_unique(dataCache, filters)), #ifdef SUPPORTTHREAD dataSegArray_(std::make_unique(MAX_SEG_ARRAY_SIZE)), supportThread_(true) @@ -50,6 +52,7 @@ void BytraceParser::WaitForParserEnd() } eventParser_->FilterAllEvents(); eventParser_->Clear(); + hilogParser_->FilterAllHilogData(); dataSegArray_.reset(); } void BytraceParser::ParseTraceDataSegment(std::unique_ptr bufferStr, size_t size) @@ -106,7 +109,9 @@ void BytraceParser::ParseTraceDataSegment(std::unique_ptr bufferStr, goto NEXT_LINE; } - if (isBytrace_) { + if (fileType_ == TRACE_FILETYPE_HILOG) { + hilogParser_->ParseHilogDataItem(bufferLine, seq_); + } else if (isBytrace_) { if (!traceBegan_) { traceBegan_ = true; } @@ -117,6 +122,7 @@ void BytraceParser::ParseTraceDataSegment(std::unique_ptr bufferStr, NEXT_LINE: packagesBegin = packagesLine + 1; + seq_++; continue; } diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h index 25074773..531b7f44 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h @@ -22,6 +22,7 @@ #include #include "bytrace_event_parser.h" +#include "bytrace_hilog_parser.h" #include "hi_sysevent_measure_filter.h" #include "log.h" #include "parser_base.h" @@ -33,7 +34,9 @@ namespace SysTuning { namespace TraceStreamer { class BytraceParser : public ParserBase { public: - BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters); + BytraceParser(TraceDataCache* dataCache, + const TraceStreamerFilters* filters, + TraceFileType fileType = TRACE_FILETYPE_BY_TRACE); ~BytraceParser(); void ParseTraceDataSegment(std::unique_ptr bufferStr, size_t size) override; @@ -101,6 +104,7 @@ private: using ArgsMap = std::unordered_map; bool isParsingOver_ = false; std::unique_ptr eventParser_; + std::unique_ptr hilogParser_; const std::regex bytraceMatcher_ = std::regex(R"(-(\d+)\s+\(?\s*(\d+|-+)?\)?\s?\[(\d+)\]\s*)" R"([a-zA-Z0-9.]{0,5}\s+(\d+\.\d+):\s+(\S+):)"); @@ -127,6 +131,8 @@ private: bool isFirstLine = true; bool isHtmlTrace_ = false; bool isHtmlTraceContent_ = false; + TraceFileType fileType_ = TRACE_FILETYPE_BY_TRACE; + int64_t seq_ = 1; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/parser/common_types.h b/trace_streamer/src/parser/common_types.h index 24d752a1..c87635b1 100644 --- a/trace_streamer/src/parser/common_types.h +++ b/trace_streamer/src/parser/common_types.h @@ -52,6 +52,15 @@ struct DataSegment { BytraceLine bufLine; std::atomic status{TS_PARSE_STATUS_INIT}; }; +struct HilogLine { + uint64_t lineSeq; + uint64_t timeStamp; + uint32_t pid; + uint32_t tid; + std::string level; + std::string tag; + std::string context; +}; struct HtraceDataSegment { std::shared_ptr seg; uint64_t timeStamp; diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn b/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn index 0c71512f..2710dd4c 100755 --- a/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn +++ b/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn @@ -67,7 +67,7 @@ ohos_source_set("htrace_pbreader_parser_src") { "${THIRD_PARTY}/perf_include/linux", "../hiperf_parser", "../hiperf_parser/include", - "../../../commonlibrary/c_utils/base/include", + "//commonlibrary/c_utils/base/include", "../../include/dummy/musl", ] if (is_mingw || is_mac) { diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp index d2266184..9a9c0cbf 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp @@ -88,6 +88,12 @@ TraceFileType GuessFileType(const uint8_t* data, size_t size) if (std::regex_search(bytraceMode, matcheLine, bytraceMatcher)) { return TRACE_FILETYPE_BY_TRACE; } + + const std::regex hilogMatcher = std::regex(R"( *(\w+ )?([\-\d: ]+\.\d+) +(\d+) +(\d+) +([FEWID]) +(.+?): +(.+))"); + if (std::regex_search(bytraceMode, matcheLine, hilogMatcher)) { + return TRACE_FILETYPE_HILOG; + } + return TRACE_FILETYPE_UN_KNOW; } } // namespace @@ -157,7 +163,7 @@ void TraceStreamerSelector::WaitForParserEnd() if (fileType_ == TRACE_FILETYPE_H_TRACE) { htraceParser_->WaitForParserEnd(); } - if (fileType_ == TRACE_FILETYPE_BY_TRACE) { + if (fileType_ == TRACE_FILETYPE_BY_TRACE || fileType_ == TRACE_FILETYPE_HILOG) { bytraceParser_->WaitForParserEnd(); } if (fileType_ == TRACE_FILETYPE_PERF) { @@ -194,8 +200,9 @@ bool TraceStreamerSelector::ParseTraceDataSegment(std::unique_ptr dat if (fileType_ == TRACE_FILETYPE_H_TRACE || fileType_ == TRACE_FILETYPE_PERF) { htraceParser_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); htraceParser_->EnableFileSeparate(enableFileSeparate_); - } else if (fileType_ == TRACE_FILETYPE_BY_TRACE || fileType_ == TRACE_FILETYPE_SYSEVENT) { - bytraceParser_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); + } else if (fileType_ == TRACE_FILETYPE_BY_TRACE || fileType_ == TRACE_FILETYPE_SYSEVENT || + fileType_ == TRACE_FILETYPE_HILOG) { + bytraceParser_ = std::make_unique(traceDataCache_.get(), streamFilters_.get(), fileType_); bytraceParser_->EnableBytrace(fileType_ == TRACE_FILETYPE_BY_TRACE); } if (fileType_ == TRACE_FILETYPE_UN_KNOW) { @@ -209,7 +216,8 @@ bool TraceStreamerSelector::ParseTraceDataSegment(std::unique_ptr dat } if (fileType_ == TRACE_FILETYPE_H_TRACE) { htraceParser_->ParseTraceDataSegment(std::move(data), size); - } else if (fileType_ == TRACE_FILETYPE_BY_TRACE || fileType_ == TRACE_FILETYPE_SYSEVENT) { + } else if (fileType_ == TRACE_FILETYPE_BY_TRACE || fileType_ == TRACE_FILETYPE_SYSEVENT || + fileType_ == TRACE_FILETYPE_HILOG) { bytraceParser_->ParseTraceDataSegment(std::move(data), size); } else if (fileType_ == TRACE_FILETYPE_PERF) { htraceParser_->StoreTraceDataSegment(std::move(data), size); -- Gitee From f699ff0794e0e783bbc39090109c021857f767a4 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:33:06 +0800 Subject: [PATCH 15/18] =?UTF-8?q?=E2=80=99add.run-metrics.func=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- trace_streamer/src/BUILD.gn | 2 + trace_streamer/src/main.cpp | 115 ++++++- trace_streamer/src/metrics/BUILD.gn | 36 +++ trace_streamer/src/metrics/memAggStrategy.h | 40 +++ trace_streamer/src/metrics/memStrategy.h | 38 +++ trace_streamer/src/metrics/metaDataStrategy.h | 31 ++ trace_streamer/src/metrics/metrics.cpp | 286 ++++++++++++++++++ trace_streamer/src/metrics/metrics.h | 112 +++++++ trace_streamer/src/metrics/sysCallStrategy.h | 33 ++ .../src/metrics/traceStateStrategy.h | 33 ++ .../src/metrics/traceTaskStrategy.h | 33 ++ .../src/trace_data/trace_data_db.cpp | 42 +++ trace_streamer/src/trace_data/trace_data_db.h | 1 + .../trace_streamer_selector.cpp | 4 + .../trace_streamer/trace_streamer_selector.h | 1 + 15 files changed, 806 insertions(+), 1 deletion(-) create mode 100644 trace_streamer/src/metrics/BUILD.gn create mode 100644 trace_streamer/src/metrics/memAggStrategy.h create mode 100644 trace_streamer/src/metrics/memStrategy.h create mode 100644 trace_streamer/src/metrics/metaDataStrategy.h create mode 100644 trace_streamer/src/metrics/metrics.cpp create mode 100644 trace_streamer/src/metrics/metrics.h create mode 100644 trace_streamer/src/metrics/sysCallStrategy.h create mode 100644 trace_streamer/src/metrics/traceStateStrategy.h create mode 100644 trace_streamer/src/metrics/traceTaskStrategy.h diff --git a/trace_streamer/src/BUILD.gn b/trace_streamer/src/BUILD.gn index ab8f4633..943336c8 100644 --- a/trace_streamer/src/BUILD.gn +++ b/trace_streamer/src/BUILD.gn @@ -62,6 +62,7 @@ trace_streamer_include = [ "filter", "table", "trace_data", + "metrics", "include", "rpc", "./", @@ -153,6 +154,7 @@ ohos_source_set("trace_streamer_source") { ":ts_sqlite", "base:base", "filter:filter", + "metrics:metrics_parser", "parser:parser", "parser/hiperf_parser:hiperf_parser", "proto_reader:proto_reader", diff --git a/trace_streamer/src/main.cpp b/trace_streamer/src/main.cpp index 425a3041..94efc2c7 100644 --- a/trace_streamer/src/main.cpp +++ b/trace_streamer/src/main.cpp @@ -28,6 +28,7 @@ #include "filter/slice_filter.h" #include "http_server.h" #include "log.h" +#include "metrics.h" #include "parser/bytrace_parser/bytrace_event_parser.h" #include "parser/bytrace_parser/bytrace_parser.h" #include "parting_string.h" @@ -47,6 +48,62 @@ using namespace SysTuning::base; constexpr size_t G_CHUNK_SIZE = 1024 * 1024; constexpr int G_MIN_PARAM_NUM = 2; constexpr size_t G_FILE_PERMISSION = 664; +const std::string memQuery = + "select max(value) as maxNum, min(value) as minNum, avg(value) as avgNum, filter.name as name, p.name as " + "processName from process_measure left join process_measure_filter as filter on filter.id= filter_id left join " + "process as p on p.id = filter.ipid where filter_id > 0 and filter.name = 'mem.rss.anon' group by filter_id order " + "by avgNum desc;"; +const std::string memTopQuery = + "select max(value) as maxNum, min(value) as minNum, avg(value) as avgNum, f.name as name, p.name as processName " + "from process_measure left join process_measure_filter as f on f.id= filter_id left join process as p on p.id = " + "f.ipid where filter_id > 0 and f.name = 'mem.rss.anon' group by filter_id order by avgNum desc limit 10;"; +const std::string cpuSqlQuery = + "SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu, group_concat(dur, ',') AS dur, " + "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " + "',') AS avg_frequency FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS dur, CAST (MIN(freq) AS INT) AS " + "min_freq, CAST (MAX(freq) AS INT) AS max_freq, CAST ( (SUM(dur * freq) / SUM(dur) ) AS INT) AS avg_frequency from " + "result group by itid, cpu)GROUP BY ipid, itid ORDER BY ipid;"; +const std::string cpuTopTenSqlQuery = + "SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu,group_concat(dur, ',') AS dur, " + "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " + "',') AS avg_frequency, sum(dur * avg_frequency) AS sumNum FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS " + "dur,CAST (MIN(freq) AS INT) AS min_freq, CAST (MAX(freq) AS INT) AS max_freq,CAST ( (SUM(dur * freq) / SUM(dur) ) " + "AS INT) AS avg_frequency from result group by itid, cpu) GROUP BY ipid, itid ORDER BY sumNum DESC LIMIT 10"; +const std::string distributedTermQuery = + "select group_concat(thread.id,',') as threadId, group_concat(thread.name,',') as threadName, " + "group_concat(process.id,',') as processId, group_concat(process.name,',') as processName, " + "group_concat(callstack.name,',') as funName, group_concat(callstack.dur,',') as dur, " + "group_concat(callstack.ts,',') as ts, cast(callstack.chainId as varchar) as chainId, callstack.spanId as spanId, " + "callstack.parentSpanId as parentSpanId, group_concat(callstack.flag,',') as flag, (select value from meta where " + "name='source_name') as trace_name from callstack inner join thread on callstack.callid = thread.id inner join " + "process on process.id = thread.ipid where (callstack.flag='S' or callstack.flag='C') group by " + "callstack.chainId,callstack.spanId,callstack.parentSpanId;"; +const std::string memUnaggQuery = + "select p.name as processName, group_concat(filter.name) as name, cast(group_concat(value) as varchar) as value, " + "cast(group_concat(ts) as varchar) as ts from process_measure m left join process_measure_filter as filter on " + "filter.id= m.filter_id left join process as p on p.id = filter.ipid where filter.name = 'mem.rss.anon' or " + "filter.name = 'mem.rss.file' or filter.name = 'mem.swap' or filter.name = 'oom_score_adj' group by " + "p.name,filter.ipid order by filter.ipid;"; +const std::string metaDataQuery = + "select cast(name as varchar) as name, cast(value as varchar) as valueText from meta UNION select " + "'start_ts',cast(start_ts as varchar) from trace_range UNION select 'end_ts',cast(end_ts as varchar) from " + "trace_range;"; +const std::string sysCallsTopQuery = + "SELECT cpu.tid AS tid, cpu.pid AS pid, callstack.name AS funName, count(callstack.name) AS frequency, " + "min(callstack.dur) AS minDur, max(callstack.dur) AS maxDur, round(avg(callstack.dur)) AS avgDur FROM callstack " + "INNER JOIN (SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu, group_concat(dur, ',') AS dur, " + "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " + "',') AS avg_frequency, sum(dur * avg_frequency) AS sumNum FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS " + "dur, CAST (MIN(freq) AS INT) AS min_freq, CAST (MAX(freq) AS INT) AS max_freq, CAST ( (SUM(dur * freq) / SUM(dur) " + ") AS INT) AS avg_frequency FROM result GROUP BY itid, cpu) GROUP BY ipid, itid ORDER BY sumNum DESC LIMIT 10) AS " + "cpu ON callstack.callid = cpu.tid GROUP BY callstack.name ORDER BY frequency DESC LIMIT 10;"; +const std::string sysCallQuery = + "select count(*) as frequency, min(dur) as minDur, max(dur) as maxDur, avg(dur) as avgDur, name as funName from " + "callstack group by name order by frequency desc limit 100;"; +const std::string traceStateQuery = "select event_name,stat_type,count,source,serverity from stat;"; +const std::string traceTaskName = + "select P.id as id, P.pid as pid, P.name as process_name, group_concat(T.name,',') as thread_name from process as " + "P left join thread as T where P.id = T.ipid group by pid;"; // set version info in meta.cpp please void ExportStatusToLog(const std::string& dbPath, TraceParserStatus status) { @@ -226,6 +283,7 @@ int ExportDatabase(TraceStreamerSelector& ts, const std::string& sqliteFilePath) struct TraceExportOption { std::string traceFilePath; std::string sqliteFilePath; + std::string metricsIndex; std::string sqlOperatorFilePath; bool interactiveState = false; bool exportMetaTable = true; @@ -239,12 +297,51 @@ int CheckFinal(char** argv, TraceExportOption& traceExportOption, HttpOption& ht { if ((traceExportOption.traceFilePath.empty() || (!traceExportOption.interactiveState && traceExportOption.sqliteFilePath.empty())) && - !httpOption.enable && !traceExportOption.separateFile && traceExportOption.sqlOperatorFilePath.empty()) { + !httpOption.enable && !traceExportOption.separateFile && traceExportOption.metricsIndex.empty() && traceExportOption.sqlOperatorFilePath.empty()) { ShowHelpInfo(argv[0]); return 1; } return 0; } +void InitMetricsMap(std::map& metricsMap) +{ + metricsMap.emplace(TRACE_MEM_UNAGG, memUnaggQuery); + metricsMap.emplace(TRACE_MEM, memQuery); + metricsMap.emplace(TRACE_MEM_TOP_TEN, memTopQuery); + metricsMap.emplace(TRACE_METADATA, metaDataQuery); + metricsMap.emplace(SYS_CALLS, sysCallQuery); + metricsMap.emplace(TRACE_STATS, traceStateQuery); + metricsMap.emplace(TRACE_TASK_NAMES, traceTaskName); +} + +const std::string MetricsSqlQuery(const std::string& metrics) +{ + std::map metricsMap; + InitMetricsMap(metricsMap); + auto itor = metricsMap.find(metrics); + if (itor == metricsMap.end()) { + TS_LOGE("metrics name error!!!"); + return ""; + } + return itor->second; +} + +void ParserAndPrintMetrics(TraceStreamerSelector& ts, const std::string& metrics) +{ + std::string result = ts.SearchDatabase(MetricsSqlQuery(metrics)); + if (result == "") { + return; + } + Metrics metricsOperator; + metricsOperator.ParserJson(metrics, result); + for (auto item : metricsOperator.GetMetricsMap()) { + if (item.second == metrics) { + metricsOperator.PrintMetricsResult(item.first); + return; + } + } +} + int CheckArgs(int argc, char** argv, TraceExportOption& traceExportOption, HttpOption& httpOption) { for (int i = 1; i < argc; i++) { @@ -275,6 +372,14 @@ int CheckArgs(int argc, char** argv, TraceExportOption& traceExportOption, HttpO } else if (!strcmp(argv[i], "-nm") || !strcmp(argv[i], "--nometa")) { traceExportOption.exportMetaTable = false; continue; + } else if (!strcmp(argv[i], "-m") || !strcmp(argv[i], "--run-metrics")) { + i++; + if (i == argc) { + ShowHelpInfo(argv[0]); + return 1; + } + traceExportOption.metricsIndex = std::string(argv[i]); + continue; } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--v") || !strcmp(argv[i], "-version") || !strcmp(argv[i], "--version")) { PrintVersion(); @@ -352,6 +457,14 @@ int main(int argc, char** argv) ExportStatusToLog(tsOption.sqliteFilePath, GetAnalysisResult()); } } + if (!tsOption.metricsIndex.empty()) { + MetaData* metaData = ts.GetMetaData(); + metaData->SetOutputFileName("command line mode"); + metaData->SetParserToolVersion(g_traceStreamerVersion.c_str()); + metaData->SetParserToolPublishDateTime(g_traceStreamerPublishVersion.c_str()); + metaData->SetTraceDataSize(g_loadSize); + ParserAndPrintMetrics(ts, tsOption.metricsIndex); + } if (!tsOption.sqlOperatorFilePath.empty()) { ReadSqlFileAndPrintResult(ts, tsOption.sqlOperatorFilePath); } diff --git a/trace_streamer/src/metrics/BUILD.gn b/trace_streamer/src/metrics/BUILD.gn new file mode 100644 index 00000000..5e9248e6 --- /dev/null +++ b/trace_streamer/src/metrics/BUILD.gn @@ -0,0 +1,36 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("../../build/ts.gni") + +ohos_source_set("metrics_parser") { + subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" + part_name = "${OHOS_PROFILER_PART_NAME}" + sources = [ + "memAggStrategy.h", + "memDataStrategy.h", + "memStrategy.h", + "metrics.cpp", + "metrics.h", + "sysCallStrategy.h", + "traceStateStrategy.h", + "traceTaskStrategy.h", + ] + deps = [] + include_dirs = [ + "${SRC}/base", + "${THIRD_PARTY}/bounds_checking_function/include", + "${THIRD_PARTY}/json/single_include/nlohmann", + ] +} diff --git a/trace_streamer/src/metrics/memAggStrategy.h b/trace_streamer/src/metrics/memAggStrategy.h new file mode 100644 index 00000000..2d3916fb --- /dev/null +++ b/trace_streamer/src/metrics/memAggStrategy.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEM_AGG_STRATEGY_H +#define MEM_AGG_STRATEGY_H +#include +#include +#include + +namespace SysTuning { +namespace TraceStreamer { +struct TypeItem { + uint64_t ts; + uint32_t oom_score; + uint32_t value; +}; + +struct ProcessValuesItem { + std::string processName; + TypeItem anonRss; + TypeItem swap; + TypeItem fileRss; + TypeItem anonAndSwap; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // MEM_AGG_STRATEGY_H diff --git a/trace_streamer/src/metrics/memStrategy.h b/trace_streamer/src/metrics/memStrategy.h new file mode 100644 index 00000000..f8ffe633 --- /dev/null +++ b/trace_streamer/src/metrics/memStrategy.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEM_STRATEGY_H +#define MEM_STRATEGY_H +#include +#include +#include + +namespace SysTuning { +namespace TraceStreamer { +struct TypeInfoItem { + uint32_t min; + uint32_t max; + uint32_t avg; +}; + +struct ProcessMetricsItems { + std::string processName; + TypeInfoItem overallCounters; +}; + +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // MEM_STRATEGY_H diff --git a/trace_streamer/src/metrics/metaDataStrategy.h b/trace_streamer/src/metrics/metaDataStrategy.h new file mode 100644 index 00000000..fa0fea42 --- /dev/null +++ b/trace_streamer/src/metrics/metaDataStrategy.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MEM_DATA_STRATEGY_H +#define MEM_DATA_STRATEGY_H +#include +#include +#include + +namespace SysTuning { +namespace TraceStreamer { +struct TraceMetadataItem { + std::string name; + std::string value; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // MEM_DATA_STRATEGY_H diff --git a/trace_streamer/src/metrics/metrics.cpp b/trace_streamer/src/metrics/metrics.cpp new file mode 100644 index 00000000..0a79b0f0 --- /dev/null +++ b/trace_streamer/src/metrics/metrics.cpp @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "metrics.h" +#include +#include "string_help.h" + +namespace SysTuning { +namespace TraceStreamer { +const uint32_t EXTRA_CHAR = 4; +Metrics ::Metrics() +{ + metricsFunction_ = { + {TRACE_MEM, std::bind(&Metrics::InitMemoryStrategy, this, std::placeholders::_1)}, + {TRACE_MEM_TOP_TEN, std::bind(&Metrics::InitMemoryStrategy, this, std::placeholders::_1)}, + {TRACE_MEM_UNAGG, std::bind(&Metrics::InitMemoryUnAggStrategy, this, std::placeholders::_1)}, + {TRACE_TASK_NAMES, std::bind(&Metrics::InitMemoryTaskNameStrategy, this, std::placeholders::_1)}, + {TRACE_STATS, std::bind(&Metrics::InitTraceStatsStrategy, this, std::placeholders::_1)}, + {TRACE_METADATA, std::bind(&Metrics::InitTraceMetaDataStrategy, this, std::placeholders::_1)}, + {SYS_CALLS, std::bind(&Metrics::InitSysCallStrategy, this, std::placeholders::_1)}}; + initMetricsMap_ = { + {METRICS_TRACE_MEM, TRACE_MEM}, + {METRICS_TRACE_MEM_TOP_TEN, TRACE_MEM_TOP_TEN}, + {METRICS_TRACE_MEM_UNAGG, TRACE_MEM_UNAGG}, + {METRICS_TRACE_TASK_NAMES, TRACE_TASK_NAMES}, + {METRICS_TRACE_STATS, TRACE_STATS}, + {METRICS_TRACE_METADATA, TRACE_METADATA}, + {METRICS_SYS_CALLS, SYS_CALLS}, + }; +} + +void Metrics::ParserJson(const std::string& metrics, std::string& result) +{ + result = result.substr(EXTRA_CHAR, result.size()); + auto it = metricsFunction_.find(metrics); + if (it == metricsFunction_.end()) { + TS_LOGE("Not support metrics!"); + return; + } + it->second(result); +} + +void Metrics::InitMemoryStrategy(const std::string& result) +{ + json jMessage = json::parse(result); + for (int i = 0; i < jMessage.at("values").size(); i++) { + TypeInfoItem typeInfoItem; + typeInfoItem.max = jMessage.at("values")[i].at(0); + typeInfoItem.min = jMessage.at("values")[i].at(1); + typeInfoItem.avg = jMessage.at("values")[i].at(2); + ProcessMetricsItems processMetricsItems; + processMetricsItems.overallCounters = typeInfoItem; + processMetricsItems.processName = jMessage.at("values")[i].at(4); + memStrategy_.emplace_back(std::move(processMetricsItems)); + } + return; +} +void Metrics::InitMemoryUnAggStrategy(const std::string& result) +{ + json jMessage = json::parse(result); + for (int i = 0; i < jMessage.at("values").size(); i++) { + ProcessValuesItem processValuesItem; + processValuesItem.processName = jMessage.at("values")[i].at(0); + auto names = SplitStringToVec(jMessage.at("values")[i].at(1), ","); + auto values = SplitStringToVec(jMessage.at("values")[i].at(2), ","); + auto times = SplitStringToVec(jMessage.at("values")[i].at(3), ","); + auto oomScoreValue = 0; + for (auto index = 0; index < names.size(); index++) { + if (names[index] == "oom_score_adj") { + oomScoreValue = atoi(values.at(index).c_str()); + } + TypeItem typeItem; + typeItem.ts = atoll(times.at(index).c_str()); + typeItem.oom_score = oomScoreValue; + typeItem.value = atoi(values.at(index).c_str()); + if (names.at(index) == "mem.rss.anon") { + processValuesItem.anonRss = typeItem; + } else if (names.at(index) == "mem.swap") { + processValuesItem.swap = typeItem; + } else if (names.at(index) == "mem.rss.file") { + processValuesItem.fileRss = typeItem; + } else if (names.at(index) == "oom_score_adj") { + processValuesItem.anonAndSwap = typeItem; + } + } + memAggStrategy_.emplace_back(processValuesItem); + } + return; +} +void Metrics::InitMemoryTaskNameStrategy(const std::string& result) +{ + json jMessage = json::parse(result); + for (int i = 0; i < jMessage.at("values").size(); i++) { + TaskProcessItem taskProcessItem; + taskProcessItem.pid = jMessage.at("values")[i].at(1); + if (jMessage.at("values")[i].at(2).is_null()) { + taskProcessItem.processName = ""; + } else { + taskProcessItem.processName = jMessage.at("values")[i].at(2); + } + taskProcessItem.threadName = SplitStringToVec(jMessage.at("values")[i].at(3), ","); + taskNameStrategy_.emplace_back(taskProcessItem); + } + return; +} +void Metrics::InitTraceStatsStrategy(const std::string& result) +{ + json jMessage = json::parse(result); + for (int i = 0; i < jMessage.at("values").size(); i++) { + StatItem statItem; + statItem.name = jMessage.at("values")[i].at(0); + statItem.count = jMessage.at("values")[i].at(2); + statItem.source = jMessage.at("values")[i].at(3); + statItem.severity = jMessage.at("values")[i].at(4); + statStrategy_.emplace_back(statItem); + } + return; +} +void Metrics::InitTraceMetaDataStrategy(const std::string& result) +{ + json jMessage = json::parse(result); + for (int i = 0; i < jMessage.at("values").size(); i++) { + TraceMetadataItem traceMetadataItem; + traceMetadataItem.name = jMessage.at("values")[i].at(0); + traceMetadataItem.value = jMessage.at("values")[i].at(1); + metaDataStrategy_.emplace_back(traceMetadataItem); + } + return; +} +void Metrics::InitSysCallStrategy(const std::string& result) +{ + json jMessage = json::parse(result); + for (int i = 0; i < jMessage.at("values").size(); i++) { + FunctionItem functionItem; + functionItem.functionName = jMessage.at("values")[i].at(4); + functionItem.durMax = jMessage.at("values")[i].at(2); + functionItem.durMin = jMessage.at("values")[i].at(1); + functionItem.durAvg = jMessage.at("values")[i].at(3); + sysCallStrategy_.emplace_back(functionItem); + } + return; +} +void Metrics::PrintMetricsResult(uint32_t metricsIndex) +{ + std::string res = "\r\n"; + std::string metricsName = ""; + std::string repeateValue = " "; + switch (metricsIndex) { + case METRICS_TRACE_MEM: + metricsName = TRACE_MEM; + for (auto item : memStrategy_) { + repeateValue += PROCESS_METRICES + PROCESS_NAME + "\"" + item.processName + "\"," + OVERALL_COUNTERS + + ANON_RSS + MIN + std::to_string(item.overallCounters.min) + "," + MAX + + std::to_string(item.overallCounters.max) + "," + AVG + + std::to_string(item.overallCounters.avg) + "}}},"; + } + repeateValue.pop_back(); + break; + case METRICS_TRACE_MEM_TOP_TEN: + metricsName = TRACE_MEM_TOP_TEN; + for (auto item : memStrategy_) { + repeateValue += PROCESS_METRICES + PROCESS_NAME + "\"" + item.processName + "\"," + OVERALL_COUNTERS + + ANON_RSS + MIN + std::to_string(item.overallCounters.min) + "," + MAX + + std::to_string(item.overallCounters.max) + "," + AVG + + std::to_string(item.overallCounters.avg) + "}}},"; + } + repeateValue.pop_back(); + break; + case METRICS_TRACE_MEM_UNAGG: + metricsName = TRACE_MEM_UNAGG; + for (auto item : memAggStrategy_) { + repeateValue += + PROCESS_VALUES + PROCESS_NAME + "\"" + item.processName + "\"," + ANON_RSS + TS + + std::to_string(item.anonRss.ts) + "," + OOM_SCORE + std::to_string(item.anonRss.oom_score) + "," + + VALUE + std::to_string(item.anonRss.value) + "}," + FILE_RSS + TS + + std::to_string(item.fileRss.ts) + "," + OOM_SCORE + std::to_string(item.fileRss.oom_score) + "," + + VALUE + std::to_string(item.fileRss.value) + "}," + SWAP + TS + std::to_string(item.swap.ts) + "," + + OOM_SCORE + std::to_string(item.swap.oom_score) + "," + VALUE + std::to_string(item.swap.value) + + "}},"; + } + repeateValue.pop_back(); + break; + case METRICS_TRACE_TASK_NAMES: + metricsName = TRACE_TASK_NAMES; + for (auto item : taskNameStrategy_) { + repeateValue += + PROCESS + PID + std::to_string(item.pid) + "," + PROCESS_NAME + "\"" + item.processName + "\","; + for (auto threadItem : item.threadName) { + repeateValue += THREAD_NAME + "\"" + threadItem + ","; + } + repeateValue.pop_back(); + repeateValue += "},"; + } + repeateValue.pop_back(); + break; + case METRICS_TRACE_STATS: + metricsName = TRACE_STATS; + for (auto item : statStrategy_) { + repeateValue += STAT + NAME + "\"" + item.name + "\"," + COUNT + std::to_string(item.count) + "," + + SOURCE + "\"" + item.source + "\"," + SEVERITY + "\"" + item.severity + "\"" + "},"; + } + repeateValue.pop_back(); + break; + case METRICS_TRACE_METADATA: + metricsName = TRACE_METADATA; + for (auto item : metaDataStrategy_) { + repeateValue += + TRACE_METADATA + ":{" + NAME + "\"" + item.name + "\"," + VALUE + "\"" + item.value + "\"" + "},"; + } + repeateValue.pop_back(); + break; + case METRICS_SYS_CALLS: + metricsName = SYS_CALLS; + for (auto item : sysCallStrategy_) { + repeateValue += FUNCTION + FUNCTION_NAME + "\"" + item.functionName + "\"," + DUR_MAX + + std::to_string(item.durMax) + "," + DUR_MIN + std::to_string(item.durMin) + "\"," + + DUR_AVG + "\"" + std::to_string(item.durAvg) + "\"" + "},"; + } + repeateValue.pop_back(); + break; + default: + break; + } + res += metricsName + ": {" + repeateValue + "}"; + res = JsonFormat(res) + "\r\n"; + std::regex strRegex(","); + auto str = std::regex_replace(res, strRegex, ""); + printf("%s", str.c_str()); + return; +} +std::string Metrics::GetLevelSpace(int level) +{ + std::string levelStr = ""; + for (int i = 0; i < level; i++) { + levelStr += " "; + } + return levelStr; +} +std::string Metrics::JsonFormat(std::string json) +{ + std::string result = ""; + int level = 0; + for (std::string::size_type index = 0; index < json.size(); index++) { + char value = json[index]; + if (level > 0 && '\n' == json[json.size() - 1]) { + result += GetLevelSpace(level); + } + switch (value) { + case '{': + case '[': + result = result + value + "\n"; + level++; + result += GetLevelSpace(level); + break; + case ',': + result = result + value + "\n"; + result += GetLevelSpace(level); + break; + case '}': + case ']': + result += "\n"; + level--; + result += GetLevelSpace(level); + result += value; + break; + default: + result += value; + break; + } + } + return result; +} +} // namespace TraceStreamer +} // namespace SysTuning diff --git a/trace_streamer/src/metrics/metrics.h b/trace_streamer/src/metrics/metrics.h new file mode 100644 index 00000000..90f1eb71 --- /dev/null +++ b/trace_streamer/src/metrics/metrics.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef METRICS_H +#define METRICS_H +#include +#include +#include +#include +#include "json.hpp" +#include "log.h" +#include "memAggStrategy.h" +#include "memStrategy.h" +#include "metaDataStrategy.h" +#include "sysCallStrategy.h" +#include "traceStateStrategy.h" +#include "traceTaskStrategy.h" + +enum METRICS_INDEX { + METRICS_TRACE_MEM, + METRICS_TRACE_MEM_TOP_TEN, + METRICS_TRACE_MEM_UNAGG, + METRICS_TRACE_TASK_NAMES, + METRICS_TRACE_STATS, + METRICS_TRACE_METADATA, + METRICS_SYS_CALLS, +}; + +const std::string TRACE_MEM = "trace_mem"; +const std::string TRACE_MEM_TOP_TEN = "trace_mem_top10"; +const std::string TRACE_MEM_UNAGG = "trace_mem_unagg"; +const std::string TRACE_TASK_NAMES = "trace_task_names"; +const std::string TRACE_STATS = "trace_stats"; +const std::string TRACE_METADATA = "trace_metadata"; +const std::string SYS_CALLS = "sys_calls"; +const std::string PROCESS_METRICES = "process_metrics:{"; +const std::string PROCESS_NAME = "process_name:"; +const std::string OVERALL_COUNTERS = "overall_counters:{"; +const std::string ANON_RSS = "anon_rss:{"; +const std::string MIN = "min:"; +const std::string MAX = "max:"; +const std::string AVG = "avg:"; +const std::string PROCESS_VALUES = "process_value:{"; +const std::string TS = "ts:"; +const std::string OOM_SCORE = "oom_score:"; +const std::string VALUE = "value:"; +const std::string FILE_RSS = "file_rss:{"; +const std::string SWAP = "swap:{"; +const std::string ANON_AND_SWAP = "anon_and_swap:{"; +const std::string PROCESS = "process:{"; +const std::string PID = "pid:"; +const std::string THREAD_NAME = "thread_name:"; +const std::string STAT = "stat:{"; +const std::string NAME = "name:"; +const std::string COUNT = "count:"; +const std::string SOURCE = "source:"; +const std::string SEVERITY = "severity:"; +const std::string FUNCTION = "function:{"; +const std::string FUNCTION_NAME = "function_name:"; +const std::string DUR_MAX = "dur_max:"; +const std::string DUR_MIN = "dur_min:"; +const std::string DUR_AVG = "dr_avg:"; + +namespace SysTuning { +namespace TraceStreamer { +using json = nlohmann::json; +class Metrics { +public: + Metrics(); + ~Metrics() {} + void ParserJson(const std::string& metrics, std::string& result); + void PrintMetricsResult(uint32_t metricsIndex); + auto GetMetricsMap() + { + return initMetricsMap_; + } + +private: + using FuncCall = std::function; + std::map metricsFunction_ = {}; + void InitMemoryStrategy(const std::string& result); + void InitMemoryUnAggStrategy(const std::string& result); + void InitMemoryTaskNameStrategy(const std::string& result); + void InitTraceStatsStrategy(const std::string& result); + void InitTraceMetaDataStrategy(const std::string& result); + void InitSysCallStrategy(const std::string& result); + std::string JsonFormat(std::string json); + std::string GetLevelSpace(int level); + std::vector memStrategy_ = {}; + std::vector memAggStrategy_ = {}; + std::vector taskNameStrategy_ = {}; + std::vector statStrategy_ = {}; + std::vector metaDataStrategy_ = {}; + std::vector sysCallStrategy_ = {}; + std::map initMetricsMap_ = {}; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // METRICS_H \ No newline at end of file diff --git a/trace_streamer/src/metrics/sysCallStrategy.h b/trace_streamer/src/metrics/sysCallStrategy.h new file mode 100644 index 00000000..363d8d63 --- /dev/null +++ b/trace_streamer/src/metrics/sysCallStrategy.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SYS_CALL_STRATEGY_H +#define SYS_CALL_STRATEGY_H +#include +#include +#include + +namespace SysTuning { +namespace TraceStreamer { +struct FunctionItem { + std::string functionName; + uint32_t durMax; + int32_t durMin; + uint32_t durAvg; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // SYS_CALL_STRATEGY_H diff --git a/trace_streamer/src/metrics/traceStateStrategy.h b/trace_streamer/src/metrics/traceStateStrategy.h new file mode 100644 index 00000000..72ca7662 --- /dev/null +++ b/trace_streamer/src/metrics/traceStateStrategy.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TRACE_STATE_STRATEGY_H +#define TRACE_STATE_STRATEGY_H +#include +#include +#include + +namespace SysTuning { +namespace TraceStreamer { +struct StatItem { + std::string name; + uint32_t count; + std::string source; + std::string severity; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // TRACE_STATE_STRATEGY_H diff --git a/trace_streamer/src/metrics/traceTaskStrategy.h b/trace_streamer/src/metrics/traceTaskStrategy.h new file mode 100644 index 00000000..78a2376c --- /dev/null +++ b/trace_streamer/src/metrics/traceTaskStrategy.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef TRACE_TASK_STRATEGY_H +#define TRACE_TASK_STRATEGY_H +#include +#include +#include +#include + +namespace SysTuning { +namespace TraceStreamer { +struct TaskProcessItem { + uint32_t pid; + std::string processName; + std::vector threadName; +}; +} // namespace TraceStreamer +} // namespace SysTuning + +#endif // TRACE_TASK_STRATEGY_H diff --git a/trace_streamer/src/trace_data/trace_data_db.cpp b/trace_streamer/src/trace_data/trace_data_db.cpp index 82799b58..31da8362 100644 --- a/trace_streamer/src/trace_data/trace_data_db.cpp +++ b/trace_streamer/src/trace_data/trace_data_db.cpp @@ -320,6 +320,48 @@ int32_t TraceDataDB::OperateDatabase(const std::string& sql) } return ret; } + +std::string TraceDataDB::SearchDatabase(const std::string& sql) +{ + Prepare(); + sqlite3_stmt* stmt = nullptr; + int32_t ret = sqlite3_prepare_v2(db_, sql.c_str(), static_cast(sql.size()), &stmt, nullptr); + if (ret != SQLITE_OK) { + TS_LOGE("sqlite3_prepare_v2(%s) failed: %d:%s", sql.c_str(), ret, sqlite3_errmsg(db_)); + return ""; + } + + std::string res = "ok\r\n"; + int32_t colCount = sqlite3_column_count(stmt); + if (colCount == 0) { + return ""; + } + res += "{\"columns\":["; + for (int32_t i = 0; i < colCount; i++) { + res += "\""; + res += sqlite3_column_name(stmt, i); + res += "\","; + } + res.pop_back(); + res += "],\"values\":["; + bool hasRow = false; + constexpr int32_t defaultLenRowString = 1024; + std::string row; + row.reserve(defaultLenRowString); + while (sqlite3_step(stmt) == SQLITE_ROW) { + hasRow = true; + GetRowString(stmt, colCount, row); + res += row + ","; + } + if (hasRow) { + res.pop_back(); + } + res += "]}\r\n"; + + sqlite3_finalize(stmt); + return res; +} + int32_t TraceDataDB::SearchDatabase(const std::string& sql, ResultCallBack resultCallBack) { Prepare(); diff --git a/trace_streamer/src/trace_data/trace_data_db.h b/trace_streamer/src/trace_data/trace_data_db.h index cc5a9fb7..a6811567 100644 --- a/trace_streamer/src/trace_data/trace_data_db.h +++ b/trace_streamer/src/trace_data/trace_data_db.h @@ -54,6 +54,7 @@ public: int32_t SearchDatabase(const std::string& sql, ResultCallBack resultCallBack); int32_t SearchDatabase(const std::string& sql, uint8_t* out, int32_t outLen); int32_t SearchDatabase(const std::string& sql, bool print); + std::string SearchDatabase(const std::string& sql); void SetCancel(bool cancel); void AppendNewTable(std::string tableName); void EnableMetaTable(bool enabled); diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp index 9a9c0cbf..4a0ff1db 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp @@ -282,6 +282,10 @@ int32_t TraceStreamerSelector::SearchDatabase(const std::string& sql, bool print { return traceDataCache_->SearchDatabase(sql, printf); } +std::string TraceStreamerSelector::SearchDatabase(const std::string& sql) +{ + return traceDataCache_->SearchDatabase(sql); +} int32_t TraceStreamerSelector::UpdateTraceRangeTime(uint8_t* data, int32_t len) { std::string traceRangeStr; diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.h b/trace_streamer/src/trace_streamer/trace_streamer_selector.h index 5f7bd52b..afb380e4 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.h +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.h @@ -39,6 +39,7 @@ public: int32_t SearchDatabase(const std::string& sql, TraceDataDB::ResultCallBack resultCallBack); int32_t SearchDatabase(const std::string& sql, uint8_t* out, int32_t outLen); int32_t SearchDatabase(const std::string& sql, bool printf); + std::string SearchDatabase(const std::string& sql); int32_t UpdateTraceRangeTime(uint8_t* data, int32_t len); void WaitForParserEnd(); void Clear(); -- Gitee From b2fd82fd578c508340966a8a91eddef06d49f818 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:34:42 +0800 Subject: [PATCH 16/18] =?UTF-8?q?=E2=80=99fix.hilog.error.and.metrics.erro?= =?UTF-8?q?r.and.code.style=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- trace_streamer/build.sh | 12 +- trace_streamer/build/protoc.sh | 15 +- trace_streamer/build/protoc_w.sh | 8 +- trace_streamer/build_operator.sh | 15 +- trace_streamer/format-code.sh | 2 - trace_streamer/src/BUILD.gn | 3 +- trace_streamer/src/base/string_help.cpp | 13 + trace_streamer/src/base/string_help.h | 1 + trace_streamer/src/base/ts_common.h | 56 +++ .../src/filter/native_hook_filter.cpp | 18 +- .../src/filter/native_hook_filter.h | 3 +- .../src/filter/perf_data_filter.cpp | 44 ++- trace_streamer/src/filter/perf_data_filter.h | 12 +- .../src/filter/task_pool_filter.cpp | 1 - trace_streamer/src/include/BUILD.gn | 31 -- .../src/include/dummy/musl/include/elf.h | 0 trace_streamer/src/main.cpp | 114 ++----- trace_streamer/src/metrics/metrics.cpp | 25 +- trace_streamer/src/metrics/metrics.h | 5 +- .../bytrace_parser/bytrace_hilog_parser.cpp | 38 ++- .../parser/hiperf_parser/perf_data_parser.cpp | 69 ++-- .../parser/hiperf_parser/perf_data_parser.h | 21 +- .../parser/htrace_pbreader_parser/BUILD.gn | 5 +- .../src/proto_reader/proto_reader.cpp | 4 +- trace_streamer/src/rpc/rpc_server.cpp | 17 + trace_streamer/src/rpc/rpc_server.h | 1 + trace_streamer/src/rpc/wasm_func.cpp | 7 + trace_streamer/src/table/base/args_table.cpp | 30 +- .../src/table/base/data_dict_table.cpp | 24 +- .../src/table/base/data_type_table.cpp | 26 +- .../table/base/datasource_clockid_table.cpp | 10 +- .../src/table/base/device_info_table.cpp | 10 +- trace_streamer/src/table/base/meta_table.cpp | 8 +- trace_streamer/src/table/base/range_table.cpp | 8 +- trace_streamer/src/table/base/span_join.cpp | 14 +- trace_streamer/src/table/base/span_join.h | 4 +- trace_streamer/src/table/base/stat_table.cpp | 14 +- .../src/table/base/symbols_table.cpp | 26 +- .../src/table/base/trace_config_table.cpp | 12 +- .../table/ebpf/bio_latency_sample_table.cpp | 46 +-- .../src/table/ebpf/ebpf_callstack_table.cpp | 32 +- .../src/table/ebpf/ebpf_elf_symbol_table.cpp | 22 +- .../src/table/ebpf/ebpf_elf_table.cpp | 30 +- .../table/ebpf/ebpf_process_maps_table.cpp | 26 +- .../table/ebpf/file_system_sample_table.cpp | 56 +-- .../src/table/ftrace/animation_table.cpp | 12 +- .../src/table/ftrace/app_startup_table.cpp | 20 +- .../src/table/ftrace/callstack_table.cpp | 58 ++-- .../table/ftrace/clk_event_filter_table.cpp | 12 +- .../table/ftrace/clock_event_filter_table.cpp | 12 +- .../src/table/ftrace/clock_snapshot_table.cpp | 12 +- .../table/ftrace/cpu_measure_filter_table.cpp | 34 +- .../src/table/ftrace/dynamic_frame_table.cpp | 20 +- .../src/table/ftrace/filter_table.cpp | 28 +- .../src/table/ftrace/frame_maps_table.cpp | 30 +- .../src/table/ftrace/frame_slice_table.cpp | 81 +++-- .../src/table/ftrace/gpu_slice_table.cpp | 30 +- .../src/table/ftrace/instants_table.cpp | 50 +-- trace_streamer/src/table/ftrace/irq_table.cpp | 50 +-- .../src/table/ftrace/measure_filter_table.cpp | 12 +- .../src/table/ftrace/measure_table.cpp | 34 +- .../src/table/ftrace/process_filter_table.cpp | 12 +- .../ftrace/process_measure_filter_table.cpp | 32 +- .../src/table/ftrace/process_table.cpp | 58 ++-- trace_streamer/src/table/ftrace/raw_table.cpp | 38 +-- .../src/table/ftrace/sched_slice_table.cpp | 70 ++-- .../ftrace/so_static_initalization_table.cpp | 20 +- .../src/table/ftrace/system_call_table.cpp | 14 +- .../ftrace/system_event_filter_table.cpp | 30 +- .../src/table/ftrace/task_pool_table.cpp | 28 +- .../src/table/ftrace/thread_filter_table.cpp | 12 +- .../src/table/ftrace/thread_state_table.cpp | 62 ++-- .../src/table/ftrace/thread_table.cpp | 75 +++-- .../table/hi_sysevent/device_state_table.cpp | 46 +-- .../hi_sysevent/sysevent_measure_table.cpp | 20 +- .../table/hiperf/perf_call_chain_table.cpp | 52 +-- .../src/table/hiperf/perf_files_table.cpp | 32 +- .../src/table/hiperf/perf_report_table.cpp | 10 +- .../src/table/hiperf/perf_sample_table.cpp | 46 +-- .../src/table/hiperf/perf_thread_table.cpp | 32 +- .../src/table/js_memory/appname_table.cpp | 12 +- .../src/table/js_memory/js_config_table.cpp | 26 +- .../js_memory/js_cpu_profiler_node_table.cpp | 23 +- .../js_cpu_profiler_sample_table.cpp | 14 +- .../table/js_memory/js_heap_edges_table.cpp | 18 +- .../table/js_memory/js_heap_files_table.cpp | 14 +- .../table/js_memory/js_heap_info_table.cpp | 14 +- .../js_memory/js_heap_location_table.cpp | 14 +- .../table/js_memory/js_heap_nodes_table.cpp | 32 +- .../table/js_memory/js_heap_sample_table.cpp | 10 +- .../table/js_memory/js_heap_string_table.cpp | 10 +- .../js_heap_trace_function_info_table.cpp | 20 +- .../js_memory/js_heap_trace_node_table.cpp | 16 +- .../table/monitor/cpu_usage_info_table.cpp | 16 +- .../src/table/monitor/disk_io_table.cpp | 24 +- .../src/table/monitor/hidump_table.cpp | 10 +- .../src/table/monitor/live_process_table.cpp | 30 +- .../src/table/monitor/log_table.cpp | 20 +- .../src/table/monitor/memory_ashmem_table.cpp | 30 +- .../src/table/monitor/memory_dma_table.cpp | 26 +- .../monitor/memory_process_gpu_table.cpp | 20 +- .../table/monitor/memory_window_gpu_table.cpp | 32 +- .../src/table/monitor/network_table.cpp | 26 +- .../monitor/paged_memory_sample_table.cpp | 24 +- .../src/table/monitor/smaps_table.cpp | 42 +-- .../native_hook/native_hook_frame_table.cpp | 44 +-- .../native_hook_statistic_table.cpp | 62 ++-- .../table/native_hook/native_hook_table.cpp | 71 ++-- .../src/trace_data/trace_data_db.cpp | 10 +- trace_streamer/src/trace_data/trace_data_db.h | 2 +- .../src/trace_data/trace_stdtype.cpp | 137 ++++---- trace_streamer/src/trace_data/trace_stdtype.h | 65 ++-- .../trace_streamer_selector.cpp | 26 +- .../trace_streamer/trace_streamer_selector.h | 5 +- trace_streamer/src/version.cpp | 4 +- trace_streamer/test/BUILD.gn | 1 + .../test/unittest/animation_filter_test.cpp | 5 - .../test/unittest/hisys_event_parser_test.cpp | 22 +- .../test/unittest/native_hook_parser_test.cpp | 2 +- trace_streamer/test/unittest/table_test.cpp | 318 +++++++++--------- .../test/unittest/task_pool_filter_test.cpp | 217 +++++------- 121 files changed, 1857 insertions(+), 1779 deletions(-) delete mode 100644 trace_streamer/src/include/BUILD.gn delete mode 100644 trace_streamer/src/include/dummy/musl/include/elf.h diff --git a/trace_streamer/build.sh b/trace_streamer/build.sh index 1a2737ac..b4af8bb1 100755 --- a/trace_streamer/build.sh +++ b/trace_streamer/build.sh @@ -43,15 +43,15 @@ if { [ "$1" == "dubaisdk" ] || [ "$1" == "sdkdemo" ] || [ "$1" == "wasm" ] || [ if [[ $PARAMS == *"debug"* ]]; then TARGET_DIR=$1"_debug" fi - if [ ! -f "out/$TARGET_DIR/clang_x64/developtools/smartperf_host/protoc" ] && [ "$1" != "protoc" ];then + if [ ! -f "out/$TARGET_DIR/protoc" ] && [ "$1" != "protoc" ];then ./build.sh protoc - mkdir -p out/$TARGET_DIR/clang_x64/developtools/smartperf_host - cp out/$target_os/clang_x64/developtools/smartperf_host/protoc out/$TARGET_DIR/clang_x64/developtools/smartperf_host/protoc + mkdir -p out/$TARGET_DIR + cp out/$target_os/protoc out/$TARGET_DIR/protoc fi - if [ ! -f "out/$TARGET_DIR/clang_x64/developtools/smartperf_host/protoreader_plugin" ] && [ "$1" != "spb" ] && [ -f "out/$TARGET_DIR/clang_x64/developtools/smartperf_host/protoc" ];then + if [ ! -f "out/$TARGET_DIR/protoreader_plugin" ] && [ "$1" != "spb" ] && [ -f "out/$TARGET_DIR/protoc" ];then ./build.sh spb - mkdir -p out/$TARGET_DIR/clang_x64/developtools/smartperf_host - cp out/$target_os/clang_x64/developtools/smartperf_host/protoreader_plugin out/$TARGET_DIR/clang_x64/developtools/smartperf_host/protoreader_plugin + mkdir -p out/$TARGET_DIR + cp out/$target_os/protoreader_plugin out/$TARGET_DIR/protoreader_plugin fi fi if [ $target_os == "windows" ];then diff --git a/trace_streamer/build/protoc.sh b/trace_streamer/build/protoc.sh index 7191cbd4..21b55070 100755 --- a/trace_streamer/build/protoc.sh +++ b/trace_streamer/build/protoc.sh @@ -14,14 +14,15 @@ set -e THIS_DIR=$(dirname ${BASH_SOURCE[0]}) -PROJECT_TOP=$(realpath $THIS_DIR/../../../..) -TAIL_DIR="thirdparty/protobuf" -SUBSYS_DIR="developtools/smartperf_host" -if [[ "$2" == *"developtools"* ]]; then - TAIL_DIR="." - SUBSYS_DIR="." - PROJECT_TOP=$(realpath $THIS_DIR/..) +PROJECT_TOP=$(realpath $THIS_DIR/..) +TAIL_DIR="." +SUBSYS_DIR="." +if [[ "$3" == *"developtools"* ]]; then + TAIL_DIR="thirdparty/protobuf" + SUBSYS_DIR="developtools/smartperf_host" + PROJECT_TOP=$(realpath $THIS_DIR/../../../..) fi + OHOS_X64_OUT=$PROJECT_TOP/$2/ LIBCXX_X64_OUT=$PROJECT_TOP/$1/ndk/libcxx/linux_x86_64 SUBSYS_X64_OUT=$PROJECT_TOP/$2/$TAIL_DIR diff --git a/trace_streamer/build/protoc_w.sh b/trace_streamer/build/protoc_w.sh index da97a2a1..adcc7bbc 100644 --- a/trace_streamer/build/protoc_w.sh +++ b/trace_streamer/build/protoc_w.sh @@ -18,11 +18,11 @@ import sys import platform THIS_DIR = os.path.dirname(os.path.abspath(__file__)) -PROJECT_TOP = os.path.realpath(os.path.join(THIS_DIR, "../../..")) -TAIL_DIR = "developtools/profiler" +PROJECT_TOP = os.path.realpath(os.path.join(THIS_DIR, "..")) +TAIL_DIR = "." -if "developtools" in sys.argv[2]: - TAIL_DIR = "." +if "developtools" in sys.argv[3]: + TAIL_DIR = "developtools/profiler" PROJECT_TOP = os.path.realpath(os.path.join(THIS_DIR, "..")) OHOS_X64_OUT = os.path.join(PROJECT_TOP, sys.argv[2]) diff --git a/trace_streamer/build_operator.sh b/trace_streamer/build_operator.sh index e26763b9..27680350 100755 --- a/trace_streamer/build_operator.sh +++ b/trace_streamer/build_operator.sh @@ -13,10 +13,7 @@ # limitations under the License. set -e ext="" -clang_dir="clang_x64" target_dir="linux" -subsys_name="developtools" -part_name="smartperf_host" is_debug="$1" target="$2" target_os="$3" @@ -75,14 +72,12 @@ fi echo "target_dir:" $target_dir echo "target:" $target +out_dir=out/$target_dir$ext if [ "$is_clean" == "true" ];then - prebuilts/$gn_path/$gn gen out/"$target_dir""$ext"/$clang_dir/$subsys_name/$part_name --clean - prebuilts/$gn_path/$ninja -C out/"$target_dir""$ext"/$clang_dir/$subsys_name/$part_name -t clean + prebuilts/$gn_path/$gn gen $out_dir --clean + prebuilts/$gn_path/$ninja -C $out_dir -t clean else - prebuilts/$gn_path/$gn gen out/"$target_dir""$ext"/$clang_dir/$subsys_name/$part_name --args='is_debug='"$is_debug"' target="'"$target"'" target_os="'"$target_os"'" is_independent_compile=true' + prebuilts/$gn_path/$gn gen $out_dir --args='is_debug='"$is_debug"' target="'"$target"'" target_os="'"$target_os"'" is_independent_compile=true' echo "begin to build ..." - prebuilts/$gn_path/$ninja -C out/"$target_dir""$ext"/$clang_dir/$subsys_name/$part_name - if [ "$target" != "protoc" ] && [ "$target" != "spb" ];then - cp -r out/"$target_dir""$ext"/$clang_dir/$subsys_name/$part_name/* out/"$target_dir""$ext"/ - fi + prebuilts/$gn_path/$ninja -C $out_dir fi diff --git a/trace_streamer/format-code.sh b/trace_streamer/format-code.sh index 8e86f549..45c761f7 100755 --- a/trace_streamer/format-code.sh +++ b/trace_streamer/format-code.sh @@ -34,14 +34,12 @@ FORMAT_DIR_LIST=( ) echo "formatting code ..." for d in ${FORMAT_DIR_LIST[@]}; do - echo $d for f in $(find $d -type f -not -name '*sql.c' -regex '.*\.\(cpp\|hpp\|c\|h\)'); do dos2unix $f chmod -x $f clang-format --verbose -i $f done for f in $(find $d -type f -not -name '*sql.c' -regex '.*\.\(gn\|gni\)'); do - echo $f ./prebuilts/$target_os/gn format $f done done diff --git a/trace_streamer/src/BUILD.gn b/trace_streamer/src/BUILD.gn index 943336c8..b91342a0 100644 --- a/trace_streamer/src/BUILD.gn +++ b/trace_streamer/src/BUILD.gn @@ -87,8 +87,7 @@ trace_streamer_include = [ "${THIRD_PARTY}/perf_include/libbpf", "${THIRD_PARTY}/googletest/googletest/include", "${COMMON_LIBRARY}/c_utils/base/include", - "//prebuilts/clang/ohos/darwin-arm64/llvm/include/c++/v1", - "include/dummy/musl", + "${THIRD_PARTY}/sqlite", ] ohos_source_set("trace_streamer_source") { diff --git a/trace_streamer/src/base/string_help.cpp b/trace_streamer/src/base/string_help.cpp index 4eae4073..74b28c13 100644 --- a/trace_streamer/src/base/string_help.cpp +++ b/trace_streamer/src/base/string_help.cpp @@ -61,3 +61,16 @@ std::vector SplitStringToVec(const std::string& str, const std::str return result; } + +std::string FormatString(const char* p) +{ + std::string str = "\""; + for (const char* c = p; *c != 0; c++) { + if (*c == '\\' || *c == '\"') { + str += "\\"; + } + str += *c; + } + str += "\""; + return str; +} diff --git a/trace_streamer/src/base/string_help.h b/trace_streamer/src/base/string_help.h index 5745c83f..1459e354 100644 --- a/trace_streamer/src/base/string_help.h +++ b/trace_streamer/src/base/string_help.h @@ -24,5 +24,6 @@ char* GetDemangleSymbolIndex(const char* mangled); std::vector SplitStringToVec(const std::string& str, const std::string& pat); bool StartWith(const std::string& str, const std::string& res); bool EndWith(const std::string& str, const std::string& res); +std::string FormatString(const char* p); #endif // SRC_TRACE_BASE_STRINGHELP_H diff --git a/trace_streamer/src/base/ts_common.h b/trace_streamer/src/base/ts_common.h index cd0ac26e..d01ac00b 100644 --- a/trace_streamer/src/base/ts_common.h +++ b/trace_streamer/src/base/ts_common.h @@ -38,6 +38,62 @@ const uint64_t SEC_TO_NS = 1000 * 1000 * 1000; const int32_t STR_DEFAULT_LEN = -1; const auto INVALID_CPU = INVALID_UINT32; const auto INVALID_TIME = INVALID_UINT64; +const std::string memQuery = + "select max(value) as maxNum, min(value) as minNum, avg(value) as avgNum, filter.name as name, p.name as " + "processName from process_measure left join process_measure_filter as filter on filter.id= filter_id left join " + "process as p on p.id = filter.ipid where filter_id > 0 and filter.name = 'mem.rss.anon' group by filter_id order " + "by avgNum desc;"; +const std::string memTopQuery = + "select max(value) as maxNum, min(value) as minNum, avg(value) as avgNum, f.name as name, p.name as processName " + "from process_measure left join process_measure_filter as f on f.id= filter_id left join process as p on p.id = " + "f.ipid where filter_id > 0 and f.name = 'mem.rss.anon' group by filter_id order by avgNum desc limit 10;"; +const std::string cpuSqlQuery = + "SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu, group_concat(dur, ',') AS dur, " + "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " + "',') AS avg_frequency FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS dur, CAST (MIN(freq) AS INT) AS " + "min_freq, CAST (MAX(freq) AS INT) AS max_freq, CAST ( (SUM(dur * freq) / SUM(dur) ) AS INT) AS avg_frequency from " + "result group by itid, cpu)GROUP BY ipid, itid ORDER BY ipid;"; +const std::string cpuTopTenSqlQuery = + "SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu,group_concat(dur, ',') AS dur, " + "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " + "',') AS avg_frequency, sum(dur * avg_frequency) AS sumNum FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS " + "dur,CAST (MIN(freq) AS INT) AS min_freq, CAST (MAX(freq) AS INT) AS max_freq,CAST ( (SUM(dur * freq) / SUM(dur) ) " + "AS INT) AS avg_frequency from result group by itid, cpu) GROUP BY ipid, itid ORDER BY sumNum DESC LIMIT 10"; +const std::string distributedTermQuery = + "select group_concat(thread.id,',') as threadId, group_concat(thread.name,',') as threadName, " + "group_concat(process.id,',') as processId, group_concat(process.name,',') as processName, " + "group_concat(callstack.name,',') as funName, group_concat(callstack.dur,',') as dur, " + "group_concat(callstack.ts,',') as ts, cast(callstack.chainId as varchar) as chainId, callstack.spanId as spanId, " + "callstack.parentSpanId as parentSpanId, group_concat(callstack.flag,',') as flag, (select value from meta where " + "name='source_name') as trace_name from callstack inner join thread on callstack.callid = thread.id inner join " + "process on process.id = thread.ipid where (callstack.flag='S' or callstack.flag='C') group by " + "callstack.chainId,callstack.spanId,callstack.parentSpanId;"; +const std::string memUnaggQuery = + "select p.name as processName, group_concat(filter.name) as name, cast(group_concat(value) as varchar) as value, " + "cast(group_concat(ts) as varchar) as ts from process_measure m left join process_measure_filter as filter on " + "filter.id= m.filter_id left join process as p on p.id = filter.ipid where filter.name = 'mem.rss.anon' or " + "filter.name = 'mem.rss.file' or filter.name = 'mem.swap' or filter.name = 'oom_score_adj' group by " + "p.name,filter.ipid order by filter.ipid;"; +const std::string metaDataQuery = + "select cast(name as varchar) as name, cast(value as varchar) as valueText from meta UNION select " + "'start_ts',cast(start_ts as varchar) from trace_range UNION select 'end_ts',cast(end_ts as varchar) from " + "trace_range;"; +const std::string sysCallsTopQuery = + "SELECT cpu.tid AS tid, cpu.pid AS pid, callstack.name AS funName, count(callstack.name) AS frequency, " + "min(callstack.dur) AS minDur, max(callstack.dur) AS maxDur, round(avg(callstack.dur)) AS avgDur FROM callstack " + "INNER JOIN (SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu, group_concat(dur, ',') AS dur, " + "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " + "',') AS avg_frequency, sum(dur * avg_frequency) AS sumNum FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS " + "dur, CAST (MIN(freq) AS INT) AS min_freq, CAST (MAX(freq) AS INT) AS max_freq, CAST ( (SUM(dur * freq) / SUM(dur) " + ") AS INT) AS avg_frequency FROM result GROUP BY itid, cpu) GROUP BY ipid, itid ORDER BY sumNum DESC LIMIT 10) AS " + "cpu ON callstack.callid = cpu.tid GROUP BY callstack.name ORDER BY frequency DESC LIMIT 10;"; +const std::string sysCallQuery = + "select count(*) as frequency, min(dur) as minDur, max(dur) as maxDur, avg(dur) as avgDur, name as funName from " + "callstack group by name order by frequency desc limit 100;"; +const std::string traceStateQuery = "select event_name,stat_type,count,source,serverity from stat;"; +const std::string traceTaskName = + "select P.id as id, P.pid as pid, P.name as process_name, group_concat(T.name,',') as thread_name from process as " + "P left join thread as T where P.id = T.ipid group by pid;"; enum BuiltinClocks { TS_CLOCK_UNKNOW = 0, TS_CLOCK_BOOTTIME = 1, diff --git a/trace_streamer/src/filter/native_hook_filter.cpp b/trace_streamer/src/filter/native_hook_filter.cpp index d0b83b15..48414a42 100644 --- a/trace_streamer/src/filter/native_hook_filter.cpp +++ b/trace_streamer/src/filter/native_hook_filter.cpp @@ -836,11 +836,18 @@ void NativeHookFilter::FinishParseNativeHookData() } // update last lib id + UpdateLastCallerPathAndSymbolIndexs(); + UpdateThreadNameWithNativeHookData(); +} +void NativeHookFilter::UpdateLastCallerPathAndSymbolIndexs() +{ GetCallIdToLastLibId(); - if (callIdToLastCallerPathIndex_.size()) { - traceDataCache_->GetNativeHookData()->UpdateLastCallerPathIndexs(callIdToLastCallerPathIndex_); + if (isStatisticMode_) { + traceDataCache_->GetNativeHookStatisticsData()->UpdateLastCallerPathAndSymbolIndexs( + callIdToLastCallerPathIndex_); + } else { + traceDataCache_->GetNativeHookData()->UpdateLastCallerPathAndSymbolIndexs(callIdToLastCallerPathIndex_); } - UpdateThreadNameWithNativeHookData(); } void NativeHookFilter::GetCallIdToLastLibId() { @@ -859,8 +866,9 @@ void NativeHookFilter::GetCallIdToLastLibId() foundLast = false; } auto filePathIndex = traceDataCache_->GetNativeHookFrameData()->FilePaths()[i]; + auto symbolIndex = traceDataCache_->GetNativeHookFrameData()->SymbolNames()[i]; if (!traceDataCache_->GetNativeHookFrameData()->Depths()[i]) { - callIdToLastCallerPathIndex_.insert(std::make_pair(callChainId, filePathIndex)); + callIdToLastCallerPathIndex_.insert({callChainId, std::make_tuple(filePathIndex, symbolIndex)}); foundLast = true; continue; } @@ -870,7 +878,7 @@ void NativeHookFilter::GetCallIdToLastLibId() auto filePath = traceDataCache_->dataDict_.GetDataFromDict(filePathIndex); auto ret = filePath.find("libc++_shared.so"); if (ret == filePath.npos) { - callIdToLastCallerPathIndex_.insert(std::make_pair(callChainId, filePathIndex)); + callIdToLastCallerPathIndex_.insert({callChainId, std::make_tuple(filePathIndex, symbolIndex)}); foundLast = true; } } diff --git a/trace_streamer/src/filter/native_hook_filter.h b/trace_streamer/src/filter/native_hook_filter.h index e07fc850..c88a50e0 100644 --- a/trace_streamer/src/filter/native_hook_filter.h +++ b/trace_streamer/src/filter/native_hook_filter.h @@ -114,6 +114,7 @@ private: void UpdateFilePathIdAndStValueToSymAddrMap(T* firstSymbolAddr, const int size, uint32_t filePathId); uint64_t GetMemMapSubTypeWithAddr(uint64_t addr); void UpdateAnonMmapDataDbIndex(uint64_t addr, uint32_t size, uint64_t row); + void UpdateLastCallerPathAndSymbolIndexs(); private: std::multimap> tsToMainEventsMap_ = {}; @@ -125,7 +126,7 @@ private: std::unordered_map> stackHashValueToFramesHashMap_ = {}; std::unordered_map> frameHashToFrameInfoMap_ = {}; std::unordered_map threadNameIdToThreadNameIndex_ = {}; - std::unordered_map callIdToLastCallerPathIndex_ = {}; + std::unordered_map> callIdToLastCallerPathIndex_ = {}; std::unordered_map functionNameIndexToVaddr_ = {}; std::unordered_map symbolIdToSymbolIndex_ = {}; std::unordered_map stackHashValueToCallChainIdMap_ = {}; diff --git a/trace_streamer/src/filter/perf_data_filter.cpp b/trace_streamer/src/filter/perf_data_filter.cpp index c9d1f24b..bb51c4da 100644 --- a/trace_streamer/src/filter/perf_data_filter.cpp +++ b/trace_streamer/src/filter/perf_data_filter.cpp @@ -20,7 +20,7 @@ namespace SysTuning { namespace TraceStreamer { PerfDataFilter::PerfDataFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : FilterBase(dataCache, filter), fileIdToRowInFileTable_(INVALID_UINT64), fileIdToRowInChainTable_(INVALID_UINT64) + : FilterBase(dataCache, filter), fileIdToRowInFileTable_(INVALID_UINT64) { } PerfDataFilter::~PerfDataFilter() = default; @@ -30,63 +30,58 @@ size_t PerfDataFilter::AppendPerfFiles(uint64_t fileId, uint32_t serial, DataInd fileIds_.emplace(fileId); auto size = traceDataCache_->GetPerfFilesData()->AppendNewPerfFiles(fileId, serial, symbols, filePath); fileIdToRowInFileTable_.Insert(fileId, serial, size); - if (!serial) { + if (!serial || serial == INVALID_UINT32) { fileIdToRow_.insert(std::make_pair(fileId, size)); } return size; } -size_t PerfDataFilter::AppendPerfCallChain(uint64_t sampleId, - uint32_t callChainId, - uint64_t vaddrInFile, - uint64_t fileId, - uint64_t symbolId) +void PerfDataFilter::AppendPerfCallChain(uint32_t callChainId, + uint32_t depth, + uint64_t ip, + uint64_t vaddrInFile, + uint64_t fileId, + uint64_t symbolId) { - auto size = traceDataCache_->GetPerfCallChainData()->AppendNewPerfCallChain(sampleId, callChainId, vaddrInFile, - fileId, symbolId); - fileIdToRowInChainTable_.Insert(fileId, symbolId, size); - return size; + traceDataCache_->GetPerfCallChainData()->AppendNewPerfCallChain(callChainId, depth, ip, vaddrInFile, fileId, + symbolId); } void PerfDataFilter::BeforeReload() { traceDataCache_->GetPerfCallChainData()->Clear(); traceDataCache_->GetPerfFilesData()->Clear(); fileIdToRowInFileTable_.Clear(); - fileIdToRowInChainTable_.Clear(); fileIds_.clear(); fileIdToRow_.clear(); } void PerfDataFilter::Finish() { auto fileIds = traceDataCache_->GetPerfCallChainData()->FileIds(); + auto ips = traceDataCache_->GetPerfCallChainData()->Ips(); auto symbolsIds = traceDataCache_->GetPerfCallChainData()->SymbolIds(); + auto vaddrs = traceDataCache_->GetPerfCallChainData()->VaddrInFiles(); auto size = traceDataCache_->GetPerfCallChainData()->Size(); auto filePath = traceDataCache_->GetPerfFilesData()->FilePaths(); auto sambols = traceDataCache_->GetPerfFilesData()->Symbols(); uint64_t flag = 1; flag = ~(flag << 63); for (auto i = 0; i < size; i++) { - if (fileIds_.find(fileIds[i]) == fileIds_.end()) { - // When the function name is empty and there is no file information to which the function belongs, - // set the function name to the virtual address of the function in the file - traceDataCache_->GetPerfCallChainData()->SetName( - i, "+0x" + base::number(traceDataCache_->GetPerfCallChainData()->VaddrInFiles()[i] & flag)); + if (fileIds[i] == INVALID_UINT64) { + traceDataCache_->GetPerfCallChainData()->SetName(i, "@0x" + + base::number(ips[i], base::INTEGER_RADIX_TYPE_HEX)); continue; } - if (symbolsIds[i] == -1) { - // When the function name is empty, if there has the file Id to which the function belongs,but the symboleid - // is -1. Set the function name as "the file name of the function at the top of the callstack + the virtual - // address of this function" + if (vaddrs[i] == 0 || symbolsIds[i] == -1) { auto pathIndex = filePath[fileIdToRow_.at(fileIds[i])]; auto fullPath = traceDataCache_->GetDataFromDict(pathIndex); auto iPos = fullPath.find_last_of('/'); fullPath = fullPath.substr(iPos + 1, -1); traceDataCache_->GetPerfCallChainData()->SetName( - i, fullPath + "+0x" + base::number(traceDataCache_->GetPerfCallChainData()->VaddrInFiles()[i] & flag)); + i, fullPath + "@0x" + base::number(ips[i] & flag, base::INTEGER_RADIX_TYPE_HEX)); continue; } - // When the function name is empty, if there has the file Id to which the function belongs,and the symboleid - // is not -1. Set the function name as the virtual address of this function + // if there has the file Id to which the function belongs,and the symboleid is not -1 and vaddrinfile is not -1. + // Set the function name as the virtual address of this function auto value = fileIdToRowInFileTable_.Find(fileIds[i], symbolsIds[i]); if (value == INVALID_UINT64) { traceDataCache_->GetPerfCallChainData()->SetName( @@ -97,7 +92,6 @@ void PerfDataFilter::Finish() traceDataCache_->GetPerfCallChainData()->SetName(i, traceDataCache_->GetDataFromDict(sambols[value])); } fileIdToRowInFileTable_.Clear(); - fileIdToRowInChainTable_.Clear(); fileIds_.clear(); fileIdToRow_.clear(); } diff --git a/trace_streamer/src/filter/perf_data_filter.h b/trace_streamer/src/filter/perf_data_filter.h index d4b0e21d..733f6eab 100644 --- a/trace_streamer/src/filter/perf_data_filter.h +++ b/trace_streamer/src/filter/perf_data_filter.h @@ -33,17 +33,17 @@ public: public: size_t AppendPerfFiles(uint64_t fileId, uint32_t serial, DataIndex symbols, DataIndex filePath); - size_t AppendPerfCallChain(uint64_t sampleId, - uint32_t callChainId, - uint64_t vaddrInFile, - uint64_t fileId, - uint64_t symbolId); + void AppendPerfCallChain(uint32_t callChainId, + uint32_t depth, + uint64_t ip, + uint64_t vaddrInFile, + uint64_t fileId, + uint64_t symbolId); void Finish(); void BeforeReload(); private: DoubleMap fileIdToRowInFileTable_; - DoubleMap fileIdToRowInChainTable_; std::set fileIds_; std::map fileIdToRow_{}; }; diff --git a/trace_streamer/src/filter/task_pool_filter.cpp b/trace_streamer/src/filter/task_pool_filter.cpp index acc31635..7b60d5bf 100644 --- a/trace_streamer/src/filter/task_pool_filter.cpp +++ b/trace_streamer/src/filter/task_pool_filter.cpp @@ -19,7 +19,6 @@ namespace SysTuning { namespace TraceStreamer { - TaskPoolFilter::TaskPoolFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) : FilterBase(dataCache, filter), IpidExecuteMap_(INVALID_INT32) { diff --git a/trace_streamer/src/include/BUILD.gn b/trace_streamer/src/include/BUILD.gn deleted file mode 100644 index e0981553..00000000 --- a/trace_streamer/src/include/BUILD.gn +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -import("//build/ohos.gni") -ohos_source_set("ibase") { - subsystem_name = "${OHOS_PROFILER_SUBSYS_NAME}" - part_name = "${OHOS_PROFILER_PART_NAME}" - sources = [ - "codec_cov.h", - "file.h", - "log.h", - "numerical_to_string.h", - "parting_string.h", - "string_to_numerical.h", - ] - include_dirs = [] - public_deps = [] - deps = [] - if (!is_independent_compile) { - configs = [ "${TS_DIR}/gn:ts_config" ] - } -} diff --git a/trace_streamer/src/include/dummy/musl/include/elf.h b/trace_streamer/src/include/dummy/musl/include/elf.h deleted file mode 100644 index e69de29b..00000000 diff --git a/trace_streamer/src/main.cpp b/trace_streamer/src/main.cpp index 94efc2c7..47f570c0 100644 --- a/trace_streamer/src/main.cpp +++ b/trace_streamer/src/main.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -48,62 +49,6 @@ using namespace SysTuning::base; constexpr size_t G_CHUNK_SIZE = 1024 * 1024; constexpr int G_MIN_PARAM_NUM = 2; constexpr size_t G_FILE_PERMISSION = 664; -const std::string memQuery = - "select max(value) as maxNum, min(value) as minNum, avg(value) as avgNum, filter.name as name, p.name as " - "processName from process_measure left join process_measure_filter as filter on filter.id= filter_id left join " - "process as p on p.id = filter.ipid where filter_id > 0 and filter.name = 'mem.rss.anon' group by filter_id order " - "by avgNum desc;"; -const std::string memTopQuery = - "select max(value) as maxNum, min(value) as minNum, avg(value) as avgNum, f.name as name, p.name as processName " - "from process_measure left join process_measure_filter as f on f.id= filter_id left join process as p on p.id = " - "f.ipid where filter_id > 0 and f.name = 'mem.rss.anon' group by filter_id order by avgNum desc limit 10;"; -const std::string cpuSqlQuery = - "SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu, group_concat(dur, ',') AS dur, " - "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " - "',') AS avg_frequency FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS dur, CAST (MIN(freq) AS INT) AS " - "min_freq, CAST (MAX(freq) AS INT) AS max_freq, CAST ( (SUM(dur * freq) / SUM(dur) ) AS INT) AS avg_frequency from " - "result group by itid, cpu)GROUP BY ipid, itid ORDER BY ipid;"; -const std::string cpuTopTenSqlQuery = - "SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu,group_concat(dur, ',') AS dur, " - "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " - "',') AS avg_frequency, sum(dur * avg_frequency) AS sumNum FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS " - "dur,CAST (MIN(freq) AS INT) AS min_freq, CAST (MAX(freq) AS INT) AS max_freq,CAST ( (SUM(dur * freq) / SUM(dur) ) " - "AS INT) AS avg_frequency from result group by itid, cpu) GROUP BY ipid, itid ORDER BY sumNum DESC LIMIT 10"; -const std::string distributedTermQuery = - "select group_concat(thread.id,',') as threadId, group_concat(thread.name,',') as threadName, " - "group_concat(process.id,',') as processId, group_concat(process.name,',') as processName, " - "group_concat(callstack.name,',') as funName, group_concat(callstack.dur,',') as dur, " - "group_concat(callstack.ts,',') as ts, cast(callstack.chainId as varchar) as chainId, callstack.spanId as spanId, " - "callstack.parentSpanId as parentSpanId, group_concat(callstack.flag,',') as flag, (select value from meta where " - "name='source_name') as trace_name from callstack inner join thread on callstack.callid = thread.id inner join " - "process on process.id = thread.ipid where (callstack.flag='S' or callstack.flag='C') group by " - "callstack.chainId,callstack.spanId,callstack.parentSpanId;"; -const std::string memUnaggQuery = - "select p.name as processName, group_concat(filter.name) as name, cast(group_concat(value) as varchar) as value, " - "cast(group_concat(ts) as varchar) as ts from process_measure m left join process_measure_filter as filter on " - "filter.id= m.filter_id left join process as p on p.id = filter.ipid where filter.name = 'mem.rss.anon' or " - "filter.name = 'mem.rss.file' or filter.name = 'mem.swap' or filter.name = 'oom_score_adj' group by " - "p.name,filter.ipid order by filter.ipid;"; -const std::string metaDataQuery = - "select cast(name as varchar) as name, cast(value as varchar) as valueText from meta UNION select " - "'start_ts',cast(start_ts as varchar) from trace_range UNION select 'end_ts',cast(end_ts as varchar) from " - "trace_range;"; -const std::string sysCallsTopQuery = - "SELECT cpu.tid AS tid, cpu.pid AS pid, callstack.name AS funName, count(callstack.name) AS frequency, " - "min(callstack.dur) AS minDur, max(callstack.dur) AS maxDur, round(avg(callstack.dur)) AS avgDur FROM callstack " - "INNER JOIN (SELECT itid AS tid, ipid AS pid, group_concat(cpu, ',') AS cpu, group_concat(dur, ',') AS dur, " - "group_concat(min_freq, ',') AS min_freq, group_concat(max_freq, ',') AS max_freq, group_concat(avg_frequency, " - "',') AS avg_frequency, sum(dur * avg_frequency) AS sumNum FROM (SELECT itid, ipid, cpu, CAST (SUM(dur) AS INT) AS " - "dur, CAST (MIN(freq) AS INT) AS min_freq, CAST (MAX(freq) AS INT) AS max_freq, CAST ( (SUM(dur * freq) / SUM(dur) " - ") AS INT) AS avg_frequency FROM result GROUP BY itid, cpu) GROUP BY ipid, itid ORDER BY sumNum DESC LIMIT 10) AS " - "cpu ON callstack.callid = cpu.tid GROUP BY callstack.name ORDER BY frequency DESC LIMIT 10;"; -const std::string sysCallQuery = - "select count(*) as frequency, min(dur) as minDur, max(dur) as maxDur, avg(dur) as avgDur, name as funName from " - "callstack group by name order by frequency desc limit 100;"; -const std::string traceStateQuery = "select event_name,stat_type,count,source,serverity from stat;"; -const std::string traceTaskName = - "select P.id as id, P.pid as pid, P.name as process_name, group_concat(T.name,',') as thread_name from process as " - "P left join thread as T where P.id = T.ipid group by pid;"; // set version info in meta.cpp please void ExportStatusToLog(const std::string& dbPath, TraceParserStatus status) { @@ -134,6 +79,9 @@ void ShowHelpInfo(const char* argv) " -h start HTTP server.\n" " -s separate arkts-plugin data, and save it in current dir with default filename.\n" " -p Specify the port of HTTP server, default is 9001.\n" + " -q select sql from file.\n" + " -m Perform operations that query metrics through linux,supports querying multiple metrics items.For " + "example:-m x,y,z.\n" " -i show information.\n" " -v show version.", argv, argv); @@ -183,7 +131,7 @@ void ReadSqlFileAndPrintResult(TraceStreamerSelector& ts, const std::string& sql { std::vector sqlStrings; LoadQueryFile(sqlOperator, sqlStrings); - for (const auto& str : sqlStrings) { + for (auto& str : sqlStrings) { ts.SearchDatabase(str, true); } } @@ -297,47 +245,29 @@ int CheckFinal(char** argv, TraceExportOption& traceExportOption, HttpOption& ht { if ((traceExportOption.traceFilePath.empty() || (!traceExportOption.interactiveState && traceExportOption.sqliteFilePath.empty())) && - !httpOption.enable && !traceExportOption.separateFile && traceExportOption.metricsIndex.empty() && traceExportOption.sqlOperatorFilePath.empty()) { + !httpOption.enable && !traceExportOption.separateFile && traceExportOption.metricsIndex.empty() && + traceExportOption.sqlOperatorFilePath.empty()) { ShowHelpInfo(argv[0]); return 1; } return 0; } -void InitMetricsMap(std::map& metricsMap) -{ - metricsMap.emplace(TRACE_MEM_UNAGG, memUnaggQuery); - metricsMap.emplace(TRACE_MEM, memQuery); - metricsMap.emplace(TRACE_MEM_TOP_TEN, memTopQuery); - metricsMap.emplace(TRACE_METADATA, metaDataQuery); - metricsMap.emplace(SYS_CALLS, sysCallQuery); - metricsMap.emplace(TRACE_STATS, traceStateQuery); - metricsMap.emplace(TRACE_TASK_NAMES, traceTaskName); -} - -const std::string MetricsSqlQuery(const std::string& metrics) -{ - std::map metricsMap; - InitMetricsMap(metricsMap); - auto itor = metricsMap.find(metrics); - if (itor == metricsMap.end()) { - TS_LOGE("metrics name error!!!"); - return ""; - } - return itor->second; -} void ParserAndPrintMetrics(TraceStreamerSelector& ts, const std::string& metrics) { - std::string result = ts.SearchDatabase(MetricsSqlQuery(metrics)); - if (result == "") { - return; - } - Metrics metricsOperator; - metricsOperator.ParserJson(metrics, result); - for (auto item : metricsOperator.GetMetricsMap()) { - if (item.second == metrics) { - metricsOperator.PrintMetricsResult(item.first); - return; + auto metricsName = SplitStringToVec(metrics, ","); + for (const auto& itemName : metricsName) { + std::string result = ts.SearchDatabase(ts.MetricsSqlQuery(itemName)); + if (result == "") { + continue; + } + Metrics metricsOperator; + metricsOperator.ParserJson(itemName, result); + for (auto item : metricsOperator.GetMetricsMap()) { + if (item.second == itemName) { + metricsOperator.PrintMetricsResult(item.first, nullptr); + continue; + } } } } @@ -426,7 +356,9 @@ int main(int argc, char** argv) TraceStreamerSelector ts; ts.EnableMetaTable(tsOption.exportMetaTable); ts.EnableFileSave(tsOption.separateFile); - if (OpenAndParserFile(ts, tsOption.traceFilePath)) { + std::regex traceInvalidStr("\\\\"); + auto strEscape = std::regex_replace(tsOption.traceFilePath, traceInvalidStr, "\\\\\\\\"); + if (OpenAndParserFile(ts, strEscape)) { if (!tsOption.sqliteFilePath.empty()) { ExportStatusToLog(tsOption.sqliteFilePath, GetAnalysisResult()); } diff --git a/trace_streamer/src/metrics/metrics.cpp b/trace_streamer/src/metrics/metrics.cpp index 0a79b0f0..75ea3087 100644 --- a/trace_streamer/src/metrics/metrics.cpp +++ b/trace_streamer/src/metrics/metrics.cpp @@ -20,6 +20,7 @@ namespace SysTuning { namespace TraceStreamer { const uint32_t EXTRA_CHAR = 4; +const uint32_t SEND_FINISH = 1; Metrics ::Metrics() { metricsFunction_ = { @@ -152,11 +153,11 @@ void Metrics::InitSysCallStrategy(const std::string& result) } return; } -void Metrics::PrintMetricsResult(uint32_t metricsIndex) +void Metrics::PrintMetricsResult(uint32_t metricsIndex, ResultCallBack callback) { std::string res = "\r\n"; std::string metricsName = ""; - std::string repeateValue = " "; + std::string repeateValue = ""; switch (metricsIndex) { case METRICS_TRACE_MEM: metricsName = TRACE_MEM; @@ -166,7 +167,6 @@ void Metrics::PrintMetricsResult(uint32_t metricsIndex) std::to_string(item.overallCounters.max) + "," + AVG + std::to_string(item.overallCounters.avg) + "}}},"; } - repeateValue.pop_back(); break; case METRICS_TRACE_MEM_TOP_TEN: metricsName = TRACE_MEM_TOP_TEN; @@ -176,7 +176,6 @@ void Metrics::PrintMetricsResult(uint32_t metricsIndex) std::to_string(item.overallCounters.max) + "," + AVG + std::to_string(item.overallCounters.avg) + "}}},"; } - repeateValue.pop_back(); break; case METRICS_TRACE_MEM_UNAGG: metricsName = TRACE_MEM_UNAGG; @@ -190,7 +189,6 @@ void Metrics::PrintMetricsResult(uint32_t metricsIndex) OOM_SCORE + std::to_string(item.swap.oom_score) + "," + VALUE + std::to_string(item.swap.value) + "}},"; } - repeateValue.pop_back(); break; case METRICS_TRACE_TASK_NAMES: metricsName = TRACE_TASK_NAMES; @@ -198,12 +196,11 @@ void Metrics::PrintMetricsResult(uint32_t metricsIndex) repeateValue += PROCESS + PID + std::to_string(item.pid) + "," + PROCESS_NAME + "\"" + item.processName + "\","; for (auto threadItem : item.threadName) { - repeateValue += THREAD_NAME + "\"" + threadItem + ","; + repeateValue += THREAD_NAME + "\"" + threadItem + "\","; } repeateValue.pop_back(); repeateValue += "},"; } - repeateValue.pop_back(); break; case METRICS_TRACE_STATS: metricsName = TRACE_STATS; @@ -211,7 +208,6 @@ void Metrics::PrintMetricsResult(uint32_t metricsIndex) repeateValue += STAT + NAME + "\"" + item.name + "\"," + COUNT + std::to_string(item.count) + "," + SOURCE + "\"" + item.source + "\"," + SEVERITY + "\"" + item.severity + "\"" + "},"; } - repeateValue.pop_back(); break; case METRICS_TRACE_METADATA: metricsName = TRACE_METADATA; @@ -219,25 +215,30 @@ void Metrics::PrintMetricsResult(uint32_t metricsIndex) repeateValue += TRACE_METADATA + ":{" + NAME + "\"" + item.name + "\"," + VALUE + "\"" + item.value + "\"" + "},"; } - repeateValue.pop_back(); break; case METRICS_SYS_CALLS: metricsName = SYS_CALLS; for (auto item : sysCallStrategy_) { repeateValue += FUNCTION + FUNCTION_NAME + "\"" + item.functionName + "\"," + DUR_MAX + - std::to_string(item.durMax) + "," + DUR_MIN + std::to_string(item.durMin) + "\"," + - DUR_AVG + "\"" + std::to_string(item.durAvg) + "\"" + "},"; + std::to_string(item.durMax) + "," + DUR_MIN + std::to_string(item.durMin) + "," + + DUR_AVG + std::to_string(item.durAvg) + "},"; } - repeateValue.pop_back(); break; default: break; } + if (repeateValue != "") { + repeateValue.pop_back(); + } res += metricsName + ": {" + repeateValue + "}"; res = JsonFormat(res) + "\r\n"; std::regex strRegex(","); auto str = std::regex_replace(res, strRegex, ""); +#ifndef IS_WASM printf("%s", str.c_str()); +#else + callback(str, SEND_FINISH); +#endif return; } std::string Metrics::GetLevelSpace(int level) diff --git a/trace_streamer/src/metrics/metrics.h b/trace_streamer/src/metrics/metrics.h index 90f1eb71..39e73648 100644 --- a/trace_streamer/src/metrics/metrics.h +++ b/trace_streamer/src/metrics/metrics.h @@ -71,7 +71,7 @@ const std::string FUNCTION = "function:{"; const std::string FUNCTION_NAME = "function_name:"; const std::string DUR_MAX = "dur_max:"; const std::string DUR_MIN = "dur_min:"; -const std::string DUR_AVG = "dr_avg:"; +const std::string DUR_AVG = "dur_avg:"; namespace SysTuning { namespace TraceStreamer { @@ -80,8 +80,9 @@ class Metrics { public: Metrics(); ~Metrics() {} + using ResultCallBack = std::function; void ParserJson(const std::string& metrics, std::string& result); - void PrintMetricsResult(uint32_t metricsIndex); + void PrintMetricsResult(uint32_t metricsIndex, ResultCallBack callback); auto GetMetricsMap() { return initMetricsMap_; diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp index 5ac5582c..276f0d00 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp @@ -28,48 +28,57 @@ BytraceHilogParser::~BytraceHilogParser() = default; bool BytraceHilogParser::HilogTimeStrToTimestamp(std::string& timeStr, uint64_t& timeStamp) const { - const uint64_t S_TO_NS = 1e9; const uint64_t MS_TO_NS = 1e6; const uint64_t US_TO_NS = 1e3; + const uint32_t TM_YEAR_FROM = 1900; + const uint32_t MS_FORMAT_LEN = 3; + const uint32_t US_FORMAT_LEN = 6; uint64_t sec; - uint64_t usec; + uint64_t nsec; std::string usecStr; std::smatch matcheLine; if (std::regex_search(timeStr, matcheLine, std::regex(R"(^\d+\.(\d+)$)"))) { size_t index = 0; usecStr = matcheLine[++index].str(); - sscanf_s(timeStr.c_str(), "%lu.%lu", &sec, &usec); + sscanf_s(timeStr.c_str(), "%lu.%lu", &sec, &nsec); } else if (std::regex_search(timeStr, matcheLine, - std::regex(R"(^(\d{4})?\-?(\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.(\d+))$)"))) { + std::regex(R"(^(\d{4})?\-?(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)$)"))) { size_t index = 0; std::string yearStr = matcheLine[++index].str(); - std::string timeStrTmp = matcheLine[++index].str(); + std::string monthStr = matcheLine[++index].str(); + std::string dayStr = matcheLine[++index].str(); + std::string hourStr = matcheLine[++index].str(); + std::string minStr = matcheLine[++index].str(); + std::string secStr = matcheLine[++index].str(); usecStr = matcheLine[++index].str(); struct tm timeInfo = {0}; - sscanf_s(timeStrTmp.c_str(), "%d-%d %d:%d:%d.%lu", &timeInfo.tm_mon, &timeInfo.tm_mday, &timeInfo.tm_hour, - &timeInfo.tm_min, &timeInfo.tm_sec, &usec); std::optional optionalYear = base::StrToInt(yearStr); if (optionalYear.has_value()) { - timeInfo.tm_year = optionalYear.value() - 1900; + timeInfo.tm_year = optionalYear.value() - TM_YEAR_FROM; } else { time_t tmNow; tmNow = time(nullptr); tm* ptmNow = localtime(&tmNow); timeInfo.tm_year = ptmNow->tm_year; } - timeInfo.tm_mon -= 1; + timeInfo.tm_mon = base::StrToInt(monthStr).value() - 1; + timeInfo.tm_mday = base::StrToInt(dayStr).value(); + timeInfo.tm_hour = base::StrToInt(hourStr).value(); + timeInfo.tm_min = base::StrToInt(minStr).value(); + timeInfo.tm_sec = base::StrToInt(secStr).value(); sec = std::mktime(&timeInfo); + nsec = base::StrToInt(usecStr).value(); } else { return false; } - if (usecStr.length() == 3) { - usec *= MS_TO_NS; - } else if (usecStr.length() == 6) { - usec *= US_TO_NS; + if (usecStr.length() == MS_FORMAT_LEN) { + nsec *= MS_TO_NS; + } else if (usecStr.length() == US_FORMAT_LEN) { + nsec *= US_TO_NS; } - timeStamp = usec + sec * SEC_TO_NS; + timeStamp = nsec + sec * SEC_TO_NS; return true; } @@ -141,6 +150,7 @@ void BytraceHilogParser::FilterAllHilogData() void BytraceHilogParser::BeginFilterHilogData(HilogLine* hilogData) { streamFilters_->statFilter_->IncreaseStat(TRACE_HILOG, STAT_EVENT_RECEIVED); + traceDataCache_->UpdateTraceTime(hilogData->timeStamp); auto curLineSeq = hilogData->lineSeq; auto newTimeStamp = hilogData->timeStamp; auto levelData = traceDataCache_->dataDict_.GetStringIndex(hilogData->level); diff --git a/trace_streamer/src/parser/hiperf_parser/perf_data_parser.cpp b/trace_streamer/src/parser/hiperf_parser/perf_data_parser.cpp index 7e56b3a4..00aef440 100644 --- a/trace_streamer/src/parser/hiperf_parser/perf_data_parser.cpp +++ b/trace_streamer/src/parser/hiperf_parser/perf_data_parser.cpp @@ -28,7 +28,7 @@ PerfDataParser::PerfDataParser(TraceDataCache* dataCache, const TraceStreamerFil runingStateIndex_(traceDataCache_->dataDict_.GetStringIndex("Running")), suspendStatIndex_(traceDataCache_->dataDict_.GetStringIndex("Suspend")), unkonwnStateIndex_(traceDataCache_->dataDict_.GetStringIndex("-")), - frameToCallChainId_(INVALID_UINT32) + pidAndStackHashToCallChainId_(INVALID_UINT32) { SymbolsFile::onRecording_ = false; } @@ -91,7 +91,7 @@ bool PerfDataParser::LoadPerfData() } bool PerfDataParser::Reload() { - frameToCallChainId_.Clear(); + pidAndStackHashToCallChainId_.Clear(); fileDataDictIdToFileId_.clear(); tidToPid_.clear(); streamFilters_->perfDataFilter_->BeforeReload(); @@ -209,6 +209,9 @@ void PerfDataParser::UpdateSymbolAndFilesData() streamFilters_->statFilter_->IncreaseStat(TRACE_PERF, STAT_EVENT_RECEIVED); streamFilters_->perfDataFilter_->AppendPerfFiles(fileId, serial++, symbolIndex, filePathIndex); } + if (symbolsFile->GetSymbols().size() == 0) { + streamFilters_->perfDataFilter_->AppendPerfFiles(fileId, INVALID_UINT32, INVALID_DATAINDEX, filePathIndex); + } fileDataDictIdToFileId_.insert(std::make_pair(filePathIndex, fileId)); ++fileId; } @@ -249,54 +252,28 @@ bool PerfDataParser::RecordCallBack(std::unique_ptr record) uint32_t PerfDataParser::UpdatePerfCallChainData(const std::unique_ptr& sample) { + std::string stackStr = ""; + for (auto& callFrame : sample->callFrames_) { + stackStr += "+" + base::number(callFrame.ip_, base::INTEGER_RADIX_TYPE_HEX); + } + auto stackHash = hashFun_(stackStr); + auto pid = sample->data_.pid; + auto callChainId = pidAndStackHashToCallChainId_.Find(pid, stackHash); + if (callChainId != INVALID_UINT32) { + return callChainId; + } + callChainId = ++callChainId_; + pidAndStackHashToCallChainId_.Insert(pid, stackHash, callChainId); uint64_t depth = 0; - bool callStackNotExist = false; - uint32_t callChainId = INVALID_UINT32; - std::vector> callStackTemp = {}; - // Filter callstack unuse data for (auto frame = sample->callFrames_.rbegin(); frame != sample->callFrames_.rend(); ++frame) { - auto symbolId = frame->symbolIndex_; - if (symbolId == -1 && frame->vaddrInFile_ == 0) { - continue; - } + uint64_t fileId = INVALID_UINT64; auto fileDataIndex = traceDataCache_->dataDict_.GetStringIndex(frame->filePath_); - auto itor = fileDataDictIdToFileId_.find(fileDataIndex); - if (itor == fileDataDictIdToFileId_.end()) { - continue; - } - auto fileId = itor->second; - callStackTemp.emplace_back(std::make_unique(depth, frame->vaddrInFile_, fileId, symbolId)); - depth++; - } - // Determine whether to write callstack data to cache - auto size = callStackTemp.size(); - for (auto itor = callStackTemp.begin(); itor != callStackTemp.end(); itor++) { - auto callstack = itor->get(); - auto ret = frameToCallChainId_.Find(callstack->fileId_, callstack->symbolId_, callstack->depth_, size); - if (ret != INVALID_UINT32) { // find it - if (callChainId == INVALID_UINT32) { - callChainId = ret; - } else if (callChainId != ret) { - callStackNotExist = true; - break; - } - } else { // not find it - callStackNotExist = true; - break; - } - } - // write callstack data to cache - if (callStackNotExist) { - callChainId = ++callChainId_; - for (auto itor = callStackTemp.begin(); itor != callStackTemp.end(); itor++) { - auto callstack = itor->get(); - frameToCallChainId_.Insert(callstack->fileId_, callstack->symbolId_, callstack->depth_, - callStackTemp.size(), callChainId); - streamFilters_->perfDataFilter_->AppendPerfCallChain( - callChainId, callstack->depth_, callstack->vaddrInFile_, callstack->fileId_, callstack->symbolId_); + if (fileDataDictIdToFileId_.count(fileDataIndex) != 0) { + fileId = fileDataDictIdToFileId_.at(fileDataIndex); } + streamFilters_->perfDataFilter_->AppendPerfCallChain(callChainId, depth++, frame->ip_, frame->vaddrInFile_, + fileId, frame->symbolIndex_); } - callStackTemp.clear(); return callChainId; } @@ -333,7 +310,7 @@ void PerfDataParser::Finish() } else { TS_LOGI("perfData time is not updated, maybe this trace file has other data"); } - frameToCallChainId_.Clear(); + pidAndStackHashToCallChainId_.Clear(); } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/parser/hiperf_parser/perf_data_parser.h b/trace_streamer/src/parser/hiperf_parser/perf_data_parser.h index e05fd810..418e5006 100644 --- a/trace_streamer/src/parser/hiperf_parser/perf_data_parser.h +++ b/trace_streamer/src/parser/hiperf_parser/perf_data_parser.h @@ -25,6 +25,7 @@ #if is_mingw #define unw_word_t uint64_t #endif +#include "numerical_to_string.h" #include "perf_events.h" #include "perf_file_format.h" #include "perf_file_reader.h" @@ -57,23 +58,8 @@ private: void UpdatePerfSampleData(uint32_t callChainId, std::unique_ptr& sample); uint32_t UpdatePerfCallChainData(const std::unique_ptr& sample); - class CallStackTemp { - public: - CallStackTemp() {} - CallStackTemp(uint32_t depth, uint64_t vaddr, uint64_t fileId, uint32_t symbolId) - : depth_(depth), vaddrInFile_(vaddr), fileId_(fileId), symbolId_(symbolId) - { - } - ~CallStackTemp() {} - uint32_t depth_ = 0; - uint64_t vaddrInFile_ = 0; - uint64_t fileId_ = 0; - uint32_t symbolId_ = 0; - }; uint32_t callChainId_ = 0; std::unique_ptr recordDataReader_ = nullptr; - const std::string cpuOffEventName_ = "sched:sched_switch"; - const std::string wakingEventName_ = "sched:sched_waking"; std::unique_ptr buffer_ = {}; size_t bufferSize_ = 0; bool cpuOffMode_ = false; @@ -98,8 +84,11 @@ private: {PERF_CLOCK_MONOTONIC_RAW, TS_MONOTONIC_RAW}, {PERF_CLOCK_BOOTTIME, TS_CLOCK_BOOTTIME}}; std::map fileDataDictIdToFileId_ = {}; - QuatraMap frameToCallChainId_; + std::hash hashFun_; + DoubleMap pidAndStackHashToCallChainId_; const std::string tmpPerfData_ = "ts_tmp.perf.data"; + const std::string cpuOffEventName_ = "sched:sched_switch"; + const std::string wakingEventName_ = "sched:sched_waking"; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn b/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn index 2710dd4c..fb6d4bd4 100755 --- a/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn +++ b/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn @@ -45,6 +45,7 @@ ohos_source_set("htrace_pbreader_parser_src") { "../../trace_data", "../../cfg", "../../trace_streamer", + "../../metrics", "${THIRD_PARTY}/bounds_checking_function/include", "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/sqlite/include", @@ -67,8 +68,8 @@ ohos_source_set("htrace_pbreader_parser_src") { "${THIRD_PARTY}/perf_include/linux", "../hiperf_parser", "../hiperf_parser/include", - "//commonlibrary/c_utils/base/include", - "../../include/dummy/musl", + "${COMMON_LIBRARY}/c_utils/base/include", + "${THIRD_PARTY}/sqlite", ] if (is_mingw || is_mac) { include_dirs += [ diff --git a/trace_streamer/src/proto_reader/proto_reader.cpp b/trace_streamer/src/proto_reader/proto_reader.cpp index f558d630..2022ce88 100644 --- a/trace_streamer/src/proto_reader/proto_reader.cpp +++ b/trace_streamer/src/proto_reader/proto_reader.cpp @@ -14,7 +14,9 @@ */ #include "proto_reader.h" +#include #include "optimize.h" +#include namespace SysTuning { namespace ProtoReader { @@ -91,7 +93,7 @@ bool ProtoReaderBase::ParseLengthDelimitedValue(ParseDataAreaResult& result, result.dataArea.SetDataAreaSize(length); result.next = cursor + length; if (length > kMaxMessageLength) { - TS_LOGD("Skip this data, because it is too large. length: %d", length); + TS_LOGD("Skip this data, because it is too large. length: %" PRIu64 "", length); result.status = SKIP; return true; } diff --git a/trace_streamer/src/rpc/rpc_server.cpp b/trace_streamer/src/rpc/rpc_server.cpp index 4534e46a..47cdb007 100644 --- a/trace_streamer/src/rpc/rpc_server.cpp +++ b/trace_streamer/src/rpc/rpc_server.cpp @@ -186,6 +186,23 @@ int32_t RpcServer::WasmSqlQuery(const uint8_t* data, size_t len, uint8_t* out, i int32_t ret = ts_->SearchDatabase(sql, out, outLen); return ret; } +bool RpcServer::SqlMetricsQueryWithCallback(const uint8_t* data, size_t len, ResultCallBack callback) const +{ + ts_->SetCancel(false); + std::string metricsName(reinterpret_cast(data), len); + std::string result = ts_->SearchDatabase(ts_->MetricsSqlQuery(metricsName)); + if (result == "") { + return false; + } + Metrics metricsOperator; + metricsOperator.ParserJson(metricsName, result); + for (auto item : metricsOperator.GetMetricsMap()) { + if (item.second == metricsName) { + metricsOperator.PrintMetricsResult(item.first, callback); + return true; + } + } +} int32_t RpcServer::WasmSqlQueryWithCallback(const uint8_t* data, size_t len, ResultCallBack callback) const { ts_->SetCancel(false); diff --git a/trace_streamer/src/rpc/rpc_server.h b/trace_streamer/src/rpc/rpc_server.h index 7534ab65..bc549af6 100644 --- a/trace_streamer/src/rpc/rpc_server.h +++ b/trace_streamer/src/rpc/rpc_server.h @@ -36,6 +36,7 @@ public: // only for wasm, no callback int32_t WasmSqlQuery(const uint8_t* data, size_t len, uint8_t* out, int32_t outLen); + bool SqlMetricsQueryWithCallback(const uint8_t* data, size_t len, ResultCallBack callback) const; int32_t WasmSqlQueryWithCallback(const uint8_t* data, size_t len, ResultCallBack callback) const; int32_t UpdateTraceTime(const uint8_t* data, int32_t len); int32_t TraceStreamer_Init_ThirdParty_Config(const uint8_t* data, int32_t len); diff --git a/trace_streamer/src/rpc/wasm_func.cpp b/trace_streamer/src/rpc/wasm_func.cpp index b9da66bd..b3c11cb6 100644 --- a/trace_streamer/src/rpc/wasm_func.cpp +++ b/trace_streamer/src/rpc/wasm_func.cpp @@ -201,6 +201,13 @@ EMSCRIPTEN_KEEPALIVE int32_t TraceStreamerSqlQueryEx(int32_t sqlLen) { return g_wasmTraceStreamer.WasmSqlQueryWithCallback(g_reqBuf, sqlLen, &ResultCallback); } +EMSCRIPTEN_KEEPALIVE int32_t TraceStreamerSqlMetricsQuery(int32_t sqlLen) +{ + if (g_wasmTraceStreamer.SqlMetricsQueryWithCallback(g_reqBuf, sqlLen, &ResultCallback)) { + return 0; + } + return -1; +} EMSCRIPTEN_KEEPALIVE int32_t TraceStreamerCancel() { g_wasmTraceStreamer.CancelSqlQuery(); diff --git a/trace_streamer/src/table/base/args_table.cpp b/trace_streamer/src/table/base/args_table.cpp index 7ae906d3..27d93dda 100644 --- a/trace_streamer/src/table/base/args_table.cpp +++ b/trace_streamer/src/table/base/args_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, KEY, DATATYPE, VALUE, ARGSETID }; +enum class Index : int32_t { ID = 0, KEY, DATATYPE, VALUE, ARGSETID }; ArgsTable::ArgsTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -57,8 +57,8 @@ void ArgsTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -77,8 +77,8 @@ void ArgsTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, si break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -119,8 +119,8 @@ int32_t ArgsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** a auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -131,8 +131,8 @@ int32_t ArgsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** a auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -145,20 +145,20 @@ int32_t ArgsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** a int32_t ArgsTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, CurrentRow()); // IdsData() will be optimized break; - case KEY: + case Index::KEY: sqlite3_result_int64(context_, static_cast(argSet_.NamesData()[CurrentRow()])); break; - case DATATYPE: + case Index::DATATYPE: sqlite3_result_int64(context_, static_cast(argSet_.DataTypes()[CurrentRow()])); break; - case VALUE: + case Index::VALUE: sqlite3_result_int64(context_, static_cast(argSet_.ValuesData()[CurrentRow()])); break; - case ARGSETID: + case Index::ARGSETID: sqlite3_result_int64(context_, static_cast(argSet_.ArgsData()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/base/data_dict_table.cpp b/trace_streamer/src/table/base/data_dict_table.cpp index 41f15f2e..19efeebe 100644 --- a/trace_streamer/src/table/base/data_dict_table.cpp +++ b/trace_streamer/src/table/base/data_dict_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, STR }; +enum class Index : int32_t { ID = 0, STR }; DataDictTable::DataDictTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -55,8 +55,8 @@ void DataDictTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -75,8 +75,8 @@ void DataDictTable::FilterByConstraint(FilterConstraints& fc, double& filterCost break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -116,8 +116,8 @@ int32_t DataDictTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -128,8 +128,8 @@ int32_t DataDictTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -143,11 +143,11 @@ int32_t DataDictTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value int32_t DataDictTable::Cursor::Column(int32_t col) const { DataIndex index = static_cast(CurrentRow()); - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case STR: + case Index::STR: sqlite3_result_text(context_, dataCache_->GetDataFromDict(index).c_str(), STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/base/data_type_table.cpp b/trace_streamer/src/table/base/data_type_table.cpp index 8876674c..93ec2e4d 100644 --- a/trace_streamer/src/table/base/data_type_table.cpp +++ b/trace_streamer/src/table/base/data_type_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPEID, DESC }; +enum class Index : int32_t { ID = 0, TYPEID, DESC }; DataTypeTable::DataTypeTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -56,8 +56,8 @@ void DataTypeTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -76,8 +76,8 @@ void DataTypeTable::FilterByConstraint(FilterConstraints& fc, double& filterCost break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -118,8 +118,8 @@ int32_t DataTypeTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -130,8 +130,8 @@ int32_t DataTypeTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -144,14 +144,14 @@ int32_t DataTypeTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value int32_t DataTypeTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TYPEID: + case Index::TYPEID: sqlite3_result_int64(context_, static_cast(dataTypeObj_.DataTypes()[CurrentRow()])); break; - case DESC: + case Index::DESC: sqlite3_result_text(context_, dataCache_->GetDataFromDict(dataTypeObj_.DataDesc()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/src/table/base/datasource_clockid_table.cpp b/trace_streamer/src/table/base/datasource_clockid_table.cpp index 196a638c..48089605 100644 --- a/trace_streamer/src/table/base/datasource_clockid_table.cpp +++ b/trace_streamer/src/table/base/datasource_clockid_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, NAME, CLOCK_ID }; +enum class Index : int32_t { ID = 0, NAME, CLOCK_ID }; DataSourceClockIdTableTable::DataSourceClockIdTableTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -44,15 +44,15 @@ DataSourceClockIdTableTable::Cursor::~Cursor() {} int32_t DataSourceClockIdTableTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, CurrentRow()); break; - case NAME: + case Index::NAME: sqlite3_result_text(context_, dataSourceClockIdData_.Names()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case CLOCK_ID: + case Index::CLOCK_ID: sqlite3_result_int(context_, static_cast(dataSourceClockIdData_.ClockIds()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/base/device_info_table.cpp b/trace_streamer/src/table/base/device_info_table.cpp index 77fbecc2..6893dbef 100644 --- a/trace_streamer/src/table/base/device_info_table.cpp +++ b/trace_streamer/src/table/base/device_info_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { PHYSICAL_WIDTH = 0, PHYSICAL_HEIGHT, PHYSICAL_FRAME_RATE }; +enum class Index : int32_t { PHYSICAL_WIDTH = 0, PHYSICAL_HEIGHT, PHYSICAL_FRAME_RATE }; DeviceInfoTable::DeviceInfoTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("physical_width", "INTEGER")); @@ -42,18 +42,18 @@ DeviceInfoTable::Cursor::~Cursor() {} int32_t DeviceInfoTable::Cursor::Column(int32_t column) const { - switch (column) { - case PHYSICAL_WIDTH: + switch (static_cast(column)) { + case Index::PHYSICAL_WIDTH: if (deviceInfoObj_.PhysicalWidth() != INVALID_UINT32) { sqlite3_result_int(context_, static_cast(deviceInfoObj_.PhysicalWidth())); } break; - case PHYSICAL_HEIGHT: + case Index::PHYSICAL_HEIGHT: if (deviceInfoObj_.PhysicalHeight() != INVALID_UINT32) { sqlite3_result_int(context_, static_cast(deviceInfoObj_.PhysicalHeight())); } break; - case PHYSICAL_FRAME_RATE: + case Index::PHYSICAL_FRAME_RATE: if (deviceInfoObj_.PhysicalFrameRate() != INVALID_UINT32) { sqlite3_result_int(context_, static_cast(deviceInfoObj_.PhysicalFrameRate())); } diff --git a/trace_streamer/src/table/base/meta_table.cpp b/trace_streamer/src/table/base/meta_table.cpp index 64a48510..e13a8268 100644 --- a/trace_streamer/src/table/base/meta_table.cpp +++ b/trace_streamer/src/table/base/meta_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { NAMEINDEX = 0, VALUE }; +enum class Index : int32_t { NAMEINDEX = 0, VALUE }; MetaTable::MetaTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("name", "TEXT")); @@ -41,12 +41,12 @@ MetaTable::Cursor::~Cursor() {} int32_t MetaTable::Cursor::Column(int32_t column) const { - switch (column) { - case NAMEINDEX: + switch (static_cast(column)) { + case Index::NAMEINDEX: sqlite3_result_text(context_, dataCache_->GetConstMetaData().Name(CurrentRow()).c_str(), STR_DEFAULT_LEN, nullptr); break; - case VALUE: + case Index::VALUE: sqlite3_result_text(context_, dataCache_->GetConstMetaData().Value(CurrentRow()).c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/src/table/base/range_table.cpp b/trace_streamer/src/table/base/range_table.cpp index 53476ad5..38255acc 100644 --- a/trace_streamer/src/table/base/range_table.cpp +++ b/trace_streamer/src/table/base/range_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { START_TS = 0, END_TS }; +enum class Index : int32_t { START_TS = 0, END_TS }; RangeTable::RangeTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("start_ts", "INTEGER")); @@ -40,11 +40,11 @@ RangeTable::Cursor::~Cursor() {} int32_t RangeTable::Cursor::Column(int32_t column) const { - switch (column) { - case START_TS: + switch (static_cast(column)) { + case Index::START_TS: sqlite3_result_int64(context_, static_cast(dataCache_->TraceStartTime())); break; - case END_TS: + case Index::END_TS: sqlite3_result_int64(context_, static_cast(dataCache_->TraceEndTime())); break; default: diff --git a/trace_streamer/src/table/base/span_join.cpp b/trace_streamer/src/table/base/span_join.cpp index 1677f2de..1014af7b 100644 --- a/trace_streamer/src/table/base/span_join.cpp +++ b/trace_streamer/src/table/base/span_join.cpp @@ -28,7 +28,7 @@ constexpr int32_t NEXT_NUMBER = 1; constexpr int32_t TSANDDUR_COLUMN = 2; constexpr int32_t PARTITIONED_COUNT = 3; -enum Index { TS, DUR, PARTITION }; +enum class Index : int32_t { TS, DUR, PARTITION }; SpanJoin::SpanJoin(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -255,7 +255,7 @@ bool SpanJoin::CaclSpan::IsQueryNext() bool SpanJoin::CaclSpan::SearchNextslice() { - while (partitionState_ != TS_REAL) { + while (partitionState_ != PartitionState::TS_REAL) { bool status = GetNextState(); if (!status) { return false; @@ -327,7 +327,7 @@ std::string SpanJoin::CaclSpan::GetMergeColumns(std::vector& column int64_t SpanJoin::CaclSpan::GetPatitonForMiss() { - return partitionState_ == TS_MISSING ? missPartitionEnd_ - NEXT_NUMBER : partition_; + return partitionState_ == PartitionState::TS_MISSING ? missPartitionEnd_ - NEXT_NUMBER : partition_; } std::unique_ptr SpanJoin::CreateCursor() @@ -401,18 +401,18 @@ SpanJoin::CaclSpan* SpanJoin::Cursor::FindQueryResult() int32_t SpanJoin::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(std::max(tableFirst_.ts_, tableSecond_.ts_))); break; } - case DUR: { + case Index::DUR: { sqlite3_result_int64(context_, static_cast(std::min(tableFirst_.endTs_, tableSecond_.endTs_) - std::max(tableFirst_.ts_, tableSecond_.ts_))); break; } - case PARTITION: { + case Index::PARTITION: { auto partResult = tableFirst_.partitionState_ == PartitionState::TS_REAL ? tableFirst_.partition_ : tableSecond_.partition_; sqlite3_result_int64(context_, static_cast(partResult)); diff --git a/trace_streamer/src/table/base/span_join.h b/trace_streamer/src/table/base/span_join.h index c80bf4f2..07e56cfe 100644 --- a/trace_streamer/src/table/base/span_join.h +++ b/trace_streamer/src/table/base/span_join.h @@ -38,8 +38,8 @@ struct TableColumnInfo { int32_t colIdx; }; -enum PartitionState { - TS_REAL, +enum class PartitionState : int32_t { + TS_REAL = 0, TS_PARTITION, TS_MISSING, TS_EOF, diff --git a/trace_streamer/src/table/base/stat_table.cpp b/trace_streamer/src/table/base/stat_table.cpp index 4934c85d..8cf75708 100644 --- a/trace_streamer/src/table/base/stat_table.cpp +++ b/trace_streamer/src/table/base/stat_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { EVENT_NAME = 0, STAT_EVENT_TYPE = 1, COUNT = 2, SEVERITY = 3, SOURCE = 4 }; +enum class Index : int32_t { EVENT_NAME = 0, STAT_EVENT_TYPE = 1, COUNT = 2, SEVERITY = 3, SOURCE = 4 }; StatTable::StatTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("event_name", "TEXT")); @@ -48,25 +48,25 @@ int32_t StatTable::Cursor::Column(int32_t column) const const StatAndInfo stat = dataCache_->GetConstStatAndInfo(); SupportedTraceEventType eventType = static_cast(CurrentRow() / STAT_EVENT_MAX); StatType statType = static_cast(CurrentRow() % STAT_EVENT_MAX); - switch (column) { - case EVENT_NAME: + switch (static_cast(column)) { + case Index::EVENT_NAME: sqlite3_result_text(context_, dataCache_->GetConstStatAndInfo().GetEvent(eventType).c_str(), STR_DEFAULT_LEN, nullptr); break; - case STAT_EVENT_TYPE: + case Index::STAT_EVENT_TYPE: sqlite3_result_text(context_, dataCache_->GetConstStatAndInfo().GetStat(statType).c_str(), STR_DEFAULT_LEN, nullptr); break; - case COUNT: + case Index::COUNT: sqlite3_result_int64(context_, static_cast(dataCache_->GetConstStatAndInfo().GetValue(eventType, statType))); break; - case SEVERITY: + case Index::SEVERITY: sqlite3_result_text(context_, dataCache_->GetConstStatAndInfo().GetSeverityDesc(eventType, statType).c_str(), STR_DEFAULT_LEN, nullptr); break; - case SOURCE: + case Index::SOURCE: sqlite3_result_text(context_, "trace", STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/base/symbols_table.cpp b/trace_streamer/src/table/base/symbols_table.cpp index 1aa017bc..2d585a43 100644 --- a/trace_streamer/src/table/base/symbols_table.cpp +++ b/trace_streamer/src/table/base/symbols_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, STR, ADDR }; +enum class Index : int32_t { ID = 0, STR, ADDR }; SymbolsTable::SymbolsTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -56,8 +56,8 @@ void SymbolsTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -76,8 +76,8 @@ void SymbolsTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -117,8 +117,8 @@ int32_t SymbolsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -129,8 +129,8 @@ int32_t SymbolsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -144,17 +144,17 @@ int32_t SymbolsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* int32_t SymbolsTable::Cursor::Column(int32_t col) const { DataIndex index = static_cast(CurrentRow()); - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case STR: + case Index::STR: sqlite3_result_text( context_, dataCache_->GetDataFromDict(dataCache_->GetConstSymbolsData().GetConstFuncNames()[index]).c_str(), STR_DEFAULT_LEN, nullptr); break; - case ADDR: + case Index::ADDR: sqlite3_result_int64(context_, static_cast(dataCache_->GetConstSymbolsData().GetConstAddrs()[index])); break; diff --git a/trace_streamer/src/table/base/trace_config_table.cpp b/trace_streamer/src/table/base/trace_config_table.cpp index cf1a96f8..8ffeab70 100644 --- a/trace_streamer/src/table/base/trace_config_table.cpp +++ b/trace_streamer/src/table/base/trace_config_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TRACE_SOURCE, KEY, VALUE }; +enum class Index : int32_t { ID = 0, TRACE_SOURCE, KEY, VALUE }; TraceConfigTable::TraceConfigTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -44,19 +44,19 @@ TraceConfigTable::Cursor::~Cursor() {} int32_t TraceConfigTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TRACE_SOURCE: + case Index::TRACE_SOURCE: sqlite3_result_text(context_, dataCache_->GetConstTraceConfigData().TraceSource()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case KEY: + case Index::KEY: sqlite3_result_text(context_, dataCache_->GetConstTraceConfigData().Key()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case VALUE: + case Index::VALUE: sqlite3_result_text(context_, dataCache_->GetConstTraceConfigData().Value()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/src/table/ebpf/bio_latency_sample_table.cpp b/trace_streamer/src/table/ebpf/bio_latency_sample_table.cpp index 4537752b..3d340ead 100644 --- a/trace_streamer/src/table/ebpf/bio_latency_sample_table.cpp +++ b/trace_streamer/src/table/ebpf/bio_latency_sample_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, TYPE, @@ -79,8 +79,8 @@ void BioLatencySampleTable::EstimateFilterCost(FilterConstraints& fc, EstimatedI ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -99,8 +99,8 @@ void BioLatencySampleTable::FilterByConstraint(FilterConstraints& fc, double& fi break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -141,8 +141,8 @@ int32_t BioLatencySampleTable::Cursor::Filter(const FilterConstraints& fc, sqlit auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -153,8 +153,8 @@ int32_t BioLatencySampleTable::Cursor::Filter(const FilterConstraints& fc, sqlit auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -167,63 +167,63 @@ int32_t BioLatencySampleTable::Cursor::Filter(const FilterConstraints& fc, sqlit int32_t BioLatencySampleTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.IdsData()[CurrentRow()])); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (bioLatencySampleObj_.CallChainIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.CallChainIds()[CurrentRow()])); } else { sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.Types()[CurrentRow()])); break; - case IPID: { + case Index::IPID: { if (bioLatencySampleObj_.Ipids()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.Ipids()[CurrentRow()])); } break; } - case ITID: { + case Index::ITID: { if (bioLatencySampleObj_.Itids()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.Itids()[CurrentRow()])); } break; } - case START_TS: { + case Index::START_TS: { if (bioLatencySampleObj_.StartTs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.StartTs()[CurrentRow()])); } break; } - case END_TS: { + case Index::END_TS: { if (bioLatencySampleObj_.EndTs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.EndTs()[CurrentRow()])); } break; } - case LATENCY_DUR: { + case Index::LATENCY_DUR: { if (bioLatencySampleObj_.LatencyDurs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.LatencyDurs()[CurrentRow()])); } break; } - case TIER: { + case Index::TIER: { if (bioLatencySampleObj_.Tiers()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.Tiers()[CurrentRow()])); } break; } - case SIZE: { + case Index::SIZE: { if (bioLatencySampleObj_.Sizes()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.Sizes()[CurrentRow()])); } break; } - case BLOCK_NUMBER: { + case Index::BLOCK_NUMBER: { if (bioLatencySampleObj_.BlockNumbers()[CurrentRow()] != INVALID_UINT64) { auto returnValueIndex0 = bioLatencySampleObj_.BlockNumbers()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(returnValueIndex0).c_str(), STR_DEFAULT_LEN, @@ -231,13 +231,13 @@ int32_t BioLatencySampleTable::Cursor::Column(int32_t column) const } break; } - case PATH: { + case Index::PATH: { if (bioLatencySampleObj_.FilePathIds()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.FilePathIds()[CurrentRow()])); } break; } - case DUR_PER_4K: { + case Index::DUR_PER_4K: { if (bioLatencySampleObj_.DurPer4k()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(bioLatencySampleObj_.DurPer4k()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ebpf/ebpf_callstack_table.cpp b/trace_streamer/src/table/ebpf/ebpf_callstack_table.cpp index c6c3cbc6..b155d97d 100644 --- a/trace_streamer/src/table/ebpf/ebpf_callstack_table.cpp +++ b/trace_streamer/src/table/ebpf/ebpf_callstack_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, DEPTH, @@ -65,8 +65,8 @@ void EbpfCallStackTable::EstimateFilterCost(FilterConstraints& fc, EstimatedInde ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -85,8 +85,8 @@ void EbpfCallStackTable::FilterByConstraint(FilterConstraints& fc, double& filte break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -127,8 +127,8 @@ int32_t EbpfCallStackTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_ auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -139,8 +139,8 @@ int32_t EbpfCallStackTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_ auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -153,17 +153,17 @@ int32_t EbpfCallStackTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_ int32_t EbpfCallStackTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(ebpfCallStackObj_.IdsData()[CurrentRow()])); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: sqlite3_result_int64(context_, static_cast(ebpfCallStackObj_.CallChainIds()[CurrentRow()])); break; - case DEPTH: + case Index::DEPTH: sqlite3_result_int64(context_, static_cast(ebpfCallStackObj_.Depths()[CurrentRow()])); break; - case IP: { + case Index::IP: { if (ebpfCallStackObj_.Ips()[CurrentRow()] != INVALID_UINT64) { auto returnValueIndex = ebpfCallStackObj_.Ips()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(returnValueIndex).c_str(), STR_DEFAULT_LEN, @@ -171,13 +171,13 @@ int32_t EbpfCallStackTable::Cursor::Column(int32_t column) const } break; } - case SYMBOLS_ID: { + case Index::SYMBOLS_ID: { if (ebpfCallStackObj_.SymbolIds()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(ebpfCallStackObj_.SymbolIds()[CurrentRow()])); } break; } - case FILE_PATH_ID: { + case Index::FILE_PATH_ID: { if (ebpfCallStackObj_.FilePathIds()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(ebpfCallStackObj_.FilePathIds()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp b/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp index b38cb0b3..e96d9f99 100644 --- a/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp +++ b/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp @@ -16,7 +16,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, ELF_ID, ST_NAME, @@ -62,8 +62,8 @@ void EbpfElfSymbolTable::EstimateFilterCost(FilterConstraints& fc, EstimatedInde ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -82,8 +82,8 @@ void EbpfElfSymbolTable::FilterByConstraint(FilterConstraints& fc, double& filte break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -114,20 +114,20 @@ EbpfElfSymbolTable::Cursor::~Cursor() {} int32_t EbpfElfSymbolTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.IdsData()[CurrentRow()])); break; - case ELF_ID: + case Index::ELF_ID: sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.ElfIds()[CurrentRow()])); break; - case ST_NAME: + case Index::ST_NAME: sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.StNames()[CurrentRow()])); break; - case ST_VALUE: + case Index::ST_VALUE: sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.StValues()[CurrentRow()])); break; - case ST_SIZE: + case Index::ST_SIZE: sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.StSizes()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp b/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp index 295ca565..9cf10d09 100644 --- a/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp +++ b/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp @@ -16,7 +16,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, ELF_ID, TEXT_VADDR, @@ -70,8 +70,8 @@ void EbpfElfTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -90,8 +90,8 @@ void EbpfElfTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -122,41 +122,41 @@ EbpfElfTable::Cursor::~Cursor() {} int32_t EbpfElfTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(ebpfElfObj_.IdsData()[CurrentRow()])); break; - case ELF_ID: + case Index::ELF_ID: sqlite3_result_int64(context_, static_cast(ebpfElfObj_.ElfIds()[CurrentRow()])); break; - case TEXT_VADDR: + case Index::TEXT_VADDR: sqlite3_result_int64(context_, static_cast(ebpfElfObj_.TextVaddrs()[CurrentRow()])); break; - case TEXT_OFFSET: + case Index::TEXT_OFFSET: sqlite3_result_int64(context_, static_cast(ebpfElfObj_.TextOffsets()[CurrentRow()])); break; - case STR_TAB_LEN: + case Index::STR_TAB_LEN: sqlite3_result_int64(context_, static_cast(ebpfElfObj_.StrTabLens()[CurrentRow()])); break; - case SYM_TAB_LEN: { + case Index::SYM_TAB_LEN: { if (ebpfElfObj_.SymTabLens()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(ebpfElfObj_.SymTabLens()[CurrentRow()])); } break; } - case FILE_NAME_LEN: { + case Index::FILE_NAME_LEN: { if (ebpfElfObj_.FileNameLens()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(ebpfElfObj_.FileNameLens()[CurrentRow()])); } break; } - case SYM_ENT_LEN: { + case Index::SYM_ENT_LEN: { if (ebpfElfObj_.SymEntLens()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(ebpfElfObj_.SymEntLens()[CurrentRow()])); } break; } - case FILE_PATH_ID: { + case Index::FILE_PATH_ID: { if (ebpfElfObj_.FileNameIndexs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(ebpfElfObj_.FileNameIndexs()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp b/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp index 75fe2b09..4cfdd7a6 100644 --- a/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp +++ b/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp @@ -16,7 +16,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, START_ADDR, END_ADDR, @@ -66,8 +66,8 @@ void EbpfProcessMapsTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -86,8 +86,8 @@ void EbpfProcessMapsTable::FilterByConstraint(FilterConstraints& fc, double& fil break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -118,32 +118,32 @@ EbpfProcessMapsTable::Cursor::~Cursor() {} int32_t EbpfProcessMapsTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.IdsData()[CurrentRow()])); break; - case START_ADDR: + case Index::START_ADDR: sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Starts()[CurrentRow()])); break; - case END_ADDR: + case Index::END_ADDR: sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Ends()[CurrentRow()])); break; - case OFFSETS: + case Index::OFFSETS: sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Offsets()[CurrentRow()])); break; - case PID: { + case Index::PID: { if (ebpfProcessMapsObj_.Pids()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Pids()[CurrentRow()])); } break; } - case FILE_NAME_LEN: { + case Index::FILE_NAME_LEN: { if (ebpfProcessMapsObj_.FileNameLens()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.FileNameLens()[CurrentRow()])); } break; } - case FILE_PATH_ID: { + case Index::FILE_PATH_ID: { if (ebpfProcessMapsObj_.FileNameIndexs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.FileNameIndexs()[CurrentRow()])); diff --git a/trace_streamer/src/table/ebpf/file_system_sample_table.cpp b/trace_streamer/src/table/ebpf/file_system_sample_table.cpp index 66065caf..172b522a 100644 --- a/trace_streamer/src/table/ebpf/file_system_sample_table.cpp +++ b/trace_streamer/src/table/ebpf/file_system_sample_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, TYPE, @@ -87,8 +87,8 @@ void FileSystemSampleTable::EstimateFilterCost(FilterConstraints& fc, EstimatedI ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -107,8 +107,8 @@ void FileSystemSampleTable::FilterByConstraint(FilterConstraints& fc, double& fi break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -149,11 +149,11 @@ int32_t FileSystemSampleTable::Cursor::Filter(const FilterConstraints& fc, sqlit auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case TYPE: + case Index::TYPE: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), fileSystemSampleTableObj_.Types()); break; @@ -165,8 +165,8 @@ int32_t FileSystemSampleTable::Cursor::Filter(const FilterConstraints& fc, sqlit auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -178,11 +178,11 @@ int32_t FileSystemSampleTable::Cursor::Filter(const FilterConstraints& fc, sqlit int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.IdsData()[CurrentRow()])); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (fileSystemSampleTableObj_.CallChainIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.CallChainIds()[CurrentRow()])); @@ -190,25 +190,25 @@ int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.Types()[CurrentRow()])); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.Ipids()[CurrentRow()])); break; - case ITID: + case Index::ITID: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.Itids()[CurrentRow()])); break; - case START_TS: + case Index::START_TS: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.StartTs()[CurrentRow()])); break; - case END_TS: + case Index::END_TS: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.EndTs()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.Durs()[CurrentRow()])); break; - case RETURN_VALUE: { + case Index::RETURN_VALUE: { if (fileSystemSampleTableObj_.ReturnValues()[CurrentRow()] != INVALID_UINT64) { auto returnValueIndex = fileSystemSampleTableObj_.ReturnValues()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(returnValueIndex).c_str(), STR_DEFAULT_LEN, @@ -216,7 +216,7 @@ int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const } break; } - case ERROR_VALUE: { + case Index::ERROR_VALUE: { if (fileSystemSampleTableObj_.ErrorCodes()[CurrentRow()] != INVALID_UINT64) { auto errorValueIndex = fileSystemSampleTableObj_.ErrorCodes()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(errorValueIndex).c_str(), STR_DEFAULT_LEN, @@ -224,25 +224,25 @@ int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const } break; } - case FD: { + case Index::FD: { if (fileSystemSampleTableObj_.Fds()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.Fds()[CurrentRow()])); } break; } - case FILE_ID: { + case Index::FILE_ID: { if (fileSystemSampleTableObj_.FileIds()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.FileIds()[CurrentRow()])); } break; } - case SIZE: { + case Index::SIZE: { if (fileSystemSampleTableObj_.Sizes()[CurrentRow()] != MAX_SIZE_T) { sqlite3_result_int64(context_, static_cast(fileSystemSampleTableObj_.Sizes()[CurrentRow()])); } break; } - case FIRST_ARGUMENT: { + case Index::FIRST_ARGUMENT: { if (fileSystemSampleTableObj_.FirstArguments()[CurrentRow()] != INVALID_UINT64) { auto firstArgIndex = fileSystemSampleTableObj_.FirstArguments()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(firstArgIndex).c_str(), STR_DEFAULT_LEN, @@ -250,7 +250,7 @@ int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const } break; } - case SECOND_ARGUMENT: { + case Index::SECOND_ARGUMENT: { if (fileSystemSampleTableObj_.SecondArguments()[CurrentRow()] != INVALID_UINT64) { auto secondArgIndex = fileSystemSampleTableObj_.SecondArguments()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(secondArgIndex).c_str(), STR_DEFAULT_LEN, @@ -258,7 +258,7 @@ int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const } break; } - case THIRD_ARGUMENT: { + case Index::THIRD_ARGUMENT: { if (fileSystemSampleTableObj_.ThirdArguments()[CurrentRow()] != INVALID_UINT64) { auto thirdArgIndex = fileSystemSampleTableObj_.ThirdArguments()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(thirdArgIndex).c_str(), STR_DEFAULT_LEN, @@ -266,7 +266,7 @@ int32_t FileSystemSampleTable::Cursor::Column(int32_t column) const } break; } - case FOURTH_ARGUMENT: { + case Index::FOURTH_ARGUMENT: { if (fileSystemSampleTableObj_.FourthArguments()[CurrentRow()] != INVALID_UINT64) { auto fourthArgIndex = fileSystemSampleTableObj_.FourthArguments()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(fourthArgIndex).c_str(), STR_DEFAULT_LEN, diff --git a/trace_streamer/src/table/ftrace/animation_table.cpp b/trace_streamer/src/table/ftrace/animation_table.cpp index 9813e88a..38c8c554 100644 --- a/trace_streamer/src/table/ftrace/animation_table.cpp +++ b/trace_streamer/src/table/ftrace/animation_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, INPUT_TIME, START_POINT, END_POINT }; +enum class Index : int32_t { ID = 0, INPUT_TIME, START_POINT, END_POINT }; AnimationTable::AnimationTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -46,23 +46,23 @@ AnimationTable::Cursor::~Cursor() {} int32_t AnimationTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(animationObj_.IdsData()[CurrentRow()])); break; - case INPUT_TIME: { + case Index::INPUT_TIME: { if (animationObj_.InputTimes()[CurrentRow()] != INVALID_TIME) { sqlite3_result_int64(context_, static_cast(animationObj_.InputTimes()[CurrentRow()])); } break; } - case START_POINT: { + case Index::START_POINT: { if (animationObj_.StartPoints()[CurrentRow()] != INVALID_TIME) { sqlite3_result_int64(context_, static_cast(animationObj_.StartPoints()[CurrentRow()])); } break; } - case END_POINT: + case Index::END_POINT: if (animationObj_.EndPoints()[CurrentRow()] != INVALID_TIME) { sqlite3_result_int64(context_, static_cast(animationObj_.EndPoints()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ftrace/app_startup_table.cpp b/trace_streamer/src/table/ftrace/app_startup_table.cpp index 3a44cbd6..a6264036 100644 --- a/trace_streamer/src/table/ftrace/app_startup_table.cpp +++ b/trace_streamer/src/table/ftrace/app_startup_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, CALL_ID, IPID, TID, START_TIME, END_TIME, START_NAME, PACKED_NAME }; +enum class Index : int32_t { ID = 0, CALL_ID, IPID, TID, START_TIME, END_TIME, START_NAME, PACKED_NAME }; AppStartupTable::AppStartupTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -48,29 +48,29 @@ AppStartupTable::Cursor::~Cursor() {} int32_t AppStartupTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, static_cast(appStartupObj_.Pids()[CurrentRow()])); break; - case TID: + case Index::TID: sqlite3_result_int64(context_, static_cast(appStartupObj_.Tids()[CurrentRow()])); break; - case CALL_ID: + case Index::CALL_ID: sqlite3_result_int64(context_, static_cast(appStartupObj_.CallIds()[CurrentRow()])); break; - case START_TIME: + case Index::START_TIME: sqlite3_result_int64(context_, static_cast(appStartupObj_.StartTimes()[CurrentRow()])); break; - case END_TIME: + case Index::END_TIME: sqlite3_result_int64(context_, static_cast(appStartupObj_.EndTimes()[CurrentRow()])); break; - case START_NAME: + case Index::START_NAME: sqlite3_result_int64(context_, static_cast(appStartupObj_.StartNames()[CurrentRow()])); break; - case PACKED_NAME: + case Index::PACKED_NAME: sqlite3_result_text(context_, dataCache_->GetDataFromDict(appStartupObj_.PackedNames()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); diff --git a/trace_streamer/src/table/ftrace/callstack_table.cpp b/trace_streamer/src/table/ftrace/callstack_table.cpp index 0d14ad1a..edc24a32 100644 --- a/trace_streamer/src/table/ftrace/callstack_table.cpp +++ b/trace_streamer/src/table/ftrace/callstack_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, TS, DUR, @@ -87,8 +87,8 @@ void CallStackTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInf ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -107,8 +107,8 @@ void CallStackTable::FilterByConstraint(FilterConstraints& fc, double& filterCos break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -149,17 +149,17 @@ int32_t CallStackTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case TS: + case Index::TS: FilterTS(c.op, argv[i], slicesObj_.TimeStampData()); break; - case CALL_ID: + case Index::CALL_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), slicesObj_.CallIds()); break; - case COOKIE_ID: + case Index::COOKIE_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), slicesObj_.Cookies()); break; default: @@ -170,8 +170,8 @@ int32_t CallStackTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -184,20 +184,20 @@ int32_t CallStackTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu int32_t CallStackTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, CurrentRow()); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(slicesObj_.TimeStampData()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(slicesObj_.DursData()[CurrentRow()])); break; - case CALL_ID: + case Index::CALL_ID: sqlite3_result_int64(context_, static_cast(slicesObj_.CallIds()[CurrentRow()])); break; - case CAT: { + case Index::CAT: { if (slicesObj_.CatsData()[CurrentRow()] != INVALID_UINT64) { auto catsDataIndex = static_cast(slicesObj_.CatsData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(catsDataIndex).c_str(), STR_DEFAULT_LEN, @@ -205,10 +205,10 @@ int32_t CallStackTable::Cursor::Column(int32_t col) const } break; } - case IDENTIFY: + case Index::IDENTIFY: sqlite3_result_int(context_, slicesObj_.IdentifysData()[CurrentRow()]); break; - case NAME: { + case Index::NAME: { if (slicesObj_.NamesData()[CurrentRow()] != INVALID_UINT64) { auto nameDataIndex = static_cast(slicesObj_.NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(nameDataIndex).c_str(), STR_DEFAULT_LEN, @@ -216,47 +216,47 @@ int32_t CallStackTable::Cursor::Column(int32_t col) const } break; } - case DEPTH: + case Index::DEPTH: sqlite3_result_int64(context_, static_cast(slicesObj_.Depths()[CurrentRow()])); break; - case COOKIE_ID: + case Index::COOKIE_ID: if (slicesObj_.Cookies()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(slicesObj_.Cookies()[CurrentRow()])); } break; - case PARENT_ID: { + case Index::PARENT_ID: { if (slicesObj_.ParentIdData()[CurrentRow()].has_value()) { sqlite3_result_int64(context_, static_cast(slicesObj_.ParentIdData()[CurrentRow()].value())); } break; } - case ARGSET: + case Index::ARGSET: if (slicesObj_.ArgSetIdsData()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(slicesObj_.ArgSetIdsData()[CurrentRow()])); } break; - case CHAIN_ID: + case Index::CHAIN_ID: if (!slicesObj_.ChainIds()[CurrentRow()].empty()) { sqlite3_result_text(context_, slicesObj_.ChainIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); } break; - case SPAN_ID: + case Index::SPAN_ID: if (!slicesObj_.SpanIds()[CurrentRow()].empty()) { sqlite3_result_text(context_, slicesObj_.SpanIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); } break; - case PARENT_SPAN_ID: + case Index::PARENT_SPAN_ID: if (!slicesObj_.ParentSpanIds()[CurrentRow()].empty()) { sqlite3_result_text(context_, slicesObj_.ParentSpanIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); } break; - case FLAG: + case Index::FLAG: if (!slicesObj_.Flags()[CurrentRow()].empty()) { sqlite3_result_text(context_, slicesObj_.Flags()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); } break; - case ARGS: + case Index::ARGS: if (!slicesObj_.ArgsData()[CurrentRow()].empty()) { sqlite3_result_text(context_, slicesObj_.ArgsData()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); } diff --git a/trace_streamer/src/table/ftrace/clk_event_filter_table.cpp b/trace_streamer/src/table/ftrace/clk_event_filter_table.cpp index 503db4c3..83b1df94 100644 --- a/trace_streamer/src/table/ftrace/clk_event_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/clk_event_filter_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, CPU }; +enum class Index : int32_t { ID = 0, TYPE, NAME, CPU }; ClkEventFilterTable::ClkEventFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -45,22 +45,22 @@ ClkEventFilterTable::Cursor::~Cursor() {} int32_t ClkEventFilterTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64( context_, static_cast(dataCache_->GetConstClkEventFilterData().IdsData()[CurrentRow()])); break; - case TYPE: { + case Index::TYPE: { size_t typeId = static_cast(dataCache_->GetConstClkEventFilterData().RatesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(typeId).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case NAME: { + case Index::NAME: { size_t strId = static_cast(dataCache_->GetConstClkEventFilterData().NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(strId).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case CPU: + case Index::CPU: sqlite3_result_int64(context_, static_cast( dataCache_->GetConstClkEventFilterData().CpusData()[CurrentRow()])); break; diff --git a/trace_streamer/src/table/ftrace/clock_event_filter_table.cpp b/trace_streamer/src/table/ftrace/clock_event_filter_table.cpp index 44bdaea7..da687920 100644 --- a/trace_streamer/src/table/ftrace/clock_event_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/clock_event_filter_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, CPU }; +enum class Index : int32_t { ID = 0, TYPE, NAME, CPU }; ClockEventFilterTable::ClockEventFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -45,22 +45,22 @@ ClockEventFilterTable::Cursor::~Cursor() {} int32_t ClockEventFilterTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast( dataCache_->GetConstClockEventFilterData().IdsData()[CurrentRow()])); break; - case TYPE: { + case Index::TYPE: { size_t typeId = static_cast(dataCache_->GetConstClockEventFilterData().TypesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(typeId).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case NAME: { + case Index::NAME: { size_t strId = static_cast(dataCache_->GetConstClockEventFilterData().NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(strId).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case CPU: + case Index::CPU: sqlite3_result_int64(context_, static_cast( dataCache_->GetConstClockEventFilterData().CpusData()[CurrentRow()])); break; diff --git a/trace_streamer/src/table/ftrace/clock_snapshot_table.cpp b/trace_streamer/src/table/ftrace/clock_snapshot_table.cpp index f644d1e7..f05ee942 100644 --- a/trace_streamer/src/table/ftrace/clock_snapshot_table.cpp +++ b/trace_streamer/src/table/ftrace/clock_snapshot_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, CLOCK_ID, TS, CLOCK_NAME }; +enum class Index : int32_t { ID = 0, CLOCK_ID, TS, CLOCK_NAME }; ClockSnapShotTable::ClockSnapShotTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -46,17 +46,17 @@ ClockSnapShotTable::Cursor::~Cursor() {} int32_t ClockSnapShotTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, CurrentRow()); break; - case CLOCK_ID: + case Index::CLOCK_ID: sqlite3_result_int64(context_, static_cast(snapShotData_.ClockIds()[CurrentRow()])); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(snapShotData_.Ts()[CurrentRow()])); break; - case CLOCK_NAME: + case Index::CLOCK_NAME: sqlite3_result_text(context_, snapShotData_.Names()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/ftrace/cpu_measure_filter_table.cpp b/trace_streamer/src/table/ftrace/cpu_measure_filter_table.cpp index 7b4f9b9c..086ec53e 100644 --- a/trace_streamer/src/table/ftrace/cpu_measure_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/cpu_measure_filter_table.cpp @@ -21,7 +21,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, CPU }; +enum class Index : int32_t { ID = 0, TYPE, NAME, CPU }; CpuMeasureFilterTable::CpuMeasureFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -60,8 +60,8 @@ void CpuMeasureFilterTable::EstimateFilterCost(FilterConstraints& fc, EstimatedI ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -80,8 +80,8 @@ void CpuMeasureFilterTable::FilterByConstraint(FilterConstraints& fc, double& fi break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -141,11 +141,11 @@ int32_t CpuMeasureFilterTable::Cursor::Filter(const FilterConstraints& fc, sqlit auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterSorted(c.col, c.op, argv[i]); break; - case CPU: + case Index::CPU: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), cpuMeasureObj_.CpuData()); break; default: @@ -156,8 +156,8 @@ int32_t CpuMeasureFilterTable::Cursor::Filter(const FilterConstraints& fc, sqlit auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -170,20 +170,20 @@ int32_t CpuMeasureFilterTable::Cursor::Filter(const FilterConstraints& fc, sqlit int32_t CpuMeasureFilterTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(cpuMeasureObj_.IdsData()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "cpu_measure_filter", STR_DEFAULT_LEN, nullptr); break; - case NAME: { + case Index::NAME: { const std::string& str = dataCache_->GetDataFromDict(static_cast(cpuMeasureObj_.NameData()[CurrentRow()])); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } - case CPU: + case Index::CPU: sqlite3_result_int64(context_, static_cast(cpuMeasureObj_.CpuData()[CurrentRow()])); break; default: @@ -202,8 +202,8 @@ void CpuMeasureFilterTable::Cursor::FilterSorted(int32_t col, unsigned char op, return; } - switch (col) { - case ID: { + switch (static_cast(col)) { + case Index::ID: { auto v = static_cast(sqlite3_value_int64(argv)); auto getValue = [](const uint32_t& row) { return row; }; switch (op) { diff --git a/trace_streamer/src/table/ftrace/dynamic_frame_table.cpp b/trace_streamer/src/table/ftrace/dynamic_frame_table.cpp index 53a2e6fe..17b7ccc9 100644 --- a/trace_streamer/src/table/ftrace/dynamic_frame_table.cpp +++ b/trace_streamer/src/table/ftrace/dynamic_frame_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, X, Y, WIDTH, HEIGHT, ALPHA, NAME, END_TIME }; +enum class Index : int32_t { ID = 0, X, Y, WIDTH, HEIGHT, ALPHA, NAME, END_TIME }; DynamicFrameTable::DynamicFrameTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -49,27 +49,27 @@ DynamicFrameTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* ta DynamicFrameTable::Cursor::~Cursor() {} int32_t DynamicFrameTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(dynamicFrameObj_.IdsData()[CurrentRow()])); break; - case X: { + case Index::X: { sqlite3_result_int(context_, static_cast(dynamicFrameObj_.Xs()[CurrentRow()])); break; } - case Y: { + case Index::Y: { sqlite3_result_int(context_, static_cast(dynamicFrameObj_.Ys()[CurrentRow()])); break; } - case WIDTH: { + case Index::WIDTH: { sqlite3_result_int(context_, static_cast(dynamicFrameObj_.Widths()[CurrentRow()])); break; } - case HEIGHT: { + case Index::HEIGHT: { sqlite3_result_int(context_, static_cast(dynamicFrameObj_.Heights()[CurrentRow()])); break; } - case ALPHA: { + case Index::ALPHA: { if (dynamicFrameObj_.Alphas()[CurrentRow()] != INVALID_UINT64) { const std::string& str = dataCache_->GetDataFromDict(static_cast(dynamicFrameObj_.Alphas()[CurrentRow()])); @@ -77,7 +77,7 @@ int32_t DynamicFrameTable::Cursor::Column(int32_t col) const } break; } - case NAME: { + case Index::NAME: { if (dynamicFrameObj_.Names()[CurrentRow()] != INVALID_UINT64) { const std::string& str = dataCache_->GetDataFromDict(static_cast(dynamicFrameObj_.Names()[CurrentRow()])); @@ -85,7 +85,7 @@ int32_t DynamicFrameTable::Cursor::Column(int32_t col) const } break; } - case END_TIME: + case Index::END_TIME: if (dynamicFrameObj_.EndTimes()[CurrentRow()] != INVALID_TIME) { sqlite3_result_int64(context_, static_cast(dynamicFrameObj_.EndTimes()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ftrace/filter_table.cpp b/trace_streamer/src/table/ftrace/filter_table.cpp index 9d12b0c1..d08bb9d3 100644 --- a/trace_streamer/src/table/ftrace/filter_table.cpp +++ b/trace_streamer/src/table/ftrace/filter_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, SOURCE_ARG_SET_ID }; +enum class Index : int32_t { ID = 0, TYPE, NAME, SOURCE_ARG_SET_ID }; FilterTable::FilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -56,8 +56,8 @@ void FilterTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -76,8 +76,8 @@ void FilterTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -118,8 +118,8 @@ int32_t FilterTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -130,8 +130,8 @@ int32_t FilterTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -144,17 +144,17 @@ int32_t FilterTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** int32_t FilterTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, CurrentRow()); // IdsData() will be optimized break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, filterObj_.TypeData()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case NAME: + case Index::NAME: sqlite3_result_text(context_, filterObj_.NameData()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case SOURCE_ARG_SET_ID: + case Index::SOURCE_ARG_SET_ID: sqlite3_result_int64(context_, static_cast(filterObj_.SourceArgSetIdData()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ftrace/frame_maps_table.cpp b/trace_streamer/src/table/ftrace/frame_maps_table.cpp index 98962f92..dba0f0bb 100644 --- a/trace_streamer/src/table/ftrace/frame_maps_table.cpp +++ b/trace_streamer/src/table/ftrace/frame_maps_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, SRC_ROW, DST_ROW }; +enum class Index : int32_t { ID = 0, SRC_ROW, DST_ROW }; FrameMapsTable::FrameMapsTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -55,8 +55,8 @@ void FrameMapsTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInf ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -75,8 +75,8 @@ void FrameMapsTable::FilterByConstraint(FilterConstraints& fc, double& filterCos break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -117,15 +117,15 @@ int32_t FrameMapsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case SRC_ROW: + case Index::SRC_ROW: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), frameMapsObj_.SrcIndexs()); break; - case DST_ROW: + case Index::DST_ROW: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameMapsObj_.DstIndexs()); break; default: @@ -136,8 +136,8 @@ int32_t FrameMapsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -150,14 +150,14 @@ int32_t FrameMapsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu int32_t FrameMapsTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case SRC_ROW: + case Index::SRC_ROW: sqlite3_result_int64(context_, static_cast(frameMapsObj_.SrcIndexs()[CurrentRow()])); break; - case DST_ROW: + case Index::DST_ROW: sqlite3_result_int64(context_, static_cast(frameMapsObj_.DstIndexs()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ftrace/frame_slice_table.cpp b/trace_streamer/src/table/ftrace/frame_slice_table.cpp index 39d70caa..de37a6c4 100644 --- a/trace_streamer/src/table/ftrace/frame_slice_table.cpp +++ b/trace_streamer/src/table/ftrace/frame_slice_table.cpp @@ -17,7 +17,22 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TS, VSYNC, IPID, ITID, CALLSTACK_ID, DUR, SRC, DST, TYPE, TYPE_DESC, FLAG, DEPTH, FRAME_NO }; +enum class Index : int32_t { + ID = 0, + TS, + VSYNC, + IPID, + ITID, + CALLSTACK_ID, + DUR, + SRC, + DST, + TYPE, + TYPE_DESC, + FLAG, + DEPTH, + FRAME_NO +}; FrameSliceTable::FrameSliceTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -66,8 +81,8 @@ void FrameSliceTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -86,8 +101,8 @@ void FrameSliceTable::FilterByConstraint(FilterConstraints& fc, double& filterCo break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -128,37 +143,37 @@ int32_t FrameSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case ITID: + case Index::ITID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.InternalTidsData()); break; - case IPID: + case Index::IPID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.Ipids()); break; - case VSYNC: + case Index::VSYNC: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.VsyncIds()); break; - case CALLSTACK_ID: + case Index::CALLSTACK_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.CallStackIds()); break; - case DUR: + case Index::DUR: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.Durs()); break; - case TYPE: + case Index::TYPE: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.Types()); break; - case FLAG: + case Index::FLAG: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.Flags()); break; - case DEPTH: + case Index::DEPTH: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.Depths()); break; - case FRAME_NO: + case Index::FRAME_NO: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), frameSliceObj_.FrameNos()); break; default: @@ -169,8 +184,8 @@ int32_t FrameSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -183,57 +198,57 @@ int32_t FrameSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val int32_t FrameSliceTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(frameSliceObj_.TimeStampData()[CurrentRow()])); break; - case VSYNC: + case Index::VSYNC: sqlite3_result_int64(context_, static_cast(frameSliceObj_.VsyncIds()[CurrentRow()])); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, static_cast(frameSliceObj_.Ipids()[CurrentRow()])); break; - case ITID: + case Index::ITID: sqlite3_result_int64(context_, static_cast(frameSliceObj_.InternalTidsData()[CurrentRow()])); break; - case CALLSTACK_ID: + case Index::CALLSTACK_ID: sqlite3_result_int64(context_, static_cast(frameSliceObj_.CallStackIds()[CurrentRow()])); break; - case DUR: + case Index::DUR: if (frameSliceObj_.Durs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(frameSliceObj_.Durs()[CurrentRow()])); } break; - case SRC: + case Index::SRC: sqlite3_result_text(context_, frameSliceObj_.Srcs()[CurrentRow()].c_str(), frameSliceObj_.Srcs()[CurrentRow()].length(), nullptr); break; - case DST: + case Index::DST: if (frameSliceObj_.Dsts()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(frameSliceObj_.Dsts()[CurrentRow()])); } break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(frameSliceObj_.Types()[CurrentRow()])); break; - case TYPE_DESC: + case Index::TYPE_DESC: sqlite3_result_text(context_, frameSliceObj_.Types()[CurrentRow()] == 0 ? "actural" : "expect", STR_DEFAULT_LEN, nullptr); break; - case FLAG: + case Index::FLAG: if (frameSliceObj_.Flags()[CurrentRow()] != INVALID_UINT8) { sqlite3_result_int(context_, static_cast(frameSliceObj_.Flags()[CurrentRow()])); } break; - case DEPTH: + case Index::DEPTH: if (frameSliceObj_.Depths()[CurrentRow()] != INVALID_UINT8) { sqlite3_result_int(context_, static_cast(frameSliceObj_.Depths()[CurrentRow()])); } break; - case FRAME_NO: + case Index::FRAME_NO: if (frameSliceObj_.FrameNos()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int(context_, static_cast(frameSliceObj_.FrameNos()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ftrace/gpu_slice_table.cpp b/trace_streamer/src/table/ftrace/gpu_slice_table.cpp index d96aa4cd..c2df87ca 100644 --- a/trace_streamer/src/table/ftrace/gpu_slice_table.cpp +++ b/trace_streamer/src/table/ftrace/gpu_slice_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, FRAME_ROW, DUR }; +enum class Index : int32_t { ID = 0, FRAME_ROW, DUR }; GPUSliceTable::GPUSliceTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -55,8 +55,8 @@ void GPUSliceTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -75,8 +75,8 @@ void GPUSliceTable::FilterByConstraint(FilterConstraints& fc, double& filterCost break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -117,14 +117,14 @@ int32_t GPUSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case FRAME_ROW: + case Index::FRAME_ROW: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), gpuSliceObj_.FrameRows()); break; - case DUR: + case Index::DUR: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), gpuSliceObj_.Durs()); break; default: @@ -135,8 +135,8 @@ int32_t GPUSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -149,14 +149,14 @@ int32_t GPUSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value int32_t GPUSliceTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case FRAME_ROW: + case Index::FRAME_ROW: sqlite3_result_int64(context_, static_cast(gpuSliceObj_.FrameRows()[CurrentRow()])); break; - case DUR: + case Index::DUR: if (gpuSliceObj_.Durs()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(gpuSliceObj_.Durs()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ftrace/instants_table.cpp b/trace_streamer/src/table/ftrace/instants_table.cpp index 18c41a97..5cf06270 100644 --- a/trace_streamer/src/table/ftrace/instants_table.cpp +++ b/trace_streamer/src/table/ftrace/instants_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { TS = 0, NAME, REF, WAKEUP_FROM, REF_TYPE, VALUE }; +enum class Index : int32_t { TS = 0, NAME, REF, WAKEUP_FROM, REF_TYPE, VALUE }; InstantsTable::InstantsTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("ts", "INTEGER")); @@ -73,14 +73,14 @@ void InstantsTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::TS: break; - case NAME: + case Index::NAME: break; - case REF: + case Index::REF: break; - case WAKEUP_FROM: + case Index::WAKEUP_FROM: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -99,8 +99,8 @@ void InstantsTable::FilterByConstraint(FilterConstraints& fc, double& filterCost break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case TS: { + switch (static_cast(c.col)) { + case Index::TS: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -145,21 +145,21 @@ int32_t InstantsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case TS: + switch (static_cast(c.col)) { + case Index::TS: FilterTS(c.op, argv[i], InstantsObj_.TimeStampData()); break; - case NAME: + case Index::NAME: indexMap_->MixRange(c.op, dataCache_->GetConstDataIndex( std::string(reinterpret_cast(sqlite3_value_text(argv[i])))), InstantsObj_.NameIndexsData()); break; - case REF: + case Index::REF: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), InstantsObj_.InternalTidsData()); break; - case WAKEUP_FROM: + case Index::WAKEUP_FROM: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), InstantsObj_.WakeupFromPidsData()); break; @@ -171,17 +171,17 @@ int32_t InstantsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::TS: indexMap_->SortBy(orderbys[i].desc); break; - case NAME: + case Index::NAME: indexMap_->SortBy(orderbys[i].desc); break; - case REF: + case Index::REF: indexMap_->SortBy(orderbys[i].desc); break; - case WAKEUP_FROM: + case Index::WAKEUP_FROM: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -195,26 +195,26 @@ int32_t InstantsTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value int32_t InstantsTable::Cursor::Column(int32_t column) const { size_t stringIdentity = static_cast(InstantsObj_.NameIndexsData()[CurrentRow()]); - switch (column) { - case TS: + switch (static_cast(column)) { + case Index::TS: sqlite3_result_int64(context_, static_cast(InstantsObj_.TimeStampData()[CurrentRow()])); break; - case NAME: { + case Index::NAME: { sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case REF: + case Index::REF: sqlite3_result_int64(context_, static_cast(InstantsObj_.InternalTidsData()[CurrentRow()])); break; - case WAKEUP_FROM: + case Index::WAKEUP_FROM: sqlite3_result_int64(context_, static_cast(InstantsObj_.WakeupFromPidsData()[CurrentRow()])); break; - case REF_TYPE: { + case Index::REF_TYPE: { sqlite3_result_text(context_, "itid", STR_DEFAULT_LEN, nullptr); break; } - case VALUE: { + case Index::VALUE: { sqlite3_result_double(context_, 0.0); break; } diff --git a/trace_streamer/src/table/ftrace/irq_table.cpp b/trace_streamer/src/table/ftrace/irq_table.cpp index f99ec2b4..08470ce7 100644 --- a/trace_streamer/src/table/ftrace/irq_table.cpp +++ b/trace_streamer/src/table/ftrace/irq_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, TS, DUR, @@ -85,8 +85,8 @@ void IrqTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei) ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -105,8 +105,8 @@ void IrqTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, siz break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -147,8 +147,8 @@ int32_t IrqTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** ar auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; default: @@ -159,8 +159,8 @@ int32_t IrqTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** ar auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -173,20 +173,20 @@ int32_t IrqTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** ar int32_t IrqTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, CurrentRow()); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(slicesObj_.TimeStampData()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(slicesObj_.DursData()[CurrentRow()])); break; - case CALL_ID: + case Index::CALL_ID: sqlite3_result_int64(context_, static_cast(slicesObj_.CallIds()[CurrentRow()])); break; - case CAT: { + case Index::CAT: { if (slicesObj_.CatsData()[CurrentRow()] != INVALID_UINT64) { auto catsDataIndex = static_cast(slicesObj_.CatsData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(catsDataIndex).c_str(), STR_DEFAULT_LEN, @@ -194,7 +194,7 @@ int32_t IrqTable::Cursor::Column(int32_t column) const } break; } - case NAME: { + case Index::NAME: { if (slicesObj_.NamesData()[CurrentRow()] != INVALID_UINT64) { auto nameDataIndex = static_cast(slicesObj_.NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(nameDataIndex).c_str(), STR_DEFAULT_LEN, @@ -202,38 +202,38 @@ int32_t IrqTable::Cursor::Column(int32_t column) const } break; } - case DEPTH: + case Index::DEPTH: sqlite3_result_int64(context_, static_cast(slicesObj_.Depths()[CurrentRow()])); break; - case COOKIE_ID: + case Index::COOKIE_ID: if (slicesObj_.Cookies()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(slicesObj_.Cookies()[CurrentRow()])); } break; - case PARENT_ID: { + case Index::PARENT_ID: { if (slicesObj_.ParentIdData()[CurrentRow()].has_value()) { sqlite3_result_int64(context_, static_cast(slicesObj_.ParentIdData()[CurrentRow()].value())); } break; } - case ARGSET: + case Index::ARGSET: if (slicesObj_.ArgSetIdsData()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(slicesObj_.ArgSetIdsData()[CurrentRow()])); } break; - case CHAIN_ID: + case Index::CHAIN_ID: sqlite3_result_text(context_, slicesObj_.ChainIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case SPAN_ID: + case Index::SPAN_ID: sqlite3_result_text(context_, slicesObj_.SpanIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case PARENT_SPAN_ID: + case Index::PARENT_SPAN_ID: sqlite3_result_text(context_, slicesObj_.ParentSpanIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case FLAG: + case Index::FLAG: sqlite3_result_text(context_, slicesObj_.Flags()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case ARGS: + case Index::ARGS: sqlite3_result_text(context_, slicesObj_.ArgsData()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/ftrace/measure_filter_table.cpp b/trace_streamer/src/table/ftrace/measure_filter_table.cpp index ff8a943b..c2855662 100644 --- a/trace_streamer/src/table/ftrace/measure_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/measure_filter_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, INTERNAL_TID }; +enum class Index : int32_t { ID = 0, TYPE, NAME, INTERNAL_TID }; MeasureFilterTable::MeasureFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -43,22 +43,22 @@ MeasureFilterTable::Cursor::~Cursor() {} int32_t MeasureFilterTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64( context_, static_cast(dataCache_->GetConstThreadMeasureFilterData().FilterIdData()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "thread_measure_filter", STR_DEFAULT_LEN, nullptr); break; - case NAME: { + case Index::NAME: { const std::string& str = dataCache_->GetDataFromDict( dataCache_->GetConstThreadMeasureFilterData().NameIndexData()[CurrentRow()]); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } - case INTERNAL_TID: + case Index::INTERNAL_TID: sqlite3_result_int64( context_, static_cast(dataCache_->GetConstThreadMeasureFilterData().InternalTidData()[CurrentRow()])); diff --git a/trace_streamer/src/table/ftrace/measure_table.cpp b/trace_streamer/src/table/ftrace/measure_table.cpp index d4c41138..40a7917c 100644 --- a/trace_streamer/src/table/ftrace/measure_table.cpp +++ b/trace_streamer/src/table/ftrace/measure_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { TYPE = 0, TS, DUR, VALUE, FILTER_ID }; +enum class Index : int32_t { TYPE = 0, TS, DUR, VALUE, FILTER_ID }; MeasureTable::MeasureTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("type", "TEXT")); @@ -83,8 +83,8 @@ void MeasureTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::TS: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -103,8 +103,8 @@ void MeasureTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case TS: { + switch (static_cast(c.col)) { + case Index::TS: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -150,11 +150,11 @@ int32_t MeasureTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case TS: + switch (static_cast(c.col)) { + case Index::TS: FilterTS(c.op, argv[i], measureObj.TimeStampData()); break; - case FILTER_ID: + case Index::FILTER_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), measureObj.FilterIdData()); break; default: @@ -165,11 +165,11 @@ int32_t MeasureTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::TS: indexMap_->SortBy(orderbys[i].desc); break; - case FILTER_ID: + case Index::FILTER_ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -182,22 +182,22 @@ int32_t MeasureTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* int32_t MeasureTable::Cursor::Column(int32_t column) const { - switch (column) { - case TYPE: + switch (static_cast(column)) { + case Index::TYPE: sqlite3_result_text(context_, "measure", STR_DEFAULT_LEN, nullptr); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(measureObj.TimeStampData()[CurrentRow()])); break; - case DUR: + case Index::DUR: if (measureObj.DursData()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(measureObj.DursData()[CurrentRow()])); } break; - case VALUE: + case Index::VALUE: sqlite3_result_int64(context_, static_cast(measureObj.ValuesData()[CurrentRow()])); break; - case FILTER_ID: + case Index::FILTER_ID: sqlite3_result_int64(context_, static_cast(measureObj.FilterIdData()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ftrace/process_filter_table.cpp b/trace_streamer/src/table/ftrace/process_filter_table.cpp index de64a289..22a57392 100644 --- a/trace_streamer/src/table/ftrace/process_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/process_filter_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, INTERNAL_PID }; +enum class Index : int32_t { ID = 0, TYPE, NAME, INTERNAL_PID }; ProcessFilterTable::ProcessFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -44,20 +44,20 @@ ProcessFilterTable::Cursor::~Cursor() {} int32_t ProcessFilterTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(processFilterObj_.IdsData()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "process_filter", STR_DEFAULT_LEN, nullptr); break; - case NAME: { + case Index::NAME: { DataIndex stringIdentity = static_cast(processFilterObj_.NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(stringIdentity).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case INTERNAL_PID: + case Index::INTERNAL_PID: sqlite3_result_int64(context_, static_cast(processFilterObj_.UpidsData()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ftrace/process_measure_filter_table.cpp b/trace_streamer/src/table/ftrace/process_measure_filter_table.cpp index 11f3d337..61738826 100644 --- a/trace_streamer/src/table/ftrace/process_measure_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/process_measure_filter_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, INTERNAL_PID }; +enum class Index : int32_t { ID = 0, TYPE, NAME, INTERNAL_PID }; ProcessMeasureFilterTable::ProcessMeasureFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -58,8 +58,8 @@ void ProcessMeasureFilterTable::EstimateFilterCost(FilterConstraints& fc, Estima ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -78,8 +78,8 @@ void ProcessMeasureFilterTable::FilterByConstraint(FilterConstraints& fc, double break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -138,16 +138,16 @@ int32_t ProcessMeasureFilterTable::Cursor::Filter(const FilterConstraints& fc, s auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), dataCache_->GetConstProcessMeasureFilterData().IdsData()); break; - case INTERNAL_PID: + case Index::INTERNAL_PID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), dataCache_->GetConstProcessMeasureFilterData().UpidsData()); break; - case NAME: + case Index::NAME: indexMap_->MixRange(c.op, dataCache_->GetConstDataIndex( std::string(reinterpret_cast(sqlite3_value_text(argv[i])))), @@ -161,8 +161,8 @@ int32_t ProcessMeasureFilterTable::Cursor::Filter(const FilterConstraints& fc, s auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -175,21 +175,21 @@ int32_t ProcessMeasureFilterTable::Cursor::Filter(const FilterConstraints& fc, s int32_t ProcessMeasureFilterTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast( dataCache_->GetConstProcessMeasureFilterData().IdsData()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "process_measure_filter", STR_DEFAULT_LEN, nullptr); break; - case NAME: { + case Index::NAME: { size_t strId = static_cast(dataCache_->GetConstProcessMeasureFilterData().NamesData()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(strId).c_str(), STR_DEFAULT_LEN, nullptr); break; } - case INTERNAL_PID: + case Index::INTERNAL_PID: sqlite3_result_int64( context_, static_cast(dataCache_->GetConstProcessMeasureFilterData().UpidsData()[CurrentRow()])); diff --git a/trace_streamer/src/table/ftrace/process_table.cpp b/trace_streamer/src/table/ftrace/process_table.cpp index 9be2d5b0..eb3339fb 100644 --- a/trace_streamer/src/table/ftrace/process_table.cpp +++ b/trace_streamer/src/table/ftrace/process_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, IPID, TYPE, @@ -76,9 +76,9 @@ void ProcessTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case IPID: - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::IPID: + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -97,9 +97,9 @@ void ProcessTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case IPID: - case ID: { + switch (static_cast(c.col)) { + case Index::IPID: + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -128,7 +128,7 @@ int32_t ProcessTable::Update(int32_t argc, sqlite3_value** argv, sqlite3_int64* constexpr int32_t colOffset = 2; for (auto i = colOffset; i < argc; i++) { auto col = i - colOffset; - if (col != NAME) { + if (static_cast(col) != Index::NAME) { continue; } const char* name = reinterpret_cast(sqlite3_value_text(argv[i])); @@ -166,12 +166,12 @@ int32_t ProcessTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: - case IPID: + switch (static_cast(c.col)) { + case Index::ID: + case Index::IPID: FilterId(c.op, argv[i]); break; - case PID: + case Index::PID: FilterIndex(c.col, c.op, argv[i]); break; default: @@ -182,9 +182,9 @@ int32_t ProcessTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: - case IPID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: + case Index::IPID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -198,39 +198,39 @@ int32_t ProcessTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value* int32_t ProcessTable::Cursor::Column(int32_t col) const { const auto& process = dataCache_->GetConstProcessData(CurrentRow()); - switch (col) { - case ID: - case IPID: + switch (static_cast(col)) { + case Index::ID: + case Index::IPID: sqlite3_result_int64(context_, CurrentRow()); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "process", STR_DEFAULT_LEN, nullptr); break; - case PID: + case Index::PID: sqlite3_result_int64(context_, process.pid_); break; - case NAME: + case Index::NAME: if (process.cmdLine_.size()) { sqlite3_result_text(context_, process.cmdLine_.c_str(), static_cast(process.cmdLine_.length()), nullptr); } break; - case START_TS: + case Index::START_TS: if (process.startT_) { sqlite3_result_int64(context_, static_cast(process.startT_)); } break; - case SWITCH_COUNT: - case SWTICH_COUNT: + case Index::SWITCH_COUNT: + case Index::SWTICH_COUNT: sqlite3_result_int64(context_, process.switchCount_); break; - case THREAD_COUNT: + case Index::THREAD_COUNT: sqlite3_result_int64(context_, process.threadCount_); break; - case SLICE_COUNT: + case Index::SLICE_COUNT: sqlite3_result_int64(context_, process.sliceSize_); break; - case MEM_COUNT: + case Index::MEM_COUNT: sqlite3_result_int64(context_, process.memSize_); break; default: @@ -294,8 +294,8 @@ void ProcessTable::Cursor::FilterPid(unsigned char op, uint64_t value) } void ProcessTable::Cursor::FilterIndex(int32_t col, unsigned char op, sqlite3_value* argv) { - switch (col) { - case PID: + switch (static_cast(col)) { + case Index::PID: /* code */ FilterPid(op, static_cast(sqlite3_value_int64(argv))); break; diff --git a/trace_streamer/src/table/ftrace/raw_table.cpp b/trace_streamer/src/table/ftrace/raw_table.cpp index 4084939b..bc5043b9 100644 --- a/trace_streamer/src/table/ftrace/raw_table.cpp +++ b/trace_streamer/src/table/ftrace/raw_table.cpp @@ -16,7 +16,7 @@ #include "raw_table.h" namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, TS, NAME, CPU, INTERNAL_TID }; +enum class Index : int32_t { ID = 0, TYPE, TS, NAME, CPU, INTERNAL_TID }; enum RawType { RAW_CPU_IDLE = 1, RAW_SCHED_WAKEUP = 2, RAW_SCHED_WAKING = 3 }; uint32_t GetNameIndex(const std::string& name) { @@ -70,8 +70,8 @@ void RawTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei) ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -90,8 +90,8 @@ void RawTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, siz break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -131,19 +131,19 @@ int32_t RawTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** ar auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case NAME: + case Index::NAME: indexMap_->MixRange( c.op, GetNameIndex(std::string(reinterpret_cast(sqlite3_value_text(argv[i])))), rawObj_.NameData()); break; - case TS: + case Index::TS: FilterTS(c.op, argv[i], rawObj_.TimeStampData()); break; - case INTERNAL_TID: + case Index::INTERNAL_TID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), rawObj_.InternalTidsData()); break; @@ -155,8 +155,8 @@ int32_t RawTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** ar auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -169,17 +169,17 @@ int32_t RawTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** ar int32_t RawTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "raw", STR_DEFAULT_LEN, nullptr); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(rawObj_.TimeStampData()[CurrentRow()])); break; - case NAME: { + case Index::NAME: { if (rawObj_.NameData()[CurrentRow()] == RAW_CPU_IDLE) { sqlite3_result_text(context_, "cpu_idle", STR_DEFAULT_LEN, nullptr); } else if (rawObj_.NameData()[CurrentRow()] == RAW_SCHED_WAKEUP) { @@ -189,10 +189,10 @@ int32_t RawTable::Cursor::Column(int32_t column) const } break; } - case CPU: + case Index::CPU: sqlite3_result_int64(context_, static_cast(rawObj_.CpuData()[CurrentRow()])); break; - case INTERNAL_TID: + case Index::INTERNAL_TID: sqlite3_result_int64(context_, static_cast(rawObj_.InternalTidData()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ftrace/sched_slice_table.cpp b/trace_streamer/src/table/ftrace/sched_slice_table.cpp index c9ece1c8..afa7a31a 100644 --- a/trace_streamer/src/table/ftrace/sched_slice_table.cpp +++ b/trace_streamer/src/table/ftrace/sched_slice_table.cpp @@ -19,7 +19,19 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, TS, DUR, TS_END, CPU, INTERNAL_TID, INTERNAL_PID, END_STATE, PRIORITY, ARGSETID }; +enum class Index : int32_t { + ID = 0, + TYPE, + TS, + DUR, + TS_END, + CPU, + INTERNAL_TID, + INTERNAL_PID, + END_STATE, + PRIORITY, + ARGSETID +}; SchedSliceTable::SchedSliceTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -65,9 +77,9 @@ void SchedSliceTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: + case Index::TS: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -86,8 +98,8 @@ void SchedSliceTable::FilterByConstraint(FilterConstraints& fc, double& filterCo break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -96,7 +108,7 @@ void SchedSliceTable::FilterByConstraint(FilterConstraints& fc, double& filterCo } break; } - case TS: { + case Index::TS: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -156,25 +168,25 @@ int32_t SchedSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case TS: + case Index::TS: FilterTS(c.op, argv[i], schedSliceObj_.TimeStampData()); break; - case CPU: + case Index::CPU: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), schedSliceObj_.CpusData()); break; - case INTERNAL_TID: + case Index::INTERNAL_TID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), schedSliceObj_.InternalTidsData()); break; - case INTERNAL_PID: + case Index::INTERNAL_PID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), schedSliceObj_.InternalPidsData()); break; - case DUR: + case Index::DUR: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), schedSliceObj_.DursData()); break; @@ -186,9 +198,9 @@ int32_t SchedSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: + case Index::TS: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -201,40 +213,40 @@ int32_t SchedSliceTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val int32_t SchedSliceTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "sched_slice", STR_DEFAULT_LEN, nullptr); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(schedSliceObj_.TimeStampData()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(schedSliceObj_.DursData()[CurrentRow()])); break; - case TS_END: + case Index::TS_END: sqlite3_result_int64(context_, static_cast(schedSliceObj_.TsEndData()[CurrentRow()])); break; - case CPU: + case Index::CPU: sqlite3_result_int64(context_, static_cast(schedSliceObj_.CpusData()[CurrentRow()])); break; - case INTERNAL_TID: + case Index::INTERNAL_TID: sqlite3_result_int64(context_, static_cast(schedSliceObj_.InternalTidsData()[CurrentRow()])); break; - case INTERNAL_PID: + case Index::INTERNAL_PID: sqlite3_result_int64(context_, static_cast(schedSliceObj_.InternalPidsData()[CurrentRow()])); break; - case END_STATE: { + case Index::END_STATE: { const std::string& str = dataCache_->GetConstSchedStateData(schedSliceObj_.EndStatesData()[CurrentRow()]); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } - case PRIORITY: + case Index::PRIORITY: sqlite3_result_int64(context_, static_cast(schedSliceObj_.PriorityData()[CurrentRow()])); break; - case ARGSETID: { + case Index::ARGSETID: { const uint32_t& argSetId = schedSliceObj_.ArgSetData()[CurrentRow()]; if (argSetId != INVALID_UINT32) { sqlite3_result_int(context_, argSetId); diff --git a/trace_streamer/src/table/ftrace/so_static_initalization_table.cpp b/trace_streamer/src/table/ftrace/so_static_initalization_table.cpp index fcb088df..6b9c7e38 100644 --- a/trace_streamer/src/table/ftrace/so_static_initalization_table.cpp +++ b/trace_streamer/src/table/ftrace/so_static_initalization_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, IPID, TID, CALL_ID, START_TIME, END_TIME, SO_NAME, DEPTH }; +enum class Index : int32_t { ID = 0, IPID, TID, CALL_ID, START_TIME, END_TIME, SO_NAME, DEPTH }; SoStaticInitalizationTable::SoStaticInitalizationTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -48,31 +48,31 @@ SoStaticInitalizationTable::Cursor::~Cursor() {} int32_t SoStaticInitalizationTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, static_cast(staticInitalizationObj_.Pids()[CurrentRow()])); break; - case TID: + case Index::TID: sqlite3_result_int64(context_, static_cast(staticInitalizationObj_.Tids()[CurrentRow()])); break; - case CALL_ID: + case Index::CALL_ID: sqlite3_result_int64(context_, static_cast(staticInitalizationObj_.CallIds()[CurrentRow()])); break; - case START_TIME: + case Index::START_TIME: sqlite3_result_int64(context_, static_cast(staticInitalizationObj_.StartTimes()[CurrentRow()])); break; - case END_TIME: + case Index::END_TIME: sqlite3_result_int64(context_, static_cast(staticInitalizationObj_.EndTimes()[CurrentRow()])); break; - case SO_NAME: + case Index::SO_NAME: sqlite3_result_text(context_, dataCache_->GetDataFromDict(staticInitalizationObj_.SoNames()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); break; - case DEPTH: + case Index::DEPTH: sqlite3_result_int64(context_, static_cast(staticInitalizationObj_.Depths()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/ftrace/system_call_table.cpp b/trace_streamer/src/table/ftrace/system_call_table.cpp index 27438d6e..73e5988c 100644 --- a/trace_streamer/src/table/ftrace/system_call_table.cpp +++ b/trace_streamer/src/table/ftrace/system_call_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { SYSCALL_NUM = 0, TYPE, IPID, TS, RET }; +enum class Index : int32_t { SYSCALL_NUM = 0, TYPE, IPID, TS, RET }; SystemCallTable::SystemCallTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("syscall_num", "INTEGER")); @@ -45,21 +45,21 @@ SystemCallTable::Cursor::~Cursor() {} int32_t SystemCallTable::Cursor::Column(int32_t column) const { - switch (column) { - case SYSCALL_NUM: + switch (static_cast(column)) { + case Index::SYSCALL_NUM: sqlite3_result_int64(context_, dataCache_->GetConstSysCallData().SysCallsData()[CurrentRow()]); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, dataCache_->GetDataFromDict(sysCallObj_.TypesData()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, dataCache_->GetConstSysCallData().IpidsData()[CurrentRow()]); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, dataCache_->GetConstSysCallData().TimeStampData()[CurrentRow()]); break; - case RET: + case Index::RET: sqlite3_result_int64(context_, dataCache_->GetConstSysCallData().RetsData()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/ftrace/system_event_filter_table.cpp b/trace_streamer/src/table/ftrace/system_event_filter_table.cpp index c669786d..73003106 100644 --- a/trace_streamer/src/table/ftrace/system_event_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/system_event_filter_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME }; +enum class Index : int32_t { ID = 0, TYPE, NAME }; SystemEventFilterTable::SystemEventFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -57,8 +57,8 @@ void SystemEventFilterTable::EstimateFilterCost(FilterConstraints& fc, Estimated ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -77,8 +77,8 @@ void SystemEventFilterTable::FilterByConstraint(FilterConstraints& fc, double& f break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -138,8 +138,8 @@ int32_t SystemEventFilterTable::Cursor::Filter(const FilterConstraints& fc, sqli auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterSorted(c.col, c.op, argv[i]); break; default: @@ -150,8 +150,8 @@ int32_t SystemEventFilterTable::Cursor::Filter(const FilterConstraints& fc, sqli auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -164,15 +164,15 @@ int32_t SystemEventFilterTable::Cursor::Filter(const FilterConstraints& fc, sqli int32_t SystemEventFilterTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, sysEventObj_.IdsData()[CurrentRow()]); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, dataCache_->GetDataFromDict(sysEventObj_.TypesData()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); break; - case NAME: + case Index::NAME: sqlite3_result_text(context_, dataCache_->GetDataFromDict(sysEventObj_.NamesData()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); break; @@ -192,8 +192,8 @@ void SystemEventFilterTable::Cursor::FilterSorted(int32_t col, unsigned char op, return; } - switch (col) { - case ID: { + switch (static_cast(col)) { + case Index::ID: { auto v = static_cast(sqlite3_value_int64(argv)); auto getValue = [](const uint32_t& row) { return row; }; switch (op) { diff --git a/trace_streamer/src/table/ftrace/task_pool_table.cpp b/trace_streamer/src/table/ftrace/task_pool_table.cpp index 2d6d8c58..20cf42f8 100644 --- a/trace_streamer/src/table/ftrace/task_pool_table.cpp +++ b/trace_streamer/src/table/ftrace/task_pool_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, ALLOCATION_TASK_ROW, EXECUTE_TASK_ROW, @@ -65,72 +65,72 @@ TaskPoolTable::Cursor::~Cursor() {} int32_t TaskPoolTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case ALLOCATION_TASK_ROW: + case Index::ALLOCATION_TASK_ROW: if (taskPoolObj_.AllocationTaskRows()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64( context_, static_cast(dataCache_->GetConstTaskPoolData().AllocationTaskRows()[CurrentRow()])); } break; - case EXECUTE_TASK_ROW: + case Index::EXECUTE_TASK_ROW: if (taskPoolObj_.ExecuteTaskRows()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ExecuteTaskRows()[CurrentRow()])); } break; - case RETURN_TASK_ROW: + case Index::RETURN_TASK_ROW: if (taskPoolObj_.ReturnTaskRows()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ReturnTaskRows()[CurrentRow()])); } break; - case ALLOCATION_ITID: + case Index::ALLOCATION_ITID: if (taskPoolObj_.AllocationItids()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().AllocationItids()[CurrentRow()])); } break; - case EXECUTE_ITID: + case Index::EXECUTE_ITID: if (taskPoolObj_.ExecuteItids()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ExecuteItids()[CurrentRow()])); } break; - case RETURN_ITID: + case Index::RETURN_ITID: if (taskPoolObj_.ReturnItids()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ReturnItids()[CurrentRow()])); } break; - case EXECUTE_ID: + case Index::EXECUTE_ID: if (taskPoolObj_.ExecuteIds()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ExecuteIds()[CurrentRow()])); } break; - case PRIORITY: + case Index::PRIORITY: if (taskPoolObj_.Prioritys()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64( context_, static_cast(dataCache_->GetConstTaskPoolData().Prioritys()[CurrentRow()])); } break; - case EXECUTE_STATE: + case Index::EXECUTE_STATE: if (taskPoolObj_.ExecuteStates()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ExecuteStates()[CurrentRow()])); } break; - case RETURN_STATE: + case Index::RETURN_STATE: if (taskPoolObj_.ReturnStates()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().ReturnStates()[CurrentRow()])); } break; - case TIMEOUT_ROW: + case Index::TIMEOUT_ROW: if (taskPoolObj_.TimeoutRows()[CurrentRow()] != INVALID_INT32) { sqlite3_result_int64(context_, static_cast( dataCache_->GetConstTaskPoolData().TimeoutRows()[CurrentRow()])); diff --git a/trace_streamer/src/table/ftrace/thread_filter_table.cpp b/trace_streamer/src/table/ftrace/thread_filter_table.cpp index 3698e765..067149b1 100644 --- a/trace_streamer/src/table/ftrace/thread_filter_table.cpp +++ b/trace_streamer/src/table/ftrace/thread_filter_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, NAME, INTERNAL_TID }; +enum class Index : int32_t { ID = 0, TYPE, NAME, INTERNAL_TID }; ThreadFilterTable::ThreadFilterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -43,21 +43,21 @@ ThreadFilterTable::Cursor::~Cursor() {} int32_t ThreadFilterTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast( dataCache_->GetConstThreadFilterData().FilterIdData()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "thread_filter", STR_DEFAULT_LEN, nullptr); break; - case NAME: { + case Index::NAME: { std::string str = dataCache_->GetDataFromDict(dataCache_->GetConstThreadFilterData().NameIndexData()[CurrentRow()]); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } - case INTERNAL_TID: + case Index::INTERNAL_TID: sqlite3_result_int64(context_, static_cast( dataCache_->GetConstThreadFilterData().InternalTidData()[CurrentRow()])); break; diff --git a/trace_streamer/src/table/ftrace/thread_state_table.cpp b/trace_streamer/src/table/ftrace/thread_state_table.cpp index a9427a0e..98f3196f 100644 --- a/trace_streamer/src/table/ftrace/thread_state_table.cpp +++ b/trace_streamer/src/table/ftrace/thread_state_table.cpp @@ -20,7 +20,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TYPE, TS, DUR, CPU, INTERNAL_TID, TID, PID, STATE, ARGSETID }; +enum class Index : int32_t { ID = 0, TYPE, TS, DUR, CPU, INTERNAL_TID, TID, PID, STATE, ARGSETID }; ThreadStateTable::ThreadStateTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -65,9 +65,9 @@ void ThreadStateTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexI ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: + case Index::TS: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -86,8 +86,8 @@ void ThreadStateTable::FilterByConstraint(FilterConstraints& fc, double& filterC break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -96,7 +96,7 @@ void ThreadStateTable::FilterByConstraint(FilterConstraints& fc, double& filterC } break; } - case TS: { + case Index::TS: { auto oldRowCount = rowCount; if (CanFilterSorted(c.op, rowCount)) { fc.UpdateConstraint(i, true); @@ -157,40 +157,40 @@ int32_t ThreadStateTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_va auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: indexMapBack->FilterId(c.op, argv[i]); break; - case TS: + case Index::TS: indexMapBack->FilterTS(c.op, argv[i], threadStateObj_.TimeStamsData()); break; - case INTERNAL_TID: + case Index::INTERNAL_TID: indexMapBack->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), threadStateObj_.ItidsData()); break; - case TID: + case Index::TID: indexMapBack->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), threadStateObj_.TidsData()); break; - case PID: + case Index::PID: indexMapBack->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), threadStateObj_.PidsData()); break; - case DUR: + case Index::DUR: indexMapBack->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), threadStateObj_.DursData()); break; - case CPU: + case Index::CPU: indexMapBack->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), threadStateObj_.CpusData()); break; - case STATE: + case Index::STATE: indexMapBack->MixRange(c.op, static_cast(dataCache_->GetThreadStateValue( std::string(reinterpret_cast(sqlite3_value_text(argv[i]))))), threadStateObj_.StatesData()); break; - case ARGSETID: + case Index::ARGSETID: indexMapBack->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), threadStateObj_.ArgSetsData()); break; @@ -205,9 +205,9 @@ int32_t ThreadStateTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_va auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: - case TS: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: + case Index::TS: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -220,39 +220,39 @@ int32_t ThreadStateTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_va int32_t ThreadStateTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TYPE: + case Index::TYPE: sqlite3_result_text(context_, "thread_state", STR_DEFAULT_LEN, nullptr); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(threadStateObj_.TimeStamsData()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(threadStateObj_.DursData()[CurrentRow()])); break; - case CPU: + case Index::CPU: if (threadStateObj_.CpusData()[CurrentRow()] != INVALID_CPU) { sqlite3_result_int64(context_, static_cast(threadStateObj_.CpusData()[CurrentRow()])); } break; - case INTERNAL_TID: + case Index::INTERNAL_TID: sqlite3_result_int64(context_, static_cast(threadStateObj_.ItidsData()[CurrentRow()])); break; - case TID: + case Index::TID: sqlite3_result_int64(context_, static_cast(threadStateObj_.TidsData()[CurrentRow()])); break; - case PID: + case Index::PID: sqlite3_result_int64(context_, static_cast(threadStateObj_.PidsData()[CurrentRow()])); break; - case STATE: { + case Index::STATE: { const std::string& str = dataCache_->GetConstSchedStateData(threadStateObj_.StatesData()[CurrentRow()]); sqlite3_result_text(context_, str.c_str(), STR_DEFAULT_LEN, nullptr); break; } - case ARGSETID: + case Index::ARGSETID: if (threadStateObj_.ArgSetsData()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(threadStateObj_.ArgSetsData()[CurrentRow()])); } diff --git a/trace_streamer/src/table/ftrace/thread_table.cpp b/trace_streamer/src/table/ftrace/thread_table.cpp index 917cc857..bcf2dc1d 100644 --- a/trace_streamer/src/table/ftrace/thread_table.cpp +++ b/trace_streamer/src/table/ftrace/thread_table.cpp @@ -17,7 +17,18 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, ITID, TYPE, TID, NAME, START_TS, END_TS, INTERNAL_PID, IS_MAIN_THREAD, SWITCH_COUNT }; +enum class Index : int32_t { + ID = 0, + ITID, + TYPE, + TID, + NAME, + START_TS, + END_TS, + INTERNAL_PID, + IS_MAIN_THREAD, + SWITCH_COUNT +}; ThreadTable::ThreadTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -62,9 +73,9 @@ void ThreadTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ITID: - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ITID: + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -83,9 +94,9 @@ void ThreadTable::FilterByConstraint(FilterConstraints& fc, double& filterCost, break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ITID: - case ID: { + switch (static_cast(c.col)) { + case Index::ITID: + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -335,14 +346,14 @@ void ThreadTable::Cursor::FilterSwitchCount(unsigned char op, uint64_t value) } void ThreadTable::Cursor::FilterIndex(int32_t col, unsigned char op, sqlite3_value* argv) { - switch (col) { - case INTERNAL_PID: + switch (static_cast(col)) { + case Index::INTERNAL_PID: FilterIpid(op, static_cast(sqlite3_value_int64(argv))); break; - case TID: + case Index::TID: FilterTid(op, static_cast(sqlite3_value_int64(argv))); break; - case SWITCH_COUNT: + case Index::SWITCH_COUNT: FilterSwitchCount(op, static_cast(sqlite3_value_int64(argv))); break; default: @@ -363,14 +374,14 @@ int32_t ThreadTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: - case ITID: + switch (static_cast(c.col)) { + case Index::ID: + case Index::ITID: FilterId(c.op, argv[i]); break; - case TID: - case INTERNAL_PID: - case SWITCH_COUNT: + case Index::TID: + case Index::INTERNAL_PID: + case Index::SWITCH_COUNT: FilterIndex(c.col, c.op, argv[i]); break; default: @@ -384,9 +395,9 @@ int32_t ThreadTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: - case ITID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: + case Index::ITID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -400,46 +411,46 @@ int32_t ThreadTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_value** int32_t ThreadTable::Cursor::Column(int32_t col) const { const auto& thread = dataCache_->GetConstThreadData(CurrentRow()); - switch (col) { - case ID: - case ITID: { + switch (static_cast(col)) { + case Index::ID: + case Index::ITID: { sqlite3_result_int64(context_, CurrentRow()); break; } - case TYPE: { + case Index::TYPE: { sqlite3_result_text(context_, "thread", strlen("thread"), nullptr); break; } - case TID: { + case Index::TID: { sqlite3_result_int64(context_, static_cast(thread.tid_)); break; } - case NAME: { + case Index::NAME: { const auto& name = dataCache_->GetDataFromDict(thread.nameIndex_); if (name.size()) { sqlite3_result_text(context_, name.c_str(), static_cast(name.length()), nullptr); } break; } - case START_TS: { + case Index::START_TS: { if (thread.startT_) { sqlite3_result_int64(context_, static_cast(thread.startT_)); } break; } - case END_TS: { + case Index::END_TS: { if (thread.endT_) { sqlite3_result_int64(context_, static_cast(thread.endT_)); } break; } - case INTERNAL_PID: { + case Index::INTERNAL_PID: { if (thread.internalPid_ != INVALID_UINT32) { sqlite3_result_int(context_, static_cast(thread.internalPid_)); } break; } - case IS_MAIN_THREAD: { + case Index::IS_MAIN_THREAD: { // When it is not clear which process the thread belongs to, is_main_thread should be set to null if (thread.internalPid_ == INVALID_UINT32) { break; @@ -448,7 +459,7 @@ int32_t ThreadTable::Cursor::Column(int32_t col) const sqlite3_result_int(context_, thread.tid_ == process.pid_); break; } - case SWITCH_COUNT: { + case Index::SWITCH_COUNT: { // When it is not clear which process the thread belongs to, is_main_thread should be set to null sqlite3_result_int(context_, thread.switchCount_); break; @@ -474,7 +485,7 @@ int32_t ThreadTable::Update(int32_t argc, sqlite3_value** argv, sqlite3_int64* p constexpr int32_t colOffset = 2; for (auto i = colOffset; i < argc; i++) { auto col = i - colOffset; - if (col != INTERNAL_PID) { + if (static_cast(col) != Index::INTERNAL_PID) { continue; } auto ipid = static_cast(sqlite3_value_int(argv[i])); diff --git a/trace_streamer/src/table/hi_sysevent/device_state_table.cpp b/trace_streamer/src/table/hi_sysevent/device_state_table.cpp index 232b4d7f..0a9d350a 100644 --- a/trace_streamer/src/table/hi_sysevent/device_state_table.cpp +++ b/trace_streamer/src/table/hi_sysevent/device_state_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, BRIGHTNESS, BT_STATE, @@ -84,68 +84,68 @@ DeviceStateTable::Cursor::~Cursor() {} int32_t DeviceStateTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, dataCache_->GetConstDeviceStateData().IdsData()[CurrentRow()]); break; - case BRIGHTNESS: + case Index::BRIGHTNESS: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Brightness()[CurrentRow()]); break; - case BT_STATE: + case Index::BT_STATE: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().BtState()[CurrentRow()]); break; - case LOCATION: + case Index::LOCATION: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Location()[CurrentRow()]); break; - case WIFI: + case Index::WIFI: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Wifi()[CurrentRow()]); break; - case STREAM_DEFAULT: + case Index::STREAM_DEFAULT: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().StreamDefault()[CurrentRow()]); break; - case VOICE_CALL: + case Index::VOICE_CALL: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().VoiceCall()[CurrentRow()]); break; - case MUSIC: + case Index::MUSIC: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Music()[CurrentRow()]); break; - case STREAM_RING: + case Index::STREAM_RING: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().StreamRing()[CurrentRow()]); break; - case MEDIA: + case Index::MEDIA: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Media()[CurrentRow()]); break; - case VOICE_ASSISTANT: + case Index::VOICE_ASSISTANT: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().VoiceAssistant()[CurrentRow()]); break; - case SYSTEM: + case Index::SYSTEM: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().System()[CurrentRow()]); break; - case ALARM: + case Index::ALARM: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Alarm()[CurrentRow()]); break; - case NOTIFICATION: + case Index::NOTIFICATION: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Notification()[CurrentRow()]); break; - case BT_SCO: + case Index::BT_SCO: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().BtSco()[CurrentRow()]); break; - case ENFORCED_AUDIBLE: + case Index::ENFORCED_AUDIBLE: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().EnforcedAudible()[CurrentRow()]); break; - case STREAM_DTMF: + case Index::STREAM_DTMF: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().StreamDtmf()[CurrentRow()]); break; - case STREAM_TTS: + case Index::STREAM_TTS: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().StreamTts()[CurrentRow()]); break; - case ACCESSIBILITY: + case Index::ACCESSIBILITY: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Accessibility()[CurrentRow()]); break; - case RECORDING: + case Index::RECORDING: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().Recording()[CurrentRow()]); break; - case STREAM_ALL: + case Index::STREAM_ALL: sqlite3_result_int(context_, dataCache_->GetConstDeviceStateData().StreamAll()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/hi_sysevent/sysevent_measure_table.cpp b/trace_streamer/src/table/hi_sysevent/sysevent_measure_table.cpp index a9db9cef..4c19a3fd 100644 --- a/trace_streamer/src/table/hi_sysevent/sysevent_measure_table.cpp +++ b/trace_streamer/src/table/hi_sysevent/sysevent_measure_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, SERIAL, TS, NAME_ID, KEY_ID, TYPE, INT_VALUE, STRING_VALUE }; +enum class Index : int32_t { ID = 0, SERIAL, TS, NAME_ID, KEY_ID, TYPE, INT_VALUE, STRING_VALUE }; SysEventMeasureTable::SysEventMeasureTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -48,29 +48,29 @@ SysEventMeasureTable::Cursor::~Cursor() {} int32_t SysEventMeasureTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, dataCache_->GetConstSyseventMeasureData().IdsData()[CurrentRow()]); break; - case SERIAL: + case Index::SERIAL: sqlite3_result_int64(context_, dataCache_->GetConstSyseventMeasureData().Serial()[CurrentRow()]); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, dataCache_->GetConstSyseventMeasureData().Ts()[CurrentRow()]); break; - case NAME_ID: + case Index::NAME_ID: sqlite3_result_int(context_, dataCache_->GetConstSyseventMeasureData().NameFilterId()[CurrentRow()]); break; - case KEY_ID: + case Index::KEY_ID: sqlite3_result_int(context_, dataCache_->GetConstSyseventMeasureData().AppKeyFilterId()[CurrentRow()]); break; - case TYPE: + case Index::TYPE: sqlite3_result_int(context_, dataCache_->GetConstSyseventMeasureData().Type()[CurrentRow()]); break; - case INT_VALUE: + case Index::INT_VALUE: sqlite3_result_double(context_, dataCache_->GetConstSyseventMeasureData().NumValue()[CurrentRow()]); break; - case STRING_VALUE: + case Index::STRING_VALUE: sqlite3_result_text(context_, dataCache_->GetDataFromDict(sysEventMeasure_.StringValue()[CurrentRow()]).c_str(), STR_DEFAULT_LEN, nullptr); diff --git a/trace_streamer/src/table/hiperf/perf_call_chain_table.cpp b/trace_streamer/src/table/hiperf/perf_call_chain_table.cpp index d2fd1542..b9cc4a77 100644 --- a/trace_streamer/src/table/hiperf/perf_call_chain_table.cpp +++ b/trace_streamer/src/table/hiperf/perf_call_chain_table.cpp @@ -17,12 +17,13 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, CALLCHAIN_ID, DEPTH, VADDR_IN_FILE, FILE_ID, SYMBOL_ID, NAME }; +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, DEPTH, IP, VADDR_IN_FILE, FILE_ID, SYMBOL_ID, NAME }; PerfCallChainTable::PerfCallChainTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("callchain_id", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("depth", "INTEGER")); + tableColumn_.push_back(TableBase::ColumnInfo("ip", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("vaddr_in_file", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("symbol_id", "INTEGER")); @@ -59,8 +60,8 @@ void PerfCallChainTable::EstimateFilterCost(FilterConstraints& fc, EstimatedInde ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -79,8 +80,8 @@ void PerfCallChainTable::FilterByConstraint(FilterConstraints& fc, double& filte break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -121,19 +122,19 @@ int32_t PerfCallChainTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_ auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case CALLCHAIN_ID: - indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), - perfCallChainObj_.SampleIds()); + case Index::CALLCHAIN_ID: + indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), + perfCallChainObj_.CallChainIds()); break; - case FILE_ID: + case Index::FILE_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfCallChainObj_.FileIds()); break; - case SYMBOL_ID: + case Index::SYMBOL_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfCallChainObj_.SymbolIds()); break; @@ -145,8 +146,8 @@ int32_t PerfCallChainTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_ auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -159,26 +160,29 @@ int32_t PerfCallChainTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_ int32_t PerfCallChainTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(perfCallChainObj_.IdsData()[CurrentRow()])); break; - case CALLCHAIN_ID: - sqlite3_result_int64(context_, static_cast(perfCallChainObj_.SampleIds()[CurrentRow()])); - break; - case DEPTH: + case Index::CALLCHAIN_ID: sqlite3_result_int64(context_, static_cast(perfCallChainObj_.CallChainIds()[CurrentRow()])); break; - case VADDR_IN_FILE: + case Index::DEPTH: + sqlite3_result_int64(context_, static_cast(perfCallChainObj_.Depths()[CurrentRow()])); + break; + case Index::IP: + sqlite3_result_int64(context_, static_cast(perfCallChainObj_.Ips()[CurrentRow()])); + break; + case Index::VADDR_IN_FILE: sqlite3_result_int64(context_, static_cast(perfCallChainObj_.VaddrInFiles()[CurrentRow()])); break; - case FILE_ID: + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(perfCallChainObj_.FileIds()[CurrentRow()])); break; - case SYMBOL_ID: + case Index::SYMBOL_ID: sqlite3_result_int64(context_, static_cast(perfCallChainObj_.SymbolIds()[CurrentRow()])); break; - case NAME: + case Index::NAME: sqlite3_result_text(context_, perfCallChainObj_.Names()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/hiperf/perf_files_table.cpp b/trace_streamer/src/table/hiperf/perf_files_table.cpp index 6c9ac4b2..11fe01a1 100644 --- a/trace_streamer/src/table/hiperf/perf_files_table.cpp +++ b/trace_streamer/src/table/hiperf/perf_files_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, FILE_ID, SERIAL_ID, SYMBOL, PATH }; +enum class Index : int32_t { ID = 0, FILE_ID, SERIAL_ID, SYMBOL, PATH }; PerfFilesTable::PerfFilesTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -57,8 +57,8 @@ void PerfFilesTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInf ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -77,8 +77,8 @@ void PerfFilesTable::FilterByConstraint(FilterConstraints& fc, double& filterCos break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -119,11 +119,11 @@ int32_t PerfFilesTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case FILE_ID: + case Index::FILE_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfFilesObj_.FileIds()); break; default: @@ -134,8 +134,8 @@ int32_t PerfFilesTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -148,24 +148,24 @@ int32_t PerfFilesTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_valu int32_t PerfFilesTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(perfFilesObj_.IdsData()[CurrentRow()])); break; - case FILE_ID: + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(perfFilesObj_.FileIds()[CurrentRow()])); break; - case SERIAL_ID: + case Index::SERIAL_ID: sqlite3_result_int(context_, static_cast(perfFilesObj_.Serials()[CurrentRow()])); break; - case SYMBOL: + case Index::SYMBOL: if (perfFilesObj_.Symbols()[CurrentRow()] != INVALID_UINT64) { auto symbolIndex = static_cast(perfFilesObj_.Symbols()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(symbolIndex).c_str(), STR_DEFAULT_LEN, nullptr); } break; - case PATH: + case Index::PATH: if (perfFilesObj_.FilePaths()[CurrentRow()] != INVALID_UINT64) { auto pathIndex = static_cast(perfFilesObj_.FilePaths()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(pathIndex).c_str(), STR_DEFAULT_LEN, nullptr); diff --git a/trace_streamer/src/table/hiperf/perf_report_table.cpp b/trace_streamer/src/table/hiperf/perf_report_table.cpp index 565dee6c..b5e14653 100644 --- a/trace_streamer/src/table/hiperf/perf_report_table.cpp +++ b/trace_streamer/src/table/hiperf/perf_report_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, REPORT_TYPE, REPORT_VALUE, @@ -47,17 +47,17 @@ PerfReportTable::Cursor::~Cursor() {} int32_t PerfReportTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(perfReportObj_.IdsData()[CurrentRow()])); break; - case REPORT_TYPE: + case Index::REPORT_TYPE: if (perfReportObj_.Types()[CurrentRow()] != INVALID_UINT64) { auto typeIndex = static_cast(perfReportObj_.Types()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(typeIndex).c_str(), STR_DEFAULT_LEN, nullptr); } break; - case REPORT_VALUE: + case Index::REPORT_VALUE: if (perfReportObj_.Values()[CurrentRow()] != INVALID_UINT64) { auto typeValueIndex = static_cast(perfReportObj_.Values()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(typeValueIndex).c_str(), STR_DEFAULT_LEN, diff --git a/trace_streamer/src/table/hiperf/perf_sample_table.cpp b/trace_streamer/src/table/hiperf/perf_sample_table.cpp index afa5dccd..3329b045 100644 --- a/trace_streamer/src/table/hiperf/perf_sample_table.cpp +++ b/trace_streamer/src/table/hiperf/perf_sample_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, TIMESTAMP, @@ -71,8 +71,8 @@ void PerfSampleTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -91,8 +91,8 @@ void PerfSampleTable::FilterByConstraint(FilterConstraints& fc, double& filterCo break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -133,22 +133,22 @@ int32_t PerfSampleTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfSampleObj_.SampleIds()); break; - case THREAD_ID: + case Index::THREAD_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfSampleObj_.Tids()); break; - case EVENT_TYPE_ID: + case Index::EVENT_TYPE_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfSampleObj_.EventTypeIds()); break; - case CPU_ID: + case Index::CPU_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfSampleObj_.CpuIds()); break; default: @@ -158,8 +158,8 @@ int32_t PerfSampleTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -172,36 +172,36 @@ int32_t PerfSampleTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val int32_t PerfSampleTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(perfSampleObj_.IdsData()[CurrentRow()])); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (perfSampleObj_.SampleIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(perfSampleObj_.SampleIds()[CurrentRow()])); } else { sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case TIMESTAMP: + case Index::TIMESTAMP: sqlite3_result_int64(context_, static_cast(perfSampleObj_.TimeStampData()[CurrentRow()])); break; - case THREAD_ID: + case Index::THREAD_ID: sqlite3_result_int64(context_, static_cast(perfSampleObj_.Tids()[CurrentRow()])); break; - case EVENT_COUNT: + case Index::EVENT_COUNT: sqlite3_result_int64(context_, static_cast(perfSampleObj_.EventCounts()[CurrentRow()])); break; - case EVENT_TYPE_ID: + case Index::EVENT_TYPE_ID: sqlite3_result_int64(context_, static_cast(perfSampleObj_.EventTypeIds()[CurrentRow()])); break; - case TIMESTAMP_TRACE: + case Index::TIMESTAMP_TRACE: sqlite3_result_int64(context_, static_cast(perfSampleObj_.TimestampTraces()[CurrentRow()])); break; - case CPU_ID: + case Index::CPU_ID: sqlite3_result_int64(context_, static_cast(perfSampleObj_.CpuIds()[CurrentRow()])); break; - case THREAD_STATE: + case Index::THREAD_STATE: if (perfSampleObj_.ThreadStates()[CurrentRow()] != INVALID_UINT64) { auto threadStateIndex = static_cast(perfSampleObj_.ThreadStates()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(threadStateIndex).c_str(), STR_DEFAULT_LEN, diff --git a/trace_streamer/src/table/hiperf/perf_thread_table.cpp b/trace_streamer/src/table/hiperf/perf_thread_table.cpp index 7906029c..cd452897 100644 --- a/trace_streamer/src/table/hiperf/perf_thread_table.cpp +++ b/trace_streamer/src/table/hiperf/perf_thread_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, THREAD_ID, PROCESS_ID, THREAD_NAME }; +enum class Index : int32_t { ID = 0, THREAD_ID, PROCESS_ID, THREAD_NAME }; PerfThreadTable::PerfThreadTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -56,8 +56,8 @@ void PerfThreadTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -76,8 +76,8 @@ void PerfThreadTable::FilterByConstraint(FilterConstraints& fc, double& filterCo break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -118,14 +118,14 @@ int32_t PerfThreadTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case THREAD_ID: + case Index::THREAD_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfThreadObj_.Tids()); break; - case PROCESS_ID: + case Index::PROCESS_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), perfThreadObj_.Pids()); break; default: @@ -136,8 +136,8 @@ int32_t PerfThreadTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -150,17 +150,17 @@ int32_t PerfThreadTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val int32_t PerfThreadTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(perfThreadObj_.IdsData()[CurrentRow()])); break; - case THREAD_ID: + case Index::THREAD_ID: sqlite3_result_int64(context_, static_cast(perfThreadObj_.Tids()[CurrentRow()])); break; - case PROCESS_ID: + case Index::PROCESS_ID: sqlite3_result_int64(context_, static_cast(perfThreadObj_.Pids()[CurrentRow()])); break; - case THREAD_NAME: + case Index::THREAD_NAME: if (perfThreadObj_.ThreadNames()[CurrentRow()] != INVALID_UINT64) { auto threadNameIndex = static_cast(perfThreadObj_.ThreadNames()[CurrentRow()]); if (dataCache_->GetDataFromDict(threadNameIndex).empty()) { diff --git a/trace_streamer/src/table/js_memory/appname_table.cpp b/trace_streamer/src/table/js_memory/appname_table.cpp index 2b168abd..046c9c83 100644 --- a/trace_streamer/src/table/js_memory/appname_table.cpp +++ b/trace_streamer/src/table/js_memory/appname_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, FLAG, APP_NAME, APP_KEY }; +enum class Index : int32_t { ID = 0, FLAG, APP_NAME, APP_KEY }; AppnameTable::AppnameTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -44,17 +44,17 @@ AppnameTable::Cursor::~Cursor() {} int32_t AppnameTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, dataCache_->GetConstAppNamesData().IdsData()[CurrentRow()]); break; - case FLAG: + case Index::FLAG: sqlite3_result_int(context_, dataCache_->GetConstAppNamesData().Falgs()[CurrentRow()]); break; - case APP_NAME: + case Index::APP_NAME: sqlite3_result_int64(context_, dataCache_->GetConstAppNamesData().EventSourceId()[CurrentRow()]); break; - case APP_KEY: + case Index::APP_KEY: sqlite3_result_int64(context_, dataCache_->GetConstAppNamesData().AppName()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/js_memory/js_config_table.cpp b/trace_streamer/src/table/js_memory/js_config_table.cpp index 59b23770..8592cdc4 100644 --- a/trace_streamer/src/table/js_memory/js_config_table.cpp +++ b/trace_streamer/src/table/js_memory/js_config_table.cpp @@ -17,7 +17,15 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { PID = 0, TYPE, INTERVAL, CAPTURE_NUMERIC_VALUE, TRACK_ALLOCATION, CPU_PROFILER, CPU_PROFILER_INTERVAL }; +enum class Index : int32_t { + PID = 0, + TYPE, + INTERVAL, + CAPTURE_NUMERIC_VALUE, + TRACK_ALLOCATION, + CPU_PROFILER, + CPU_PROFILER_INTERVAL +}; JsConfigTable::JsConfigTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("pid", "INTEGER")); @@ -47,26 +55,26 @@ JsConfigTable::Cursor::~Cursor() {} int32_t JsConfigTable::Cursor::Column(int32_t col) const { - switch (col) { - case PID: + switch (static_cast(col)) { + case Index::PID: sqlite3_result_int64(context_, static_cast(jsConfig_.Pids()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(jsConfig_.Types()[CurrentRow()])); break; - case INTERVAL: + case Index::INTERVAL: sqlite3_result_int64(context_, static_cast(jsConfig_.Intervals()[CurrentRow()])); break; - case CAPTURE_NUMERIC_VALUE: + case Index::CAPTURE_NUMERIC_VALUE: sqlite3_result_int64(context_, static_cast(jsConfig_.CaptureNumericValue()[CurrentRow()])); break; - case TRACK_ALLOCATION: + case Index::TRACK_ALLOCATION: sqlite3_result_int64(context_, static_cast(jsConfig_.TrackAllocations()[CurrentRow()])); break; - case CPU_PROFILER: + case Index::CPU_PROFILER: sqlite3_result_int64(context_, static_cast(jsConfig_.CpuProfiler()[CurrentRow()])); break; - case CPU_PROFILER_INTERVAL: + case Index::CPU_PROFILER_INTERVAL: sqlite3_result_int64(context_, static_cast(jsConfig_.CpuProfilerInterval()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_cpu_profiler_node_table.cpp b/trace_streamer/src/table/js_memory/js_cpu_profiler_node_table.cpp index 341a784d..fe4bbecc 100644 --- a/trace_streamer/src/table/js_memory/js_cpu_profiler_node_table.cpp +++ b/trace_streamer/src/table/js_memory/js_cpu_profiler_node_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { FUNCTION_ID = 0, FUNCTION_NAME, SCRIPT_ID, @@ -56,37 +56,36 @@ JsCpuProfilerNodeTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBas } JsCpuProfilerNodeTable::Cursor::~Cursor() {} - int32_t JsCpuProfilerNodeTable::Cursor::Column(int32_t col) const { - switch (col) { - case FUNCTION_ID: + switch (static_cast(col)) { + case Index::FUNCTION_ID: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.FunctionIds()[CurrentRow()])); break; - case FUNCTION_NAME: + case Index::FUNCTION_NAME: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.FunctionNames()[CurrentRow()])); break; - case SCRIPT_ID: + case Index::SCRIPT_ID: sqlite3_result_text(context_, jsCpuProfilerNodes_.ScriptIds()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case URL: + case Index::URL: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.Urls()[CurrentRow()])); break; - case LINE_NUMBER: + case Index::LINE_NUMBER: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.LineNumbers()[CurrentRow()])); break; - case COLUMN_NUMBER: + case Index::COLUMN_NUMBER: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.ColumnNumbers()[CurrentRow()])); break; - case HIT_COUNT: + case Index::HIT_COUNT: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.HitCounts()[CurrentRow()])); break; - case CHILDREN: + case Index::CHILDREN: sqlite3_result_text(context_, jsCpuProfilerNodes_.Children()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case PARENT_ID: + case Index::PARENT_ID: sqlite3_result_int64(context_, static_cast(jsCpuProfilerNodes_.Parents()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_cpu_profiler_sample_table.cpp b/trace_streamer/src/table/js_memory/js_cpu_profiler_sample_table.cpp index abc92836..ca962c73 100644 --- a/trace_streamer/src/table/js_memory/js_cpu_profiler_sample_table.cpp +++ b/trace_streamer/src/table/js_memory/js_cpu_profiler_sample_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, FUNCTION_ID, START_TIME, END_TIME, DUR }; +enum class Index : int32_t { ID = 0, FUNCTION_ID, START_TIME, END_TIME, DUR }; JsCpuProfilerSampleTable::JsCpuProfilerSampleTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -45,20 +45,20 @@ JsCpuProfilerSampleTable::Cursor::~Cursor() {} int32_t JsCpuProfilerSampleTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(jsCpuProfilerSample_.IdsData()[CurrentRow()])); break; - case FUNCTION_ID: + case Index::FUNCTION_ID: sqlite3_result_int64(context_, static_cast(jsCpuProfilerSample_.FunctionIds()[CurrentRow()])); break; - case START_TIME: + case Index::START_TIME: sqlite3_result_int64(context_, static_cast(jsCpuProfilerSample_.StartTimes()[CurrentRow()])); break; - case END_TIME: + case Index::END_TIME: sqlite3_result_int64(context_, static_cast(jsCpuProfilerSample_.EndTimes()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(jsCpuProfilerSample_.Durs()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_edges_table.cpp b/trace_streamer/src/table/js_memory/js_heap_edges_table.cpp index a583ad92..3fcffb1e 100644 --- a/trace_streamer/src/table/js_memory/js_heap_edges_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_edges_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, EDGE_INDEX, TYPE, NAME_OR_INDEX, TO_NODE, FROM_NODE_ID, TO_NODE_ID }; +enum class Index : int32_t { FILE_ID = 0, EDGE_INDEX, TYPE, NAME_OR_INDEX, TO_NODE, FROM_NODE_ID, TO_NODE_ID }; JsHeapEdgesTable::JsHeapEdgesTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -47,26 +47,26 @@ JsHeapEdgesTable::Cursor::~Cursor() {} int32_t JsHeapEdgesTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.FileIds()[CurrentRow()])); break; - case EDGE_INDEX: + case Index::EDGE_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.EdgeIndexs()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.Types()[CurrentRow()])); break; - case NAME_OR_INDEX: + case Index::NAME_OR_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.NameOrIndexs()[CurrentRow()])); break; - case TO_NODE: + case Index::TO_NODE: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.ToNodes()[CurrentRow()])); break; - case FROM_NODE_ID: + case Index::FROM_NODE_ID: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.FromNodeIds()[CurrentRow()])); break; - case TO_NODE_ID: + case Index::TO_NODE_ID: sqlite3_result_int64(context_, static_cast(jsHeapEdges_.ToNodeIds()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_files_table.cpp b/trace_streamer/src/table/js_memory/js_heap_files_table.cpp index 369ddce6..29d135a2 100644 --- a/trace_streamer/src/table/js_memory/js_heap_files_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_files_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, FILE_NAME, START_TIME, END_TIME, SELF_SIZE_COUNT }; +enum class Index : int32_t { ID = 0, FILE_NAME, START_TIME, END_TIME, SELF_SIZE_COUNT }; JsHeapFilesTable::JsHeapFilesTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -45,20 +45,20 @@ JsHeapFilesTable::Cursor::~Cursor() {} int32_t JsHeapFilesTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(jsHeapFiles_.IDs()[CurrentRow()])); break; - case FILE_NAME: + case Index::FILE_NAME: sqlite3_result_text(context_, jsHeapFiles_.FilePaths()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case START_TIME: + case Index::START_TIME: sqlite3_result_int64(context_, static_cast(jsHeapFiles_.StartTimes()[CurrentRow()])); break; - case END_TIME: + case Index::END_TIME: sqlite3_result_int64(context_, static_cast(jsHeapFiles_.EndTimes()[CurrentRow()])); break; - case SELF_SIZE_COUNT: + case Index::SELF_SIZE_COUNT: sqlite3_result_int64(context_, static_cast(jsHeapFiles_.SelfSizeCount()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_info_table.cpp b/trace_streamer/src/table/js_memory/js_heap_info_table.cpp index 8a52c970..eaac27b0 100644 --- a/trace_streamer/src/table/js_memory/js_heap_info_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_info_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, KEY, TYPE, INT_VALUE, STR_VALUE }; +enum class Index : int32_t { FILE_ID = 0, KEY, TYPE, INT_VALUE, STR_VALUE }; JsHeapInfoTable::JsHeapInfoTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -45,22 +45,22 @@ JsHeapInfoTable::Cursor::~Cursor() {} int32_t JsHeapInfoTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64( context_, static_cast(jsHeapInfo_.FileIds()[CurrentRow()])); // IdsData() will be optimized break; - case KEY: + case Index::KEY: sqlite3_result_text(context_, jsHeapInfo_.Keys()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(jsHeapInfo_.Types()[CurrentRow()])); break; - case INT_VALUE: + case Index::INT_VALUE: sqlite3_result_int64(context_, static_cast(jsHeapInfo_.IntValues()[CurrentRow()])); break; - case STR_VALUE: + case Index::STR_VALUE: sqlite3_result_text(context_, jsHeapInfo_.StrValues()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_location_table.cpp b/trace_streamer/src/table/js_memory/js_heap_location_table.cpp index e653ce36..3186d819 100644 --- a/trace_streamer/src/table/js_memory/js_heap_location_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_location_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, OBJECT_INDEX, SCRIPT_ID, LINE, COLUMN }; +enum class Index : int32_t { FILE_ID = 0, OBJECT_INDEX, SCRIPT_ID, LINE, COLUMN }; JsHeapLocationTable::JsHeapLocationTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -45,20 +45,20 @@ JsHeapLocationTable::Cursor::~Cursor() {} int32_t JsHeapLocationTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapLocation_.FileIds()[CurrentRow()])); break; - case OBJECT_INDEX: + case Index::OBJECT_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapLocation_.ObjectIndexs()[CurrentRow()])); break; - case SCRIPT_ID: + case Index::SCRIPT_ID: sqlite3_result_int64(context_, static_cast(jsHeapLocation_.ScriptIds()[CurrentRow()])); break; - case LINE: + case Index::LINE: sqlite3_result_int64(context_, static_cast(jsHeapLocation_.Lines()[CurrentRow()])); break; - case COLUMN: + case Index::COLUMN: sqlite3_result_int64(context_, static_cast(jsHeapLocation_.Columns()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_nodes_table.cpp b/trace_streamer/src/table/js_memory/js_heap_nodes_table.cpp index dc2f960f..8824afc7 100644 --- a/trace_streamer/src/table/js_memory/js_heap_nodes_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_nodes_table.cpp @@ -17,7 +17,17 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, NODE_INDEX, TYPE, NAME, NODE_ID, SELF_SIZE, EDGE_COUNT, TRACE_NODE_ID, DETACHEDNESS }; +enum class Index : int32_t { + FILE_ID = 0, + NODE_INDEX, + TYPE, + NAME, + NODE_ID, + SELF_SIZE, + EDGE_COUNT, + TRACE_NODE_ID, + DETACHEDNESS +}; JsHeapNodesTable::JsHeapNodesTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -49,32 +59,32 @@ JsHeapNodesTable::Cursor::~Cursor() {} int32_t JsHeapNodesTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.FileIds()[CurrentRow()])); break; - case NODE_INDEX: + case Index::NODE_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.NodeIndexs()[CurrentRow()])); break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.Types()[CurrentRow()])); break; - case NAME: + case Index::NAME: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.Names()[CurrentRow()])); break; - case NODE_ID: + case Index::NODE_ID: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.NodeIds()[CurrentRow()])); break; - case SELF_SIZE: + case Index::SELF_SIZE: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.SelfSizes()[CurrentRow()])); break; - case EDGE_COUNT: + case Index::EDGE_COUNT: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.EdgeCounts()[CurrentRow()])); break; - case TRACE_NODE_ID: + case Index::TRACE_NODE_ID: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.TraceNodeIds()[CurrentRow()])); break; - case DETACHEDNESS: + case Index::DETACHEDNESS: sqlite3_result_int64(context_, static_cast(jsHeapNodes_.DetachedNess()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_sample_table.cpp b/trace_streamer/src/table/js_memory/js_heap_sample_table.cpp index ff24b74c..dd58fca2 100644 --- a/trace_streamer/src/table/js_memory/js_heap_sample_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_sample_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, TIMESTAMP_US, LAST_ASSIGNED_ID }; +enum class Index : int32_t { FILE_ID = 0, TIMESTAMP_US, LAST_ASSIGNED_ID }; JsHeapSampleTable::JsHeapSampleTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -43,14 +43,14 @@ JsHeapSampleTable::Cursor::~Cursor() {} int32_t JsHeapSampleTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapSample_.FileIds()[CurrentRow()])); break; - case TIMESTAMP_US: + case Index::TIMESTAMP_US: sqlite3_result_int64(context_, static_cast(jsHeapSample_.TimeStampUs()[CurrentRow()])); break; - case LAST_ASSIGNED_ID: + case Index::LAST_ASSIGNED_ID: sqlite3_result_int64(context_, static_cast(jsHeapSample_.LastAssignedIds()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_string_table.cpp b/trace_streamer/src/table/js_memory/js_heap_string_table.cpp index 01da1de3..fd983606 100644 --- a/trace_streamer/src/table/js_memory/js_heap_string_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_string_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, FILE_INDEX, STRING }; +enum class Index : int32_t { FILE_ID = 0, FILE_INDEX, STRING }; JsHeapStringTable::JsHeapStringTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -43,14 +43,14 @@ JsHeapStringTable::Cursor::~Cursor() {} int32_t JsHeapStringTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapString_.FileIds()[CurrentRow()])); break; - case FILE_INDEX: + case Index::FILE_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapString_.FileIndexs()[CurrentRow()])); break; - case STRING: + case Index::STRING: sqlite3_result_text(context_, jsHeapString_.Strings()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_trace_function_info_table.cpp b/trace_streamer/src/table/js_memory/js_heap_trace_function_info_table.cpp index af03f74c..d67a7b07 100644 --- a/trace_streamer/src/table/js_memory/js_heap_trace_function_info_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_trace_function_info_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, FUNCTION_INDEX, FUNCTION_ID, NAME, SCRIPT_NAME, SCRIPT_ID, LINE, COLUMN }; +enum class Index : int32_t { FILE_ID = 0, FUNCTION_INDEX, FUNCTION_ID, NAME, SCRIPT_NAME, SCRIPT_ID, LINE, COLUMN }; JsHeapTraceFunctionInfoTable::JsHeapTraceFunctionInfoTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -48,29 +48,29 @@ JsHeapTraceFunctionInfoTable::Cursor::~Cursor() {} int32_t JsHeapTraceFunctionInfoTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.FileIds()[CurrentRow()])); break; - case FUNCTION_INDEX: + case Index::FUNCTION_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.FunctionIndexs()[CurrentRow()])); break; - case FUNCTION_ID: + case Index::FUNCTION_ID: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.FunctionIds()[CurrentRow()])); break; - case NAME: + case Index::NAME: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.Names()[CurrentRow()])); break; - case SCRIPT_NAME: + case Index::SCRIPT_NAME: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.ScriptNames()[CurrentRow()])); break; - case SCRIPT_ID: + case Index::SCRIPT_ID: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.ScriptIds()[CurrentRow()])); break; - case LINE: + case Index::LINE: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.Lines()[CurrentRow()])); break; - case COLUMN: + case Index::COLUMN: sqlite3_result_int64(context_, static_cast(jsHeapTraceFuncInfo_.Columns()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/js_memory/js_heap_trace_node_table.cpp b/trace_streamer/src/table/js_memory/js_heap_trace_node_table.cpp index ba3a80c3..0e95e122 100644 --- a/trace_streamer/src/table/js_memory/js_heap_trace_node_table.cpp +++ b/trace_streamer/src/table/js_memory/js_heap_trace_node_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { FILE_ID = 0, TRACE_NODE_ID, FUNCTION_INFO_INDEX, COUNT, SIZE, PARENT_ID }; +enum class Index : int32_t { FILE_ID = 0, TRACE_NODE_ID, FUNCTION_INFO_INDEX, COUNT, SIZE, PARENT_ID }; JsHeapTraceNodeTable::JsHeapTraceNodeTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("file_id", "INTEGER")); @@ -46,23 +46,23 @@ JsHeapTraceNodeTable::Cursor::~Cursor() {} int32_t JsHeapTraceNodeTable::Cursor::Column(int32_t col) const { - switch (col) { - case FILE_ID: + switch (static_cast(col)) { + case Index::FILE_ID: sqlite3_result_int64(context_, static_cast(jsHeapTraceNode_.FileIds()[CurrentRow()])); break; - case TRACE_NODE_ID: + case Index::TRACE_NODE_ID: sqlite3_result_int64(context_, static_cast(jsHeapTraceNode_.TraceNodeIDs()[CurrentRow()])); break; - case FUNCTION_INFO_INDEX: + case Index::FUNCTION_INFO_INDEX: sqlite3_result_int64(context_, static_cast(jsHeapTraceNode_.FunctionInfoIndexs()[CurrentRow()])); break; - case COUNT: + case Index::COUNT: sqlite3_result_int64(context_, static_cast(jsHeapTraceNode_.Counts()[CurrentRow()])); break; - case SIZE: + case Index::SIZE: sqlite3_result_int64(context_, static_cast(jsHeapTraceNode_.NodeSizes()[CurrentRow()])); break; - case PARENT_ID: + case Index::PARENT_ID: sqlite3_result_int64(context_, static_cast(jsHeapTraceNode_.ParentIds()[CurrentRow()])); break; default: diff --git a/trace_streamer/src/table/monitor/cpu_usage_info_table.cpp b/trace_streamer/src/table/monitor/cpu_usage_info_table.cpp index 7da5974e..3fdaff1d 100644 --- a/trace_streamer/src/table/monitor/cpu_usage_info_table.cpp +++ b/trace_streamer/src/table/monitor/cpu_usage_info_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { TS = 0, DUR, TOTAL_LOAD, USER_LOAD, SYSTEM_LOAD, THREADS }; +enum class Index : int32_t { TS = 0, DUR, TOTAL_LOAD, USER_LOAD, SYSTEM_LOAD, THREADS }; CpuUsageInfoTable::CpuUsageInfoTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("ts", "INTEGER")); @@ -46,28 +46,28 @@ CpuUsageInfoTable::Cursor::~Cursor() {} int32_t CpuUsageInfoTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(cpuUsageInfoObj_.TimeStampData()[CurrentRow()])); break; } - case DUR: { + case Index::DUR: { sqlite3_result_int64(context_, static_cast(cpuUsageInfoObj_.Durs()[CurrentRow()])); break; } - case TOTAL_LOAD: { + case Index::TOTAL_LOAD: { sqlite3_result_int64(context_, static_cast(cpuUsageInfoObj_.TotalLoad()[CurrentRow()])); break; } - case USER_LOAD: { + case Index::USER_LOAD: { sqlite3_result_double(context_, cpuUsageInfoObj_.UserLoad()[CurrentRow()]); break; } - case SYSTEM_LOAD: { + case Index::SYSTEM_LOAD: { sqlite3_result_double(context_, cpuUsageInfoObj_.SystemLoad()[CurrentRow()]); break; } - case THREADS: { + case Index::THREADS: { sqlite3_result_int(context_, static_cast(cpuUsageInfoObj_.Threads()[CurrentRow()])); break; } diff --git a/trace_streamer/src/table/monitor/disk_io_table.cpp b/trace_streamer/src/table/monitor/disk_io_table.cpp index 14ca7235..4f37e84b 100644 --- a/trace_streamer/src/table/monitor/disk_io_table.cpp +++ b/trace_streamer/src/table/monitor/disk_io_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { TS = 0, DUR, RD, @@ -61,44 +61,44 @@ DiskIOTable::Cursor::~Cursor() {} int32_t DiskIOTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(diskIODataObj_.TimeStampData()[CurrentRow()])); break; } - case DUR: { + case Index::DUR: { sqlite3_result_int64(context_, static_cast(diskIODataObj_.Durs()[CurrentRow()])); break; } - case RD: { + case Index::RD: { sqlite3_result_int64(context_, static_cast(diskIODataObj_.RdDatas()[CurrentRow()])); break; } - case WR: { + case Index::WR: { sqlite3_result_int64(context_, static_cast(diskIODataObj_.WrDatas()[CurrentRow()])); break; } - case RD_SPEED: { + case Index::RD_SPEED: { sqlite3_result_double(context_, static_cast(diskIODataObj_.RdSpeedDatas()[CurrentRow()])); break; } - case WR_SPEED: { + case Index::WR_SPEED: { sqlite3_result_double(context_, static_cast(diskIODataObj_.WrSpeedDatas()[CurrentRow()])); break; } - case RD_COUNT: { + case Index::RD_COUNT: { sqlite3_result_int64(context_, static_cast(diskIODataObj_.RdCountDatas()[CurrentRow()])); break; } - case WR_COUNT: { + case Index::WR_COUNT: { sqlite3_result_int64(context_, static_cast(diskIODataObj_.WrCountDatas()[CurrentRow()])); break; } - case RD_COUNT_SPEED: { + case Index::RD_COUNT_SPEED: { sqlite3_result_double(context_, static_cast(diskIODataObj_.RdCountPerSecDatas()[CurrentRow()])); break; } - case WR_COUNT_SPEED: { + case Index::WR_COUNT_SPEED: { sqlite3_result_double(context_, static_cast(diskIODataObj_.WrCountPerSecDatas()[CurrentRow()])); break; } diff --git a/trace_streamer/src/table/monitor/hidump_table.cpp b/trace_streamer/src/table/monitor/hidump_table.cpp index d72d6832..1202ac6e 100644 --- a/trace_streamer/src/table/monitor/hidump_table.cpp +++ b/trace_streamer/src/table/monitor/hidump_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TS, FPS }; +enum class Index : int32_t { ID = 0, TS, FPS }; HidumpTable::HidumpTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -42,14 +42,14 @@ HidumpTable::Cursor::~Cursor() {} int32_t HidumpTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(hidumpObj_.TimeStampData()[CurrentRow()])); break; - case FPS: { + case Index::FPS: { sqlite3_result_int64(context_, static_cast(hidumpObj_.Fpss()[CurrentRow()])); break; } diff --git a/trace_streamer/src/table/monitor/live_process_table.cpp b/trace_streamer/src/table/monitor/live_process_table.cpp index 558dcfe8..0ae4ded0 100644 --- a/trace_streamer/src/table/monitor/live_process_table.cpp +++ b/trace_streamer/src/table/monitor/live_process_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { TS = 0, DUR, CPU_TIME, @@ -67,60 +67,60 @@ LiveProcessTable::Cursor::~Cursor() {} int32_t LiveProcessTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(liveProcessDetailDataObj_.TimeStampData()[CurrentRow()])); break; } - case DUR: { + case Index::DUR: { sqlite3_result_int64(context_, static_cast(liveProcessDetailDataObj_.Durs()[CurrentRow()])); break; } - case CPU_TIME: { + case Index::CPU_TIME: { sqlite3_result_int64(context_, static_cast(liveProcessDetailDataObj_.CpuTimes()[CurrentRow()])); break; } - case PROCESS_ID: { + case Index::PROCESS_ID: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.ProcessID()[CurrentRow()])); break; } - case PROCESS_NAME: { + case Index::PROCESS_NAME: { sqlite3_result_text(context_, liveProcessDetailDataObj_.ProcessName()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; } - case PARENT_PROCESS_ID: { + case Index::PARENT_PROCESS_ID: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.ParentProcessID()[CurrentRow()])); break; } - case UID: { + case Index::UID: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.Uid()[CurrentRow()])); break; } - case USER_NAME: { + case Index::USER_NAME: { sqlite3_result_text(context_, liveProcessDetailDataObj_.UserName()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; } - case CPU_USAGE: { + case Index::CPU_USAGE: { sqlite3_result_double(context_, liveProcessDetailDataObj_.CpuUsage()[CurrentRow()]); break; } - case PSS_INFO: { + case Index::PSS_INFO: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.PssInfo()[CurrentRow()])); break; } - case THREAD_SUM: { + case Index::THREAD_SUM: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.Threads()[CurrentRow()])); break; } - case DISK_WRITES: { + case Index::DISK_WRITES: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.DiskWrites()[CurrentRow()])); break; } - case DISK_READS: { + case Index::DISK_READS: { sqlite3_result_int(context_, static_cast(liveProcessDetailDataObj_.DiskReads()[CurrentRow()])); break; } diff --git a/trace_streamer/src/table/monitor/log_table.cpp b/trace_streamer/src/table/monitor/log_table.cpp index b638acaf..4febc2d6 100644 --- a/trace_streamer/src/table/monitor/log_table.cpp +++ b/trace_streamer/src/table/monitor/log_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { SEQ = 0, TS, PID, TID, LEVEL, TAG, CONTEXT, ORIGINTS }; +enum class Index : int32_t { SEQ = 0, TS, PID, TID, LEVEL, TAG, CONTEXT, ORIGINTS }; LogTable::LogTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("seq", "INTEGER")); @@ -48,21 +48,21 @@ LogTable::Cursor::~Cursor() {} int32_t LogTable::Cursor::Column(int32_t column) const { - switch (column) { - case SEQ: + switch (static_cast(column)) { + case Index::SEQ: sqlite3_result_int64(context_, static_cast(logInfoObj_.HilogLineSeqs()[CurrentRow()])); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, static_cast(logInfoObj_.TimeStampData()[CurrentRow()])); break; - case PID: { + case Index::PID: { sqlite3_result_int64(context_, static_cast(logInfoObj_.Pids()[CurrentRow()])); break; } - case TID: + case Index::TID: sqlite3_result_int64(context_, static_cast(logInfoObj_.Tids()[CurrentRow()])); break; - case LEVEL: { + case Index::LEVEL: { if (logInfoObj_.Levels()[CurrentRow()] != INVALID_UINT64) { auto levelDataIndex = static_cast(logInfoObj_.Levels()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(levelDataIndex).c_str(), STR_DEFAULT_LEN, @@ -70,7 +70,7 @@ int32_t LogTable::Cursor::Column(int32_t column) const } break; } - case TAG: { + case Index::TAG: { if (logInfoObj_.Tags()[CurrentRow()] != INVALID_UINT64) { auto tagDataIndex = static_cast(logInfoObj_.Tags()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(tagDataIndex).c_str(), STR_DEFAULT_LEN, @@ -78,7 +78,7 @@ int32_t LogTable::Cursor::Column(int32_t column) const } break; } - case CONTEXT: { + case Index::CONTEXT: { if (logInfoObj_.Contexts()[CurrentRow()] != INVALID_UINT64) { auto contextDataIndex = static_cast(logInfoObj_.Contexts()[CurrentRow()]); sqlite3_result_text(context_, dataCache_->GetDataFromDict(contextDataIndex).c_str(), STR_DEFAULT_LEN, @@ -86,7 +86,7 @@ int32_t LogTable::Cursor::Column(int32_t column) const } break; } - case ORIGINTS: { + case Index::ORIGINTS: { sqlite3_result_int64(context_, static_cast(logInfoObj_.OriginTimeStamData()[CurrentRow()])); break; } diff --git a/trace_streamer/src/table/monitor/memory_ashmem_table.cpp b/trace_streamer/src/table/monitor/memory_ashmem_table.cpp index 736bd171..2687c89b 100644 --- a/trace_streamer/src/table/monitor/memory_ashmem_table.cpp +++ b/trace_streamer/src/table/monitor/memory_ashmem_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, TS, IPID, @@ -67,44 +67,44 @@ MemoryAshMemTable::Cursor::~Cursor() {} int32_t MemoryAshMemTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, AshMemDataObj_.IdsData()[CurrentRow()]); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, AshMemDataObj_.TimeStampData()[CurrentRow()]); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, AshMemDataObj_.Ipids()[CurrentRow()]); break; - case ADJ: + case Index::ADJ: sqlite3_result_int(context_, AshMemDataObj_.Adjs()[CurrentRow()]); break; - case FD: + case Index::FD: sqlite3_result_int(context_, AshMemDataObj_.Fds()[CurrentRow()]); break; - case ASHMEM_NAME_ID: + case Index::ASHMEM_NAME_ID: sqlite3_result_int(context_, AshMemDataObj_.AshmemNameIds()[CurrentRow()]); break; - case SIZE: + case Index::SIZE: sqlite3_result_int64(context_, AshMemDataObj_.Sizes()[CurrentRow()]); break; - case PSS: + case Index::PSS: sqlite3_result_int64(context_, AshMemDataObj_.Psss()[CurrentRow()]); break; - case ASHMEM_ID: + case Index::ASHMEM_ID: sqlite3_result_int64(context_, AshMemDataObj_.AshmemIds()[CurrentRow()]); break; - case TIME: + case Index::TIME: sqlite3_result_int64(context_, AshMemDataObj_.Times()[CurrentRow()]); break; - case REF_COUNT: + case Index::REF_COUNT: sqlite3_result_int64(context_, AshMemDataObj_.RefCounts()[CurrentRow()]); break; - case PURGED: + case Index::PURGED: sqlite3_result_int64(context_, AshMemDataObj_.Purgeds()[CurrentRow()]); break; - case FLAG: + case Index::FLAG: sqlite3_result_int(context_, AshMemDataObj_.Flags()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/monitor/memory_dma_table.cpp b/trace_streamer/src/table/monitor/memory_dma_table.cpp index fb292ab5..3b282532 100644 --- a/trace_streamer/src/table/monitor/memory_dma_table.cpp +++ b/trace_streamer/src/table/monitor/memory_dma_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, TS, IPID, @@ -63,38 +63,38 @@ MemoryDmaTable::Cursor::~Cursor() {} int32_t MemoryDmaTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, DmaMemDataObj_.IdsData()[CurrentRow()]); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, DmaMemDataObj_.TimeStampData()[CurrentRow()]); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, DmaMemDataObj_.Ipids()[CurrentRow()]); break; - case FD: + case Index::FD: sqlite3_result_int(context_, DmaMemDataObj_.Fds()[CurrentRow()]); break; - case SIZE: + case Index::SIZE: sqlite3_result_int64(context_, DmaMemDataObj_.Sizes()[CurrentRow()]); break; - case INO: + case Index::INO: sqlite3_result_int(context_, DmaMemDataObj_.Inos()[CurrentRow()]); break; - case EXP_PID: + case Index::EXP_PID: sqlite3_result_int(context_, DmaMemDataObj_.ExpPids()[CurrentRow()]); break; - case EXP_TASK_COMM: + case Index::EXP_TASK_COMM: sqlite3_result_int64(context_, DmaMemDataObj_.ExpTaskCommIds()[CurrentRow()]); break; - case BUF_NAME_ID: + case Index::BUF_NAME_ID: sqlite3_result_int64(context_, DmaMemDataObj_.BufNameIds()[CurrentRow()]); break; - case EXP_NAME_ID: + case Index::EXP_NAME_ID: sqlite3_result_int64(context_, DmaMemDataObj_.ExpNameIds()[CurrentRow()]); break; - case FLAG: + case Index::FLAG: sqlite3_result_int(context_, DmaMemDataObj_.Flags()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/monitor/memory_process_gpu_table.cpp b/trace_streamer/src/table/monitor/memory_process_gpu_table.cpp index 039d2f2b..ecf2b4b4 100644 --- a/trace_streamer/src/table/monitor/memory_process_gpu_table.cpp +++ b/trace_streamer/src/table/monitor/memory_process_gpu_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, TS, GPU_NAME_ID, @@ -57,30 +57,30 @@ MemoryProcessGpuTable::Cursor::~Cursor() {} int32_t MemoryProcessGpuTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, GpuProcessMemDataObj_.IdsData()[CurrentRow()]); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, GpuProcessMemDataObj_.TimeStampData()[CurrentRow()]); break; - case GPU_NAME_ID: + case Index::GPU_NAME_ID: sqlite3_result_int64(context_, GpuProcessMemDataObj_.GpuNameIds()[CurrentRow()]); break; - case ALL_GPU_SIZE: + case Index::ALL_GPU_SIZE: sqlite3_result_int64(context_, GpuProcessMemDataObj_.AllGpuSizes()[CurrentRow()]); break; - case ADDR: + case Index::ADDR: sqlite3_result_text(context_, GpuProcessMemDataObj_.Addrs()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, GpuProcessMemDataObj_.Ipids()[CurrentRow()]); break; - case ITID: + case Index::ITID: sqlite3_result_int64(context_, GpuProcessMemDataObj_.Itids()[CurrentRow()]); break; - case USED_GPU_SIZE: + case Index::USED_GPU_SIZE: sqlite3_result_int64(context_, GpuProcessMemDataObj_.UsedGpuSizes()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/monitor/memory_window_gpu_table.cpp b/trace_streamer/src/table/monitor/memory_window_gpu_table.cpp index 3cf6ff27..1c7c51b0 100644 --- a/trace_streamer/src/table/monitor/memory_window_gpu_table.cpp +++ b/trace_streamer/src/table/monitor/memory_window_gpu_table.cpp @@ -17,7 +17,17 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, TS, WINDOW_NAME_ID, WINDOW_ID, MODULE_NAME_ID, CATEGORY_NAME_ID, SIZE, COUNT, PURGEABLE_SIZE }; +enum class Index : int32_t { + ID = 0, + TS, + WINDOW_NAME_ID, + WINDOW_ID, + MODULE_NAME_ID, + CATEGORY_NAME_ID, + SIZE, + COUNT, + PURGEABLE_SIZE +}; MemoryWindowGpuTable::MemoryWindowGpuTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -49,32 +59,32 @@ MemoryWindowGpuTable::Cursor::~Cursor() {} int32_t MemoryWindowGpuTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, GpuWindowMemDataObj_.IdsData()[CurrentRow()]); break; - case TS: + case Index::TS: sqlite3_result_int64(context_, GpuWindowMemDataObj_.TimeStampData()[CurrentRow()]); break; - case WINDOW_NAME_ID: + case Index::WINDOW_NAME_ID: sqlite3_result_int64(context_, GpuWindowMemDataObj_.WindowNameIds()[CurrentRow()]); break; - case WINDOW_ID: + case Index::WINDOW_ID: sqlite3_result_int64(context_, GpuWindowMemDataObj_.WindowIds()[CurrentRow()]); break; - case MODULE_NAME_ID: + case Index::MODULE_NAME_ID: sqlite3_result_int64(context_, GpuWindowMemDataObj_.ModuleNameIds()[CurrentRow()]); break; - case CATEGORY_NAME_ID: + case Index::CATEGORY_NAME_ID: sqlite3_result_int64(context_, GpuWindowMemDataObj_.CategoryNameIds()[CurrentRow()]); break; - case SIZE: + case Index::SIZE: sqlite3_result_int64(context_, GpuWindowMemDataObj_.Sizes()[CurrentRow()]); break; - case COUNT: + case Index::COUNT: sqlite3_result_int(context_, GpuWindowMemDataObj_.Counts()[CurrentRow()]); break; - case PURGEABLE_SIZE: + case Index::PURGEABLE_SIZE: sqlite3_result_int64(context_, GpuWindowMemDataObj_.PurgeableSizes()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/monitor/network_table.cpp b/trace_streamer/src/table/monitor/network_table.cpp index 52eb6d79..648ab165 100644 --- a/trace_streamer/src/table/monitor/network_table.cpp +++ b/trace_streamer/src/table/monitor/network_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { TS = 0, DUR, TX, @@ -63,53 +63,53 @@ NetworkTable::Cursor::~Cursor() {} int32_t NetworkTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(networkDataObj_.TimeStampData()[CurrentRow()])); break; } - case TX: { + case Index::TX: { sqlite3_result_int64(context_, static_cast(networkDataObj_.TxDatas()[CurrentRow()])); break; } - case RX: { + case Index::RX: { sqlite3_result_int64(context_, static_cast(networkDataObj_.RxDatas()[CurrentRow()])); break; } - case DUR: { + case Index::DUR: { sqlite3_result_int64(context_, static_cast(networkDataObj_.Durs()[CurrentRow()])); break; } - case TX_SPEED: { + case Index::TX_SPEED: { sqlite3_result_double(context_, static_cast(networkDataObj_.TxSpeed()[CurrentRow()])); break; } - case RX_SPEED: { + case Index::RX_SPEED: { sqlite3_result_double(context_, static_cast(dataCache_->GetConstNetworkData().RxSpeed()[CurrentRow()])); break; } - case PACKET_IN: { + case Index::PACKET_IN: { sqlite3_result_int64(context_, static_cast(dataCache_->GetConstNetworkData().PacketIn()[CurrentRow()])); break; } - case PACKET_IN_SEC: { + case Index::PACKET_IN_SEC: { sqlite3_result_double(context_, static_cast(dataCache_->GetConstNetworkData().PacketInSec()[CurrentRow()])); break; } - case PACKET_OUT: { + case Index::PACKET_OUT: { sqlite3_result_int64(context_, static_cast(dataCache_->GetConstNetworkData().PacketOut()[CurrentRow()])); break; } - case PACKET_OUT_SEC: { + case Index::PACKET_OUT_SEC: { sqlite3_result_double(context_, static_cast(dataCache_->GetConstNetworkData().PacketOutSec()[CurrentRow()])); break; } - case NET_TYPE: { + case Index::NET_TYPE: { sqlite3_result_text(context_, dataCache_->GetConstNetworkData().NetTypes()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/src/table/monitor/paged_memory_sample_table.cpp b/trace_streamer/src/table/monitor/paged_memory_sample_table.cpp index 19470b31..dd4456ea 100644 --- a/trace_streamer/src/table/monitor/paged_memory_sample_table.cpp +++ b/trace_streamer/src/table/monitor/paged_memory_sample_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, CALLCHAIN_ID, TYPE, IPID, START_TS, END_TS, DUR, SIZE, ADDR, ITID }; +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, TYPE, IPID, START_TS, END_TS, DUR, SIZE, ADDR, ITID }; PagedMemorySampleTable::PagedMemorySampleTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -49,11 +49,11 @@ PagedMemorySampleTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBas PagedMemorySampleTable::Cursor::~Cursor() {} int32_t PagedMemorySampleTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.IdsData()[CurrentRow()])); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (PagedMemorySampleDataObj_.CallChainIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.CallChainIds()[CurrentRow()])); @@ -61,31 +61,31 @@ int32_t PagedMemorySampleTable::Cursor::Column(int32_t column) const sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.Types()[CurrentRow()])); break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.Ipids()[CurrentRow()])); break; - case ITID: + case Index::ITID: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.Itids()[CurrentRow()])); break; - case START_TS: + case Index::START_TS: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.StartTs()[CurrentRow()])); break; - case END_TS: + case Index::END_TS: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.EndTs()[CurrentRow()])); break; - case DUR: + case Index::DUR: sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.Durs()[CurrentRow()])); break; - case SIZE: { + case Index::SIZE: { if (PagedMemorySampleDataObj_.Sizes()[CurrentRow()] != MAX_SIZE_T) { sqlite3_result_int64(context_, static_cast(PagedMemorySampleDataObj_.Sizes()[CurrentRow()])); } break; } - case ADDR: { + case Index::ADDR: { if (PagedMemorySampleDataObj_.Addr()[CurrentRow()] != INVALID_UINT64) { auto firstArgIndex = PagedMemorySampleDataObj_.Addr()[CurrentRow()]; sqlite3_result_text(context_, dataCache_->GetDataFromDict(firstArgIndex).c_str(), STR_DEFAULT_LEN, diff --git a/trace_streamer/src/table/monitor/smaps_table.cpp b/trace_streamer/src/table/monitor/smaps_table.cpp index 4cb64422..b3510f56 100644 --- a/trace_streamer/src/table/monitor/smaps_table.cpp +++ b/trace_streamer/src/table/monitor/smaps_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, TIME_STAMP, START_ADDRESS, @@ -79,62 +79,62 @@ SmapsTable::Cursor::~Cursor() {} int32_t SmapsTable::Cursor::Column(int32_t col) const { - switch (col) { - case ID: + switch (static_cast(col)) { + case Index::ID: sqlite3_result_int64(context_, smapsObj_.IdsData()[CurrentRow()]); break; - case TIME_STAMP: + case Index::TIME_STAMP: sqlite3_result_int64(context_, smapsObj_.TimeStamps()[CurrentRow()]); break; - case START_ADDRESS: + case Index::START_ADDRESS: sqlite3_result_text(context_, smapsObj_.StartAddrs()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case END_ADDRESS: + case Index::END_ADDRESS: sqlite3_result_text(context_, smapsObj_.EndAddrs()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; - case DIRTY: + case Index::DIRTY: sqlite3_result_int64(context_, smapsObj_.Dirtys()[CurrentRow()]); break; - case SWAPPER: + case Index::SWAPPER: sqlite3_result_int64(context_, smapsObj_.Swappers()[CurrentRow()]); break; - case RSS: + case Index::RSS: sqlite3_result_int64(context_, smapsObj_.Rss()[CurrentRow()]); break; - case PSS: + case Index::PSS: sqlite3_result_int64(context_, smapsObj_.Pss()[CurrentRow()]); break; - case SIZE: + case Index::SIZE: sqlite3_result_int64(context_, smapsObj_.Sizes()[CurrentRow()]); break; - case RESIDE: + case Index::RESIDE: sqlite3_result_double(context_, smapsObj_.Resides()[CurrentRow()]); break; - case PROTECTION: + case Index::PROTECTION: sqlite3_result_int64(context_, smapsObj_.ProtectionIds()[CurrentRow()]); break; - case PATH: + case Index::PATH: sqlite3_result_int64(context_, smapsObj_.PathIds()[CurrentRow()]); break; - case SHARED_CLEAN: + case Index::SHARED_CLEAN: sqlite3_result_int64(context_, smapsObj_.SharedClean()[CurrentRow()]); break; - case SHARED_DIRTY: + case Index::SHARED_DIRTY: sqlite3_result_int64(context_, smapsObj_.SharedDirty()[CurrentRow()]); break; - case PRIVATE_CLEAN: + case Index::PRIVATE_CLEAN: sqlite3_result_int64(context_, smapsObj_.PrivateClean()[CurrentRow()]); break; - case PRIVATE_DIRTY: + case Index::PRIVATE_DIRTY: sqlite3_result_int64(context_, smapsObj_.PrivateDirty()[CurrentRow()]); break; - case SWAP: + case Index::SWAP: sqlite3_result_int64(context_, smapsObj_.Swap()[CurrentRow()]); break; - case SWAP_PSS: + case Index::SWAP_PSS: sqlite3_result_int64(context_, smapsObj_.SwapPss()[CurrentRow()]); break; - case TYPE: + case Index::TYPE: sqlite3_result_int64(context_, smapsObj_.Type()[CurrentRow()]); break; default: diff --git a/trace_streamer/src/table/native_hook/native_hook_frame_table.cpp b/trace_streamer/src/table/native_hook/native_hook_frame_table.cpp index 41727a39..fbaa7d4d 100644 --- a/trace_streamer/src/table/native_hook/native_hook_frame_table.cpp +++ b/trace_streamer/src/table/native_hook/native_hook_frame_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { ID = 0, CALLCHAIN_ID, DEPTH, IP, SYMBOL_ID, FILE_ID, OFFSET, SYMBOL_OFFSET, VADDR }; +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, DEPTH, IP, SYMBOL_ID, FILE_ID, OFFSET, SYMBOL_OFFSET, VADDR }; NativeHookFrameTable::NativeHookFrameTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); @@ -61,8 +61,8 @@ void NativeHookFrameTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -81,8 +81,8 @@ void NativeHookFrameTable::FilterByConstraint(FilterConstraints& fc, double& fil break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -123,19 +123,19 @@ int32_t NativeHookFrameTable::Cursor::Filter(const FilterConstraints& fc, sqlite auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), nativeHookFrameInfoObj_.CallChainIds()); break; - case SYMBOL_ID: + case Index::SYMBOL_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), nativeHookFrameInfoObj_.SymbolNames()); break; - case FILE_ID: + case Index::FILE_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), nativeHookFrameInfoObj_.FilePaths()); break; @@ -147,8 +147,8 @@ int32_t NativeHookFrameTable::Cursor::Filter(const FilterConstraints& fc, sqlite auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -161,11 +161,11 @@ int32_t NativeHookFrameTable::Cursor::Filter(const FilterConstraints& fc, sqlite int32_t NativeHookFrameTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (nativeHookFrameInfoObj_.CallChainIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.CallChainIds()[CurrentRow()])); @@ -173,35 +173,35 @@ int32_t NativeHookFrameTable::Cursor::Column(int32_t column) const sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case DEPTH: + case Index::DEPTH: sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.Depths()[CurrentRow()])); break; - case IP: + case Index::IP: if (nativeHookFrameInfoObj_.Ips()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.Ips()[CurrentRow()])); } break; - case SYMBOL_ID: + case Index::SYMBOL_ID: if (nativeHookFrameInfoObj_.SymbolNames()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.SymbolNames()[CurrentRow()])); } break; - case FILE_ID: { + case Index::FILE_ID: { if (nativeHookFrameInfoObj_.FilePaths()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.FilePaths()[CurrentRow()])); } break; } - case OFFSET: { + case Index::OFFSET: { sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.Offsets()[CurrentRow()])); break; } - case SYMBOL_OFFSET: { + case Index::SYMBOL_OFFSET: { sqlite3_result_int64(context_, static_cast(nativeHookFrameInfoObj_.SymbolOffsets()[CurrentRow()])); break; } - case VADDR: { + case Index::VADDR: { if (!nativeHookFrameInfoObj_.Vaddrs()[CurrentRow()].empty()) { sqlite3_result_text(context_, nativeHookFrameInfoObj_.Vaddrs()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); diff --git a/trace_streamer/src/table/native_hook/native_hook_statistic_table.cpp b/trace_streamer/src/table/native_hook/native_hook_statistic_table.cpp index d70c5669..a55b2aea 100644 --- a/trace_streamer/src/table/native_hook/native_hook_statistic_table.cpp +++ b/trace_streamer/src/table/native_hook/native_hook_statistic_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, IPID, @@ -27,7 +27,9 @@ enum Index { APPLY_COUNT, RELEASE_COUNT, APPLY_SIZE, - RELEASE_SIZE + RELEASE_SIZE, + LAST_LIB_ID, + LAST_SYMBOL_ID }; NativeHookStatisticTable::NativeHookStatisticTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -41,6 +43,8 @@ NativeHookStatisticTable::NativeHookStatisticTable(const TraceDataCache* dataCac tableColumn_.push_back(TableBase::ColumnInfo("release_count", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("apply_size", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("release_size", "INTEGER")); + tableColumn_.push_back(TableBase::ColumnInfo("last_lib_id", "INTEGER")); + tableColumn_.push_back(TableBase::ColumnInfo("last_symbol_id", "INTEGER")); tablePriKey_.push_back("id"); } @@ -73,8 +77,8 @@ void NativeHookStatisticTable::EstimateFilterCost(FilterConstraints& fc, Estimat ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -93,8 +97,8 @@ void NativeHookStatisticTable::FilterByConstraint(FilterConstraints& fc, double& break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -135,11 +139,11 @@ int32_t NativeHookStatisticTable::Cursor::Filter(const FilterConstraints& fc, sq auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), nativeHookStatisticInfoObj_.CallChainIds()); break; @@ -151,8 +155,8 @@ int32_t NativeHookStatisticTable::Cursor::Filter(const FilterConstraints& fc, sq auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -165,11 +169,11 @@ int32_t NativeHookStatisticTable::Cursor::Filter(const FilterConstraints& fc, sq int32_t NativeHookStatisticTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (nativeHookStatisticInfoObj_.CallChainIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.CallChainIds()[CurrentRow()])); @@ -177,45 +181,59 @@ int32_t NativeHookStatisticTable::Cursor::Column(int32_t column) const sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case IPID: + case Index::IPID: if (nativeHookStatisticInfoObj_.Ipids()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.Ipids()[CurrentRow()])); } break; - case TS: + case Index::TS: if (nativeHookStatisticInfoObj_.TimeStampData()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.TimeStampData()[CurrentRow()])); } break; - case MEMORY_TYPE: + case Index::MEMORY_TYPE: sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.MemoryTypes()[CurrentRow()])); break; - case MEMORY_SUB_TYPE: + case Index::MEMORY_SUB_TYPE: if (nativeHookStatisticInfoObj_.MemorySubTypes()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.MemorySubTypes()[CurrentRow()])); } break; - case APPLY_COUNT: + case Index::APPLY_COUNT: sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.ApplyCounts()[CurrentRow()])); break; - case RELEASE_COUNT: + case Index::RELEASE_COUNT: sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.ReleaseCounts()[CurrentRow()])); break; - case APPLY_SIZE: { + case Index::APPLY_SIZE: { sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.ApplySizes()[CurrentRow()])); break; } - case RELEASE_SIZE: { + case Index::RELEASE_SIZE: { sqlite3_result_int64(context_, static_cast(nativeHookStatisticInfoObj_.ReleaseSizes()[CurrentRow()])); break; } + case Index::LAST_LIB_ID: { + if (nativeHookStatisticInfoObj_.LastCallerPathIndexs()[CurrentRow()] != INVALID_DATAINDEX) { + sqlite3_result_int64( + context_, static_cast(nativeHookStatisticInfoObj_.LastCallerPathIndexs()[CurrentRow()])); + } + break; + } + case Index::LAST_SYMBOL_ID: { + if (nativeHookStatisticInfoObj_.LastSymbolIndexs()[CurrentRow()] != INVALID_DATAINDEX) { + sqlite3_result_int64( + context_, static_cast(nativeHookStatisticInfoObj_.LastSymbolIndexs()[CurrentRow()])); + } + break; + } default: TS_LOGF("Unregistered column : %d", column); break; diff --git a/trace_streamer/src/table/native_hook/native_hook_table.cpp b/trace_streamer/src/table/native_hook/native_hook_table.cpp index af2c34a4..9564bc86 100644 --- a/trace_streamer/src/table/native_hook/native_hook_table.cpp +++ b/trace_streamer/src/table/native_hook/native_hook_table.cpp @@ -17,7 +17,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { +enum class Index : int32_t { ID = 0, CALLCHAIN_ID, IPID, @@ -31,7 +31,8 @@ enum Index { MEM_SIZE, ALL_MEM_SIZE, CURRENT_SIZE_DUR, - LAST_LIB_ID + LAST_LIB_ID, + LAST_SYMBOL_ID }; NativeHookTable::NativeHookTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -49,6 +50,7 @@ NativeHookTable::NativeHookTable(const TraceDataCache* dataCache) : TableBase(da tableColumn_.push_back(TableBase::ColumnInfo("all_heap_size", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("current_size_dur", "INTEGER")); tableColumn_.push_back(TableBase::ColumnInfo("last_lib_id", "INTEGER")); + tableColumn_.push_back(TableBase::ColumnInfo("last_symbol_id", "INTEGER")); tablePriKey_.push_back("id"); } @@ -81,8 +83,8 @@ void NativeHookTable::EstimateFilterCost(FilterConstraints& fc, EstimatedIndexIn ei.isOrdered = true; auto orderbys = fc.GetOrderBys(); for (auto i = 0; i < orderbys.size(); i++) { - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: break; default: // other columns can be sorted by SQLite ei.isOrdered = false; @@ -101,8 +103,8 @@ void NativeHookTable::FilterByConstraint(FilterConstraints& fc, double& filterCo break; } const auto& c = fcConstraints[i]; - switch (c.col) { - case ID: { + switch (static_cast(c.col)) { + case Index::ID: { if (CanFilterId(c.op, rowCount)) { fc.UpdateConstraint(i, true); filterCost += 1; // id can position by 1 step @@ -143,17 +145,18 @@ int32_t NativeHookTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto& cs = fc.GetConstraints(); for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; - switch (c.col) { - case ID: + switch (static_cast(c.col)) { + case Index::ID: FilterId(c.op, argv[i]); break; - case IPID: + case Index::IPID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), nativeHookObj_.Ipids()); break; - case ITID: - indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), nativeHookObj_.Itids()); + case Index::ITID: + indexMap_->MixRange(c.op, static_cast(sqlite3_value_int(argv[i])), + nativeHookObj_.InternalTidsData()); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: indexMap_->MixRange(c.op, static_cast(sqlite3_value_int64(argv[i])), nativeHookObj_.CallChainIds()); break; @@ -165,8 +168,8 @@ int32_t NativeHookTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val auto orderbys = fc.GetOrderBys(); for (auto i = orderbys.size(); i > 0;) { i--; - switch (orderbys[i].iColumn) { - case ID: + switch (static_cast(orderbys[i].iColumn)) { + case Index::ID: indexMap_->SortBy(orderbys[i].desc); break; default: @@ -179,72 +182,78 @@ int32_t NativeHookTable::Cursor::Filter(const FilterConstraints& fc, sqlite3_val int32_t NativeHookTable::Cursor::Column(int32_t column) const { - switch (column) { - case ID: + switch (static_cast(column)) { + case Index::ID: sqlite3_result_int64(context_, static_cast(CurrentRow())); break; - case CALLCHAIN_ID: + case Index::CALLCHAIN_ID: if (nativeHookObj_.CallChainIds()[CurrentRow()] != INVALID_UINT32) { sqlite3_result_int64(context_, static_cast(nativeHookObj_.CallChainIds()[CurrentRow()])); } else { sqlite3_result_int64(context_, static_cast(INVALID_CALL_CHAIN_ID)); } break; - case IPID: + case Index::IPID: sqlite3_result_int64(context_, static_cast(nativeHookObj_.Ipids()[CurrentRow()])); break; - case ITID: - sqlite3_result_int64(context_, static_cast(nativeHookObj_.Itids()[CurrentRow()])); + case Index::ITID: + sqlite3_result_int64(context_, static_cast(nativeHookObj_.InternalTidsData()[CurrentRow()])); break; - case EVENT_TYPE: { + case Index::EVENT_TYPE: { if (!nativeHookObj_.EventTypes()[CurrentRow()].empty()) { sqlite3_result_text(context_, nativeHookObj_.EventTypes()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); } break; } - case SUB_TYPE_ID: { + case Index::SUB_TYPE_ID: { if (nativeHookObj_.SubTypes()[CurrentRow()] != INVALID_UINT64) { sqlite3_result_int64(context_, static_cast(nativeHookObj_.SubTypes()[CurrentRow()])); } break; } - case START_TS: + case Index::START_TS: sqlite3_result_int64(context_, static_cast(nativeHookObj_.TimeStampData()[CurrentRow()])); break; - case END_TS: + case Index::END_TS: if (static_cast(nativeHookObj_.EndTimeStamps()[CurrentRow()]) != 0) { sqlite3_result_int64(context_, static_cast(nativeHookObj_.EndTimeStamps()[CurrentRow()])); } break; - case DURATION: + case Index::DURATION: if (static_cast(nativeHookObj_.Durations()[CurrentRow()]) != 0) { sqlite3_result_int64(context_, static_cast(nativeHookObj_.Durations()[CurrentRow()])); } break; - case ADDR: { + case Index::ADDR: { sqlite3_result_int64(context_, static_cast(nativeHookObj_.Addrs()[CurrentRow()])); break; } - case MEM_SIZE: { + case Index::MEM_SIZE: { sqlite3_result_int64(context_, static_cast(nativeHookObj_.MemSizes()[CurrentRow()])); break; } - case ALL_MEM_SIZE: { + case Index::ALL_MEM_SIZE: { sqlite3_result_int64(context_, static_cast(nativeHookObj_.AllMemSizes()[CurrentRow()])); break; } - case CURRENT_SIZE_DUR: { + case Index::CURRENT_SIZE_DUR: { sqlite3_result_int64(context_, static_cast(nativeHookObj_.CurrentSizeDurs()[CurrentRow()])); break; } - case LAST_LIB_ID: { - if (nativeHookObj_.LastCallerPathIndexs()[CurrentRow()] != INVALID_UINT64) { + case Index::LAST_LIB_ID: { + if (nativeHookObj_.LastCallerPathIndexs()[CurrentRow()] != INVALID_DATAINDEX) { sqlite3_result_int64(context_, static_cast(nativeHookObj_.LastCallerPathIndexs()[CurrentRow()])); } break; } + case Index::LAST_SYMBOL_ID: { + if (nativeHookObj_.LastSymbolIndexs()[CurrentRow()] != INVALID_DATAINDEX) { + sqlite3_result_int64(context_, static_cast(nativeHookObj_.LastSymbolIndexs()[CurrentRow()])); + } + break; + } default: TS_LOGF("Unregistered column : %d", column); break; diff --git a/trace_streamer/src/trace_data/trace_data_db.cpp b/trace_streamer/src/trace_data/trace_data_db.cpp index 31da8362..fd6c66f3 100644 --- a/trace_streamer/src/trace_data/trace_data_db.cpp +++ b/trace_streamer/src/trace_data/trace_data_db.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include "codec_cov.h" #include "file.h" @@ -264,12 +265,15 @@ std::vector TraceDataDB::SearchData() } return values; } -int32_t TraceDataDB::SearchDatabase(const std::string& sql, bool print) +int32_t TraceDataDB::SearchDatabase(std::string& sql, bool print) { Prepare(); int32_t rowCount = 0; sqlite3_stmt* stmt = nullptr; int32_t ret = sqlite3_prepare_v2(db_, sql.c_str(), static_cast(sql.size()), &stmt, nullptr); + if (sql.back() != '\n') { + sql += "\r\n"; + } printf("Executing sql: %s", sql.c_str()); if (ret != SQLITE_OK) { TS_LOGE("sqlite3_prepare_v2(%s) failed: %d:%s", sql.c_str(), ret, sqlite3_errmsg(db_)); @@ -499,9 +503,7 @@ void TraceDataDB::GetRowString(sqlite3_stmt* stmt, int32_t colCount, std::string int32_t type = sqlite3_column_type(stmt, i); switch (type) { case SQLITE_TEXT: - rowStr += "\""; - rowStr += p; - rowStr += "\""; + rowStr += FormatString(p); break; default: rowStr += p; diff --git a/trace_streamer/src/trace_data/trace_data_db.h b/trace_streamer/src/trace_data/trace_data_db.h index a6811567..e798d582 100644 --- a/trace_streamer/src/trace_data/trace_data_db.h +++ b/trace_streamer/src/trace_data/trace_data_db.h @@ -53,7 +53,7 @@ public: int32_t OperateDatabase(const std::string& sql); int32_t SearchDatabase(const std::string& sql, ResultCallBack resultCallBack); int32_t SearchDatabase(const std::string& sql, uint8_t* out, int32_t outLen); - int32_t SearchDatabase(const std::string& sql, bool print); + int32_t SearchDatabase(std::string& sql, bool print); std::string SearchDatabase(const std::string& sql); void SetCancel(bool cancel); void AppendNewTable(std::string tableName); diff --git a/trace_streamer/src/trace_data/trace_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype.cpp index a4a8ae17..d9f8c30e 100644 --- a/trace_streamer/src/trace_data/trace_stdtype.cpp +++ b/trace_streamer/src/trace_data/trace_stdtype.cpp @@ -483,12 +483,58 @@ const std::deque& LogInfo::OriginTimeStamData() const { return originTs_; } -void NativeHook::UpdateCallChainId(size_t row, uint32_t callChainId) +void NativeHookSampleBase::AppendNativeHookSampleBase(uint32_t callChainId, + uint32_t ipid, + uint32_t itid, + uint64_t timeStamp) { - if (row < Size()) { - callChainIds_[row] = callChainId; - } else { - TS_LOGE("Native hook update callChainId failed!!!"); + ids_.emplace_back(Size()); + callChainIds_.emplace_back(callChainId); + ipids_.emplace_back(ipid); + internalTids_.emplace_back(itid); + timeStamps_.emplace_back(timeStamp); + lastCallerPathIndexs_.emplace_back(INVALID_DATAINDEX); + lastSymbolIndexs_.emplace_back(INVALID_DATAINDEX); +} +void NativeHookSampleBase::AppendNativeHookSampleBase(uint32_t callChainId, uint32_t ipid, uint64_t timeStamp) +{ + ids_.emplace_back(Size()); + callChainIds_.emplace_back(callChainId); + ipids_.emplace_back(ipid); + timeStamps_.emplace_back(timeStamp); + lastCallerPathIndexs_.emplace_back(INVALID_DATAINDEX); + lastSymbolIndexs_.emplace_back(INVALID_DATAINDEX); +} +const std::deque& NativeHookSampleBase::CallChainIds() const +{ + return callChainIds_; +} +const std::deque& NativeHookSampleBase::Ipids() const +{ + return ipids_; +} +const std::deque& NativeHookSampleBase::LastCallerPathIndexs() const +{ + return lastCallerPathIndexs_; +} +const std::deque& NativeHookSampleBase::LastSymbolIndexs() const +{ + return lastSymbolIndexs_; +} +void NativeHookSampleBase::UpdateLastCallerPathAndSymbolIndexs( + std::unordered_map>& callIdToLasLibId) +{ + if (callIdToLasLibId.empty()) { + return; + } + for (auto i = 0; i < Size(); ++i) { + auto symbolIt = callIdToLasLibId.find(callChainIds_[i]); + if (symbolIt != callIdToLasLibId.end()) { + std::tie(lastCallerPathIndexs_[i], lastSymbolIndexs_[i]) = symbolIt->second; + } else { + lastCallerPathIndexs_[i] = INVALID_DATAINDEX; + lastSymbolIndexs_[i] = INVALID_DATAINDEX; + } } } size_t NativeHook::AppendNewNativeHookData(uint32_t callChainId, @@ -502,12 +548,9 @@ size_t NativeHook::AppendNewNativeHookData(uint32_t callChainId, uint64_t addr, int64_t memSize) { - callChainIds_.emplace_back(callChainId); - ipids_.emplace_back(ipid); - itids_.emplace_back(itid); + AppendNativeHookSampleBase(callChainId, ipid, itid, timeStamp); eventTypes_.emplace_back(eventType); subTypes_.emplace_back(subType); - timeStamps_.emplace_back(timeStamp); endTimeStamps_.emplace_back(endTimeStamp); durations_.emplace_back(duration); addrs_.emplace_back(addr); @@ -526,9 +569,16 @@ size_t NativeHook::AppendNewNativeHookData(uint32_t callChainId, allMemSizes_.emplace_back(countMmapSizes_); } currentSizeDurs_.emplace_back(0); - lastCallerPathIndexs_.emplace_back(INVALID_UINT64); return Size() - 1; } +void NativeHook::UpdateCallChainId(size_t row, uint32_t callChainId) +{ + if (row < Size()) { + callChainIds_[row] = callChainId; + } else { + TS_LOGE("Native hook update callChainId failed!!!"); + } +} void NativeHook::UpdateEndTimeStampAndDuration(size_t row, uint64_t endTimeStamp) { endTimeStamps_[row] = endTimeStamp; @@ -546,32 +596,6 @@ void NativeHook::UpdateMemMapSubType(uint64_t row, uint64_t tagId) TS_LOGE("subTypes_ row is invalid!"); } } -void NativeHook::UpdateLastCallerPathIndexs(std::unordered_map& callIdToLasLibId) -{ - if (callIdToLasLibId.empty()) { - return; - } - for (auto i = 0; i < Size(); ++i) { - auto symbolIt = callIdToLasLibId.find(callChainIds_[i]); - if (symbolIt != callIdToLasLibId.end()) { - lastCallerPathIndexs_[i] = symbolIt->second; - } else { - lastCallerPathIndexs_[i] = INVALID_UINT64; - } - } -} -const std::deque& NativeHook::CallChainIds() const -{ - return callChainIds_; -} -const std::deque& NativeHook::Ipids() const -{ - return ipids_; -} -const std::deque& NativeHook::Itids() const -{ - return itids_; -} const std::deque& NativeHook::EventTypes() const { return eventTypes_; @@ -604,10 +628,6 @@ const std::deque& NativeHook::CurrentSizeDurs() const { return currentSizeDurs_; } -const std::deque& NativeHook::LastCallerPathIndexs() const -{ - return lastCallerPathIndexs_; -} size_t NativeHookFrame::AppendNewNativeHookFrame(uint32_t callChainId, uint64_t depth, uint64_t ip, @@ -749,10 +769,7 @@ size_t NativeHookStatistic::AppendNewNativeHookStatistic(uint32_t ipid, uint64_t applySize, uint64_t releaseSize) { - ids_.emplace_back(Size()); - ipids_.emplace_back(ipid); - timeStamps_.emplace_back(timeStamp); - callChainIds_.emplace_back(callChainId); + AppendNativeHookSampleBase(callChainId, ipid, timeStamp); memoryTypes_.emplace_back(memoryType); applyCounts_.emplace_back(applyCount); memSubTypes_.emplace_back(subMemType); @@ -761,14 +778,7 @@ size_t NativeHookStatistic::AppendNewNativeHookStatistic(uint32_t ipid, releaseSizes_.emplace_back(releaseSize); return Size() - 1; } -const std::deque& NativeHookStatistic::Ipids() const -{ - return ipids_; -} -const std::deque& NativeHookStatistic::CallChainIds() const -{ - return callChainIds_; -} + const std::deque& NativeHookStatistic::MemoryTypes() const { return memoryTypes_; @@ -804,29 +814,35 @@ const std::deque& Hidump::Fpss() const return fpss_; } -size_t PerfCallChain::AppendNewPerfCallChain(uint64_t sampleId, - uint32_t callChainId, +size_t PerfCallChain::AppendNewPerfCallChain(uint32_t callChainId, + uint32_t depth, + uint64_t ip, uint64_t vaddrInFile, uint64_t fileId, uint64_t symbolId) { ids_.emplace_back(Size()); - sampleIds_.emplace_back(sampleId); callChainIds_.emplace_back(callChainId); + depths_.emplace_back(depth); + ips_.emplace_back(ip); vaddrInFiles_.emplace_back(vaddrInFile); fileIds_.emplace_back(fileId); symbolIds_.emplace_back(symbolId); names_.emplace_back(""); return Size() - 1; } -const std::deque& PerfCallChain::SampleIds() const -{ - return sampleIds_; -} const std::deque& PerfCallChain::CallChainIds() const { return callChainIds_; } +const std::deque& PerfCallChain::Depths() const +{ + return depths_; +} +const std::deque& PerfCallChain::Ips() const +{ + return ips_; +} const std::deque& PerfCallChain::VaddrInFiles() const { return vaddrInFiles_; @@ -851,8 +867,9 @@ void PerfCallChain::SetName(uint64_t index, const std::string& name) void PerfCallChain::Clear() { CacheBase::Clear(); - sampleIds_.clear(); callChainIds_.clear(); + depths_.clear(); + ips_.clear(); vaddrInFiles_.clear(); fileIds_.clear(); symbolIds_.clear(); diff --git a/trace_streamer/src/trace_data/trace_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype.h index 58334ef7..e1101899 100644 --- a/trace_streamer/src/trace_data/trace_stdtype.h +++ b/trace_streamer/src/trace_data/trace_stdtype.h @@ -740,8 +740,32 @@ private: std::deque contexts_ = {}; std::deque originTs_ = {}; }; +class NativeHookSampleBase : public CacheBase { +public: + void AppendNativeHookSampleBase(uint32_t callChainId, uint32_t ipid, uint32_t itid, uint64_t timeStamp); + void AppendNativeHookSampleBase(uint32_t callChainId, uint32_t ipid, uint64_t timeStamp); + const std::deque& CallChainIds() const; + const std::deque& Ipids() const; + const std::deque& LastCallerPathIndexs() const; + const std::deque& LastSymbolIndexs() const; + void UpdateLastCallerPathAndSymbolIndexs( + std::unordered_map>& callIdToLasLibId); + void Clear() override + { + CacheBase::Clear(); + callChainIds_.clear(); + ipids_.clear(); + lastCallerPathIndexs_.clear(); + lastSymbolIndexs_.clear(); + } -class NativeHook : public CacheBase { +public: + std::deque callChainIds_ = {}; + std::deque ipids_ = {}; + std::deque lastCallerPathIndexs_ = {}; + std::deque lastSymbolIndexs_ = {}; +}; +class NativeHook : public NativeHookSampleBase { public: size_t AppendNewNativeHookData(uint32_t callChainId, uint32_t ipid, @@ -757,10 +781,6 @@ public: void UpdateEndTimeStampAndDuration(size_t row, uint64_t endTimeStamp); void UpdateCurrentSizeDur(size_t row, uint64_t timeStamp); void UpdateMemMapSubType(uint64_t row, uint64_t tagId); - void UpdateLastCallerPathIndexs(std::unordered_map& callIdToLasLibId); - const std::deque& CallChainIds() const; - const std::deque& Ipids() const; - const std::deque& Itids() const; const std::deque& EventTypes() const; const std::deque& SubTypes() const; const std::deque& EndTimeStamps() const; @@ -769,13 +789,9 @@ public: const std::deque& MemSizes() const; const std::deque& AllMemSizes() const; const std::deque& CurrentSizeDurs() const; - const std::deque& LastCallerPathIndexs() const; void Clear() override { - CacheBase::Clear(); - callChainIds_.clear(); - ipids_.clear(); - itids_.clear(); + NativeHookSampleBase::Clear(); eventTypes_.clear(); subTypes_.clear(); endTimeStamps_.clear(); @@ -784,13 +800,9 @@ public: memSizes_.clear(); allMemSizes_.clear(); currentSizeDurs_.clear(); - lastCallerPathIndexs_.clear(); } private: - std::deque callChainIds_ = {}; - std::deque ipids_ = {}; - std::deque itids_ = {}; std::deque eventTypes_ = {}; std::deque subTypes_ = {}; std::deque endTimeStamps_ = {}; @@ -799,7 +811,6 @@ private: std::deque memSizes_ = {}; std::deque allMemSizes_ = {}; std::deque currentSizeDurs_ = {}; - std::deque lastCallerPathIndexs_ = {}; int64_t countHeapSizes_ = 0; int64_t countMmapSizes_ = 0; const std::string ALLOC_EVET = "AllocEvent"; @@ -876,7 +887,7 @@ private: std::map symbolIdToSymbolName_ = {}; }; -class NativeHookStatistic : public CacheBase { +class NativeHookStatistic : public NativeHookSampleBase { public: size_t AppendNewNativeHookStatistic(uint32_t ipid, uint64_t timeStamp, @@ -887,9 +898,6 @@ public: uint64_t releaseCount, uint64_t applySize, uint64_t releaseSize); - - const std::deque& Ipids() const; - const std::deque& CallChainIds() const; const std::deque& MemoryTypes() const; const std::deque& MemorySubTypes() const; const std::deque& ApplyCounts() const; @@ -898,11 +906,7 @@ public: const std::deque& ReleaseSizes() const; void Clear() override { - CacheBase::Clear(); - ids_.clear(); - ipids_.clear(); - callChainIds_.clear(); - timeStamps_.clear(); + NativeHookSampleBase::Clear(); memoryTypes_.clear(); applyCounts_.clear(); releaseCounts_.clear(); @@ -911,8 +915,6 @@ public: } private: - std::deque ipids_ = {}; - std::deque callChainIds_ = {}; std::deque memoryTypes_ = {}; std::deque memSubTypes_ = {}; std::deque applyCounts_ = {}; @@ -932,13 +934,15 @@ private: class PerfCallChain : public CacheBase { public: - size_t AppendNewPerfCallChain(uint64_t sampleId, - uint32_t callChainId, + size_t AppendNewPerfCallChain(uint32_t callChainId, + uint32_t depth, + uint64_t ip, uint64_t vaddrInFile, uint64_t fileId, uint64_t symbolId); - const std::deque& SampleIds() const; const std::deque& CallChainIds() const; + const std::deque& Depths() const; + const std::deque& Ips() const; const std::deque& VaddrInFiles() const; const std::deque& FileIds() const; const std::deque& SymbolIds() const; @@ -947,8 +951,9 @@ public: void Clear() override; private: - std::deque sampleIds_ = {}; std::deque callChainIds_ = {}; + std::deque depths_ = {}; + std::deque ips_ = {}; std::deque vaddrInFiles_ = {}; std::deque fileIds_ = {}; std::deque symbolIds_ = {}; diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp index 4a0ff1db..539112f2 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp @@ -78,9 +78,6 @@ TraceFileType GuessFileType(const uint8_t* data, size_t size) if (start.compare(0, std::string("PERFILE2").length(), "PERFILE2") == 0) { return TRACE_FILETYPE_PERF; } - if (start.compare(0, std::string("\x1f\x8b").length(), "\x1f\x8b") == 0) { - return TRACE_FILETYPE_PERF; - } const std::regex bytraceMatcher = std::regex(R"(-(\d+)\s+\(?\s*(\d+|-+)?\)?\s?\[(\d+)\]\s*)" R"([a-zA-Z0-9.]{0,5}\s+(\d+\.\d+):\s+(\S+):)"); std::smatch matcheLine; @@ -278,7 +275,7 @@ int32_t TraceStreamerSelector::SearchDatabase(const std::string& sql, uint8_t* o { return traceDataCache_->SearchDatabase(sql, out, outLen); } -int32_t TraceStreamerSelector::SearchDatabase(const std::string& sql, bool printf) +int32_t TraceStreamerSelector::SearchDatabase(std::string& sql, bool printf) { return traceDataCache_->SearchDatabase(sql, printf); } @@ -286,6 +283,27 @@ std::string TraceStreamerSelector::SearchDatabase(const std::string& sql) { return traceDataCache_->SearchDatabase(sql); } +void TraceStreamerSelector::InitMetricsMap(std::map& metricsMap) +{ + metricsMap.emplace(TRACE_MEM_UNAGG, memUnaggQuery); + metricsMap.emplace(TRACE_MEM, memQuery); + metricsMap.emplace(TRACE_MEM_TOP_TEN, memTopQuery); + metricsMap.emplace(TRACE_METADATA, metaDataQuery); + metricsMap.emplace(SYS_CALLS, sysCallQuery); + metricsMap.emplace(TRACE_STATS, traceStateQuery); + metricsMap.emplace(TRACE_TASK_NAMES, traceTaskName); +} +const std::string TraceStreamerSelector::MetricsSqlQuery(const std::string& metrics) +{ + std::map metricsMap; + InitMetricsMap(metricsMap); + auto itor = metricsMap.find(metrics); + if (itor == metricsMap.end()) { + TS_LOGE("metrics name error!!!"); + return ""; + } + return itor->second; +} int32_t TraceStreamerSelector::UpdateTraceRangeTime(uint8_t* data, int32_t len) { std::string traceRangeStr; diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.h b/trace_streamer/src/trace_streamer/trace_streamer_selector.h index afb380e4..da6bf57a 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.h +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.h @@ -17,6 +17,7 @@ #define TRACE_STREAMER_SELECTOR_H #include #include +#include "metrics.h" #include "trace_data/trace_data_cache.h" #include "trace_streamer_filters.h" @@ -38,7 +39,7 @@ public: int32_t OperateDatabase(const std::string& sql); int32_t SearchDatabase(const std::string& sql, TraceDataDB::ResultCallBack resultCallBack); int32_t SearchDatabase(const std::string& sql, uint8_t* out, int32_t outLen); - int32_t SearchDatabase(const std::string& sql, bool printf); + int32_t SearchDatabase(std::string& sql, bool printf); std::string SearchDatabase(const std::string& sql); int32_t UpdateTraceRangeTime(uint8_t* data, int32_t len); void WaitForParserEnd(); @@ -54,6 +55,8 @@ public: void UpdateTaskPoolTraceStatus(bool status); void UpdateAppStartTraceStatus(bool status); void UpdateBinderRunnableTraceStatus(bool status); + void InitMetricsMap(std::map& metricsMap); + const std::string MetricsSqlQuery(const std::string& metrics); private: void InitFilter(); diff --git a/trace_streamer/src/version.cpp b/trace_streamer/src/version.cpp index a23579e4..6358f438 100644 --- a/trace_streamer/src/version.cpp +++ b/trace_streamer/src/version.cpp @@ -14,5 +14,5 @@ */ #include "version.h" size_t g_loadSize = 0; -const std::string g_traceStreamerVersion = "3.4.8"; // version -const std::string g_traceStreamerPublishVersion = "2023/8/10"; // publish datetime +const std::string g_traceStreamerVersion = "3.4.9"; // version +const std::string g_traceStreamerPublishVersion = "2023/8/18"; // publish datetime diff --git a/trace_streamer/test/BUILD.gn b/trace_streamer/test/BUILD.gn index 097252ad..2b352af9 100755 --- a/trace_streamer/test/BUILD.gn +++ b/trace_streamer/test/BUILD.gn @@ -91,6 +91,7 @@ if (is_test) { "../src/table", "../src/table/base", "../src/filter", + "../src/metrics", "../src/base", "../src/rpc", "../src/include", diff --git a/trace_streamer/test/unittest/animation_filter_test.cpp b/trace_streamer/test/unittest/animation_filter_test.cpp index 4d618b25..1b11b314 100644 --- a/trace_streamer/test/unittest/animation_filter_test.cpp +++ b/trace_streamer/test/unittest/animation_filter_test.cpp @@ -132,9 +132,7 @@ HWTEST_F(AnimationFilterTest, UpdateDevicePos, TestSize.Level1) TS_LOGI("test36-3"); TracePoint point; BytraceLine line; - std::string validFuncPrefix{"H:RSUniRender::Process:[EntryView]"}; - std::vector invalidFuncArgs{ "()", "(1,)", @@ -149,7 +147,6 @@ HWTEST_F(AnimationFilterTest, UpdateDevicePos, TestSize.Level1) auto res = stream_.streamFilters_->animationFilter_->UpdateDeviceInfoEvent(point, line); EXPECT_FALSE(res); } - std::vector validFuncArgs{ "(0, 0, 1024, 1920)", "(0,0, 628, 720)", @@ -175,7 +172,6 @@ HWTEST_F(AnimationFilterTest, UpdateDeviceFps, TestSize.Level1) TS_LOGI("test36-4"); TracePoint point; BytraceLine line; - std::string validName{"H:GenerateVsyncCount:1"}; auto timeDiffFps60 = BILLION_NANOSECONDS / FPS_60; line.ts = 59557002299000; @@ -224,7 +220,6 @@ HWTEST_F(AnimationFilterTest, UpdateDynamicFrameInfo, TestSize.Level1) { TS_LOGI("test36-5"); TracePoint point; - CallStack* callStackSlice = stream_.traceDataCache_->GetInternalSlicesData(); std::vector callStackNames{ stream_.traceDataCache_->GetDataIndex("H:RSMainThread::OnVsync"), diff --git a/trace_streamer/test/unittest/hisys_event_parser_test.cpp b/trace_streamer/test/unittest/hisys_event_parser_test.cpp index 779c3164..37bdf5ce 100644 --- a/trace_streamer/test/unittest/hisys_event_parser_test.cpp +++ b/trace_streamer/test/unittest/hisys_event_parser_test.cpp @@ -19,6 +19,7 @@ #include "htrace_hisysevent_parser.h" #include "string_to_numerical.h" #include "trace_streamer_selector.h" +#include "hi_sysevent_measure_filter.h" using namespace testing::ext; using namespace SysTuning::TraceStreamer; @@ -53,8 +54,8 @@ HWTEST_F(HtraceHisysEventParserTest, ParseNoArray, TestSize.Level1) "0000\",\"pid_\":722,\"tid_\":3462,\"uid_\":1201,\"START_TIME\":22611696002,\"END_TIME\":23617705010,\"GAS_" "GAUGE\":124,\"LEVEL\":33,\"SCREEN\":11,\"CHARGE\":21,\"CURRENT\":-404,\"CAPACITY\":9898,\"level_\":\"MINOR\"," "\"id_\":\"16494176919818340149\",\"info_\":\"\"}"; - HtraceHisyseventParser::json jMessage; - HtraceHisyseventParser::JsonData jData; + json jMessage; + JsonData jData; size_t maxArraySize = 0; uint64_t serial = 1; std::vector noArrayIndex; @@ -63,7 +64,8 @@ HWTEST_F(HtraceHisysEventParserTest, ParseNoArray, TestSize.Level1) ss << jsMessage; ss >> jMessage; HtraceHisyseventParser HisysEvent(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); - (void)HisysEvent.JGetData(jMessage, jData, maxArraySize, noArrayIndex, arrayIndex); + (void)stream_.streamFilters_->hiSysEventMeasureFilter_->JGetData(jMessage, jData, maxArraySize, noArrayIndex, + arrayIndex); EXPECT_TRUE(jData.eventSource == "POWER_IDE_BATTERY"); EXPECT_EQ(jData.timeStamp, 22611696002); EXPECT_EQ(maxArraySize, 0); @@ -94,8 +96,8 @@ HWTEST_F(HtraceHisysEventParserTest, ParseHaveArrayData, TestSize.Level1) "\"BACKGROUND_ENERGY\":[638,65,12],\"SCREEN_ON_COUNT\":[23,558,75],\"SCREEN_ON_ENERGY\":[552,142,120],\"SCREEN_" "OFF_COUNT\":[78,354,21],\"SCREEN_OFF_ENERGY\":[352,65,436],\"level_\":\"MINOR\",\"id_\":" "\"17560016619580787102\",\"info_\":\"\"}"; - HtraceHisyseventParser::json jMessage; - HtraceHisyseventParser::JsonData jData; + json jMessage; + JsonData jData; size_t maxArraySize = 0; uint64_t serial = 1; std::vector noArrayIndex; @@ -104,7 +106,8 @@ HWTEST_F(HtraceHisysEventParserTest, ParseHaveArrayData, TestSize.Level1) ss << jsMessage; ss >> jMessage; HtraceHisyseventParser HisysEvent(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); - (void)HisysEvent.JGetData(jMessage, jData, maxArraySize, noArrayIndex, arrayIndex); + (void)stream_.streamFilters_->hiSysEventMeasureFilter_->JGetData(jMessage, jData, maxArraySize, noArrayIndex, + arrayIndex); EXPECT_TRUE(jData.eventSource == "POWER_IDE_WIFISCAN"); EXPECT_EQ(jData.timeStamp, 16611696002); EXPECT_EQ(maxArraySize, 3); @@ -144,8 +147,8 @@ HWTEST_F(HtraceHisysEventParserTest, MixedDataAnalysis, TestSize.Level1) jsMessage.push_back(jsMessage2); uint64_t serial = 1; for (auto i = jsMessage.begin(); i != jsMessage.end(); i++) { - HtraceHisyseventParser::json jMessage; - HtraceHisyseventParser::JsonData jData; + json jMessage; + JsonData jData; size_t maxArraySize = 0; std::vector noArrayIndex; std::vector arrayIndex; @@ -153,7 +156,8 @@ HWTEST_F(HtraceHisysEventParserTest, MixedDataAnalysis, TestSize.Level1) ss << *i; ss >> jMessage; HtraceHisyseventParser HisysEvent(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); - (void)HisysEvent.JGetData(jMessage, jData, maxArraySize, noArrayIndex, arrayIndex); + (void)stream_.streamFilters_->hiSysEventMeasureFilter_->JGetData(jMessage, jData, maxArraySize, noArrayIndex, + arrayIndex); if (jData.eventSource == "POWER_IDE_WIFISCAN") { EXPECT_TRUE(jData.eventSource == "POWER_IDE_WIFISCAN"); EXPECT_EQ(jData.timeStamp, 16611696002); diff --git a/trace_streamer/test/unittest/native_hook_parser_test.cpp b/trace_streamer/test/unittest/native_hook_parser_test.cpp index 780b1688..4138ca6f 100644 --- a/trace_streamer/test/unittest/native_hook_parser_test.cpp +++ b/trace_streamer/test/unittest/native_hook_parser_test.cpp @@ -118,7 +118,7 @@ public: } callChainId_ = nativeHook.CallChainIds()[index]; ipid_ = nativeHook.Ipids()[index]; - itid_ = nativeHook.Itids()[index]; + itid_ = nativeHook.InternalTidsData()[index]; eventType_ = nativeHook.EventTypes()[index]; subType_ = nativeHook.SubTypes()[index]; startTimeStamp_ = nativeHook.TimeStampData()[index]; diff --git a/trace_streamer/test/unittest/table_test.cpp b/trace_streamer/test/unittest/table_test.cpp index 79c5b4fa..b1af8b31 100644 --- a/trace_streamer/test/unittest/table_test.cpp +++ b/trace_streamer/test/unittest/table_test.cpp @@ -50,7 +50,7 @@ HWTEST_F(TableTest, AppnameTableTest, TestSize.Level1) DataIndex eventSource = stream_.traceDataCache_->GetDataIndex("eventSource"); DataIndex appName = stream_.traceDataCache_->GetDataIndex("app1"); stream_.traceDataCache_->GetAppNamesData()->AppendAppName(flags, eventSource, appName); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -78,17 +78,17 @@ HWTEST_F(TableTest, ArgsTableTest, TestSize.Level1) stream_.traceDataCache_->InitDB(); stream_.traceDataCache_->GetArgSetData()->AppendNewArg(nameId0, dataType0, value0, argSet0); stream_.traceDataCache_->GetArgSetData()->AppendNewArg(nameId1, dataType1, value1, argSet1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 2); } /** @@ -130,17 +130,17 @@ HWTEST_F(TableTest, CallstackTableTest, TestSize.Level1) startT, durationNs, internalTid, cat, nameIdentify, name, depth, cookid, parentId); stream_.traceDataCache_->GetInternalSlicesData()->AppendInternalAsyncSlice( startT1, durationNs1, internalTid1, cat1, nameIdentify1, name1, depth1, cookid1, parentId1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 0); } /** @@ -168,17 +168,17 @@ HWTEST_F(TableTest, ClkEventFilterTableTest, TestSize.Level1) uint64_t cpu1 = 1; stream_.traceDataCache_->GetClkEventFilterData()->AppendNewFilter(id, rate, name, cpu); stream_.traceDataCache_->GetClkEventFilterData()->AppendNewFilter(id1, rate1, name1, cpu1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 2); } /** @@ -206,17 +206,17 @@ HWTEST_F(TableTest, ClockEventFilterTableTest, TestSize.Level1) uint64_t cpu1 = 1; stream_.traceDataCache_->GetClockEventFilterData()->AppendNewFilter(id, type, name, cpu); stream_.traceDataCache_->GetClockEventFilterData()->AppendNewFilter(id1, type1, name1, cpu1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 2); } /** @@ -243,17 +243,17 @@ HWTEST_F(TableTest, CpuMeasureFilterTableTest, TestSize.Level1) stream_.traceDataCache_->GetCpuMeasuresData()->AppendNewFilter(filterId, name, cpu); stream_.traceDataCache_->GetCpuMeasuresData()->AppendNewFilter(filterId1, name1, cpu1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 1); } /** @@ -281,10 +281,10 @@ HWTEST_F(TableTest, CpuUsageFilterTableTest, TestSize.Level1) stream_.traceDataCache_->GetCpuUsageInfoData()->AppendNewData(newTimeStamp, dur, totalLoad, userLoad, userLoad, thread); - stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + stream_.traceDataCache_->SearchDatabase(sqlSelect, false); stream_.traceDataCache_->GetCpuUsageInfoData()->AppendNewData(newTimeStamp1, dur1, totalLoad1, userLoad1, userLoad1, thread1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); } /** @@ -302,17 +302,17 @@ HWTEST_F(TableTest, DataDictTableTest, TestSize.Level1) std::string sqlSelect4 = "select * from data_dict where id >= 1"; std::string sqlSelect5 = "select * from data_dict where data <= 1"; stream_.traceDataCache_->GetDataFromDict(1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 61); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 59); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 60); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 1); } /** @@ -336,17 +336,17 @@ HWTEST_F(TableTest, DataTypeTableTest, TestSize.Level1) stream_.traceDataCache_->GetDataTypeData()->AppendNewDataType(dataType, dataDescIndex); stream_.traceDataCache_->GetDataTypeData()->AppendNewDataType(dataType1, dataDescIndex1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 6); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 4); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 4); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 2); } /** @@ -371,7 +371,7 @@ HWTEST_F(TableTest, DiskIoTableTest, TestSize.Level1) stream_.traceDataCache_->GetDiskIOData()->AppendNewData(ts, dur, rd, wr, rdPerSec, wrPerSec, rdCountPerSec, wrCountPerSec, rdCount, wrCount); - stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + stream_.traceDataCache_->SearchDatabase(sqlSelect, false); } /** * @tc.name: EbpfCallstackTableTest @@ -408,22 +408,22 @@ HWTEST_F(TableTest, EbpfCallstackTableTest, TestSize.Level1) stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timeStamp, fps); stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timestamp1, fps1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect6.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect6, false); EXPECT_EQ(row, 2); stream_.traceDataCache_->GetEbpfCallStack()->AppendNewData(callChainId, depth, ip, symbolId, filePathId); stream_.traceDataCache_->GetEbpfCallStack()->AppendNewData(callChainId1, depth1, ip1, symbolId1, filePathId1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 2); } /** @@ -483,11 +483,11 @@ HWTEST_F(TableTest, FileSystemSampleTableTest, TestSize.Level1) stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timeStamp, fps); stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timestamp1, fps1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 0); stream_.traceDataCache_->GetFileSystemSample()->AppendNewData( @@ -496,11 +496,11 @@ HWTEST_F(TableTest, FileSystemSampleTableTest, TestSize.Level1) stream_.traceDataCache_->GetFileSystemSample()->AppendNewData( callChainId1, type1, ipid1, itid1, startTs1, endTs1, dur1, returnValue1, errorCode1, size1, fd1, fileId1, firstArgument1, secondArgument1, thirdArgument1, fourthArgument1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); } /** @@ -516,7 +516,7 @@ HWTEST_F(TableTest, HidumpTableTest, TestSize.Level1) uint32_t fps = 1; stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timeStamp, fps); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -538,7 +538,7 @@ HWTEST_F(TableTest, HisysEventMeasureTableTest, TestSize.Level1) stream_.traceDataCache_->GetSyseventMeasureData()->AppendData(ts, nameId, keyId, type, numericValue, stringValue, serial); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -575,22 +575,22 @@ HWTEST_F(TableTest, InstantTableTest, TestSize.Level1) stream_.traceDataCache_->GetMeasureData()->AppendMeasureData(type, timeStamp, value, filterId); stream_.traceDataCache_->GetMeasureData()->AppendMeasureData(type1, timestamp1, value1, filterId1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); stream_.traceDataCache_->GetInstantsData()->AppendInstantEventData(timeStamp, nameIndex, internalTid, wakeupFromInternalPid); stream_.traceDataCache_->GetInstantsData()->AppendInstantEventData(timestamp1, nameIndex1, internalTid1, wakeupFromInternalPid1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 0); } /** @@ -638,7 +638,7 @@ HWTEST_F(TableTest, IoLatencySampleTableTest, TestSize.Level1) stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timeStamp, fps); stream_.traceDataCache_->GetHidumpData()->AppendNewHidumpInfo(timestamp1, fps1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); stream_.traceDataCache_->GetBioLatencySampleData()->AppendNewData( @@ -646,9 +646,9 @@ HWTEST_F(TableTest, IoLatencySampleTableTest, TestSize.Level1) stream_.traceDataCache_->GetBioLatencySampleData()->AppendNewData(callChainId1, type1, ipid1, itid1, startTs1, endTs1, latencyDur1, tier1, size1, blockNumber1, filePathId1, durPer4k1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); } /** @@ -683,9 +683,9 @@ HWTEST_F(TableTest, IrqTableTest, TestSize.Level1) depth, parentId); stream_.traceDataCache_->GetIrqData()->AppendInternalSlice(startT1, durationNs1, internalTid1, cat1, nameIdentify1, name1, depth1, parentId1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); } /** @@ -714,7 +714,7 @@ HWTEST_F(TableTest, LiveProcessTableTest, TestSize.Level1) stream_.traceDataCache_->GetLiveProcessData()->AppendNewData(newTimeStamp, dur, processID, processName, parentProcessID, uid, userName, cpuUsage, pssInfo, cpuTime, threads, diskWrites, diskReads); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -736,7 +736,7 @@ HWTEST_F(TableTest, LogTableTest, TestSize.Level1) uint64_t originTs = 1; stream_.traceDataCache_->GetHilogData()->AppendNewLogInfo(seq, timeStamp, pid, tid, level, tag, context, originTs); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -761,9 +761,9 @@ HWTEST_F(TableTest, MeasureTableTest, TestSize.Level1) stream_.traceDataCache_->GetMeasureData()->AppendMeasureData(type, timeStamp, value, filterId); stream_.traceDataCache_->GetMeasureData()->AppendMeasureData(type1, timestamp1, value1, filterId1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); } /** @@ -781,7 +781,7 @@ HWTEST_F(TableTest, MeasureFilterTableTest, TestSize.Level1) uint64_t internalTid = 1; stream_.traceDataCache_->GetThreadMeasureFilterData()->AppendNewFilter(filterId, nameIndex, internalTid); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 0); } /** @@ -795,7 +795,7 @@ HWTEST_F(TableTest, MetaTableTest, TestSize.Level1) std::string sqlSelect = "select * from meta"; stream_.traceDataCache_->GetMetaData(); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 9); } /** @@ -839,15 +839,15 @@ HWTEST_F(TableTest, NativeHookTableTest, TestSize.Level1) callChainId, ipid, itid, eventType, subType, timeStamp, endTimestamp, duration, addr, memSize); stream_.traceDataCache_->GetNativeHookData()->AppendNewNativeHookData( callChainId1, ipid1, itid1, eventType1, subType1, timestamp1, endTimestamp1, duration1, addr1, memSize1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); } /** @@ -888,15 +888,15 @@ HWTEST_F(TableTest, NativeHookFrameTableTest, TestSize.Level1) stream_.traceDataCache_->GetNativeHookFrameData()->AppendNewNativeHookFrame( callChainId1, depth1, ip1, sp1, symbolName1, filePath1, offset1, symbolOffset1, vaddr1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); } /** @@ -922,7 +922,7 @@ HWTEST_F(TableTest, NetworkTableTest, TestSize.Level1) stream_.traceDataCache_->GetNetworkData()->AppendNewNetData(newTimeStamp, tx, rx, dur, rxSpeed, txSpeed, packetIn, packetInSec, packetOut, packetOutSec, netType); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -938,32 +938,34 @@ HWTEST_F(TableTest, PerfCallchainTableTest, TestSize.Level1) std::string sqlSelect2 = "select * from perf_callchain where callchain_id > 1"; std::string sqlSelect3 = "select * from perf_callchain where file_id < 1"; std::string sqlSelect4 = "select * from perf_callchain where symbol_id >= 1"; - uint64_t sampleId = stream_.traceDataCache_->GetDataIndex("sample"); uint64_t callChainId = stream_.traceDataCache_->GetDataIndex("callChain"); + uint32_t depth = 0; + uint64_t ip = 123; uint64_t vaddrInFile = 1; uint64_t fileId = stream_.traceDataCache_->GetDataIndex("file"); uint64_t symbolId = stream_.traceDataCache_->GetDataIndex("symbolId"); - uint64_t sampleId1 = stream_.traceDataCache_->GetDataIndex("sample1"); - uint64_t callChainId1 = stream_.traceDataCache_->GetDataIndex("callChain1"); + uint64_t callChainId1 = 2; + uint32_t depth1 = 1; + uint64_t ip1 = 234; uint64_t vaddrInFile1 = 2; uint64_t fileId1 = stream_.traceDataCache_->GetDataIndex("file1"); uint64_t symbolId1 = stream_.traceDataCache_->GetDataIndex("symbolId1"); - stream_.traceDataCache_->GetPerfCallChainData()->AppendNewPerfCallChain(sampleId, callChainId, vaddrInFile, fileId, + stream_.traceDataCache_->GetPerfCallChainData()->AppendNewPerfCallChain(callChainId, depth, vaddrInFile, ip, fileId, symbolId); - stream_.traceDataCache_->GetPerfCallChainData()->AppendNewPerfCallChain(sampleId1, callChainId1, vaddrInFile1, + stream_.traceDataCache_->GetPerfCallChainData()->AppendNewPerfCallChain(callChainId1, depth1, vaddrInFile1, ip1, fileId1, symbolId1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); } /** @@ -989,11 +991,11 @@ HWTEST_F(TableTest, PerfFilesTableTest, TestSize.Level1) stream_.traceDataCache_->GetPerfFilesData()->AppendNewPerfFiles(fileIds, serial, symbols, filePath); stream_.traceDataCache_->GetPerfFilesData()->AppendNewPerfFiles(fileIds1, serial1, symbols1, filePath1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); } /** @@ -1009,7 +1011,7 @@ HWTEST_F(TableTest, PerfReportTableTest, TestSize.Level1) DataIndex value = stream_.traceDataCache_->GetDataIndex("value"); stream_.traceDataCache_->GetPerfReportData()->AppendNewPerfReport(type, value); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1048,17 +1050,17 @@ HWTEST_F(TableTest, PerfSampleTableTest, TestSize.Level1) timestampTrace, cpuId, threadState); stream_.traceDataCache_->GetPerfSampleData()->AppendNewPerfSample( sampleId1, timestamp1, tid1, eventCount1, eventTypeId1, timestampTrace1, cpuId1, threadState1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 1); } /** @@ -1083,13 +1085,13 @@ HWTEST_F(TableTest, PerfThreadTableTest, TestSize.Level1) stream_.traceDataCache_->GetPerfThreadData()->AppendNewPerfThread(pid, tid, threadName); stream_.traceDataCache_->GetPerfThreadData()->AppendNewPerfThread(pid1, tid1, threadName1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); } /** @@ -1103,9 +1105,9 @@ HWTEST_F(TableTest, ProcessTableTest, TestSize.Level1) std::string sqlSelect = "select * from process"; std::string sqlSelect1 = "select * from process where id = 1"; - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 0); } /** @@ -1122,7 +1124,7 @@ HWTEST_F(TableTest, ProcessFilterTableTest, TestSize.Level1) uint32_t internalPid = 1; stream_.traceDataCache_->GetProcessFilterData()->AppendNewFilter(id, name, internalPid); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1140,7 +1142,7 @@ HWTEST_F(TableTest, ProcessMeasureTableTest, TestSize.Level1) uint32_t filterId = 1; stream_.traceDataCache_->GetProcessMeasureData()->AppendMeasureData(type, timeStamp, value, filterId); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1165,13 +1167,13 @@ HWTEST_F(TableTest, ProcessMeasureFilterTableTest, TestSize.Level1) stream_.traceDataCache_->GetProcessMeasureFilterData()->AppendNewFilter(id, name, internalPid); stream_.traceDataCache_->GetProcessMeasureFilterData()->AppendNewFilter(id1, name1, internalPid1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 2); } /** @@ -1201,15 +1203,15 @@ HWTEST_F(TableTest, RawTableTest, TestSize.Level1) stream_.traceDataCache_->GetRawData()->AppendRawData(id, timeStamp, name, cpu, internalTid); stream_.traceDataCache_->GetRawData()->AppendRawData(id1, timestamp1, name1, cpu1, internalTid1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); } /** @@ -1243,19 +1245,19 @@ HWTEST_F(TableTest, SchedSliceTest, TestSize.Level1) stream_.traceDataCache_->GetSchedSliceData()->AppendSchedSlice(ts, dur, cpu, internalTid, endState, priority); stream_.traceDataCache_->GetSchedSliceData()->AppendSchedSlice(ts1, dur1, cpu1, internalTid1, endState1, priority1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect6.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect6, false); EXPECT_EQ(row, 0); } /** @@ -1291,7 +1293,7 @@ HWTEST_F(TableTest, SmapsTest, TestSize.Level1) stream_.traceDataCache_->GetSmapsData()->AppendNewData( timeStamp, ipid, startAddr, endAddr, dirty, swapper, rss, pss, size, reside, protectionId, pathId, sharedClean, sharedDirty, privateClean, privateDirty, swap, swapPss, type); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1304,7 +1306,7 @@ HWTEST_F(TableTest, StatTableTest, TestSize.Level1) TS_LOGI("test31-38"); std::string sqlSelect = "select * from stat"; stream_.traceDataCache_->GetStatAndInfo(); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 430); } /** @@ -1326,11 +1328,11 @@ HWTEST_F(TableTest, SymbolsTableTest, TestSize.Level1) stream_.traceDataCache_->GetSymbolsData()->InsertSymbol(name, addr); stream_.traceDataCache_->GetSymbolsData()->InsertSymbol(name1, addr1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); } /** @@ -1349,7 +1351,7 @@ HWTEST_F(TableTest, SyscallTableTest, TestSize.Level1) int64_t ret = 1; stream_.traceDataCache_->GetSysCallData()->AppendSysCallData(sysCallNum, type, ipid, timeStamp, ret); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1376,17 +1378,17 @@ HWTEST_F(TableTest, SysEventFilterTableTest, TestSize.Level1) stream_.traceDataCache_->GetSysMeasureFilterData()->AppendNewFilter(filterId, type, nameId); stream_.traceDataCache_->GetSysMeasureFilterData()->AppendNewFilter(filterId1, type1, nameId1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 2); } /** @@ -1404,7 +1406,7 @@ HWTEST_F(TableTest, SysMemMeasureTableTest, TestSize.Level1) uint32_t filterId = stream_.traceDataCache_->GetDataIndex("filter"); stream_.traceDataCache_->GetSysMemMeasureData()->AppendMeasureData(type, timeStamp, value, filterId); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1417,7 +1419,7 @@ HWTEST_F(TableTest, ThreadTableTest, TestSize.Level1) TS_LOGI("test31-43"); std::string sqlSelect = "select * from thread"; - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1434,7 +1436,7 @@ HWTEST_F(TableTest, ThreadFilterTableTest, TestSize.Level1) uint64_t internalTid = 1; stream_.traceDataCache_->GetThreadFilterData()->AppendNewFilter(filterId, nameIndex, internalTid); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } /** @@ -1468,23 +1470,23 @@ HWTEST_F(TableTest, ThreadStateTableTest, TestSize.Level1) stream_.traceDataCache_->GetThreadStateData()->AppendThreadState(ts, dur, cpu, itid, idState); stream_.traceDataCache_->GetThreadStateData()->AppendThreadState(ts1, dur1, cpu1, itid1, idState1); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect1.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect2.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect2, false); EXPECT_EQ(row, 2); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect3.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect3, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect4.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect4, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect5.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect5, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect6.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect6, false); EXPECT_EQ(row, 1); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect7.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect7, false); EXPECT_EQ(row, 0); - row = stream_.traceDataCache_->SearchDatabase(sqlSelect8.c_str(), false); + row = stream_.traceDataCache_->SearchDatabase(sqlSelect8, false); EXPECT_EQ(row, 0); } /** @@ -1498,7 +1500,7 @@ HWTEST_F(TableTest, TraceRangeTableTest, TestSize.Level1) std::string sqlSelect = "select * from trace_range"; stream_.traceDataCache_->UpdateTraceRange(); - auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect.c_str(), false); + auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 1); } } // namespace TraceStreamer diff --git a/trace_streamer/test/unittest/task_pool_filter_test.cpp b/trace_streamer/test/unittest/task_pool_filter_test.cpp index c0979f45..e16a015a 100644 --- a/trace_streamer/test/unittest/task_pool_filter_test.cpp +++ b/trace_streamer/test/unittest/task_pool_filter_test.cpp @@ -51,7 +51,67 @@ HWTEST_F(TaskPoolFilterTest, CheckTheSameTaskTest, TestSize.Level1) uint32_t res = stream_.streamFilters_->taskPoolFilter_->CheckTheSameTask(executeId, index); EXPECT_EQ(res, INVALID_INT32); } +class TaskPoolData { +public: + TaskPoolData(InternalTid expectAllocationItid, + InternalTid expectExecuteItid, + InternalTid expectReturnItid, + uint32_t executeId, + uint32_t priority, + uint32_t executeState, + uint32_t returnState) + : expectAllocationItid_(expectAllocationItid), + expectExecuteItid_(expectExecuteItid), + expectReturnItid_(expectReturnItid), + executeId_(executeId), + priority_(priority), + executeState_(executeState), + returnState_(returnState){}; + TaskPoolData(size_t index, const TaskPoolInfo* taskpool) + : expectAllocationItid_(taskpool->allocationItids_[index]), + expectExecuteItid_(taskpool->executeItids_[index]), + expectReturnItid_(taskpool->returnItids_[index]), + executeId_(taskpool->executeIds_[index]), + priority_(taskpool->prioritys_[index]), + executeState_(taskpool->executeStates_[index]), + returnState_(taskpool->returnStates_[index]){}; + friend bool operator==(const TaskPoolData& first, const TaskPoolData& second); + +private: + InternalTid expectAllocationItid_; + InternalTid expectExecuteItid_; + InternalTid expectReturnItid_; + uint32_t executeId_; + uint32_t priority_; + uint32_t executeState_; + uint32_t returnState_; +}; +bool operator==(const TaskPoolData& first, const TaskPoolData& second) +{ + if (first.expectAllocationItid_ != second.expectAllocationItid_) { + return false; + } + if (first.expectExecuteItid_ != second.expectExecuteItid_) { + return false; + } + if (first.expectReturnItid_ != second.expectReturnItid_) { + return false; + } + if (first.executeId_ != second.executeId_) { + return false; + } + if (first.priority_ != second.priority_) { + return false; + } + if (first.executeState_ != second.executeState_) { + return false; + } + if (first.returnState_ != second.returnState_) { + return false; + } + return true; +} /** * @tc.name: TaskPoolEventTest1 * @tc.desc: TaskPoolEvent function Test @@ -68,56 +128,25 @@ HWTEST_F(TaskPoolFilterTest, TaskPoolEventTest1, TestSize.Level1) stream_.traceDataCache_->taskPoolTraceEnabled_ = true; PrintEventParser printEvent(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - auto res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 9); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, INVALID_INT32); + + TaskPoolData firstResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData firstExpect(1, INVALID_INT32, INVALID_INT32, 9, 1, 1, INVALID_INT32); + EXPECT_TRUE(firstResult == firstExpect); comm = "e.myapplication"; taskPoolStr = "B|16502|H:Task Perform: taskId : 1, executeId : 9"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 9); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, INVALID_INT32); + + TaskPoolData secondResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData secondExpect(1, 1, INVALID_INT32, 9, 1, 1, INVALID_INT32); + EXPECT_TRUE(secondResult == secondExpect); comm = "TaskWorkThread"; taskPoolStr = "H:Task PerformTask End: taskId : 1, executeId : 9, performResult : IsCanceled"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 9); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, INVALID_INT32); + TaskPoolData thirdResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData thirdExpect(1, 1, INVALID_INT32, 9, 1, 1, INVALID_INT32); + EXPECT_TRUE(thirdResult == thirdExpect); } /** @@ -136,56 +165,23 @@ HWTEST_F(TaskPoolFilterTest, TaskPoolEventTest2, TestSize.Level1) stream_.traceDataCache_->taskPoolTraceEnabled_ = true; PrintEventParser printEvent(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - auto res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, INVALID_INT32); + TaskPoolData firstResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData firstExpect(INVALID_INT32, 1, INVALID_INT32, 1, INVALID_INT32, INVALID_INT32, INVALID_INT32); + EXPECT_TRUE(firstResult == firstExpect); comm = "e.myapplication"; taskPoolStr = "B|16502|H:Task Allocation: taskId : 1, executeId : 1, priority : 1, executeState : 1"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, INVALID_INT32); + TaskPoolData secondResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData secondExpect(1, 1, INVALID_INT32, 1, 1, 1, INVALID_INT32); + EXPECT_TRUE(secondResult == secondExpect); comm = "TaskWorkThread"; taskPoolStr = "B|16502|H:Task PerformTask End: taskId : 1, executeId : 1, performResult : IsCanceled"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, 0); + TaskPoolData thirdResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData thirdExpect(1, 1, 1, 1, 1, 1, 0); + EXPECT_TRUE(thirdResult == thirdExpect); } /** @@ -204,61 +200,28 @@ HWTEST_F(TaskPoolFilterTest, TaskPoolEventTest3, TestSize.Level1) stream_.traceDataCache_->taskPoolTraceEnabled_ = true; PrintEventParser printEvent(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - auto res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, 1); + TaskPoolData firstResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData firstExpect(INVALID_INT32, INVALID_INT32, 1, 1, INVALID_INT32, INVALID_INT32, 1); + EXPECT_TRUE(firstResult == firstExpect); comm = "e.myapplication"; taskPoolStr = "B|16502|H:Task Allocation: taskId : 1, executeId : 1, priority : 1, executeState : 1"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, INVALID_INT32); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, 1); + TaskPoolData secondResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData secondExpect(1, INVALID_INT32, 1, 1, 1, 1, 1); + EXPECT_TRUE(secondResult == secondExpect); comm = "TaskWorkThread"; taskPoolStr = "B|16502|H:Task Perform: taskId : 1, executeId : 1"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->allocationItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnItids_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeIds_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->prioritys_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->executeStates_[0]; - EXPECT_EQ(res, 1); - res = stream_.traceDataCache_->GetTaskPoolData()->returnStates_[0]; - EXPECT_EQ(res, 1); + TaskPoolData thirdResult(0, stream_.traceDataCache_->GetTaskPoolData()); + TaskPoolData thirdExpect(1, 1, 1, 1, 1, 1, 1); + EXPECT_TRUE(thirdResult == thirdExpect); comm = "TaskWorkThread"; taskPoolStr = "B|16502|H:Thread Timeout Exit"; printEvent.ParsePrintEvent(comm, ts, pid, taskPoolStr, line); - res = stream_.traceDataCache_->GetTaskPoolData()->timeoutRows_[0]; + auto res = stream_.traceDataCache_->GetTaskPoolData()->timeoutRows_[0]; EXPECT_EQ(res, 3); } } // namespace TraceStreamer -- Gitee From f56cb8c642e9035d5db9333987a09384be24c91f Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:36:18 +0800 Subject: [PATCH 17/18] =?UTF-8?q?=E2=80=99add.html.trace.and.text.hilog.ut?= =?UTF-8?q?=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- trace_streamer/test/BUILD.gn | 1 + .../test/unittest/bytrace_parser_test.cpp | 64 +++++++++++++++++++ .../test/unittest/hilog_parser_test.cpp | 55 ++++++++++++++++ 3 files changed, 120 insertions(+) diff --git a/trace_streamer/test/BUILD.gn b/trace_streamer/test/BUILD.gn index 2b352af9..2a271184 100755 --- a/trace_streamer/test/BUILD.gn +++ b/trace_streamer/test/BUILD.gn @@ -99,6 +99,7 @@ if (is_test) { "../src/parser/bytrace_parser", "../src/parser", "../src/cfg", + "../src/metrics", "../src/parser/ebpf_parser", "../src/proto_reader", "../src/proto_reader/include", diff --git a/trace_streamer/test/unittest/bytrace_parser_test.cpp b/trace_streamer/test/unittest/bytrace_parser_test.cpp index de29a043..12154854 100644 --- a/trace_streamer/test/unittest/bytrace_parser_test.cpp +++ b/trace_streamer/test/unittest/bytrace_parser_test.cpp @@ -240,5 +240,69 @@ HWTEST_F(BytraceParserTest, LineParserWithInvalidTs, TestSize.Level1) EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 0); EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); } + +/** + * @tc.name: NomalHtmlBytraceFile + * @tc.desc: Test ParseTraceDataItem interface Parse normal html format bytrace data + * @tc.type: FUNC + */ +HWTEST_F(BytraceParserTest, NomalHtmlBytraceFile, TestSize.Level1) +{ + TS_LOGI("test2-10"); + constexpr uint32_t bufSize = 1024; + auto buf = std::make_unique(bufSize); + char realBuf[] = "\r\n\r\n\r\n\n"; + auto realBufSize = sizeof(realBuf); + + if (memcpy_s(buf.get(), bufSize, realBuf, realBufSize)) { + EXPECT_TRUE(false); + return; + } + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), realBufSize); + bytraceParser.WaitForParserEnd(); + stream_.traceDataCache_->ExportDatabase(dbPath_); + EXPECT_TRUE(access(dbPath_.c_str(), F_OK) == 0); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 1); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 0); +} + +/** + * @tc.name: MultiScriptHtmlBytraceFile + * @tc.desc: Test ParseTraceDataItem interface Parse html format bytrace data with multiple script section + * @tc.type: FUNC + */ +HWTEST_F(BytraceParserTest, MultiScriptHtmlBytraceFile, TestSize.Level1) +{ + TS_LOGI("test2-11"); + constexpr uint32_t bufSize = 1024; + auto buf = std::make_unique(bufSize); + char realBuf[] = "\r\n\r\n\r\n" + "\n"; + auto realBufSize = sizeof(realBuf); + if (memcpy_s(buf.get(), bufSize, realBuf, realBufSize)) { + EXPECT_TRUE(false); + return; + } + BytraceParser bytraceParser(stream_.traceDataCache_.get(), stream_.streamFilters_.get()); + bytraceParser.ParseTraceDataSegment(std::move(buf), realBufSize); + bytraceParser.WaitForParserEnd(); + stream_.traceDataCache_->ExportDatabase(dbPath_); + EXPECT_TRUE(access(dbPath_.c_str(), F_OK) == 0); + EXPECT_TRUE(bytraceParser.TraceCommentLines() == 0); + EXPECT_TRUE(bytraceParser.ParsedTraceValidLines() == 1); + EXPECT_TRUE(bytraceParser.ParsedTraceInvalidLines() == 1); +} + } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/test/unittest/hilog_parser_test.cpp b/trace_streamer/test/unittest/hilog_parser_test.cpp index 5507cc1d..179d289f 100644 --- a/trace_streamer/test/unittest/hilog_parser_test.cpp +++ b/trace_streamer/test/unittest/hilog_parser_test.cpp @@ -375,5 +375,60 @@ HWTEST_F(HilogParserTest, ParseHilogInfoHasDuplicateHilogLine, TestSize.Level1) eventCount = stream_.traceDataCache_->GetConstStatAndInfo().GetValue(TRACE_HILOG, STAT_EVENT_NOTMATCH); EXPECT_TRUE(1 == eventCount); } + +/** + * @tc.name: ParseTxtHilogInfo + * @tc.desc: Parse a text format HilogInfo + * @tc.type: FUNC + */ +HWTEST_F(HilogParserTest, ParseTxtHilogInfo, TestSize.Level1) +{ + TS_LOGI("test8-7"); + constexpr size_t readSize = 1024; + constexpr uint32_t lineLength = 256; + char data[] = "08-07 11:04:45.947 523 640 E C04200/Root: <205>cannot find windowNode\n"; + + std::unique_ptr ta = + std::make_unique(); + ta->EnableMetaTable(false); + + std::unique_ptr buf = std::make_unique(readSize); + memcpy_s(buf.get(), readSize, data, sizeof(data)); + + EXPECT_TRUE(ta->ParseTraceDataSegment(std::move(buf), sizeof(data))); + ta->WaitForParserEnd(); + + EXPECT_TRUE(ta->traceDataCache_->GetConstHilogData().HilogLineSeqs().size() == 1); +} + +/** + * @tc.name: ParseTxtHilogInfoWithTimeFormat + * @tc.desc: Parse a text format HilogInfo with different time format + * @tc.type: FUNC + */ +HWTEST_F(HilogParserTest, ParseTxtHilogInfoWithTimeFormat, TestSize.Level1) +{ + TS_LOGI("test8-7"); + constexpr size_t readSize = 1024; + constexpr uint32_t lineLength = 256; + char data[] = "08-07 11:04:45.947 523 640 E C04200/Root: <205>cannot find windowNode\n" + "CST 08-05 17:41:00.039 955 955 I C03900/Ace: [list_layout_algorithm.cpp(Measure)-(0)] child size is empty\n" + "CST 2017-08-05 17:41:19.409 840 926 I C01560/WifiDeviceServiceImpl: thread work normally\n" + "1501926013.969 1585 1585 I C02d10/HiView-DOCDB: close ejdb success\n" + "2337.006 601 894 E C01200/Ces: [access_token_helper.cpp:(RecordSensitivePermissionUsage):52] permission denied\n"; + + std::unique_ptr ta = + std::make_unique(); + ta->EnableMetaTable(false); + + std::unique_ptr buf = std::make_unique(readSize); + memcpy_s(buf.get(), readSize, data, sizeof(data)); + + EXPECT_TRUE(ta->ParseTraceDataSegment(std::move(buf), sizeof(data))); + ta->WaitForParserEnd(); + + EXPECT_TRUE(ta->traceDataCache_->GetConstHilogData().HilogLineSeqs().size() == 5); +} + } // namespace TraceStreamer } // namespace SysTuning \ No newline at end of file -- Gitee From d6b60df3c3a2bc154c36ce00b00be77d552e0cc9 Mon Sep 17 00:00:00 2001 From: zhangzepeng Date: Mon, 28 Aug 2023 11:39:52 +0800 Subject: [PATCH 18/18] =?UTF-8?q?=E2=80=99support.parse.two.thread.change.?= =?UTF-8?q?cpu.and.fix.code.style=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzepeng --- .../table/gpu_counter_object_table.cpp | 8 ++-- .../sdk/demo_sdk/table/gpu_counter_table.cpp | 10 ++--- .../sdk/demo_sdk/table/meta_table.cpp | 8 ++-- .../sdk/demo_sdk/table/slice_object_table.cpp | 8 ++-- .../sdk/demo_sdk/table/slice_table.cpp | 12 +++--- .../table/gpu_counter_object_table.cpp | 8 ++-- .../sdk/dubai_sdk/table/gpu_counter_table.cpp | 10 ++--- .../sdk/dubai_sdk/table/meta_table.cpp | 8 ++-- .../dubai_sdk/table/slice_object_table.cpp | 8 ++-- .../sdk/dubai_sdk/table/slice_table.cpp | 16 +++---- .../sdk/dubai_sdk/table/table_base.cpp | 16 +++---- trace_streamer/src/filter/cpu_filter.cpp | 42 ++++++++++++------- .../htrace_event_parser.cpp | 3 ++ .../src/parser/print_event_parser.h | 2 +- trace_streamer/src/parser/thread_state_flag.h | 2 +- .../test/unittest/hisys_event_parser_test.cpp | 3 +- 16 files changed, 89 insertions(+), 75 deletions(-) diff --git a/trace_streamer/sdk/demo_sdk/table/gpu_counter_object_table.cpp b/trace_streamer/sdk/demo_sdk/table/gpu_counter_object_table.cpp index 8e63c4df..80c0669c 100644 --- a/trace_streamer/sdk/demo_sdk/table/gpu_counter_object_table.cpp +++ b/trace_streamer/sdk/demo_sdk/table/gpu_counter_object_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { COUNTER_ID = 0, COUNTER_NAME = 1 }; +enum class Index : int32_t { COUNTER_ID = 0, COUNTER_NAME = 1 }; GpuCounterObjectTable::GpuCounterObjectTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("counter_id", "INTEGER")); @@ -43,12 +43,12 @@ GpuCounterObjectTable::Cursor::~Cursor() {} int32_t GpuCounterObjectTable::Cursor::Column(int32_t column) const { - switch (column) { - case COUNTER_ID: { + switch (static_cast(column)) { + case Index::COUNTER_ID: { sqlite3_result_int64(context_, static_cast(gpuCounterObjectDataObj_.CounterId()[CurrentRow()])); break; } - case COUNTER_NAME: { + case Index::COUNTER_NAME: { sqlite3_result_text(context_, gpuCounterObjectDataObj_.CounterName()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/sdk/demo_sdk/table/gpu_counter_table.cpp b/trace_streamer/sdk/demo_sdk/table/gpu_counter_table.cpp index f44e99a0..91acce7c 100644 --- a/trace_streamer/sdk/demo_sdk/table/gpu_counter_table.cpp +++ b/trace_streamer/sdk/demo_sdk/table/gpu_counter_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { TS = 0, COUNTER_ID = 1, VALUE = 2 }; +enum class Index : int32_t { TS = 0, COUNTER_ID = 1, VALUE = 2 }; GpuCounterTable::GpuCounterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("ts", "INTEGER")); @@ -45,16 +45,16 @@ GpuCounterTable::Cursor::~Cursor() {} int32_t GpuCounterTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(gpuCounterDataObj_.TimeStamp()[CurrentRow()])); break; } - case COUNTER_ID: { + case Index::COUNTER_ID: { sqlite3_result_int64(context_, static_cast(gpuCounterDataObj_.CounterId()[CurrentRow()])); break; } - case VALUE: { + case Index::VALUE: { sqlite3_result_int64(context_, static_cast(gpuCounterDataObj_.Value()[CurrentRow()])); break; } diff --git a/trace_streamer/sdk/demo_sdk/table/meta_table.cpp b/trace_streamer/sdk/demo_sdk/table/meta_table.cpp index 0059d3e0..91652d41 100644 --- a/trace_streamer/sdk/demo_sdk/table/meta_table.cpp +++ b/trace_streamer/sdk/demo_sdk/table/meta_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { NAMEINDEX = 0, VALUE }; +enum class Index : int32_t { NAMEINDEX = 0, VALUE }; MetaTable::MetaTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("name", "TEXT")); @@ -42,12 +42,12 @@ MetaTable::Cursor::~Cursor() {} int32_t MetaTable::Cursor::Column(int32_t column) const { - switch (column) { - case NAMEINDEX: + switch (static_cast(column)) { + case Index::NAMEINDEX: sqlite3_result_text(context_, dataCache_->GetConstMetaData().Name(CurrentRow()).c_str(), STR_DEFAULT_LEN, nullptr); break; - case VALUE: + case Index::VALUE: sqlite3_result_text(context_, dataCache_->GetConstMetaData().Value(CurrentRow()).c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/sdk/demo_sdk/table/slice_object_table.cpp b/trace_streamer/sdk/demo_sdk/table/slice_object_table.cpp index f08418df..0b2e3997 100644 --- a/trace_streamer/sdk/demo_sdk/table/slice_object_table.cpp +++ b/trace_streamer/sdk/demo_sdk/table/slice_object_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { SLICE_ID = 0, SLICE_NAME = 1 }; +enum class Index : int32_t { SLICE_ID = 0, SLICE_NAME = 1 }; SliceObjectTable::SliceObjectTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("slice_id", "INTEGER")); @@ -43,12 +43,12 @@ SliceObjectTable::Cursor::~Cursor() {} int32_t SliceObjectTable::Cursor::Column(int32_t column) const { - switch (column) { - case SLICE_ID: { + switch (static_cast(column)) { + case Index::SLICE_ID: { sqlite3_result_int64(context_, static_cast(sliceObjectDataObj_.SliceId()[CurrentRow()])); break; } - case SLICE_NAME: { + case Index::SLICE_NAME: { sqlite3_result_text(context_, sliceObjectDataObj_.SliceName()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/sdk/demo_sdk/table/slice_table.cpp b/trace_streamer/sdk/demo_sdk/table/slice_table.cpp index 4eb7b200..4dc79277 100644 --- a/trace_streamer/sdk/demo_sdk/table/slice_table.cpp +++ b/trace_streamer/sdk/demo_sdk/table/slice_table.cpp @@ -18,7 +18,7 @@ namespace SysTuning { namespace TraceStreamer { -enum Index { TS = 0, ENDTS = 1, VALUE = 2, SLICE_ID = 3 }; +enum class Index : int32_t { TS = 0, ENDTS = 1, VALUE = 2, SLICE_ID = 3 }; SliceTable::SliceTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("start_ts", "INTEGER")); @@ -46,20 +46,20 @@ SliceTable::Cursor::~Cursor() {} int32_t SliceTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.TimeStamp()[CurrentRow()])); break; } - case ENDTS: { + case Index::ENDTS: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.EndTs()[CurrentRow()])); break; } - case VALUE: { + case Index::VALUE: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.Value()[CurrentRow()])); break; } - case SLICE_ID: { + case Index::SLICE_ID: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.SliceId()[CurrentRow()])); break; } diff --git a/trace_streamer/sdk/dubai_sdk/table/gpu_counter_object_table.cpp b/trace_streamer/sdk/dubai_sdk/table/gpu_counter_object_table.cpp index 2d1a577b..616b59e3 100644 --- a/trace_streamer/sdk/dubai_sdk/table/gpu_counter_object_table.cpp +++ b/trace_streamer/sdk/dubai_sdk/table/gpu_counter_object_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { COUNTER_ID = 0, COUNTER_NAME = 1 }; +enum class Index : int32_t { COUNTER_ID = 0, COUNTER_NAME = 1 }; } GpuCounterObjectTable::GpuCounterObjectTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -45,12 +45,12 @@ GpuCounterObjectTable::Cursor::~Cursor() {} int32_t GpuCounterObjectTable::Cursor::Column(int32_t column) const { - switch (column) { - case COUNTER_ID: { + switch (static_cast(column)) { + case Index::COUNTER_ID: { sqlite3_result_int64(context_, static_cast(gpuCounterObjectDataObj_.CounterId()[CurrentRow()])); break; } - case COUNTER_NAME: { + case Index::COUNTER_NAME: { sqlite3_result_text(context_, gpuCounterObjectDataObj_.CounterName()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/sdk/dubai_sdk/table/gpu_counter_table.cpp b/trace_streamer/sdk/dubai_sdk/table/gpu_counter_table.cpp index 4aed65a5..0d504958 100644 --- a/trace_streamer/sdk/dubai_sdk/table/gpu_counter_table.cpp +++ b/trace_streamer/sdk/dubai_sdk/table/gpu_counter_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { TS = 0, COUNTER_ID = 1, VALUE = 2 }; +enum class Index : int32_t { TS = 0, COUNTER_ID = 1, VALUE = 2 }; } GpuCounterTable::GpuCounterTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -47,16 +47,16 @@ GpuCounterTable::Cursor::~Cursor() {} int32_t GpuCounterTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(gpuCounterDataObj_.TimeStamp()[CurrentRow()])); break; } - case COUNTER_ID: { + case Index::COUNTER_ID: { sqlite3_result_int64(context_, static_cast(gpuCounterDataObj_.CounterId()[CurrentRow()])); break; } - case VALUE: { + case Index::VALUE: { sqlite3_result_int64(context_, static_cast(gpuCounterDataObj_.Value()[CurrentRow()])); break; } diff --git a/trace_streamer/sdk/dubai_sdk/table/meta_table.cpp b/trace_streamer/sdk/dubai_sdk/table/meta_table.cpp index 93e0a6ab..03f8bbf8 100644 --- a/trace_streamer/sdk/dubai_sdk/table/meta_table.cpp +++ b/trace_streamer/sdk/dubai_sdk/table/meta_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { NAMEINDEX = 0, VALUE }; +enum class Index : int32_t { NAMEINDEX = 0, VALUE }; } MetaTable::MetaTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -44,12 +44,12 @@ MetaTable::Cursor::~Cursor() {} int32_t MetaTable::Cursor::Column(int32_t column) const { - switch (column) { - case NAMEINDEX: + switch (static_cast(column)) { + case Index::NAMEINDEX: sqlite3_result_text(context_, dataCache_->GetConstMetaData().Name(CurrentRow()).c_str(), STR_DEFAULT_LEN, nullptr); break; - case VALUE: + case Index::VALUE: sqlite3_result_text(context_, dataCache_->GetConstMetaData().Value(CurrentRow()).c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/sdk/dubai_sdk/table/slice_object_table.cpp b/trace_streamer/sdk/dubai_sdk/table/slice_object_table.cpp index 1e212152..b64c68e5 100644 --- a/trace_streamer/sdk/dubai_sdk/table/slice_object_table.cpp +++ b/trace_streamer/sdk/dubai_sdk/table/slice_object_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { SLICE_ID = 0, SLICE_NAME = 1 }; +enum class Index : int32_t { SLICE_ID = 0, SLICE_NAME = 1 }; } SliceObjectTable::SliceObjectTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -45,12 +45,12 @@ SliceObjectTable::Cursor::~Cursor() {} int32_t SliceObjectTable::Cursor::Column(int32_t column) const { - switch (column) { - case SLICE_ID: { + switch (static_cast(column)) { + case Index::SLICE_ID: { sqlite3_result_int64(context_, static_cast(sliceObjectDataObj_.SliceId()[CurrentRow()])); break; } - case SLICE_NAME: { + case Index::SLICE_NAME: { sqlite3_result_text(context_, sliceObjectDataObj_.SliceName()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; diff --git a/trace_streamer/sdk/dubai_sdk/table/slice_table.cpp b/trace_streamer/sdk/dubai_sdk/table/slice_table.cpp index 90405357..835c8937 100644 --- a/trace_streamer/sdk/dubai_sdk/table/slice_table.cpp +++ b/trace_streamer/sdk/dubai_sdk/table/slice_table.cpp @@ -19,7 +19,7 @@ namespace SysTuning { namespace TraceStreamer { namespace { -enum Index { TS = 0, ENDTS = 1, ST = 2, ET = 3, VALUE = 4, SLICE_ID = 5 }; +enum class Index : int32_t { TS = 0, ENDTS = 1, ST = 2, ET = 3, VALUE = 4, SLICE_ID = 5 }; } SliceTable::SliceTable(const TraceDataCache* dataCache) : TableBase(dataCache) { @@ -50,28 +50,28 @@ SliceTable::Cursor::~Cursor() {} int32_t SliceTable::Cursor::Column(int32_t column) const { - switch (column) { - case TS: { + switch (static_cast(column)) { + case Index::TS: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.TimeStamp()[CurrentRow()])); break; } - case ENDTS: { + case Index::ENDTS: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.EndTs()[CurrentRow()])); break; } - case ST: { + case Index::ST: { sqlite3_result_text(context_, sliceDataObj_.StartTime()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; } - case ET: { + case Index::ET: { sqlite3_result_text(context_, sliceDataObj_.EndTime()[CurrentRow()].c_str(), STR_DEFAULT_LEN, nullptr); break; } - case VALUE: { + case Index::VALUE: { sqlite3_result_double(context_, static_cast(sliceDataObj_.Value()[CurrentRow()])); break; } - case SLICE_ID: { + case Index::SLICE_ID: { sqlite3_result_int64(context_, static_cast(sliceDataObj_.SliceId()[CurrentRow()])); break; } diff --git a/trace_streamer/sdk/dubai_sdk/table/table_base.cpp b/trace_streamer/sdk/dubai_sdk/table/table_base.cpp index e66c66ca..aa1ff9e6 100644 --- a/trace_streamer/sdk/dubai_sdk/table/table_base.cpp +++ b/trace_streamer/sdk/dubai_sdk/table/table_base.cpp @@ -233,14 +233,14 @@ void TableBase::Cursor::FilterTS(unsigned char op, sqlite3_value* argv, const st case SQLITE_INDEX_CONSTRAINT_LT: { indexMap_->IntersectLessEqual(times, v, getValue); break; - case SQLITE_INDEX_CONSTRAINT_ISNOTNULL: { - indexMap_->RemoveNullElements(times, v); - break; - } - default: - break; - } // end of switch (op) - } + } + case SQLITE_INDEX_CONSTRAINT_ISNOTNULL: { + indexMap_->RemoveNullElements(times, v); + break; + } + default: + break; + } // end of switch (op) } int32_t TableBase::Cursor::RowId(sqlite3_int64* id) diff --git a/trace_streamer/src/filter/cpu_filter.cpp b/trace_streamer/src/filter/cpu_filter.cpp index 6be217a2..5ea02216 100644 --- a/trace_streamer/src/filter/cpu_filter.cpp +++ b/trace_streamer/src/filter/cpu_filter.cpp @@ -73,27 +73,39 @@ void CpuFilter::InsertSwitchEvent(uint64_t ts, } if (prevPid) { + bool isChangeCpu = false; auto lastRow = RowOfInternalTidInStateTable(prevPid); if (lastRow != INVALID_UINT64) { - CheckWakeupEvent(prevPid); - traceDataCache_->GetThreadStateData()->UpdateDuration(static_cast(lastRow), ts); - streamFilters_->processFilter_->AddCpuStateCount(prevPid); - auto thread = traceDataCache_->GetThreadData(prevPid); - if (thread && !thread->switchCount_) { - thread->switchCount_ = 1; + auto lastCpu = traceDataCache_->GetConstThreadStateData().CpusData()[lastRow]; + auto lastState = traceDataCache_->GetConstThreadStateData().StatesData()[lastRow]; + auto lastStartTs = traceDataCache_->GetConstThreadStateData().TimeStamsData()[lastRow]; + if ((cpu != lastCpu) && (lastState == TASK_RUNNING) && (ts == lastStartTs)) { + isChangeCpu = true; + } + if (!isChangeCpu) { + CheckWakeupEvent(prevPid); + traceDataCache_->GetThreadStateData()->UpdateDuration(static_cast(lastRow), ts); + streamFilters_->processFilter_->AddCpuStateCount(prevPid); + auto thread = traceDataCache_->GetThreadData(prevPid); + if (thread && !thread->switchCount_) { + thread->switchCount_ = 1; + } } } - auto threadStateRow = - traceDataCache_->GetThreadStateData()->AppendThreadState(ts, INVALID_TIME, INVALID_CPU, prevPid, prevState); - btInfo.threadStateRow = threadStateRow; - if (prevState == TASK_UNINTERRUPTIBLE || prevState == TASK_DK) { - if (!pidToThreadSliceRow.count(prevPid)) { - pidToThreadSliceRow.emplace(std::make_pair(prevPid, threadStateRow)); - } else { - pidToThreadSliceRow.at(prevPid) = threadStateRow; + + if (!isChangeCpu) { + auto threadStateRow = traceDataCache_->GetThreadStateData()->AppendThreadState( + ts, INVALID_TIME, INVALID_CPU, prevPid, prevState); + btInfo.threadStateRow = threadStateRow; + if (prevState == TASK_UNINTERRUPTIBLE || prevState == TASK_DK) { + if (!pidToThreadSliceRow.count(prevPid)) { + pidToThreadSliceRow.emplace(std::make_pair(prevPid, threadStateRow)); + } else { + pidToThreadSliceRow.at(prevPid) = threadStateRow; + } } + (void)RemberInternalTidInStateTable(prevPid, threadStateRow, prevState); } - (void)RemberInternalTidInStateTable(prevPid, threadStateRow, prevState); } if (traceDataCache_->BinderRunnableTraceEnabled() && iTidToTransaction_.find(prevPid) != iTidToTransaction_.end()) { uint64_t transactionId = iTidToTransaction_.at(prevPid); diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.cpp b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.cpp index ee4bbdbf..3fdddf2a 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.cpp +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.cpp @@ -400,6 +400,9 @@ bool HtraceEventParser::SchedSwitchEvent(const ProtoReader::DataArea& event) std::string prevCommStr = msg.prev_comm().ToStdString(); std::string nextCommStr = msg.next_comm().ToStdString(); auto prevState = msg.prev_state(); + if (prevState == TASK_WAKEKILL) { + prevState = TASK_RUNNABLE; + } auto nextInternalTid = streamFilters_->processFilter_->UpdateOrCreateThreadWithName(eventTimeStamp_, nextPidValue, nextCommStr); diff --git a/trace_streamer/src/parser/print_event_parser.h b/trace_streamer/src/parser/print_event_parser.h index d23360f0..d76d6572 100644 --- a/trace_streamer/src/parser/print_event_parser.h +++ b/trace_streamer/src/parser/print_event_parser.h @@ -78,7 +78,7 @@ private: const uint32_t maxPointLength_; TraceStreamerConfig config_{}; const DataIndex recvievVsync_ = traceDataCache_->GetDataIndex("H:ReceiveVsync"); - const DataIndex rsOnVsyncEvent_ = traceDataCache_->GetDataIndex("H:RSMainThread::OnVsync"); + const DataIndex rsOnVsyncEvent_ = traceDataCache_->GetDataIndex("H:RSMainThread::DoComposition"); const std::string onFrameQueeuStartEvent_ = "H:M: Frame queued"; const std::string onLauncherVsyncEvent_ = "launcher"; const DataIndex marshRwTransactionData_ = traceDataCache_->GetDataIndex("H:MarshRSTransactionData"); diff --git a/trace_streamer/src/parser/thread_state_flag.h b/trace_streamer/src/parser/thread_state_flag.h index b31a58b8..f1192aef 100644 --- a/trace_streamer/src/parser/thread_state_flag.h +++ b/trace_streamer/src/parser/thread_state_flag.h @@ -73,7 +73,7 @@ private: {'Z', EXITZOMBIE}, {'x', TASKDEAD}, {'I', TASKDEAD}, - {'K', WAKEKILL}, + {'K', RUNNABLE}, {'P', PARKED}, {'N', NOLOAD}, {'|', VALID}, diff --git a/trace_streamer/test/unittest/hisys_event_parser_test.cpp b/trace_streamer/test/unittest/hisys_event_parser_test.cpp index 37bdf5ce..734be427 100644 --- a/trace_streamer/test/unittest/hisys_event_parser_test.cpp +++ b/trace_streamer/test/unittest/hisys_event_parser_test.cpp @@ -15,11 +15,10 @@ #include #include - +#include "hi_sysevent_measure_filter.h" #include "htrace_hisysevent_parser.h" #include "string_to_numerical.h" #include "trace_streamer_selector.h" -#include "hi_sysevent_measure_filter.h" using namespace testing::ext; using namespace SysTuning::TraceStreamer; -- Gitee