diff --git a/ide/src/base-ui/chart/column/LitChartColumn.ts b/ide/src/base-ui/chart/column/LitChartColumn.ts index 9686adff97a3241eb4d28e16a63c9507e5762b50..a8071a473ab36b517123ec08265993152158bc50 100644 --- a/ide/src/base-ui/chart/column/LitChartColumn.ts +++ b/ide/src/base-ui/chart/column/LitChartColumn.ts @@ -193,62 +193,98 @@ export class LitChartColumn extends BaseElement { return this.litChartColumnCfg?.data || []; } + haveSeriesField():void{ + let maxValue = Math.max(...this.litChartColumnCfg!.data.map((it) => it[this.litChartColumnCfg!.yField])); + maxValue = Math.ceil(maxValue * 0.1) * 10; + let partWidth = (this.clientWidth - this.offset!.x!) / this.litChartColumnCfg!.data.length; + let partHeight = this.clientHeight - this.offset!.y!; + let gap = partHeight / 5; + let valGap = maxValue / 5; + for (let i = 0; i <= 5; i++) { + this.rowLines.push({ + y: gap * i, + label: + this.litChartColumnCfg!.removeUnit === true + ? `${maxValue - valGap * i}` + : `${getProbablyTime(maxValue - valGap * i)}`, + }); + } + if (!this.litChartColumnCfg!.notSort) { + this.litChartColumnCfg?.data.sort( + (a, b) => b[this.litChartColumnCfg!.yField] - a[this.litChartColumnCfg!.yField] + ); + } + this.litChartColumnCfg?.data.forEach((litChartColumnItem, litChartColumnIndex, array) => { + this.data.push({ + color: this.litChartColumnCfg!.color(litChartColumnItem), + obj: litChartColumnItem, + root: true, + xLabel: litChartColumnItem[this.litChartColumnCfg!.xField], + yLabel: litChartColumnItem[this.litChartColumnCfg!.yField], + bgFrame: { + x: this.offset!.x! + partWidth * litChartColumnIndex, + y: 0, + w: partWidth, + h: partHeight, + }, + centerX: this.offset!.x! + partWidth * litChartColumnIndex + partWidth / 2, + centerY: + partHeight - + (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue + + (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 2, + frame: { + x: this.offset!.x! + partWidth * litChartColumnIndex + partWidth / 6, + y: partHeight - (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue, + w: partWidth - partWidth / 3, + h: (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue, + }, + height: 0, + heightStep: Math.ceil((litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 60), + process: true, + }); + }); + } + + noSeriesField(itemEl:any,y:number,initH:number,maxValue:number,partWidth:number,partHeight:number,reduceGroupIndex:number):void{ + this.data.push({ + color: this.litChartColumnCfg!.color(itemEl), + obj: itemEl, + root: y === 0, + type: itemEl[this.litChartColumnCfg!.seriesField], + xLabel: itemEl[this.litChartColumnCfg!.xField], + yLabel: itemEl[this.litChartColumnCfg!.yField], + bgFrame: { + x: this.offset!.x! + partWidth * reduceGroupIndex, + y: 0, + w: partWidth, + h: partHeight, + }, + centerX: this.offset!.x! + partWidth * reduceGroupIndex + partWidth / 2, + centerY: + partHeight - + initH - + (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue + + (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 2, + frame: { + x: this.offset!.x! + partWidth * reduceGroupIndex + partWidth / 6, + y: partHeight - (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue - initH, + w: partWidth - partWidth / 3, + h: (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue, + }, + height: 0, + heightStep: Math.ceil((itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 60), + process: true, + }); + } + measure() { if (!this.litChartColumnCfg) return; this.data = []; this.rowLines = []; if (!this.litChartColumnCfg.seriesField) { - let maxValue = Math.max(...this.litChartColumnCfg.data.map((it) => it[this.litChartColumnCfg!.yField])); - maxValue = Math.ceil(maxValue * 0.1) * 10; - let partWidth = (this.clientWidth - this.offset!.x!) / this.litChartColumnCfg.data.length; - let partHeight = this.clientHeight - this.offset!.y!; - let gap = partHeight / 5; - let valGap = maxValue / 5; - for (let i = 0; i <= 5; i++) { - this.rowLines.push({ - y: gap * i, - label: - this.litChartColumnCfg.removeUnit === true - ? `${maxValue - valGap * i}` - : `${getProbablyTime(maxValue - valGap * i)}`, - }); - } - if (!this.litChartColumnCfg.notSort) { - this.litChartColumnCfg?.data.sort( - (a, b) => b[this.litChartColumnCfg!.yField] - a[this.litChartColumnCfg!.yField] - ); - } - this.litChartColumnCfg?.data.forEach((litChartColumnItem, litChartColumnIndex, array) => { - this.data.push({ - color: this.litChartColumnCfg!.color(litChartColumnItem), - obj: litChartColumnItem, - root: true, - xLabel: litChartColumnItem[this.litChartColumnCfg!.xField], - yLabel: litChartColumnItem[this.litChartColumnCfg!.yField], - bgFrame: { - x: this.offset!.x! + partWidth * litChartColumnIndex, - y: 0, - w: partWidth, - h: partHeight, - }, - centerX: this.offset!.x! + partWidth * litChartColumnIndex + partWidth / 2, - centerY: - partHeight - - (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue + - (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 2, - frame: { - x: this.offset!.x! + partWidth * litChartColumnIndex + partWidth / 6, - y: partHeight - (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue, - w: partWidth - partWidth / 3, - h: (litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue, - }, - height: 0, - heightStep: Math.ceil((litChartColumnItem[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 60), - process: true, - }); - }); + this.haveSeriesField(); } else { - let reduceGroup = this.litChartColumnCfg.data.reduce((pre, current, index, arr) => { + let reduceGroup = this.litChartColumnCfg!.data.reduce((pre, current, index, arr) => { (pre[current[this.litChartColumnCfg!.xField]] = pre[current[this.litChartColumnCfg!.xField]] || []).push( current ); @@ -278,35 +314,7 @@ export class LitChartColumn extends BaseElement { let elements = reduceGroup[reduceGroupKey]; let initH = 0; elements.forEach((itemEl: any, y: number) => { - this.data.push({ - color: this.litChartColumnCfg!.color(itemEl), - obj: itemEl, - root: y == 0, - type: itemEl[this.litChartColumnCfg!.seriesField], - xLabel: itemEl[this.litChartColumnCfg!.xField], - yLabel: itemEl[this.litChartColumnCfg!.yField], - bgFrame: { - x: this.offset!.x! + partWidth * reduceGroupIndex, - y: 0, - w: partWidth, - h: partHeight, - }, - centerX: this.offset!.x! + partWidth * reduceGroupIndex + partWidth / 2, - centerY: - partHeight - - initH - - (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue + - (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 2, - frame: { - x: this.offset!.x! + partWidth * reduceGroupIndex + partWidth / 6, - y: partHeight - (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue - initH, - w: partWidth - partWidth / 3, - h: (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue, - }, - height: 0, - heightStep: Math.ceil((itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue / 60), - process: true, - }); + this.noSeriesField(itemEl,y,initH,maxValue,partWidth,partHeight,reduceGroupIndex); initH += (itemEl[this.litChartColumnCfg!.yField] * partHeight) / maxValue; }); }); diff --git a/ide/src/base-ui/chart/pagenation/PageNation.ts b/ide/src/base-ui/chart/pagenation/PageNation.ts index b5f132b64d903d8813cb0e194f5842ed5084b2a5..2039e69205e509b8537a271f13d35674a476e069 100644 --- a/ide/src/base-ui/chart/pagenation/PageNation.ts +++ b/ide/src/base-ui/chart/pagenation/PageNation.ts @@ -91,6 +91,44 @@ export class PageNation { }); } + createElement(jumpDiv:HTMLElement):void{ + // Create input field + this.inputBox = document.createElement('input'); + this.inputBox.value = this.pageInfo.current; + this.setElementStyles(this.inputBox, { + width: '35px', + height: '30px', + textAlign: 'center', + outline: 'none', + padding: '0', + border: '0', + 'border-radius': '5px', + }); + jumpDiv.appendChild(this.inputBox); + let span = document.createElement('span'); + span.style.width = '1px'; + span.style.height = '24px'; + span.style.alignSelf = 'center'; + span.style.backgroundColor = '#999999'; + jumpDiv.appendChild(span); + // Create button + this.btn = document.createElement('button'); + this.btn.innerText = ''; + this.btn.name = 'goto'; + this.setElementStyles(this.btn, { + height: '32px', + width: '30px', + cursor: 'pointer', + backgroundColor: '#FFF', + border: '0', + 'border-radius': '5px', + }); + this.btn.style.background = `url('img/arrowright.png') no-repeat 98% center var(--dark-background3,#FFFFFF)`; + this.btn.style.backgroundPosition = 'center'; + jumpDiv.appendChild(this.btn); + this.element.appendChild(jumpDiv); + } + // 创建元素 首页 上一页 按钮组 下一页 尾页 输入框 按钮 createPageElement() { //首页 @@ -102,18 +140,15 @@ export class PageNation { cursor: 'pointer', margin: '0 5px', }); - this.first = this.origin.cloneNode(true); this.first.innerText = this.pageInfo.first; this.first.name = 'first'; this.element.appendChild(this.first); - this.prev = this.origin.cloneNode(true); this.prev.innerText = '<'; this.prev.name = 'prev'; this.prev.style.padding = '5px 10px'; this.element.appendChild(this.prev); - // 创建ul this.list = document.createElement('ul'); this.setElementStyles(this.list, { @@ -141,41 +176,7 @@ export class PageNation { jumpDiv.style.height = '32px'; jumpDiv.style.marginLeft = '10px'; - // 创建输入框 - this.inputBox = document.createElement('input'); - this.inputBox.value = this.pageInfo.current; - this.setElementStyles(this.inputBox, { - width: '35px', - height: '30px', - textAlign: 'center', - outline: 'none', - padding: '0', - border: '0', - 'border-radius': '5px', - }); - jumpDiv.appendChild(this.inputBox); - let span = document.createElement('span'); - span.style.width = '1px'; - span.style.height = '24px'; - span.style.alignSelf = 'center'; - span.style.backgroundColor = '#999999'; - jumpDiv.appendChild(span); - // 创建按钮 - this.btn = document.createElement('button'); - this.btn.innerText = ''; - this.btn.name = 'goto'; - this.setElementStyles(this.btn, { - height: '32px', - width: '30px', - cursor: 'pointer', - backgroundColor: '#FFF', - border: '0', - 'border-radius': '5px', - }); - this.btn.style.background = `url('img/arrowright.png') no-repeat 98% center var(--dark-background3,#FFFFFF)`; - this.btn.style.backgroundPosition = 'center'; - jumpDiv.appendChild(this.btn); - this.element.appendChild(jumpDiv); + this.createElement(jumpDiv); } // 判断首页 上一页 下一页 尾页 是否可以点击 @@ -209,10 +210,8 @@ export class PageNation { } bindPageList() { - // clear ul里面的内容 - this.list.innerHTML = ''; - //每次加载之前先清空ul里面的内容 - const { pageSize, current, totalpage } = this.pageInfo; + this.list.innerHTML = '';// clear ul its contents + const { pageSize, current, totalpage } = this.pageInfo;//Clean the ul before each load const origin = document.createElement('li'); origin.dataset.name = 'item'; this.setElementStyles(origin, { @@ -229,11 +228,11 @@ export class PageNation { } return; } - // 左边5个 中间 ... 右边2个 + // Five on the left... Two on the right if (this.bindLeftList(current, totalpage, origin)) { return; } - // 当前页面 大于5页 小于倒数第5页 + // The current page is larger than 5 pages and smaller than the last 5 pages for (let index = 0; index < 2; index++) { this.buildLi(origin, index, current); } diff --git a/ide/src/base-ui/chart/pie/LitChartPie.ts b/ide/src/base-ui/chart/pie/LitChartPie.ts index 55d6fe23efeaed93db3aa1e0d15f21a75e409b97..73b2a4b822d08c28d886ecf1395fde5a97f8f4c3 100644 --- a/ide/src/base-ui/chart/pie/LitChartPie.ts +++ b/ide/src/base-ui/chart/pie/LitChartPie.ts @@ -154,6 +154,38 @@ export class LitChartPie extends BaseElement { return this.litChartPieConfig; } + addCanvasOnmousemoveEvent():void{ + this.canvas!.onmousemove = (ev) => { + let rect = this.getBoundingClientRect(); + let x = ev.pageX - rect.left - this.centerX!; + let y = ev.pageY - rect.top - this.centerY!; + if (isPointIsCircle(0, 0, x, y, this.radius!)) { + let degree = this.computeDegree(x, y); + this.data.forEach((it) => { + it.hover = degree >= it.startDegree! && degree <= it.endDegree!; + this.updateHoverItemStatus(it); + it.obj.isHover = it.hover; + if (it.hover && this.litChartPieConfig) { + this.litChartPieConfig.hoverHandler?.(it.obj); + this.showTip( + ev.pageX - rect.left + 10, + ev.pageY - this.offsetTop - 10, + this.litChartPieConfig.tip ? this.litChartPieConfig!.tip(it) : `${it.key}: ${it.value}` + ); + } + }); + } else { + this.hideTip(); + this.data.forEach((it) => { + it.hover = false; + it.obj.isHover = false; + this.updateHoverItemStatus(it); + }); + this.litChartPieConfig?.hoverHandler?.(undefined); + } + this.render(); + }; + } connectedCallback() { super.connectedCallback(); this.eleShape = this.shadowRoot!.querySelector('#shape'); @@ -188,36 +220,7 @@ export class LitChartPie extends BaseElement { }); } }; - this.canvas!.onmousemove = (ev) => { - let rect = this.getBoundingClientRect(); - let x = ev.pageX - rect.left - this.centerX!; - let y = ev.pageY - rect.top - this.centerY!; - if (isPointIsCircle(0, 0, x, y, this.radius!)) { - let degree = this.computeDegree(x, y); - this.data.forEach((it) => { - it.hover = degree >= it.startDegree! && degree <= it.endDegree!; - this.updateHoverItemStatus(it); - it.obj.isHover = it.hover; - if (it.hover && this.litChartPieConfig) { - this.litChartPieConfig.hoverHandler?.(it.obj); - this.showTip( - ev.pageX - rect.left + 10, - ev.pageY - this.offsetTop - 10, - this.litChartPieConfig.tip ? this.litChartPieConfig!.tip(it) : `${it.key}: ${it.value}` - ); - } - }); - } else { - this.hideTip(); - this.data.forEach((it) => { - it.hover = false; - it.obj.isHover = false; - this.updateHoverItemStatus(it); - }); - this.litChartPieConfig?.hoverHandler?.(undefined); - } - this.render(); - }; + this.addCanvasOnmousemoveEvent(); this.render(); } @@ -255,6 +258,40 @@ export class LitChartPie extends BaseElement { }).observe(this); } + handleData():void{ + this.textRects = []; + if (this.litChartPieConfig!.showChartLine) { + this.data.forEach((dataItem) => { + let text = `${dataItem.value}`; + let metrics = this.ctx!.measureText(text); + let textWidth = metrics.width; + let textHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent; + this.ctx!.beginPath(); + this.ctx!.strokeStyle = dataItem.color!; + this.ctx!.fillStyle = '#595959'; + let deg = dataItem.startDegree! + (dataItem.endDegree! - dataItem.startDegree!) / 2; + let dep = 25; + let x1 = 0 + this.radius! * Math.cos((deg * Math.PI) / 180); + let y1 = 0 + this.radius! * Math.sin((deg * Math.PI) / 180); + let x2 = 0 + (this.radius! + 13) * Math.cos((deg * Math.PI) / 180); + let y2 = 0 + (this.radius! + 13) * Math.sin((deg * Math.PI) / 180); + let x3 = 0 + (this.radius! + dep) * Math.cos((deg * Math.PI) / 180); + let y3 = 0 + (this.radius! + dep) * Math.sin((deg * Math.PI) / 180); + this.ctx!.moveTo(x1, y1); + this.ctx!.lineTo(x2, y2); + this.ctx!.stroke(); + let rect = this.correctRect({ + x: x3 - textWidth / 2, + y: y3 + textHeight / 2, + w: textWidth, + h: textHeight, + }); + this.ctx?.fillText(text, rect.x, rect.y); + this.ctx?.closePath(); + }); + } + } + render(ease: boolean = true) { if (!this.canvas || !this.litChartPieConfig) return; if (this.radius! <= 0) return; @@ -287,7 +324,6 @@ export class LitChartPie extends BaseElement { this.ctx!.stroke(); this.ctx?.closePath(); }); - this.data .filter((it) => it.hover) .forEach((it) => { @@ -301,38 +337,7 @@ export class LitChartPie extends BaseElement { this.ctx!.stroke(); this.ctx?.closePath(); }); - - this.textRects = []; - if (this.litChartPieConfig.showChartLine) { - this.data.forEach((dataItem) => { - let text = `${dataItem.value}`; - let metrics = this.ctx!.measureText(text); - let textWidth = metrics.width; - let textHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent; - this.ctx!.beginPath(); - this.ctx!.strokeStyle = dataItem.color!; - this.ctx!.fillStyle = '#595959'; - let deg = dataItem.startDegree! + (dataItem.endDegree! - dataItem.startDegree!) / 2; - let dep = 25; - let x1 = 0 + this.radius! * Math.cos((deg * Math.PI) / 180); - let y1 = 0 + this.radius! * Math.sin((deg * Math.PI) / 180); - let x2 = 0 + (this.radius! + 13) * Math.cos((deg * Math.PI) / 180); - let y2 = 0 + (this.radius! + 13) * Math.sin((deg * Math.PI) / 180); - let x3 = 0 + (this.radius! + dep) * Math.cos((deg * Math.PI) / 180); - let y3 = 0 + (this.radius! + dep) * Math.sin((deg * Math.PI) / 180); - this.ctx!.moveTo(x1, y1); - this.ctx!.lineTo(x2, y2); - this.ctx!.stroke(); - let rect = this.correctRect({ - x: x3 - textWidth / 2, - y: y3 + textHeight / 2, - w: textWidth, - h: textHeight, - }); - this.ctx?.fillText(text, rect.x, rect.y); - this.ctx?.closePath(); - }); - } + this.handleData(); if (this.data.filter((it) => it.ease!.process).length > 0) { requestAnimationFrame(() => this.render(ease)); } @@ -390,46 +395,31 @@ export class LitChartPie extends BaseElement { let maxY = r1.y + r1.h > rect.y + rect.h ? r1.y + r1.h : rect.y + rect.h; let minX = r1.x < rect.x ? r1.x : rect.x; let minY = r1.y < rect.y ? r1.y : rect.y; - if (maxX - minX < rect.w + r1.w && maxY - minY < r1.h + rect.h) { - cross = true; - } else { - cross = false; - } + cross = maxX - minX < rect.w + r1.w && maxY - minY < r1.h + rect.h; crossW = Math.abs(maxX - minX - (rect.w + r1.w)); crossH = Math.abs(maxY - minY - (rect.y + r1.y)); if (rect.x > r1.x) { - //right if (rect.y > r1.y) { - //bottom direction = 'Right-Bottom'; } else if (rect.y == r1.y) { - //middle direction = 'Right'; } else { - //top direction = 'Right-Top'; } } else if (rect.x < r1.x) { - //left if (rect.y > r1.y) { - //bottom direction = 'Left-Bottom'; } else if (rect.y == r1.y) { - //middle direction = 'Left'; } else { - //top direction = 'Left-Top'; } } else { if (rect.y > r1.y) { - //bottom direction = 'Bottom'; } else if (rect.y == r1.y) { - //middle direction = 'Right'; //superposition default right } else { - //top direction = 'Top'; } } diff --git a/ide/src/base-ui/chart/scatter/LitChartScatter.ts b/ide/src/base-ui/chart/scatter/LitChartScatter.ts index 5b448066539ea1539545214b2d1e5184f99bd878..cc9cff75a96e6bfd71e7da0baa894f48d142f79c 100644 --- a/ide/src/base-ui/chart/scatter/LitChartScatter.ts +++ b/ide/src/base-ui/chart/scatter/LitChartScatter.ts @@ -50,8 +50,8 @@ export class LitChartScatter extends BaseElement { this.canvas2 = document.createElement('canvas'); this.canvas2.height = this.clientHeight; this.canvas2.width = this.clientWidth; - let context2 = this.canvas2.getContext('2d'); - if (this.canvas?.width != 0 && this.canvas?.height != 0) { + let context2: CanvasRenderingContext2D | null = this.canvas2.getContext('2d'); + if (this.canvas?.width !== 0 && this.canvas?.height !== 0) { context2!.drawImage(this.canvas!, 0, 0); } } @@ -59,7 +59,14 @@ export class LitChartScatter extends BaseElement { drawBackground(): void { let w: number = this.clientWidth; let h: number = this.clientHeight; - let color: CanvasGradient = this.ctx?.createRadialGradient(w / 2, h / 2, 0.2 * w, w / 2, h / 2, 0.5 * w)!; + let color: CanvasGradient = this.ctx?.createRadialGradient( + w / 2, + h / 2, + 0.2 * w, + w / 2, + h / 2, + 0.5 * w + )!; color?.addColorStop(0, '#eaeaea'); color?.addColorStop(1, '#ccc'); if (this.options) { @@ -97,7 +104,7 @@ export class LitChartScatter extends BaseElement { drawAxis(options: LitChartScatterConfig): void { let text: Array = new Array(); if (options) { - text = options.AxisLabel; + text = options.axisLabel; } this.ctx!.font = '10px KATTI'; this.ctx!.fillStyle = '#000000'; @@ -119,24 +126,29 @@ export class LitChartScatter extends BaseElement { * 绘制y轴坐标 */ drawYLabels(options: LitChartScatterConfig): void { + const AXAIS_DELTA: number = 5; + const QUYU: number = 100; // 添加原点刻度 this.ctx!.font = '12px KATTI'; this.ctx!.fillStyle = '#000000'; this.ctx!.strokeStyle = '#000000'; - this.ctx?.fillText('0', this.originX - 5, this.originY + 10); + this.ctx?.fillText('0', this.originX - AXAIS_DELTA, this.originY + AXAIS_DELTA * 2); let yAxis: Array = []; if (options) { yAxis = options.yAxisLabel; } // 画Y轴坐标尺 for (let i = 0; i < yAxis.length; i++) { - let length1 = - (this.originY - this.finalY - ((this.originY - this.finalY) % 100)) * (yAxis[i] / yAxis[yAxis.length - 1]); - let length2 = this.originY - length1; + let length1: number = + (this.originY - this.finalY - ((this.originY - this.finalY) % QUYU)) * + (yAxis[i] / yAxis[yAxis.length - 1]); + let length2: number = this.originY - length1; + let text: string = yAxis[i].toString(); + let x: number = this.originX - this.ctx?.measureText(text).width! - AXAIS_DELTA; this.ctx?.beginPath(); this.ctx?.moveTo(this.originX, length2); - this.ctx?.lineTo(this.originX + 5, length2); - this.ctx?.fillText(yAxis[i].toString(), this.originX - 40, length2 + 5); + this.ctx?.lineTo(this.originX + AXAIS_DELTA, length2); + this.ctx?.fillText(text, x, length2 + AXAIS_DELTA); this.ctx?.stroke(); } } @@ -147,18 +159,21 @@ export class LitChartScatter extends BaseElement { // 画X轴坐标尺 this.ctx!.fillStyle = '#000000'; this.ctx!.strokeStyle = '#000000'; + const QUYU: number = 100; + const DELTA: number = 5; let xAxis: Array = []; if (options) { xAxis = options.xAxisLabel; } for (let i = 0; i < xAxis.length; i++) { - let length3 = - (this.finalX - this.originX - ((this.finalX - this.originX) % 100)) * (xAxis[i] / xAxis[xAxis.length - 1]); - let length4 = this.originX + length3; + let length3: number = + (this.finalX - this.originX - ((this.finalX - this.originX) % QUYU)) * + (xAxis[i] / xAxis[xAxis.length - 1]); + let length4: number = this.originX + length3; this.ctx?.beginPath(); this.ctx?.moveTo(length4, this.originY); - this.ctx?.lineTo(length4, this.originY - 5); - this.ctx?.fillText(xAxis[i].toString(), length4 - 5, this.originY + 10); + this.ctx?.lineTo(length4, this.originY - DELTA); + this.ctx?.fillText(xAxis[i].toString(), length4 - DELTA * 3, this.originY + DELTA * 2); this.ctx?.stroke(); } } @@ -173,6 +188,8 @@ export class LitChartScatter extends BaseElement { let colorPool: Array = new Array(); let colorPoolText: Array = new Array(); let rectY: number = this.clientHeight * 0.05; + const QUYU: number = 100; + const WIDTH_DELTA: number = 70; if (options) { data = options.data; yAxis = options.yAxisLabel; @@ -181,15 +198,15 @@ export class LitChartScatter extends BaseElement { colorPoolText = options.colorPoolText(); options.paintingData = []; } - let xLength = this.finalX - this.originX - ((this.finalX - this.originX) % 100); - let yLength = this.originY - this.finalY - ((this.originY - this.finalY) % 100); + let xLength: number = this.finalX - this.originX - ((this.finalX - this.originX) % QUYU); + let yLength: number = this.originY - this.finalY - ((this.originY - this.finalY) % QUYU); for (let i = 0; i < data.length; i++) { for (let j = 0; j < data[i].length; j++) { // 打点x坐标 - let x = this.originX + (data[i][j][0] / xAxis[xAxis.length - 1]) * xLength; + let x: number = this.originX + (data[i][j][0] / xAxis[xAxis.length - 1]) * xLength; // 打点y坐标 - let y = this.originY - (data[i][j][1] / yAxis[yAxis.length - 1]) * yLength; - let r = 6; + let y: number = this.originY - (data[i][j][1] / yAxis[yAxis.length - 1]) * yLength; + let r: number = 6; if (i > 0) { options.paintingData[data[i][j][2] - 1] = { x, @@ -211,15 +228,21 @@ export class LitChartScatter extends BaseElement { } if (data[i].length) { rectY = rectY + 20; - this.ctx?.fillText(colorPoolText[i] + ': ', this.clientWidth - 70, rectY + 4); - this.drawCycle(this.clientWidth - 20, rectY, 7.5, 0.8, colorPool[i]); + this.ctx?.fillText(colorPoolText[i] + ': ', this.clientWidth - WIDTH_DELTA, rectY + 4); + this.drawCycle(this.clientWidth - (QUYU / 5), rectY, 7.5, 0.8, colorPool[i]); } } } /** * 画圆点 */ - drawCycle(x: number, y: number, r: number, transparency: number, color: string): void { + drawCycle( + x: number, + y: number, + r: number, + transparency: number, + color: string + ): void { this.ctx!.fillStyle = color; this.ctx?.beginPath(); this.ctx!.globalAlpha = transparency; @@ -233,31 +256,44 @@ export class LitChartScatter extends BaseElement { */ drawLoadLine(data: Array): void { let maxXAxis: number = 1; + const QUYU: number = 100; + const FOR_VALUE = 60; if (this.options) { maxXAxis = this.options.xAxisLabel[this.options.xAxisLabel.length - 1]; } // data[1]用来标注n Hz负载线 let addr1: number = - this.originX + (this.finalX - this.originX - ((this.finalX - this.originX) % 100)) * (data[0] / maxXAxis); - let addr2: number = (this.originY - this.finalY - ((this.originY - this.finalY) % 100)) / 60; + this.originX + + (this.finalX - this.originX - ((this.finalX - this.originX) % QUYU)) * + (data[0] / maxXAxis); + let addr2: number = + (this.originY - this.finalY - ((this.originY - this.finalY) % QUYU)) / FOR_VALUE; let y: number = this.originY; this.ctx!.strokeStyle = '#ff0000'; - for (let i = 0; i < 60; i++) { + for (let i = 0; i < FOR_VALUE; i++) { this.ctx?.beginPath(); this.ctx?.moveTo(addr1, y); y -= addr2; this.ctx?.lineTo(addr1, y); - if (i % 2 != 0) { + if (i % 2 !== 0) { this.ctx?.stroke(); } } this.ctx!.font = '10px KATTI'; this.ctx!.fillStyle = '#ff0000'; - this.ctx?.fillText(data[1] + 'Hz最大负载线', addr1 - 20, this.originY - addr2 * 60 - 15); + this.ctx?.fillText( + data[1] + 'Hz最大负载线', + addr1 - FOR_VALUE / 3, + this.originY - addr2 * FOR_VALUE - FOR_VALUE / 4 + ); this.ctx!.fillStyle = '#000000'; - this.ctx?.fillText('过供给区', addr1 / 2, y + 30); + this.ctx?.fillText('过供给区', addr1 / 2, y + FOR_VALUE / 2); this.ctx?.fillText('欠供给区', addr1 / 2, this.originY - this.finalY); - this.ctx?.fillText('超负载区', addr1 + 20, (this.finalY + this.originY) / 2); + this.ctx?.fillText( + '超负载区', + addr1 + FOR_VALUE / 3, + (this.finalY + this.originY) / 2 + ); } /** @@ -265,23 +301,27 @@ export class LitChartScatter extends BaseElement { */ drawBalanceLine(data: Array): void { let maxXAxis: number = 1; + const QUYU: number = 100; + const FOR_VALUE = 60; if (this.options) { maxXAxis = this.options.xAxisLabel[this.options.xAxisLabel.length - 1]; } // data[1]用来标注n Hz均衡线 let addr1: number = - ((this.finalX - this.originX - ((this.finalX - this.originX) % 100)) * (data[0] / maxXAxis)) / 60; - let addr2: number = (this.originY - this.finalY - ((this.originY - this.finalY) % 100)) / 60; + ((this.finalX - this.originX - ((this.finalX - this.originX) % QUYU)) * + (data[0] / maxXAxis)) / FOR_VALUE; + let addr2: number = + (this.originY - this.finalY - ((this.originY - this.finalY) % QUYU)) / FOR_VALUE; let x: number = this.originX; let y: number = this.originY; this.ctx!.strokeStyle = '#00ff00'; - for (let i = 0; i < 60; i++) { + for (let i = 0; i < FOR_VALUE; i++) { this.ctx?.beginPath(); this.ctx?.moveTo(x, y); x += addr1; y -= addr2; this.ctx?.lineTo(x, y); - if (i % 2 == 0) { + if (i % 2 === 0) { this.ctx?.stroke(); } } @@ -295,7 +335,10 @@ export class LitChartScatter extends BaseElement { } /*检测是否hover在散点之上*/ - checkHover(options: LitChartScatterConfig | undefined, pos: Object): Object | boolean { + checkHover( + options: LitChartScatterConfig | undefined, + pos: Object + ): Object | boolean { let data: Array = []; if (options) { data = options.paintingData; @@ -304,7 +347,13 @@ export class LitChartScatter extends BaseElement { for (let i = 0; i < data.length; i++) { found = false; // @ts-ignore - if (Math.sqrt(Math.pow(pos.x - data[i].x, 2) + Math.pow(pos.y - data[i].y, 2)) < data[i].r) { + if ( + Math.sqrt( + // @ts-ignore + Math.pow(pos.x - data[i].x, 2) + Math.pow(pos.y - data[i].y, 2) + // @ts-ignore + ) < data[i].r + ) { found = data[i]; break; } @@ -336,10 +385,14 @@ export class LitChartScatter extends BaseElement { //利用离屏canvas恢复hover前的状态 resetHoverWithOffScreen(): void { let obj: Object | null = null; + const STEP_VALUE: number = 12; + const OUT_CYCLE: number = 2; if (this.options) { obj = this.options.hoverData; } - if (!obj) return; + if (!obj) { + return; + } // @ts-ignore let { x, y, r, c, color } = obj; let step = 0.5; @@ -349,18 +402,18 @@ export class LitChartScatter extends BaseElement { //绘制外圆范围 this.ctx?.drawImage( this.canvas2!, - x - r - 12 * step, - y - r - 12 * step, - 2 * (r + 12 * step), - 2 * (r + 12 * step), - x - r - 12 * step, - y - r - 12 * step, - 2 * (r + 12 * step), - 2 * (r + 12 * step) + x - r - STEP_VALUE * step, + y - r - STEP_VALUE * step, + OUT_CYCLE * (r + STEP_VALUE * step), + OUT_CYCLE * (r + STEP_VALUE * step), + x - r - STEP_VALUE * step, + y - r - STEP_VALUE * step, + OUT_CYCLE * (r + STEP_VALUE * step), + OUT_CYCLE * (r + STEP_VALUE * step) ); //绘制内圆 this.ctx?.beginPath(); - this.ctx?.arc(x, y, r + i * step, 0, 2 * Math.PI, false); + this.ctx?.arc(x, y, r + i * step, 0, OUT_CYCLE * Math.PI, false); this.ctx?.closePath(); this.ctx!.fillStyle = color; this.ctx!.globalAlpha = 0.8; @@ -374,8 +427,9 @@ export class LitChartScatter extends BaseElement { * 显示提示框 */ showTip(data: any): void { + const Y_DELTA: number = 70; this.scatterTipEL!.style.display = 'flex'; - this.scatterTipEL!.style.top = `${data.y - 70}px`; + this.scatterTipEL!.style.top = `${data.y - Y_DELTA}px`; this.scatterTipEL!.style.left = `${data.x}px`; this.scatterTipEL!.innerHTML = this.options!.tip(data); // @ts-ignore @@ -403,7 +457,6 @@ export class LitChartScatter extends BaseElement { this.originY = this.clientHeight * 0.9; this.finalX = this.clientWidth; this.finalY = this.clientHeight * 0.1; - /*hover效果*/ this.canvas!.onmousemove = (event) => { let pos: Object = { @@ -416,7 +469,8 @@ export class LitChartScatter extends BaseElement { */ if (hoverPoint) { this.showTip(hoverPoint); - let samePoint: boolean = this.options!.hoverData === hoverPoint ? true : false; + let samePoint: boolean = + this.options!.hoverData === hoverPoint ? true : false; if (!samePoint) { this.resetHoverWithOffScreen(); this.options!.hoverData = hoverPoint; @@ -488,56 +542,60 @@ export class LitChartScatter extends BaseElement { background-repeat:no-repeat; background-position:center; } - - #labels{ - display: grid; - grid-template-columns: auto auto auto auto auto; - /*justify-content: center;*/ - /*align-items: center;*/ - width: 100%; - height: 25%; - box-sizing: border-box; - position: absolute; - bottom: 0px; - left: 0; - /*margin: 0px 10px;*/ - padding-left: 10px; - padding-right: 10px; - pointer-events: none ; - } - .name{ - flex: 1; - font-size: 9pt; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - /*color: #666;*/ - color: var(--dark-color1,#252525); - pointer-events: painted; - } - .label{ - display: flex; - align-items: center; - max-lines: 1; - white-space: nowrap; - overflow: hidden; - padding-right: 5px; - } - .tag{ - display: flex; - align-items: center; - justify-content: center; - width: 10px; - height: 10px; - border-radius: 5px; - margin-right: 5px; - } - -
-
- -
-
-
`; + ` + this.dismantlingHtml(); + } + + /** + * 拆解initHtml大函数块 + * @returns html + */ + dismantlingHtml(): string { + return` + #labels{ + display: grid; + grid-template-columns: auto auto auto auto auto; + width: 100%; + height: 25%; + box-sizing: border-box; + position: absolute; + bottom: 0px; + left: 0; + padding-left: 10px; + padding-right: 10px; + pointer-events: none; + } + .name{ + flex: 1; + font-size: 9pt; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--dark-color1,#252525); + pointer-events: painted; + } + .label{ + display: flex; + align-items: center; + max-lines: 1; + white-space: nowrap; + overflow: hidden; + padding-right: 5px; + } + .tag{ + display: flex; + align-items: center; + justify-content: center; + width: 10px; + height: 10px; + border-radius: 5px; + margin-right: 5px; + } + +
+
+ +
+
+
`; } } diff --git a/ide/src/base-ui/chart/scatter/LitChartScatterConfig.ts b/ide/src/base-ui/chart/scatter/LitChartScatterConfig.ts index 61df7fb9da82238a87367a30790f2e323e75c3a8..586a7b3066d09a0f0835cc06d0a454453ab42dfb 100644 --- a/ide/src/base-ui/chart/scatter/LitChartScatterConfig.ts +++ b/ide/src/base-ui/chart/scatter/LitChartScatterConfig.ts @@ -19,7 +19,7 @@ export interface LitChartScatterConfig { // x轴坐标数组 xAxisLabel: Array; // 坐标轴名称 - AxisLabel: Array; + axisLabel: Array; // 用于判断是否绘制负载线及均衡线 drawload: boolean; // 用于存放最大负载线及均衡线的参数值 diff --git a/ide/src/doc/quickstart_animation.html b/ide/src/doc/quickstart_animation.html index 29ab5dfdf607f674b7366e6639629fe835b55f49..f6cfb8db7ba59caedc8301bcc82e6945435b9e1d 100644 --- a/ide/src/doc/quickstart_animation.html +++ b/ide/src/doc/quickstart_animation.html @@ -801,7 +801,7 @@
  • -Animation effect:动效配置项的总开关。解析时请打开对应的Flags标记(Disabled切换为Enabled)。
    +AnimationAnalysis:动效配置项的总开关。解析时请打开对应的Flags标记(Disabled切换为Enabled)。
     
diff --git a/ide/src/doc/quickstart_bio.html b/ide/src/doc/quickstart_bio.html index a378d2ab14d6dfeeb8e4f994ae70b15164e5146d..b1fa979c52bf810125b3352055d300269fd33539 100644 --- a/ide/src/doc/quickstart_bio.html +++ b/ide/src/doc/quickstart_bio.html @@ -1070,9 +1070,9 @@ Hide System so:隐藏系统库文件 。

点击Disk I/O Latency Calltree左下角的柱状图的图标,会切换到火焰图页面。
GitHub Logo
- 进入到火焰图页面,火焰图的展示跟Callinfo的tab页的调用栈显示一致,鼠标放到色块上,悬浮框可以显示调用栈名称和Duration时长。
+ 进入到火焰图页面,火焰图的展示跟 Disk I/O Latency Calltree 的tab页的调用栈显示一致,鼠标放到色块上,悬浮框可以显示调用栈名称和Duration时长。
GitHub Logo
- 鼠标左键火焰图,会进入下一级界面,右键回到上一级。
+ 鼠标点击火焰图,会进入下一级界面,点击上级则返回上一级界面。
GitHub Logo

diff --git a/ide/src/doc/quickstart_filesystem.html b/ide/src/doc/quickstart_filesystem.html index f95185d7d4734601bce9042d7381ec4f9c3b5d2e..15a8f8b984008939cff0fb4d26833cf99ff823aa 100644 --- a/ide/src/doc/quickstart_filesystem.html +++ b/ide/src/doc/quickstart_filesystem.html @@ -1172,9 +1172,9 @@ Hide System so:隐藏系统库文件。

点击FileSystem Calltre左下角的柱状图的图标,会切换到火焰图页面。
GitHub Logo
- 进入到火焰图页面,火焰图的展示跟Callinfo的tab页的调用栈显示一致,鼠标放到色块上,悬浮框可以显示调用栈名称和Duration时长。
+ 进入到火焰图页面,火焰图的展示跟 Filesystem Calltree 的tab页的调用栈显示一致,鼠标放到色块上,悬浮框可以显示调用栈名称和Duration时长。
GitHub Logo
- 鼠标左键火焰图,会进入下一级界面,右键回到上一级。
+ 鼠标点击火焰图,会进入下一级界面,点击上级则返回上一级界面。
GitHub Logo

diff --git a/ide/src/doc/quickstart_hiperf.html b/ide/src/doc/quickstart_hiperf.html index b15b688bd48daf6cb16c5aa30a2bcd8184bd0477..f371d3ccda468581101a095bebe850b5f5bdd25c 100644 --- a/ide/src/doc/quickstart_hiperf.html +++ b/ide/src/doc/quickstart_hiperf.html @@ -1013,7 +1013,7 @@ Hide System so:隐藏系统库文件。

点击Perf Profile左下角的柱状图的图标,会切换到火焰图页面。
GitHub Logo
- 进入到火焰图页面,火焰图的展示跟Callinfo的tab页的调用栈显示一致,鼠标放到色块上,悬浮框可以显示调用栈名称,lib,addr,Count,%in + 进入到火焰图页面,火焰图的展示跟 Perf Profile 的tab页的调用栈显示一致,鼠标放到色块上,悬浮框可以显示调用栈名称,lib,addr,Count,%in current thread,%in current process,&in all process。
GitHub Logo

diff --git a/ide/src/index.ts b/ide/src/index.ts index 758be7e6615277f1cd94f4aeee667ee23c1d5a1c..bd5dd96a23dafe4a5a1f69d01d2a56ba96ae312b 100644 --- a/ide/src/index.ts +++ b/ide/src/index.ts @@ -1,16 +1,17 @@ -// 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. - +/* + * 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 './trace/SpApplication'; import { SpApplication } from './trace/SpApplication'; document.body.innerHTML = ''; diff --git a/ide/src/js-heap/LoadDatabase.ts b/ide/src/js-heap/LoadDatabase.ts index b48e818c797357e491fab700b5f68ea40f991d28..cbad93232e1e31116f19f377980cff99a35d3ec1 100644 --- a/ide/src/js-heap/LoadDatabase.ts +++ b/ide/src/js-heap/LoadDatabase.ts @@ -16,17 +16,15 @@ import { HeapDataInterface, ParseListener } from './HeapDataInterface'; import { AllocationFunction, FileType } from './model/UiStruct'; import { getTimeForLog } from './utils/Utils'; import { HeapNode, FileStruct } from './model/DatabaseStruct'; +import { info } from '../log/Log'; import { + queryHeapEdge, queryHeapFile, queryHeapInfo, queryHeapNode, - queryHeapEdge, - queryHeapFunction, - queryHeapTraceNode, - queryHeapSample, - queryHeapString, -} from '../trace/database/SqlLite'; -import { info } from '../log/Log'; + queryHeapSample, queryHeapString +} from "../trace/database/sql/SqlLite.sql"; +import {queryHeapFunction, queryHeapTraceNode} from "../trace/database/sql/Func.sql"; export class LoadDatabase { private static loadDB: LoadDatabase; diff --git a/ide/src/trace/SpApplication.html.ts b/ide/src/trace/SpApplication.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..892b0d28086715bd7e512e27154f2e919eef4a67 --- /dev/null +++ b/ide/src/trace/SpApplication.html.ts @@ -0,0 +1,382 @@ +/* + * 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. + */ +export const SpApplicationHtml = ` + +
+ + +
+ + + + +
+
+ + + + + + + + + + + + + + + +
+
+ `; \ No newline at end of file diff --git a/ide/src/trace/SpApplication.ts b/ide/src/trace/SpApplication.ts index 282145cc85cd25351aa8540368f4124df8144786..8919f6601065f0caa7e1166cd317e5486234ba29 100644 --- a/ide/src/trace/SpApplication.ts +++ b/ide/src/trace/SpApplication.ts @@ -29,7 +29,7 @@ import { LitProgressBar } from '../base-ui/progress-bar/LitProgressBar'; import { SpRecordTrace } from './component/SpRecordTrace'; import { SpWelcomePage } from './component/SpWelcomePage'; import { LitSearch } from './component/trace/search/Search'; -import { DbPool, queryExistFtrace, queryTraceType, threadPool } from './database/SqlLite'; +import { DbPool, threadPool } from './database/SqlLite'; import './component/trace/search/Search'; import './component/SpWelcomePage'; import './component/SpSystemTrace'; @@ -60,6 +60,8 @@ import './component/SpKeyboard'; import { parseKeyPathJson } from './component/Utils'; import { Utils } from './component/trace/base/Utils'; import "../base-ui/chart/scatter/LitChartScatter"; +import {SpApplicationHtml} from "./SpApplication.html"; +import {queryExistFtrace} from "./database/sql/SqlLite.sql"; @element('sp-application') export class SpApplication extends BaseElement { @@ -93,7 +95,6 @@ export class SpApplication extends BaseElement { static skinChange: Function | null | undefined = null; static skinChange2: Function | null | undefined = null; skinChangeArray: Array = []; - private icon: HTMLDivElement | undefined | null; private rootEL: HTMLDivElement | undefined | null; private spHelp: SpHelp | undefined | null; private keyCodeMap = { @@ -209,374 +210,7 @@ export class SpApplication extends BaseElement { } initHtml(): string { - return ` - -
- - -
- - - - -
-
- - - - - - - - - - - - - - - -
-
- `; + return SpApplicationHtml; } initElements() { @@ -926,30 +560,22 @@ export class SpApplication extends BaseElement { title: 'Download File', icon: 'download', clickHandler: function () { - if (that.vs) { - that.vsDownload(mainMenu, fileName, isServer, dbName); - } else { - that.download(mainMenu, fileName, isServer, dbName); - SpStatisticsHttpUtil.addOrdinaryVisitAction({ - event: 'download', - action: 'download', - }); - } + that.download(mainMenu, fileName, isServer, dbName); + SpStatisticsHttpUtil.addOrdinaryVisitAction({ + event: 'download', + action: 'download', + }); }, }, { title: 'Download Database', icon: 'download', clickHandler: function () { - if (that.vs) { - that.vsDownloadDB(mainMenu, fileName); - } else { - that.downloadDB(mainMenu, fileName); - SpStatisticsHttpUtil.addOrdinaryVisitAction({ - event: 'download_db', - action: 'download', - }); - } + that.downloadDB(mainMenu, fileName); + SpStatisticsHttpUtil.addOrdinaryVisitAction({ + event: 'download_db', + action: 'download', + }); }, }, ]; @@ -1079,90 +705,6 @@ export class SpApplication extends BaseElement { litSearch.setPercent(command + ' ', SpApplication.loadingProgress); } - function handleServerMode( - ev: any, - showFileName: string, - fileSize: string, - fileName: string, - isClickHandle?: boolean - ) { - threadPool.init('server').then(() => { - info('init server ok'); - litSearch.setPercent('parse trace', 1); - // Load the trace file and send it to the background parse to return the db file path - const fd = new FormData(); - if (that.vs && isClickHandle) { - fd.append('convertType', 'vsUpload'); - fd.append('filePath', ev as any); - } else { - fd.append('file', ev as any); - } - let uploadPath = `https://${window.location.host.split(':')[0]}:${window.location.port}/application/upload`; - if (that.vs) { - uploadPath = `http://${window.location.host.split(':')[0]}:${window.location.port}/application/upload`; - } - info('upload trace'); - let dbName = ''; - fetch(uploadPath, { - method: 'POST', - body: fd, - }) - .then((res) => { - litSearch.setPercent('load database', 5); - if (res.ok) { - info(' server Parse trace file success'); - return res.text(); - } else { - if (res.status == 404) { - info(' server Parse trace file failed'); - litSearch.setPercent('This File is not supported!', -1); - progressEL.loading = false; - that.freshMenuDisable(false); - return Promise.reject(); - } - } - }) - .then((res) => { - if (res != undefined) { - dbName = res; - info('get trace db'); - let loadPath = `https://${window.location.host.split(':')[0]}:${window.location.port}`; - if (that.vs) { - loadPath = `http://${window.location.host.split(':')[0]}:${window.location.port}`; - } - SpApplication.loadingProgress = 0; - SpApplication.progressStep = 3; - spSystemTrace!.loadDatabaseUrl( - loadPath + res, - (command: string, percent: number) => { - setProgress(command); - }, - (res) => { - info('loadDatabaseUrl success'); - mainMenu.menus!.splice(1, mainMenu.menus!.length > 2 ? 1 : 0, { - collapsed: false, - title: 'Current Trace', - second: false, - icon: '', - describe: 'Actions on the current trace', - children: getTraceOptionMenus(showFileName, fileSize, fileName, true, dbName), - }); - litSearch.setPercent('', 101); - chartFilter!.setAttribute('mode', ''); - progressEL.loading = false; - that.freshMenuDisable(false); - } - ); - } else { - litSearch.setPercent('', 101); - progressEL.loading = false; - that.freshMenuDisable(false); - } - spInfoAndStats.initInfoAndStatsData(); - }); - }); - } - function sendCutFileMessage(timStamp: number) { that.pageTimStamp = timStamp; threadPool.init('wasm').then(() => { @@ -1717,7 +1259,7 @@ export class SpApplication extends BaseElement { let resultLastIndexOf = firstText.lastIndexOf('_'); let searchResult = firstText.slice(resultLastIndexOf + 1, firstText.length) if (isNormalType) { - pageNumber = traceTypePage.lastIndexOf(Number(searchResult) + 1); + pageNumber = traceTypePage.lastIndexOf(Number(searchResult)); } else { fileType = searchResult; } @@ -1831,11 +1373,6 @@ export class SpApplication extends BaseElement { fileName.lastIndexOf('.') == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf('.')); document.title = `${showFileName} (${fileSize}M)`; TraceRow.rangeSelectObject = undefined; - if (that.server) { - info('Parse trace using server mode '); - handleServerMode(openResult.filePath, showFileName, fileSize, fileName, isClickHandle); - return; - } if (that.wasm) { info('Parse trace using wasm mode '); const vsUpload = new FormData(); @@ -1876,11 +1413,6 @@ export class SpApplication extends BaseElement { fileName.lastIndexOf('.') == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf('.')); document.title = `${showFileName} (${fileSize}M)`; TraceRow.rangeSelectObject = undefined; - if (that.server) { - info('Parse trace using server mode '); - handleServerMode(ev, showFileName, fileSize, fileName); - return; - } if (that.sqlite) { info('Parse trace using sql mode'); litSearch.setPercent('', 0); @@ -2541,62 +2073,6 @@ export class SpApplication extends BaseElement { } } - private vsDownloadDB(mainMenu: LitMainMenu, fileDbName: string) { - let fileName = fileDbName?.substring(0, fileDbName?.lastIndexOf('.')) + '.db'; - threadPool.submit( - 'download-db', - '', - {}, - (reqBufferDB: any) => { - Cmd.showSaveFile((filePath: string) => { - if (filePath != '') { - this.itemIconLoading(mainMenu, 'Current Trace', 'Download Database', true); - const fd = new FormData(); - fd.append('convertType', 'download'); - fd.append('filePath', filePath); - fd.append('file', new File([reqBufferDB], fileName)); - Cmd.uploadFile(fd, (res: Response) => { - if (res.ok) { - this.itemIconLoading(mainMenu, 'Current Trace', 'Download Database', false); - } - }); - } - }); - }, - 'download-db' - ); - } - - private vsDownload(mainMenu: LitMainMenu, fileName: string, isServer: boolean, dbName?: string) { - Cmd.showSaveFile((filePath: string) => { - if (filePath != '') { - this.itemIconLoading(mainMenu, 'Current Trace', 'Download File', true); - if (isServer) { - if (dbName != '') { - let file = dbName?.substring(0, dbName?.lastIndexOf('.')) + fileName.substring(fileName.lastIndexOf('.')); - Cmd.copyFile(file, filePath, (res: Response) => { - this.itemIconLoading(mainMenu, 'Current Trace', 'Download File', false); - }); - } - } else { - this.readTraceFileBuffer().then((buffer) => { - if (buffer) { - const fd = new FormData(); - fd.append('convertType', 'download'); - fd.append('filePath', filePath); - fd.append('file', new File([buffer], fileName)); - Cmd.uploadFile(fd, (res: Response) => { - if (res.ok) { - this.itemIconLoading(mainMenu, 'Current Trace', 'Download File', false); - } - }); - } - }); - } - } - }); - } - freshMenuDisable(disable: boolean) { let mainMenu = this.shadowRoot?.querySelector('#main-menu') as LitMainMenu; // @ts-ignore diff --git a/ide/src/trace/bean/BoxSelection.ts b/ide/src/trace/bean/BoxSelection.ts index f990d2bfb5d0d334df0fa60b47bc2f11ae5149d9..c02908b22fda1c5beb21dd6bf32b1cee35070341 100644 --- a/ide/src/trace/bean/BoxSelection.ts +++ b/ide/src/trace/bean/BoxSelection.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CpuFreqLimitsStruct } from '../database/ui-worker/ProcedureWorkerCpuFreqLimits'; +import { CpuFreqLimitsStruct } from '../database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits'; import { ClockStruct } from '../database/ui-worker/ProcedureWorkerClock'; import { IrqStruct } from '../database/ui-worker/ProcedureWorkerIrq'; import { FuncStruct } from '../database/ui-worker/ProcedureWorkerFunc'; diff --git a/trace_streamer/src/table/ftrace/measure_filter_table.h b/ide/src/trace/bean/NumBean.ts similarity index 42% rename from trace_streamer/src/table/ftrace/measure_filter_table.h rename to ide/src/trace/bean/NumBean.ts index 9e638452999a573b62968594ff85579520be0dba..dd27083a08d9d6e2182d75a30fa6be4ae9910262 100644 --- a/trace_streamer/src/table/ftrace/measure_filter_table.h +++ b/ide/src/trace/bean/NumBean.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,28 +13,15 @@ * limitations under the License. */ -#ifndef THREAD_MEASURE_FILTER_H -#define THREAD_MEASURE_FILTER_H - -#include "table_base.h" -#include "trace_data_cache.h" - -namespace SysTuning { -namespace TraceStreamer { -class MeasureFilterTable : public TableBase { -public: - explicit MeasureFilterTable(const TraceDataCache* dataCache); - ~MeasureFilterTable() override; - std::unique_ptr CreateCursor() override; - -private: - class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache* dataCache, TableBase* table); - ~Cursor() override; - int32_t Column(int32_t column) const override; - }; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // THREAD_MEASURE_FILTER_H +export const NUM_3 = 3; +export const NUM_7 = 7; +export const NUM_16 = 16; +export const NUM_30 = 30; +export const NUM_60 = 60; +export const NUM_200 = 200; +export const NUM_300 = 300; +export const NUM_450 = 450; +export const NUM_600 = 600; +export const NUM_1800 = 1800; +export const NUM_3600 = 3600; +export const NUM_16384 = 16384; diff --git a/ide/src/trace/component/SpInfoAndStas.ts b/ide/src/trace/component/SpInfoAndStas.ts index 987d7b544a73903c7d2271c04951d41b98837316..b357ed344b099de1c4d513cb4911f8baa8b0c12c 100644 --- a/ide/src/trace/component/SpInfoAndStas.ts +++ b/ide/src/trace/component/SpInfoAndStas.ts @@ -14,11 +14,11 @@ */ import { BaseElement, element } from '../../base-ui/BaseElement'; -import { querySelectTraceStats, queryTraceMetaData } from '../database/SqlLite'; import { LitTable } from '../../base-ui/table/lit-table'; import '../../base-ui/table/lit-table'; import { info } from '../../log/Log'; import { LitProgressBar } from '../../base-ui/progress-bar/LitProgressBar'; +import {querySelectTraceStats, queryTraceMetaData} from "../database/sql/SqlLite.sql"; @element('sp-info-and-stats') export class SpInfoAndStats extends BaseElement { diff --git a/ide/src/trace/component/SpMetrics.ts b/ide/src/trace/component/SpMetrics.ts index 6419f53d1bee8d1cc828910966832a59e7d873c4..f7d0110b253a1a7c3eda73c61e10372121fd4125 100644 --- a/ide/src/trace/component/SpMetrics.ts +++ b/ide/src/trace/component/SpMetrics.ts @@ -15,11 +15,10 @@ import { BaseElement, element } from '../../base-ui/BaseElement'; -import { queryMetric } from '../database/SqlLite'; - import '../../base-ui/table/lit-table'; import { LitProgressBar } from '../../base-ui/progress-bar/LitProgressBar'; import { SpStatisticsHttpUtil } from '../../statistics/util/SpStatisticsHttpUtil'; +import {queryMetric} from "../database/sql/SqlLite.sql"; @element('sp-metrics') export class SpMetrics extends BaseElement { diff --git a/ide/src/trace/component/SpQuerySQL.ts b/ide/src/trace/component/SpQuerySQL.ts index ae0038466dc88beed5e8bfb439b00cbe3a797e39..4158fe2666286aea8d6a8c82d060a00bf2327344 100644 --- a/ide/src/trace/component/SpQuerySQL.ts +++ b/ide/src/trace/component/SpQuerySQL.ts @@ -14,7 +14,6 @@ */ import { BaseElement, element } from '../../base-ui/BaseElement'; -import { queryCustomizeSelect } from '../database/SqlLite'; import { LitTable } from '../../base-ui/table/lit-table'; import '../../base-ui/table/lit-table'; import { LitTableColumn } from '../../base-ui/table/lit-table-column'; @@ -25,6 +24,7 @@ import { PaginationBox } from '../../base-ui/chart/pagenation/PaginationBox'; import { SpStatisticsHttpUtil } from '../../statistics/util/SpStatisticsHttpUtil'; import { getAllSql } from './trace/base/CommonSql'; import { LitIcon } from '../../base-ui/icon/LitIcon'; +import {queryCustomizeSelect} from "../database/sql/SqlLite.sql"; @element('sp-query-sql') export class SpQuerySQL extends BaseElement { diff --git a/ide/src/trace/component/SpRecordConfigModel.ts b/ide/src/trace/component/SpRecordConfigModel.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a25301b1626914668606b070babca7f15bd2fbf --- /dev/null +++ b/ide/src/trace/component/SpRecordConfigModel.ts @@ -0,0 +1,880 @@ +/* + * 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 { + ArkTSConfig, + CreateSessionRequest, + FpsConfig, HiebpfConfig, HilogConfig, + HiperfPluginConfig, HiSystemEventConfig, levelFromJSON, + MemoryConfig, + NativeHookConfig, + ProfilerPluginConfig, + ProfilerSessionConfig, + ProfilerSessionConfigBufferConfig, + ProfilerSessionConfigBufferConfigPolicy, + ProfilerSessionConfigMode, + sysMeminfoTypeFromJSON, + sysVMeminfoTypeFromJSON, + TracePluginConfig +} from './setting/bean/ProfilerServiceTypes'; +import {SpRecordSetting} from './setting/SpRecordSetting'; +import {SpVmTracker} from './setting/SpVmTracker'; +import {SpProbesConfig} from './setting/SpProbesConfig'; +import {info} from '../../log/Log'; +import { SpAllocations } from './setting/SpAllocations'; +import { SpApplication } from '../SpApplication'; +import { PerfConfig, SpRecordPerf } from './setting/SpRecordPerf'; +import { SpFileSystem } from './setting/SpFileSystem'; +import { SpSdkConfig } from './setting/SpSdkConfig'; +import { SpHisysEvent } from './setting/SpHisysEvent'; +import { SpArkTs } from './setting/SpArkTs'; +import { SpHilogRecord } from './setting/SpHilogRecord'; + +export const MEM_INFO = [ + 'MEMINFO_ACTIVE', + 'MEMINFO_ACTIVE_ANON', + 'MEMINFO_ACTIVE_FILE', + 'MEMINFO_ANON_PAGES', + 'MEMINFO_BUFFERS', + 'MEMINFO_CACHED', + 'MEMINFO_CMA_FREE', + 'MEMINFO_CMA_TOTAL', + 'MEMINFO_COMMIT_LIMIT', + 'MEMINFO_COMMITED_AS', + 'MEMINFO_DIRTY', + 'MEMINFO_INACTIVE', + 'MEMINFO_INACTIVE_ANON', + 'MEMINFO_INACTIVE_FILE', + 'MEMINFO_KERNEL_STACK', + 'MEMINFO_MAPPED', + 'MEMINFO_MEM_AVAILABLE', + 'MEMINFO_MEM_FREE', + 'MEMINFO_MEM_TOTAL', + 'MEMINFO_MLOCKED', + 'MEMINFO_PAGE_TABLES', + 'MEMINFO_SHMEM', + 'MEMINFO_SLAB', + 'MEMINFO_SLAB_RECLAIMABLE', + 'MEMINFO_SLAB_UNRECLAIMABLE', + 'MEMINFO_SWAP_CACHED', + 'MEMINFO_SWAP_FREE', + 'MEMINFO_SWAP_TOTAL', + 'MEMINFO_UNEVICTABLE', + 'MEMINFO_VMALLOC_CHUNK', + 'MEMINFO_VMALLOC_TOTAL', + 'MEMINFO_VMALLOC_USED', + 'MEMINFO_WRITEBACK', + 'MEMINFO_KERNEL_RECLAIMABLE', + 'PMEM_ACTIVE_PURG', + 'PMEM_INACTIVE_PURG', + 'PMEM_PINED_PURG', +]; + +export const VMEM_INFO = [ + 'VMEMINFO_UNSPECIFIED', + 'VMEMINFO_NR_FREE_PAGES', + 'VMEMINFO_NR_ALLOC_BATCH', + 'VMEMINFO_NR_INACTIVE_ANON', + 'VMEMINFO_NR_ACTIVE_ANON', + 'VMEMINFO_NR_INACTIVE_FILE', + 'VMEMINFO_NR_ACTIVE_FILE', + 'VMEMINFO_NR_UNEVICTABLE', + 'VMEMINFO_NR_MLOCK', + 'VMEMINFO_NR_ANON_PAGES', + 'VMEMINFO_NR_MAPPED', + 'VMEMINFO_NR_FILE_PAGES', + 'VMEMINFO_NR_DIRTY', + 'VMEMINFO_NR_WRITEBACK', + 'VMEMINFO_NR_SLAB_RECLAIMABLE', + 'VMEMINFO_NR_SLAB_UNRECLAIMABLE', + 'VMEMINFO_NR_PAGE_TABLE_PAGES', + 'VMEMINFO_NR_KERNEL_STACK', + 'VMEMINFO_NR_OVERHEAD', + 'VMEMINFO_NR_UNSTABLE', + 'VMEMINFO_NR_BOUNCE', + 'VMEMINFO_NR_VMSCAN_WRITE', + 'VMEMINFO_NR_VMSCAN_IMMEDIATE_RECLAIM', + 'VMEMINFO_NR_WRITEBACK_TEMP', + 'VMEMINFO_NR_ISOLATED_ANON', + 'VMEMINFO_NR_ISOLATED_FILE', + 'VMEMINFO_NR_SHMEM', + 'VMEMINFO_NR_DIRTIED', + 'VMEMINFO_NR_WRITTEN', + 'VMEMINFO_NR_PAGES_SCANNED', + 'VMEMINFO_WORKINGSET_REFAULT', + 'VMEMINFO_WORKINGSET_ACTIVATE', + 'VMEMINFO_WORKINGSET_NODERECLAIM', + 'VMEMINFO_NR_ANON_TRANSPARENT_HUGEPAGES', + 'VMEMINFO_NR_FREE_CMA', + 'VMEMINFO_NR_SWAPCACHE', + 'VMEMINFO_NR_DIRTY_THRESHOLD', + 'VMEMINFO_NR_DIRTY_BACKGROUND_THRESHOLD', + 'VMEMINFO_PGPGIN', + 'VMEMINFO_PGPGOUT', + 'VMEMINFO_PGPGOUTCLEAN', + 'VMEMINFO_PSWPIN', + 'VMEMINFO_PSWPOUT', + 'VMEMINFO_PGALLOC_DMA', +]; + +export const VMEM_INFO_SECOND = [ + 'VMEMINFO_PGALLOC_NORMAL', + 'VMEMINFO_PGALLOC_MOVABLE', + 'VMEMINFO_PGFREE', + 'VMEMINFO_PGACTIVATE', + 'VMEMINFO_PGDEACTIVATE', + 'VMEMINFO_PGFAULT', + 'VMEMINFO_PGMAJFAULT', + 'VMEMINFO_PGREFILL_DMA', + 'VMEMINFO_PGREFILL_NORMAL', + 'VMEMINFO_PGREFILL_MOVABLE', + 'VMEMINFO_PGSTEAL_KSWAPD_DMA', + 'VMEMINFO_PGSTEAL_KSWAPD_NORMAL', + 'VMEMINFO_PGSTEAL_KSWAPD_MOVABLE', + 'VMEMINFO_PGSTEAL_DIRECT_DMA', + 'VMEMINFO_PGSTEAL_DIRECT_NORMAL', + 'VMEMINFO_PGSTEAL_DIRECT_MOVABLE', + 'VMEMINFO_PGSCAN_KSWAPD_DMA', + 'VMEMINFO_PGSCAN_KSWAPD_NORMAL', + 'VMEMINFO_PGSCAN_KSWAPD_MOVABLE', + 'VMEMINFO_PGSCAN_DIRECT_DMA', + 'VMEMINFO_PGSCAN_DIRECT_NORMAL', + 'VMEMINFO_PGSCAN_DIRECT_MOVABLE', + 'VMEMINFO_PGSCAN_DIRECT_THROTTLE', + 'VMEMINFO_PGINODESTEAL', + 'VMEMINFO_SLABS_SCANNED', + 'VMEMINFO_KSWAPD_INODESTEAL', + 'VMEMINFO_KSWAPD_LOW_WMARK_HIT_QUICKLY', + 'VMEMINFO_KSWAPD_HIGH_WMARK_HIT_QUICKLY', + 'VMEMINFO_PAGEOUTRUN', + 'VMEMINFO_ALLOCSTALL', + 'VMEMINFO_PGROTATED', + 'VMEMINFO_DROP_PAGECACHE', + 'VMEMINFO_DROP_SLAB', + 'VMEMINFO_PGMIGRATE_SUCCESS', + 'VMEMINFO_PGMIGRATE_FAIL', + 'VMEMINFO_COMPACT_MIGRATE_SCANNED', + 'VMEMINFO_COMPACT_FREE_SCANNED', + 'VMEMINFO_COMPACT_ISOLATED', + 'VMEMINFO_COMPACT_STALL', + 'VMEMINFO_COMPACT_FAIL', + 'VMEMINFO_COMPACT_SUCCESS', + 'VMEMINFO_COMPACT_DAEMON_WAKE', + 'VMEMINFO_UNEVICTABLE_PGS_CULLED', + 'VMEMINFO_UNEVICTABLE_PGS_SCANNED', + 'VMEMINFO_UNEVICTABLE_PGS_RESCUED', + 'VMEMINFO_UNEVICTABLE_PGS_MLOCKED', + 'VMEMINFO_UNEVICTABLE_PGS_MUNLOCKED', +]; + +export const VMEM_INFO_THIRD = [ + 'VMEMINFO_UNEVICTABLE_PGS_CLEARED', + 'VMEMINFO_UNEVICTABLE_PGS_STRANDED', + 'VMEMINFO_NR_ZSPAGES', + 'VMEMINFO_NR_ION_HEAP', + 'VMEMINFO_NR_GPU_HEAP', + 'VMEMINFO_ALLOCSTALL_DMA', + 'VMEMINFO_ALLOCSTALL_MOVABLE', + 'VMEMINFO_ALLOCSTALL_NORMAL', + 'VMEMINFO_COMPACT_DAEMON_FREE_SCANNED', + 'VMEMINFO_COMPACT_DAEMON_MIGRATE_SCANNED', + 'VMEMINFO_NR_FASTRPC', + 'VMEMINFO_NR_INDIRECTLY_RECLAIMABLE', + 'VMEMINFO_NR_ION_HEAP_POOL', + 'VMEMINFO_NR_KERNEL_MISC_RECLAIMABLE', + 'VMEMINFO_NR_SHADOW_CALL_STACK_BYTES', + 'VMEMINFO_NR_SHMEM_HUGEPAGES', + 'VMEMINFO_NR_SHMEM_PMDMAPPED', + 'VMEMINFO_NR_UNRECLAIMABLE_PAGES', + 'VMEMINFO_NR_ZONE_ACTIVE_ANON', + 'VMEMINFO_NR_ZONE_ACTIVE_FILE', + 'VMEMINFO_NR_ZONE_INACTIVE_ANON', + 'VMEMINFO_NR_ZONE_INACTIVE_FILE', + 'VMEMINFO_NR_ZONE_UNEVICTABLE', + 'VMEMINFO_NR_ZONE_WRITE_PENDING', + 'VMEMINFO_OOM_KILL', + 'VMEMINFO_PGLAZYFREE', + 'VMEMINFO_PGLAZYFREED', + 'VMEMINFO_PGREFILL', + 'VMEMINFO_PGSCAN_DIRECT', + 'VMEMINFO_PGSCAN_KSWAPD', + 'VMEMINFO_PGSKIP_DMA', + 'VMEMINFO_PGSKIP_MOVABLE', + 'VMEMINFO_PGSKIP_NORMAL', + 'VMEMINFO_PGSTEAL_DIRECT', + 'VMEMINFO_PGSTEAL_KSWAPD', + 'VMEMINFO_SWAP_RA', + 'VMEMINFO_SWAP_RA_HIT', + 'VMEMINFO_WORKINGSET_RESTORE', +]; +// sys.mem.total sys.mem.free sys.mem.buffers sys.mem.cached sys.mem.shmem sys.mem.slab sys.mem.swap.total +// sys.mem.swap.free sys.mem.mapped sys.mem.vmalloc.used sys.mem.page.tables sys.mem.kernel.stack +// sys.mem.active sys.mem.inactive sys.mem.unevictable sys.mem.vmalloc.total sys.mem.slab.unreclaimable +// sys.mem.cma.total sys.mem.cma.free +export const ABALITY_MEM_INFO = [ + 'MEMINFO_MEM_TOTAL', + 'MEMINFO_MEM_FREE', + 'MEMINFO_BUFFERS', + 'MEMINFO_CACHED', + 'MEMINFO_SHMEM', + 'MEMINFO_SLAB', + 'MEMINFO_SWAP_TOTAL', + 'MEMINFO_SWAP_FREE', + 'MEMINFO_MAPPED', + 'MEMINFO_VMALLOC_USED', + 'MEMINFO_PAGE_TABLES', + 'MEMINFO_KERNEL_STACK', + 'MEMINFO_ACTIVE', + 'MEMINFO_INACTIVE', + 'MEMINFO_UNEVICTABLE', + 'MEMINFO_VMALLOC_TOTAL', + 'MEMINFO_SLAB_UNRECLAIMABLE', + 'MEMINFO_CMA_TOTAL', + 'MEMINFO_CMA_FREE', + 'MEMINFO_KERNEL_RECLAIMABLE', + 'PMEM_ACTIVE_PURG', + 'PMEM_INACTIVE_PURG', + 'PMEM_PINED_PURG', +]; + +export const schedulingEvents = [ + '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', +]; + +export const powerEvents = [ + 'regulator/regulator_set_voltage', + 'regulator/regulator_set_voltage_complete', + 'power/clock_enable', + 'power/clock_disable', + 'power/clock_set_rate', + 'power/suspend_resume', +]; + +export const cpuFreqEvents = ['power/cpu_frequency', 'power/cpu_idle', 'power/suspend_resume']; + +export const sysCallsEvents = ['raw_syscalls/sys_enter', 'raw_syscalls/sys_exit']; + +export const highFrequencyEvents = [ + 'mm_event/mm_event_record', + 'kmem/rss_stat', + 'ion/ion_stat', + 'dmabuf_heap/dma_heap_stat', + 'kmem/ion_heap_grow', + 'kmem/ion_heap_shrink', +]; + +export const advancedConfigEvents = [ + 'sched/sched_switch', + 'sched/sched_wakeup', + 'sched/sched_wakeup_new', + 'sched/sched_waking', + 'sched/sched_process_exit', + 'sched/sched_process_free', + 'irq/irq_handler_entry', + 'irq/irq_handler_exit', + 'irq/softirq_entry', + 'irq/softirq_exit', + 'irq/softirq_raise', + 'power/clock_disable', + 'power/clock_enable', + 'power/clock_set_rate', + 'power/cpu_frequency', + 'power/cpu_idle', + 'clk/clk_disable', + 'clk/clk_disable_complete', + 'clk/clk_enable', + 'clk/clk_enable_complete', + 'clk/clk_set_rate', + 'clk/clk_set_rate_complete', + 'binder/binder_transaction', + 'binder/binder_transaction_alloc_buf', + 'binder/binder_transaction_received', + 'binder/binder_lock', + 'binder/binder_locked', + 'binder/binder_unlock', + 'workqueue/workqueue_execute_start', + 'workqueue/workqueue_execute_end', + 'oom/oom_score_adj_update', + 'ftrace/print', +]; + +export function createSessionRequest(recordSetting: SpRecordSetting): CreateSessionRequest { + let bufferConfig: ProfilerSessionConfigBufferConfig = { + pages: recordSetting.bufferSize * 256, + policy: ProfilerSessionConfigBufferConfigPolicy.RECYCLE, + }; + let sessionConfig: ProfilerSessionConfig = { + buffers: [bufferConfig], + sessionMode: ProfilerSessionConfigMode.OFFLINE, + resultMaxSize: 0, + keepAliveTime: 0, + }; + return { + requestId: 1, + sessionConfig: sessionConfig, + pluginConfigs: [], + }; +} + +export function createMemoryPluginConfig( + reportingFrequency: number, + spVmTracker: SpVmTracker, + probesConfig: SpProbesConfig, + request: CreateSessionRequest +):void { + let hasSamp = spVmTracker!.startSamp && spVmTracker!.process !== ''; + if (probesConfig!.memoryConfig.length > 0 || hasMonitorMemory || hasSamp) { + let memoryConfig = initMemoryPluginConfig(hasSamp, spVmTracker, probesConfig); + if (hasMonitorMemory) { + ABALITY_MEM_INFO.forEach((va) => { + memoryConfig.sysMeminfoCounters.push(sysMeminfoTypeFromJSON(va)); + }); + } + probesConfig!.memoryConfig.forEach((value) => { + if (value.indexOf('Kernel meminfo') !== -1) { + if (hasMonitorMemory) { + memoryConfig.sysMeminfoCounters = []; + } + MEM_INFO.forEach((va) => { + memoryConfig.sysMeminfoCounters.push(sysMeminfoTypeFromJSON(va)); + }); + } + if (value.indexOf('Virtual memory stats') !== -1) { + VMEM_INFO.forEach((me) => { + memoryConfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me)); + }); + VMEM_INFO_SECOND.forEach((me) => { + memoryConfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me)); + }); + VMEM_INFO_THIRD.forEach((me) => { + memoryConfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me)); + }); + } + }); + request.pluginConfigs.push({ + pluginName: 'memory-plugin', + sampleInterval: reportingFrequency * 1000, + configData: memoryConfig, + }); + } +} + +function initMemoryPluginConfig( + hasSamp: boolean, + spVmTracker: SpVmTracker, + probesConfig: SpProbesConfig, +): MemoryConfig { + let memoryConfig: MemoryConfig = { + reportProcessTree: false, + reportSysmemMemInfo: false, + sysMeminfoCounters: [], + reportSysmemVmemInfo: false, + sysVmeminfoCounters: [], + reportProcessMemInfo: false, + reportAppMemInfo: false, + reportAppMemByMemoryService: false, + pid: [], + }; + if (probesConfig!.memoryConfig.length > 0 || hasMonitorMemory) { + memoryConfig.reportProcessTree = true; + memoryConfig.reportSysmemMemInfo = true; + memoryConfig.reportSysmemVmemInfo = true; + memoryConfig.reportProcessMemInfo = true; + } + if (spVmTracker!.startSamp) { + memoryConfig.reportProcessMemInfo = true; + } + if (hasSamp || hasMonitorMemory) { + memoryConfig.reportPurgeableAshmemInfo = true; + memoryConfig.reportDmaMemInfo = true; + memoryConfig.reportGpuMemInfo = true; + } + if (hasSamp) { + memoryConfig.reportSmapsMemInfo = true; + memoryConfig.reportGpuDumpInfo = true; + let pid = Number(spVmTracker?.process); + memoryConfig.pid.push(pid); + } + return memoryConfig; +} + +export function createHTracePluginConfig( + probesConfig: SpProbesConfig, + request: CreateSessionRequest +): void { + if ( + probesConfig!.traceConfig.length > 0 && + probesConfig!.traceConfig.find((value) => value !== 'FPS')) + { + let tracePluginConfig: TracePluginConfig = { + ftraceEvents: createTraceEvents(probesConfig!.traceConfig), + hitraceCategories: [], + hitraceApps: [], + bufferSizeKb: probesConfig!.ftraceBufferSize, + flushIntervalMs: 1000, + flushThresholdKb: 4096, + parseKsyms: true, + clock: 'boot', + tracePeriodMs: 200, + rawDataPrefix: '', + traceDurationMs: 0, + debugOn: false, + }; + if (probesConfig!.traceEvents.length > 0) { + tracePluginConfig.hitraceCategories = probesConfig!.traceEvents; + } + request.pluginConfigs.push({ + pluginName: 'ftrace-plugin', + sampleInterval: 1000, + configData: tracePluginConfig, + }); + } +} + +export function createFpsPluginConfig( + probesConfig: SpProbesConfig, + request: CreateSessionRequest +): void { + let fpsConfig: FpsConfig = { + reportFps: true, + }; + if (probesConfig!.traceConfig.length > 0 && probesConfig!.traceConfig.indexOf('FPS') !== -1) { + request.pluginConfigs.push({ + pluginName: 'hidump-plugin', + sampleInterval: 1000, + configData: fpsConfig, + }); + } +} + +export function createMonitorPlugin( + probesConfig: SpProbesConfig, + request: CreateSessionRequest +): void { + hasMonitorMemory = probesConfig.recordAbility; + if (!probesConfig.recordAbility) { + return; + } + let cpuPlugin = { + pluginName: 'cpu-plugin', + sampleInterval: 1000, + configData: { + pid: 0, + reportProcessInfo: true, + }, + }; + let processPlugin = { + pluginName: 'process-plugin', + sampleInterval: 1000, + configData: { + report_process_tree: true, + report_cpu: true, + report_diskio: true, + report_pss: true, + }, + }; + let diskIoPlugin = { + pluginName: 'diskio-plugin', + sampleInterval: 1000, + configData: { + reportIoStats: 'IO_REPORT', + }, + }; + let netWorkPlugin = { + pluginName: 'network-plugin', + sampleInterval: 1000, + configData: {}, + }; + request.pluginConfigs.push(processPlugin); + request.pluginConfigs.push(cpuPlugin); + request.pluginConfigs.push(diskIoPlugin); + request.pluginConfigs.push(netWorkPlugin); +} + +export function createNativePluginConfig( + reportingFrequency: number, + spAllocations: SpAllocations, + selectVersion: string | null, + request: CreateSessionRequest +): void { + if (spAllocations!.appProcess !== '' && spAllocations!.startSamp) { + let nativeConfig = initNativePluginConfig(spAllocations, selectVersion); + let maxProcessSize = 4; + if (selectVersion !== undefined && selectVersion !== '3.2') { + nativeConfig.callframeCompress = true; + nativeConfig.recordAccurately = spAllocations!.record_accurately; + nativeConfig.offlineSymbolization = spAllocations!.offline_symbolization; + if (spAllocations!.record_statistics) { + nativeConfig.statisticsInterval = spAllocations!.statistics_interval; + } + nativeConfig.startupMode = spAllocations!.startup_mode; + if (spAllocations!.response_lib_mode) { + nativeConfig.responseLibraryMode = spAllocations!.response_lib_mode; + maxProcessSize = 8; + } + if (spAllocations!.sample_interval) { + nativeConfig.sampleInterval = spAllocations!.sample_interval; + } + } + if (spAllocations!.expandPids.length > 1) { + nativeConfig.expandPids = spAllocations!.expandPids.splice(0, maxProcessSize); + } + request.pluginConfigs.push({ + pluginName: 'nativehook', + sampleInterval: reportingFrequency * 1000, + configData: nativeConfig, + }); + } +} + +function initNativePluginConfig( + spAllocations: SpAllocations, + selectVersion: string | null, +): NativeHookConfig { + let appProcess = spAllocations!.appProcess; + let processName = ''; + let processId = ''; + if (spAllocations!.startup_mode && selectVersion !== '3.2') { + processName = appProcess; + } else { + if (appProcess.indexOf('(') !== -1) { + processId = appProcess.slice(appProcess.lastIndexOf('(') + 1, appProcess.lastIndexOf(')')); + } else { + processId = appProcess; + } + if (/^[0-9]+.?[0-9]*/.test(processId)) { + let pid = Number(processId); + } else { + processName = appProcess; + } + } + let nativeConfig: NativeHookConfig; + if (spAllocations!.expandPids.length === 1) { + nativeConfig = { + pid: spAllocations!.expandPids[0], + saveFile: false, + fileName: '', + filterSize: spAllocations!.filter, + smbPages: spAllocations!.shared, + maxStackDepth: spAllocations!.unwind, + processName: processName, + stringCompressed: true, + fpUnwind: spAllocations!.fp_unwind, + blocked: true, + }; + } else { + nativeConfig = { + saveFile: false, + fileName: '', + filterSize: spAllocations!.filter, + smbPages: spAllocations!.shared, + maxStackDepth: spAllocations!.unwind, + processName: processName, + stringCompressed: true, + fpUnwind: spAllocations!.fp_unwind, + blocked: true, + }; + } + return nativeConfig; +} + +function initHiPerfConfig( + perfConfig: PerfConfig | undefined, + recordArgs: string +): string{ + if (perfConfig?.cpu && !perfConfig?.cpu.includes('ALL') && perfConfig?.cpu.length > 0) { + recordArgs = `${recordArgs} -c ${perfConfig?.cpu}`; + } + if (perfConfig?.cpuPercent !== 0) { + recordArgs = `${recordArgs} --cpu-limit ${perfConfig?.cpuPercent}`; + } + if (perfConfig?.eventList && !perfConfig?.eventList.includes('NONE') && perfConfig?.eventList.length > 0) { + recordArgs = `${recordArgs} -e ${perfConfig?.eventList}`; + if (perfConfig?.isOffCpu) { + recordArgs = `${recordArgs},sched:sched_waking`; + } + } else { + recordArgs = `${recordArgs} -e hw-cpu-cycles`; + if (perfConfig?.isOffCpu) { + recordArgs = `${recordArgs},sched:sched_waking`; + } + } + if (perfConfig?.callStack !== 'none') { + recordArgs = `${recordArgs} --call-stack ${perfConfig?.callStack}`; + } + if (perfConfig?.branch !== 'none') { + recordArgs = `${recordArgs} -j ${perfConfig?.branch}`; + } + if (perfConfig?.clockType) { + recordArgs = `${recordArgs} --clockid ${perfConfig?.clockType}`; + } + if (perfConfig?.isOffCpu) { + recordArgs = `${recordArgs} --offcpu`; + } + if (perfConfig?.noInherit) { + recordArgs = `${recordArgs} --no-inherit`; + } + if (perfConfig?.mmap) { + recordArgs = `${recordArgs} -m ${perfConfig.mmap}`; + } + return recordArgs; +} + +export function createHiPerfConfig( + reportingFrequency: number, + spRecordPerf: SpRecordPerf, + recordSetting: SpRecordSetting, + request: CreateSessionRequest +): void { + if (!spRecordPerf!.startSamp) { + return; + } + let perfConfig = spRecordPerf!.getPerfConfig(); + let recordArgs = ''; + 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 (!isNaN(Number(processIdOrName[0]))) { + recordArgs = `${recordArgs} -p ${perfConfig?.process}`; + } else { + recordArgs = `${recordArgs} --app ${perfConfig?.process}`; + } + } else { + if (!isNaN(Number(process))) { + recordArgs = `${recordArgs} -p ${perfConfig?.process}`; + } else { + recordArgs = `${recordArgs} --app ${perfConfig?.process}`; + } + } + } else { + recordArgs = `${recordArgs} -a `; + } + recordArgs = initHiPerfConfig(perfConfig, recordArgs); + info('record config Args is: ', recordArgs); + let hiPerf: HiperfPluginConfig = { + isRoot: false, + outfileName: '/data/local/tmp/perf.data', + recordArgs: recordArgs, + }; + if (SpApplication.isLongTrace) { + hiPerf.splitOutfileName = `${recordSetting!.longOutPath}hiprofiler_data_hiperf.htrace`; + } + request.pluginConfigs.push({ + pluginName: 'hiperf-plugin', + sampleInterval: reportingFrequency * 1000, + configData: hiPerf, + }); +} + +export function createSystemConfig( + spFileSystem: SpFileSystem, + recordSetting: SpRecordSetting, + request: CreateSessionRequest +): void { + if (!spFileSystem!.startRecord) { + return; + } + let systemConfig = spFileSystem!.getSystemConfig(); + let recordArgs = 'hiebpf'; + let recordEvent = []; + if (spFileSystem?.startFileSystem) { + recordEvent.push('fs'); + } + if (spFileSystem?.startVirtualMemory) { + recordEvent.push('ptrace'); + } + if (spFileSystem?.startIo) { + recordEvent.push('bio'); + } + if (recordEvent.length > 0) { + recordArgs += ` --events ${recordEvent.toString()}`; + } + recordArgs += ` --duration ${recordSetting?.maxDur}`; + if (systemConfig?.process && !systemConfig?.process.includes('ALL') && systemConfig?.process.length > 0) { + recordArgs = `${recordArgs} --pids ${systemConfig?.process}`; + } + recordArgs += ` --max_stack_depth ${systemConfig?.unWindLevel}`; + let systemPluginConfig: HiebpfConfig = { + cmdLine: recordArgs, + outfileName: '/data/local/tmp/ebpf.data', + }; + if (SpApplication.isLongTrace) { + systemPluginConfig.splitOutfileName = `${recordSetting?.longOutPath}hiprofiler_data_ebpf.htrace`; + } + request.pluginConfigs.push({ + pluginName: 'hiebpf-plugin', + sampleInterval: 1000, + configData: systemPluginConfig, + }); +} + +export function createSdkConfig( + spSdkConfig: SpSdkConfig, + request: CreateSessionRequest +): void { + if (spSdkConfig.startSamp && spSdkConfig.getPlugName() !== '') { + let gpuConfig = spSdkConfig!.getGpuConfig(); + request.pluginConfigs.push({ + pluginName: spSdkConfig!.getPlugName(), + sampleInterval: spSdkConfig!.getSampleInterval(), + configData: gpuConfig, + }); + } + return; +} + +export function createHiSystemEventPluginConfig( + spHiSysEvent: SpHisysEvent, + request: CreateSessionRequest +): void { + if (!spHiSysEvent.startSamp) { + return; + } + request.pluginConfigs.push({ + pluginName: 'hisysevent-plugin', + configData: { + msg: 'hisysevent-plugin', + subscribe_domain: spHiSysEvent.domain, + subscribe_event: spHiSysEvent.eventName, + }, + }); +} + +export function createArkTsConfig( + spArkTs: SpArkTs, + recordSetting: SpRecordSetting, + request: CreateSessionRequest +): void { + if (spArkTs.process !== '' && spArkTs.startSamp) { + let process = spArkTs!.process; + let re = /^[0-9]+.?[0-9]*/; + let pid = 0; + let processId = ''; + if (process.indexOf('(') !== -1) { + processId = process.slice(process.lastIndexOf('(') + 1, process.lastIndexOf(')')); + } else { + processId = process; + } + if (re.test(processId)) { + pid = Number(processId); + } + let arkTSConfig: ArkTSConfig = { + pid: pid, + type: spArkTs.radioBoxType, + interval: spArkTs.intervalValue, + capture_numeric_value: spArkTs.grabNumeric, + track_allocations: spArkTs.grabAllocations, + enable_cpu_profiler: spArkTs.grabCpuProfiler, + cpu_profiler_interval: spArkTs.intervalCpuValue, + }; + if (SpApplication.isLongTrace) { + arkTSConfig.splitOutfileName = `${recordSetting?.longOutPath}hiprofiler_data_arkts.htrace`; + } + request.pluginConfigs.push({ + pluginName: 'arkts-plugin', + sampleInterval: 5000, + configData: arkTSConfig, + }); + } + return; +} + +export function createHiLogConfig( + reportingFrequency: number, + spHiLog: SpHilogRecord, + request: CreateSessionRequest +): void { + if (!spHiLog.recordHilog) { + return; + } + let appProcess = spHiLog!.appProcess; + let re = /^[0-9]+.?[0-9]*/; + let pid = 0; + let processId = ''; + if (appProcess.indexOf('(') !== -1) { + processId = appProcess.slice(appProcess.lastIndexOf('(') + 1, appProcess.lastIndexOf(')')); + } else { + processId = appProcess; + } + if (re.test(processId)) { + pid = Number(processId); + } + let hiLogConfig: HilogConfig = { + pid: pid, + logLevel: levelFromJSON(spHiLog!.appLogLevel), + needClear: true, + }; + request.pluginConfigs.push({ + pluginName: 'hilog-plugin', + sampleInterval: reportingFrequency * 1000, + configData: hiLogConfig, + }); +} + +export function createTraceEvents(traceConfig: Array): Array { + let traceEvents = new Set(); + traceConfig.forEach((config) => { + switch (config) { + case 'Scheduling details': + schedulingEvents.forEach((eve: string) => { + traceEvents.add(eve); + }); + break; + case 'CPU Frequency and idle states': + cpuFreqEvents.forEach((eve: string) => { + traceEvents.add(eve); + }); + break; + case 'High frequency memory': + highFrequencyEvents.forEach((eve: string) => { + traceEvents.add(eve); + }); + break; + case 'Advanced ftrace config': + advancedConfigEvents.forEach((eve: string) => { + traceEvents.add(eve); + }); + break; + case 'Syscalls': + sysCallsEvents.forEach((eve: string) => { + traceEvents.add(eve); + }); + break; + case 'Board voltages & frequency': + powerEvents.forEach((eve: string) => { + traceEvents.add(eve); + }); + break; + } + }); + let ftraceEventsArray: string[] = []; + info('traceEvents length is: ', traceEvents.size); + for (const ftraceEvent of traceEvents) { + ftraceEventsArray.push(ftraceEvent); + } + return ftraceEventsArray; +} + +let hasMonitorMemory = false; diff --git a/ide/src/trace/component/SpRecordTrace.html.ts b/ide/src/trace/component/SpRecordTrace.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..905c398fdec7c1a4387e54d31681cfc6f81bbf2b --- /dev/null +++ b/ide/src/trace/component/SpRecordTrace.html.ts @@ -0,0 +1,203 @@ +/* + * 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. + */ + +export const SpRecordTraceHtml = ` + +
+
+
+ Target Platform: +
+ + +
+ + Add HDC Device +
+ Disconnect + + Record + + + Cancel + +
+
+
+ It looks like you didn't add any probes. Please add at least one +
+
+
+ +
+
+
+
+ `; diff --git a/ide/src/trace/component/SpRecordTrace.ts b/ide/src/trace/component/SpRecordTrace.ts index b1174d761d2df60d244a1a667e293ec0baa492bb..f30f0f08d9e9042c079ab31622b49ef967ba8bcf 100644 --- a/ide/src/trace/component/SpRecordTrace.ts +++ b/ide/src/trace/component/SpRecordTrace.ts @@ -27,29 +27,7 @@ import LitSwitch from '../../base-ui/switch/lit-switch'; import { LitSlider } from '../../base-ui/slider/LitSlider'; import { - CpuConfig, - CreateSessionRequest, - DiskioConfig, - HiebpfConfig, - FpsConfig, - HilogConfig, - HiperfPluginConfig, - HiSystemEventConfig, - ArkTSConfig, - levelFromJSON, - MemoryConfig, - NativeHookConfig, - NetworkConfig, - ProcessConfig, - ProfilerPluginConfig, - ProfilerSessionConfig, - ProfilerSessionConfigBufferConfig, - ProfilerSessionConfigBufferConfigPolicy, - ProfilerSessionConfigMode, - sysMeminfoTypeFromJSON, - sysVMeminfoTypeFromJSON, - TracePluginConfig, - Type, + CreateSessionRequest } from './setting/bean/ProfilerServiceTypes'; import { PluginConvertUtils } from './setting/utils/PluginConvertUtils'; import { SpAllocations } from './setting/SpAllocations'; @@ -59,7 +37,7 @@ import { LitButton } from '../../base-ui/button/LitButton'; import { SpApplication } from '../SpApplication'; import { LitSearch } from './trace/search/Search'; import { LitProgressBar } from '../../base-ui/progress-bar/LitProgressBar'; -import { info, log } from '../../log/Log'; +import { log } from '../../log/Log'; import { CmdConstant } from '../../command/CmdConstant'; import { Cmd } from '../../command/Cmd'; import { SpFileSystem } from './setting/SpFileSystem'; @@ -72,18 +50,61 @@ import { SpArkTs } from './setting/SpArkTs'; import { SpWebHdcShell } from './setting/SpWebHdcShell'; import { SpHilogRecord } from './setting/SpHilogRecord'; import { LongTraceDBUtils } from '../database/LongTraceDBUtils'; +import { + createFpsPluginConfig, + createHTracePluginConfig, + createHiPerfConfig, + createMemoryPluginConfig, + createMonitorPlugin, + createNativePluginConfig, + createSessionRequest, + createSystemConfig, createSdkConfig, createHiSystemEventPluginConfig, createArkTsConfig, createHiLogConfig, +} from './SpRecordConfigModel'; +import { SpRecordTraceHtml } from './SpRecordTrace.html'; @element('sp-record-trace') export class SpRecordTrace extends BaseElement { public static serialNumber: string = ''; public static selectVersion: string | null; - // 1GB - public static MaxFileSize: number = 1024 * 1024 * 1024; public static isVscode = false; public static cancelRecord = false; static supportVersions = ['3.2', '4.0+']; + public deviceSelect: HTMLSelectElement | undefined; + public deviceVersion: HTMLSelectElement | undefined; + private _menuItems: Array | undefined; + private recordButtonText: HTMLSpanElement | undefined; + private devicePrompt: HTMLSpanElement | undefined; + private recordButton: LitButton | undefined; + private cancelButton: LitButton | undefined; + private sp: SpApplication | undefined; + private progressEL: LitProgressBar | undefined; + private litSearch: LitSearch | undefined; + private addButton: LitButton | undefined | null; + private disconnectButton: LitButton | undefined | null; + private recordSetting: SpRecordSetting | undefined; + private probesConfig: SpProbesConfig | undefined; + private traceCommand: SpTraceCommand | undefined; + private spAllocations: SpAllocations | undefined; + private spRecordPerf: SpRecordPerf | undefined; + private spFileSystem: SpFileSystem | undefined; + private spSdkConfig: SpSdkConfig | undefined; + private spVmTracker: SpVmTracker | undefined; + private spHiSysEvent: SpHisysEvent | undefined; + private spRecordTemplate: SpRecordTemplate | undefined; + private spArkTs: SpArkTs | undefined; + private spHiLog: SpHilogRecord | undefined; + private ftraceSlider: LitSlider | undefined | null; + private spWebShell: SpWebHdcShell | undefined; + private menuGroup: LitMainMenuGroup | undefined | null; + private appContent: HTMLElement | undefined | null; + private record = 'Record'; + private stop = 'StopRecord'; private nowChildItem: HTMLElement | undefined; private longTraceList: Array = []; + private refreshDeviceTimer: number | undefined; + private hintEl: HTMLSpanElement | undefined; + private selectedTemplate: Map = new Map(); + private hintTimeOut: number = -1; set record_template(re: boolean) { if (re) { @@ -114,319 +135,17 @@ export class SpRecordTrace extends BaseElement { return this.hasAttribute('vs'); } - static MEM_INFO = [ - 'MEMINFO_ACTIVE', - 'MEMINFO_ACTIVE_ANON', - 'MEMINFO_ACTIVE_FILE', - 'MEMINFO_ANON_PAGES', - 'MEMINFO_BUFFERS', - 'MEMINFO_CACHED', - 'MEMINFO_CMA_FREE', - 'MEMINFO_CMA_TOTAL', - 'MEMINFO_COMMIT_LIMIT', - 'MEMINFO_COMMITED_AS', - 'MEMINFO_DIRTY', - 'MEMINFO_INACTIVE', - 'MEMINFO_INACTIVE_ANON', - 'MEMINFO_INACTIVE_FILE', - 'MEMINFO_KERNEL_STACK', - 'MEMINFO_MAPPED', - 'MEMINFO_MEM_AVAILABLE', - 'MEMINFO_MEM_FREE', - 'MEMINFO_MEM_TOTAL', - 'MEMINFO_MLOCKED', - 'MEMINFO_PAGE_TABLES', - 'MEMINFO_SHMEM', - 'MEMINFO_SLAB', - 'MEMINFO_SLAB_RECLAIMABLE', - 'MEMINFO_SLAB_UNRECLAIMABLE', - 'MEMINFO_SWAP_CACHED', - 'MEMINFO_SWAP_FREE', - 'MEMINFO_SWAP_TOTAL', - 'MEMINFO_UNEVICTABLE', - 'MEMINFO_VMALLOC_CHUNK', - 'MEMINFO_VMALLOC_TOTAL', - 'MEMINFO_VMALLOC_USED', - 'MEMINFO_WRITEBACK', - 'MEMINFO_KERNEL_RECLAIMABLE', - 'PMEM_ACTIVE_PURG', - 'PMEM_INACTIVE_PURG', - 'PMEM_PINED_PURG', - ]; - static VMEM_INFO = [ - 'VMEMINFO_UNSPECIFIED', - 'VMEMINFO_NR_FREE_PAGES', - 'VMEMINFO_NR_ALLOC_BATCH', - 'VMEMINFO_NR_INACTIVE_ANON', - 'VMEMINFO_NR_ACTIVE_ANON', - 'VMEMINFO_NR_INACTIVE_FILE', - 'VMEMINFO_NR_ACTIVE_FILE', - 'VMEMINFO_NR_UNEVICTABLE', - 'VMEMINFO_NR_MLOCK', - 'VMEMINFO_NR_ANON_PAGES', - 'VMEMINFO_NR_MAPPED', - 'VMEMINFO_NR_FILE_PAGES', - 'VMEMINFO_NR_DIRTY', - 'VMEMINFO_NR_WRITEBACK', - 'VMEMINFO_NR_SLAB_RECLAIMABLE', - 'VMEMINFO_NR_SLAB_UNRECLAIMABLE', - 'VMEMINFO_NR_PAGE_TABLE_PAGES', - 'VMEMINFO_NR_KERNEL_STACK', - 'VMEMINFO_NR_OVERHEAD', - 'VMEMINFO_NR_UNSTABLE', - 'VMEMINFO_NR_BOUNCE', - 'VMEMINFO_NR_VMSCAN_WRITE', - 'VMEMINFO_NR_VMSCAN_IMMEDIATE_RECLAIM', - 'VMEMINFO_NR_WRITEBACK_TEMP', - 'VMEMINFO_NR_ISOLATED_ANON', - 'VMEMINFO_NR_ISOLATED_FILE', - 'VMEMINFO_NR_SHMEM', - 'VMEMINFO_NR_DIRTIED', - 'VMEMINFO_NR_WRITTEN', - 'VMEMINFO_NR_PAGES_SCANNED', - 'VMEMINFO_WORKINGSET_REFAULT', - 'VMEMINFO_WORKINGSET_ACTIVATE', - 'VMEMINFO_WORKINGSET_NODERECLAIM', - 'VMEMINFO_NR_ANON_TRANSPARENT_HUGEPAGES', - 'VMEMINFO_NR_FREE_CMA', - 'VMEMINFO_NR_SWAPCACHE', - 'VMEMINFO_NR_DIRTY_THRESHOLD', - 'VMEMINFO_NR_DIRTY_BACKGROUND_THRESHOLD', - 'VMEMINFO_PGPGIN', - 'VMEMINFO_PGPGOUT', - 'VMEMINFO_PGPGOUTCLEAN', - 'VMEMINFO_PSWPIN', - 'VMEMINFO_PSWPOUT', - 'VMEMINFO_PGALLOC_DMA', - ]; - static VMEM_INFO_SECOND = [ - 'VMEMINFO_PGALLOC_NORMAL', - 'VMEMINFO_PGALLOC_MOVABLE', - 'VMEMINFO_PGFREE', - 'VMEMINFO_PGACTIVATE', - 'VMEMINFO_PGDEACTIVATE', - 'VMEMINFO_PGFAULT', - 'VMEMINFO_PGMAJFAULT', - 'VMEMINFO_PGREFILL_DMA', - 'VMEMINFO_PGREFILL_NORMAL', - 'VMEMINFO_PGREFILL_MOVABLE', - 'VMEMINFO_PGSTEAL_KSWAPD_DMA', - 'VMEMINFO_PGSTEAL_KSWAPD_NORMAL', - 'VMEMINFO_PGSTEAL_KSWAPD_MOVABLE', - 'VMEMINFO_PGSTEAL_DIRECT_DMA', - 'VMEMINFO_PGSTEAL_DIRECT_NORMAL', - 'VMEMINFO_PGSTEAL_DIRECT_MOVABLE', - 'VMEMINFO_PGSCAN_KSWAPD_DMA', - 'VMEMINFO_PGSCAN_KSWAPD_NORMAL', - 'VMEMINFO_PGSCAN_KSWAPD_MOVABLE', - 'VMEMINFO_PGSCAN_DIRECT_DMA', - 'VMEMINFO_PGSCAN_DIRECT_NORMAL', - 'VMEMINFO_PGSCAN_DIRECT_MOVABLE', - 'VMEMINFO_PGSCAN_DIRECT_THROTTLE', - 'VMEMINFO_PGINODESTEAL', - 'VMEMINFO_SLABS_SCANNED', - 'VMEMINFO_KSWAPD_INODESTEAL', - 'VMEMINFO_KSWAPD_LOW_WMARK_HIT_QUICKLY', - 'VMEMINFO_KSWAPD_HIGH_WMARK_HIT_QUICKLY', - 'VMEMINFO_PAGEOUTRUN', - 'VMEMINFO_ALLOCSTALL', - 'VMEMINFO_PGROTATED', - 'VMEMINFO_DROP_PAGECACHE', - 'VMEMINFO_DROP_SLAB', - 'VMEMINFO_PGMIGRATE_SUCCESS', - 'VMEMINFO_PGMIGRATE_FAIL', - 'VMEMINFO_COMPACT_MIGRATE_SCANNED', - 'VMEMINFO_COMPACT_FREE_SCANNED', - 'VMEMINFO_COMPACT_ISOLATED', - 'VMEMINFO_COMPACT_STALL', - 'VMEMINFO_COMPACT_FAIL', - 'VMEMINFO_COMPACT_SUCCESS', - 'VMEMINFO_COMPACT_DAEMON_WAKE', - 'VMEMINFO_UNEVICTABLE_PGS_CULLED', - 'VMEMINFO_UNEVICTABLE_PGS_SCANNED', - 'VMEMINFO_UNEVICTABLE_PGS_RESCUED', - 'VMEMINFO_UNEVICTABLE_PGS_MLOCKED', - 'VMEMINFO_UNEVICTABLE_PGS_MUNLOCKED', - ]; - static VMEM_INFO_THIRD = [ - 'VMEMINFO_UNEVICTABLE_PGS_CLEARED', - 'VMEMINFO_UNEVICTABLE_PGS_STRANDED', - 'VMEMINFO_NR_ZSPAGES', - 'VMEMINFO_NR_ION_HEAP', - 'VMEMINFO_NR_GPU_HEAP', - 'VMEMINFO_ALLOCSTALL_DMA', - 'VMEMINFO_ALLOCSTALL_MOVABLE', - 'VMEMINFO_ALLOCSTALL_NORMAL', - 'VMEMINFO_COMPACT_DAEMON_FREE_SCANNED', - 'VMEMINFO_COMPACT_DAEMON_MIGRATE_SCANNED', - 'VMEMINFO_NR_FASTRPC', - 'VMEMINFO_NR_INDIRECTLY_RECLAIMABLE', - 'VMEMINFO_NR_ION_HEAP_POOL', - 'VMEMINFO_NR_KERNEL_MISC_RECLAIMABLE', - 'VMEMINFO_NR_SHADOW_CALL_STACK_BYTES', - 'VMEMINFO_NR_SHMEM_HUGEPAGES', - 'VMEMINFO_NR_SHMEM_PMDMAPPED', - 'VMEMINFO_NR_UNRECLAIMABLE_PAGES', - 'VMEMINFO_NR_ZONE_ACTIVE_ANON', - 'VMEMINFO_NR_ZONE_ACTIVE_FILE', - 'VMEMINFO_NR_ZONE_INACTIVE_ANON', - 'VMEMINFO_NR_ZONE_INACTIVE_FILE', - 'VMEMINFO_NR_ZONE_UNEVICTABLE', - 'VMEMINFO_NR_ZONE_WRITE_PENDING', - 'VMEMINFO_OOM_KILL', - 'VMEMINFO_PGLAZYFREE', - 'VMEMINFO_PGLAZYFREED', - 'VMEMINFO_PGREFILL', - 'VMEMINFO_PGSCAN_DIRECT', - 'VMEMINFO_PGSCAN_KSWAPD', - 'VMEMINFO_PGSKIP_DMA', - 'VMEMINFO_PGSKIP_MOVABLE', - 'VMEMINFO_PGSKIP_NORMAL', - 'VMEMINFO_PGSTEAL_DIRECT', - 'VMEMINFO_PGSTEAL_KSWAPD', - 'VMEMINFO_SWAP_RA', - 'VMEMINFO_SWAP_RA_HIT', - 'VMEMINFO_WORKINGSET_RESTORE', - ]; - // sys.mem.total sys.mem.free sys.mem.buffers sys.mem.cached sys.mem.shmem sys.mem.slab sys.mem.swap.total - // sys.mem.swap.free sys.mem.mapped sys.mem.vmalloc.used sys.mem.page.tables sys.mem.kernel.stack - // sys.mem.active sys.mem.inactive sys.mem.unevictable sys.mem.vmalloc.total sys.mem.slab.unreclaimable - // sys.mem.cma.total sys.mem.cma.free - static ABALITY_MEM_INFO = [ - 'MEMINFO_MEM_TOTAL', - 'MEMINFO_MEM_FREE', - 'MEMINFO_BUFFERS', - 'MEMINFO_CACHED', - 'MEMINFO_SHMEM', - 'MEMINFO_SLAB', - 'MEMINFO_SWAP_TOTAL', - 'MEMINFO_SWAP_FREE', - 'MEMINFO_MAPPED', - 'MEMINFO_VMALLOC_USED', - 'MEMINFO_PAGE_TABLES', - 'MEMINFO_KERNEL_STACK', - 'MEMINFO_ACTIVE', - 'MEMINFO_INACTIVE', - 'MEMINFO_UNEVICTABLE', - 'MEMINFO_VMALLOC_TOTAL', - 'MEMINFO_SLAB_UNRECLAIMABLE', - 'MEMINFO_CMA_TOTAL', - 'MEMINFO_CMA_FREE', - 'MEMINFO_KERNEL_RECLAIMABLE', - 'PMEM_ACTIVE_PURG', - 'PMEM_INACTIVE_PURG', - 'PMEM_PINED_PURG', - ]; - - schedulingEvents = [ - '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', - ]; - powerEvents = [ - 'regulator/regulator_set_voltage', - 'regulator/regulator_set_voltage_complete', - 'power/clock_enable', - 'power/clock_disable', - 'power/clock_set_rate', - 'power/suspend_resume', - ]; - cpuFreqEvents = ['power/cpu_frequency', 'power/cpu_idle', 'power/suspend_resume']; - sysCallsEvents = ['raw_syscalls/sys_enter', 'raw_syscalls/sys_exit']; - highFrequencyEvents = [ - 'mm_event/mm_event_record', - 'kmem/rss_stat', - 'ion/ion_stat', - 'dmabuf_heap/dma_heap_stat', - 'kmem/ion_heap_grow', - 'kmem/ion_heap_shrink', - ]; - advancedConfigEvents = [ - 'sched/sched_switch', - 'sched/sched_wakeup', - 'sched/sched_wakeup_new', - 'sched/sched_waking', - 'sched/sched_process_exit', - 'sched/sched_process_free', - 'irq/irq_handler_entry', - 'irq/irq_handler_exit', - 'irq/softirq_entry', - 'irq/softirq_exit', - 'irq/softirq_raise', - 'power/clock_disable', - 'power/clock_enable', - 'power/clock_set_rate', - 'power/cpu_frequency', - 'power/cpu_idle', - 'clk/clk_disable', - 'clk/clk_disable_complete', - 'clk/clk_enable', - 'clk/clk_enable_complete', - 'clk/clk_set_rate', - 'clk/clk_set_rate_complete', - 'binder/binder_transaction', - 'binder/binder_transaction_alloc_buf', - 'binder/binder_transaction_received', - 'binder/binder_lock', - 'binder/binder_locked', - 'binder/binder_unlock', - 'workqueue/workqueue_execute_start', - 'workqueue/workqueue_execute_end', - 'oom/oom_score_adj_update', - 'ftrace/print', - ]; - private _menuItems: Array | undefined; - - public deviceSelect: HTMLSelectElement | undefined; - public deviceVersion: HTMLSelectElement | undefined; - private recordButtonText: HTMLSpanElement | undefined; - private devicePrompt: HTMLSpanElement | undefined; - private recordButton: LitButton | undefined; - private cancelButton: LitButton | undefined; - private sp: SpApplication | undefined; - private progressEL: LitProgressBar | undefined; - private litSearch: LitSearch | undefined; - private addButton: LitButton | undefined | null; - private disconnectButton: LitButton | undefined | null; - - private recordSetting: SpRecordSetting | undefined; - private probesConfig: SpProbesConfig | undefined; - private traceCommand: SpTraceCommand | undefined; - private spAllocations: SpAllocations | undefined; - private spRecordPerf: SpRecordPerf | undefined; - private spFileSystem: SpFileSystem | undefined; - private spSdkConfig: SpSdkConfig | undefined; - private spVmTracker: SpVmTracker | undefined; - private spHisysEvent: SpHisysEvent | undefined; - private spRecordTemplate: SpRecordTemplate | undefined; - private spArkTs: SpArkTs | undefined; - private spHilog: SpHilogRecord | undefined; - - private ftraceSlider: LitSlider | undefined | null; - - private spWebShell: SpWebHdcShell | undefined; - private menuGroup: LitMainMenuGroup | undefined | null; - private appContent: HTMLElement | undefined | null; - private record = 'Record'; - private stop = 'StopRecord'; - - compareArray(devs: Array): boolean { + private compareArray(devs: Array): boolean { let clearFlag: boolean = false; - if (devs.length != this.deviceSelect!.options.length) { + if (devs.length !== this.deviceSelect!.options.length) { clearFlag = true; } else { - let optionArray = new Array(); - for (let i = 0; i < this.deviceSelect!.options.length; i++) { - optionArray.push(this.deviceSelect!.options[i].value); + let optionArray: string[] = []; + for (let index = 0; index < this.deviceSelect!.options.length; index++) { + optionArray.push(this.deviceSelect!.options[index].value); } devs.forEach((value) => { - if (optionArray.indexOf(value) == -1) { + if (optionArray.indexOf(value) === -1) { clearFlag = true; } }); @@ -434,43 +153,14 @@ export class SpRecordTrace extends BaseElement { return clearFlag; } - refreshDeviceList(): void { + private refreshDeviceList(): void { if (this.vs) { - Cmd.execHdcCmd(CmdConstant.CMD_HDC_DEVICES, (res: string) => { - let devs: string[] = res.trim().replace(/\r\n/g, '\r').replace(/\n/g, '\r').split(/\r/); - if (devs.length == 1 && devs[0].indexOf('Empty') != -1) { - this.deviceSelect!.innerHTML = ''; - return; - } - let clearFlag = this.compareArray(devs); - if (clearFlag) { - this.deviceSelect!.innerHTML = ''; - if (devs.length == 0) { - this.recordButton!.hidden = true; - this.disconnectButton!.hidden = true; - this.devicePrompt!.innerText = 'Device not connected'; - } - for (let i = 0; i < devs.length; i++) { - let dev = devs[i]; - let option = document.createElement('option'); - option.className = 'select'; - option.textContent = dev; - this.deviceSelect!.appendChild(option); - if (i == 0) { - option.selected = true; - this.recordButton!.hidden = false; - this.disconnectButton!.hidden = false; - SpRecordTrace.serialNumber = option.value; - this.devicePrompt!.innerText = ''; - } - } - } - }); + this.refreshDeviceListByVs(); } else { this.deviceSelect!.innerHTML = ''; // @ts-ignore HdcDeviceManager.getDevices().then((devs: USBDevice[]) => { - if (devs.length == 0) { + if (devs.length === 0) { this.recordButton!.hidden = true; this.disconnectButton!.hidden = true; this.devicePrompt!.innerText = 'Device not connected'; @@ -484,57 +174,95 @@ export class SpRecordTrace extends BaseElement { } option.textContent = dev!.serialNumber ? dev!.serialNumber!.toString() : 'hdc Device'; this.deviceSelect!.appendChild(option); - if (len == 0) { + if (len === 0) { option.selected = true; this.recordButton!.hidden = false; this.disconnectButton!.hidden = false; this.devicePrompt!.innerText = ''; SpRecordTrace.serialNumber = option.value; - HdcDeviceManager.connect(option.value).then((result) => { - if (result) { - HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_VERSION, false).then((version) => { - SpRecordTrace.selectVersion = this.getDeviceVersion(version); - this.setDeviceVersionSelect(SpRecordTrace.selectVersion); - this.nativeMemoryHideBySelectVersion(); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - if (this.nowChildItem === this.spWebShell) { - window.publish(window.SmartEvent.UI.DeviceConnect, option.value); - } - }); - } else { - SpRecordTrace.selectVersion = SpRecordTrace.supportVersions[0]; - this.setDeviceVersionSelect(SpRecordTrace.selectVersion); - this.nativeMemoryHideBySelectVersion(); - let cmdTxt = PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - cmdTxt, - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - } - }); + this.refreshDeviceVersion(option); } } }); } } - getDeviceVersion(version: string): string { - if (version.indexOf('3.2') != -1) { + private refreshDeviceVersion(option: HTMLOptionElement): void { + HdcDeviceManager.connect(option.value).then((result) => { + if (result) { + HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_VERSION, false).then((version) => { + SpRecordTrace.selectVersion = this.getDeviceVersion(version); + this.setDeviceVersionSelect(SpRecordTrace.selectVersion); + this.nativeMemoryHideBySelectVersion(); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + if (this.nowChildItem === this.spWebShell) { + window.publish(window.SmartEvent.UI.DeviceConnect, option.value); + } + }); + } else { + SpRecordTrace.selectVersion = SpRecordTrace.supportVersions[0]; + this.setDeviceVersionSelect(SpRecordTrace.selectVersion); + this.nativeMemoryHideBySelectVersion(); + let cmdTxt = PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + cmdTxt, + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + } + }); + } + + private refreshDeviceListByVs(): void { + Cmd.execHdcCmd(CmdConstant.CMD_HDC_DEVICES, (res: string) => { + let devs: string[] = res.trim().replace(/\r\n/g, '\r').replace(/\n/g, '\r').split(/\r/); + if (devs.length === 1 && devs[0].indexOf('Empty') !== -1) { + this.deviceSelect!.innerHTML = ''; + return; + } + let clearFlag = this.compareArray(devs); + if (clearFlag) { + this.deviceSelect!.innerHTML = ''; + if (devs.length === 0) { + this.recordButton!.hidden = true; + this.disconnectButton!.hidden = true; + this.devicePrompt!.innerText = 'Device not connected'; + } + for (let i = 0; i < devs.length; i++) { + let dev = devs[i]; + let option = document.createElement('option'); + option.className = 'select'; + option.textContent = dev; + this.deviceSelect!.appendChild(option); + if (i === 0) { + option.selected = true; + this.recordButton!.hidden = false; + this.disconnectButton!.hidden = false; + SpRecordTrace.serialNumber = option.value; + this.devicePrompt!.innerText = ''; + } + } + } + }); + } + + private getDeviceVersion(version: string): string { + if (version.indexOf('3.2') !== -1) { return '3.2'; - } else if (version.indexOf('4.') != -1) { + } else if (version.indexOf('4.') !== -1) { return '4.0+'; } return '3.2'; } - freshMenuDisable(disable: boolean): void { + + private freshMenuDisable(disable: boolean): void { let mainMenu = this.sp!.shadowRoot?.querySelector('#main-menu') as LitMainMenu; - mainMenu.menus?.forEach((men) => { - men.children.forEach((child: any) => { + mainMenu.menus?.forEach((men): void => { + men.children.forEach((child: HTMLElement): void => { // @ts-ignore child.disabled = disable; }); @@ -542,7 +270,7 @@ export class SpRecordTrace extends BaseElement { mainMenu.menus = mainMenu.menus; } - refreshConfig(isTraceConfig: boolean) { + refreshConfig(isTraceConfig: boolean): void { let recordSettingEl = this.shadowRoot?.querySelector('record-setting') as SpRecordSetting; if (recordSettingEl) { if (isTraceConfig) { @@ -555,7 +283,7 @@ export class SpRecordTrace extends BaseElement { } } - refreshHint() { + refreshHint(): void { let flags = FlagsConfig.getAllFlagConfig(); let showHint = false; for (let i = 0; i < flags.length; i++) { @@ -577,15 +305,13 @@ export class SpRecordTrace extends BaseElement { return this.hasAttribute('show_hint'); } - private hintTimeOut: number = -1; - set showHint(bool: boolean) { if (bool) { if (this.hasAttribute('show_hint')) { this.removeAttribute('show_hint'); this.hintTimeOut = window.setTimeout(() => { this.setAttribute('show_hint', ''); - }, 200); + }, timeOut); } else { this.setAttribute('show_hint', ''); } @@ -598,154 +324,33 @@ export class SpRecordTrace extends BaseElement { } } - private refreshDeviceTimer: number | undefined; - private hintEl: HTMLSpanElement | undefined; - private selectedTemplate: Map = new Map(); - initElements(): void { let parentElement = this.parentNode as HTMLElement; if (parentElement) { parentElement.style.overflow = 'hidden'; } - this.recordSetting = new SpRecordSetting(); - this.probesConfig = new SpProbesConfig(); - this.traceCommand = new SpTraceCommand(); - this.spAllocations = new SpAllocations(); - this.spRecordPerf = new SpRecordPerf(); - this.spFileSystem = new SpFileSystem(); - this.spSdkConfig = new SpSdkConfig(); - 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.initConfigPage(); this.hintEl = this.shadowRoot?.querySelector('#hint') as HTMLSpanElement; - - this.addButton = this.shadowRoot?.querySelector('.add'); - this.addButton!.addEventListener('click', () => { - if (this.vs) { - this.refreshDeviceList(); - } else { - // @ts-ignore - HdcDeviceManager.findDevice().then((usbDevices) => { - log(usbDevices); - this.refreshDeviceList(); - }); - } - }); this.deviceSelect = this.shadowRoot?.querySelector('#device-select') as HTMLSelectElement; this.deviceVersion = this.shadowRoot?.querySelector('#device-version') as HTMLSelectElement; this.devicePrompt = this.shadowRoot?.querySelector('.prompt') as HTMLSpanElement; - this.deviceSelect?.addEventListener('mousedown', (evt) => { - if (this.deviceSelect!.options.length === 0) { - evt.preventDefault(); - } - }); - this.deviceSelect!.onchange = (): void => { - if (this.deviceSelect!.options.length > 0) { - this.recordButton!.hidden = false; - this.disconnectButton!.hidden = false; - this.devicePrompt!.innerText = ''; - } else { - this.recordButton!.hidden = true; - this.disconnectButton!.hidden = true; - this.devicePrompt!.innerText = 'Device not connected'; - } - let deviceItem = this.deviceSelect!.options[this.deviceSelect!.selectedIndex]; - let value = deviceItem.value; - SpRecordTrace.serialNumber = value; - if (this.vs) { - let cmd = Cmd.formatString(CmdConstant.CMD_GET_VERSION_DEVICES, [SpRecordTrace.serialNumber]); - Cmd.execHdcCmd(cmd, (deviceVersion: string) => { - this.selectedDevice(deviceVersion); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - }); - } else { - HdcDeviceManager.connect(value).then((result) => { - if (result) { - HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_VERSION, true).then((deviceVersion) => { - this.selectedDevice(deviceVersion); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - if (this.nowChildItem === this.spWebShell) { - window.publish(window.SmartEvent.UI.DeviceConnect, value); - } - }); - } else { - SpRecordTrace.selectVersion = SpRecordTrace.supportVersions[0]; - this.setDeviceVersionSelect(SpRecordTrace.selectVersion); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - } - }); - } - }; - this.deviceVersion.onchange = (): void => { - let versionItem = this.deviceVersion!.options[this.deviceVersion!.selectedIndex]; - SpRecordTrace.selectVersion = versionItem.getAttribute('device-version'); - this.spAllocations!.startup_mode = false; - this.nativeMemoryHideBySelectVersion(); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - }; - this.appendDeviceVersion(); - // @ts-ignore - if (navigator.usb) { - // @ts-ignore - navigator.usb.addEventListener( - 'disconnect', - // @ts-ignore - (ev: USBConnectionEvent) => { - this.usbDisConnectionListener(ev); - } - ); - } this.disconnectButton = this.shadowRoot?.querySelector('.disconnect'); - this.disconnectButton?.addEventListener('click', (evt) => { - let index = this.deviceSelect!.selectedIndex; - if (index != -1) { - let selectOption = this.deviceSelect!.options[index]; - let value = selectOption.value; - HdcDeviceManager.disConnect(value).then((re) => { - this.deviceSelect!.removeChild(selectOption); - if (this.nowChildItem === this.spWebShell) { - window.publish(window.SmartEvent.UI.DeviceDisConnect, value); - } - if (this.deviceSelect!.selectedIndex != -1) { - let item = this.deviceSelect!.options[this.deviceSelect!.selectedIndex]; - SpRecordTrace.serialNumber = item.value; - } else { - this.recordButton!.hidden = true; - this.disconnectButton!.hidden = true; - this.devicePrompt!.innerText = 'Device not connected'; - this.sp!.search = false; - SpRecordTrace.serialNumber = ''; - } - }); - } - }); - this.recordButton = this.shadowRoot?.querySelector('.record') as LitButton; this.recordButtonText = this.shadowRoot?.querySelector('.record_text') as HTMLSpanElement; this.cancelButton = this.shadowRoot?.querySelector('.cancel') as LitButton; this.sp = document.querySelector('sp-application') as SpApplication; this.progressEL = this.sp?.shadowRoot?.querySelector('.progress') as LitProgressBar; this.litSearch = this.sp?.shadowRoot?.querySelector('#lit-record-search') as LitSearch; - if (this.deviceSelect!.options && this.deviceSelect!.options.length > 0) { + this.menuGroup = this.shadowRoot?.querySelector('#menu-group') as LitMainMenuGroup; + this.addButton = this.shadowRoot?.querySelector('.add'); + if (this.record_template) { + this.buildTemplateTraceItem(); + } else { + this.buildNormalTraceItem(); + } + this.initMenuItems(); + this.appendDeviceVersion(); + if (this.deviceSelect?.options && this.deviceSelect?.options.length > 0) { this.disconnectButton!.hidden = false; this.recordButton!.hidden = false; this.devicePrompt!.innerText = ''; @@ -754,69 +359,225 @@ export class SpRecordTrace extends BaseElement { this.recordButton!.hidden = true; this.devicePrompt!.innerText = 'Device not connected'; } - this.recordButton!.addEventListener('mousedown', (event) => { - if (event.button === 0) { - if (this.recordButtonText!.textContent === this.record) { - this.recordButtonListener(); - } else { - this.stopRecordListener(); + } + + connectedCallback(): void { + super.connectedCallback(); + this.addButton!.addEventListener('click', this.addButtonClickEvent); + this.deviceSelect!.addEventListener('mousedown', this.deviceSelectMouseDownEvent); + this.deviceSelect!.addEventListener('change', this.deviceSelectChangeEvent); + this.deviceVersion!.addEventListener('change', this.deviceVersionChangeEvent); + this.disconnectButton?.addEventListener('click', this.disconnectButtonClickEvent); + this.recordButton?.addEventListener('mousedown', this.recordButtonMouseDownEvent); + this.cancelButton?.addEventListener('click', this.cancelRecordListener); + this.spRecordPerf?.addEventListener('addProbe', this.recordAddProbeEvent); + this.spAllocations?.addEventListener('addProbe', this.recordAddProbeEvent); + this.probesConfig?.addEventListener('addProbe', this.recordAddProbeEvent); + this.spRecordTemplate?.addEventListener('addProbe', this.recordTempAddProbe); + this.spRecordTemplate?.addEventListener('delProbe', this.recordTempDelProbe); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.addButton!.removeEventListener('click', this.addButtonClickEvent); + this.deviceSelect!.removeEventListener('mousedown', this.deviceSelectMouseDownEvent); + this.deviceSelect!.removeEventListener('change', this.deviceSelectChangeEvent); + this.deviceVersion!.removeEventListener('change', this.deviceVersionChangeEvent); + this.disconnectButton?.removeEventListener('click', this.disconnectButtonClickEvent); + this.recordButton?.removeEventListener('mousedown', this.recordButtonMouseDownEvent); + this.cancelButton?.removeEventListener('click', this.cancelRecordListener); + this.spRecordPerf?.removeEventListener('addProbe', this.recordAddProbeEvent); + this.spAllocations?.removeEventListener('addProbe', this.recordAddProbeEvent); + this.probesConfig?.removeEventListener('addProbe', this.recordAddProbeEvent); + this.spRecordTemplate?.removeEventListener('addProbe', this.recordTempAddProbe); + this.spRecordTemplate?.removeEventListener('delProbe', this.recordTempDelProbe); + } + + recordTempAddProbe = (ev: CustomEventInit<{ elementId: string }>): void => { + 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.cancelButton!.addEventListener('click', () => { - this.cancelRecordListener(); - }); - this.spRecordPerf!.addEventListener('addProbe', () => { - this.showHint = false; - }); - this.spAllocations!.addEventListener('addProbe', () => { - this.showHint = false; - }); - this.probesConfig!.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; - } - } + } + }; + + recordTempDelProbe = (ev: CustomEventInit<{ elementId: string }>): void => { + if ( + FlagsConfig.DEFAULT_CONFIG.find((flagItem): boolean => { + return flagItem.title === ev.detail!.elementId; + }) + ) { + this.selectedTemplate['delete'](ev.detail!.elementId); + if (this.selectedTemplate.size === 0) { + this.showHint = false; } - }); - 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; + } + }; + + recordAddProbeEvent = (): void => { + this.showHint = false; + }; + + addButtonClickEvent = (event: MouseEvent): void => { + if (this.vs) { + this.refreshDeviceList(); + } else { + // @ts-ignore + HdcDeviceManager.findDevice().then((usbDevices): void => { + log(usbDevices); + this.refreshDeviceList(); + }); + } + }; + + deviceSelectMouseDownEvent = (evt: MouseEvent): void => { + if (this.deviceSelect!.options.length === 0) { + evt.preventDefault(); + } + }; + + deviceSelectChangeEvent = (): void => { + if (this.deviceSelect!.options.length > 0) { + this.recordButton!.hidden = false; + this.disconnectButton!.hidden = false; + this.devicePrompt!.innerText = ''; + } else { + this.recordButton!.hidden = true; + this.disconnectButton!.hidden = true; + this.devicePrompt!.innerText = 'Device not connected'; + } + let deviceItem = this.deviceSelect!.options[this.deviceSelect!.selectedIndex]; + let value = deviceItem.value; + SpRecordTrace.serialNumber = value; + if (this.vs) { + let cmd = Cmd.formatString(CmdConstant.CMD_GET_VERSION_DEVICES, [SpRecordTrace.serialNumber]); + Cmd.execHdcCmd(cmd, (deviceVersion: string) => { + this.selectedDevice(deviceVersion); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + }); + } else { + HdcDeviceManager.connect(value).then((result): void => { + if (result) { + HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_VERSION, true).then((deviceVersion) => { + this.selectedDevice(deviceVersion); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + if (this.nowChildItem === this.spWebShell) { + window.publish(window.SmartEvent.UI.DeviceConnect, value); + } + }); + } else { + SpRecordTrace.selectVersion = SpRecordTrace.supportVersions[0]; + this.setDeviceVersionSelect(SpRecordTrace.selectVersion); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + } + }); + } + }; + + deviceVersionChangeEvent = (): void => { + let versionItem = this.deviceVersion!.options[this.deviceVersion!.selectedIndex]; + SpRecordTrace.selectVersion = versionItem.getAttribute('device-version'); + this.spAllocations!.startup_mode = false; + this.nativeMemoryHideBySelectVersion(); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + }; + + disconnectButtonClickEvent = (): void => { + let index = this.deviceSelect!.selectedIndex; + if (index !== -1) { + let selectOption = this.deviceSelect!.options[index]; + let value = selectOption.value; + HdcDeviceManager.disConnect(value).then((): void => { + this.deviceSelect!.removeChild(selectOption); + if (this.nowChildItem === this.spWebShell) { + window.publish(window.SmartEvent.UI.DeviceDisConnect, value); } + if (this.deviceSelect!.selectedIndex !== -1) { + let item = this.deviceSelect!.options[this.deviceSelect!.selectedIndex]; + SpRecordTrace.serialNumber = item.value; + } else { + this.recordButton!.hidden = true; + this.disconnectButton!.hidden = true; + this.devicePrompt!.innerText = 'Device not connected'; + this.sp!.search = false; + SpRecordTrace.serialNumber = ''; + } + }); + } + }; + + recordButtonMouseDownEvent = (event: MouseEvent): void => { + if (event.button === 0) { + if (this.recordButtonText!.textContent === this.record) { + this.recordButtonListener(); + } else { + this.stopRecordListener(); } - }); - this.menuGroup = this.shadowRoot?.querySelector('#menu-group') as LitMainMenuGroup; + } + }; + + private initConfigPage(): void { + this.recordSetting = new SpRecordSetting(); + this.probesConfig = new SpProbesConfig(); + this.traceCommand = new SpTraceCommand(); + this.spAllocations = new SpAllocations(); + this.spRecordPerf = new SpRecordPerf(); + this.spFileSystem = new SpFileSystem(); + this.spSdkConfig = new SpSdkConfig(); + this.spVmTracker = new SpVmTracker(); + this.spHiSysEvent = new SpHisysEvent(); + this.spArkTs = new SpArkTs(); + this.spHiLog = new SpHilogRecord(); + this.spWebShell = new SpWebHdcShell(); + this.spRecordTemplate = new SpRecordTemplate(this); this.appContent = this.shadowRoot?.querySelector('#app-content') as HTMLElement; if (this.record_template) { this.appContent.append(this.spRecordTemplate); } else { this.appContent.append(this.recordSetting); } - this.initMenuItems(); + // @ts-ignore + if (navigator.usb) { + // @ts-ignore + navigator.usb.addEventListener( + 'disconnect', + // @ts-ignore + (ev: USBConnectionEvent) => { + this.usbDisConnectionListener(ev); + } + ); + } } - private nativeMemoryHideBySelectVersion() { + private nativeMemoryHideBySelectVersion(): void { let divConfigs = this.spAllocations?.shadowRoot?.querySelectorAll('.version-controller'); if (divConfigs) { - if (SpRecordTrace.selectVersion != '3.2') { + if (SpRecordTrace.selectVersion !== '3.2') { for (let divConfig of divConfigs) { divConfig!.style.zIndex = '1'; } @@ -860,13 +621,15 @@ export class SpRecordTrace extends BaseElement { this.cancelButtonShow(false); if (this.vs) { let cmd = Cmd.formatString(CmdConstant.CMS_HDC_STOP, [SpRecordTrace.serialNumber]); - Cmd.execHdcCmd(cmd, (res: string) => {}); + Cmd.execHdcCmd(cmd, (): void => { + }); } else { let selectedOption = this.deviceSelect!.options[this.deviceSelect!.selectedIndex] as HTMLOptionElement; HdcDeviceManager.connect(selectedOption.value).then((result) => { if (result) { try { - HdcDeviceManager.shellResultAsString(CmdConstant.CMS_STOP, true).then((result) => {}); + HdcDeviceManager.shellResultAsString(CmdConstant.CMS_STOP, true).then((): void => { + }); } catch (exception) { this.recordButtonDisable(false); log(exception); @@ -876,12 +639,12 @@ export class SpRecordTrace extends BaseElement { } } - cancelRecordListener(): void { + cancelRecordListener = (): void => { this.recordButtonText!.textContent = this.record; this.cancelButtonShow(false); if (this.vs) { let cmd = Cmd.formatString(CmdConstant.CMS_HDC_CANCEL, [SpRecordTrace.serialNumber]); - Cmd.execHdcCmd(cmd, (res: string) => { + Cmd.execHdcCmd(cmd, () => { this.freshMenuDisable(false); this.freshConfigMenuDisable(false); this.progressEL!.loading = false; @@ -907,16 +670,17 @@ export class SpRecordTrace extends BaseElement { this.deviceSelect!.style.pointerEvents = 'auto'; this.deviceVersion!.style.pointerEvents = 'auto'; SpRecordTrace.cancelRecord = true; - HdcDeviceManager.stopHiprofiler(CmdConstant.CMS_CANCEL).then((result) => {}); + HdcDeviceManager.stopHiprofiler(CmdConstant.CMS_CANCEL).then((): void => { + }); } catch (exception) { log(exception); } } }); } - } + }; - private cancelButtonShow(show: boolean) { + private cancelButtonShow(show: boolean): void { if (show) { this.cancelButton!.style.visibility = 'visible'; } else { @@ -924,214 +688,19 @@ export class SpRecordTrace extends BaseElement { } } - private initMenuItems(): void { - let that = this; - if (this.record_template) { - this._menuItems = [ - { - title: 'Record setting', - icon: 'properties', - fileChoose: false, - clickHandler: function (event: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.recordSetting!); - that.freshMenuItemsStatus('Record setting'); - }, - }, - { - title: 'Trace template', - icon: 'realIntentionBulb', - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spRecordTemplate!); - that.freshMenuItemsStatus('Trace template'); - }, - }, - { - title: 'Trace command', - icon: 'dbsetbreakpoint', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.traceCommand!); - that.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(that.makeRequest(), false), - that.recordSetting!.output, - that.recordSetting!.maxDur - ); - that.freshMenuItemsStatus('Trace command'); - }, - }, - ]; - } else { - this._menuItems = [ - { - title: 'Record setting', - icon: 'properties', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.recordSetting!); - that.freshMenuItemsStatus('Record setting'); - }, - }, - { - title: 'Trace command', - icon: 'dbsetbreakpoint', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.freshMenuItemsStatus('Trace command'); - let request = that.makeRequest(); - that.appContent!.innerHTML = ''; - that.appContent!.append(that.traceCommand!); - that.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(request, false), - that.recordSetting!.output, - that.recordSetting!.maxDur - ); - }, - }, - { - title: 'Hdc Shell', - icon: 'file-config', - fileChoose: false, - clickHandler: function (ev: InputEvent) { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spWebShell!); - that.spWebShell!.shellDiv!.scrollTop = that.spWebShell!.currentScreenRemain; - setTimeout(() => { - that.spWebShell!.hdcShellFocus(); - }, 100); - that.nowChildItem = that.spWebShell!; - that.freshMenuItemsStatus('Hdc Shell'); - }, - }, - { - title: 'Probes config', - icon: 'realIntentionBulb', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.probesConfig!); - that.freshMenuItemsStatus('Probes config'); - }, - }, - { - title: 'Native Memory', - icon: 'externaltools', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - let startNativeSwitch = that.spAllocations?.shadowRoot?.getElementById('switch-disabled') as LitSwitch; - let recordModeSwitch = that.probesConfig?.shadowRoot?.querySelector('lit-switch') as LitSwitch; - let checkDesBoxDis = that.probesConfig?.shadowRoot?.querySelectorAll('check-des-box'); - let litCheckBoxDis = that.probesConfig?.shadowRoot?.querySelectorAll('lit-check-box'); - - that.ftraceSlider = that.probesConfig?.shadowRoot?.querySelector('#ftrace-buff-size-slider'); - startNativeSwitch.addEventListener('change', (event: any) => { - let detail = event.detail; - if (detail!.checked) { - recordModeSwitch.removeAttribute('checked'); - - checkDesBoxDis?.forEach((item: any) => { - item.setAttribute('disabled', ''); - item.checked = false; - }); - - litCheckBoxDis?.forEach((item: any) => { - item.setAttribute('disabled', ''); - item.checked = false; - }); - - that.ftraceSlider!.setAttribute('disabled', ''); - } - }); - - let divConfigs = that.spAllocations?.shadowRoot?.querySelectorAll('.version-controller'); - if ((!SpRecordTrace.selectVersion || SpRecordTrace.selectVersion === '3.2') && divConfigs) { - for (let divConfig of divConfigs) { - divConfig!.style.zIndex = '-1'; - } - } - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spAllocations!); - that.freshMenuItemsStatus('Native Memory'); - }, - }, - { - title: 'Hiperf', - icon: 'realIntentionBulb', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spRecordPerf!); - that.freshMenuItemsStatus('Hiperf'); - }, - }, - { - title: 'eBPF Config', - icon: 'file-config', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spFileSystem!); - that.spFileSystem!.setAttribute('long_trace', ''); - that.freshMenuItemsStatus('eBPF Config'); - }, - }, - { - title: 'VM Tracker', - icon: 'vm-tracker', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spVmTracker!); - that.freshMenuItemsStatus('VM Tracker'); - }, - }, - { - title: 'HiSystemEvent', - icon: 'externaltools', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spHisysEvent!); - that.freshMenuItemsStatus('HiSystemEvent'); - }, - }, - { - title: 'Ark Ts', - icon: 'file-config', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spArkTs!); - 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', - fileChoose: false, - clickHandler: function (ev: InputEvent): void { - that.appContent!.innerHTML = ''; - that.appContent!.append(that.spSdkConfig!); - that.freshMenuItemsStatus('SDK Config'); - }, - }, - ]; - } + private traceCommandClickHandler(recordTrace: SpRecordTrace): void { + recordTrace.appContent!.innerHTML = ''; + recordTrace.appContent!.append(recordTrace.traceCommand!); + recordTrace.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(recordTrace.makeRequest(), false), + recordTrace.recordSetting!.output, + recordTrace.recordSetting!.maxDur + ); + recordTrace.freshMenuItemsStatus('Trace command'); + } - this._menuItems?.forEach((item) => { + private initMenuItems(): void { + this._menuItems?.forEach((item): void => { let th = new LitMainMenuItem(); th.setAttribute('icon', item.icon || ''); th.setAttribute('title', item.title || ''); @@ -1141,7 +710,7 @@ export class SpRecordTrace extends BaseElement { th.style.lineHeight = '28px'; th.style.fontWeight = '700'; th.removeAttribute('file'); - th.addEventListener('click', (e) => { + th.addEventListener('click', (): void => { if (item.clickHandler) { item.clickHandler(item); } @@ -1150,39 +719,117 @@ export class SpRecordTrace extends BaseElement { }); } - // @ts-ignore - usbConnectionListener(event: USBConnectionEvent): void { - if (event.isTrusted) { - this.recordButton!.hidden = false; - this.disconnectButton!.hidden = false; - // @ts-ignore - let usbDevice: USBDevice = event.device; - let option = document.createElement('option'); - option.className = 'select'; - if (typeof usbDevice.serialNumber === 'string') { - option.value = usbDevice.serialNumber; + private recordCommandClickHandler(recordTrace: SpRecordTrace): void { + let request = recordTrace.makeRequest(); + recordTrace.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(request, false), + recordTrace.recordSetting!.output, + recordTrace.recordSetting!.maxDur + ); + } + + private hdcShellClickHandler(recordTrace: SpRecordTrace): void { + recordTrace.spWebShell!.shellDiv!.scrollTop = recordTrace.spWebShell!.currentScreenRemain; + setTimeout(() => { + recordTrace.spWebShell!.hdcShellFocus(); + }, 100); + recordTrace.nowChildItem = recordTrace.spWebShell!; + } + + private nativeMemoryClickHandler(recordTrace: SpRecordTrace): void { + let startNativeSwitch = recordTrace.spAllocations?.shadowRoot?.getElementById('switch-disabled') as LitSwitch; + let recordModeSwitch = recordTrace.probesConfig?.shadowRoot?.querySelector('lit-switch') as LitSwitch; + let checkDesBoxDis = recordTrace.probesConfig?.shadowRoot?.querySelectorAll('check-des-box'); + let litCheckBoxDis = recordTrace.probesConfig?.shadowRoot?.querySelectorAll('lit-check-box'); + recordTrace.ftraceSlider = recordTrace.probesConfig?.shadowRoot?. + querySelector('#ftrace-buff-size-slider'); + startNativeSwitch.addEventListener('change', (event: any): void => { + let detail = event.detail; + if (detail!.checked) { + recordModeSwitch.removeAttribute('checked'); + checkDesBoxDis?.forEach((item: any): void => { + item.setAttribute('disabled', ''); + item.checked = false; + }); + litCheckBoxDis?.forEach((item: any): void => { + item.setAttribute('disabled', ''); + item.checked = false; + }); + recordTrace.ftraceSlider!.setAttribute('disabled', ''); } - option.selected = true; - option.textContent = usbDevice!.serialNumber ? usbDevice!.serialNumber.replace(/"/g, '') : 'hdc Device'; - this.deviceSelect!.appendChild(option); - SpRecordTrace.serialNumber = option.value; - if (this.nowChildItem === this.spWebShell) { - window.publish(window.SmartEvent.UI.DeviceConnect, option.value); + }); + let divConfigs = recordTrace.spAllocations?.shadowRoot?.querySelectorAll('.version-controller'); + if ((!SpRecordTrace.selectVersion || SpRecordTrace.selectVersion === '3.2') && divConfigs) { + for (let divConfig of divConfigs) { + divConfig!.style.zIndex = '-1'; } } } + private eBPFConfigClickHandler(recordTrace: SpRecordTrace): void { + recordTrace.spFileSystem!.setAttribute('long_trace', ''); + } + + private buildMenuItem( + title: string, + icon: string, + configPage: BaseElement, + clickHandlerFun?: Function, + fileChoose: boolean = false + ): MenuItem { + let that = this; + return { + title: title, + icon: icon, + fileChoose: fileChoose, + clickHandler: (): void => { + that.appContent!.innerHTML = ''; + that.appContent!.append(configPage); + that.freshMenuItemsStatus(title); + if (clickHandlerFun) { + clickHandlerFun(that); + } + }, + }; + } + + private buildTemplateTraceItem(): void { + this._menuItems = [ + this.buildMenuItem('Record setting', 'properties', this.recordSetting!), + this.buildMenuItem('Trace template', 'realIntentionBulb', this.spRecordTemplate!), + this.buildMenuItem('Trace command', 'dbsetbreakpoint', this.spRecordTemplate!, this.traceCommandClickHandler), + ]; + } + + private buildNormalTraceItem(): void { + this._menuItems = [ + this.buildMenuItem('Record setting', 'properties', this.recordSetting!), + this.buildMenuItem('Trace command', 'dbsetbreakpoint', this.traceCommand!, this.recordCommandClickHandler), + this.buildMenuItem('Hdc Shell', 'file-config', this.spWebShell!, this.hdcShellClickHandler), + this.buildMenuItem('Probes config', 'realIntentionBulb', this.probesConfig!), + this.buildMenuItem('Native Memory', 'externaltools', this.spAllocations!, this.nativeMemoryClickHandler), + this.buildMenuItem('Hiperf', 'realIntentionBulb', this.spRecordPerf!), + this.buildMenuItem('eBPF Config', 'file-config', this.spFileSystem!, this.eBPFConfigClickHandler), + this.buildMenuItem('VM Tracker', 'vm-tracker', this.spVmTracker!), + this.buildMenuItem('HiSystemEvent', 'externaltools', this.spHiSysEvent!), + this.buildMenuItem('Ark Ts', 'file-config', this.spArkTs!), + this.buildMenuItem('Hilog', 'realIntentionBulb', this.spHiLog!), + this.buildMenuItem('SDK Config', 'file-config', this.spSdkConfig!) + ]; + } + // @ts-ignore usbDisConnectionListener(event: USBConnectionEvent): void { // @ts-ignore let disConnectDevice: USBDevice = event.device; for (let index = 0; index < this.deviceSelect!.children.length; index++) { let option = this.deviceSelect!.children[index] as HTMLOptionElement; - if (option.value == disConnectDevice.serialNumber) { + if (option.value === disConnectDevice.serialNumber) { let optValue = option.value; - HdcDeviceManager.disConnect(optValue).then(() => {}); + HdcDeviceManager.disConnect(optValue).then(() => { + }); this.deviceSelect!.removeChild(option); - if (SpRecordTrace.serialNumber == optValue) { + if (SpRecordTrace.serialNumber === optValue) { if (this.nowChildItem === this.spWebShell) { window.publish(window.SmartEvent.UI.DeviceDisConnect, optValue); } @@ -1201,16 +848,121 @@ export class SpRecordTrace extends BaseElement { } } + private vsCodeRecordCmd(traceCommandStr: string): void { + Cmd.execHdcCmd(Cmd.formatString(CmdConstant.CMS_HDC_STOP, [SpRecordTrace.serialNumber]), (stopRes: string) => { + let cmd = Cmd.formatString(CmdConstant.CMD_MOUNT_DEVICES, [SpRecordTrace.serialNumber]); + Cmd.execHdcCmd(cmd, (res: string) => { + this.sp!.search = true; + this.progressEL!.loading = true; + this.litSearch!.clear(); + this.litSearch!.setPercent(`tracing ${this.recordSetting!.maxDur * 1000}ms`, -1); + this.initRecordUIState(); + this.recordButtonText!.textContent = this.stop; + this.cancelButtonShow(true); + Cmd.execHdcTraceCmd(traceCommandStr, SpRecordTrace.serialNumber, (traceResult: string) => { + if (traceResult.indexOf('DestroySession done') != -1) { + this.litSearch!.setPercent('tracing htrace down', -1); + let cmd = Cmd.formatString(CmdConstant.CMD_FIEL_RECV_DEVICES, [ + SpRecordTrace.serialNumber, + this.recordSetting!.output, + ]); + Cmd.execFileRecv(cmd, this.recordSetting!.output, (rt: ArrayBuffer) => { + this.litSearch!.setPercent('downloading Hitrace file ', 101); + let fileName = this.recordSetting!.output.substring(this.recordSetting!.output.lastIndexOf('/') + 1); + let file = new File([rt], fileName); + let main = this!.parentNode!.parentNode!.querySelector('lit-main-menu') as LitMainMenu; + let children = main.menus as Array; + let child = children[0].children as Array; + let fileHandler = child[0].fileHandler; + if (fileHandler && !SpRecordTrace.cancelRecord) { + this.recordButtonText!.textContent = this.record; + this.cancelButtonShow(false); + this.freshMenuDisable(false); + this.freshConfigMenuDisable(false); + fileHandler({detail: file}); + } else { + SpRecordTrace.cancelRecord = false; + } + }); + } else { + this.litSearch!.setPercent('tracing htrace failed, please check your config ', -2); + this.recordButtonText!.textContent = this.record; + this.freshMenuDisable(false); + this.freshConfigMenuDisable(false); + this.progressEL!.loading = false; + } + this.buttonDisable(false); + }); + }); + }); + } + + private initRecordCmdStatus(): void { + this.appContent!.innerHTML = ''; + this.appContent!.append(this.traceCommand!); + let config = this.makeRequest(); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(config, false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + this.freshMenuItemsStatus('Trace command'); + } + + private webRecordCmd(traceCommandStr: string, selectedOption: HTMLOptionElement): void { + HdcDeviceManager.connect(selectedOption.value).then((result) => { + log(`result is ${result}`); + if (result) { + this.initRecordCmdStatus(); + try { + HdcDeviceManager.stopHiprofiler(CmdConstant.CMS_CANCEL).then(() => { + HdcDeviceManager.shellResultAsString(CmdConstant.CMD_MOUNT, true).then(() => { + this.sp!.search = true; + this.progressEL!.loading = true; + this.litSearch!.clear(); + this.litSearch!.setPercent(`tracing ${this.recordSetting!.maxDur * 1000}ms`, -1); + this.buttonDisable(true); + this.freshMenuDisable(true); + this.freshConfigMenuDisable(true); + if (SpApplication.isLongTrace) { + HdcDeviceManager.shellResultAsString( + CmdConstant.CMD_CLEAR_LONG_FOLD + this.recordSetting!.longOutPath, + false + ).then(() => { + HdcDeviceManager.shellResultAsString( + CmdConstant.CMD_MKDIR_LONG_FOLD + this.recordSetting!.longOutPath, + false + ).then(() => { + this.recordLongTraceCmd(traceCommandStr); + }); + }); + } else { + this.recordTraceCmd(traceCommandStr); + } + }); + }); + } catch (e) { + this.freshMenuDisable(false); + this.freshConfigMenuDisable(false); + this.buttonDisable(false); + } + } else { + this.sp!.search = true; + this.litSearch!.clear(); + this.litSearch!.setPercent('please kill other hdc-server !', -2); + } + }); + } + recordButtonListener(): void { 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.showHint = true; + this.showHint = true; + if (request.pluginConfigs.length === 0) { + this.hintEl!.textContent = 'It looks like you didn\'t add any probes. Please add at least one'; return; - } else { - this.showHint = false; } + this.showHint = false; let traceCommandStr = PluginConvertUtils.createHdcCmd( PluginConvertUtils.BeanToCmdTxt(request, false), this.recordSetting!.output, @@ -1228,142 +980,44 @@ export class SpRecordTrace extends BaseElement { }, }); let selectedOption = this.deviceSelect!.options[this.deviceSelect!.selectedIndex] as HTMLOptionElement; - if (selectedOption) { - SpRecordTrace.serialNumber = selectedOption.value; - } else { - this.sp!.search = true; - this.litSearch!.clear(); - this.progressEL!.loading = false; - this.litSearch!.setPercent('please connect device', -2); - } - - if (this.vs) { - this.appContent!.innerHTML = ''; - this.appContent!.append(this.traceCommand!); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - this.freshMenuItemsStatus('Trace command'); - Cmd.execHdcCmd(Cmd.formatString(CmdConstant.CMS_HDC_STOP, [SpRecordTrace.serialNumber]), (stopRes: string) => { - let cmd = Cmd.formatString(CmdConstant.CMD_MOUNT_DEVICES, [SpRecordTrace.serialNumber]); - Cmd.execHdcCmd(cmd, (res: string) => { - this.sp!.search = true; - this.progressEL!.loading = true; - this.litSearch!.clear(); - this.litSearch!.setPercent(`tracing ${this.recordSetting!.maxDur * 1000}ms`, -1); - this.initRecordUIState(); - this.recordButtonText!.textContent = this.stop; - this.cancelButtonShow(true); - Cmd.execHdcTraceCmd(traceCommandStr, SpRecordTrace.serialNumber, (traceResult: string) => { - if (traceResult.indexOf('DestroySession done') != -1) { - this.litSearch!.setPercent('tracing htrace down', -1); - let cmd = Cmd.formatString(CmdConstant.CMD_FIEL_RECV_DEVICES, [ - SpRecordTrace.serialNumber, - this.recordSetting!.output, - ]); - Cmd.execFileRecv(cmd, this.recordSetting!.output, (rt: ArrayBuffer) => { - this.litSearch!.setPercent('downloading Hitrace file ', 101); - let fileName = this.recordSetting!.output.substring(this.recordSetting!.output.lastIndexOf('/') + 1); - let file = new File([rt], fileName); - let main = this!.parentNode!.parentNode!.querySelector('lit-main-menu') as LitMainMenu; - let children = main.menus as Array; - let child = children[0].children as Array; - let fileHandler = child[0].fileHandler; - if (fileHandler && !SpRecordTrace.cancelRecord) { - this.recordButtonText!.textContent = this.record; - this.cancelButtonShow(false); - this.freshMenuDisable(false); - this.freshConfigMenuDisable(false); - fileHandler({ detail: file }); - } else { - SpRecordTrace.cancelRecord = false; - } - }); - } else { - this.litSearch!.setPercent('tracing htrace failed, please check your config ', -2); - this.recordButtonText!.textContent = this.record; - this.freshMenuDisable(false); - this.freshConfigMenuDisable(false); - this.progressEL!.loading = false; - } - this.buttonDisable(false); - }); - }); - }); - } else { - HdcDeviceManager.connect(selectedOption.value).then((result) => { - log(`result is ${result}`); - if (result) { - this.appContent!.innerHTML = ''; - this.appContent!.append(this.traceCommand!); - let config = this.makeRequest(); - this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( - PluginConvertUtils.BeanToCmdTxt(config, false), - this.recordSetting!.output, - this.recordSetting!.maxDur - ); - this.freshMenuItemsStatus('Trace command'); - try { - HdcDeviceManager.stopHiprofiler(CmdConstant.CMS_CANCEL).then(() => { - HdcDeviceManager.shellResultAsString(CmdConstant.CMD_MOUNT, true).then(() => { - this.sp!.search = true; - this.progressEL!.loading = true; - this.litSearch!.clear(); - this.litSearch!.setPercent(`tracing ${this.recordSetting!.maxDur * 1000}ms`, -1); - this.buttonDisable(true); - this.freshMenuDisable(true); - this.freshConfigMenuDisable(true); - if (SpApplication.isLongTrace) { - HdcDeviceManager.shellResultAsString( - CmdConstant.CMD_CLEAR_LONG_FOLD + this.recordSetting!.longOutPath, - false - ).then(() => { - HdcDeviceManager.shellResultAsString( - CmdConstant.CMD_MKDIR_LONG_FOLD + this.recordSetting!.longOutPath, - false - ).then(() => { - this.recordLongTraceCmd(traceCommandStr); - }); - }); - } else { - this.recordTraceCmd(traceCommandStr); - } - }); - }); - } catch (e) { - this.freshMenuDisable(false); - this.freshConfigMenuDisable(false); - this.buttonDisable(false); - } - } else { - this.sp!.search = true; - this.litSearch!.clear(); - this.litSearch!.setPercent('please kill other hdc-server !', -2); - } - }); + if (selectedOption) { + SpRecordTrace.serialNumber = selectedOption.value; + } else { + this.sp!.search = true; + this.litSearch!.clear(); + this.progressEL!.loading = false; + this.litSearch!.setPercent('please connect device', -2); + } + if (this.vs) { + this.appContent!.innerHTML = ''; + this.appContent!.append(this.traceCommand!); + this.traceCommand!.hdcCommon = PluginConvertUtils.createHdcCmd( + PluginConvertUtils.BeanToCmdTxt(this.makeRequest(), false), + this.recordSetting!.output, + this.recordSetting!.maxDur + ); + this.freshMenuItemsStatus('Trace command'); + this.vsCodeRecordCmd(traceCommandStr); + } else { + this.webRecordCmd(traceCommandStr, selectedOption); } } private recordTraceCmd(traceCommandStr: string): void { HdcDeviceManager.shellResultAsString(CmdConstant.CMD_SHELL + traceCommandStr, false).then((traceResult) => { let re = this.isSuccess(traceResult); - if (re == 0) { - this.litSearch!.setPercent('tracing htrace down', -1); + if (re === 0) { + this.litSearch!.setPercent('Tracing htrace down', -1); HdcDeviceManager.shellResultAsString(CmdConstant.CMD_TRACE_FILE_SIZE + this.recordSetting!.output, false).then( (traceFileSize) => { - this.litSearch!.setPercent(`traceFileSize is ${traceFileSize}`, -1); - if (traceFileSize.indexOf('No such') != -1) { - this.litSearch!.setPercent('No such file or directory', -2); - this.buttonDisable(false); - this.freshConfigMenuDisable(false); - this.freshMenuDisable(false); - } else if (Number(traceFileSize) <= SpRecordTrace.MaxFileSize) { + this.litSearch!.setPercent(`TraceFileSize is ${traceFileSize}`, -1); + if (traceFileSize.indexOf('No such') !== -1) { + this.refreshDisableStyle(false, true, 'No such file or directory', -2); + } else if (Number(traceFileSize) <= MaxFileSize) { HdcDeviceManager.fileRecv(this.recordSetting!.output, (perNumber: number) => { - this.litSearch!.setPercent('downloading Hitrace file ', perNumber); + this.litSearch!.setPercent('Downloading Hitrace file ', perNumber); }).then((pullRes) => { - this.litSearch!.setPercent('downloading Hitrace file ', 101); + this.litSearch!.setPercent('Downloading Hitrace file ', 101); pullRes.arrayBuffer().then((buffer) => { let fileName = this.recordSetting!.output.substring(this.recordSetting!.output.lastIndexOf('/') + 1); let file = new File([buffer], fileName); @@ -1372,10 +1026,7 @@ export class SpRecordTrace extends BaseElement { let child = children[0].children as Array; let fileHandler = child[0].fileHandler; if (fileHandler && !SpRecordTrace.cancelRecord) { - this.freshConfigMenuDisable(false); - this.freshMenuDisable(false); - this.buttonDisable(false); - this.recordButtonDisable(false); + this.refreshDisableStyle(false, false); fileHandler({ detail: file, }); @@ -1386,33 +1037,17 @@ 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); - this.freshMenuDisable(false); + this.refreshDisableStyle(false, true, 'Htrace file is too big', -2); } } ); - } 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); + } else if (re === 2) { + this.refreshDisableStyle(false, true, 'Stop tracing htrace ', -1); + } else if (re === -1) { + this.refreshDisableStyle(false, true, '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); - this.buttonDisable(false); + this.refreshDisableStyle(false, true, 'Tracing htrace failed, please check your config ', -2); } }); } @@ -1427,7 +1062,7 @@ export class SpRecordTrace extends BaseElement { false ).then((traceFileSize) => { this.litSearch!.setPercent(`traceFileSize is ${traceFileSize}`, -1); - if (traceFileSize.indexOf('No such') != -1) { + if (traceFileSize.indexOf('No such') !== -1) { this.litSearch!.setPercent('No such file or directory', -2); this.buttonDisable(false); this.freshConfigMenuDisable(false); @@ -1437,43 +1072,50 @@ 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); + this.refreshDisableStyle(false, true, 'stop tracing htrace ', -1); } else if (re === -1) { - this.recordButtonDisable(false); - this.litSearch!.setPercent('The device is abnormal', -2); + this.refreshDisableStyle(false, true, '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); - this.buttonDisable(false); + this.refreshDisableStyle(false, true, 'tracing htrace failed, please check your config ', -2); } }); } + private refreshDisableStyle( + disable: boolean, + isFreshSearch: boolean, + percentName?: string, + percentValue?: number + ): void { + if (isFreshSearch) { + this.litSearch!.setPercent(percentName, percentValue!); + } + this.recordButtonDisable(disable); + this.freshConfigMenuDisable(disable); + this.freshMenuDisable(disable); + this.buttonDisable(disable); + } + + private getLongTraceTypePage(): Array { + let traceTypePage: Array = []; + for (let fileIndex = 0; fileIndex < this.longTraceList.length; fileIndex++) { + let traceFileName = this.longTraceList[fileIndex]; + if (this.sp!.fileTypeList.some((fileType) => traceFileName.toLowerCase().includes(fileType))) { + continue; + } + let firstLastIndexOf = traceFileName.lastIndexOf('.'); + let firstText = traceFileName.slice(0, firstLastIndexOf); + let resultLastIndexOf = firstText.lastIndexOf('_'); + traceTypePage.push(Number(firstText.slice(resultLastIndexOf + 1, firstText.length)) - 1); + } + traceTypePage.sort((leftNum: number, rightNum: number) => leftNum - rightNum); + return traceTypePage; + } + private loadLongTraceFile(timStamp: number) { return new Promise(async (resolve) => { - let maxSize = 48 * 1024 * 1024; - let traceTypePage: Array = []; - for (let fileIndex = 0; fileIndex < this.longTraceList.length; fileIndex++) { - let traceFileName = this.longTraceList[fileIndex]; - if (this.sp!.fileTypeList.some((fileType) => traceFileName.toLowerCase().includes(fileType))) { - continue; - } - let firstLastIndexOf = traceFileName.lastIndexOf('.'); - let firstText = traceFileName.slice(0, firstLastIndexOf); - let resultLastIndexOf = firstText.lastIndexOf('_'); - traceTypePage.push(Number(firstText.slice(resultLastIndexOf + 1, firstText.length)) - 1); - } - traceTypePage.sort((leftNum: number, rightNum: number) => leftNum - rightNum); + let traceTypePage = this.getLongTraceTypePage(); for (let fileIndex = 0; fileIndex < this.longTraceList.length; fileIndex++) { if (this.longTraceList[fileIndex] !== '') { let types = this.sp!.fileTypeList.filter((type) => @@ -1500,7 +1142,7 @@ export class SpRecordTrace extends BaseElement { ); this.litSearch!.setPercent(`downloading ${fileType} file `, 101); let buffer = await pullRes.arrayBuffer(); - let chunks = Math.ceil(buffer.byteLength / maxSize); + let chunks = Math.ceil(buffer.byteLength / indexDBMaxSize); let offset = 0; let sliceLen = 0; let message = { @@ -1510,18 +1152,18 @@ export class SpRecordTrace extends BaseElement { size: 0, }; for (let chunkIndex = 0; chunkIndex < chunks; chunkIndex++) { - let start = chunkIndex * maxSize; - let end = Math.min(start + maxSize, buffer.byteLength); + let start = chunkIndex * indexDBMaxSize; + let end = Math.min(start + indexDBMaxSize, buffer.byteLength); let chunk = buffer.slice(start, end); if (chunkIndex === 0) { message.fileType = fileType; message.startIndex = chunkIndex; } - sliceLen = Math.min(buffer.byteLength - offset, maxSize); + sliceLen = Math.min(buffer.byteLength - offset, indexDBMaxSize); if (chunkIndex === 0 && fileType === 'trace') { this.sp!.longTraceHeadMessageList.push({ pageNum: pageNumber, - data: buffer.slice(offset, 1024), + data: buffer.slice(offset, kbSize), }); } this.sp!.longTraceDataList.push({ @@ -1545,18 +1187,7 @@ export class SpRecordTrace extends BaseElement { if (offset >= buffer.byteLength) { message.endIndex = chunkIndex; message.size = buffer.byteLength; - if (this.sp!.longTraceTypeMessageMap) { - if (this.sp!.longTraceTypeMessageMap?.has(pageNumber)) { - let oldTypeList = this.sp!.longTraceTypeMessageMap?.get(pageNumber); - oldTypeList?.push(message); - this.sp!.longTraceTypeMessageMap?.set(pageNumber, oldTypeList!); - } else { - this.sp!.longTraceTypeMessageMap?.set(pageNumber, [message]); - } - } else { - this.sp!.longTraceTypeMessageMap = new Map(); - this.sp!.longTraceTypeMessageMap.set(pageNumber, [message]); - } + this.longTraceFileMapHandler(pageNumber, message); } } } @@ -1565,6 +1196,26 @@ export class SpRecordTrace extends BaseElement { }); } + private longTraceFileMapHandler(pageNumber: number, message: { + fileType: string, + startIndex: number, + endIndex: number, + size: number, + }): void { + if (this.sp!.longTraceTypeMessageMap) { + if (this.sp!.longTraceTypeMessageMap?.has(pageNumber)) { + let oldTypeList = this.sp!.longTraceTypeMessageMap?.get(pageNumber); + oldTypeList?.push(message); + this.sp!.longTraceTypeMessageMap?.set(pageNumber, oldTypeList!); + } else { + this.sp!.longTraceTypeMessageMap?.set(pageNumber, [message]); + } + } else { + this.sp!.longTraceTypeMessageMap = new Map(); + this.sp!.longTraceTypeMessageMap.set(pageNumber, [message]); + } + } + private recordLongTrace(): void { let querySelector = this.sp!.shadowRoot?.querySelector('.long_trace_page') as HTMLDivElement; if (querySelector) { @@ -1612,13 +1263,13 @@ export class SpRecordTrace extends BaseElement { } private isSuccess(traceResult: string): number { - if (traceResult.indexOf('CreateSession FAIL') != -1 || traceResult.indexOf('failed') != -1) { + if (traceResult.indexOf('CreateSession FAIL') !== -1 || traceResult.indexOf('failed') !== -1) { return 1; - } else if (traceResult.indexOf('Signal') != -1) { + } else if (traceResult.indexOf('Signal') !== -1) { return 2; - } else if (traceResult.indexOf('signal(2)') != -1) { + } else if (traceResult.indexOf('signal(2)') !== -1) { return 0; - } else if (traceResult.indexOf('The device is abnormal') != -1) { + } else if (traceResult.indexOf('The device is abnormal') !== -1) { return -1; } else { return 0; @@ -1626,7 +1277,7 @@ export class SpRecordTrace extends BaseElement { } private makeRequest = (): CreateSessionRequest => { - let request = this.createSessionRequest(); + let request = createSessionRequest(this.recordSetting!); if (this.record_template) { let templateConfigs = this.spRecordTemplate?.getTemplateConfig(); templateConfigs?.forEach((config) => { @@ -1638,769 +1289,30 @@ export class SpRecordTrace extends BaseElement { request.sessionConfig!.splitFileMaxSizeMb = this.recordSetting!.longTraceSingleFileMaxSize; request.sessionConfig!.splitFileMaxNum = 20; } - let hasMonitorMemory = false; - let hasSamps = false; - if (this.probesConfig!.traceConfig.length > 0) { - if ( - this.probesConfig!.traceConfig.find((value) => { - return value != 'FPS'; - }) - ) { - request.pluginConfigs.push(this.createHtracePluginConfig()); - } - if (this.probesConfig!.traceConfig.indexOf('FPS') != -1) { - request.pluginConfigs.push(this.createFpsPluginConfig()); - } - } - if (this.probesConfig!.recordAbility) { - hasMonitorMemory = true; - this.createMonitorPlugin(this, request); - } - let reportingFrequency: number; - if (this.recordSetting!.maxDur > 20) { - reportingFrequency = 5; - } else { + let reportingFrequency: number = 5; + if (this.recordSetting!.maxDur <= 20) { reportingFrequency = 2; } - if (this.spVmTracker!.startSamp && this.spVmTracker!.process != '') { - hasSamps = true; - } - if (this.probesConfig!.memoryConfig.length > 0 || hasMonitorMemory || hasSamps) { - request.pluginConfigs.push( - this.createMemoryPluginConfig( - reportingFrequency, - this.probesConfig!.memoryConfig.length > 0, - hasMonitorMemory, - hasSamps - ) - ); - } - - if (this.spAllocations!.appProcess !== '' && this.spAllocations!.startSamp) { - request.pluginConfigs.push(this.createNativePluginConfig(reportingFrequency)); - } - if (this.spRecordPerf!.startSamp) { - request.pluginConfigs.push(this.createHiperConfig(reportingFrequency)); - } - if (this.spFileSystem!.startRecord) { - request.pluginConfigs.push(this.createSystemConfig()); - } - if (this.spSdkConfig!.startSamp && this.spSdkConfig!.getPlugName() != '') { - request.pluginConfigs.push(this.createSdkConfig()); - } - if (this.spHisysEvent?.startSamp) { - request.pluginConfigs.push( - this.createHiSystemEventPluginConfig(this.spHisysEvent.domain, this.spHisysEvent.eventName) - ); - } - if (this.spArkTs!.process != '' && this.spArkTs!.startSamp) { - request.pluginConfigs.push(this.createArkTsConfig()); - } - if (this.spHilog!.recordHilog) { - request.pluginConfigs.push(this.createHilogConfig(reportingFrequency)); - } + createHTracePluginConfig(this.probesConfig!, request); + createFpsPluginConfig(this.probesConfig!, request); + createMonitorPlugin(this.probesConfig!, request); + createMemoryPluginConfig(reportingFrequency, this.spVmTracker!, this.probesConfig!, request); + createNativePluginConfig(reportingFrequency, this.spAllocations!, SpRecordTrace.selectVersion, request); + createHiPerfConfig(reportingFrequency, this.spRecordPerf!, this.recordSetting!, request); + createSystemConfig(this.spFileSystem!, this.recordSetting!, request); + createSdkConfig(this.spSdkConfig!, request); + createHiSystemEventPluginConfig(this.spHiSysEvent!, request); + createArkTsConfig(this.spArkTs!, this.recordSetting!, request); + createHiLogConfig(reportingFrequency, this.spHiLog!, request); } return request; }; - private createSessionRequest(): CreateSessionRequest { - let bufferConfig: ProfilerSessionConfigBufferConfig = { - pages: this.recordSetting!.bufferSize * 256, - policy: ProfilerSessionConfigBufferConfigPolicy.RECYCLE, - }; - let sessionConfig: ProfilerSessionConfig = { - buffers: [bufferConfig], - sessionMode: ProfilerSessionConfigMode.OFFLINE, - resultMaxSize: 0, - keepAliveTime: 0, - }; - return { - requestId: 1, - sessionConfig: sessionConfig, - pluginConfigs: [], - }; - } - - private createMonitorPlugin(that: this, request: CreateSessionRequest): void { - let processPlugin = that.createProcessPlugin(); - let cpuPlugin = that.createCpuPlugin(); - let diskIoPlugin = that.createDiskIOPlugin(); - let netWorkPlugin = that.createNetworkPlugin(); - request.pluginConfigs.push(processPlugin); - request.pluginConfigs.push(cpuPlugin); - request.pluginConfigs.push(diskIoPlugin); - request.pluginConfigs.push(netWorkPlugin); - } - - private createNetworkPlugin(): ProfilerPluginConfig { - let netWorkConfig: NetworkConfig = {}; - let netWorkPlugin: ProfilerPluginConfig = { - pluginName: 'network-plugin', - sampleInterval: 1000, - configData: netWorkConfig, - }; - return netWorkPlugin; - } - - private createDiskIOPlugin(): ProfilerPluginConfig { - let diskIoConfig: DiskioConfig = { - reportIoStats: 'IO_REPORT', - }; - let diskIoPlugin: ProfilerPluginConfig = { - pluginName: 'diskio-plugin', - sampleInterval: 1000, - configData: diskIoConfig, - }; - return diskIoPlugin; - } - - private createCpuPlugin(): ProfilerPluginConfig { - let cpuConfig: CpuConfig = { - pid: 0, - reportProcessInfo: true, - }; - let cpuPlugin: ProfilerPluginConfig = { - pluginName: 'cpu-plugin', - sampleInterval: 1000, - configData: cpuConfig, - }; - return cpuPlugin; - } - - private createProcessPlugin(): ProfilerPluginConfig { - let processConfig: ProcessConfig = { - report_process_tree: true, - report_cpu: true, - report_diskio: true, - report_pss: true, - }; - let processPlugin: ProfilerPluginConfig = { - pluginName: 'process-plugin', - sampleInterval: 1000, - configData: processConfig, - }; - return processPlugin; - } - - createTraceEvents(traceConfig: Array): Array { - let traceEvents = new Set(); - traceConfig.forEach((config) => { - switch (config) { - case 'Scheduling details': - this.schedulingEvents.forEach((eve: string) => { - traceEvents.add(eve); - }); - break; - case 'CPU Frequency and idle states': - this.cpuFreqEvents.forEach((eve: string) => { - traceEvents.add(eve); - }); - break; - case 'High frequency memory': - this.highFrequencyEvents.forEach((eve: string) => { - traceEvents.add(eve); - }); - break; - case 'Advanced ftrace config': - this.advancedConfigEvents.forEach((eve: string) => { - traceEvents.add(eve); - }); - break; - case 'Syscalls': - this.sysCallsEvents.forEach((eve: string) => { - traceEvents.add(eve); - }); - break; - case 'Board voltages & frequency': - this.powerEvents.forEach((eve: string) => { - traceEvents.add(eve); - }); - break; - } - }); - let ftraceEventsArray: string[] = []; - info('traceEvents length is: ', traceEvents.size); - for (const ftraceEvent of traceEvents) { - ftraceEventsArray.push(ftraceEvent); - } - return ftraceEventsArray; - } - initHtml(): string { - return ` - -
-
-
- Target Platform: -
- - -
- - Add HDC Device -
- Disconnect - Record - Cancel -
-
-
- It looks like you didn't add any probes. Please add at least one -
-
- -
- -
-
-
-
- `; - } - - private createHilogConfig(reportingFrequency: number): ProfilerPluginConfig { - let appProcess = this.spHilog!.appProcess; - let re = /^[0-9]+.?[0-9]*/; - let pid = 0; - let processId = ''; - if (appProcess.indexOf('(') != -1) { - processId = appProcess.slice(appProcess.lastIndexOf('(') + 1, appProcess.lastIndexOf(')')); - } else { - processId = appProcess; - } - if (re.test(processId)) { - pid = Number(processId); - } - let hilogConfig: HilogConfig = { - pid: pid, - logLevel: levelFromJSON(this.spHilog!.appLogLevel), - needClear: true, - }; - let hilogConfigProfilerPluginConfig: ProfilerPluginConfig = { - pluginName: 'hilog-plugin', - sampleInterval: reportingFrequency * 1000, - configData: hilogConfig, - }; - return hilogConfigProfilerPluginConfig; - } - - private isNumber(str: string): boolean { - return !isNaN(Number(str)); - } - - private createHiperConfig(reportingFrequency: number): ProfilerPluginConfig { - let perfConfig = this.spRecordPerf!.getPerfConfig(); - let recordArgs = ''; - 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}`; - } else { - recordArgs = `${recordArgs} --app ${perfConfig?.process}`; - } - } else { - if (this.isNumber(process)) { - recordArgs = `${recordArgs} -p ${perfConfig?.process}`; - } else { - recordArgs = `${recordArgs} --app ${perfConfig?.process}`; - } - } - } else { - recordArgs = `${recordArgs} -a `; - } - if (perfConfig?.cpu && !perfConfig?.cpu.includes('ALL') && perfConfig?.cpu.length > 0) { - recordArgs = `${recordArgs} -c ${perfConfig?.cpu}`; - } - if (perfConfig?.cpuPercent != 0) { - recordArgs = `${recordArgs} --cpu-limit ${perfConfig?.cpuPercent}`; - } - if (perfConfig?.eventList && !perfConfig?.eventList.includes('NONE') && perfConfig?.eventList.length > 0) { - recordArgs = `${recordArgs} -e ${perfConfig?.eventList}`; - if (perfConfig?.isOffCpu) { - recordArgs = `${recordArgs},sched:sched_waking`; - } - } else { - recordArgs = `${recordArgs} -e hw-cpu-cycles`; - if (perfConfig?.isOffCpu) { - recordArgs = `${recordArgs},sched:sched_waking`; - } - } - if (perfConfig?.callStack != 'none') { - recordArgs = `${recordArgs} --call-stack ${perfConfig?.callStack}`; - } - - if (perfConfig?.branch != 'none') { - recordArgs = `${recordArgs} -j ${perfConfig?.branch}`; - } - - if (perfConfig?.clockType) { - recordArgs = `${recordArgs} --clockid ${perfConfig?.clockType}`; - } - - if (perfConfig?.isOffCpu) { - recordArgs = `${recordArgs} --offcpu`; - } - - if (perfConfig?.noInherit) { - recordArgs = `${recordArgs} --no-inherit`; - } - - if (perfConfig?.mmap) { - recordArgs = `${recordArgs} -m ${perfConfig.mmap}`; - } - info('record config Args is: ', recordArgs); - let hiPerf: HiperfPluginConfig = { - isRoot: false, - outfileName: '/data/local/tmp/perf.data', - recordArgs: recordArgs, - }; - if (SpApplication.isLongTrace) { - hiPerf.splitOutfileName = `${this.recordSetting!.longOutPath}hiprofiler_data_hiperf.htrace`; - } - let hiPerfPluginConfig: ProfilerPluginConfig = { - pluginName: 'hiperf-plugin', - sampleInterval: reportingFrequency * 1000, - configData: hiPerf, - }; - return hiPerfPluginConfig; - } - - private createSystemConfig(): ProfilerPluginConfig { - let systemConfig = this.spFileSystem!.getSystemConfig(); - let recordArgs = 'hiebpf'; - let recordEvent = []; - if (this.spFileSystem?.startFileSystem) { - recordEvent.push('fs'); - } - if (this.spFileSystem?.startVirtualMemory) { - recordEvent.push('ptrace'); - } - if (this.spFileSystem?.startIo) { - recordEvent.push('bio'); - } - if (recordEvent.length > 0) { - 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 += ` --max_stack_depth ${systemConfig?.unWindLevel}`; - let systemPluginConfig: HiebpfConfig = { - cmdLine: recordArgs, - outfileName: '/data/local/tmp/ebpf.data', - }; - if (SpApplication.isLongTrace) { - systemPluginConfig.splitOutfileName = `${this.recordSetting?.longOutPath}hiprofiler_data_ebpf.htrace`; - } - let ebpfPluginConfig: ProfilerPluginConfig = { - pluginName: 'hiebpf-plugin', - sampleInterval: 1000, - configData: systemPluginConfig, - }; - return ebpfPluginConfig; - } - - private createNativePluginConfig(reportingFrequency: number): ProfilerPluginConfig { - let appProcess = this.spAllocations!.appProcess; - let re = /^[0-9]+.?[0-9]*/; - let pid = 0; - let processName = ''; - let processId = ''; - if (this.spAllocations!.startup_mode && SpRecordTrace.selectVersion !== '3.2') { - processName = appProcess; - } else { - if (appProcess.indexOf('(') != -1) { - processId = appProcess.slice(appProcess.lastIndexOf('(') + 1, appProcess.lastIndexOf(')')); - } else { - processId = appProcess; - } - if (re.test(processId)) { - pid = Number(processId); - } else { - processName = appProcess; - } - } - let nativeConfig: NativeHookConfig; - if (this.spAllocations!.expandPids.length === 1) { - nativeConfig = { - pid: this.spAllocations!.expandPids[0], - saveFile: false, - fileName: '', - filterSize: this.spAllocations!.filter, - smbPages: this.spAllocations!.shared, - maxStackDepth: this.spAllocations!.unwind, - processName: processName, - stringCompressed: true, - fpUnwind: this.spAllocations!.fp_unwind, - blocked: true, - }; - } else { - nativeConfig = { - saveFile: false, - fileName: '', - filterSize: this.spAllocations!.filter, - smbPages: this.spAllocations!.shared, - maxStackDepth: this.spAllocations!.unwind, - processName: processName, - stringCompressed: true, - fpUnwind: this.spAllocations!.fp_unwind, - blocked: true, - }; - } - let maxProcessSize = 4; - if (SpRecordTrace.selectVersion !== undefined && SpRecordTrace.selectVersion !== '3.2') { - nativeConfig.callframeCompress = true; - nativeConfig.recordAccurately = this.spAllocations!.record_accurately; - nativeConfig.offlineSymbolization = this.spAllocations!.offline_symbolization; - if (this.spAllocations!.record_statistics) { - nativeConfig.statisticsInterval = this.spAllocations!.statistics_interval; - } - nativeConfig.startupMode = this.spAllocations!.startup_mode; - if (this.spAllocations!.response_lib_mode) { - nativeConfig.responseLibraryMode = this.spAllocations!.response_lib_mode; - maxProcessSize = 8; - } - if (this.spAllocations!.sample_interval) { - nativeConfig.sampleInterval = this.spAllocations!.sample_interval; - } - } - if (this.spAllocations!.expandPids.length > 1) { - nativeConfig.expandPids = this.spAllocations!.expandPids.splice(0, maxProcessSize); - } - let nativePluginConfig: ProfilerPluginConfig = { - pluginName: 'nativehook', - sampleInterval: reportingFrequency * 1000, - configData: nativeConfig, - }; - return nativePluginConfig; - } - - private createMemoryPluginConfig( - reportingFrequency: number, - hasmemoryConfig: boolean, - hasMonitorMemory: boolean, - hasSmaps: boolean - ): ProfilerPluginConfig { - let memoryconfig: MemoryConfig = { - reportProcessTree: false, - reportSysmemMemInfo: false, - sysMeminfoCounters: [], - reportSysmemVmemInfo: false, - sysVmeminfoCounters: [], - reportProcessMemInfo: false, - reportAppMemInfo: false, - reportAppMemByMemoryService: false, - pid: [], - }; - if (hasmemoryConfig || hasMonitorMemory) { - memoryconfig.reportProcessTree = true; - memoryconfig.reportSysmemMemInfo = true; - memoryconfig.reportSysmemVmemInfo = true; - memoryconfig.reportProcessMemInfo = true; - } - if (this.spVmTracker!.startSamp) { - memoryconfig.reportProcessMemInfo = true; - } - if (hasSmaps || hasMonitorMemory) { - memoryconfig.reportPurgeableAshmemInfo = true; - memoryconfig.reportDmaMemInfo = true; - memoryconfig.reportGpuMemInfo = true; - } - if (hasSmaps) { - memoryconfig.reportSmapsMemInfo = true; - memoryconfig.reportGpuDumpInfo = true; - let pid = Number(this.spVmTracker?.process); - memoryconfig.pid.push(pid); - } - if (hasMonitorMemory) { - SpRecordTrace.ABALITY_MEM_INFO.forEach((va) => { - memoryconfig.sysMeminfoCounters.push(sysMeminfoTypeFromJSON(va)); - }); - } - this.probesConfig!.memoryConfig.forEach((value) => { - if (value.indexOf('Kernel meminfo') != -1) { - if (hasMonitorMemory) { - memoryconfig.sysMeminfoCounters = []; - } - SpRecordTrace.MEM_INFO.forEach((va) => { - memoryconfig.sysMeminfoCounters.push(sysMeminfoTypeFromJSON(va)); - }); - } - if (value.indexOf('Virtual memory stats') != -1) { - SpRecordTrace.VMEM_INFO.forEach((me) => { - memoryconfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me)); - }); - SpRecordTrace.VMEM_INFO_SECOND.forEach((me) => { - memoryconfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me)); - }); - SpRecordTrace.VMEM_INFO_THIRD.forEach((me) => { - memoryconfig.sysVmeminfoCounters.push(sysVMeminfoTypeFromJSON(me)); - }); - } - }); - let profilerPluginConfig: ProfilerPluginConfig = { - pluginName: 'memory-plugin', - sampleInterval: reportingFrequency * 1000, - configData: memoryconfig, - }; - return profilerPluginConfig; + return SpRecordTraceHtml; } - private createArkTsConfig(): ProfilerPluginConfig { - let process = this.spArkTs!.process; - let re = /^[0-9]+.?[0-9]*/; - let pid = 0; - let processId = ''; - if (process.indexOf('(') != -1) { - processId = process.slice(process.lastIndexOf('(') + 1, process.lastIndexOf(')')); - } else { - processId = process; - } - if (re.test(processId)) { - pid = Number(processId); - } - let arkTSConfig: ArkTSConfig = { - pid: pid, - type: this.spArkTs!.radioBoxType, - interval: this.spArkTs!.intervalValue, - capture_numeric_value: this.spArkTs!.grabNumeric, - track_allocations: this.spArkTs!.grabAllocations, - enable_cpu_profiler: this.spArkTs!.grabCpuProfiler, - cpu_profiler_interval: this.spArkTs!.intervalCpuValue, - }; - if (SpApplication.isLongTrace) { - arkTSConfig.splitOutfileName = `${this.recordSetting?.longOutPath}hiprofiler_data_arkts.htrace`; - } - let arkTSPluginConfig: ProfilerPluginConfig = { - pluginName: 'arkts-plugin', - sampleInterval: 5000, - configData: arkTSConfig, - }; - - return arkTSPluginConfig; - } - - private createFpsPluginConfig(): ProfilerPluginConfig { - let fpsConfig: FpsConfig = { - reportFps: true, - }; - let fpsPlugin: ProfilerPluginConfig = { - pluginName: 'hidump-plugin', - sampleInterval: 1000, - configData: fpsConfig, - }; - return fpsPlugin; - } - - private createHiSystemEventPluginConfig( - domainName: string, - eventName: string - ): ProfilerPluginConfig { - let hiSystemEventConfig: HiSystemEventConfig = { - msg: 'hisysevent-plugin', - subscribe_domain: domainName, - subscribe_event: eventName, - }; - let hiSystemEventPlugin: ProfilerPluginConfig = { - pluginName: 'hisysevent-plugin', - configData: hiSystemEventConfig, - }; - return hiSystemEventPlugin; - } - - private createHtracePluginConfig(): ProfilerPluginConfig { - let tracePluginConfig: TracePluginConfig = { - ftraceEvents: this.createTraceEvents(this.probesConfig!.traceConfig), - hitraceCategories: [], - hitraceApps: [], - bufferSizeKb: this.probesConfig!.ftraceBufferSize, - flushIntervalMs: 1000, - flushThresholdKb: 4096, - parseKsyms: true, - clock: 'boot', - tracePeriodMs: 200, - rawDataPrefix: '', - traceDurationMs: 0, - debugOn: false, - }; - if (this.probesConfig!.traceEvents.length > 0) { - tracePluginConfig.hitraceCategories = this.probesConfig!.traceEvents; - } - let htraceProfilerPluginConfig: ProfilerPluginConfig = { - pluginName: 'ftrace-plugin', - sampleInterval: 1000, - configData: tracePluginConfig, - }; - return htraceProfilerPluginConfig; - } - - private createSdkConfig(): ProfilerPluginConfig<{}> { - let gpuConfig = this.spSdkConfig!.getGpuConfig(); - let gpuPluginConfig: ProfilerPluginConfig<{}> = { - pluginName: this.spSdkConfig!.getPlugName(), - sampleInterval: this.spSdkConfig!.getSampleInterval(), - configData: gpuConfig, - }; - return gpuPluginConfig; - } - - freshConfigMenuDisable(disable: boolean): void { + private freshConfigMenuDisable(disable: boolean): void { let querySelectors = this.shadowRoot?.querySelectorAll('lit-main-menu-item'); querySelectors!.forEach((item) => { if (item.title !== 'Hdc Shell') { @@ -2416,42 +1328,35 @@ export class SpRecordTrace extends BaseElement { public startRefreshDeviceList(): void { if (this.refreshDeviceTimer === undefined) { - this.refreshDeviceTimer = window.setInterval(() => { + this.refreshDeviceTimer = window.setInterval((): void => { this.refreshDeviceList(); }, 5000); } } - recordButtonDisable(disable: boolean): void { - if (disable) { - this.recordButton!.style.pointerEvents = 'none'; - } else { - this.recordButton!.style.pointerEvents = 'auto'; - } + private recordButtonDisable(disable: boolean): void { + this.recordButton!.style.pointerEvents = disable ? 'none' : 'auto'; } - buttonDisable(disable: boolean): void { + + private buttonDisable(disable: boolean): void { + let pointerEventValue = 'auto'; + this.recordButtonText!.textContent = this.record; if (disable) { - this.disconnectButton!.style.pointerEvents = 'none'; + pointerEventValue = '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'; - this.deviceVersion!.style.pointerEvents = 'auto'; } + this.cancelButtonShow(disable); + this.disconnectButton!.style.pointerEvents = pointerEventValue; + this.addButton!.style.pointerEvents = pointerEventValue; + this.deviceSelect!.style.pointerEvents = pointerEventValue; + this.deviceVersion!.style.pointerEvents = pointerEventValue; } - freshMenuItemsStatus(currentValue: string): void { + private freshMenuItemsStatus(currentValue: string): void { let litMainMenuGroup = this.shadowRoot?.querySelector('lit-main-menu-group'); let litMainMenuItemNodeListOf = litMainMenuGroup!.querySelectorAll('lit-main-menu-item'); litMainMenuItemNodeListOf.forEach((item) => { - item.back = item.title == currentValue; + item.back = item.title === currentValue; }); } @@ -2473,3 +1378,9 @@ export class SpRecordTrace extends BaseElement { } } } + +const kbSize = 1024; +const timeOut = 200; +const unitSize = 48; +const indexDBMaxSize = unitSize * kbSize * kbSize; +export const MaxFileSize: number = kbSize * kbSize * kbSize; diff --git a/ide/src/trace/component/SpSystemTrace.html.ts b/ide/src/trace/component/SpSystemTrace.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..3361b352f23f73308d881232d0b66890d7e038bc --- /dev/null +++ b/ide/src/trace/component/SpSystemTrace.html.ts @@ -0,0 +1,111 @@ +/* + * 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. + */ + +export const SpSystemTraceHtml = ` + +
+ + +
+ +
+
+
+
+ +
+ `; \ No newline at end of file diff --git a/ide/src/trace/component/SpSystemTrace.ts b/ide/src/trace/component/SpSystemTrace.ts index 57ef09b21683059114bd9ed9755537d47fd46c06..9de005ff127caf4949ffa380f2b16765c45cc247 100644 --- a/ide/src/trace/component/SpSystemTrace.ts +++ b/ide/src/trace/component/SpSystemTrace.ts @@ -17,15 +17,7 @@ import { BaseElement, element } from '../../base-ui/BaseElement'; import './trace/TimerShaftElement'; import './trace/base/TraceRow'; import { - queryBySelectAllocationOrReturn, - queryBySelectExecute, - queryEbpfSamplesCount, - querySceneSearchFunc, - querySearchFunc, threadPool, - queryCpuKeyPathData, - queryTaskPoolRelationData, - queryTaskPoolOtherRelationData, } from '../database/SqlLite'; import { RangeSelectStruct, TraceRow } from './trace/base/TraceRow'; import { TimerShaftElement } from './trace/TimerShaftElement'; @@ -54,18 +46,18 @@ import { Rect, } from '../database/ui-worker/ProcedureWorkerCommon'; import { SpChartManager } from './chart/SpChartManager'; -import { CpuStruct, WakeupBean } from '../database/ui-worker/ProcedureWorkerCPU'; +import { CpuStruct, WakeupBean } from '../database/ui-worker/cpu/ProcedureWorkerCPU'; import { ProcessStruct } from '../database/ui-worker/ProcedureWorkerProcess'; import { CpuFreqStruct } from '../database/ui-worker/ProcedureWorkerFreq'; -import { CpuFreqLimitsStruct } from '../database/ui-worker/ProcedureWorkerCpuFreqLimits'; +import { CpuFreqLimitsStruct } from '../database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits'; import { ThreadStruct } from '../database/ui-worker/ProcedureWorkerThread'; import { func, FuncStruct } from '../database/ui-worker/ProcedureWorkerFunc'; -import { CpuStateStruct } from '../database/ui-worker/ProcedureWorkerCpuState'; -import { HiPerfCpuStruct } from '../database/ui-worker/ProcedureWorkerHiPerfCPU'; -import { HiPerfProcessStruct } from '../database/ui-worker/ProcedureWorkerHiPerfProcess'; -import { HiPerfThreadStruct } from '../database/ui-worker/ProcedureWorkerHiPerfThread'; -import { HiPerfEventStruct } from '../database/ui-worker/ProcedureWorkerHiPerfEvent'; -import { HiPerfReportStruct } from '../database/ui-worker/ProcedureWorkerHiPerfReport'; +import { CpuStateStruct } from '../database/ui-worker/cpu/ProcedureWorkerCpuState'; +import { HiPerfCpuStruct } from '../database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU'; +import { HiPerfProcessStruct } from '../database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess'; +import { HiPerfThreadStruct } from '../database/ui-worker/hiperf/ProcedureWorkerHiPerfThread'; +import { HiPerfEventStruct } from '../database/ui-worker/hiperf/ProcedureWorkerHiPerfEvent'; +import { HiPerfReportStruct } from '../database/ui-worker/hiperf/ProcedureWorkerHiPerfReport'; import { FpsStruct } from '../database/ui-worker/ProcedureWorkerFPS'; import { CpuAbilityMonitorStruct } from '../database/ui-worker/ProcedureWorkerCpuAbility'; import { DiskAbilityMonitorStruct } from '../database/ui-worker/ProcedureWorkerDiskIoAbility'; @@ -106,12 +98,22 @@ import { TabPaneCounterSample } from './trace/sheet/cpu/TabPaneCounterSample'; import { LitSearch } from './trace/search/Search'; import { TabPaneFlag } from './trace/timer-shaft/TabPaneFlag'; import { LitTabpane } from '../../base-ui/tabs/lit-tabpane'; -import { HiPerfCallChartStruct } from '../database/ui-worker/ProcedureWorkerHiPerfCallChart'; +import { HiPerfCallChartStruct } from '../database/ui-worker/hiperf/ProcedureWorkerHiPerfCallChart'; import { InitAnalysis } from '../database/logic-worker/ProcedureLogicWorkerCommon'; import { searchCpuDataSender } from '../database/data-trafic/CpuDataSender'; import { type SpKeyboard } from '../component/SpKeyboard'; import { enableVSync, resetVSync } from './chart/VSync'; -import {QueryEnum} from "../database/data-trafic/QueryEnum"; +import {QueryEnum} from "../database/data-trafic/utils/QueryEnum"; +import {SpSystemTraceHtml} from "./SpSystemTrace.html"; +import {queryEbpfSamplesCount} from "../database/sql/Memory.sql"; +import {queryBySelectExecute} from "../database/sql/ProcessThread.sql"; +import { + querySceneSearchFunc, querySearchFunc, + queryTaskPoolOtherRelationData, + queryTaskPoolRelationData +} from "../database/sql/Func.sql"; +import {queryBySelectAllocationOrReturn} from "../database/sql/SqlLite.sql"; +import {queryCpuKeyPathData} from "../database/sql/Cpu.sql"; function dpr(): number { return window.devicePixelRatio || 1; @@ -344,8 +346,8 @@ export class SpSystemTrace extends BaseElement { rightStar?.addEventListener('click', () => { let wakeupLists = []; wakeupLists.push(CpuStruct.selectCpuStruct?.cpu); - for (let i = 0; i < SpSystemTrace.wakeupList.length; i++) { - wakeupLists.push(SpSystemTrace.wakeupList[i].cpu); + for (let wakeupBean of SpSystemTrace.wakeupList) { + wakeupLists.push(wakeupBean.cpu); } let wakeupCpuLists = Array.from(new Set(wakeupLists)).sort(); for (let i = 0; i < wakeupCpuLists.length; i++) { @@ -645,9 +647,7 @@ export class SpSystemTrace extends BaseElement { }); } }); - rows.forEach((it) => { - it.checkType = '2'; - }); + rows.forEach((it) => it.checkType = '2'); } else { this.queryAllTraceRow().forEach((row) => { row.checkType = '-1'; @@ -692,7 +692,6 @@ export class SpSystemTrace extends BaseElement { minFilterId: it.getAttribute('minFilterId'), cpu: it.getAttribute('cpu'), }); - // selection.cpuFreqLimitDatas.push(it.dataList!); } else if (it.rowType == TraceRow.ROW_TYPE_PROCESS) { this.pushPidToSelection(selection, it.rowId!); if (it.getAttribute('hasStartup') === 'true') { @@ -707,7 +706,6 @@ export class SpSystemTrace extends BaseElement { if (!it.expansion) { processChildRows = [...it.childrenList]; } - selection.processIds.push(parseInt(it.rowId!)); processChildRows.forEach((th) => { th.rangeSelect = true; th.checkType = '2'; @@ -1149,19 +1147,28 @@ export class SpSystemTrace extends BaseElement { Math.min(filterJank.ts!, rangeData!.startNS || 0) < filterJank.dur! + (rangeData!.endNS || 0) - (rangeData!.startNS || 0); if (it.name == 'Actual Timeline') { - selection.jankFramesData = []; - let jankDatas = it.dataListCache.filter((jankData: any) => { - return isIntersect(jankData, TraceRow.rangeSelectObject!); - }); - selection.jankFramesData.push(jankDatas); + if (it.rowParentId === 'frameTime') { + it.dataListCache.forEach((jankData: any) => { + if (isIntersect(jankData, TraceRow.rangeSelectObject!)) { + selection.jankFramesData.push(jankData); + } + }); + } else { + selection.jankFramesData.push(it.rowParentId); + } } else if (it.folder) { selection.jankFramesData = []; it.childrenList.forEach((child) => { if (child.rowType == TraceRow.ROW_TYPE_JANK && child.name == 'Actual Timeline') { - let jankDatas = child.dataListCache.filter((jankData: any) => { - return isIntersect(jankData, TraceRow.rangeSelectObject!); - }); - selection.jankFramesData.push(jankDatas); + if (it.rowParentId === 'frameTime') { + it.dataListCache.forEach((jankData: any) => { + if (isIntersect(jankData, TraceRow.rangeSelectObject!)) { + selection.jankFramesData.push(jankData); + } + }); + } else { + selection.jankFramesData.push(child.rowParentId); + } } }); } @@ -2091,6 +2098,12 @@ export class SpSystemTrace extends BaseElement { (SoStruct.selectSoStruct.startTs || 0) + (SoStruct.selectSoStruct.dur || 0), shiftKey ); + } else if (AllAppStartupStruct.selectStartupStruct) { + this.slicestime = this.timerShaftEL?.setSlicesMark( + AllAppStartupStruct.selectStartupStruct.startTs || 0, + (AllAppStartupStruct.selectStartupStruct.startTs || 0) + (AllAppStartupStruct.selectStartupStruct.dur || 0), + shiftKey + ); } else if (FrameAnimationStruct.selectFrameAnimationStruct) { this.timerShaftEL?.setSlicesMark( FrameAnimationStruct.selectFrameAnimationStruct.startTs || 0, @@ -2484,6 +2497,7 @@ export class SpSystemTrace extends BaseElement { JsCpuProfilerStruct.selectJsCpuProfilerStruct = undefined; SnapshotStruct.selectSnapshotStruct = undefined; HiPerfCallChartStruct.selectStruct = undefined; + AllAppStartupStruct.selectStartupStruct = undefined; } isWASDKeyPress() { @@ -2599,7 +2613,7 @@ export class SpSystemTrace extends BaseElement { ], [ TraceRow.ROW_TYPE_ALL_APPSTARTUPS, - () => AllAppStartupStruct.hoverStartupStruct !== null && AllAppStartupStruct.hoverStartupStruct !== undefined, + (): boolean => AllAppStartupStruct.hoverStartupStruct !== null && AllAppStartupStruct.hoverStartupStruct !== undefined, ], [TraceRow.ROW_TYPE_STATIC_INIT, () => SoStruct.hoverSoStruct !== null && SoStruct.hoverSoStruct !== undefined], [TraceRow.ROW_TYPE_JANK, () => JankStruct.hoverJankStruct !== null && JankStruct.hoverJankStruct !== undefined], @@ -2827,7 +2841,6 @@ export class SpSystemTrace extends BaseElement { let endParentRow = this.shadowRoot?.querySelector>( `trace-row[row-id='${data.pid}'][folder]` ); - //this.drawThreadLine(endParentRow, ThreadStruct.selectThreadStruct, data); }); } ); @@ -3291,8 +3304,7 @@ export class SpSystemTrace extends BaseElement { ); if (!selectRow) { let collectList = this.favoriteChartListEL!.getAllCollectRows(); - for (let index = 0; index < collectList.length; index++) { - let selectCollectRow = collectList[index]; + for (let selectCollectRow of collectList) { if (selectCollectRow.rowId === allocationRowId.toString() && selectCollectRow.rowType === 'func') { selectRow = selectCollectRow; break; @@ -3527,8 +3539,7 @@ export class SpSystemTrace extends BaseElement { ); } if (!startRow) { - for (let index = 0; index < collectList.length; index++) { - let collectChart = collectList[index]; + for (let collectChart of collectList) { if (collectChart.rowId === selectRowId && collectChart.rowType === 'janks') { startRow = collectChart; break; @@ -3720,13 +3731,59 @@ export class SpSystemTrace extends BaseElement { } drawThreadLine(endParentRow: any, selectThreadStruct: ThreadStruct | undefined, data: any) { - let collectList = this.favoriteChartListEL!.getCollectRows(); - let startRow: any; - if (selectThreadStruct == undefined || selectThreadStruct == null) { + const collectList = this.favoriteChartListEL!.getCollectRows(); + if (!selectThreadStruct) { return; } - let selectRowId = selectThreadStruct?.tid; - startRow = this.shadowRoot?.querySelector>( + const selectRowId = selectThreadStruct?.tid; + let startRow = this.getStartRow(selectRowId, collectList); + if (!endParentRow) { + return; + } + let endRowStruct: any = this.shadowRoot?.querySelector>( + `trace-row[row-id='${data.tid}'][row-type='thread']` + ); + if (!endRowStruct) { + endRowStruct = endParentRow.childrenList.find((item: TraceRow) => { + return item.rowId === `${data.tid}` && item.rowType === 'thread'; + }); + } + if (endRowStruct) { + let findJankEntry = endRowStruct!.dataListCache!.find((dat: any) => dat.startTime == data.startTime && dat.dur! > 0); + let ts: number = 0; + if (findJankEntry) { + ts = selectThreadStruct.startTime! + selectThreadStruct.dur! / 2; + const [startY, startRowEl, startOffSetY] = this.calculateStartY(startRow, selectThreadStruct); + const [endY, endRowEl, endOffSetY] = this.calculateEndY(endParentRow, endRowStruct); + this.addPointPair( + this.makePoint( + ns2xByTimeShaft(ts, this.timerShaftEL!), + ts, + startY, + startRowEl!, + startOffSetY, + 'thread', + LineType.straightLine, + selectThreadStruct.startTime == ts + ), + this.makePoint( + ns2xByTimeShaft(findJankEntry.startTime!, this.timerShaftEL!), + findJankEntry.startTime!, + endY, + endRowEl, + endOffSetY, + 'thread', + LineType.straightLine, + true + ) + ); + this.refreshCanvas(true); + } + } + } + + getStartRow(selectRowId: number | undefined, collectList: any[]): any { + let startRow = this.shadowRoot?.querySelector>( `trace-row[row-id='${selectRowId}'][row-type='thread']` ); if (!startRow) { @@ -3738,91 +3795,46 @@ export class SpSystemTrace extends BaseElement { } } } - function collectionHasThread(threadRow: any): boolean { - for (let item of collectList!) { - if (item.rowId === threadRow.rowId && item.rowType === threadRow.rowType) { - return false; - } - } - return true; - } + return startRow; + } - if (endParentRow) { - //终点的父泳道过滤出选中的Struct - let endRowStruct: any; - //泳道展开的情况,查找endRowStruct - endRowStruct = this.shadowRoot?.querySelector>( - `trace-row[row-id='${data.tid}'][row-type='thread']` - ); - //泳道未展开的情况,查找endRowStruct - if (!endRowStruct) { - endRowStruct = endParentRow.childrenList.find((item: TraceRow) => { - return item.rowId === `${data.tid}` && item.rowType === 'thread'; - }); - } - if (endRowStruct) { - let findJankEntry = endRowStruct!.dataListCache!.find( - (dat: any) => dat.startTime == data.startTime && dat.dur! > 0 - ); - //连线规则 - let ts: number = 0; - if (findJankEntry) { - ts = selectThreadStruct.startTime! + selectThreadStruct.dur! / 2; - let startParentRow: any; - // startRow为子泳道,子泳道不存在,使用父泳道 - if (startRow) { - startParentRow = this.shadowRoot?.querySelector>( - `trace-row[row-id='${startRow.rowParentId}'][folder]` - ); - } else { - startRow = this.shadowRoot?.querySelector>( - `trace-row[row-id='${selectThreadStruct?.pid}'][folder]` - ); - } - let endY = endRowStruct!.translateY!; - let endRowEl = endRowStruct; - let endOffSetY = 20 * 0.5; - let expansionFlag = collectionHasThread(endRowStruct); - if (!endParentRow.expansion && expansionFlag) { - endY = endParentRow!.translateY!; - endRowEl = endParentRow; - endOffSetY = 10 * 0.5; - } - let startY = startRow!.translateY!; - let startRowEl = startRow; - let startOffSetY = 20 * 0.5; - expansionFlag = collectionHasThread(startRow); - if (startParentRow && !startParentRow.expansion && expansionFlag) { - startY = startParentRow!.translateY!; - startRowEl = startParentRow; - startOffSetY = 10 * 0.5; - } - this.addPointPair( - this.makePoint( - ns2xByTimeShaft(ts, this.timerShaftEL!), - ts, - startY, - startRowEl!, - startOffSetY, - 'thread', - LineType.StraightLine, - selectThreadStruct.startTime == ts - ), - this.makePoint( - ns2xByTimeShaft(findJankEntry.startTime!, this.timerShaftEL!), - findJankEntry.startTime!, - endY, - endRowEl, - endOffSetY, - 'thread', - LineType.StraightLine, - true - ) - ); - this.refreshCanvas(true); - } + calculateStartY(startRow: any, selectThreadStruct: ThreadStruct): [number, any, number] { + let startY = startRow!.translateY!; + let startRowEl = startRow; + let startOffSetY = 20 * 0.5; + const startParentRow = this.shadowRoot?.querySelector>( + `trace-row[row-id='${startRow.rowParentId}'][folder]` + );; + const expansionFlag = this.collectionHasThread(startRow); + if (startParentRow && !startParentRow.expansion && expansionFlag) { + startY = startParentRow.translateY!; + startRowEl = startParentRow; + startOffSetY = 10 * 0.5; + } + return [startY, startRowEl, startOffSetY]; + } + + calculateEndY(endParentRow: any, endRowStruct: any): [number, any, number] { + let endY = endRowStruct.translateY!; + let endRowEl = endRowStruct; + let endOffSetY = 20 * 0.5; + const expansionFlag = this.collectionHasThread(endRowStruct); + if (!endParentRow.expansion && expansionFlag) { + endY = endParentRow.translateY!; + endRowEl = endParentRow; + endOffSetY = 10 * 0.5; + } + return [endY, endRowEl, endOffSetY]; + } + + collectionHasThread(threadRow: any): boolean { + const collectList = this.favoriteChartListEL!.getCollectRows(); + for (let item of collectList!) { + if (item.rowId === threadRow.rowId && item.rowType === threadRow.rowType) { + return false; } } + return true; } translateByMouseMove(ev: MouseEvent): void { @@ -4758,101 +4770,6 @@ export class SpSystemTrace extends BaseElement { } initHtml(): string { - return ` - -
- - -
- -
-
-
-
- -
- `; + return SpSystemTraceHtml; } } diff --git a/ide/src/trace/component/chart/PerfDataQuery.ts b/ide/src/trace/component/chart/PerfDataQuery.ts index 929a5e6466790d5b46eac4c3c0e147871b1bacf3..c7090f7d55f9034d373073935b8bae9d1db5dc3e 100644 --- a/ide/src/trace/component/chart/PerfDataQuery.ts +++ b/ide/src/trace/component/chart/PerfDataQuery.ts @@ -13,12 +13,12 @@ * limitations under the License. */ -import { queryPerfFiles, queryPerfCallChainName } from '../../database/SqlLite'; import { PerfCall, PerfFile } from '../../bean/PerfProfile'; import { info } from '../../../log/Log'; import { SpHiPerf } from './SpHiPerf'; import { procedurePool } from '../../database/Procedure'; import { SpSystemTrace } from '../SpSystemTrace'; +import {queryPerfFiles} from "../../database/sql/Perf.sql"; export class PerfDataQuery { filesData: any = {}; diff --git a/ide/src/trace/component/chart/SpAbilityMonitorChart.ts b/ide/src/trace/component/chart/SpAbilityMonitorChart.ts index 17c35034cee255024f0ac222c7e7a6bdd2e5cbd3..4b1e556f352a846c80d056fb55baf73e6e7633e5 100644 --- a/ide/src/trace/component/chart/SpAbilityMonitorChart.ts +++ b/ide/src/trace/component/chart/SpAbilityMonitorChart.ts @@ -14,20 +14,10 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - queryAbilityExits, - queryCPuAbilityMaxData, - queryDiskIoMaxData, - queryDmaAbilityData, - queryGpuMemoryAbilityData, - queryMemoryMaxData, - queryNetWorkMaxData, - queryPurgeableSysData, -} from '../../database/SqlLite'; import { info } from '../../../log/Log'; import { TraceRow } from '../trace/base/TraceRow'; import { Utils } from '../trace/base/Utils'; -import { type EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { type EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { type ProcessStruct } from '../../database/ui-worker/ProcedureWorkerProcess'; import { CpuAbilityMonitorStruct, CpuAbilityRender } from '../../database/ui-worker/ProcedureWorkerCpuAbility'; import { MemoryAbilityMonitorStruct, MemoryAbilityRender } from '../../database/ui-worker/ProcedureWorkerMemoryAbility'; @@ -50,7 +40,9 @@ import { abilityPurgeableDataSender, } from '../../database/data-trafic/VmTrackerDataSender'; import { MemoryConfig } from '../../bean/MemoryConfig'; -import { resetAbility } from '../../database/data-trafic/VmTrackerDataReceiver'; +import {queryMemoryMaxData} from "../../database/sql/Memory.sql"; +import {queryDiskIoMaxData, queryNetWorkMaxData} from "../../database/sql/SqlLite.sql"; +import {queryAbilityExits, queryCPuAbilityMaxData, queryPurgeableSysData} from "../../database/sql/Ability.sql"; export class SpAbilityMonitorChart { private trace: SpSystemTrace; constructor(trace: SpSystemTrace) { @@ -98,7 +90,6 @@ export class SpAbilityMonitorChart { if (this.hasTable(result, 'trace_network')) { await this.initNetworkAbility(processRow); } - resetAbility(); // 初始化PurgeableToTal和PurgeablePin泳道图 let totalDataList = await queryPurgeableSysData(false); let pinDataList = await queryPurgeableSysData(true); @@ -189,14 +180,7 @@ export class SpAbilityMonitorChart { traceRow.name = `CPU ${cpuNameList[0]} Load`; traceRow.supplierFrame = (): Promise => cpuAbilityUserDataSender(traceRow, 'CpuAbilityMonitorData').then((res): CpuAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); traceRow.focusHandler = (ev): void => { @@ -240,14 +224,7 @@ export class SpAbilityMonitorChart { userTraceRow.name = `CPU ${cpuNameList[1]} Load`; userTraceRow.supplierFrame = (): Promise => cpuAbilityUserDataSender(userTraceRow, 'CpuAbilityUserData').then((res): CpuAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); userTraceRow.focusHandler = (ev): void => { @@ -295,14 +272,7 @@ export class SpAbilityMonitorChart { sysTraceRow.name = `CPU ${cpuNameList[2]} Load`; sysTraceRow.supplierFrame = (): Promise => cpuAbilityUserDataSender(sysTraceRow, 'CpuAbilitySystemData').then((res): CpuAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); sysTraceRow.focusHandler = (ev): void => { @@ -363,14 +333,7 @@ export class SpAbilityMonitorChart { memoryUsedTraceRow.supplierFrame = (): Promise => { return abilityMemoryUsedDataSender(memoryTotalId, memoryUsedTraceRow).then( (res): MemoryAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -423,14 +386,7 @@ export class SpAbilityMonitorChart { cachedFilesTraceRow.name = memoryNameList[1]; cachedFilesTraceRow.supplierFrame = (): Promise => abilityMemoryUsedDataSender(cachedId, cachedFilesTraceRow).then((res): MemoryAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); cachedFilesTraceRow.focusHandler = (ev): void => { @@ -481,14 +437,7 @@ export class SpAbilityMonitorChart { compressedTraceRow.name = memoryNameList[2]; compressedTraceRow.supplierFrame = (): Promise => abilityMemoryUsedDataSender(swapId, compressedTraceRow).then((res): MemoryAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); compressedTraceRow.focusHandler = (ev): void => { @@ -545,14 +494,7 @@ export class SpAbilityMonitorChart { bytesReadTraceRow.name = 'Disk ' + diskIONameList[0]; bytesReadTraceRow.supplierFrame = (): Promise => abilityBytesReadDataSender(bytesReadTraceRow, 'AbilityBytesReadData').then((res): DiskAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); bytesReadTraceRow.focusHandler = (ev): void => { @@ -602,14 +544,7 @@ export class SpAbilityMonitorChart { bytesWrittenTraceRow.supplierFrame = (): Promise => abilityBytesReadDataSender(bytesWrittenTraceRow, 'AbilityBytesWrittenData').then( (res): DiskAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -659,14 +594,7 @@ export class SpAbilityMonitorChart { readOpsTraceRow.name = 'Disk ' + diskIONameList[2]; readOpsTraceRow.supplierFrame = (): Promise => abilityBytesReadDataSender(readOpsTraceRow, 'AbilityReadOpsData').then((res): DiskAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; }); readOpsTraceRow.focusHandler = (ev): void => { @@ -716,14 +644,7 @@ export class SpAbilityMonitorChart { writtenOpsTraceRow.supplierFrame = (): Promise => abilityBytesReadDataSender(writtenOpsTraceRow, 'AbilityWrittenOpsData').then( (res): DiskAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -782,14 +703,7 @@ export class SpAbilityMonitorChart { bytesInTraceRow.supplierFrame = (): Promise => abilityBytesInTraceDataSender(bytesInTraceRow, 'AbilityBytesInTraceData').then( (res): NetworkAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -840,14 +754,7 @@ export class SpAbilityMonitorChart { bytesOutTraceRow.supplierFrame = (): Promise => abilityBytesInTraceDataSender(bytesOutTraceRow, 'AbilityBytesOutTraceData').then( (res): NetworkAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -898,14 +805,7 @@ export class SpAbilityMonitorChart { packetInTraceRow.supplierFrame = (): Promise => abilityBytesInTraceDataSender(packetInTraceRow, 'AbilityPacketInTraceData').then( (res): NetworkAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -956,14 +856,7 @@ export class SpAbilityMonitorChart { packetOutTraceRow.supplierFrame = (): Promise => abilityBytesInTraceDataSender(packetOutTraceRow, 'AbilityPacketsOutTraceData').then( (res): NetworkAbilityMonitorStruct[] => { - let endNS = TraceRow.range?.endNS || 0; - res.forEach((it, i) => { - if (i === res.length - 1) { - it.dur = (endNS || 0) - (it.startNS || 0); - } else { - it.dur = (res[i + 1].startNS || 0) - (it.startNS || 0); - } - }); + this.computeDur(res); return res; } ); @@ -1148,4 +1041,15 @@ export class SpAbilityMonitorChart { }); } } -} + + private computeDur(list: Array): void { + let endNS = TraceRow.range?.endNS || 0; + list.forEach((it, i) => { + if (i === list.length - 1) { + it.dur = (endNS || 0) - (it.startNS || 0); + } else { + it.dur = (list[i + 1].startNS || 0) - (it.startNS || 0); + } + }); + } +} \ No newline at end of file diff --git a/ide/src/trace/component/chart/SpAllAppStartups.ts b/ide/src/trace/component/chart/SpAllAppStartups.ts index 917f44efe0505cc1f33bb4bebfccc92798e06a41..faf9f5ea812ce5de20d898237c3fa97d1d9a982e 100644 --- a/ide/src/trace/component/chart/SpAllAppStartups.ts +++ b/ide/src/trace/component/chart/SpAllAppStartups.ts @@ -17,7 +17,7 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { CpuFreqStruct } from '../../database/ui-worker/ProcedureWorkerFreq'; -import { queryAppStartupProcessIds, queryProcessStartup, querySingleAppStartupsName } from '../../database/SqlLite'; +import { queryAppStartupProcessIds, queryProcessStartup, querySingleAppStartupsName } from '../../database/sql/ProcessThread.sql'; import { FlagsConfig } from '../SpFlags'; import { AllAppStartupStruct, AllAppStartupRender } from '../../database/ui-worker/ProcedureWorkerAllAppStartup'; @@ -91,13 +91,7 @@ export class SpAllAppStartupsChart { } sendRes.push({ dur: singleDur, - value: undefined, startTs: minStartTs, - pid: SpAllAppStartupsChart.allAppStartupsAva[i], - process: undefined, - itid: undefined, - endItid: undefined, - tid: SpAllAppStartupsChart.allAppStartupsAva[i], startName: undefined, stepName: SpAllAppStartupsChart.AllAppStartupsNameArr[i], translateY: undefined, diff --git a/ide/src/trace/component/chart/SpArkTsChart.ts b/ide/src/trace/component/chart/SpArkTsChart.ts index 1628694fb89ee0d3bc1b1eafe3471669b6b106db..086f0312a1af1c72eeac28937b0a9934e1db7048 100644 --- a/ide/src/trace/component/chart/SpArkTsChart.ts +++ b/ide/src/trace/component/chart/SpArkTsChart.ts @@ -16,7 +16,7 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; import { info } from '../../../log/Log'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { type EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { type EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { type HeapTimelineRender, HeapTimelineStruct } from '../../database/ui-worker/ProcedureWorkerHeapTimeline'; import { HeapDataInterface, type ParseListener } from '../../../js-heap/HeapDataInterface'; import { LoadDatabase } from '../../../js-heap/LoadDatabase'; @@ -27,15 +27,11 @@ import { Utils } from '../trace/base/Utils'; import { type JsCpuProfilerChartFrame } from '../../bean/JsStruct'; import { type JsCpuProfilerRender, JsCpuProfilerStruct } from '../../database/ui-worker/ProcedureWorkerCpuProfiler'; import { ns2s } from '../../database/ui-worker/ProcedureWorkerCommon'; -import { - queryAllSnapshotNames, - queryJsCpuProfilerConfig, - queryJsCpuProfilerData, - queryJsMemoryData, -} from '../../database/SqlLite'; import { cpuProfilerDataSender } from '../../database/data-trafic/ArkTsSender'; +import {queryJsCpuProfilerConfig, queryJsCpuProfilerData} from "../../database/sql/Cpu.sql"; +import {queryJsMemoryData} from "../../database/sql/Memory.sql"; const TYPE_SNAPSHOT = 0; const TYPE_TIMELINE = 1; diff --git a/ide/src/trace/component/chart/SpChartManager.ts b/ide/src/trace/component/chart/SpChartManager.ts index 5f5bf3306839e9aa3e8b83b5084e0f48bef6ee31..95959d5371797056968dc648e9eed7888110272c 100644 --- a/ide/src/trace/component/chart/SpChartManager.ts +++ b/ide/src/trace/component/chart/SpChartManager.ts @@ -18,15 +18,6 @@ import { SpHiPerf } from './SpHiPerf'; import { SpCpuChart } from './SpCpuChart'; import { SpFreqChart } from './SpFreqChart'; import { SpFpsChart } from './SpFpsChart'; -import { - getCpuUtilizationRate, - queryAppStartupProcessIds, - queryDataDICT, - queryMemoryConfig, - queryTaskPoolCallStack, - queryThreadAndProcessName, - queryTotalTime, -} from '../../database/SqlLite'; import { info, log } from '../../../log/Log'; import { SpNativeMemoryChart } from './SpNativeMemoryChart'; import { SpAbilityMonitorChart } from './SpAbilityMonitorChart'; @@ -40,7 +31,7 @@ import { VmTrackerChart } from './SpVmTrackerChart'; import { SpClockChart } from './SpClockChart'; import { SpIrqChart } from './SpIrqChart'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { TraceRow } from '../trace/base/TraceRow'; import { SpFrameTimeChart } from './SpFrameTimeChart'; import { Utils } from '../trace/base/Utils'; @@ -52,6 +43,14 @@ import { SpHiSysEventChart } from './SpHiSysEventChart'; import { SpAllAppStartupsChart } from './SpAllAppStartups'; import {procedurePool} from "../../database/Procedure"; import { SpSegmentationChart } from './SpSegmentationChart'; +import { + queryAppStartupProcessIds, + queryDataDICT, + queryThreadAndProcessName +} from "../../database/sql/ProcessThread.sql"; +import {queryTaskPoolCallStack, queryTotalTime} from "../../database/sql/SqlLite.sql"; +import {getCpuUtilizationRate} from "../../database/sql/Cpu.sql"; +import {queryMemoryConfig} from "../../database/sql/Memory.sql"; export class SpChartManager { static APP_STARTUP_PID_ARR: Array = []; diff --git a/ide/src/trace/component/chart/SpClockChart.ts b/ide/src/trace/component/chart/SpClockChart.ts index 2d40ff685efaf9c89f55df16d7d2bc243da4f1e7..8ad47f6d1e62d885a2b5e8f657ec6cc89c21aa26 100644 --- a/ide/src/trace/component/chart/SpClockChart.ts +++ b/ide/src/trace/component/chart/SpClockChart.ts @@ -14,15 +14,15 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { queryClockData, queryClockFrequency, queryClockState, queryScreenState } from '../../database/SqlLite'; import { TraceRow } from '../trace/base/TraceRow'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { info } from '../../../log/Log'; import { ClockRender, ClockStruct } from '../../database/ui-worker/ProcedureWorkerClock'; import { ColorUtils } from '../trace/base/ColorUtils'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { Utils } from '../trace/base/Utils'; import { clockDataSender } from '../../database/data-trafic/ClockDataSender'; +import {queryClockData} from "../../database/sql/Clock.sql"; export class SpClockChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpCpuChart.ts b/ide/src/trace/component/chart/SpCpuChart.ts index 44a8978841ef9c03906f49b2f585d01fc7881259..a0b0e25a5edc32fadaa1b7e860eb919d4428c348 100644 --- a/ide/src/trace/component/chart/SpCpuChart.ts +++ b/ide/src/trace/component/chart/SpCpuChart.ts @@ -14,22 +14,16 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - queryCpuCount, - queryCpuData, - queryCpuDataCount, - queryCpuMax, - queryCpuSchedSlice, -} from '../../database/SqlLite'; import { info } from '../../../log/Log'; import { TraceRow } from '../trace/base/TraceRow'; import { procedurePool } from '../../database/Procedure'; -import { CpuRender, CpuStruct } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { CpuRender, CpuStruct } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { Utils } from '../trace/base/Utils'; import { cpuDataSender } from '../../database/data-trafic/CpuDataSender'; -import { TraficEnum } from '../../database/data-trafic/QueryEnum'; -import {cpuList} from "../../database/data-trafic/AllMemoryCache"; +import { TraficEnum } from '../../database/data-trafic/utils/QueryEnum'; +import {cpuList} from "../../database/data-trafic/utils/AllMemoryCache"; +import {queryCpuCount, queryCpuDataCount, queryCpuMax, queryCpuSchedSlice} from "../../database/sql/Cpu.sql"; export class SpCpuChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpEBPFChart.ts b/ide/src/trace/component/chart/SpEBPFChart.ts index 7bdde56dea96a2890735b9536997bb5f88b5541a..851b3663111f8b6233517a35a06e8f0e611ed2f9 100644 --- a/ide/src/trace/component/chart/SpEBPFChart.ts +++ b/ide/src/trace/component/chart/SpEBPFChart.ts @@ -16,19 +16,14 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; import { procedurePool } from '../../database/Procedure'; -import { - getDiskIOLatencyChartDataByProcess, - getDiskIOProcess, - getFileSysChartDataByType, - getFileSysVirtualMemoryChartData, - hasFileSysData, -} from '../../database/SqlLite'; import { EBPFChartStruct, EBPFRender } from '../../database/ui-worker/ProcedureWorkerEBPF'; import { ColorUtils } from '../trace/base/ColorUtils'; import { Utils } from '../trace/base/Utils'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { diskIoSender, fileSysVMSender, fileSystemSender } from '../../database/data-trafic/EBPFSender'; +import { hasFileSysData } from '../../database/sql/Memory.sql'; +import { getDiskIOProcess } from '../../database/sql/SqlLite.sql'; export class SpEBPFChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpFpsChart.ts b/ide/src/trace/component/chart/SpFpsChart.ts index aeb0b9f7a68cf3788fededf340cce6e9246d488a..6d1001abe1436097c0723e0395408de0ca22034f 100644 --- a/ide/src/trace/component/chart/SpFpsChart.ts +++ b/ide/src/trace/component/chart/SpFpsChart.ts @@ -14,11 +14,11 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { getFps } from '../../database/SqlLite'; import { TraceRow } from '../trace/base/TraceRow'; import { info } from '../../../log/Log'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { FpsRender, FpsStruct } from '../../database/ui-worker/ProcedureWorkerFPS'; +import {getFps} from "../../database/sql/SqlLite.sql"; export class SpFpsChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpFrameTimeChart.ts b/ide/src/trace/component/chart/SpFrameTimeChart.ts index 90a569850c4d331931eb37b2c7ecaf7b8994a403..4d9375ce122112474911980e0a8de4f7efc442a9 100644 --- a/ide/src/trace/component/chart/SpFrameTimeChart.ts +++ b/ide/src/trace/component/chart/SpFrameTimeChart.ts @@ -17,15 +17,6 @@ import { TraceRow } from '../trace/base/TraceRow'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { JankRender, JankStruct } from '../../database/ui-worker/ProcedureWorkerJank'; import { SpSystemTrace } from '../SpSystemTrace'; -import { - queryAllProcessNames, - queryAnimationIdAndNameData, - queryAnimationTimeRangeData, - queryDynamicIdAndNameData, - queryFrameApp, - queryFrameTimeData, - queryPhysicalData, -} from '../../database/SqlLite'; import { JanksStruct } from '../../bean/JanksStruct'; import { ns2xByTimeShaft, type PairPoint } from '../../database/ui-worker/ProcedureWorkerCommon'; import { FrameDynamicRender, FrameDynamicStruct } from '../../database/ui-worker/ProcedureWorkerFrameDynamic'; @@ -34,11 +25,19 @@ import { type BaseStruct } from '../../bean/BaseStruct'; import { FrameSpacingRender, FrameSpacingStruct } from '../../database/ui-worker/ProcedureWorkerFrameSpacing'; import { FlagsConfig, type Params } from '../SpFlags'; import { type AnimationRanges, type DeviceStruct } from '../../bean/FrameComponentBean'; -import { type EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { type EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { TreeItemData } from '../../../base-ui/tree/LitTree'; -import { QueryEnum } from '../../database/data-trafic/QueryEnum'; +import { QueryEnum } from '../../database/data-trafic/utils/QueryEnum'; import { frameAnimationSender, frameDynamicSender, frameSpacingSender } from '../../database/data-trafic/FrameDynamicEffectSender'; import { frameJanksSender } from '../../database/data-trafic/FrameJanksSender'; +import { + queryAnimationIdAndNameData, + queryAnimationTimeRangeData, + queryDynamicIdAndNameData, + queryFrameApp, + queryFrameTimeData, queryPhysicalData +} from "../../database/sql/SqlLite.sql"; +import {queryAllProcessNames} from "../../database/sql/ProcessThread.sql"; export class SpFrameTimeChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpFreqChart.ts b/ide/src/trace/component/chart/SpFreqChart.ts index 1db6aae5bb6e98b438a12aa5295b7945f249cbff..72f2488b966fa576757fe71b9081d07718ab60f5 100644 --- a/ide/src/trace/component/chart/SpFreqChart.ts +++ b/ide/src/trace/component/chart/SpFreqChart.ts @@ -14,25 +14,25 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - getCpuLimitFreqId, - getCpuLimitFreqMax, - queryCpuFreq, - queryCpuMaxFreq, - queryCpuStateFilter, -} from '../../database/SqlLite'; import { info } from '../../../log/Log'; import { TraceRow } from '../trace/base/TraceRow'; import { ColorUtils } from '../trace/base/ColorUtils'; -import { CpuFreqLimitRender, CpuFreqLimitsStruct } from '../../database/ui-worker/ProcedureWorkerCpuFreqLimits'; +import { CpuFreqLimitRender, CpuFreqLimitsStruct } from '../../database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { CpuFreqStruct, FreqRender } from '../../database/ui-worker/ProcedureWorkerFreq'; -import { CpuStateRender, CpuStateStruct } from '../../database/ui-worker/ProcedureWorkerCpuState'; +import { CpuStateRender, CpuStateStruct } from '../../database/ui-worker/cpu/ProcedureWorkerCpuState'; import { FolderSupplier, FolderThreadHandler } from './SpChartManager'; import { Utils } from '../trace/base/Utils'; -import { cpuFreqDataSender } from '../../database/data-trafic/CpuFreqDataSender'; -import { cpuStateSender } from '../../database/data-trafic/CpuStateSender'; -import { cpuFreqLimitSender } from '../../database/data-trafic/CpuFreqLimitDataSender'; +import { cpuFreqDataSender } from '../../database/data-trafic/cpu/CpuFreqDataSender'; +import { cpuStateSender } from '../../database/data-trafic/cpu/CpuStateSender'; +import { cpuFreqLimitSender } from '../../database/data-trafic/cpu/CpuFreqLimitDataSender'; +import { + getCpuLimitFreqId, + getCpuLimitFreqMax, + queryCpuFreq, + queryCpuMaxFreq, + queryCpuStateFilter +} from "../../database/sql/Cpu.sql"; export class SpFreqChart { private trace: SpSystemTrace; private folderRow: TraceRow | undefined; diff --git a/ide/src/trace/component/chart/SpHiPerf.ts b/ide/src/trace/component/chart/SpHiPerf.ts index 3b12a39f4e8a1416cd80155de945b03296c8eba1..61534ae2ba9bd0972fa05534c5b36ad031d6b478 100644 --- a/ide/src/trace/component/chart/SpHiPerf.ts +++ b/ide/src/trace/component/chart/SpHiPerf.ts @@ -15,42 +15,38 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; -import { - queryHiPerfCpuData, - queryHiPerfCpuMergeData, - queryHiPerfCpuMergeData2, - queryHiPerfProcessData, - queryHiPerfThreadData, - queryPerfEventType, - queryPerfCmdline, - queryPerfThread, -} from '../../database/SqlLite'; import { Utils } from '../trace/base/Utils'; import { PerfThread } from '../../bean/PerfProfile'; -import { HiperfCpuRender, HiPerfCpuStruct } from '../../database/ui-worker/ProcedureWorkerHiPerfCPU'; -import { HiPerfCallChartRender, HiPerfCallChartStruct } from '../../database/ui-worker/ProcedureWorkerHiPerfCallChart'; -import { HiperfThreadRender, HiPerfThreadStruct } from '../../database/ui-worker/ProcedureWorkerHiPerfThread'; -import { HiperfProcessRender, HiPerfProcessStruct } from '../../database/ui-worker/ProcedureWorkerHiPerfProcess'; +import { HiperfCpuRender, HiPerfCpuStruct } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU'; +import { HiPerfCallChartRender, HiPerfCallChartStruct } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfCallChart'; +import { HiperfThreadRender, HiPerfThreadStruct } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfThread'; +import { HiperfProcessRender, HiPerfProcessStruct } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess'; import { info } from '../../../log/Log'; -import { HiPerfEventStruct } from '../../database/ui-worker/ProcedureWorkerHiPerfEvent'; +import { HiPerfEventStruct } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfEvent'; import { perfDataQuery } from './PerfDataQuery'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; -import { type HiPerfReportStruct } from '../../database/ui-worker/ProcedureWorkerHiPerfReport'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; +import { type HiPerfReportStruct } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfReport'; import { SpChartManager } from './SpChartManager'; import { procedurePool } from '../../database/Procedure'; import { HiPerfChartFrame } from '../../bean/PerfStruct'; -import { HiperfCpuRender2 } from '../../database/ui-worker/ProcedureWorkerHiPerfCPU2'; -import { hiperfCpuDataSender } from '../../database/data-trafic/HiperfCpuDataSender'; -import { hiperfProcessDataSender } from '../../database/data-trafic/HiperfProcessDataSender'; -import { HiperfProcessRender2 } from '../../database/ui-worker/ProcedureWorkerHiPerfProcess2'; -import { hiperfThreadDataSender } from '../../database/data-trafic/HiperfThreadDataSender'; -import { HiperfThreadRender2 } from '../../database/ui-worker/ProcedureWorkerHiPerfThread2'; +import { HiperfCpuRender2 } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU2'; +import { hiperfCpuDataSender } from '../../database/data-trafic/hiperf/HiperfCpuDataSender'; +import { hiperfProcessDataSender } from '../../database/data-trafic/hiperf/HiperfProcessDataSender'; +import { HiperfProcessRender2 } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess2'; +import { hiperfThreadDataSender } from '../../database/data-trafic/hiperf/HiperfThreadDataSender'; +import { HiperfThreadRender2 } from '../../database/ui-worker/hiperf/ProcedureWorkerHiPerfThread2'; import { hiperfCallChartDataCacheSender, hiperfCallChartDataSender, hiperfCallStackCacheSender, -} from '../../database/data-trafic/HiperfCallChartSender'; +} from '../../database/data-trafic/hiperf/HiperfCallChartSender'; +import { + queryHiPerfCpuMergeData2, + queryPerfCmdline, + queryPerfEventType, + queryPerfThread +} from "../../database/sql/Perf.sql"; export interface ResultData { existA: boolean | null | undefined; diff --git a/ide/src/trace/component/chart/SpHiSysEnergyChart.ts b/ide/src/trace/component/chart/SpHiSysEnergyChart.ts index 832f874de8ce99e90cf31ca36bb2cd755a9545b0..aec455284f880fd33b6f2d89bcc2cf2c0e733dfd 100644 --- a/ide/src/trace/component/chart/SpHiSysEnergyChart.ts +++ b/ide/src/trace/component/chart/SpHiSysEnergyChart.ts @@ -14,37 +14,47 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - queryAnomalyData, - queryConfigEnergyAppName, - queryEnergyEventExits, - queryMaxStateValue, - queryPowerData, - queryStateInitValue, - queryEnergyAppName, - querySystemAllData, -} from '../../database/SqlLite'; import { info } from '../../../log/Log'; import { TraceRow } from '../trace/base/TraceRow'; import { BaseStruct } from '../../bean/BaseStruct'; -import { EnergyAnomalyRender, EnergyAnomalyStruct } from '../../database/ui-worker/ProcedureWorkerEnergyAnomaly'; -import { EnergySystemStruct, EnergySystemRender } from '../../database/ui-worker/ProcedureWorkerEnergySystem'; -import { EnergyPowerStruct, EnergyPowerRender } from '../../database/ui-worker/ProcedureWorkerEnergyPower'; -import { EnergyStateStruct, EnergyStateRender } from '../../database/ui-worker/ProcedureWorkerEnergyState'; +import { + EnergyAnomalyRender, + EnergyAnomalyStruct +} from '../../database/ui-worker/ProcedureWorkerEnergyAnomaly'; +import { + EnergySystemStruct, + EnergySystemRender +} from '../../database/ui-worker/ProcedureWorkerEnergySystem'; +import { + EnergyPowerStruct, + EnergyPowerRender +} from '../../database/ui-worker/ProcedureWorkerEnergyPower'; +import { + EnergyStateStruct, + EnergyStateRender +} from '../../database/ui-worker/ProcedureWorkerEnergyState'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { TreeItemData } from '../../../base-ui/tree/LitTree'; import { energySysEventSender, hiSysEnergyAnomalyDataSender, hiSysEnergyPowerSender, hiSysEnergyStateSender } from '../../database/data-trafic/EnergySysEventSender'; +import { + queryAnomalyData, + queryConfigEnergyAppName, + queryEnergyAppName, + queryEnergyEventExits, queryMaxStateValue, queryStateInitValue +} from '../../database/sql/SqlLite.sql'; +import { queryPowerData } from '../../database/sql/ProcessThread.sql'; +import { NUM_200, NUM_3 } from '../../bean/NumBean'; export class SpHiSysEnergyChart { static app_name: string | null; - private trace: SpSystemTrace; + trace: SpSystemTrace; private energyTraceRow: TraceRow | undefined; - private timer: any; + private timer: number | undefined; private eventNameMap: Map = new Map(); private appKeyMap: Map = new Map(); private eventValueMap: Map = new Map(); @@ -92,9 +102,9 @@ export class SpHiSysEnergyChart { this.trace = trace; } - async init() { + async init(): Promise { let result = await queryEnergyEventExits(); - if (result.length <= 0) return; + if (result.length <= 0) {return} let anomalyData = await queryAnomalyData(); let powerData = await queryPowerData(); for (let index = 0; index < anomalyData.length; index++) { @@ -116,98 +126,46 @@ export class SpHiSysEnergyChart { await this.initState(); } - private initEnergyRow = async () => { - SpHiSysEnergyChart.app_name = ''; - let appNameFromTable = await queryEnergyAppName(); - let configAppName = await queryConfigEnergyAppName(); - if (configAppName.length > 0 && appNameFromTable.length > 0) { - let name = configAppName[0].process_name; - if (name != null) { - let filterList = appNameFromTable.filter((appNameFromTableElement) => { - return appNameFromTableElement.string_value?.trim() == name; - }); - if (filterList.length > 0) { - SpHiSysEnergyChart.app_name = name; - } - } - } - if (appNameFromTable.length > 0 && SpHiSysEnergyChart.app_name == '') { - SpHiSysEnergyChart.app_name = appNameFromTable[0].string_value; - } - this.energyTraceRow = TraceRow.skeleton(); - this.energyTraceRow.addRowSettingPop(); - this.energyTraceRow.rowSetting = 'enable'; - this.energyTraceRow.rowSettingPopoverDirection = 'bottomLeft'; - let nameList: Array = []; - for (let index = 0; index < appNameFromTable.length; index++) { - let appName = appNameFromTable[index].string_value; - nameList.push({ - key: `${appName}`, - title: `${appName}`, - checked: index === 0, - }); - } - this.energyTraceRow.rowSettingList = nameList; - this.energyTraceRow.onRowSettingChangeHandler = (value): void => { - SpHiSysEnergyChart.app_name = value[0]; - this.trace.refreshCanvas(false); - }; - this.energyTraceRow.rowId = `energy`; - this.energyTraceRow.rowType = TraceRow.ROW_TYPE_ENERGY; - this.energyTraceRow.rowParentId = ''; - this.energyTraceRow.folder = true; - this.energyTraceRow.addTemplateTypes('EnergyEvent'); - this.energyTraceRow.name = 'Energy'; - this.energyTraceRow.style.height = '40px'; - this.energyTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; - this.energyTraceRow.selectChangeHandler = this.trace.selectChangeHandler; - this.energyTraceRow.supplier = () => new Promise>((resolve) => resolve([])); - this.energyTraceRow.onThreadHandler = (useCache) => { + private async initEnergyRow(): Promise { + await this.initEnergyChartRow(); + this.energyTraceRow!.favoriteChangeHandler = this.trace.favoriteChangeHandler; + this.energyTraceRow!.selectChangeHandler = this.trace.selectChangeHandler; + this.energyTraceRow!.supplier = (): Promise => new Promise>( + (resolve) => resolve([])); + this.energyTraceRow!.onThreadHandler = (useCache: boolean): void => { this.energyTraceRow?.canvasSave(this.trace.canvasPanelCtx!); if (this.energyTraceRow!.expansion) { this.trace.canvasPanelCtx?.clearRect(0, 0, this.energyTraceRow!.frame.width, this.energyTraceRow!.frame.height); } else { - (renders['empty'] as EmptyRender).renderMainThread( + (renders.empty as EmptyRender).renderMainThread( { context: this.trace.canvasPanelCtx, useCache: useCache, - type: ``, + type: '', }, this.energyTraceRow! ); } this.energyTraceRow?.canvasRestore(this.trace.canvasPanelCtx!, this.trace); }; - this.energyTraceRow.addEventListener('expansion-change', () => { + this.energyTraceRow!.addEventListener('expansion-change', () => { TraceRow.range!.refresh = true; this.trace.refreshCanvas(false); if (this.timer) { clearTimeout(this.timer); } - this.timer = setTimeout(() => { + this.timer = window.setTimeout((): void => { TraceRow.range!.refresh = false; - }, 200); + }, NUM_200); }); this.trace.rowsEL?.appendChild(this.energyTraceRow!); }; private initAnomaly = (): void => { let time = new Date().getTime(); - let anomalyTraceRow = TraceRow.skeleton(); - anomalyTraceRow.rowParentId = `energy`; - anomalyTraceRow.rowHidden = true; - anomalyTraceRow.rowId = 'energy-anomaly'; - anomalyTraceRow.rowType = TraceRow.ROW_TYPE_ANOMALY_ENERGY; - anomalyTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; - anomalyTraceRow.selectChangeHandler = this.trace.selectChangeHandler; - anomalyTraceRow.setAttribute('height', `55px`); - let element = anomalyTraceRow.shadowRoot?.querySelector('.root') as HTMLDivElement; - element!.style.height = `55px`; - anomalyTraceRow.style.width = `100%`; - anomalyTraceRow.setAttribute('children', ''); - anomalyTraceRow.name = 'Anomaly Event'; - anomalyTraceRow.supplierFrame = () => { - return hiSysEnergyAnomalyDataSender(anomalyTraceRow).then((res) => { + let anomalyTraceRow = this.initAnomalyChartRow(); + anomalyTraceRow.supplierFrame = async (): Promise => { + return hiSysEnergyAnomalyDataSender(anomalyTraceRow).then((res: EnergyAnomalyStruct[]) => { for (let index = 0; index < res.length; index++) { let item = res[index]; item.eventName = this.eventNameMap.get(res[index].id!); @@ -217,17 +175,10 @@ export class SpHiSysEnergyChart { return res; }); }; - anomalyTraceRow.focusHandler = () => { - this.trace?.displayTip( - anomalyTraceRow, - EnergyAnomalyStruct.hoverEnergyAnomalyStruct, - `AnomalyName:${EnergyAnomalyStruct.hoverEnergyAnomalyStruct?.eventName || ''}` - ); - }; - anomalyTraceRow.findHoverStruct = () => { + anomalyTraceRow.findHoverStruct = (): void => { EnergyAnomalyStruct.hoverEnergyAnomalyStruct = anomalyTraceRow.getHoverStruct(); }; - anomalyTraceRow.onThreadHandler = (useCache) => { + anomalyTraceRow.onThreadHandler = (useCache: boolean): void => { let context: CanvasRenderingContext2D; if (anomalyTraceRow.currentContext) { context = anomalyTraceRow.currentContext; @@ -235,11 +186,11 @@ export class SpHiSysEnergyChart { context = anomalyTraceRow.collect ? this.trace.canvasFavoritePanelCtx! : this.trace.canvasPanelCtx!; } anomalyTraceRow.canvasSave(context); - (renders['energyAnomaly'] as EnergyAnomalyRender).renderMainThread( + (renders.energyAnomaly as EnergyAnomalyRender).renderMainThread( { context: context, useCache: useCache, - type: `energyAnomaly`, + type: 'energyAnomaly', appName: SpHiSysEnergyChart.app_name || '', canvasWidth: this.trace.canvasPanel?.width || 0, }, @@ -254,45 +205,16 @@ export class SpHiSysEnergyChart { private initSystem = (): void => { let time = new Date().getTime(); - let systemTraceRow = TraceRow.skeleton(); - systemTraceRow.rowParentId = `energy`; - systemTraceRow.rowHidden = true; - systemTraceRow.rowId = 'energy-system'; - systemTraceRow.rowType = TraceRow.ROW_TYPE_SYSTEM_ENERGY; - systemTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; - systemTraceRow.selectChangeHandler = this.trace.selectChangeHandler; - systemTraceRow.setAttribute('height', `80px`); - let element = systemTraceRow.shadowRoot?.querySelector('.root') as HTMLDivElement; - element!.style.height = `90px`; - systemTraceRow.style.width = `100%`; - systemTraceRow.setAttribute('children', ''); - systemTraceRow.name = 'System Event'; - systemTraceRow.supplierFrame = () => { - return energySysEventSender(systemTraceRow).then((res) => { + let systemTraceRow = this.initSystemChartRow(); + systemTraceRow.supplierFrame = async (): Promise => { + return energySysEventSender(systemTraceRow).then((res: EnergySystemStruct[]) => { return res; }); }; - systemTraceRow.focusHandler = () => { - this.trace?.displayTip( - systemTraceRow, - EnergySystemStruct.hoverEnergySystemStruct, - `
-
WORKSCHEDULER:
${ - EnergySystemStruct.hoverEnergySystemStruct?.workScheduler! || 0 - }
-
POWER_RUNNINGLOCK:
${ - EnergySystemStruct.hoverEnergySystemStruct?.power! || 0 - }
-
LOCATION:
${ - EnergySystemStruct.hoverEnergySystemStruct?.location! || 0 - }
-
` - ); - }; - systemTraceRow.findHoverStruct = () => { + systemTraceRow.findHoverStruct = (): void => { EnergySystemStruct.hoverEnergySystemStruct = systemTraceRow.getHoverStruct(); }; - systemTraceRow.onThreadHandler = (useCache) => { + systemTraceRow.onThreadHandler = (useCache: boolean): void => { let context: CanvasRenderingContext2D; if (systemTraceRow.currentContext) { context = systemTraceRow.currentContext; @@ -300,11 +222,11 @@ export class SpHiSysEnergyChart { context = systemTraceRow.collect ? this.trace.canvasFavoritePanelCtx! : this.trace.canvasPanelCtx!; } systemTraceRow.canvasSave(context); - (renders['energySystem'] as EnergySystemRender).renderMainThread( + (renders.energySystem as EnergySystemRender).renderMainThread( { context: context, useCache: useCache, - type: `energySystem`, + type: 'energySystem', }, systemTraceRow ); @@ -317,20 +239,8 @@ export class SpHiSysEnergyChart { private initPower = (): void => { let time = new Date().getTime(); - let powerTraceRow = TraceRow.skeleton(); - powerTraceRow.rowParentId = `energy`; - powerTraceRow.rowHidden = true; - powerTraceRow.rowId = 'energy-power'; - powerTraceRow.rowType = TraceRow.ROW_TYPE_POWER_ENERGY; - powerTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; - powerTraceRow.selectChangeHandler = this.trace.selectChangeHandler; - powerTraceRow.setAttribute('height', `200px`); - let element = powerTraceRow.shadowRoot?.querySelector('.root') as HTMLDivElement; - element!.style.height = `200px`; - powerTraceRow.style.width = `100%`; - powerTraceRow.setAttribute('children', ''); - powerTraceRow.name = 'Power'; - powerTraceRow.supplierFrame = () => { + let powerTraceRow = this.initPowerChartRow(); + powerTraceRow.supplierFrame = async (): Promise => { return hiSysEnergyPowerSender(powerTraceRow).then((res) => { for (let index = 0; index < res.length; index++) { let item = res[index]; @@ -341,42 +251,7 @@ export class SpHiSysEnergyChart { return this.getPowerData(res); }); }; - powerTraceRow.focusHandler = () => { - this.trace?.displayTip( - powerTraceRow, - EnergyPowerStruct.hoverEnergyPowerStruct, - `
-
CPU:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.cpu! || 0 - }
-
location:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.location! || 0 - }
-
GPU:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.gpu! || 0 - }
-
display:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.display! || 0 - }
-
camera:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.camera! || 0 - }
-
bluetooth:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.bluetooth! || 0 - }
-
flashlight:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.flashlight! || 0 - }
-
audio:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.audio! || 0 - }
-
wifiScan:
${ - EnergyPowerStruct.hoverEnergyPowerStruct?.wifiscan! || 0 - }
-
` - ); - }; - powerTraceRow.onThreadHandler = (useCache) => { + powerTraceRow.onThreadHandler = (useCache: boolean): void => { let context: CanvasRenderingContext2D; if (powerTraceRow.currentContext) { context = powerTraceRow.currentContext; @@ -384,11 +259,11 @@ export class SpHiSysEnergyChart { context = powerTraceRow.collect ? this.trace.canvasFavoritePanelCtx! : this.trace.canvasPanelCtx!; } powerTraceRow.canvasSave(context); - (renders['energyPower'] as EnergyPowerRender).renderMainThread( + (renders.energyPower as EnergyPowerRender).renderMainThread( { context: context, useCache: useCache, - type: `energyPower`, + type: 'energyPower', appName: SpHiSysEnergyChart.app_name || '', }, powerTraceRow! @@ -400,13 +275,296 @@ export class SpHiSysEnergyChart { info('The time to load the energy power is: ', durTime); }; - async getPowerData(items: any): Promise { + private initState = async (): Promise => { + let time = new Date().getTime(); + for (let index = 0; index < this.stateList.length; index++) { + let stateResult = await queryStateInitValue(this.stateName[index], this.initValueList[index]); + let maxStateData = await queryMaxStateValue(this.stateName[index]); + if (!maxStateData[0]) { + continue; + } + let maxStateTotal = this.getMaxStateTotal(maxStateData); + let stateTraceRow = this.initStatChartRow(index); + stateTraceRow.supplierFrame = async (): Promise => { + const res = await hiSysEnergyStateSender(this.stateName, index, stateTraceRow); + let stateInitValue = this.initValueList[index] === 'nocolumn' ? [] : stateResult; + for (let i = 0; i < res.length; i++) { + let item = res[i]; + item.type = this.stateName[index]; + } + return stateInitValue.concat(res); + }; + stateTraceRow.onThreadHandler = (useCache: boolean): void => { + let context: CanvasRenderingContext2D; + if (stateTraceRow.currentContext) { + context = stateTraceRow.currentContext; + } else { + context = stateTraceRow.collect ? this.trace.canvasFavoritePanelCtx! : this.trace.canvasPanelCtx!; + } + stateTraceRow.canvasSave(context); + (renders.energyState as EnergyStateRender).renderMainThread( + { + context: context, + useCache: useCache, + type: `energyState${index}`, + maxState: maxStateData[0].maxValue, + maxStateName: maxStateData[0].type.toLocaleLowerCase().endsWith('br_switch_state') ? + '-1' : + maxStateTotal.toString(), + }, + stateTraceRow + ); + stateTraceRow.canvasRestore(context, this.trace); + }; + this.energyTraceRow?.addChildTraceRow(stateTraceRow); + let durTime = new Date().getTime() - time; + info('The time to load the Ability Memory is: ', durTime); + } + }; + + private getMaxStateTotal(maxStateData: Array<{ + type: string; + maxValue: number; + }>): string { + let maxStateTotal = maxStateData[0].maxValue.toString(); + let statType = maxStateData[0].type.toLocaleLowerCase(); + if (statType.includes('state') && !statType.endsWith('br_switch_state')) { + if (maxStateData[0].maxValue === 0) { + maxStateTotal = 'enable'; + } else { + maxStateTotal = 'disable'; + } + } else if (statType.includes('sensor')) { + if (statType.includes('enable')) { + maxStateTotal = 'enable'; + } else { + maxStateTotal = 'disable'; + } + } + return maxStateTotal; + } + + private initStatChartRow(index: number): TraceRow { + let stateTraceRow = TraceRow.skeleton(); + stateTraceRow.rowParentId = 'energy'; + stateTraceRow.rowHidden = true; + stateTraceRow.rowId = `energy-state-${this.stateList[index]}`; + stateTraceRow.rowType = TraceRow.ROW_TYPE_STATE_ENERGY; + stateTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; + stateTraceRow.selectChangeHandler = this.trace.selectChangeHandler; + stateTraceRow.style.height = '40px'; + stateTraceRow.style.width = '100%'; + stateTraceRow.setAttribute('children', ''); + stateTraceRow.name = `${this.stateList[index]}`; + stateTraceRow.focusHandler = (): void => { + let tip; + if (EnergyStateStruct.hoverEnergyStateStruct?.type!.toLocaleLowerCase().includes('state')) { + tip = `Switch Status: ${ + EnergyStateStruct.hoverEnergyStateStruct?.value === 1 ? 'disable' : 'enable' + }`; + if (EnergyStateStruct.hoverEnergyStateStruct?.type!.toLocaleLowerCase().endsWith('br_switch_state')) { + tip = `${SpHiSysEnergyChart.getBlueToothState( + EnergyStateStruct.hoverEnergyStateStruct?.value + )}`; + } + } else { + tip = `value: ${EnergyStateStruct.hoverEnergyStateStruct?.value?.toFixed(2) || 0}`; + } + this.trace?.displayTip(stateTraceRow, EnergyStateStruct.hoverEnergyStateStruct, tip); + }; + return stateTraceRow; + } + + private async initEnergyChartRow(): Promise { + SpHiSysEnergyChart.app_name = ''; + let appNameFromTable = await queryEnergyAppName(); + let configAppName = await queryConfigEnergyAppName(); + if (configAppName.length > 0 && appNameFromTable.length > 0) { + let name = configAppName[0].process_name; + if (name !== null) { + let filterList = appNameFromTable.filter((appNameFromTableElement) => { + return appNameFromTableElement.string_value?.trim() === name; + }); + if (filterList.length > 0) { + SpHiSysEnergyChart.app_name = name; + } + } + } + if (appNameFromTable.length > 0 && SpHiSysEnergyChart.app_name === '') { + SpHiSysEnergyChart.app_name = appNameFromTable[0].string_value; + } + this.energyTraceRow = TraceRow.skeleton(); + this.energyTraceRow.addRowSettingPop(); + this.energyTraceRow.rowSetting = 'enable'; + this.energyTraceRow.rowSettingPopoverDirection = 'bottomLeft'; + let nameList: Array = []; + for (let index = 0; index < appNameFromTable.length; index++) { + let appName = appNameFromTable[index].string_value; + nameList.push({ + key: `${appName}`, + title: `${appName}`, + checked: index === 0, + }); + } + this.energyTraceRow.rowSettingList = nameList; + this.energyTraceRow.onRowSettingChangeHandler = (value): void => { + SpHiSysEnergyChart.app_name = value[0]; + this.trace.refreshCanvas(false); + }; + this.energyTraceRow.rowId = 'energy'; + this.energyTraceRow.rowType = TraceRow.ROW_TYPE_ENERGY; + this.energyTraceRow.rowParentId = ''; + this.energyTraceRow.folder = true; + this.energyTraceRow.addTemplateTypes('EnergyEvent'); + this.energyTraceRow.name = 'Energy'; + this.energyTraceRow.style.height = '40px'; + } + + private initAnomalyChartRow(): TraceRow { + let anomalyTraceRow = TraceRow.skeleton(); + anomalyTraceRow.rowParentId = 'energy'; + anomalyTraceRow.rowHidden = true; + anomalyTraceRow.rowId = 'energy-anomaly'; + anomalyTraceRow.rowType = TraceRow.ROW_TYPE_ANOMALY_ENERGY; + anomalyTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; + anomalyTraceRow.selectChangeHandler = this.trace.selectChangeHandler; + anomalyTraceRow.setAttribute('height', '55px'); + let element = anomalyTraceRow.shadowRoot?.querySelector('.root') as HTMLDivElement; + element!.style.height = '55px'; + anomalyTraceRow.style.width = '100%'; + anomalyTraceRow.setAttribute('children', ''); + anomalyTraceRow.name = 'Anomaly Event'; + anomalyTraceRow.focusHandler = (): void => { + this.trace?.displayTip( + anomalyTraceRow, + EnergyAnomalyStruct.hoverEnergyAnomalyStruct, + `AnomalyName:${EnergyAnomalyStruct.hoverEnergyAnomalyStruct?.eventName || ''}` + ); + }; + return anomalyTraceRow; + } + + private initSystemChartRow(): TraceRow { + let systemTraceRow = TraceRow.skeleton(); + systemTraceRow.rowParentId = 'energy'; + systemTraceRow.rowHidden = true; + systemTraceRow.rowId = 'energy-system'; + systemTraceRow.rowType = TraceRow.ROW_TYPE_SYSTEM_ENERGY; + systemTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; + systemTraceRow.selectChangeHandler = this.trace.selectChangeHandler; + systemTraceRow.setAttribute('height', '80px'); + let element = systemTraceRow.shadowRoot?.querySelector('.root') as HTMLDivElement; + element!.style.height = '90px'; + systemTraceRow.style.width = '100%'; + systemTraceRow.setAttribute('children', ''); + systemTraceRow.name = 'System Event'; + systemTraceRow.focusHandler = (): void => { + this.trace?.displayTip( + systemTraceRow, + EnergySystemStruct.hoverEnergySystemStruct, + this.getSystemFocusHtml() + ); + }; + return systemTraceRow; + } + + private getSystemFocusHtml(): string { + return ` +
+
+
WORKSCHEDULER:
+
${EnergySystemStruct.hoverEnergySystemStruct?.workScheduler! || 0}
+
+
+
POWER_RUNNINGLOCK:
+
${EnergySystemStruct.hoverEnergySystemStruct?.power! || 0}
+
+
+
LOCATION:
+
${EnergySystemStruct.hoverEnergySystemStruct?.location! || 0}
+
+
`; + } + + private getPowerFocusHtml(): string { + return ` +
+
+
CPU:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.cpu! || 0}
+
+
+
location:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.location! || 0}
+
+
+
GPU:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.gpu! || 0}
+
+
+
display:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.display! || 0}
+
+
+
camera:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.camera! || 0}
+
+
+
bluetooth:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.bluetooth! || 0}
+
+
+
flashlight:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.flashlight! || 0}
+
+
+
audio:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.audio! || 0}
+
+
+
wifiScan:
+
${EnergyPowerStruct.hoverEnergyPowerStruct?.wifiscan! || 0}
+
+
`; + } + + private initPowerChartRow(): TraceRow { + let powerTraceRow = TraceRow.skeleton(); + powerTraceRow.rowParentId = 'energy'; + powerTraceRow.rowHidden = true; + powerTraceRow.rowId = 'energy-power'; + powerTraceRow.rowType = TraceRow.ROW_TYPE_POWER_ENERGY; + powerTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; + powerTraceRow.selectChangeHandler = this.trace.selectChangeHandler; + powerTraceRow.setAttribute('height', '200px'); + let element = powerTraceRow.shadowRoot?.querySelector('.root') as HTMLDivElement; + element!.style.height = '200px'; + powerTraceRow.style.width = '100%'; + powerTraceRow.setAttribute('children', ''); + powerTraceRow.name = 'Power'; + powerTraceRow.focusHandler = (): void => { + this.trace?.displayTip( + powerTraceRow, + EnergyPowerStruct.hoverEnergyPowerStruct, + this.getPowerFocusHtml() + ); + }; + return powerTraceRow; + } + + private getPowerData(items: any): EnergyPowerStruct[] { let powerDataMap: any = {}; - let appNameList: any = []; - items.forEach((item: any) => { + let appNameList: string[] = []; + items.forEach((item: { + id: number, + startNS: number, + eventName: string, + appKey: string, + eventValue: string + }): void => { let dataItem = powerDataMap[item.startNS]; - if (dataItem == undefined) { - if (item.appKey == 'APPNAME') { + if (dataItem === undefined) { + if (item.appKey === 'APPNAME') { let appMap: any = {}; let appNames = item.eventValue.split(','); appNameList = appNames; @@ -420,21 +578,8 @@ export class SpHiSysEnergyChart { } } } else { - if (item.appKey != 'APPNAME') { - let values = item.eventValue.split(','); - for (let i = 0; i < values.length; i++) { - let appName = appNameList[i]; - let obj = dataItem[appName]; - if (obj != undefined) { - let eventName = item.eventName.split('_'); - let s = eventName[eventName.length - 1].toLocaleLowerCase(); - if (obj[s] == undefined) { - obj[s] = parseInt(values[i]); - } else { - obj[s] += parseInt(values[i]); - } - } - } + if (item.appKey !== 'APPNAME') { + this.powerDataMap(item.eventName, item.eventValue, appNameList, dataItem); } else { let dataMap = powerDataMap[item.startNS]; let appNames = item.eventValue.split(','); @@ -449,97 +594,25 @@ export class SpHiSysEnergyChart { } } }); - // @ts-ignore return Object.values(powerDataMap); } - private initState = async () => { - let time = new Date().getTime(); - for (let index = 0; index < this.stateList.length; index++) { - let stateResult = await queryStateInitValue(this.stateName[index], this.initValueList[index]); - let maxStateData = await queryMaxStateValue(this.stateName[index]); - if (!maxStateData[0]) { - continue; - } - let maxStateTotal = maxStateData[0].maxValue.toString(); - let statType = maxStateData[0].type.toLocaleLowerCase(); - if (statType.includes('state') && !statType.endsWith('br_switch_state')) { - if (maxStateData[0].maxValue == 0) { - maxStateTotal = 'enable'; + private powerDataMap(name: string, eventValue: string, appNameList: string[], dataItem: any): void { + let values = eventValue.split(','); + for (let i = 0; i < values.length; i++) { + let appName = appNameList[i]; + let obj = dataItem[appName]; + if (obj !== undefined) { + let eventName = name.split('_'); + let s = eventName[eventName.length - 1].toLocaleLowerCase(); + if (obj[s] === undefined) { + obj[s] = parseInt(values[i]); } else { - maxStateTotal = 'disable'; - } - } else if(statType.includes('sensor')) { - if (statType.includes('enable')) { - maxStateTotal = 'enable'; - } else { - maxStateTotal = 'disable'; - } - } - let stateTraceRow = TraceRow.skeleton(); - stateTraceRow.rowParentId = `energy`; - stateTraceRow.rowHidden = true; - stateTraceRow.rowId = `energy-state-${this.stateList[index]}`; - stateTraceRow.rowType = TraceRow.ROW_TYPE_STATE_ENERGY; - stateTraceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; - stateTraceRow.selectChangeHandler = this.trace.selectChangeHandler; - stateTraceRow.style.height = '40px'; - stateTraceRow.style.width = `100%`; - stateTraceRow.setAttribute('children', ''); - stateTraceRow.name = `${this.stateList[index]}`; - stateTraceRow.supplierFrame = () => { - return hiSysEnergyStateSender(this.stateName, index, stateTraceRow).then((res) => { - let stateInitValue = this.initValueList[index] == 'nocolumn' ? [] : stateResult; - for (let i = 0; i < res.length; i++) { - let item = res[i]; - item.type = this.stateName[index]; - } - return stateInitValue.concat(res); - }); - }; - stateTraceRow.focusHandler = () => { - let tip = ''; - if (EnergyStateStruct.hoverEnergyStateStruct?.type!.toLocaleLowerCase().includes('state')) { - tip = `Switch Status: ${ - EnergyStateStruct.hoverEnergyStateStruct?.value == 1 ? 'disable' : 'enable' - }`; - if (EnergyStateStruct.hoverEnergyStateStruct?.type!.toLocaleLowerCase().endsWith('br_switch_state')) { - tip = `${SpHiSysEnergyChart.getBlueToothState( - EnergyStateStruct.hoverEnergyStateStruct?.value - )}`; - } - } else { - tip = `value: ${EnergyStateStruct.hoverEnergyStateStruct?.value?.toFixed(2) || 0}`; - } - this.trace?.displayTip(stateTraceRow, EnergyStateStruct.hoverEnergyStateStruct, tip); - }; - stateTraceRow.onThreadHandler = (useCache) => { - let context: CanvasRenderingContext2D; - if (stateTraceRow.currentContext) { - context = stateTraceRow.currentContext; - } else { - context = stateTraceRow.collect ? this.trace.canvasFavoritePanelCtx! : this.trace.canvasPanelCtx!; + obj[s] += parseInt(values[i]); } - stateTraceRow.canvasSave(context); - (renders['energyState'] as EnergyStateRender).renderMainThread( - { - context: context, - useCache: useCache, - type: `energyState${index}`, - maxState: maxStateData[0].maxValue, - maxStateName: maxStateData[0].type.toLocaleLowerCase().endsWith('br_switch_state') - ? '-1' - : maxStateTotal.toString(), - }, - stateTraceRow - ); - stateTraceRow.canvasRestore(context, this.trace); - }; - this.energyTraceRow?.addChildTraceRow(stateTraceRow); - let durTime = new Date().getTime() - time; - info('The time to load the Ability Memory is: ', durTime); + } } - }; + } public static getBlueToothState(num: number | undefined): string { switch (num) { @@ -549,7 +622,7 @@ export class SpHiSysEnergyChart { return 'STATE_TURN_ON'; case 2: return 'STATE_TURNING_OFF'; - case 3: + case NUM_3: return 'STATE_TURN_OFF'; default: return 'UNKNOWN_STATE'; diff --git a/ide/src/trace/component/chart/SpHiSysEventChart.ts b/ide/src/trace/component/chart/SpHiSysEventChart.ts index eb6b45e2736313b0ff9e31d197058f432b5cd7ff..0302323800900e51a90f31cb3a95f6e63b762c56 100644 --- a/ide/src/trace/component/chart/SpHiSysEventChart.ts +++ b/ide/src/trace/component/chart/SpHiSysEventChart.ts @@ -18,7 +18,7 @@ import { TraceRow } from '../trace/base/TraceRow'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { HiSysEventRender, HiSysEventStruct } from '../../database/ui-worker/ProcedureWorkerHiSysEvent'; import { hiSysEventDataSender } from '../../database/data-trafic/HiSysEventDataSender'; -import { queryHiSysEventData } from '../../database/SqlLite'; +import {queryHiSysEventData} from "../../database/sql/Perf.sql"; export class SpHiSysEventChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpIrqChart.ts b/ide/src/trace/component/chart/SpIrqChart.ts index b30b099479d186825f21429901ac001cd05dfce1..eb237f96325325641c10dd921303322bf0bd8fc8 100644 --- a/ide/src/trace/component/chart/SpIrqChart.ts +++ b/ide/src/trace/component/chart/SpIrqChart.ts @@ -15,12 +15,12 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; -import { queryAllFuncNames, queryAllIrqNames, queryIrqData, queryIrqList } from '../../database/SqlLite'; import { info } from '../../../log/Log'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { IrqRender, IrqStruct } from '../../database/ui-worker/ProcedureWorkerIrq'; import { irqDataSender } from '../../database/data-trafic/IrqDataSender'; +import {queryAllIrqNames, queryIrqList} from "../../database/sql/Irq.sql"; export class SpIrqChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpLogChart.ts b/ide/src/trace/component/chart/SpLogChart.ts index 305c826cfb82dc41b072f65612c7b4363675c1f4..bd946543f8640b74f4bca0128405969469b09f83 100644 --- a/ide/src/trace/component/chart/SpLogChart.ts +++ b/ide/src/trace/component/chart/SpLogChart.ts @@ -18,7 +18,7 @@ import { TraceRow } from '../trace/base/TraceRow'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { LogRender, LogStruct } from '../../database/ui-worker/ProcedureWorkerLog'; import { LogDataSender } from '../../database/data-trafic/LogDataSender'; -import {queryLogData} from "../../database/SqlLite"; +import {queryLogData} from "../../database/sql/SqlLite.sql"; export class SpLogChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpNativeMemoryChart.ts b/ide/src/trace/component/chart/SpNativeMemoryChart.ts index f51d7ad0c3a469e8f490a55e6cdaa092802928e1..e5e07d2f89bb25c0f8a819dd2c956a1eeae00fb1 100644 --- a/ide/src/trace/component/chart/SpNativeMemoryChart.ts +++ b/ide/src/trace/component/chart/SpNativeMemoryChart.ts @@ -14,13 +14,6 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - queryBootTime, - queryHeapGroupByEvent, - queryNativeHookProcess, - queryNativeHookStatisticsCount, - queryNativeMemoryRealTime, -} from '../../database/SqlLite'; import { TraceRow } from '../trace/base/TraceRow'; import { info } from '../../../log/Log'; import { procedurePool } from '../../database/Procedure'; @@ -28,12 +21,16 @@ import { type NativeEventHeap } from '../../bean/NativeHook'; import { HeapRender, HeapStruct } from '../../database/ui-worker/ProcedureWorkerHeap'; import { Utils } from '../trace/base/Utils'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { type BaseStruct } from '../../bean/BaseStruct'; import { nativeMemoryChartDataCacheSender, nativeMemoryChartDataSender, } from '../../database/data-trafic/NativeMemoryDataSender'; +import {queryNativeHookProcess, queryNativeHookStatisticsCount} from "../../database/sql/NativeHook.sql"; +import {queryHeapGroupByEvent} from "../../database/sql/SqlLite.sql"; +import {queryNativeMemoryRealTime} from "../../database/sql/Memory.sql"; +import {queryBootTime} from "../../database/sql/Clock.sql"; export class SpNativeMemoryChart { static EVENT_HEAP: Array = []; diff --git a/ide/src/trace/component/chart/SpProcessChart.ts b/ide/src/trace/component/chart/SpProcessChart.ts index c1eead3097dde5ae4957687b7ebc914b4aa7115c..11678c2fe8d04c295e151a785daa82162a825ac4 100644 --- a/ide/src/trace/component/chart/SpProcessChart.ts +++ b/ide/src/trace/component/chart/SpProcessChart.ts @@ -14,28 +14,6 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - getMaxDepthByTid, - queryAllFuncNames, - queryAllJankProcess, - queryAllProcessNames, - queryAllSoInitNames, - queryAllSrcSlices, - queryAllThreadName, - queryEventCountMap, - queryMemFilterIdMaxValue, - queryProcess, - queryProcessAsyncFunc, - queryProcessByTable, - queryProcessContentCount, - queryProcessMem, - queryProcessMemData, - queryProcessSoMaxDepth, - queryProcessThreads, - queryProcessThreadsByTable, - queryStartupPidArray, - queryTaskPoolProcessIds, -} from '../../database/SqlLite'; import { Utils } from '../trace/base/Utils'; import { info } from '../../../log/Log'; import { TraceRow } from '../trace/base/TraceRow'; @@ -51,15 +29,25 @@ import { AppStartupRender, AppStartupStruct } from '../../database/ui-worker/Pro import { SoRender, SoStruct } from '../../database/ui-worker/ProcedureWorkerSoInit'; import { FlagsConfig } from '../SpFlags'; import { JanksStruct } from '../../bean/JanksStruct'; -import { processDataSender } from '../../database/data-trafic/ProcessDataSender'; -import { threadDataSender } from '../../database/data-trafic/ThreadDataSender'; -import { funcDataSender } from '../../database/data-trafic/FuncDataSender'; -import { processMemDataSender } from '../../database/data-trafic/ProcessMemDataSender'; -import { processStartupDataSender } from '../../database/data-trafic/ProcessStartupDataSender'; -import { processSoInitDataSender } from '../../database/data-trafic/ProcessSoInitDataSender'; -import { processExpectedDataSender } from '../../database/data-trafic/ProcessExpectedDataSender'; -import { processActualDataSender } from '../../database/data-trafic/ProcessActualDataSender'; -import { processDeliverInputEventDataSender } from '../../database/data-trafic/ProcessDeliverInputEventDataSender'; +import { processDataSender } from '../../database/data-trafic/process/ProcessDataSender'; +import { threadDataSender } from '../../database/data-trafic/process/ThreadDataSender'; +import { funcDataSender } from '../../database/data-trafic/process/FuncDataSender'; +import { processMemDataSender } from '../../database/data-trafic/process/ProcessMemDataSender'; +import { processStartupDataSender } from '../../database/data-trafic/process/ProcessStartupDataSender'; +import { processSoInitDataSender } from '../../database/data-trafic/process/ProcessSoInitDataSender'; +import { processExpectedDataSender } from '../../database/data-trafic/process/ProcessExpectedDataSender'; +import { processActualDataSender } from '../../database/data-trafic/process/ProcessActualDataSender'; +import { processDeliverInputEventDataSender } from '../../database/data-trafic/process/ProcessDeliverInputEventDataSender'; +import {getMaxDepthByTid, queryAllFuncNames, queryProcessAsyncFunc} from "../../database/sql/Func.sql"; +import {queryMemFilterIdMaxValue} from "../../database/sql/Memory.sql"; +import {queryAllSoInitNames, queryAllSrcSlices, queryEventCountMap} from "../../database/sql/SqlLite.sql"; +import { + queryAllProcessNames, + queryAllThreadName, queryProcess, queryProcessByTable, + queryProcessContentCount, queryProcessMem, queryProcessSoMaxDepth, + queryProcessThreads, queryProcessThreadsByTable, queryStartupPidArray, queryTaskPoolProcessIds +} from "../../database/sql/ProcessThread.sql"; +import {queryAllJankProcess} from "../../database/sql/Janks.sql"; export class SpProcessChart { private readonly trace: SpSystemTrace; diff --git a/ide/src/trace/component/chart/SpSdkChart.ts b/ide/src/trace/component/chart/SpSdkChart.ts index 2927e664d9b7b46f89c30a256fb109e359c52723..5fb96f035e652c72327a8d31d38949af0526942f 100644 --- a/ide/src/trace/component/chart/SpSdkChart.ts +++ b/ide/src/trace/component/chart/SpSdkChart.ts @@ -17,97 +17,107 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; import { BaseStruct } from '../../bean/BaseStruct'; -import { - queryCounterMax, - querySdkCount, - querySdkCounterData, - querySdkSliceData, - queryStartTime, -} from '../../database/SqlLite'; import { CounterStruct, SdkCounterRender } from '../../database/ui-worker/ProduceWorkerSdkCounter'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { SdkSliceRender, SdkSliceStruct } from '../../database/ui-worker/ProduceWorkerSdkSlice'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { TabUtil } from '../trace/sheet/sdk/TabUtil'; +import { + queryCounterMax, + querySdkCount, + querySdkCounterData, + querySdkSliceData +} from '../../database/sql/Sdk.sql'; +import { queryStartTime } from '../../database/sql/SqlLite.sql'; +import { NUM_7 } from '../../bean/NumBean'; export class SpSdkChart { - private trace: SpSystemTrace; + trace: SpSystemTrace; private pluginName = 'dubai-plugin'; constructor(trace: SpSystemTrace) { this.trace = trace; } - parseJson(startTime: number, map: Map) { + private parseJsonByCounterType(startTime: number, showType: any, configObj: any, table: any): void { + let chartSql = this.createSql( + startTime, + showType.tableName, + showType.columns, + 'where counter_id' + ' = $counter_id' + ); + let maxValue = this.createMaxValueSql(showType.tableName, 'where counter_id = $counter_id'); + let innerTable = showType.inner; + let countSql = this.createSql(startTime, innerTable.tableName, innerTable.columns); + table.push({ + countSql: countSql, + chartSql: chartSql, + maxSql: maxValue, + type: 'counter', + name: configObj.disPlayName, + pluginName: configObj.pluginName, + }); + } + + private parseJsonBySliceType(startTime: number, showType: any, configObj: any, table: any[]): void { + let chartSql = this.createSliceSql( + startTime, + showType.tableName, + showType.columns, + 'where' + ` slice_id = $column_id and (start_ts - ${ startTime }) between $startNS and $endNS;` + ); + let innerTable = showType.inner; + let countSql; + let countOtherSql = ''; + if (configObj.pluginName === this.pluginName) { + countSql = this.createSql( + startTime, + innerTable.tableName, + innerTable.columns, + 'where slice_name like $suffix' + ); + countOtherSql = this.createSql( + startTime, + innerTable.tableName, + innerTable.columns, + '' + + 'where slice_name not like \'%_cpu\' and slice_name not like \'%_display\' and ' + + 'slice_name not like \'%_gpu\' and slice_name not like \'%_System_idle\' and ' + + 'slice_name not like \'%_wifi_data\' and slice_name not like \'%_sensor\' and ' + + 'slice_name not like \'%_audio\' ' + ); + } else { + countSql = this.createSql(startTime, innerTable.tableName, innerTable.columns); + } + table.push({ + countSql: countSql, + chartSql: chartSql, + type: 'slice', + name: configObj.disPlayName, + pluginName: configObj.pluginName, + countOtherSql: countOtherSql, + }); + } + + parseJson(startTime: number, map: Map): Map{ let tablesMap = new Map(); let keys = map.keys(); for (let key of keys) { - let table = []; + let table: any[] = []; let configObj: any = map.get(key); - if (configObj != undefined) { + if (configObj !== undefined) { let configStr = configObj.jsonConfig; let json = JSON.parse(configStr); let tableConfig = json.tableConfig; - if (tableConfig != null) { + if (tableConfig !== null) { let showTypes = tableConfig.showType; for (let i = 0; i < showTypes.length; i++) { let showType = showTypes[i]; let type = TabUtil.getTableType(showType); - if (type == 'counter') { - let chartSql = this.createSql( - startTime, - showType.tableName, - showType.columns, - 'where counter_id' + ' = $counter_id' - ); - let maxValue = this.createMaxValueSql(showType.tableName, 'where counter_id = $counter_id'); - let innerTable = showType.inner; - let countSql = this.createSql(startTime, innerTable.tableName, innerTable.columns); - table.push({ - countSql: countSql, - chartSql: chartSql, - maxSql: maxValue, - type: 'counter', - name: configObj.disPlayName, - pluginName: configObj.pluginName, - }); - } else if (type == 'slice') { - let chartSql = this.createSliceSql( - startTime, - showType.tableName, - showType.columns, - 'where' + ' slice_id = $column_id and (start_ts - ' + startTime + ') between $startNS and $endNS;' - ); - let innerTable = showType.inner; - let countSql; - let countOtherSql = ''; - if (configObj.pluginName == this.pluginName) { - countSql = this.createSql( - startTime, - innerTable.tableName, - innerTable.columns, - 'where slice_name like $suffix' - ); - countOtherSql = this.createSql( - startTime, - innerTable.tableName, - innerTable.columns, - '' + - "where slice_name not like '%_cpu' and slice_name not like '%_display' and slice_name not like '%_gpu'" + - "and slice_name not like '%_System_idle' and slice_name not like '%_wifi_data' " + - "and slice_name not like '%_sensor' and slice_name not like '%_audio' " - ); - } else { - countSql = this.createSql(startTime, innerTable.tableName, innerTable.columns); - } - table.push({ - countSql: countSql, - chartSql: chartSql, - type: 'slice', - name: configObj.disPlayName, - pluginName: configObj.pluginName, - countOtherSql: countOtherSql, - }); + if (type === 'counter') { + this.parseJsonByCounterType(startTime, showType, configObj, table); + } else if (type === 'slice') { + this.parseJsonBySliceType(startTime, showType, configObj, table); } } tablesMap.set(key, table); @@ -121,29 +131,29 @@ export class SpSdkChart { let sliceSelectSql = 'select '; for (let i = 0; i < columns.length; i++) { let column = columns[i]; - if (column.column == 'start_ts') { - column.column = '(start_ts - ' + startTime + ') AS start_ts'; + if (column.column === 'start_ts') { + column.column = `(start_ts - ${ startTime }) AS start_ts`; } - if (column.column == 'end_ts') { - column.column = '(end_ts - ' + startTime + ') AS end_ts'; + if (column.column === 'end_ts') { + column.column = `(end_ts - ${ startTime }) AS end_ts`; } - if (i == columns.length - 1) { - sliceSelectSql = sliceSelectSql + column.column + ' '; + if (i === columns.length - 1) { + sliceSelectSql = `${sliceSelectSql + column.column } `; } else { - sliceSelectSql = sliceSelectSql + column.column + ', '; + sliceSelectSql = `${sliceSelectSql + column.column }, `; } } - sliceSelectSql = sliceSelectSql + 'from ' + tableName; - if (where != undefined) { - sliceSelectSql = sliceSelectSql + ' ' + where; + sliceSelectSql = `${sliceSelectSql }from ${ tableName}`; + if (where !== undefined) { + sliceSelectSql = `${sliceSelectSql } ${ where}`; } return sliceSelectSql; } private createMaxValueSql(tableName: string, where?: string): string { - let selectSql = 'select max(value) as max_value from ' + tableName; - if (where != undefined) { - selectSql = selectSql + ' ' + where; + let selectSql = `select max(value) as max_value from ${ tableName}`; + if (where !== undefined) { + selectSql = `${selectSql } ${ where}`; } return selectSql; } @@ -152,44 +162,44 @@ export class SpSdkChart { let selectSql = 'select '; for (let i = 0; i < columns.length; i++) { let column = columns[i]; - if (column.column == 'ts') { - column.column = 'ts - ' + startTime + ' AS ts'; + if (column.column === 'ts') { + column.column = `ts - ${ startTime } AS ts`; } - if (i == columns.length - 1) { - selectSql = selectSql + column.column + ' '; + if (i === columns.length - 1) { + selectSql = `${selectSql + column.column } `; } else { - selectSql = selectSql + column.column + ', '; + selectSql = `${selectSql + column.column }, `; } } - selectSql = selectSql + 'from ' + tableName; - if (where != undefined) { - selectSql = selectSql + ' ' + where; + selectSql = `${selectSql }from ${ tableName}`; + if (where !== undefined) { + selectSql = `${selectSql } ${ where}`; } return selectSql; } - async init() { + async init(): Promise { let configMap = SpSystemTrace.SDK_CONFIG_MAP; - if (configMap == undefined) return; + if (configMap === undefined) {return} let res = await queryStartTime(); let startTime = res[0].start_ts; let tablesMap = this.parseJson(startTime, configMap); let tableKeys = tablesMap.keys(); for (let componentId of tableKeys) { let table = tablesMap.get(componentId); - if (table != null) { + if (table !== null) { let nodeRow = this.initNodeRow(componentId, table[0].name); for (let index = 0; index < table.length; index++) { let sqlMap = table[index]; - if (sqlMap.type == 'counter') { + if (sqlMap.type === 'counter') { let result = await querySdkCount(sqlMap.countSql, componentId); for (let i = 0; i < result.length; i++) { await this.initCounter(nodeRow, i, result[i], sqlMap, componentId); } - } else if (sqlMap.type == 'slice' && sqlMap.pluginName == this.pluginName) { + } else if (sqlMap.type === 'slice' && sqlMap.pluginName === this.pluginName) { let suffixList = ['cpu', 'display', 'gpu', 'System_idle', 'wifi_data', 'sensor', 'audio']; for (let i = 0; i < suffixList.length; i++) { - let result = await querySdkCount(sqlMap.countSql, componentId, { $suffix: '%' + suffixList[i] }); + let result = await querySdkCount(sqlMap.countSql, componentId, {$suffix: `%${ suffixList[i]}`}); if (result.length > 0) { let groupNodeRow = await this.initSecondaryRow(nodeRow, i, suffixList[i]); for (let i = 0; i < result.length; i++) { @@ -199,12 +209,12 @@ export class SpSdkChart { } let result = await querySdkCount(sqlMap.countOtherSql, componentId); if (result.length > 0) { - let groupNodeRow = await this.initSecondaryRow(nodeRow, 7, 'other'); + let groupNodeRow = await this.initSecondaryRow(nodeRow, NUM_7, 'other'); for (let i = 0; i < result.length; i++) { await this.initSlice(groupNodeRow, i, result[i], sqlMap, componentId); } } - } else if (sqlMap.type == 'slice') { + } else if (sqlMap.type === 'slice') { let result = await querySdkCount(sqlMap.countSql, componentId, {}); for (let i = 0; i < result.length; i++) { await this.initSlice(nodeRow, i, result[i], sqlMap, componentId); @@ -214,40 +224,51 @@ export class SpSdkChart { } } } - - private initCounter = async ( - nodeRow: TraceRow, - index: number, - result: any, - sqlMap: any, - componentId: number - ) => { + + private initCounterChartRow( + componentId: number, + expansion: boolean, + counterId: string, + counterName: string + ): TraceRow { let traceRow = TraceRow.skeleton(); traceRow.rowParentId = `Sdk-${componentId}`; - traceRow.rowHidden = !nodeRow.expansion; - traceRow.rowId = result.counter_id + '-' + componentId; + traceRow.rowHidden = !expansion; + traceRow.rowId = `${counterId }-${ componentId}`; traceRow.rowType = TraceRow.ROW_TYPE_SDK_COUNTER; traceRow.folderPaddingLeft = 30; traceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; traceRow.selectChangeHandler = this.trace.selectChangeHandler; traceRow.style.height = '40px'; - traceRow.style.width = `100%`; + traceRow.style.width = '100%'; traceRow.setAttribute('children', ''); - traceRow.name = `${result.counter_name}`; - traceRow.supplier = () => querySdkCounterData(sqlMap.chartSql, result.counter_id, componentId); - traceRow.focusHandler = () => { + traceRow.name = `${counterName}`; + return traceRow; + } + + private initCounter = async ( + nodeRow: TraceRow, + index: number, + result: any, + sqlMap: any, + componentId: number + ): Promise => { + let traceRow = this.initCounterChartRow(componentId, nodeRow.expansion, result.counter_id, result.counter_name); + traceRow.supplier = async (): Promise => + querySdkCounterData(sqlMap.chartSql, result.counter_id, componentId); + traceRow.focusHandler = (): void => { this.trace?.displayTip( traceRow, CounterStruct.hoverCounterStruct, `${CounterStruct.hoverCounterStruct?.value?.toFixed(2)}` ); }; - traceRow.findHoverStruct = () => { + traceRow.findHoverStruct = (): void => { CounterStruct.hoverCounterStruct = traceRow.getHoverStruct(); }; let maxList = await queryCounterMax(sqlMap.maxSql, result.counter_id, componentId); let maxCounter = maxList[0].max_value; - traceRow.onThreadHandler = (useCache) => { + traceRow.onThreadHandler = (useCache: boolean): void => { let context: CanvasRenderingContext2D; if (traceRow.currentContext) { context = traceRow.currentContext; @@ -270,7 +291,7 @@ export class SpSdkChart { nodeRow.addChildTraceRow(traceRow); }; - private initNodeRow = (index: number, name: string) => { + private initNodeRow = (index: number, name: string): TraceRow => { let sdkFolder = TraceRow.skeleton(); sdkFolder.rowId = `Sdk-${index}`; sdkFolder.index = index; @@ -281,17 +302,17 @@ export class SpSdkChart { sdkFolder.name = `${name}`; sdkFolder.favoriteChangeHandler = this.trace.favoriteChangeHandler; sdkFolder.selectChangeHandler = this.trace.selectChangeHandler; - sdkFolder.supplier = () => new Promise>((resolve) => resolve([])); - sdkFolder.onThreadHandler = (useCache) => { + sdkFolder.supplier = async (): Promise => new Promise<[]>((resolve) => resolve([])); + sdkFolder.onThreadHandler = (useCache: boolean): void => { sdkFolder.canvasSave(this.trace.canvasPanelCtx!); if (sdkFolder.expansion) { this.trace.canvasPanelCtx?.clearRect(0, 0, sdkFolder.frame.width, sdkFolder.frame.height); } else { - (renders['empty'] as EmptyRender).renderMainThread( + (renders.empty as EmptyRender).renderMainThread( { context: this.trace.canvasPanelCtx, useCache: useCache, - type: ``, + type: '', }, sdkFolder ); @@ -302,7 +323,11 @@ export class SpSdkChart { return sdkFolder; }; - private initSecondaryRow = async (nodeRow: TraceRow, index: number, name: string) => { + private initSecondaryRow = async ( + nodeRow: TraceRow, + index: number, + name: string + ): Promise> => { let sdkSecondFolder = TraceRow.skeleton(); sdkSecondFolder.rowId = `Sdk-${name}-${index}`; sdkSecondFolder.index = index; @@ -315,17 +340,17 @@ export class SpSdkChart { sdkSecondFolder.name = `${name}`; sdkSecondFolder.favoriteChangeHandler = this.trace.favoriteChangeHandler; sdkSecondFolder.selectChangeHandler = this.trace.selectChangeHandler; - sdkSecondFolder.supplier = () => new Promise>((resolve) => resolve([])); - sdkSecondFolder.onThreadHandler = (useCache) => { + sdkSecondFolder.supplier = async (): Promise => new Promise<[]>((resolve) => resolve([])); + sdkSecondFolder.onThreadHandler = (useCache: boolean): void => { sdkSecondFolder.canvasSave(this.trace.canvasPanelCtx!); if (sdkSecondFolder.expansion) { this.trace.canvasPanelCtx?.clearRect(0, 0, sdkSecondFolder.frame.width, sdkSecondFolder.frame.height); } else { - (renders['empty'] as EmptyRender).renderMainThread( + (renders.empty as EmptyRender).renderMainThread( { context: this.trace.canvasPanelCtx, useCache: useCache, - type: ``, + type: '', }, sdkSecondFolder ); @@ -335,27 +360,39 @@ export class SpSdkChart { this.trace.rowsEL?.appendChild(sdkSecondFolder); return sdkSecondFolder; }; - - private initSlice = async ( - nodeRow: TraceRow, - index: number, - result: any, - sqlMap: any, + + private initSliceChartRow( + expansion: boolean, + rowId: string, + sliceId: string, + sliceName: string, componentId: number - ) => { + ): TraceRow { let traceRow = TraceRow.skeleton(); traceRow.rowType = TraceRow.ROW_TYPE_SDK_SLICE; - traceRow.rowHidden = !nodeRow.expansion; - traceRow.rowParentId = nodeRow.rowId; + traceRow.rowHidden = !expansion; + traceRow.rowParentId = rowId; traceRow.folderPaddingLeft = 30; traceRow.style.height = '40px'; - traceRow.style.width = `100%`; - traceRow.name = `${result.slice_name}`; + traceRow.style.width = '100%'; + traceRow.name = `${sliceName}`; traceRow.setAttribute('children', ''); traceRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; traceRow.selectChangeHandler = this.trace.selectChangeHandler; - traceRow.rowId = result.slice_id + '-' + componentId; - traceRow.supplier = () => + traceRow.rowId = `${sliceId }-${ componentId}`; + return traceRow; + } + + private initSlice = async ( + nodeRow: TraceRow, + index: number, + result: any, + sqlMap: any, + componentId: number + ): Promise => { + let traceRow = this.initSliceChartRow(nodeRow.expansion, nodeRow.rowId!, + result.slice_id, result.slice_name, componentId); + traceRow.supplier = async () : Promise=> querySdkSliceData( sqlMap.chartSql, result.slice_id, @@ -363,17 +400,17 @@ export class SpSdkChart { TraceRow.range?.endNS || 0, componentId ); - traceRow.focusHandler = () => { + traceRow.focusHandler = (): void => { this.trace?.displayTip( traceRow, SdkSliceStruct.hoverSdkSliceStruct, `${SdkSliceStruct.hoverSdkSliceStruct?.value}` ); }; - traceRow.findHoverStruct = () => { + traceRow.findHoverStruct = (): void => { SdkSliceStruct.hoverSdkSliceStruct = traceRow.getHoverStruct(); }; - traceRow.onThreadHandler = (useCache: boolean) => { + traceRow.onThreadHandler = (useCache: boolean): void => { let context: CanvasRenderingContext2D; if (traceRow.currentContext) { context = traceRow.currentContext; diff --git a/ide/src/trace/component/chart/SpSegmentationChart.ts b/ide/src/trace/component/chart/SpSegmentationChart.ts index caec30bfa5da2190c285598cf2be611ed6a28136..9def972a74f03413330cb1d41fd915747ef91bf2 100644 --- a/ide/src/trace/component/chart/SpSegmentationChart.ts +++ b/ide/src/trace/component/chart/SpSegmentationChart.ts @@ -13,14 +13,18 @@ * limitations under the License. */ -import { SpSystemTrace } from '../SpSystemTrace'; +import { type SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; -import { FreqExtendRender, CpuFreqExtendStruct } from '../../database/ui-worker/ProcedureWorkerFreqExtend'; -import { BinderRender, BinderStruct } from '../../database/ui-worker/procedureWorkerBinder'; -import { queryIrqList } from '../../database/SqlLite'; -import { BaseStruct } from '../../bean/BaseStruct'; +import { type EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { type FreqExtendRender, CpuFreqExtendStruct } from '../../database/ui-worker/ProcedureWorkerFreqExtend'; +import { type BinderRender, BinderStruct } from '../../database/ui-worker/procedureWorkerBinder'; +import { queryIrqList } from '../../database/sql/Irq.sql'; +import { type BaseStruct } from '../../bean/BaseStruct'; + +const UNIT_HEIGHT: number = 20; +const MS_TO_US: number = 1000000; +const MIN_HEIGHT: number = 2; export class SpSegmentationChart { static trace: SpSystemTrace; static jsonRow: TraceRow | undefined; @@ -52,13 +56,12 @@ export class SpSegmentationChart { chartData = binderList.map((v: BinderDataStruct) => { return { cpu: - v.name === 'binder transaction' - ? 0 - : v.name === 'binder transaction async' - ? 1 - : v.name === 'binder reply' - ? 2 - : 3, + v.name === 'binder transaction' ? + 0 : + v.name === 'binder transaction async' ? + 1 : + v.name === 'binder reply' ? + MS_TO_US : 3, startNS: v.startNS, dur: v.dur, name: `${v.name}`, @@ -67,14 +70,13 @@ export class SpSegmentationChart { cycle: v.idx, idx: v.idx, count: v.count, - }; - }); + } + }) SpSegmentationChart.binderRow!.dataList = []; SpSegmentationChart.binderRow!.dataListCache = []; SpSegmentationChart.binderRow!.isComplete = false; - SpSegmentationChart.binderRow!.style.height = `${ - BinderStruct.maxHeight > 2 ? BinderStruct.maxHeight * 20 + 20 : 40 - }px`; + SpSegmentationChart.binderRow!.style.height = `${BinderStruct.maxHeight > MS_TO_US ? BinderStruct.maxHeight * UNIT_HEIGHT + UNIT_HEIGHT : 40 + }px`; // @ts-ignore SpSegmentationChart.binderRow!.supplier = (): Promise> => new Promise>((resolve) => resolve(chartData)); @@ -108,7 +110,7 @@ export class SpSegmentationChart { async init() { let irqList = await queryIrqList(); - if (irqList.length == 0) { + if (irqList.length === 0) { return; } else { await this.initFolder(); @@ -122,15 +124,15 @@ export class SpSegmentationChart { async initFolder() { let row = TraceRow.skeleton(); row.setAttribute('disabled-check', ''); - row.rowId = `unkown`; + row.rowId = 'segmentation'; row.index = 0; row.rowType = TraceRow.ROW_TYPE_SPSEGNENTATION; row.rowParentId = ''; row.folder = true; row.style.height = '40px'; - row.name = `Segmentation`; - row.supplier = () => new Promise>((resolve) => resolve([])); - row.onThreadHandler = (useCache) => { + row.name = 'Segmentation'; + row.supplier = (): Promise> => new Promise>((resolve) => resolve([])); + row.onThreadHandler = (useCache): void => { row.canvasSave(SpSegmentationChart.trace.canvasPanelCtx!); if (row.expansion) { SpSegmentationChart.trace.canvasPanelCtx?.clearRect(0, 0, row.frame.width, row.frame.height); @@ -139,13 +141,13 @@ export class SpSegmentationChart { { context: SpSegmentationChart.trace.canvasPanelCtx, useCache: useCache, - type: ``, + type: '', }, row ); } row.canvasRestore(SpSegmentationChart.trace.canvasPanelCtx!); - }; + } this.rowFolder = row; SpSegmentationChart.trace.rowsEL?.appendChild(row); } @@ -153,16 +155,16 @@ export class SpSegmentationChart { async initCpuFreq() { // json文件泳道 SpSegmentationChart.jsonRow = TraceRow.skeleton(); - SpSegmentationChart.jsonRow.rowId = `json0`; + SpSegmentationChart.jsonRow.rowId = 'cpu-freq'; SpSegmentationChart.jsonRow.rowType = TraceRow.ROW_TYPE_CPU_COMPUTILITY; SpSegmentationChart.jsonRow.rowParentId = ''; SpSegmentationChart.jsonRow.style.height = '40px'; - SpSegmentationChart.jsonRow.name = `Cpu Computility`; + SpSegmentationChart.jsonRow.name = 'Cpu Computility'; SpSegmentationChart.jsonRow.favoriteChangeHandler = SpSegmentationChart.trace.favoriteChangeHandler; SpSegmentationChart.jsonRow.addRowCheckFilePop(); SpSegmentationChart.jsonRow.rowSetting = 'checkFile'; // 拿到了用户传递的数据 - SpSegmentationChart.jsonRow.onRowCheckFileChangeHandler = (e: string | ArrayBuffer | null) => { + SpSegmentationChart.jsonRow.onRowCheckFileChangeHandler = (e: string | ArrayBuffer | null): void => { // @ts-ignore let chartData = JSON.parse(e); let mapData = new Map(); @@ -170,204 +172,203 @@ export class SpSegmentationChart { chartData.map((v) => { for (let key in v.freqInfo) { mapData.set(Number(key), Number(v.freqInfo[key])); - } + }; SpSegmentationChart.freqInfoMapData.set(v.cpuId, mapData); mapData = new Map(); - }); - }; - SpSegmentationChart.jsonRow.focusHandler = (ev) => { + }) + } + SpSegmentationChart.jsonRow.focusHandler = (ev): void => { SpSegmentationChart.trace?.displayTip( SpSegmentationChart.jsonRow!, CpuFreqExtendStruct.hoverCpuFreqStruct, - `${ - CpuFreqExtendStruct.hoverCpuFreqStruct === undefined ? 0 : CpuFreqExtendStruct.hoverCpuFreqStruct.value! + `${CpuFreqExtendStruct.hoverCpuFreqStruct === undefined ? 0 : CpuFreqExtendStruct.hoverCpuFreqStruct.value! }` - ); - }; - SpSegmentationChart.jsonRow.findHoverStruct = () => { + ) + } + SpSegmentationChart.jsonRow.findHoverStruct = (): void => { CpuFreqExtendStruct.hoverCpuFreqStruct = SpSegmentationChart.jsonRow!.getHoverStruct(); - }; + } // @ts-ignore SpSegmentationChart.jsonRow.supplier = (): Promise> => new Promise>((resolve) => resolve([])); - SpSegmentationChart.jsonRow.onThreadHandler = (useCache) => { + SpSegmentationChart.jsonRow.onThreadHandler = (useCache): void => { let context: CanvasRenderingContext2D; if (SpSegmentationChart.jsonRow!.currentContext) { context = SpSegmentationChart.jsonRow!.currentContext; } else { - context = SpSegmentationChart.jsonRow!.collect - ? SpSegmentationChart.trace.canvasFavoritePanelCtx! - : SpSegmentationChart.trace.canvasPanelCtx!; + context = SpSegmentationChart.jsonRow!.collect ? + SpSegmentationChart.trace.canvasFavoritePanelCtx! : + SpSegmentationChart.trace.canvasPanelCtx!; } SpSegmentationChart.jsonRow!.canvasSave(context); (renders['freq-extend'] as FreqExtendRender).renderMainThread( { context: context, useCache: useCache, - type: `json0`, + type: 'cpu-freq', }, SpSegmentationChart.jsonRow! - ); + ) SpSegmentationChart.jsonRow!.canvasRestore(context); - }; + } SpSegmentationChart.trace.rowsEL?.appendChild(SpSegmentationChart.jsonRow); this.rowFolder!.addChildTraceRow(SpSegmentationChart.jsonRow); } async initGpuTrace() { SpSegmentationChart.GpuRow = TraceRow.skeleton(); - SpSegmentationChart.GpuRow.rowId = `gpurow`; + SpSegmentationChart.GpuRow.rowId = 'gpurow'; SpSegmentationChart.GpuRow.rowType = TraceRow.ROW_TYPE_GPU_COMPUTILITY; SpSegmentationChart.GpuRow.rowParentId = ''; SpSegmentationChart.GpuRow.style.height = '40px'; - SpSegmentationChart.GpuRow.name = `Gpu Computility`; + SpSegmentationChart.GpuRow.name = 'Gpu Computility'; SpSegmentationChart.GpuRow.favoriteChangeHandler = SpSegmentationChart.trace.favoriteChangeHandler; SpSegmentationChart.GpuRow.selectChangeHandler = SpSegmentationChart.trace.selectChangeHandler; // @ts-ignore SpSegmentationChart.GpuRow.supplier = (): Promise> => new Promise>((resolve) => resolve([])); - SpSegmentationChart.GpuRow.focusHandler = (ev) => { + SpSegmentationChart.GpuRow.focusHandler = (ev): void => { SpSegmentationChart.trace?.displayTip( SpSegmentationChart.GpuRow!, CpuFreqExtendStruct.hoverCpuFreqStruct, - `${ - CpuFreqExtendStruct.hoverCpuFreqStruct === undefined ? 0 : CpuFreqExtendStruct.hoverCpuFreqStruct.value! + `${CpuFreqExtendStruct.hoverCpuFreqStruct === undefined ? 0 : CpuFreqExtendStruct.hoverCpuFreqStruct.value! }` ); - }; - SpSegmentationChart.GpuRow.findHoverStruct = () => { + } + SpSegmentationChart.GpuRow.findHoverStruct = (): void => { CpuFreqExtendStruct.hoverCpuFreqStruct = SpSegmentationChart.GpuRow!.getHoverStruct(); - }; - SpSegmentationChart.GpuRow.onThreadHandler = (useCache) => { + } + SpSegmentationChart.GpuRow.onThreadHandler = (useCache): void => { let context: CanvasRenderingContext2D; if (SpSegmentationChart.GpuRow!.currentContext) { context = SpSegmentationChart.GpuRow!.currentContext; } else { - context = SpSegmentationChart.GpuRow!.collect - ? SpSegmentationChart.trace.canvasFavoritePanelCtx! - : SpSegmentationChart.trace.canvasPanelCtx!; + context = SpSegmentationChart.GpuRow!.collect ? + SpSegmentationChart.trace.canvasFavoritePanelCtx! : + SpSegmentationChart.trace.canvasPanelCtx!; } SpSegmentationChart.GpuRow!.canvasSave(context); (renders['freq-extend'] as FreqExtendRender).renderMainThread( { context: context, useCache: useCache, - type: `json1`, + type: 'gpu-freq', }, SpSegmentationChart.GpuRow! - ); + ) SpSegmentationChart.GpuRow!.canvasRestore(context); - }; + } SpSegmentationChart.trace.rowsEL?.appendChild(SpSegmentationChart.GpuRow); this.rowFolder!.addChildTraceRow(SpSegmentationChart.GpuRow); } async initSchedTrace() { SpSegmentationChart.schedRow = TraceRow.skeleton(); - SpSegmentationChart.schedRow.rowId = `sched_switch Count`; + SpSegmentationChart.schedRow.rowId = 'sched_switch Count'; SpSegmentationChart.schedRow.rowType = TraceRow.ROW_TYPE_SCHED_SWITCH; SpSegmentationChart.schedRow.rowParentId = ''; SpSegmentationChart.schedRow.style.height = '40px'; - SpSegmentationChart.schedRow.name = `Sched_switch Count`; + SpSegmentationChart.schedRow.name = 'Sched_switch Count'; SpSegmentationChart.schedRow.favoriteChangeHandler = SpSegmentationChart.trace.favoriteChangeHandler; SpSegmentationChart.schedRow.selectChangeHandler = SpSegmentationChart.trace.selectChangeHandler; - SpSegmentationChart.schedRow.focusHandler = (ev) => { + SpSegmentationChart.schedRow.focusHandler = (ev): void => { SpSegmentationChart.trace?.displayTip( SpSegmentationChart.schedRow!, CpuFreqExtendStruct.hoverCpuFreqStruct, `${CpuFreqExtendStruct.hoverCpuFreqStruct?.value!}` - ); - }; - SpSegmentationChart.schedRow.findHoverStruct = () => { + ) + } + SpSegmentationChart.schedRow.findHoverStruct = (): void => { CpuFreqExtendStruct.hoverCpuFreqStruct = SpSegmentationChart.schedRow!.getHoverStruct(); - }; + } // @ts-ignore SpSegmentationChart.schedRow.supplier = (): Promise> => new Promise>((resolve) => resolve([])); - SpSegmentationChart.schedRow.onThreadHandler = (useCache) => { + SpSegmentationChart.schedRow.onThreadHandler = (useCache): void => { let context: CanvasRenderingContext2D; if (SpSegmentationChart.schedRow!.currentContext) { context = SpSegmentationChart.schedRow!.currentContext; } else { - context = SpSegmentationChart.schedRow!.collect - ? SpSegmentationChart.trace.canvasFavoritePanelCtx! - : SpSegmentationChart.trace.canvasPanelCtx!; + context = SpSegmentationChart.schedRow!.collect ? + SpSegmentationChart.trace.canvasFavoritePanelCtx! : + SpSegmentationChart.trace.canvasPanelCtx!; } SpSegmentationChart.schedRow!.canvasSave(context); (renders['freq-extend'] as FreqExtendRender).renderMainThread( { context: context, useCache: useCache, - type: `json0`, + type: 'sched', }, SpSegmentationChart.schedRow! - ); + ) SpSegmentationChart.schedRow!.canvasRestore(context); - }; + } SpSegmentationChart.trace.rowsEL?.appendChild(SpSegmentationChart.schedRow); this.rowFolder!.addChildTraceRow(SpSegmentationChart.schedRow); } async initBinderTrace() { SpSegmentationChart.binderRow = TraceRow.skeleton(); - SpSegmentationChart.binderRow.rowId = `binderrow`; + SpSegmentationChart.binderRow.rowId = 'binderrow'; SpSegmentationChart.binderRow.rowType = TraceRow.ROW_TYPE_BINDER_COUNT; SpSegmentationChart.binderRow.rowParentId = ''; - SpSegmentationChart.binderRow.name = `Binder Count`; + SpSegmentationChart.binderRow.name = 'Binder Count'; SpSegmentationChart.binderRow.style.height = '40px'; SpSegmentationChart.binderRow.favoriteChangeHandler = SpSegmentationChart.trace.favoriteChangeHandler; SpSegmentationChart.binderRow.selectChangeHandler = SpSegmentationChart.trace.selectChangeHandler; - SpSegmentationChart.binderRow.findHoverStruct = () => { - BinderStruct.hoverCpuFreqStruct = SpSegmentationChart.binderRow!.dataListCache.find((v: BinderStruct) => { + SpSegmentationChart.binderRow.findHoverStruct = (): void => { + BinderStruct.hoverCpuFreqStruct = SpSegmentationChart.binderRow!.dataListCache.find((v: BinderStruct): BinderStruct => { if (SpSegmentationChart.binderRow!.isHover) { if ( v.frame!.x < SpSegmentationChart.binderRow!.hoverX && v.frame!.x + v.frame!.width > SpSegmentationChart.binderRow!.hoverX && - BinderStruct.maxHeight * 20 - v.depth * 20 + 20 < SpSegmentationChart.binderRow!.hoverY && - BinderStruct.maxHeight * 20 - v.depth * 20 + v.value * 20 + 20 > SpSegmentationChart.binderRow!.hoverY + BinderStruct.maxHeight * UNIT_HEIGHT - v.depth * UNIT_HEIGHT + UNIT_HEIGHT < SpSegmentationChart.binderRow!.hoverY && + BinderStruct.maxHeight * UNIT_HEIGHT - v.depth * UNIT_HEIGHT + v.value * UNIT_HEIGHT + UNIT_HEIGHT > SpSegmentationChart.binderRow!.hoverY ) { return v; + } else { + return new BinderStruct(); } + } else { + return new BinderStruct(); } - }); - }; + }) + } SpSegmentationChart.binderRow.supplier = (): Promise> => new Promise>((resolve) => resolve([])); - SpSegmentationChart.binderRow.onThreadHandler = (useCache) => { + SpSegmentationChart.binderRow.onThreadHandler = (useCache): void => { let context: CanvasRenderingContext2D; if (SpSegmentationChart.binderRow!.currentContext) { context = SpSegmentationChart.binderRow!.currentContext; } else { - context = SpSegmentationChart.binderRow!.collect - ? SpSegmentationChart.trace.canvasFavoritePanelCtx! - : SpSegmentationChart.trace.canvasPanelCtx!; + context = SpSegmentationChart.binderRow!.collect ? + SpSegmentationChart.trace.canvasFavoritePanelCtx! : + SpSegmentationChart.trace.canvasPanelCtx!; } SpSegmentationChart.binderRow!.canvasSave(context); (renders.binder as BinderRender).renderMainThread( { context: context, useCache: useCache, - type: `binder`, + type: 'binder', }, SpSegmentationChart.binderRow! - ); + ) SpSegmentationChart.binderRow!.canvasRestore(context); - }; - SpSegmentationChart.binderRow.focusHandler = (ev) => { + } + SpSegmentationChart.binderRow.focusHandler = (ev): void => { SpSegmentationChart.trace!.displayTip( SpSegmentationChart.binderRow!, BinderStruct.hoverCpuFreqStruct, - `Cycle: ${ - BinderStruct.hoverCpuFreqStruct ? BinderStruct.hoverCpuFreqStruct.cycle : 0 + `Cycle: ${BinderStruct.hoverCpuFreqStruct ? BinderStruct.hoverCpuFreqStruct.cycle : 0 }
- Name: ${ - BinderStruct.hoverCpuFreqStruct ? BinderStruct.hoverCpuFreqStruct.name : '' - }
- Count: ${ - BinderStruct.hoverCpuFreqStruct ? BinderStruct.hoverCpuFreqStruct.value : 0 - }` + Name: ${BinderStruct.hoverCpuFreqStruct ? BinderStruct.hoverCpuFreqStruct.name : '' + }
+ Count: ${BinderStruct.hoverCpuFreqStruct ? BinderStruct.hoverCpuFreqStruct.value : 0 + }` ); - }; + } SpSegmentationChart.trace.rowsEL?.appendChild(SpSegmentationChart.binderRow); this.rowFolder!.addChildTraceRow(SpSegmentationChart.binderRow); } @@ -407,8 +408,8 @@ function setCpuData(data: Array, currentMaxValue: number, t startNS: v.startNS, cycle: v.cycle, type, - }; - }); + } + }) CpuFreqExtendStruct.maxValue = currentMaxValue; SpSegmentationChart.jsonRow!.dataList = []; SpSegmentationChart.jsonRow!.dataListCache = []; @@ -426,13 +427,13 @@ function setGpuData(data: Array, currentMaxValue: number, t } return { cpu: 7, - dur: v.dur ? Number(v.dur * 1000000) : 0, + dur: v.dur ? Number(v.dur * MS_TO_US) : 0, value: Number(v.count), startNS: Number(v.startNS), cycle: Number(v.cycle), type, - }; - }); + } + }) CpuFreqExtendStruct.maxValue = currentMaxValue; SpSegmentationChart.GpuRow!.dataList = []; SpSegmentationChart.GpuRow!.dataListCache = []; @@ -449,23 +450,25 @@ function setSchedData(data: Array, currentMaxValue: number } return { cpu: 5, - dur: Number(v.duration) * 1000000, - value: v.count, - startNS: Number(v.cycleStartTime) * 1000000, + dur: Number(v.duration) * 100000, + value: Number(v.count), + startNS: Number(v.cycleStartTime) * MS_TO_US, cycle: v.cycle, type, - }; - }); + } + }) CpuFreqExtendStruct.maxValue = currentMaxValue!; SpSegmentationChart.schedRow!.dataList = []; SpSegmentationChart.schedRow!.dataListCache = []; SpSegmentationChart.schedRow!.isComplete = false; - SpSegmentationChart.schedRow!.supplier = (): Promise> => - new Promise>((resolve) => resolve(chartData)); + // @ts-ignore + SpSegmentationChart.schedRow!.supplier = (): Promise> => + new Promise>((resolve) => resolve(chartData)); } function setBinderData(data: Array>, binderList: Array): void { data.map((v: Array) => { + // 统计每一竖列的最大count let listCount = 0; v.map((t: BinderDataStruct) => { listCount += t.count; @@ -477,59 +480,59 @@ function setBinderData(data: Array>, binderList: Array { return i.name === 'binder transaction'; - }).length > 0 - ? v.filter((i: BinderDataStruct) => { - return i.name === 'binder transaction'; - })[0].count - : 0); + }).length > 0 ? + v.filter((i: BinderDataStruct) => { + return i.name === 'binder transaction'; + })[0].count : + 0); } if (t.name === 'binder reply') { t.depth = t.count + (v.filter((i: BinderDataStruct) => { return i.name === 'binder transaction'; - }).length > 0 - ? v.filter((i: BinderDataStruct) => { - return i.name === 'binder transaction'; - })[0].count - : 0) + + }).length > 0 ? + v.filter((i: BinderDataStruct) => { + return i.name === 'binder transaction'; + })[0].count : + 0) + (v.filter((i: BinderDataStruct) => { return i.name === 'binder transaction async'; - }).length > 0 - ? v.filter((i: BinderDataStruct) => { - return i.name === 'binder transaction async'; - })[0].count - : 0); + }).length > 0 ? + v.filter((i: BinderDataStruct) => { + return i.name === 'binder transaction async'; + })[0].count : + 0); } if (t.name === 'binder async rcv') { t.depth = t.count + (v.filter((i: BinderDataStruct) => { return i.name === 'binder transaction'; - }).length > 0 - ? v.filter((i: BinderDataStruct) => { - return i.name === 'binder transaction'; - })[0].count - : 0) + + }).length > 0 ? + v.filter((i: BinderDataStruct) => { + return i.name === 'binder transaction'; + })[0].count : + 0) + (v.filter((i: BinderDataStruct) => { return i.name === 'binder transaction async'; - }).length > 0 - ? v.filter((i: BinderDataStruct) => { - return i.name === 'binder transaction async'; - })[0].count - : 0) + + }).length > 0 ? + v.filter((i: BinderDataStruct) => { + return i.name === 'binder transaction async'; + })[0].count : + 0) + (v.filter((i: BinderDataStruct) => { return i.name === 'binder reply'; - }).length > 0 - ? v.filter((i: BinderDataStruct) => { - return i.name === 'binder reply'; - })[0].count - : 0); + }).length > 0 ? + v.filter((i: BinderDataStruct) => { + return i.name === 'binder reply'; + })[0].count : + 0); } binderList.push(t); - }); + }) BinderStruct.maxHeight = BinderStruct.maxHeight > listCount ? BinderStruct.maxHeight : JSON.parse(JSON.stringify(listCount)); listCount = 0; - }); + }) } diff --git a/ide/src/trace/component/chart/SpVirtualMemChart.ts b/ide/src/trace/component/chart/SpVirtualMemChart.ts index e04afa2124ad4d9ade576ab3245bfc296333f6e2..dc7a67f97f81e7ea7192b7fc471db1c44a41999b 100644 --- a/ide/src/trace/component/chart/SpVirtualMemChart.ts +++ b/ide/src/trace/component/chart/SpVirtualMemChart.ts @@ -15,45 +15,50 @@ import { SpSystemTrace } from '../SpSystemTrace'; import { TraceRow } from '../trace/base/TraceRow'; -import { queryVirtualMemory } from '../../database/SqlLite'; -import { VirtualMemoryRender, VirtualMemoryStruct } from '../../database/ui-worker/ProcedureWorkerVirtualMemory'; +import { + VirtualMemoryRender, + VirtualMemoryStruct +} from '../../database/ui-worker/ProcedureWorkerVirtualMemory'; import { renders } from '../../database/ui-worker/ProcedureWorker'; -import { EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { virtualMemoryDataSender } from '../../database/data-trafic/VirtualMemoryDataSender'; +import { queryVirtualMemory } from '../../database/sql/Memory.sql'; +import { NUM_16 } from '../../bean/NumBean'; +import { BaseStruct } from '../../bean/BaseStruct'; export class SpVirtualMemChart { - private trace: SpSystemTrace; + trace: SpSystemTrace; constructor(trace: SpSystemTrace) { this.trace = trace; } - async init() { + async init(): Promise { let array = await queryVirtualMemory(); - if (array.length == 0) { + if (array.length === 0) { return; } let vmFolder = TraceRow.skeleton(); - vmFolder.rowId = `VirtualMemory`; + vmFolder.rowId = 'VirtualMemory'; vmFolder.index = 0; vmFolder.rowType = TraceRow.ROW_TYPE_VIRTUAL_MEMORY_GROUP; vmFolder.rowParentId = ''; vmFolder.folder = true; - vmFolder.name = `Virtual Memory`; + vmFolder.name = 'Virtual Memory'; vmFolder.style.height = '40px'; vmFolder.favoriteChangeHandler = this.trace.favoriteChangeHandler; vmFolder.selectChangeHandler = this.trace.selectChangeHandler; - vmFolder.supplier = () => new Promise>((resolve) => resolve([])); - vmFolder.onThreadHandler = (useCache) => { + vmFolder.supplier = async (): Promise => new Promise<[]>((resolve) => resolve([])); + vmFolder.onThreadHandler = (useCache): void => { vmFolder.canvasSave(this.trace.canvasPanelCtx!); if (vmFolder.expansion) { this.trace.canvasPanelCtx?.clearRect(0, 0, vmFolder.frame.width, vmFolder.frame.height); } else { - (renders['empty'] as EmptyRender).renderMainThread( + (renders.empty as EmptyRender).renderMainThread( { context: this.trace.canvasPanelCtx, useCache: useCache, - type: ``, + type: '', }, vmFolder ); @@ -61,21 +66,40 @@ export class SpVirtualMemChart { vmFolder.canvasRestore(this.trace.canvasPanelCtx!, this.trace); }; this.trace.rowsEL?.appendChild(vmFolder); - array.forEach((it, idx) => this.initVirtualMemoryRow(vmFolder, it.id, it.name, idx)); + array.forEach((it) => this.initVirtualMemoryRow(vmFolder, it.id, it.name)); } - initVirtualMemoryRow(folder: TraceRow, id: number, name: string, idx: number) { + private initVirtualMemoryChartRow( + id: number, + folder: TraceRow, + name: string + ): TraceRow { let virtualMemoryRow = TraceRow.skeleton(); virtualMemoryRow.rowId = `${id}`; virtualMemoryRow.rowType = TraceRow.ROW_TYPE_VIRTUAL_MEMORY; virtualMemoryRow.rowParentId = folder.rowId; virtualMemoryRow.rowHidden = !folder.expansion; virtualMemoryRow.style.height = '40px'; - virtualMemoryRow.name = `${name.substring(16)}`; + virtualMemoryRow.name = `${name.substring(NUM_16)}`; virtualMemoryRow.setAttribute('children', ''); virtualMemoryRow.favoriteChangeHandler = this.trace.favoriteChangeHandler; virtualMemoryRow.selectChangeHandler = this.trace.selectChangeHandler; - virtualMemoryRow.supplierFrame = () => + virtualMemoryRow.focusHandler = (): void => { + this.trace?.displayTip( + virtualMemoryRow, + VirtualMemoryStruct.hoverStruct, + `value:${VirtualMemoryStruct.hoverStruct?.value}` + ); + }; + virtualMemoryRow.findHoverStruct = (): void => { + VirtualMemoryStruct.hoverStruct = virtualMemoryRow.getHoverStruct(); + }; + return virtualMemoryRow; + } + + initVirtualMemoryRow(folder: TraceRow, id: number, name: string): void { + let virtualMemoryRow = this.initVirtualMemoryChartRow(id, folder, name); + virtualMemoryRow.supplierFrame = async (): Promise => virtualMemoryDataSender(id, virtualMemoryRow).then((resultVm) => { let maxValue = 0; if (!virtualMemoryRow.isComplete) { @@ -88,7 +112,7 @@ export class SpVirtualMemChart { } else { resultVm[j].maxValue = Number(virtualMemoryRow.getAttribute('maxValue')); } - if (j == resultVm.length - 1) { + if (j === resultVm.length - 1) { resultVm[j].duration = (TraceRow.range?.totalNS || 0) - (resultVm[j].startTime || 0); } else { resultVm[j].duration = (resultVm[j + 1].startTime || 0) - (resultVm[j].startTime || 0); @@ -101,17 +125,7 @@ export class SpVirtualMemChart { } return resultVm; }); - virtualMemoryRow.focusHandler = () => { - this.trace?.displayTip( - virtualMemoryRow, - VirtualMemoryStruct.hoverStruct, - `value:${VirtualMemoryStruct.hoverStruct?.value}` - ); - }; - virtualMemoryRow.findHoverStruct = () => { - VirtualMemoryStruct.hoverStruct = virtualMemoryRow.getHoverStruct(); - }; - virtualMemoryRow.onThreadHandler = (useCache) => { + virtualMemoryRow.onThreadHandler = (useCache): void => { let context: CanvasRenderingContext2D; if (virtualMemoryRow.currentContext) { context = virtualMemoryRow.currentContext; diff --git a/ide/src/trace/component/chart/SpVmTrackerChart.ts b/ide/src/trace/component/chart/SpVmTrackerChart.ts index aced39d8f926225fb6f0acdd6cc70eac49e963d5..b2a959c399118d1c9bb9d114ca3689f0df6956f3 100644 --- a/ide/src/trace/component/chart/SpVmTrackerChart.ts +++ b/ide/src/trace/component/chart/SpVmTrackerChart.ts @@ -14,22 +14,11 @@ */ import { SpSystemTrace } from '../SpSystemTrace'; -import { - querySmapsExits, - queryGpuTotalType, - queryGpuWindowType, - queryisExistsGpuMemoryData, - queryisExistsGpuData, - queryisExistsGpuResourceData, - queryisExistsShmData, - queryisExistsDmaData, - queryisExistsPurgeableData, -} from '../../database/SqlLite'; import { TraceRow } from '../trace/base/TraceRow'; import { type BaseStruct } from '../../bean/BaseStruct'; import { renders } from '../../database/ui-worker/ProcedureWorker'; import { Utils } from '../trace/base/Utils'; -import { type EmptyRender } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { type EmptyRender } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { info } from '../../../log/Log'; import { type SnapshotRender, SnapshotStruct } from '../../database/ui-worker/ProcedureWorkerSnapshot'; import { type TreeItemData } from '../../../base-ui/tree/LitTree'; @@ -47,6 +36,19 @@ import { shmDataSender, } from '../../database/data-trafic/VmTrackerDataSender'; import { resetVmTracker } from '../../database/data-trafic/VmTrackerDataReceiver'; +import {querySmapsExits} from "../../database/sql/Smaps.sql"; +import { + queryisExistsGpuMemoryData, + queryisExistsPurgeableData, + queryisExistsShmData +} from "../../database/sql/Memory.sql"; +import {queryisExistsDmaData} from "../../database/sql/Dma.sql"; +import { + queryGpuTotalType, + queryGpuWindowType, + queryisExistsGpuData, + queryisExistsGpuResourceData +} from "../../database/sql/Gpu.sql"; export class VmTrackerChart { private trace: SpSystemTrace; diff --git a/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsFrequency.ts b/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsFrequency.ts index a8e5199ad48c106e126d719431861e13411e8c80..296828ea660862891ae42befb0da0718f6e2179b 100644 --- a/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsFrequency.ts +++ b/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsFrequency.ts @@ -92,44 +92,7 @@ export class TabCpuDetailsFrequency extends BaseElement { this.cpuDetailsFrequencyData = getDataNo(this.cpuDetailsFrequencyData); this.tableNoData!.noData = this.cpuDetailsFrequencyData.length == 0; this.noData(this.cpuDetailsFrequencyData.length == 0); - this.cpuDetailsFrequencyPie!.config = { - appendPadding: 0, - data: this.cpuDetailsFrequencyData, - angleField: 'sum', - colorField: 'value', - radius: 1, - label: { - type: 'outer', - }, - tip: (freObj) => { - return `
-
frequency:${freObj.obj.value}
-
min:${freObj.obj.min}
-
max:${freObj.obj.max}
-
average:${freObj.obj.avg}
-
duration:${freObj.obj.sumTimeStr}
-
ratio:${freObj.obj.ratio}%
-
- `; - }, - hoverHandler: (cpuDetailsFreqData) => { - if (cpuDetailsFreqData) { - this.cpuDetailsFrequencyUsageTbl!.setCurrentHover(cpuDetailsFreqData); - } else { - this.cpuDetailsFrequencyUsageTbl!.mouseOut(); - } - }, - angleClick: (it) => { - this.tabCpuDetailsThreads!.setShow = true; - this.shadowRoot!.querySelector('.d-box')!.style.display = 'none'; - this.tabCpuDetailsThreads!.init(cpu, it); - }, - interactions: [ - { - type: 'element-active', - }, - ], - }; + this.setFrequencyPieConfig(cpu); if (this.cpuDetailsFrequencySortColumn != '') { this.sortByColumn({ key: this.cpuDetailsFrequencySortColumn, @@ -142,6 +105,47 @@ export class TabCpuDetailsFrequency extends BaseElement { }); } + private setFrequencyPieConfig(cpu: number): void { + this.cpuDetailsFrequencyPie!.config = { + appendPadding: 0, + data: this.cpuDetailsFrequencyData, + angleField: 'sum', + colorField: 'value', + radius: 1, + label: { + type: 'outer', + }, + tip: (freObj) => { + return `
+
frequency:${freObj.obj.value}
+
min:${freObj.obj.min}
+
max:${freObj.obj.max}
+
average:${freObj.obj.avg}
+
duration:${freObj.obj.sumTimeStr}
+
ratio:${freObj.obj.ratio}%
+
+ `; + }, + hoverHandler: (cpuDetailsFreqData) => { + if (cpuDetailsFreqData) { + this.cpuDetailsFrequencyUsageTbl!.setCurrentHover(cpuDetailsFreqData); + } else { + this.cpuDetailsFrequencyUsageTbl!.mouseOut(); + } + }, + angleClick: (it) => { + this.tabCpuDetailsThreads!.setShow = true; + this.shadowRoot!.querySelector('.d-box')!.style.display = 'none'; + this.tabCpuDetailsThreads!.init(cpu, it); + }, + interactions: [ + { + type: 'element-active', + }, + ], + }; + } + noData(value: boolean) { this.shadowRoot!.querySelector('.fre-chart-box')!.style.display = value ? 'none' : 'block'; this.shadowRoot!.querySelector('.table-box')!.style.width = value ? '100%' : '60%'; diff --git a/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIdle.ts b/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIdle.ts index 7b1c5516e1a75993407b72d510f4b792bda59be8..1135a125bf58f90df099e484933152b9386f203a 100644 --- a/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIdle.ts +++ b/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIdle.ts @@ -88,45 +88,7 @@ export class TabCpuDetailsIdle extends BaseElement { this.cpuDetailsLdlData = getDataNo(this.cpuDetailsLdlData); this.tableNoData!.noData = this.cpuDetailsLdlData.length == 0; this.noData(this.cpuDetailsLdlData.length == 0); - this.cpuDetailsLdlPie!.config = { - appendPadding: 0, - data: this.cpuDetailsLdlData, - angleField: 'sum', - colorField: 'value', - radius: 1, - label: { - type: 'outer', - color: - type !== 'CPU Idle' - ? undefined - : (it) => { - return pieChartColors[(it as any).value]; - }, - }, - hoverHandler: (data) => { - if (data) { - this.cpuDetailsLdlUsageTbl!.setCurrentHover(data); - } else { - this.cpuDetailsLdlUsageTbl!.mouseOut(); - } - }, - tip: (idleObj) => { - return `
-
idle:${idleObj.obj.value}
-
min:${idleObj.obj.min}
-
max:${idleObj.obj.max}
-
average:${idleObj.obj.avg}
-
duration:${idleObj.obj.sumTimeStr}
-
ratio:${idleObj.obj.ratio}%
-
- `; - }, - interactions: [ - { - type: 'element-active', - }, - ], - }; + this.setLdlPieConfig(type); if (this.cpuDetailsLdlSortColumn != '') { this.sortByColumn({ key: this.cpuDetailsLdlSortColumn, @@ -139,6 +101,48 @@ export class TabCpuDetailsIdle extends BaseElement { }); } + private setLdlPieConfig(type: string): void { + this.cpuDetailsLdlPie!.config = { + appendPadding: 0, + data: this.cpuDetailsLdlData, + angleField: 'sum', + colorField: 'value', + radius: 1, + label: { + type: 'outer', + color: + type !== 'CPU Idle' + ? undefined + : (it) => { + return pieChartColors[(it as any).value]; + }, + }, + hoverHandler: (data) => { + if (data) { + this.cpuDetailsLdlUsageTbl!.setCurrentHover(data); + } else { + this.cpuDetailsLdlUsageTbl!.mouseOut(); + } + }, + tip: (idleObj) => { + return `
+
idle:${idleObj.obj.value}
+
min:${idleObj.obj.min}
+
max:${idleObj.obj.max}
+
average:${idleObj.obj.avg}
+
duration:${idleObj.obj.sumTimeStr}
+
ratio:${idleObj.obj.ratio}%
+
+ `; + }, + interactions: [ + { + type: 'element-active', + }, + ], + }; + } + noData(value: boolean) { this.shadowRoot!.querySelector('.idle-chart-box')!.style.display = value ? 'none' : 'block'; this.shadowRoot!.querySelector('.cpu_idle_table-box')!.style.width = value ? '100%' : '60%'; diff --git a/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIrq.ts b/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIrq.ts index 99f571b97b5c59a721ac5995f37baab060e716a1..b1053bda1b64e5d65fe991cd2ad37a4037b8fc9c 100644 --- a/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIrq.ts +++ b/ide/src/trace/component/schedulingAnalysis/TabCpuDetailsIrq.ts @@ -87,40 +87,7 @@ export class TabCpuDetailsIrq extends BaseElement { this.cpuDetailsLrqData = getDataNo(this.cpuDetailsLrqData); this.tableNoData!.noData = this.cpuDetailsLrqData.length == 0; this.noData(this.cpuDetailsLrqData.length == 0); - this.cpuDetailsLrqPie!.config = { - appendPadding: 0, - data: this.cpuDetailsLrqData, - angleField: 'sum', - colorField: 'value', - radius: 1, - label: { - type: 'outer', - }, - tip: (irqObj) => { - return `
-
block:${irqObj.obj.block}
-
name:${irqObj.obj.value}
-
min:${irqObj.obj.min}
-
max:${irqObj.obj.max}
-
average:${irqObj.obj.avg}
-
duration:${irqObj.obj.sumTimeStr}
-
ratio:${irqObj.obj.ratio}%
-
- `; - }, - hoverHandler: (data) => { - if (data) { - this.cpuDetailsLrqUsageTbl!.setCurrentHover(data); - } else { - this.cpuDetailsLrqUsageTbl!.mouseOut(); - } - }, - interactions: [ - { - type: 'element-active', - }, - ], - }; + this.setLrqPieConfig(); if (this.cpuDetailsLrqSortColumn != '') { this.sortByColumn({ key: this.cpuDetailsLrqSortColumn, @@ -133,6 +100,43 @@ export class TabCpuDetailsIrq extends BaseElement { }); } + private setLrqPieConfig(): void { + this.cpuDetailsLrqPie!.config = { + appendPadding: 0, + data: this.cpuDetailsLrqData, + angleField: 'sum', + colorField: 'value', + radius: 1, + label: { + type: 'outer', + }, + tip: (irqObj) => { + return `
+
block:${irqObj.obj.block}
+
name:${irqObj.obj.value}
+
min:${irqObj.obj.min}
+
max:${irqObj.obj.max}
+
average:${irqObj.obj.avg}
+
duration:${irqObj.obj.sumTimeStr}
+
ratio:${irqObj.obj.ratio}%
+
+ `; + }, + hoverHandler: (data) => { + if (data) { + this.cpuDetailsLrqUsageTbl!.setCurrentHover(data); + } else { + this.cpuDetailsLrqUsageTbl!.mouseOut(); + } + }, + interactions: [ + { + type: 'element-active', + }, + ], + }; + } + noData(value: boolean) { this.shadowRoot!.querySelector('.irq-chart-box')!.style.display = value ? 'none' : 'block'; this.shadowRoot!.querySelector('.table-box')!.style.width = value ? '100%' : '60%'; diff --git a/ide/src/trace/component/schedulingAnalysis/Top20FrequencyThread.ts b/ide/src/trace/component/schedulingAnalysis/Top20FrequencyThread.ts index ca8954fd45e6adf44ad13d5f62f5f234b6831bb9..ca417a2c85d8166d27c910c121f32177a5099dc6 100644 --- a/ide/src/trace/component/schedulingAnalysis/Top20FrequencyThread.ts +++ b/ide/src/trace/component/schedulingAnalysis/Top20FrequencyThread.ts @@ -20,13 +20,13 @@ import { info } from '../../../log/Log'; import '../../../base-ui/chart/pie/LitChartPie'; import { LitChartPie } from '../../../base-ui/chart/pie/LitChartPie'; import { LitSelect } from '../../../base-ui/select/LitSelect'; -import { queryThreads } from '../../database/SqlLite'; import { LitSelectOption } from '../../../base-ui/select/LitSelectOption'; import '../../../base-ui/progress-bar/LitProgressBar'; import { LitProgressBar } from '../../../base-ui/progress-bar/LitProgressBar'; import './TableNoData'; import { TableNoData } from './TableNoData'; import { getProbablyTime } from '../../database/logic-worker/ProcedureLogicWorkerCommon'; +import {queryThreads} from "../../database/sql/ProcessThread.sql"; @element('top20-frequency-thread') export class Top20FrequencyThread extends BaseElement { @@ -163,41 +163,45 @@ export class Top20FrequencyThread extends BaseElement { this.frequencyThreadTbl!.recycleDataSource = res; } this.frequencyThreadTbl!.reMeauseHeight(); - this.frequencyThreadPie!.config = { - appendPadding: 10, - data: this.getPieChartData(res), - angleField: 'time', - colorField: 'freq', - colorFieldTransferHandler: (value) => (value === -1 ? 'unknown' : value), - radius: 0.8, - label: { - type: 'outer', - }, - tip: (obj) => { - return `
+ this.setThreadPieConfig(res); + this.frequencyThreadProgress!.loading = false; + this.shadowRoot!.querySelector('#tb_vessel')!.scrollTop = 0; + }); + } + + private setThreadPieConfig(res: any): void { + this.frequencyThreadPie!.config = { + appendPadding: 10, + data: this.getPieChartData(res), + angleField: 'time', + colorField: 'freq', + colorFieldTransferHandler: (value) => (value === -1 ? 'unknown' : value), + radius: 0.8, + label: { + type: 'outer', + }, + tip: (obj) => { + return `
freq:${obj.obj.freq === -1 ? 'unknown' : obj.obj.freq}
cpu:${obj.obj.cpu}
time:${obj.obj.timeStr}
ratio:${obj.obj.ratio}%
`; + }, + hoverHandler: (data) => { + if (data) { + this.frequencyThreadTbl!.setCurrentHover(data); + } else { + this.frequencyThreadTbl!.mouseOut(); + } + }, + interactions: [ + { + type: 'element-active', }, - hoverHandler: (data) => { - if (data) { - this.frequencyThreadTbl!.setCurrentHover(data); - } else { - this.frequencyThreadTbl!.mouseOut(); - } - }, - interactions: [ - { - type: 'element-active', - }, - ], - }; - this.frequencyThreadProgress!.loading = false; - this.shadowRoot!.querySelector('#tb_vessel')!.scrollTop = 0; - }); + ], + }; } getPieChartData(res: any[]) { diff --git a/ide/src/trace/component/schedulingAnalysis/Top20ThreadCpuUsage.ts b/ide/src/trace/component/schedulingAnalysis/Top20ThreadCpuUsage.ts index bce9c87ff54ea706bdf2bad11a49187802eb0d79..0e1b72cf582c82592ec38dafe075ed53df2c8883 100644 --- a/ide/src/trace/component/schedulingAnalysis/Top20ThreadCpuUsage.ts +++ b/ide/src/trace/component/schedulingAnalysis/Top20ThreadCpuUsage.ts @@ -122,7 +122,10 @@ export class Top20ThreadCpuUsage extends BaseElement { this.cpuSetting!.style.display = 'inline'; this.cpuSetting?.init(); }); + this.tabListener(); + } + private tabListener(): void { for (let key of this.map!.keys()) { let tab = this.map!.get(key)!.table; let chart = this.map!.get(key)!.chart; @@ -179,6 +182,7 @@ export class Top20ThreadCpuUsage extends BaseElement { } }; } + let type = 'number'; if (detail.key === 'bigTimeStr') { @@ -242,7 +246,7 @@ export class Top20ThreadCpuUsage extends BaseElement { } } - queryData() { + queryData(): void { this.progress!.loading = true; this.queryLogicWorker(`scheduling-Thread CpuUsage`, `query Thread Cpu Usage Analysis Time:`, (res) => { this.nodata!.noData = res.keys().length === 0; @@ -277,39 +281,58 @@ export class Top20ThreadCpuUsage extends BaseElement { } return data; }); - obj.chart.config = { - data: this.getArrayDataBySize(key, source), - appendPadding: 10, - xField: 'tid', - yField: 'total', - seriesField: key === 'total' ? 'size' : '', - color: (a) => { - if (a.size === 'big core') { - return '#2f72f8'; - } else if (a.size === 'middle core') { - return '#ffab67'; - } else if (a.size === 'small core') { - return '#a285d2'; - } else { - return '#0a59f7'; - } - }, - hoverHandler: (no) => { - let data = source.find((it) => it.no === no); - if (data) { - data.isHover = true; - obj.table!.setCurrentHover(data); - } else { - obj.table!.mouseOut(); - } - }, - tip: (a) => { - if (a && a[0]) { - let tip = ''; - let total = 0; - for (let obj of a) { - total += obj.obj.total; - tip = `${tip} + this.setChartConfig(obj, key, source); + this.assignmentData(key, source, obj); + } + this.progress!.loading = false; + }); + } + + private assignmentData(key: string, source: any[], obj: { chart: LitChartColumn; table: LitTable }): void { + if (key == 'total') { + this.data = source; + } else if (key == 'small') { + this.dataSmall = source; + } else if (key == 'mid') { + this.dataMid = source; + } else if (key == 'big') { + this.dataBig = source; + } + if (this.sort[key].key != '') { + this.sortByColumn(this.sort[key], obj.table, source); + } else { + obj.table.recycleDataSource = source; + } + } + + private setChartConfig(obj: { chart: LitChartColumn; table: LitTable }, key: string, source: any[]): void { + obj.chart.config = { + data: this.getArrayDataBySize(key, source), + appendPadding: 10, + xField: 'tid', + yField: 'total', + seriesField: key === 'total' ? 'size' : '', + color: (a) => { + if (a.size === 'big core') { + return '#2f72f8'; + } else if (a.size === 'middle core') { + return '#ffab67'; + } else if (a.size === 'small core') { + return '#a285d2'; + } else { + return '#0a59f7'; + } + }, + hoverHandler: (no) => { + this.setHover(source, no, obj); + }, + tip: (a) => { + if (a && a[0]) { + let tip = ''; + let total = 0; + for (let obj of a) { + total += obj.obj.total; + tip = `${tip}
+:host{ + display: block; + width: 100%; + border-radius: 0 16px 16px 0; + height: 100%; +} +.title { + grid-column: span 2 / auto; + margin-top: 5vh; +} +.allocation-font-style{ + font-family: Helvetica-Bold; + font-size: 1em; + color: var(--dark-color1,#000000); + line-height: 28px; + font-weight: 700; +} +.root { + padding-top: 30px; + margin-left: 40px; + display: grid; + grid-template-columns: repeat(2, 1fr); + grid-template-rows: min-content 1fr min-content; + width: 90%; + border-radius: 0 16px 16px 0; + margin-bottom: 30px; +} +.allocation-inner-font-style { + font-family: Helvetica,serif; + font-size: 1em; + color: var(--dark-color1,#000000); + text-align: left; + line-height: 20px; + font-weight: 400; + display:flex; + width:75%; + margin-top: 3px; + +} +input { + width: 72%; + height: 25px; + border:0; + outline:none; + border-radius: 16px; + text-indent:2% +} +input::-webkit-input-placeholder{ + color:var(--bark-prompt,#999999); +} +.allocation-select { + height: 30px; + border: 0; + border-radius: 3px; + outline: none; + border: 1px solid var(--dark-border,#B3B3B3); + width: 60px; + background-color:var(--dark-background5, #FFFFFF) + font-family: Helvetica; + font-size: 14px; + color: var(--dark-color,#212121) + text-align: center; + line-height: 16px; + font-weight: 400; + border-radius: 16px; +} +.allocation-application{ + display: flex; + flex-direction: column; + grid-gap: 15px; + margin-top: 40px; +} +.allocation-switchstyle{ + margin-top: 40px; + display: flex; +} +.allocation-inputstyle{ + background: var(--dark-background5,#FFFFFF); + border: 1px solid var(--dark-background5,#ccc); + font-family: Helvetica; + font-size: 14px; + color: var(--dark-color1,#212121); + text-align: left; + line-height: 16px; + font-weight: 400; +} + +input::-webkit-input-placeholder{ + background: var(--dark-background5,#FFFFFF); +} + +:host([startSamp]) .allocation-inputstyle { + background: var(--dark-background5,#FFFFFF); +} + +:host(:not([startSamp])) .allocation-inputstyle { + color: #b7b7b7; + background: var(--dark-background1,#f5f5f5); +} + +#one_mb{ + background-color:var(--dark-background5, #FFFFFF) +} +#one_kb{ + background-color:var(--dark-background5, #FFFFFF) +} +#two_mb{ + background-color:var(--dark-background5, #FFFFFF) +} +#two_kb{ + background-color:var(--dark-background5, #FFFFFF) +} +.processSelect { + border-radius: 15px; + width: 84%; +} +.value-range { + opacity: 0.6; + font-family: Helvetica; + font-size: 1em; + color: var(--dark-color,#000000); + text-align: left; + line-height: 20px; + font-weight: 400; +} +.record-title{ + margin-bottom: 16px; + grid-column: span 3; +} +#interval-slider { + margin: 0 8px; + grid-column: span 2; +} +.resultSize{ + display: grid; + grid-template-rows: 1fr; + grid-template-columns: min-content min-content; + background-color: var(--dark-background5,#F2F2F2); + -webkit-appearance:none; + color: var(--dark-color,#6a6f77); + width: 150px; + margin: 0 30px 0 0; + height: 40px; + border-radius:20px; + outline:0; + border:1px solid var(--dark-border,#c8cccf); +} +.record-mode{ + font-family: Helvetica-Bold; + font-size: 1em; + color: var(--dark-color1,#000000); + line-height: 28px; + font-weight: 400; + margin-bottom: 16px; + grid-column: span 1; +} +.allocation-record-prompt{ + opacity: 0.6; + font-family: Helvetica; + font-size: 14px; + text-align: center; + line-height: 35px; + font-weight: 400; +} +.interval-result{ + -webkit-appearance:none; + border: none; + text-align: center; + width: 90px; + font-size:14px; + outline:0; + margin: 5px 0 5px 5px; + background-color: var(--dark-background5,#F2F2F2); + color:var(--dark-color,#6a6f77); +} + +.allocation-title { + opacity: 0.9; + font-family: Helvetica-Bold; + margin-right: 10px; + font-size: 18px; + text-align: center; + line-height: 40px; + font-weight: 700; +} + +lit-switch { + height: 38px; + margin-top: 10px; + display: inline; + float: right; +} + + +
+
+ Start Native Memory Record + +
+
+ ProcessId or ProcessName + Record process + + +
+
+ Max unwind level + Max Unwind Level Rang is 0 - 512, default 10 + +
+
+ Shared Memory Size (One page equals 4 KB) + Shared Memory Size Range is 0 - 131072 page, default 16384 page +
+ + Page +
+
+
+ Filter Memory Size + Filter size Range is 0 - 65535 byte, default 0 byte +
+ + Byte +
+
+
+ Use Fp Unwind + +
+
+ Sample Interval (Available on recent OpenHarmony 4.0) + Max Sample Interval Rang is 0 - 65535, default 0 + +
+
+ + Use Record Accurately (Available on recent OpenHarmony 4.0) + +
+
+ + Use Offline Symbolization (Available on recent OpenHarmony 4.0) + +
+
+ + Use Startup Mode (Available on recent OpenHarmony 4.0) + +
+
+ + Use Response Lib Mode (Available on recent OpenHarmony 4.0) + +
+
+
+ Use Record Statistics (Available on recent OpenHarmony 4.0) + Time between following interval (0 = disabled) +
+ + +
+ + S +
+
+
+`; diff --git a/ide/src/trace/component/setting/SpAllocations.ts b/ide/src/trace/component/setting/SpAllocations.ts index af6ebe132def21f3b3351e2ff8df084650e90484..3c1e45d8568f173e61ee898d314a9a01150742c6 100644 --- a/ide/src/trace/component/setting/SpAllocations.ts +++ b/ide/src/trace/component/setting/SpAllocations.ts @@ -15,13 +15,22 @@ import { BaseElement, element } from '../../../base-ui/BaseElement'; import { log } from '../../../log/Log'; -import { SpApplication } from '../../SpApplication'; -import { LitSearch } from '../trace/search/Search'; import { SpRecordTrace } from '../SpRecordTrace'; import { Cmd } from '../../../command/Cmd'; import LitSwitch from '../../../base-ui/switch/lit-switch'; import { LitSlider } from '../../../base-ui/slider/LitSlider'; import { LitSelectV } from '../../../base-ui/select/LitSelectV'; +import { SpAllocationHtml } from './SpAllocation.html'; +import { + NUM_16384, + NUM_1800, + NUM_30, + NUM_300, + NUM_3600, + NUM_450, + NUM_60, + NUM_600 +} from '../../bean/NumBean'; @element('sp-allocations') export class SpAllocations extends BaseElement { @@ -31,10 +40,8 @@ export class SpAllocations extends BaseElement { private shareMemoryUnit: HTMLSelectElement | null | undefined; private filterMemory: HTMLInputElement | null | undefined; private intervalResultInput: HTMLInputElement | null | undefined; - private filterMemoryUnit: HTMLSelectElement | null | undefined; private fpUnWind: LitSwitch | null | undefined; private statisticsSlider: LitSlider | null | undefined; - private recordAccurately: LitSwitch | null | undefined; private offlineSymbol: LitSwitch | null | undefined; private startupMode: LitSwitch | null | undefined; @@ -61,24 +68,23 @@ export class SpAllocations extends BaseElement { } get unwind(): number { - log('unwind value is :' + this.unwindEL!.value); + log(`unwind value is :${ this.unwindEL!.value}`); return Number(this.unwindEL!.value); } get shared(): number { let value = this.shareMemory?.value || ''; - log('shareMemory value is :' + value); - if (value != '') { - let unit = Number(this.shareMemory?.value) || 16384; - return unit; + log(`shareMemory value is :${ value}`); + if (value !== '') { + return Number(this.shareMemory?.value) || NUM_16384; } - return 16384; + return NUM_16384; } get filter(): number { let value = this.filterMemory?.value || ''; - log('filter value is :' + value); - if (value != '') { + log(`filter value is :${ value}`); + if (value !== '') { return Number(value); } return 0; @@ -86,7 +92,7 @@ export class SpAllocations extends BaseElement { get fp_unwind(): boolean { let value = this.fpUnWind?.checked; - if (value != undefined) { + if (value !== undefined) { return value; } return true; @@ -94,7 +100,7 @@ export class SpAllocations extends BaseElement { get record_accurately(): boolean { let value = this.recordAccurately?.checked; - if (value != undefined) { + if (value !== undefined) { return value; } return true; @@ -102,7 +108,7 @@ export class SpAllocations extends BaseElement { get offline_symbolization(): boolean { let value = this.offlineSymbol?.checked; - if (value != undefined) { + if (value !== undefined) { return value; } return true; @@ -125,7 +131,7 @@ export class SpAllocations extends BaseElement { get response_lib_mode(): boolean { let value = this.responseLibMode?.checked; - if (value != undefined) { + if (value !== undefined) { return value; } return false; @@ -133,7 +139,7 @@ export class SpAllocations extends BaseElement { get startup_mode(): boolean { let value = this.startupMode?.checked; - if (value != undefined) { + if (value !== undefined) { return value; } return false; @@ -164,21 +170,37 @@ export class SpAllocations extends BaseElement { return Number(this.sampleInterval!.value); } - connectedCallback() { + connectedCallback(): void { this.unwindEL?.addEventListener('keydown', this.handleInputChange); this.shareMemory?.addEventListener('keydown', this.handleInputChange); this.shareMemoryUnit?.addEventListener('keydown', this.handleInputChange); this.filterMemory?.addEventListener('keydown', this.handleInputChange); + this.intervalResultInput?.addEventListener('keydown', this.handleInputChange); + this.filterSize?.addEventListener('keydown', this.handleInputChange); + this.statisticsSlider?.addEventListener('input', this.statisticsSliderInputHandler); + this.intervalResultInput?.addEventListener('input', this.intervalResultInputHandler); + this.intervalResultInput?.addEventListener('focusout', this.intervalResultFocusOutHandler); + this.statisticsSlider?.shadowRoot?.querySelector('#slider')!. + addEventListener('mouseup', this.statisticsSliderMouseupHandler); + this.startupMode?.addEventListener('change',this.startupModeChangeHandler); } - disconnectedCallback() { + disconnectedCallback(): void { this.unwindEL?.removeEventListener('keydown', this.handleInputChange); this.shareMemory?.removeEventListener('keydown', this.handleInputChange); this.shareMemoryUnit?.removeEventListener('keydown', this.handleInputChange); this.filterMemory?.removeEventListener('keydown', this.handleInputChange); + this.intervalResultInput?.removeEventListener('keydown', this.handleInputChange); + this.filterSize?.removeEventListener('keydown', this.handleInputChange); + this.statisticsSlider?.removeEventListener('input', this.statisticsSliderInputHandler); + this.intervalResultInput?.removeEventListener('input', this.intervalResultInputHandler); + this.intervalResultInput?.removeEventListener('focusout', this.intervalResultFocusOutHandler); + this.statisticsSlider?.shadowRoot?.querySelector('#slider')!. + removeEventListener('mouseup', this.statisticsSliderMouseupHandler); + this.startupMode?.removeEventListener('change',this.startupModeChangeHandler); } - handleInputChange = (ev: KeyboardEvent) => { + handleInputChange = (ev: KeyboardEvent): void => { // @ts-ignore if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { ev.preventDefault(); @@ -187,57 +209,22 @@ export class SpAllocations extends BaseElement { initElements(): void { this.filterSize = this.shadowRoot?.querySelector('#filterSized'); - this.filterSize!.addEventListener('keydown', (ev: any) => { - if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { - ev.preventDefault(); - } - }); this.processId = this.shadowRoot?.getElementById('pid') as LitSelectV; let process = this.processId.shadowRoot?.querySelector('input') as HTMLInputElement; - process!.addEventListener('mousedown', (ev) => { - if (this.startSamp) { - process.readOnly = false; - Cmd.getProcess().then((processList) => { - this.processId?.dataSource(processList, ''); - if (processList.length > 0 && !this.startup_mode) { - this.processId?.dataSource(processList, 'ALL-Process'); - } else { - this.processId?.dataSource([], ''); - } - }); - } else { - process.readOnly = true; - return; - } - if (this.startSamp && (SpRecordTrace.serialNumber === '' || this.startup_mode)) { - this.processId?.dataSource([], ''); - } else { - } + process!.addEventListener('mousedown', () => { + this.processMouseDownHandler(process); }); this.unwindEL = this.shadowRoot?.getElementById('unwind') as HTMLInputElement; this.shareMemory = this.shadowRoot?.getElementById('shareMemory') as HTMLInputElement; this.shareMemoryUnit = this.shadowRoot?.getElementById('shareMemoryUnit') as HTMLSelectElement; this.filterMemory = this.shadowRoot?.getElementById('filterSized') as HTMLInputElement; - this.filterMemoryUnit = this.shadowRoot?.getElementById('filterSizedUnit') as HTMLSelectElement; this.fpUnWind = this.shadowRoot?.getElementById('use_fp_unwind') as LitSwitch; this.recordAccurately = this.shadowRoot?.getElementById('use_record_accurately') as LitSwitch; this.offlineSymbol = this.shadowRoot?.getElementById('use_offline_symbolization') as LitSwitch; this.startupMode = this.shadowRoot?.getElementById('use_startup_mode') as LitSwitch; this.responseLibMode = this.shadowRoot?.getElementById('response_lib_mode') as LitSwitch; this.sampleInterval = this.shadowRoot?.getElementById('sample-interval-input') as HTMLInputElement; - let stepValue = [0, 1, 10, 30, 60, 300, 600, 1800, 3600]; this.statisticsSlider = this.shadowRoot?.querySelector('#interval-slider') as LitSlider; - - this.unwindEL.addEventListener('keydown', (ev: any) => { - if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { - ev.preventDefault(); - } - }); - this.shareMemory.addEventListener('keydown', (ev: any) => { - if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { - ev.preventDefault(); - } - }); this.recordStatisticsResult = this.shadowRoot?.querySelector( '.record-statistics-result' ) as HTMLDivElement; @@ -252,115 +239,12 @@ export class SpAllocations extends BaseElement { }; let parentElement = this.statisticsSlider!.parentNode as Element; this.intervalResultInput = this.shadowRoot?.querySelector('.interval-result') as HTMLInputElement; - this.intervalResultInput!.addEventListener('keydown', (ev: any) => { - if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { - ev.preventDefault(); - } - }); this.intervalResultInput.value = '10'; - this.statisticsSlider.addEventListener('input', (evt) => { - this.statisticsSlider!.sliderStyle = { - minRange: 0, - maxRange: 3600, - defaultValue: this.recordStatisticsResult!.getAttribute('percent') + '', - resultUnit: 'S', - stepSize: 450, - lineColor: 'var(--dark-color3,#46B1E3)', - buttonColor: '#999999', - }; - this.intervalResultInput!.style.color = 'var(--dark-color1,#000000)'; - if (this.recordStatisticsResult!.hasAttribute('percent')) { - let step = Math.round(Number(this.recordStatisticsResult!.getAttribute('percent')) / 450); - this.recordStatisticsResult!.setAttribute('percentValue', stepValue[step] + ''); - this.intervalResultInput!.value = stepValue[step] + ''; - } - }); parentElement.setAttribute('percent', '3600'); this.intervalResultInput.style.color = 'var(--dark-color1,#000000)'; - this.intervalResultInput.addEventListener('input', (ev) => { - if (this.recordStatisticsResult!.hasAttribute('percent')) { - this.recordStatisticsResult!.removeAttribute('percent'); - } - this.intervalResultInput!.style.color = 'var(--dark-color1,#000000)'; - this.intervalResultInput!.parentElement!.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; - this.intervalResultInput!.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; - if (this.intervalResultInput!.value.trim() === '') { - this.intervalResultInput!.style.color = 'red'; - parentElement.setAttribute('percent', '3600'); - return; - } - let memorySize = Number(this.intervalResultInput!.value); - if ( - memorySize < this.statisticsSlider!.sliderStyle.minRange || - memorySize > this.statisticsSlider!.sliderStyle.maxRange - ) { - this.intervalResultInput!.style.color = 'red'; - parentElement.setAttribute('percent', '3600'); - } else { - let defaultSize = 0; - let stepSize = 450; - let inputValue = Number(this.intervalResultInput!.value); - for (let stepIndex = 0; stepIndex < stepValue.length; stepIndex++) { - let currentValue = stepValue[stepIndex]; - if (inputValue === currentValue) { - defaultSize = stepIndex * stepSize; - break; - } else if (inputValue < currentValue && stepIndex !== 0) { - defaultSize = - ((inputValue - stepValue[stepIndex - 1]) / (currentValue - stepValue[stepIndex - 1])) * stepSize + - stepSize * (stepIndex - 1); - break; - } - } - this.statisticsSlider!.percent = defaultSize + ''; - let htmlInputElement = this.statisticsSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; - this.statisticsSlider!.sliderStyle = { - minRange: 0, - maxRange: 3600, - defaultValue: defaultSize + '', - resultUnit: 'S', - stepSize: 1, - lineColor: 'var(--dark-color3,#46B1E3)', - buttonColor: '#999999', - }; - htmlInputElement.value = defaultSize + ''; - parentElement.setAttribute('percent', this.intervalResultInput!.value); - parentElement.setAttribute('percentValue', this.intervalResultInput!.value); - } - }); - - this.intervalResultInput.addEventListener('focusout', (ev) => { - if (this.intervalResultInput!.value.trim() === '') { - parentElement.setAttribute('percent', '3600'); - this.intervalResultInput!.value = '3600'; - this.intervalResultInput!.style.color = 'var(--dark-color,#6a6f77)'; - parentElement.setAttribute('percent', this.intervalResultInput!.value); - parentElement.setAttribute('percentValue', this.intervalResultInput!.value); - this.statisticsSlider!.percent = this.intervalResultInput!.value; - let htmlInputElement = this.statisticsSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; - htmlInputElement.value = this.intervalResultInput!.value; - } - }); - this.statisticsSlider.shadowRoot?.querySelector('#slider')!.addEventListener('mouseup', (ev) => { - setTimeout(() => { - let percentValue = this.recordStatisticsResult!.getAttribute('percent'); - let index = Math.round(Number(percentValue) / 450); - index = index < 1 ? 0 : index; - this.intervalResultInput!.value = stepValue[index] + ''; - this.recordStatisticsResult!.setAttribute('percentValue', stepValue[index] + ''); - }); - }); - this.startupMode.addEventListener('change', (evt) => { - process.value = ''; - if (this.startup_mode) { - process!.placeholder = 'please input process'; - } else { - process!.placeholder = 'please select process'; - } - }); - let litSwitch = this.shadowRoot?.querySelector('#switch-disabled') as LitSwitch; - litSwitch.addEventListener('change', (event: any) => { + litSwitch.addEventListener('change', (event: Event): void => { + // @ts-ignore let detail = event.detail; if (detail.checked) { this.unDisable(); @@ -371,7 +255,130 @@ export class SpAllocations extends BaseElement { this.disable(); } - private unDisable() { + startupModeChangeHandler = (): void => { + let process = this.processId?.shadowRoot?.querySelector('input') as HTMLInputElement; + process.value = ''; + if (this.startup_mode) { + process!.placeholder = 'please input process'; + } else { + process!.placeholder = 'please select process'; + } + }; + + statisticsSliderMouseupHandler = (): void => { + setTimeout(() => { + let percentValue = this.recordStatisticsResult!.getAttribute('percent'); + let index = Math.round(Number(percentValue) / NUM_450); + index = index < 1 ? 0 : index; + this.intervalResultInput!.value = `${stepValue[index] }`; + this.recordStatisticsResult!.setAttribute('percentValue', `${stepValue[index] }`); + }); + }; + + intervalResultFocusOutHandler = (): void => { + let parentElement = this.statisticsSlider!.parentNode as Element; + if (this.intervalResultInput!.value.trim() === '') { + parentElement.setAttribute('percent', '3600'); + this.intervalResultInput!.value = '3600'; + this.intervalResultInput!.style.color = 'var(--dark-color,#6a6f77)'; + parentElement.setAttribute('percent', this.intervalResultInput!.value); + parentElement.setAttribute('percentValue', this.intervalResultInput!.value); + this.statisticsSlider!.percent = this.intervalResultInput!.value; + let htmlInputElement = this.statisticsSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; + htmlInputElement.value = this.intervalResultInput!.value; + } + }; + + statisticsSliderInputHandler = (): void => { + this.statisticsSlider!.sliderStyle = { + minRange: 0, + maxRange: 3600, + defaultValue: `${this.recordStatisticsResult!.getAttribute('percent')}`, + resultUnit: 'S', + stepSize: 450, + lineColor: 'var(--dark-color3,#46B1E3)', + buttonColor: '#999999', + }; + this.intervalResultInput!.style.color = 'var(--dark-color1,#000000)'; + if (this.recordStatisticsResult!.hasAttribute('percent')) { + let step = Math.round(Number(this.recordStatisticsResult!.getAttribute('percent')) / NUM_450); + this.recordStatisticsResult!.setAttribute('percentValue', `${stepValue[step]}`); + this.intervalResultInput!.value = `${stepValue[step]}`; + } + }; + + private processMouseDownHandler(process: HTMLInputElement): void { + if (this.startSamp) { + process.readOnly = false; + Cmd.getProcess().then((processList) => { + this.processId?.dataSource(processList, ''); + if (processList.length > 0 && !this.startup_mode) { + this.processId?.dataSource(processList, 'ALL-Process'); + } else { + this.processId?.dataSource([], ''); + } + }); + } else { + process.readOnly = true; + return; + } + if (this.startSamp && (SpRecordTrace.serialNumber === '' || this.startup_mode)) { + this.processId?.dataSource([], ''); + } else { + } + } + + intervalResultInputHandler = (): void => { + let parentElement = this.statisticsSlider!.parentNode as Element; + if (this.recordStatisticsResult!.hasAttribute('percent')) { + this.recordStatisticsResult!.removeAttribute('percent'); + } + this.intervalResultInput!.style.color = 'var(--dark-color1,#000000)'; + this.intervalResultInput!.parentElement!.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; + this.intervalResultInput!.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; + if (this.intervalResultInput!.value.trim() === '') { + this.intervalResultInput!.style.color = 'red'; + parentElement.setAttribute('percent', '3600'); + return; + } + if (Number(this.intervalResultInput!.value) < this.statisticsSlider!.sliderStyle.minRange || + Number(this.intervalResultInput!.value) > this.statisticsSlider!.sliderStyle.maxRange) { + this.intervalResultInput!.style.color = 'red'; + parentElement.setAttribute('percent', '3600'); + } else { + let defaultSize = 0; + let stepSize = 450; + let inputValue = Number(this.intervalResultInput!.value); + for (let stepIndex = 0; stepIndex < stepValue.length; stepIndex++) { + let currentValue = stepValue[stepIndex]; + if (inputValue === currentValue) { + defaultSize = stepIndex * stepSize; + break; + } else if (inputValue < currentValue && stepIndex !== 0) { + defaultSize = + ((inputValue - stepValue[stepIndex - 1]) / (currentValue - stepValue[stepIndex - 1])) * stepSize + + stepSize * (stepIndex - 1); + break; + } + } + this.statisticsSlider!.percent = `${defaultSize}`; + let htmlInputElement = this.statisticsSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; + this.statisticsSlider!.sliderStyle = { + minRange: 0, + maxRange: 3600, + defaultValue: `${defaultSize}`, + resultUnit: 'S', + stepSize: 1, + lineColor: 'var(--dark-color3,#46B1E3)', + buttonColor: '#999999', + }; + htmlInputElement.value = `${defaultSize}`; + parentElement.setAttribute('percent', this.intervalResultInput!.value); + parentElement.setAttribute('percentValue', this.intervalResultInput!.value); + } + }; + + private unDisable(): void { this.startSamp = true; if (this.fpUnWind) { this.fpUnWind.disabled = false; @@ -399,7 +406,7 @@ export class SpAllocations extends BaseElement { this.statisticsSlider!.disabled = false; } - private disable() { + private disable(): void { this.startSamp = false; if (this.fpUnWind) { this.fpUnWind.disabled = true; @@ -428,272 +435,8 @@ export class SpAllocations extends BaseElement { } initHtml(): string { - return ` - -
-
- Start Native Memory Record - -
-
- ProcessId or ProcessName - Record process - - -
-
- Max unwind level - Max Unwind Level Rang is 0 - 512, default 10 - -
-
- Shared Memory Size (One page equals 4 KB) - Shared Memory Size Range is 0 - 131072 page, default 16384 page -
- - Page -
-
-
- Filter Memory Size - Filter size Range is 0 - 65535 byte, default 0 byte -
- - Byte -
-
-
- Use Fp Unwind - -
-
- Sample Interval (Available on recent OpenHarmony 4.0) - Max Sample Interval Rang is 1 - 65535, default 256 - -
-
- Use Record Accurately (Available on recent OpenHarmony 4.0) - -
-
- Use Offline Symbolization (Available on recent OpenHarmony 4.0) - -
-
- Use Startup Mode (Available on recent OpenHarmony 4.0) - -
-
- Use Response Lib Mode (Available on recent OpenHarmony 4.0) - -
-
-
- Use Record Statistics (Available on recent OpenHarmony 4.0) - Time between following interval (0 = disabled) -
- - -
- - S -
-
-
- `; + return SpAllocationHtml; } } + +const stepValue = [0, 1, 10, NUM_30, NUM_60, NUM_300, NUM_600, NUM_1800, NUM_3600]; diff --git a/ide/src/trace/component/setting/SpArkTs.html.ts b/ide/src/trace/component/setting/SpArkTs.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff4744845051125c41f7a71b4fc64686a80a0dd7 --- /dev/null +++ b/ide/src/trace/component/setting/SpArkTs.html.ts @@ -0,0 +1,188 @@ +/* + * 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. + */ + +export const SpArkTsHtml = ` +
+
+ Long trace mode! If current data Trace is too large, it may not open! +
+
+
+ Start Ark Ts Record + +
+
+
+
+ Process + Record process +
+ +
+
+
+ Select profiling type +
+
+ Start cpu profiler + +
+
+ Interval(Available on recent OpenHarmony 4.0) +
+ + μs +
+
+
+ Start memory profiler + +
+
+ Heap snapshot +
+ Heap snapshot profiles show memory distribution among your page’s + JavaScript objects and related DOM nodes. +
+ + +
+ Interval(Available on recent OpenHarmony 4.0) +
+ + S +
+
+ + Allocation insteumentation on timeline +
+ Allocation timelines show insturmented Javascript memory allocations + over time. Once profile is recorded you can select a time interval to see objects that + werre allocated within it and still alive by the end of recording. Use this profile + type to isolate memory leaks. +
+ + +
+
+
+ +
+`; diff --git a/ide/src/trace/component/setting/SpArkTs.ts b/ide/src/trace/component/setting/SpArkTs.ts index 836360ebed6a319ed3cecc9a71fa2c77464f0ba3..94629c1d04c76a9bf76dc4a1192eee7e70f15aca 100644 --- a/ide/src/trace/component/setting/SpArkTs.ts +++ b/ide/src/trace/component/setting/SpArkTs.ts @@ -24,6 +24,7 @@ import { LitRadioBox } from '../../../base-ui/radiobox/LitRadioBox'; import { SpCheckDesBox } from './SpCheckDesBox'; import LitSwitch from '../../../base-ui/switch/lit-switch'; import { SpApplication } from '../../SpApplication'; +import { SpArkTsHtml } from './SpArkTs.html'; @element('sp-ark-ts') export class SpArkTs extends BaseElement { @@ -33,6 +34,7 @@ export class SpArkTs extends BaseElement { private interval: HTMLInputElement | undefined | null; private memorySwitch: LitSwitch | undefined | null; private cpuSwitch: LitSwitch | undefined | null; + private litSwitch: LitSwitch | undefined | null; set startSamp(jsHeapStart: boolean) { if (jsHeapStart) { @@ -57,7 +59,7 @@ export class SpArkTs extends BaseElement { let memorySwitch = this.shadowRoot?.querySelector('#memory-switch'); let type: string; if (memorySwitch!.getAttribute('checked') !== null) { - this.radioBox = this.shadowRoot?.querySelector(`lit-radio[checked]`); + this.radioBox = this.shadowRoot?.querySelector('lit-radio[checked]'); type = this.radioBox?.getAttribute('type') || ''; } else { type = '-1'; @@ -112,14 +114,14 @@ export class SpArkTs extends BaseElement { this.processInput = this.shadowRoot?.querySelector('lit-allocation-select'); let processInput = this.processInput?.shadowRoot?.querySelector('.multipleSelect') as HTMLDivElement; this.cpuSwitch = this.shadowRoot?.querySelector('#cpu-switch') as LitSwitch; - processInput!.addEventListener('mousedown', (ev) => { - if (SpRecordTrace.serialNumber == '') { + processInput!.addEventListener('mousedown', () => { + if (SpRecordTrace.serialNumber === '') { this.processInput!.processData = []; this.processInput!.initData(); } }); processInput!.addEventListener('mouseup', () => { - if (SpRecordTrace.serialNumber == '') { + if (SpRecordTrace.serialNumber === '') { this.processInput!.processData = []; this.processInput!.initData(); } else { @@ -129,64 +131,69 @@ export class SpArkTs extends BaseElement { }); } }); - this.interval!.addEventListener('focusout', () => { - if (this.interval!.value === '') { - this.interval!.value = '10'; - } - }); - - let litSwitch = this.shadowRoot?.querySelector('lit-switch') as LitSwitch; - litSwitch.addEventListener('change', (event: any) => { - let detail = event.detail; - if (detail.checked) { - this.unDisable(); - this.unMemoryDisable(); - } else { - this.disable(); - this.memoryDisable(); - } - }); + this.litSwitch = this.shadowRoot?.querySelector('lit-switch') as LitSwitch; this.memorySwitch = this.shadowRoot?.querySelector('#memory-switch') as LitSwitch; - this.memorySwitch.addEventListener('change', (event: any) => { - let detail = event.detail; - if (detail.checked) { - this.unMemoryDisable(); - } else { - if (!this.cpuSwitch?.checked) { - litSwitch.checked = false; - this.disable(); - } - this.memoryDisable(); - } - }); - this.cpuSwitch = this.shadowRoot?.querySelector('#cpu-switch') as LitSwitch; - this.cpuSwitch.addEventListener('change', (event: any) => { - let detail = event.detail; - let interval = this.shadowRoot?.querySelectorAll('#cpuInterval'); - if (!detail.checked && !this.memorySwitch?.checked) { - litSwitch.checked = false; - this.disable(); - } else if (detail.checked) { - interval!.forEach((item) => { - item.disabled = false; - item.style.background = 'var(--dark-background5,#FFFFFF)'; - }); - } else { - interval!.forEach((item) => { - item.disabled = true; - item.style.color = '#b7b7b7'; - item.style.background = 'var(--dark-background1,#f5f5f5)'; - }); - litSwitch.checked = true; - this.startSamp = true; - } - }); this.disable(); this.memoryDisable(); } - private memoryDisable() { + intervalFocusoutHandler = (): void => { + if (this.interval!.value === '') { + this.interval!.value = '10'; + } + }; + + litSwitchChangeHandler = (event: Event): void => { + // @ts-ignore + let detail = event.detail; + if (detail.checked) { + this.unDisable(); + this.unMemoryDisable(); + } else { + this.disable(); + this.memoryDisable(); + } + }; + + memorySwitchChangeHandler = (event: Event): void => { + // @ts-ignore + let detail = event.detail; + if (detail.checked) { + this.unMemoryDisable(); + } else { + if (!this.cpuSwitch?.checked) { + this.litSwitch!.checked = false; + this.disable(); + } + this.memoryDisable(); + } + }; + + cpuSwitchChangeHandler = (event: Event): void => { + // @ts-ignore + let detail = event.detail; + let interval = this.shadowRoot?.querySelectorAll('#cpuInterval'); + if (!detail.checked && !this.memorySwitch?.checked) { + this.litSwitch!.checked = false; + this.disable(); + } else if (detail.checked) { + interval!.forEach((item) => { + item.disabled = false; + item.style.background = 'var(--dark-background5,#FFFFFF)'; + }); + } else { + interval!.forEach((item) => { + item.disabled = true; + item.style.color = '#b7b7b7'; + item.style.background = 'var(--dark-background1,#f5f5f5)'; + }); + this.litSwitch!.checked = true; + this.startSamp = true; + } + }; + + private memoryDisable(): void { let interval = this.shadowRoot?.querySelectorAll('#interval'); interval!.forEach((item) => { item.disabled = true; @@ -203,7 +210,7 @@ export class SpArkTs extends BaseElement { }); } - private unMemoryDisable() { + private unMemoryDisable(): void { let interval = this.shadowRoot?.querySelectorAll('#interval'); interval!.forEach((item) => { item.disabled = false; @@ -219,7 +226,7 @@ export class SpArkTs extends BaseElement { }); } - private disable() { + private disable(): void { this.startSamp = false; this.processInput!.setAttribute('disabled', ''); let heapConfigs = this.shadowRoot?.querySelectorAll('.select'); @@ -239,7 +246,7 @@ export class SpArkTs extends BaseElement { }); } - private unDisable() { + private unDisable(): void { this.startSamp = true; this.processInput!.removeAttribute('disabled'); let heapConfigs = this.shadowRoot?.querySelectorAll('.select'); @@ -266,174 +273,21 @@ export class SpArkTs extends BaseElement { } else { traceMode!.style.display = 'none'; } + this.interval!.addEventListener('focusout', this.intervalFocusoutHandler); + this.litSwitch!.addEventListener('change', this.litSwitchChangeHandler); + this.memorySwitch!.addEventListener('change', this.memorySwitchChangeHandler); + this.cpuSwitch!.addEventListener('change', this.cpuSwitchChangeHandler); + } + + disconnectedCallback(): void { + super.disconnectedCallback(); + this.interval!.removeEventListener('focusout', this.intervalFocusoutHandler); + this.litSwitch!.removeEventListener('change', this.litSwitchChangeHandler); + this.memorySwitch!.removeEventListener('change', this.memorySwitchChangeHandler); + this.cpuSwitch!.removeEventListener('change', this.cpuSwitchChangeHandler); } initHtml(): string { - return ` - -
-
- Long trace mode! If current data Trace is too large, it may not open! -
-
-
- Start Ark Ts Record - -
-
-
-
- Process - Record process -
- -
-
-
- Select profiling type -
-
- Start cpu profiler - -
-
- Interval(Available on recent OpenHarmony 4.0) -
- - μs -
-
-
- Start memory profiler - -
-
- Heap snapshot -
- Heap snapshot profiles show memory distribution among your page’s JavaScript objects and related DOM nodes. -
- - -
- Interval(Available on recent OpenHarmony 4.0) -
- - S -
-
- Allocation insteumentation on timeline -
- Allocation timelines show insturmented Javascript memory allocations over time. Once profile is recorded you can select a time interval to see objects that werre allocated within it and still alive by the end of recording. Use this profile type to isolate memory leaks. -
- - -
-
-
- -
- `; + return SpArkTsHtml; } } diff --git a/ide/src/trace/component/setting/SpFIleSystem.html.ts b/ide/src/trace/component/setting/SpFIleSystem.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd4307d7d7901b0f2f49c02bc7426d06ceb45fc8 --- /dev/null +++ b/ide/src/trace/component/setting/SpFIleSystem.html.ts @@ -0,0 +1,137 @@ +/* + * 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. + */ + +export const SpFIleSystemHtml = ` + +
+
+ Long trace mode! If current data Trace is too large, it may not open! +
+
+
+ Start FileSystem Record + +
+
+
+
+ Start Page Fault Record + +
+
+
+
+ Start BIO Latency Record + +
+
+
+
+ Process + Record process +
+ +
+
+
+ Max Unwind Level +
+ +
+
+`; diff --git a/ide/src/trace/component/setting/SpFileSystem.ts b/ide/src/trace/component/setting/SpFileSystem.ts index 0a1cce88f66aa49b6c4dcd76dd70a998849e3da5..664a042c0339fde6d1cc36a4b4501ee7c048a380 100644 --- a/ide/src/trace/component/setting/SpFileSystem.ts +++ b/ide/src/trace/component/setting/SpFileSystem.ts @@ -20,12 +20,10 @@ import '../../../base-ui/select/LitSelectV'; import '../../../base-ui/select/LitSelect'; import '../../../base-ui/switch/lit-switch'; -import { LitSelect } from '../../../base-ui/select/LitSelect'; import { SpRecordTrace } from '../SpRecordTrace'; import { Cmd } from '../../../command/Cmd'; -import { CmdConstant } from '../../../command/CmdConstant'; -import { HdcDeviceManager } from '../../../hdc/HdcDeviceManager'; import { SpApplication } from '../../SpApplication'; +import { SpFIleSystemHtml } from './SpFIleSystem.html'; @element('sp-file-system') export class SpFileSystem extends BaseElement { @@ -127,7 +125,7 @@ export class SpFileSystem extends BaseElement { this.switchChange(); this.processInput = this.shadowRoot?.querySelector('lit-select-v'); this.maximum = this.shadowRoot?.querySelector('#maxUnwindLevel'); - this.maximum?.addEventListener('keyup', (eve: Event) => { + this.maximum?.addEventListener('keyup', () => { this.maximum!.value = this.maximum!.value.replace(/\D/g, ''); if (this.maximum!.value !== '') { let mun = parseInt(this.maximum!.value); @@ -137,7 +135,7 @@ export class SpFileSystem extends BaseElement { } }); this.selectProcess = this.processInput!.shadowRoot?.querySelector('input') as HTMLInputElement; - this.selectProcess!.addEventListener('mousedown', (ev) => { + this.selectProcess!.addEventListener('mousedown', () => { if (SpRecordTrace.serialNumber === '') { this.processInput!.dataSource([], ''); } else { @@ -156,29 +154,17 @@ export class SpFileSystem extends BaseElement { let fileSystemSwitch = this.shadowRoot?.querySelector('#fileSystem'); fileSystemSwitch!.addEventListener('change', (event: CustomEventInit) => { let detail = event.detail; - if (detail!.checked) { - this.startFileSystem = true; - } else { - this.startFileSystem = false; - } + this.startFileSystem = detail!.checked; }); let pageFaultSwitch = this.shadowRoot?.querySelector('#pageFault'); pageFaultSwitch!.addEventListener('change', (event: CustomEventInit) => { let detail = event.detail; - if (detail!.checked) { - this.startVirtualMemory = true; - } else { - this.startVirtualMemory = false; - } + this.startVirtualMemory = detail!.checked; }); let bioLatencySwitch = this.shadowRoot?.querySelector('#bioLatency'); bioLatencySwitch!.addEventListener('change', (event: CustomEventInit) => { let detail = event.detail; - if (detail!.checked) { - this.startIo = true; - } else { - this.startIo = false; - } + this.startIo = detail!.checked; }); } @@ -220,128 +206,7 @@ export class SpFileSystem extends BaseElement { } initHtml(): string { - return ` - -
-
- Long trace mode! If current data Trace is too large, it may not open! -
-
-
- Start FileSystem Record - -
-
-
-
- Start Page Fault Record - -
-
-
-
- Start BIO Latency Record - -
-
-
-
- Process - Record process -
- -
-
-
- Max Unwind Level -
- -
-
- `; + return SpFIleSystemHtml; } } diff --git a/ide/src/trace/component/setting/SpHilogRecord.html.ts b/ide/src/trace/component/setting/SpHilogRecord.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..b121c1601143586a98446c3af6f4145ca37c2136 --- /dev/null +++ b/ide/src/trace/component/setting/SpHilogRecord.html.ts @@ -0,0 +1,120 @@ +/* + * 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. + */ + +export const SpHiLogRecordHtml = ` + +
+
+
+ Start Hilog Record + +
+
+
+ Process + Record process +
+ + +
+
+
+ Level + Record logs level +
+ + ${getHiLogLevel() + .map( + (level): string => + `${ level }` + ) + .join('')} + +
+
+
+ `; + +function getHiLogLevel(): string[] { + return ['ALL-Level', 'Debug', 'Info', 'Warn', 'Error', 'Fatal']; +} diff --git a/ide/src/trace/component/setting/SpHilogRecord.ts b/ide/src/trace/component/setting/SpHilogRecord.ts index f6cb7740282065bc8d930363c8c07c262ad4f36f..1c3f87c4b9b3c2cf0459b6016dcc1fe00e5d341c 100644 --- a/ide/src/trace/component/setting/SpHilogRecord.ts +++ b/ide/src/trace/component/setting/SpHilogRecord.ts @@ -22,6 +22,7 @@ import { SpRecordTrace } from '../SpRecordTrace'; import { Cmd } from '../../../command/Cmd'; import { LitAllocationSelect } from '../../../base-ui/select/LitAllocationSelect'; import { LitSelect } from '../../../base-ui/select/LitSelect'; +import { SpHiLogRecordHtml } from './SpHilogRecord.html'; @element('sp-hi-log') export class SpHilogRecord extends BaseElement { @@ -62,7 +63,7 @@ export class SpHilogRecord extends BaseElement { } }); let processInputEl = this.processSelectEl.shadowRoot?.querySelector('.multipleSelect') as HTMLInputElement; - processInputEl.addEventListener('mousedown', (ev) => { + processInputEl.addEventListener('mousedown', () => { if (SpRecordTrace.serialNumber === '') { this.processSelectEl!.processData = []; this.processSelectEl!.initData(); @@ -79,114 +80,11 @@ export class SpHilogRecord extends BaseElement { }); } - attributeChangedCallback(name: string, oldValue: string, newValue: string) { + attributeChangedCallback(name: string, oldValue: string, newValue: string): void { super.attributeChangedCallback(name, oldValue, newValue); } - getHiLogLevel(): string[] { - return ['ALL-Level', 'Debug', 'Info', 'Warn', 'Error', 'Fatal']; - } - initHtml(): string { - return ` - -
-
-
- Start Hilog Record - -
-
-
- Process - Record process -
- - -
-
-
- Level - Record logs level -
- - ${this.getHiLogLevel() - .map( - (level, index): string => - '' + level + '' - ) - .join('')} - - -
-
-
- `; + return SpHiLogRecordHtml; } } diff --git a/ide/src/trace/component/setting/SpProbesConfig.html.ts b/ide/src/trace/component/setting/SpProbesConfig.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..595c770fe8be111cb1c6edc06f87f376e1be3a34 --- /dev/null +++ b/ide/src/trace/component/setting/SpProbesConfig.html.ts @@ -0,0 +1,196 @@ +/* + * 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. + */ + +export const SpProbesConfigHtml = ` + +
+
+ Record mode + +
+
+
+
+
+ + +
+ +
+
+
+
+

Buffer Size

+

The ftrace buffer size range is 2048 KB to 307200 KB

+
+
+ + +
+ + KB +
+
+
+
+
+
+ Memory Config +
+
+
+
+ Ability Config +
+
+
+
+`; diff --git a/ide/src/trace/component/setting/SpProbesConfig.ts b/ide/src/trace/component/setting/SpProbesConfig.ts index d3f3582e2b0a3a57be969a2130d274f8e942ba57..52db0c685aee8bf244f0dec30e0d548f40be00ee 100644 --- a/ide/src/trace/component/setting/SpProbesConfig.ts +++ b/ide/src/trace/component/setting/SpProbesConfig.ts @@ -14,21 +14,17 @@ */ import { BaseElement, element } from '../../../base-ui/BaseElement'; -import { checkDesBean, SpCheckDesBox } from './SpCheckDesBox'; +import { SpCheckDesBox } from './SpCheckDesBox'; import { LitCheckBox, LitCheckBoxChangeEvent } from '../../../base-ui/checkbox/LitCheckBox'; import { LitRadioGroup } from '../../../base-ui/radiobox/LitRadioGroup'; import { info, log } from '../../../log/Log'; import { LitSlider } from '../../../base-ui/slider/LitSlider'; import LitSwitch from '../../../base-ui/switch/lit-switch'; +import { SpProbesConfigHtml } from './SpProbesConfig.html'; @element('probes-config') export class SpProbesConfig extends BaseElement { - private traceConfigList: Array | undefined; - private memoryConfigList: Array | undefined; - private abilityConfigList: Array | undefined; - private hitraceConfigList: Array | undefined; private hitrace: SpCheckDesBox | undefined; - private _traceConfig: HTMLElement | undefined; private _memoryConfig: HTMLElement | undefined | null; private _abilityConfig: HTMLElement | undefined | null; @@ -50,7 +46,8 @@ export class SpProbesConfig extends BaseElement { } get traceConfig() { - let selectedTrace = this._traceConfig?.querySelectorAll(`check-des-box[checked]`) || []; + let selectedTrace = this._traceConfig?. + querySelectorAll('check-des-box[checked]') || []; let values = []; for (const litCheckBoxElement of selectedTrace) { values.push(litCheckBoxElement.value); @@ -81,7 +78,7 @@ export class SpProbesConfig extends BaseElement { return values; } - get recordAbility() { + get recordAbility(): boolean { let selectedMemory = this._abilityConfig?.querySelectorAll( 'check-des-box[checked]' ) as NodeListOf; @@ -111,35 +108,9 @@ export class SpProbesConfig extends BaseElement { } } - initElements(): void { - this.ftraceBuffSizeResultInput = this.shadowRoot?.querySelector('.ftrace-buff-size-result') as HTMLInputElement; - this.ftraceBuffSizeResultInput!.addEventListener('keydown', (ev: any) => { - if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { - ev.preventDefault(); - } - }); - this.traceConfigList = [ - { - value: 'Scheduling details', - isSelect: true, - des: 'enables high-detailed tracking of scheduling events', - }, - { - value: 'CPU Frequency and idle states', - isSelect: true, - des: 'Records cpu frequency and idle state change viaftrace', - }, - { - value: 'Advanced ftrace config', - isSelect: false, - des: - 'Enable individual events and tune the kernel-tracing(ftrace) module.' + - 'The events enabled here are in addition to those from' + - ' enabled by other probes.', - }, - ]; + private initTraceConfigList(): void { this._traceConfig = this.shadowRoot?.querySelector('.trace-config') as HTMLElement; - this.traceConfigList.forEach((configBean) => { + traceConfigList.forEach((configBean) => { let checkDesBox = new SpCheckDesBox(); checkDesBox.value = configBean.value; checkDesBox.checked = configBean.isSelect; @@ -149,23 +120,11 @@ export class SpProbesConfig extends BaseElement { }); this._traceConfig?.appendChild(checkDesBox); }); - this.memoryConfigList = [ - { - value: 'Kernel meminfo', - isSelect: false, - des: 'polling of /proc/meminfo', - }, - { - value: 'Virtual memory stats', - isSelect: false, - des: - 'Periodically polls virtual memory stats from /proc/vmstat.' + - ' Allows to gather statistics about swap,' + - 'eviction, compression and pagecache efficiency', - }, - ]; + } + + private initMemoryConfigList(): void { this._memoryConfig = this.shadowRoot?.querySelector('.memory-config'); - this.memoryConfigList.forEach((configBean) => { + memoryConfigList.forEach((configBean) => { let checkDesBox = new SpCheckDesBox(); checkDesBox.value = configBean.value; checkDesBox.checked = configBean.isSelect; @@ -175,15 +134,11 @@ export class SpProbesConfig extends BaseElement { }); this._memoryConfig?.appendChild(checkDesBox); }); - this.abilityConfigList = [ - { - value: 'AbilityMonitor', - isSelect: false, - des: 'Tracks the AbilityMonitor', - }, - ]; + } + + private initAbilityConfigList(): void { this._abilityConfig = this.shadowRoot?.querySelector('.ability-config'); - this.abilityConfigList.forEach((configBean) => { + abilityConfigList.forEach((configBean) => { let checkDesBox = new SpCheckDesBox(); checkDesBox.value = configBean.value; checkDesBox.checked = configBean.isSelect; @@ -193,79 +148,12 @@ export class SpProbesConfig extends BaseElement { }); this._abilityConfig?.appendChild(checkDesBox); }); + } - this.hitraceConfigList = [ - { value: 'ability', isSelect: true }, - { value: 'accesscontrol', isSelect: false }, - { value: 'accessibility', isSelect: false }, - { value: 'account', isSelect: false }, - { value: 'ace', isSelect: true }, - { value: 'app', isSelect: true }, - { value: 'ark', isSelect: true }, - { value: 'binder', isSelect: true }, - { value: 'bluetooth', isSelect: false }, - { value: 'cloud', isSelect: false }, - { value: 'commonlibrary', isSelect: false }, - { value: 'daudio', isSelect: false }, - { value: 'dcamera', isSelect: false }, - { value: 'deviceauth', isSelect: false }, - { value: 'devicemanager', isSelect: false }, - { value: 'deviceprofile', isSelect: false }, - { value: 'dhfwk', isSelect: false }, - { value: 'dinput', isSelect: false }, - { value: 'disk', isSelect: true }, - { value: 'distributeddatamgr', isSelect: false }, - { value: 'dlpcre', isSelect: false }, - { value: 'dsched', isSelect: false }, - { value: 'dscreen', isSelect: false }, - { value: 'dslm', isSelect: false }, - { value: 'dsoftbus', isSelect: false }, - { value: 'ffrt', isSelect: false }, - { value: 'filemanagement', isSelect: false }, - { value: 'freq', isSelect: true }, - { value: 'graphic', isSelect: true }, - { value: 'gresource', isSelect: false }, - { value: 'hdcd', isSelect: false }, - { value: 'hdf', isSelect: false }, - { value: 'huks', isSelect: false }, - { value: 'i2c', isSelect: false }, - { value: 'idle', isSelect: true }, - { value: 'interconn', isSelect: false }, - { value: 'irq', isSelect: true }, - { value: 'mdfs', isSelect: false }, - { value: 'memory', isSelect: false }, - { value: 'memreclaim', isSelect: true }, - { value: 'misc', isSelect: false }, - { value: 'mmc', isSelect: true }, - { value: 'msdp', isSelect: false }, - { value: 'multimodalinput', isSelect: true }, - { value: 'musl', isSelect: false }, - { value: 'net', isSelect: false }, - { value: 'notification', isSelect: false }, - { value: 'nweb', isSelect: false }, - { value: 'ohos', isSelect: true }, - { value: 'pagecache', isSelect: true }, - { value: 'power', isSelect: false }, - { value: 'regulators', isSelect: false }, - { value: 'rpc', isSelect: true }, - { value: 'samgr', isSelect: false }, - { value: 'sched', isSelect: true }, - { value: 'sensors', isSelect: false }, - { value: 'sync', isSelect: true }, - { value: 'usb', isSelect: false }, - { value: 'ufs', isSelect: false }, - { value: 'useriam', isSelect: false }, - { value: 'virse', isSelect: false }, - { value: 'window', isSelect: true }, - { value: 'workq', isSelect: true }, - { value: 'zaudio', isSelect: true }, - { value: 'zcamera', isSelect: true }, - { value: 'zimage', isSelect: true }, - { value: 'zmedia', isSelect: true }, - ]; + private initHiTraceConfigList(): void { this.hitrace = this.shadowRoot?.getElementById('hitrace') as SpCheckDesBox; let parent = this.shadowRoot?.querySelector('.user-events') as Element; - this.hitraceConfigList?.forEach((hitraceConfig: any) => { + hiTraceConfigList.forEach((hitraceConfig: any) => { let litCheckBox = new LitCheckBox(); litCheckBox.setAttribute('name', 'userEvents'); litCheckBox.value = hitraceConfig.value; @@ -275,7 +163,7 @@ export class SpProbesConfig extends BaseElement { if (this.hitrace?.checked === false) { this.hitrace.checked = detail!.checked; } - if (detail!.checked === false && this.hitrace?.checked === true) { + if (!detail!.checked && this.hitrace?.checked === true) { let hasChecked = false; const nodes = parent?.querySelectorAll('lit-check-box[name=userEvents]'); nodes.forEach((vv) => { @@ -291,11 +179,22 @@ export class SpProbesConfig extends BaseElement { }); parent.append(litCheckBox); }); - this.bufferSizeSliderInit(); + } + initElements(): void { + this.ftraceBuffSizeResultInput = this.shadowRoot?.querySelector('.ftrace-buff-size-result') as HTMLInputElement; + this.ftraceBuffSizeResultInput!.addEventListener('keydown', (ev: any) => { + if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { + ev.preventDefault(); + } + }); + this.initTraceConfigList(); + this.initMemoryConfigList(); + this.initAbilityConfigList(); + this.initHiTraceConfigList(); + this.bufferSizeSliderInit(); let litSwitch = this.shadowRoot?.querySelector('lit-switch') as LitSwitch; this.ftraceSlider = this.shadowRoot?.querySelector('#ftrace-buff-size-slider'); - litSwitch.addEventListener('change', (event: any) => { let detail = event.detail; if (detail!.checked) { @@ -306,10 +205,10 @@ export class SpProbesConfig extends BaseElement { }); } - private bufferSizeSliderInit() { - let ftraceBufferSizeSlider = this.shadowRoot?.querySelector('#ftrace-buff-size-slider') as LitSlider; + private bufferSizeSliderInit(): void { + let bufferSizeSlider = this.shadowRoot?.querySelector('#ftrace-buff-size-slider') as LitSlider; this.ftraceBufferSizeResult = this.shadowRoot?.querySelector('#ftrace-buff-size-div') as HTMLDivElement; - ftraceBufferSizeSlider.sliderStyle = { + bufferSizeSlider.sliderStyle = { minRange: 2048, maxRange: 307200, defaultValue: '20480', @@ -318,298 +217,127 @@ export class SpProbesConfig extends BaseElement { lineColor: 'var(--dark-color3,#46B1E3)', buttonColor: '#999999', }; - let ftraceBufferSizeSliderParent = ftraceBufferSizeSlider!.parentNode as Element; - let ftraceBuffSizeResultInput = this.shadowRoot?.querySelector('.ftrace-buff-size-result') as HTMLInputElement; - ftraceBuffSizeResultInput!.onkeydown = (ev): void => { + let bufferSizeSliderParent = bufferSizeSlider!.parentNode as Element; + let buffSizeResult = this.shadowRoot?.querySelector('.ftrace-buff-size-result') as HTMLInputElement; + buffSizeResult!.onkeydown = (ev): void => { // @ts-ignore if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { ev.preventDefault(); } }; - ftraceBuffSizeResultInput.value = ftraceBufferSizeSlider.sliderStyle.defaultValue; - ftraceBufferSizeSlider.addEventListener('input', (evt) => { - ftraceBuffSizeResultInput.parentElement!.classList.remove('border-red'); + buffSizeResult.value = bufferSizeSlider.sliderStyle.defaultValue; + bufferSizeSlider.addEventListener('input', () => { + buffSizeResult.parentElement!.classList.remove('border-red'); if (this.ftraceBufferSizeResult!.hasAttribute('percent')) { - ftraceBuffSizeResultInput.value = Number(this.ftraceBufferSizeResult!.getAttribute('percent')).toString(); + buffSizeResult.value = Number(this.ftraceBufferSizeResult!.getAttribute('percent')).toString(); } else { - ftraceBuffSizeResultInput.value = '20480'; + buffSizeResult.value = '20480'; } }); - ftraceBufferSizeSliderParent.setAttribute('percent', '20480'); - ftraceBuffSizeResultInput.style.color = 'var(--dark-color1,#000000)'; - ftraceBuffSizeResultInput.addEventListener('input', (ev) => { - if (this.ftraceBufferSizeResult!.hasAttribute('percent')) { - this.ftraceBufferSizeResult!.removeAttribute('percent'); - } - ftraceBuffSizeResultInput.style.color = 'var(--dark-color1,#000000)'; - ftraceBuffSizeResultInput.parentElement!.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; - ftraceBuffSizeResultInput.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; - if (ftraceBuffSizeResultInput.value.trim() === '') { - ftraceBuffSizeResultInput.style.color = 'red'; - ftraceBufferSizeSliderParent.setAttribute('percent', '20480'); - return; - } - let ftraceBufferSize = Number(ftraceBuffSizeResultInput.value); - if ( - ftraceBufferSize < ftraceBufferSizeSlider!.sliderStyle.minRange || - ftraceBufferSize > ftraceBufferSizeSlider!.sliderStyle.maxRange - ) { - ftraceBuffSizeResultInput.parentElement!.classList.add('border-red'); - ftraceBufferSizeSliderParent.setAttribute('percent', '20480'); - } else { - ftraceBuffSizeResultInput.parentElement!.classList.remove('border-red'); - ftraceBufferSizeSlider!.percent = ftraceBuffSizeResultInput.value; - let htmlInputElement = ftraceBufferSizeSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; - htmlInputElement.value = ftraceBuffSizeResultInput.value; - ftraceBufferSizeSliderParent.setAttribute('percent', ftraceBuffSizeResultInput.value); - ftraceBufferSizeSliderParent.setAttribute('percentValue', ftraceBuffSizeResultInput.value); - } + bufferSizeSliderParent.setAttribute('percent', '20480'); + buffSizeResult.style.color = 'var(--dark-color1,#000000)'; + buffSizeResult.addEventListener('input', () => { + this.ftraceBuffSizeResultInputHandler(buffSizeResult, bufferSizeSliderParent, bufferSizeSlider); }); - ftraceBuffSizeResultInput.addEventListener('focusout', (ev) => { - if (ftraceBuffSizeResultInput.value.trim() === '') { - ftraceBuffSizeResultInput.parentElement!.classList.remove('border-red'); - ftraceBufferSizeSliderParent.setAttribute('percent', '20480'); - ftraceBuffSizeResultInput.value = '20480'; - ftraceBuffSizeResultInput.style.color = 'var(--dark-color,#6a6f77)'; - ftraceBufferSizeSliderParent.setAttribute('percent', ftraceBuffSizeResultInput.value); - ftraceBufferSizeSliderParent.setAttribute('percentValue', ftraceBuffSizeResultInput.value); - ftraceBufferSizeSlider!.percent = ftraceBuffSizeResultInput.value; - let htmlInputElement = ftraceBufferSizeSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; - htmlInputElement.value = ftraceBuffSizeResultInput.value; + buffSizeResult.addEventListener('focusout', () => { + if (buffSizeResult.value.trim() === '') { + buffSizeResult.parentElement!.classList.remove('border-red'); + bufferSizeSliderParent.setAttribute('percent', '20480'); + buffSizeResult.value = '20480'; + buffSizeResult.style.color = 'var(--dark-color,#6a6f77)'; + bufferSizeSliderParent.setAttribute('percent', buffSizeResult.value); + bufferSizeSliderParent.setAttribute('percentValue', buffSizeResult.value); + bufferSizeSlider!.percent = buffSizeResult.value; + let htmlInputElement = bufferSizeSlider!.shadowRoot?.querySelector('#slider') as HTMLInputElement; + htmlInputElement.value = buffSizeResult.value; } }); } - private unDisable() { + private ftraceBuffSizeResultInputHandler( + buffSizeResultEl: HTMLInputElement, + bufferSizeSliderParentEl: Element, + bufferSizeSliderEl: LitSlider + ): void { + if (this.ftraceBufferSizeResult!.hasAttribute('percent')) { + this.ftraceBufferSizeResult!.removeAttribute('percent'); + } + buffSizeResultEl.style.color = 'var(--dark-color1,#000000)'; + buffSizeResultEl.parentElement!.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; + buffSizeResultEl.style.backgroundColor = 'var(--dark-background5,#F2F2F2)'; + if (buffSizeResultEl.value.trim() === '') { + buffSizeResultEl.style.color = 'red'; + bufferSizeSliderParentEl.setAttribute('percent', '20480'); + return; + } + let ftraceBufferSize = Number(buffSizeResultEl.value); + if ( + ftraceBufferSize < bufferSizeSliderEl!.sliderStyle.minRange || + ftraceBufferSize > bufferSizeSliderEl!.sliderStyle.maxRange + ) { + buffSizeResultEl.parentElement!.classList.add('border-red'); + bufferSizeSliderParentEl.setAttribute('percent', '20480'); + } else { + buffSizeResultEl.parentElement!.classList.remove('border-red'); + bufferSizeSliderEl!.percent = buffSizeResultEl.value; + let htmlInputElement = bufferSizeSliderEl!.shadowRoot?.querySelector('#slider') as HTMLInputElement; + htmlInputElement.value = buffSizeResultEl.value; + bufferSizeSliderParentEl.setAttribute('percent', buffSizeResultEl.value); + bufferSizeSliderParentEl.setAttribute('percentValue', buffSizeResultEl.value); + } + } + + private unDisable(): void { this.startSamp = true; let checkDesBoxDis = this.shadowRoot?.querySelectorAll('check-des-box'); let litCheckBoxDis = this.shadowRoot?.querySelectorAll('lit-check-box'); - let defaultSelected: any = []; defaultSelected = defaultSelected.concat( - this.traceConfigList, - this.memoryConfigList, - this.abilityConfigList, - this.hitraceConfigList + traceConfigList, + memoryConfigList, + abilityConfigList, + hiTraceConfigList ); - - this.shadowRoot?.querySelector("[value='Hitrace categories']")?.setAttribute('checked', 'true'); + this.shadowRoot?.querySelector('[value=\'Hitrace categories\']')?.setAttribute('checked', 'true'); this.ftraceSlider!.removeAttribute('disabled'); - - checkDesBoxDis?.forEach((item: any) => { + checkDesBoxDis?.forEach((item: SpCheckDesBox) => { item.removeAttribute('disabled'); }); - - litCheckBoxDis?.forEach((item: any) => { + litCheckBoxDis?.forEach((item: LitCheckBox) => { item.removeAttribute('disabled'); }); - defaultSelected.filter((item: any) => { - if (item.isSelect) - this.shadowRoot?.querySelector(`[value='${item.value}']`)?.setAttribute('checked', 'true'); + if (item.isSelect) { + this.shadowRoot?.querySelector(`[value='${item.value}']`)?. + setAttribute('checked', 'true'); + } }); } - private disable() { + private disable(): void { this.startSamp = false; let checkDesBoxDis = this.shadowRoot?.querySelectorAll('check-des-box'); let litCheckBoxDis = this.shadowRoot?.querySelectorAll('lit-check-box'); this.ftraceSlider!.setAttribute('disabled', ''); - checkDesBoxDis?.forEach((item: any) => { + checkDesBoxDis?.forEach((item: SpCheckDesBox) => { item.setAttribute('disabled', ''); item.checked = false; }); - litCheckBoxDis?.forEach((item: any) => { + litCheckBoxDis?.forEach((item: LitCheckBox) => { item.setAttribute('disabled', ''); item.checked = false; }); } initHtml(): string { - return ` - -
-
- Record mode - -
-
-
-
-
- - -
- -
-
-
-
-

Buffer Size

-

The ftrace buffer size range is 2048 KB to 307200 KB

-
-
- - -
- - KB -
-
-
-
-
-
- Memory Config -
-
-
-
- Ability Config -
-
-
-
- `; + return SpProbesConfigHtml; } //当 custom element首次被插入文档DOM时,被调用。 - public connectedCallback() { + public connectedCallback(): void { let parent = this.shadowRoot?.querySelector('.user-events') as Element; const siblingNode = parent?.querySelectorAll('lit-check-box[name=userEvents]'); this.hitrace!.addEventListener('onchange', (ev: CustomEventInit) => { @@ -621,3 +349,118 @@ export class SpProbesConfig extends BaseElement { }); } } + +const hiTraceConfigList = [ + {value: 'ability', isSelect: true}, + {value: 'accesscontrol', isSelect: false}, + {value: 'accessibility', isSelect: false}, + {value: 'account', isSelect: false}, + {value: 'ace', isSelect: true}, + {value: 'app', isSelect: true}, + {value: 'ark', isSelect: true}, + {value: 'binder', isSelect: true}, + {value: 'bluetooth', isSelect: false}, + {value: 'cloud', isSelect: false}, + {value: 'commonlibrary', isSelect: false}, + {value: 'daudio', isSelect: false}, + {value: 'dcamera', isSelect: false}, + {value: 'deviceauth', isSelect: false}, + {value: 'devicemanager', isSelect: false}, + {value: 'deviceprofile', isSelect: false}, + {value: 'dhfwk', isSelect: false}, + {value: 'dinput', isSelect: false}, + {value: 'disk', isSelect: true}, + {value: 'distributeddatamgr', isSelect: false}, + {value: 'dlpcre', isSelect: false}, + {value: 'dsched', isSelect: false}, + {value: 'dscreen', isSelect: false}, + {value: 'dslm', isSelect: false}, + {value: 'dsoftbus', isSelect: false}, + {value: 'ffrt', isSelect: false}, + {value: 'filemanagement', isSelect: false}, + {value: 'freq', isSelect: true}, + {value: 'graphic', isSelect: true}, + {value: 'gresource', isSelect: false}, + {value: 'hdcd', isSelect: false}, + {value: 'hdf', isSelect: false}, + {value: 'huks', isSelect: false}, + {value: 'i2c', isSelect: false}, + {value: 'idle', isSelect: true}, + {value: 'interconn', isSelect: false}, + {value: 'irq', isSelect: true}, + {value: 'mdfs', isSelect: false}, + {value: 'memory', isSelect: false}, + {value: 'memreclaim', isSelect: true}, + {value: 'misc', isSelect: false}, + {value: 'mmc', isSelect: true}, + {value: 'msdp', isSelect: false}, + {value: 'multimodalinput', isSelect: true}, + {value: 'musl', isSelect: false}, + {value: 'net', isSelect: false}, + {value: 'notification', isSelect: false}, + {value: 'nweb', isSelect: false}, + {value: 'ohos', isSelect: true}, + {value: 'pagecache', isSelect: true}, + {value: 'power', isSelect: false}, + {value: 'regulators', isSelect: false}, + {value: 'rpc', isSelect: true}, + {value: 'samgr', isSelect: false}, + {value: 'sched', isSelect: true}, + {value: 'sensors', isSelect: false}, + {value: 'sync', isSelect: true}, + {value: 'usb', isSelect: false}, + {value: 'ufs', isSelect: false}, + {value: 'useriam', isSelect: false}, + {value: 'virse', isSelect: false}, + {value: 'window', isSelect: true}, + {value: 'workq', isSelect: true}, + {value: 'zaudio', isSelect: true}, + {value: 'zcamera', isSelect: true}, + {value: 'zimage', isSelect: true}, + {value: 'zmedia', isSelect: true}, +]; + +const traceConfigList = [ + { + value: 'Scheduling details', + isSelect: true, + des: 'enables high-detailed tracking of scheduling events', + }, + { + value: 'CPU Frequency and idle states', + isSelect: true, + des: 'Records cpu frequency and idle state change viaftrace', + }, + { + value: 'Advanced ftrace config', + isSelect: false, + des: + 'Enable individual events and tune the kernel-tracing(ftrace) module.' + + 'The events enabled here are in addition to those from' + + ' enabled by other probes.', + }, +]; + +const memoryConfigList = [ + { + value: 'Kernel meminfo', + isSelect: false, + des: 'polling of /proc/meminfo', + }, + { + value: 'Virtual memory stats', + isSelect: false, + des: + 'Periodically polls virtual memory stats from /proc/vmstat.' + + ' Allows to gather statistics about swap,' + + 'eviction, compression and pagecache efficiency', + }, +]; + +const abilityConfigList = [ + { + value: 'AbilityMonitor', + isSelect: false, + des: 'Tracks the AbilityMonitor', + }, +]; diff --git a/ide/src/trace/component/setting/SpRecordPerf.html.ts b/ide/src/trace/component/setting/SpRecordPerf.html.ts new file mode 100644 index 0000000000000000000000000000000000000000..573f17e57e77a5e92f8af011ab07d6e462fb85e7 --- /dev/null +++ b/ide/src/trace/component/setting/SpRecordPerf.html.ts @@ -0,0 +1,166 @@ +/* + * 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. + */ + +export const SpRecordPerfHtml = ` + +
+
+ Long trace mode! If current data Trace is too large, it may not open! +
+
+
+ +
+`; diff --git a/ide/src/trace/component/setting/SpRecordPerf.ts b/ide/src/trace/component/setting/SpRecordPerf.ts index 99fe8ce8e222cacb1043e1749f6a8d262a6f2052..86c95802288fbc96679118d51fef9637cc987a64 100644 --- a/ide/src/trace/component/setting/SpRecordPerf.ts +++ b/ide/src/trace/component/setting/SpRecordPerf.ts @@ -29,6 +29,7 @@ import { SpApplication } from '../../SpApplication'; import { LitSearch } from '../trace/search/Search'; import { Cmd } from '../../../command/Cmd'; import { CmdConstant } from '../../../command/CmdConstant'; +import { SpRecordPerfHtml } from './SpRecordPerf.html'; @element('sp-record-perf') export class SpRecordPerf extends BaseElement { @@ -93,14 +94,7 @@ export class SpRecordPerf extends BaseElement { perfConfig.process = 'ALL'; break; } - if (processSelect.value.length > 0) { - let result = processSelect.value.match(/\((.+?)\)/g); - if (result) { - perfConfig.process = result.toString().replaceAll('(', '').replaceAll(')', ''); - } else { - perfConfig.process = processSelect.value; - } - } + perfConfig = this.perfConfigByProcess(processSelect, perfConfig); break; case 'CPU': let selectV = value as LitSelectV; @@ -115,7 +109,6 @@ export class SpRecordPerf extends BaseElement { } break; case 'CPU Percent': - let selectSlider = value as LitSlider; let parEle = value.parentElement; if (parEle!.hasAttribute('percent')) { let percent = parEle!.getAttribute('percent'); @@ -124,13 +117,13 @@ export class SpRecordPerf extends BaseElement { break; case 'Frequency': let input = value as HTMLInputElement; - if (input.value != '') { + if (input.value !== '') { perfConfig.frequency = Number(input.value); } break; case 'Period': let periodInput = value as HTMLInputElement; - if (periodInput.value != '') { + if (periodInput.value !== '') { perfConfig.period = Number(periodInput.value); } break; @@ -144,18 +137,17 @@ export class SpRecordPerf extends BaseElement { break; case 'Call Stack': let callStack = value as LitSelect; - if (callStack.value != '') { + if (callStack.value !== '') { perfConfig.callStack = callStack.value; } break; case 'Branch': let branch = value as LitSelect; - if (branch.value != '') { + if (branch.value !== '') { perfConfig.branch = branch.value; } break; case 'Mmap Pages': - let pages = value as LitSlider; let parent = value.parentElement; if (parent!.hasAttribute('percent')) { let pagesPercent = parent!.getAttribute('percent'); @@ -164,7 +156,7 @@ export class SpRecordPerf extends BaseElement { break; case 'Clock Type': let clock = value as LitSelect; - if (clock.value != '') { + if (clock.value !== '') { perfConfig.clockType = clock.value; } break; @@ -174,6 +166,18 @@ export class SpRecordPerf extends BaseElement { return perfConfig; } + private perfConfigByProcess(processSelect: LitSelectV, perfConfig: PerfConfig): PerfConfig { + if (processSelect.value.length > 0) { + let result = processSelect.value.match(/\((.+?)\)/g); + if (result) { + perfConfig.process = result.toString().replaceAll('(', '').replaceAll(')', ''); + } else { + perfConfig.process = processSelect.value; + } + } + return perfConfig; + } + initElements(): void { let that = this; this.initConfigList(); @@ -200,43 +204,47 @@ export class SpRecordPerf extends BaseElement { case 'select-multiple': let html = ''; let placeholder = config.selectArray[0]; - if (config.title == 'Event List') { + if (config.title === 'Event List') { placeholder = 'NONE'; } - html += ``; + html += ``; config.selectArray.forEach((value: string) => { html += `${value}`; }); - html += ``; + html += ''; recordPerfDiv.innerHTML = recordPerfDiv.innerHTML + html; break; case 'lit-slider': - let silder = `
- -
`; + let silder = ` +
+
`; recordPerfDiv.innerHTML = recordPerfDiv.innerHTML + silder; let litSlider = recordPerfDiv.querySelector('.silderclass'); litSlider!.percent = config.litSliderStyle.defaultValue; let sliderBody = recordPerfDiv.querySelector('.sliderBody'); let bufferInput = recordPerfDiv?.querySelector('.sliderInput') as HTMLInputElement; - litSlider!.addEventListener('input', (evt) => { + litSlider!.addEventListener('input', () => { bufferInput.value = sliderBody!.getAttribute('percent') + config.litSliderStyle.resultUnit; }); litSlider!.sliderStyle = config.litSliderStyle; break; case 'Mmap-lit-slider': let defaultValue = Math.pow(2, config.litSliderStyle.defaultValue); - let mapsilder = `
- -
`; + let mapsilder = ` +
`; recordPerfDiv.innerHTML = recordPerfDiv.innerHTML + mapsilder; let maplitSlider = recordPerfDiv.querySelector('.silderclass'); maplitSlider!.percent = config.litSliderStyle.defaultValue; let mapsliderBody = recordPerfDiv.querySelector('.sliderBody'); let mapbufferInput = recordPerfDiv?.querySelector('.sliderInput') as HTMLInputElement; - maplitSlider!.addEventListener('input', (evt) => { + maplitSlider!.addEventListener('input', () => { let percnet = mapsliderBody!.getAttribute('percent'); - if (percnet != null) { + if (percnet !== null) { mapbufferInput.value = Math.pow(2, Number(percnet)) + config.litSliderStyle.resultUnit; } }); @@ -248,30 +256,27 @@ export class SpRecordPerf extends BaseElement { recordPerfInput.textContent = config.value; recordPerfInput.value = config.value; recordPerfInput.title = config.title; - recordPerfInput.oninput = (ev) => { + recordPerfInput.oninput = (): void => { recordPerfInput.value = recordPerfInput.value.replace(/\D/g, ''); }; recordPerfDiv.appendChild(recordPerfInput); break; case 'select': let recordPerfSelect = ''; - recordPerfSelect += ``; + recordPerfSelect += ``; config.selectArray.forEach((value: string) => { recordPerfSelect += `${value}`; }); - recordPerfSelect += ``; + recordPerfSelect += ''; recordPerfDiv.innerHTML = recordPerfDiv.innerHTML + recordPerfSelect; break; case 'switch': let recordPerfSwitch = document.createElement('lit-switch') as LitSwitch; recordPerfSwitch.className = 'config'; recordPerfSwitch.title = config.title; - if (config.value) { - recordPerfSwitch.checked = true; - } else { - recordPerfSwitch.checked = false; - } - if (config.title == 'Start Hiperf Sampling') { + recordPerfSwitch.checked = !!config.value; + if (config.title === 'Start Hiperf Sampling') { recordPerfSwitch.addEventListener('change', (event: CustomEventInit) => { let detail = event.detail; if (detail!.checked) { @@ -295,10 +300,10 @@ export class SpRecordPerf extends BaseElement { }); let sp = document.querySelector('sp-application') as SpApplication; let recordPerfSearch = sp?.shadowRoot?.querySelector('#lit-record-search') as LitSearch; - this.processSelect = this.shadowRoot?.querySelector("lit-select-v[title='Process']"); + this.processSelect = this.shadowRoot?.querySelector('lit-select-v[title=\'Process\']'); this.recordProcessInput = this.processSelect?.shadowRoot?.querySelector('input'); let querySelector = this.processSelect!.shadowRoot?.querySelector('input') as HTMLInputElement; - querySelector.addEventListener('mousedown', (ev) => { + querySelector.addEventListener('mousedown', () => { if (SpRecordTrace.serialNumber === '') { this.processSelect!.dataSource([], 'ALL-Process'); } else { @@ -310,7 +315,7 @@ export class SpRecordPerf extends BaseElement { (processList) => { this.processSelect?.dataSource(processList, 'ALL-Process'); }, - (rejected) => { + () => { sp.search = true; recordPerfSearch.clear(); recordPerfSearch.setPercent('please kill other hdc-server !', -2); @@ -319,16 +324,16 @@ export class SpRecordPerf extends BaseElement { } }); - this.cpuSelect = this.shadowRoot?.querySelector("lit-select-v[title='CPU']"); + this.cpuSelect = this.shadowRoot?.querySelector('lit-select-v[title=\'CPU\']'); let inputCpu = this.cpuSelect!.shadowRoot?.querySelector('input') as HTMLInputElement; let cpuData: Array = []; - inputCpu.addEventListener('mousedown', (ev) => { - if (SpRecordTrace.serialNumber == '') { + inputCpu.addEventListener('mousedown', () => { + if (SpRecordTrace.serialNumber === '') { this.cpuSelect!.dataSource([], 'ALL-CPU'); } }); inputCpu!.addEventListener('mouseup', () => { - if (SpRecordTrace.serialNumber == '') { + if (SpRecordTrace.serialNumber === '') { this.cpuSelect?.dataSource([], ''); } else { if (sp.search) { @@ -367,16 +372,16 @@ export class SpRecordPerf extends BaseElement { } } }); - this.eventSelect = this.shadowRoot?.querySelector("lit-select-v[title='Event List']"); + this.eventSelect = this.shadowRoot?.querySelector('lit-select-v[title=\'Event List\']'); let inputEvent = this.eventSelect!.shadowRoot?.querySelector('input') as HTMLInputElement; let eventData: Array = []; - inputEvent.addEventListener('mousedown', (ev) => { - if (SpRecordTrace.serialNumber == '') { + inputEvent.addEventListener('mousedown', () => { + if (SpRecordTrace.serialNumber === '') { this.eventSelect!.dataSource([], ''); } }); inputEvent!.addEventListener('click', () => { - if (SpRecordTrace.serialNumber == '') { + if (SpRecordTrace.serialNumber === '') { this.eventSelect?.dataSource( [ 'hw-cpu-cycles', @@ -445,16 +450,16 @@ export class SpRecordPerf extends BaseElement { } }); - this.frequencySetInput = this.shadowRoot?.querySelector("input[title='Frequency']"); + this.frequencySetInput = this.shadowRoot?.querySelector('input[title=\'Frequency\']'); this.frequencySetInput!.onkeydown = (ev): void => { // @ts-ignore if (ev.key === '0' && ev.target.value.length === 1 && ev.target.value === '0') { ev.preventDefault(); } }; - this.offCPUSwitch = this.shadowRoot?.querySelector("lit-switch[title='Off CPU']"); - this.callSelect = this.shadowRoot?.querySelector("lit-select[title='Call Stack']"); - this.addOptionButton!.addEventListener('click', (event) => { + this.offCPUSwitch = this.shadowRoot?.querySelector('lit-switch[title=\'Off CPU\']'); + this.callSelect = this.shadowRoot?.querySelector('lit-select[title=\'Call Stack\']'); + this.addOptionButton!.addEventListener('click', () => { if (!this.startSamp) { return; } @@ -464,7 +469,7 @@ export class SpRecordPerf extends BaseElement { this.disable(); } - getSoftHardWareEvents(eventListResult: Map) { + getSoftHardWareEvents(eventListResult: Map): string[] { let shEvents = []; let hardwareEvents = eventListResult.get('hardware'); if (hardwareEvents) { @@ -490,22 +495,23 @@ export class SpRecordPerf extends BaseElement { if (line.startsWith('Supported')) { let startSign: string = 'for'; type = line.substring(line.indexOf(startSign) + startSign.length, line.lastIndexOf(':')).trim(); - events = new Array(); + events = []; eventMap.set(type, events); - } else if (line.indexOf('not support') != -1 || line.trim().length == 0 || line.indexOf('Text file busy') != -1) { + } else if (line.indexOf('not support') !== -1 || line.trim().length === 0 || + line.indexOf('Text file busy') !== -1) { // do not need deal with it } else { let event: string = line.split(' ')[0]; let ventMap = eventMap.get(type); - if (ventMap != null) { - ventMap.push(event); + if (ventMap !== null) { + ventMap!.push(event); } } } return eventMap; } - private unDisable() { + private unDisable(): void { if (this.processSelect) { this.processSelect.removeAttribute('disabled'); } @@ -523,7 +529,7 @@ export class SpRecordPerf extends BaseElement { } } - private disable() { + private disable(): void { if (this.processSelect) { this.processSelect.setAttribute('disabled', ''); } @@ -609,7 +615,7 @@ export class SpRecordPerf extends BaseElement { }, { title: 'No Inherit', - des: "Don't trace child processes", + des: 'Don\'t trace child processes', hidden: true, type: 'switch', value: false, @@ -664,157 +670,7 @@ export class SpRecordPerf extends BaseElement { } initHtml(): string { - return ` - -
-
- Long trace mode! If current data Trace is too large, it may not open! -
-
-
- -
- `; + return SpRecordPerfHtml; } } diff --git a/ide/src/trace/component/trace/SpChartList.ts b/ide/src/trace/component/trace/SpChartList.ts index 2ab4e0b393815921fd7b1bb2ebc2ba9f66f2adaf..5d0a252ae20ec3a8f0e33b2195ff2673caa7cd8e 100644 --- a/ide/src/trace/component/trace/SpChartList.ts +++ b/ide/src/trace/component/trace/SpChartList.ts @@ -28,7 +28,7 @@ import { } from '../../database/ui-worker/ProcedureWorkerCommon'; import { Flag } from './timer-shaft/Flag'; import { TimerShaftElement } from './TimerShaftElement'; -import { CpuStruct } from '../../database/ui-worker/ProcedureWorkerCPU'; +import { CpuStruct } from '../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { WakeupBean } from '../../bean/WakeupBean'; import { LitIcon } from '../../../base-ui/icon/LitIcon'; diff --git a/ide/src/trace/component/trace/base/ColorUtils.ts b/ide/src/trace/component/trace/base/ColorUtils.ts index fd9074b4fa44e9d8fa96ae91407609c8a09df3b6..1e6128aa25b6c0146858643a879102ffc9addf34 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'; +import { CpuStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCPU'; export class ColorUtils { public static GREY_COLOR: string = '#f0f0f0'; diff --git a/ide/src/trace/component/trace/base/CustomThemeColor.ts b/ide/src/trace/component/trace/base/CustomThemeColor.ts index 762cc311ed6f06cfea7cfea62b4d7e9f516102c4..010704ae9789ab2312619ed551daced22642f22b 100644 --- a/ide/src/trace/component/trace/base/CustomThemeColor.ts +++ b/ide/src/trace/component/trace/base/CustomThemeColor.ts @@ -92,44 +92,11 @@ export class CustomThemeColor extends BaseElement { } initElements(): void { - this.radios = this.shadowRoot?.querySelectorAll('.litRadio'); this.colorsEl = this.shadowRoot?.querySelector('.colors') as HTMLDivElement; this.application = document.querySelector('body > sp-application') as SpApplication; this.systemTrace = this.application.shadowRoot!.querySelector('#sp-system-trace'); let close = this.shadowRoot?.querySelector('.page-close'); - if (this.radios) { - for (let i = 0; i < this.radios.length; i++) { - this.radios![i].shadowRoot!.querySelector('.selected')!.classList.add('blue'); - this.radios[i].addEventListener('click', (evt) => { - // 点击颜色模式的单选框,色板切换 - if (this.radios![i].innerHTML === Theme.LIGHT) { - if (this.radios![i].getAttribute('checked') === null) { - this.colorsArray = - window.localStorage.getItem('LightThemeColors') === null - ? [...ColorUtils.FUNC_COLOR_A] - : JSON.parse(window.localStorage.getItem('LightThemeColors')!); - this.theme = Theme.LIGHT; - } else { - return; - } - } else if (this.radios![i].innerHTML === Theme.DARK) { - if (this.radios![i].getAttribute('checked') === null) { - this.colorsArray = - window.localStorage.getItem('DarkThemeColors') === null - ? [...ColorUtils.FUNC_COLOR_B] - : JSON.parse(window.localStorage.getItem('DarkThemeColors')!); - this.theme = Theme.DARK; - } else { - return; - } - } - this.colorsEl!.innerHTML = ''; - this.createColorsEl(this.colorsEl!); - this.confirmOPerate(); - }); - } - } - + this.radioClick(); close!.addEventListener('click', (ev) => { if (this.application!.hasAttribute('custom-color')) { this.application!.removeAttribute('custom-color'); @@ -165,6 +132,42 @@ export class CustomThemeColor extends BaseElement { }); } + private radioClick(): void { + this.radios = this.shadowRoot?.querySelectorAll('.litRadio'); + if (this.radios) { + for (let i = 0; i < this.radios.length; i++) { + this.radios![i].shadowRoot!.querySelector('.selected')!.classList.add('blue'); + this.radios[i].addEventListener('click', (evt) => { + // 点击颜色模式的单选框,色板切换 + if (this.radios![i].innerHTML === Theme.LIGHT) { + if (this.radios![i].getAttribute('checked') === null) { + this.colorsArray = + window.localStorage.getItem('LightThemeColors') === null + ? [...ColorUtils.FUNC_COLOR_A] + : JSON.parse(window.localStorage.getItem('LightThemeColors')!); + this.theme = Theme.LIGHT; + } else { + return; + } + } else if (this.radios![i].innerHTML === Theme.DARK) { + if (this.radios![i].getAttribute('checked') === null) { + this.colorsArray = + window.localStorage.getItem('DarkThemeColors') === null + ? [...ColorUtils.FUNC_COLOR_B] + : JSON.parse(window.localStorage.getItem('DarkThemeColors')!); + this.theme = Theme.DARK; + } else { + return; + } + } + this.colorsEl!.innerHTML = ''; + this.createColorsEl(this.colorsEl!); + this.confirmOPerate(); + }); + } + } + } + confirmOPerate() { window.localStorage.setItem('Theme', this.theme); if (this.theme === Theme.LIGHT) { diff --git a/ide/src/trace/component/trace/base/RangeSelect.ts b/ide/src/trace/component/trace/base/RangeSelect.ts index a46dfbf4d5caa0eaf70eaceccb402cd33c163d5c..1606e4d46445b10505ddc6fefd79cf48c74645a6 100644 --- a/ide/src/trace/component/trace/base/RangeSelect.ts +++ b/ide/src/trace/component/trace/base/RangeSelect.ts @@ -19,7 +19,7 @@ import { TimerShaftElement } from '../TimerShaftElement'; import { info } from '../../../../log/Log'; import './Extension'; import { SpSystemTrace } from '../../SpSystemTrace'; -import { querySearchRowFuncData } from '../../../database/SqlLite'; +import {querySearchRowFuncData} from "../../../database/sql/Func.sql"; export class RangeSelect { private rowsEL: HTMLDivElement | undefined | null; @@ -138,86 +138,36 @@ export class RangeSelect { this.endPageX = ev.pageX; this.endPageY = ev.pageY; if (this.isTouchMark(ev) && TraceRow.rangeSelectObject) { - info('isTouchMark'); - let x1 = - ((TraceRow.rangeSelectObject!.startNS! - TraceRow.range!.startNS) * - (this.timerShaftEL?.canvas?.clientWidth || 0)) / - (TraceRow.range!.endNS - TraceRow.range!.startNS); - let x2 = - ((TraceRow.rangeSelectObject!.endNS! - TraceRow.range!.startNS) * - (this.timerShaftEL?.canvas?.clientWidth || 0)) / - (TraceRow.range!.endNS - TraceRow.range!.startNS); - this.mark = { startMark: x1, endMark: x2 }; - let mouseX = ev.pageX - this.rowsPaneEL!.getBoundingClientRect().left - 248; - if (mouseX > x1 - 5 && mouseX < x1 + 5) { - this.isHover = true; - document.body.style.cursor = 'ew-resize'; - this.movingMark = x1 < x2 ? 'markA' : 'markB'; - } else if (mouseX > x2 - 5 && mouseX < x2 + 5) { - this.isHover = true; - document.body.style.cursor = 'ew-resize'; - this.movingMark = x2 < x1 ? 'markA' : 'markB'; - } else { - this.isHover = false; - document.body.style.cursor = 'default'; - } + this.handleTouchMark(ev); } else { document.body.style.cursor = 'default'; } if (this.isHover && this.isMouseDown) { - let rangeSelect: RangeSelectStruct | undefined; - this.rangeTraceRow = rows.filter((it) => { - if (it.rangeSelect) { - if (!rangeSelect) { - rangeSelect = new RangeSelectStruct(); - let mouseX = ev.pageX - this.rowsEL!.getBoundingClientRect().left - 248; - mouseX = mouseX < 0 ? 0 : mouseX; - let markA = this.movingMark == 'markA' ? mouseX : this.mark.startMark; - let markB = this.movingMark == 'markB' ? mouseX : this.mark.endMark; - let startX = markA < markB ? markA : markB; - let endX = markB < markA ? markA : markB; - rangeSelect.startX = startX; - rangeSelect.endX = endX; - rangeSelect.startNS = RangeSelect.SetNS(it, startX); - rangeSelect.endNS = RangeSelect.SetNS(it, endX); - if (rangeSelect.startNS <= TraceRow.range!.startNS) { - rangeSelect.startNS = TraceRow.range!.startNS; - } - if (rangeSelect.endNS >= TraceRow.range!.endNS) { - rangeSelect.endNS = TraceRow.range!.endNS; - } - if (startX < 0) { - rangeSelect.startNS = TraceRow.rangeSelectObject!.startNS!; - } - if (endX > it.frame.width) { - rangeSelect.endNS = TraceRow.rangeSelectObject!.endNS!; - } - } - TraceRow.rangeSelectObject = rangeSelect; - return true; - } - }); - this.timerShaftEL!.sportRuler!.isRangeSelect = (this.rangeTraceRow?.length || 0) > 0; - this.timerShaftEL!.sportRuler!.draw(); + this.handleRangeSelectAndDraw(rows, ev); return; } if (!this.isMouseDown) { - this.timerShaftEL!.sportRuler!.isRangeSelect = this.rangeTraceRow?.isNotEmpty() ?? false; - this.timerShaftEL!.sportRuler!.draw(); + this.handleDrawForNotMouseDown(); return; } + this.handleRangeSelect(rows); + this.timerShaftEL!.sportRuler!.isRangeSelect = this.rangeTraceRow!.length > 0; + this.timerShaftEL!.sportRuler!.draw(); + } + + private handleRangeSelect(rows: Array>): void { let rangeSelect: RangeSelectStruct | undefined; let favoriteRect = this.trace?.favoriteChartListEL?.getBoundingClientRect(); let favoriteLimit = favoriteRect!.top + favoriteRect!.height; this.rangeTraceRow = rows.filter((it) => { let domRect = it.getBoundingClientRect(); - let itRect = { x: domRect.x, y: domRect.y, width: domRect.width, height: domRect.height }; + let itRect = {x: domRect.x, y: domRect.y, width: domRect.width, height: domRect.height}; if (itRect.y < favoriteLimit && !it.collect) { let offset = favoriteLimit - itRect.y; itRect.y = itRect.y + offset; itRect.height = itRect.height - offset; } - if(it.sticky){ + if (it.sticky) { itRect.y = 0; itRect.height = 0; } @@ -254,10 +204,76 @@ export class RangeSelect { row.docompositionList = []; }); } - this.timerShaftEL!.sportRuler!.isRangeSelect = this.rangeTraceRow?.length > 0; + } + + private handleDrawForNotMouseDown(): void { + this.timerShaftEL!.sportRuler!.isRangeSelect = this.rangeTraceRow?.isNotEmpty() ?? false; + this.timerShaftEL!.sportRuler!.draw(); + } + + private handleRangeSelectAndDraw(rows: Array>, ev: MouseEvent): void { + let rangeSelect: RangeSelectStruct | undefined; + this.rangeTraceRow = rows.filter((it) => { + if (it.rangeSelect) { + if (!rangeSelect) { + rangeSelect = new RangeSelectStruct(); + let mouseX = ev.pageX - this.rowsEL!.getBoundingClientRect().left - 248; + mouseX = mouseX < 0 ? 0 : mouseX; + let markA = this.movingMark == 'markA' ? mouseX : this.mark.startMark; + let markB = this.movingMark == 'markB' ? mouseX : this.mark.endMark; + let startX = markA < markB ? markA : markB; + let endX = markB < markA ? markA : markB; + rangeSelect.startX = startX; + rangeSelect.endX = endX; + rangeSelect.startNS = RangeSelect.SetNS(it, startX); + rangeSelect.endNS = RangeSelect.SetNS(it, endX); + if (rangeSelect.startNS <= TraceRow.range!.startNS) { + rangeSelect.startNS = TraceRow.range!.startNS; + } + if (rangeSelect.endNS >= TraceRow.range!.endNS) { + rangeSelect.endNS = TraceRow.range!.endNS; + } + if (startX < 0) { + rangeSelect.startNS = TraceRow.rangeSelectObject!.startNS!; + } + if (endX > it.frame.width) { + rangeSelect.endNS = TraceRow.rangeSelectObject!.endNS!; + } + } + TraceRow.rangeSelectObject = rangeSelect; + return true; + } + }); + this.timerShaftEL!.sportRuler!.isRangeSelect = (this.rangeTraceRow?.length || 0) > 0; this.timerShaftEL!.sportRuler!.draw(); } + private handleTouchMark(ev: MouseEvent): void { + info('isTouchMark'); + let x1 = + ((TraceRow.rangeSelectObject!.startNS! - TraceRow.range!.startNS) * + (this.timerShaftEL?.canvas?.clientWidth || 0)) / + (TraceRow.range!.endNS - TraceRow.range!.startNS); + let x2 = + ((TraceRow.rangeSelectObject!.endNS! - TraceRow.range!.startNS) * + (this.timerShaftEL?.canvas?.clientWidth || 0)) / + (TraceRow.range!.endNS - TraceRow.range!.startNS); + this.mark = {startMark: x1, endMark: x2}; + let mouseX = ev.pageX - this.rowsPaneEL!.getBoundingClientRect().left - 248; + if (mouseX > x1 - 5 && mouseX < x1 + 5) { + this.isHover = true; + document.body.style.cursor = 'ew-resize'; + this.movingMark = x1 < x2 ? 'markA' : 'markB'; + } else if (mouseX > x2 - 5 && mouseX < x2 + 5) { + this.isHover = true; + document.body.style.cursor = 'ew-resize'; + this.movingMark = x2 < x1 ? 'markA' : 'markB'; + } else { + this.isHover = false; + document.body.style.cursor = 'default'; + } + } + static SetNS(row: TraceRow, num: number): number { return Math.floor( ((TraceRow.range!.endNS - TraceRow.range!.startNS) * num) / row.frame.width + TraceRow.range!.startNS! diff --git a/ide/src/trace/component/trace/base/TraceRow.ts b/ide/src/trace/component/trace/base/TraceRow.ts index edbcb9b574db35c4ac3efd49691c840c25e77ce5..453191b79c6ffec5b01baa4f56cb5624377b13c6 100644 --- a/ide/src/trace/component/trace/base/TraceRow.ts +++ b/ide/src/trace/component/trace/base/TraceRow.ts @@ -723,23 +723,7 @@ export class TraceRow extends HTMLElement { } } } - this.checkBoxEL!.onchange = (ev: any) => { - info('checkBoxEL onchange '); - if (!ev.target.checked) { - info('checkBoxEL target not checked'); - this.rangeSelect = false; - this.checkType = '0'; - } else { - this.rangeSelect = true; - this.checkType = '2'; - } - this.setCheckBox(ev.target.checked); - ev.stopPropagation(); - }; - // 防止事件冒泡触发两次describeEl的点击事件 - this.checkBoxEL!.onclick = (ev: any) => { - ev.stopPropagation(); - }; + this.checkBoxEvent(); this.describeEl?.addEventListener('click', () => { if (this.folder) { this.expansion = !this.expansion; @@ -764,6 +748,26 @@ export class TraceRow extends HTMLElement { this.checkType = '-1'; } + private checkBoxEvent(): void { + this.checkBoxEL!.onchange = (ev: any) => { + info('checkBoxEL onchange '); + if (!ev.target.checked) { + info('checkBoxEL target not checked'); + this.rangeSelect = false; + this.checkType = '0'; + } else { + this.rangeSelect = true; + this.checkType = '2'; + } + this.setCheckBox(ev.target.checked); + ev.stopPropagation(); + }; + // 防止事件冒泡触发两次describeEl的点击事件 + this.checkBoxEL!.onclick = (ev: any) => { + ev.stopPropagation(); + }; + } + addRowCheckFilePop(): void { this.rowCheckFilePop = document.createElement('litpopover') as LitPopover; this.rowCheckFilePop.innerHTML = `
@@ -961,6 +965,32 @@ export class TraceRow extends HTMLElement { this.drawLine(ev.currentTarget, ''); return undefined; }; + this.describeElEvent(); + this.collectEL!.onclick = (e) => { + if (this.isComplete) { + this.collect = !this.collect; + if (this.collect) { + this.describeEl!.draggable = false; + } else { + this.describeEl!.draggable = false; + } + document.dispatchEvent( + new CustomEvent('collect', { + detail: { + type: e.type, + row: this, + }, + }) + ); + this.favoriteChangeHandler?.(this); + } + }; + if (!this.args['skeleton']) { + this.initCanvas(this.canvas); + } + } + + private describeElEvent(): void { this.describeEl!.ondragend = (ev: any) => { rowDragElement = null; ev.target.classList.remove('drag'); @@ -1003,28 +1033,6 @@ export class TraceRow extends HTMLElement { } }); }; - this.collectEL!.onclick = (e) => { - if (this.isComplete) { - this.collect = !this.collect; - if (this.collect) { - this.describeEl!.draggable = false; - } else { - this.describeEl!.draggable = false; - } - document.dispatchEvent( - new CustomEvent('collect', { - detail: { - type: e.type, - row: this, - }, - }) - ); - this.favoriteChangeHandler?.(this); - } - }; - if (!this.args['skeleton']) { - this.initCanvas(this.canvas); - } } rowDragstart(ev: any) { @@ -1400,7 +1408,7 @@ export class TraceRow extends HTMLElement { user-select: none; text-overflow: ellipsis; white-space:nowrap; - max-width: 200px; + max-width: 190px; } :host([highlight]) .name{ color: #4b5766; diff --git a/ide/src/trace/component/trace/base/TraceRowConfig.ts b/ide/src/trace/component/trace/base/TraceRowConfig.ts index 46b97e8725b5df381bd7fdf98dbc34b1f0457356..0675806b12803144a47928150747aaacdef8065b 100644 --- a/ide/src/trace/component/trace/base/TraceRowConfig.ts +++ b/ide/src/trace/component/trace/base/TraceRowConfig.ts @@ -20,7 +20,7 @@ import { TraceRow } from './TraceRow'; import { SpSystemTrace } from '../../SpSystemTrace'; import { LitSearch } from '../search/Search'; import { TraceSheet } from './TraceSheet'; -import { CpuStruct } from '../../../database/ui-worker/ProcedureWorkerCPU'; +import { CpuStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { type BaseStruct } from '../../../bean/BaseStruct'; import { LitIcon } from '../../../../base-ui/icon/LitIcon'; @@ -292,31 +292,35 @@ export class TraceRowConfig extends BaseElement { } } }); - this.spSystemTrace?.collectRows.forEach((favoriteRow) => { - let isShowRow: boolean = false; - if (this.selectTypeList!.length === 0) { + this.handleCollectRow(); + } + this.refreshSystemPanel(); + } + + private handleCollectRow(): void { + this.spSystemTrace?.collectRows.forEach((favoriteRow) => { + let isShowRow: boolean = false; + if (this.selectTypeList!.length === 0) { + favoriteRow.rowHidden = false; + favoriteRow.setAttribute('scene', ''); + } else { + if (favoriteRow.parentRowEl) { + favoriteRow.parentRowEl.expansion = false; + let favoriteList = [...favoriteRow.parentRowEl!.templateType]; + isShowRow = favoriteList.some((type) => this.selectTypeList!.includes(type)); + } else { + let typeList = [...favoriteRow.templateType]; + isShowRow = typeList.some((type) => this.selectTypeList!.includes(type)); + } + if (isShowRow) { favoriteRow.rowHidden = false; favoriteRow.setAttribute('scene', ''); } else { - if (favoriteRow.parentRowEl) { - favoriteRow.parentRowEl.expansion = false; - let favoriteList = [...favoriteRow.parentRowEl!.templateType]; - isShowRow = favoriteList.some((type) => this.selectTypeList!.includes(type)); - } else { - let typeList = [...favoriteRow.templateType]; - isShowRow = typeList.some((type) => this.selectTypeList!.includes(type)); - } - if (isShowRow) { - favoriteRow.rowHidden = false; - favoriteRow.setAttribute('scene', ''); - } else { - favoriteRow.removeAttribute('scene'); - favoriteRow.rowHidden = true; - } + favoriteRow.removeAttribute('scene'); + favoriteRow.rowHidden = true; } - }); - } - this.refreshSystemPanel(); + } + }); } refreshNodes(nodes: SubsystemNode[]): void { @@ -406,6 +410,7 @@ export class TraceRowConfig extends BaseElement { let jsonUrl = `https://${window.location.host.split(':')[0]}:${ window.location.port }/application/trace/config/custom_temp_config.json`; + let localJson = ''; this.switchButton!.addEventListener('click', () => { if(this.switchButton!.title === 'Show charts template') { this.switchButton!.title = 'Show subSystem template'; @@ -423,17 +428,22 @@ export class TraceRowConfig extends BaseElement { if(localText) { this.loadTempConfig(localText); } else { - fetch(jsonUrl) - .then((res) => { - if (res.ok) { - res.text().then((text) => { - this.loadTempConfig(text); - }); - } - }) - ['catch']((err) => { - console.log(err); - }); + if (localJson === '') { + fetch(jsonUrl) + .then((res) => { + if (res.ok) { + res.text().then((text) => { + localJson = text; + this.loadTempConfig(localJson); + }); + } + }) + ['catch']((err) => { + console.log(err); + }); + } else { + this.loadTempConfig(localJson); + } } } }); @@ -532,12 +542,22 @@ export class TraceRowConfig extends BaseElement { let subSystems: SubsystemNode[] = []; if (keys.indexOf(subsystemsKey) >= 0) { let subsystemsData = configJson[subsystemsKey]; + if (this.traceRowList) { + this.otherRowNames = []; + for (let index = 0; index < this.traceRowList.length; index++) { + let item = this.traceRowList[index]; + this.otherRowNames.push({ + nodeName: item.name, + scene: [...item.templateType], + }); + } + } for (let subIndex = 0; subIndex < subsystemsData.length; subIndex++) { let currentSystemData = subsystemsData[subIndex]; - let currentSubName = currentSystemData.subsystem; - if (!currentSubName) { + if(!currentSystemData.hasOwnProperty('subsystem')) { continue; } + let currentSubName = currentSystemData.subsystem; id++; let subsystemStruct: SubsystemNode = { id: id, @@ -554,11 +574,11 @@ export class TraceRowConfig extends BaseElement { } for (let compIndex = 0; compIndex < currentCompDates.length; compIndex++) { let currentCompDate = currentCompDates[compIndex]; - let currentCompName = currentCompDate.component; - let currentChartDates = currentCompDate.charts; - if (!currentCompName || !currentChartDates) { + if(!currentCompDate.hasOwnProperty('component') && !currentCompDate.hasOwnProperty('charts')) { continue; } + let currentCompName = currentCompDate.component; + let currentChartDates = currentCompDate.charts; id++; let componentStruct: SubsystemNode = { id: id, @@ -571,11 +591,11 @@ export class TraceRowConfig extends BaseElement { }; for (let chartIndex = 0; chartIndex < currentChartDates.length; chartIndex++) { let currentChartDate = currentChartDates[chartIndex]; - let currentChartName = currentChartDate.chartName; - let currentChartId = currentChartDate.chartId; - if (!currentChartName || !currentChartId) { + if(!currentChartDate.hasOwnProperty('chartName') && !currentChartDate.hasOwnProperty('chartId')) { continue; } + let currentChartName = currentChartDate.chartName; + let currentChartId = currentChartDate.chartId; let findChartNames: Array | undefined = []; let scene: string[] = []; if (this.traceRowList) { @@ -589,18 +609,18 @@ export class TraceRowConfig extends BaseElement { chartId = match[0].trim(); name = item.name.split(match[0])[0]; if (name !== 'Cpu') { - if (name.toLowerCase().endsWith(currentChartName.toLowerCase()) || currentChartId === chartId) { + if ((currentChartName !== undefined && name.toLowerCase().endsWith(currentChartName.toLowerCase())) || currentChartId === chartId) { scene.push(...item.templateType); findChartNames.push(item.name); } } else { - if (name.toLowerCase().endsWith(currentChartName.toLowerCase())) { + if ((currentChartName !== undefined && name.toLowerCase().endsWith(currentChartName.toLowerCase()))) { scene.push(...item.templateType); findChartNames.push(item.name); } } } else { - if (item.name.toLowerCase().endsWith(currentChartName.toLowerCase())) { + if ((currentChartName !== undefined && name.toLowerCase().endsWith(currentChartName.toLowerCase()))) { scene.push(...item.templateType); findChartNames.push(item.name); } @@ -926,6 +946,8 @@ export class TraceRowConfig extends BaseElement { height: 35px; line-height: 35px; margin-left: 10px; + text-overflow: ellipsis; + overflow: hidden; } .chart-option { height: 35px; @@ -973,7 +995,7 @@ export class TraceRowConfig extends BaseElement { } .layout { display: grid; - grid-template-columns: 1fr 1fr; + grid-template-columns: 80% 20%; } .scene-check-box { justify-self: center; diff --git a/ide/src/trace/component/trace/base/TraceSheet.ts b/ide/src/trace/component/trace/base/TraceSheet.ts index 4c58b8224428d33e30d6eecd441d2ebe7750cf8c..8a19e11f2f100b30fe2edad32e230e803cfc6ebe 100644 --- a/ide/src/trace/component/trace/base/TraceSheet.ts +++ b/ide/src/trace/component/trace/base/TraceSheet.ts @@ -24,13 +24,13 @@ import { type WakeupBean } from '../../../bean/WakeupBean'; import { type LitIcon } from '../../../../base-ui/icon/LitIcon'; import { tabConfig } from './TraceSheetConfig'; import { type TabPaneBoxChild } from '../sheet/cpu/TabPaneBoxChild'; -import { type CpuStruct } from '../../../database/ui-worker/ProcedureWorkerCPU'; +import { type CpuStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { CpuFreqStruct } from '../../../database/ui-worker/ProcedureWorkerFreq'; -import { CpuFreqLimitsStruct } from '../../../database/ui-worker/ProcedureWorkerCpuFreqLimits'; +import { CpuFreqLimitsStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits'; import { type ThreadStruct } from '../../../database/ui-worker/ProcedureWorkerThread'; import { type FuncStruct } from '../../../database/ui-worker/ProcedureWorkerFunc'; import { ProcessMemStruct } from '../../../database/ui-worker/ProcedureWorkerMem'; -import { CpuStateStruct } from '../../../database/ui-worker/ProcedureWorkerCpuState'; +import { CpuStateStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCpuState'; import { type ClockStruct } from '../../../database/ui-worker/ProcedureWorkerClock'; import { type IrqStruct } from '../../../database/ui-worker/ProcedureWorkerIrq'; import { type JankStruct } from '../../../database/ui-worker/ProcedureWorkerJank'; diff --git a/ide/src/trace/component/trace/base/Utils.ts b/ide/src/trace/component/trace/base/Utils.ts index 81acef78178229cead3e05503dd58c20327b894f..f54e1bf14ae365c923a761c327081c18a344c54f 100644 --- a/ide/src/trace/component/trace/base/Utils.ts +++ b/ide/src/trace/component/trace/base/Utils.ts @@ -15,7 +15,7 @@ import { SelectionParam } from '../../../bean/BoxSelection'; import { procedurePool } from '../../../database/Procedure'; -import { queryNativeHookResponseTypes } from '../../../database/SqlLite'; +import {queryNativeHookResponseTypes} from "../../../database/sql/NativeHook.sql"; export class Utils { private static statusMap: Map = new Map(); diff --git a/ide/src/trace/component/trace/search/Search.ts b/ide/src/trace/component/trace/search/Search.ts index e0d7822c207a363d4dcda37fbf86aba040feceb5..50e79c94ce7be9eb5f24e813a7e4a12d89d605d7 100644 --- a/ide/src/trace/component/trace/search/Search.ts +++ b/ide/src/trace/component/trace/search/Search.ts @@ -237,11 +237,7 @@ export class LitSearch extends BaseElement { this.totalEL = this.shadowRoot!.querySelector('#total'); this.indexEL = this.shadowRoot!.querySelector('#index'); this.searchHistoryListEL = this.shadowRoot!.querySelector('.search-history-list'); - this._retarge_index = this.shadowRoot!.querySelector("input[name='retarge_index']"); - let _root = this.shadowRoot!.querySelector('.root'); - let _prompt = this.shadowRoot!.querySelector('#prompt'); - this.search!.addEventListener('focus', () => { this.searchFocusListener(); }); @@ -275,7 +271,17 @@ export class LitSearch extends BaseElement { }) ); }); + this.keyUpListener(); + this.shadowRoot?.querySelector("input[name='retarge_index']")?.addEventListener('keydown', (e: any) => { + if (e.keyCode == 13) { + e.stopPropagation(); + } + }); + } + private keyUpListener(): void { + let _root = this.shadowRoot!.querySelector('.root'); + let _prompt = this.shadowRoot!.querySelector('#prompt'); // 添加翻页监听事件 this.shadowRoot?.querySelector("input[name='retarge_index']")?.addEventListener('keyup', (e: any) => { if (e.keyCode == 13) { @@ -303,11 +309,6 @@ export class LitSearch extends BaseElement { } e.stopPropagation(); }); - this.shadowRoot?.querySelector("input[name='retarge_index']")?.addEventListener('keydown', (e: any) => { - if (e.keyCode == 13) { - e.stopPropagation(); - } - }); } initHtml(): string { diff --git a/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts b/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts index def1cc8a13e0b21192124a9ef06bc3826d0e0b0f..dc8598a3d97cac8180d4989b3bc5b4b6f33d6296 100644 --- a/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts +++ b/ide/src/trace/component/trace/sheet/TabPaneCurrentSelection.ts @@ -18,25 +18,10 @@ import { type LitTable } from '../../../../base-ui/table/lit-table'; import '../../../../base-ui/table/lit-table-column'; import { AllAppStartupStruct } from '../../../database/ui-worker/ProcedureWorkerAllAppStartup'; -import { - queryBinderArgsByArgset, - queryBinderByArgsId, - queryBinderBySliceId, - queryFlowsData, - queryGpuDur, - queryPrecedingData, - queryRunnableTimeByRunning, - queryThreadByItid, - queryThreadNearData, - queryThreadStateArgs, - queryThreadWakeUp, - queryThreadWakeUpFrom, - queryWakeupListPriority, -} from '../../../database/SqlLite'; import { type WakeupBean } from '../../../bean/WakeupBean'; import { SpApplication } from '../../../SpApplication'; import { TraceRow } from '../base/TraceRow'; -import { CpuStruct } from '../../../database/ui-worker/ProcedureWorkerCPU'; +import { CpuStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { ThreadStruct } from '../../../database/ui-worker/ProcedureWorkerThread'; import { FuncStruct } from '../../../database/ui-worker/ProcedureWorkerFunc'; import { ProcessMemStruct } from '../../../database/ui-worker/ProcedureWorkerMem'; @@ -51,6 +36,19 @@ import { AppStartupStruct } from '../../../database/ui-worker/ProcedureWorkerApp import { SoStruct } from '../../../database/ui-worker/ProcedureWorkerSoInit'; import { type SelectionParam } from '../../../bean/BoxSelection'; import { type FrameAnimationStruct } from '../../../database/ui-worker/ProcedureWorkerFrameAnimation'; +import { + queryBinderByArgsId, + queryBinderBySliceId, + queryFlowsData, + queryPrecedingData, queryThreadByItid +} from "../../../database/sql/SqlLite.sql"; +import { + queryBinderArgsByArgset, queryRunnableTimeByRunning, + queryThreadNearData, + queryThreadStateArgs, queryThreadWakeUp, queryThreadWakeUpFrom +} from "../../../database/sql/ProcessThread.sql"; +import {queryGpuDur} from "../../../database/sql/Gpu.sql"; +import {queryWakeupListPriority} from "../../../database/sql/Cpu.sql"; const INPUT_WORD = 'This is the interval from when the task became eligible to run \n(e.g.because of notifying a wait queue it was a suspended on) to\n when it started running.'; diff --git a/ide/src/trace/component/trace/sheet/TabPaneFilter.ts b/ide/src/trace/component/trace/sheet/TabPaneFilter.ts index ef3eb6fa0675e43c8fdec2f873c160f1b3540428..7b1272347f97b9f83cae9342797087b64e66b794 100644 --- a/ide/src/trace/component/trace/sheet/TabPaneFilter.ts +++ b/ide/src/trace/component/trace/sheet/TabPaneFilter.ts @@ -21,7 +21,7 @@ import { LitIcon } from '../../../../base-ui/icon/LitIcon'; import '../../../../base-ui/popover/LitPopoverV'; import { LitCheckBox } from '../../../../base-ui/checkbox/LitCheckBox'; import { LitSelect } from '../../../../base-ui/select/LitSelect'; -import { queryTransferList } from '../../../database/SqlLite'; +import {queryTransferList} from "../../../database/sql/Perf.sql"; export interface FilterData { inputValue: string; diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneCpuAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneCpuAbility.ts index be51b88877a536030b6177665180349d4a73888e..8673dadeaabdac5c3fb8ca35495f0849992d15fd 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneCpuAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneCpuAbility.ts @@ -16,12 +16,12 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabCpuAbilityData } from '../../../../database/SqlLite'; import { SystemCpuSummary } from '../../../../bean/AbilityMonitor'; import { Utils } from '../../base/Utils'; import { ColorUtils } from '../../base/ColorUtils'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import { getTabCpuAbilityData } from '../../../../database/sql/Ability.sql'; @element('tabpane-cpu-ability') export class TabPaneCpuAbility extends BaseElement { @@ -133,61 +133,53 @@ export class TabPaneCpuAbility extends BaseElement { `; } - sortByColumn(detail: any) { - // @ts-ignore - function compare(property, sort, type) { - return function (cpuAbilityLeftData: SystemCpuSummary, cpuAbilityRightData: SystemCpuSummary) { - if (type === 'number') { - return sort === 2 - ? // @ts-ignore - parseFloat(cpuAbilityRightData[property]) - parseFloat(cpuAbilityLeftData[property]) - : // @ts-ignore - parseFloat(cpuAbilityLeftData[property]) - parseFloat(cpuAbilityRightData[property]); - } else if (type === 'durationStr') { - return sort === 2 - ? cpuAbilityRightData.duration - cpuAbilityLeftData.duration - : cpuAbilityLeftData.duration - cpuAbilityRightData.duration; - } else if (type === 'totalLoadStr') { - return sort === 2 - ? cpuAbilityRightData.totalLoad - cpuAbilityLeftData.totalLoad - : cpuAbilityLeftData.totalLoad - cpuAbilityRightData.totalLoad; - } else if (type === 'userLoadStr') { - return sort === 2 - ? cpuAbilityRightData.userLoad - cpuAbilityLeftData.userLoad - : cpuAbilityLeftData.userLoad - cpuAbilityRightData.userLoad; - } else if (type === 'systemLoadStr') { - return sort === 2 - ? cpuAbilityRightData.systemLoad - cpuAbilityLeftData.systemLoad - : cpuAbilityLeftData.systemLoad - cpuAbilityRightData.systemLoad; - } else { - // @ts-ignore - if (cpuAbilityRightData[property] > cpuAbilityLeftData[property]) { - return sort === 2 ? 1 : -1; - } else { - // @ts-ignore - if (cpuAbilityRightData[property] == cpuAbilityLeftData[property]) { - return 0; - } else { - return sort === 2 ? -1 : 1; - } - } - } - }; + getPropertyByType = (property: string, type: string) => (data: SystemCpuSummary): number | string => { + switch (type) { + case 'number': + // @ts-ignore + return parseFloat(data[property]); + case 'durationStr': + return data.duration; + case 'totalLoadStr': + return data.totalLoad; + case 'userLoadStr': + return data.userLoad; + case 'systemLoadStr': + return data.systemLoad; + default: + // @ts-ignore + return data[property]; } + }; - if (detail.key === 'startTime') { - this.cpuAbilitySource.sort(compare(detail.key, detail.sort, 'string')); - } else if (detail.key === 'durationStr') { - this.cpuAbilitySource.sort(compare(detail.key, detail.sort, 'durationStr')); - } else if (detail.key === 'totalLoadStr') { - this.cpuAbilitySource.sort(compare(detail.key, detail.sort, 'totalLoadStr')); - } else if (detail.key === 'userLoadStr') { - this.cpuAbilitySource.sort(compare(detail.key, detail.sort, 'userLoadStr')); - } else if (detail.key === 'systemLoadStr') { - this.cpuAbilitySource.sort(compare(detail.key, detail.sort, 'systemLoadStr')); - } else { - this.cpuAbilitySource.sort(compare(detail.key, detail.sort, 'number')); + compareFunction = (sort: number, getProperty: (data: SystemCpuSummary) => number | string) => + (cpuAbilityLeftData: SystemCpuSummary, cpuAbilityRightData: SystemCpuSummary) => { + let leftValue = getProperty(cpuAbilityLeftData); + let rightValue = getProperty(cpuAbilityRightData); + let result = 0; + if (leftValue > rightValue) { + result = sort === 2 ? -1 : 1; + } else if (leftValue < rightValue) { + result = sort === 2 ? 1 : -1; } + return result; + }; + + compare = (property: string, sort: number, type: string) => { + let getProperty = this.getPropertyByType(property, type); + return this.compareFunction(sort, getProperty); + }; + + sortByColumn(detail: any) { + let typeMaping: { [key: string]: string } = { + startTime: 'string', + durationStr: 'durationStr', + totalLoadStr: 'totalLoadStr', + userLoadStr: 'userLoadStr', + systemLoadStr: 'systemLoadStr', + }; + let type = typeMaping[detail.key] || 'number'; + this.cpuAbilitySource.sort(this.compare(detail.key, detail.sort, type)); this.cpuAbilityTbl!.recycleDataSource = this.cpuAbilitySource; } } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneDiskAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneDiskAbility.ts index c259c007bbfe5d43537ddce1452d6ed610100811..108143055482a6558bd0833f5c882708f4e5d510 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneDiskAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneDiskAbility.ts @@ -16,12 +16,12 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabDiskAbilityData } from '../../../../database/SqlLite'; import { SystemDiskIOSummary } from '../../../../bean/AbilityMonitor'; import { Utils } from '../../base/Utils'; import { ColorUtils } from '../../base/ColorUtils'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import {getTabDiskAbilityData} from "../../../../database/sql/Ability.sql"; @element('tabpane-disk-ability') export class TabPaneDiskAbility extends BaseElement { @@ -148,91 +148,58 @@ export class TabPaneDiskAbility extends BaseElement { `; } - sortByColumn(detail: any) { + getPropertyByType = (property: string, type: string) => (data: SystemDiskIOSummary): number | string => { + let typeMap = { + // @ts-ignore + number: parseFloat(data[property]), + durationStr: data.duration, + dataReadStr: data.dataRead, + dataReadSecStr: data.dataReadSec, + dataWriteStr: data.dataWrite, + dataWriteSecStr: data.dataWriteSec, + readsInStr: data.readsIn, + readsInSecStr: data.readsInSec, + writeOutStr: data.writeOut, + writeOutSecStr: data.writeOutSec + }; // @ts-ignore - function compare(property, sort, type) { - return function (diskAbilityLeftData: SystemDiskIOSummary, diskAbilityRightData: SystemDiskIOSummary) { - if (type === 'number') { - return sort === 2 - ? // @ts-ignore - parseFloat(diskAbilityRightData[property]) - parseFloat(diskAbilityLeftData[property]) - : // @ts-ignore - parseFloat(diskAbilityLeftData[property]) - parseFloat(diskAbilityRightData[property]); - } else if (type === 'durationStr') { - return sort === 2 - ? diskAbilityRightData.duration - diskAbilityLeftData.duration - : diskAbilityLeftData.duration - diskAbilityRightData.duration; - } else if (type === 'dataReadStr') { - return sort === 2 - ? diskAbilityRightData.dataRead - diskAbilityLeftData.dataRead - : diskAbilityLeftData.dataRead - diskAbilityRightData.dataRead; - } else if (type === 'dataReadSecStr') { - return sort === 2 - ? diskAbilityRightData.dataReadSec - diskAbilityLeftData.dataReadSec - : diskAbilityLeftData.dataReadSec - diskAbilityRightData.dataReadSec; - } else if (type === 'dataWriteStr') { - return sort === 2 - ? diskAbilityRightData.dataWrite - diskAbilityLeftData.dataWrite - : diskAbilityLeftData.dataWrite - diskAbilityRightData.dataWrite; - } else if (type === 'dataWriteSecStr') { - return sort === 2 - ? diskAbilityRightData.dataWriteSec - diskAbilityLeftData.dataWriteSec - : diskAbilityLeftData.dataWriteSec - diskAbilityRightData.dataWriteSec; - } else if (type === 'readsInStr') { - return sort === 2 - ? diskAbilityRightData.readsIn - diskAbilityLeftData.readsIn - : diskAbilityLeftData.readsIn - diskAbilityRightData.readsIn; - } else if (type === 'readsInSecStr') { - return sort === 2 - ? diskAbilityRightData.readsInSec - diskAbilityLeftData.readsInSec - : diskAbilityLeftData.readsInSec - diskAbilityRightData.readsInSec; - } else if (type === 'writeOutStr') { - return sort === 2 - ? diskAbilityRightData.writeOut - diskAbilityLeftData.writeOut - : diskAbilityLeftData.writeOut - diskAbilityRightData.writeOut; - } else if (type === 'writeOutSecStr') { - return sort === 2 - ? diskAbilityRightData.writeOutSec - diskAbilityLeftData.writeOutSec - : diskAbilityLeftData.writeOutSec - diskAbilityRightData.writeOutSec; - } else { - // @ts-ignore - if (diskAbilityRightData[property] > diskAbilityLeftData[property]) { - return sort === 2 ? 1 : -1; - } else { - // @ts-ignore - if (diskAbilityRightData[property] == diskAbilityLeftData[property]) { - return 0; - } else { - return sort === 2 ? -1 : 1; - } - } - } - }; - } + return typeMap[type] || data[property]; + }; - if (detail.key === 'startTime') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'string')); - } else if (detail.key === 'durationStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'durationStr')); - } else if (detail.key === 'dataReadStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'dataReadStr')); - } else if (detail.key === 'dataReadSecStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'dataReadSecStr')); - } else if (detail.key === 'dataWriteStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'dataWriteStr')); - } else if (detail.key === 'dataWriteSecStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'dataWriteSecStr')); - } else if (detail.key === 'readsInStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'readsInStr')); - } else if (detail.key === 'readsInSecStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'readsInSecStr')); - } else if (detail.key === 'writeOutStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'writeOutStr')); - } else if (detail.key === 'writeOutSecStr') { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'writeOutSecStr')); - } else { - this.diskAbilitySource.sort(compare(detail.key, detail.sort, 'number')); - } + compareFunction = (sort: number, getProperty: (data: SystemDiskIOSummary) => number | string) => + (diskAbilityLeftData: SystemDiskIOSummary, diskAbilityRightData: SystemDiskIOSummary) => { + let leftValue = getProperty(diskAbilityLeftData); + let rightValue = getProperty(diskAbilityRightData); + let result = 0; + if (leftValue > rightValue) { + result = sort === 2 ? -1 : 1; + } else if (leftValue < rightValue) { + result = sort === 2 ? 1 : -1; + } + return result; + }; + + compareDisk(property: string, sort: number, type: string) { + let getProperty = this.getPropertyByType(property, type); + return this.compareFunction(sort, getProperty); + } + + sortByColumn(detail: any) { + let typeMapping = { + startTime: 'string', + durationStr: 'durationStr', + dataReadStr: 'dataReadStr', + dataReadSecStr: 'dataReadSecStr', + dataWriteStr: 'dataWriteStr', + dataWriteSecStr: 'dataWriteSecStr', + readsInStr: 'readsInStr', + readsInSecStr: 'readsInSecStr', + writeOutStr: 'writeOutStr', + writeOutSecStr: 'writeOutSecStr' + }; + // @ts-ignore + let type = typeMapping[detail.key] || 'number'; + this.diskAbilitySource.sort(this.compareDisk(detail.key, detail.sort, type)); this.diskAbilityTbl!.recycleDataSource = this.diskAbilitySource; } } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbility.ts index 7e55d1ba38549513b597889465fb55da3b658493..803eeee4ed46a16e01a529479802403237451f1a 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbility.ts @@ -18,9 +18,9 @@ import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; import { Dma } from '../../../../bean/AbilityMonitor'; import { resizeObserver } from '../SheetUtils'; -import { getTabDmaAbilityData } from '../../../../database/SqlLite'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { Utils } from '../../base/Utils'; +import {getTabDmaAbilityData} from "../../../../database/sql/Dma.sql"; @element('tabpane-dma-ability') export class TabPaneDmaAbility extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbilityComparison.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbilityComparison.ts index fd145f63a64bac489f4964402b69287358187c90..f2520ac75da763e8028742c29900067841268f3d 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbilityComparison.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneDmaAbilityComparison.ts @@ -18,19 +18,19 @@ import { type LitSelect } from '../../../../../base-ui/select/LitSelect'; import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { DmaComparison } from '../../../../bean/AbilityMonitor'; -import { getTabDmaAbilityComparisonData } from '../../../../database/SqlLite'; import { type SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { Utils } from '../../base/Utils'; import { compare, resizeObserverFromMemory } from '../SheetUtils'; import '../TabPaneJsMemoryFilter'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {getTabDmaAbilityComparisonData} from "../../../../database/sql/Dma.sql"; @element('tabpane-dma-ability-comparison') export class TabPaneDmaAbilityComparison extends BaseElement { private damClickTable: LitTable | null | undefined; private comparisonSelect: TabPaneJsMemoryFilter | null | undefined; private selectEl: LitSelect | null | undefined; - private selfData: Array = []; + private selfDatas: Array = []; private comparisonSource: Array = []; initElements(): void { @@ -64,11 +64,11 @@ export class TabPaneDmaAbilityComparison extends BaseElement { } async comparisonDataByDB(startNs: number, dataList: Array): Promise { - this.selfData = []; - const selfData = await this.queryDataByDB(startNs); + this.selfDatas = []; + const selfDatas = await this.queryDataByDB(startNs); const dataArray = []; - for (const item of selfData) { - this.selfData.push(new DmaComparison(item.process, item.value)); + for (const item of selfDatas) { + this.selfDatas.push(new DmaComparison(item.process, item.value)); } for (let item of dataList) { if (item.startNs !== startNs) { @@ -111,7 +111,7 @@ export class TabPaneDmaAbilityComparison extends BaseElement { for (const item of data) { comparison.push(new DmaComparison(item.process, item.value)); } - comparisonData = compare(this.selfData, comparison); + comparisonData = compare(this.selfDatas, comparison); for (const item of comparisonData) { item.sizes = Utils.getBinaryByteWithUnit(item.value); } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneDmaSelectAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneDmaSelectAbility.ts index 0c705852aa654fb6b82f3248dff1c92f7ba4803b..06be9f0d172370ff27f1421b409031f606f410e5 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneDmaSelectAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneDmaSelectAbility.ts @@ -16,10 +16,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type Dma } from '../../../../bean/AbilityMonitor'; -import { getTabDmaAbilityClickData } from '../../../../database/SqlLite'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { Utils } from '../../base/Utils'; +import {getTabDmaAbilityClickData} from "../../../../database/sql/Dma.sql"; @element('tabpane-dma-selection-ability') export class TabPaneDmaSelectAbility extends BaseElement { @@ -37,19 +37,6 @@ export class TabPaneDmaSelectAbility extends BaseElement { }); } - connectedCallback(): void { - super.connectedCallback(); - new ResizeObserver(() => { - if (this.parentElement?.clientHeight !== 0) { - // @ts-ignore - this.damClickTable?.shadowRoot?.querySelector('.table').style.height = - this.parentElement!.clientHeight - 18 + 'px'; - this.parentElement!.style.overflow = 'hidden'; - this.damClickTable?.reMeauseHeight(); - } - }).observe(this.parentElement!); - } - private init(): void { const thTable = this.tableThead!.querySelector('.th'); const dmaSelectTblNodes = thTable!.querySelectorAll('div'); @@ -63,6 +50,19 @@ export class TabPaneDmaSelectAbility extends BaseElement { } } + connectedCallback(): void { + super.connectedCallback(); + new ResizeObserver(() => { + if (this.parentElement?.clientHeight !== 0) { + // @ts-ignore + this.damClickTable?.shadowRoot?.querySelector('.table').style.height = + this.parentElement!.clientHeight - 18 + 'px'; + this.parentElement!.style.overflow = 'hidden'; + this.damClickTable?.reMeauseHeight(); + } + }).observe(this.parentElement!); + } + queryDmaClickDataByDB(startNs: number): void { this.init(); getTabDmaAbilityClickData(startNs).then((data) => { @@ -110,8 +110,8 @@ export class TabPaneDmaSelectAbility extends BaseElement { } :host{ display: flex; - flex-direction: column; padding: 10px 10px; + flex-direction: column; } @@ -140,84 +140,44 @@ export class TabPaneDmaSelectAbility extends BaseElement { } sortDmaByColumn(column: string, sort: number): void { + const sortFunction = function (leftData: any, rightData: any, sortType: number, property: string): number { + if (sortType === 1) { + return typeof leftData[property] === 'string' + ? `${leftData[property]}`.localeCompare(`${rightData[property]}`) + : leftData[property] - rightData[property]; + } else { + return typeof rightData[property] === 'string' + ? `${rightData[property]}`.localeCompare(`${leftData[property]}`) + : rightData[property] - leftData[property]; + } + }; + switch (sort) { case 0: this.damClickTable!.recycleDataSource = this.dmaClickSource; break; default: - let array = [...this.dmaClickSource]; - switch (column) { - case 'process': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? `${dmaAbilityLeftData.process}`.localeCompare(`${dmaAbilityRightData.process}`) - : `${dmaAbilityRightData.process}`.localeCompare(`${dmaAbilityLeftData.process}`); - }); - break; - case 'startNs': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? dmaAbilityLeftData.startNs - dmaAbilityRightData.startNs - : dmaAbilityRightData.startNs - dmaAbilityLeftData.startNs; - }); - break; - case 'expTaskComm': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? `${dmaAbilityLeftData.expTaskComm}`.localeCompare(`${dmaAbilityRightData.expTaskComm}`) - : `${dmaAbilityRightData.expTaskComm}`.localeCompare(`${dmaAbilityLeftData.expTaskComm}`); - }); - break; - case 'fd': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? dmaAbilityLeftData.fd - dmaAbilityRightData.fd - : dmaAbilityRightData.fd - dmaAbilityLeftData.fd; - }); - break; - case 'size': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? dmaAbilityLeftData.size - dmaAbilityRightData.size - : dmaAbilityRightData.size - dmaAbilityLeftData.size; - }); - break; - case 'ino': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? dmaAbilityLeftData.ino - dmaAbilityRightData.ino - : dmaAbilityRightData.ino - dmaAbilityLeftData.ino; - }); - break; - case 'expPid': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? dmaAbilityLeftData.expPid - dmaAbilityRightData.expPid - : dmaAbilityRightData.expPid - dmaAbilityLeftData.expPid; - }); - break; - case 'flag': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? dmaAbilityLeftData.flag - dmaAbilityRightData.flag - : dmaAbilityRightData.flag - dmaAbilityLeftData.flag; - }); - break; - case 'bufName': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? `${dmaAbilityLeftData.bufName}`.localeCompare(`${dmaAbilityRightData.bufName}`) - : `${dmaAbilityRightData.bufName}`.localeCompare(`${dmaAbilityLeftData.bufName}`); - }); - break; - case 'expName': - this.damClickTable!.recycleDataSource = array.sort((dmaAbilityLeftData, dmaAbilityRightData) => { - return sort === 1 - ? `${dmaAbilityLeftData.expName}`.localeCompare(`${dmaAbilityRightData.expName}`) - : `${dmaAbilityRightData.expName}`.localeCompare(`${dmaAbilityLeftData.expName}`); - }); - break; - } + this.sortByColumn(column, sort, sortFunction); + break; + } + } + + sortByColumn(column: string, sort: number, sortFunction: Function): void { + let array = [...this.dmaClickSource]; + switch (column) { + case 'process': + case 'expTaskComm': + case 'bufName': + case 'expName': + this.damClickTable!.recycleDataSource = array.sort((leftData, rightData) => sortFunction(leftData, rightData, sort, column)); + break; + case 'startNs': + case 'fd': + case 'size': + case 'ino': + case 'expPid': + case 'flag': + this.damClickTable!.recycleDataSource = array.sort((leftData, rightData) => sortFunction(leftData, rightData, sort, column)); break; } } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryAbility.ts index a27a2e6cf8cf74573c5e8172140cc98a8acf245b..0d9134cdae4d43cf852ba7cfdf585b467ac080b0 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryAbility.ts @@ -18,11 +18,11 @@ import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { GpuMemory } from '../../../../bean/AbilityMonitor'; import { resizeObserver } from '../SheetUtils'; -import { getTabGpuMemoryAbilityData } from '../../../../database/SqlLite'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { Utils } from '../../base/Utils'; import { SpSystemTrace } from '../../../SpSystemTrace'; +import { getTabGpuMemoryAbilityData } from '../../../../database/sql/Ability.sql'; @element('tabpane-gpu-memory-ability') export class TabPaneGpuMemoryAbility extends BaseElement { @@ -105,8 +105,8 @@ export class TabPaneGpuMemoryAbility extends BaseElement { this.total.minSizes = Utils.getBinaryByteWithUnit(this.total.minSize); this.total.maxSizes = Utils.getBinaryByteWithUnit(this.total.maxSize); this.gpuMemorySource = data; - this.gpuMemorySource.sort(function (gpuMemoryLeftData: GpuMemory, gpuMemoryRightData: GpuMemory) { - return gpuMemoryRightData.avgSize - gpuMemoryLeftData.avgSize; + this.gpuMemorySource.sort(function (gpuMemLeftData: GpuMemory, gpuMemRightData: GpuMemory) { + return gpuMemRightData.avgSize - gpuMemLeftData.avgSize; }); this.gpuMemoryTableTbl!.recycleDataSource = [this.total, ...this.gpuMemorySource]; } else { @@ -155,8 +155,7 @@ export class TabPaneGpuMemoryAbility extends BaseElement { -
- `; +
`; } sortGpuMemoryByColumn(column: string, sort: number): void { @@ -168,38 +167,38 @@ export class TabPaneGpuMemoryAbility extends BaseElement { let array = [...this.gpuMemorySource]; switch (column) { case 'process': - array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + array.sort((gpuMemLeftData, gpuMemRightData) => { return sort === 1 - ? `${gpuMemoryLeftData.process}`.localeCompare(`${gpuMemoryRightData.process}`) - : `${gpuMemoryRightData.process}`.localeCompare(`${gpuMemoryLeftData.process}`); + ? `${gpuMemLeftData.process}`.localeCompare(`${gpuMemRightData.process}`) + : `${gpuMemRightData.process}`.localeCompare(`${gpuMemLeftData.process}`); }); break; case 'gpuName': - array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + array.sort((gpuMemLeftData, gpuMemRightData) => { return sort === 1 - ? `${gpuMemoryLeftData.gpuName}`.localeCompare(`${gpuMemoryRightData.gpuName}`) - : `${gpuMemoryRightData.gpuName}`.localeCompare(`${gpuMemoryLeftData.gpuName}`); + ? `${gpuMemLeftData.gpuName}`.localeCompare(`${gpuMemRightData.gpuName}`) + : `${gpuMemRightData.gpuName}`.localeCompare(`${gpuMemLeftData.gpuName}`); }); break; case 'avgSize': - array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + array.sort((gpuMemLeftData, gpuMemRightData) => { return sort === 1 - ? gpuMemoryLeftData.avgSize - gpuMemoryRightData.avgSize - : gpuMemoryRightData.avgSize - gpuMemoryLeftData.avgSize; + ? gpuMemLeftData.avgSize - gpuMemRightData.avgSize + : gpuMemRightData.avgSize - gpuMemLeftData.avgSize; }); break; case 'minSize': - array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + array.sort((gpuMemLeftData, gpuMemRightData) => { return sort === 1 - ? gpuMemoryLeftData.minSize - gpuMemoryRightData.minSize - : gpuMemoryRightData.minSize - gpuMemoryLeftData.minSize; + ? gpuMemLeftData.minSize - gpuMemRightData.minSize + : gpuMemRightData.minSize - gpuMemLeftData.minSize; }); break; case 'maxSize': - array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + array.sort((gpuMemLeftData, gpuMemRightData) => { return sort === 1 - ? gpuMemoryLeftData.maxSize - gpuMemoryRightData.maxSize - : gpuMemoryRightData.maxSize - gpuMemoryLeftData.maxSize; + ? gpuMemLeftData.maxSize - gpuMemRightData.maxSize + : gpuMemRightData.maxSize - gpuMemLeftData.maxSize; }); break; } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryComparison.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryComparison.ts index 05dcc9b2729d8e15836ae63554ac5e42eca2755f..60c53871061ad6f2be5c1c9d69b9a55cd7075181 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryComparison.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemoryComparison.ts @@ -18,13 +18,13 @@ import { LitSelect } from '../../../../../base-ui/select/LitSelect'; import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { GpuMemoryComparison } from '../../../../bean/AbilityMonitor'; -import { getTabGpuMemoryComparisonData } from '../../../../database/SqlLite'; import { type SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { Utils } from '../../base/Utils'; import { compare, resizeObserverFromMemory } from '../SheetUtils'; import '../TabPaneJsMemoryFilter'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {getTabGpuMemoryComparisonData} from "../../../../database/sql/Ability.sql"; @element('tabpane-gpu-memory-comparison') export class TabPaneGpuMemoryComparison extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemorySelectAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemorySelectAbility.ts index fadb4f13a0bd2a788eccefe231132937fab4d3a4..ae1b86a0dce410c3656b991c46893beb803182c9 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemorySelectAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneGpuMemorySelectAbility.ts @@ -16,13 +16,13 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type GpuMemory } from '../../../../bean/AbilityMonitor'; -import { getTabGpuMemoryAbilityClickData } from '../../../../database/SqlLite'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { Utils } from '../../base/Utils'; +import {getTabGpuMemoryAbilityClickData} from "../../../../database/sql/Ability.sql"; @element('tabpane-gpu-memory-selection-ability') export class TabPaneGpuMemorySelectAbility extends BaseElement { - private gpuMemoryClickTable: LitTable | null | undefined; + private gpuMemoryClickTables: LitTable | null | undefined; private gpuMemoryClickSource: Array = []; private tableThead: HTMLDivElement | undefined | null; @@ -33,9 +33,9 @@ export class TabPaneGpuMemorySelectAbility extends BaseElement { } initElements(): void { - this.gpuMemoryClickTable = this.shadowRoot?.querySelector('#gpuMemoryClickTable'); - this.tableThead = this.gpuMemoryClickTable?.shadowRoot?.querySelector('.thead') as HTMLDivElement; - this.gpuMemoryClickTable!.addEventListener('column-click', (e) => { + this.gpuMemoryClickTables = this.shadowRoot?.querySelector('#gpuMemoryClickTables'); + this.tableThead = this.gpuMemoryClickTables?.shadowRoot?.querySelector('.thead') as HTMLDivElement; + this.gpuMemoryClickTables!.addEventListener('column-click', (e) => { // @ts-ignore this.sortGpuMemoryByColumn(e.detail.key, e.detail.sort); }); @@ -45,11 +45,11 @@ export class TabPaneGpuMemorySelectAbility extends BaseElement { super.connectedCallback(); new ResizeObserver(() => { if (this.parentElement?.clientHeight !== 0) { - let gpuMemoryTbl = this.gpuMemoryClickTable?.shadowRoot?.querySelector('.table'); + let gpuMemoryTbl = this.gpuMemoryClickTables?.shadowRoot?.querySelector('.table'); // @ts-ignore gpuMemoryTbl.style.height = this.parentElement.clientHeight - 18 + 'px'; this.parentElement!.style.overflow = 'hidden'; - this.gpuMemoryClickTable?.reMeauseHeight(); + this.gpuMemoryClickTables?.reMeauseHeight(); } }).observe(this.parentElement!); } @@ -80,7 +80,7 @@ export class TabPaneGpuMemorySelectAbility extends BaseElement { item.sizes = Utils.getBinaryByteWithUnit(item.size); item.timeStamp = ns2s(item.startNs); }); - this.gpuMemoryClickTable!.recycleDataSource = data.sort(function ( + this.gpuMemoryClickTables!.recycleDataSource = data.sort(function ( gpuMemoryLeftData: GpuMemory, gpuMemoryRightData: GpuMemory ) { @@ -88,7 +88,7 @@ export class TabPaneGpuMemorySelectAbility extends BaseElement { }); this.gpuMemoryClickSource = data; } else { - this.gpuMemoryClickTable!.recycleDataSource = []; + this.gpuMemoryClickTables!.recycleDataSource = []; this.gpuMemoryClickSource = []; } }); @@ -97,7 +97,7 @@ export class TabPaneGpuMemorySelectAbility extends BaseElement { initHtml(): string { return ` - + @@ -122,34 +122,34 @@ export class TabPaneGpuMemorySelectAbility extends BaseElement { sortGpuMemoryByColumn(column: string, sort: number): void { switch (sort) { case 0: - this.gpuMemoryClickTable!.recycleDataSource = this.gpuMemoryClickSource; + this.gpuMemoryClickTables!.recycleDataSource = this.gpuMemoryClickSource; break; default: let array = [...this.gpuMemoryClickSource]; switch (column) { case 'process': - this.gpuMemoryClickTable!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + this.gpuMemoryClickTables!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { return sort === 1 ? `${gpuMemoryLeftData.process}`.localeCompare(`${gpuMemoryRightData.process}`) : `${gpuMemoryRightData.process}`.localeCompare(`${gpuMemoryLeftData.process}`); }); break; case 'startNs': - this.gpuMemoryClickTable!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + this.gpuMemoryClickTables!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { return sort === 1 ? gpuMemoryLeftData.startNs - gpuMemoryRightData.startNs : gpuMemoryRightData.startNs - gpuMemoryLeftData.startNs; }); break; case 'gpuName': - this.gpuMemoryClickTable!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + this.gpuMemoryClickTables!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { return sort === 1 ? `${gpuMemoryLeftData.gpuName}`.localeCompare(`${gpuMemoryRightData.gpuName}`) : `${gpuMemoryRightData.gpuName}`.localeCompare(`${gpuMemoryLeftData.gpuName}`); }); break; case 'size': - this.gpuMemoryClickTable!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { + this.gpuMemoryClickTables!.recycleDataSource = array.sort((gpuMemoryLeftData, gpuMemoryRightData) => { return sort === 1 ? gpuMemoryLeftData.size - gpuMemoryRightData.size : gpuMemoryRightData.size - gpuMemoryLeftData.size; diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneHistoryProcesses.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneHistoryProcesses.ts index 6cdf5dc66517517f6fd0175c81507acd783382f9..765245497202e5654532cecc2aef36849553b6eb 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneHistoryProcesses.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneHistoryProcesses.ts @@ -16,11 +16,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabProcessHistoryData } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { ProcessHistory } from '../../../../bean/AbilityMonitor'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import { getTabProcessHistoryData } from '../../../../database/sql/ProcessThread.sql'; @element('tabpane-history-processes') export class TabPaneHistoryProcesses extends BaseElement { @@ -160,68 +160,48 @@ export class TabPaneHistoryProcesses extends BaseElement { `; } - sortByColumn(detail: any) { - // @ts-ignore - function compare(property, sort, type) { - return function (historyProcessLeftData: ProcessHistory, historyProcessRightData: ProcessHistory) { - if (type === 'number') { - return sort === 2 - ? // @ts-ignore - parseFloat(historyProcessRightData[property]) - parseFloat(historyProcessLeftData[property]) - : // @ts-ignore - parseFloat(historyProcessLeftData[property]) - parseFloat(historyProcessRightData[property]); - } else if (type === 'cpuTime') { - return sort === 2 - ? historyProcessRightData.cpuTimeNumber - historyProcessLeftData.cpuTimeNumber - : historyProcessLeftData.cpuTimeNumber - historyProcessRightData.cpuTimeNumber; - } else if (type === 'lastSeen') { - return sort === 2 - ? historyProcessRightData.lastSeenNumber - historyProcessLeftData.lastSeenNumber - : historyProcessLeftData.lastSeenNumber - historyProcessRightData.lastSeenNumber; - } else if (type === 'firstSeen') { - return sort === 2 - ? historyProcessRightData.firstSeenNumber - historyProcessLeftData.firstSeenNumber - : historyProcessLeftData.firstSeenNumber - historyProcessRightData.firstSeenNumber; - } else if (type === 'alive') { - let aaaa = 0; - let bbbb = 0; - // @ts-ignore - if (historyProcessRightData[property] == 'Yes') { - bbbb = 1; - } - // @ts-ignore - if (historyProcessLeftData[property] == 'Yes') { - aaaa = 1; - } - if (aaaa - bbbb == 0) { - return 0; - } - return aaaa - bbbb ? -1 : 1; - } else { - // @ts-ignore - if (historyProcessRightData[property] > historyProcessLeftData[property]) { - return sort === 2 ? 1 : -1; - } else { - // @ts-ignore - if (historyProcessRightData[property] == historyProcessLeftData[property]) { - return 0; - } else { - return sort === 2 ? -1 : 1; - } - } - } - }; - } + compare(property: string, sort: number, type: string) { + let compareValues = (left: number, right: number) => { + if (sort === 2) { + return right - left; + } else { + return left - right; + } + }; + + return function (historyProcessLeftData: ProcessHistory, historyProcessRightData: ProcessHistory) { + if (type === 'number') { + // @ts-ignore + return compareValues(parseFloat(historyProcessLeftData[property]), parseFloat(historyProcessRightData[property])); + } else if (type === 'cpuTime' || type === 'lastSeen' || type === 'firstSeen') { + // @ts-ignore + return compareValues(historyProcessLeftData[type + 'Number'], historyProcessRightData[type + 'Number']); + } else if (type === 'alive') { + // @ts-ignore + let leftValue = historyProcessLeftData[property] === 'Yes' ? 1 : 0; + // @ts-ignore + let rightValue = historyProcessRightData[property] === 'Yes' ? 1 : 0; + return compareValues(leftValue, rightValue); + } else { + // @ts-ignore + return compareValues(historyProcessLeftData[property], historyProcessRightData[property]); + } + }; + } + sortByColumn(detail: any) { + let type; if (detail.key === 'startTime' || detail.key === 'processName') { - this.historyProcessSource.sort(compare(detail.key, detail.sort, 'string')); + type = 'string'; } else if (detail.key == 'cpuTime') { - this.historyProcessSource.sort(compare(detail.key, detail.sort, 'cpuTime')); + type = 'cpuTime'; } else if (detail.key === 'alive') { - this.historyProcessSource.sort(compare(detail.key, detail.sort, 'alive')); + type = 'alive'; } else { - this.historyProcessSource.sort(compare(detail.key, detail.sort, 'number')); + type = 'number'; } + let compareFunction = this.compare(detail.key, detail.sort, type); + this.historyProcessSource.sort(compareFunction); this.historyProcessTbl!.recycleDataSource = this.historyProcessSource; } } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneLiveProcesses.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneLiveProcesses.ts index ba7ba7c06833f49c82049d1bbc191f358a64f584..c737b0ee21734500785dc85a83842c36df0b5203 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneLiveProcesses.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneLiveProcesses.ts @@ -16,11 +16,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabLiveProcessData } from '../../../../database/SqlLite'; import { LiveProcess } from '../../../../bean/AbilityMonitor'; import { Utils } from '../../base/Utils'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import {getTabLiveProcessData} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-live-processes') export class TabPaneLiveProcesses extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneMemoryAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneMemoryAbility.ts index 1f4cff24d37f465a053832b165b1f0eb270e3d58..6a80d70b300f03b0ccf92e66e2afa2bf619e0f44 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneMemoryAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneMemoryAbility.ts @@ -16,11 +16,12 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabMemoryAbilityData, queryStartTime } from '../../../../database/SqlLite'; import { SystemMemorySummary } from '../../../../bean/AbilityMonitor'; import { Utils } from '../../base/Utils'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import {queryStartTime} from "../../../../database/sql/SqlLite.sql"; +import {getTabMemoryAbilityData} from "../../../../database/sql/Ability.sql"; @element('tabpane-memory-ability') export class TabPaneMemoryAbility extends BaseElement { @@ -76,6 +77,32 @@ export class TabPaneMemoryAbility extends BaseElement { return array; } + getMemoryKeys() { + return { + 'sys.mem.total': 'memoryTotal', + 'sys.mem.free': 'memFree', + 'sys.mem.buffers': 'buffers', + 'sys.mem.cached': 'cached', + 'sys.mem.shmem': 'shmem', + 'sys.mem.slab': 'slab', + 'sys.mem.swap.total': 'swapTotal', + 'sys.mem.swap.free': 'swapFree', + 'sys.mem.mapped': 'mapped', + 'sys.mem.vmalloc.used': 'vmallocUsed', + 'sys.mem.page.tables': 'pageTables', + 'sys.mem.kernel.stack': 'kernelStack', + 'sys.mem.active': 'active', + 'sys.mem.inactive': 'inactive', + 'sys.mem.unevictable': 'unevictable', + 'sys.mem.vmalloc.total': 'vmallocTotal', + 'sys.mem.slab.unreclaimable': 'sUnreclaim', + 'sys.mem.cma.total': 'cmaTotal', + 'sys.mem.cma.free': 'cmaFree', + 'sys.mem.kernel.reclaimable': 'kReclaimable', + 'sys.mem.zram': 'zram' + }; + } + queryDataByDB(val: SelectionParam | any) { queryStartTime().then((res) => { let startTime = res[0].start_ts; @@ -87,91 +114,25 @@ export class TabPaneMemoryAbility extends BaseElement { let lastTime = 0; for (const item of items) { let systemMemorySummary = new SystemMemorySummary(); - if (item.startTime - startTime <= 0) { - systemMemorySummary.startTimeStr = '0:000.000.000'; - } else { - systemMemorySummary.startTimeStr = Utils.getTimeStampHMS(item.startTime - startTime); - } - if (lastTime !== 0) { - systemMemorySummary.durationNumber = item.startTime - lastTime; - systemMemorySummary.durationStr = Utils.getDurString(systemMemorySummary.durationNumber); - } else { - systemMemorySummary.durationNumber = 0; - systemMemorySummary.durationStr = '-'; - } + systemMemorySummary.startTimeStr = (item.startTime - startTime <= 0) ? '0:000.000.000' + : Utils.getTimeStampHMS(item.startTime - startTime); + systemMemorySummary.durationNumber = (lastTime !== 0) ? item.startTime - lastTime : 0; + systemMemorySummary.durationStr = (lastTime !== 0) ? Utils.getDurString(systemMemorySummary.durationNumber) : '-'; lastTime = item.startTime; let memorys = item.value.split(','); let names = item.name.split(','); if (memorys.length != names.length) { continue; } + let memoryKeys: { [key: string]: string } = this.getMemoryKeys(); for (let i = 0; i < names.length; i++) { - switch (names[i]) { - case 'sys.mem.total': - systemMemorySummary.memoryTotal = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.free': - systemMemorySummary.memFree = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.buffers': - systemMemorySummary.buffers = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.cached': - systemMemorySummary.cached = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.shmem': - systemMemorySummary.shmem = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.slab': - systemMemorySummary.slab = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.swap.total': - systemMemorySummary.swapTotal = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.swap.free': - systemMemorySummary.swapFree = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.mapped': - systemMemorySummary.mapped = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.vmalloc.used': - systemMemorySummary.vmallocUsed = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.page.tables': - systemMemorySummary.pageTables = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.kernel.stack': - systemMemorySummary.kernelStack = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.active': - systemMemorySummary.active = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.inactive': - systemMemorySummary.inactive = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.unevictable': - systemMemorySummary.unevictable = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.vmalloc.total': - systemMemorySummary.vmallocTotal = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.slab.unreclaimable': - systemMemorySummary.sUnreclaim = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.cma.total': - systemMemorySummary.cmaTotal = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.cma.free': - systemMemorySummary.cmaFree = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.kernel.reclaimable': - systemMemorySummary.kReclaimable = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; - case 'sys.mem.zram': - systemMemorySummary.zram = Utils.getBinaryKBWithUnit(Number(memorys[i])); - break; + let key = memoryKeys[names[i]]; + if (key) { + // @ts-ignore + systemMemorySummary[key] = Utils.getBinaryKBWithUnit(Number(memorys[i])); } } + ; this.memoryAbilitySource.push(systemMemorySummary); } this.memoryAbilityTbl!.recycleDataSource = this.memoryAbilitySource; @@ -236,9 +197,9 @@ export class TabPaneMemoryAbility extends BaseElement { if (type === 'number') { return sort === 2 ? // @ts-ignore - parseFloat(memoryAbilityRightData[property]) - parseFloat(memoryAbilityLeftData[property]) + parseFloat(memoryAbilityRightData[property]) - parseFloat(memoryAbilityLeftData[property]) : // @ts-ignore - parseFloat(memoryAbilityLeftData[property]) - parseFloat(memoryAbilityRightData[property]); + parseFloat(memoryAbilityLeftData[property]) - parseFloat(memoryAbilityRightData[property]); } else if (type === 'durationStr') { return sort === 2 ? memoryAbilityRightData.durationNumber - memoryAbilityLeftData.durationNumber diff --git a/ide/src/trace/component/trace/sheet/ability/TabPaneNetworkAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPaneNetworkAbility.ts index 5906da1aa3fd5cb31333f2c1e520e6d4d8119b0f..b0810ceb77c58ef4278e1028220f8119ccf538aa 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPaneNetworkAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPaneNetworkAbility.ts @@ -16,12 +16,12 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabNetworkAbilityData } from '../../../../database/SqlLite'; import { SystemNetworkSummary } from '../../../../bean/AbilityMonitor'; import { Utils } from '../../base/Utils'; import { ColorUtils } from '../../base/ColorUtils'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import {getTabNetworkAbilityData} from "../../../../database/sql/Ability.sql"; @element('tabpane-network-ability') export class TabPaneNetworkAbility extends BaseElement { @@ -140,90 +140,66 @@ export class TabPaneNetworkAbility extends BaseElement { `; } - sortByColumn(detail: any) { + compare(property: string, sort: number, type: string) { + let getProperty = this.getPropertyByType(property, type); + return this.compareFunction(sort, getProperty); + } + + compareFunction = (sort: number, getProperty: (data: SystemNetworkSummary) => number | string) => + (networkAbilityLeftData: SystemNetworkSummary, networkAbilityRightData: SystemNetworkSummary) => { + let leftValue = getProperty(networkAbilityLeftData); + let rightValue = getProperty(networkAbilityRightData); + let result = 0; + if (leftValue > rightValue) { + result = sort === 2 ? -1 : 1; + } else if (leftValue < rightValue) { + result = sort === 2 ? 1 : -1; + } + return result; + }; + + getPropertyByType = (property: string, type: string) => (data: SystemNetworkSummary): number | string => { + let typeMap = { + // @ts-ignore + number: parseFloat(data[property]), + durationStr: data.duration, + dataReceivedStr: data.dataReceived, + dataReceivedSecStr: data.dataReceivedSec, + dataSendStr: data.dataSend, + dataSendSecStr: data.dataSendSec, + packetsInStr: data.packetsIn, + packetsInSecStr: data.packetsInSec, + packetsOutStr: data.packetsOut, + packetsOutSecStr: data.packetsOutSec + }; // @ts-ignore - function compare(property, sort, type) { - return function (networkAbilityLeftData: SystemNetworkSummary, networkAbilityRightData: SystemNetworkSummary) { - if (type === 'number') { - return sort === 2 - ? // @ts-ignore - parseFloat(networkAbilityRightData[property]) - parseFloat(networkAbilityLeftData[property]) - : // @ts-ignore - parseFloat(networkAbilityLeftData[property]) - parseFloat(networkAbilityRightData[property]); - } else if (type === 'durationStr') { - return sort === 2 - ? networkAbilityRightData.duration - networkAbilityLeftData.duration - : networkAbilityLeftData.duration - networkAbilityRightData.duration; - } else if (type === 'dataReceivedStr') { - return sort === 2 - ? networkAbilityRightData.dataReceived - networkAbilityLeftData.dataReceived - : networkAbilityLeftData.dataReceived - networkAbilityRightData.dataReceived; - } else if (type === 'dataReceivedSecStr') { - return sort === 2 - ? networkAbilityRightData.dataReceivedSec - networkAbilityLeftData.dataReceivedSec - : networkAbilityLeftData.dataReceivedSec - networkAbilityRightData.dataReceivedSec; - } else if (type === 'dataSendStr') { - return sort === 2 - ? networkAbilityRightData.dataSend - networkAbilityLeftData.dataSend - : networkAbilityLeftData.dataSend - networkAbilityRightData.dataSend; - } else if (type === 'dataSendSecStr') { - return sort === 2 - ? networkAbilityRightData.dataSendSec - networkAbilityLeftData.dataSendSec - : networkAbilityLeftData.dataSendSec - networkAbilityRightData.dataSendSec; - } else if (type === 'packetsInStr') { - return sort === 2 - ? networkAbilityRightData.packetsIn - networkAbilityLeftData.packetsIn - : networkAbilityLeftData.packetsIn - networkAbilityRightData.packetsIn; - } else if (type === 'packetsInSecStr') { - return sort === 2 - ? networkAbilityRightData.packetsInSec - networkAbilityLeftData.packetsInSec - : networkAbilityLeftData.packetsInSec - networkAbilityRightData.packetsInSec; - } else if (type === 'packetsOutStr') { - return sort === 2 - ? networkAbilityRightData.packetsOut - networkAbilityLeftData.packetsOut - : networkAbilityLeftData.packetsOut - networkAbilityRightData.packetsOut; - } else if (type === 'packetsOutSecStr') { - return sort === 2 - ? networkAbilityRightData.packetsOutSec - networkAbilityLeftData.packetsOutSec - : networkAbilityLeftData.packetsOutSec - networkAbilityRightData.packetsOutSec; - } else { - // @ts-ignore - if (networkAbilityRightData[property] > networkAbilityLeftData[property]) { - return sort === 2 ? 1 : -1; - } else { - // @ts-ignore - if (networkAbilityRightData[property] == networkAbilityLeftData[property]) { - return 0; - } else { - return sort === 2 ? -1 : 1; - } - } - } - }; - } + return typeMap[type] || data[property]; + }; + sortByColumn(detail: any) { + // @ts-ignore if (detail.key === 'startTime') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'string')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'string')); } else if (detail.key === 'durationStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'durationStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'durationStr')); } else if (detail.key === 'dataReceivedStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'dataReceivedStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'dataReceivedStr')); } else if (detail.key === 'dataReceivedSecStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'dataReceivedSecStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'dataReceivedSecStr')); } else if (detail.key === 'dataSendStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'dataSendStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'dataSendStr')); } else if (detail.key === 'dataSendSecStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'dataSendSecStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'dataSendSecStr')); } else if (detail.key === 'packetsInStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'packetsInStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'packetsInStr')); } else if (detail.key === 'packetsInSecStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'packetsInSecStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'packetsInSecStr')); } else if (detail.key === 'packetsOutStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'packetsOutStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'packetsOutStr')); } else if (detail.key === 'packetsOutSecStr') { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'packetsOutSecStr')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'packetsOutSecStr')); } else { - this.networkAbilitySource.sort(compare(detail.key, detail.sort, 'number')); + this.networkAbilitySource.sort(this.compare(detail.key, detail.sort, 'number')); } this.networkAbilityTbl!.recycleDataSource = this.networkAbilitySource; } diff --git a/ide/src/trace/component/trace/sheet/ability/TabPanePurgPin.ts b/ide/src/trace/component/trace/sheet/ability/TabPanePurgPin.ts index 154ff2f2eb346930d2d92de9fc667a392cb6d4ec..a762e0115b7af0a983816e431eb5c1ce05668f18 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPanePurgPin.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPanePurgPin.ts @@ -17,10 +17,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { queryProcessPurgeableTab, querySysPurgeableTab } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; import { PurgeableTabStruct } from './TabPanePurgTotal'; +import {querySysPurgeableTab} from "../../../../database/sql/Ability.sql"; +import {queryProcessPurgeableTab} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-purg-pin') export class TabPanePurgPin extends BaseElement { @@ -50,26 +51,7 @@ export class TabPanePurgPin extends BaseElement { true ).then((purgePinResults) => { this.purgeablePinTable!.loading = false; - if (purgePinResults.length > 0) { - for (let i = 0; i < purgePinResults.length; i++) { - this.purgeablePinSource.push( - this.toTabStruct( - purgePinResults[i].name, - purgePinResults[i].maxSize, - purgePinResults[i].minSize, - purgePinResults[i].avgSize - ) - ); - } - this.sortByColumn({ key: this.sortKey, sort: this.sortType }); - let total = this.totalData(this.purgeablePinSource); - this.purgeablePinSource.unshift(total); - this.purgeablePinTable!.recycleDataSource = this.purgeablePinSource; - this.purgeablePinSource.shift(); - } else { - this.purgeablePinSource = []; - this.purgeablePinTable!.recycleDataSource = []; - } + this.getDataSource(purgePinResults) }); } else if (selection.purgeablePinVM.length > 0) { this.purgeablePinSource = []; @@ -81,25 +63,29 @@ export class TabPanePurgPin extends BaseElement { true ).then((results) => { this.purgeablePinTable!.loading = false; - if (results.length > 0) { - for (let i = 0; i < results.length; i++) { - this.purgeablePinSource.push( - this.toTabStruct(results[i].name, results[i].maxSize, results[i].minSize, results[i].avgSize) - ); - } - this.sortByColumn({ key: this.sortKey, sort: this.sortType }); - let total = this.totalData(this.purgeablePinSource); - this.purgeablePinSource.unshift(total); - this.purgeablePinTable!.recycleDataSource = this.purgeablePinSource; - this.purgeablePinSource.shift(); - } else { - this.purgeablePinSource = []; - this.purgeablePinTable!.recycleDataSource = []; - } + this.getDataSource(results) }); } } + getDataSource(res: any): void{ + if (res.length > 0) { + for (let i = 0; i < res.length; i++) { + this.purgeablePinSource.push( + this.toTabStruct(res[i].name, res[i].maxSize, res[i].minSize, res[i].avgSize) + ); + } + this.sortByColumn({ key: this.sortKey, sort: this.sortType }); + let total = this.totalData(this.purgeablePinSource); + this.purgeablePinSource.unshift(total); + this.purgeablePinTable!.recycleDataSource = this.purgeablePinSource; + this.purgeablePinSource.shift(); + } else { + this.purgeablePinSource = []; + this.purgeablePinTable!.recycleDataSource = []; + } + } + private init(): void { const thTable = this.tabTitle!.querySelector('.th'); const purgePinTblNodes = thTable!.querySelectorAll('div'); diff --git a/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinComparisonAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinComparisonAbility.ts index c71142cabe82951c6023bf762cf9aa523ba719b0..9478dec86a3077a52521e63c7031d64d1bb81041 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinComparisonAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinComparisonAbility.ts @@ -17,10 +17,10 @@ import { type LitSelect } from '../../../../../base-ui/select/LitSelect'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type SelectionParam } from '../../../../bean/BoxSelection'; -import { querySysPurgeableSelectionTab } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { CompareStruct, compare, resizeObserverFromMemory } from '../SheetUtils'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {querySysPurgeableSelectionTab} from "../../../../database/sql/Ability.sql"; @element('tabpane-purgeable-pin-comparison-ability') export class TabPanePurgPinComparisonAbility extends BaseElement { private purgeablePinTable: LitTable | null | undefined; diff --git a/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinSelection.ts b/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinSelection.ts index b77e9cda15b6cb5888cc214db1cd5ec3be1cd979..014e99b3a75072d86e2ddb40e8f2630c290bce5a 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinSelection.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPanePurgPinSelection.ts @@ -17,10 +17,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { type SelectionParam } from '../../../../bean/BoxSelection'; -import { queryProcessPurgeableSelectionTab, querySysPurgeableSelectionTab } from '../../../../database/SqlLite'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; +import {querySysPurgeableSelectionTab} from "../../../../database/sql/Ability.sql"; +import {queryProcessPurgeableSelectionTab} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-purg-pin-selection') export class TabPanePurgPinSelection extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotal.ts b/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotal.ts index ae825aabf5fd000aa956f7939f859619667bd8a8..3bd823241ad56bac53884eebd82efe53c23e9585 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotal.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotal.ts @@ -17,9 +17,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { querySysPurgeableTab, queryProcessPurgeableTab } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; +import { querySysPurgeableTab } from '../../../../database/sql/Ability.sql'; +import { queryProcessPurgeableTab } from '../../../../database/sql/ProcessThread.sql'; @element('tabpane-purg-total') export class TabPanePurgTotal extends BaseElement { @@ -29,6 +30,7 @@ export class TabPanePurgTotal extends BaseElement { private purgTotalTimeRange: HTMLLabelElement | undefined | null; private sortKey = 'avgSize'; private sortType = 2; + set data(selection: SelectionParam) { //@ts-ignore this.purgeableTotalTable?.shadowRoot?.querySelector('.table')?.style?.height = `${ @@ -48,26 +50,7 @@ export class TabPanePurgTotal extends BaseElement { (MemoryConfig.getInstance().interval * 1000000) / 5 ).then((purgeTotalResults) => { this.purgeableTotalTable!.loading = false; - if (purgeTotalResults.length > 0) { - for (let i = 0; i < purgeTotalResults.length; i++) { - this.purgeableTotalSource.push( - this.toTabStruct( - purgeTotalResults[i].name, - purgeTotalResults[i].maxSize, - purgeTotalResults[i].minSize, - purgeTotalResults[i].avgSize - ) - ); - } - this.sortByColumn({ key: this.sortKey, sort: this.sortType }); - let total = this.totalData(this.purgeableTotalSource); - this.purgeableTotalSource.unshift(total); - this.purgeableTotalTable!.recycleDataSource = this.purgeableTotalSource; - this.purgeableTotalSource.shift(); - } else { - this.purgeableTotalSource = []; - this.purgeableTotalTable!.recycleDataSource = []; - } + this.getPurgeableTotalSource(purgeTotalResults); }); } else if (selection.purgeableTotalVM.length > 0) { this.purgeableTotalSource = []; @@ -78,25 +61,29 @@ export class TabPanePurgTotal extends BaseElement { MemoryConfig.getInstance().iPid ).then((results) => { this.purgeableTotalTable!.loading = false; - if (results.length > 0) { - for (let i = 0; i < results.length; i++) { - this.purgeableTotalSource.push( - this.toTabStruct(results[i].name, results[i].maxSize, results[i].minSize, results[i].avgSize) - ); - } - this.sortByColumn({ key: this.sortKey, sort: this.sortType }); - let total = this.totalData(this.purgeableTotalSource); - this.purgeableTotalSource.unshift(total); - this.purgeableTotalTable!.recycleDataSource = this.purgeableTotalSource; - this.purgeableTotalSource.shift(); - } else { - this.purgeableTotalSource = []; - this.purgeableTotalTable!.recycleDataSource = []; - } + this.getPurgeableTotalSource(results); }); } } + getPurgeableTotalSource(results: any): void { + if (results.length > 0) { + for (let i = 0; i < results.length; i++) { + this.purgeableTotalSource.push( + this.toTabStruct(results[i].name, results[i].maxSize, results[i].minSize, results[i].avgSize) + ); + } + this.sortByColumn({key: this.sortKey, sort: this.sortType}); + let total = this.totalData(this.purgeableTotalSource); + this.purgeableTotalSource.unshift(total); + this.purgeableTotalTable!.recycleDataSource = this.purgeableTotalSource; + this.purgeableTotalSource.shift(); + } else { + this.purgeableTotalSource = []; + this.purgeableTotalTable!.recycleDataSource = []; + } + } + private init(): void { const thTable = this.tabTitle!.querySelector('.th'); const purgeTotalTblNode = thTable!.querySelectorAll('div'); @@ -163,6 +150,7 @@ export class TabPanePurgTotal extends BaseElement { } }; } + if (detail.key === 'type') { this.purgeableTotalSource.sort(compare(detail.key, detail.sort, 'string')); } else { diff --git a/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalComparisonAbility.ts b/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalComparisonAbility.ts index 9a13b18d4370f4f2e6b80decb6902d7709b348f8..7c3b19cbe4e94f7ed6990417a25e1f13643adaa4 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalComparisonAbility.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalComparisonAbility.ts @@ -17,10 +17,10 @@ import { type LitSelect } from '../../../../../base-ui/select/LitSelect'; import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; -import { querySysPurgeableSelectionTab } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { CompareStruct, compare, resizeObserverFromMemory } from '../SheetUtils'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {querySysPurgeableSelectionTab} from "../../../../database/sql/Ability.sql"; @element('tabpane-purgeable-total-comparison-ability') export class TabPanePurgTotalComparisonAbility extends BaseElement { private purgeableTotalTable: LitTable | null | undefined; diff --git a/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.ts b/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.ts index fb94b7968b95c857a0d33c0aaf13fd09f65cc32f..025f74d2ac696f2d9d30e3b45fc9c981b6ee7b2d 100644 --- a/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.ts +++ b/ide/src/trace/component/trace/sheet/ability/TabPanePurgTotalSelection.ts @@ -17,10 +17,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { queryProcessPurgeableSelectionTab, querySysPurgeableSelectionTab } from '../../../../database/SqlLite'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; +import { querySysPurgeableSelectionTab } from '../../../../database/sql/Ability.sql'; +import { queryProcessPurgeableSelectionTab } from '../../../../database/sql/ProcessThread.sql'; @element('tabpane-purg-total-selection') export class TabPanePurgTotalSelection extends BaseElement { @@ -38,7 +39,7 @@ export class TabPanePurgTotalSelection extends BaseElement { await querySysPurgeableSelectionTab(startNs).then((purgeTotalSelectResults) => { this.purgeableSelectionSource = []; if (purgeTotalSelectResults.length > 0) { - this.purgeableSelectionSource.push({ name: 'TimeStamp', value: ns2s(startNs) }); + this.purgeableSelectionSource.push({name: 'TimeStamp', value: ns2s(startNs)}); this.purgeableSelectionSource.push({ name: 'TimeStamp(Absolute)', value: (startNs + (window as any).recordStartNS) / 1000000000, @@ -54,7 +55,7 @@ export class TabPanePurgTotalSelection extends BaseElement { await queryProcessPurgeableSelectionTab(startNs, MemoryConfig.getInstance().iPid).then((results) => { this.purgeableSelectionSource = []; if (results.length > 0) { - this.purgeableSelectionSource.push({ name: 'TimeStamp(Relative)', value: ns2s(startNs) }); + this.purgeableSelectionSource.push({name: 'TimeStamp(Relative)', value: ns2s(startNs)}); this.purgeableSelectionSource.push({ name: 'TimeStamp(Absolute)', value: (startNs + (window as any).recordStartNS) / 1000000000, @@ -69,25 +70,25 @@ export class TabPanePurgTotalSelection extends BaseElement { } } - initElements(): void { - this.purgeableSelectionTable = this.shadowRoot?.querySelector('#selectionTbl'); - } - connectedCallback(): void { super.connectedCallback(); resizeObserver(this.parentElement!, this.purgeableSelectionTable!); } + initElements(): void { + this.purgeableSelectionTable = this.shadowRoot?.querySelector('#totalSelectionTbl'); + } + initHtml(): string { return ` - + diff --git a/ide/src/trace/component/trace/sheet/binder/TabPaneBinderDataCut.ts b/ide/src/trace/component/trace/sheet/binder/TabPaneBinderDataCut.ts index 7201b9f204f75d4a152ff41d02db05c651e4427b..10050fa7f9a49613c7cb52b4a92b0604df1f99f9 100644 --- a/ide/src/trace/component/trace/sheet/binder/TabPaneBinderDataCut.ts +++ b/ide/src/trace/component/trace/sheet/binder/TabPaneBinderDataCut.ts @@ -14,25 +14,25 @@ */ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; -import { LitTable, RedrawTreeForm } from '../../../../../base-ui/table/lit-table'; +import { type LitTable, RedrawTreeForm } from '../../../../../base-ui/table/lit-table'; import { Utils } from '../../base/Utils'; -import { SelectionParam } from '../../../../bean/BoxSelection'; +import { type SelectionParam } from '../../../../bean/BoxSelection'; import { - BinderItem, - BinderGroup, - DataSource, - FuncNameCycle, - BinderDataStruct, + type BinderItem, + type BinderGroup, + type DataSource, + type FuncNameCycle, + type BinderDataStruct, } from '../../../../bean/BinderProcessThread'; -import { querySingleFuncNameCycle, queryBinderByThreadId, queryLoopFuncNameCycle } from '../../../../database/SqlLite'; +import { querySingleFuncNameCycle, queryLoopFuncNameCycle } from '../../../../../trace/database/sql/Func.sql'; +import { queryBinderByThreadId } from '../../../../../trace/database/sql/ProcessThread.sql'; import { resizeObserver } from '../SheetUtils'; -import { LitChartColumn } from '../../../../../base-ui/chart/column/LitChartColumn'; +import { type LitChartColumn } from '../../../../../base-ui/chart/column/LitChartColumn'; import '../../../../../base-ui/chart/column/LitChartColumn'; -// import { SpSegmentationChart } from '../../../chart/SpSegmentationChart'; @element('tabpane-binder-datacut') export class TabPaneBinderDataCut extends BaseElement { - private threadBindersTbl: LitTable | null | undefined; + private threadBindersCutTbl: LitTable | null | undefined; private currentSelectionParam: SelectionParam | any; private threadStatesDIV: Element | null | undefined; private cycleARangeArr: BinderGroup[] | undefined; @@ -60,8 +60,8 @@ export class TabPaneBinderDataCut extends BaseElement { this.clickLoop(false); this.clickSingle(false); this.currentSelectionParam = threadStatesParam; - this.threadBindersTbl!.recycleDataSource = []; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.threadBindersCutTbl!.recycleDataSource = []; + this.tHeadClick(this.threadBindersCutTbl!.recycleDataSource); } dispalyQueryArea(b: boolean): void { @@ -89,6 +89,7 @@ export class TabPaneBinderDataCut extends BaseElement { } async dataLoopCut(threadId: HTMLInputElement, threadFunc: HTMLInputElement): Promise { + this.threadBindersCutTbl!.loading = true; this.currentThreadId = ''; let threadIds: number[] = this.currentSelectionParam.threadIds; //@ts-ignore @@ -98,10 +99,8 @@ export class TabPaneBinderDataCut extends BaseElement { let leftNS: number = this.currentSelectionParam.leftNs; let rightNS: number = this.currentSelectionParam.rightNs; if (threadIdValue !== '' && threadFuncName !== '') { - // SpSegmentationChart.setBinderChartData("BINDER", []); this.clickLoop(true); this.clickSingle(false); - this.threadBindersTbl!.loading = true; threadId.style.border = '1px solid rgb(151,151,151)'; threadFunc.style.border = '1px solid rgb(151,151,151)'; this.funcNameCycleArr = await queryLoopFuncNameCycle(threadFuncName, threadIdValue, leftNS, rightNS); @@ -129,13 +128,11 @@ export class TabPaneBinderDataCut extends BaseElement { } } let finalBinderCutArr: BinderItem[] = this.completionCycleName(binderCutArr, 'loop'); - this.threadBindersTbl!.recycleDataSource = this.transferToTreeData(finalBinderCutArr); - this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.threadBindersCutTbl!.recycleDataSource = this.transferToTreeData(finalBinderCutArr); + this.threadBindersCutTbl!.loading = false; + this.tHeadClick(this.threadBindersCutTbl!.recycleDataSource); } else { - this.threadBindersTbl!.recycleDataSource = []; - this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.clearTableData(); } } else { this.verifyInputIsEmpty(threadIdValue, threadFuncName, threadId, threadFunc); @@ -143,6 +140,7 @@ export class TabPaneBinderDataCut extends BaseElement { } async dataSingleCut(threadId: HTMLInputElement, threadFunc: HTMLInputElement): Promise { + this.threadBindersCutTbl!.loading = true; this.currentThreadId = ''; let threadIds: number[] = this.currentSelectionParam.threadIds; //@ts-ignore @@ -152,12 +150,10 @@ export class TabPaneBinderDataCut extends BaseElement { let leftNS: number = this.currentSelectionParam.leftNs; let rightNS: number = this.currentSelectionParam.rightNs; if (threadIdValue !== '' && threadFuncName !== '') { - // SpSegmentationChart.setBinderChartData("BINDER", []); this.clickLoop(false); this.clickSingle(true); threadId.style.border = '1px solid rgb(151,151,151)'; threadFunc.style.border = '1px solid rgb(151,151,151)'; - this.threadBindersTbl!.loading = true; this.funcNameCycleArr = await querySingleFuncNameCycle(threadFuncName, threadIdValue, leftNS, rightNS); let binderItemArr: BinderItem[] = await queryBinderByThreadId(processIds, threadIds, leftNS, rightNS); if (this.funcNameCycleArr.length !== 0) { @@ -167,7 +163,7 @@ export class TabPaneBinderDataCut extends BaseElement { if ( binderItemArr[i].ts > this.funcNameCycleArr[j].cycleStartTime && binderItemArr[i].ts + binderItemArr[i].dur < - this.funcNameCycleArr[j].cycleStartTime + this.funcNameCycleArr[j]!.cycleDur + this.funcNameCycleArr[j].cycleStartTime + this.funcNameCycleArr[j]!.cycleDur ) { binderItemArr[i].cycleDur = this.funcNameCycleArr[j].cycleDur; binderItemArr[i].cycleStartTime = this.funcNameCycleArr[j].cycleStartTime; @@ -181,19 +177,23 @@ export class TabPaneBinderDataCut extends BaseElement { } } let finalBinderCutArr: BinderItem[] = this.completionCycleName(binderCutArr, 'single'); - this.threadBindersTbl!.recycleDataSource = this.transferToTreeData(finalBinderCutArr); - this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.threadBindersCutTbl!.recycleDataSource = this.transferToTreeData(finalBinderCutArr); + this.threadBindersCutTbl!.loading = false; + this.tHeadClick(this.threadBindersCutTbl!.recycleDataSource); } else { - this.threadBindersTbl!.recycleDataSource = []; - this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.clearTableData(); } } else { this.verifyInputIsEmpty(threadIdValue, threadFuncName, threadId, threadFunc); } } + clearTableData(): void { + this.threadBindersCutTbl!.recycleDataSource = []; + this.threadBindersCutTbl!.loading = false; + this.tHeadClick(this.threadBindersCutTbl!.recycleDataSource); + } + verifyInputIsEmpty( threadIdValue: string, threadFuncName: string, @@ -203,9 +203,7 @@ export class TabPaneBinderDataCut extends BaseElement { if (threadIdValue === '') { threadId.style.border = '1px solid rgb(255,0,0)'; threadId.setAttribute('placeholder', 'Please input thread id'); - this.threadBindersTbl!.recycleDataSource = []; - this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.clearTableData(); } else { threadId.style.border = '1px solid rgb(151,151,151)'; } @@ -213,9 +211,7 @@ export class TabPaneBinderDataCut extends BaseElement { if (threadFuncName === '') { threadFunc.style.border = '1px solid rgb(255,0,0)'; threadFunc.setAttribute('placeholder', 'Please input function name'); - this.threadBindersTbl!.recycleDataSource = []; - this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.clearTableData(); } else { threadFunc.style.border = '1px solid rgb(151,151,151)'; } @@ -319,14 +315,10 @@ export class TabPaneBinderDataCut extends BaseElement { if (group[`${it.pid}`]) { let process = group[`${it.pid}`]; process.totalCount += it.count; - let thread = process.children.find( - (child: BinderGroup) => child.title === it.thread + ' ' + '[' + it.tid + ']' - ); + let thread = process.children.find((child: BinderGroup) => child.title === it.thread + ' ' + '[' + it.tid + ']'); if (thread) { thread.totalCount += it.count; - let cycle = thread.children.find( - (child: BinderGroup) => child.title === it.thread + ' ' + '[' + it.tid + ']' + '[' + it.id + ']' - ); + let cycle = thread.children.find((child: BinderGroup) => child.title === it.thread + ' ' + '[' + it.tid + ']' + '[' + it.id + ']'); if (cycle) { cycle.totalCount += it.count; cycle.binderTransactionCount += it.name === 'binder transaction' ? it.count : 0; @@ -350,8 +342,6 @@ export class TabPaneBinderDataCut extends BaseElement { group[`${it.pid}`] = { title: it.process + ' ' + '[' + it.pid + ']', totalCount: it.count, - tid: it.tid, - pid: it.pid, type: 'process', children: [ { @@ -374,6 +364,7 @@ export class TabPaneBinderDataCut extends BaseElement { addCycleNumber(groupArr: Array): Array { for (let i = 0; i < groupArr.length; i++) { if (groupArr[i].type === 'cycle') { + groupArr[i].title = 'cycle ' + (i + 1) + '_' + groupArr[i].thread; groupArr[i].idx = i + 1; } else { @@ -395,32 +386,32 @@ export class TabPaneBinderDataCut extends BaseElement { return groupArr; } - private theadClick(data: Array): void { - let labels = this.threadBindersTbl?.shadowRoot?.querySelector('.th > .td')!.querySelectorAll('label'); + private tHeadClick(data: Array): void { + let labels = this.threadBindersCutTbl?.shadowRoot?.querySelector('.th > .td')!.querySelectorAll('label'); if (labels) { for (let i = 0; i < labels.length; i++) { let label = labels[i].innerHTML; labels[i].addEventListener('click', (e) => { - if (label.includes('Process') && i === 0) { - this.threadBindersTbl!.setStatus(data, false); - this.threadBindersTbl!.recycleDs = this.threadBindersTbl!.meauseTreeRowElement( + if (label.includes('Process')) { + this.threadBindersCutTbl!.setStatus(data, false); + this.threadBindersCutTbl!.recycleDs = this.threadBindersCutTbl!.meauseTreeRowElement( data, RedrawTreeForm.Retract ); - } else if (label.includes('Thread') && i === 1) { + } else if (label.includes('Thread')) { for (let item of data) { item.status = true; if (item.children != undefined && item.children.length > 0) { - this.threadBindersTbl!.setStatus(item.children, false); + this.threadBindersCutTbl!.setStatus(item.children, false); } } - this.threadBindersTbl!.recycleDs = this.threadBindersTbl!.meauseTreeRowElement( + this.threadBindersCutTbl!.recycleDs = this.threadBindersCutTbl!.meauseTreeRowElement( data, RedrawTreeForm.Retract ); - } else if (label.includes('Cycle') && i === 2) { - this.threadBindersTbl!.setStatus(data, true); - this.threadBindersTbl!.recycleDs = this.threadBindersTbl!.meauseTreeRowElement(data, RedrawTreeForm.Expand); + } else if (label.includes('Cycle')) { + this.threadBindersCutTbl!.setStatus(data, true); + this.threadBindersCutTbl!.recycleDs = this.threadBindersCutTbl!.meauseTreeRowElement(data, RedrawTreeForm.Expand); } }); } @@ -486,36 +477,15 @@ export class TabPaneBinderDataCut extends BaseElement { return currentSelectThread; } - initElements(): void { - this.threadBindersTbl = this.shadowRoot?.querySelector('#tb-binder-count'); - this.chartTotal = this.shadowRoot!.querySelector('#chart_cycle'); - this.cycleAStartRangeDIV = this.shadowRoot?.querySelector('#cycle-a-start-range'); - this.cycleAEndRangeDIV = this.shadowRoot?.querySelector('#cycle-a-end-range'); - this.cycleBStartRangeDIV = this.shadowRoot?.querySelector('#cycle-b-start-range'); - this.cycleBEndRangeDIV = this.shadowRoot?.querySelector('#cycle-b-end-range'); - - this.threadStatesDIV = this.shadowRoot!.querySelector('#dataCut'); - this.threadStatesDIV?.children[2].children[0].addEventListener('click', (e) => { - this.dispalyQueryArea(true); - this.dataSource = []; - // @ts-ignore - this.dataSingleCut(this.threadStatesDIV!.children[0], this.threadStatesDIV?.children[1]); - }); - this.threadStatesDIV?.children[2].children[1].addEventListener('click', (e) => { - this.dispalyQueryArea(true); - this.dataSource = []; - // @ts-ignore - this.dataLoopCut(this.threadStatesDIV?.children[0], this.threadStatesDIV?.children[1]); - }); - - this.threadBindersTbl!.addEventListener('row-click', (evt: any) => { + rowClickFunc(): void { + this.threadBindersCutTbl!.addEventListener('row-click', (evt: any) => { let currentData: BinderGroup = evt.detail.data; if (currentData.type === 'thread') { this.currentThreadId = currentData.tid + '' + currentData.pid; this.clearCycleRange(); currentData.isSelected = true; - this.threadBindersTbl!.clearAllSelection(currentData); - this.threadBindersTbl!.setCurrentSelection(currentData); + this.threadBindersCutTbl!.clearAllSelection(currentData); + this.threadBindersCutTbl!.setCurrentSelection(currentData); this.rowCycleData = currentData.children; this.dispalyQueryArea(false); let totalCount = currentData.totalCount; @@ -527,20 +497,17 @@ export class TabPaneBinderDataCut extends BaseElement { if (this.dataSource!.length > 0) { this.drawColumn(); } - let threaId = currentData.tid; - let rowThreadBinderArr = this.findThreadByThreadId(this.cacheBinderArr!, threaId); - let binderWithCountList: Array = this.binderWithCountList(rowThreadBinderArr!); - // SpSegmentationChart.setBinderChartData('BINDER', binderWithCountList); } if (currentData.type === 'cycle' && currentData.tid + '' + currentData.pid === this.currentThreadId) { currentData.isSelected = true; - this.threadBindersTbl!.clearAllSelection(currentData); - this.threadBindersTbl!.setCurrentSelection(currentData); - // SpSegmentationChart.tabHover('BINDER', true, currentData.idx); + this.threadBindersCutTbl!.clearAllSelection(currentData); + this.threadBindersCutTbl!.setCurrentSelection(currentData); } }); + } + queryBtnFunc(): void { this.shadowRoot?.querySelector('#query-btn')?.addEventListener('click', () => { this.cycleARangeArr = this.rowCycleData?.filter((it: BinderGroup) => { return ( @@ -575,6 +542,31 @@ export class TabPaneBinderDataCut extends BaseElement { }); } + initElements(): void { + this.threadBindersCutTbl = this.shadowRoot?.querySelector('#tb-binder-count'); + this.chartTotal = this.shadowRoot!.querySelector('#chart_cycle'); + this.cycleAStartRangeDIV = this.shadowRoot?.querySelector('#cycle-a-start-range'); + this.cycleAEndRangeDIV = this.shadowRoot?.querySelector('#cycle-a-end-range'); + this.cycleBStartRangeDIV = this.shadowRoot?.querySelector('#cycle-b-start-range'); + this.cycleBEndRangeDIV = this.shadowRoot?.querySelector('#cycle-b-end-range'); + + this.threadStatesDIV = this.shadowRoot!.querySelector('#dataCut'); + this.threadStatesDIV?.children[2].children[0].addEventListener('click', (e) => { + this.dispalyQueryArea(true); + this.dataSource = []; + // @ts-ignore + this.dataSingleCut(this.threadStatesDIV!.children[0], this.threadStatesDIV?.children[1]); + }); + this.threadStatesDIV?.children[2].children[1].addEventListener('click', (e) => { + this.dispalyQueryArea(true); + this.dataSource = []; + // @ts-ignore + this.dataLoopCut(this.threadStatesDIV?.children[0], this.threadStatesDIV?.children[1]); + }); + this.rowClickFunc(); + this.queryBtnFunc(); + } + clearCycleRange(): void { this.cycleAStartRangeDIV!.value = ''; this.cycleAEndRangeDIV!.value = ''; @@ -607,8 +599,8 @@ export class TabPaneBinderDataCut extends BaseElement { if (a && a[0]) { let tip: string = ''; tip = `
-
Average count: ${a[0].obj.yAverage}
-
`; +
Average count: ${a[0].obj.yAverage}
+
`; return tip; } else { return ''; @@ -620,7 +612,7 @@ export class TabPaneBinderDataCut extends BaseElement { connectedCallback(): void { super.connectedCallback(); - resizeObserver(this.parentElement!, this.threadBindersTbl!); + resizeObserver(this.parentElement!, this.threadBindersCutTbl!); } initHtml(): string { diff --git a/ide/src/trace/component/trace/sheet/binder/TabPaneBinders.ts b/ide/src/trace/component/trace/sheet/binder/TabPaneBinders.ts index b7bb68dc5ff391c82069e7bafd41b312153afad6..aee1c856f38e83c6b19cbb595998f0bc4cd46b17 100644 --- a/ide/src/trace/component/trace/sheet/binder/TabPaneBinders.ts +++ b/ide/src/trace/component/trace/sheet/binder/TabPaneBinders.ts @@ -17,7 +17,7 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable, RedrawTreeForm } from '../../../../../base-ui/table/lit-table'; import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; import '../../../StackBar'; -import { queryBinderByThreadId } from '../../../../database/SqlLite'; +import { queryBinderByThreadId } from '../../../../database/sql/ProcessThread.sql'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; import { BinderGroup, BinderItem } from '../../../../bean/BinderProcessThread'; @@ -52,12 +52,12 @@ export class TabPaneBinders extends BaseElement { this.threadBindersTbl!.recycleDataSource = this.transferToTreeData(binderList); this.threadBindersTblSource = this.threadBindersTbl!.recycleDataSource; this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.threadBinderHeadClick(this.threadBindersTbl!.recycleDataSource); } else if (binderList.length === 0) { this.threadBindersTbl!.recycleDataSource = []; this.threadBindersTblSource = []; this.threadBindersTbl!.loading = false; - this.theadClick(this.threadBindersTbl!.recycleDataSource); + this.threadBinderHeadClick(this.threadBindersTbl!.recycleDataSource); } }); } @@ -121,19 +121,19 @@ export class TabPaneBinders extends BaseElement { return Object.values(group); } - private theadClick(data: Array): void { + private threadBinderHeadClick(data: Array): void { let labels = this.threadBindersTbl?.shadowRoot?.querySelector('.th > .td')!.querySelectorAll('label'); if (labels) { for (let i = 0; i < labels.length; i++) { let label = labels[i].innerHTML; labels[i].addEventListener('click', (e) => { - if (label.includes('Process') && i === 0) { + if (label.includes('Process')) { this.threadBindersTbl!.setStatus(data, false); this.threadBindersTbl!.recycleDs = this.threadBindersTbl!.meauseTreeRowElement( data, RedrawTreeForm.Retract ); - } else if (label.includes('Thread') && i === 1) { + } else if (label.includes('Thread')) { for (let item of data) { item.status = true; if (item.children !== undefined && item.children.length > 0) { diff --git a/ide/src/trace/component/trace/sheet/clock/TabPaneClockCounter.ts b/ide/src/trace/component/trace/sheet/clock/TabPaneClockCounter.ts index d1afe0da1a7b1d6ce79a05007d24d2251f07c05e..6527b429c55666724f456f91917614c5386c95ea 100644 --- a/ide/src/trace/component/trace/sheet/clock/TabPaneClockCounter.ts +++ b/ide/src/trace/component/trace/sheet/clock/TabPaneClockCounter.ts @@ -41,7 +41,7 @@ export class TabPaneClockCounter extends BaseElement { let sumCount = 0; for (let key of collect.keys()) { let counters = collect.get(key); - let res = await counters?.({ startNS: clockCounterValue.leftNs, endNS: clockCounterValue.rightNs }); + let res = await counters?.({ startNS: clockCounterValue.leftNs, endNS: clockCounterValue.rightNs, queryAll: true }); let sd = this.createSelectCounterData(key, res || [], clockCounterValue.leftNs, clockCounterValue.rightNs); sumCount += Number.parseInt(sd.count || '0'); dataSource.push(sd); diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts index 232fa680bb96d44d98b36e4f65cc31ab18a8010c..d666acc50dbb6a00b277890bff7aff8862977c35 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneBoxChild.ts @@ -16,10 +16,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { BoxJumpParam, SelectionData } from '../../../../bean/BoxSelection'; -import { getTabBoxChildData } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { SPTChild } from '../../../../bean/StateProcessThread'; import { resizeObserver } from '../SheetUtils'; +import {getTabBoxChildData} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-box-child') export class TabPaneBoxChild extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCounterSample.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCounterSample.ts index 158115754a081012e890600bad6661016f1e8ce6..e7bec32f002ed7e29a2a4a73654c44fd0a9850e6 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCounterSample.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCounterSample.ts @@ -16,7 +16,6 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPaneCounterSampleData } from '../../../../database/SqlLite'; import { LitProgressBar } from '../../../../../base-ui/progress-bar/LitProgressBar'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; @@ -25,7 +24,8 @@ import { dataFilterHandler, drawLines } from '../../../../database/ui-worker/Pro import { TraceRow } from '../../base/TraceRow'; import { CpuFreqStruct } from '../../../../database/ui-worker/ProcedureWorkerFreq'; import { CpuState } from '../../../../database/logic-worker/ProcedureLogicWorkerCpuState'; -import { CpuStateStruct } from '../../../../database/ui-worker/ProcedureWorkerCpuState'; +import { CpuStateStruct } from '../../../../database/ui-worker/cpu/ProcedureWorkerCpuState'; +import {getTabPaneCounterSampleData} from "../../../../database/sql/Cpu.sql"; @element('tabpane-counter-sample') export class TabPaneCounterSample extends BaseElement { @@ -74,7 +74,10 @@ export class TabPaneCounterSample extends BaseElement { // @ts-ignore this.sortTable(evt.detail.key, evt.detail.sort); }); + this.rowClickEvent(); + } + private rowClickEvent(): void { this.counterSampleTbl!.addEventListener('row-click', (evt) => { // @ts-ignore let data = evt.detail.data; @@ -97,7 +100,7 @@ export class TabPaneCounterSample extends BaseElement { cpuStateFilter[i].value === data.value && cpuStateFilter[i].cpu === data.cpu && Math.max(TraceRow.rangeSelectObject?.startNS!, cpuStateFilter[i].startTs!) < - Math.min(TraceRow.rangeSelectObject?.endNS!, cpuStateFilter[i].startTs! + cpuStateFilter[i].dur!) + Math.min(TraceRow.rangeSelectObject?.endNS!, cpuStateFilter[i].startTs! + cpuStateFilter[i].dur!) ) { CpuStateStruct.hoverStateStruct = cpuStateFilter[i]; } diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts index 5776e8c2b72fc6550f5792d7a7f665354107912e..491773edee0b966a7b819e601c517fba3a055b83 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByProcess.ts @@ -16,10 +16,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabCpuByProcess } from '../../../../database/SqlLite'; import { log } from '../../../../../log/Log'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; +import {getTabCpuByProcess} from "../../../../database/sql/Cpu.sql"; @element('tabpane-cpu-process') export class TabPaneCpuByProcess extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts index b4317de4106823f2894a38eca3b8ab06b1bfa112..d3bcce68b33511d63354d426a90969444e1ff806 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuByThread.ts @@ -16,11 +16,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabCpuByThread } from '../../../../database/SqlLite'; import { log } from '../../../../../log/Log'; import { getProbablyTime } from '../../../../database/logic-worker/ProcedureLogicWorkerCommon'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; +import {getTabCpuByThread} from "../../../../database/sql/Cpu.sql"; @element('tabpane-cpu-thread') export class TabPaneCpuByThread extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts index b25a44cdb209a6659505571c2560134f8ae9563d..8d0dca7a5e9a8d8e7abd4f5212c19b030c6d8b7f 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneCpuUsage.ts @@ -16,9 +16,9 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabCpuFreq, getTabCpuUsage } from '../../../../database/SqlLite'; import { CpuUsage, Freq } from '../../../../bean/CpuUsage'; import { resizeObserver } from '../SheetUtils'; +import {getTabCpuFreq, getTabCpuUsage} from "../../../../database/sql/Cpu.sql"; @element('tabpane-cpu-usage') export class TabPaneCpuUsage extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneFrequencySample.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneFrequencySample.ts index 1bf8dfeb720bfaf0624e323130a6d106b38bfbc2..81391bb5630c1c93c24a69d256f78b8820858948 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneFrequencySample.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneFrequencySample.ts @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2023 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 @@ -16,7 +16,8 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPaneFrequencySampleData, getTabPaneCounterSampleData } from '../../../../database/SqlLite'; +import { getTabPaneFrequencySampleData } from '../../../../database/sql/SqlLite.sql'; +import { getTabPaneCounterSampleData } from '../../../../database/sql/Cpu.sql'; import { ColorUtils } from '../../base/ColorUtils'; import { resizeObserver } from '../SheetUtils'; import { CpuFreqStruct } from '../../../../database/ui-worker/ProcedureWorkerFreq'; @@ -41,7 +42,7 @@ export class TabPaneFrequencySample extends BaseElement { private freqResult: Array = []; set data(frequencySampleValue: SelectionParam | any) { - if (frequencySampleValue == this.selectionParam) { + if (frequencySampleValue === this.selectionParam) { return; } this.selectionParam = frequencySampleValue; @@ -70,57 +71,7 @@ export class TabPaneFrequencySample extends BaseElement { this.sortTable(evt.detail.key, evt.detail.sort); }); this.frequencySampleTbl!.addEventListener('row-click', (evt) => { - // @ts-ignore - let data = evt.detail.data; - if (this._rangeRow && this._rangeRow!.length > 0) { - let rangeTraceRow = this._rangeRow!.filter(function (item) { - return item.name.includes('Frequency'); - }); - let freqFilter = []; - for (let row of rangeTraceRow!) { - let context = row.collect ? this.systemTrace!.canvasFavoritePanelCtx! : this.systemTrace!.canvasPanelCtx!; - freqFilter.push(...row.dataListCache); - row.canvasSave(context); - context.clearRect(row.frame.x, row.frame.y, row.frame.width, row.frame.height); - drawLines(context!, TraceRow.range?.xs || [], row.frame.height, this.systemTrace!.timerShaftEL!.lineColor()); - if (row.name.includes('Frequency') && parseInt(row.name.replace(/[^\d]/g, ' ')) === data.cpu) { - CpuFreqStruct.hoverCpuFreqStruct = undefined; - for (let i = 0; i < freqFilter!.length; i++) { - if ( - freqFilter[i].value === data.value && - freqFilter[i].cpu === data.cpu && - Math.max(TraceRow.rangeSelectObject?.startNS!, freqFilter[i].startNS!) < - Math.min(TraceRow.rangeSelectObject?.endNS!, freqFilter[i].startNS! + freqFilter[i].dur!) - ) { - CpuFreqStruct.hoverCpuFreqStruct = freqFilter[i]; - } - if (freqFilter[i].cpu === data.cpu) { - CpuFreqStruct.draw(context, freqFilter[i]); - } - } - } else { - for (let i = 0; i < freqFilter!.length; i++) { - if ( - row.name.includes('Frequency') && - freqFilter[i].cpu !== data.cpu && - freqFilter[i].cpu === parseInt(row.name.replace(/[^\d]/g, ' ')) - ) { - CpuFreqStruct.draw(context, freqFilter[i]); - } - } - } - let s = CpuFreqStruct.maxFreqName; - let textMetrics = context.measureText(s); - context.globalAlpha = 0.8; - context.fillStyle = '#f0f0f0'; - context.fillRect(0, 5, textMetrics.width + 8, 18); - context.globalAlpha = 1; - context.fillStyle = '#333'; - context.textBaseline = 'middle'; - context.fillText(s, 4, 5 + 9); - row.canvasRestore(context, this.systemTrace); - } - } + this.clickTblRowEvent(evt); }); this.frequencySampleTbl!.addEventListener('button-click', (evt) => { //@ts-ignore @@ -129,8 +80,62 @@ export class TabPaneFrequencySample extends BaseElement { //@ts-ignore this.handleClick(evt.detail.key, this.frequencySampleClickType); }); + //开启一个线程计算busyTime + this.worker = new Worker(new URL('../../../../database/StateBusyTimeWorker', import.meta.url)); + } + clickTblRowEvent(evt: Event): void { + // @ts-ignore + let data = evt.detail.data; + if (this._rangeRow && this._rangeRow!.length > 0) { + let rangeTraceRow = this._rangeRow!.filter(function (item) { + return item.name.includes('Frequency'); + }); + let freqFilter = []; + for (let row of rangeTraceRow!) { + let context = row.collect ? this.systemTrace!.canvasFavoritePanelCtx! : this.systemTrace!.canvasPanelCtx!; + freqFilter.push(...row.dataListCache); + row.canvasSave(context); + context.clearRect(row.frame.x, row.frame.y, row.frame.width, row.frame.height); + drawLines(context!, TraceRow.range?.xs || [], row.frame.height, this.systemTrace!.timerShaftEL!.lineColor()); + if (row.name.includes('Frequency') && parseInt(row.name.replace(/[^\d]/g, ' ')) === data.cpu) { + CpuFreqStruct.hoverCpuFreqStruct = undefined; + for (let i = 0; i < freqFilter!.length; i++) { + if ( + freqFilter[i].value === data.value && + freqFilter[i].cpu === data.cpu && + Math.max(TraceRow.rangeSelectObject?.startNS!, freqFilter[i].startNS!) < + Math.min(TraceRow.rangeSelectObject?.endNS!, freqFilter[i].startNS! + freqFilter[i].dur!) + ) { + CpuFreqStruct.hoverCpuFreqStruct = freqFilter[i]; + } + if (freqFilter[i].cpu === data.cpu) { + CpuFreqStruct.draw(context, freqFilter[i]); + } + } + } else { + for (let i = 0; i < freqFilter!.length; i++) { + if ( + row.name.includes('Frequency') && + freqFilter[i].cpu !== data.cpu && + freqFilter[i].cpu === parseInt(row.name.replace(/[^\d]/g, ' ')) + ) { + CpuFreqStruct.draw(context, freqFilter[i]); + } + } + } + let s = CpuFreqStruct.maxFreqName; + let textMetrics = context.measureText(s); + context.globalAlpha = 0.8; + context.fillStyle = '#f0f0f0'; + context.fillRect(0, 5, textMetrics.width + 8, 18); + context.globalAlpha = 1; + context.fillStyle = '#333'; + context.textBaseline = 'middle'; + context.fillText(s, 4, 5 + 9); + row.canvasRestore(context, this.systemTrace); + } + } } - connectedCallback() { super.connectedCallback(); resizeObserver(this.parentElement!, this.frequencySampleTbl!, 25, this.frequencyLoadingPage, 24); @@ -139,8 +144,6 @@ export class TabPaneFrequencySample extends BaseElement { async queryDataByDB(frqSampleParam: SelectionParam | any) { let sampleMap = new Map(); let frqSampleList = new Array(); - let stateFiliterIds: Array = []; - let cpuFiliterOrder: Array = []; this.frequencySampleTbl!.loading = true; if (this.frequencySampleClickType) this.frequencySampleClickType = !this.frequencySampleClickType; if (this.busyTimeLoadingHide) this.busyTimeLoadingHide = !this.busyTimeLoadingHide; @@ -152,7 +155,7 @@ export class TabPaneFrequencySample extends BaseElement { this.freqResult = result; frqSampleParam.cpuFreqFilterIds.forEach((a: number) => { this.getInitTime( - result.filter((f) => f.filterId == a), + result.filter((f) => f.filterId === a), sampleMap, frqSampleParam ); @@ -164,6 +167,12 @@ export class TabPaneFrequencySample extends BaseElement { this.frequencySampleSource = frqSampleList; this.frequencySampleTbl!.loading = false; this.sortTable(this.frequencySampleSortKey, this.frequencySampleSortType); + this.getBusyTimeData(frqSampleParam, sampleMap, result); + } + + async getBusyTimeData(frqSampleParam: SelectionParam, sampleMap: Map, result: Array) { + let stateFiliterIds: Array = []; + let cpuFiliterOrder: Array = []; //找出框选的cpu fre所对应的cpu state this.freqBusyDataList = []; if (!frqSampleParam.cpuStateRowsId.length) { @@ -173,8 +182,8 @@ export class TabPaneFrequencySample extends BaseElement { }); } else { frqSampleParam.cpuFreqFilterNames.forEach((item: string) => { - let cpuStateIds = frqSampleParam.cpuStateRowsId.filter( - (it: any) => it.cpu == item.replace(/[^\d]/g, ' ').trim() + let cpuStateIds:any = frqSampleParam.cpuStateRowsId.filter( + (it: any) => it.cpu === Number(item.replace(/[^\d]/g, ' ').trim()) ); stateFiliterIds.push(cpuStateIds[0].filterId); cpuFiliterOrder.push(cpuStateIds[0].cpu); @@ -184,8 +193,6 @@ export class TabPaneFrequencySample extends BaseElement { frqSampleParam.rightNs + frqSampleParam.recordStartNs, stateFiliterIds ); - //开启一个线程计算busyTime - this.worker = new Worker(new URL('../../../../database/StateBusyTimeWorker', import.meta.url)); let msg = { frqSampleParam, result, @@ -204,25 +211,23 @@ export class TabPaneFrequencySample extends BaseElement { if (this.frequencySampleClickType) { this.handleClick(this.frequencySampleSortKey, this.frequencySampleClickType); } - this.worker!.terminate(); }; } } - getInitTime(initFreqResult: Array, sampleMap: Map, selectionParam: SelectionParam) { let leftStartNs = selectionParam.leftNs + selectionParam.recordStartNs; let rightEndNs = selectionParam.rightNs + selectionParam.recordStartNs; - if (initFreqResult.length == 0) return; + if (initFreqResult.length === 0) { return }; let includeData = initFreqResult.findIndex((a) => a.ts >= leftStartNs); if (includeData !== 0) { initFreqResult = initFreqResult.slice( - includeData == -1 ? initFreqResult.length - 1 : includeData - 1, + includeData === -1 ? initFreqResult.length - 1 : includeData - 1, initFreqResult.length ); } - if (initFreqResult[0].ts < leftStartNs && includeData !== 0) initFreqResult[0].ts = leftStartNs; + if (initFreqResult[0].ts < leftStartNs && includeData !== 0) { initFreqResult[0].ts = leftStartNs }; initFreqResult.forEach((item, idx) => { - if (idx + 1 == initFreqResult.length) { + if (idx + 1 === initFreqResult.length) { item.time = rightEndNs - item.ts; } else { item.time = initFreqResult[idx + 1].ts - item.ts; @@ -245,7 +250,7 @@ export class TabPaneFrequencySample extends BaseElement { //点击按钮控制busyTime显示与否 handleClick(key: string, type: boolean) { let res = new Array(); - if (this.freqResult.length == 0) { + if (this.freqResult.length === 0) { return; } //当busyTime的值计算完毕后进入if判断 @@ -265,33 +270,33 @@ export class TabPaneFrequencySample extends BaseElement { } sortTable(key: string, type: number) { - if (type == 0) { + if (type === 0) { this.frequencySampleTbl!.recycleDataSource = this.frequencySampleSource; } else { let arr = Array.from(this.frequencySampleSource); arr.sort((frequencySampleLeftData, frequencySampleRightData): number => { - if (key == 'timeStr') { - if (type == 1) { + if (key === 'timeStr') { + if (type === 1) { return frequencySampleLeftData.time - frequencySampleRightData.time; } else { return frequencySampleRightData.time - frequencySampleLeftData.time; } - } else if (key == 'counter') { + } else if (key === 'counter') { if (frequencySampleLeftData.counter > frequencySampleRightData.counter) { return type === 2 ? -1 : 1; - } else if (frequencySampleLeftData.counter == frequencySampleRightData.counter) { + } else if (frequencySampleLeftData.counter === frequencySampleRightData.counter) { return 0; } else { return type === 2 ? 1 : -1; } - } else if (key == 'valueStr') { - if (type == 1) { + } else if (key === 'valueStr') { + if (type === 1) { return frequencySampleLeftData.value - frequencySampleRightData.value; } else { return frequencySampleRightData.value - frequencySampleLeftData.value; } - } else if (key == 'busyTimeStr') { - if (type == 1) { + } else if (key === 'busyTimeStr') { + if (type === 1) { return frequencySampleLeftData.busyTimeStr - frequencySampleRightData.busyTimeStr; } else { return frequencySampleRightData.busyTimeStr - frequencySampleLeftData.busyTimeStr; diff --git a/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts b/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts index 1fe39def394617fbd219981d28f9e413636bb496..27b43335da57758e590d33b3470e11d5dfa812e1 100644 --- a/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts +++ b/ide/src/trace/component/trace/sheet/cpu/TabPaneSchedPriority.ts @@ -19,8 +19,8 @@ import { SelectionParam } from '../../../../bean/BoxSelection'; import { resizeObserver } from '../SheetUtils'; import { procedurePool } from '../../../../database/Procedure'; import { Utils } from '../../base/Utils'; -import { queryThreadStateArgsByName } from '../../../../database/SqlLite'; import { Priority } from '../../../../bean/StateProcessThread'; +import {queryThreadStateArgsByName} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-sched-priority') export class TabPaneSchedPriority extends BaseElement { @@ -90,7 +90,7 @@ export class TabPaneSchedPriority extends BaseElement { async (res: Array) => { for (const item of res) { if (['R', 'R+'].includes(item.state)) { - runnableMap.set(`${item.itid}_${item.endTs}`, item); + runnableMap.set(`${item.itId}_${item.endTs}`, item); } if (item.cpu === null || !sptParam.cpus.includes(item.cpu)) { continue; @@ -111,7 +111,7 @@ export class TabPaneSchedPriority extends BaseElement { setPriority(runningPriority, strArg); resultData.push(runningPriority); - const runnableItem = runnableMap.get(`${item.itid}_${item.startTs}`); + const runnableItem = runnableMap.get(`${item.itId}_${item.startTs}`); if (runnableItem) { const runnablePriority = new Priority(); runnablePriority.priority = slice.priority; diff --git a/ide/src/trace/component/trace/sheet/energy/TabPaneEnergyAnomaly.ts b/ide/src/trace/component/trace/sheet/energy/TabPaneEnergyAnomaly.ts index 7751905f65bcf83b97d4203e1f2d1dc6892cb22e..014a3eebb2571fd91f99ce5cecc7502fc7f29b75 100644 --- a/ide/src/trace/component/trace/sheet/energy/TabPaneEnergyAnomaly.ts +++ b/ide/src/trace/component/trace/sheet/energy/TabPaneEnergyAnomaly.ts @@ -17,10 +17,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { SpHiSysEnergyChart } from '../../../chart/SpHiSysEnergyChart'; import { LitTable } from '../../../../../base-ui/table/lit-table'; -import { queryAnomalyDetailedData } from '../../../../database/SqlLite'; import { SelectionParam } from '../../../../bean/BoxSelection'; import { EnergyAnomalyStruct } from '../../../../database/ui-worker/ProcedureWorkerEnergyAnomaly'; import { resizeObserver } from '../SheetUtils'; +import {queryAnomalyDetailedData} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-anomaly-details') export class TabPaneEnergyAnomaly extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/energy/TabPanePowerBattery.ts b/ide/src/trace/component/trace/sheet/energy/TabPanePowerBattery.ts index c9189081780e2c98613519ff3f12814a8c92d8fa..130029e9e0ac5afe0fc39be1e82076b089bd891f 100644 --- a/ide/src/trace/component/trace/sheet/energy/TabPanePowerBattery.ts +++ b/ide/src/trace/component/trace/sheet/energy/TabPanePowerBattery.ts @@ -16,10 +16,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPowerBatteryData } from '../../../../database/SqlLite'; import { SpHiSysEnergyChart } from '../../../chart/SpHiSysEnergyChart'; import '../../../../../base-ui/table/lit-table'; import { resizeObserver } from '../SheetUtils'; +import {getTabPowerBatteryData} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-power-battery') export class TabPanePowerBattery extends BaseElement { @@ -40,7 +40,6 @@ export class TabPanePowerBattery extends BaseElement { queryDataByDB(val: SelectionParam | any) { getTabPowerBatteryData(val.rightNs).then((result) => { - let list: Array = []; let powerData: any = { POWER_IDE_BATTERY: { gas_gauge: [], @@ -56,49 +55,27 @@ export class TabPanePowerBattery extends BaseElement { result.forEach((item) => { let powerDatum: any = powerData[item.eventName]; if (item.appKey.toLocaleLowerCase() === 'appname') { - powerDatum['appName'] = SpHiSysEnergyChart.app_name; + powerDatum.appName = SpHiSysEnergyChart.app_name; } else { let eventData: Array = item.eventValue.split(','); - if (eventData.length > 0) { - let i = eventData.length - 1 >= 0 ? eventData.length - 1 : 0; - powerDatum[item.appKey.toLocaleLowerCase()] = eventData[i]; - } else { - powerDatum[item.appKey.toLocaleLowerCase()] = eventData.toString(); - } + let eventValue = eventData[eventData.length - 1] || ''; + powerDatum[item.appKey.toLocaleLowerCase()] = eventValue; } }); - list.push({ - name: 'Gas Gauge', - value: powerData['POWER_IDE_BATTERY'].gas_gauge + ' mAh', - }); - list.push({ - name: 'Charge', - value: powerData['POWER_IDE_BATTERY'].charge, - }); - list.push({ - name: 'Screen', - value: powerData['POWER_IDE_BATTERY'].screen, - }); - list.push({ - name: 'Level', - value: powerData['POWER_IDE_BATTERY'].level + ' %', - }); - list.push({ - name: 'Current', - value: powerData['POWER_IDE_BATTERY'].current + ' mA', - }); - list.push({ - name: 'Capacity', - value: powerData['POWER_IDE_BATTERY'].capacity + ' mAh', - }); - list.push({ name: 'APP Name', value: SpHiSysEnergyChart.app_name! }); - if (list.length > 0) { - this.tblPower!.recycleDataSource = list; - } else { - this.tblPower!.recycleDataSource = []; - } + let list = [ + { name: 'Gas Gauge', value: powerData.POWER_IDE_BATTERY.gas_gauge + ' mAh' }, + { name: 'Charge', value: powerData.POWER_IDE_BATTERY.charge }, + { name: 'Screen', value: powerData.POWER_IDE_BATTERY.screen }, + { name: 'Level', value: powerData.POWER_IDE_BATTERY.level + ' %' }, + { name: 'Current', value: powerData.POWER_IDE_BATTERY.current + ' mA' }, + { name: 'Capacity', value: powerData.POWER_IDE_BATTERY.capacity + ' mAh' }, + { name: 'APP Name', value: SpHiSysEnergyChart.app_name! }, + ]; + + this.tblPower!.recycleDataSource = list; + this.tblPower?.shadowRoot?.querySelectorAll('.tr').forEach((tr) => { - let td = tr.querySelectorAll('.td'); + const td = tr.querySelectorAll('.td'); this.setTableStyle(td[0], '0.9', '16px'); this.setTableStyle(td[1], '0.6', '20px'); }); diff --git a/ide/src/trace/component/trace/sheet/energy/TabPanePowerDetails.ts b/ide/src/trace/component/trace/sheet/energy/TabPanePowerDetails.ts index bd31a6818b398cae32a70baec32e26ba8c7e5935..ce76129ffabdc16ddb22f0f20565d5b8cadea93b 100644 --- a/ide/src/trace/component/trace/sheet/energy/TabPanePowerDetails.ts +++ b/ide/src/trace/component/trace/sheet/energy/TabPanePowerDetails.ts @@ -16,11 +16,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPowerDetailsData } from '../../../../database/SqlLite'; import { log } from '../../../../../log/Log'; import { PowerDetailsEnergy } from '../../../../bean/EnergyStruct'; import { SpHiSysEnergyChart } from '../../../chart/SpHiSysEnergyChart'; import { resizeObserver } from '../SheetUtils'; +import {getTabPowerDetailsData} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-power-details') export class TabPanePowerDetails extends BaseElement { @@ -37,6 +37,84 @@ export class TabPanePowerDetails extends BaseElement { resizeObserver(this.parentElement!, this.tblPowerDetails!); } + getTimeTypeValue() { + return [ + 'foreground_duration', + 'background_duration', + 'screen_on_duration', + 'screen_off_duration', + 'foreground_count', + 'background_count', + 'screen_on_count', + 'screen_off_count', + 'duration', + 'energy', + 'usage', + 'camera_id', + ]; + } + + getDurationTypeValue() { + return [ + 'background_time', + 'screen_on_time', + 'screen_off_time', + 'load', + 'uid', + 'usage', + 'charge', + 'foreground_count', + 'background_count', + 'screen_on_count', + 'screen_off_count', + 'energy', + 'duration', + ]; + } + + getEnergyTypeValue() { + return [ + 'background_time', + 'screen_on_time', + 'screen_off_time', + 'load', + 'charge', + 'foreground_count', + 'background_count', + 'screen_on_count', + 'screen_off_count', + 'camera_id', + 'uid', + 'foreground_duration', + 'foreground_energy', + 'background_duration', + 'background_energy', + 'screen_on_duration', + 'screen_on_energy', + 'screen_off_duration', + 'screen_off_energy', + ]; + } + + getCountTypeValue() { + return [ + 'background_time', + 'screen_on_time', + 'screen_off_time', + 'load', + 'energy', + 'usage', + 'foreground_duration', + 'background_duration', + 'screen_on_duration', + 'screen_off_duration', + 'camera_id', + 'uid', + 'duration', + 'charge', + ]; + } + initElements(): void { this.tblPowerDetails = this.shadowRoot?.querySelector('#tb-power-details-energy'); this.tblPowerDetails!.addEventListener('column-click', (evt) => { @@ -45,75 +123,43 @@ export class TabPanePowerDetails extends BaseElement { }); this.sourcePowerDetails = []; this.itemType = { - time_type: [ - 'foreground_duration', - 'background_duration', - 'screen_on_duration', - 'screen_off_duration', - 'foreground_count', - 'background_count', - 'screen_on_count', - 'screen_off_count', - 'duration', - 'energy', - 'usage', - 'camera_id', - ], - duration_type: [ - 'background_time', - 'screen_on_time', - 'screen_off_time', - 'load', - 'uid', - 'usage', - 'charge', - 'foreground_count', - 'background_count', - 'screen_on_count', - 'screen_off_count', - 'energy', - 'duration', - ], - energy_type: [ - 'background_time', - 'screen_on_time', - 'screen_off_time', - 'load', - 'charge', - 'foreground_count', - 'background_count', - 'screen_on_count', - 'screen_off_count', - 'camera_id', - 'uid', - 'foreground_duration', - 'foreground_energy', - 'background_duration', - 'background_energy', - 'screen_on_duration', - 'screen_on_energy', - 'screen_off_duration', - 'screen_off_energy', - ], - count_type: [ - 'background_time', - 'screen_on_time', - 'screen_off_time', - 'load', - 'energy', - 'usage', - 'foreground_duration', - 'background_duration', - 'screen_on_duration', - 'screen_off_duration', - 'camera_id', - 'uid', - 'duration', - 'charge', - ], + time_type:[], + duration_type:[], + energy_type:[], + count_type:[] + } + this.itemType.time_type = this.getTimeTypeValue(); + this.itemType.duration_type = this.getDurationTypeValue(); + this.itemType.energy_type = this.getEnergyTypeValue(); + this.itemType.count_type = this.getCountTypeValue(); + } + + getPowerData() { + return { + POWER_IDE_CPU: new PowerDetailsEnergy('CPU'), + POWER_IDE_LOCATION: new PowerDetailsEnergy('LOCATION'), + POWER_IDE_GPU: new PowerDetailsEnergy('GPU'), + POWER_IDE_DISPLAY: new PowerDetailsEnergy('DISPLAY'), + POWER_IDE_CAMERA: new PowerDetailsEnergy('CAMERA'), + POWER_IDE_BLUETOOTH: new PowerDetailsEnergy('BLUETOOTH'), + POWER_IDE_FLASHLIGHT: new PowerDetailsEnergy('FLASHLIGHT'), + POWER_IDE_AUDIO: new PowerDetailsEnergy('AUDIO'), + POWER_IDE_WIFISCAN: new PowerDetailsEnergy('WIFISCAN'), }; } + getTotalEnergy(powerData: any) { + return powerData['POWER_IDE_CPU'].getTotalEnergy(false) + + powerData['POWER_IDE_LOCATION'].getTotalEnergy(false) + + powerData['POWER_IDE_GPU'].getTotalEnergy(true) + + powerData['POWER_IDE_DISPLAY'].getTotalEnergy(true) + + powerData['POWER_IDE_CAMERA'].getTotalEnergy(false) + + powerData['POWER_IDE_BLUETOOTH'].getTotalEnergy(false) + + powerData['POWER_IDE_FLASHLIGHT'].getTotalEnergy(false) + + powerData['POWER_IDE_AUDIO'].getTotalEnergy(false) + + powerData['POWER_IDE_WIFISCAN'].getTotalEnergy(false); + } + queryDataByDB(val: SelectionParam | any) { getTabPowerDetailsData(val.leftNs - val.leftNs, val.rightNs).then((items) => { log('getTabPowerDetailsData size :' + items.length); @@ -123,18 +169,7 @@ export class TabPanePowerDetails extends BaseElement { set.add('LOAD'); set.add('CHARGE'); set.add('CAMERA_ID'); - - let powerData: any = { - POWER_IDE_CPU: new PowerDetailsEnergy('CPU'), - POWER_IDE_LOCATION: new PowerDetailsEnergy('LOCATION'), - POWER_IDE_GPU: new PowerDetailsEnergy('GPU'), - POWER_IDE_DISPLAY: new PowerDetailsEnergy('DISPLAY'), - POWER_IDE_CAMERA: new PowerDetailsEnergy('CAMERA'), - POWER_IDE_BLUETOOTH: new PowerDetailsEnergy('BLUETOOTH'), - POWER_IDE_FLASHLIGHT: new PowerDetailsEnergy('FLASHLIGHT'), - POWER_IDE_AUDIO: new PowerDetailsEnergy('AUDIO'), - POWER_IDE_WIFISCAN: new PowerDetailsEnergy('WIFISCAN'), - }; + let powerData: any = this.getPowerData(); let tsMax = 0; let currentAppIndex = -1; items.forEach((item) => { @@ -143,29 +178,15 @@ export class TabPanePowerDetails extends BaseElement { powerDatum['appName'] = SpHiSysEnergyChart.app_name; currentAppIndex = item.eventValue.split(',').indexOf(SpHiSysEnergyChart.app_name!); tsMax = 0; - } else if (currentAppIndex > -1) { + } else if (currentAppIndex > -1 && (set.has(item.appKey) ? item.startNS >= tsMax : true)) { if (set.has(item.appKey)) { - if (item.startNS >= tsMax) { - powerDatum[item.appKey.toLocaleLowerCase()] = item.eventValue; - tsMax = item.startNS; - } + powerDatum[item.appKey.toLocaleLowerCase()] = item.startNS >= tsMax ? (tsMax = item.startNS, item.eventValue) : powerDatum[item.appKey.toLocaleLowerCase()]; } else { - powerDatum[item.appKey.toLocaleLowerCase()] += parseInt(item.eventValue.split(',')[currentAppIndex]); + powerDatum[item.appKey.toLocaleLowerCase()] = (powerDatum[item.appKey.toLocaleLowerCase()] || 0) + parseInt(item.eventValue.split(',')[currentAppIndex]); } } }); - - let totalEnergy = - powerData['POWER_IDE_CPU'].getTotalEnergy(false) + - powerData['POWER_IDE_LOCATION'].getTotalEnergy(false) + - powerData['POWER_IDE_GPU'].getTotalEnergy(true) + - powerData['POWER_IDE_DISPLAY'].getTotalEnergy(true) + - powerData['POWER_IDE_CAMERA'].getTotalEnergy(false) + - powerData['POWER_IDE_BLUETOOTH'].getTotalEnergy(false) + - powerData['POWER_IDE_FLASHLIGHT'].getTotalEnergy(false) + - powerData['POWER_IDE_AUDIO'].getTotalEnergy(false) + - powerData['POWER_IDE_WIFISCAN'].getTotalEnergy(false); - + let totalEnergy = this.getTotalEnergy(powerData); detailsData.push(this.setEnergyItems(powerData, totalEnergy, 'POWER_IDE_CPU', false, 'time_type')); detailsData.push(this.setEnergyItems(powerData, totalEnergy, 'POWER_IDE_LOCATION', false, 'duration_type')); detailsData.push(this.setEnergyItems(powerData, totalEnergy, 'POWER_IDE_GPU', true, 'energy_type')); @@ -175,7 +196,6 @@ export class TabPanePowerDetails extends BaseElement { detailsData.push(this.setEnergyItems(powerData, totalEnergy, 'POWER_IDE_FLASHLIGHT', false, 'duration_type')); detailsData.push(this.setEnergyItems(powerData, totalEnergy, 'POWER_IDE_AUDIO', false, 'duration_type')); detailsData.push(this.setEnergyItems(powerData, totalEnergy, 'POWER_IDE_WIFISCAN', false, 'count_type')); - if (detailsData.length > 0) { this.sourcePowerDetails = detailsData; this.tblPowerDetails!.recycleDataSource = detailsData; @@ -183,12 +203,7 @@ export class TabPanePowerDetails extends BaseElement { this.sourcePowerDetails = []; this.tblPowerDetails!.recycleDataSource = []; } - this.tblPowerDetails?.shadowRoot?.querySelectorAll('.td').forEach((td) => { - td.style.fontSize = '14px'; - td.style.fontWeight = '400'; - td.style.opacity = '0.9'; - td.style.lineHeight = '16px'; - }); + this.updateTableStyles(); }); let th = this.tblPowerDetails?.shadowRoot?.querySelector('.th'); if (th) { @@ -196,6 +211,15 @@ export class TabPanePowerDetails extends BaseElement { } } + updateTableStyles() { + this.tblPowerDetails?.shadowRoot?.querySelectorAll('.td').forEach((td) => { + td.style.fontSize = '14px'; + td.style.fontWeight = '400'; + td.style.opacity = '0.9'; + td.style.lineHeight = '16px'; + }); + } + setEnergyItems(powerData: any, totalEnergy: number, energyName: string, isSimpleEnergy: boolean, type: any): any { let ratio = (powerData[energyName].getTotalEnergy(isSimpleEnergy) * 100) / totalEnergy; if (totalEnergy == 0) { @@ -298,13 +322,13 @@ export class TabPanePowerDetails extends BaseElement { if (type === 'number') { return sort === 2 ? // @ts-ignore - parseFloat(bPowerDetails[property] == '-' ? 0 : bPowerDetails[property]) - - // @ts-ignore - parseFloat(aPowerDetails[property] == '-' ? 0 : aPowerDetails[property]) + parseFloat(bPowerDetails[property] == '-' ? 0 : bPowerDetails[property]) - + // @ts-ignore + parseFloat(aPowerDetails[property] == '-' ? 0 : aPowerDetails[property]) : // @ts-ignore - parseFloat(aPowerDetails[property] == '-' ? 0 : aPowerDetails[property]) - - // @ts-ignore - parseFloat(bPowerDetails[property] == '-' ? 0 : bPowerDetails[property]); + parseFloat(aPowerDetails[property] == '-' ? 0 : aPowerDetails[property]) - + // @ts-ignore + parseFloat(bPowerDetails[property] == '-' ? 0 : bPowerDetails[property]); } else { // @ts-ignore if (bPowerDetails[property] > aPowerDetails[property]) { diff --git a/ide/src/trace/component/trace/sheet/energy/TabPaneSystemDetails.ts b/ide/src/trace/component/trace/sheet/energy/TabPaneSystemDetails.ts index dde0764ffa22bc6fa36017f640a7972b2922d503..b6f370080255f238815bdead0a81a6d9fb4b60e6 100644 --- a/ide/src/trace/component/trace/sheet/energy/TabPaneSystemDetails.ts +++ b/ide/src/trace/component/trace/sheet/energy/TabPaneSystemDetails.ts @@ -17,14 +17,14 @@ import { SystemDetailsEnergy } from '../../../../bean/EnergyStruct'; import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { - querySysLocationDetailsData, - querySysLockDetailsData, - querySystemWorkData, -} from '../../../../database/SqlLite'; import { SpHiSysEnergyChart } from '../../../chart/SpHiSysEnergyChart'; import { resizeObserver } from '../SheetUtils'; import { type LitSlicerTrack } from '../../../../../base-ui/slicer/lit-slicer'; +import { + querySysLocationDetailsData, + querySysLockDetailsData, + querySystemWorkData +} from "../../../../database/sql/SqlLite.sql"; @element('tabpane-system-details') export class TabPaneSystemDetails extends BaseElement { @@ -101,6 +101,10 @@ export class TabPaneSystemDetails extends BaseElement { this.detailsTbl!.dataSource = this.detailsSource; this.boxDetails!.style.width = '65%'; } + this.detailsTblStyle(); + } + + detailsTblStyle(){ this.detailsTbl!.shadowRoot?.querySelectorAll('.tr').forEach((tr) => { tr.style.gridTemplateColumns = '120px 1fr'; }); @@ -162,20 +166,23 @@ export class TabPaneSystemDetails extends BaseElement { log_level: '', eventName: 'Event Name', }); - this.tblSystemDetails!.recycleDataSource = this.eventSource.concat(itemList); this.detailsTbl!.dataSource = []; this.boxDetails!.style.width = '100%'; - this.tblSystemDetails?.shadowRoot?.querySelectorAll('.td').forEach((td) => { - td.style.fontSize = '14px'; - if (td.getAttribute('title') === 'Event Name' || td.getAttribute('title') === 'Time') { - td.style.fontWeight = '700'; - } else { - td.style.fontWeight = '400'; - td.style.opacity = '0.9'; - td.style.lineHeight = '16px'; - } - }); + this.tblSystemDetailsStyle(); + }); + } + + tblSystemDetailsStyle(){ + this.tblSystemDetails?.shadowRoot?.querySelectorAll('.td').forEach((td) => { + td.style.fontSize = '14px'; + if (td.getAttribute('title') === 'Event Name' || td.getAttribute('title') === 'Time') { + td.style.fontWeight = '700'; + } else { + td.style.fontWeight = '400'; + td.style.opacity = '0.9'; + td.style.lineHeight = '16px'; + } }); } 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 c79666e4ae19b2a4fad5ee64c4291d7cd0f77cd2..75ed7c9ffc0bc105c00b9c0118c686b64774d9bf 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneCallTree.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneCallTree.ts @@ -341,137 +341,173 @@ export class TabPaneCallTree extends BaseElement { this.addEventListener('contextmenu', (event) => { event.preventDefault(); // 阻止默认的上下文菜单弹框 }); - this.callTreeTbl!.addEventListener('row-click', (evt: any) => { - // @ts-ignore - let data = evt.detail.data as MerageBean; - document.dispatchEvent( - new CustomEvent('number_calibration', { - detail: { time: data.tsArray, durations: data.durArray }, - }) - ); - this.setRightTableData(data); - data.isSelected = true; - this.callTreeSelectedData = data; - this.callTreeTbr?.clearAllSelection(data); - this.callTreeTbr?.setCurrentSelection(data); - // @ts-ignore - if ((evt.detail as any).callBack) { - // @ts-ignore - (evt.detail as any).callBack(true); + this.rowClickEvent(); + let boundFilterFunc = this.filterFunc.bind(this); + this.callTreeFilter!.getDataLibrary(boundFilterFunc); + this.callTreeFilter!.getDataMining(boundFilterFunc); + this.handleCallTreeData(); + this.handleConstraintsData(); + this.handleFilterData(); + this.callTreeColumnClick(); + } + + private filterFunc(data: any): void { + let callTreeFuncArgs: any[] = []; + if (data.type === 'check') { + this.handleCheckType(data, callTreeFuncArgs); + } else if (data.type === 'select') { + this.handleSelectType(callTreeFuncArgs, data); + } else if (data.type === 'button') { + if (data.item === 'symbol') { + if (this.callTreeSelectedData && !this.callTreeSelectedData.canCharge) { + return; + } + if (this.callTreeSelectedData !== undefined) { + this.handleSymbolCase(data, callTreeFuncArgs); + } else { + return; + } + } else if (data.item === 'library') { + if (this.callTreeSelectedData && !this.callTreeSelectedData.canCharge) { + return; + } + if (this.callTreeSelectedData !== undefined && this.callTreeSelectedData.libName !== '') { + this.handleLibraryCase(data, callTreeFuncArgs); + } else { + return; + } + } else if (data.item === 'restore') { + this.handleRestoreCase(data, callTreeFuncArgs); } + } + this.performDataProcessing(callTreeFuncArgs); + }; + + private handleLibraryCase(data: any, callTreeFuncArgs: any[]): void { + this.callTreeFilter!.addDataMining({name: this.callTreeSelectedData.libName}, data.item); + callTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [this.callTreeSelectedData.libName, false, false], }); - this.callTreeTbr = this.shadowRoot?.querySelector('#tb-list'); - this.callTreeTbr!.addEventListener('row-click', (evt: any): void => { + } + + private handleSymbolCase(data: any, callTreeFuncArgs: any[]): void { + this.callTreeFilter!.addDataMining({name: this.callTreeSelectedData.symbolName}, data.item); + callTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [this.callTreeSelectedData.symbolName, false, true], + }); + } + + private callTreeColumnClick(): void { + this.callTreeTbl!.addEventListener('column-click', (evt: Event): void => { // @ts-ignore - let data = evt.detail.data as MerageBean; - this.callTreeTbl?.clearAllSelection(data); - (data as any).isSelected = true; - this.callTreeTbl!.scrollToData(data); + this.callTreeSortKey = evt.detail.key; // @ts-ignore - if ((evt.detail as any).callBack) { - // @ts-ignore - (evt.detail as any).callBack(true); + this.callTreeSortType = evt.detail.sort; + // @ts-ignore + this.setLTableData(this.callTreeDataSource); + this.frameChart!.data = this.callTreeDataSource; + }); + } + + private performDataProcessing(callTreeFuncArgs: any[]): void { + this.getDataByWorker(callTreeFuncArgs, (result: any[]) => { + this.setLTableData(result); + this.frameChart!.data = this.callTreeDataSource; + if (this.isChartShow) this.frameChart?.calculateChartData(); + this.callTreeTbl!.move1px(); + if (this.callTreeSelectedData) { + this.callTreeSelectedData.isSelected = false; + this.callTreeTbl?.clearAllSelection(this.callTreeSelectedData); + this.callTreeTbr!.recycleDataSource = []; + this.callTreeSelectedData = undefined; } }); - let filterFunc = (data: any): void => { - let callTreeFuncArgs: any[] = []; - if (data.type === 'check') { - if (data.item.checked) { - callTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [data.item.name, data.item.select === '0', data.item.type === 'symbol'], - }); - } else { - callTreeFuncArgs.push({ - funcName: 'resotreAllNode', - funcArgs: [[data.item.name]], - }); - callTreeFuncArgs.push({ + } + + private handleRestoreCase(data: any, callTreeFuncArgs: any[]): void { + if (data.remove !== undefined && data.remove.length > 0) { + let list = data.remove.map((item: any) => { + return item.name; + }); + callTreeFuncArgs.push({ + funcName: 'resotreAllNode', + funcArgs: [list], + }); + callTreeFuncArgs.push({ + funcName: 'resetAllNode', + funcArgs: [], + }); + list.forEach((symbolName: string) => { + callTreeFuncArgs.push({ + funcName: 'clearSplitMapData', + funcArgs: [symbolName], + }); + }); + } + } + + private handleFilterData(): void { + this.callTreeFilter!.getFilterData((callTreeFilterData: FilterData) => { + if (this.searchValue !== this.callTreeFilter!.filterValue) { + this.searchValue = this.callTreeFilter!.filterValue; + let callTreeArgs = [ + { + funcName: 'setSearchValue', + funcArgs: [this.searchValue], + }, + { funcName: 'resetAllNode', funcArgs: [], - }); - callTreeFuncArgs.push({ - funcName: 'clearSplitMapData', - funcArgs: [data.item.name], - }); - } - } else if (data.type === 'select') { - callTreeFuncArgs.push({ - funcName: 'resotreAllNode', - funcArgs: [[data.item.name]], + }, + ]; + this.getDataByWorker(callTreeArgs, (result: any[]): void => { + this.callTreeTbl!.isSearch = true; + this.callTreeTbl!.setStatus(result, true); + this.setLTableData(result); + this.frameChart!.data = this.callTreeDataSource; + this.switchFlameChart(callTreeFilterData); }); - callTreeFuncArgs.push({ + } else { + this.callTreeTbl!.setStatus(this.callTreeDataSource, true); + this.setLTableData(this.callTreeDataSource); + this.switchFlameChart(callTreeFilterData); + } + }); + } + + private handleConstraintsData(): void { + this.callTreeFilter!.getCallTreeConstraintsData((data: any) => { + let callTreeConstraintsArgs: any[] = [ + { + funcName: 'resotreAllNode', + funcArgs: [[this.callTreeNumRuleName]], + }, + { funcName: 'clearSplitMapData', - funcArgs: [data.item.name], - }); - callTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [data.item.name, data.item.select === '0', data.item.type === 'symbol'], + funcArgs: [this.callTreeNumRuleName], + }, + ]; + if (data.checked) { + callTreeConstraintsArgs.push({ + funcName: 'hideNumMaxAndMin', + funcArgs: [parseInt(data.min), data.max], }); - } else if (data.type === 'button') { - if (data.item === 'symbol') { - if (this.callTreeSelectedData && !this.callTreeSelectedData.canCharge) { - return; - } - if (this.callTreeSelectedData !== undefined) { - this.callTreeFilter!.addDataMining({ name: this.callTreeSelectedData.symbolName }, data.item); - callTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [this.callTreeSelectedData.symbolName, false, true], - }); - } else { - return; - } - } else if (data.item === 'library') { - if (this.callTreeSelectedData && !this.callTreeSelectedData.canCharge) { - return; - } - if (this.callTreeSelectedData !== undefined && this.callTreeSelectedData.libName !== '') { - this.callTreeFilter!.addDataMining({ name: this.callTreeSelectedData.libName }, data.item); - callTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [this.callTreeSelectedData.libName, false, false], - }); - } else { - return; - } - } else if (data.item === 'restore') { - if (data.remove !== undefined && data.remove.length > 0) { - let list = data.remove.map((item: any) => { - return item.name; - }); - callTreeFuncArgs.push({ - funcName: 'resotreAllNode', - funcArgs: [list], - }); - callTreeFuncArgs.push({ - funcName: 'resetAllNode', - funcArgs: [], - }); - list.forEach((symbolName: string) => { - callTreeFuncArgs.push({ - funcName: 'clearSplitMapData', - funcArgs: [symbolName], - }); - }); - } - } } - this.getDataByWorker(callTreeFuncArgs, (result: any[]) => { + callTreeConstraintsArgs.push({ + funcName: 'resetAllNode', + funcArgs: [], + }); + this.getDataByWorker(callTreeConstraintsArgs, (result: any[]) => { this.setLTableData(result); this.frameChart!.data = this.callTreeDataSource; if (this.isChartShow) this.frameChart?.calculateChartData(); - this.callTreeTbl!.move1px(); - if (this.callTreeSelectedData) { - this.callTreeSelectedData.isSelected = false; - this.callTreeTbl?.clearAllSelection(this.callTreeSelectedData); - this.callTreeTbr!.recycleDataSource = []; - this.callTreeSelectedData = undefined; - } }); - }; - this.callTreeFilter!.getDataLibrary(filterFunc); - this.callTreeFilter!.getDataMining(filterFunc); + }); + } + + private handleCallTreeData(): void { this.callTreeFilter!.getCallTreeData((data: any) => { if ([InvertOptionIndex, hideThreadOptionIndex, hideEventOptionIndex].includes(data.value)) { this.refreshAllNode({ @@ -510,67 +546,77 @@ export class TabPaneCallTree extends BaseElement { }); } }); - this.callTreeFilter!.getCallTreeConstraintsData((data: any) => { - let callTreeConstraintsArgs: any[] = [ - { - funcName: 'resotreAllNode', - funcArgs: [[this.callTreeNumRuleName]], - }, - { - funcName: 'clearSplitMapData', - funcArgs: [this.callTreeNumRuleName], - }, - ]; - if (data.checked) { - callTreeConstraintsArgs.push({ - funcName: 'hideNumMaxAndMin', - funcArgs: [parseInt(data.min), data.max], - }); - } - callTreeConstraintsArgs.push({ + } + + private handleSelectType(callTreeFuncArgs: any[], data: any): void { + callTreeFuncArgs.push({ + funcName: 'resotreAllNode', + funcArgs: [[data.item.name]], + }); + callTreeFuncArgs.push({ + funcName: 'clearSplitMapData', + funcArgs: [data.item.name], + }); + callTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [data.item.name, data.item.select === '0', data.item.type === 'symbol'], + }); + } + + private handleCheckType(data: any, callTreeFuncArgs: any[]): void { + if (data.item.checked) { + callTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [data.item.name, data.item.select === '0', data.item.type === 'symbol'], + }); + } else { + callTreeFuncArgs.push({ + funcName: 'resotreAllNode', + funcArgs: [[data.item.name]], + }); + callTreeFuncArgs.push({ funcName: 'resetAllNode', funcArgs: [], }); - this.getDataByWorker(callTreeConstraintsArgs, (result: any[]) => { - this.setLTableData(result); - this.frameChart!.data = this.callTreeDataSource; - if (this.isChartShow) this.frameChart?.calculateChartData(); + callTreeFuncArgs.push({ + funcName: 'clearSplitMapData', + funcArgs: [data.item.name], }); - }); - this.callTreeFilter!.getFilterData((callTreeFilterData: FilterData) => { - if (this.searchValue !== this.callTreeFilter!.filterValue) { - this.searchValue = this.callTreeFilter!.filterValue; - let callTreeArgs = [ - { - funcName: 'setSearchValue', - funcArgs: [this.searchValue], - }, - { - funcName: 'resetAllNode', - funcArgs: [], - }, - ]; - this.getDataByWorker(callTreeArgs, (result: any[]): void => { - this.callTreeTbl!.isSearch = true; - this.callTreeTbl!.setStatus(result, true); - this.setLTableData(result); - this.frameChart!.data = this.callTreeDataSource; - this.switchFlameChart(callTreeFilterData); - }); - } else { - this.callTreeTbl!.setStatus(this.callTreeDataSource, true); - this.setLTableData(this.callTreeDataSource); - this.switchFlameChart(callTreeFilterData); + } + } + + private rowClickEvent(): void { + this.callTreeTbl!.addEventListener('row-click', (evt: any) => { + // @ts-ignore + let data = evt.detail.data as MerageBean; + document.dispatchEvent( + new CustomEvent('number_calibration', { + detail: {time: data.tsArray, durations: data.durArray}, + }) + ); + this.setRightTableData(data); + data.isSelected = true; + this.callTreeSelectedData = data; + this.callTreeTbr?.clearAllSelection(data); + this.callTreeTbr?.setCurrentSelection(data); + // @ts-ignore + if ((evt.detail as any).callBack) { + // @ts-ignore + (evt.detail as any).callBack(true); } }); - this.callTreeTbl!.addEventListener('column-click', (evt: Event): void => { - // @ts-ignore - this.callTreeSortKey = evt.detail.key; + this.callTreeTbr = this.shadowRoot?.querySelector('#tb-list'); + this.callTreeTbr!.addEventListener('row-click', (evt: any): void => { // @ts-ignore - this.callTreeSortType = evt.detail.sort; + let data = evt.detail.data as MerageBean; + this.callTreeTbl?.clearAllSelection(data); + (data as any).isSelected = true; + this.callTreeTbl!.scrollToData(data); // @ts-ignore - this.setLTableData(this.callTreeDataSource); - this.frameChart!.data = this.callTreeDataSource; + if ((evt.detail as any).callBack) { + // @ts-ignore + (evt.detail as any).callBack(true); + } }); } @@ -602,38 +648,22 @@ export class TabPaneCallTree extends BaseElement { let isHideEvent: boolean = filterData.callTree[2]; let isHideThread: boolean = filterData.callTree[3]; let list = filterData.dataMining.concat(filterData.dataLibrary); - callTreeArgs.push({ - funcName: 'hideThread', - funcArgs: [isHideThread], - }); - callTreeArgs.push({ - funcName: 'hideEvent', - funcArgs: [isHideEvent], - }); - callTreeArgs.push({ - funcName: 'getCallChainsBySampleIds', - funcArgs: [isTopDown, this.queryFuncName], - }); + callTreeArgs.push({funcName: 'hideThread', funcArgs: [isHideThread],}); + callTreeArgs.push({funcName: 'hideEvent', funcArgs: [isHideEvent],}); + callTreeArgs.push({funcName: 'getCallChainsBySampleIds', funcArgs: [isTopDown, this.queryFuncName],}); this.callTreeTbr!.recycleDataSource = []; if (isHideSystemLibrary) { - callTreeArgs.push({ - funcName: 'hideSystemLibrary', - funcArgs: [true], - }); + callTreeArgs.push({funcName: 'hideSystemLibrary', funcArgs: [true],}); } if (filterData.callTreeConstraints.checked) { callTreeArgs.push({ - funcName: 'hideNumMaxAndMin', - funcArgs: [parseInt(filterData.callTreeConstraints.inputs[0]), filterData.callTreeConstraints.inputs[1]], + funcName: 'hideNumMaxAndMin', funcArgs: [parseInt(filterData.callTreeConstraints.inputs[0]), + filterData.callTreeConstraints.inputs[1]], }); } + callTreeArgs.push({funcName: 'splitAllProcess', funcArgs: [list],}); callTreeArgs.push({ - funcName: 'splitAllProcess', - funcArgs: [list], - }); - callTreeArgs.push({ - funcName: 'resetAllNode', - funcArgs: [], + funcName: 'resetAllNode', funcArgs: [], }); if (this._rowClickData && this._rowClickData.libId !== undefined && this._currentCallTreeLevel === 3) { callTreeArgs.push({ 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 767267fd6eda15b5c1d43fe6cdfb173d76239351..4ef186812dd3b479fc46769ea950efa1e8f81d8b 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneFileSystemCalltree.ts @@ -289,137 +289,138 @@ export class TabpaneFilesystemCalltree extends BaseElement { this.fsCallTreeTbl!.rememberScrollTop = true; this.fsCallTreeFilter = this.shadowRoot?.querySelector('#filter'); this.fsCallTreeFilter!.disabledTransfer(true); - this.fsCallTreeTbl!.addEventListener('row-click', (evt: any) => { - // @ts-ignore - let data = evt.detail.data as FileMerageBean; - document.dispatchEvent( - new CustomEvent('number_calibration', { - detail: { time: data.tsArray, durations: data.durArray }, - }) - ); - this.setRightTableData(data); - data.isSelected = true; - this.fsCallTreeCurrentSelectedData = data; - this.fsCallTreeTbr?.clearAllSelection(data); - this.fsCallTreeTbr?.setCurrentSelection(data); - // @ts-ignore - if ((evt.detail as any).callBack) { - // @ts-ignore - (evt.detail as any).callBack(true); + this.tblRowClickEvent(); + this.fsCallTreeTbr = this.shadowRoot?.querySelector('#tb-filesystem-list'); + this.tbrRowClickEvent(); + let boundFilterFunc = this.filterFunc.bind(this); + this.fsCallTreeFilter!.getDataLibrary(boundFilterFunc); + this.fsCallTreeFilter!.getDataMining(boundFilterFunc); + this.handleCallTreeData(); + this.handleConstraintsData(); + this.handleFilterData(); + this.callTreeColumnClick(); + } + + private filterFunc(data: any): void { + let fsCallTreeFuncArgs: any[] = []; + if (data.type === 'check') { + this.handleCheckType(data, fsCallTreeFuncArgs); + } else if (data.type === 'select') { + this.handleSelectType(fsCallTreeFuncArgs, data); + } else if (data.type === 'button') { + if (data.item == 'symbol') { + if (this.fsCallTreeCurrentSelectedData && !this.fsCallTreeCurrentSelectedData.canCharge) { + return; + } + if (this.fsCallTreeCurrentSelectedData !== undefined) { + this.handleSymbolCase(data, fsCallTreeFuncArgs); + } else { + return; + } + } else if (data.item === 'library') { + if (this.fsCallTreeCurrentSelectedData && !this.fsCallTreeCurrentSelectedData.canCharge) { + return; + } + if (this.fsCallTreeCurrentSelectedData !== undefined && this.fsCallTreeCurrentSelectedData.libName !== '') { + this.handleLibraryCase(data, fsCallTreeFuncArgs); + } else { + return; + } + } else if (data.item === 'restore') { + this.handleRestoreCase(data, fsCallTreeFuncArgs); } + } + this.performDataProcessing(fsCallTreeFuncArgs); + }; + + private handleSymbolCase(data: any, fsCallTreeFuncArgs: any[]): void { + this.fsCallTreeFilter!.addDataMining({name: this.fsCallTreeCurrentSelectedData.symbolName}, data.item); + fsCallTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [this.fsCallTreeCurrentSelectedData.symbolName, false, true], }); - this.fsCallTreeTbr = this.shadowRoot?.querySelector('#tb-filesystem-list'); - this.fsCallTreeTbr!.addEventListener('row-click', (evt: any): void => { + } + + private handleLibraryCase(data: any, fsCallTreeFuncArgs: any[]): void { + this.fsCallTreeFilter!.addDataMining({name: this.fsCallTreeCurrentSelectedData.libName}, data.item); + fsCallTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [this.fsCallTreeCurrentSelectedData.libName, false, false], + }); + } + + private callTreeColumnClick(): void { + this.fsCallTreeTbl!.addEventListener('column-click', (evt): void => { // @ts-ignore - let data = evt.detail.data as FileMerageBean; - this.fsCallTreeTbl?.clearAllSelection(data); - (data as any).isSelected = true; - this.fsCallTreeTbl!.scrollToData(data); + this.fsCallTreeSortKey = evt.detail.key; // @ts-ignore - if ((evt.detail as any).callBack) { - // @ts-ignore - (evt.detail as any).callBack(true); - } + this.fsCallTreeSortType = evt.detail.sort; + // @ts-ignore + this.setLTableData(this.fsCallTreeDataSource); + this.frameChart!.data = this.fsCallTreeDataSource; }); - let filterFunc = (data: any): void => { - let fsCallTreeFuncArgs: any[] = []; - if (data.type === 'check') { - if (data.item.checked) { - fsCallTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [data.item.name, data.item.select === '0', data.item.type === 'symbol'], - }); - } else { - fsCallTreeFuncArgs.push({ - funcName: 'resotreAllNode', - funcArgs: [[data.item.name]], - }); - fsCallTreeFuncArgs.push({ + } + + private handleFilterData(): void { + this.fsCallTreeFilter!.getFilterData((data: FilterData): void => { + if (this.searchValue != this.fsCallTreeFilter!.filterValue) { + this.searchValue = this.fsCallTreeFilter!.filterValue; + let fileArgs = [ + { + funcName: 'setSearchValue', + funcArgs: [this.searchValue], + }, + { funcName: 'resetAllNode', funcArgs: [], - }); - fsCallTreeFuncArgs.push({ - funcName: 'clearSplitMapData', - funcArgs: [data.item.name], - }); - } - } else if (data.type === 'select') { - fsCallTreeFuncArgs.push({ - funcName: 'resotreAllNode', - funcArgs: [[data.item.name]], + }, + ]; + this.getDataByWorker(fileArgs, (result: any[]): void => { + this.fsCallTreeTbl!.isSearch = true; + this.fsCallTreeTbl!.setStatus(result, true); + this.setLTableData(result); + this.frameChart!.data = this.fsCallTreeDataSource; + this.switchFlameChart(data); }); - fsCallTreeFuncArgs.push({ + } else { + this.fsCallTreeTbl!.setStatus(this.fsCallTreeDataSource, true); + this.setLTableData(this.fsCallTreeDataSource); + this.switchFlameChart(data); + } + }); + } + + private handleConstraintsData(): void { + this.fsCallTreeFilter!.getCallTreeConstraintsData((data: any) => { + let fsCallTreeConstraintsArgs: any[] = [ + { + funcName: 'resotreAllNode', + funcArgs: [[this.fsCallTreeNumRuleName]], + }, + { funcName: 'clearSplitMapData', - funcArgs: [data.item.name], - }); - fsCallTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [data.item.name, data.item.select == '0', data.item.type == 'symbol'], + funcArgs: [this.fsCallTreeNumRuleName], + }, + ]; + if (data.checked) { + fsCallTreeConstraintsArgs.push({ + funcName: 'hideNumMaxAndMin', + funcArgs: [parseInt(data.min), data.max], }); - } else if (data.type === 'button') { - if (data.item == 'symbol') { - if (this.fsCallTreeCurrentSelectedData && !this.fsCallTreeCurrentSelectedData.canCharge) { - return; - } - if (this.fsCallTreeCurrentSelectedData !== undefined) { - this.fsCallTreeFilter!.addDataMining({ name: this.fsCallTreeCurrentSelectedData.symbolName }, data.item); - fsCallTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [this.fsCallTreeCurrentSelectedData.symbolName, false, true], - }); - } else { - return; - } - } else if (data.item === 'library') { - if (this.fsCallTreeCurrentSelectedData && !this.fsCallTreeCurrentSelectedData.canCharge) { - return; - } - if (this.fsCallTreeCurrentSelectedData !== undefined && this.fsCallTreeCurrentSelectedData.libName !== '') { - this.fsCallTreeFilter!.addDataMining({ name: this.fsCallTreeCurrentSelectedData.libName }, data.item); - fsCallTreeFuncArgs.push({ - funcName: 'splitTree', - funcArgs: [this.fsCallTreeCurrentSelectedData.libName, false, false], - }); - } else { - return; - } - } else if (data.item === 'restore') { - if (data.remove !== undefined && data.remove.length > 0) { - let list = data.remove.map((item: any) => { - return item.name; - }); - fsCallTreeFuncArgs.push({ - funcName: 'resotreAllNode', - funcArgs: [list], - }); - fsCallTreeFuncArgs.push({ - funcName: 'resetAllNode', - funcArgs: [], - }); - list.forEach((symbolName: string) => { - fsCallTreeFuncArgs.push({ - funcName: 'clearSplitMapData', - funcArgs: [symbolName], - }); - }); - } - } } - this.getDataByWorker(fsCallTreeFuncArgs, (result: any[]): void => { + fsCallTreeConstraintsArgs.push({ + funcName: 'resetAllNode', + funcArgs: [], + }); + this.getDataByWorker(fsCallTreeConstraintsArgs, (result: any[]): void => { this.setLTableData(result); this.frameChart!.data = this.fsCallTreeDataSource; if (this.isChartShow) this.frameChart?.calculateChartData(); - this.fsCallTreeTbl!.move1px(); - if (this.fsCallTreeCurrentSelectedData) { - this.fsCallTreeCurrentSelectedData.isSelected = false; - this.fsCallTreeTbl?.clearAllSelection(this.fsCallTreeCurrentSelectedData); - this.fsCallTreeTbr!.recycleDataSource = []; - this.fsCallTreeCurrentSelectedData = undefined; - } }); - }; - this.fsCallTreeFilter!.getDataLibrary(filterFunc); - this.fsCallTreeFilter!.getDataMining(filterFunc); + }); + } + + private handleCallTreeData(): void { this.fsCallTreeFilter!.getCallTreeData((data: any): void => { if ([InvertOptionIndex, hideThreadOptionIndex, hideEventOptionIndex].includes(data.value)) { this.refreshAllNode({ @@ -458,67 +459,116 @@ export class TabpaneFilesystemCalltree extends BaseElement { }); } }); - this.fsCallTreeFilter!.getCallTreeConstraintsData((data: any) => { - let fsCallTreeConstraintsArgs: any[] = [ - { - funcName: 'resotreAllNode', - funcArgs: [[this.fsCallTreeNumRuleName]], - }, - { - funcName: 'clearSplitMapData', - funcArgs: [this.fsCallTreeNumRuleName], - }, - ]; - if (data.checked) { - fsCallTreeConstraintsArgs.push({ - funcName: 'hideNumMaxAndMin', - funcArgs: [parseInt(data.min), data.max], - }); + } + + private performDataProcessing(fsCallTreeFuncArgs: any[]): void { + this.getDataByWorker(fsCallTreeFuncArgs, (result: any[]): void => { + this.setLTableData(result); + this.frameChart!.data = this.fsCallTreeDataSource; + if (this.isChartShow) this.frameChart?.calculateChartData(); + this.fsCallTreeTbl!.move1px(); + if (this.fsCallTreeCurrentSelectedData) { + this.fsCallTreeCurrentSelectedData.isSelected = false; + this.fsCallTreeTbl?.clearAllSelection(this.fsCallTreeCurrentSelectedData); + this.fsCallTreeTbr!.recycleDataSource = []; + this.fsCallTreeCurrentSelectedData = undefined; } - fsCallTreeConstraintsArgs.push({ + }); + } + + private handleRestoreCase(data: any, fsCallTreeFuncArgs: any[]): void { + if (data.remove !== undefined && data.remove.length > 0) { + let list = data.remove.map((item: any) => { + return item.name; + }); + fsCallTreeFuncArgs.push({ + funcName: 'resotreAllNode', + funcArgs: [list], + }); + fsCallTreeFuncArgs.push({ funcName: 'resetAllNode', funcArgs: [], }); - this.getDataByWorker(fsCallTreeConstraintsArgs, (result: any[]): void => { - this.setLTableData(result); - this.frameChart!.data = this.fsCallTreeDataSource; - if (this.isChartShow) this.frameChart?.calculateChartData(); + list.forEach((symbolName: string) => { + fsCallTreeFuncArgs.push({ + funcName: 'clearSplitMapData', + funcArgs: [symbolName], + }); }); + } + } + + private handleSelectType(fsCallTreeFuncArgs: any[], data: any): void { + fsCallTreeFuncArgs.push({ + funcName: 'resotreAllNode', + funcArgs: [[data.item.name]], }); - this.fsCallTreeFilter!.getFilterData((data: FilterData): void => { - if (this.searchValue != this.fsCallTreeFilter!.filterValue) { - this.searchValue = this.fsCallTreeFilter!.filterValue; - let fileArgs = [ - { - funcName: 'setSearchValue', - funcArgs: [this.searchValue], - }, - { - funcName: 'resetAllNode', - funcArgs: [], - }, - ]; - this.getDataByWorker(fileArgs, (result: any[]): void => { - this.fsCallTreeTbl!.isSearch = true; - this.fsCallTreeTbl!.setStatus(result, true); - this.setLTableData(result); - this.frameChart!.data = this.fsCallTreeDataSource; - this.switchFlameChart(data); - }); - } else { - this.fsCallTreeTbl!.setStatus(this.fsCallTreeDataSource, true); - this.setLTableData(this.fsCallTreeDataSource); - this.switchFlameChart(data); - } + fsCallTreeFuncArgs.push({ + funcName: 'clearSplitMapData', + funcArgs: [data.item.name], }); - this.fsCallTreeTbl!.addEventListener('column-click', (evt): void => { + fsCallTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [data.item.name, data.item.select == '0', data.item.type == 'symbol'], + }); + } + + private handleCheckType(data: any, fsCallTreeFuncArgs: any[]): void { + if (data.item.checked) { + fsCallTreeFuncArgs.push({ + funcName: 'splitTree', + funcArgs: [data.item.name, data.item.select === '0', data.item.type === 'symbol'], + }); + } else { + fsCallTreeFuncArgs.push({ + funcName: 'resotreAllNode', + funcArgs: [[data.item.name]], + }); + fsCallTreeFuncArgs.push({ + funcName: 'resetAllNode', + funcArgs: [], + }); + fsCallTreeFuncArgs.push({ + funcName: 'clearSplitMapData', + funcArgs: [data.item.name], + }); + } + } + + private tbrRowClickEvent(): void { + this.fsCallTreeTbr!.addEventListener('row-click', (evt: any): void => { // @ts-ignore - this.fsCallTreeSortKey = evt.detail.key; + let data = evt.detail.data as FileMerageBean; + this.fsCallTreeTbl?.clearAllSelection(data); + (data as any).isSelected = true; + this.fsCallTreeTbl!.scrollToData(data); // @ts-ignore - this.fsCallTreeSortType = evt.detail.sort; + if ((evt.detail as any).callBack) { + // @ts-ignore + (evt.detail as any).callBack(true); + } + }); + } + + private tblRowClickEvent(): void { + this.fsCallTreeTbl!.addEventListener('row-click', (evt: any) => { // @ts-ignore - this.setLTableData(this.fsCallTreeDataSource); - this.frameChart!.data = this.fsCallTreeDataSource; + let data = evt.detail.data as FileMerageBean; + document.dispatchEvent( + new CustomEvent('number_calibration', { + detail: {time: data.tsArray, durations: data.durArray}, + }) + ); + this.setRightTableData(data); + data.isSelected = true; + this.fsCallTreeCurrentSelectedData = data; + this.fsCallTreeTbr?.clearAllSelection(data); + this.fsCallTreeTbr?.setCurrentSelection(data); + // @ts-ignore + if ((evt.detail as any).callBack) { + // @ts-ignore + (evt.detail as any).callBack(true); + } }); } @@ -585,24 +635,12 @@ export class TabpaneFilesystemCalltree extends BaseElement { let isHideEvent: boolean = filterData.callTree[2]; let isHideThread: boolean = filterData.callTree[3]; let list = filterData.dataMining.concat(filterData.dataLibrary); - fileSysCallTreeArgs.push({ - funcName: 'hideThread', - funcArgs: [isHideThread], - }); - fileSysCallTreeArgs.push({ - funcName: 'hideEvent', - funcArgs: [isHideEvent], - }); - fileSysCallTreeArgs.push({ - funcName: 'getCallChainsBySampleIds', - funcArgs: [isTopDown, 'fileSystem'], - }); + fileSysCallTreeArgs.push({funcName: 'hideThread', funcArgs: [isHideThread],}); + fileSysCallTreeArgs.push({funcName: 'hideEvent', funcArgs: [isHideEvent],}); + fileSysCallTreeArgs.push({funcName: 'getCallChainsBySampleIds', funcArgs: [isTopDown, 'fileSystem'],}); this.fsCallTreeTbr!.recycleDataSource = []; if (isHideSystemLibrary) { - fileSysCallTreeArgs.push({ - funcName: 'hideSystemLibrary', - funcArgs: [], - }); + fileSysCallTreeArgs.push({funcName: 'hideSystemLibrary', funcArgs: [],}); } if (filterData.callTreeConstraints.checked) { fileSysCallTreeArgs.push({ @@ -610,14 +648,8 @@ export class TabpaneFilesystemCalltree extends BaseElement { funcArgs: [parseInt(filterData.callTreeConstraints.inputs[0]), filterData.callTreeConstraints.inputs[1]], }); } - fileSysCallTreeArgs.push({ - funcName: 'splitAllProcess', - funcArgs: [list], - }); - fileSysCallTreeArgs.push({ - funcName: 'resetAllNode', - funcArgs: [], - }); + fileSysCallTreeArgs.push({funcName: 'splitAllProcess', funcArgs: [list],}); + fileSysCallTreeArgs.push({funcName: 'resetAllNode', funcArgs: [],}); if (this._fsRowClickData && this._fsRowClickData.libId !== undefined && this._currentFsCallTreeLevel === 3) { fileSysCallTreeArgs.push({ funcName: 'showLibLevelData', 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 2ae7372ad7e5359f77a683400b00c7a2e0019252..7b4416ef01fab88db13769c55676157674e0d8f5 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatistics.ts @@ -16,9 +16,9 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPaneFilesystemStatistics } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { LitProgressBar } from '../../../../../base-ui/progress-bar/LitProgressBar'; +import {getTabPaneFilesystemStatistics} from "../../../../database/sql/SqlLite.sql"; @element('tabpane-file-statistics') export class TabPaneFileStatistics extends BaseElement { @@ -117,48 +117,7 @@ export class TabPaneFileStatistics extends BaseElement { avgDuration: '', children: [], }; - result.forEach((item, idx) => { - if (fileStatisticsFatherMap.has(item.type)) { - let fileStatisticsObj = fileStatisticsFatherMap.get(item.type); - fileStatisticsObj.count += item.count; - fileStatisticsObj.logicalReads += item.logicalReads; - fileStatisticsObj.logicalWrites += item.logicalWrites; - fileStatisticsObj.otherFile += item.otherFile; - fileStatisticsObj.allDuration += item.allDuration; - fileStatisticsObj.minDuration = - fileStatisticsObj.minDuration <= item.minDuration ? fileStatisticsObj.minDuration : item.minDuration; - fileStatisticsObj.maxDuration = - fileStatisticsObj.maxDuration >= item.maxDuration ? fileStatisticsObj.maxDuration : item.maxDuration; - fileStatisticsObj.children.push(this.getInitData(item)); - } else { - fileStatisticsFatherMap.set(item.type, { - type: item.type, - count: item.count, - logicalReads: item.logicalReads, - logicalWrites: item.logicalWrites, - otherFile: item.otherFile, - allDuration: item.allDuration, - minDuration: item.minDuration, - maxDuration: item.maxDuration, - children: [this.getInitData(item)], - }); - } - if (idx == 0) { - fileStatisticsAllNode.minDuration = item.minDuration; - } else { - fileStatisticsAllNode.minDuration = - fileStatisticsAllNode.minDuration <= item.minDuration - ? fileStatisticsAllNode.minDuration - : item.minDuration; - } - fileStatisticsAllNode.count += item.count; - fileStatisticsAllNode.logicalReads += item.logicalReads; - fileStatisticsAllNode.logicalWrites += item.logicalWrites; - fileStatisticsAllNode.otherFile += item.otherFile; - fileStatisticsAllNode.allDuration += item.allDuration; - fileStatisticsAllNode.maxDuration = - fileStatisticsAllNode.maxDuration >= item.maxDuration ? fileStatisticsAllNode.maxDuration : item.maxDuration; - }); + this.handleResult(result, fileStatisticsFatherMap, fileStatisticsAllNode); fileStatisticsFatherMap.forEach((item) => { item.avgDuration = item.allDuration / item.count; let node = this.getInitData(item); @@ -180,6 +139,51 @@ export class TabPaneFileStatistics extends BaseElement { }); } + private handleResult(result: Array, fileStatisticsFatherMap: Map, fileStatisticsAllNode: any): void { + result.forEach((item, idx) => { + if (fileStatisticsFatherMap.has(item.type)) { + let fileStatisticsObj = fileStatisticsFatherMap.get(item.type); + fileStatisticsObj.count += item.count; + fileStatisticsObj.logicalReads += item.logicalReads; + fileStatisticsObj.logicalWrites += item.logicalWrites; + fileStatisticsObj.otherFile += item.otherFile; + fileStatisticsObj.allDuration += item.allDuration; + fileStatisticsObj.minDuration = + fileStatisticsObj.minDuration <= item.minDuration ? fileStatisticsObj.minDuration : item.minDuration; + fileStatisticsObj.maxDuration = + fileStatisticsObj.maxDuration >= item.maxDuration ? fileStatisticsObj.maxDuration : item.maxDuration; + fileStatisticsObj.children.push(this.getInitData(item)); + } else { + fileStatisticsFatherMap.set(item.type, { + type: item.type, + count: item.count, + logicalReads: item.logicalReads, + logicalWrites: item.logicalWrites, + otherFile: item.otherFile, + allDuration: item.allDuration, + minDuration: item.minDuration, + maxDuration: item.maxDuration, + children: [this.getInitData(item)], + }); + } + if (idx == 0) { + fileStatisticsAllNode.minDuration = item.minDuration; + } else { + fileStatisticsAllNode.minDuration = + fileStatisticsAllNode.minDuration <= item.minDuration + ? fileStatisticsAllNode.minDuration + : item.minDuration; + } + fileStatisticsAllNode.count += item.count; + fileStatisticsAllNode.logicalReads += item.logicalReads; + fileStatisticsAllNode.logicalWrites += item.logicalWrites; + fileStatisticsAllNode.otherFile += item.otherFile; + fileStatisticsAllNode.allDuration += item.allDuration; + fileStatisticsAllNode.maxDuration = + fileStatisticsAllNode.maxDuration >= item.maxDuration ? fileStatisticsAllNode.maxDuration : item.maxDuration; + }); + } + sortTable(fileStatisticsAllNode: any, key: string) { fileStatisticsAllNode.children.sort((fileStatisticsA: any, fileStatisticsB: any) => { if (this.fileStatisticsSortType == 1) { diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.ts index 283ec7acc1f34742e59896ca5e707eb5586d2270..37d9a49a2dc8bf80e6994425d84cf2a7443513d2 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneFilesystemStatisticsAnalysis.ts @@ -124,70 +124,15 @@ export class TabPaneFilesystemStatisticsAnalysis extends BaseElement { this.checkBoxs = popover!.querySelectorAll('.check-wrap > lit-check-box'); this.fsTableArray = this.shadowRoot!.querySelectorAll('lit-table') as NodeListOf; for (let fsTable of this.fsTableArray) { - fsTable!.addEventListener('column-click', (evt) => { - // @ts-ignore - this.fsSortColumn = evt.detail.key; - // @ts-ignore - this.fsSortType = evt.detail.sort; - this.sortByColumn(); - }); + this.columnClickListeners(fsTable); fsTable!.addEventListener('contextmenu', function (event) { event.preventDefault(); // 阻止默认的上下文菜单弹框 }); - fsTable!.addEventListener('row-hover', (evt) => { - // @ts-ignore - let detail = evt.detail; - if (detail.data) { - let tableData = detail.data; - tableData.isHover = true; - if (detail.callBack) { - detail.callBack(true); - } - } - this.fsPieChart?.showHover(); - this.fsPieChart?.hideTip(); - }); - fsTable!.addEventListener('row-click', (evt) => { - // @ts-ignore - let detail = evt.detail; - if (detail.button === 2) { - let fsTab = this.parentElement?.parentElement?.querySelector( - '#box-file-system-calltree > tabpane-filesystem-calltree' - ); - fsTab!.cWidth = this.clientWidth; - fsTab!.currentFsCallTreeLevel = this.currentLevel; - if (this.hideProcessCheckBox?.checked) { - detail.data.pid = undefined; - } - if (this.hideThreadCheckBox?.checked) { - detail.data.tid = undefined; - } - fsTab!.fsRowClickData = detail.data; - let title = ''; - if (this.titleEl?.textContent === '') { - title = detail.data.tableName; - } else { - title = this.titleEl?.textContent + ' / ' + detail.data.tableName; - } - fsTab!.pieTitle = title; - // 是否是在表格上右键点击跳转到火焰图的 - this.fsCurrentSelection!.isRowClick = true; - fsTab!.data = this.fsCurrentSelection; - } - }); + this.initTableRowHoverListeners(fsTable); + this.initTableRowClickListeners(fsTable); } for (let box of this.checkBoxs) { - box!.addEventListener('change', (event) => { - if (this.hideProcessCheckBox!.checked && this.hideThreadCheckBox!.checked) { - this.hideThread(); - this.fsBack!.style.visibility = 'hidden'; - } else if (this.hideProcessCheckBox!.checked && !this.hideThreadCheckBox!.checked) { - this.hideProcess(); - } else { - this.reset(this.fileStatisticsAnalysisTableProcess!, false); - this.getFilesystemProcess(this.fileStatisticsAnalysisProcessData); - } - }); + this.checkBoxListener(box); } const addRowClickEventListener = (fsTable: LitTable, clickEvent: Function) => { fsTable.addEventListener('row-click', (evt) => { @@ -198,13 +143,83 @@ export class TabPaneFilesystemStatisticsAnalysis extends BaseElement { } }); }; - addRowClickEventListener(this.fileStatisticsAnalysisTableProcess!, this.fileProcessLevelClickEvent.bind(this)); addRowClickEventListener(this.fileStatisticsAnalysisTableType!, this.fileTypeLevelClickEvent.bind(this)); addRowClickEventListener(this.fileStatisticsAnalysisTableThread!, this.fileThreadLevelClickEvent.bind(this)); addRowClickEventListener(this.fileStatisticsAnalysisTableSo!, this.fileSoLevelClickEvent.bind(this)); } + private checkBoxListener(box: LitCheckBox): void { + box!.addEventListener('change', (event) => { + if (this.hideProcessCheckBox!.checked && this.hideThreadCheckBox!.checked) { + this.hideThread(); + this.fsBack!.style.visibility = 'hidden'; + } else if (this.hideProcessCheckBox!.checked && !this.hideThreadCheckBox!.checked) { + this.hideProcess(); + } else { + this.reset(this.fileStatisticsAnalysisTableProcess!, false); + this.getFilesystemProcess(this.fileStatisticsAnalysisProcessData); + } + }); + } + + private initTableRowClickListeners(fsTable: LitTable): void { + fsTable!.addEventListener('row-click', (evt) => { + // @ts-ignore + let detail = evt.detail; + if (detail.button === 2) { + let fsTab = this.parentElement?.parentElement?.querySelector( + '#box-file-system-calltree > tabpane-filesystem-calltree' + ); + fsTab!.cWidth = this.clientWidth; + fsTab!.currentFsCallTreeLevel = this.currentLevel; + if (this.hideProcessCheckBox?.checked) { + detail.data.pid = undefined; + } + if (this.hideThreadCheckBox?.checked) { + detail.data.tid = undefined; + } + fsTab!.fsRowClickData = detail.data; + let title = ''; + if (this.titleEl?.textContent === '') { + title = detail.data.tableName; + } else { + title = this.titleEl?.textContent + ' / ' + detail.data.tableName; + } + fsTab!.pieTitle = title; + // 是否是在表格上右键点击跳转到火焰图的 + this.fsCurrentSelection!.isRowClick = true; + fsTab!.data = this.fsCurrentSelection; + } + }); + } + + private initTableRowHoverListeners(fsTable: LitTable): void { + fsTable!.addEventListener('row-hover', (evt) => { + // @ts-ignore + let detail = evt.detail; + if (detail.data) { + let tableData = detail.data; + tableData.isHover = true; + if (detail.callBack) { + detail.callBack(true); + } + } + this.fsPieChart?.showHover(); + this.fsPieChart?.hideTip(); + }); + } + + private columnClickListeners(fsTable: LitTable): void { + fsTable!.addEventListener('column-click', (evt) => { + // @ts-ignore + this.fsSortColumn = evt.detail.key; + // @ts-ignore + this.fsSortType = evt.detail.sort; + this.sortByColumn(); + }); + } + private reset(showTable: LitTable, isShowBack: boolean): void { this.clearData(); if (isShowBack) { 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 d155ae4c6b211dfde3e6e08a8a6ed0504bf756ff..38b4d17ab17413e768405cdd9a7ecea83b8a3e5e 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatistics.ts @@ -16,11 +16,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPaneIOTierStatisticsData } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { LitProgressBar } from '../../../../../base-ui/progress-bar/LitProgressBar'; -import { TabPaneFilter } from '../TabPaneFilter'; import { SpSystemTrace } from '../../../SpSystemTrace'; +import { getTabPaneIOTierStatisticsData } from "../../../../database/sql/SqlLite.sql"; @element('tabpane-io-tier-statistics') export class TabPaneIOTierStatistics extends BaseElement { @@ -125,45 +124,8 @@ export class TabPaneIOTierStatistics extends BaseElement { children: [], }; result.forEach((resultItem, idx) => { - if (ioTierChildMap.has(resultItem[firstLevel] + '_' + resultItem[secondLevel])) { - let currentChildObject = ioTierChildMap.get(resultItem[firstLevel] + '_' + resultItem[secondLevel]); - currentChildObject.count += resultItem.count; - currentChildObject.allDuration += resultItem.allDuration; - currentChildObject.minDuration = - currentChildObject.minDuration <= resultItem.minDuration - ? currentChildObject.minDuration - : resultItem.minDuration; - currentChildObject.maxDuration = - currentChildObject.maxDuration >= resultItem.maxDuration - ? currentChildObject.maxDuration - : resultItem.maxDuration; - currentChildObject.children.push(this.getInitData(resultItem, 'path', null)); - } else { - ioTierChildMap.set(resultItem[firstLevel] + '_' + resultItem[secondLevel], { - ...resultItem, - children: [this.getInitData(resultItem, 'path', null)], - }); - } - - if (ioTierFatherMap.has(resultItem[firstLevel])) { - let currentFatherObject = ioTierFatherMap.get(resultItem[firstLevel]); - currentFatherObject.count += resultItem.count; - currentFatherObject.allDuration += resultItem.allDuration; - currentFatherObject.minDuration = - currentFatherObject.minDuration <= resultItem.minDuration - ? currentFatherObject.minDuration - : resultItem.minDuration; - currentFatherObject.maxDuration = - currentFatherObject.maxDuration >= resultItem.maxDuration - ? currentFatherObject.maxDuration - : resultItem.maxDuration; - currentFatherObject.children.push(this.getInitData(resultItem)); - } else { - ioTierFatherMap.set(resultItem[firstLevel], { - ...resultItem, - children: [this.getInitData(resultItem)], - }); - } + this.updateIoTierChildMap(ioTierChildMap, resultItem, firstLevel, secondLevel); + this.updateIoTierFatherMap(ioTierFatherMap, resultItem, firstLevel); if (idx == 0) { ioTierAllNode.minDuration = resultItem.minDuration; } else { @@ -175,7 +137,63 @@ export class TabPaneIOTierStatistics extends BaseElement { ioTierAllNode.maxDuration = ioTierAllNode.maxDuration >= resultItem.maxDuration ? ioTierAllNode.maxDuration : resultItem.maxDuration; }); + this.calculateAvgDuration(ioTierFatherMap, ioTierChildMap, ioTierAllNode); + ioTierAllNode = this.getInitData(ioTierAllNode); + ioTierAllNode.title = 'All'; + ioTierAllNode.path = {tier: null, pid: null, path: null, value: 'All'}; + this.ioTierStatisticsSource = result.length > 0 ? [ioTierAllNode] : []; + let newSource = JSON.parse(JSON.stringify(this.ioTierStatisticsSource)); + if (this.ioTierStatisticsSortType != 0 && result.length > 0) + this.sortTable(newSource[0], this.ioTierStatisticsSortKey); + this.ioTierStatisticsTbl!.recycleDataSource = newSource; + } + private updateIoTierFatherMap(ioTierFatherMap: Map, resultItem: any, firstLevel: string): void { + if (ioTierFatherMap.has(resultItem[firstLevel])) { + let currentFatherObject = ioTierFatherMap.get(resultItem[firstLevel]); + currentFatherObject.count += resultItem.count; + currentFatherObject.allDuration += resultItem.allDuration; + currentFatherObject.minDuration = + currentFatherObject.minDuration <= resultItem.minDuration + ? currentFatherObject.minDuration + : resultItem.minDuration; + currentFatherObject.maxDuration = + currentFatherObject.maxDuration >= resultItem.maxDuration + ? currentFatherObject.maxDuration + : resultItem.maxDuration; + currentFatherObject.children.push(this.getInitData(resultItem)); + } else { + ioTierFatherMap.set(resultItem[firstLevel], { + ...resultItem, + children: [this.getInitData(resultItem)], + }); + } + } + + private updateIoTierChildMap(ioTierChildMap: Map, resultItem: any, firstLevel: string, + secondLevel: string): void { + if (ioTierChildMap.has(resultItem[firstLevel] + '_' + resultItem[secondLevel])) { + let currentChildObject = ioTierChildMap.get(resultItem[firstLevel] + '_' + resultItem[secondLevel]); + currentChildObject.count += resultItem.count; + currentChildObject.allDuration += resultItem.allDuration; + currentChildObject.minDuration = + currentChildObject.minDuration <= resultItem.minDuration + ? currentChildObject.minDuration + : resultItem.minDuration; + currentChildObject.maxDuration = + currentChildObject.maxDuration >= resultItem.maxDuration + ? currentChildObject.maxDuration + : resultItem.maxDuration; + currentChildObject.children.push(this.getInitData(resultItem, 'path', null)); + } else { + ioTierChildMap.set(resultItem[firstLevel] + '_' + resultItem[secondLevel], { + ...resultItem, + children: [this.getInitData(resultItem, 'path', null)], + }); + } + } + + private calculateAvgDuration(ioTierFatherMap: Map, ioTierChildMap: Map, ioTierAllNode: any): void { for (let ks of ioTierFatherMap.keys()) { let sp = ioTierFatherMap.get(ks); sp!.children = []; @@ -212,14 +230,6 @@ export class TabPaneIOTierStatistics extends BaseElement { } ioTierAllNode.avgDuration = ioTierAllNode.allDuration / ioTierAllNode.count; - ioTierAllNode = this.getInitData(ioTierAllNode); - ioTierAllNode.title = 'All'; - ioTierAllNode.path = { tier: null, pid: null, path: null, value: 'All' }; - this.ioTierStatisticsSource = result.length > 0 ? [ioTierAllNode] : []; - let newSource = JSON.parse(JSON.stringify(this.ioTierStatisticsSource)); - if (this.ioTierStatisticsSortType != 0 && result.length > 0) - this.sortTable(newSource[0], this.ioTierStatisticsSortKey); - this.ioTierStatisticsTbl!.recycleDataSource = newSource; } sortTable(allNode: any, key: string) { diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.ts index 7521c71c6f1124c76782f6f013c007099278c331..0388ccaf43128a0dcbc13c152d589752cfb92223 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneIOTierStatisticsAnalysis.ts @@ -130,72 +130,12 @@ export class TabPaneIOTierStatisticsAnalysis extends BaseElement { this.ioTableArray = this.shadowRoot!.querySelectorAll('lit-table') as NodeListOf; for (let ioTable of this.ioTableArray) { ioTable.shadowRoot!.querySelector('.table')!.style.height = 'calc(100% - 31px)'; - ioTable!.addEventListener('column-click', (evt) => { - // @ts-ignore - this.ioSortColumn = evt.detail.key; - // @ts-ignore - this.ioSortType = evt.detail.sort; - this.sortByColumn(); - }); - ioTable!.addEventListener('contextmenu', function (event) { - event.preventDefault(); // 阻止默认的上下文菜单弹框 - }); - ioTable!.addEventListener('row-hover', (evt) => { - // @ts-ignore - let detail = evt.detail; - if (detail.data) { - let tableData = detail.data; - tableData.isHover = true; - if (detail.callBack) { - detail.callBack(true); - } - } - this.ioPieChart?.showHover(); - this.ioPieChart?.hideTip(); - }); - ioTable!.addEventListener('row-click', (evt) => { - // @ts-ignore - let detail = evt.detail; - if (detail.button === 2) { - let ioTab = this.parentElement?.parentElement?.querySelector( - '#box-io-calltree > tabpane-io-calltree' - ); - if (detail.button === 2) { - ioTab!.cWidth = this.clientWidth; - ioTab!.currentCallTreeLevel = this.currentLevel; - if (this.hideProcessCheckBox?.checked) { - detail.data.pid = undefined; - } - if (this.hideThreadCheckBox?.checked) { - detail.data.tid = undefined; - } - ioTab!.rowClickData = detail.data; - let title = ''; - if (this.titleEl?.textContent === '') { - title = detail.data.tableName; - } else { - title = this.titleEl?.textContent + ' / ' + detail.data.tableName; - } - ioTab!.pieTitle = title; - // 是否是在表格上右键点击跳转到火焰图的 - this.currentSelection!.isRowClick = true; - ioTab!.data = this.currentSelection; - } - } - }); + this.columnClickEvent(ioTable); + this.rowHoverEvent(ioTable); + this.rowClickEvent(ioTable); } for (let box of this.checkBoxs) { - box!.addEventListener('change', (event) => { - if (this.hideProcessCheckBox!.checked && this.hideThreadCheckBox!.checked) { - this.hideThread(); - this.iOTierStatisticsAnalysisBack!.style.visibility = 'hidden'; - } else if (this.hideProcessCheckBox!.checked && !this.hideThreadCheckBox!.checked) { - this.hideProcess(); - } else { - this.reset(this.ioTierTableProcess!, false); - this.getIOTierProcess(this.processData); - } - }); + this.checkBoxEvent(box); } const addRowClickEventListener = (ioTable: LitTable, clickEvent: Function) => { @@ -214,6 +154,82 @@ export class TabPaneIOTierStatisticsAnalysis extends BaseElement { addRowClickEventListener(this.ioTierTableSo!, this.ioTierSoLevelClickEvent.bind(this)); } + private columnClickEvent(ioTable: LitTable): void { + ioTable!.addEventListener('column-click', (evt) => { + // @ts-ignore + this.ioSortColumn = evt.detail.key; + // @ts-ignore + this.ioSortType = evt.detail.sort; + this.sortByColumn(); + }); + ioTable!.addEventListener('contextmenu', function (event) { + event.preventDefault(); // 阻止默认的上下文菜单弹框 + }); + } + + private checkBoxEvent(box: LitCheckBox): void { + box!.addEventListener('change', (event) => { + if (this.hideProcessCheckBox!.checked && this.hideThreadCheckBox!.checked) { + this.hideThread(); + this.iOTierStatisticsAnalysisBack!.style.visibility = 'hidden'; + } else if (this.hideProcessCheckBox!.checked && !this.hideThreadCheckBox!.checked) { + this.hideProcess(); + } else { + this.reset(this.ioTierTableProcess!, false); + this.getIOTierProcess(this.processData); + } + }); + } + + private rowClickEvent(ioTable: LitTable): void { + ioTable!.addEventListener('row-click', (evt) => { + // @ts-ignore + let detail = evt.detail; + if (detail.button === 2) { + let ioTab = this.parentElement?.parentElement?.querySelector( + '#box-io-calltree > tabpane-io-calltree' + ); + if (detail.button === 2) { + ioTab!.cWidth = this.clientWidth; + ioTab!.currentCallTreeLevel = this.currentLevel; + if (this.hideProcessCheckBox?.checked) { + detail.data.pid = undefined; + } + if (this.hideThreadCheckBox?.checked) { + detail.data.tid = undefined; + } + ioTab!.rowClickData = detail.data; + let title = ''; + if (this.titleEl?.textContent === '') { + title = detail.data.tableName; + } else { + title = this.titleEl?.textContent + ' / ' + detail.data.tableName; + } + ioTab!.pieTitle = title; + // 是否是在表格上右键点击跳转到火焰图的 + this.currentSelection!.isRowClick = true; + ioTab!.data = this.currentSelection; + } + } + }); + } + + private rowHoverEvent(ioTable: LitTable): void { + ioTable!.addEventListener('row-hover', (evt) => { + // @ts-ignore + let detail = evt.detail; + if (detail.data) { + let tableData = detail.data; + tableData.isHover = true; + if (detail.callBack) { + detail.callBack(true); + } + } + this.ioPieChart?.showHover(); + this.ioPieChart?.hideTip(); + }); + } + private reset(showTable: LitTable, isShowBack: boolean): void { this.clearData(); if (isShowBack) { diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneIoCompletionTimes.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneIoCompletionTimes.ts index 57fa58e7aad3cc2b8590e141af343f80eee42492..3e68cf871a97dfff3996612627ef2f8767fc3097 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneIoCompletionTimes.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneIoCompletionTimes.ts @@ -25,7 +25,7 @@ import { VM_TYPE_MAP, } from '../../../../database/logic-worker/ProcedureLogicWorkerFileSystem'; import { FilterData, TabPaneFilter } from '../TabPaneFilter'; -import { getTabIoCompletionTimesType } from '../../../../database/SqlLite'; +import { getTabIoCompletionTimesType } from '../../../../database/sql/SqlLite.sql'; @element('tabpane-io-completiontimes') export class TabPaneIoCompletionTimes extends BaseElement { @@ -228,66 +228,44 @@ export class TabPaneIoCompletionTimes extends BaseElement { }); } - sortioCompletionTimesTable(ioCompletionTimesKey: string, type: number) { + sortioCompletionTimesTable(ioCompletionTimesKey: string, type: number): void { if (type == 0) { this.ioCompletionTimesTbl!.recycleDataSource = this.ioCompletionTimesSource; } else { let arr = Array.from(this.ioCompletionTimesSource); arr.sort((ioCompletionTimesA, ioCompletionTimesB): number => { - if (ioCompletionTimesKey == 'startTsStr') { - if (type == 1) { - return ioCompletionTimesA.startTs - ioCompletionTimesB.startTs; - } else { - return ioCompletionTimesB.startTs - ioCompletionTimesA.startTs; - } - } else if (ioCompletionTimesKey == 'durStr') { - if (type == 1) { - return ioCompletionTimesA.dur - ioCompletionTimesB.dur; - } else { - return ioCompletionTimesB.dur - ioCompletionTimesA.dur; - } - } else if (ioCompletionTimesKey == 'process') { - if (ioCompletionTimesA.process > ioCompletionTimesB.process) { - return type === 2 ? 1 : -1; - } else if (ioCompletionTimesA.process == ioCompletionTimesB.process) { - return 0; - } else { - return type === 2 ? -1 : 1; - } - } else if (ioCompletionTimesKey == 'durPer4kStr') { - if (type == 1) { - return ioCompletionTimesA.durPer4k - ioCompletionTimesB.durPer4k; - } else { - return ioCompletionTimesB.durPer4k - ioCompletionTimesA.durPer4k; - } - } else if (ioCompletionTimesKey == 'thread') { - if (ioCompletionTimesA.thread > ioCompletionTimesB.thread) { - return type === 2 ? 1 : -1; - } else if (ioCompletionTimesA.thread == ioCompletionTimesB.thread) { - return 0; - } else { - return type === 2 ? -1 : 1; - } - } else if (ioCompletionTimesKey == 'operation') { - if (ioCompletionTimesA.operation > ioCompletionTimesB.operation) { - return type === 2 ? 1 : -1; - } else if (ioCompletionTimesA.operation == ioCompletionTimesB.operation) { - return 0; - } else { - return type === 2 ? -1 : 1; - } - } else if (ioCompletionTimesKey == 'sizeStr') { - if (type == 1) { - return ioCompletionTimesA.size - ioCompletionTimesB.size; - } else { - return ioCompletionTimesB.size - ioCompletionTimesA.size; - } - } else if (ioCompletionTimesKey == 'tier') { - if (type == 1) { - return ioCompletionTimesA.tier - ioCompletionTimesB.tier; - } else { - return ioCompletionTimesB.tier - ioCompletionTimesA.tier; - } + if (ioCompletionTimesKey === 'startTsStr') { + return type === 1 + ? ioCompletionTimesA.startTs - ioCompletionTimesB.startTs + : ioCompletionTimesB.startTs - ioCompletionTimesA.startTs; + } else if (ioCompletionTimesKey === 'durStr') { + return type === 1 + ? ioCompletionTimesA.dur - ioCompletionTimesB.dur + : ioCompletionTimesB.dur - ioCompletionTimesA.dur; + } else if (ioCompletionTimesKey === 'process') { + return ioCompletionTimesA.process === ioCompletionTimesB.process + ? 0 : (type === 2 ? (ioCompletionTimesA.process > ioCompletionTimesB.process ? 1 : -1) + : (ioCompletionTimesA.process > ioCompletionTimesB.process ? -1 : 1)); + } else if (ioCompletionTimesKey === 'durPer4kStr') { + return type === 1 + ? ioCompletionTimesA.durPer4k - ioCompletionTimesB.durPer4k + : ioCompletionTimesB.durPer4k - ioCompletionTimesA.durPer4k; + } else if (ioCompletionTimesKey === 'thread') { + return ioCompletionTimesA.thread > ioCompletionTimesB.thread + ? (type === 2 ? 1 : -1) : (ioCompletionTimesA.thread === ioCompletionTimesB.thread + ? 0 : (type === 2 ? -1 : 1)); + } else if (ioCompletionTimesKey === 'operation') { + return ioCompletionTimesA.operation > ioCompletionTimesB.operation + ? (type === 2 ? 1 : -1) : (ioCompletionTimesA.operation === ioCompletionTimesB.operation + ? 0 : (type === 2 ? -1 : 1)); + } else if (ioCompletionTimesKey === 'sizeStr') { + return type === 1 + ? ioCompletionTimesA.size - ioCompletionTimesB.size + : ioCompletionTimesB.size - ioCompletionTimesA.size; + } else if (ioCompletionTimesKey === 'tier') { + return type === 1 + ? ioCompletionTimesA.tier - ioCompletionTimesB.tier + : ioCompletionTimesB.tier - ioCompletionTimesA.tier; } else { return 0; } diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneVMEvents.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneVMEvents.ts index af97a433f048d7c03ef9cfd6d27501598ceb12b4..0053590301e49754bbdf40ed832671579d138294 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneVMEvents.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneVMEvents.ts @@ -21,7 +21,7 @@ import { LitProgressBar } from '../../../../../base-ui/progress-bar/LitProgressB import { procedurePool } from '../../../../database/Procedure'; import { VirtualMemoryEvent, VM_TYPE_MAP } from '../../../../database/logic-worker/ProcedureLogicWorkerFileSystem'; import { FilterData, TabPaneFilter } from '../TabPaneFilter'; -import { getTabVirtualMemoryType } from '../../../../database/SqlLite'; +import {getTabVirtualMemoryType} from "../../../../database/sql/Memory.sql"; @element('tabpane-virtualmemory-event') export class TabPaneVirtualMemoryEvents 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 943c7961f4ded9749cf10fc87be2658172150ca4..b2331a8ee0c47c9003f293d754fec79e7827e08b 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatistics.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatistics.ts @@ -16,12 +16,12 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabPaneVirtualMemoryStatisticsData } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { LitProgressBar } from '../../../../../base-ui/progress-bar/LitProgressBar'; import { TabPaneFilter } from '../TabPaneFilter'; import '../TabPaneFilter'; import { VM_TYPE_MAP } from '../../../../database/logic-worker/ProcedureLogicWorkerFileSystem'; +import {getTabPaneVirtualMemoryStatisticsData} from "../../../../database/sql/Memory.sql"; @element('tabpane-virtual-memory-statistics') export class TabPaneVirtualMemoryStatistics extends BaseElement { @@ -134,41 +134,8 @@ export class TabPaneVirtualMemoryStatistics extends BaseElement { children: [], }; result.forEach((item, idx) => { - if (vmMemoryStatChildMap.has(item[firstLevel] + '_' + item[secondLevel])) { - let vmMemoryStatChildObj = vmMemoryStatChildMap.get(item[firstLevel] + '_' + item[secondLevel]); - vmMemoryStatChildObj.count += item.count; - vmMemoryStatChildObj.allDuration += item.allDuration; - vmMemoryStatChildObj.minDuration = - vmMemoryStatChildObj.minDuration <= item.minDuration ? vmMemoryStatChildObj.minDuration : item.minDuration; - vmMemoryStatChildObj.maxDuration = - vmMemoryStatChildObj.maxDuration >= item.maxDuration ? vmMemoryStatChildObj.maxDuration : item.maxDuration; - vmMemoryStatChildObj.children.push( - this.getInitData(item, firstLevel == 'type' ? 'tname' : 'type', firstLevel == 'type' ? 'tid' : null) - ); - } else { - vmMemoryStatChildMap.set(item[firstLevel] + '_' + item[secondLevel], { - ...item, - children: [ - this.getInitData(item, firstLevel == 'type' ? 'tname' : 'type', firstLevel == 'type' ? 'tid' : null), - ], - }); - } - - if (vmMemoryStatFatherMap.has(item[firstLevel])) { - let vmMemoryStatFatherObj = vmMemoryStatFatherMap.get(item[firstLevel]); - vmMemoryStatFatherObj.count += item.count; - vmMemoryStatFatherObj.allDuration += item.allDuration; - vmMemoryStatFatherObj.minDuration = - vmMemoryStatFatherObj.minDuration <= item.minDuration ? vmMemoryStatFatherObj.minDuration : item.minDuration; - vmMemoryStatFatherObj.maxDuration = - vmMemoryStatFatherObj.maxDuration >= item.maxDuration ? vmMemoryStatFatherObj.maxDuration : item.maxDuration; - vmMemoryStatFatherObj.children.push(this.getInitData(item)); - } else { - vmMemoryStatFatherMap.set(item[firstLevel], { - ...item, - children: [this.getInitData(item)], - }); - } + this.processChildMap(vmMemoryStatChildMap, item, firstLevel, secondLevel); + this.processFatherMap(vmMemoryStatFatherMap, item, firstLevel); if (idx == 0) { vmMemoryStatAllNode.minDuration = item.minDuration; } else { @@ -180,7 +147,20 @@ export class TabPaneVirtualMemoryStatistics extends BaseElement { vmMemoryStatAllNode.maxDuration = vmMemoryStatAllNode.maxDuration >= item.maxDuration ? vmMemoryStatAllNode.maxDuration : item.maxDuration; }); + this.handleFatherMap(vmMemoryStatFatherMap, firstLevel, vmMemoryStatChildMap, vmMemoryStatAllNode); + + vmMemoryStatAllNode.avgDuration = vmMemoryStatAllNode.allDuration / vmMemoryStatAllNode.count; + vmMemoryStatAllNode = this.getInitData(vmMemoryStatAllNode); + vmMemoryStatAllNode.title = 'All'; + vmMemoryStatAllNode.path = { type: null, tid: null, pid: null, value: 'All' }; + this.vmStatisticsSource = result.length > 0 ? [vmMemoryStatAllNode] : []; + let newSource = JSON.parse(JSON.stringify(this.vmStatisticsSource)); + if (this.vmStatisticsSortType != 0 && result.length > 0) + this.sortVmStatisticsTable(newSource[0], this.vmStatisticsSortKey); + this.vmStatisticsTbl!.recycleDataSource = newSource; + } + private handleFatherMap(vmMemoryStatFatherMap: Map, firstLevel: string, vmMemoryStatChildMap: Map, vmMemoryStatAllNode: any): void { for (let ks of vmMemoryStatFatherMap.keys()) { let sp = vmMemoryStatFatherMap.get(ks); sp!.children = []; @@ -193,48 +173,86 @@ export class TabPaneVirtualMemoryStatistics extends BaseElement { vmMemoryStatNode.path = { type: null, tid: null, pid: null, value: vmMemoryStatNode.title }; vmMemoryStatNode.path[firstLevel == 'type' ? 'type' : 'pid'] = vmMemoryStatNode[firstLevel == 'type' ? 'type' : 'pid']; - for (let kst of vmMemoryStatChildMap.keys()) { - if (kst.startsWith(ks + '_')) { - let spt = vmMemoryStatChildMap.get(kst); - let data = this.getInitData( - spt!, - firstLevel == 'type' ? 'pname' : 'tname', - firstLevel == 'type' ? 'pid' : 'tid' - ); - data.path = { - type: null, - tid: null, - pid: null, - value: 'All-' + vmMemoryStatNode.title + '-' + data.title, - }; - data.path[firstLevel == 'type' ? 'type' : 'pid'] = vmMemoryStatNode[firstLevel == 'type' ? 'type' : 'pid']; - data.path[firstLevel == 'type' ? 'pid' : 'tid'] = data[firstLevel == 'type' ? 'pid' : 'tid']; - data.children.forEach((e: any) => { - e.path = { - type: null, - tid: null, - pid: null, - value: 'All-' + vmMemoryStatNode.title + '-' + data.title + '-' + e.title, - }; - e.path[firstLevel == 'type' ? 'type' : 'pid'] = vmMemoryStatNode[firstLevel == 'type' ? 'type' : 'pid']; - e.path[firstLevel == 'type' ? 'pid' : 'tid'] = data[firstLevel == 'type' ? 'pid' : 'tid']; - e.path[firstLevel == 'type' ? 'tid' : 'type'] = e[firstLevel == 'type' ? 'tid' : 'type']; - }); - sp!.children.push(data); - } - } + this.handleChildMap(vmMemoryStatChildMap, ks, firstLevel, vmMemoryStatNode, sp); vmMemoryStatAllNode.children.push(vmMemoryStatNode); } + } - vmMemoryStatAllNode.avgDuration = vmMemoryStatAllNode.allDuration / vmMemoryStatAllNode.count; - vmMemoryStatAllNode = this.getInitData(vmMemoryStatAllNode); - vmMemoryStatAllNode.title = 'All'; - vmMemoryStatAllNode.path = { type: null, tid: null, pid: null, value: 'All' }; - this.vmStatisticsSource = result.length > 0 ? [vmMemoryStatAllNode] : []; - let newSource = JSON.parse(JSON.stringify(this.vmStatisticsSource)); - if (this.vmStatisticsSortType != 0 && result.length > 0) - this.sortVmStatisticsTable(newSource[0], this.vmStatisticsSortKey); - this.vmStatisticsTbl!.recycleDataSource = newSource; + private handleChildMap(vmMemoryStatChildMap: Map, ks: any, firstLevel: string, vmMemoryStatNode: any, sp: any): void { + for (let kst of vmMemoryStatChildMap.keys()) { + if (kst.startsWith(ks + '_')) { + let spt = vmMemoryStatChildMap.get(kst); + let data = this.getInitData( + spt!, + firstLevel == 'type' ? 'pname' : 'tname', + firstLevel == 'type' ? 'pid' : 'tid' + ); + this.handledata(data, vmMemoryStatNode, firstLevel); + sp!.children.push(data); + } + } + } + + private handledata(data: any, vmMemoryStatNode: any, firstLevel: string): void { + data.path = { + type: null, + tid: null, + pid: null, + value: 'All-' + vmMemoryStatNode.title + '-' + data.title, + }; + data.path[firstLevel == 'type' ? 'type' : 'pid'] = vmMemoryStatNode[firstLevel == 'type' ? 'type' : 'pid']; + data.path[firstLevel == 'type' ? 'pid' : 'tid'] = data[firstLevel == 'type' ? 'pid' : 'tid']; + data.children.forEach((e: any) => { + e.path = { + type: null, + tid: null, + pid: null, + value: 'All-' + vmMemoryStatNode.title + '-' + data.title + '-' + e.title, + }; + e.path[firstLevel == 'type' ? 'type' : 'pid'] = vmMemoryStatNode[firstLevel == 'type' ? 'type' : 'pid']; + e.path[firstLevel == 'type' ? 'pid' : 'tid'] = data[firstLevel == 'type' ? 'pid' : 'tid']; + e.path[firstLevel == 'type' ? 'tid' : 'type'] = e[firstLevel == 'type' ? 'tid' : 'type']; + }); + } + + private processFatherMap(vmMemoryStatFatherMap: Map, item: any, firstLevel: string): void { + if (vmMemoryStatFatherMap.has(item[firstLevel])) { + let vmMemoryStatFatherObj = vmMemoryStatFatherMap.get(item[firstLevel]); + vmMemoryStatFatherObj.count += item.count; + vmMemoryStatFatherObj.allDuration += item.allDuration; + vmMemoryStatFatherObj.minDuration = + vmMemoryStatFatherObj.minDuration <= item.minDuration ? vmMemoryStatFatherObj.minDuration : item.minDuration; + vmMemoryStatFatherObj.maxDuration = + vmMemoryStatFatherObj.maxDuration >= item.maxDuration ? vmMemoryStatFatherObj.maxDuration : item.maxDuration; + vmMemoryStatFatherObj.children.push(this.getInitData(item)); + } else { + vmMemoryStatFatherMap.set(item[firstLevel], { + ...item, + children: [this.getInitData(item)], + }); + } + } + + private processChildMap(vmMemoryStatChildMap: Map, item: any, firstLevel: string, secondLevel: string): void { + if (vmMemoryStatChildMap.has(item[firstLevel] + '_' + item[secondLevel])) { + let vmMemoryStatChildObj = vmMemoryStatChildMap.get(item[firstLevel] + '_' + item[secondLevel]); + vmMemoryStatChildObj.count += item.count; + vmMemoryStatChildObj.allDuration += item.allDuration; + vmMemoryStatChildObj.minDuration = + vmMemoryStatChildObj.minDuration <= item.minDuration ? vmMemoryStatChildObj.minDuration : item.minDuration; + vmMemoryStatChildObj.maxDuration = + vmMemoryStatChildObj.maxDuration >= item.maxDuration ? vmMemoryStatChildObj.maxDuration : item.maxDuration; + vmMemoryStatChildObj.children.push( + this.getInitData(item, firstLevel == 'type' ? 'tname' : 'type', firstLevel == 'type' ? 'tid' : null) + ); + } else { + vmMemoryStatChildMap.set(item[firstLevel] + '_' + item[secondLevel], { + ...item, + children: [ + this.getInitData(item, firstLevel == 'type' ? 'tname' : 'type', firstLevel == 'type' ? 'tid' : null), + ], + }); + } } sortVmStatisticsTable(allNode: any, key: string) { diff --git a/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.ts b/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.ts index 537db893ad4e326f1d6f8403f1f1907e7f8796bb..77838e9df781bfe1f4d12e162464309fd58f7798 100644 --- a/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.ts +++ b/ide/src/trace/component/trace/sheet/file-system/TabPaneVirtualMemoryStatisticsAnalysis.ts @@ -129,70 +129,15 @@ export class TabPaneVirtualMemoryStatisticsAnalysis extends BaseElement { this.checkBoxs = popover!.querySelectorAll('.check-wrap > lit-check-box'); this.vmTableArray = this.shadowRoot!.querySelectorAll('lit-table') as NodeListOf; for (let vmTable of this.vmTableArray) { - vmTable!.addEventListener('column-click', (evt) => { - // @ts-ignore - this.vmSortColumn = evt.detail.key; - // @ts-ignore - this.vmSortType = evt.detail.sort; - this.sortByColumn(); - }); + this.columnClickEvent(vmTable); vmTable!.addEventListener('contextmenu', function (event) { event.preventDefault(); // 阻止默认的上下文菜单弹框 }); - vmTable!.addEventListener('row-hover', (evt) => { - // @ts-ignore - let detail = evt.detail; - if (detail.data) { - let tableData = detail.data; - tableData.isHover = true; - if (detail.callBack) { - detail.callBack(true); - } - } - this.vmPieChart?.showHover(); - this.vmPieChart?.hideTip(); - }); - vmTable!.addEventListener('row-click', (evt) => { - // @ts-ignore - let detail = evt.detail; - if (detail.button === 2) { - let vmTab = this.parentElement?.parentElement?.querySelector( - '#box-vm-calltree > tabpane-vm-calltree' - ); - vmTab!.cWidth = this.clientWidth; - vmTab!.currentCallTreeLevel = this.currentLevel; - if (this.hideProcessCheckBox?.checked) { - detail.data.pid = undefined; - } - if (this.hideThreadCheckBox?.checked) { - detail.data.tid = undefined; - } - vmTab!.rowClickData = detail.data; - let title = ''; - if (this.titleEl?.textContent === '') { - title = detail.data.tableName; - } else { - title = this.titleEl?.textContent + ' / ' + detail.data.tableName; - } - vmTab!.pieTitle = title; - // 是否是在表格上右键点击跳转到火焰图的 - this.vmCurrentSelection!.isRowClick = true; - vmTab!.data = this.vmCurrentSelection; - } - }); + this.rowHoverEvent(vmTable); + this.rowClickEvent(vmTable); } for (let box of this.checkBoxs) { - box!.addEventListener('change', (event) => { - if (this.hideProcessCheckBox!.checked && this.hideThreadCheckBox!.checked) { - this.hideThread(); - this.vmBack!.style.visibility = 'hidden'; - } else if (this.hideProcessCheckBox!.checked && !this.hideThreadCheckBox!.checked) { - this.hideProcess(); - } else { - this.reset(this.vmStatisticsAnalysisTableProcess!, false); - this.getVirtualMemoryProcess(this.vmStatisticsAnalysisProcessData); - } - }); + this.checkBoxEvent(box); } const addRowClickEventListener = (vmTable: LitTable, clickEvent: Function) => { vmTable.addEventListener('row-click', (evt) => { @@ -210,6 +155,77 @@ export class TabPaneVirtualMemoryStatisticsAnalysis extends BaseElement { addRowClickEventListener(this.vmStatisticsAnalysisTableSo!, this.vmSoLevelClickEvent.bind(this)); } + private columnClickEvent(vmTable: LitTable): void { + vmTable!.addEventListener('column-click', (evt) => { + // @ts-ignore + this.vmSortColumn = evt.detail.key; + // @ts-ignore + this.vmSortType = evt.detail.sort; + this.sortByColumn(); + }); + } + + private checkBoxEvent(box: LitCheckBox): void { + box!.addEventListener('change', (event) => { + if (this.hideProcessCheckBox!.checked && this.hideThreadCheckBox!.checked) { + this.hideThread(); + this.vmBack!.style.visibility = 'hidden'; + } else if (this.hideProcessCheckBox!.checked && !this.hideThreadCheckBox!.checked) { + this.hideProcess(); + } else { + this.reset(this.vmStatisticsAnalysisTableProcess!, false); + this.getVirtualMemoryProcess(this.vmStatisticsAnalysisProcessData); + } + }); + } + + private rowClickEvent(vmTable: LitTable) { + vmTable!.addEventListener('row-click', (evt) => { + // @ts-ignore + let detail = evt.detail; + if (detail.button === 2) { + let vmTab = this.parentElement?.parentElement?.querySelector( + '#box-vm-calltree > tabpane-vm-calltree' + ); + vmTab!.cWidth = this.clientWidth; + vmTab!.currentCallTreeLevel = this.currentLevel; + if (this.hideProcessCheckBox?.checked) { + detail.data.pid = undefined; + } + if (this.hideThreadCheckBox?.checked) { + detail.data.tid = undefined; + } + vmTab!.rowClickData = detail.data; + let title = ''; + if (this.titleEl?.textContent === '') { + title = detail.data.tableName; + } else { + title = this.titleEl?.textContent + ' / ' + detail.data.tableName; + } + vmTab!.pieTitle = title; + // 是否是在表格上右键点击跳转到火焰图的 + this.vmCurrentSelection!.isRowClick = true; + vmTab!.data = this.vmCurrentSelection; + } + }); + } + + private rowHoverEvent(vmTable: LitTable): void { + vmTable!.addEventListener('row-hover', (evt) => { + // @ts-ignore + let detail = evt.detail; + if (detail.data) { + let tableData = detail.data; + tableData.isHover = true; + if (detail.callBack) { + detail.callBack(true); + } + } + this.vmPieChart?.showHover(); + this.vmPieChart?.hideTip(); + }); + } + private reset(showTable: LitTable, isShowBack: boolean): void { this.clearData(); if (isShowBack) { diff --git a/ide/src/trace/component/trace/sheet/fps/TabPaneFps.ts b/ide/src/trace/component/trace/sheet/fps/TabPaneFps.ts index c20ea92c015b4d1f065683835233f02dff20287d..59af7ad2ac6ccb52792fe389fb3ba3ef89fad202 100644 --- a/ide/src/trace/component/trace/sheet/fps/TabPaneFps.ts +++ b/ide/src/trace/component/trace/sheet/fps/TabPaneFps.ts @@ -16,10 +16,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabFps } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { log } from '../../../../../log/Log'; import { resizeObserver } from '../SheetUtils'; +import {getTabFps} from "../../../../database/sql/SqlLite.sql"; @element('tabpane-fps') export class TabPaneFps extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/freq/TabPaneCpuFreqLimits.ts b/ide/src/trace/component/trace/sheet/freq/TabPaneCpuFreqLimits.ts index 435a664f9c0b35966cd1e4c5e4c1a0fa2fd4773f..fbd6ebd0e264caf0e4a339fde120b45d38b0be8f 100644 --- a/ide/src/trace/component/trace/sheet/freq/TabPaneCpuFreqLimits.ts +++ b/ide/src/trace/component/trace/sheet/freq/TabPaneCpuFreqLimits.ts @@ -18,9 +18,9 @@ import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; import { Utils } from '../../base/Utils'; import { ColorUtils } from '../../base/ColorUtils'; -import { CpuFreqLimitsStruct } from '../../../../database/ui-worker/ProcedureWorkerCpuFreqLimits'; +import { CpuFreqLimitsStruct } from '../../../../database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits'; import { resizeObserver } from '../SheetUtils'; -import { getCpuLimitFreqBoxSelect } from '../../../../database/SqlLite'; +import {getCpuLimitFreqBoxSelect} from "../../../../database/sql/Cpu.sql"; @element('tabpane-cpu-freq-limits') export class TabPaneCpuFreqLimits extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqDataCut.ts b/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqDataCut.ts index 24f4c4bf1280756abfdc21cd812946feb7f9379b..35827ad2750227e741a2b96df6d5275145e2d62a 100644 --- a/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqDataCut.ts +++ b/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqDataCut.ts @@ -14,904 +14,1267 @@ */ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable, RedrawTreeForm } from '../../../../../base-ui/table/lit-table'; -import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; -import '../../../StackBar' -import { getTabRunningPercent, queryCpuFreqUsageData, queryCpuFreqFilterId, querySearchFuncData } from '../../../../database/SqlLite'; +import { SelectionParam } from '../../../../bean/BoxSelection'; +import '../../../StackBar'; +import { getTabRunningPercent } from '../../../../database/sql/ProcessThread.sql'; +import { queryCpuFreqUsageData, queryCpuFreqFilterId } from '../../../../database/sql/Cpu.sql'; +import { querySearchFuncData } from '../../../../database/sql/Func.sql'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; -import { SliceGroup } from '../../../../bean/StateProcessThread'; -import { SpSegmentationChart } from "../../../chart/SpSegmentationChart"; -import { TabPaneFreqUsageConfig, TabPaneRunningConfig, TabPaneCpuFreqConfig } from "./TabPaneFreqUsageConfig"; import { LitChartScatter } from '../../../../../base-ui/chart/scatter/LitChartScatter'; +import { SpSegmentationChart } from '../../../chart/SpSegmentationChart'; +import { TabPaneFreqUsageConfig, type TabPaneRunningConfig, TabPaneCpuFreqConfig} from './TabPaneFreqUsageConfig'; @element('tabpane-freqdatacut') export class TabPaneFreqDataCut extends BaseElement { - private threadStatesTbl: LitTable | null | undefined; - private threadStatesTblSource: Array = []; - private currentSelectionParam: SelectionParam | any; - private threadStatesDIV: HTMLDivElement | null | undefined; - private scatterInput: HTMLInputElement | null | undefined; - private initData: Map> = new Map(); - private processArr: Array = []; - private threadArr: Array = []; - private statisticsScatter: LitChartScatter | null | undefined; + private threadStatesTbl: LitTable | null | undefined; + private threadStatesTblSource: Array = []; + private currentSelectionParam: SelectionParam | any; + private threadStatesDIV: HTMLDivElement | null | undefined; + private scatterInput: HTMLInputElement | null | undefined; + private initData: Map> = new Map(); + private processArr: Array = []; + private threadArr: Array = []; + private statisticsScatter: LitChartScatter | null | undefined; - set data(threadStatesParam: SelectionParam | any) { - if (this.currentSelectionParam === threadStatesParam) { - return; - } - this.currentSelectionParam = threadStatesParam; - this.initData = new Map(); - this.threadArr = []; - this.initUI(); - this.init(threadStatesParam); - let pidArr: Array = []; - // 整理进程级的数组信息 - let processArr: Array = threadStatesParam.processIds.length > 1 ? [...new Set(threadStatesParam.processIds)] : threadStatesParam.processIds; - for (let i of processArr) { - pidArr.push(new TabPaneFreqUsageConfig(Utils.PROCESS_MAP.get(i) === null ? 'Process ' + i : Utils.PROCESS_MAP.get(i) + ' ' + i, '', i, '', 0, '', '', 0, '', 0, 'process', -1, [])); - } - // 拷贝给私有属性,以便后续进行数据切割时免除整理进程层级数据 - this.processArr = pidArr; + set data(threadStatesParam: SelectionParam) { + if (this.currentSelectionParam === threadStatesParam) { + return; } - /** - * 初始化数据 - */ - async init(threadStatesParam: SelectionParam | any): Promise { - let [runningData, sum]: Array = await this.queryRunningData(threadStatesParam); - let cpuFreqData: Array = await this.queryCpuFreqData(threadStatesParam); - if (runningData.size > 0) { - // 将cpu频点数据与running状态数据整合,保证其上该段时长内有对应的cpu频点数据 - this.mergeFreqData(runningData, cpuFreqData, sum); - this.threadStatesTbl!.loading = false; - } else { - this.threadStatesTblSource = []; - this.threadStatesTbl!.recycleDataSource = []; - this.threadStatesTbl!.loading = false; - } + this.currentSelectionParam = threadStatesParam; + this.initData = new Map(); + this.threadArr = []; + this.initUI(); + this.init(threadStatesParam); + let pidArr: Array = []; + // 整理进程级的数组信息 + let processArr: Array = + threadStatesParam.processIds.length > 1 + ? [...new Set(threadStatesParam.processIds)] + : threadStatesParam.processIds; + for (let i of processArr) { + pidArr.push( + new TabPaneFreqUsageConfig( + Utils.PROCESS_MAP.get(i) === null ? 'Process ' + i : Utils.PROCESS_MAP.get(i) + ' ' + i, + '', i, '', 0, '', '', 0, '', 0, 'process', -1, []) + ); } - /** - * 重置UI输入框等组件为默认状态 - */ - initUI(): void { - this.threadStatesTblSource = []; - this.threadStatesTbl!.recycleDataSource = []; - this.threadStatesTbl!.loading = true; - let tableValue: any = this.threadStatesTbl; - tableValue.value = []; - let divRoot1: any = this.shadowRoot?.querySelector('#dataCutThreadId'); - divRoot1.value = ''; - divRoot1.style.border = '1px solid rgb(151,151,151)'; - let divRoot2: any = this.shadowRoot?.querySelector('#dataCutThreadFunc'); - divRoot2.value = ''; - divRoot2.style.border = '1px solid rgb(151,151,151)'; - let divRoot3: any = this.shadowRoot?.querySelector('#maxFreq'); - divRoot3.style.border = '1px solid rgb(151,151,151)'; - let divRoot4: any = this.shadowRoot?.querySelector('#maxHz'); - divRoot4.style.border = '1px solid rgb(151,151,151)'; - let divRoot5: any = this.shadowRoot?.querySelector('#cycle-a-start-range'); - divRoot5.value = '' - let divRoot6: any = this.shadowRoot?.querySelector('#cycle-a-end-range'); - divRoot6.value = ''; - let divRoot7: any = this.shadowRoot?.querySelector('#cycle-b-start-range'); - divRoot7.value = ''; - let divRoot8: any = this.shadowRoot?.querySelector('#cycle-b-end-range'); - divRoot8.value = ''; - // @ts-ignore - this.shadowRoot?.querySelector('#cycleQuery')!.style.display = 'none'; - // @ts-ignore - this.statisticsScatter!.config = undefined; + // 拷贝给私有属性,以便后续进行数据切割时免除整理进程层级数据 + this.processArr = pidArr; + } + /** + * 初始化数据 + */ + async init(threadStatesParam: SelectionParam): Promise { + let {runningMap, sum}: { + runningMap: Map>, + sum: number + } + = await this.queryRunningData(threadStatesParam); + let cpuFreqData: Array = await this.queryCpuFreqData( + threadStatesParam + ); + if (runningMap.size > 0) { + // 将cpu频点数据与running状态数据整合,保证其上该段时长内有对应的cpu频点数据 + this.mergeFreqData(runningMap, cpuFreqData, sum); + this.threadStatesTbl!.loading = false; + } else { + this.threadStatesTblSource = []; + this.threadStatesTbl!.recycleDataSource = []; + this.threadStatesTbl!.loading = false; } - /** - * 查询cpu频点信息 - */ - async queryCpuFreqData(threadStatesParam: SelectionParam | any): Promise> { - // 查询cpu及id信息 - let result: Array = await queryCpuFreqFilterId(); - // 以键值对形式将cpu及id进行对应,后续会将频点数据与其对应cpu进行整合 - let IdMap: Map = new Map(); - let queryId: Array = []; - for (let i = 0; i < result.length; i++) { - queryId.push(result[i].id); - IdMap.set(result[i].id, result[i].cpu); - } - let dealArr: Array = []; - // 通过id去查询频点数据 - let res: Array = await queryCpuFreqUsageData(queryId); - for (let i of res) { - let obj = new TabPaneCpuFreqConfig(i.startNS + threadStatesParam.recordStartNs, IdMap.get(i.filter_id)!, i.value, i.dur) - dealArr.push(obj); - } - return dealArr; + } + /** + * 重置UI输入框等组件为默认状态 + */ + initUI(): void { + this.threadStatesTblSource = []; + this.threadStatesTbl!.recycleDataSource = []; + this.threadStatesTbl!.loading = true; + // @ts-ignore + this.threadStatesTbl.value = []; + // @ts-ignore + this.shadowRoot?.querySelector('#dataCutThreadId').style.border = '1px solid rgb(151,151,151)'; + // @ts-ignore + this.shadowRoot?.querySelector('#dataCutThreadFunc').style.border = '1px solid rgb(151,151,151)'; + // @ts-ignore + this.shadowRoot?.querySelector('#maxFreq').style.border = '1px solid rgb(151,151,151)'; + // @ts-ignore + this.shadowRoot?.querySelector('#maxHz').style.border = '1px solid rgb(151,151,151)'; + // @ts-ignore + this.shadowRoot?.querySelector('#cycle-a-start-range').value = ''; + // @ts-ignore + this.shadowRoot?.querySelector('#cycle-a-end-range').value = ''; + // @ts-ignore + this.shadowRoot?.querySelector('#cycle-b-start-range').value = ''; + // @ts-ignore + this.shadowRoot?.querySelector('#cycle-b-end-range').value = ''; + // @ts-ignore + this.shadowRoot?.querySelector('#cycleQuery')!.style.display = 'none'; + // @ts-ignore + this.statisticsScatter!.config = undefined; + this.parentElement!.style.overflow = 'hidden'; + } + /** + * 查询cpu频点信息 + */ + async queryCpuFreqData(threadStatesParam: SelectionParam): Promise> { + // 查询cpu及id信息 + let result: Array<{ id: number; cpu: number }> = await queryCpuFreqFilterId(); + // 以键值对形式将cpu及id进行对应,后续会将频点数据与其对应cpu进行整合 + let idMap: Map = new Map(); + let queryId: Array = []; + for (let i = 0; i < result.length; i++) { + queryId.push(result[i].id); + idMap.set(result[i].id, result[i].cpu); } + let dealArr: Array = []; + // 通过id去查询频点数据 + let res: Array<{ + startNS: number; + filter_id: number; + value: number; + dur: number} + > = await queryCpuFreqUsageData(queryId); + for (let i of res) { + dealArr.push( + new TabPaneCpuFreqConfig( + i.startNS + threadStatesParam.recordStartNs, + idMap.get(i.filter_id)!, + i.value, + i.dur + )); + } + return dealArr; + } - /** - * 查询框选区域内的所有running状态数据 - */ - async queryRunningData(threadStatesParam: SelectionParam | any): Promise> { - let result: Array = await getTabRunningPercent(threadStatesParam.threadIds, threadStatesParam.leftNs, threadStatesParam.rightNs); - let needDeal: Map> = new Map(), sum: number = 0; - if (result != null && result.length > 0) { - let processArr: Array = threadStatesParam.processIds.length > 1 ? [...new Set(threadStatesParam.processIds)] : threadStatesParam.processIds; - for (let e of result) { - if (processArr.includes(e.pid)) { - if (needDeal.get(e.pid + '_' + e.tid) === undefined) { - this.threadArr.push(new TabPaneFreqUsageConfig(Utils.THREAD_MAP.get(e.tid) + ' ' + e.tid, '', e.pid, e.tid, 0, '', '', 0, '', 0, 'thread', -1, [])); - needDeal.set(e.pid + '_' + e.tid, new Array()); - } - if ((e.ts < (threadStatesParam.leftNs + threadStatesParam.recordStartNs)) && ((e.ts + e.dur) > (threadStatesParam.leftNs + threadStatesParam.recordStartNs))) { - const ts = e.ts; - e.ts = threadStatesParam.leftNs + threadStatesParam.recordStartNs; - e.dur = ts + e.dur - (threadStatesParam.leftNs + threadStatesParam.recordStartNs); - } - if ((e.ts + e.dur) > (threadStatesParam.rightNs + threadStatesParam.recordStartNs)) { - e.dur = threadStatesParam.rightNs + threadStatesParam.recordStartNs - e.ts; - } - let process = Utils.PROCESS_MAP.get(e.pid); - let thread = Utils.THREAD_MAP.get(e.tid); - e.process = process == null || process.length == 0 ? '[NULL]' : process; - e.thread = thread == null || thread.length == 0 ? '[NULL]' : thread; - let arr: any = needDeal.get(e.pid + '_' + e.tid); - sum += e.dur; - arr.push(e); - } - } + /** + * 查询框选区域内的所有running状态数据 + */ + async queryRunningData(threadStatesParam: SelectionParam): + Promise<{runningMap: Map>; sum: number}> { + let result: Array + = await getTabRunningPercent(threadStatesParam.threadIds, threadStatesParam.leftNs, threadStatesParam.rightNs); + let needDeal: Map> = new Map(); + let sum: number = 0; + if (result !== null && result.length > 0) { + let processArr: Array = threadStatesParam.processIds.length > 1 + ? [...new Set(threadStatesParam.processIds)] : threadStatesParam.processIds; + for (let e of result) { + if (processArr.includes(e.pid)) { + if (needDeal.get(e.pid + '_' + e.tid) === undefined) { + this.threadArr.push( + new TabPaneFreqUsageConfig(Utils.THREAD_MAP.get(e.tid) + ' ' + e.tid, + '', e.pid, e.tid, 0, '', '', 0, '', 0, 'thread', -1, []) + ); + needDeal.set(e.pid + '_' + e.tid, new Array()); + } + if (e.ts < threadStatesParam.leftNs + threadStatesParam.recordStartNs && + e.ts + e.dur > threadStatesParam.leftNs + threadStatesParam.recordStartNs) { + const ts = e.ts; + e.ts = threadStatesParam.leftNs + threadStatesParam.recordStartNs; + e.dur = ts + e.dur - (threadStatesParam.leftNs + threadStatesParam.recordStartNs); + } + if (e.ts + e.dur > threadStatesParam.rightNs + threadStatesParam.recordStartNs) { + e.dur = threadStatesParam.rightNs + threadStatesParam.recordStartNs - e.ts; + } + e.process = Utils.PROCESS_MAP.get(e.pid) === null ? '[NULL]' : Utils.PROCESS_MAP.get(e.pid)!; + e.thread = Utils.THREAD_MAP.get(e.tid) === null ? '[NULL]' : Utils.THREAD_MAP.get(e.tid)!; + let arr: Array | undefined = needDeal.get(e.pid + '_' + e.tid); + sum += e.dur; + arr?.push(e); } - return [needDeal, sum]; + } } + return {'runningMap': needDeal, 'sum': sum}; + } - /** - * 将cpu频点数据与running状态数据整合,保证其上该段时长内有对应的cpu频点数据 - */ - mergeFreqData(needDeal: Map>, dealArr: Array, sum: number): void { - needDeal.forEach((value: Array, key: string) => { - let resultList: Array = []; - for (let i = 0; i < value.length; i++) { - for (let j = 0; j < dealArr.length; j++) { - // 只需要判断running状态数据与频点数据cpu相同的情况 - if (value[i].cpu === dealArr[j].cpu) { - // running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running状态数据的持续时间小于频点结束时间减去running状态数据开始时间的情况 - if (value[i].ts > dealArr[j].startNS && value[i].ts < (dealArr[j].startNS + dealArr[j].dur) && value[i].dur < (dealArr[j].startNS + dealArr[j].dur - value[i].ts)) { - resultList.push(new TabPaneFreqUsageConfig(value[i].thread, value[i].ts, value[i].pid, value[i].tid, 0, value[i].cpu, dealArr[j].value, value[i].dur, '', value[i].dur / sum * 100, 'freqdata', -1, undefined)); - break; - } - // running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running状态数据的持续时间大于频点结束时间减去running状态数据开始时间的情况 - if (value[i].ts > dealArr[j].startNS && value[i].ts < (dealArr[j].startNS + dealArr[j].dur) && value[i].dur > (dealArr[j].startNS + dealArr[j].dur - value[i].ts)) { - resultList.push(new TabPaneFreqUsageConfig(value[i].thread, value[i].ts, value[i].pid, value[i].tid, 0, value[i].cpu, dealArr[j].value, (dealArr[j].startNS + dealArr[j].dur - value[i].ts), '', (dealArr[j].startNS + dealArr[j].dur - value[i].ts) / sum * 100, 'freqdata', -1, undefined)); - } - // running状态数据的开始时间小于频点数据开始时间,running状态数据的结束时间大于频点数据开始时间。且running状态数据在频点数据开始时间后的持续时间小于频点数据持续时间的情况 - if (value[i].ts < dealArr[j].startNS && (value[i].ts + value[i].dur) > dealArr[j].startNS && (value[i].dur + value[i].ts - dealArr[j].startNS) < dealArr[j].dur) { - resultList.push(new TabPaneFreqUsageConfig(value[i].thread, dealArr[j].startNS, value[i].pid, value[i].tid, 0, value[i].cpu, dealArr[j].value, (value[i].dur + value[i].ts - dealArr[j].startNS), '', (value[i].dur + value[i].ts - dealArr[j].startNS) / sum * 100, 'freqdata', -1, undefined)); - break; - } - // running状态数据的开始时间小于频点数据开始时间,running状态数据的结束时间大于频点数据开始时间。且running状态数据在频点数据开始时间后的持续时间大于频点数据持续时间的情况 - if (value[i].ts < dealArr[j].startNS && (value[i].ts + value[i].dur) > dealArr[j].startNS && (value[i].dur + value[i].ts - dealArr[j].startNS) > dealArr[j].dur) { - resultList.push(new TabPaneFreqUsageConfig(value[i].thread, dealArr[j].startNS, value[i].pid, value[i].tid, 0, value[i].cpu, dealArr[j].value, dealArr[j].dur, '', dealArr[j].dur / sum * 100, 'freqdata', -1, undefined)); - } - // running状态数据的开始时间小于频点数据开始时间,running状态数据的持续时间小于频点数据开始时间的情况 - if (value[i].ts < dealArr[j].startNS && (value[i].ts + value[i].dur) < dealArr[j].startNS) { - resultList.push(new TabPaneFreqUsageConfig(value[i].thread, value[i].ts, value[i].pid, value[i].tid, 0, value[i].cpu, 'unknown', value[i].dur, '', value[i].dur / sum * 100, 'freqdata', -1, undefined)); - break; - } - } - } + /** + * 将cpu频点数据与running状态数据整合,保证其上该段时长内有对应的cpu频点数据 + */ + mergeFreqData( + needDeal: Map>, + dealArr: Array, + sum: number + ): void { + needDeal.forEach((value: Array, key: string) => { + let resultList: Array = []; + for (let i = 0; i < value.length; i++) { + for (let j = 0; j < dealArr.length; j++) { + // 只需要判断running状态数据与频点数据cpu相同的情况 + if (value[i].cpu === dealArr[j].cpu) { + // running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running状态数据的持续时间小于频点结束时间减去running状态数据开始时间的情况 + if (value[i].ts > dealArr[j].startNS && + value[i].ts < dealArr[j].startNS + dealArr[j].dur && + value[i].dur < dealArr[j].startNS + dealArr[j].dur - value[i].ts) { + resultList.push(new TabPaneFreqUsageConfig(value[i].thread, value[i].ts, value[i].pid, + value[i].tid, 0, value[i].cpu,dealArr[j].value, value[i].dur, '', (value[i].dur / sum) * 100, + 'freqdata', -1, undefined)); + break; } - this.initData.set(key, resultList); - }) - } - /** - * single方式切割数据功能 - */ - dataSingleCut(threadId: HTMLInputElement, threadFunc: HTMLInputElement, resultList: Map>): void { - threadId.style.border = '1px solid rgb(151,151,151)'; - threadFunc.style.border = '1px solid rgb(151,151,151)'; - let threadIdValue = threadId.value.trim(); - let threadFuncName = threadFunc.value.trim(); - let leftNS = this.currentSelectionParam.leftNs; - let rightNS = this.currentSelectionParam.rightNs; - let tableValue: any = this.threadStatesTbl; - tableValue.value = []; - if (threadIdValue != '' && threadFuncName != '') { - // 根据用户输入的线程ID,方法名去查询数据库,得到对应的方法起始时间,持续时间等数据,以便作为依据进行后续数据切割 - querySearchFuncData(threadFuncName, Number(threadIdValue), leftNS, rightNS).then(result => { - if (result != null && result.length > 0) { - // targetMap为全局initData的拷贝对象,dealArr数组用来存放周期切割依据数据 - let targetMap: Map> = new Map(), dealArr: Array = []; - // 新创建map对象接收传过来的实参map - resultList.forEach((item: Array, key: string) => { - targetMap.set(key, JSON.parse(JSON.stringify(item))); - }) - // 整理周期切割依据的数据 - for (let i of result) { - if (i.startTime + this.currentSelectionParam.recordStartNs + i.dur < this.currentSelectionParam.rightNs + this.currentSelectionParam.recordStartNs) { - dealArr.push({ 'ts': i.startTime + this.currentSelectionParam.recordStartNs, 'dur': i.dur }); - } - } - let cycleMap: Map> = new Map(), totalList: Map> = new Map(); - this.mergeSingleData(dealArr, targetMap, cycleMap, totalList); - // 拷贝线程数组,防止数据污染 - let threadArr = JSON.parse(JSON.stringify(this.threadArr)); - // 拷贝进程数组,防止数据污染 - let processArr = JSON.parse(JSON.stringify(this.processArr)); - // 将周期层级防止到线程层级下 - this.mergeThreadData(threadArr, cycleMap); - // 将原始数据放置到对应的线程层级下,周期数据前 - let totalData = this.merge(totalList); - this.mergeTotalData(threadArr, totalData); - // 合并数据到进程层级下 - this.mergePidData(processArr, threadArr); - this.fixedDeal(processArr); - this.threadStatesTblSource = processArr; - this.threadStatesTbl!.recycleDataSource = processArr; - this.threadStatesTbl!.loading = false; - this.threadClick(processArr); - } else { - this.threadStatesTblSource = []; - this.threadStatesTbl!.recycleDataSource = []; - this.threadStatesTbl!.loading = false; - } - }) - } else { - this.threadStatesTbl!.loading = false; - if (threadIdValue == '') { - threadId.style.border = '2px solid rgb(255,0,0)'; + // running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running状态数据的持续时间大于频点结束时间减去running状态数据开始时间的情况 + if (value[i].ts > dealArr[j].startNS && + value[i].ts < dealArr[j].startNS + dealArr[j].dur && + value[i].dur > dealArr[j].startNS + dealArr[j].dur - value[i].ts) { + resultList.push(new TabPaneFreqUsageConfig(value[i].thread, value[i].ts, value[i].pid, + value[i].tid, 0, value[i].cpu, dealArr[j].value, dealArr[j].startNS + dealArr[j].dur - value[i].ts, '', + ((dealArr[j].startNS + dealArr[j].dur - value[i].ts) / sum) * 100, 'freqdata', -1, undefined)); + } + // running状态数据的开始时间小于频点数据开始时间,running状态数据的结束时间大于频点数据开始时间。且running状态数据在频点数据开始时间后的持续时间小于频点数据持续时间的情况 + if (value[i].ts < dealArr[j].startNS && + value[i].ts + value[i].dur > dealArr[j].startNS && + value[i].dur + value[i].ts - dealArr[j].startNS < dealArr[j].dur) { + resultList.push(new TabPaneFreqUsageConfig(value[i].thread, dealArr[j].startNS, value[i].pid, + value[i].tid, 0, value[i].cpu, dealArr[j].value, value[i].dur + value[i].ts - dealArr[j].startNS, '', + ((value[i].dur + value[i].ts - dealArr[j].startNS) / sum) * 100, 'freqdata', -1, undefined )); + break; } - if (threadFuncName == '') { - threadFunc.style.border = '2px solid rgb(255,0,0)'; + // running状态数据的开始时间小于频点数据开始时间,running状态数据的结束时间大于频点数据开始时间。且running状态数据在频点数据开始时间后的持续时间大于频点数据持续时间的情况 + if (value[i].ts < dealArr[j].startNS && + value[i].ts + value[i].dur > dealArr[j].startNS && + value[i].dur + value[i].ts - dealArr[j].startNS > dealArr[j].dur) { + resultList.push(new TabPaneFreqUsageConfig( value[i].thread, dealArr[j].startNS, value[i].pid, value[i].tid, + 0, value[i].cpu, dealArr[j].value, dealArr[j].dur, '', (dealArr[j].dur / sum) * 100, 'freqdata', -1, undefined)); } + // running状态数据的开始时间小于频点数据开始时间,running状态数据的持续时间小于频点数据开始时间的情况 + if (value[i].ts < dealArr[j].startNS && value[i].ts + value[i].dur < dealArr[j].startNS) { + resultList.push(new TabPaneFreqUsageConfig(value[i].thread, value[i].ts, value[i].pid, value[i].tid, + 0, value[i].cpu, 'unknown', value[i].dur, '', (value[i].dur / sum) * 100, 'freqdata', -1, undefined)); + break; + } + } } + } + this.initData.set(key, resultList); + }); + } + /** + * single方式切割数据功能 + */ + dataSingleCut( + threadId: HTMLInputElement, + threadFunc: HTMLInputElement, + resultList: Map> + ): void { + let threadIdValue: string = threadId.value.trim(); + let threadFuncName: string = threadFunc.value.trim(); + let rightNS: number = this.currentSelectionParam.rightNs; + let recordStartNs: number = this.currentSelectionParam.recordStartNs; + // @ts-ignore + this.threadStatesTbl.value = []; + if (threadIdValue !== '' && threadFuncName !== '') { + // 根据用户输入的线程ID,方法名去查询数据库,得到对应的方法起始时间,持续时间等数据,以便作为依据进行后续数据切割 + querySearchFuncData(threadFuncName, Number(threadIdValue), this.currentSelectionParam.leftNs, rightNS).then((result) => { + if (result !== null && result.length > 0) { + // targetMap为全局initData的拷贝对象,dealArr数组用来存放周期切割依据数据 + let targetMap: Map> = new Map(); + let dealArr: Array<{ts: number, dur: number}> = []; + // 新创建map对象接收传过来的实参map + resultList.forEach((item: Array, key: string) => { + targetMap.set(key, JSON.parse(JSON.stringify(item))); + }); + // 整理周期切割依据的数据 + for (let i of result) { + if (i.startTime! + recordStartNs + i.dur! < rightNS + recordStartNs) { + dealArr.push({ts: i.startTime! + recordStartNs, dur: i.dur!}); + } + } + let cycleMap: Map> = new Map(); + let totalList: Map> = new Map(); + this.mergeSingleData(dealArr, targetMap, cycleMap, totalList); + // 拷贝线程数组,防止数据污染 + let threadArr: Array = JSON.parse(JSON.stringify(this.threadArr)); + // 拷贝进程数组,防止数据污染 + let processArr: Array = JSON.parse(JSON.stringify(this.processArr)); + // 将周期层级防止到线程层级下 + this.mergeThreadData(threadArr, cycleMap); + // 将原始数据放置到对应的线程层级下,周期数据前 + this.mergeTotalData(threadArr, this.merge(totalList)); + // 合并数据到进程层级下 + this.mergePidData(processArr, threadArr); + this.fixedDeal(processArr); + this.threadStatesTblSource = processArr; + this.threadStatesTbl!.recycleDataSource = processArr; + this.threadClick(processArr); + } else { + this.threadStatesTblSource = []; + this.threadStatesTbl!.recycleDataSource = []; + } + this.threadStatesTbl!.loading = false; + }); + } else { + this.threadStatesTbl!.loading = false; + if (threadIdValue === '') { + threadId.style.border = '2px solid rgb(255,0,0)'; + } + if (threadFuncName === '') { + threadFunc.style.border = '2px solid rgb(255,0,0)'; + } } - /** - * 整合Single切割方式中的频点数据与方法周期数据 - */ - mergeSingleData(dealArr: Array, targetMap: Map>, cycleMap: Map>, totalList: Map>): void { - let timeDur = this.currentSelectionParam.recordStartNs; - targetMap.forEach((value, key) => { - cycleMap.set(key, new Array()); - totalList.set(key, new Array()); - for (let i = 0; i < dealArr.length; i++) { - let cpuArr: Array = [], resList: Array = [], cpuMap: Map> = new Map(); - // 时间倍数值 - const countMutiple = 1000000; - cpuMap.set(key, new Array()); - cycleMap.get(key)?.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[0].thread, ((dealArr[i].ts - timeDur) / 1000000).toFixed(3), '', '', 0, '', '', 0, (dealArr[i].dur / 1000000).toFixed(3), 0, 'cycle', i + 1, [])); - for (let j = 0; j < value.length; j++) { - // 判断若用户导入json文件,则替换为对应cpu下的对应频点的算力值进行算力消耗计算 - let consumptionMap: Map | undefined ; - if (SpSegmentationChart.freqInfoMapData.size > 0 ) { - consumptionMap = SpSegmentationChart.freqInfoMapData.get(value[j].cpu); - } + } + /** + * 整合Single切割方式中的频点数据与方法周期数据 + */ + mergeSingleData( + dealArr: Array<{ts: number, dur: number}>, + targetMap: Map>, + cycleMap: Map>, + totalList: Map> + ): void { + let timeDur = this.currentSelectionParam.recordStartNs; + targetMap.forEach((value: any, key) => { + cycleMap.set(key, new Array()); + totalList.set(key, new Array()); + for (let i = 0; i < dealArr.length; i++) { + let cpuArr: Array = []; + let resList: Array = []; + let cpuMap: Map> = new Map(); + // 时间倍数值 + const countMutiple: number = 1000000; + const MIN_NUM: number = 3; + cpuMap.set(key, new Array()); + cycleMap.get(key)?.push( + new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[0].thread, + ((dealArr[i].ts - timeDur) / countMutiple).toFixed(MIN_NUM), key.split('_')[0], key.split('_')[1], + 0, '', '', 0, (dealArr[i].dur / countMutiple).toFixed(MIN_NUM), 0, 'cycle', i + 1, [] )); + this.dismantlingSingle( + value, + dealArr[i], + { + i: i, + key: key, + countMutiple: countMutiple, + cpuArr, + cpuMap + }, + resList, + totalList + ); + this.mergeData(resList); + // 整理排序相同周期下的数据 + this.mergeCpuData(cpuMap.get(key)!, resList); + // 将cpu数据放置到对应周期层级下 + this.mergeCycleData(cycleMap.get(key)![i], cpuMap.get(key)!); + } + }); + } - // 若存在算力值,则直接取值做计算。若不存在算力值,且频点值不为unknown的情况,则取频点值做计算,若为unknown,则取0做兼容 - const consumption = (consumptionMap && consumptionMap.get(value[j].freq)) ? consumptionMap.get(value[j].freq) : (value[j].freq == 'unknown' ? 0 : value[j].freq); - if (!cpuArr.includes(value[j].cpu)) { - cpuArr.push(value[j].cpu); - cpuMap.get(key)?.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, 0, value[j].cpu, '', 0, '', 0, 'cpu', -1, [])); - } - // 以下为频点数据按Single周期切割数据如何取舍的判断条件,dealArr为周期切割依据,value为某一线程下的频点汇总数据 - // 如果频点数据开始时间大于某一周期起始时间,小于该周期的结束时间。且频点数据结束时间小于周期结束时间的情况 - if (dealArr[i].ts < value[j].ts && dealArr[i].ts + dealArr[i].dur > value[j].ts && dealArr[i].ts + dealArr[i].dur > value[j].ts + value[j].dur) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (consumption * value[j].dur) / countMutiple, value[j].cpu, value[j].freq, value[j].dur, '', value[j].percent, 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (consumption * value[j].dur) / countMutiple, value[j].cpu, value[j].freq, value[j].dur, '', value[j].percent, 'freqdata', i, undefined)); - } - // 如果频点数据开始时间大于某一周期起始时间,小于该周期的结束时间。且频点数据结束时间大于等于周期结束时间的情况 - if (dealArr[i].ts < value[j].ts && dealArr[i].ts + dealArr[i].dur > value[j].ts && dealArr[i].ts + dealArr[i].dur <= value[j].ts + value[j].dur) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (dealArr[i].ts + dealArr[i].dur - value[j].ts) * consumption / countMutiple, value[j].cpu, value[j].freq, dealArr[i].ts + dealArr[i].dur - value[j].ts, '', (dealArr[i].ts + dealArr[i].dur - value[j].ts) / value[j].dur * value[j].percent, 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (dealArr[i].ts + dealArr[i].dur - value[j].ts) * consumption / countMutiple, value[j].cpu, value[j].freq, dealArr[i].ts + dealArr[i].dur - value[j].ts, '', (dealArr[i].ts + dealArr[i].dur - value[j].ts) / value[j].dur * value[j].percent, 'freqdata', i, undefined)); - break; - } - // 如果频点数据开始时间小于某一周期起始时间,结束时间大于该周期的开始时间。且频点数据结束时间大于周期结束时间的情况 - if (dealArr[i].ts > value[j].ts && value[j].ts + value[j].dur > dealArr[i].ts && value[j].ts + value[j].dur > dealArr[i].ts + dealArr[i].dur) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, dealArr[i].dur * consumption / countMutiple, value[j].cpu, value[j].freq, dealArr[i].dur, '', dealArr[i].dur / value[j].dur * value[j].percent, 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, dealArr[i].dur * consumption / countMutiple, value[j].cpu, value[j].freq, dealArr[i].dur, '', dealArr[i].dur / value[j].dur * value[j].percent, 'freqdata', i, undefined)); - break; - } - // 如果频点数据开始时间小于某一周期起始时间,结束时间大于该周期的开始时间。且频点数据结束时间小于等于周期结束时间的情况 - if (dealArr[i].ts > value[j].ts && value[j].ts + value[j].dur > dealArr[i].ts && value[j].ts + value[j].dur <= dealArr[i].ts + dealArr[i].dur) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (value[j].ts + value[j].dur - dealArr[i].ts) * consumption / countMutiple, value[j].cpu, value[j].freq, value[j].ts + value[j].dur - dealArr[i].ts, '', (value[j].ts + value[j].dur - dealArr[i].ts) / value[j].dur * value[j].percent, 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (value[j].ts + value[j].dur - dealArr[i].ts) * consumption / countMutiple, value[j].cpu, value[j].freq, value[j].ts + value[j].dur - dealArr[i].ts, '', (value[j].ts + value[j].dur - dealArr[i].ts) / value[j].dur * value[j].percent, 'freqdata', i, undefined)); - } - } - this.mergeData(resList); - // 整理排序相同周期下的数据 - this.mergeCpuData(cpuMap.get(key)!, resList); - // 将cpu数据放置到对应周期层级下 - this.mergeCycleData(cycleMap.get(key)![i], cpuMap.get(key)); - } - }); + /** + * 拆解Single大函数 + * @param value 频点数据数组 + * @param funData 方法对象 + * @param constant 常量 + * @param resList 周期数组 + * @param totalList total数组 + */ + dismantlingSingle( + value: Array, funData: {ts: number, dur: number}, + constant: {i: number, key: string, countMutiple: number, cpuArr: Array, cpuMap: Map>}, + resList: Array, + totalList: Map> + ): void{ + // 判断若用户导入json文件,则替换为对应cpu下的对应频点的算力值进行算力消耗计算 + for (let j = 0; j < value.length; j++) { + let startTime = Number(value[j].ts); + let percent = Number(value[j].percent); + // @ts-ignore + let consumptionMap: Map = + SpSegmentationChart.freqInfoMapData.size > 0 && SpSegmentationChart.freqInfoMapData.get(Number(value[j].cpu)); + // 若存在算力值,则直接取值做计算。若不存在算力值,且频点值不为unknown的情况,则取频点值做计算,若为unknown,则取0做兼容 + const consumption: number = Number(consumptionMap && consumptionMap.get(Number(value[j].freq)) + ? consumptionMap.get(Number(value[j].freq)) : (value[j].freq === 'unknown' ? 0 : value[j].freq)); + if (!constant.cpuArr.includes(Number(value[j].cpu))) { + constant.cpuArr.push(Number(value[j].cpu)); + constant.cpuMap.get(constant.key)?.push( + new TabPaneFreqUsageConfig('cycle' + (constant.i + 1) + '—' + value[j].thread, '', + value[j].pid, value[j].tid, 0, value[j].cpu, '', 0, '', 0, 'cpu', -1, [])); + } + // 以下为频点数据按Single周期切割数据如何取舍的判断条件,dealArr为周期切割依据,value为某一线程下的频点汇总数据 + // 如果频点数据开始时间大于某一周期起始时间,小于该周期的结束时间。且频点数据结束时间小于周期结束时间的情况 + if (funData.ts < startTime && funData.ts + funData.dur > startTime && + funData.ts + funData.dur > startTime + value[j].dur) { + resList.push(this.returnSingleObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 1)!); + totalList.get(constant.key)?.push(this.returnSingleObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 1)!); + } + // 如果频点数据开始时间大于某一周期起始时间,小于该周期的结束时间。且频点数据结束时间大于等于周期结束时间的情况 + if (funData.ts < startTime && funData.ts + funData.dur > startTime && + funData.ts + funData.dur <= startTime + value[j].dur) { + resList.push(this.returnSingleObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 2)!); + totalList.get(constant.key)?.push(this.returnSingleObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 2)!); + break; + } + // 如果频点数据开始时间小于某一周期起始时间,结束时间大于该周期的开始时间。且频点数据结束时间大于周期结束时间的情况 + if (funData.ts > startTime && startTime + value[j].dur > funData.ts && + startTime + value[j].dur > funData.ts + funData.dur) { + resList.push(this.returnSingleObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 3)!); + totalList.get(constant.key)?.push(this.returnSingleObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 3)!); + break; + } + // 如果频点数据开始时间小于某一周期起始时间,结束时间大于该周期的开始时间。且频点数据结束时间小于等于周期结束时间的情况 + if (funData.ts > startTime && startTime + value[j].dur > funData.ts && + startTime + value[j].dur <= funData.ts + funData.dur) { + resList.push(this.returnSingleObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 4)!); + totalList.get(constant.key)?.push(this.returnSingleObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], funData, 4)!); + } } - /** - * Loop方式切割数据功能 - */ - dataLoopCut(threadId: HTMLInputElement, threadFunc: HTMLInputElement, resultList: Map>): void { - threadId.style.border = '1px solid rgb(151,151,151)'; - threadFunc.style.border = '1px solid rgb(151,151,151)'; - let threadIdValue = threadId!.value.trim(); - let threadFuncName = threadFunc.value.trim(); - let leftNS = this.currentSelectionParam.leftNs; - let rightNS = this.currentSelectionParam.rightNs; - let tableValue: any = this.threadStatesTbl; - tableValue.value = []; - if (threadIdValue !== '' && threadFuncName !== '') { - querySearchFuncData(threadFuncName, Number(threadIdValue), leftNS, rightNS).then(res => { - if (res !== null && res.length > 0) { - // targetMap为全局initData的拷贝对象,cutArr数组用来存放周期切割依据数据 - let targetMap: Map> = new Map(), cutArr: Array = []; - // 新创建map对象接收传过来的实参map - resultList.forEach((item: Array, key: string) => { - targetMap.set(key, JSON.parse(JSON.stringify(item))); - }) - // 根据线程id及方法名获取的数据,处理后用作切割时间依据,时间跨度为整个方法开始时间到末个方法开始时间 - for (let i of res) { - cutArr[cutArr.length - 1] && (cutArr[cutArr.length - 1].dur = i.startTime ? i.startTime + this.currentSelectionParam.recordStartNs - cutArr[cutArr.length - 1].ts : 0); - cutArr.push({ 'ts': i.startTime + this.currentSelectionParam.recordStartNs }); - } - let cycleMap: Map> = new Map(); - let totalList: Map> = new Map(); - this.mergeLoopData(cutArr, targetMap, cycleMap, totalList); - let threadArr: Array = JSON.parse(JSON.stringify(this.threadArr)); - let processArr: Array = JSON.parse(JSON.stringify(this.processArr)); - this.mergeThreadData(threadArr, cycleMap); - let totalData = this.merge(totalList); - this.mergeTotalData(threadArr, totalData); - this.mergePidData(processArr, threadArr); - this.fixedDeal(processArr); - this.threadStatesTblSource = processArr; - this.threadStatesTbl!.recycleDataSource = processArr; - this.threadStatesTbl!.loading = false; - this.threadClick(processArr); - } else { - this.threadStatesTblSource = []; - this.threadStatesTbl!.recycleDataSource = []; - this.threadStatesTbl!.loading = false; - } - }) + } + /** + * + * @param str 周期列头 + * @param arg 常量参数 + * @param value 频点数据对象 + * @param funData 方法对象 + * @param flag 标志位 + * @returns 频点数据对象 + */ + returnSingleObj( + str: string, + arg: {i: number, percent: number, startTime: number, consumption: number, countMutiple: number}, + value: TabPaneFreqUsageConfig, + funData: {ts: number, dur: number}, + flag: number + ): TabPaneFreqUsageConfig | undefined{ + switch (flag) { + case 1: + return new TabPaneFreqUsageConfig(str, '', value.pid, value.tid, (arg.consumption * value.dur) / arg.countMutiple, + value.cpu, value.freq, value.dur, '', arg.percent, 'freqdata', arg.i, undefined); + case 2: + return new TabPaneFreqUsageConfig(str,'', value.pid, value.tid, ((funData.ts + funData.dur - arg.startTime) + * arg.consumption) / arg.countMutiple, value.cpu, value.freq, funData.ts + funData.dur - arg.startTime, '', + ((funData.ts + funData.dur - arg.startTime) / value.dur) * arg.percent, 'freqdata', arg.i, undefined); + case 3: + return new TabPaneFreqUsageConfig(str, '', value.pid, value.tid, (funData.dur * arg.consumption) / arg.countMutiple, value.cpu, + value.freq, funData.dur, '', (funData.dur / value.dur) * arg.percent, 'freqdata', arg.i, undefined); + case 4: + return new TabPaneFreqUsageConfig(str, '', value.pid, value.tid, + ((arg.startTime + value.dur - funData.ts) * arg.consumption) / arg.countMutiple, + value.cpu, value.freq, arg.startTime + value.dur - funData.ts, '', + ((arg.startTime + value.dur - funData.ts) / value.dur) * arg.percent, + 'freqdata', arg.i, undefined); + default: + break; + } + } + + /** + * Loop方式切割数据功能 + */ + dataLoopCut( + threadId: HTMLInputElement, + threadFunc: HTMLInputElement, + resultList: Map> + ): void { + let threadIdValue: string = threadId.value.trim(); + let threadFuncName: string = threadFunc.value.trim(); + let rightNS: number = this.currentSelectionParam.rightNs; + let recordStartNs: number = this.currentSelectionParam.recordStartNs; + // @ts-ignore + this.threadStatesTbl.value = []; + if (threadIdValue !== '' && threadFuncName !== '') { + querySearchFuncData(threadFuncName, Number(threadIdValue), this.currentSelectionParam.leftNs, rightNS).then((res) => { + if (res !== null && res.length > 0) { + // targetMap为全局initData的拷贝对象,cutArr数组用来存放周期切割依据数据 + let targetMap: Map> = new Map(); + let cutArr: Array<{ts: number, dur?: number}> = []; + // 新创建map对象接收传过来的实参map + resultList.forEach((item: Array, key: string) => { + targetMap.set(key, JSON.parse(JSON.stringify(item))); + }); + // 根据线程id及方法名获取的数据,处理后用作切割时间依据,时间跨度为整个方法开始时间到末个方法开始时间 + for (let i of res) { + cutArr[cutArr.length - 1] && (cutArr[cutArr.length - 1].dur = i.startTime ? i.startTime + + recordStartNs - cutArr[cutArr.length - 1].ts : 0); + cutArr.push({ts: i.startTime! + recordStartNs}); + } + let cycleMap: Map> = new Map(); + let totalList: Map> = new Map(); + this.mergeLoopData(cutArr, targetMap, cycleMap, totalList); + let threadArr: Array = JSON.parse(JSON.stringify(this.threadArr)); + let processArr: Array = JSON.parse(JSON.stringify(this.processArr)); + this.mergeThreadData(threadArr, cycleMap); + this.mergeTotalData(threadArr, this.merge(totalList)); + this.mergePidData(processArr, threadArr); + this.fixedDeal(processArr); + this.threadStatesTblSource = processArr; + this.threadStatesTbl!.recycleDataSource = processArr; + this.threadClick(processArr); } else { - this.threadStatesTbl!.loading = false; - if (threadIdValue === '') { - threadId.style.border = '2px solid rgb(255,0,0)'; - } - if (threadFuncName === '') { - threadFunc.style.border = '2px solid rgb(255,0,0)'; - } + this.threadStatesTblSource = []; + this.threadStatesTbl!.recycleDataSource = []; } + }); + this.threadStatesTbl!.loading = false; + } else { + this.threadStatesTbl!.loading = false; + if (threadIdValue === '') { + threadId.style.border = '2px solid rgb(255,0,0)'; + } + if (threadFuncName === '') { + threadFunc.style.border = '2px solid rgb(255,0,0)'; + } } - /** - * 整合Loop切割方式中的频点数据与方法周期数据 - */ - mergeLoopData(cutArr: Array, targetMap: Map>, cycleMap: Map>, totalList: Map>): void { - let timeDur: number = this.currentSelectionParam.recordStartNs; - targetMap.forEach((value, key) => { - cycleMap.set(key, new Array()); - totalList.set(key, new Array()); - for (let i = 0; i < cutArr.length - 1; i++) { - let cpuArr: Array = [], resList: Array = [], cpuMap: Map> = new Map(); - // 时间倍数值 - const countMutiple = 1000000; - cpuMap.set(key, new Array()); - // 创建周期层级数据 - cycleMap.get(key)?.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[0].thread, ((cutArr[i].ts - timeDur) / 1000000).toFixed(3), '', '', 0, '', '', 0, (cutArr[i].dur / 1000000).toFixed(3), 0, 'cycle', i + 1, [])); - for (let j = 0; j < value.length; j++) { - // 判断若用户导入json文件,则替换为对应cpu下的对应频点的算力值进行算力消耗计算 - let consumptionMap: Map | undefined; - if (SpSegmentationChart.freqInfoMapData.size > 0){ - consumptionMap = SpSegmentationChart.freqInfoMapData.get(value[j].cpu); - } - // 若存在算力值,则直接取值做计算。若不存在算力值,且频点值不为unknown的情况,则取频点值做计算,若为unknown,则取0做兼容 - const consumption = (consumptionMap && consumptionMap.get(value[j].freq)) ? consumptionMap.get(value[j].freq) : (value[j].freq == 'unknown' ? 0 : value[j].freq); - if (!cpuArr.includes(value[j].cpu)) { - cpuArr.push(value[j].cpu); - // 创建cpu层级数据,以便后续生成树结构 - cpuMap.get(key)?.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, 0, value[j].cpu, '', 0, '', 0, 'cpu', -1, [])); - } - // 以下为频点数据按Loop周期切割数据如何取舍的判断条件,cutArr为周期切割依据,value为某一线程下的频点汇总数据 - // 如果频点数据开始时间大于某一周期起始时间,且结束时间小于等于下一同名方法开始时间的情况 - if (value[j].ts >= cutArr[i].ts && (value[j].ts + value[j].dur) <= cutArr[i + 1].ts) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (consumption * value[j].dur) / countMutiple, value[j].cpu, value[j].freq, value[j].dur, '', value[j].percent, 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (consumption * value[j].dur) / countMutiple, value[j].cpu, value[j].freq, value[j].dur, '', value[j].percent, 'freqdata', i, undefined)); - } - // 如果频点数据开始时间大于某一周期起始时间,且结束时间大于下一同名方法开始时间的情况 - if (value[j].ts >= cutArr[i].ts && (value[j].ts + value[j].dur) > cutArr[i + 1].ts) { - if (cutArr[i + 1].ts - value[j].ts > 0) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (consumption * (cutArr[i + 1].ts - value[j].ts)) / countMutiple, value[j].cpu, value[j].freq, cutArr[i + 1].ts - value[j].ts, '', value[j].percent * ((cutArr[i + 1].ts - value[j].ts) / value[j].dur), 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (consumption * (cutArr[i + 1].ts - value[j].ts)) / countMutiple, value[j].cpu, value[j].freq, cutArr[i + 1].ts - value[j].ts, '', value[j].percent * ((cutArr[i + 1].ts - value[j].ts) / value[j].dur), 'freqdata', i, undefined)); - break; - } - } - // 如果频点数据开始时间小于某一周期起始时间,且结束时间大于下一同名方法开始时间的情况 - if (value[j].ts < cutArr[i].ts && (value[j].ts + value[j].dur) > cutArr[i + 1].ts) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (consumption * (cutArr[i + 1].ts - cutArr[i].ts)) / countMutiple, value[j].cpu, value[j].freq, cutArr[i + 1].ts - cutArr[i].ts, '', value[j].percent * ((cutArr[i + 1].ts - cutArr[i].ts) / value[j].dur), 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (consumption * (cutArr[i + 1].ts - cutArr[i].ts)) / countMutiple, value[j].cpu, value[j].freq, cutArr[i + 1].ts - cutArr[i].ts, '', value[j].percent * ((cutArr[i + 1].ts - cutArr[i].ts) / value[j].dur), 'freqdata', i, undefined)); - } - // 如果频点数据开始时间小于某一周期起始时间,结束时间大于该方法开始时间。且频点数据结束时间小于下一同名方法开始时间 - if (value[j].ts < cutArr[i].ts && (value[j].ts + value[j].dur) > cutArr[i].ts && (value[j].ts + value[j].dur) < cutArr[i + 1].ts) { - resList.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[j].thread, '', value[j].pid, value[j].tid, (consumption * (value[j].dur + value[j].ts - cutArr[i].ts)) / countMutiple, value[j].cpu, value[j].freq, value[j].dur + value[j].ts - cutArr[i].ts, '', value[j].percent * ((value[j].dur + value[j].ts - cutArr[i].ts) / value[j].dur), 'freqdata', i, undefined)); - totalList.get(key)?.push(new TabPaneFreqUsageConfig(value[j].thread, '', value[j].pid, value[j].tid, (consumption * (value[j].dur + value[j].ts - cutArr[i].ts)) / countMutiple, value[j].cpu, value[j].freq, value[j].dur + value[j].ts - cutArr[i].ts, '', value[j].percent * ((value[j].dur + value[j].ts - cutArr[i].ts) / value[j].dur), 'freqdata', i, undefined)); - } - } - // 合并相同周期内的数据 - this.mergeData(resList); - // 整理排序相同周期下的数据 - this.mergeCpuData(cpuMap.get(key)!, resList); - // 将cpu数据放置到对应周期层级下 - this.mergeCycleData(cycleMap.get(key)![i], cpuMap.get(key)); - } - }); + } + /** + * 整合Loop切割方式中的频点数据与方法周期数据 + */ + mergeLoopData( + cutArr: Array<{ts: number, dur?: number}>, + targetMap: Map>, + cycleMap: Map>, + totalList: Map> + ): void { + let timeDur: number = this.currentSelectionParam.recordStartNs; + targetMap.forEach((value: any, key) => { + cycleMap.set(key, new Array()); + totalList.set(key, new Array()); + for (let i = 0; i < cutArr.length - 1; i++) { + let cpuArr: Array = []; + let resList: Array = []; + let cpuMap: Map> = new Map(); + // 时间倍数值 + const countMutiple: number = 1000000; + const MIN_NUM: number = 3; + cpuMap.set(key, new Array()); + // 创建周期层级数据 + cycleMap.get(key)?.push(new TabPaneFreqUsageConfig('cycle' + (i + 1) + '—' + value[0].thread, + ((cutArr[i].ts - timeDur) / countMutiple).toFixed(MIN_NUM), key.split('_')[0], key.split('_')[1], 0, '', + '', 0, (cutArr[i].dur! / countMutiple).toFixed(MIN_NUM), 0, 'cycle', i + 1, [])); + this.dismantlingLoop( + value, + cutArr, + { + i: i, + key: key, + countMutiple: countMutiple, + cpuArr, + cpuMap + }, + resList, + totalList + ); + // 合并相同周期内的数据 + this.mergeData(resList); + // 整理排序相同周期下的数据 + this.mergeCpuData(cpuMap.get(key)!, resList); + // 将cpu数据放置到对应周期层级下 + this.mergeCycleData(cycleMap.get(key)![i], cpuMap.get(key)!); + } + }); + } + /** + * 拆解Loop大函数 + * @param value 频点数据数组 + * @param funData 方法对象 + * @param constant 常量 + * @param resList 周期数组 + * @param totalList total数组 + */ + dismantlingLoop( + value: Array, cutArr:Array<{ts: number, dur?: number}>, + constant: {i: number, key: string, countMutiple: number, cpuArr: Array, cpuMap: Map>}, + resList: Array, + totalList: Map>): void { + for (let j = 0; j < value.length; j++) { + // 判断若用户导入json文件,则替换为对应cpu下的对应频点的算力值进行算力消耗计算 + let startTime = Number(value[j].ts); + let percent = Number(value[j].percent); + // @ts-ignore + let consumptionMap: Map = + SpSegmentationChart.freqInfoMapData.size > 0 && SpSegmentationChart.freqInfoMapData.get(Number(value[j].cpu)); + // 若存在算力值,则直接取值做计算。若不存在算力值,且频点值不为unknown的情况,则取频点值做计算,若为unknown,则取0做兼容 + const consumption: number = Number(consumptionMap && consumptionMap.get(Number(value[j].freq)) + ? consumptionMap.get(Number(value[j].freq)) : (value[j].freq === 'unknown' ? 0 : value[j].freq)); + if (!constant.cpuArr.includes(Number(value[j].cpu))) { + constant.cpuArr.push(Number(value[j].cpu)); + // 创建cpu层级数据,以便后续生成树结构 + constant.cpuMap.get(constant.key)?.push(new TabPaneFreqUsageConfig('cycle' + (constant.i + 1) + '—' + value[j].thread, + '', value[j].pid, value[j].tid, 0, value[j].cpu, '', 0, '', 0, 'cpu', -1, [])); + } + // 以下为频点数据按Loop周期切割数据如何取舍的判断条件,cutArr为周期切割依据,value为某一线程下的频点汇总数据 + // 如果频点数据开始时间大于某一周期起始时间,且结束时间小于等于下一同名方法开始时间的情况 + if (startTime >= cutArr[constant.i].ts && startTime + value[j].dur <= cutArr[constant.i + 1].ts) { + resList.push(this.returnLoopObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 1)!); + totalList.get(constant.key)?.push(this.returnLoopObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 1)!); + } + // 如果频点数据开始时间大于某一周期起始时间,且结束时间大于下一同名方法开始时间的情况 + if (startTime >= cutArr[constant.i].ts && startTime + value[j].dur > cutArr[constant.i + 1].ts) { + if (cutArr[constant.i + 1].ts - startTime > 0) { + resList.push(this.returnLoopObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 2)!); + totalList.get(constant.key)?.push(this.returnLoopObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 2)!); + break; + } + } + // 如果频点数据开始时间小于某一周期起始时间,且结束时间大于下一同名方法开始时间的情况 + if (startTime < cutArr[constant.i].ts && startTime + value[j].dur > cutArr[constant.i + 1].ts) { + resList.push(this.returnLoopObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 3)!); + totalList.get(constant.key)?.push(this.returnLoopObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 3)!); + } + // 如果频点数据开始时间小于某一周期起始时间,结束时间大于该方法开始时间。且频点数据结束时间小于下一同名方法开始时间 + if (startTime < cutArr[constant.i].ts && + startTime + value[j].dur > cutArr[constant.i].ts && startTime + value[j].dur < cutArr[constant.i + 1].ts) { + resList.push(this.returnLoopObj('cycle' + (constant.i + 1) + '—' + value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 4)!); + totalList.get(constant.key)?.push(this.returnLoopObj(value[j].thread, + {i: constant.i, percent, startTime, consumption, countMutiple: constant.countMutiple} ,value[j], cutArr, 4)!); + } } - /** - * 切割后整合好的周期频点数据放置到对应的线程下 - */ - mergeThreadData(threadArr: Array, cycleMap: Map>): void { - for (let i = 0; i < threadArr.length; i++) { - let cycleMapData = cycleMap.get(threadArr[i].pid + '_' + threadArr[i].tid); - for (let j = 0; j < cycleMapData!.length; j++) { - threadArr[i].children.push(cycleMapData![j]); - threadArr[i].count += cycleMapData![j].count; - threadArr[i].dur += cycleMapData![j].dur; - threadArr[i].percent += cycleMapData![j].percent; - } + } + + /** + * + * @param str 周期列头 + * @param arg 常量参数 + * @param value 频点数据对象 + * @param funData 方法对象 + * @param flag 标志位 + * @returns 频点数据对象 + */ + returnLoopObj( + str: string, + arg: {i: number, percent: number, startTime: number, consumption: number, countMutiple: number}, + value: TabPaneFreqUsageConfig, + cutArr: Array<{ts: number, dur?: number}>, + flag: number + ): TabPaneFreqUsageConfig | undefined{ + switch (flag) { + case 1: + return new TabPaneFreqUsageConfig(str, '', value.pid, + value.tid, (arg.consumption * value.dur) / arg.countMutiple, value.cpu, value.freq, + value.dur, '', value.percent, 'freqdata', arg.i, undefined); + case 2: + return new TabPaneFreqUsageConfig(str, '', value.pid, value.tid, + (arg.consumption * (cutArr[arg.i + 1].ts - arg.startTime)) / arg.countMutiple, value.cpu, value.freq, + cutArr[arg.i + 1].ts - arg.startTime, '', arg.percent * ((cutArr[arg.i + 1].ts - arg.startTime) / value.dur), + 'freqdata', arg.i, undefined); + case 3: + return new TabPaneFreqUsageConfig(str, '', value.pid, value.tid, + (arg.consumption * (cutArr[arg.i + 1].ts - cutArr[arg.i].ts)) / arg.countMutiple, value.cpu, value.freq, + cutArr[arg.i + 1].ts - cutArr[arg.i].ts, '', arg.percent * ((cutArr[arg.i + 1].ts - cutArr[arg.i].ts) / value.dur), + 'freqdata', arg.i, undefined); + case 4: + return new TabPaneFreqUsageConfig(str, '', value.pid, value.tid, (arg.consumption * (value.dur + arg.startTime - cutArr[arg.i].ts)) + / arg.countMutiple, value.cpu, value.freq, value.dur + arg.startTime - cutArr[arg.i].ts, '', arg.percent + * ((value.dur + arg.startTime - cutArr[arg.i].ts) / value.dur), 'freqdata', arg.i, undefined); + default: + break; + } + } + + /** + * 切割后整合好的周期频点数据放置到对应的线程下 + */ + mergeThreadData( + threadArr: Array, + cycleMap: Map> + ): void { + for (let i = 0; i < threadArr.length; i++) { + let cycleMapData: Array = cycleMap.get( + threadArr[i].pid + '_' + threadArr[i].tid + )!; + for (let j = 0; j < cycleMapData!.length; j++) { + threadArr[i].children?.push(cycleMapData![j]); + threadArr[i].count += cycleMapData![j].count; + threadArr[i].dur += cycleMapData![j].dur; + // @ts-ignore + threadArr[i].percent += cycleMapData![j].percent; + } + } + } + /** + * 切割后整合好的线程级频点数据放置到对应的进程 + */ + mergePidData( + pidArr: Array, + threadArr: Array + ): void { + for (let i = 0; i < pidArr.length; i++) { + for (let j = 0; j < threadArr.length; j++) { + if (pidArr[i].pid === threadArr[j].pid) { + pidArr[i].children?.push(threadArr[j]); + pidArr[i].count += threadArr[j].count; + pidArr[i].dur += threadArr[j].dur; + // @ts-ignore + pidArr[i].percent += threadArr[j].percent; } + } } - /** - * 切割后整合好的线程级频点数据放置到对应的进程 - */ - mergePidData(pidArr: Array, threadArr: Array): void { - for (let i = 0; i < pidArr.length; i++) { - for (let j = 0; j < threadArr.length; j++) { - if (pidArr[i].pid === threadArr[j].pid) { - pidArr[i].children.push(threadArr[j]); - pidArr[i].count += threadArr[j].count; - pidArr[i].dur += threadArr[j].dur; - pidArr[i].percent += threadArr[j].percent; - } - } + } + /** + * 合并相同周期内运行所在cpu相同、频点相同的数据 + */ + mergeData(resList: Array): void { + // 合并相同周期内的数据 + for (let i = 0; i < resList.length; i++) { + for (let j = i + 1; j < resList.length; j++) { + if ( + resList[i].cpu === resList[j].cpu && + resList[i].freq === resList[j].freq && + resList[i].id === resList[j].id + ) { + resList[i].dur += resList[j].dur; + // @ts-ignore + resList[i].percent += resList[j].percent; + resList[i].count += resList[j].count; + resList.splice(j, 1); + j--; } + } } - /** - * 合并相同周期内运行所在cpu相同、频点相同的数据 - */ - mergeData(resList: Array): void { - // 合并相同周期内的数据 - for (let i = 0; i < resList.length; i++) { - for (let j = i + 1; j < resList.length; j++) { - if (resList[i].cpu === resList[j].cpu && resList[i].freq === resList[j].freq && resList[i].id === resList[j].id) { - resList[i].dur += resList[j].dur; - resList[i].percent += resList[j].percent; - resList[i].count += resList[j].count; - resList.splice(j, 1); - j--; - } - } + } + /** + * 将cpu层级数据放到对应的周期层级下 + */ + mergeCycleData( + obj: TabPaneFreqUsageConfig, + arr: Array + ): void { + for (let i = 0; i < arr!.length; i++) { + if (arr![i].count === 0 && arr![i].dur === 0) { + continue; + } + obj.children?.push(arr![i]); + obj.count += arr![i].count; + obj.dur += arr![i].dur; + // @ts-ignore + obj.percent += arr![i].percent; + } + } + /** + * 将切割好的不区分周期的数据作为total数据放到对应的线程层级下,周期数据前 + */ + mergeTotalData( + threadArr: Array, + totalData: Array + ): void { + for (let i = 0; i < threadArr.length; i++) { + for (let j = 0; j < totalData.length; j++) { + if ( + Number(threadArr[i].pid) === Number(totalData[j].pid) && + Number(threadArr[i].tid) === Number(totalData[j].tid) + ) { + totalData[j].thread = 'TotalData'; + // @ts-ignore + threadArr[i].children.unshift(totalData[j]); } + } } - /** - * 将cpu层级数据放到对应的周期层级下 - */ - mergeCycleData(obj: TabPaneFreqUsageConfig, arr: Array | undefined): void { - for (let i = 0; i < arr!.length; i++) { - if (arr![i].count === 0 && arr![i].dur === 0) { - continue; - } - obj.children?.push(arr![i]); - obj.count += arr![i].count; - obj.dur += arr![i].dur; - obj.percent += arr![i].percent; + } + /** + * 整理排序相同周期下的数据 + */ + mergeCpuData( + cpuArray: Array, + resList: Array + ): void { + // 以算力消耗降序排列 + resList.sort((a, b) => b.count - a.count); + // 以cpu升序排列 + cpuArray.sort(( + a: TabPaneFreqUsageConfig, + b: TabPaneFreqUsageConfig + ) => Number(a.cpu) - Number(b.cpu)); + cpuArray.forEach((item: TabPaneFreqUsageConfig) => { + for (let s = 0; s < resList.length; s++) { + if (item.cpu === resList[s].cpu) { + item.children?.push(resList[s]); + item.count += resList[s].count; + item.dur += resList[s].dur; + // @ts-ignore + item.percent += resList[s].percent; + } + } + }); + } + /** + * 切割好的不区分周期的数据,以相同cpu相同频点的进行整合 + */ + merge( + totalList: Map> + ): Array { + let result: Array = new Array(); + totalList.forEach((value: Array, key: string) => { + let countNum = result.push( + new TabPaneFreqUsageConfig('', '', key.split('_')[0], key.split('_')[1], + 0, '', '', 0, '', 0, 'cycle', 0, [] + ) + ); + let cpuArr: Array = []; + let flagArr: Array = []; + for (let i = 0; i < value.length; i++) { + if (!flagArr.includes(value[i].cpu)) { + flagArr.push(value[i].cpu); + let flag = cpuArr.push( + new TabPaneFreqUsageConfig(value[i].thread, '', value[i].pid, value[i].tid, + 0, value[i].cpu, '', 0, '', 0, 'cpu', -1, [] + ) + ); + result[countNum - 1].children?.push(cpuArr[flag - 1]); + } + for (let j = i + 1; j < value.length; j++) { + if (value[i].cpu === value[j].cpu && value[i].freq === value[j].freq) { + value[i].dur += value[j].dur; + // @ts-ignore + value[i].percent += value[j].percent; + value[i].count += value[j].count; + value.splice(j, 1); + j--; + } + } + } + result[countNum - 1].children?.sort((a: TabPaneFreqUsageConfig, b: TabPaneFreqUsageConfig) => Number(a.cpu) - Number(b.cpu)); + for (let i = 0; i < cpuArr.length; i++) { + for (let j = 0; j < value.length; j++) { + if (cpuArr[i].cpu === value[j].cpu) { + cpuArr[i].children?.push(value[j]); + cpuArr[i].dur += value[j].dur; + cpuArr[i].count += value[j].count; + // @ts-ignore + cpuArr[i].percent += value[j].percent; + } } + result[countNum - 1].dur += cpuArr[i].dur; + result[countNum - 1].count += cpuArr[i].count; + // @ts-ignore + result[countNum - 1].percent += cpuArr[i].percent; + } + }); + return result; + } + /** + * 递归整理数据,取小数位数,转换单位 + */ + fixedDeal(arr: Array): void { + if (arr === undefined) { + return; } - /** - * 将切割好的不区分周期的数据作为total数据放到对应的线程层级下,周期数据前 - */ - mergeTotalData(threadArr: Array, totalData: Array): void { - for (let i = 0; i < threadArr.length; i++) { - for (let j = 0; j < totalData.length; j++) { - if (Number(threadArr[i].pid) === Number(totalData[j].pid) && Number(threadArr[i].tid) === Number(totalData[j].tid)) { - totalData[j].thread = 'TotalData'; - threadArr[i].children.unshift(totalData[j]); - } - } + for (let i = 0; i < arr.length; i++) { + // @ts-ignore + arr[i].percent = arr[i].percent.toFixed(2); + // @ts-ignore + arr[i].dur = (arr[i].dur / 1000000).toFixed(3); + if (arr[i].freq !== '') { + if (arr[i].freq === 'unknown') { + arr[i].freq = 'unknown'; + } else { + // @ts-ignore + arr[i].freq = arr[i].freq / 1000; } + } + if (!(SpSegmentationChart.freqInfoMapData.size > 0)) { + // @ts-ignore + arr[i].count = (arr[i].count / 1000).toFixed(3); + } else { + // @ts-ignore + arr[i].count = arr[i].count.toFixed(3); + } + // @ts-ignore + this.fixedDeal(arr[i].children); } - /** - * 整理排序相同周期下的数据 - */ - mergeCpuData(cpuArray: Array, resList: Array): void { - // 以算力消耗降序排列 - resList.sort((a, b) => b.count - a.count); - // 以cpu升序排列 - cpuArray.sort((a: any, b: any) => a.cpu - b.cpu); - cpuArray.forEach((item: any) => { - for (let s = 0; s < resList.length; s++) { - if (item.cpu === resList[s].cpu) { - item.children.push(resList[s]); - item.count += resList[s].count; - item.dur += resList[s].dur; - item.percent += resList[s].percent; - } - } - }); + } - } - /** - * 切割好的不区分周期的数据,以相同cpu相同频点的进行整合 - */ - merge(totalList: Map>): Array { - let result: Array = new Array(); - totalList.forEach((value: any, key: any) => { - let countNum = result.push(new TabPaneFreqUsageConfig('', '', key.split('_')[0], key.split('_')[1], 0, '', '', 0, '', 0, 'cycle', 0, [])); - let cpuArr: Array = []; - let flagArr: Array = []; - for (let i = 0; i < value.length; i++) { - if (!flagArr.includes(value[i].cpu)) { - flagArr.push(value[i].cpu); - let flag = cpuArr.push(new TabPaneFreqUsageConfig(value[i].thread, '', value[i].pid, value[i].tid, 0, value[i].cpu, '', 0, '', 0, 'cpu', -1, [])); - result[countNum - 1].children?.push(cpuArr[flag - 1]); - } - for (let j = i + 1; j < value.length; j++) { - if (value[i].cpu === value[j].cpu && value[i].freq === value[j].freq) { - value[i].dur += value[j].dur; - value[i].percent += value[j].percent; - value[i].count += value[j].count; - value.splice(j, 1); - j--; - } - } + /** + * 绑定表格点击事件 + */ + private threadClick(data: Array): void { + let labels = this.threadStatesTbl?.shadowRoot?.querySelector('.th > .td')!.querySelectorAll('label'); + if (labels) { + for (let i = 0; i < labels.length; i++) { + let label = labels[i].innerHTML; + labels[i].addEventListener('click', (e) => { + if (!this.threadStatesTblSource.length && !this.threadStatesTbl!.recycleDataSource.length) { + data = []; + } + if (label.includes('Process') && i === 0) { + this.threadStatesTbl!.setStatus(data, false); + this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); + } else if (label.includes('Thread') && i === 1) { + for (let item of data) { + // @ts-ignore + item.status = true; + if (item.children !== undefined && item.children.length > 0) { + this.threadStatesTbl!.setStatus(item.children, false); + } } - result[countNum - 1].children?.sort((a: any, b: any) => a.cpu - b.cpu); - for (let i = 0; i < cpuArr.length; i++) { - for (let j = 0; j < value.length; j++) { - if (cpuArr[i].cpu === value[j].cpu) { - cpuArr[i].children.push(value[j]); - cpuArr[i].dur += value[j].dur; - cpuArr[i].count += value[j].count; - cpuArr[i].percent += value[j].percent; - } + this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement( data, RedrawTreeForm.Retract); + } else if (label.includes('Cycle') && i === 2) { + for (let item of data) { + // @ts-ignore + item.status = true; + for (let value of item.children ? item.children : []) { + // @ts-ignore + value.status = true; + if (value.children !== undefined && value.children.length > 0) { + this.threadStatesTbl!.setStatus(value.children, false); } - result[countNum - 1].dur += cpuArr[i].dur; - result[countNum - 1].count += cpuArr[i].count; - result[countNum - 1].percent += cpuArr[i].percent; + } } + this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); + } else if (label.includes('CPU') && i === 3) { + this.threadStatesTbl!.setStatus(data, true); + this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Expand); + } }); - return result; + } } - /** - * 递归整理数据,取小数位数,转换单位 - */ - fixedDeal(arr: Array): void { - if (arr === undefined) { - return; + } + /** + * 散点图渲染数据整理 + */ + render(res: Array, str: string, queryCycleScatter: Array): void { + let maxFreq: HTMLInputElement = this.scatterInput!.querySelector('#maxFreq')!; + let maxHz: HTMLInputElement = this.scatterInput!.querySelector('#maxHz')!; + if (maxFreq.value && maxHz.value) { + if (/^[0-9]*$/.test(maxFreq.value) && /^[0-9]*$/.test(maxHz.value)) { + this.organizeData(res, str, queryCycleScatter, maxFreq.value, maxHz.value); + } else { + if (!/^[0-9]*$/.test(maxFreq.value)) { + maxFreq.style.border = '2px solid rgb(255,0,0)'; } - for (let i = 0; i < arr.length; i++) { - arr[i].percent = arr[i].percent > 100 ? 100 : arr[i].percent; - arr[i].percent = arr[i].percent.toFixed(2); - arr[i].dur = (arr[i].dur / 1000000).toFixed(3); - if (arr[i].freq !== '') { - if (arr[i].freq === 'unknown') { - arr[i].freq = 'unknown'; - } else { - arr[i].freq = arr[i].freq / 1000; - } - } - if(!(SpSegmentationChart.freqInfoMapData.size > 0)) { - arr[i].count = (arr[i].count / 1000).toFixed(3); - }else{ - arr[i].count = (arr[i].count).toFixed(3); - } - this.fixedDeal(arr[i].children); + if (!/^[0-9]*$/.test(maxHz.value)) { + maxHz.style.border = '2px solid rgb(255,0,0)'; } + } + } else { + if (maxFreq.value === '') { + maxFreq.style.border = '2px solid rgb(255,0,0)'; + } + if (maxHz.value === '') { + maxHz.style.border = '2px solid rgb(255,0,0)'; + } + SpSegmentationChart.setChartData('CPU-FREQ', []); } - - /** - * 绑定表格点击事件 - */ - private threadClick(data: Array): void { - let labels = this.threadStatesTbl?.shadowRoot?.querySelector('.th > .td')!.querySelectorAll('label'); - if (labels) { - for (let i = 0; i < labels.length; i++) { - let label = labels[i].innerHTML; - labels[i].addEventListener('click', (e) => { - if (!this.threadStatesTblSource.length && !this.threadStatesTbl!.recycleDataSource.length) { - data = []; - } - if (label.includes('Process') && i === 0) { - this.threadStatesTbl!.setStatus(data, false); - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); - } else if (label.includes('Thread') && i === 1) { - for (let item of data) { - item.status = true; - if (item.children != undefined && item.children.length > 0) { - this.threadStatesTbl!.setStatus(item.children, false); - } - } - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); - } else if (label.includes('Cycle') && i === 2) { - for (let item of data) { - item.status = true; - for (let value of item.children ? item.children : []) { - value.status = true; - if (value.children != undefined && value.children.length > 0) { - this.threadStatesTbl!.setStatus(value.children, false); - } - } - } - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); - } else if (label.includes('CPU') && i === 3) { - this.threadStatesTbl!.setStatus(data, true); - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Expand); - } - }); - } - } + } + /** + * 数据整理 + */ + organizeData( + res: Array, + str: string, + queryCycleScatter: Array, + maxFreqValue: string, + maxHzValue: string + ): void { + // @ts-ignore + this.shadowRoot?.querySelector('#cycleQuery')!.style.display = 'block'; + // @ts-ignore + let freq: Map = SpSegmentationChart.freqInfoMapData.size > 0 && + SpSegmentationChart.freqInfoMapData.get(SpSegmentationChart.freqInfoMapData.size - 1); + // @ts-ignore + let yAxis: number = freq && freq.get(Number(maxFreqValue) * 1000) + ? freq.get(Number(maxFreqValue) * 1000) : Number(maxFreqValue); + let xAxis: number = (yAxis * 1000) / Number(maxHzValue); + // 需要做筛选时,会利用下面的cycleA、cycleB数组 + let scatterArr: Array> = []; + let traceRowdata: Array<{ + dur: number; + startNS: number; + value: number; + cycle: number; + }> = []; + let cycleA: Array> = []; + let cycleB: Array> = []; + let cycleAStart: number = queryCycleScatter[0] || 0; + let cycleAEnd: number = queryCycleScatter[1] || 0; + let cycleBStart: number = queryCycleScatter[2] || 0; + let cycleBEnd: number = queryCycleScatter[3] || 0; + for (let i = 1; i < res.length; i++) { + const count: number = Number(res[i].count); + const dur: number = Number(res[i].cdur); + const rdur: number = Number(res[i].dur); //MHz·ms ms ms + scatterArr.push([count, count / dur, i, dur, rdur]); + traceRowdata.push({ + dur: dur * 1000000, + value: count, + startNS: Number(res[i].ts) * 1000000, + cycle: i - 1, + }); + if (dur >= cycleAStart && dur < cycleAEnd) { + cycleA.push([count, count / dur, i, dur, rdur]); + } + if (dur >= cycleBStart && dur < cycleBEnd) { + cycleB.push([count, count / dur, i, dur, rdur]); + } } - /** - * 散点图渲染数据整理 - */ - render(res: Array, str: string, queryCycleScatter: Array): void { - let maxFreq: HTMLInputElement = this.scatterInput!.querySelector('#maxFreq')!; - let maxHz: HTMLInputElement = this.scatterInput!.querySelector('#maxHz')!; - maxFreq.style.border = '1px solid rgb(151,151,151)'; - maxHz.style.border = '1px solid rgb(151,151,151)'; - if (maxFreq.value && maxHz.value) { - if (/^[0-9]*$/.test(maxFreq.value) && /^[0-9]*$/.test(maxHz.value)) { - // @ts-ignore - this.shadowRoot?.querySelector('#cycleQuery')!.style.display = 'block'; - let freq: Map | undefined; - if (SpSegmentationChart.freqInfoMapData.size > 0){ - freq = SpSegmentationChart.freqInfoMapData.get(SpSegmentationChart.freqInfoMapData.size - 1) - } - // @ts-ignore - let yAxis: number = (freq && freq.get(Number(maxFreq.value) * 1000)) ? freq.get(Number(maxFreq.value) * 1000) : Number(maxFreq.value); - let xAxis: number = yAxis * 1000 / Number(maxHz.value);//MHz·s - // 需要做筛选时,会利用下面的cycleA、cycleB数组 - let scatterArr: Array> = [], traceRowdata: Array = [], cycleA: Array> = [], cycleB: Array> = []; - let cycleAStart: number = queryCycleScatter[0] || 0, cycleAEnd: number = queryCycleScatter[1] || 0, cycleBStart: number = queryCycleScatter[2] || 0, cycleBEnd: number = queryCycleScatter[3] || 0; - for (let i = 1; i < res.length; i++) { - const count: number = Number(res[i].count), dur: number = Number(res[i].cdur), r_dur: number = Number(res[i].dur);//MHz·ms ms ms - scatterArr.push([count, count / dur, i, dur, r_dur]); - traceRowdata.push( - { - 'dur': dur * 1000000, - 'value': count, - 'freq': Math.round(count / dur) * 1000, - 'startNS': Number(res[i].ts) * 1000000, - 'cycle': i - 1 - } - ); - if (dur >= cycleAStart && dur < cycleAEnd) { - cycleA.push([count, count / dur, i, dur, r_dur]); - } - if (dur >= cycleBStart && dur < cycleBEnd) { - cycleB.push([count, count / dur, i, dur, r_dur]); - } - } - this.statisticsScatter!.config = { - // 纵轴坐标值 - yAxisLabel: [Math.round(yAxis / 5), Math.round(yAxis * 2 / 5), Math.round(yAxis * 3 / 5), Math.round(yAxis * 4 / 5), Math.round(yAxis)], - // 横轴坐标值 - xAxisLabel: [Math.round(xAxis / 5), Math.round(xAxis * 2 / 5), Math.round(xAxis * 3 / 5), Math.round(xAxis * 4 / 5), Math.round(xAxis), Math.round(xAxis * 6 / 5)], - // 横轴字段、纵轴字段 - AxisLabel: ['负载', '算力供给'], - // 是否加载最大负载线及均衡线 - drawload: true, - // 最大负载线及均衡线值 - load: [xAxis, Number(maxHz.value)], - // 绘制点数据信息存储数组 - paintingData: [], - // 当前移入点坐标信息 - hoverData: {}, - // 颜色池 - colorPool: () => ['#2f72f8', '#ffab67', '#a285d2'], - // 移入数据点时是否触发函数 - //@ts-ignore - hoverEvent: SpSegmentationChart.tabHover, - // 渐变色背景信息 - globalGradient: undefined, - // 渲染数据点 - data: [scatterArr, cycleA, cycleB], - // 散点图title - title: str, - colorPoolText: () => ['Total', 'CycleA', 'CycleB'], - tip: (data: any) => { - return ` -
- Cycle: ${data.c[2]};
- Comsumption: ${data.c[0]};
- Cycle_dur: ${data.c[3]} ms;
- Running_dur: ${data.c[4]} ms;
-
- ` - } - }; - SpSegmentationChart.setChartData('CPU-FREQ', traceRowdata); - } else { - if (!/^[0-9]*$/.test(maxFreq.value)) { - maxFreq.style.border = '2px solid rgb(255,0,0)'; - } - if (!/^[0-9]*$/.test(maxHz.value)) { - maxHz.style.border = '2px solid rgb(255,0,0)'; - } - } - } else { - if (maxFreq.value === '') { - maxFreq.style.border = '2px solid rgb(255,0,0)'; - maxFreq.setAttribute('placeholder', 'Please input maxFreq'); - } - if (maxHz.value === '') { - maxHz.style.border = '2px solid rgb(255,0,0)'; - maxHz.setAttribute('placeholder', 'Please input Fps'); - } - SpSegmentationChart.setChartData('CPU-FREQ', []); + this.setConfig(Number(maxHzValue), str, scatterArr, yAxis, xAxis, cycleA, cycleB); + SpSegmentationChart.setChartData('CPU-FREQ', traceRowdata); + } - } - } + /** + * 配置散点图 + */ + setConfig(maxHz: number, str: string, scatterArr: Array>, + yAxis: number, xAxis: number, cycleA: Array>, cycleB: Array> + ): void { + const DELTA: number = 5; + this.statisticsScatter!.config = { + // 纵轴坐标值 + yAxisLabel: [ + Math.round(yAxis / DELTA), + Math.round((yAxis * 2) / DELTA), + Math.round((yAxis * 3) / DELTA), + Math.round((yAxis * 4) / DELTA), + Math.round(yAxis), + ], + // 横轴坐标值 + xAxisLabel: [ + Math.round(xAxis / DELTA), + Math.round((xAxis * 2) / DELTA), + Math.round((xAxis * 3) / DELTA), + Math.round((xAxis * 4) / DELTA), + Math.round(xAxis), + Math.round((xAxis * 6) / DELTA), + ], + // 横轴字段、纵轴字段 + axisLabel: ['负载', '算力供给'], + // 是否加载最大负载线及均衡线 + drawload: true, + // 最大负载线及均衡线值 + load: [xAxis, maxHz], + // 绘制点数据信息存储数组 + paintingData: [], + // 当前移入点坐标信息 + hoverData: {}, + // 颜色池 + colorPool: () => ['#2f72f8', '#ffab67', '#a285d2'], + // 移入数据点时是否触发函数 + //@ts-ignore + hoverEvent: SpSegmentationChart.tabHover, + // 渐变色背景信息 + globalGradient: undefined, + // 渲染数据点 + data: [scatterArr, cycleA, cycleB], + // 散点图title + title: str, + colorPoolText: (): Array => ['Total', 'CycleA', 'CycleB'], + tip: (data: {c: Array}): string => { + return ` +
+ Cycle: ${data.c[2]};
+ Comsumption: ${data.c[0]};
+ Cycle_dur: ${data.c[3]} ms;
+ Running_dur: ${data.c[4]} ms;
+
+ `; + }, + }; + } - initElements(): void { - this.threadStatesTbl = this.shadowRoot?.querySelector('#tb-running-datacut'); - // 绑定single、loop按钮点击事件 - this.threadStatesDIV = this.shadowRoot?.querySelector('#dataCut'); - this.threadStatesDIV?.children[2].children[0].addEventListener('click', (e) => { - this.threadStatesTbl!.loading = true; - // @ts-ignore - this.dataSingleCut(this.threadStatesDIV?.children[0]!, this.threadStatesDIV?.children[1]!, this.initData); - }) - this.threadStatesDIV?.children[2].children[1].addEventListener('click', (e) => { - this.threadStatesTbl!.loading = true; - // @ts-ignore - this.dataLoopCut(this.threadStatesDIV?.children[0]!, this.threadStatesDIV?.children[1]!, this.initData); - }) - this.statisticsScatter = this.shadowRoot?.querySelector('#chart-scatter'); - // 增加表格thread层级点击更新散点图事件、周期层级点击高亮泳道图对应段事件 - let scatterData: Array = new Array(); - let str: string = ''; - this.threadStatesTbl!.addEventListener('row-click', (evt): void => { - // @ts-ignore - if (evt.detail.flag === 'thread') { - // @ts-ignore - scatterData = evt.detail.children; - // @ts-ignore - str = evt.detail.thread; - this.render(scatterData, str, []); - } - // @ts-ignore - if (evt.detail.flag === 'cycle') { - // @ts-ignore - SpSegmentationChart.tabHover('CPU-FREQ', true, evt.detail.id - 1); + initElements(): void { + this.threadStatesTbl = this.shadowRoot?.querySelector('#tb-running-datacut'); + // 绑定事件 + this.addListener(); + this.statisticsScatter = this.shadowRoot?.querySelector('#chart-scatter'); + // 增加表格thread层级点击更新散点图事件、周期层级点击高亮泳道图对应段事件 + let scatterData: Array = new Array(); + let str: string = ''; + this.threadStatesTbl!.addEventListener('row-click', (evt): void => { + // @ts-ignore + if (evt.detail.flag === 'thread') { + // @ts-ignore + scatterData = evt.detail.children; + // @ts-ignore + str = evt.detail.thread; + this.render(scatterData, str, []); + } + // @ts-ignore + if (evt.detail.flag === 'cycle' && evt.detail.pid === scatterData[evt.detail.id - 1].pid + // @ts-ignore + && evt.detail.tid === scatterData[evt.detail.id - 1].tid && evt.detail.id > 0) { + // @ts-ignore + SpSegmentationChart.tabHover('CPU-FREQ', true, evt.detail.id - 1); + } + }); + this.scatterInput = this.shadowRoot?.querySelector('.chart-box'); + this.shadowRoot?.querySelector('#query-btn')!.addEventListener('click', (e) => { + // @ts-ignore + let cycleAStartValue = this.shadowRoot?.querySelector('#cycle-a-start-range')!.value; + // @ts-ignore + let cycleAEndValue = this.shadowRoot?.querySelector('#cycle-a-end-range')!.value; + // @ts-ignore + let cycleBStartValue = this.shadowRoot?.querySelector('#cycle-b-start-range')!.value; + // @ts-ignore + let cycleBEndValue = this.shadowRoot?.querySelector('#cycle-b-end-range')!.value; + let queryCycleScatter = [Number(cycleAStartValue), Number(cycleAEndValue), Number(cycleBStartValue), Number(cycleBEndValue)]; + this.render(scatterData, str, queryCycleScatter); + }); + } + /** + * 配置监听事件 + */ + addListener(): void { + // 绑定single、loop按钮点击事件 + this.threadStatesDIV = this.shadowRoot?.querySelector('#dataCut'); + this.threadStatesDIV?.children[2].children[0].addEventListener('click', (e) => { + this.threadStatesTbl!.loading = true; + // @ts-ignore + this.dataSingleCut(this.threadStatesDIV?.children[0]!, this.threadStatesDIV?.children[1]!, this.initData); + } + ); + this.threadStatesDIV?.children[2].children[1].addEventListener('click', (e) => { + this.threadStatesTbl!.loading = true; + // @ts-ignore + this.dataLoopCut(this.threadStatesDIV?.children[0]!, this.threadStatesDIV?.children[1]!, this.initData); + } + ); + this.threadStatesDIV?.children[0].addEventListener('focus', (e) => { + // @ts-ignore + this.threadStatesDIV?.children[0]!.style.border = '1px solid rgb(151,151,151)'; + } + ); + this.threadStatesDIV?.children[1].addEventListener('focus', (e) => { + // @ts-ignore + this.threadStatesDIV?.children[1]!.style.border = '1px solid rgb(151,151,151)'; + } + ); + this.shadowRoot?.querySelector('#maxFreq')?.addEventListener('focus', (e) => { + // @ts-ignore + this.shadowRoot?.querySelector('#maxFreq')!.style.border = '1px solid rgb(151,151,151)'; + }); + this.shadowRoot?.querySelector('#maxHz')?.addEventListener('focus', (e) => { + // @ts-ignore + this.shadowRoot?.querySelector('#maxHz')!.style.border = '1px solid rgb(151,151,151)'; + }); + } - } - }); - this.scatterInput = this.shadowRoot?.querySelector('.chart-box'); - this.shadowRoot?.querySelector('#query-btn')!.addEventListener('click', (e) => { - // @ts-ignore - let cycleAStartValue = this.shadowRoot?.querySelector('#cycle-a-start-range')!.value; - // @ts-ignore - let cycleAEndValue = this.shadowRoot?.querySelector('#cycle-a-end-range')!.value; - // @ts-ignore - let cycleBStartValue = this.shadowRoot?.querySelector('#cycle-b-start-range')!.value; - // @ts-ignore - let cycleBEndValue = this.shadowRoot?.querySelector('#cycle-b-end-range')!.value; - let queryCycleScatter = [Number(cycleAStartValue), Number(cycleAEndValue), Number(cycleBStartValue), Number(cycleBEndValue)]; - this.render(scatterData, str, queryCycleScatter); - }) - } + connectedCallback(): void { + super.connectedCallback(); + resizeObserver(this.parentElement!, this.threadStatesTbl!); + } - connectedCallback(): void { - super.connectedCallback(); - resizeObserver(this.parentElement!, this.threadStatesTbl!); + initHtml(): string { + return ` + + ` + this.htmlUp() + this.htmlDown(); + } - initHtml(): string { - return ` - + htmlUp(): string { + return `
- - -
- - -
+ + +
+ +
- - -
- - - - - - - - - - - - - - - - - - -
- -
-
- maxFreq: - - Fps: - -
-
+
+ + +
+ + + + + + + + + + + + + + + + + + +
+ `; + } + + htmlDown(): string { + return ` + +
+
+ maxFreq: + + Fps: + +
+
+
+ + +
+
+
+ `; + } } diff --git a/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqUsage.ts b/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqUsage.ts index 57f7e72e6ae10b13a7d56e59393cac89fa95e343..77cb916c9952cd7d2c03f3dfb0b2121a45a1c35b 100644 --- a/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqUsage.ts +++ b/ide/src/trace/component/trace/sheet/frequsage/TabPaneFreqUsage.ts @@ -15,306 +15,467 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable, RedrawTreeForm } from '../../../../../base-ui/table/lit-table'; -import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; -import '../../../StackBar' -import { getTabRunningPercent, queryCpuFreqUsageData, queryCpuFreqFilterId } from '../../../../database/SqlLite'; +import { SelectionParam } from '../../../../bean/BoxSelection'; +import '../../../StackBar'; +import { getTabRunningPercent } from '../../../../database/sql/ProcessThread.sql'; +import { queryCpuFreqUsageData, queryCpuFreqFilterId } from '../../../../database/sql/Cpu.sql'; import { Utils } from '../../base/Utils'; import { resizeObserver } from '../SheetUtils'; -import { SliceGroup } from '../../../../bean/StateProcessThread'; -import { SpSegmentationChart } from "../../../chart/SpSegmentationChart"; -import { TabPaneFreqUsageConfig, TabPaneRunningConfig, TabPaneCpuFreqConfig } from "./TabPaneFreqUsageConfig"; +import { SpSegmentationChart } from '../../../chart/SpSegmentationChart'; +import { TabPaneFreqUsageConfig, type TabPaneRunningConfig, TabPaneCpuFreqConfig } from './TabPaneFreqUsageConfig'; @element('tabpane-frequsage') export class TabPaneFreqUsage extends BaseElement { - private threadStatesTbl: LitTable | null | undefined; - private threadStatesTblSource: Array = []; - private currentSelectionParam: Selection | undefined; - private threadArr: Array = []; + private threadStatesTbl: LitTable | null | undefined; + private threadStatesTblSource: Array = []; + private currentSelectionParam: SelectionParam | undefined; + private threadArr: Array = []; - set data(threadStatesParam: SelectionParam | any) { - if (this.currentSelectionParam === threadStatesParam) { - return; - } - this.threadStatesTbl!.loading = true; - this.currentSelectionParam = threadStatesParam; - this.threadStatesTblSource = []; - this.threadStatesTbl!.recycleDataSource = []; - let tableValue: any = this.threadStatesTbl; - tableValue.value = []; - this.threadArr = []; - this.init(threadStatesParam); + set data(threadStatesParam: SelectionParam) { + if (this.currentSelectionParam === threadStatesParam) { + return; } - /** - * 初始化数据 - */ - async init(threadStatesParam: SelectionParam | any): Promise { - let [runningData, sum] = await this.queryRunningData(threadStatesParam); - let cpuFreqData: Array = await this.queryCpuFreqData(threadStatesParam); - let cpuMap: Map> = new Map(); - if (runningData.size > 0) { - // 创建进程级的数组 - let pidArr: Array = [], processArr: Array = threadStatesParam.processIds.length > 1 ? [...new Set(threadStatesParam.processIds)] : threadStatesParam.processIds; - for (let i of processArr) { - pidArr.push(new TabPaneFreqUsageConfig(Utils.PROCESS_MAP.get(i) === null ? 'Process ' + i : Utils.PROCESS_MAP.get(i) + ' ' + i, '', i, '', 0, '', '', 0, '', 0, 'process', -1, [])); - } - // 将cpu频点数据与running状态数据整合,保证其上该段时长内有对应的cpu频点数据 - this.mergeFreqData(runningData, cpuMap, cpuFreqData, sum, threadStatesParam); - // 将频点数据放置到对应cpu层级下 - this.mergeCpuData(cpuMap, runningData); - // 将cpu层级数据放置到线程分组下 - this.mergeThreadData(this.threadArr, cpuMap); - // 将线程层级数据放置到进程级分组下 - this.mergePidData(pidArr, this.threadArr); - // 百分比保留两位小数 - this.fixedDeal(pidArr) - this.threadStatesTblSource = pidArr; - this.threadStatesTbl!.recycleDataSource = pidArr; - this.threadStatesTbl!.loading = false; - this.theadClick(pidArr); - this.threadStatesTbl!.loading = false; - } else { - this.threadStatesTblSource = []; - this.threadStatesTbl!.recycleDataSource = []; - this.threadStatesTbl!.loading = false; - } + this.threadStatesTbl!.loading = true; + this.currentSelectionParam = threadStatesParam; + this.threadStatesTblSource = []; + this.threadStatesTbl!.recycleDataSource = []; + // @ts-ignore + this.threadStatesTbl.value = []; + this.threadArr = []; + this.init(threadStatesParam); + } + /** + * 初始化数据 + */ + async init(threadStatesParam: SelectionParam): Promise { + let { runningMap, sum }: { + runningMap: Map>; + sum: number; + } = await this.queryRunningData(threadStatesParam); + let cpuFreqData: Array = await this.queryCpuFreqData(threadStatesParam); + let cpuMap: Map> = new Map(); + if (runningMap.size > 0) { + // 创建进程级的数组 + let pidArr: Array = []; + let processArr: Array = threadStatesParam.processIds.length > 1 + ? [...new Set(threadStatesParam.processIds)] : threadStatesParam.processIds; + for (let i of processArr) { + pidArr.push(new TabPaneFreqUsageConfig(Utils.PROCESS_MAP.get(i) === null ? 'Process ' + i + : Utils.PROCESS_MAP.get(i) + ' ' + i, '', i, '', 0, '', '', 0, '', 0, 'process', -1, [])); + } + // 将cpu频点数据与running状态数据整合,保证其上该段时长内有对应的cpu频点数据 + this.mergeFreqData( + runningMap, + cpuMap, + cpuFreqData, + sum, + threadStatesParam + ); + // 将频点数据放置到对应cpu层级下 + // @ts-ignore + this.mergeCpuData(cpuMap, runningMap); + // 将cpu层级数据放置到线程分组下 + this.mergeThreadData(this.threadArr, cpuMap); + // 将线程层级数据放置到进程级分组下 + this.mergePidData(pidArr, this.threadArr); + // 百分比保留两位小数 + this.fixedDeal(pidArr); + this.threadStatesTblSource = pidArr; + this.threadStatesTbl!.recycleDataSource = pidArr; + this.threadStatesTbl!.loading = false; + this.threadClick(pidArr); + this.threadStatesTbl!.loading = false; + } else { + this.threadStatesTblSource = []; + this.threadStatesTbl!.recycleDataSource = []; + this.threadStatesTbl!.loading = false; } - /** - * 查询cpu频点信息 - */ - async queryCpuFreqData(threadStatesParam: SelectionParam | any): Promise> { - // 查询cpu及id信息 - let result: Array = await queryCpuFreqFilterId(); - // 以键值对形式将cpu及id进行对应,后续会将频点数据与其对应cpu进行整合 - let IdMap: Map = new Map(); - let queryId: Array = []; - for (let i = 0; i < result.length; i++) { - queryId.push(result[i].id); - IdMap.set(result[i].id, result[i].cpu); - } - let dealArr: Array = []; - // 通过id去查询频点数据 - let res: Array = await queryCpuFreqUsageData(queryId); - for (let i of res) { - let obj = new TabPaneCpuFreqConfig(i.startNS + threadStatesParam.recordStartNs, IdMap.get(i.filter_id)!, i.value, i.dur) - dealArr.push(obj); - } - return dealArr; + } + /** + * 查询cpu频点信息 + */ + async queryCpuFreqData( + threadStatesParam: SelectionParam + ): Promise> { + // 查询cpu及id信息 + let result: Array<{id: number, cpu: number}> = await queryCpuFreqFilterId(); + // 以键值对形式将cpu及id进行对应,后续会将频点数据与其对应cpu进行整合 + let IdMap: Map = new Map(); + let queryId: Array = []; + for (let i = 0; i < result.length; i++) { + queryId.push(result[i].id); + IdMap.set(result[i].id, result[i].cpu); + } + let dealArr: Array = []; + // 通过id去查询频点数据 + let res: Array<{ + startNS: number, + filter_id: number, + value: number, + dur: number + }> = await queryCpuFreqUsageData(queryId); + for (let i of res) { + let obj = new TabPaneCpuFreqConfig( + i.startNS + threadStatesParam.recordStartNs, + IdMap.get(i.filter_id)!, + i.value, + i.dur + ); + dealArr.push(obj); } + return dealArr; + } - /** - * 查询框选区域内的所有running状态数据 - */ - async queryRunningData(threadStatesParam: SelectionParam | any): Promise> { - // 查询running状态线程数据 - let result: Array = await getTabRunningPercent(threadStatesParam.threadIds, threadStatesParam.leftNs, threadStatesParam.rightNs); - let needDeal: Map> = new Map(), sum: number = 0; - if (result != null && result.length > 0) { - // 将running线程数据存到map中 - for (let e of result) { - if(threadStatesParam.processIds.includes(e.pid)){ - if (needDeal.get(e.pid + '_' + e.tid) === undefined) { - this.threadArr.push(new TabPaneFreqUsageConfig(Utils.THREAD_MAP.get(e.tid) + ' ' + e.tid, '', e.pid, e.tid, 0, '', '', 0, '', 0, 'thread', -1, [])); - needDeal.set(e.pid + '_' + e.tid, new Array()); - } - if ((e.ts < (threadStatesParam.leftNs + threadStatesParam.recordStartNs)) && ((e.ts + e.dur) > (threadStatesParam.leftNs + threadStatesParam.recordStartNs))) { - const ts = e.ts; - e.ts = threadStatesParam.leftNs + threadStatesParam.recordStartNs; - e.dur = ts + e.dur - (threadStatesParam.leftNs + threadStatesParam.recordStartNs); - } - if ((e.ts + e.dur) > (threadStatesParam.rightNs + threadStatesParam.recordStartNs)) { - e.dur = threadStatesParam.rightNs + threadStatesParam.recordStartNs - e.ts; - } - let process = Utils.PROCESS_MAP.get(e.pid); - let thread = Utils.THREAD_MAP.get(e.tid); - e.process = process == null || process.length == 0 ? '[NULL]' : process; - e.thread = thread == null || thread.length == 0 ? '[NULL]' : thread; - let arr: any = needDeal.get(e.pid + '_' + e.tid); - sum += e.dur; - arr.push(e); - } - } + /** + * 查询框选区域内的所有running状态数据 + */ + async queryRunningData(threadStatesParam: SelectionParam): Promise<{ + runningMap: Map>; + sum: number; + }> { + // 查询running状态线程数据 + let result: Array = + await getTabRunningPercent(threadStatesParam.threadIds, threadStatesParam.leftNs, threadStatesParam.rightNs); + let needDeal: Map> = new Map(); + let sum: number = 0; + if (result !== null && result.length > 0) { + // 将running线程数据存到map中 + for (let e of result) { + if (threadStatesParam.processIds.includes(e.pid)) { + if (needDeal.get(e.pid + '_' + e.tid) === undefined) { + this.threadArr.push(new TabPaneFreqUsageConfig(Utils.THREAD_MAP.get(e.tid) + ' ' + e.tid, + '', e.pid, e.tid, 0, '', '', 0, '', 0, 'thread', -1, [])); + needDeal.set(e.pid + '_' + e.tid, new Array()); + } + if (e.ts < threadStatesParam.leftNs + threadStatesParam.recordStartNs && + e.ts + e.dur > threadStatesParam.leftNs + threadStatesParam.recordStartNs) { + const ts = e.ts; + e.ts = threadStatesParam.leftNs + threadStatesParam.recordStartNs; + e.dur = ts + e.dur - + (threadStatesParam.leftNs + threadStatesParam.recordStartNs); + } + if (e.ts + e.dur > threadStatesParam.rightNs + threadStatesParam.recordStartNs) { + e.dur = threadStatesParam.rightNs + threadStatesParam.recordStartNs - e.ts; + } + e.process = Utils.PROCESS_MAP.get(e.pid) === null ? '[NULL]' : Utils.PROCESS_MAP.get(e.pid)!; + e.thread = Utils.THREAD_MAP.get(e.tid) === null ? '[NULL]' : Utils.THREAD_MAP.get(e.tid)!; + let arr: Array = needDeal.get(e.pid + '_' + e.tid)!; + sum += e.dur; + arr?.push(e); } - return [needDeal, sum]; + } } + return { runningMap: needDeal, sum: sum }; + } - /** - * 整合running数据与频点数据 - */ - mergeFreqData(needDeal: Map>, cpuMap: Map>, dealArr: Array, sum: number, threadStatesParam: SelectionParam | any): void { - needDeal.forEach((value: Array, key: string) => { - let resultList: Array = [], cpuArr: Array = []; - cpuMap.set(key, new Array()); - const multiple: number = 1000; - for (let i = 0; i < value.length; i++) { - if (!cpuArr.includes(value[i].cpu)) { - cpuArr.push(value[i].cpu); - cpuMap.get(key)?.push(new TabPaneFreqUsageConfig(value[i].tid + '_' + Utils.THREAD_MAP.get(value[i].tid), '', value[i].pid, value[i].tid, 0, value[i].cpu, '', 0, '', 0, 'cpu', -1, [])); - } - for (let j = 0; j < dealArr.length; j++) { - const consumption = SpSegmentationChart.freqInfoMapData.size > 0 ? SpSegmentationChart.freqInfoMapData.get(value[i].cpu)?.get(dealArr[j].value) : dealArr[j].value; - - // 只需要合并相同cpu的数据 - if (value[i].cpu === dealArr[j].cpu) { - // 当running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running数据的持续时间小于频点结束时间减去running数据开始时间的差值的情况 - if (value[i].ts > dealArr[j].startNS && value[i].ts < (dealArr[j].startNS + dealArr[j].dur) && value[i].dur < (dealArr[j].startNS + dealArr[j].dur - value[i].ts)) { - resultList.push(new TabPaneFreqUsageConfig(value[i].tid + '_' + value[i].thread, value[i].ts, '', '', (consumption! * value[i].dur) / multiple, value[i].cpu, dealArr[j].value, value[i].dur, '', value[i].dur / sum * 100, 'freqdata', -1, undefined)); - break; - } - // 当running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running数据的持续时间大于等于频点结束时间减去running数据开始时间的差值的情况 - if (value[i].ts > dealArr[j].startNS && value[i].ts < (dealArr[j].startNS + dealArr[j].dur) && value[i].dur >= (dealArr[j].startNS + dealArr[j].dur - value[i].ts)) { - resultList.push(new TabPaneFreqUsageConfig(value[i].tid + '_' + value[i].thread, value[i].ts, '', '', (consumption! * (dealArr[j].startNS + dealArr[j].dur - value[i].ts)) / multiple, value[i].cpu, dealArr[j].value, (dealArr[j].startNS + dealArr[j].dur - value[i].ts), '', (dealArr[j].startNS + dealArr[j].dur - value[i].ts) / sum * 100, 'freqdata', -1, undefined)); - } - // 当running状态数据的开始时间小于等于频点数据开始时间,结束时间大于频点开始时间。且running数据的持续时间减去频点数据开始时间的差值小于频点数据持续时间的情况 - if (value[i].ts <= dealArr[j].startNS && (value[i].ts + value[i].dur) > dealArr[j].startNS && (value[i].dur + value[i].ts - dealArr[j].startNS) < dealArr[j].dur) { - resultList.push(new TabPaneFreqUsageConfig(value[i].tid + '_' + value[i].thread, dealArr[j].startNS, '', '', (consumption! * (value[i].dur + value[i].ts - dealArr[j].startNS)) / multiple, value[i].cpu, dealArr[j].value, (value[i].dur + value[i].ts - dealArr[j].startNS), '', (value[i].dur + value[i].ts - dealArr[j].startNS) / sum * 100, 'freqdata', -1, undefined)); - break; - } - // 当running状态数据的开始时间小于等于频点数据开始时间,结束时间大于频点开始时间。且running数据的持续时间减去频点数据开始时间的差值大于等于频点数据持续时间的情况 - if (value[i].ts <= dealArr[j].startNS && (value[i].ts + value[i].dur) > dealArr[j].startNS && (value[i].dur + value[i].ts - dealArr[j].startNS) >= dealArr[j].dur) { - resultList.push(new TabPaneFreqUsageConfig(value[i].tid + '_' + value[i].thread, dealArr[j].startNS, '', '', (consumption! * dealArr[j].dur) / multiple, value[i].cpu, dealArr[j].value, dealArr[j].dur, '', dealArr[j].dur / sum * 100, 'freqdata', -1, undefined)); - } - // 当running状态数据的开始时间小于等于频点数据开始时间,结束时间小于等于频点开始时间的情况 - if (value[i].ts <= dealArr[j].startNS && (value[i].ts + value[i].dur) <= dealArr[j].startNS){ - resultList.push(new TabPaneFreqUsageConfig(value[i].tid + '_' + value[i].thread, value[i].ts, '', '', 0, value[i].cpu, 'unknown', value[i].dur, '', value[i].dur / sum * 100, 'freqdata', -1, undefined)); - break; - } - } - } + /** + * 整合running数据与频点数据 + */ + mergeFreqData( + needDeal: Map>, + cpuMap: Map>, + dealArr: Array, + sum: number, + threadStatesParam: SelectionParam + ): void { + needDeal.forEach((value: Array, key: string) => { + let resultList: Array = []; + let cpuArr: Array = []; + cpuMap.set(key, new Array()); + const multiple: number = 1000; + for (let i = 0; i < value.length; i++) { + this.pushCpuMap(cpuArr, cpuMap, value[i], key); + for (let j = 0; j < dealArr.length; j++) { + const consumption: number = (SpSegmentationChart.freqInfoMapData.size > 0 + ? SpSegmentationChart.freqInfoMapData.get(value[i].cpu)?.get(dealArr[j].value) : dealArr[j].value)!; + // 只需要合并相同cpu的数据 + if (value[i].cpu === dealArr[j].cpu) { + // 当running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running数据的持续时间小于频点结束时间减去running数据开始时间的差值的情况 + if (value[i].ts > dealArr[j].startNS && value[i].ts < dealArr[j].startNS + dealArr[j].dur && + value[i].dur < dealArr[j].startNS + dealArr[j].dur - value[i].ts ) { + resultList.push(this.pushNewData(value[i], dealArr[j], {id: 1, sum: sum, consumption: consumption, multiple: multiple})!); + break; } - cpuMap.get(key)?.sort((a: any, b: any) => a.cpu - b.cpu); - needDeal.set(key, this.mergeData(resultList, threadStatesParam)); - }) - } - - /** - * 合并同一线程内,当运行所在cpu和频点相同时,dur及percent进行累加求和 - */ - mergeData(resultList: Array, threadStatesParam: SelectionParam | any): Array{ - for (let i = 0; i < resultList.length; i++) { - for (let j = i + 1; j < resultList.length; j++) { - if (resultList[i].cpu === resultList[j].cpu && resultList[i].freq === resultList[j].freq) { - resultList[i].dur += resultList[j].dur; - resultList[i].percent += resultList[j].percent; - resultList[i].count += resultList[j].count; - resultList.splice(j, 1); - j--; - } + // 当running状态数据的开始时间大于频点数据开始时间,小于频点结束时间。且running数据的持续时间大于等于频点结束时间减去running数据开始时间的差值的情况 + if (value[i].ts > dealArr[j].startNS && value[i].ts < dealArr[j].startNS + dealArr[j].dur && + value[i].dur >= dealArr[j].startNS + dealArr[j].dur - value[i].ts) { + resultList.push(this.pushNewData(value[i], dealArr[j], {id: 2, sum: sum, consumption: consumption, multiple: multiple})!); + } + // 当running状态数据的开始时间小于等于频点数据开始时间,结束时间大于频点开始时间。且running数据的持续时间减去频点数据开始时间的差值小于频点数据持续时间的情况 + if (value[i].ts <= dealArr[j].startNS && value[i].ts + value[i].dur > dealArr[j].startNS && + value[i].dur + value[i].ts - dealArr[j].startNS < dealArr[j].dur) { + resultList.push(this.pushNewData(value[i], dealArr[j], {id: 3, sum: sum, consumption: consumption, multiple: multiple})!); + break; + } + // 当running状态数据的开始时间小于等于频点数据开始时间,结束时间大于频点开始时间。且running数据的持续时间减去频点数据开始时间的差值大于等于频点数据持续时间的情况 + if (value[i].ts <= dealArr[j].startNS && value[i].ts + value[i].dur > dealArr[j].startNS && + value[i].dur + value[i].ts - dealArr[j].startNS >= dealArr[j].dur) { + resultList.push(this.pushNewData(value[i], dealArr[j], {id: 4, sum: sum, consumption: consumption, multiple: multiple})!); + } + // 当running状态数据的开始时间小于等于频点数据开始时间,结束时间小于等于频点开始时间的情况 + if (value[i].ts <= dealArr[j].startNS && value[i].ts + value[i].dur <= dealArr[j].startNS) { + resultList.push(this.pushNewData(value[i], dealArr[j], {id: 5, sum: sum, consumption: consumption, multiple: multiple})!); + break; } - resultList[i].ts = resultList[i].ts - threadStatesParam.recordStartNs; + } } - resultList.sort((a, b) => b.count - a.count); - return resultList; + } + cpuMap.get(key)?.sort((a: any, b: any) => a.cpu - b.cpu); + // @ts-ignore + needDeal.set(key, this.mergeData(resultList, threadStatesParam)); + }); + } + + pushCpuMap( + cpuArr: Array, + cpuMap: Map>, + value: TabPaneRunningConfig, + key: string + ): void { + if (!cpuArr.includes(value.cpu)) { + cpuArr.push(value.cpu); + cpuMap.get(key)?.push( + new TabPaneFreqUsageConfig( + value.tid + '_' + Utils.THREAD_MAP.get(value.tid), + '', + value.pid, + value.tid, + 0, + value.cpu, + '', + 0, + '', + 0, + 'cpu', + -1, + [] + ) + ); } + } - /** - * 将整理好的running频点数据通过map的键放到对应的cpu分组层级下 - */ - mergeCpuData(cpuMap: Map>, needDeal: Map>): void { - cpuMap.forEach((value: Array, key: string) => { - let arr = needDeal.get(key); - for (let i = 0; i < value.length; i++) { - for (let j = 0; j < arr!.length; j++) { - if (arr![j].cpu === value[i].cpu) { - value[i].children?.push(arr![j]); - value[i].count += arr![j].count; - value[i].dur += arr![j].dur; - value[i].percent += arr![j].percent; - } - } - } - }); + /** + * + * @param arg1 running 状态数据 + * @param arg2 cpu频点数据 + * @param arg3 算力值、倍数等常量 + * @returns + */ + pushNewData( + arg1: TabPaneRunningConfig, + arg2: TabPaneCpuFreqConfig, + arg3: { + id: number, + sum: number, + consumption: number, + multiple: number, + } + ): TabPaneFreqUsageConfig | undefined{ + const num: number = 100; + if (arg3.id === 1) { + return new TabPaneFreqUsageConfig( + arg1.tid + '_' + arg1.thread, arg1.ts, '', '', (arg3.consumption! * arg1.dur) / arg3.multiple, + arg1.cpu, arg2.value, arg1.dur, '', (arg1.dur / arg3.sum) * num, 'freqdata', -1, undefined); } + if (arg3.id === 2) { + return new TabPaneFreqUsageConfig( + arg1.tid + '_' + arg1.thread, arg1.ts, '', '', (arg3.consumption! * + (arg2.startNS + arg2.dur - arg1.ts)) / arg3.multiple, arg1.cpu, arg2.value, arg2.startNS + arg2.dur - arg1.ts, + '', ((arg2.startNS + arg2.dur - arg1.ts) / arg3.sum) * num, 'freqdata', -1, undefined); + } + if (arg3.id === 3) { + return new TabPaneFreqUsageConfig( + arg1.tid + '_' + arg1.thread, arg2.startNS, '', '', + (arg3.consumption! * (arg1.dur + arg1.ts - arg2.startNS)) / arg3.multiple, arg1.cpu, arg2.value, + arg1.dur + arg1.ts - arg2.startNS, '', ((arg1.dur + arg1.ts - arg2.startNS) / arg3.sum) * num, 'freqdata', -1, undefined); + } + if (arg3.id === 4) { + return new TabPaneFreqUsageConfig( + arg1.tid + '_' + arg1.thread, arg2.startNS, '', '', + (arg3.consumption! * arg2.dur) / arg3.multiple, arg1.cpu, arg2.value, arg2.dur, + '', (arg2.dur / arg3.sum) * num, 'freqdata', -1, undefined); + } + if (arg3.id === 5) { + return new TabPaneFreqUsageConfig( + arg1.tid + '_' + arg1.thread, + arg1.ts, '', '', 0, arg1.cpu, 'unknown', arg1.dur, + '', (arg1.dur / arg3.sum) * num, 'freqdata', -1, undefined); + } + } - /** - * 将整理好的cpu层级数据放到对应的线程下 - */ - mergeThreadData(threadArr: Array, cpuMap: Map>): void { - for (let i = 0; i < threadArr.length; i++) { - let cpuMapData = cpuMap.get(threadArr[i].pid + '_' + threadArr[i].tid); - for (let j = 0; j < cpuMapData!.length; j++) { - threadArr[i].children.push(cpuMapData![j]); - threadArr[i].count += cpuMapData![j].count; - threadArr[i].dur += cpuMapData![j].dur; - threadArr[i].percent += cpuMapData![j].percent; - } + /** + * 合并同一线程内,当运行所在cpu和频点相同时,dur及percent进行累加求和 + */ + mergeData( + resultList: Array, + threadStatesParam: SelectionParam + ): Array { + for (let i = 0; i < resultList.length; i++) { + for (let j = i + 1; j < resultList.length; j++) { + if ( + resultList[i].cpu === resultList[j].cpu && + resultList[i].freq === resultList[j].freq + ) { + resultList[i].dur += resultList[j].dur; + // @ts-ignore + resultList[i].percent += resultList[j].percent; + resultList[i].count += resultList[j].count; + resultList.splice(j, 1); + j--; } + } + // @ts-ignore + resultList[i].ts = resultList[i].ts - threadStatesParam.recordStartNs; } + resultList.sort((a, b) => b.count - a.count); + return resultList; + } - /** - * 将整理好的线程层级数据放到对应的进程下 - */ - mergePidData(pidArr: Array, threadArr: Array): void { - for (let i = 0; i < pidArr.length; i++) { - for (let j = 0; j < threadArr.length; j++) { - if (pidArr[i].pid === threadArr[j].pid) { - pidArr[i].children.push(threadArr[j]); - pidArr[i].count += threadArr[j].count; - pidArr[i].dur += threadArr[j].dur; - pidArr[i].percent += threadArr[j].percent; - } - } + /** + * 将整理好的running频点数据通过map的键放到对应的cpu分组层级下 + */ + mergeCpuData( + cpuMap: Map>, + needDeal: Map> + ): void { + cpuMap.forEach((value: Array, key: string) => { + let arr = needDeal.get(key); + for (let i = 0; i < value.length; i++) { + for (let j = 0; j < arr!.length; j++) { + if (arr![j].cpu === value[i].cpu) { + value[i].children?.push(arr![j]); + value[i].count += arr![j].count; + value[i].dur += arr![j].dur; + // @ts-ignore + value[i].percent += arr![j].percent; + } } + } + }); + } + + /** + * 将整理好的cpu层级数据放到对应的线程下 + */ + mergeThreadData( + threadArr: Array, + cpuMap: Map> + ): void { + for (let i = 0; i < threadArr.length; i++) { + let cpuMapData = cpuMap.get(threadArr[i].pid + '_' + threadArr[i].tid); + for (let j = 0; j < cpuMapData!.length; j++) { + threadArr[i].children?.push(cpuMapData![j]); + threadArr[i].count += cpuMapData![j].count; + threadArr[i].dur += cpuMapData![j].dur; + // @ts-ignore + threadArr[i].percent += cpuMapData![j].percent; + } } + } - /** - * 递归整理数据小数位 - */ - fixedDeal(arr: Array): void { - if (arr == undefined) { - return; - } - for (let i = 0; i < arr.length; i++) { - arr[i].percent = arr[i].percent > 100 ? 100 : arr[i].percent; - arr[i].percent = arr[i].percent.toFixed(2); - arr[i].dur = (arr[i].dur / 1000000).toFixed(3); - arr[i].count = (arr[i].count / 1000000).toFixed(3); - if (arr[i].freq !== '') { - if (arr[i].freq === 'unknown') { - arr[i].freq = 'unknown'; - } else { - arr[i].freq = arr[i].freq / 1000; - } - } - this.fixedDeal(arr[i].children); + /** + * 将整理好的线程层级数据放到对应的进程下 + */ + mergePidData( + pidArr: Array, + threadArr: Array + ): void { + for (let i = 0; i < pidArr.length; i++) { + for (let j = 0; j < threadArr.length; j++) { + if (pidArr[i].pid === threadArr[j].pid) { + pidArr[i].children?.push(threadArr[j]); + pidArr[i].count += threadArr[j].count; + pidArr[i].dur += threadArr[j].dur; + // @ts-ignore + pidArr[i].percent += threadArr[j].percent; } + } } - /** - * 表头点击事件 - */ - private theadClick(data: Array): void { - let labels = this.threadStatesTbl?.shadowRoot?.querySelector('.th > .td')!.querySelectorAll('label'); - if (labels) { - for (let i = 0; i < labels.length; i++) { - let label = labels[i].innerHTML; - labels[i].addEventListener('click', (e) => { - if (label.includes('Process') && i === 0) { - this.threadStatesTbl!.setStatus(data, false); - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); - } else if (label.includes('Thread') && i === 1) { - for (let item of data) { - item.status = true; - if (item.children != undefined && item.children.length > 0) { - this.threadStatesTbl!.setStatus(item.children, false); - } - } - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Retract); - } else if (label.includes('CPU') && i === 2) { - this.threadStatesTbl!.setStatus(data, true); - this.threadStatesTbl!.recycleDs = this.threadStatesTbl!.meauseTreeRowElement(data, RedrawTreeForm.Expand); - } - }); - } - } + } + + /** + * 递归整理数据小数位 + */ + fixedDeal(arr: Array): void { + const multiple: number = 1000000; + const freqMultiple: number = 1000; + const fixedNum: number = 3; + const percentNum: number = 2; + if (arr === undefined) { + return; } - initElements(): void { - this.threadStatesTbl = this.shadowRoot?.querySelector('#tb-running-percent'); + for (let i = 0; i < arr.length; i++) { + // @ts-ignore + arr[i].percent = arr[i].percent.toFixed(percentNum); + // @ts-ignore + arr[i].dur = (arr[i].dur / multiple).toFixed(fixedNum); + // @ts-ignore + arr[i].count = (arr[i].count / multiple).toFixed(fixedNum); + if (arr[i].freq !== '') { + if (arr[i].freq === 'unknown') { + arr[i].freq = 'unknown'; + } else { + // @ts-ignore + arr[i].freq = arr[i].freq / freqMultiple; + } + } + this.fixedDeal(arr[i].children!); } - connectedCallback(): void { - super.connectedCallback(); - resizeObserver(this.parentElement!, this.threadStatesTbl!); + } + /** + * 表头点击事件 + */ + private threadClick(data: Array): void { + let labels = this.threadStatesTbl?.shadowRoot + ?.querySelector('.th > .td')! + .querySelectorAll('label'); + if (labels) { + for (let i = 0; i < labels.length; i++) { + let label = labels[i].innerHTML; + labels[i].addEventListener('click', (e) => { + if (label.includes('Process') && i === 0) { + this.threadStatesTbl!.setStatus(data, false); + this.threadStatesTbl!.recycleDs = + this.threadStatesTbl!.meauseTreeRowElement( + data, + RedrawTreeForm.Retract + ); + } else if (label.includes('Thread') && i === 1) { + for (let item of data) { + // @ts-ignore + item.status = true; + if (item.children !== undefined && item.children.length > 0) { + this.threadStatesTbl!.setStatus(item.children, false); + } + } + this.threadStatesTbl!.recycleDs = + this.threadStatesTbl!.meauseTreeRowElement( + data, + RedrawTreeForm.Retract + ); + } else if (label.includes('CPU') && i === 2) { + this.threadStatesTbl!.setStatus(data, true); + this.threadStatesTbl!.recycleDs = + this.threadStatesTbl!.meauseTreeRowElement( + data, + RedrawTreeForm.Expand + ); + } + }); + } } - initHtml(): string { - return ` + } + initElements(): void { + this.threadStatesTbl = this.shadowRoot?.querySelector( + '#tb-running-percent' + ); + } + connectedCallback(): void { + super.connectedCallback(); + resizeObserver(this.parentElement!, this.threadStatesTbl!); + } + initHtml(): string { + return ` -
- - -
- - -
+ +
+ + +
+ + +
+
+ `; + } + + initContentBottom(): string { + return ` +
+
+ + + + + + + + + +
-
-
- - - - - - - - - - + + - `; +
+ `; } } diff --git a/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkCounter.ts b/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkCounter.ts index 030111e9ad10f0d3fbce040d17b645b926810338..a3e4c8d99134c08394a8b95bff719e8826cbea60 100644 --- a/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkCounter.ts +++ b/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkCounter.ts @@ -16,12 +16,13 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabSdkCounterData, getTabSdkCounterLeftData, queryStartTime } from '../../../../database/SqlLite'; import { LitTableColumn } from '../../../../../base-ui/table/lit-table-column'; import { Utils } from '../../base/Utils'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { TabUtil } from './TabUtil'; import { resizeObserver } from '../SheetUtils'; +import {getTabSdkCounterData, getTabSdkCounterLeftData} from "../../../../database/sql/Sdk.sql"; +import {queryStartTime} from "../../../../database/sql/SqlLite.sql"; @element('tabpane-sdk-counter') export class TabPaneSdkCounter extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkSlice.ts b/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkSlice.ts index e2e3371fa66d7b5a9a36776cf7197dc83a54437a..7016d85963af0c1298b0191209ccc94e9e7a7eb0 100644 --- a/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkSlice.ts +++ b/ide/src/trace/component/trace/sheet/sdk/TabPaneSdkSlice.ts @@ -16,12 +16,13 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionData, SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabSdkSliceData, queryStartTime, queryTotalTime } from '../../../../database/SqlLite'; import { LitTableColumn } from '../../../../../base-ui/table/lit-table-column'; import { Utils } from '../../base/Utils'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { TabUtil } from './TabUtil'; import { resizeObserver } from '../SheetUtils'; +import {getTabSdkSliceData} from "../../../../database/sql/Sdk.sql"; +import {queryTotalTime} from "../../../../database/sql/SqlLite.sql"; @element('tabpane-sdk-slice') export class TabPaneSdkSlice 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 7487fe6aaa8a5a45806090b37f5fbbab013b1282..46171d4869c43083ee3e5e57349ef41388bbeb8d 100644 --- a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsComparison.ts +++ b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsComparison.ts @@ -17,11 +17,11 @@ import { type LitSelect } from '../../../../../base-ui/select/LitSelect'; import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabSmapsStatisticData } from '../../../../database/SqlLite'; import { resizeObserverFromMemory } from '../SheetUtils'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; import { TabPaneSmapsStatistics } from './TabPaneSmapsStatistics'; import { type SmapsType } from '../../../../bean/SmapsStruct'; +import {getTabSmapsStatisticData} from "../../../../database/sql/Smaps.sql"; @element('tabpane-smaps-comparison') export class TabPaneSmapsComparison extends TabPaneSmapsStatistics { diff --git a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsRecord.ts b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsRecord.ts index 78d9471f955ce497b31c8d9e4d1597e357e9111e..71c4a5ffe09d75fc624467b3c4288c38120ce4ee 100644 --- a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsRecord.ts +++ b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsRecord.ts @@ -18,12 +18,12 @@ import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { SmapsType } from '../../../../bean/SmapsStruct'; -import { querySmapsRecordTabData } from '../../../../database/SqlLite'; import { getByteWithUnit } from '../../../../database/logic-worker/ProcedureLogicWorkerCommon'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { resizeObserver } from '../SheetUtils'; +import {querySmapsRecordTabData} from "../../../../database/sql/Smaps.sql"; @element('tabpane-smaps-record') export class TabPaneSmapsRecord extends BaseElement { private smapsRecordTable: LitTable | undefined | null; diff --git a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsSample.ts b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsSample.ts index 4827f62228a2fd71ec2ed37b8531fc8ffec2f9e3..0b6772e5b3be75de9bb660083d1a9d4ce35be27f 100644 --- a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsSample.ts +++ b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsSample.ts @@ -15,12 +15,12 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { getTabSmapsData, getTabSmapsSampleData } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { log } from '../../../../../log/Log'; import { Smaps, SmapsType, TYPE_STRING } from '../../../../bean/SmapsStruct'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { SpSystemTrace } from '../../../SpSystemTrace'; +import {getTabSmapsData, getTabSmapsSampleData} from "../../../../database/sql/Smaps.sql"; @element('tabpane-smaps-sample') export class TabPaneSmapsSample extends BaseElement { private tblSmapsSample: LitTable | null | undefined; diff --git a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts index 44f7a5769231c4aaa5f8f890dcc19675c5b5a67a..72d693709162010fdd4511abc911a8c6e66b3bf7 100644 --- a/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts +++ b/ide/src/trace/component/trace/sheet/smaps/TabPaneSmapsStatistics.ts @@ -15,16 +15,15 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { SelectionParam } from '../../../../bean/BoxSelection'; -import { - getTabSmapsMaxSize, - getTabSmapsStatisticData, - getTabSmapsStatisticMaxSize, - getTabSmapsStatisticSelectData, -} from '../../../../database/SqlLite'; import { type Smaps, SmapsTreeObj, SmapsType, TYPE_STRING } from '../../../../bean/SmapsStruct'; import { Utils } from '../../base/Utils'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { SpSystemTrace } from '../../../SpSystemTrace'; +import { + getTabSmapsMaxSize, getTabSmapsStatisticData, + getTabSmapsStatisticMaxSize, + getTabSmapsStatisticSelectData +} from "../../../../database/sql/Smaps.sql"; @element('tabpane-smaps-statistics') export class TabPaneSmapsStatistics extends BaseElement { private tblSmapsStatistics: LitTable | null | undefined; diff --git a/ide/src/trace/component/trace/sheet/task/TabPaneTaskFrames.ts b/ide/src/trace/component/trace/sheet/task/TabPaneTaskFrames.ts index 1d3e7f09b632c871d5c58d16d04bd124187c7fc4..c68d6cd17be2eb6990197c078d085f8f6531ae2b 100644 --- a/ide/src/trace/component/trace/sheet/task/TabPaneTaskFrames.ts +++ b/ide/src/trace/component/trace/sheet/task/TabPaneTaskFrames.ts @@ -18,14 +18,11 @@ import { SelectionParam } from '../../../../bean/BoxSelection'; import { LitTable } from '../../../../../base-ui/table/lit-table'; import { resizeObserver } from '../SheetUtils'; import { FuncStruct } from '../../../../database/ui-worker/ProcedureWorkerFunc'; -import { - queryConcurrencyTask, - queryTaskListByExecuteTaskIds, - queryTaskPoolTotalNum, -} from '../../../../database/SqlLite'; import { BaseStruct } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { type LitProgressBar } from '../../../../../base-ui/progress-bar/LitProgressBar'; +import {queryTaskListByExecuteTaskIds, queryTaskPoolTotalNum} from "../../../../database/sql/SqlLite.sql"; +import {queryConcurrencyTask} from "../../../../database/sql/Perf.sql"; const ALLOCATION_TASK = 'H:Task Allocation:'; const PERFORM_TASK = 'H:Task Perform:'; diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaSelectVmTracker.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaSelectVmTracker.ts index 812906df97770824da8ad33fc1d0436a9e975c0c..07d1610b784975d276170bb11b48acad77937844 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaSelectVmTracker.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaSelectVmTracker.ts @@ -17,10 +17,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type Dma } from '../../../../bean/AbilityMonitor'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { getTabDmaVMTrackerClickData } from '../../../../database/SqlLite'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { Utils } from '../../base/Utils'; import { ns2s } from '../../TimerShaftElement'; +import {getTabDmaVMTrackerClickData} from "../../../../database/sql/Dma.sql"; @element('tabpane-dma-selection-vmtracker') export class TabPaneDmaSelectVmTracker extends BaseElement { @@ -129,71 +129,33 @@ export class TabPaneDmaSelectVmTracker extends BaseElement { `; } + private compareValues(a: any, b: any, sort: number): number { + if (sort === 1) { + return a > b ? 1 : a < b ? -1 : 0; + } else { + return a < b ? 1 : a > b ? -1 : 0; + } + } + sortDmaByColumn(column: string, sort: number): void { - switch (sort) { - case 0: - this.damClickTable!.recycleDataSource = this.dmaClickSource; - break; - default: - let array = [...this.dmaClickSource]; - switch (column) { - case 'startNs': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 - ? dmaVmLeftData.startNs - dmaVmRightData.startNs - : dmaVmRightData.startNs - dmaVmLeftData.startNs; - }); - break; - case 'expTaskComm': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 - ? `${dmaVmLeftData.expTaskComm}`.localeCompare(`${dmaVmRightData.expTaskComm}`) - : `${dmaVmRightData.expTaskComm}`.localeCompare(`${dmaVmLeftData.expTaskComm}`); - }); - break; - case 'fd': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 ? dmaVmLeftData.fd - dmaVmRightData.fd : dmaVmRightData.fd - dmaVmLeftData.fd; - }); - break; - case 'size': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 ? dmaVmLeftData.size - dmaVmRightData.size : dmaVmRightData.size - dmaVmLeftData.size; - }); - break; - case 'ino': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 ? dmaVmLeftData.ino - dmaVmRightData.ino : dmaVmRightData.ino - dmaVmLeftData.ino; - }); - break; - case 'expPid': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 - ? dmaVmLeftData.expPid - dmaVmRightData.expPid - : dmaVmRightData.expPid - dmaVmLeftData.expPid; - }); - break; - case 'flag': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 ? dmaVmLeftData.flag - dmaVmRightData.flag : dmaVmRightData.flag - dmaVmLeftData.flag; - }); - break; - case 'bufName': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 - ? `${dmaVmLeftData.bufName}`.localeCompare(`${dmaVmRightData.bufName}`) - : `${dmaVmRightData.bufName}`.localeCompare(`${dmaVmLeftData.bufName}`); - }); - break; - case 'expName': - this.damClickTable!.recycleDataSource = array.sort((dmaVmLeftData, dmaVmRightData) => { - return sort === 1 - ? `${dmaVmLeftData.expName}`.localeCompare(`${dmaVmRightData.expName}`) - : `${dmaVmRightData.expName}`.localeCompare(`${dmaVmLeftData.expName}`); - }); - break; - } - break; + const comparisonFunctions: { [key: string]: (a: any, b: any) => number } = { + 'startNs': (a, b) => this.compareValues(a.startNs, b.startNs, sort), + 'expTaskComm': (a, b) => this.compareValues(`${a.expTaskComm}`, `${b.expTaskComm}`, sort), + 'fd': (a, b) => this.compareValues(a.fd, b.fd, sort), + 'size': (a, b) => this.compareValues(a.size, b.size, sort), + 'ino': (a, b) => this.compareValues(a.ino, b.ino, sort), + 'expPid': (a, b) => this.compareValues(a.expPid, b.expPid, sort), + 'flag': (a, b) => this.compareValues(a.flag, b.flag, sort), + 'bufName': (a, b) => this.compareValues(`${a.bufName}`, `${b.bufName}`, sort), + 'expName': (a, b) => this.compareValues(`${a.expName}`, `${b.expName}`, sort) + }; + + if (sort === 0) { + this.damClickTable!.recycleDataSource = this.dmaClickSource; + } else { + const array = [...this.dmaClickSource]; + const comparisonFunction = comparisonFunctions[column] || (() => 0); + this.damClickTable!.recycleDataSource = array.sort(comparisonFunction); } } } diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTracker.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTracker.ts index cf611d231d7d09de6e66c5e8d71d962201c81a68..f4ffba4eb249ea3b7bc04b73660560b56b7700d6 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTracker.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTracker.ts @@ -17,10 +17,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { resizeObserver } from '../SheetUtils'; -import { getTabDmaVmTrackerData } from '../../../../database/SqlLite'; import { type Dma } from '../../../../bean/AbilityMonitor'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { Utils } from '../../base/Utils'; +import {getTabDmaVmTrackerData} from "../../../../database/sql/Dma.sql"; @element('tabpane-dma-vmtracker') export class TabPaneDmaVmTracker extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTrackerComparison.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTrackerComparison.ts index b6233f713177e111e21d4b1c4b825e797d5e15d0..a0104d63cdad4f9413017aab961c9a6fc58855c8 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTrackerComparison.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneDmaVmTrackerComparison.ts @@ -19,26 +19,26 @@ import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type DmaComparison } from '../../../../bean/AbilityMonitor'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { getTabDmaVmTrackerComparisonData } from '../../../../database/SqlLite'; import { type SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { Utils } from '../../base/Utils'; import { resizeObserverFromMemory } from '../SheetUtils'; import '../TabPaneJsMemoryFilter'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {getTabDmaVmTrackerComparisonData} from "../../../../database/sql/Dma.sql"; @element('tabpane-dma-vmtracker-comparison') export class TabPaneDmaVmTrackerComparison extends BaseElement { - private damClickTable: LitTable | null | undefined; + private damClickTables: LitTable | null | undefined; private comparisonSelect: TabPaneJsMemoryFilter | null | undefined; private selectEl: LitSelect | null | undefined; private selfData: Array = []; private comparisonSource: Array = []; initElements(): void { - this.damClickTable = this.shadowRoot?.querySelector('#damClickTable'); + this.damClickTables = this.shadowRoot?.querySelector('#damClickTables'); this.comparisonSelect = this.shadowRoot?.querySelector('#filter') as TabPaneJsMemoryFilter; this.selectEl = this.comparisonSelect?.shadowRoot?.querySelector('lit-select'); - this.damClickTable!.addEventListener('column-click', (e) => { + this.damClickTables!.addEventListener('column-click', (e) => { // @ts-ignore this.sortDmaByColumn(e.detail.key, e.detail.sort); }); @@ -46,7 +46,7 @@ export class TabPaneDmaVmTrackerComparison extends BaseElement { connectedCallback(): void { super.connectedCallback(); - resizeObserverFromMemory(this.parentElement!, this.damClickTable!, this.comparisonSelect!); + resizeObserverFromMemory(this.parentElement!, this.damClickTables!, this.comparisonSelect!); } async queryDataByDB(startNs: number): Promise { @@ -102,19 +102,19 @@ export class TabPaneDmaVmTrackerComparison extends BaseElement { comparison[0].value = this.selfData[0].value - comparison[0].value; comparison[0].sizes = Utils.getBinaryByteWithUnit(comparison[0].value); this.comparisonSource = comparison; - this.damClickTable!.recycleDataSource = comparison; + this.damClickTables!.recycleDataSource = comparison; } sortDmaByColumn(column: string, sort: number): void { switch (sort) { case 0: - this.damClickTable!.recycleDataSource = this.comparisonSource; + this.damClickTables!.recycleDataSource = this.comparisonSource; break; default: let array = [...this.comparisonSource]; switch (column) { case 'sizeDelta': - this.damClickTable!.recycleDataSource = array.sort((dmaComparisonLeftData, dmaComparisonRightData) => { + this.damClickTables!.recycleDataSource = array.sort((dmaComparisonLeftData, dmaComparisonRightData) => { return sort === 1 ? dmaComparisonLeftData.value - dmaComparisonRightData.value : dmaComparisonRightData.value - dmaComparisonLeftData.value; @@ -128,7 +128,7 @@ export class TabPaneDmaVmTrackerComparison extends BaseElement { initHtml(): string { return ` - + diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemorySelectVmTracker.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemorySelectVmTracker.ts index 5e9a4f5644148c61ca51f24130257b79259279e4..15c9134d8b28cb5f32ccf7e6ebdfaf34ef85b9d5 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemorySelectVmTracker.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemorySelectVmTracker.ts @@ -17,9 +17,9 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type GpuMemory } from '../../../../bean/AbilityMonitor'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { getTabGpuMemoryVMTrackerClickData } from '../../../../database/SqlLite'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { Utils } from '../../base/Utils'; +import {getTabGpuMemoryVMTrackerClickData} from "../../../../database/sql/Memory.sql"; @element('tabpane-gpu-memory-selection-vmtracker') export class TabPaneGpuMemorySelectVmTracker extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTracker.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTracker.ts index a3af32e2b9721f38587b9847263109e67e3a59c1..5b740f0f848fc49e8f1990f90d201613e6e6070f 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTracker.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTracker.ts @@ -17,11 +17,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { resizeObserver } from '../SheetUtils'; -import { getTabGpuMemoryData } from '../../../../database/SqlLite'; import { GpuMemory } from '../../../../bean/AbilityMonitor'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { Utils } from '../../base/Utils'; import { SpSystemTrace } from '../../../SpSystemTrace'; +import {getTabGpuMemoryData} from "../../../../database/sql/Memory.sql"; @element('tabpane-gpu-memory-vmtracker') export class TabPaneGpuMemoryVmTracker extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts index ebc9671cdb29281c62252b5e2a5380dfafa6219c..dde58aefdb21fcab96ce21a8cae51d5743b267d6 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuMemoryVmTrackerComparison.ts @@ -19,27 +19,27 @@ import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { GpuMemoryComparison } from '../../../../bean/AbilityMonitor'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { getTabGpuMemoryVmTrackerComparisonData } from '../../../../database/SqlLite'; import { type SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { Utils } from '../../base/Utils'; import { compare, resizeObserverFromMemory } from '../SheetUtils'; import '../TabPaneJsMemoryFilter'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {getTabGpuMemoryVmTrackerComparisonData} from "../../../../database/sql/Memory.sql"; @element('tabpane-gpu-memory-vmtracker-comparison') export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { - private gpuMemoryClickTable: LitTable | null | undefined; + private gpuMemoryClickTables: LitTable | null | undefined; private comparisonSelect: TabPaneJsMemoryFilter | null | undefined; private selectEl: LitSelect | null | undefined; private selfData = new Array(); private comparisonSource: Array = []; initElements(): void { - this.gpuMemoryClickTable = this.shadowRoot?.querySelector('#gpuMemoryClickTable'); + this.gpuMemoryClickTables = this.shadowRoot?.querySelector('#gpuMemoryClickTables'); this.comparisonSelect = this.shadowRoot?.querySelector('#filter') as TabPaneJsMemoryFilter; this.selectEl = this.comparisonSelect?.shadowRoot?.querySelector('lit-select'); - this.gpuMemoryClickTable!.addEventListener('column-click', (e) => { + this.gpuMemoryClickTables!.addEventListener('column-click', (e) => { // @ts-ignore this.sortGpuMemoryByColumn(e.detail.key, e.detail.sort); }); @@ -47,7 +47,7 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { connectedCallback(): void { super.connectedCallback(); - resizeObserverFromMemory(this.parentElement!, this.gpuMemoryClickTable!, this.comparisonSelect!); + resizeObserverFromMemory(this.parentElement!, this.gpuMemoryClickTables!, this.comparisonSelect!); } async queryDataByDB(startNs: number): Promise { @@ -79,7 +79,7 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { } } this.selectStamps(dataArray); - this.getComparisonData(dataArray[0].startNs); + this.getComparisonsData(dataArray[0].startNs); } selectStamps(dataList: Array): void { @@ -100,7 +100,7 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { option.addEventListener('onSelected', async (e) => { for (let f of dataList) { if (input.value === f.name) { - this.getComparisonData(f.startNs); + this.getComparisonsData(f.startNs); } } e.stopPropagation(); @@ -108,7 +108,7 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { }); } - async getComparisonData(targetStartNs: number): Promise { + async getComparisonsData(targetStartNs: number): Promise { let comparisonData: GpuMemoryComparison[] = []; let comparison: GpuMemoryComparison[] = []; let data = await this.queryDataByDB(targetStartNs); @@ -120,19 +120,19 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { item.sizes = Utils.getBinaryByteWithUnit(item.value); } this.comparisonSource = comparisonData; - this.gpuMemoryClickTable!.recycleDataSource = comparisonData; + this.gpuMemoryClickTables!.recycleDataSource = comparisonData; } sortGpuMemoryByColumn(column: string, sort: number): void { switch (sort) { case 0: - this.gpuMemoryClickTable!.recycleDataSource = this.comparisonSource; + this.gpuMemoryClickTables!.recycleDataSource = this.comparisonSource; break; default: let array = [...this.comparisonSource]; switch (column) { case 'thread': - this.gpuMemoryClickTable!.recycleDataSource = array.sort( + this.gpuMemoryClickTables!.recycleDataSource = array.sort( (gpuMComparisonLeftData, gpuMComparisonRightData) => { return sort === 1 ? `${gpuMComparisonLeftData.thread}`.localeCompare(`${gpuMComparisonRightData.thread}`) @@ -141,14 +141,14 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { ); break; case 'gpuName': - this.gpuMemoryClickTable!.recycleDataSource = array.sort((gpuMCompVmLeftData, gpuMCompVmRightData) => { + this.gpuMemoryClickTables!.recycleDataSource = array.sort((gpuMCompVmLeftData, gpuMCompVmRightData) => { return sort === 1 ? `${gpuMCompVmLeftData.gpuName}`.localeCompare(`${gpuMCompVmRightData.gpuName}`) : `${gpuMCompVmRightData.gpuName}`.localeCompare(`${gpuMCompVmLeftData.gpuName}`); }); break; case 'sizeDelta': - this.gpuMemoryClickTable!.recycleDataSource = array.sort((gpuMCompVmLeftData, gpuMCompVmRightData) => { + this.gpuMemoryClickTables!.recycleDataSource = array.sort((gpuMCompVmLeftData, gpuMCompVmRightData) => { return sort === 1 ? gpuMCompVmLeftData.value - gpuMCompVmRightData.value : gpuMCompVmRightData.value - gpuMCompVmLeftData.value; @@ -162,7 +162,7 @@ export class TabPaneGpuMemoryVmTrackerComparison extends BaseElement { initHtml(): string { return ` - + diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuResourceVmTracker.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuResourceVmTracker.ts index 6677de14574612c540231ec15a171469a5f62514..a7e3dc96631a27c230f32810ca39bf8251f95a42 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuResourceVmTracker.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneGpuResourceVmTracker.ts @@ -15,11 +15,11 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; -import { queryGpuResourceTabData } from '../../../../database/SqlLite'; import { getByteWithUnit } from '../../../../database/logic-worker/ProcedureLogicWorkerCommon'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { resizeObserver } from '../SheetUtils'; +import {queryGpuResourceTabData} from "../../../../database/sql/Gpu.sql"; @element('tabpane-gpu-resource') export class TabPaneGpuResourceVmTracker extends BaseElement { private gpuResourceTable: LitTable | undefined | null; diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgPinComparisonVM.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgPinComparisonVM.ts index cf0c20e106cf022c8dd07555f7cda1e5a0c70df4..58fa1abeb80bfea3e8349fe3bf7ab767ebdc65aa 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgPinComparisonVM.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgPinComparisonVM.ts @@ -18,25 +18,25 @@ import { type LitSelect } from '../../../../../base-ui/select/LitSelect'; import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { queryProcessPurgeableSelectionTab } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { CompareStruct, compare, resizeObserverFromMemory } from '../SheetUtils'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import {queryProcessPurgeableSelectionTab} from "../../../../database/sql/ProcessThread.sql"; @element('tabpane-purgeable-pin-comparison-vm') export class TabPanePurgPinComparisonVM extends BaseElement { - private purgeablePinTable: LitTable | null | undefined; + private purgeablePinTables: LitTable | null | undefined; private purgeablePinSource: Array = []; private filterEl: TabPaneJsMemoryFilter | undefined | null; private selectEl: LitSelect | undefined | null; public initElements(): void { - this.purgeablePinTable = this.shadowRoot?.querySelector('#tb-purgeable-pin'); + this.purgeablePinTables = this.shadowRoot?.querySelector('#tb-purgeable-pin'); this.filterEl = this.shadowRoot!.querySelector('#filter'); this.selectEl = this.filterEl?.shadowRoot?.querySelector('lit-select'); } public totalData(data: SelectionParam | any, dataList: any): void { //@ts-ignore - this.purgeablePinTable?.shadowRoot?.querySelector('.table')?.style?.height = `${ + this.purgeablePinTables?.shadowRoot?.querySelector('.table')?.style?.height = `${ this.parentElement!.clientHeight - 45 }px`; this.purgeablePinSource = []; @@ -80,9 +80,9 @@ export class TabPanePurgPinComparisonVM extends BaseElement { let tableData = await this.queryPinVMData(baseTime, targetTime); this.purgeablePinSource.push(tableData); if (this.purgeablePinSource.length > 0) { - this.purgeablePinTable!.recycleDataSource = this.purgeablePinSource; + this.purgeablePinTables!.recycleDataSource = this.purgeablePinSource; } else { - this.purgeablePinTable!.recycleDataSource = []; + this.purgeablePinTables!.recycleDataSource = []; } } private async queryPinVMData(baseTime: number, targetTime: number): Promise { @@ -117,15 +117,15 @@ export class TabPanePurgPinComparisonVM extends BaseElement { public connectedCallback(): void { super.connectedCallback(); - resizeObserverFromMemory(this.parentElement!, this.purgeablePinTable!, this.filterEl!); + resizeObserverFromMemory(this.parentElement!, this.purgeablePinTables!, this.filterEl!); } public initHtml(): string { return ` diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgTotalComparisonVM.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgTotalComparisonVM.ts index 4878985211de127f0b19689fd58234bc201caa4d..4bcad116abd1549ef287e92ae144fdef09c38532 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgTotalComparisonVM.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPanePurgTotalComparisonVM.ts @@ -18,25 +18,27 @@ import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; -import { queryProcessPurgeableSelectionTab } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { CompareStruct, compare, resizeObserverFromMemory } from '../SheetUtils'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; +import { queryProcessPurgeableSelectionTab } from '../../../../database/sql/ProcessThread.sql'; + @element('tabpane-purgeable-total-comparison-vm') export class TabPanePurgTotalComparisonVM extends BaseElement { - private purgeableTotalTable: LitTable | null | undefined; + private purgeableTotalTables: LitTable | null | undefined; private purgeableTotalSource: Array = []; private filterEl: TabPaneJsMemoryFilter | undefined | null; private selectEl: LitSelect | undefined | null; public initElements(): void { - this.purgeableTotalTable = this.shadowRoot?.querySelector('#tb-purgeable-total'); + this.purgeableTotalTables = this.shadowRoot?.querySelector('#tb-purgeable-total'); this.filterEl = this.shadowRoot!.querySelector('#filter'); this.selectEl = this.filterEl?.shadowRoot?.querySelector('lit-select'); } + public totalData(data: SelectionParam | any, dataList: any): void { //@ts-ignore - this.purgeableTotalTable?.shadowRoot?.querySelector('.table')?.style?.height = `${ + this.purgeableTotalTables?.shadowRoot?.querySelector('.table')?.style?.height = `${ this.parentElement!.clientHeight - 45 }px`; this.purgeableTotalSource = []; @@ -48,8 +50,9 @@ export class TabPanePurgTotalComparisonVM extends BaseElement { } fileArr = fileArr.sort(); this.initSelect(data.startNs, fileArr); - this.updateComparisonData(data.startNs, fileArr[0].startNs); + this.updateComparisonsData(data.startNs, fileArr[0].startNs); } + private initSelect(fileStartNs: number, purgeTotalComList: Array): void { let that = this; let input = this.selectEl!.shadowRoot?.querySelector('input') as HTMLInputElement; @@ -68,25 +71,27 @@ export class TabPanePurgTotalComparisonVM extends BaseElement { a.addEventListener('onSelected', (e: any) => { for (let f of purgeTotalComList) { if (input.value === f.name) { - that.updateComparisonData(fileStartNs, f.startNs); + that.updateComparisonsData(fileStartNs, f.startNs); } } e.stopPropagation(); }); }); } - private async updateComparisonData(baseTime: number, targetTime: number): Promise { + + private async updateComparisonsData(baseTime: number, targetTime: number): Promise { this.purgeableTotalSource = []; let tableData = await this.queryTotalVMData(baseTime, targetTime); this.purgeableTotalSource.push(tableData); if (this.purgeableTotalSource.length > 0) { - this.purgeableTotalTable!.recycleDataSource = this.purgeableTotalSource; + this.purgeableTotalTables!.recycleDataSource = this.purgeableTotalSource; } else { - this.purgeableTotalTable!.recycleDataSource = []; + this.purgeableTotalTables!.recycleDataSource = []; } } + private async queryTotalVMData(baseTime: number, targetTime: number): Promise { - let delta = { + let deltas = { purgSumDelta: '0Bytes', shmPurgDelta: '0Bytes', }; @@ -105,27 +110,28 @@ export class TabPanePurgTotalComparisonVM extends BaseElement { let compareData = compare(targetArr, baseArr); for (let data of compareData) { if (data.key === 'TotalPurg') { - delta.purgSumDelta = Utils.getBinaryByteWithUnit(data.value); + deltas.purgSumDelta = Utils.getBinaryByteWithUnit(data.value); } else if (data.key === 'ShmPurg') { - delta.shmPurgDelta = Utils.getBinaryByteWithUnit(data.value); + deltas.shmPurgDelta = Utils.getBinaryByteWithUnit(data.value); } } }); }); - return delta; + return deltas; } public connectedCallback(): void { super.connectedCallback(); - resizeObserverFromMemory(this.parentElement!, this.purgeableTotalTable!, this.filterEl!); + resizeObserverFromMemory(this.parentElement!, this.purgeableTotalTables!, this.filterEl!); } + public initHtml(): string { return ` diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShm.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShm.ts index ec647f6daafa6c327859ef6cb959e44debad64c7..a83412bd9baeb12fe018335335a14552379db993 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShm.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShm.ts @@ -15,10 +15,10 @@ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; import { type SelectionParam } from '../../../../bean/BoxSelection'; -import { queryVmTrackerShmSizeData } from '../../../../database/SqlLite'; import { Utils } from '../../base/Utils'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; +import {queryVmTrackerShmSizeData} from "../../../../database/sql/Memory.sql"; @element('tabpane-vmtracker-shm') export class TabPaneVmTrackerShm extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmComparison.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmComparison.ts index 18ebc96814f7a9319beda4533acb79adcf200935..df8c2930d5e127cdaa32c1f1ebb6cddc43a4ec70 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmComparison.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmComparison.ts @@ -14,7 +14,6 @@ */ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { type LitTable } from '../../../../../base-ui/table/lit-table'; -import { queryVmTrackerShmSelectionData } from '../../../../database/SqlLite'; import { type SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; @@ -23,6 +22,7 @@ import { LitSelectOption } from '../../../../../base-ui/select/LitSelectOption'; import { type LitSelect } from '../../../../../base-ui/select/LitSelect'; import { type TabPaneJsMemoryFilter } from '../TabPaneJsMemoryFilter'; import { resizeObserverFromMemory } from '../SheetUtils'; +import {queryVmTrackerShmSelectionData} from "../../../../database/sql/Memory.sql"; @element('tabpane-vmtracker-shm-comparison') export class TabPaneVmTrackerShmComparison extends BaseElement { diff --git a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmSelection.ts b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmSelection.ts index 03b2c464d4323a2f6f7984626824b9a6320191fe..76131e3ce0e2b0d6a64e424546a000d553414d43 100644 --- a/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmSelection.ts +++ b/ide/src/trace/component/trace/sheet/vmtracker/TabPaneVmTrackerShmSelection.ts @@ -14,12 +14,12 @@ */ import { BaseElement, element } from '../../../../../base-ui/BaseElement'; import { LitTable } from '../../../../../base-ui/table/lit-table'; -import { queryVmTrackerShmSelectionData } from '../../../../database/SqlLite'; import { SpSystemTrace } from '../../../SpSystemTrace'; import { Utils } from '../../base/Utils'; import { SnapshotStruct } from '../../../../database/ui-worker/ProcedureWorkerSnapshot'; import { MemoryConfig } from '../../../../bean/MemoryConfig'; import { ns2s } from '../../../../database/ui-worker/ProcedureWorkerCommon'; +import {queryVmTrackerShmSelectionData} from "../../../../database/sql/Memory.sql"; @element('tabpane-vmtracker-shm-selection') export class TabPaneVmTrackerShmSelection extends BaseElement { @@ -83,82 +83,34 @@ export class TabPaneVmTrackerShmSelection extends BaseElement { } } + private compareValues(a: any, b: any, sort: number): number { + if (sort === 1) { + return a > b ? 1 : a < b ? -1 : 0; + } else { + return a < b ? 1 : a > b ? -1 : 0; + } + } + sortByColumn(column: string, sort: number): void { - switch (sort) { - case 0: - this.TableEl!.snapshotDataSource = this.shmData; - break; - default: - let arr = [...this.shmData]; - switch (column) { - case 'ts': - this.TableEl!.snapshotDataSource = arr.sort((leftTs, rightTs) => { - return sort === 1 ? leftTs.startNS - rightTs.startNS : rightTs.startNS - leftTs.startNS; - }); - break; - case 'fd': - this.TableEl!.snapshotDataSource = arr.sort((leftFd, rightFd) => { - return sort === 1 ? leftFd.fd - rightFd.fd : rightFd.fd - leftFd.fd; - }); - break; - case 'sizeStr': - this.TableEl!.snapshotDataSource = arr.sort((leftSize, rightSize) => { - return sort === 1 ? leftSize.size - rightSize.size : rightSize.size - leftSize.size; - }); - break; - case 'adj': - this.TableEl!.snapshotDataSource = arr.sort((leftAdj, rightAdj) => { - return sort === 1 ? leftAdj.adj - rightAdj.adj : rightAdj.adj - leftAdj.adj; - }); - break; - case 'name': - this.TableEl!.snapshotDataSource = arr.sort((leftName, rightName) => { - if (sort === 1) { - if (leftName.name > rightName.name) { - return 1; - } else if (leftName.name === rightName.name) { - return 0; - } else { - return -1; - } - } else { - if (rightName.name > leftName.name) { - return 1; - } else if (leftName.name === rightName.name) { - return 0; - } else { - return -1; - } - } - }); - break; - case 'id': - this.TableEl!.snapshotDataSource = arr.sort((leftId, rightId) => { - return sort === 1 ? leftId.id - rightId.id : rightId.id - leftId.id; - }); - break; - case 'time': - this.TableEl!.snapshotDataSource = arr.sort((leftTime, rightTime) => { - return sort === 1 ? leftTime.time - rightTime.time : rightTime.time - leftTime.time; - }); - break; - case 'count': - this.TableEl!.snapshotDataSource = arr.sort((leftCount, rightCount) => { - return sort === 1 ? leftCount.count - rightCount.count : rightCount.count - leftCount.count; - }); - break; - case 'purged': - this.TableEl!.snapshotDataSource = arr.sort((leftPurged, rightPurged) => { - return sort === 1 ? leftPurged.purged - rightPurged.purged : rightPurged.purged - leftPurged.purged; - }); - break; - case 'flag': - this.TableEl!.snapshotDataSource = arr.sort((leftFlag, rightFlag) => { - return sort === 1 ? leftFlag.flag - rightFlag.flag : rightFlag.flag - leftFlag.flag; - }); - break; - } - break; + const comparisonFunctions: { [key: string]: (a: any, b: any) => number } = { + 'ts': (a, b) => this.compareValues(a.startNS, b.startNS, sort), + 'fd': (a, b) => this.compareValues(a.fd, b.fd, sort), + 'sizeStr': (a, b) => this.compareValues(a.size, b.size, sort), + 'adj': (a, b) => this.compareValues(a.adj, b.adj, sort), + 'name': (a, b) => this.compareValues(a.name, b.name, sort), + 'id': (a, b) => this.compareValues(a.id, b.id, sort), + 'time': (a, b) => this.compareValues(a.time, b.time, sort), + 'count': (a, b) => this.compareValues(a.count, b.count, sort), + 'purged': (a, b) => this.compareValues(a.purged, b.purged, sort), + 'flag': (a, b) => this.compareValues(a.flag, b.flag, sort) + }; + + if (sort === 0) { + this.TableEl!.snapshotDataSource = this.shmData; + } else { + const array = [...this.shmData]; + const comparisonFunction = comparisonFunctions[column] || (() => 0); + this.TableEl!.snapshotDataSource = array.sort(comparisonFunction); } } diff --git a/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts b/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts index 029e860fee473d34d6fa2eaa06ed4456cce74861..5c6dfb707242537f271d47b8434deba697bd3f71 100644 --- a/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts +++ b/ide/src/trace/component/trace/timer-shaft/RangeRuler.ts @@ -17,7 +17,7 @@ import { Graph } from './Graph'; import { Rect } from './Rect'; import { ns2s, ns2UnitS, TimerShaftElement } from '../TimerShaftElement'; import { ColorUtils, interpolateColorBrightness } from '../base/ColorUtils'; -import { CpuStruct } from '../../../database/ui-worker/ProcedureWorkerCPU'; +import { CpuStruct } from '../../../database/ui-worker/cpu/ProcedureWorkerCPU'; import { CurrentSlicesTime, SpSystemTrace } from '../../SpSystemTrace'; const MarkPadding = 5; diff --git a/ide/src/trace/database/Procedure.ts b/ide/src/trace/database/Procedure.ts index 07312db0669c906fdcf286aedc4a9d6f952b83a1..36bc14d68899e8c9bcb6f0b5bcfe26b5295c62f9 100644 --- a/ide/src/trace/database/Procedure.ts +++ b/ide/src/trace/database/Procedure.ts @@ -135,7 +135,7 @@ class ProcedurePool { return newThread; } - logicDataThread() { + private logicDataThread(): ProcedureThread | undefined { // @ts-ignore if (window.useWb) { return; @@ -146,6 +146,16 @@ class ProcedurePool { }) ); thread.name = this.logicDataHandles[this.works.length - this.names.length]; + this.sendMessage(thread); + thread.worker!.onmessageerror = (e) => {}; + thread.worker!.onerror = (e) => {}; + thread.id = this.works.length; + thread.busy = false; + this.works?.push(thread); + return thread; + } + + private sendMessage(thread: ProcedureThread): void { thread.worker!.onmessage = (event: MessageEvent) => { thread.busy = false; if (event.data.isQuery) { @@ -184,12 +194,6 @@ class ProcedurePool { this.onComplete(); } }; - thread.worker!.onmessageerror = (e) => {}; - thread.worker!.onerror = (e) => {}; - thread.id = this.works.length; - thread.busy = false; - this.works?.push(thread); - return thread; } close = () => { diff --git a/ide/src/trace/database/SqlLite.ts b/ide/src/trace/database/SqlLite.ts index 76d5ce2773d122d5bdbd2ee9a1214a376bf708c0..33a1baeb2170e3359878435f3742a9a70660466e 100644 --- a/ide/src/trace/database/SqlLite.ts +++ b/ide/src/trace/database/SqlLite.ts @@ -12,81 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import { Counter, Fps, SelectionData } from '../bean/BoxSelection'; -import { WakeupBean } from '../bean/WakeupBean'; -import { BinderArgBean } from '../bean/BinderArgBean'; -import { SPTChild } from '../bean/StateProcessThread'; -import { CpuUsage, Freq } from '../bean/CpuUsage'; - -import { - NativeEvent, - NativeEventHeap, - NativeHookMalloc, - NativeHookProcess, - NativeHookSampleQueryInfo, - NativeHookStatistics, -} from '../bean/NativeHook'; -import { - Dma, - DmaComparison, - GpuMemory, - GpuMemoryComparison, - LiveProcess, - ProcessHistory, - SystemCpuSummary, - SystemDiskIOSummary, - SystemNetworkSummary, -} from '../bean/AbilityMonitor'; -import { PerfCall, PerfCallChain, PerfCmdLine, PerfFile, PerfSample, PerfStack, PerfThread } from '../bean/PerfProfile'; -import { SearchFuncBean } from '../bean/SearchFuncBean'; -import { CounterSummary, SdkSliceSummary } from '../bean/SdkSummary'; -import { Smaps } from '../bean/SmapsStruct'; -import { CpuFreqRowLimit } from '../component/chart/SpFreqChart'; -import { CpuFreqLimitsStruct } from './ui-worker/ProcedureWorkerCpuFreqLimits'; -import { CpuStruct } from './ui-worker/ProcedureWorkerCPU'; -import { CpuFreqStruct } from './ui-worker/ProcedureWorkerFreq'; -import { ThreadStruct } from './ui-worker/ProcedureWorkerThread'; -import { FuncStruct } from './ui-worker/ProcedureWorkerFunc'; -import { ProcessMemStruct } from './ui-worker/ProcedureWorkerMem'; -import { FpsStruct } from './ui-worker/ProcedureWorkerFPS'; -import { CpuAbilityMonitorStruct } from './ui-worker/ProcedureWorkerCpuAbility'; -import { MemoryAbilityMonitorStruct } from './ui-worker/ProcedureWorkerMemoryAbility'; -import { DiskAbilityMonitorStruct } from './ui-worker/ProcedureWorkerDiskIoAbility'; -import { NetworkAbilityMonitorStruct } from './ui-worker/ProcedureWorkerNetworkAbility'; -import { EnergyAnomalyStruct } from './ui-worker/ProcedureWorkerEnergyAnomaly'; -import { EnergyStateStruct } from './ui-worker/ProcedureWorkerEnergyState'; -import { CounterStruct } from './ui-worker/ProduceWorkerSdkCounter'; -import { SdkSliceStruct } from './ui-worker/ProduceWorkerSdkSlice'; -import { SystemDetailsEnergy } from '../bean/EnergyStruct'; -import { ClockStruct } from './ui-worker/ProcedureWorkerClock'; -import { IrqStruct } from './ui-worker/ProcedureWorkerIrq'; -import { - HeapEdge, - HeapLocation, - HeapNode, - HeapSample, - HeapTraceFunctionInfo, -} from '../../js-heap/model/DatabaseStruct'; -import { FileInfo } from '../../js-heap/model/UiStruct'; -import { AppStartupStruct } from './ui-worker/ProcedureWorkerAppStartup'; -import { SoStruct } from './ui-worker/ProcedureWorkerSoInit'; -import { HeapTreeDataBean } from './logic-worker/ProcedureLogicWorkerCommon'; -import { TaskTabStruct } from '../component/trace/sheet/task/TabPaneTaskFrames'; -import { LogStruct } from './ui-worker/ProcedureWorkerLog'; -import { HiSysEventStruct } from './ui-worker/ProcedureWorkerHiSysEvent'; -import { info } from '../../log/Log'; -import { type DeviceStruct } from '../bean/FrameComponentBean'; -import { type FrameSpacingStruct } from './ui-worker/ProcedureWorkerFrameSpacing'; -import { type FrameDynamicStruct } from './ui-worker/ProcedureWorkerFrameDynamic'; -import { type FrameAnimationStruct } from './ui-worker/ProcedureWorkerFrameAnimation'; -import { type SnapshotStruct } from './ui-worker/ProcedureWorkerSnapshot'; -import { type MemoryConfig } from '../bean/MemoryConfig'; -import { KeyPathStruct } from '../bean/KeyPathStruct'; -import { JanksStruct } from '../bean/JanksStruct'; -import { FuncNameCycle, BinderItem } from '../bean/BinderProcessThread'; -import { GpuCountBean, SearchGpuFuncBean } from '../bean/GpufreqBean'; - class DataWorkerThread { taskMap: any = {}; worker?: Worker; @@ -524,6279 +449,3 @@ export function query( ); }); } - -export const queryEventCountMap = (): Promise< - Array<{ - eventName: string; - count: number; - }> -> => query('queryEventCountMap', `select event_name as eventName,count from stat where stat_type = 'received';`); - -export const queryProcess = (): Promise< - Array<{ - pid: number | null; - processName: string | null; - }> -> => - query( - 'queryProcess', - ` - SELECT - pid, processName - FROM - temp_query_process where pid != 0` - ); - -export const queryProcessByTable = (): Promise< - Array<{ - pid: number | null; - processName: string | null; - }> -> => - query( - 'queryProcessByTable', - ` - SELECT - pid, name as processName - FROM - process where pid != 0` - ); -export const queryAllFuncNames = (): Promise> => { - return query( - 'queryAllFuncNames', - ` - select id,name from callstack;` - ); -}; -export const queryProcessAsyncFunc = (_funName?: string): Promise> => - query( - 'queryProcessAsyncFunc', - ` -select tid, - P.pid, - A.name as threadName, - is_main_thread, - c.callid as track_id, - c.ts-D.start_ts as startTs, - c.dur, - c.name as funName, - c.parent_id, - c.id, - c.cookie, - c.depth, - c.argsetid -from thread A,trace_range D -left join callstack C on A.id = C.callid -left join process P on P.id = A.ipid -where startTs not null and cookie not null ${_funName ? 'funName=$funName' : ''};`, - { - funName: _funName, - } - ); - -export const queryTotalTime = (): Promise> => - query( - 'queryTotalTime', - ` - select - start_ts as recordStartNS,end_ts as recordEndNS,end_ts-start_ts as total - from - trace_range;` - ); - -export const getCpuUtilizationRate = ( - startNS: number, - endNS: number -): Promise< - Array<{ - cpu: number; - ro: number; - rate: number; - }> -> => - query( - 'getCpuUtilizationRate', - ` - with cpu as ( - select - cpu, - ts, - dur, - (case when ro < 99 then ro else 99 end) as ro , - (case when ro < 99 then stime+ro*cell else stime + 99 * cell end) as st, - (case when ro < 99 then stime + (ro+1)*cell else etime end) as et - from ( - select - cpu, - ts, - A.dur, - ((ts+A.dur)-D.start_ts)/((D.end_ts-D.start_ts)/100) as ro, - D.start_ts as stime, - D.end_ts etime, - (D.end_ts-D.start_ts)/100 as cell - from - sched_slice A - left join - trace_range D - left join - thread B on A.itid = B.id - where - tid != 0 - and (A.ts) - between D.start_ts and D.end_ts)) - select cpu,ro, - sum(case - when ts <= st and ts + dur <= et then (ts + dur - st) - when ts <= st and ts + dur > et then et-st - when ts > st and ts + dur <= et then dur - when ts > st and ts + dur > et then et - ts end)/cast(et-st as float) as rate - from cpu - group by cpu,ro;`, - {} - ); - -export const getFps = () => - query( - 'getFps', - ` - select - distinct(ts-tb.start_ts) as startNS, fps - from - hidump c ,trace_range tb - where - startNS >= 0 - --order by startNS; - `, - {} - ); - -export const getFunDataByTid = (tid: number, ipid: number): Promise> => - query( - 'getFunDataByTid', - ` - select - c.ts-D.start_ts as startTs, - c.dur, - c.name as funName, - c.argsetid, - c.depth, - c.id as id, - A.itid as itid, - A.ipid as ipid -from thread A,trace_range D -left join callstack C on A.id = C.callid -where startTs not null and c.cookie is null and tid = $tid and A.ipid = $ipid`, - { $tid: tid, $ipid: ipid } - ); - -export const getMaxDepthByTid = (): Promise> => - query( - 'getMaxDepthByTid', - ` - select -tid, -ipid, - MAX(c.depth + 1) as maxDepth -from thread A -left join callstack C on A.id = C.callid -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 -): Promise> => { - let condition = ` - ${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, - IP.pid as processId, - A.name as thread, - B.state as state, - A.tid as threadId, - B.dur as duration, - B.ts - TR.start_ts as startNs, - B.cpu, - C.priority - from - thread_state AS B - left join - thread as A - on - B.itid = A.itid - left join - process AS IP - on - A.ipid = IP.ipid - left join - trace_range AS TR - left join - sched_slice as C - on - B.itid = C.itid - and - C.ts = B.ts - where - B.dur > 0 - and - IP.pid not null - and - 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( - 'getTabCpuUsage', - ` - select - cpu, - sum(case - when (A.ts - B.start_ts) < $leftNS - then (A.ts - B.start_ts + A.dur - $leftNS) - when (A.ts - B.start_ts) >= $leftNS - and (A.ts - B.start_ts + A.dur) <= $rightNS - then A.dur - when (A.ts - B.start_ts + A.dur) > $rightNS - then ($rightNS - (A.ts - B.start_ts)) end) / cast($rightNS - $leftNS as float) as usage - from - thread_state A, - trace_range B - where - (A.ts - B.start_ts) > 0 and A.dur > 0 - and - cpu in (${cpus.join(',')}) - and - (A.ts - B.start_ts + A.dur) > $leftNS - and - (A.ts - B.start_ts) < $rightNS - group by - cpu`, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabCpuFreq = (cpus: Array, leftNs: number, rightNs: number): Promise> => - query( - 'getTabCpuFreq', - ` - select - cpu, - value, - (ts - tr.start_ts) as startNs - from - measure m, - trace_range tr - inner join - cpu_measure_filter t - on - m.filter_id = t.id - where - (name = 'cpufreq' or name='cpu_frequency') - and - cpu in (${cpus.join(',')}) - and - startNs > 0 - and - startNs < $rightNS - --order by startNs - `, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabFps = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabFps', - ` - select - distinct(ts-tb.start_ts) as startNS, - fps - from - hidump c, - trace_range tb - where - startNS <= $rightNS - and - startNS >= 0 - --order by startNS; - `, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabCounters = (processFilterIds: Array, virtualFilterIds: Array, startTime: number) => { - let processSql = `select - t1.filter_id as trackId, - t2.name, - value, - t1.ts - t3.start_ts as startTime - from - process_measure t1 - left join - process_measure_filter t2 - on - t1.filter_id = t2.id - left join - trace_range t3 - where - filter_id in (${processFilterIds.join(',')}) - and - startTime <= ${startTime}`; - let virtualSql = `select - t1.filter_id as trackId, - t2.name, - value, - t1.ts - t3.start_ts as startTime - from - sys_mem_measure t1 - left join - sys_event_filter t2 - on - t1.filter_id = t2.id - left join - trace_range t3 - where - filter_id in (${virtualFilterIds.join(',')}) - and - startTime <= ${startTime}`; - let sql = ''; - if (processFilterIds.length > 0 && virtualFilterIds.length > 0) { - sql = `${processSql} union ${virtualSql}`; - } else { - if (processFilterIds.length > 0) { - sql = processSql; - } else { - sql = virtualSql; - } - } - return query('getTabCounters', sql, {}); -}; - -export const getTabVirtualCounters = (virtualFilterIds: Array, startTime: number) => - query( - 'getTabVirtualCounters', - ` - select - table1.filter_id as trackId, - table2.name, - value, - table1.ts - table3.start_ts as startTime - from - sys_mem_measure table1 - left join - sys_event_filter table2 - on - table1.filter_id = table2.id - left join - trace_range table3 - where - filter_id in (${virtualFilterIds.join(',')}) - and - startTime <= $startTime - `, - { $startTime: startTime } - ); - -export const getTabCpuByProcess = (cpus: Array, leftNS: number, rightNS: number) => - query( - 'getTabCpuByProcess', - ` - select - B.pid as pid, - sum(B.dur) as wallDuration, - avg(B.dur) as avgDuration, - count(B.tid) as occurrences - from - thread_state AS B - left join - trace_range AS TR - where - B.cpu in (${cpus.join(',')}) - and - not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS )) - group by - B.pid - order by - wallDuration desc;`, - { $rightNS: rightNS, $leftNS: leftNS } - ); - -export const getTabCpuByThread = (cpus: Array, leftNS: number, rightNS: number) => - query( - 'getTabCpuByThread', - ` - select - TS.pid as pid, - TS.tid as tid, - TS.cpu, - sum( min(${rightNS},(TS.ts - TR.start_ts + TS.dur)) - max(${leftNS},TS.ts - TR.start_ts)) wallDuration, - count(TS.tid) as occurrences - from - thread_state AS TS - left join - trace_range AS TR - where - TS.cpu in (${cpus.join(',')}) - and - not ((TS.ts - TR.start_ts + TS.dur < $leftNS) or (TS.ts - TR.start_ts > $rightNS)) - group by - TS.cpu, - TS.pid, - TS.tid - order by - wallDuration desc;`, - { $rightNS: rightNS, $leftNS: leftNS } - ); - -export const getTabSlices = ( - funTids: Array, - pids: Array, - leftNS: number, - rightNS: number -): Promise> => - query( - 'getTabSlices', - ` - select - c.name as name, - sum(c.dur) as wallDuration, - avg(c.dur) as avgDuration, - count(c.name) as occurrences - from - thread T, trace_range TR - left join process P on T.ipid = P.id - left join - callstack C - on - T.id = C.callid - where - C.ts > 0 - and - c.dur >= 0 - and - T.tid in (${funTids.join(',')}) - and - P.pid in (${pids.join(',')}) - and - c.cookie is null - and - not ((C.ts - TR.start_ts + C.dur < $leftNS) or (C.ts - TR.start_ts > $rightNS)) - group by - c.name - order by - wallDuration desc;`, - { $leftNS: leftNS, $rightNS: rightNS } - ); - -export const getTabSlicesAsyncFunc = ( - asyncNames: Array, - asyncPid: Array, - leftNS: number, - rightNS: number -): Promise> => - query( - 'getTabSlicesAsyncFunc', - ` - select - c.name as name, - sum(c.dur) as wallDuration, - avg(c.dur) as avgDuration, - count(c.name) as occurrences - from - thread A, trace_range D - left join - callstack C - on - A.id = C.callid - left join process P on P.id = A.ipid - where - C.ts > 0 - and - c.dur >= -1 - and - c.cookie not null - and - P.pid in (${asyncPid.join(',')}) - and - c.name in (${asyncNames.map((it) => "'" + it + "'").join(',')}) - and - not ((C.ts - D.start_ts + C.dur < $leftNS) or (C.ts - D.start_ts > $rightNS)) - group by - c.name - order by - wallDuration desc;`, - { $leftNS: leftNS, $rightNS: rightNS } - ); - -export const getTabThreadStates = (tIds: Array, leftNS: number, rightNS: number): Promise> => - query( - 'getTabThreadStates', - ` - select - B.pid, - B.tid, - B.state, - sum(B.dur) as wallDuration, - avg(ifnull(B.dur,0)) as avgDuration, - count(B.tid) as occurrences - from - thread_state AS B - left join - trace_range AS TR - where - B.tid in (${tIds.join(',')}) - and - not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS)) - group by - B.pid, B.tid, B.state - order by - wallDuration desc;`, - { $leftNS: leftNS, $rightNS: rightNS } - ); - -// 查询线程状态详细信息 -export const getTabThreadStatesDetail = (tIds: Array, leftNS: number, rightNS: number): Promise> => - query( - 'getTabThreadStates', - `select - B.pid, - B.tid, - B.state, - B.ts, - B.dur - from - thread_state AS B - left join - trace_range AS TR - where - B.tid in (${tIds.join(',')}) - and - not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS)) - order by ts;`, - { $leftNS: leftNS, $rightNS: rightNS } - ); - -// 框选区域内running的时间 -export const getTabRunningPersent = (tIds: Array, leftNS: number, rightNS: number): Promise> => - query( - 'getTabRunningPersent', - ` - select - B.pid, - B.tid, - B.state, - B.cpu, - B.dur, - B.ts - from - thread_state AS B - left join - trace_range AS TR - where - B.tid in (${tIds.join(',')}) - and - B.state='Running' - and - not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) - order by - ts;`, - { $leftNS: leftNS, $rightNS: rightNS } - ); -// 框选区域内sleeping的时间 -export const getTabSleepingTime = (tIds: Array, leftNS: number, rightNS: number): Promise> => - query( - 'getTabRunningPersent', - ` - select - B.pid, - B.tid, - B.state, - B.cpu, - B.dur, - B.ts - from - thread_state AS B - left join - trace_range AS TR - where - B.tid in (${tIds.join(',')}) - and - B.state='Sleeping' - and - not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) - order by - ts;`, - { $leftNS: leftNS, $rightNS: rightNS } - ); - -export const getTabThreadStatesCpu = (tIds: Array, leftNS: number, rightNS: number): Promise> => { - let sql = ` -select - B.pid, - B.tid, - B.cpu, - sum( min(${rightNS},(B.ts - TR.start_ts + B.dur)) - max(${leftNS},B.ts - TR.start_ts)) wallDuration -from thread_state as B -left join trace_range as TR -where cpu notnull - and B.tid in (${tIds.join(',')}) - and not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) -group by B.tid, B.pid, B.cpu;`; - return query('getTabThreadStatesCpu', sql, { - $leftNS: leftNS, - $rightNS: rightNS, - }); -}; - -export const getTabStartups = (ids: Array, leftNS: number, rightNS: number): Promise> => { - let sql = ` -select - P.pid, - P.name as process, - (A.start_time - B.start_ts) as startTs, - (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur, - A.start_name as startName -from app_startup A,trace_range B -left join process P on A.ipid = P.ipid -where P.pid in (${ids.join(',')}) -and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS})) -order by start_name;`; - return query('getTabStartups', sql, {}); -}; - -export const getTabStaticInit = (ids: Array, leftNS: number, rightNS: number): Promise> => { - let sql = ` -select - P.pid, - P.name as process, - (A.start_time - B.start_ts) as startTs, - (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur, - A.so_name as soName -from static_initalize A,trace_range B -left join process P on A.ipid = P.ipid -where P.pid in (${ids.join(',')}) -and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS})) -order by dur desc;`; - return query('getTabStaticInit', sql, {}); -}; - -export const queryBinderArgsByArgset = (argset: number): Promise> => - query( - 'queryBinderArgsByArgset', - ` - select - * - from - args_view - where - argset = $argset;`, - { $argset: argset } - ); - -export const queryCpuData = (cpu: number, startNS: number, endNS: number): Promise> => - query( - 'queryCpuData', - ` - SELECT - B.pid as processId, - B.cpu, - B.tid, - B.itid as id, - B.dur, - B.ts - TR.start_ts AS startTime, - B.arg_setid as argSetID -from thread_state AS B - left join trace_range AS TR -where B.itid is not null - and - B.cpu = $cpu - and - startTime between $startNS and $endNS;`, - { - $cpu: cpu, - $startNS: startNS, - $endNS: endNS, - } - ); - -export const queryCpuFreq = (): Promise> => - query( - 'queryCpuFreq', - ` - select - cpu,id as filterId - from - cpu_measure_filter - where - (name='cpufreq' or name='cpu_frequency') - order by cpu; - ` - ); - -export const queryCpuFreqData = (cpu: number): Promise> => - query( - 'queryCpuFreqData', - ` - select - cpu, - value, - ifnull(dur,tb.end_ts - c.ts) dur, - ts-tb.start_ts as startNS - from - measure c, - trace_range tb - inner join - cpu_measure_filter t - on - c.filter_id = t.id - where - (name = 'cpufreq' or name='cpu_frequency') - and - cpu= $cpu - --order by ts; - `, - { $cpu: cpu } - ); - -export const queryCpuMax = (): Promise> => - query( - 'queryCpuMax', - ` - select - cpu - from - sched_slice - order by - cpu - desc limit 1;` - ); - -export const queryCpuDataCount = () => - query('queryCpuDataCount', 'select count(1) as count,cpu from thread_state where cpu not null group by cpu'); - -export const queryCpuCount = (): Promise> => - query( - 'queryCpuCount', - ` - select max(cpuCount) cpuCount from -(select ifnull((max(cpu) + 1),0) cpuCount from cpu_measure_filter where name in ('cpu_frequency','cpu_idle') - union all - select ifnull((max(callid)+1),0) cpuCount from irq -) A;` - ); - -export const queryCpuSchedSlice = (): Promise> => - query( - 'queryCpuSchedSlice', - ` - select (ts - start_ts) as ts, - itid, - end_state as endState, - priority - from sched_slice,trace_range;` - ); - -export const queryCpuStateFilter = (): Promise> => - query( - 'queryCpuStateFilter', - `select cpu,id as filterId from cpu_measure_filter where name = 'cpu_idle' order by cpu;`, - {} - ); - -export const queryCpuState = (cpuFilterId: number): Promise> => - query( - 'queryCpuState', - ` - select (A.ts - B.start_ts) as startTs,ifnull(dur,B.end_ts - A.ts) dur, - value - from measure A,trace_range B - where filter_id = $filterId;`, - { $filterId: cpuFilterId } - ); - -export const queryCpuMaxFreq = (): Promise> => - query( - 'queryCpuMaxFreq', - ` - select - max(value) as maxFreq - from - measure c - inner join - cpu_measure_filter t - on - c.filter_id = t.id - where - (name = 'cpufreq' or name='cpu_frequency');` - ); - -export const queryProcessData = (pid: number, startNS: number, endNS: number): Promise> => - query( - 'queryProcessData', - ` - select ta.cpu, - dur, - ts-${(window as any).recordStartNS} as startTime -from thread_state ta -where ta.cpu is not null and pid=$pid and startTime between $startNS and $endNS;`, - { - $pid: pid, - $startNS: startNS, - $endNS: endNS, - } - ); - -export const queryProcessMem = (): Promise> => - query( - 'queryProcessMem', - ` - select - process_measure_filter.id as trackId, - process_measure_filter.name as trackName, - ipid as upid, - process.pid, - process.name as processName - from - process_measure_filter - join - process using (ipid) - order by trackName;` - ); - -export const queryProcessThreadDataCount = (): Promise> => - query( - `queryProcessThreadDataCount`, - `select pid,count(id) as count - from thread_state - where ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} group by pid;`, - {} - ); - -export const queryProcessFuncDataCount = (): Promise> => - query( - `queryProcessFuncDataCount`, - `select - P.pid, - count(tid) as count - from callstack C - left join thread A on A.id = C.callid - left join process AS P on P.id = A.ipid - where C.ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} - group by pid;`, - {} - ); - -export const queryProcessMemDataCount = (): Promise> => - query( - `queryProcessMemDataCount`, - `select - p.pid as pid, count(value) count - from process_measure c - left join process_measure_filter f on f.id = c.filter_id - left join process p on p.ipid = f.ipid -where f.id not NULL and value>0 - and c.ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} -group by p.pid`, - {} - ); - -export const queryProcessMemData = (trackId: number): Promise> => - query( - 'queryProcessMemData', - ` - select - c.type, - ts, - value, - filter_id as track_id, - c.ts-tb.start_ts startTime - from - process_measure c, - trace_range tb - where - filter_id = $id;`, - { $id: trackId } - ); - -export const queryThreads = (): Promise> => - query('queryThreads', `select id,tid,(ifnull(name,'Thread') || '(' || tid || ')') name from thread where id != 0;`); - -export const queryDataDICT = (): Promise> => query('queryDataDICT', `select * from data_dict;`); - -export const queryAppStartupProcessIds = (): Promise> => - query( - 'queryAppStartupProcessIds', - ` - SELECT pid FROM process - WHERE ipid IN ( - SELECT ipid FROM app_startup - UNION - SELECT t.ipid FROM app_startup a LEFT JOIN thread t ON a.call_id = t.itid -);` - ); - -export const queryTaskPoolProcessIds = (): Promise> => - query( - 'queryAppStartupProcessIds', - `SELECT pid -FROM - process -WHERE - ipid IN ( - SELECT DISTINCT - ( ipid ) - FROM - thread - WHERE - itid IN ( SELECT DISTINCT ( callid ) FROM callstack WHERE name LIKE 'H:Task%' ) - AND name = 'TaskWorkThread' - )` - ); - -export const queryProcessContentCount = (): Promise> => - query(`queryProcessContentCount`, `select pid,switch_count,thread_count,slice_count,mem_count from process;`); -export const queryProcessThreadsByTable = (): Promise> => - query( - 'queryProcessThreadsByTable', - ` - select p.pid as pid,p.ipid as upid,t.tid as tid,p.name as processName,t.name as threadName,t.switch_count as switchCount from thread t left join process p on t.ipid = p.id where t.tid != 0; - ` - ); -export const queryVirtualMemory = (): Promise> => - query('queryVirtualMemory', `select id,name from sys_event_filter where type='sys_virtual_memory_filter'`); -export const queryVirtualMemoryData = (filterId: number): Promise> => - query( - 'queryVirtualMemoryData', - `select ts-${ - (window as any).recordStartNS - } as startTime,value,filter_id as filterID from sys_mem_measure where filter_id=$filter_id`, - { $filter_id: filterId } - ); -export const queryProcessThreads = (): Promise> => - query( - 'queryProcessThreads', - ` - select - the_tracks.ipid as upid, - the_tracks.itid as utid, - total_dur as hasSched, - process.pid as pid, - thread.tid as tid, - process.name as processName, - thread.switch_count as switchCount, - thread.name as threadName - from ( - select ipid,itid from sched_slice group by itid - ) the_tracks - left join (select itid,sum(dur) as total_dur from thread_state where state != 'S' group by itid) using(itid) - left join thread using(itid) - left join process using(ipid) - order by total_dur desc,the_tracks.ipid,the_tracks.itid;`, - {} - ); - -export const queryThreadData = (tid: number, pid: number): Promise> => - query( - 'queryThreadData', - ` - select - B.itid as id - , B.tid - , B.cpu - , B.ts - TR.start_ts AS startTime - , B.dur - , B.state - , B.pid - , B.arg_setid as argSetID -from thread_state AS B - left join trace_range AS TR -where B.tid = $tid and B.pid = $pid;`, - { $tid: tid, $pid: pid } - ); - -export const queryStartupPidArray = (): Promise> => - query( - 'queryStartupPidArray', - ` - select distinct pid -from app_startup A,trace_range B left join process P on A.ipid = p.ipid -where A.start_time between B.start_ts and B.end_ts;`, - {} - ); - -export const queryProcessStartup = (pid: number): Promise> => - query( - 'queryProcessStartup', - ` - select - P.pid, - A.tid, - A.call_id as itid, - (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs, - (case - when A.start_time < B.start_ts then (A.end_time - B.start_ts) - when A.end_time = -1 then 0 - else (A.end_time - A.start_time) end) as dur, - A.start_name as startName -from app_startup A,trace_range B -left join process P on A.ipid = P.ipid -where P.pid = $pid -order by start_name;`, - { $pid: pid } - ); - -export const queryProcessAllAppStartup = (pids: Array): Promise> => - query( - 'queryProcessStartup', - ` - select - P.pid, - A.tid, - A.call_id as itid, - (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs, - (case - when A.start_time < B.start_ts then (A.end_time - B.start_ts) - when A.end_time = -1 then 0 - else (A.end_time - A.start_time) end) as dur, - A.start_name as startName -from app_startup A,trace_range B -left join process P on A.ipid = P.ipid -where P.pid in(${pids.join(',')}) -order by start_name;`, - { $pid: pids } - ); - -export const querySingleAppStartupsName = (pid: number): Promise> => - query( - 'queryAllAppStartupsName', - `select name from process - where pid=$pid`, - { $pid: pid } - ); - -export const queryProcessSoMaxDepth = (): Promise> => - query( - 'queryProcessSoMaxDepth', - `select p.pid,max(depth) maxDepth -from static_initalize S,trace_range B left join process p on S.ipid = p.ipid -where S.start_time between B.start_ts and B.end_ts -group by p.pid;`, - {} - ); - -export const queryAllSoInitNames = (): Promise> => { - return query( - 'queryAllSoInitNames', - ` - select id,so_name as name from static_initalize;` - ); -}; - -export const queryAllSrcSlices = (): Promise> => { - return query( - 'queryAllSrcSlices', - ` - select src,id from frame_slice;` - ); -}; - -export const queryAllThreadName = (): Promise> => { - return query( - 'queryAllThreadName', - ` - select name,tid from thread;` - ); -}; - -export const queryAllProcessNames = (): Promise> => { - return query( - 'queryAllProcessNames', - ` - select id, name, pid from process;` - ); -}; - -export const queryProcessSoInitData = (pid: number): Promise> => - query( - 'queryProcessSoInitData', - ` - select - P.pid, - T.tid, - A.call_id as itid, - (A.start_time - B.start_ts) as startTs, - (A.end_time - A.start_time) as dur, - A.so_name as soName, - A.depth -from static_initalize A,trace_range B -left join process P on A.ipid = P.ipid -left join thread T on A.call_id = T.itid -where P.pid = $pid;`, - { $pid: pid } - ); - -export const queryThreadAndProcessName = (): Promise> => - query( - 'queryThreadAndProcessName', - ` - select tid id,name,'t' type from thread -union all -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', - `This is the interval from when the task became eligible to run -(e.g.because of notifying a wait queue it was a suspended on) to when it started running.` - ); - -export const queryThreadWakeUp = (itid: number, startTime: number, dur: number): Promise> => - query( - 'queryThreadWakeUp', - ` -select TA.tid,min(TA.ts - TR.start_ts) as ts,TA.pid,TA.dur,TA.state,TA.cpu,TA.itid,TA.arg_setid as argSetID -from - (select min(ts) as wakeTs,ref as itid from instant,trace_range - where name = 'sched_wakeup' - and wakeup_from = $itid - and ts > start_ts + $startTime - and ts < start_ts + $startTime + $dur - group by ref - ) TW -left join thread_state TA on TW.itid = TA.itid -left join trace_range TR -where TA.ts > TW.wakeTs -group by TA.tid,TA.pid; - `, - { $itid: itid, $startTime: startTime, $dur: dur } - ); - -export const queryThreadNearData = (itid: number, startTime: number): Promise> => - query( - 'queryThreadNearData', - ` -select itid,tid,pid,cpu,state,arg_setid as argSetID,dur,max((A.ts - B.start_ts)) as startTime -from thread_state A,trace_range B -where itid = ${itid} -and (A.ts - B.start_ts) < ${startTime} and A.ts > B.start_ts -union -select itid,tid,pid,cpu,state,arg_setid as argSetID,dur,min((A.ts - B.start_ts)) as startTime -from thread_state A,trace_range B -where itid = ${itid} -and (A.ts - B.start_ts) > ${startTime} and A.ts < B.end_ts; - `, - {} - ); - -export const queryRunnableTimeByRunning = (tid: number, startTime: number): Promise> => { - let sql = ` -select ts from thread_state,trace_range where ts + dur -start_ts = ${startTime} and state = 'R' and tid=${tid} limit 1 - `; - return query('queryRunnableTimeByRunning', sql, {}); -}; - -export const queryThreadWakeUpFrom = (itid: number, startTime: number): Promise> => { - let sql = ` -select (A.ts - B.start_ts) as ts, - A.tid, - A.itid, - A.pid, - A.cpu, - A.dur, - A.arg_setid as argSetID -from thread_state A,trace_range B -where A.state = 'Running' -and A.itid = (select wakeup_from from instant where ts = ${startTime} and ref = ${itid} limit 1) -and (A.ts - B.start_ts) < (${startTime} - B.start_ts) -order by ts desc limit 1 - `; - return query('queryThreadWakeUpFrom', sql, {}); -}; -/*-------------------------------------------------------------------------------------*/ - -export const queryHeapGroupByEvent = (type: string): Promise> => { - let sql1 = ` - select - event_type as eventType, - sum(heap_size) as sumHeapSize - from native_hook - where event_type = 'AllocEvent' or event_type = 'MmapEvent' - group by event_type - `; - let sql2 = ` - select (case when type = 0 then 'AllocEvent' else 'MmapEvent' end) eventType, - sum(apply_size) sumHeapSize - from native_hook_statistic - group by eventType; - `; - return query('queryHeapGroupByEvent', type === 'native_hook' ? sql1 : sql2, {}); -}; - -export const queryAllHeapByEvent = (): Promise> => - query( - 'queryAllHeapByEvent', - ` - select * from ( - select h.start_ts - t.start_ts as startTime, - h.heap_size as heapSize, - h.event_type as eventType -from native_hook h ,trace_range t -where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts -and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent') -union -select h.end_ts - t.start_ts as startTime, - h.heap_size as heapSize, - (case when h.event_type = 'AllocEvent' then 'FreeEvent' else 'MunmapEvent' end) as eventType -from native_hook h ,trace_range t -where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts -and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent') -and h.end_ts not null ) order by startTime; -`, - {} - ); - -export const queryHeapAllData = ( - startTs: number, - endTs: number, - ipids: Array -): Promise> => - query( - 'queryHeapAllData', - ` - select - h.start_ts - t.start_ts as startTs, - h.end_ts - t.start_ts as endTs, - h.heap_size as heapSize, - h.event_type as eventType, - h.callchain_id as eventId - from - native_hook h - inner join - trace_range t - where - event_type = 'AllocEvent' - and - ipid in (${ipids.join(',')}) - and - (h.start_ts - t.start_ts between ${startTs} and ${endTs} or h.end_ts - t.start_ts between ${startTs} and ${endTs})`, - { ipids: ipids, $startTs: startTs, $endTs: endTs } - ); - -export const queryNativeHookStatistics = ( - leftNs: number, - rightNs: number, - ipid: number -): Promise> => - query( - 'queryNativeHookStatistics', - ` - select - event_type as eventType, - sub_type_id as subTypeId, - max(heap_size) as max, - sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte, - sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount, - sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte, - sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount - from - native_hook A, - trace_range B - where - (A.start_ts - B.start_ts) between ${leftNs} and ${rightNs} - and (event_type = 'AllocEvent' or event_type = 'MmapEvent') - and ipid = ${ipid} - group by event_type;`, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const queryNativeHookStatisticsMalloc = ( - leftNs: number, - rightNs: number, - ipid: number -): Promise> => - query( - 'queryNativeHookStatisticsMalloc', - ` - select - event_type as eventType, - heap_size as heapSize, - sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte, - sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount, - sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte, - sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount - from - native_hook A, - trace_range B - where - (A.start_ts - B.start_ts) between ${leftNs} and ${rightNs} - and - (event_type = 'AllocEvent' or event_type = 'MmapEvent') - and - sub_type_id is null - and ipid = ${ipid} - group by - event_type, - heap_size - order by heap_size desc - `, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const queryNativeHookStatisticsSubType = ( - leftNs: number, - rightNs: number, - ipid: number -): Promise> => - query( - 'queryNativeHookStatisticsSubType', - ` - select - event_type as eventType, - sub_type_id as subTypeId, - max(heap_size) as max, - sum(case when ((NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte, - sum(case when ((NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount, - sum(case when ((NH.end_ts - TR.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte, - sum(case when ((NH.end_ts - TR.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount - from - native_hook NH, - trace_range TR - where - (NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs} - and - (event_type = 'MmapEvent') - and ipid = ${ipid} - group by - event_type,sub_type_id; - `, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const queryNativeHookSubType = (leftNs: number, rightNs: number, ipid: number): Promise> => - query( - 'queryNativeHookSubType', - `select distinct( - case when sub_type_id is null then -1 else sub_type_id end -) as subTypeId, -(case when sub_type_id is null then 'Other MmapEvent' else DD.data end) as subType - from - native_hook NH, - trace_range TR - left join data_dict DD on NH.sub_type_id = DD.id -where event_type = 'MmapEvent' and - (NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs} - and ipid = ${ipid} - `, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const queryNativeHookStatisticSubType = (leftNs: number, rightNs: number, ipid: number): Promise> => - query( - 'queryNativeHookStatisticSubType', - `SELECT DISTINCT - CASE - WHEN type = 3 AND sub_type_id NOT NULL THEN sub_type_id - ELSE type - END AS subTypeId, - CASE - WHEN type = 2 THEN 'FILE_PAGE_MSG' - WHEN type = 3 AND sub_type_id NOT NULL THEN D.data - WHEN type = 3 THEN 'MEMORY_USING_MSG' - ELSE 'Other MmapEvent' - END AS subType - FROM - native_hook_statistic NHS - LEFT JOIN data_dict D ON NHS.sub_type_id = D.id, - trace_range TR - WHERE - NHS.type >= 1 AND - (NHS.ts - TR.start_ts) between ${leftNs} and ${rightNs} - AND ipid = ${ipid} - `, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const queryNativeHookStatisticsCount = (): Promise> => - query('queryNativeHookStatisticsCount', `select count(1) num from native_hook_statistic`, {}); - -export const queryNativeHookProcess = (table: string): Promise> => { - let sql = ` - select - distinct ${table}.ipid, - pid, - name - from - ${table} - left join - process p - on - ${table}.ipid = p.id - `; - return query('queryNativeHookProcess', sql, {}); -}; - -export const queryNativeHookSnapshotTypes = (ipid: number): Promise> => - query( - 'queryNativeHookSnapshotTypes', - ` -select - event_type as eventType, - data as subType - from - native_hook left join data_dict on native_hook.sub_type_id = data_dict.id - where - (event_type = 'AllocEvent' or event_type = 'MmapEvent') - and ipid = ${ipid} - group by - event_type,data;`, - {} - ); - -export const queryAllHookData = (rightNs: number, ipid: number): Promise> => - query( - 'queryAllHookData', - ` - select - callchain_id as eventId, - event_type as eventType, - data as subType, - addr, - heap_size as growth, - (n.start_ts - t.start_ts) as startTs, - (n.end_ts - t.start_ts) as endTs - from - native_hook n left join data_dict on n.sub_type_id = data_dict.id, - trace_range t - where - (event_type = 'AllocEvent' or event_type = 'MmapEvent') - and ipid = ${ipid} - and - n.start_ts between t.start_ts and ${rightNs} + t.start_ts`, - { $rightNs: rightNs } - ); - -export const queryNativeHookResponseTypes = ( - leftNs: number, - rightNs: number, - types: Array, - isStatistic: boolean -): Promise> => { - const table = isStatistic ? 'native_hook_statistic' : 'native_hook'; - const tsKey = isStatistic ? 'ts' : 'start_ts'; - const type = isStatistic ? 'type' : 'event_type'; - return query( - 'queryNativeHookResponseTypes', - ` - select - distinct last_lib_id as lastLibId, - data_dict.data as value - from - ${table} A ,trace_range B - left join data_dict on A.last_lib_id = data_dict.id - where - A.${tsKey} - B.start_ts - between ${leftNs} and ${rightNs} and A.${type} in (${types.join(',')}); - `, - { $leftNs: leftNs, $rightNs: rightNs, $types: types } - ); -}; -/** - * HiPerf - */ -export const queryHiPerfEventList = (): Promise> => - query('queryHiPerfEventList', `select id,report_value from perf_report where report_type='config_name'`, {}); -export const queryHiPerfEventListData = (eventTypeId: number): Promise> => - query( - 'queryHiPerfEventListData', - ` - select s.callchain_id, - (s.timestamp_trace-t.start_ts) startNS - from perf_sample s,trace_range t - where - event_type_id=${eventTypeId} - and s.thread_id != 0 - and s.callchain_id != -1; -`, - { $eventTypeId: eventTypeId } - ); -export const queryHiPerfEventData = (eventTypeId: number, cpu: number): Promise> => - query( - 'queryHiPerfEventList', - ` - select s.callchain_id, - (s.timestamp_trace-t.start_ts) startNS - from perf_sample s,trace_range t - where - event_type_id=${eventTypeId} - and cpu_id=${cpu} - and s.thread_id != 0 - and s.callchain_id != -1; -`, - { $eventTypeId: eventTypeId, $cpu: cpu } - ); -export const queryHiPerfCpuData = (cpu: number): Promise> => - query( - 'queryHiPerfCpuData', - ` - select s.callchain_id, - (s.timestamp_trace-t.start_ts) startNS, event_count, event_type_id - from perf_sample s,trace_range t - where - cpu_id=${cpu} - and s.thread_id != 0;`, - { $cpu: cpu } - ); -export const queryHiPerfCpuMergeData = (): Promise> => - query( - 'queryHiPerfCpuData', - `select s.callchain_id,(s.timestamp_trace-t.start_ts) startNS, event_count, event_type_id from perf_sample s,trace_range t -where s.thread_id != 0;`, - {} - ); -export const queryHiPerfCpuMergeData2 = (): Promise> => - query( - 'queryHiPerfCpuData2', - `select distinct cpu_id from perf_sample where thread_id != 0 order by cpu_id desc;`, - {} - ); - -export const queryHiPerfProcessData = (pid: number): Promise> => - query( - 'queryHiPerfProcessData', - ` -SELECT sp.callchain_id, - th.thread_name, - th.thread_id tid, - th.process_id pid, - sp.timestamp_trace - tr.start_ts startNS, - event_count, - event_type_id -from perf_sample sp, - trace_range tr - left join perf_thread th on th.thread_id = sp.thread_id -where pid = ${pid} and sp.thread_id != 0 `, - { $pid: pid } - ); - -export const queryHiPerfThreadData = (tid: number): Promise> => - query( - 'queryHiPerfThreadData', - ` -SELECT sp.callchain_id, - th.thread_name, - th.thread_id tid, - th.process_id pid, - sp.timestamp_trace - tr.start_ts startNS, - event_count, - event_type_id -from perf_sample sp, - trace_range tr - left join perf_thread th on th.thread_id = sp.thread_id -where tid = ${tid} and sp.thread_id != 0 ;`, - { $tid: tid } - ); -export const querySelectTraceStats = (): Promise< - Array<{ - event_name: string; - stat_type: string; - count: number; - source: string; - serverity: string; - }> -> => query('querySelectTraceStats', 'select event_name,stat_type,count,source,serverity from stat'); - -export const queryCustomizeSelect = (sql: string): Promise> => query('queryCustomizeSelect', sql); - -export const queryDistributedTerm = (): Promise< - Array<{ - threadId: string; - threadName: string; - processId: string; - processName: string; - funName: string; - dur: string; - ts: string; - chainId: string; - spanId: string; - parentSpanId: string; - flag: string; - trace_name: string; - }> -> => - query( - 'queryDistributedTerm', - ` - 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` - ); - -export const queryTraceCpu = (): Promise< - Array<{ - tid: string; - pid: string; - cpu: string; - dur: string; - min_freq: string; - max_freq: string; - avg_frequency: string; - }> -> => - query( - 'queryTraceCpu', - `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 - ` - ); - -export const queryTraceCpuTop = (): Promise< - Array<{ - tid: string; - pid: string; - cpu: string; - duration: string; - min_freq: string; - max_freq: string; - avg_frequency: string; - sumNum: string; - }> -> => - query( - 'queryTraceCpuTop', - `SELECT - ipid AS pid, - itid AS tid, - group_concat(cpu, ',') AS cpu, - group_concat(dur, ',') AS dur, - group_concat(avg_frequency, ',') AS avg_frequency, - group_concat(min_freq, ',') AS min_freq, - group_concat(max_freq, ',') AS max_freq, - 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; - ` - ); - -export const queryTraceMemory = (): Promise< - Array<{ - maxNum: string; - minNum: string; - avgNum: string; - name: string; - processName: string; - }> -> => - query( - 'queryTraceMemory', - ` - 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` - ); - -export const queryTraceMemoryTop = (): Promise< - Array<{ - maxNum: string; - minNum: string; - avgNum: string; - name: string; - processName: string; - }> -> => - query( - 'queryTraceMemoryTop', - ` - 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` - ); - -export const queryTraceMemoryUnAgg = (): Promise< - Array<{ - processName: string; - name: string; - value: string; - ts: string; - }> -> => - query( - 'queryTraceMemoryUnAgg', - ` - 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` - ); - -export const queryTraceTaskName = (): Promise< - Array<{ - id: string; - pid: string; - process_name: string; - thread_name: string; - }> -> => - query( - 'queryTraceTaskName', - ` - 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` - ); - -export const queryTraceMetaData = (): Promise< - Array<{ - name: string; - valueText: string; - }> -> => - query( - 'queryTraceMetaData', - ` - 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` - ); - -export const querySystemCalls = (): Promise< - Array<{ - frequency: string; - minDur: number; - maxDur: number; - avgDur: number; - funName: string; - }> -> => - query( - 'querySystemCalls', - ` - 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` - ); - -export const querySystemCallsTop = (): Promise< - Array<{ - tid: string; - pid: string; - funName: string; - frequency: string; - minDur: string; - maxDur: string; - avgDur: string; - }> -> => - query( - 'querySystemCallsTop', - `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` - ); - -export const getTabLiveProcessData = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabLiveProcessData', - `SELECT - process.id as processId, - process.name as processName, - process.ppid as responsibleProcess, - process.uud as userName, - process.usag as cpu, - process.threadN as threads, - process.pss as memory, - process.cpu_time as cpuTime, - process.disk_reads as diskReads, - process.disk_writes as diskWrite - FROM - ( - SELECT - tt.process_id AS id, - tt.process_name AS name, - tt.parent_process_id AS ppid, - tt.uid as uud, - tt.cpu_usage as usag, - tt.thread_num AS threadN, - mt.maxTT - TR.start_ts as endTs, - tt.pss_info as pss, - tt.cpu_time, - tt.disk_reads, - tt.disk_writes - FROM - live_process tt - LEFT JOIN trace_range AS TR - LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT - from live_process re GROUP BY re.process_name, re.process_id ) mt - on mt.idd = tt.process_id where endTs >= $rightNS - GROUP BY - tt.process_name, - tt.process_id - ) process ;`, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabProcessHistoryData = ( - leftNs: number, - rightNs: number, - processId: number | undefined, - threadId: number | undefined -): Promise> => - query( - 'getTabProcessHistoryData', - `SELECT - process.id as processId, - process.isD as alive, - process.startTS as firstSeen, - process.endTs as lastSeen, - process.name as processName, - process.ppid as responsibleProcess, - process.uuid as userName, - process.cpu_time as cpuTime, - 0 as pss - FROM - ( - SELECT - tt.process_id AS id, - tt.process_name AS name, - tt.parent_process_id AS ppid, - tt.uid AS uuid, - tt.cpu_time, - (mt.minTT - TR.start_ts ) AS startTS, - mt.maxTT - TR.start_ts as endTs, - (mt.maxTT - TR.start_ts - $rightNS) > 0 as isD - FROM - live_process tt - LEFT JOIN trace_range AS TR - LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT - from live_process re GROUP BY re.process_name, re.process_id ) mt - on mt.idd = tt.process_id - GROUP BY - tt.process_name, - tt.process_id - ) process;`, - { - $leftNS: leftNs, - $rightNS: rightNs, - $processID: processId, - $threadID: threadId, - } - ); - -export const getTabCpuAbilityData = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabCpuAbilityData', - `SELECT - ( n.ts - TR.start_ts ) AS startTime, - n.dur AS duration, - n.total_load AS totalLoad, - n.user_load AS userLoad, - n.system_load AS systemLoad, - n.process_num AS threads - FROM - cpu_usage AS n, - trace_range AS TR - WHERE - ( n.ts - TR.start_ts ) >= ifnull(( - SELECT - ( usage.ts - TR.start_ts ) - FROM - cpu_usage usage, - trace_range TR - WHERE - ( usage.ts - TR.start_ts ) <= $leftNS - ORDER BY - usage.ts DESC - LIMIT 1 - ),0) - AND ( n.ts - TR.start_ts ) <= $rightNS - ORDER BY - startTime ASC; - `, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabMemoryAbilityData = ( - leftNs: number, - rightNs: number -): Promise< - Array<{ - startTime: number; - value: string; - name: string; - }> -> => - query( - 'getTabMemoryAbilityData', - `SELECT - m.ts AS startTime, - GROUP_CONCAT( IFNULL( m.value, 0 ) ) AS value, - GROUP_CONCAT( f.name ) AS name - FROM - sys_mem_measure AS m - INNER JOIN sys_event_filter AS f ON m.filter_id = f.id - AND (f.name = 'sys.mem.total' - or f.name = 'sys.mem.free' - or f.name = 'sys.mem.buffers' - or f.name = 'sys.mem.cached' - or f.name = 'sys.mem.shmem' - or f.name = 'sys.mem.slab' - or f.name = 'sys.mem.swap.total' - or f.name = 'sys.mem.swap.free' - or f.name = 'sys.mem.mapped' - or f.name = 'sys.mem.vmalloc.used' - or f.name = 'sys.mem.page.tables' - or f.name = 'sys.mem.kernel.stack' - or f.name = 'sys.mem.active' - or f.name = 'sys.mem.inactive' - or f.name = 'sys.mem.unevictable' - or f.name = 'sys.mem.vmalloc.total' - or f.name = 'sys.mem.slab.unreclaimable' - or f.name = 'sys.mem.cma.total' - or f.name = 'sys.mem.cma.free' - or f.name = 'sys.mem.kernel.reclaimable' - or f.name = 'sys.mem.zram' - ) - AND m.ts >= ifnull(( - SELECT - m.ts AS startTime - FROM - sys_mem_measure AS m - INNER JOIN sys_event_filter AS f ON m.filter_id = f.id - AND m.ts <= $leftNS - AND (f.name = 'sys.mem.total' - or f.name = 'sys.mem.kernel.stack' - or f.name = 'sys.mem.free' - or f.name = 'sys.mem.swap.free' - or f.name = 'sys.mem.cma.free' - or f.name = 'sys.mem.inactive' - or f.name = 'sys.mem.buffers' - or f.name = 'sys.mem.cached' - or f.name = 'sys.mem.shmem' - or f.name = 'sys.mem.slab' - or f.name = 'sys.mem.swap.total' - or f.name = 'sys.mem.vmalloc.used' - or f.name = 'sys.mem.page.tables' - or f.name = 'sys.mem.active' - or f.name = 'sys.mem.unevictable' - or f.name = 'sys.mem.vmalloc.total' - or f.name = 'sys.mem.slab.unreclaimable' - or f.name = 'sys.mem.cma.total' - or f.name = 'sys.mem.mapped' - or f.name = 'sys.mem.kernel.reclaimable' - or f.name = 'sys.mem.zram' - ) - ORDER BY - m.ts DESC - LIMIT 1 - ),0) - AND m.ts <= $rightNS GROUP BY m.ts;`, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabNetworkAbilityData = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabNetworkAbilityData', - `SELECT - ( n.ts - TR.start_ts ) AS startTime, - n.dur AS duration, - n.rx AS dataReceived, - n.tx_speed AS dataReceivedSec, - n.tx AS dataSend, - n.rx_speed AS dataSendSec, - n.packet_in AS packetsIn, - n.packet_in_sec AS packetsInSec, - n.packet_out AS packetsOut, - n.packet_out_sec AS packetsOutSec - FROM - network AS n, - trace_range AS TR - WHERE - ( n.ts - TR.start_ts ) >= ifnull(( - SELECT - ( nn.ts - T.start_ts ) AS startTime - FROM - network nn, - trace_range T - WHERE - ( nn.ts - T.start_ts ) <= $leftNS - ORDER BY - nn.ts DESC - LIMIT 1 - ),0) - AND ( n.ts - TR.start_ts ) <= $rightNS - ORDER BY - startTime ASC`, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabDiskAbilityData = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabDiskAbilityData', - `SELECT - ( n.ts - TR.start_ts ) AS startTime, - n.dur AS duration, - n.rd AS dataRead, - n.rd_speed AS dataReadSec, - n.wr AS dataWrite, - n.wr_speed AS dataWriteSec, - n.rd_count AS readsIn, - n.rd_count_speed AS readsInSec, - n.wr_count AS writeOut, - n.wr_count_speed AS writeOutSec - FROM - diskio AS n, - trace_range AS TR - WHERE - ( n.ts - TR.start_ts ) >= ifnull(( - SELECT - ( nn.ts - T.start_ts ) AS startTime - FROM - diskio AS nn, - trace_range AS T - WHERE - ( nn.ts - T.start_ts ) <= $leftNS - ORDER BY - nn.ts DESC - LIMIT 1 - ),0) - AND ( n.ts - TR.start_ts ) <= $rightNS - ORDER BY - startTime ASC; - `, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const queryCpuAbilityData = (): Promise> => - query( - 'queryCpuAbilityData', - `select - (t.total_load) as value, - (t.ts - TR.start_ts) as startNS - from cpu_usage t, trace_range AS TR;` - ); - -export const queryCpuAbilityUserData = (): Promise> => - query( - 'queryCpuAbilityUserData', - `select - t.user_load as value, - (t.ts - TR.start_ts) as startNS - from cpu_usage t, trace_range AS TR;` - ); - -export const queryCpuAbilitySystemData = (): Promise> => - query( - 'queryCpuAbilitySystemData', - `select - t.system_load as value, - (t.ts - TR.start_ts) as startNS - from cpu_usage t, trace_range AS TR;` - ); - -export const queryMemoryUsedAbilityData = (id: string): Promise> => - query( - 'queryMemoryUsedAbilityData', - `select - t.value as value, - (t.ts - TR.start_ts) as startNS - from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, - { $id: id } - ); - -export const queryCachedFilesAbilityData = (id: string): Promise> => - query( - 'queryCachedFilesAbilityData', - `select - t.value as value, - (t.ts - TR.start_ts) as startNS - from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, - { $id: id } - ); - -export const queryCompressedAbilityData = (id: string): Promise> => - query( - 'queryCompressedAbilityData', - `select - t.value as value, - (t.ts - TR.start_ts) as startNS - from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, - { $id: id } - ); - -export const querySwapUsedAbilityData = (id: string): Promise> => - query( - 'querySwapUsedAbilityData', - `select - t.value as value, - (t.ts - TR.start_ts) as startNS - from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, - { $id: id } - ); - -export const queryBytesReadAbilityData = (): Promise> => - query( - 'queryBytesReadAbilityData', - `select - t.rd_speed as value, - (t.ts - TR.start_ts) as startNS - from diskio t, trace_range AS TR;` - ); - -export const queryBytesWrittenAbilityData = (): Promise> => - query( - 'queryBytesWrittenAbilityData', - `select - t.wr_speed as value, - (t.ts - TR.start_ts) as startNS - from diskio t, trace_range AS TR;` - ); - -export const queryReadAbilityData = (): Promise> => - query( - 'queryReadAbilityData', - `select - t.rd_count_speed as value, - (t.ts - TR.start_ts) as startNS - from diskio t, trace_range AS TR;` - ); - -export const queryWrittenAbilityData = (): Promise> => - query( - 'queryWrittenAbilityData', - `select - t.wr_count_speed as value, - (t.ts - TR.start_ts) as startNS - from diskio t, trace_range AS TR;` - ); - -export const queryBytesInAbilityData = (): Promise> => - query( - 'queryBytesInAbilityData', - `select - t.tx_speed as value, - (t.ts - TR.start_ts) as startNS - from network t, trace_range AS TR;` - ); - -export const queryBytesOutAbilityData = (): Promise> => - query( - 'queryBytesOutAbilityData', - `select - t.rx_speed as value, - (t.ts - TR.start_ts) as startNS - from network t, trace_range AS TR;` - ); - -export const queryPacketsInAbilityData = (): Promise> => - query( - 'queryPacketsInAbilityData', - `select - t.packet_in_sec as value, - (t.ts - TR.start_ts) as startNS - from network t, trace_range AS TR;` - ); - -export const queryPacketsOutAbilityData = (): Promise> => - query( - 'queryPacketsOutAbilityData', - `select - t.packet_out_sec as value, - (t.ts - TR.start_ts) as startNS - from network t, trace_range AS TR;` - ); - -export const queryNetWorkMaxData = (): Promise> => - query( - 'queryNetWorkMaxData', - `select - ifnull(max(tx_speed),0) as maxIn, - ifnull(max(rx_speed),0) as maxOut, - ifnull(max(packet_in_sec),0) as maxPacketIn, - ifnull(max(packet_in_sec),0) as maxPacketOut - from network` - ); - -export const queryMemoryMaxData = (memoryName: string): Promise> => - query( - 'queryMemoryMaxData', - `SELECT ifnull(max(m.value),0) as maxValue, - filter_id - from sys_mem_measure m - WHERE m.filter_id = - (SELECT id FROM sys_event_filter WHERE name = $memoryName) -`, - { $memoryName: memoryName } - ); - -export const queryDiskIoMaxData = (): Promise> => - query( - 'queryDiskIoMaxData', - `select - ifnull(max(rd_speed),0) as bytesRead, - ifnull(max(wr_speed),0) as bytesWrite, - ifnull(max(rd_count_speed),0) as readOps, - ifnull(max(wr_count_speed),0) as writeOps - from diskio` - ); - -export const queryAbilityExits = (): Promise> => - query( - 'queryAbilityExits', - `select - event_name - from stat s - where s.event_name in ('trace_diskio','trace_network', 'trace_cpu_usage','sys_memory') - and s.stat_type ='received' and s.count > 0` - ); - -export const queryStartTime = (): Promise> => query('queryStartTime', `SELECT start_ts FROM trace_range`); - -export const queryPerfFiles = (): Promise> => - query('queryPerfFiles', `select file_id as fileId,symbol,path from perf_files`, {}); - -export const queryPerfCallChainName = (): Promise> => - query('queryPerfCallChainName', `select callchain_id,depth,name from perf_callchain`, {}); - -export const queryPerfProcess = (): Promise> => - query( - 'queryPerfThread', - `select process_id as pid,thread_name as processName from perf_thread where process_id = thread_id`, - {} - ); - -export const queryPerfThread = (): Promise> => - query( - 'queryPerfThread', - `select a.thread_id as tid, - a.thread_name as threadName, - a.process_id as pid, - b.thread_name as processName -from perf_thread a - left join (select distinct process_id, thread_name from perf_thread where process_id = thread_id) b - on a.process_id = b.process_id -order by pid;`, - {} - ); - -export const queryPerfSampleListByTimeRange = ( - leftNs: number, - rightNs: number, - cpus: Array, - processes: Array, - threads: Array, - eventTypeId?: number -): Promise> => { - let sql = ` -select A.callchain_id as sampleId, - A.thread_id as tid, - C.thread_name as threadName, - A.thread_state as state, - C.process_id as pid, - (timestamp_trace - R.start_ts) as time, - cpu_id as core -from perf_sample A,trace_range R -left join perf_thread C on A.thread_id = C.thread_id -where time >= $leftNs and time <= $rightNs and A.thread_id != 0 - `; - if (eventTypeId !== undefined) { - sql = `${sql} and event_type_id = ${eventTypeId}`; - } - if (cpus.length != 0 || processes.length != 0 || threads.length != 0) { - let arg1 = cpus.length > 0 ? `or core in (${cpus.join(',')}) ` : ''; - let arg2 = processes.length > 0 ? `or pid in (${processes.join(',')}) ` : ''; - let arg3 = threads.length > 0 ? `or tid in (${threads.join(',')})` : ''; - let arg = `${arg1}${arg2}${arg3}`.substring(3); - sql = `${sql} and (${arg})`; - } - return query('queryPerfSampleListByTimeRange', sql, { - $leftNs: leftNs, - $rightNs: rightNs, - }); -}; - -export const queryPerfSampleIdsByTimeRange = ( - leftNs: number, - rightNs: number, - cpus: Array, - processes: Array, - threads: Array -): Promise> => { - let sql = ` -select A.callchain_id as sampleId -from perf_sample A,trace_range R -left join perf_thread C on A.thread_id = C.thread_id -where (timestamp_trace - R.start_ts) >= $leftNs and (timestamp_trace - R.start_ts) <= $rightNs and A.thread_id != 0 - `; - if (cpus.length != 0 || processes.length != 0 || threads.length != 0) { - let arg1 = cpus.length > 0 ? `or A.cpu_id in (${cpus.join(',')}) ` : ''; - let arg2 = processes.length > 0 ? `or C.process_id in (${processes.join(',')}) ` : ''; - let arg3 = threads.length > 0 ? `or A.thread_id in (${threads.join(',')})` : ''; - let arg = `${arg1}${arg2}${arg3}`.substring(3); - sql = `${sql} and (${arg})`; - } - return query('queryPerfSampleIdsByTimeRange', sql, { - $leftNs: leftNs, - $rightNs: rightNs, - }); -}; - -export const queryPerfSampleCallChain = (sampleId: number): Promise> => - query( - 'queryPerfSampleCallChain', - ` - select - callchain_id as callChainId, - callchain_id as sampleId, - file_id as fileId, - symbol_id as symbolId, - vaddr_in_file as vaddrInFile, - name as symbol -from perf_callchain where callchain_id = $sampleId; - `, - { $sampleId: sampleId } - ); - -export const queryPerfCmdline = (): Promise> => - query( - 'queryPerfCmdline', - ` - select report_value from perf_report where report_type = 'cmdline' - `, - {} - ); -export const queryPerfEventType = (): Promise> => - query( - 'queryPerfEventType', - ` - select id,report_value as report from perf_report where id in ( -select distinct event_type_id from perf_sample); - `, - {} - ); - -export const queryCPuAbilityMaxData = (): Promise> => - query( - 'queryCPuAbilityMaxData', - `select ifnull(max(total_load),0) as totalLoad, - ifnull(max(user_load),0) as userLoad, - ifnull(max(system_load),0) as systemLoad - from cpu_usage` - ); - -export const searchCpuData = (keyword: string): Promise> => { - let id = parseInt(keyword); - let sql = ` - select B.pid as processId, - B.cpu, - B.tid, - 'cpu' as type, - B.itid as id, - B.dur as dur, - B.ts - TR.start_ts as startTime, - B.arg_setid as argSetID -from thread_state AS B, trace_range TR - left join process p on B.pid = p.pid - left join thread t on B.itid = t.itid -where B.cpu not null and B.ts between TR.start_ts and TR.end_ts - and ( - t.name like '%${keyword}%' - or B.tid = ${Number.isNaN(id) ? -1 : id} - or B.pid = ${Number.isNaN(id) ? -1 : id} - or p.name like '%${keyword}%' - ) -order by startTime;`; - return query('searchCpuData', sql, {}); -}; - -export const querySearchFunc = (search: string): Promise> => - query( - 'querySearchFunc', - ` - select c.cookie, - c.id, - c.name as funName, - c.ts - r.start_ts as startTime, - c.dur, - c.depth, - t.tid, - t.name as threadName, - p.pid, - c.argsetid, - 'func' as type - from callstack c left join thread t on c.callid = t.id left join process p on t.ipid = p.id - left join trace_range r - where c.name like '%${search}%' and startTime > 0; - `, - { $search: search } - ); - -export const querySceneSearchFunc = (search: string, processList: Array): Promise> => - query( - 'querySearchFunc', - ` - select c.cookie, - c.id, - c.name as funName, - c.ts - r.start_ts as startTime, - c.dur, - c.depth, - t.tid, - t.name as threadName, - p.pid, - c.argsetid, - 'func' as type - from callstack c left join thread t on c.callid = t.id left join process p on t.ipid = p.id - left join trace_range r - where c.name like '%${search}%' ESCAPE '\\' and startTime > 0 and p.pid in (${processList.join(',')}); - `, - { $search: search } - ); - -export const queryBinderBySliceId = (id: number): Promise> => - query( - 'queryBinderBySliceId', - `select c.ts-D.start_ts as startTs, - c.dur, - t.tid,p.pid,c.depth,c.argsetid,c.name as funName,c.cookie - from callstack c,trace_range D - left join thread t on c.callid = t.id - left join process p on p.id = t.ipid -where cat = 'binder' and c.id = $id;`, - { $id: id } - ); - -export const queryThreadByItid = (itid: number, ts: number): Promise> => - query( - 'queryThreadByItid', - `select tid,pid,c.dur,c.depth,c.name -from thread t left join process p on t.ipid = p.ipid -left join callstack c on t.itid = c.callid -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 startTs, - c.dur, - t.tid, - p.pid, - c.depth, - c.argsetid, - c.name as funName, - c.cookie - from callstack c,trace_range D - left join thread t on c.callid = t.id - left join process p on p.id = t.ipid -where cat = 'binder' and c.argsetid = $id`; - if (isNext) { - sql += ' and c.ts > $startTime + D.start_ts'; - } else { - sql += ' and c.ts < $startTime + D.start_ts'; - } - return query('queryBinderByArgsId', sql, { - $id: id, - $startTime: startTime, - }); -}; - -export const getTabPaneFilesystemStatisticsFather = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabPaneFilesystemStatisticsFather', - ` - select SUM(dur) as allDuration, - count(f.type) as count, - min(dur) as minDuration, - max(dur) as maxDuration, - round(avg(dur),2) as avgDuration, - p.name, - f.type, - p.pid, - sum(ifnull(size,0)) as size - from file_system_sample as f - left join process as p on f.ipid=p.ipid - where f.start_ts >= $leftNs - and end_ts <= $rightNs - group by f.type; - `, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const getTabPaneFilesystemStatisticsChild = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabPaneFilesystemStatisticsChild', - ` - select SUM(dur) as allDuration, - count(f.type) as count, - min(dur) as minDuration, - max(dur) as maxDuration, - round(avg(dur),2) as avgDuration, - p.name, - p.pid, - f.type, - sum(ifnull(size,0)) as size - from file_system_sample as f left join process as p on f.ipid=p.ipid - where f.start_ts >= $leftNs - and end_ts <= $rightNs - group by f.type, f.ipid; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const getTabPaneFilesystemStatisticsAll = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabPaneFilesystemStatisticsAll', - ` - select SUM(dur) as allDuration, - count(type) as count, - min(dur) as minDuration, - max(dur) as maxDuration, - round(avg(dur),2) as avgDuration, - type - from file_system_sample - where start_ts >= $leftNs - and end_ts <= $rightNs; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const getTabPaneFilesystemStatistics = (leftNs: number, rightNs: number, types: number[]): Promise> => - query( - 'getTabPaneFilesystemStatistics', - ` - select p.pid, - ifnull(p.name,'Process') as name, - f.type, - count(f.ipid) as count, - sum(ifnull(size,0)) as size, - sum(case when f.type = 2 then ifnull(size,0) else 0 end) as logicalReads, - sum(case when f.type = 3 then ifnull(size,0) else 0 end) as logicalWrites, - sum(case when f.type != 2 and f.type != 3 then ifnull(size,0) else 0 end) as otherFile, - sum(dur) as allDuration, - min(dur) as minDuration, - max(dur) as maxDuration, - avg(dur) as avgDuration - from file_system_sample as f left join process as p on f.ipid=p.ipid - where end_ts >= $leftNs - and end_ts <= $rightNs - and f.type in (${types.join(',')}) - group by f.type,f.ipid - order by f.type; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const getTabPaneVirtualMemoryStatisticsData = (leftNs: number, rightNs: number): Promise> => - query( - 'getTabPaneVirtualMemoryStatisticsData', - ` - select p.pid, - t.tid, - ifnull(p.name,'Process') as pname, - ifnull(t.name,'Thread') as tname, - f.type, - f.ipid, - f.itid, - count(f.ipid) as count, - sum(dur) as allDuration, - min(dur) as minDuration, - max(dur) as maxDuration, - avg(dur) as avgDuration - from paged_memory_sample as f left join process as p on f.ipid=p.ipid left join thread as t on f.itid=t.itid - where f.end_ts >= $leftNs - and f.end_ts <= $rightNs - group by f.type,f.ipid,f.itid - order by f.type; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); - -export const getTabPaneIOTierStatisticsData = ( - leftNs: number, - rightNs: number, - diskIOipids: Array -): Promise> => { - let str = ''; - if (diskIOipids.length > 0) { - str = ` and i.ipid in (${diskIOipids.join(',')})`; - } - return query( - 'getTabPaneIOTierStatisticsData', - ` - select p.pid, - ifnull(p.name,'Process') as pname, - i.tier, - i.ipid, - path_id as path, - count(i.ipid) as count, - sum(latency_dur) as allDuration, - min(latency_dur) as minDuration, - max(latency_dur) as maxDuration, - avg(latency_dur) as avgDuration - from bio_latency_sample as i left join process as p on i.ipid=p.ipid - where i.start_ts+latency_dur >= $leftNs - and i.start_ts+latency_dur <= $rightNs - ${str} - group by i.tier,i.ipid,i.path_id - order by i.tier; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); -}; - -export const getTabPaneCounterSampleData = ( - leftNs: number, - rightNs: number, - cpuStateFilterIds: Array -): Promise> => { - let str = ''; - if (cpuStateFilterIds.length > 0) { - str = ` and filter_id in (${cpuStateFilterIds.join(',')})`; - } - return query( - 'getTabPaneCounterSampleData', - ` - select value, filter_id as filterId, ts, f.cpu - from measure left join cpu_measure_filter as f on f.id=filter_id - where - ts <= $rightNs${str} order by ts asc; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); -}; - -export const getTabPaneFrequencySampleData = ( - leftNs: number, - rightNs: number, - cpuFreqFilterIds: Array -): Promise> => { - let str = ''; - if (cpuFreqFilterIds.length > 0) { - str = ` and filter_id in (${cpuFreqFilterIds.join(',')})`; - } - return query( - 'getTabPaneFrequencySampleData', - ` - select value, filter_id as filterId, ts, f.cpu - from measure left join cpu_measure_filter as f on f.id=filter_id - where - ts <= $rightNs${str} order by ts asc; -`, - { $leftNs: leftNs, $rightNs: rightNs } - ); -}; - -export const hasFileSysData = (): Promise> => - query( - 'hasFileSysData', - ` - select - fsCount, - vmCount, - ioCount from - (select count(1) as fsCount from file_system_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) ) - ,(select count(1) as vmCount from paged_memory_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) ) - ,(select count(1) as ioCount from bio_latency_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) ); - `, - {} - ); - -export const getFileSysChartDataByType = (type: number): Promise> => - query( - 'getFileSysChartData', - ` - select - (A.start_ts -B.start_ts) as startNS, - (A.end_ts - B.start_ts) as endNS, - dur - from file_system_sample A,trace_range B - where type = $type and startNS > 0;`, - { $type: type }, - 'exec' - ); - -export const getFileSysVirtualMemoryChartData = (): Promise> => - query( - 'getFileSysVirtualMemoryChartData', - ` - select - (A.start_ts -B.start_ts) as startNS, - (A.end_ts - B.start_ts) as endNS, - dur as dur - from paged_memory_sample A,trace_range B - where startNS > 0 - order by A.start_ts;`, - {}, - 'exec' - ); - -export const getDiskIOProcess = (): Promise> => - query( - 'getDiskIOProcess', - ` - select name,B.ipid,pid - from (select distinct ipid from bio_latency_sample A,trace_range B where A.start_ts between B.start_ts and B.end_ts) A - left join process B on A.ipid = B.ipid;`, - {} - ); - -export const getDiskIOLatencyChartDataByProcess = ( - all: boolean, - ipid: number, - typeArr: Array -): Promise> => - query( - 'getDiskIOLatencyChartDataByProcess', - ` - select - (A.start_ts -B.start_ts) as startNS, - (A.start_ts - B.start_ts + A.latency_dur) as endNS, - latency_dur as dur - from bio_latency_sample A,trace_range B - where type in (${typeArr.join(',')}) and startNS > 0 - ${all ? '' : 'and ipid = ' + ipid} - order by A.start_ts;`, - {}, - 'exec' - ); - -export const querySdkCount = (sql: string, componentId: number, args?: any): Promise> => - query('querySdkCount', sql, args, 'exec-sdk-' + componentId); - -export const querySdkCounterData = ( - sql: string, - counter_id: number, - componentId: number -): Promise> => - query('querySdkCounterData', sql, { $counter_id: counter_id }, 'exec-sdk-' + componentId); - -export const getTabSdkCounterData = ( - sqlStr: string, - startTime: number, - leftNs: number, - rightNs: number, - counters: Array, - componentId: number -): Promise> => - query( - 'getTabSdkCounterData', - sqlStr, - { - $startTime: startTime, - $leftNs: leftNs, - $rightNs: rightNs, - $counters: counters, - }, - 'exec-sdk-' + componentId - ); - -export const getTabSdkCounterLeftData = ( - sqlStr: string, - leftNs: number, - counters: Array, - componentId: number -): Promise> => - query( - 'getTabSdkCounterLeftData', - sqlStr, - { - $leftNs: leftNs, - $counters: counters, - }, - 'exec-sdk-' + componentId - ); - -export const getTabSdkSliceData = ( - sqlStr: string, - startTime: number, - leftNs: number, - rightNs: number, - slices: Array, - componentId: number -): Promise> => - query( - 'getTabSdkSliceData', - sqlStr, - { - $startTime: startTime, - $leftNs: leftNs, - $rightNs: rightNs, - $slices: slices, - }, - 'exec-sdk-' + componentId - ); - -export const querySdkSliceData = ( - sqlStr: string, - column_id: number, - startNS: number, - endNS: number, - componentId: number -): Promise> => - query( - 'querySdkSliceData', - sqlStr, - { $column_id: column_id, $startNS: startNS, $endNS: endNS }, - 'exec-sdk-' + componentId - ); - -export const queryCounterMax = (sqlStr: string, counter_id: number, componentId: number): Promise> => - query('queryCounterMax', sqlStr, { $counter_id: counter_id }, 'exec-sdk-' + componentId); - -export const queryAnomalyData = (): Promise> => - query( - 'queryAnomalyData', - `select - S.id, - (S.ts - TR.start_ts) as startNS, - D.data as eventName, - D2.data as appKey, - (case when S.type==1 then group_concat(S.string_value,',') else group_concat(S.int_value,',') end) as Value - from trace_range AS TR,hisys_event_measure as S - left join data_dict as D on D.id=S.name_id - left join app_name as APP on APP.id=S.key_id - left join data_dict as D2 on D2.id=APP.app_key - where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_KERNEL_WAKELOCK','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_WAKEUP') - or (D.data in ('ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_ENERGY','ANOMALY_ALARM_WAKEUP') and D2.data in ("APPNAME")) - group by S.serial,D.data` - ); - -export const querySystemLocationData = (): Promise< - Array<{ - ts: string; - eventName: string; - appKey: string; - Value: string; - }> -> => - query( - 'querySystemLocationData', - `SELECT - ( S.ts - TR.start_ts ) AS ts, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - WHERE - D.data = 'GNSS_STATE' AND D2.data = 'STATE' - GROUP BY - S.serial, - APP.app_key, - D.data, - D2.data;` - ); - -export const querySystemLockData = (): Promise< - Array<{ - ts: string; - eventName: string; - appKey: string; - Value: string; - }> -> => - query( - 'querySystemLockData', - `SELECT - ( S.ts - TR.start_ts ) AS ts, - D.data AS eventName, - D2.data AS appKey, - group_concat(( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - WHERE - ( D.data = 'POWER_RUNNINGLOCK' AND D2.data in ('TAG','MESSAGE')) - GROUP BY - S.serial;` - ); - -export const querySystemAllData = (): Promise< - Array<{ - id: number; - eventName: string; - eventValue: string; - }> -> => - query( - 'querySystemAllData', - `SELECT - S.id, - D.data AS eventName, - contents AS eventValue - FROM - trace_range AS TR, - hisys_all_event AS S - LEFT JOIN data_dict AS D ON S.event_name_id = D.id - LEFT JOIN data_dict AS D2 ON S.domain_id = D2.id - WHERE - eventName IN ( 'POWER_RUNNINGLOCK', 'GNSS_STATE', 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' );` - ); - -export const querySystemSchedulerData = (): Promise< - Array<{ - startNs: string; - eventName: string; - appKey: string; - Value: string; - }> -> => - query( - 'querySystemSchedulerData', - `SELECT - ( S.ts - TR.start_ts ) AS startNs, - D.data AS eventName, - group_concat(D2.data, ',') AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - WHERE - D.data IN ( 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' ) AND D2.data in ('NAME','TYPE','WORKID') - GROUP BY - S.serial;` - ); - -export const querySystemDetailsData = (rightNs: number, eventName: string): Promise> => - query( - 'querySystemDetailsData', - `SELECT - ( S.ts - TR.start_ts ) AS ts, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - WHERE - D.data in ($eventName) - AND - D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') - AND - (S.ts - TR.start_ts) <= $rightNS - GROUP BY - S.serial, - APP.app_key, - D.data, - D2.data;`, - { $rightNS: rightNs, $eventName: eventName } - ); - -export const querySystemWorkData = (rightNs: number): Promise> => - query( - 'querySystemWorkData', - `SELECT - ( S.ts - TR.start_ts ) AS ts, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D - ON D.id = S.name_id - LEFT JOIN app_name AS APP - ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 - ON D2.id = APP.app_key - WHERE - D.data in ("WORK_REMOVE", "WORK_STOP", "WORK_ADD", "WORK_START") - and - D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') - and (S.ts - TR.start_ts) <= $rightNS - GROUP BY - S.serial, - APP.app_key, - D.data, - D2.data;`, - { $rightNS: rightNs } - ); - -export const queryMaxPowerValue = ( - appName: string -): Promise< - Array<{ - maxValue: number; - }> -> => - query( - 'queryMaxPowerValue', - `SELECT - max( item ) AS maxValue - FROM - ( - SELECT - sum( energy + background_energy + screen_on_energy + screen_off_energy + foreground_energy ) AS item - FROM - energy - WHERE - app_name = $appName - GROUP BY - startNs);`, - { $appName: appName } - ); - -export const queryPowerData = (): Promise< - Array<{ - id: number; - startNS: number; - eventName: string; - appKey: string; - eventValue: string; - }> -> => - query( - 'queryPowerData', - `SELECT - S.id, - ( S.ts - TR.start_ts ) AS startNS, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D - ON D.id = S.name_id - LEFT JOIN app_name AS APP - ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 - ON D2.id = APP.app_key - where - D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN') - and - D2.data in ('BACKGROUND_ENERGY','FOREGROUND_ENERGY','SCREEN_ON_ENERGY','SCREEN_OFF_ENERGY','ENERGY','APPNAME') - GROUP BY - S.serial, - APP.app_key, - D.data, - D2.data - ORDER BY - eventName;`, - {} - ); - -export const getTabPowerDetailsData = ( - leftNs: number, - rightNs: number -): Promise< - Array<{ - startNS: number; - eventName: string; - appKey: string; - eventValue: string; - }> -> => - query( - 'getTabPowerDetailsData', - `SELECT - ( S.ts - TR.start_ts ) AS startNS, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - where - D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN') - and - D2.data in ('APPNAME') - GROUP BY - S.serial, - APP.app_key, - D.data, - D2.data - UNION - SELECT - ( S.ts - TR.start_ts ) AS startNS, - D1.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D1 ON D1.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - where - D1.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN') - and - D2.data in ('CHARGE','BACKGROUND_TIME','SCREEN_ON_TIME','SCREEN_OFF_TIME','LOAD','USAGE','DURATION','CAMERA_ID', - 'FOREGROUND_COUNT','BACKGROUND_COUNT','SCREEN_ON_COUNT','SCREEN_OFF_COUNT','COUNT','UID','FOREGROUND_DURATION', - 'FOREGROUND_ENERGY','BACKGROUND_DURATION','BACKGROUND_ENERGY','SCREEN_ON_DURATION','SCREEN_ON_ENERGY', - 'SCREEN_OFF_DURATION','SCREEN_OFF_ENERGY','ENERGY') - and - (S.ts - TR.start_ts) >= $leftNS - and (S.ts - TR.start_ts) <= $rightNS - GROUP BY - S.serial, - APP.app_key, - D1.data, - D2.data - ORDER BY - eventName;`, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const getTabPowerBatteryData = ( - rightNs: number -): Promise< - Array<{ - ts: number; - eventName: string; - appKey: string; - eventValue: string; - }> -> => - query( - 'getTabPowerBatteryData', - `select - MAX(S.ts) as ts, - D.data as eventName, - D2.data as appKey, - group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as eventValue - from - trace_range AS TR, - hisys_event_measure as S - left join - data_dict as D - on - D.id=S.name_id - left join - app_name as APP - on - APP.id=S.key_id - left join - data_dict as D2 - on - D2.id=APP.app_key - where - D.data = 'POWER_IDE_BATTERY' - and D2.data in ('GAS_GAUGE','CHARGE','SCREEN','LEVEL','CURRENT','CAPACITY','UID') - and (S.ts - TR.start_ts) >= 0 - and (S.ts - TR.start_ts) <= $rightNS - group by APP.app_key,D.data,D2.data;`, - { $rightNS: rightNs } - ); - -export const queryMaxStateValue = ( - eventName: string -): Promise< - Array<{ - type: string; - maxValue: number; - }> -> => - query( - 'queryMaxStateValue', - `select - D.data as type, - max(S.int_value) as maxValue - from trace_range AS TR,hisys_event_measure as S - left join data_dict as D on D.id=S.name_id - left join app_name as APP on APP.id=S.key_id - left join data_dict as D2 on D2.id=APP.app_key - where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end) - and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME') - group by APP.app_key,D.data,D2.data;`, - { $eventName: eventName } - ); - -export const queryStateData = (eventName: string): Promise> => - query( - 'queryStateData', - `select - (S.ts-TR.start_ts) as startNs, - D.data as type, - D2.data as appKey, - S.int_value as value - from trace_range AS TR,hisys_event_measure as S - left join data_dict as D on D.id=S.name_id - left join app_name as APP on APP.id=S.key_id - left join data_dict as D2 on D2.id=APP.app_key - where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end) - and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME') - group by S.serial,APP.app_key,D.data,D2.data;`, - { $eventName: eventName } - ); - -export const queryEnergyAppName = (): Promise< - Array<{ - string_value: string | null; - }> -> => - query( - 'queryEnergyAppName', - ` - SELECT - DISTINCT hisys_event_measure.string_value from data_dict - left join app_name on app_name.app_key=data_dict.id - left join hisys_event_measure on hisys_event_measure.key_id = app_name.id - where data_dict.data = "APPNAME"` - ); - -export const queryAnomalyDetailedData = (leftNs: number, rightNs: number): Promise> => - query( - 'queryAnomalyDetailedData', - `select - S.ts, - D.data as eventName, - D2.data as appKey, - group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as Value - from trace_range AS TR,hisys_event_measure as S - left join data_dict as D on D.id=S.name_id - left join app_name as APP on APP.id=S.key_id - left join data_dict as D2 on D2.id=APP.app_key - where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_ALARM_WAKEUP','ANOMALY_KERNEL_WAKELOCK', - 'ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_CPU_ENERGY','ANOMALY_WAKEUP') - and D2.data in ('APPNAME') - and (S.ts - TR.start_ts) >= $leftNS - and (S.ts - TR.start_ts) <= $rightNS - group by S.serial,APP.app_key,D.data,D2.data - union - select - S.ts, - D.data as eventName, - D2.data as appKey, - group_concat((case when S.type == 1 then S.string_value else S.int_value end), ',') as Value - from trace_range AS TR,hisys_event_measure as S - left join data_dict as D on D.id = S.name_id - left join app_name as APP on APP.id = S.key_id - left join data_dict as D2 on D2.id = APP.app_key - where D.data in ('ANOMALY_SCREEN_OFF_ENERGY', 'ANOMALY_ALARM_WAKEUP', 'ANOMALY_KERNEL_WAKELOCK', - 'ANOMALY_RUNNINGLOCK', 'ANORMALY_APP_ENERGY', 'ANOMALY_GNSS_ENERGY', 'ANOMALY_CPU_HIGH_FREQUENCY', 'ANOMALY_CPU_ENERGY', 'ANOMALY_WAKEUP') - and D2.data not in ('pid_', 'tid_', 'type_', 'tz_', 'uid_', 'domain_', 'id_', 'level_', 'info_', 'tag_', 'APPNAME') - and (S.ts - TR.start_ts) >= $leftNS - and (S.ts - TR.start_ts) <= $rightNS - group by S.serial, APP.app_key, D.data, D2.data;`, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -export const queryGpuTotalType = (): Promise> => - query( - 'queryGpuTotalType', - ` - select distinct module_name_id id,data - from memory_window_gpu A, trace_range TR left join data_dict B on A.module_name_id = B.id - where window_name_id = 0 - and A.ts < TR.end_ts - ` - ); - -export const queryGpuDataByTs = ( - ts: number, - window: number, - module: number | null -): Promise< - Array<{ - windowNameId: number; - windowId: number; - moduleId: number; - categoryId: number; - size: number; - }> -> => { - let condition = - module === null - ? `and window_name_id = ${window}` - : `and window_name_id = ${window} and module_name_id = ${module}`; - let sql = `select window_name_id as windowNameId, - window_id as windowId, - module_name_id as moduleId, - category_name_id as categoryId, - size - from memory_window_gpu, trace_range - where ts - start_ts = ${ts} ${condition} - `; - return query('queryGpuDataByTs', sql); -}; - -export const queryGpuTotalData = (moduleId: number | null): Promise> => { - let moduleCondition = moduleId === null ? '' : `and module_name_id = ${moduleId}`; - let sql = ` - select (ts - start_ts) startNs, sum(size) value - from memory_window_gpu,trace_range - where window_name_id = 0 ${moduleCondition} - and ts< end_ts - group by ts; - `; - return query('queryGpuTotalData', sql); -}; - -// GL 或 Graph 泳道图 -export const queryGpuData = (ipid: number, name: string): Promise> => { - let sql = ` - select (ts - start_ts) startNs,sum(value) value - from process_measure, trace_range - where filter_id = ( - select id - from process_measure_filter - where name = ${name} and ipid = ${ipid} - ) - and ts between start_ts and end_ts - group by ts; - `; - return query('queryGpuData', sql); -}; -// 判断VM Tracker Gl或 Graph泳道图是否有数据 -export const queryisExistsGpuData = ( - ipid: number, - name: string -): Promise> => { - let sql = ` - SELECT EXISTS ( - SELECT 1 - FROM process_measure, trace_range - WHERE filter_id = ( - SELECT id - FROM process_measure_filter - WHERE name = ${name} AND ipid = ${ipid} - ) - AND ts BETWEEN start_ts AND end_ts - ) AS data_exists; - `; - return query('queryGpuData', sql); -}; - -// GL 或 Graph 框选Tab页 -export const queryGpuDataTab = ( - ipid: number, - leftNs: number, - rightNs: number, - interval: number, - name: string -): Promise> => { - let sql = ` - select (ts - start_ts) startTs,sum(value) * 1024 size - from process_measure, trace_range - where filter_id = ( - select id - from process_measure_filter - where name = ${name} and ipid = ${ipid} - ) - and not ((startTs + ${interval} < ${leftNs}) or (startTs > ${rightNs})) - group by ts; - `; - return query('queryGpuGLDataByRange', sql); -}; - -export const queryGpuDataByRange = ( - leftNs: number, - rightNs: number, - interval: number -): Promise< - Array<{ - startTs: number; - windowId: number; - moduleId: number; - categoryId: number; - avgSize: number; - maxSize: number; - minSize: number; - }> -> => { - let sql = `select (ts - start_ts) startTs, - window_name_id windowId, - module_name_id moduleId, - category_name_id categoryId, - avg(size) avgSize, - max(size) maxSize, - min(size) minSize - from memory_window_gpu,trace_range - where not ((startTs + ${interval} < ${leftNs}) or (startTs > ${rightNs})) - group by window_name_id,module_name_id,category_name_id - order by avgSize DESC; - `; - return query('queryGpuWindowData', sql); -}; - -export const queryGpuWindowData = ( - windowId: number, - moduleId: number | null -): Promise> => { - let moduleCondition = moduleId === null ? '' : `and module_name_id = ${moduleId}`; - let sql = ` - select (ts - start_ts) startNs, sum(size) value - from memory_window_gpu,trace_range - where window_name_id = ${windowId} ${moduleCondition} - and ts < end_ts - group by ts; - `; - return query('queryGpuWindowData', sql); -}; - -export const queryGpuWindowType = (): Promise> => - query( - 'queryGpuWindowType', - ` - select distinct A.window_name_id as id,B.data, null as pid -from memory_window_gpu A, trace_range tr left join data_dict B on A.window_name_id = B.id -where window_name_id != 0 -and A.ts < tr.end_ts -union all -select distinct A.module_name_id id, B.data, A.window_name_id pid -from memory_window_gpu A, trace_range TR left join data_dict B on A.module_name_id = B.id -where window_name_id != 0 -and A.ts < TR.end_ts - ` - ); - -export const querySmapsExits = (): Promise> => - query( - 'querySmapsExits', - `select - event_name - from stat s - where s.event_name = 'trace_smaps' - and s.stat_type ='received' and s.count > 0` - ); - -export const querySmapsData = (columnName: string): Promise> => - query( - 'querySmapsCounterData', - `SELECT (A.timestamp - B.start_ts) as startNs, sum(${columnName}) * 1024 as value, $columnName as name FROM smaps A,trace_range B WHERE A.timestamp < B.end_ts GROUP by A.timestamp;`, - { $columnName: columnName } - ); - -export const querySmapsDataMax = (columnName: string): Promise> => - query( - 'querySmapsDataMax', - ` - SELECT (A.timestamp - B.start_ts) as startNS,sum(${columnName}) as max_value FROM smaps A,trace_range B GROUP by A.timestamp order by max_value desc LIMIT 1` - ); - -export const getTabSmapsMaxSize = (leftNs: number, rightNs: number, dur: number): Promise> => - query( - 'getTabSmapsMaxRss', - ` -SELECT (A.timestamp - B.start_ts) as startNS, sum(virtaul_size) *1024 as max_value FROM smaps A,trace_range B where startNS <= $rightNs and (startNS+$dur)>=$leftNs`, - { $rightNs: rightNs, $leftNs: leftNs, $dur: dur } - ); - -export const getTabSmapsData = (leftNs: number, rightNs: number, dur: number): Promise> => - query( - 'getTabSmapsData', - ` - SELECT - (A.timestamp - t.start_ts) AS startNs, - start_addr as startAddr, - end_addr as endAddr, - A.type, - resident_size * 1024 AS rss, - protection_id as pid, - pss * 1024 as pss,virtaul_size * 1024 AS size,reside,A.path_id AS path, - shared_clean * 1024 as sharedClean,shared_dirty * 1024 as sharedDirty,private_clean * 1024 as privateClean, - private_dirty * 1024 as privateDirty,swap * 1024 as swap,swap_pss * 1024 as swapPss - FROM smaps A, - trace_range AS t - WHERE (startNs) <= $rightNs and (startNs+$dur) >=$leftNs`, - { $rightNs: rightNs, $leftNs: leftNs, $dur: dur }, - 'exec' - ); - -export const getTabVirtualMemoryType = (startTime: number, endTime: number): Promise> => - query( - 'getTabVirtualMemoryType', - ` - SELECT type from paged_memory_sample s,trace_range t - WHERE s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts group by type`, - { $startTime: startTime, $endTime: endTime }, - 'exec' - ); - -export const getTabIoCompletionTimesType = (startTime: number, endTime: number): Promise> => - query( - 'getTabIoCompletionTimesType', - ` - SELECT tier from bio_latency_sample s,trace_range t - WHERE s.start_ts + s.latency_dur between $startTime + t.start_ts and $endTime + t.start_ts group by tier`, - { $startTime: startTime, $endTime: endTime }, - 'exec' - ); - -export const getCpuLimitFreqId = (): Promise> => - query( - 'getCpuMaxMinFreqId', - ` - select cpu,MAX(iif(name = 'cpu_frequency_limits_max',id,0)) as maxFilterId,MAX(iif(name = 'cpu_frequency_limits_min',id,0)) as minFilterId from cpu_measure_filter where name in ('cpu_frequency_limits_max','cpu_frequency_limits_min') group by cpu -`, - {} - ); - -export const getCpuLimitFreqMax = (filterIds: string): Promise> => { - return query( - 'getCpuLimitFreqMax', - ` - select max(value) as maxValue,filter_id as filterId from measure where filter_id in (${filterIds}) group by filter_id -`, - {} - ); -}; - -export const getCpuLimitFreq = (maxId: number, minId: number, cpu: number): Promise> => - query( - 'getCpuLimitFreq', - ` - select ts - T.start_ts as startNs, - dur, - max(value) as max, - min(value) as min, - $cpu as cpu - from measure,trace_range T where filter_id in ($maxId,$minId) group by ts -`, - { $maxId: maxId, $minId: minId, $cpu: cpu } - ); - -export const getCpuLimitFreqBoxSelect = ( - arr: Array<{ - maxFilterId: string; - minFilterId: string; - cpu: string; - }>, - rightNS: number -): Promise> => { - let ids = []; - let condition = `(case`; - for (let item of arr) { - condition = `${condition} when filter_id in (${item.maxFilterId}, ${item.minFilterId}) then ${item.cpu}`; - ids.push(item.maxFilterId, item.minFilterId); - } - condition = `${condition} else -1 end) as cpu`; - let sql = ` - select - ts - T.start_ts as startNs, - dur, - max(value) as max, - min(value) as min, - ${condition} - from measure,trace_range T - where filter_id in (${ids.join(',')}) - and ts - T.start_ts < ${rightNS} - group by ts - `; - console.log(sql); - return query('getCpuLimitFreqBoxSelect', sql, {}); -}; - -export const queryEnergyEventExits = (): Promise> => - query( - 'queryEnergyEventExits', - `select - event_name - from stat s - where s.event_name = 'trace_hisys_event' - and s.stat_type ='received' and s.count > 0` - ); - -export const queryEbpfSamplesCount = (startTime: number, endTime: number, ipids: number[]): Promise> => - query( - 'queryEbpfSamplesCount', - ` - select -fsCount, - vmCount from -(select count(1) as fsCount from file_system_sample s,trace_range t where s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts ${ - ipids.length > 0 ? `and s.ipid in (${ipids.join(',')})` : '' - }) -,(select count(1) as vmCount from paged_memory_sample s,trace_range t where s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts ${ - ipids.length > 0 ? `and s.ipid in (${ipids.join(',')})` : '' - }); -`, - { $startTime: startTime, $endTime: endTime } - ); - -export const querySysLockDetailsData = (rightNs: number, eventName: string): Promise> => - query( - 'querySysLockDetailsData', - `SELECT - ( S.ts - TR.start_ts ) AS ts, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - WHERE - D.data in ($eventName) - AND - D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') - AND - (S.ts - TR.start_ts) <= $rightNS - GROUP BY - S.serial, APP.app_key, D.data, D2.data;`, - { $rightNS: rightNs, $eventName: eventName } - ); - -export const queryStateInitValue = (eventName: string, keyName: string): Promise> => - query( - 'queryStateInitValue', - `select - 0 as startNs, - $eventName as type, - '' as appKey, - (case $keyName - when 'brightness' then device_state.brightness - when 'wifi' then device_state.wifi - when 'bt_state' then device_state.bt_state - when 'location' then device_state.location - else 0 end) as value - from device_state;`, - { $eventName: eventName, $keyName: keyName } - ); - -export const querySysLocationDetailsData = (rightNs: number, eventName: string): Promise> => - query( - 'querySysLocationDetailsData', - `SELECT - ( S.ts - TR.start_ts ) AS ts, - D.data AS eventName, - D2.data AS appKey, - group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue - FROM - trace_range AS TR, - hisys_event_measure AS S - LEFT JOIN data_dict AS D ON D.id = S.name_id - LEFT JOIN app_name AS APP ON APP.id = S.key_id - LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key - WHERE - D.data in ($eventName) - and - D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') - and (S.ts - TR.start_ts) <= $rightNS - GROUP BY - S.serial, - APP.app_key, - D.data, - D2.data;`, - { $rightNS: rightNs, $eventName: eventName } - ); -export const queryNativeMemoryRealTime = (): Promise> => - query( - 'queryNativeMemoryRealTime', - `select cs.ts,cs.clock_name from datasource_clockid dc left join clock_snapshot cs on dc.clock_id = cs.clock_id where data_source_name = 'memory-plugin' or data_source_name = 'nativehook' -`, - {} - ); - -export const queryBootTime = (): Promise> => - query( - 'queryBootTime', - `select CS.ts -TR.start_ts as ts ,clock_name from clock_snapshot as CS ,trace_range as TR - where clock_name = 'boottime'`, - {} - ); - -export const queryConfigEnergyAppName = (): Promise< - Array<{ - process_name: string; - }> -> => - query( - 'queryConfigEnergyAppName', - ` - SELECT value from trace_config where trace_source = 'hisys_event' and key = 'process_name'` - ); - -export const queryClockData = (): Promise< - Array<{ - name: string; - num: number; - srcname: string; - }> -> => - query( - 'queryClockData', - ` - select name || ' Frequency' name, COUNT(*) num, name srcname -from (select id, name - from clock_event_filter - where type = 'clock_set_rate') -group by name -union -select name || ' State' name, COUNT(*) num, name srcname -from (select id, name - from clock_event_filter - where type != 'clock_set_rate') -group by name; -` - ); - -export const queryClockFrequency = (clockName: string): Promise> => - query( - 'queryClockFrequency', - `with freq as ( select measure.filter_id, measure.ts, measure.type, measure.value from clock_event_filter -left join measure -where clock_event_filter.name = $clockName and clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id -order by measure.ts) -select freq.filter_id as filterId,freq.ts - r.start_ts as startNS,freq.type,freq.value from freq,trace_range r order by startNS`, - { $clockName: clockName } - ); - -export const queryClockState = (clockName: string): Promise> => - query( - 'queryClockState', - `with state as ( -select filter_id, ts, endts, endts-ts as dur, type, value from -(select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value from clock_event_filter,trace_range -left join measure -where clock_event_filter.name = $clockName and clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id -order by measure.ts)) -select s.filter_id as filterId,s.ts-r.start_ts as startNS,s.type,s.value,s.dur from state s,trace_range r`, - { $clockName: clockName } - ); - -export const queryScreenState = (): Promise> => - query( - 'queryScreenState', - `select m.type, m.ts-r.start_ts as startNS, value, filter_id as filterId from measure m,trace_range r where filter_id in (select id from process_measure_filter where name = 'ScreenState') order by startNS; -` - ); - -export const queryIrqList = (): Promise> => - query('queryIrqList', `select cat as name,callid as cpu from irq where cat!= 'ipi' group by cat,callid`); - -export const queryAllIrqNames = (): Promise> => { - return query( - 'queryAllIrqNames', - `select id,case when cat = 'ipi' then 'IPI' || name else name end as ipiName, name from irq;` - ); -}; - -export const queryIrqData = (callid: number, cat: string): Promise> => { - let sqlSoftIrq = ` - select i.ts - t.start_ts as startNS,i.dur,i.name,i.depth,argsetid as argSetId,i.id from irq i, -trace_range t where i.callid = ${callid} and i.cat = 'softirq' - `; - let sqlIrq = ` - select i.ts - t.start_ts as startNS,i.dur, - case when i.cat = 'ipi' then 'IPI' || i.name else i.name end as name, - i.depth, - argsetid as argSetId, - i.id - from irq i,trace_range t - where i.callid = ${callid} and ((i.cat = 'irq' and i.flag ='1') or i.cat = 'ipi') - `; - return query('queryIrqData', cat === 'irq' ? sqlIrq : sqlSoftIrq, {}); -}; - -export const queryIrqDataBoxSelect = (callIds: Array, startNS: number, endNS: number): Promise> => { - let sqlIrq = ` -select case when i.cat = 'ipi' then 'IPI' || i.name else i.name end as irqName, - sum(dur) as wallDuration, - max(dur) as maxDuration, - count(1) as count, - avg(ifnull(dur, 0)) as avgDuration -from irq i, - trace_range t -where ((i.cat = 'irq' and i.flag = '1') or i.cat = 'ipi') - and callid in (${callIds.join(',')}) - and max(i.ts - t.start_ts, ${startNS}) <= min(i.ts - t.start_ts + dur, ${endNS}) -group by irqName; - `; - return query('queryIrqDataBoxSelect', callIds.length > 0 ? sqlIrq : '', {}); -}; - -export const querySoftIrqDataBoxSelect = ( - callIds: Array, - startNS: number, - endNS: number -): Promise> => { - let sqlIrq = ` -select i.name as irqName, - sum(dur) as wallDuration, - max(dur) as maxDuration, - count(1) as count, - avg(ifnull(dur, 0)) as avgDuration -from irq i, - trace_range t -where callid in (${callIds.join(',')}) - and i.cat = 'softirq' - and max(i.ts - t.start_ts, ${startNS}) <= min(i.ts - t.start_ts + dur, ${endNS}) -group by irqName; - `; - return query('querySoftIrqDataBoxSelect', callIds.length > 0 ? sqlIrq : '', {}); -}; - -export const queryAllJankProcess = (): Promise< - Array<{ - pid: number; - }> -> => - query( - 'queryAllJankProcess', - ` - SELECT DISTINCT p.pid - FROM frame_slice AS a - LEFT JOIN process AS p ON a.ipid = p.ipid - ` - ); - -export const queryAllExpectedData = (): Promise> => - query( - 'queryAllExpectedData', - ` - SELECT - a.id, - (a.ts - TR.start_ts) AS ts, - a.vsync as name, - a.type, - a.dur, - p.pid, - p.name as cmdline - FROM frame_slice AS a, trace_range AS TR - LEFT JOIN process AS p ON a.ipid = p.ipid - WHERE a.type = 1 - and (a.flag <> 2 or a.flag is null) - ORDER BY a.ipid,ts;` - ); - -export const queryAllActualData = (): Promise> => - query( - 'queryAllActualData', - ` - SELECT - a.id, - (a.ts - TR.start_ts) AS ts, - a.vsync AS name, - a.type, - a.dur, - a.src AS src_slice, - a.flag AS jank_tag, - a.dst AS dst_slice, - p.pid, - p.name AS cmdline, - (case when p.name like '%render_service' then 'render_service' else 'app' end) as frame_type - FROM frame_slice AS a, trace_range AS TR - LEFT JOIN process AS p ON a.ipid = p.ipid - WHERE a.type = 0 - AND a.flag <> 2 - ORDER BY a.ipid, ts;` - ); - -export const queryActualFrameDate = (): Promise> => - query( - 'queryActualFrameDate', - `SELECT - sf.id, - 'frameTime' as frame_type, - fs.ipid, - fs.vsync as name, - fs.dur as app_dur, - (sf.ts + sf.dur - fs.ts) as dur, - (fs.ts - TR.start_ts) AS ts, - fs.type, - (case when (sf.flag == 1 or fs.flag == 1 ) then 1 when (sf.flag == 3 or fs.flag == 3 ) then 3 else 0 end) as jank_tag, - pro.pid, - pro.name as cmdline, - (sf.ts - TR.start_ts) AS rs_ts, - sf.vsync AS rs_vsync, - sf.dur AS rs_dur, - sf.ipid AS rs_ipid, - proc.pid AS rs_pid, - proc.name AS rs_name - FROM frame_slice AS fs - LEFT JOIN process AS pro ON pro.id = fs.ipid - LEFT JOIN frame_slice AS sf ON fs.dst = sf.id - LEFT JOIN process AS proc ON proc.id = sf.ipid - LEFT JOIN trace_range TR - WHERE fs.dst IS NOT NULL - AND fs.type = 0 - AND fs.flag <> 2 - UNION - SELECT - -1 as id, - 'frameTime' as frame_type, - fs.ipid, - fs.vsync as name, - fs.dur as app_dur, - fs.dur, - (fs.ts - TR.start_ts) AS ts, - fs.type, - fs.flag as jank_tag, - pro.pid, - pro.name as cmdline, - NULL AS rs_ts, - NULL AS rs_vsync, - NULL AS rs_dur, - NULL AS rs_ipid, - NULL AS rs_pid, - NULL AS rs_name - FROM frame_slice AS fs - LEFT JOIN process AS pro ON pro.id = fs.ipid - LEFT JOIN trace_range TR - WHERE fs.dst IS NULL - AND pro.name NOT LIKE '%render_service%' - AND fs.type = 0 - AND fs.flag <> 2 - ORDER BY ts;` - ); - -export const queryExpectedFrameDate = (): Promise> => - query( - 'queryExpectedFrameDate', - ` - SELECT - sf.id, - 'frameTime' as frame_type, - fs.ipid, - fs.vsync as name, - fs.dur as app_dur, - (sf.ts + sf.dur - fs.ts) as dur, - (fs.ts - TR.start_ts) AS ts, - fs.type, - fs.flag, - pro.pid, - pro.name as cmdline, - (sf.ts - TR.start_ts) AS rs_ts, - sf.vsync AS rs_vsync, - sf.dur AS rs_dur, - sf.ipid AS rs_ipid, - proc.pid AS rs_pid, - proc.name AS rs_name - FROM frame_slice AS fs - LEFT JOIN process AS pro ON pro.id = fs.ipid - LEFT JOIN frame_slice AS sf ON fs.dst = sf.id - LEFT JOIN process AS proc ON proc.id = sf.ipid - LEFT JOIN trace_range TR - WHERE fs.dst IS NOT NULL - AND fs.type = 1 - UNION - SELECT - -1 as id, - 'frameTime' as frame_type, - fs.ipid, - fs.vsync as name, - fs.dur as app_dur, - fs.dur, - (fs.ts - TR.start_ts) AS ts, - fs.type, - fs.flag, - pro.pid, - pro.name as cmdline, - NULL AS rs_ts, - NULL AS rs_vsync, - NULL AS rs_dur, - NULL AS rs_ipid, - NULL AS rs_pid, - NULL AS rs_name - FROM frame_slice AS fs - LEFT JOIN process AS pro ON pro.id = fs.ipid - LEFT JOIN trace_range TR - WHERE fs.dst IS NULL - AND pro.name NOT LIKE '%render_service%' - AND fs.type = 1 - ORDER BY ts;` - ); - -export const queryFlowsData = (src_slice: Array): Promise> => - query( - 'queryFlowsData', - ` - SELECT fs.vsync AS name, - p.pid, - p.name AS cmdline, - fs.type - FROM frame_slice AS fs - LEFT JOIN process AS p ON fs.ipid = p.ipid - WHERE fs.type = 0 - AND fs.id IN (${src_slice.join(',')});` - ); - -export const queryJumpJanksData = (processId: number, vsync: number): Promise> => - query( - 'queryJumpJanksData', - ` - SELECT - fs.id, - fs.ts - TR.start_ts as ts, - fs.vsync AS name, - fs.type, - fs.dur, - 0 as depth, - 'app' as frame_type, - fs.src as src_slice, - fs.flag as jank_tag, - fs.dst as dst_slice, - p.pid, - p.name AS cmdline - FROM frame_slice AS fs, trace_range as TR - LEFT JOIN process AS p ON fs.ipid = p.ipid - WHERE fs.type = 0 and p.pid = $processId and fs.vsync = $vsync;`,{ $processId: processId, $vsync: vsync } - ); - -export const queryPrecedingData = (dst_slice: string): Promise> => - query( - 'queryFlowsData', - ` - SELECT a.vsync AS name, - p.pid, - p.name AS cmdline, - a.type - FROM frame_slice AS a - LEFT JOIN process AS p ON a.ipid = p.ipid - WHERE a.type = 0 - AND a.id = $dst_slice;`, - { $dst_slice: dst_slice } - ); - -export const queryFrameTimeData = (): Promise> => - query( - 'queryFrameTimeData', - ` - SELECT DISTINCT p.pid - FROM frame_slice AS a - LEFT JOIN process AS p - ON a.ipid = p.ipid;` - ); - -export const queryGpuDur = (id: number): Promise => - query( - 'queryGpuDur', - ` - SELECT dur AS gpu_dur - FROM gpu_slice - WHERE frame_row = $id;`, - { $id: id } - ); - -export const queryAllSnapshotNames = (): Promise> => - query( - 'queryAllSnapshotNames', - `SELECT f.id, - f.file_name AS name - FROM - js_heap_files f, - trace_range t - WHERE - ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' ) - OR f.file_name = 'Timeline'` - ); -export const queryHeapFile = (): Promise> => - query( - 'queryHeapFile', - `SELECT f.id, - f.file_name AS name, - f.start_time - t.start_ts AS startTs, - f.end_time - t.start_ts AS endTs, - f.self_size AS size, - c.pid - FROM - js_heap_files f, - trace_range t, - js_config c - WHERE - ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' ) - OR f.file_name = 'Timeline'` - ); - -export const queryHeapInfo = (fileId: number): Promise> => - query( - 'queryHeapInfo', - `SELECT file_id as fileId, key, type, int_value as intValue, str_value as strValue - FROM js_heap_info WHERE file_id = ${fileId}` - ); - -export const queryHeapNode = (fileId: number): Promise> => - query( - 'queryHeapNode', - `SELECT node_index as nodeIndex,type,name as nameIdx,id,self_size as selfSize,edge_count as edgeCount,trace_node_id as traceNodeId,detachedness - FROM js_heap_nodes WHERE file_id = ${fileId}` - ); - -export const queryHeapEdge = (fileId: number): Promise> => - query( - 'queryHeapEdge', - `SELECT edge_index as edgeIndex,type,name_or_index as nameOrIndex,to_node as nodeId,from_node_id as fromNodeId,to_node_id as toNodeId - FROM js_heap_edges WHERE file_id = ${fileId}` - ); - -export const queryHeapFunction = (fileId: number): Promise> => - query( - 'queryHeapFunction', - `SELECT function_index as index ,function_id as id ,name,script_name as scriptName,script_id as scriptId,line,column - FROM js_heap_trace_function_info WHERE file_id = ${fileId}` - ); - -export const queryHeapTraceNode = (fileId: number): Promise> => - query( - 'queryHeapTraceNode', - `SELECT F.name, - F.script_name as scriptName, - F.script_id as scriptId, - F.column, - F.line, - N.id, - N.function_info_index as functionInfoIndex, - N.parent_id as parentId, - N.count, - N.size, - IFNULL( S.live_count, 0 ) AS liveCount, - IFNULL( S.live_size, 0 ) AS liveSize - FROM - js_heap_trace_node N - LEFT JOIN ( - SELECT - trace_node_id as traceNodeId, - SUM( self_size ) AS liveSize, - count( * ) AS liveCount - FROM - js_heap_nodes - WHERE - file_id = ${fileId} - AND trace_node_id != 0 - GROUP BY - trace_node_id - ) S ON N.id = S.trace_node_id - LEFT JOIN js_heap_trace_function_info F ON (F.file_id = N.file_id - AND F.function_index = N.function_info_index) - WHERE - N.file_id = ${fileId} - ORDER BY - N.id` - ); - -export const queryHeapSample = (fileId: number): Promise> => - query( - 'queryHeapSample', - `SELECT timestamp_us as timestamp , last_assigned_id as lastAssignedId, 0 as size - FROM js_heap_sample WHERE file_id = ${fileId}` - ); - -export const queryHeapLocation = (fileId: number): Promise> => - query( - 'queryHeapLocation', - `SELECT object_index as objectIndex,script_id as scriptId ,column - FROM js_heap_location WHERE file_id = ${fileId}` - ); - -export const queryHeapString = (fileId: number): Promise> => - query( - 'queryHeapString', - `SELECT string - FROM js_heap_string WHERE file_id = ${fileId}` - ); -export const queryTraceRange = (): Promise> => - query('queryTraceRange', `SELECT t.start_ts as startTs, t.end_ts as endTs FROM trace_range t`); - -export const queryHiPerfProcessCount = ( - leftNs: number, - rightNs: number, - cpus: Array, - threads: Array, - processes: Array -): Promise> => { - let str = ''; - if (processes.length > 0) { - str = ` and C.process_id in (${processes.join(',')})`; - } - if (threads.length > 0) { - str = ` and A.thread_id in (${threads.join(',')}) `; - } - if (processes.length > 0 && threads.length > 0) { - str = ` and (C.process_id in (${processes.join(',')}) or A.thread_id in (${threads.join(',')}))`; - } - if (cpus.length > 0) { - str = ` and A.cpu_id in (${cpus.join(',')})`; - } - if (cpus.length > 0 && processes.length > 0) { - str = ` and (C.process_id in (${processes.join(',')}) or A.cpu_id in (${cpus.join(',')}))`; - } - return query( - 'queryHiPerfProcessCount', - ` - select C.process_id as pid, - (A.timestamp_trace - R.start_ts) as time, - C.thread_name as threadName, - A.thread_id as tid, - A.id, - A.callchain_id - from perf_sample A,trace_range R - left join perf_thread C on A.thread_id = C.thread_id and A.thread_id != 0 - where time >= $leftNs and time <= $rightNs and A.callchain_id > 0 - ${str} - `, - { $leftNs: leftNs, $rightNs: rightNs } - ); -}; - -export const queryConcurrencyTask = ( - itid: number, - selectStartTime: number, - selectEndTime: number -): Promise => - query( - 'queryConcurrencyTask', - `SELECT thread.tid, - thread.ipid, - callstack.name AS funName, - callstack.ts AS startTs, - (case when callstack.dur = -1 then (SELECT end_ts FROM trace_range) else callstack.dur end) as dur, - callstack.id, - task_pool.priority, - task_pool.allocation_task_row AS allocationTaskRow, - task_pool.execute_task_row AS executeTaskRow, - task_pool.return_task_row AS returnTaskRow, - task_pool.execute_id AS executeId - FROM thread - LEFT JOIN callstack ON thread.id = callstack.callid - LEFT JOIN task_pool ON callstack.id = task_pool.execute_task_row - WHERE ipid in (SELECT thread.ipid - FROM thread - WHERE thread.itid = $itid) - AND thread.name = 'TaskWorkThread' - AND callstack.name LIKE 'H:Task Perform:%' - AND -- 左包含 - (($selectStartTime <= callstack.ts AND $selectEndTime > callstack.ts) - OR -- 右包含 - ($selectStartTime < callstack.ts + callstack.dur AND $selectEndTime >= callstack.ts + callstack.dur) - OR -- 包含 - ($selectStartTime >= callstack.ts AND $selectEndTime <= callstack.ts + - (case when callstack.dur = -1 then (SELECT end_ts FROM trace_range) else callstack.dur end)) - OR -- 被包含 - ($selectStartTime <= callstack.ts AND $selectEndTime >= callstack.ts + callstack.dur)) - ORDER BY callstack.ts;`, - { $itid: itid, $selectStartTime: selectStartTime, $selectEndTime: selectEndTime } - ); - -export const queryBySelectExecute = ( - executeId: string, - itid: number -): Promise< - Array<{ - tid: number; - allocation_task_row: number; - execute_task_row: number; - return_task_row: number; - priority: number; - }> -> => { - let sqlStr = `SELECT thread.tid, - task_pool.allocation_task_row, - task_pool.execute_task_row, - task_pool.return_task_row, - task_pool.priority - FROM task_pool - LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row - LEFT JOIN thread ON thread.id = callstack.callid - WHERE task_pool.execute_id = $executeId AND task_pool.execute_itid = $itid; - `; - return query('queryBySelectExecute', sqlStr, { $executeId: executeId, $itid: itid }); -}; - -export const queryTaskPoolOtherRelationData = ( - ids: Array, - tid: number -): Promise< - Array -> => { - let sqlStr = `select - c.ts-D.start_ts as startTs, - c.dur, - c.name as funName, - c.argsetid, - c.depth, - c.id as id, - A.itid as itid, - A.ipid as ipid - from thread A,trace_range D - left join callstack C on A.id = C.callid - where startTs not null and c.cookie is null and tid = $tid and c.id in (${ids.join(',')})`; - return query('queryTaskPoolOtherRelationData', sqlStr, { $ids: ids, $tid: tid }); -}; - -export const queryTaskPoolRelationData = ( - ids: Array, - tids: Array -): Promise< - Array -> => { - const sqlArray: Array = []; - if (ids.length > 0) { - for (let index = 0; index < ids.length; index++) { - if (index !== 0) { - sqlArray.push(`or`); - } - sqlArray.push(`( tid = ${tids[index]} and c.id = ${ids[index]})`); - } - } - let sql = sqlArray.join(' '); - let sqlStr = `select - c.ts-D.start_ts as startTs, - c.dur, - c.name as funName, - c.argsetid, - c.depth, - c.id as id, - A.itid as itid, - A.ipid as ipid - from thread A,trace_range D - left join callstack C on A.id = C.callid - where startTs not null and c.cookie is null and (${sql})`; - return query('queryTaskPoolRelationData', sqlStr); -}; - -export const queryBySelectAllocationOrReturn = ( - executeId: string, - itid: number -): Promise< - Array<{ - tid: number; - allocation_task_row: number; - execute_task_row: number; - return_task_row: number; - priority: number; - }> -> => { - let sqlStr = `SELECT thread.tid, - task_pool.allocation_task_row, - task_pool.execute_task_row, - task_pool.return_task_row, - task_pool.priority - FROM task_pool - LEFT JOIN callstack ON callstack.id = task_pool.execute_task_row - LEFT JOIN thread ON thread.id = callstack.callid - WHERE task_pool.execute_task_row IS NOT NULL AND task_pool.execute_id = $executeId - AND task_pool.allocation_itid = $itid; - `; - return query('queryBySelectAllocationOrReturn', sqlStr, { $executeId: executeId, $itid: itid }); -}; - -export const queryTaskListByExecuteTaskIds = ( - executeTaskIds: Array, - ipid: number -): Promise> => { - let sqlStr = ` - SELECT thread.ipid, - task_pool.allocation_task_row AS allocationTaskRow, - task_pool.execute_task_row AS executeTaskRow, - task_pool.return_task_row AS returnTaskRow, - task_pool.execute_id AS executeId, - task_pool.priority - FROM task_pool - LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row - LEFT JOIN thread ON thread.id = callstack.callid - WHERE task_pool.execute_id IN (${executeTaskIds.join(',')}) - AND thread.ipid = $ipid - AND task_pool.execute_task_row IS NOT NULL; - `; - return query('queryTaskListByExecuteTaskIds', sqlStr, { $executeTaskIds: executeTaskIds, $ipid: ipid }); -}; - -export const queryTaskPoolCallStack = (): Promise> => { - let sqlStr = `select * from callstack where name like 'H:Task%';`; - return query('queryTaskPoolCallStack', sqlStr, {}); -}; - -export const queryTaskPoolTotalNum = (itid: number) => - query( - 'queryTaskPoolTotalNum', - `SELECT thread.tid - FROM thread - LEFT JOIN callstack ON thread.id = callstack.callid - WHERE ipid in (SELECT thread.ipid - FROM thread - WHERE thread.itid = $itid) - AND thread.name = 'TaskWorkThread' - GROUP BY thread.tid;`, - { $itid: itid } - ); - -export const queryFrameAnimationData = (): Promise> => - query( - 'queryFrameAnimationData', - `SELECT a.id AS animationId, - 'Response delay' as status, - (CASE WHEN a.input_time NOT NULL - THEN ( a.input_time - R.start_ts ) - ELSE ( a.start_point - R.start_ts ) END - ) AS startTs, - (a.start_point - R.start_ts) AS endTs, - 0 AS frameInfo, - a.name AS name - FROM - animation AS a, - trace_range AS R - UNION - SELECT a.id AS animationId, - 'Completion delay' as status, - (CASE WHEN a.input_time NOT NULL - THEN ( a.input_time - R.start_ts ) - ELSE ( a.start_point - R.start_ts ) END - ) AS startTs, - (a.end_point - R.start_ts) AS endTs, - a.frame_info AS frameInfo, - a.name AS name - FROM - animation AS a, - trace_range AS R - ORDER BY - endTs;` - ); - -export const queryAnimationTimeRangeData = (): Promise> => - query( - 'queryAnimationTimeRangeData', - `SELECT 'Response delay' as status, - (CASE WHEN a.input_time NOT NULL - THEN ( a.input_time - R.start_ts ) - ELSE ( a.start_point - R.start_ts ) END - ) AS startTs, - (a.start_point - R.start_ts) AS endTs - FROM - animation AS a, - trace_range AS R - UNION - SELECT 'Completion delay' as status, - (CASE WHEN a.input_time NOT NULL - THEN ( a.input_time - R.start_ts ) - ELSE ( a.start_point - R.start_ts ) END - ) AS startTs, - (a.end_point - R.start_ts) AS endTs - FROM - animation AS a, - trace_range AS R - ORDER BY - endTs;` - ); - -export const queryFrameDynamicData = (): Promise => - query( - 'queryFrameDynamicData', - `SELECT - d.id, - d.x, - d.y, - d.width, - d.height, - d.alpha, - d.name AS appName, - (d.end_time - R.start_ts) AS ts - FROM - dynamic_frame AS d, - trace_range AS R - ORDER BY - d.end_time;` - ); - -export const queryDynamicIdAndNameData = (): Promise> => - query('queryDynamicIdAndNameData', `SELECT id, name AS appName FROM dynamic_frame;`); - -export const queryAnimationIdAndNameData = (): Promise< - Array<{ - id: number; - name: string; - info: string; - }> -> => query('queryAnimationIdAndNameData', `SELECT id, name, frame_info as info FROM animation;`); - -export const queryFrameApp = (): Promise< - Array<{ - name: string; - }> -> => - query( - 'queryFrameApp', - `SELECT - DISTINCT d.name - FROM - dynamic_frame AS d, - trace_range AS R - WHERE - d.end_time >= R.start_ts - AND - d.end_time <= R.end_ts;` - ); - -export const queryFrameSpacing = (): Promise> => - query( - 'queryFrameSpacing', - `SELECT - d.id, - d.width AS currentFrameWidth, - d.height AS currentFrameHeight, - d.name AS nameId, - (d.end_time - R.start_ts) AS currentTs, - d.x, - d.y - FROM - dynamic_frame AS d, - trace_range AS R - ORDER BY - d.end_time;` - ); - -export const queryPhysicalData = (): Promise> => - query( - 'queryPhysicalData', - `SELECT physical_width AS physicalWidth, - physical_height AS physicalHeight, - physical_frame_rate AS physicalFrameRate - FROM device_info;` - ); - -export const queryJsCpuProfilerConfig = (): Promise> => - query('queryJsCpuProfilerConfig', `SELECT pid, type, enable_cpu_Profiler as enableCpuProfiler FROM js_config`); -export const queryJsCpuProfilerData = (): Promise> => - query('queryJsCpuProfilerData', `SELECT 1 WHERE EXISTS(select 1 from js_cpu_profiler_node)`); - -export const queryJsMemoryData = (): Promise> => - query('queryJsMemoryData', `SELECT 1 WHERE EXISTS(SELECT 1 FROM js_heap_nodes)`); - -export const queryVmTrackerShmData = (iPid: number): Promise> => - query( - 'queryVmTrackerShmData', - `SELECT (A.ts - B.start_ts) as startNs, - sum(A.size) as value - FROM - memory_ashmem A,trace_range B - where - A.ipid = ${iPid} - AND A.ts < B.end_ts - and - flag = 0 - GROUP by A.ts`, - {} - ); - -export const queryisExistsShmData = (iPid: number): Promise> => - query( - 'queryisExistsShmData', - `SELECT EXISTS ( - SELECT 1 - FROM memory_ashmem A,trace_range B - where A.ipid = ${iPid} - AND A.ts < B.end_ts - AND flag = 0 - GROUP BY A.ts - ) AS data_exists`, - {} - ); - -export const queryVmTrackerShmSizeData = ( - leftNs: number, - rightNs: number, - iPid: number, - dur: number -): Promise> => - query( - 'queryVmTrackerShmSizeData', - `SELECT ( A.ts - B.start_ts ) AS startNS, - A.flag, - avg( A.size ) AS avg, - max( A.size ) AS max, - min( A.size ) AS min, - sum( A.size ) AS sum - FROM - memory_ashmem A, - trace_range B - WHERE - startNS <= ${rightNs} and (startNS+ ${dur}) >=${leftNs} - AND ipid = ${iPid}`, - {} - ); - -export const queryVmTrackerShmSelectionData = (startNs: number, ipid: number): Promise> => - query( - 'queryVmTrackerShmSelectionData', - `SELECT (A.ts - B.start_ts) as startNS,A.ipid, - A.fd,A.size,A.adj,A.ashmem_name_id as name, - A.ashmem_id as id,A.time,A.purged,A.ref_count as count, - A.flag - FROM memory_ashmem A,trace_range B - where startNS = ${startNs} and ipid = ${ipid};`, - {} - ); -export const getTabSmapsSampleData = (leftNs: number): Promise> => - query( - 'getTabSmapsSampleData', - ` - SELECT - (A.timestamp - t.start_ts) AS startNs, - start_addr as startAddr, - end_addr as endAddr, - A.type, - resident_size * 1024 AS rss, - protection_id as pid, - pss * 1024 as pss,virtaul_size * 1024 AS size,reside,A.path_id AS path, - shared_clean * 1024 as sharedClean,shared_dirty * 1024 as sharedDirty,private_clean * 1024 as privateClean, - private_dirty * 1024 as privateDirty,swap * 1024 as swap,swap_pss * 1024 as swapPss - FROM smaps A, - trace_range AS t - WHERE (startNs) = ${leftNs}`, - { $leftNs: leftNs }, - 'exec' - ); - -// VM Tracker Smaps Record Tab页 -export const querySmapsRecordTabData = ( - startNs: number, - ipid: number, - pixelmapId: number, - typeId: number -): Promise> => - query( - 'querySmapsRecordTabData', - `select 'RenderServiceCpu' as name, IFNULL(sum(mem_size), 0) as size from memory_rs_image, trace_range tr - where ipid = ${ipid} and (ts - tr.start_ts) = ${startNs} and type_id = ${pixelmapId} - union all - select 'SkiaCpu' as name, total_size as size from memory_cpu,trace_range - where (ts - start_ts) = ${startNs} - union all - select 'GLESHostCache' as name, 0 - union all - select 'VirtaulSize' as name, sum(virtaul_size) * 1024 as size from smaps, trace_range - where type = ${typeId} and (timeStamp - start_ts) = ${startNs}` - ); - -export const getTabSmapsStatisticMaxSize = (rightNs: number): Promise> => - query( - 'getTabSmapsStatisticMaxRss', - ` -SELECT (A.timestamp - B.start_ts) as startNS, sum(virtaul_size) * 1024 as max_value FROM smaps A,trace_range B where startNS = $rightNs`, - { $rightNs: rightNs } - ); -export const queryMemoryConfig = (): Promise> => - query( - 'queryMemoryConfiig', - `SELECT ipid as iPid, process.pid AS pid, - process.name AS processName, - (SELECT value FROM trace_config WHERE trace_source = 'memory_config' AND key = 'sample_interval') AS interval - FROM - trace_config - LEFT JOIN process ON value = ipid - WHERE - trace_source = 'memory_config' - AND key = 'ipid' - ;` - ); - -// Ability Monitor Dma泳道图 -export const queryDmaAbilityData = (): Promise> => - query( - 'queryDmaAbilityData', - `SELECT - (A.ts - B.start_ts) as startNs, - sum(A.size) as value, - E.data as expTaskComm, - A.flag as flag - FROM memory_dma A,trace_range B - left join data_dict as E on E.id=A.exp_task_comm_id - WHERE - A.flag = 0 - AND A.ts < B.end_ts - GROUP by A.ts - LIMIT 1;` - ); - -// Ability Monitor SkiaGpuMemory泳道图 -export const queryGpuMemoryAbilityData = (): Promise> => - query( - 'queryGpuMemoryAbilityData', - `SELECT - (A.ts - B.start_ts) as startNs, - sum(A.used_gpu_size) as value - FROM memory_process_gpu A,trace_range B - WHERE A.ts < B.end_ts - GROUP by A.ts - LIMIT 1;` - ); - -// VM Tracker Dma泳道图 -export const queryDmaSampsData = (process: number): Promise> => - query( - 'queryDmaSampsData', - `SELECT - (A.ts - B.start_ts) as startNs, - sum(A.size) as value, - A.flag as flag, - A.ipid as ipid, - E.data as expTaskComm - FROM memory_dma A,trace_range B - left join data_dict as E on E.id=A.exp_task_comm_id - WHERE - A.flag = 0 - AND $pid = A.ipid - AND A.ts < B.end_ts - GROUP by A.ts;`, - { $pid: process } - ); - -export const queryisExistsDmaData = (process: number): Promise> => - query( - 'queryisExistsDmaData', - `SELECT EXISTS ( - SELECT 1 - FROM memory_dma A,trace_range B - left join data_dict as E on E.id=A.exp_task_comm_id - WHERE A.flag = 0 - AND $pid = A.ipid - AND A.ts < B.end_ts - GROUP by A.ts - ) AS data_exists`, - { $pid: process } - ); - -// VM Tracker Gpu Memory泳道图 -export const queryGpuMemoryData = (processId: number): Promise> => - query( - 'queryGpuMemorySampsData', - `SELECT - (A.ts - B.start_ts) as startNs, - sum(A.used_gpu_size) as value, - A.ipid as ipid - FROM memory_process_gpu A,trace_range B - WHERE - $pid = A.ipid - AND A.ts < B.end_ts - GROUP by A.ts;`, - { $pid: processId } - ); - -// 判断VM Tracker Gpu Memory泳道图是否有数据 -export const queryisExistsGpuMemoryData = (processId: number): Promise> => - query( - 'queryisExistsGpuMemoryData', - `SELECT EXISTS ( - SELECT 1 - FROM memory_process_gpu A, trace_range B - WHERE $pid = A.ipid - AND A.ts < B.end_ts - GROUP BY A.ts - ) AS data_exists`, - { $pid: processId } - ); - -// VM Tracker Gpu Resourcet泳道图 -export const queryGpuResourceData = (categoryNameId: number): Promise> => - query( - 'queryGpuResourceData', - `SELECT - subquery1.startNs, - IFNULL(subquery1.totalSize, 0) as aSize, - IFNULL(subquery2.size, 0) as bSize, - (IFNULL(subquery1.totalSize, 0) - IFNULL(subquery2.size, 0)) AS value - FROM - (SELECT (ts - start_ts) AS startNs,SUM(total_size) AS totalSize - FROM memory_profile, trace_range - WHERE ts between start_ts and end_ts - GROUP BY ts) AS subquery1 - LEFT JOIN - (SELECT (ts - start_ts) AS startNs, SUM(size) AS size - FROM memory_window_gpu, trace_range - WHERE ts between start_ts and end_ts - AND category_name_id = ${categoryNameId} - GROUP BY ts) AS subquery2 - ON subquery1.startNs = subquery2.startNs` - ); - -export const queryisExistsGpuResourceData = (categoryNameId: number): Promise> => - query( - 'queryisExistsGpuResourceData', - `SELECT EXISTS ( - SELECT 1 - FROM - (SELECT (ts - start_ts) AS startNs - FROM memory_profile, trace_range - WHERE ts between start_ts and end_ts - GROUP BY ts) AS subquery1 - LEFT JOIN - (SELECT (ts - start_ts) AS startNs - FROM memory_window_gpu, trace_range - WHERE ts between start_ts and end_ts - AND category_name_id = ${categoryNameId} - GROUP BY ts) AS subquery2 - ON subquery1.startNs = subquery2.startNs - ) AS data_exists - ` - ); - -// VM Tracker Gpu Resource Tab页 -export const queryGpuResourceTabData = ( - startNs: number -): Promise> => - query( - 'queryGpuResourceTabData', - `SELECT (ts - start_ts) as startNs, channel_id as channelId, sum(total_size) as totalSize - FROM memory_profile, trace_range - WHERE (ts - start_ts) = ${startNs} - GROUP by ts, channelId` - ); - -// Ability Monitor Purgeable泳道图 -export const queryPurgeableSysData = (isPin?: boolean): Promise> => { - const pinCondition = isPin ? ' AND a.ref_count > 0' : ''; - const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')"; - return query( - 'queryPurgeableSysData', - `SELECT - startNs, - sum( value ) AS value - FROM - ( - SELECT - m.ts - tr.start_ts AS startNs, - sum( m.value ) AS value - FROM - sys_mem_measure m, - trace_range tr - LEFT JOIN sys_event_filter f ON f.id = m.filter_id - WHERE - m.ts < tr.end_ts - AND f.name IN ${names} - GROUP BY - m.ts UNION ALL - SELECT - a.ts - tr.start_ts AS startNs, - sum( a.size ) AS value - FROM - memory_ashmem a, - trace_range tr - WHERE - a.ts < tr.end_ts - AND a.flag = 0 - ${pinCondition} - GROUP BY - a.ts - ) - GROUP BY startNs - LIMIT 1` - ); -}; - -// VM Tracker Purgeable泳道图 -export const queryPurgeableProcessData = (ipid: number, isPin?: boolean): Promise> => { - const pinSql = isPin ? ' AND a.ref_count > 0' : ''; - const names = isPin ? " ('mem.purg_pin')" : "('mem.purg_sum')"; - return query( - 'queryPurgeableProcessData', - `SELECT startNs, sum( value ) AS value - FROM - (SELECT - m.ts - tr.start_ts AS startNs, - sum(m.value) AS value - FROM - process_measure m, - trace_range tr - LEFT JOIN process_measure_filter f ON f.id = m.filter_id - WHERE - m.ts < tr.end_ts - AND f.name = ${names} - AND f.ipid = ${ipid} - GROUP BY m.ts - UNION ALL - SELECT - a.ts - tr.start_ts AS startNs, - sum( a.pss ) AS value - FROM - memory_ashmem a, - trace_range tr - WHERE - a.ts < tr.end_ts - AND a.flag = 0 - AND a.ipid = ${ipid} - ${pinSql} - GROUP BY a.ts) - GROUP BY startNs` - ); -}; - -export const queryisExistsPurgeableData = (ipid: number, isPin?: boolean): Promise> => { - const pinSql = isPin ? ' AND a.ref_count > 0' : ''; - const names = isPin ? " ('mem.purg_pin')" : "('mem.purg_sum')"; - return query( - 'queryisExistsPurgeableData', - `SELECT EXISTS ( - SELECT 1 - FROM - (SELECT 1 - FROM - process_measure m, - trace_range tr - LEFT JOIN process_measure_filter f ON f.id = m.filter_id - WHERE - m.ts < tr.end_ts - AND f.name = ${names} - AND f.ipid = ${ipid} - UNION ALL - SELECT 1 - FROM - memory_ashmem a, - trace_range tr - WHERE - a.ts < tr.end_ts - AND a.flag = 0 - AND a.ipid = ${ipid} - ${pinSql}) - ) AS data_exists` - ); -}; - -//Ability Monitor Purgeable 框选 tab页 -export const querySysPurgeableTab = ( - leftNs: number, - rightNs: number, - dur: number, - isPin?: boolean -): Promise> => { - let pinsql = isPin ? ' AND ref_count > 0' : ''; - const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')"; - return query( - 'querySysPurgeableTab', - `SELECT name, MAX( size ) AS maxSize,MIN( size ) AS minSize,AVG( size ) AS avgSize - FROM - (SELECT - 'ShmPurg' AS name, - ts - tr.start_ts AS startTs, - SUM( size ) AS size - FROM - memory_ashmem, - trace_range tr - WHERE flag = 0 - ${pinsql} - GROUP BY ts UNION - SELECT - CASE - WHEN - f.name = 'sys.mem.active.purg' THEN - 'ActivePurg' - WHEN f.name = 'sys.mem.inactive.purg' THEN - 'InActivePurg' ELSE 'PinedPurg' - END AS name, - m.ts - tr.start_ts AS startTs, - m.value AS size - FROM - sys_mem_measure m, - trace_range tr - LEFT JOIN sys_event_filter f ON f.id = m.filter_id - WHERE - f.name IN ${names} - ), - trace_range tr - WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs - GROUP BY name` - ); -}; - -//Ability Monitor Purgeable 点选 tab页 -export const querySysPurgeableSelectionTab = (startNs: number, isPin?: boolean): Promise> => { - const pinSql = isPin ? ' AND ref_count > 0' : ''; - const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')"; - return query( - 'querySysPurgeableSelectionTab', - `SELECT - ( CASE WHEN f.name = 'sys.mem.active.purg' THEN 'ActivePurg' WHEN f.name = 'sys.mem.inactive.purg' THEN 'InActivePurg' ELSE 'PinedPurg' END ) AS name, - m.value AS value - FROM - sys_mem_measure m, - trace_range tr - LEFT JOIN sys_event_filter f ON f.id = m.filter_id - WHERE - f.name IN ${names} - AND m.ts - tr.start_ts = ${startNs} - UNION - SELECT - 'ShmPurg' AS name, - SUM( size ) AS value - FROM - memory_ashmem, - trace_range tr - WHERE - memory_ashmem.ts - tr.start_ts = ${startNs} - AND flag=0 - ${pinSql} - GROUP BY ts` - ); -}; - -/////////////////////////////////////////////// -//VM Purgeable 框选 tab页 -export const queryProcessPurgeableTab = ( - leftNs: number, - rightNs: number, - dur: number, - ipid: number, - isPin?: boolean -): Promise> => { - const pinSql = isPin ? ' AND ref_count > 0' : ''; - let filterSql = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'"; - return query( - 'queryProcessPurgeableTab', - `SELECT name, MAX(size) AS maxSize, MIN(size) AS minSize, AVG(size) AS avgSize - FROM - (SELECT - 'ShmPurg' AS name, ts - tr.start_ts AS startTs, SUM( pss ) AS size - FROM - memory_ashmem, - trace_range tr - WHERE - ipid = ${ipid} - AND flag = 0 - ${pinSql} - GROUP BY ts - UNION - SELECT - CASE - WHEN f.name = 'mem.purg_pin' THEN - 'PinedPurg' ELSE 'TotalPurg' - END AS name, - m.ts - tr.start_ts AS startTs, - sum( m.value ) AS size - FROM - process_measure m, - trace_range tr - LEFT JOIN process_measure_filter f ON f.id = m.filter_id - WHERE f.name = ${filterSql} - AND f.ipid = ${ipid} - GROUP BY m.ts - ) combined_data, trace_range tr - WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs - GROUP BY name` - ); -}; - -//VM Purgeable 点选 tab页 -export const queryProcessPurgeableSelectionTab = ( - startNs: number, - ipid: number, - isPin?: boolean -): Promise> => { - const condition = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'"; - const pinSql = isPin ? ' AND ref_count > 0' : ''; - return query( - 'queryProcessPurgeableSelectionTab', - `SELECT - ( CASE WHEN f.name = 'mem.purg_pin' THEN 'PinedPurg' ELSE 'TotalPurg' END ) AS name, - SUM( m.value ) AS value - FROM - process_measure m, - trace_range tr - left join process_measure_filter f on f.id = m.filter_id - WHERE - f.name = ${condition} - AND m.ts - tr.start_ts = ${startNs} - AND f.ipid = ${ipid} - GROUP BY m.ts - UNION - SELECT - 'ShmPurg' AS name, - SUM( pss ) AS size - FROM - memory_ashmem, - trace_range tr - WHERE - ipid = ${ipid} - AND ts - tr.start_ts = ${startNs} - AND flag = 0 - ${pinSql} - GROUP BY ts` - ); -}; - -export const getTabSmapsStatisticData = (rightNs: number): Promise> => - query( - 'getTabSmapsStatisticData', - `SELECT - (A.timestamp - t.start_ts) AS startNs, - start_addr as startAddr, - end_addr as endAddr, - A.type, - sum(resident_size) * 1024 AS rss, - protection_id as pid, - count(A.path_id) as count, - sum(pss) * 1024 as pss ,sum(virtaul_size) * 1024 AS size,sum(reside) as reside,A.path_id AS path, - sum(shared_clean) * 1024 as sharedClean,sum(shared_dirty) * 1024 as sharedDirty,sum(private_clean) * 1024 as privateClean,sum(private_dirty) * 1024 as privateDirty, - sum(swap) * 1024 as swap,sum(swap_pss) * 1024 as swapPss - FROM smaps A, - trace_range AS t - WHERE (startNs) =$rightNs - group by type,path`, - { $rightNs: rightNs }, - 'exec' - ); - -export const getTabSmapsStatisticSelectData = (leftNs: number, rightNs: number, dur: number): Promise> => - query( - 'getTabSmapsStatisticData', - `SELECT - (A.timestamp - t.start_ts) AS startNs, - start_addr as startAddr, - end_addr as endAddr, - A.type, - sum(resident_size) * 1024 AS rss, - protection_id as pid, - count(A.path_id) as count, - sum(pss) * 1024 as pss ,sum(virtaul_size) * 1024 AS size,sum(reside) as reside,A.path_id AS path, - sum(shared_clean) * 1024 as sharedClean,sum(shared_dirty) * 1024 as sharedDirty,sum(private_clean) * 1024 as privateClean,sum(private_dirty) * 1024 as privateDirty, - sum(swap) * 1024 as swap,sum(swap_pss) * 1024 as swapPss - FROM smaps A, - trace_range AS t - WHERE (startNs) <=$rightNs and (startNs+$dur)>=$leftNs - group by type,path`, - { $rightNs: rightNs, $leftNs: leftNs, $dur: dur }, - 'exec' - ); - -//Ability Monitor Dma 框选 -export const getTabDmaAbilityData = (leftNs: number, rightNs: number, dur: number): Promise> => - query( - 'getTabDmaAbilityData', - `SELECT (S.ts-TR.start_ts) as startNs, - MAX(S.size) as maxSize, - MIN(S.size) as minSize, - Avg(S.size) as avgSize, - E.pid as processId, - E.name as processName - from trace_range as TR,memory_dma as S - left join process as E on E.ipid=S.ipid - WHERE - $leftNS <= startNs + ${dur} and $rightNS >= startNs - and flag = 0 - GROUP by E.pid - `, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -//Ability Monitor SkiaGpuMemory 框选 -export const getTabGpuMemoryAbilityData = (leftNs: number, rightNs: number, dur: number): Promise> => - query( - 'getTabGpuMemoryAbilityData', - `SELECT (S.ts-TR.start_ts) as startNs, - gpu_name_id as gpuNameId, - MAX(S.used_gpu_size) as maxSize, - MIN(S.used_gpu_size) as minSize, - Avg(S.used_gpu_size) as avgSize, - E.pid as processId, - E.name as processName - from trace_range as TR,memory_process_gpu as S - left join process as E on E.ipid=S.ipid - WHERE - $leftNS <= startNs + ${dur} - and - $rightNS >= startNs - GROUP by - E.pid ,S.gpu_name_id - `, - { $leftNS: leftNs, $rightNS: rightNs } - ); - -//VM Tracker Dma 框选 -export const getTabDmaVmTrackerData = ( - leftNs: number, - rightNs: number, - processId: number, - dur: number -): Promise> => - query( - 'getTabDmaVmTrackerData', - `SELECT (S.ts-TR.start_ts) as startNs, - MAX(S.size) as maxSize, - MIN(S.size) as minSize, - Avg(S.size) as avgSize - from trace_range as TR,memory_dma as S - left join data_dict as C on C.id=S.exp_task_comm_id - where - $leftNS <= startNs + ${dur} and $rightNS >= startNs - and flag = 0 - and - $pid = S.ipid - `, - { $leftNS: leftNs, $rightNS: rightNs, $pid: processId } - ); -//VM Tracker SkiaGpuMemory 框选 -export const getTabGpuMemoryData = ( - leftNs: number, - rightNs: number, - processId: number, - dur: number -): Promise> => - query( - 'getTabGpuMemoryData', - `SELECT - (S.ts-TR.start_ts) as startNs, - gpu_name_id as gpuNameId, - T.tid as threadId, - T.name as threadName, - MAX(S.used_gpu_size) as maxSize, - MIN(S.used_gpu_size) as minSize, - Avg(S.used_gpu_size) as avgSize - from trace_range as TR,memory_process_gpu as S - left join thread as T on T.itid=S.itid - where - $leftNS <= startNs + ${dur} - and - $rightNS >= startNs - and - $pid = S.ipid - group by gpu_name_id,threadId - `, - { $leftNS: leftNs, $rightNS: rightNs, $pid: processId } - ); - -//Ability Monitor Dma 点选 -export const getTabDmaAbilityClickData = (startNs: number): Promise> => - query( - 'getTabDmaAbilityClickData', - `SELECT - (S.ts-TR.start_ts) as startNs, - S.fd as fd, - S.size as size, - S.ino as ino, - S.exp_pid as expPid, - buf_name_id as bufName, - exp_name_id as expName, - exp_task_comm_id as expTaskComm, - E.pid as processId, - E.name as processName, - S.flag as flag - from trace_range as TR,memory_dma as S - left join process as E on E.ipid=S.ipid - WHERE - startNs = ${startNs} - `, - { $startNs: startNs } - ); - -//VM Tracker Dma 点选 -export const getTabDmaVMTrackerClickData = (startNs: number, processId: number): Promise> => - query( - 'getTabDmaVMTrackerClickData', - `SELECT - (S.ts-TR.start_ts) as startNs, - S.fd as fd, - S.size as size, - S.ino as ino, - S.exp_pid as expPid, - buf_name_id as bufName, - exp_name_id as expName, - exp_task_comm_id as expTaskComm, - S.flag as flag - from trace_range as TR,memory_dma as S - WHERE - startNs = ${startNs} - AND - $pid = S.ipid - `, - { $startNs: startNs, $pid: processId } - ); - -//Ability Monitor SkiaGpuMemory 点选 -export const getTabGpuMemoryAbilityClickData = (startNs: number): Promise> => - query( - 'getTabGpuMemoryAbilityClickData', - `SELECT - (S.ts-TR.start_ts) as startNs, - S.used_gpu_size as size, - E.pid as processId, - E.name as processName, - A.data as gpuName - from trace_range as TR,memory_process_gpu as S - left join process as E on E.ipid=S.ipid - left join data_dict as A on A.id=S.gpu_name_id - WHERE - startNs = ${startNs} - `, - { $startNs: startNs } - ); - -//VM Tracker SkiaGpuMemory 点选 -export const getTabGpuMemoryVMTrackerClickData = (startNs: number, processId: number): Promise> => - query( - 'getTabGpuMemoryVMTrackerClickData', - `SELECT - (S.ts-TR.start_ts) as startNs, - S.used_gpu_size as size, - T.tid as threadId, - T.name as threadName, - A.data as gpuName - from trace_range as TR,memory_process_gpu as S - left join thread as T on T.itid=S.itid - left join data_dict as A on A.id=S.gpu_name_id - WHERE - startNs = ${startNs} - AND - $pid = S.ipid - `, - { $startNs: startNs, $pid: processId } - ); - -//Ability Monitor Dma 点选比较 -export const getTabDmaAbilityComparisonData = (startNs: number): Promise> => - query( - 'getTabDmaAbilityComparisonData', - `SELECT - (S.ts-TR.start_ts) as startNs, - sum(S.size) as value, - E.pid as processId, - E.name as processName - from trace_range as TR,memory_dma as S - left join process as E on E.ipid=S.ipid - WHERE - startNs = ${startNs} - GROUP by - E.pid - `, - { $startNs: startNs } - ); - -//Ability Monitor Gpu Memory 点选比较 -export const getTabGpuMemoryComparisonData = (startNs: number): Promise> => - query( - 'getTabGpuMemoryComparisonData', - `SELECT - (S.ts-TR.start_ts) as startNs, - sum(S.used_gpu_size) as value, - E.pid as processId, - S.gpu_name_id as gpuNameId, - E.name as processName - from trace_range as TR,memory_process_gpu as S - left join process as E on E.ipid=S.ipid - WHERE - startNs = ${startNs} - GROUP by - E.pid, S.gpu_name_id - `, - { $startNs: startNs } - ); - -//VM Tracker Dma 点选比较 -export const getTabDmaVmTrackerComparisonData = (startNs: number, processId: number): Promise> => - query( - 'getTabDmaVmTrackerComparisonData', - `SELECT - (S.ts-TR.start_ts) as startNs, - sum(S.size) as value - from trace_range as TR,memory_dma as S - WHERE - startNs = ${startNs} - AND - $pid = S.ipid - `, - { $startNs: startNs, $pid: processId } - ); - -//VM Tracker Gpu Memory 点选比较 -export const getTabGpuMemoryVmTrackerComparisonData = ( - startNs: number, - processId: number -): Promise> => - query( - 'getTabGpuMemoryVmTrackerComparisonData', - `SELECT - (S.ts-TR.start_ts) as startNs, - sum(S.used_gpu_size) as value, - T.tid as threadId, - T.name as threadName, - S.gpu_name_id as gpuNameId - from trace_range as TR,memory_process_gpu as S - left join thread as T on T.itid=S.itid - WHERE - startNs = ${startNs} - AND - $pid = S.ipid - `, - { $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.ts - tr.start_ts as startNs FROM log AS l, trace_range tr WHERE startNs > 0 LIMIT 1;`, - ); - -export const queryMetric = (metricName: string): Promise> => - query('queryMetric', metricName, '', 'exec-metric'); - -export const queryExistFtrace = (): Promise> => - query( - 'queryExistFtrace', - `select 1 from thread_state - UNION - select 1 from args;` - ); - -export const queryTraceType = (): Promise< - Array<{ - value: string; - }> -> => - query( - 'queryTraceType', - `SELECT m.value - FROM - meta AS m - WHERE - m.name = 'source_type';` - ); - -export const queryTransferList = (): Promise> => - query('queryTransferList', `select id, report_value as cmdStr from perf_report where report_type = 'config_name'`); - -export const getTabRunningPercent = (tIds: Array, leftNS: number, rightNS: number): Promise> => - query( - 'getTabRunningPercent', - ` - select - B.pid,B.tid,B.state,B.cpu,B.dur,B.ts - from - thread_state AS B - left join - trace_range AS TR - where - B.tid in (${tIds.join(',')}) - and - B.state='Running' - and - not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) - order by ts - `, - { $leftNS: leftNS, $rightNS: rightNS } - ); - -export const querySearchFuncData = ( - funcName: string, - tIds: number, - leftNS: number, - rightNS: number -): Promise> => - query( - 'querySearchFuncData', - ` - select - c.cookie, - c.id, - c.name as funName, - c.ts - r.start_ts as startTime, - c.dur, - c.depth, - t.tid, - t.name as threadName, - p.pid, - 'func' as type - from - callstack c - left join - thread t - on - c.callid = t.id - left join - process p - on - t.ipid = p.id - left join - trace_range r - where - c.name like '${funcName}' - and - t.tid = ${tIds} - and - not ((startTime < ${leftNS}) or (startTime > ${rightNS})); - `, - { $search: funcName } - ); - -export const queryCpuFreqUsageData = (Ids: Array): Promise> => - query( - 'queryCpuFreqUsageData', - `select - value, - ifnull(dur,tb.end_ts - c.ts) dur, - ts-tb.start_ts as startNS, - filter_id - from - measure c, - trace_range tb - where - c.filter_id in (${Ids.join(',')}) - ` - ); - -export const queryCpuFreqFilterId = (): Promise> => - query( - 'queryCpuFreqFilterId', - ` - select - id, - cpu - from - cpu_measure_filter - where - name='cpufreq' - or - name='cpu_frequency' - ` - ); - -export const queryRealTime = (): Promise< - Array<{ - ts: number; - }> -> => query('queryRealTime', `select CS.ts as ts from clock_snapshot as CS where clock_name = 'realtime';`); - -export const queryHiSysEventData = (): Promise> => - query( - 'queryHiSysEventData', - `SELECT l.ts - tr.start_ts as startNs FROM hisys_all_event AS l, trace_range tr WHERE startNs > 0 LIMIT 1` - ); - -export const querySearchRowFuncData = ( - funcName: string, - tIds: number, - leftNS: number, - rightNS: number -): Promise> => - query( - 'querySearchRowFuncData', - ` - select - c.name as funName, - c.ts - r.start_ts as startTime, - t.tid, - t.name as threadName, - 'func' as type - from - callstack c - left join - thread t - on - c.callid = t.id - left join - process p - on - t.ipid = p.id - left join - trace_range r - where - c.name like '${funcName}' - and - t.tid = ${tIds} - and - not ((startTime < ${leftNS}) or (startTime > ${rightNS})); - `, - { $search: funcName } - ); - -export const queryCpuKeyPathData = (threads: Array): Promise> => { - const sqlArray: Array = []; - sqlArray.push(` 1 = 0`); - for (const thread of threads) { - sqlArray.push(` or (tid = ${thread.tid} and ts in (${thread.tsArray}))`); - } - let sql = sqlArray.join(' '); - return query( - 'queryCpuKeyPathData', - `SELECT B.pid as processId, - B.cpu, - B.tid, - B.itid as id, - B.dur AS dur, - B.ts - T.start_ts AS startTime, - B.arg_setid as argSetID, - 1 as isKeyPath - from thread_state AS B - left join trace_range as T - where ${sql}` - ); -}; - -export const queryMemFilterIdMaxValue = (): Promise> => { - return query( - 'queryMemFilterIdMaxValue', - `select filter_id as filterId,max(value) maxValue from process_measure group by filter_id;` - ); -}; - -export const queryHiSysEventTabData = (leftNs: number, rightNs: number): Promise> => - query( - 'queryHiSysEventTabData', - `SELECT S.id, - D2.data AS domain, - D.data AS eventName, - type AS eventType, - time_zone AS tz, - pid, - tid, - uid, - info, - level, - seq, - contents, - S.ts - TR.start_ts AS startTs, - 1 AS dur, - CASE - WHEN level = 'MINOR' THEN - 0 - WHEN level = 'CRITICAL' THEN - 1 - END AS depth - FROM hisys_all_event AS S ,trace_range AS TR - LEFT JOIN data_dict AS D on S.event_name_id = D.id - LEFT JOIN data_dict AS D2 on S.domain_id = D2.id - WHERE S.id is not null - and startTs >= ${Math.floor(leftNs)} - and startTs <= ${Math.floor(rightNs)} - ORDER BY S.ts` - ); - -export const queryLogAllData = (oneDayTime: number, leftNs: number, rightNs: number): Promise> => - query( - 'queryLogAllData', - `SELECT - l.seq AS id, - CASE - WHEN l.ts < ${oneDayTime} THEN 0 - ELSE (l.ts - TR.start_ts) - END AS startTs, - CASE l.level - WHEN 'D' THEN 'Debug' - WHEN 'I' THEN 'Info' - WHEN 'W' THEN 'Warn' - WHEN 'E' THEN 'Error' - WHEN 'F' THEN 'Fatal' - END AS level, - l.tag AS tag, - l.context AS context, - (strftime( '%m-%d %H:%M:%S', l.origints / 1000000000, 'unixepoch', 'localtime' ) || '.' || printf('%03d', (l.origints / 1000000) % 1000)) AS originTime, - COALESCE(p.name, 'Process ' || l.pid) AS processName - FROM - log AS l - LEFT JOIN trace_range AS TR ON l.ts >= TR.start_ts - LEFT JOIN process AS p ON p.pid = l.pid - WHERE - startTs >= ${Math.floor(leftNs)} - AND startTs <= ${Math.floor(rightNs)} - ORDER BY - l.ts;`, - { $oneDayTime: oneDayTime } - ); - -export const querySchedThreadStates = ( - tIds: Array, - leftStartNs: number, - rightEndNs: number -): Promise> => - query( - 'getTabThreadStates', - ` - select - B.id, - B.pid, - B.tid, - B.state, - B.type, - B.dur, - B.ts, - B.dur + B.ts as endTs - from - thread_state AS B - where - B.tid in (${tIds.join(',')}) - and - not ((B.ts + ifnull(B.dur,0) < $leftStartNs) or (B.ts > $rightEndNs)) - order by - B.pid; - `, - { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs } - ); - -export const querySingleCutData = ( - funcName: string, - tIds: string, - leftStartNs: number, - rightEndNs: number -): Promise> => - query( - 'querySingleCutData', - ` - select - c.id, - c.name, - c.ts as cycleStartTime, - c.ts + c.dur as cycleEndTime, - c.depth, - t.tid, - p.pid, - c.dur - from - callstack c - left join - thread t on c.callid = t.id - left join - process p on t.ipid = p.id - left join - trace_range r - where - c.name = '${funcName}' - and - t.tid = '${tIds}' - and - not ((c.ts < $leftStartNs) or (c.ts + ifnull(c.dur, 0) > $rightEndNs)) - `, - { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs } - ); - -export const queryLoopCutData = ( - funcName: string, - tIds: string, - leftStartNs: number, - rightEndNs: number -): Promise> => - query( - 'queryLoopCutData', - ` - select - c.id, - c.name, - c.ts as cycleStartTime, - c.depth, - t.tid, - p.pid - from callstack c - left join - thread t on c.callid = t.id - left join - process p on t.ipid = p.id - where - c.name = '${funcName}' - and - t.tid = '${tIds}' - and - not ((c.ts < $leftStartNs) or (c.ts > $rightEndNs)) - order by - c.ts - `, - { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs } - ); -export const getTabBindersCount = ( - pIds: number[], - tIds: number[], - leftNS: number, - rightNS: number -): Promise> => - query( - 'getTabBindersCount', - ` - SELECT - c.name, - c.dur, - 1 AS count, - c.ts, - c.ts - r.start_ts AS startTime, - c.ts -r.start_ts + c.dur AS endTime, - t.tid, - p.pid - FROM - callstack c, trace_range r - LEFT JOIN - thread t - ON - c.callid = t.id - LEFT JOIN - process p - ON - t.ipid = p.id - WHERE - c.name in ('binder transaction', 'binder async rcv', 'binder reply', 'binder transaction async') - AND - t.tid in (${tIds.join(',')}) - AND - p.pid in (${pIds.join(',')}) - AND NOT - ((startTime < ${leftNS}) - OR - (endTime > ${rightNS})); - `, - { - $pIds: pIds, - $tIds: tIds, - $leftNS: leftNS, - $rightNS: rightNS, - } - ); - -export const queryBinderByThreadId = ( - pIds: number[], - tIds: Array, - leftNS: number, - rightNS: number -): Promise> => - query( - 'queryBinderByThreadId', - ` - SELECT - c.name, - 1 AS count, - c.ts - r.start_ts AS ts, - c.dur, - c.ts - r.start_ts AS startTime, - c.ts - r.start_ts + c.dur AS endTime, - t.tid, - p.pid - FROM - callstack c, trace_range r - LEFT JOIN - thread t - ON - c.callid = t.id - LEFT JOIN - process p - ON - t.ipid = p.id - WHERE - c.name in ('binder transaction', 'binder async rcv', 'binder reply', 'binder transaction async') - AND - t.tid in (${tIds.join(',')}) - AND - p.pid in (${pIds.join(',')}) - AND NOT - ((startTime < ${leftNS}) - OR - (endTime > ${rightNS})) - `, - { - $pIds: pIds, - $tIds: tIds, - $leftNS: leftNS, - $rightNS: rightNS, - } - ); - -export const querySingleFuncNameCycle = ( - funcName: string, - tIds: string, - leftNS: number, - rightNS: number -): Promise> => - query( - 'querySingleFuncNameCycle', - ` - SELECT - c.name AS funcName, - c.ts - r.start_ts AS cycleStartTime, - c.dur AS cycleDur, - c.id, - t.tid, - p.pid, - c.ts - r.start_ts + c.dur AS endTime - FROM - callstack c, trace_range r - LEFT JOIN - thread t - ON - c.callid = t.id - LEFT JOIN - process p - ON - t.ipid = p.id - WHERE - c.name = '${funcName}' - AND - t.tid = ${tIds} - AND NOT - ((cycleStartTime < ${leftNS}) - OR - (endTime > ${rightNS})) - `, - { - $funcName: funcName, - $tIds: tIds, - $leftNS: leftNS, - $rightNS: rightNS, - } - ); - -export const queryLoopFuncNameCycle = ( - funcName: string, - tIds: string, - leftNS: number, - rightNS: number -): Promise> => - query( - 'queryLoopFuncNameCycle', - ` - SELECT - c.name AS funcName, - c.ts - r.start_ts AS cycleStartTime, - 0 AS cycleDur, - c.id, - t.tid, - p.pid - FROM - callstack c, trace_range r - LEFT JOIN - thread t - ON - c.callid = t.id - LEFT JOIN - process p - ON - t.ipid = p.id - WHERE - c.name = '${funcName}' - AND - t.tid = ${tIds} - AND NOT - ((cycleStartTime < ${leftNS}) - OR - (cycleStartTime > ${rightNS})) - `, - { - $funcName: funcName, - $tIds: tIds, - $leftNS: leftNS, - $rightNS: rightNS, - } - ); -export const getGpufreqData = (leftNS: number, rightNS: number, earliest: boolean): Promise> => { - let queryCondition: string = ''; - if (!earliest) { - queryCondition += ` where not ((s.ts - r.start_ts + ifnull(s.dur,0) < ${leftNS}) or (s.ts - r.start_ts > ${rightNS}))`; - } - return query( - 'getGpufreqData', - ` - with state as - (select - name, - filter_id, - ts, - endts, - endts-ts as dur, - type, - value - from - (select - measure.filter_id, - clock_event_filter.name, - measure.ts, - lead(ts, 1, null) over( order by measure.ts) endts, - measure.type, - measure.value - from - clock_event_filter, - trace_range - left join - measure - where - clock_event_filter.name = 'gpufreq' - and - clock_event_filter.type = 'clock_set_rate' - and - clock_event_filter.id = measure.filter_id - order by measure.ts) - where - endts is not null - ) - select - s.name as thread, - s.filter_id as filterId, - s.value/1000000 as freq, - s.value*s.dur as count, - s.value, - s.ts, - s.ts-r.start_ts as startNS, - s.dur, - s.endts- r.start_ts as endTime - from - state s, - trace_range r - ${queryCondition} - order by ts - `, - { $leftNS: leftNS, $rightNS: rightNS } - ); -}; - -export const getGpufreqDataCut = ( - tIds: string, - funcName: string, - leftNS: number, - rightNS: number, - single: boolean, - loop: boolean -): Promise> => { - let queryCondition: string = ''; - if (single) { - queryCondition += `select s.funName,s.startTime,s.dur,s.startTime+s.dur as endTime,s.depth,s.tid,s.threadName,s.pid from state s - where endTime between ${leftNS} and ${rightNS}`; - } - if (loop) { - queryCondition += `select s.funName,s.startTime,s.loopEndTime-s.startTime as dur,s.loopEndTime as endTime,s.depth,s.tid,s.threadName,s.pid from state s - where endTime between ${leftNS} and ${rightNS} `; - } - return query( - 'getGpufreqDataCut', - ` - with state as - (select - * - from - (select - c.name as funName, - c.ts - r.start_ts as startTime, - c.dur, - lead(c.ts - r.start_ts, 1, null) over( order by c.ts - r.start_ts) loopEndTime, - c.depth, - t.tid, - t.name as threadName, - p.pid - from - callstack c - left join - thread t on c.callid = t.id - left join - process p on t.ipid = p.id - left join - trace_range r - where - c.name like '%${funcName}%' - and - tid = '${tIds}' - and - startTime between ${leftNS} and ${rightNS})) - ${queryCondition} - `, - { $search: funcName } - ); -}; diff --git a/ide/src/trace/database/StateBusyTimeWorker.ts b/ide/src/trace/database/StateBusyTimeWorker.ts index cf0475608cd88a960d59321ad08cdc3d6907cf6e..97ba010b48d1a84f660e1a02b9fa9f804d5a3b64 100644 --- a/ide/src/trace/database/StateBusyTimeWorker.ts +++ b/ide/src/trace/database/StateBusyTimeWorker.ts @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2023 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 @@ -20,30 +20,29 @@ function getBusyTime( leftStartNs: number, rightEndNs: number ) { - if (initFreqResult.length == 0) return; - if (initStateResult.length == 0) return; + if (initFreqResult.length == 0) { return }; + if (initStateResult.length == 0) { return }; //处理被框选的freq的第一个数据 let includeData = initFreqResult.findIndex((a) => a.ts >= leftStartNs); if (includeData !== 0) { initFreqResult = initFreqResult.slice( - includeData == -1 ? initFreqResult.length - 1 : includeData - 1, + includeData === -1 ? initFreqResult.length - 1 : includeData - 1, initFreqResult.length ); } - let startNS = includeData == 0 ? initFreqResult[0].ts : leftStartNs; - if (initFreqResult[0].ts < leftStartNs && includeData !== 0) initFreqResult[0].ts - leftStartNs; + let startNS = includeData === 0 ? initFreqResult[0].ts : leftStartNs; //处理对应的state泳道被框选的第一个数据 let includeStateData = initStateResult.findIndex((a) => a.ts >= startNS); if (includeStateData !== 0) { initStateResult = initStateResult.slice( - includeStateData == -1 ? initStateResult.length - 1 : includeStateData - 1, + includeStateData === -1 ? initStateResult.length - 1 : includeStateData - 1, initStateResult.length ); } if (initStateResult[0].ts < startNS && includeStateData !== 0 && includeStateData !== -1) initStateResult[0].ts = startNS; //处理被框选的freq最后一个数据 - if (initFreqResult[initFreqResult.length - 1].ts != rightEndNs) { + if (initFreqResult[initFreqResult.length - 1].ts !== rightEndNs) { initFreqResult.push({ ts: rightEndNs, value: initFreqResult[initFreqResult.length - 1].value, @@ -51,12 +50,16 @@ function getBusyTime( }); } //处理被框选的freq最后一个数据 - if (initStateResult[initStateResult.length - 1].ts != rightEndNs) { + if (initStateResult[initStateResult.length - 1].ts !== rightEndNs) { initStateResult.push({ ts: rightEndNs, value: initStateResult[initStateResult.length - 1].value, }); } + handleBusyTimeLogic(initFreqResult, initStateResult, sampleMap, startNS); +} + +function handleBusyTimeLogic(initFreqResult: Array, initStateResult: Array, sampleMap: Map, startNS: number) { let freqIndex = 1; let stateIndex = 1; let beginNs = startNS; diff --git a/ide/src/trace/database/TraceWorker.ts b/ide/src/trace/database/TraceWorker.ts index 16175eb48f7220bb4cb56c79e4ff50267dc40603..9d19f8e28063c2bc97ddefa605322dd00205ad35 100644 --- a/ide/src/trace/database/TraceWorker.ts +++ b/ide/src/trace/database/TraceWorker.ts @@ -14,11 +14,12 @@ */ importScripts('trace_streamer_builtin.js'); -import { execProtoForWorker } from './data-trafic/ExecProtoForWorker'; -import { QueryEnum, TraficEnum } from './data-trafic/QueryEnum'; +import { execProtoForWorker } from './data-trafic/utils/ExecProtoForWorker'; +import { QueryEnum, TraficEnum } from './data-trafic/utils/QueryEnum'; import { temp_init_sql_list } from './TempSql'; // @ts-ignore import { BatchSphData } from '../proto/SphBaseData'; + let Module: any = null; let enc = new TextEncoder(); let dec = new TextDecoder(); @@ -80,8 +81,8 @@ function initWASM() { locateFile: (s: any) => { return s; }, - print: (line: any) => {}, - printErr: (line: any) => {}, + print: (line: any) => { }, + printErr: (line: any) => { }, onRuntimeInitialized: () => { resolve('ok'); }, @@ -99,10 +100,10 @@ function initThirdWASM(wasmFunctionName: string) { locateFile: (s: any) => { return s; }, - print: (line: any) => {}, - printErr: (line: any) => {}, - onRuntimeInitialized: () => {}, - onAbort: () => {}, + print: (line: any) => { }, + printErr: (line: any) => { }, + onRuntimeInitialized: () => { }, + onAbort: () => { }, }); } @@ -206,7 +207,7 @@ async function obligateFileBufferSpace(size: number): Promise { let splitB = keyB.split('/'); let timeA = splitA[splitA.length - 1].split('-')[0]; let timeB = splitB[splitB.length - 1].split('-')[0]; - return parseInt(timeA) - parseInt(timeB) + return parseInt(timeA) - parseInt(timeB); } else { return 0; } @@ -306,48 +307,7 @@ self.onmessage = async (e: MessageEvent) => { let model = thirdWasmMap.get(componentID); if (!model && config.componentId === componentID) { importScripts(config.wasmJsName); - let thirdMode = initThirdWASM(config.wasmName); - let configPluginName = config.pluginName; - let pluginNameUintArray = enc.encode(configPluginName); - let pluginNameBuffer = thirdMode._InitPluginName(pluginNameUintArray.length); - thirdMode.HEAPU8.set(pluginNameUintArray, pluginNameBuffer); - thirdMode._TraceStreamerGetPluginNameEx(configPluginName.length); - let thirdQueryDataCallBack = (heapPtr: number, size: number, isEnd: number, isConfig: number) => { - if (isConfig == 1) { - let out: Uint8Array = thirdMode.HEAPU8.slice(heapPtr, heapPtr + size); - thirdJsonResult.set(componentID, { - jsonConfig: dec.decode(out), - disPlayName: config.disPlayName, - pluginName: config.pluginName, - }); - } else { - let out: Uint8Array = thirdMode.HEAPU8.slice(heapPtr, heapPtr + size); - bufferSlice.push(out); - if (isEnd == 1) { - arr = merged(); - bufferSlice.length = 0; - } - } - }; - let fn = thirdMode.addFunction(thirdQueryDataCallBack, 'viiii'); - let thirdreqBufferAddr = thirdMode._Init(fn, REQ_BUF_SIZE); - let updateTraceTimeCallBack = (heapPtr: number, size: number) => { - let out: Uint8Array = thirdMode.HEAPU8.slice(heapPtr, heapPtr + size); - Module.HEAPU8.set(out, reqBufferAddr); - Module._UpdateTraceTime(out.length); - }; - let traceRangeFn = thirdMode.addFunction(updateTraceTimeCallBack, 'vii'); - let mm = thirdMode._InitTraceRange(traceRangeFn, 1024); - thirdMode._TraceStreamer_In_JsonConfig(); - thirdMode.HEAPU8.set(headUnitArray, thirdreqBufferAddr); - thirdMode._ParserData(headUnitArray!.length, 100); - let out: Uint8Array = Module.HEAPU8.slice(heapPtr, heapPtr + size); - thirdMode.HEAPU8.set(out, thirdreqBufferAddr); - thirdMode._ParserData(out.length, componentID); - thirdWasmMap.set(componentID, { - model: thirdMode, - bufferAddr: thirdreqBufferAddr, - }); + setThirdWasmMap(config, heapPtr, size, componentID); } else { let mm = model.model; let out: Uint8Array = Module.HEAPU8.slice(heapPtr, heapPtr + size); @@ -359,6 +319,54 @@ self.onmessage = async (e: MessageEvent) => { let fn1 = Module.addFunction(sendDataCallback, 'viii'); let reqBufferAddr1 = Module._TraceStreamer_Set_ThirdParty_DataDealer(fn1, REQ_BUF_SIZE); } + function initTraceRange(thirdMode: any): any { + let updateTraceTimeCallBack = (heapPtr: number, size: number) => { + let out: Uint8Array = thirdMode.HEAPU8.slice(heapPtr, heapPtr + size); + Module.HEAPU8.set(out, reqBufferAddr); + Module._UpdateTraceTime(out.length); + }; + let traceRangeFn = thirdMode.addFunction(updateTraceTimeCallBack, 'vii'); + let mm = thirdMode._InitTraceRange(traceRangeFn, 1024); + return mm; + } + function setThirdWasmMap(config: any, heapPtr: number, size: number, componentID: number) { + let thirdMode = initThirdWASM(config.wasmName); + let configPluginName = config.pluginName; + let pluginNameUintArray = enc.encode(configPluginName); + let pluginNameBuffer = thirdMode._InitPluginName(pluginNameUintArray.length); + thirdMode.HEAPU8.set(pluginNameUintArray, pluginNameBuffer); + thirdMode._TraceStreamerGetPluginNameEx(configPluginName.length); + let thirdQueryDataCallBack = (heapPtr: number, size: number, isEnd: number, isConfig: number) => { + if (isConfig == 1) { + let out: Uint8Array = thirdMode.HEAPU8.slice(heapPtr, heapPtr + size); + thirdJsonResult.set(componentID, { + jsonConfig: dec.decode(out), + disPlayName: config.disPlayName, + pluginName: config.pluginName, + }); + } else { + let out: Uint8Array = thirdMode.HEAPU8.slice(heapPtr, heapPtr + size); + bufferSlice.push(out); + if (isEnd == 1) { + arr = merged(); + bufferSlice.length = 0; + } + } + }; + let fn = thirdMode.addFunction(thirdQueryDataCallBack, 'viiii'); + let thirdreqBufferAddr = thirdMode._Init(fn, REQ_BUF_SIZE); + let mm = initTraceRange(thirdMode); + thirdMode._TraceStreamer_In_JsonConfig(); + thirdMode.HEAPU8.set(headUnitArray, thirdreqBufferAddr); + thirdMode._ParserData(headUnitArray!.length, 100); + let out: Uint8Array = Module.HEAPU8.slice(heapPtr, heapPtr + size); + thirdMode.HEAPU8.set(out, thirdreqBufferAddr); + thirdMode._ParserData(out.length, componentID); + thirdWasmMap.set(componentID, { + model: thirdMode, + bufferAddr: thirdreqBufferAddr, + }); + } let wrSize = 0; let r2 = -1; let rowTraceStr = Array.from(new Uint32Array(e.data.buffer.slice(0, 4))); @@ -592,7 +600,7 @@ self.onmessage = async (e: MessageEvent) => { string, { traceFileType: string; - dataArray: [{ data: Uint8Array | Array<{ offset: number; size: number }>; dataTypes: string }]; + dataArray: [{ data: Uint8Array | Array<{ offset: number; size: number; }>; dataTypes: string; }]; } > = new Map(); let cutFileCallBack = (heapPtr: number, size: number, dataType: number, isEnd: number) => { @@ -618,7 +626,7 @@ self.onmessage = async (e: MessageEvent) => { if (cutFilePageInfo) { let jsonStr: string = dec.decode(out); let jsonObj = JSON.parse(jsonStr); - let valueArray: Array<{ offset: number; size: number }> = jsonObj.value; + let valueArray: Array<{ offset: number; size: number; }> = jsonObj.value; cutFilePageInfo.dataArray.push({ data: valueArray, dataTypes: 'json' }); } } @@ -691,7 +699,7 @@ self.onmessage = async (e: MessageEvent) => { } } else { if (receiveData.data.length > 0) { - let needCutMessage = receiveData.data as Array<{ offset: number; size: number }>; + let needCutMessage = receiveData.data as Array<{ offset: number; size: number; }>; let startOffset = needCutMessage[0].offset; let nowCutInfoList: Array = []; let isBeforeCutFinish = false; @@ -832,6 +840,51 @@ function indexedDataToBufferData(sourceData: any): Uint8Array { return resultUintArray; } +async function splitFileAndSaveArkTs( + maxSize: number, + currentChunkOffset: number, + currentChunk: Uint8Array, + fileType: string, + pageNum: number, + saveStartOffset: number, + saveIndex: number, + timStamp: number, + db: IDBDatabase) { + for (let arkTsAllDataIndex = 0; arkTsAllDataIndex < arkTsData.length; arkTsAllDataIndex++) { + let currentArkTsData = arkTsData[arkTsAllDataIndex]; + let freeSize = maxSize - currentChunkOffset; + if (currentArkTsData.length > freeSize) { + let freeSaveData = currentArkTsData.slice(0, freeSize); + currentChunk.set(freeSaveData, currentChunkOffset); + let arg2 = setArg(currentChunk, fileType, pageNum, saveStartOffset, saveIndex, maxSize, timStamp); + await addDataToIndexeddb(db, arg2); + saveStartOffset += maxSize; + saveIndex++; + let remnantData = currentArkTsData.slice(freeSize); + let remnantDataLength: number = Math.ceil(remnantData.length / maxSize); + for (let newSliceIndex = 0; newSliceIndex < remnantDataLength; newSliceIndex++) { + let newSliceSize = newSliceIndex * maxSize; + let number = Math.min(newSliceSize + maxSize, remnantData.length); + let saveArray = remnantData.slice(newSliceSize, number); + if (newSliceIndex === remnantDataLength - 1 && number - newSliceSize < maxSize) { + currentChunk = new Uint8Array(maxSize); + currentChunkOffset = 0; + currentChunk.set(saveArray, currentChunkOffset); + currentChunkOffset += saveArray.length; + } else { + let arg2 = setArg(saveArray, fileType, pageNum, saveStartOffset, saveIndex, maxSize, timStamp); + await addDataToIndexeddb(db, arg2); + saveStartOffset += maxSize; + saveIndex++; + } + } + } else { + currentChunk.set(currentArkTsData, currentChunkOffset); + currentChunkOffset += currentArkTsData.length; + } + } +} + async function splitFileAndSave( timStamp: number, fileType: string, @@ -858,12 +911,7 @@ async function splitFileAndSave( const transaction = db.transaction(STORE_NAME, 'readonly'); const store = transaction.objectStore(STORE_NAME); const index = store.index('QueryCompleteFile'); - let range = IDBKeyRange.bound( - [timStamp, fileType, 0, queryStartIndex], - [timStamp, fileType, 0, queryEndIndex], - false, - false - ); + let range = getRange(timStamp, fileType, queryStartIndex, queryEndIndex); const getRequest = index.openCursor(range); let res = await queryDataFromIndexeddb(getRequest); queryStartIndex = queryEndIndex + 1; @@ -883,55 +931,8 @@ async function splitFileAndSave( Module._TraceStreamerLongTraceSplitFileEx(sliceLen, 0, pageNum); } if (arkTsDataSize > 0 && fileType === 'arkts') { - for (let arkTsAllDataIndex = 0; arkTsAllDataIndex < arkTsData.length; arkTsAllDataIndex++) { - let currentArkTsData = arkTsData[arkTsAllDataIndex]; - let freeSize = maxSize - currentChunkOffset; - if (currentArkTsData.length > freeSize) { - let freeSaveData = currentArkTsData.slice(0, freeSize); - currentChunk.set(freeSaveData, currentChunkOffset); - await addDataToIndexeddb(db, { - buf: currentChunk, - id: `${fileType}_new_${timStamp}_${pageNum}_${saveIndex}`, - fileType: `${fileType}_new`, - pageNum: pageNum, - startOffset: saveStartOffset, - endOffset: saveStartOffset + maxSize, - index: saveIndex, - timStamp: timStamp, - }); - saveStartOffset += maxSize; - saveIndex++; - let remnantData = currentArkTsData.slice(freeSize); - let remnantDataLength: number = Math.ceil(remnantData.length / maxSize); - for (let newSliceIndex = 0; newSliceIndex < remnantDataLength; newSliceIndex++) { - let newSliceSize = newSliceIndex * maxSize; - let number = Math.min(newSliceSize + maxSize, remnantData.length); - let saveArray = remnantData.slice(newSliceSize, number); - if (newSliceIndex === remnantDataLength - 1 && number - newSliceSize < maxSize) { - currentChunk = new Uint8Array(maxSize); - currentChunkOffset = 0; - currentChunk.set(saveArray, currentChunkOffset); - currentChunkOffset += saveArray.length; - } else { - await addDataToIndexeddb(db, { - buf: saveArray, - id: `${fileType}_new_${timStamp}_${pageNum}_${saveIndex}`, - fileType: `${fileType}_new`, - pageNum: pageNum, - startOffset: saveStartOffset, - endOffset: saveStartOffset + maxSize, - index: saveIndex, - timStamp: timStamp, - }); - saveStartOffset += maxSize; - saveIndex++; - } - } - } else { - currentChunk.set(currentArkTsData, currentChunkOffset); - currentChunkOffset += currentArkTsData.length; - } - } + splitFileAndSaveArkTs(maxSize, currentChunkOffset, + currentChunk, fileType, pageNum, saveStartOffset, saveIndex, timStamp, db); } } } @@ -940,21 +941,42 @@ async function splitFileAndSave( let remnantArray = new Uint8Array(currentChunkOffset); let remnantChunk = currentChunk.slice(0, currentChunkOffset); remnantArray.set(remnantChunk, 0); - await addDataToIndexeddb(db, { - buf: remnantArray, - id: `${fileType}_new_${timStamp}_${pageNum}_${saveIndex}`, - fileType: `${fileType}_new`, - pageNum: pageNum, - startOffset: saveStartOffset, - endOffset: saveStartOffset + maxSize, - index: saveIndex, - timStamp: timStamp, - }); + let arg2 = setArg(remnantArray, fileType, pageNum, saveStartOffset, saveIndex, maxSize, timStamp); + await addDataToIndexeddb(db, arg2); arkTsDataSize = 0; arkTsData.length = 0; } } +function setArg( + remnantArray: Uint8Array, + fileType: string, + pageNum: number, + saveStartOffset: number, + saveIndex: number, + maxSize: number, + timStamp: number +): any { + return { + buf: remnantArray, + id: `${fileType}_new_${timStamp}_${pageNum}_${saveIndex}`, + fileType: `${fileType}_new`, + pageNum: pageNum, + startOffset: saveStartOffset, + endOffset: saveStartOffset + maxSize, + index: saveIndex, + timStamp: timStamp, + }; +} +function getRange(timStamp: number, fileType: string, queryStartIndex: number, queryEndIndex: number) { + return IDBKeyRange.bound( + [timStamp, fileType, 0, queryStartIndex], + [timStamp, fileType, 0, queryEndIndex], + false, + false + ); +} + enum DataTypeEnum { data, json, @@ -1023,7 +1045,7 @@ enum FileTypeEnum { function cutFileBufferByOffSet(out: Uint8Array, uint8Array: Uint8Array) { let jsonStr: string = dec.decode(out); let jsonObj = JSON.parse(jsonStr); - let valueArray: Array<{ offset: number; size: number }> = jsonObj.value; + let valueArray: Array<{ offset: number; size: number; }> = jsonObj.value; const sum = valueArray.reduce((total, obj) => total + obj.size, 0); let cutBuffer = new Uint8Array(sum); let offset = 0; @@ -1040,37 +1062,7 @@ function cutFileByRange(e: MessageEvent) { let cutRightTs = e.data.rightTs; let uint8Array = new Uint8Array(e.data.buffer); let resultBuffer: Array = []; - let cutFileCallBack = (heapPtr: number, size: number, fileType: number, isEnd: number) => { - let out: Uint8Array = Module.HEAPU8.slice(heapPtr, heapPtr + size); - if (FileTypeEnum.data === fileType) { - resultBuffer.push(out); - } else if (FileTypeEnum.json === fileType) { - let cutBuffer = cutFileBufferByOffSet(out, uint8Array); - resultBuffer.push(cutBuffer); - } - if (isEnd) { - const cutResultFileLength = resultBuffer.reduce((total, obj) => total + obj.length, 0); - let cutBuffer = new Uint8Array(cutResultFileLength); - let offset = 0; - resultBuffer.forEach((item) => { - cutBuffer.set(item, offset); - offset += item.length; - }); - resultBuffer.length = 0; - self.postMessage( - { - id: e.data.id, - action: e.data.action, - cutStatus: true, - msg: 'split success', - buffer: e.data.buffer, - cutBuffer: cutBuffer.buffer, - }, - // @ts-ignore - [e.data.buffer, cutBuffer.buffer] - ); - } - }; + let cutFileCallBack = cutFileCallBackFunc(resultBuffer, uint8Array, e); splitReqBufferAddr = Module._InitializeSplitFile(Module.addFunction(cutFileCallBack, 'viiii'), REQ_BUF_SIZE); let cutTimeRange = `${cutLeftTs};${cutRightTs};`; let cutTimeRangeBuffer = enc.encode(cutTimeRange); @@ -1104,9 +1096,41 @@ function cutFileByRange(e: MessageEvent) { } } } +function cutFileCallBackFunc(resultBuffer: Array, uint8Array: Uint8Array, e: MessageEvent): Function { + return (heapPtr: number, size: number, fileType: number, isEnd: number) => { + let out: Uint8Array = Module.HEAPU8.slice(heapPtr, heapPtr + size); + if (FileTypeEnum.data === fileType) { + resultBuffer.push(out); + } else if (FileTypeEnum.json === fileType) { + let cutBuffer = cutFileBufferByOffSet(out, uint8Array); + resultBuffer.push(cutBuffer); + } + if (isEnd) { + const cutResultFileLength = resultBuffer.reduce((total, obj) => total + obj.length, 0); + let cutBuffer = new Uint8Array(cutResultFileLength); + let offset = 0; + resultBuffer.forEach((item) => { + cutBuffer.set(item, offset); + offset += item.length; + }); + resultBuffer.length = 0; + self.postMessage( + { + id: e.data.id, + action: e.data.action, + cutStatus: true, + msg: 'split success', + buffer: e.data.buffer, + cutBuffer: cutBuffer.buffer, + }, + // @ts-ignore + [e.data.buffer, cutBuffer.buffer] + ); + } + }; +} function createView(sql: string) { - // console.log("createView:",sql); let array = enc.encode(sql); Module.HEAPU8.set(array, reqBufferAddr); let res = Module._TraceStreamerSqlOperateEx(array.length); @@ -1129,7 +1153,6 @@ function query(name: string, sql: string, params: any): void { }); } start = new Date().getTime(); - // console.log(sql); let sqlUintArray = enc.encode(sql); Module.HEAPU8.set(sqlUintArray, reqBufferAddr); Module._TraceStreamerSqlQueryEx(sqlUintArray.length); @@ -1145,7 +1168,6 @@ function querySdk(name: string, sql: string, sdkParams: any, action: string) { } }); } - // console.log(name,sql); let sqlUintArray = enc.encode(sql); let commentId = action.substring(action.lastIndexOf('-') + 1); let key = Number(commentId); diff --git a/ide/src/trace/database/data-trafic/AbilityMonitorReceiver.ts b/ide/src/trace/database/data-trafic/AbilityMonitorReceiver.ts index dd73a26a17e6dbc69e497e7e5d466300d8bed482..e1c39e693bf17d017f210ad3f0e915cbe56c9ad0 100644 --- a/ide/src/trace/database/data-trafic/AbilityMonitorReceiver.ts +++ b/ide/src/trace/database/data-trafic/AbilityMonitorReceiver.ts @@ -10,205 +10,333 @@ // 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 { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; +export const cpuAbilityMonitorDataSql = (args: any): string => { + return `select + (t.total_load) as value, + (t.ts - ${args.recordStartNS} ) as startNs + from cpu_usage t`; +}; +export const cpuAbilityUserDataSql = (args: any): string => { + return `select + t.user_load as value, + (t.ts - ${args.recordStartNS} ) as startNs + from cpu_usage t`; +}; +export const cpuAbilitySystemDataSql = (args: any): string => { + return `select + t.system_load as value, + (t.ts - ${args.recordStartNS} ) as startNs + from cpu_usage t`; +}; +export const abilityMemoryDataSql = (args: any): string => { + return `select + t.value as value, + (t.ts - ${args.recordStartNS} ) as startNs + from sys_mem_measure t + where t.filter_id = ${args.id}`; +}; +export const abilityBytesReadDataSql = (args: any): string => { + return `select + t.rd_speed as value, + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; +}; +export const abilityBytesWrittenDataSql = (args: any): string => { + return `select + t.wr_speed as value, + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; +}; +export const abilityReadOpsDataSql = (args: any): string => { + return `select + t.rd_count_speed as value, + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; +}; +export const abilityWrittenOpsDataSql = (args: any): string => { + return `select + t.wr_count_speed as value, + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; +}; +export const abilityBytesInTraceDataSql = (args: any): string => { + return `select + t.tx_speed as value, + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; +}; +export const abilityBytesOutTraceDataSql = (args: any): string => { + return `select + t.rx_speed as value, + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; +}; +export const abilityPacketInDataSql = (args: any): string => { + return `select + t.packet_in_sec as value, + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; +}; +export const abilityPacketsOutDataSql = (args: any): string => { + return `select + t.packet_out_sec as value, + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; +}; export const cpuAbilityMonitorDataProtoSql = (args: any): string => { return `select (t.total_load) as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from cpu_usage t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from cpu_usage t`; }; export const cpuAbilityUserDataProtoSql = (args: any): string => { return `select t.user_load as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from cpu_usage t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from cpu_usage t`; }; export const cpuAbilitySystemDataProtoSql = (args: any): string => { return `select t.system_load as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from cpu_usage t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from cpu_usage t`; }; export const abilityMemoryDataProtoSql = (args: any): string => { return `select t.value as value, - (t.ts - ${args.recordStartNS} ) as startNs, - t.dur as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px + (t.ts - ${args.recordStartNS} ) as startNs from sys_mem_measure t - where t.filter_id = ${args.id} - and startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + where t.filter_id = ${args.id}`; }; export const abilityBytesReadDataProtoSql = (args: any): string => { return `select t.rd_speed as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from diskio t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; }; export const abilityBytesWrittenDataProtoSql = (args: any): string => { return `select t.wr_speed as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from diskio t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; }; export const abilityReadOpsDataProtoSql = (args: any): string => { return `select t.rd_count_speed as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from diskio t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; }; export const abilityWrittenOpsDataProtoSql = (args: any): string => { return `select t.wr_count_speed as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from diskio t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from diskio t`; }; export const abilityBytesInTraceDataProtoSql = (args: any): string => { return `select t.tx_speed as value, - (t.ts - ${args.recordStartNS} ) as startNs, - t.dur as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from network t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; }; export const abilityBytesOutTraceDataProtoSql = (args: any): string => { return `select t.rx_speed as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from network t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; }; export const abilityPacketInDataProtoSql = (args: any): string => { return `select t.packet_in_sec as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from network t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; }; export const abilityPacketsOutDataProtoSql = (args: any): string => { return `select t.packet_out_sec as value, - (t.ts - ${args.recordStartNS} ) as startNs, - max(ifnull(t.dur, ${args.recordEndNS} - t.ts)) as dur, - ((t.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) as px - from network t - where startNs + (ifnull(dur,0)) >= ${Math.floor(args.startNS)} - and startNs <= ${Math.floor(args.endNS)} - group by px`; + (t.ts - ${args.recordStartNS} ) as startNs + from network t`; }; +let totalList: Array = []; +let userList: Array = []; +let systemList: Array = []; +let memoryList: Array = []; +let memoryListMap = new Map>(); +let bytesReadList: Array = []; +let bytesWriteList: Array = []; +let readOpsList: Array = []; +let writeOpsList: Array = []; +let bytesInList: Array = []; +let bytesOutList: Array = []; +let packetInList: Array = []; +let packetOutList: Array = []; + +export function resetAbilityMonitor(): void { + totalList = []; + userList = []; + systemList = []; + memoryList = []; + memoryListMap.clear(); + bytesReadList = []; + bytesWriteList = []; + readOpsList = []; + writeOpsList = []; + bytesInList = []; + bytesOutList = []; + packetInList = []; + packetOutList = []; +} /** * @param data * @param proc */ + export function cpuAbilityMonitorDataReceiver(data: any, proc: Function): void { - let sql = cpuAbilityMonitorDataProtoSql(data.params); - let res = proc(sql); - cpuArrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (totalList.length === 0) { + totalList = proc(cpuAbilityMonitorDataSql(data.params)); + } + cpuArrayBufferHandler(data, totalList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = cpuAbilityMonitorDataProtoSql(data.params); + let res = proc(sql); + cpuArrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function cpuAbilityUserDataReceiver(data: any, proc: Function): void { - let sql = cpuAbilityUserDataProtoSql(data.params); - let res = proc(sql); - cpuArrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (userList.length === 0) { + userList = proc(cpuAbilityUserDataSql(data.params)); + } + cpuArrayBufferHandler(data, userList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = cpuAbilityUserDataProtoSql(data.params); + let res = proc(sql); + cpuArrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function cpuAbilitySystemDataReceiver(data: any, proc: Function): void { - let sql = cpuAbilitySystemDataProtoSql(data.params); - let res = proc(sql); - cpuArrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (systemList.length === 0) { + systemList = proc(cpuAbilitySystemDataSql(data.params)); + } + cpuArrayBufferHandler(data, systemList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = cpuAbilitySystemDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityMemoryUsedDataReceiver(data: any, proc: Function): void { - let sql = abilityMemoryDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (!memoryListMap.has(data.params.id)) { + memoryList = proc(abilityMemoryDataSql(data.params)); + memoryListMap.set(data.params.id, memoryList); + } + let list = memoryListMap.get(data.params.id) || []; + arrayBufferHandler(data, list, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityMemoryDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityBytesReadDataReceiver(data: any, proc: Function): void { - let sql = abilityBytesReadDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (bytesReadList.length === 0) { + bytesReadList = proc(abilityBytesReadDataSql(data.params)); + } + arrayBufferHandler(data, bytesReadList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityBytesReadDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityBytesWrittenDataReceiver(data: any, proc: Function): void { - let sql = abilityBytesWrittenDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (bytesWriteList.length === 0) { + bytesWriteList = proc(abilityBytesWrittenDataSql(data.params)); + } + arrayBufferHandler(data, bytesWriteList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityBytesWrittenDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityReadOpsDataReceiver(data: any, proc: Function): void { - let sql = abilityReadOpsDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (readOpsList.length === 0) { + readOpsList = proc(abilityReadOpsDataSql(data.params)); + } + arrayBufferHandler(data, readOpsList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityReadOpsDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityWrittenOpsDataReceiver(data: any, proc: Function): void { - let sql = abilityWrittenOpsDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (writeOpsList.length === 0) { + writeOpsList = proc(abilityWrittenOpsDataSql(data.params)); + } + arrayBufferHandler(data, writeOpsList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityWrittenOpsDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityBytesInTraceDataReceiver(data: any, proc: Function): void { - let sql = abilityBytesInTraceDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (bytesInList.length === 0) { + bytesInList = proc(abilityBytesInTraceDataSql(data.params)); + } + arrayBufferHandler(data, bytesInList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityBytesInTraceDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityBytesOutTraceDataReceiver(data: any, proc: Function): void { - let sql = abilityBytesOutTraceDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (bytesOutList.length === 0) { + bytesOutList = proc(abilityBytesOutTraceDataSql(data.params)); + } + arrayBufferHandler(data, bytesOutList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityBytesOutTraceDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityPacketInTraceDataReceiver(data: any, proc: Function): void { - let sql = abilityPacketInDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (packetInList.length === 0) { + packetInList = proc(abilityPacketInDataSql(data.params)); + } + arrayBufferHandler(data, packetInList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityPacketInDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } export function abilityPacketsOutTraceDataReceiver(data: any, proc: Function): void { - let sql = abilityPacketsOutDataProtoSql(data.params); - let res = proc(sql); - arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + if (data.params.trafic === TraficEnum.Memory) { + if (packetOutList.length === 0) { + packetOutList = proc(abilityPacketsOutDataSql(data.params)); + } + arrayBufferHandler(data, packetOutList, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = abilityPacketsOutDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } } function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { diff --git a/ide/src/trace/database/data-trafic/AbilityMonitorSender.ts b/ide/src/trace/database/data-trafic/AbilityMonitorSender.ts index 545c51e60a409de8c98b7784edc78d7e795cc758..076c1deb402b19776b419994eeaae2d9653244f7 100644 --- a/ide/src/trace/database/data-trafic/AbilityMonitorSender.ts +++ b/ide/src/trace/database/data-trafic/AbilityMonitorSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { DiskAbilityMonitorStruct } from '../ui-worker/ProcedureWorkerDiskIoAbility'; @@ -24,7 +24,7 @@ export function cpuAbilityUserDataSender( row: TraceRow, type: string ): Promise { - let trafic: number = TraficEnum.ProtoBuffer; + let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { @@ -63,7 +63,7 @@ export function abilityMemoryUsedDataSender( id: string = '', row: TraceRow ): Promise { - let trafic: number = TraficEnum.ProtoBuffer; + let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { @@ -95,7 +95,7 @@ export function abilityBytesReadDataSender( row: TraceRow, type: string ): Promise { - let trafic: number = TraficEnum.ProtoBuffer; + let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { @@ -136,7 +136,7 @@ export function abilityBytesInTraceDataSender( row: TraceRow, type: string ): Promise { - let trafic: number = TraficEnum.ProtoBuffer; + let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { diff --git a/ide/src/trace/database/data-trafic/ArkTsReceiver.ts b/ide/src/trace/database/data-trafic/ArkTsReceiver.ts index c0e8f28d3317f14d504029a21a279940969b9b72..f079f6810cd1c96dcb546f72f9f4a1d686aaad05 100644 --- a/ide/src/trace/database/data-trafic/ArkTsReceiver.ts +++ b/ide/src/trace/database/data-trafic/ArkTsReceiver.ts @@ -16,7 +16,7 @@ import { DataCache, JsProfilerSymbol, convertJSON } from '../../database/logic-worker/ProcedureLogicWorkerCommon'; import { JsCpuProfilerChartFrame, type JsCpuProfilerUIStruct } from '../../bean/JsStruct'; import { JsCpuProfilerSample, SampleType } from '../logic-worker/ProcedureLogicWorkerJsCpuProfiler'; -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; const dataCache = DataCache.getInstance(); const ROOT_ID = 1; diff --git a/ide/src/trace/database/data-trafic/ArkTsSender.ts b/ide/src/trace/database/data-trafic/ArkTsSender.ts index 3ba6c1d3fc4e2d82be2d76c2da0a89014be32ef0..dad2960c9190f44ad0f52352357282d27c6b2343 100644 --- a/ide/src/trace/database/data-trafic/ArkTsSender.ts +++ b/ide/src/trace/database/data-trafic/ArkTsSender.ts @@ -16,7 +16,7 @@ import { TraceRow } from '../../component/trace/base/TraceRow'; import { threadPool } from '../SqlLite'; import { JsCpuProfilerStruct } from '../ui-worker/ProcedureWorkerCpuProfiler'; -import { CHART_OFFSET_LEFT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, QueryEnum, TraficEnum } from './utils/QueryEnum'; export function cpuProfilerDataSender(row: TraceRow) { let trafic: number = TraficEnum.ProtoBuffer; diff --git a/ide/src/trace/database/data-trafic/ClockDataReceiver.ts b/ide/src/trace/database/data-trafic/ClockDataReceiver.ts index 1447725bbd96ace7def6650fe500750f660d13cb..a25e2300607640b6013aac9d4a656c4c83e292a9 100644 --- a/ide/src/trace/database/data-trafic/ClockDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/ClockDataReceiver.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { TraficEnum } from './QueryEnum'; -import { filterDataByGroup } from "./DataFilter"; -import {clockList} from "./AllMemoryCache"; +import { TraficEnum } from './utils/QueryEnum'; +import { filterDataByGroup } from "./utils/DataFilter"; +import {clockList} from "./utils/AllMemoryCache"; export const chartClockDataSql = (args: any): string => { if (args.sqlType === 'clockFrequency') { @@ -99,8 +99,13 @@ export function clockDataReceiver(data: any, proc: Function): void { } else { list = clockList.get(data.params.sqlType + data.params.clockName) || []; } - res = filterDataByGroup(list || [], 'startNs', 'dur', data.params.startNS, data.params.endNS, data.params.width); - arrayBufferHandler(data, res,false); + if (data.params.queryAll) { + //框选时候取数据,只需要根据时间过滤数据 + res = (list || []).filter(it => it.startNs + it.dur >= data.params.startNS && it.startNs <= data.params.endNS); + } else { + res = filterDataByGroup(list || [], 'startNs', 'dur', data.params.startNS, data.params.endNS, data.params.width, "value"); + } + arrayBufferHandler(data, res,true); } else { let sql = chartClockDataSql(data.params); let res = proc(sql); diff --git a/ide/src/trace/database/data-trafic/ClockDataSender.ts b/ide/src/trace/database/data-trafic/ClockDataSender.ts index a274f8a448a4a895031f469795c3925401351c82..ae2cd745172b4a08ba29544e68876bd81dcc014c 100644 --- a/ide/src/trace/database/data-trafic/ClockDataSender.ts +++ b/ide/src/trace/database/data-trafic/ClockDataSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { ClockStruct } from '../ui-worker/ProcedureWorkerClock'; @@ -24,7 +24,7 @@ export function clockDataSender( ): Promise { let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; - if ((trafic === TraficEnum.SharedArrayBuffer||trafic===TraficEnum.Memory) && !row.sharedArrayBuffers) { + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { filterId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), value: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), @@ -43,6 +43,7 @@ export function clockDataSender( totalNS: args ? (args.endNS - args.startNS) : (TraceRow.range?.totalNS || 0), recordStartNS: window.recordStartNS, recordEndNS: window.recordEndNS, + queryAll: args && args.queryAll, t: Date.now(), width: width, trafic: trafic, diff --git a/ide/src/trace/database/data-trafic/CpuDataReceiver.ts b/ide/src/trace/database/data-trafic/CpuDataReceiver.ts index d538e41fe22272ff15cbba4930ad23b0cc541f32..9deae21e1300e61f3212bf384e7310e9a3814546 100644 --- a/ide/src/trace/database/data-trafic/CpuDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/CpuDataReceiver.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {TraficEnum} from './QueryEnum'; -import {filterDataByGroup} from './DataFilter'; -import {cpuList} from './AllMemoryCache'; +import {TraficEnum} from './utils/QueryEnum'; +import {filterDataByGroup} from './utils/DataFilter'; +import {cpuList} from './utils/AllMemoryCache'; export const chartCpuDataProtoSql = (args: any): string => { return ` @@ -54,6 +54,9 @@ export function cpuDataReceiver(data: any, proc: Function): void { let res: any[], list: any[]; if (!cpuList.has(data.params.cpu)) { list = proc(chartCpuDataProtoSqlMem(data.params)); + if (data.params.cpu === 0) { + console.log(list); + } for (let i = 0; i < list.length; i++) { if (list[i].dur == -1) { list[i].nofinish = 1; @@ -71,7 +74,7 @@ export function cpuDataReceiver(data: any, proc: Function): void { list = cpuList.get(data.params.cpu) || []; } res = filterDataByGroup(list || [], 'startTime', 'dur', data.params.startNS, data.params.endNS, data.params.width); - arrayBufferHandler(data, res, false); + arrayBufferHandler(data, res, true); } else { let sql = chartCpuDataProtoSql(data.params); let res = proc(sql); @@ -97,7 +100,7 @@ function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { let id = new Uint16Array(transfer ? res.length : data.params.sharedArrayBuffers.id); let processId = new Int16Array(transfer ? res.length : data.params.sharedArrayBuffers.processId); let cpu = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.cpu); - let argSetId = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.argSetId); + let argSetId = new Int8Array(transfer ? res.length : data.params.sharedArrayBuffers.argSetId); let nofinish = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.nofinish); res.forEach((it, i) => { data.params.trafic === TraficEnum.ProtoBuffer && (it = it.cpuData); diff --git a/ide/src/trace/database/data-trafic/CpuDataSender.ts b/ide/src/trace/database/data-trafic/CpuDataSender.ts index 8a45ec002decf806f891ec183540f63a61febf97..4b46c69d0683f20a95fcfd7289755c8e00c5005f 100644 --- a/ide/src/trace/database/data-trafic/CpuDataSender.ts +++ b/ide/src/trace/database/data-trafic/CpuDataSender.ts @@ -11,15 +11,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CpuStruct } from '../ui-worker/ProcedureWorkerCPU'; -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CpuStruct } from '../ui-worker/cpu/ProcedureWorkerCPU'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; export function cpuDataSender(cpu: number, row: TraceRow): Promise { let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; - if ((trafic === TraficEnum.SharedArrayBuffer || trafic === TraficEnum.Memory) && !row.sharedArrayBuffers) { + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { processId: new SharedArrayBuffer(Uint16Array.BYTES_PER_ELEMENT * MAX_COUNT), id: new SharedArrayBuffer(Uint16Array.BYTES_PER_ELEMENT * MAX_COUNT), @@ -27,7 +27,7 @@ export function cpuDataSender(cpu: number, row: TraceRow): Promise { diff --git a/ide/src/trace/database/data-trafic/EBPFSender.ts b/ide/src/trace/database/data-trafic/EBPFSender.ts index f025cea18de1a29dd876aaa90d76934e5c3b86ba..382ea9e05db9fec02db3d3923bafd2a015e26b30 100644 --- a/ide/src/trace/database/data-trafic/EBPFSender.ts +++ b/ide/src/trace/database/data-trafic/EBPFSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { EBPFChartStruct } from '../ui-worker/ProcedureWorkerEBPF'; diff --git a/ide/src/trace/database/data-trafic/EnergySysEventReceiver.ts b/ide/src/trace/database/data-trafic/EnergySysEventReceiver.ts index 4017c0bf61f10158b633033d7e9335dd5904d872..955d5101f2c8b9840425d497aecd301656b5336e 100644 --- a/ide/src/trace/database/data-trafic/EnergySysEventReceiver.ts +++ b/ide/src/trace/database/data-trafic/EnergySysEventReceiver.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; export const systemDataSql = (args: any): string => { return `SELECT S.id, diff --git a/ide/src/trace/database/data-trafic/EnergySysEventSender.ts b/ide/src/trace/database/data-trafic/EnergySysEventSender.ts index 57c4ae58b85f51ba5e891928c73bd998a1ab9978..c1ae0928bb41ad991a4ed14d0b5d6cfd5d2a3396 100644 --- a/ide/src/trace/database/data-trafic/EnergySysEventSender.ts +++ b/ide/src/trace/database/data-trafic/EnergySysEventSender.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { EnergySystemStruct } from '../ui-worker/ProcedureWorkerEnergySystem'; diff --git a/ide/src/trace/database/data-trafic/FrameDynamicEffectReceiver.ts b/ide/src/trace/database/data-trafic/FrameDynamicEffectReceiver.ts index 137eab99c99e98b5c981b6baad344bf77b35b3d7..b54fdc5f8996bc073e024f2474a7dddf8c829e0e 100644 --- a/ide/src/trace/database/data-trafic/FrameDynamicEffectReceiver.ts +++ b/ide/src/trace/database/data-trafic/FrameDynamicEffectReceiver.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; import { FrameAnimationStruct } from '../ui-worker/ProcedureWorkerFrameAnimation'; import { FrameSpacingStruct } from '../ui-worker/ProcedureWorkerFrameSpacing'; diff --git a/ide/src/trace/database/data-trafic/FrameDynamicEffectSender.ts b/ide/src/trace/database/data-trafic/FrameDynamicEffectSender.ts index 99be7d4337d6b63c74819724c3d30348de2c5b1a..5fb769fbd77af11b85ad2beb7137a3c44969d9ff 100644 --- a/ide/src/trace/database/data-trafic/FrameDynamicEffectSender.ts +++ b/ide/src/trace/database/data-trafic/FrameDynamicEffectSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { FrameAnimationStruct } from '../ui-worker/ProcedureWorkerFrameAnimation'; diff --git a/ide/src/trace/database/data-trafic/FrameJanksReceiver.ts b/ide/src/trace/database/data-trafic/FrameJanksReceiver.ts index 4fe99576b005841a3849d6335a74e8e7cf3e00fc..3a687acfe6ee56bd4171e7899d36444206c2be04 100644 --- a/ide/src/trace/database/data-trafic/FrameJanksReceiver.ts +++ b/ide/src/trace/database/data-trafic/FrameJanksReceiver.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; import { JanksStruct } from '../../bean/JanksStruct'; export const chartExpectedMemoryDataSql = (args: any): string => { @@ -245,7 +245,7 @@ export function frameExpectedReceiver(data: any, proc: Function): void { frameDepthList = new Map(); let sql = chartExpectedMemoryDataSql(data.params); let res = proc(sql); - frameJanksReceiver(data, res, 'expect', false); + frameJanksReceiver(data, res, 'expect', true); } else { let sql = chartExpectedDataSql(data.params); let res = proc(sql); @@ -257,7 +257,7 @@ export function frameActualReceiver(data: any, proc: Function): void { if (data.params.trafic === TraficEnum.Memory) { let sql = chartActualMemoryDataSql(data.params); let res = proc(sql); - frameJanksReceiver(data, res, 'actual', false); + frameJanksReceiver(data, res, 'actual', true); } else { let sql = chartActualDataSql(data.params); let res = proc(sql); diff --git a/ide/src/trace/database/data-trafic/FrameJanksSender.ts b/ide/src/trace/database/data-trafic/FrameJanksSender.ts index 656048feb64d53b117f0366d92bc500ba84ec4fd..5c5fa005317f9cbd84f9c87f48ac01d41d42c28d 100644 --- a/ide/src/trace/database/data-trafic/FrameJanksSender.ts +++ b/ide/src/trace/database/data-trafic/FrameJanksSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { JanksStruct } from '../../bean/JanksStruct'; @@ -22,7 +22,7 @@ export function frameJanksSender(queryEnum: number, row: TraceRow): transferJankDataType = TraficEnum.ProtoBuffer; } let width = row.clientWidth - CHART_OFFSET_LEFT; - if ((transferJankDataType === TraficEnum.SharedArrayBuffer || transferJankDataType === TraficEnum.Memory) && !row.sharedArrayBuffers) { + if ((transferJankDataType === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { id: new SharedArrayBuffer(Uint16Array.BYTES_PER_ELEMENT * MAX_COUNT), ipid: new SharedArrayBuffer(Uint16Array.BYTES_PER_ELEMENT * MAX_COUNT), diff --git a/ide/src/trace/database/data-trafic/HiSysEventDataReceiver.ts b/ide/src/trace/database/data-trafic/HiSysEventDataReceiver.ts index 82a1b0bcc0873e38e8683eff3f1c7673cafc81a8..fccdebea982d41898decd52b40abd2cb13005a9e 100644 --- a/ide/src/trace/database/data-trafic/HiSysEventDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/HiSysEventDataReceiver.ts @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; export const chartHiSysEventDataSql = (args: any): string => { return ` diff --git a/ide/src/trace/database/data-trafic/HiSysEventDataSender.ts b/ide/src/trace/database/data-trafic/HiSysEventDataSender.ts index 9d7c3b83dccf38144a8e4f87becd99d031e7f244..bb4fc80175228d2e7d2793747f8e8520cfb640ea 100644 --- a/ide/src/trace/database/data-trafic/HiSysEventDataSender.ts +++ b/ide/src/trace/database/data-trafic/HiSysEventDataSender.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { HiSysEventStruct } from '../ui-worker/ProcedureWorkerHiSysEvent'; diff --git a/ide/src/trace/database/data-trafic/IrqDataReceiver.ts b/ide/src/trace/database/data-trafic/IrqDataReceiver.ts index 32ce91bece3d64e23888aa2b529af6c30193a6ed..d3946890295fa87593943d9028ef9ac3f8457546 100644 --- a/ide/src/trace/database/data-trafic/IrqDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/IrqDataReceiver.ts @@ -11,9 +11,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { TraficEnum } from './QueryEnum'; -import {filterDataByGroup} from "./DataFilter"; -import {lrqList} from "./AllMemoryCache"; +import { TraficEnum } from './utils/QueryEnum'; +import {filterDataByGroup} from "./utils/DataFilter"; +import {lrqList} from "./utils/AllMemoryCache"; export const chartIrqDataSql = (args: any): string => { if (args.name === 'irq') { @@ -82,7 +82,7 @@ export function irqDataReceiver(data: any, proc: Function): void { list = lrqList.get(data.params.cpu + data.params.name) || []; } res = filterDataByGroup(list || [], 'startNs', 'dur', data.params.startNS, data.params.endNS, data.params.width); - arrayBufferHandler(data, res,false); + arrayBufferHandler(data, res,true); } else { let sql = chartIrqDataSql(data.params); let res = proc(sql); @@ -94,7 +94,7 @@ function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { let startNS = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startNS); let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); let depth = new Uint32Array(transfer ? res.length : data.params.sharedArrayBuffers.depth); - let argSetId = new Uint32Array(transfer ? res.length : data.params.sharedArrayBuffers.argSetId); + let argSetId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.argSetId); let id = new Uint32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); res.forEach((it, i) => { data.params.trafic === TraficEnum.ProtoBuffer && (it = it.irqData); diff --git a/ide/src/trace/database/data-trafic/IrqDataSender.ts b/ide/src/trace/database/data-trafic/IrqDataSender.ts index c534c7066679fd5dc31a1bdd57ed6aadfcfe7c9e..4bc20fd545d3a220af8b0f98a5ac09f608238099 100644 --- a/ide/src/trace/database/data-trafic/IrqDataSender.ts +++ b/ide/src/trace/database/data-trafic/IrqDataSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { IrqStruct } from '../ui-worker/ProcedureWorkerIrq'; @@ -19,9 +19,9 @@ import { IrqStruct } from '../ui-worker/ProcedureWorkerIrq'; export function irqDataSender(cpu: number, name: string, row: TraceRow): Promise { let trafic: number = TraficEnum.ProtoBuffer; let width = row.clientWidth - CHART_OFFSET_LEFT; - if ((trafic === TraficEnum.SharedArrayBuffer||trafic===TraficEnum.Memory) && !row.sharedArrayBuffers) { + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { - argSetId: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + argSetId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), depth: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), id: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), @@ -51,7 +51,7 @@ export function irqDataSender(cpu: number, name: string, row: TraceRow { return `SELECT diff --git a/ide/src/trace/database/data-trafic/LogDataSender.ts b/ide/src/trace/database/data-trafic/LogDataSender.ts index 6318304941e56c2ab8ca337f2c07287aed6e300a..ea7087839920718a508c288cc7b181304dfa558c 100644 --- a/ide/src/trace/database/data-trafic/LogDataSender.ts +++ b/ide/src/trace/database/data-trafic/LogDataSender.ts @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { LogStruct } from '../ui-worker/ProcedureWorkerLog'; diff --git a/ide/src/trace/database/data-trafic/NativeMemoryDataReceiver.ts b/ide/src/trace/database/data-trafic/NativeMemoryDataReceiver.ts index ff3ed6239d3150d16f8fd59262c46fb3d4f647c9..b7fdb545d0095abedd6afced4847c8a7d0f41050 100644 --- a/ide/src/trace/database/data-trafic/NativeMemoryDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/NativeMemoryDataReceiver.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; interface NativeMemoryCacheType { maxSize: number; diff --git a/ide/src/trace/database/data-trafic/NativeMemoryDataSender.ts b/ide/src/trace/database/data-trafic/NativeMemoryDataSender.ts index 999c6c13393aaa2691e87c4d5b5920a0e6701c25..5fee7a6fb50bbf0377948bd3d5cf3ceaa0ce1fcc 100644 --- a/ide/src/trace/database/data-trafic/NativeMemoryDataSender.ts +++ b/ide/src/trace/database/data-trafic/NativeMemoryDataSender.ts @@ -10,7 +10,7 @@ // 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 { QueryEnum, TraficEnum } from './QueryEnum'; +import { QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; diff --git a/ide/src/trace/database/data-trafic/VirtualMemoryDataReceiver.ts b/ide/src/trace/database/data-trafic/VirtualMemoryDataReceiver.ts index a664defe6eda20591cdfcab3ffacc13a0b85cf33..35805352115764b8b151b1ce78286340e3482ece 100644 --- a/ide/src/trace/database/data-trafic/VirtualMemoryDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/VirtualMemoryDataReceiver.ts @@ -11,12 +11,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; export const chartVirtualMemoryDataSql = (args: any): string => { return ` - select ts - ${args.recordStartNS} as startTime, - filter_id as filterId, + select ts - ${args.recordStartNS} as startTime, + filter_id as filterId, + value + from sys_mem_measure + where filter_id = ${args.filterId}`; +}; + +export const chartVirtualMemoryDataProtoSql = (args: any): string => { + return ` + select ts - ${args.recordStartNS} as startTime, + filter_id as filterId, value, ((ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px from sys_mem_measure @@ -26,19 +35,26 @@ export const chartVirtualMemoryDataSql = (args: any): string => { group by px;`; }; +let vmList: Array = []; +let vmListMap = new Map>(); + +export function resetVM(): void { + vmList = []; + vmListMap.clear(); +} + export function virtualMemoryDataReceiver(data: any, proc: Function): void { - let sql = chartVirtualMemoryDataSql(data.params); - let res = proc(sql); - switch (data.params.trafic) { - case TraficEnum.SharedArrayBuffer: - arrayBufferHandler(data, res, false); - break; - case TraficEnum.ProtoBuffer: - arrayBufferHandler(data, res, true); - break; - case TraficEnum.TransferArrayBuffer: - arrayBufferHandler(data, res, true); - break; + if (data.params.trafic === TraficEnum.Memory) { + if (!vmListMap.has(data.params.filterId)) { + vmList = proc(chartVirtualMemoryDataSql(data.params)); + vmListMap.set(data.params.filterId, vmList); + } + let list = vmListMap.get(data.params.filterId) || []; + arrayBufferHandler(data, list, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } else { + let sql = chartVirtualMemoryDataProtoSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); } } @@ -64,6 +80,7 @@ function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { } : {}, len: res.length, + transfer: transfer, }, transfer ? [startTime.buffer, value.buffer, filterID.buffer] : [] ); diff --git a/ide/src/trace/database/data-trafic/VirtualMemoryDataSender.ts b/ide/src/trace/database/data-trafic/VirtualMemoryDataSender.ts index 707ffe1aff8a71ff4b9de974d7d90bbfaecdcc1b..053ca3d68e57dcf2d6f2ada55bd10f6d42f7adbc 100644 --- a/ide/src/trace/database/data-trafic/VirtualMemoryDataSender.ts +++ b/ide/src/trace/database/data-trafic/VirtualMemoryDataSender.ts @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { VirtualMemoryStruct } from '../ui-worker/ProcedureWorkerVirtualMemory'; @@ -20,7 +20,7 @@ export function virtualMemoryDataSender( filterId: number, row: TraceRow ): Promise { - let trafic: number = TraficEnum.ProtoBuffer; + let trafic: number = TraficEnum.Memory; let width = row.clientWidth - CHART_OFFSET_LEFT; if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { row.sharedArrayBuffers = { @@ -43,18 +43,8 @@ export function virtualMemoryDataSender( trafic: trafic, sharedArrayBuffers: row.sharedArrayBuffers, }, - (res: any, len: number) => { - switch (trafic) { - case TraficEnum.SharedArrayBuffer: - resolve(arrayBufferHandler(row.sharedArrayBuffers, len)); - break; - case TraficEnum.ProtoBuffer: - resolve(arrayBufferHandler(res, len)); - break; - case TraficEnum.TransferArrayBuffer: - resolve(arrayBufferHandler(res, len)); - break; - } + (res: any, len: number, transfer: boolean) => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); } ); }); diff --git a/ide/src/trace/database/data-trafic/VmTrackerDataReceiver.ts b/ide/src/trace/database/data-trafic/VmTrackerDataReceiver.ts index 51becdeaa0fe67e1352c0b5ff88b5d5aa6fc75d2..2aaa9b9bb5926233a0d071b32737d1ee4947670f 100644 --- a/ide/src/trace/database/data-trafic/VmTrackerDataReceiver.ts +++ b/ide/src/trace/database/data-trafic/VmTrackerDataReceiver.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { TraficEnum } from './QueryEnum'; +import { TraficEnum } from './utils/QueryEnum'; export const chartSMapsDataSqlMem = (args: any): string => { return `SELECT (A.timestamp - ${args.recordStartNS}) as startNs, diff --git a/ide/src/trace/database/data-trafic/VmTrackerDataSender.ts b/ide/src/trace/database/data-trafic/VmTrackerDataSender.ts index 27754d02fdc8b21091914b1e6351aab54d15f245..93c2ad9088047b4fb1828e5b5b07620a764d1241 100644 --- a/ide/src/trace/database/data-trafic/VmTrackerDataSender.ts +++ b/ide/src/trace/database/data-trafic/VmTrackerDataSender.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './QueryEnum'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum'; import { threadPool } from '../SqlLite'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { SnapshotStruct } from '../ui-worker/ProcedureWorkerSnapshot'; diff --git a/ide/src/trace/database/data-trafic/cpu/CpuFreqDataReceiver.ts b/ide/src/trace/database/data-trafic/cpu/CpuFreqDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebd35724f023d92adfd1100d8e3c5250ab5341da --- /dev/null +++ b/ide/src/trace/database/data-trafic/cpu/CpuFreqDataReceiver.ts @@ -0,0 +1,120 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import {filterDataByGroup} from "../utils/DataFilter"; +import {cpuFreqList} from "../utils/AllMemoryCache"; + +export const chartCpuFreqDataSql = (args: any): string => { + return `select ${args.cpu} cpu, + value, + max(ifnull(dur, ${args.recordEndNS}-c.ts)) dur, + ts - ${ + args.recordStartNS + } as startNs, + ((ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from measure c + where c.filter_id = (select id from cpu_measure_filter t where t.cpu = ${ + args.cpu + } and (t.name = 'cpufreq' or t.name = 'cpu_frequency') + limit 1) + and startNs + ifnull(dur, ${args.recordEndNS}-c.ts) >= ${Math.floor(args.startNS)} + and startNs <= ${Math.floor(args.endNS)} + group by px + union + select ${args.cpu} cpu, + max(value), + dur dur, + ts - ${ + args.recordStartNS + } as startNs, + ((ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from measure c + where c.filter_id = (select id from cpu_measure_filter t where t.cpu = ${ + args.cpu + } and (t.name = 'cpufreq' or t.name = 'cpu_frequency') + limit 1) + and startNs + ifnull(dur, ${args.recordEndNS}-c.ts) >= ${Math.floor(args.startNS)} + and startNs <= ${Math.floor(args.endNS)} + group by px; + ;`; +}; + +export const chartCpuFreqDataSqlMem = (args: any): string => { + return ` + select cpu, + value, + ifnull(dur, ${args.recordEndNS} - c.ts) dur, + ts - ${args.recordStartNS} as startNs + from measure c + inner join + cpu_measure_filter t + on c.filter_id = t.id + where (name = 'cpufreq' or name = 'cpu_frequency') + and cpu = ${args.cpu}; + `; +}; + +export function cpuFreqDataReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + let res: any[], list: any[]; + if (!cpuFreqList.has(data.params.cpu)) { + list = proc(chartCpuFreqDataSqlMem(data.params)); + for (let i = 0; i < list.length; i++) { + if (list[i].dur===-1 || list[i].dur===null || list[i].dur === undefined){ + list[i].dur = data.params.recordEndNS - data.params.recordStartNS - list[i].startNs; + } + } + cpuFreqList.set(data.params.cpu, list); + } else { + list = cpuFreqList.get(data.params.cpu) || []; + } + res = filterDataByGroup(list || [], 'startNs', 'dur', data.params.startNS, data.params.endNS, data.params.width, "value"); + arrayBufferHandler(data, res,true); + } else { + let sql = chartCpuFreqDataSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res,data.params.trafic !== TraficEnum.SharedArrayBuffer); + } +} + +export function arrayBufferHandler(data: any, res: any[], transfer:boolean): void { + let startNS = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startNS); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let value = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.value); + let cpu = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.cpu); + res.forEach((it, i): void => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.cpuFreqData); + startNS[i] = it.startNs; + dur[i] = it.dur; + cpu[i] = it.cpu; + value[i] = it.value; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startNS: startNS.buffer, + dur: dur.buffer, + value: value.buffer, + cpu: cpu.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [startNS.buffer, dur.buffer, value.buffer, cpu.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/cpu/CpuFreqDataSender.ts b/ide/src/trace/database/data-trafic/cpu/CpuFreqDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..24cfaeb7b2cf2155ca17a02817f5c34afc0e86b1 --- /dev/null +++ b/ide/src/trace/database/data-trafic/cpu/CpuFreqDataSender.ts @@ -0,0 +1,66 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { CpuFreqStruct } from '../../ui-worker/ProcedureWorkerFreq'; + +export function cpuFreqDataSender(cpu: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + cpu: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT), + value: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + startNS: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.CpuFreqData, + { + cpu: cpu, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): CpuFreqStruct[] { + let outArr: CpuFreqStruct[] = []; + let cpu = new Uint8Array(buffers.cpu); + let value = new Uint32Array(buffers.value); + let startNS = new Float64Array(buffers.startNS); + let dur = new Float64Array(buffers.dur); + for (let i = 0; i < len; i++) { + outArr.push({ + cpu: cpu[i], + value: value[i], + dur: dur[i], + startNS: startNS[i], + } as CpuFreqStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/cpu/CpuFreqLimitDataReceiver.ts b/ide/src/trace/database/data-trafic/cpu/CpuFreqLimitDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f7c5a643ca6d2d4b8f0c445f055921de4684047 --- /dev/null +++ b/ide/src/trace/database/data-trafic/cpu/CpuFreqLimitDataReceiver.ts @@ -0,0 +1,116 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import {filterDataByGroup} from "../utils/DataFilter"; +import {cpuFreqLimitList} from "../utils/AllMemoryCache"; + +export const chartCpuFreqLimitDataSql = (args: any): string => { + return ` + SELECT + max AS max, + min AS min, + value, + max(dura) AS dur, + startNs AS startNs, + ${args.cpu} AS cpu, + (startNs / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + FROM ( + SELECT ts - ${args.recordStartNS} AS startNs, + case when dur is null then (${args.endNS + args.recordStartNS} - ts) else dur end AS dura, + value, + MAX (value) AS max, + MIN (value) AS min + FROM measure + WHERE filter_id IN (${args.maxId}, ${args.minId}) + AND startNs + dura >= ${Math.floor(args.startNS)} + AND startNs <= ${Math.floor(args.endNS)} + GROUP BY ts + ) AS subquery + GROUP BY px; + `; +}; + +export const chartCpuFreqLimitDataSqlMem = (args: any): string => { + return ` + select ts - ${args.recordStartNS} as startNs, + dur, + max(value) as max, + min(value) as min, + $cpu as cpu + from measure where filter_id in (${args.maxId}, ${args.minId}) + group by ts; + `; +}; + + + +export function cpuFreqLimitReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + let res: any[], list: any[]; + if (!cpuFreqLimitList.has(data.params.cpu)) { + let sql = chartCpuFreqLimitDataSqlMem(data.params); + list = proc(sql); + for (let i = 0; i < list.length; i++) { + if(i { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.cpuFreqLimitData); + startNs[i] = it.startNs; + dur[i] = it.dur; + value[i] = it.value; + max[i] = it.max; + min[i] = it.min; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startNs: startNs.buffer, + dur: dur.buffer, + value: value.buffer, + max: max.buffer, + min: min.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [startNs.buffer, dur.buffer, value.buffer, max.buffer, min.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/cpu/CpuFreqLimitDataSender.ts b/ide/src/trace/database/data-trafic/cpu/CpuFreqLimitDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..5561ff42fd711d9fb46e13ad852f47441e89833e --- /dev/null +++ b/ide/src/trace/database/data-trafic/cpu/CpuFreqLimitDataSender.ts @@ -0,0 +1,75 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { CpuFreqLimitsStruct } from '../../ui-worker/cpu/ProcedureWorkerCpuFreqLimits'; + +export function cpuFreqLimitSender( + maxId: number, + minId: number, + cpu: number, + row: TraceRow +): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + value: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + max: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + min: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + startNs: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve, reject): void => { + threadPool.submitProto( + QueryEnum.CpuFreqLimitData, + { + maxId: maxId, + minId: minId, + cpu: cpu, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(res: any, len: number): CpuFreqLimitsStruct[] { + let outArr: CpuFreqLimitsStruct[] = []; + let startNs = new Float64Array(res.startNs); + let dur = new Float64Array(res.dur); + let value = new Uint32Array(res.value); + let max = new Uint32Array(res.max); + let min = new Uint32Array(res.min); + for (let i = 0; i < len; i++) { + outArr.push({ + value: value[i], + max: max[i], + min: min[i], + dur: dur[i], + startNs: startNs[i], + } as unknown as CpuFreqLimitsStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/cpu/CpuStateReceiver.ts b/ide/src/trace/database/data-trafic/cpu/CpuStateReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..91dd37b18841f240b47ddc88a033d570cca4c787 --- /dev/null +++ b/ide/src/trace/database/data-trafic/cpu/CpuStateReceiver.ts @@ -0,0 +1,106 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import {filterDataByGroup} from "../utils/DataFilter"; +import {cpuStateList} from "../utils/AllMemoryCache"; + +export const chartCpuStateDataSql = (args: any): string => { + return ` + select (value) as value, + max(ifnull(dur, ${args.recordEndNS} - A.ts)) as dur, + (A.ts - ${args.recordStartNS}) as startTs, + ((A.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from measure A + where filter_id = ${args.filterId} + and startTs + ifnull(dur, ${args.recordEndNS} - A.ts) >= ${Math.floor(args.startNS)} + and startTs <= ${Math.floor(args.endNS)} + group by px + union + select max(value) as value, + (ifnull(dur, ${args.recordEndNS} - A.ts)) as dur, + (A.ts - ${args.recordStartNS}) as startTs, + ((A.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from measure A + where filter_id = ${args.filterId} + and startTs + ifnull(dur, ${args.recordEndNS} - A.ts) >= ${Math.floor(args.startNS)} + and startTs <= ${Math.floor(args.endNS)} + group by px + ;`; +}; + +export const chartCpuStateDataSqlMem = (args: any): string => { + return ` + select (A.ts - ${args.recordStartNS}) as startTs,ifnull(dur,${args.recordEndNS} - A.ts) dur, + value + from measure A + where filter_id = ${args.filterId}; + `; +}; + + + +export function cpuStateReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + let res: any[], list: any[]; + if (!cpuStateList.has(data.params.filterId)) { + list = proc(chartCpuStateDataSqlMem(data.params)); + for (let i = 0; i < list.length; i++) { + if (list[i].dur===-1 || list[i].dur===null || list[i].dur === undefined){ + list[i].dur = data.params.recordEndNS - data.params.recordStartNS - list[i].startTs; + } + } + cpuStateList.set(data.params.filterId, list); + } else { + list = cpuStateList.get(data.params.filterId) || []; + } + res = filterDataByGroup(list || [], 'startTs', 'dur', data.params.startNS, data.params.endNS, data.params.width, "value"); + arrayBufferHandler(data, res,true); + } else { + let sql = chartCpuStateDataSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res,data.params.trafic !== TraficEnum.SharedArrayBuffer); + } +} + +let heights = [4, 12, 21, 30]; + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let startTs = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTs); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let value = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.value); + let height = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.height); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.cpuStateData); + startTs[i] = it.startTs; + dur[i] = it.dur; + value[i] = it.value; + height[i] = heights[it.value]; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startTs: startTs.buffer, + dur: dur.buffer, + value: value.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [startTs.buffer, dur.buffer, value.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/cpu/CpuStateSender.ts b/ide/src/trace/database/data-trafic/cpu/CpuStateSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..fec316198c94fb39a2467eb566d9a85dfe05925e --- /dev/null +++ b/ide/src/trace/database/data-trafic/cpu/CpuStateSender.ts @@ -0,0 +1,65 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { CpuStateStruct } from '../../ui-worker/cpu/ProcedureWorkerCpuState'; + +export function cpuStateSender(filterId: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + value: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + startTs: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + height: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve, reject): void => { + threadPool.submitProto( + QueryEnum.CpuStateData, + { + filterId: filterId, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(res: any, len: number): CpuStateStruct[] { + let outArr: CpuStateStruct[] = []; + let startTs = new Float64Array(res.startTs); + let dur = new Float64Array(res.dur); + let value = new Uint32Array(res.value); + let height = new Uint8Array(res.value); + for (let i = 0; i < len; i++) { + outArr.push({ + value: value[i], + dur: dur[i], + height: height[i], + startTs: startTs[i], + } as unknown as CpuStateStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfCallChartReceiver.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfCallChartReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..304eb7ad5ca32142be13e5c826790bb56d3d1142 --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfCallChartReceiver.ts @@ -0,0 +1,490 @@ +// 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 { TraficEnum } from "../utils/QueryEnum"; + +interface HiPerfSampleType { + callchainId: number; + startTs: number; + eventCount: number; + threadId: number; + cpuId: number; + eventTypeId: number; +} + +const dataCache: { + startTs: Array; + dur: Array; + depth: Array; + eventCount: Array; + symbolId: Array; + fileId: Array; + callchainId: Array; + selfDur: Array; + name: Array; + callstack: Map; + sampleList: Array; + maxDepth: number; +} = { + callstack: new Map(), + sampleList: [], + maxDepth: 1, + startTs: [], + dur: [], + depth: [], + eventCount: [], + symbolId: [], + fileId: [], + callchainId: [], + selfDur: [], + name: [], +}; + +export const chartHiperfCallChartDataSql = (args: any): string => { + const sql = ` + select callchain_id as callchainId, + timestamp_trace - ${args.recordStartNS} as startTs, + event_count as eventCount, + A.thread_id as threadId, + cpu_id as cpuId, + event_type_id as eventTypeId + from perf_sample A + where callchain_id != -1 and A.thread_id != 0`; + return sql; +}; + +export function hiPerfCallChartDataHandler(data: any, proc: Function): void { + if (data.params.isCache) { + let res: Array = proc(chartHiperfCallChartDataSql(data.params)); + dataCache.sampleList = res.map(it => { + if (data.params.trafic === TraficEnum.ProtoBuffer) { + return { + callchainId: it.hiperfCallChartData.callchainId || 0, + startTs: it.hiperfCallChartData.startTs || 0, + eventCount: it.hiperfCallChartData.eventCount || 0, + threadId: it.hiperfCallChartData.threadId || 0, + cpuId: it.hiperfCallChartData.cpuId || 0, + eventTypeId: it.hiperfCallChartData.eventTypeId || 0, + } + } else { + return it; + } + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: 'ok', + len: 0, + }, + [] + ); + } else { + let res: Array = []; + if (!data.params.isComplete) { + res = dataCache.sampleList.filter((it) => { + let cpuThreadFilter = data.params.type === 0 ? it.cpuId === data.params.id : it.threadId === data.params.id; + let eventTypeFilter = data.params.eventTypeId === -2 ? true : it.eventTypeId === data.params.eventTypeId; + return cpuThreadFilter && eventTypeFilter; + }); + } + arrayBufferHandler(data, res, true, !data.params.isComplete); + } +} + +export function hiPerfCallStackCacheHandler(data: any, proc: Function): void { + if (data.params.isCache) { + hiPerfCallChartClearCache(true); + arrayBufferCallStackHandler(data, proc(hiPerfCallStackDataCacheSql())); + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean, loadData: boolean): void { + if (loadData) { + let result = combinePerfSampleByCallChainId(res, data.params); + hiPerfCallChartClearCache(false); + const getArrayData = (combineData: Array): void => { + for (let item of combineData) { + if (item.depth > -1) { + dataCache.startTs.push(item.startTime); + dataCache.dur.push(item.totalTime); + dataCache.depth.push(item.depth); + dataCache.eventCount.push(item.eventCount); + dataCache.symbolId.push(item.symbolId); + dataCache.fileId.push(item.fileId); + dataCache.callchainId.push(item.callchainId); + dataCache.name.push(item.name); + let self = item.totalTime || 0; + if (item.children) { + (item.children as Array).forEach((child) => { + self -= child.totalTime; + }); + } + dataCache.selfDur.push(self); + } + if (item.depth + 1 > dataCache.maxDepth) { + dataCache.maxDepth = item.depth + 1; + } + if (item.children && item.children.length > 0) { + getArrayData(item.children); + } + } + }; + getArrayData(result); + } + setTimeout((): void => { + arrayBufferCallback(data, transfer); + }, 150); +} + +function arrayBufferCallback(data: any, transfer: boolean): void { + let dataFilter = filterPerfCallChartData( + data.params.startNS, + data.params.endNS, + data.params.totalNS, + data.params.frame, + data.params.expand + ); + let len = dataFilter.startTs.length; + let startTs = new Float64Array(len); + let dur = new Float64Array(len); + let depth = new Int32Array(len); + let eventCount = new Int32Array(len); + let symbolId = new Int32Array(len); + let fileId = new Int32Array(len); + let callchainId = new Int32Array(len); + let selfDur = new Int32Array(len); + let name = new Int32Array(len); + for (let i = 0; i < len; i++) { + startTs[i] = dataFilter.startTs[i]; + dur[i] = dataFilter.dur[i]; + depth[i] = dataFilter.depth[i]; + eventCount[i] = dataFilter.eventCount[i]; + symbolId[i] = dataFilter.symbolId[i]; + fileId[i] = dataFilter.fileId[i]; + callchainId[i] = dataFilter.callchainId[i]; + selfDur[i] = dataFilter.selfDur[i]; + name[i] = dataFilter.name[i]; + } + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startTs: startTs.buffer, + dur: dur.buffer, + depth: depth.buffer, + callchainId: callchainId.buffer, + eventCount: eventCount.buffer, + symbolId: symbolId.buffer, + fileId: fileId.buffer, + selfDur: selfDur.buffer, + name: name.buffer, + maxDepth: dataCache.maxDepth, + } + : {}, + len: len, + }, + transfer + ? [ + startTs.buffer, + dur.buffer, + depth.buffer, + callchainId.buffer, + eventCount.buffer, + symbolId.buffer, + fileId.buffer, + selfDur.buffer, + name.buffer, + ] + : [] + ); +} + +export function filterPerfCallChartData( + startNS: number, + endNS: number, + totalNS: number, + frame: any, + expand: boolean +): { + startTs: Array; + dur: Array; + depth: Array; + eventCount: Array; + symbolId: Array; + fileId: Array; + callchainId: Array; + selfDur: Array; + name: Array; +} { + let dataSource: { + startTs: Array; + dur: Array; + depth: Array; + eventCount: Array; + symbolId: Array; + fileId: Array; + callchainId: Array; + selfDur: Array; + name: Array; + } = { + startTs: [], + dur: [], + depth: [], + eventCount: [], + symbolId: [], + fileId: [], + callchainId: [], + selfDur: [], + name: [], + }; + let data: any = {}; + dataCache.startTs.reduce((pre, current, index) => { + if ( + dataCache.dur[index] > 0 && + current + dataCache.dur[index] >= startNS && + current <= endNS && + ((!expand && dataCache.depth[index] === 0) || expand) + ) { + let x = 0; + if (current > startNS && current < endNS) { + x = Math.trunc(ns2x(current, startNS, endNS, totalNS, frame)); + } else { + x = 0; + } + let key = `${x}-${dataCache.depth[index]}`; + let preIndex = pre[key]; + if (preIndex !== undefined) { + pre[key] = dataCache.dur[preIndex] > dataCache.dur[index] ? preIndex : index; + } else { + pre[key] = index; + } + } + return pre; + }, data); + Reflect.ownKeys(data).map((kv: string | symbol): void => { + let index = data[kv as string] as number; + dataSource.startTs.push(dataCache.startTs[index]); + dataSource.dur.push(dataCache.dur[index]); + dataSource.depth.push(dataCache.depth[index]); + dataSource.eventCount.push(dataCache.eventCount[index]); + dataSource.symbolId.push(dataCache.symbolId[index]); + dataSource.fileId.push(dataCache.fileId[index]); + dataSource.callchainId.push(dataCache.callchainId[index]); + dataSource.selfDur.push(dataCache.selfDur[index]); + dataSource.name.push(dataCache.name[index]); + }); + return dataSource; +} + +// 将perf_sample表的数据根据callchain_id分组并赋值startTime,endTime等等 +function combinePerfSampleByCallChainId(sampleList: Array, params: any): any[] { + let arr: any = new Array(); + let newPerfData = (sample: any): any => { + let perfSample: any = {}; + perfSample.children = new Array(); + perfSample.children[0] = {}; + perfSample.depth = -1; + perfSample.callchainId = sample.callchainId; + perfSample.threadId = sample.threadId; + perfSample.id = sample.id; + perfSample.startTime = sample.startTs; + perfSample.eventCount = sample.eventCount; + return perfSample; + }; + for (let i = 0; i < sampleList.length; i++) { + if (arr.length > 0) { + let last = arr[arr.length - 1]; + last.endTime = sampleList[i].startTs; + last.totalTime = last.endTime - last.startTime; + if (last.callchainId === sampleList[i].callchainId) { + last.eventCount += sampleList[i].eventCount; + } else { + arr.push(newPerfData(sampleList[i])); + } + } else { + arr.push(newPerfData(sampleList[i])); + } + } + let last = arr[arr.length - 1]; + if (last && (last.endTime === 0 || last.endTime === undefined)) { + last.endTime = params.totalNS; + last.totalTime = last.endTime - last.startTime; + } + return combineChartData(arr, params); +} + +function combineChartData(samples: any, params: any): Array { + let combineSample: any = []; + // 遍历sample表查到的数据,并且为其匹配相应的callchain数据 + for (let sample of samples) { + let stackTop = dataCache.callstack.get(`${sample.callchainId}-0`); + if (stackTop) { + let stackTopSymbol = JSON.parse(JSON.stringify(stackTop)); + stackTopSymbol.startTime = sample.startTime; + stackTopSymbol.endTime = sample.endTime; + stackTopSymbol.totalTime = sample.endTime - sample.startTime; + stackTopSymbol.threadId = sample.threadId; + stackTopSymbol.cpuId = sample.cpuId; + stackTopSymbol.eventCount = sample.eventCount; + setDur(stackTopSymbol); + sample.children = new Array(); + sample.children.push(stackTopSymbol); + // 每一项都和combineSample对比 + if (combineSample.length === 0) { + combineSample.push(sample); + } else { + if (params.type === 0) { + if (combineSample[combineSample.length - 1].threadId === sample.threadId) { + combinePerfCallData(combineSample[combineSample.length - 1], sample); + } else { + combineSample.push(sample); + } + } else { + if (combineSample[combineSample.length - 1].cpuId === sample.cpuId) { + combinePerfCallData(combineSample[combineSample.length - 1], sample); + } else { + combineSample.push(sample); + } + } + } + } + } + return combineSample; +} + +// 递归设置dur,startTime,endTime +function setDur(data: any): void { + if (data.children && data.children.length > 0) { + data.children[0].totalTime = data.totalTime; + data.children[0].startTime = data.startTime; + data.children[0].endTime = data.endTime; + data.children[0].threadId = data.threadId; + data.children[0].cpuId = data.cpuId; + data.children[0].eventCount = data.eventCount; + setDur(data.children[0]); + } else { + return; + } +} + +// hiperf火焰图合并逻辑 +function combinePerfCallData(data1: any, data2: any): void { + if (fixMergeRuler(data1, data2)) { + data1.endTime = data2.endTime; + data1.eventCount += data2.eventCount; + if (data1.children && data1.children.length > 0 && data2.children && data2.children.length > 0) { + if (fixMergeRuler(data1.children[data1.children.length - 1], data2.children[0])) { + combinePerfCallData(data1.children[data1.children.length - 1], data2.children[0]); + } else { + if (data1.children[data1.children.length - 1].depth === data2.children[0].depth) { + data1.children.push(data2.children[0]); + } + } + } else if (data2.children && data2.children.length > 0 && (!data1.children || data1.children.length === 0)) { + data1.endTime = data2.endTime; + data1.totalTime = data1.endTime - data1.endTime; + data1.children = new Array(); + data1.children.push(data2.children[0]); + } else { + } + } + data1.totalTime = data1.endTime - data1.startTime; + return; +} + +/** + * 合并规则 + * @param data1 + * @param data2 + */ +function fixMergeRuler(data1: any, data2: any): boolean { + return data1.depth === data2.depth && data1.name === data2.name; +} + +export const hiPerfCallStackDataCacheSql = (): string => { + return `select c.callchain_id as callchainId, + c.file_id as fileId, + c.depth, + c.symbol_id as symbolId, + c.name + from perf_callchain c + where callchain_id != -1;`; +}; + +export function hiPerfCallChartClearCache(clearStack: boolean): void { + if (clearStack) { + dataCache.callstack.clear(); + dataCache.sampleList.length = 0; + } + dataCache.startTs = []; + dataCache.dur = []; + dataCache.depth = []; + dataCache.eventCount = []; + dataCache.symbolId = []; + dataCache.fileId = []; + dataCache.callchainId = []; + dataCache.selfDur = []; + dataCache.name = []; + dataCache.maxDepth = 1; +} + +function arrayBufferCallStackHandler(data: any, res: any[]): void { + for (const stack of res) { + let item = stack; + if (data.params.trafic === TraficEnum.ProtoBuffer) { + item = { + callchainId: stack.hiperfCallStackData.callchainId || 0, + fileId: stack.hiperfCallStackData.fileId || 0, + depth: stack.hiperfCallStackData.depth || 0, + symbolId: stack.hiperfCallStackData.symbolId || 0, + name: stack.hiperfCallStackData.name || 0, + } + } + dataCache.callstack.set(`${item.callchainId}-${item.depth}`, item); + let parentSymbol = dataCache.callstack.get(`${item.callchainId}-${item.depth - 1}`); + if (parentSymbol && parentSymbol.callchainId === item.callchainId && parentSymbol.depth === item.depth - 1) { + parentSymbol.children = new Array(); + parentSymbol.children.push(item); + } + } + for (let key of Array.from(dataCache.callstack.keys())) { + if (!key.endsWith('-0')) { + dataCache.callstack.delete(key); + } + } + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: 'ok', + len: res.length, + }, + [] + ); +} + +function ns2x(ns: number, startNS: number, endNS: number, duration: number, rect: any): number { + if (endNS === 0) { + endNS = duration; + } + let xSize: number = ((ns - startNS) * rect.width) / (endNS - startNS); + if (xSize < 0) { + xSize = 0; + } else if (xSize > rect.width) { + xSize = rect.width; + } + return xSize; +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfCallChartSender.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfCallChartSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3c867321952fb9a4338d5476b9fd562952992b7 --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfCallChartSender.ts @@ -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. +import { QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { FuncStruct } from '../../ui-worker/ProcedureWorkerFunc'; +import { SpSystemTrace } from '../../../component/SpSystemTrace'; + +export function hiperfCallChartDataSender( + row: TraceRow, + setting: { + startTime: number; + eventTypeId: number; + type: number; + id: number; + } +): Promise { + return new Promise((resolve, reject) => { + threadPool.submitProto( + QueryEnum.HiperfCallChart, + { + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + totalNS: (TraceRow.range?.endNS || 0) - (TraceRow.range?.startNS || 0), + frame: row.frame, + expand: row.funcExpand, + isComplete: row.isComplete, + startTime: setting.startTime, + eventTypeId: setting.eventTypeId, + type: setting.type, + id: setting.id, + }, + (res: any, len: number): void => { + resolve(arrayBufferHandler(res, len)); + } + ); + }); +} + +export function hiperfCallStackCacheSender(): Promise { + return new Promise((resolve, reject) => { + threadPool.submitProto( + QueryEnum.HiperfCallStack, + { + recordStartNS: window.recordStartNS, + trafic: TraficEnum.TransferArrayBuffer, + isCache: true, + }, + (res: any, len: number): void => { + resolve('ok'); + } + ); + }); +} + +export function hiperfCallChartDataCacheSender(): Promise { + return new Promise((resolve, reject) => { + threadPool.submitProto( + QueryEnum.HiperfCallChart, + { + recordStartNS: window.recordStartNS, + trafic: TraficEnum.TransferArrayBuffer, + isCache: true, + }, + (res: any, len: number): void => { + resolve('ok'); + } + ); + }); +} + +function arrayBufferHandler(res: any, len: number) { + let outArr: any[] = []; + let startTs = new Float64Array(res.startTs); + let dur = new Float64Array(res.dur); + let depth = new Int32Array(res.depth); + let eventCount = new Int32Array(res.eventCount); + let symbolId = new Int32Array(res.symbolId); + let fileId = new Int32Array(res.fileId); + let callchainId = new Int32Array(res.callchainId); + let selfDur = new Int32Array(res.selfDur); + let name = new Int32Array(res.name); + for (let i = 0; i < len; i++) { + outArr.push({ + startTime: startTs[i], + totalTime: dur[i], + endTime: startTs[i] + dur[i], + depth: depth[i], + eventCount: eventCount[i], + fileId: fileId[i], + symbolId: symbolId[i], + callchain_id: callchainId[i], + selfDur: selfDur[i], + name: SpSystemTrace.DATA_DICT.get(name[i]), + } as any); + } + return { + maxDepth: res.maxDepth, + dataList: outArr, + }; +} + diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfCpuDataReceiver.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfCpuDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f3c99f04b503d9a3e79708e23a5c8a4d9414648 --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfCpuDataReceiver.ts @@ -0,0 +1,125 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; + +export const chartHiperfCpuData10MSProtoSql = (args: any): string => { + return `select + startNS as startNS, + max(event_count) eventCount, + sample_count as sampleCount, + event_type_id as eventTypeId, + callchain_id as callchainId, + (startNS / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from (select s.callchain_id, + (s.timestamp_trace - ${args.recordStartNS}) / 10000000 * 10000000 startNS, + sum(event_count) event_count, + count(event_count) sample_count, + event_type_id + from perf_sample s + where s.thread_id != 0 ${args.cpu >= 0 ? 'and cpu_id =' + args.cpu : ''} ${ + args.drawType >= 0 ? 'and event_type_id =' + args.drawType : '' + } + group by startNS) + where startNS + 10000000 >= ${Math.floor(args.startNS)} + and startNS <= ${Math.floor(args.endNS)} + group by px;`; +}; +export const chartHiperfCpuDataProtoSql = (args: any): string => { + return `select + (s.timestamp_trace - ${args.recordStartNS}) startNS, + event_count as eventCount, + 1 as sampleCount, + event_type_id as eventTypeId, + s.callchain_id as callchainId, + (s.timestamp_trace - ${args.recordStartNS}) / (${Math.floor( + (args.endNS - args.startNS) / args.width + )}) AS px + from perf_sample s + where s.thread_id != 0 ${args.cpu >= 0 ? 'and cpu_id =' + args.cpu : ''} ${ + args.drawType >= 0 ? 'and event_type_id =' + args.drawType : '' + } + and startNS >= ${Math.floor(args.startNS)} + and startNS <= ${Math.floor(args.endNS)} + group by px; + `; +}; + +export function hiperfCpuDataReceiver(data: any, proc: Function): void { + let sql: string; + if (data.params.scale > 30_000_000) { + sql = chartHiperfCpuData10MSProtoSql(data.params); + } else { + sql = chartHiperfCpuDataProtoSql(data.params); + } + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); +} + +function protoBufferHandler(data: any, res: any[]): void {} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let maxCpuCount = data.params.maxCpuCount; + let intervalPerf = data.params.intervalPerf; + let usage = data.params.drawType === -2; + let startNS = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startNS); + let eventCount = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.eventCount); + let sampleCount = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.sampleCount); + let eventTypeId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.eventTypeId); + let callChainId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.callChainId); + let height = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.height); + let maxEventCount = Math.max( + ...res.map((it) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.hiperfData); + return it.eventCount; + }) + ); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.hiperfData); + startNS[i] = it.startNS || it.startNs; //startNS + eventCount[i] = it.eventCount; //event_count + sampleCount[i] = it.sampleCount; //sample_count + eventTypeId[i] = it.eventTypeId; //event_type_id + callChainId[i] = it.callchainId; //callchain_id + if (usage) { + if (maxCpuCount === -1) { + height[i] = Math.floor((it.sampleCount / (10 / intervalPerf)) * 40); + } else { + height[i] = Math.floor((it.sampleCount / (10 / intervalPerf) / maxCpuCount) * 40); + } + } else { + height[i] = Math.floor((it.eventCount / maxEventCount) * 40); + } + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startNS: startNS.buffer, + eventCount: eventCount.buffer, + sampleCount: sampleCount.buffer, + eventTypeId: eventTypeId.buffer, + callChainId: callChainId.buffer, + height: height.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer + ? [startNS.buffer, eventCount.buffer, sampleCount.buffer, eventTypeId.buffer, callChainId.buffer, height.buffer] + : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfCpuDataSender.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfCpuDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e7c9af1ecc0dcd75262d2ec3f4aecb59629ffff --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfCpuDataSender.ts @@ -0,0 +1,83 @@ +// 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 { TraceRow } from '../../../component/trace/base/TraceRow'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { HiPerfCpuStruct } from '../../ui-worker/hiperf/ProcedureWorkerHiPerfCPU'; + +export function hiperfCpuDataSender( + cpu: number, + drawType: number, + maxCpuCount: number, + intervalPerf: number, + scale: number, + row: TraceRow +): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + startNS: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + eventCount: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + sampleCount: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + eventTypeId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + callChainId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + height: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve, reject) => { + threadPool.submitProto( + QueryEnum.HiperfCpuData, + { + cpu: cpu, + scale: scale, + maxCpuCount: maxCpuCount, + drawType: drawType, + intervalPerf: intervalPerf, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean) => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): HiPerfCpuStruct[] { + let outArr: HiPerfCpuStruct[] = []; + let startNS = new Float64Array(buffers.startNS); + let eventCount = new Int32Array(buffers.eventCount); + let sampleCount = new Int32Array(buffers.sampleCount); + let eventTypeId = new Int32Array(buffers.eventTypeId); + let callChainId = new Int32Array(buffers.callChainId); + let height = new Int32Array(buffers.height); + for (let i = 0; i < len; i++) { + outArr.push({ + startNS: startNS[i], + eventCount: eventCount[i], + sampleCount: sampleCount[i], + event_type_id: eventTypeId[i], + callchain_id: callChainId[i], + height: height[i], + dur: 10_000_000, + } as HiPerfCpuStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfProcessDataReceiver.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfProcessDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5d3bc36fd7a8b90436fb5d81bd3edbe39115aa5 --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfProcessDataReceiver.ts @@ -0,0 +1,125 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; + +export const chartHiperfProcessData10MSProtoSql = (args: any): string => { + return `select startNS as startNS, + max(event_count) eventCount, + sample_count as sampleCount, + event_type_id as eventTypeId, + callchain_id as callchainId, + (startNS / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from (SELECT sp.callchain_id, +-- th.thread_name, +-- th.thread_id tid, +-- th.process_id pid, + (sp.timestamp_trace - ${args.recordStartNS}) / 10000000 * 10000000 startNS, + sum(event_count) event_count, + count(event_count) sample_count, + event_type_id + from perf_sample sp + where sp.thread_id in (select thread_id + from perf_thread + where perf_thread.process_id = ${args.pid}) + and sp.thread_id != 0 ${args.drawType >= 0 ? 'and event_type_id =' + args.drawType : ''} + group by startNS) + where startNS + 10000000 >= ${Math.floor(args.startNS)} + and startNS <= ${Math.floor(args.endNS)} + group by px;`; +}; +export const chartHiperfProcessDataProtoSql = (args: any): string => { + return `SELECT (sp.timestamp_trace - ${args.recordStartNS}) startNS, + event_count as eventCount, + 1 as sampleCount, + event_type_id as eventTypeId, + sp.callchain_id as callchainId, + (sp.timestamp_trace - ${args.recordStartNS}) / (${Math.floor( + (args.endNS - args.startNS) / args.width + )}) AS px + from perf_sample sp + where sp.thread_id in (select thread_id + from perf_thread + where perf_thread.process_id = ${args.pid}) + and sp.thread_id != 0 ${args.drawType >= 0 ? 'and event_type_id =' + args.drawType : ''} + and startNS >= ${Math.floor(args.startNS)} + and startNS <= ${Math.floor(args.endNS)} + group by px;`; +}; + +export function hiperfProcessDataReceiver(data: any, proc: Function): void { + let sql: string; + if (data.params.scale > 30_000_000) { + sql = chartHiperfProcessData10MSProtoSql(data.params); + } else { + sql = chartHiperfProcessDataProtoSql(data.params); + } + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let maxCpuCount = data.params.maxCpuCount; + let intervalPerf = data.params.intervalPerf; + let usage = data.params.drawType === -2; + let startNS = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startNS); + let eventCount = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.eventCount); + let sampleCount = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.sampleCount); + let eventTypeId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.eventTypeId); + let callChainId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.callChainId); + let height = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.height); + let maxEventCount = Math.max( + ...res.map((it) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.hiperfData); + return it.eventCount; + }) + ); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.hiperfData); + startNS[i] = it.startNS || it.startNs; + eventCount[i] = it.eventCount; + sampleCount[i] = it.sampleCount; + eventTypeId[i] = it.eventTypeId; + callChainId[i] = it.callchainId; + if (usage) { + if (maxCpuCount === -1) { + height[i] = Math.floor((it.sampleCount / (10 / intervalPerf)) * 40); + } else { + height[i] = Math.floor((it.sampleCount / (10 / intervalPerf) / maxCpuCount) * 40); + } + } else { + height[i] = Math.floor((it.eventCount / maxEventCount) * 40); + } + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startNS: startNS.buffer, + eventCount: eventCount.buffer, + sampleCount: sampleCount.buffer, + eventTypeId: eventTypeId.buffer, + callChainId: callChainId.buffer, + height: height.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer + ? [startNS.buffer, eventCount.buffer, sampleCount.buffer, eventTypeId.buffer, callChainId.buffer, height.buffer] + : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfProcessDataSender.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfProcessDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..a42fb5c1f83f4c6028ed7555ff26c31f3435f845 --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfProcessDataSender.ts @@ -0,0 +1,83 @@ +// 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 { TraceRow } from '../../../component/trace/base/TraceRow'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { HiPerfCpuStruct } from '../../ui-worker/hiperf/ProcedureWorkerHiPerfCPU'; +import { HiPerfProcessStruct } from '../../ui-worker/hiperf/ProcedureWorkerHiPerfProcess'; + +export function hiperfProcessDataSender( + pid: number, + drawType: number, + intervalPerf: number, + scale: number, + row: TraceRow +): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + startNS: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + eventCount: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + sampleCount: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + eventTypeId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + callChainId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + height: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.HiperfProcessData, + { + pid: pid, + maxCpuCount: -1, + scale: scale, + drawType: drawType, + intervalPerf: intervalPerf, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): HiPerfProcessStruct[] { + let outArr: HiPerfProcessStruct[] = []; + let startNS = new Float64Array(buffers.startNS); + let eventCount = new Int32Array(buffers.eventCount); + let sampleCount = new Int32Array(buffers.sampleCount); + let eventTypeId = new Int32Array(buffers.eventTypeId); + let callChainId = new Int32Array(buffers.callChainId); + let height = new Int32Array(buffers.height); + for (let i = 0; i < len; i++) { + outArr.push({ + startNS: startNS[i], + event_count: eventCount[i], + sampleCount: sampleCount[i], + event_type_id: eventTypeId[i], + callchain_id: callChainId[i], + height: height[i], + dur: 10_000_000, + } as unknown as HiPerfProcessStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfThreadDataReceiver.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfThreadDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..989bcb039f0767435a0e5d77dee6fcb92e17289c --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfThreadDataReceiver.ts @@ -0,0 +1,118 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; + +export const chartHiperfThreadData10MSProtoSql = (args: any): string => { + return `select startNS as startNS, + max(event_count) eventCount, + sample_count as sampleCount, + event_type_id as eventTypeId, + callchain_id as callchainId, + (startNS / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from (SELECT sp.callchain_id, + (sp.timestamp_trace - ${args.recordStartNS}) / 10000000 * 10000000 startNS, + sum(event_count) event_count, + count(event_count) sample_count, + event_type_id + from perf_sample sp + where sp.thread_id = ${args.tid} + and sp.thread_id != 0 ${args.drawType >= 0 ? 'and event_type_id =' + args.drawType : ''} + group by startNS) + where startNS + 10000000 >= ${Math.floor(args.startNS)} + and startNS <= ${Math.floor(args.endNS)} + group by px;`; +}; +export const chartHiperfThreadDataProtoSql = (args: any): string => { + return `SELECT (sp.timestamp_trace - ${args.recordStartNS}) startNS, + event_count as eventCount, + 1 as sampleCount, + event_type_id as eventTypeId, + sp.callchain_id as callchainId, + (sp.timestamp_trace - ${args.recordStartNS}) / (${Math.floor( + (args.endNS - args.startNS) / args.width + )}) AS px + from perf_sample sp + where sp.thread_id = ${args.tid} + and sp.thread_id != 0 ${args.drawType >= 0 ? 'and event_type_id =' + args.drawType : ''} + and startNS >= ${Math.floor(args.startNS)} + and startNS <= ${Math.floor(args.endNS)} + group by px;`; +}; + +export function hiperfThreadDataReceiver(data: any, proc: Function): void { + let sql: string; + if (data.params.scale > 30_000_000) { + sql = chartHiperfThreadData10MSProtoSql(data.params); + } else { + sql = chartHiperfThreadDataProtoSql(data.params); + } + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let maxCpuCount = data.params.maxCpuCount; + let intervalPerf = data.params.intervalPerf; + let usage = data.params.drawType === -2; + let startNS = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startNS); + let eventCount = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.eventCount); + let sampleCount = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.sampleCount); + let eventTypeId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.eventTypeId); + let callChainId = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.callChainId); + let height = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.height); + let maxEventCount = Math.max( + ...res.map((it) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.hiperfData); + return it.eventCount; + }) + ); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.hiperfData); + startNS[i] = it.startNS || it.startNs; + eventCount[i] = it.eventCount; + sampleCount[i] = it.sampleCount; + eventTypeId[i] = it.eventTypeId; + callChainId[i] = it.callchainId; + if (usage) { + if (maxCpuCount === -1) { + height[i] = Math.floor((it.sampleCount / (10 / intervalPerf)) * 40); + } else { + height[i] = Math.floor((it.sampleCount / (10 / intervalPerf) / maxCpuCount) * 40); + } + } else { + height[i] = Math.floor((it.eventCount / maxEventCount) * 40); + } + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startNS: startNS.buffer, + eventCount: eventCount.buffer, + sampleCount: sampleCount.buffer, + eventTypeId: eventTypeId.buffer, + callChainId: callChainId.buffer, + height: height.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer + ? [startNS.buffer, eventCount.buffer, sampleCount.buffer, eventTypeId.buffer, callChainId.buffer, height.buffer] + : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/hiperf/HiperfThreadDataSender.ts b/ide/src/trace/database/data-trafic/hiperf/HiperfThreadDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6d4fd8d409e6af3a672bbec3d540e6551724bc0 --- /dev/null +++ b/ide/src/trace/database/data-trafic/hiperf/HiperfThreadDataSender.ts @@ -0,0 +1,83 @@ +// 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 { TraceRow } from '../../../component/trace/base/TraceRow'; +import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { HiPerfCpuStruct } from '../../ui-worker/hiperf/ProcedureWorkerHiPerfCPU'; +import { HiPerfThreadStruct } from '../../ui-worker/hiperf/ProcedureWorkerHiPerfThread'; + +export function hiperfThreadDataSender( + tid: number, + drawType: number, + intervalPerf: number, + scale: number, + row: TraceRow +): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + startNS: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + eventCount: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + sampleCount: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + eventTypeId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + callChainId: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + height: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.HiperfThreadData, + { + tid: tid, + maxCpuCount: -1, + scale: scale, + drawType: drawType, + intervalPerf: intervalPerf, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): HiPerfThreadStruct[] { + let outArr: HiPerfThreadStruct[] = []; + let startNS = new Float64Array(buffers.startNS); + let eventCount = new Int32Array(buffers.eventCount); + let sampleCount = new Int32Array(buffers.sampleCount); + let eventTypeId = new Int32Array(buffers.eventTypeId); + let callChainId = new Int32Array(buffers.callChainId); + let height = new Int32Array(buffers.height); + for (let i = 0; i < len; i++) { + outArr.push({ + startNS: startNS[i], + event_count: eventCount[i], + sampleCount: sampleCount[i], + event_type_id: eventTypeId[i], + callchain_id: callChainId[i], + height: height[i], + dur: 10_000_000, + } as unknown as HiPerfThreadStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/FuncDataReceiver.ts b/ide/src/trace/database/data-trafic/process/FuncDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cd2ce12f6a2bcc9c9d8ec8d37f2b6db8de1557e --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/FuncDataReceiver.ts @@ -0,0 +1,124 @@ +// 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 { threadCallStackList } from "../utils/AllMemoryCache"; +import { filterDataByGroupLayer } from "../utils/DataFilter"; +import { TraficEnum } from "../utils/QueryEnum"; + + +export const chartFuncDataSql = (args: any):string => { + return ` + select + startTs, + dur, + ifnull(argsetid, -1) as argsetid, + depth, + id, + max(dur2) as dur2, + (startTs) / (${Math.floor((args.endNS - args.startNS) / args.width)}) + (depth * ${ args.width }) AS px + from ( + select c.ts - ${args.recordStartNS} as startTs, + c.dur as dur, + case when (c.dur=-1 ) then ${args.recordEndNS} else c.dur end as dur2, + c.argsetid, + c.depth, + c.id as id + --c.name as funName, + from callstack C + where startTs not null + and c.cookie is null + and c.callid in (select id from thread where tid=${args.tid} + and ipid=${args.ipid}) + and startTs + dur2 >= ${Math.floor(args.startNS)} + and startTs <= ${Math.floor(args.endNS)} + ) + group by px; +`; +}; + +export const chartFuncDataSqlMem = (args:any):string =>{ + return `select c.ts - ${args.recordStartNS} as startTs, + c.dur as dur, + ifnull(c.argsetid, -1) as argsetid, + c.depth, + c.id as id + --c.name as funName, + from callstack C + where startTs not null + and c.cookie is null + and c.callid in (select id from thread where tid=${args.tid} + and ipid=${args.ipid})`; +} +export function funcDataReceiver(data: any, proc: Function):void { + if (data.params.trafic === TraficEnum.Memory) { + let key = `${data.params.tid}${data.params.ipid}` + if (!threadCallStackList.has(key)) { + let list = proc(chartFuncDataSqlMem(data.params)); + for (let i = 0; i < list.length; i++) { + if (list[i].dur == -1) { + list[i].nofinish = 1; + list[i].dur = data.params.endNS - list[i].startTs; + } else { + list[i].nofinish = 0; + } + } + threadCallStackList.set(key, list); + } + let array = threadCallStackList.get(key) || []; + let res = filterDataByGroupLayer( + array, + 'depth', + 'startTs', + 'dur', data.params.startNS, data.params.endNS, data.params.width); + arrayBufferHandler(data, res, true,array.length===0); + } else { + let sql = chartFuncDataSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer,false); + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean,isEmpty:boolean): void { + let startTs = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTs); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let argsetid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.argsetid); + let depth = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.depth); + let id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processFuncData); + startTs[i] = it.startTs; + dur[i] = it.dur; + argsetid[i] = it.argsetid; + depth[i] = it.depth; + id[i] = it.id; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startTs: startTs.buffer, + dur: dur.buffer, + argsetid: argsetid.buffer, + depth: depth.buffer, + id: id.buffer, + } + : {}, + len: res.length, + transfer: transfer, + isEmpty:isEmpty, + }, + transfer ? [startTs.buffer, dur.buffer, argsetid.buffer, depth.buffer, id.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/FuncDataSender.ts b/ide/src/trace/database/data-trafic/process/FuncDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..63a474cd5a16d6c19bff3dd4f400232059e9cb9b --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/FuncDataSender.ts @@ -0,0 +1,73 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { FuncStruct } from '../../ui-worker/ProcedureWorkerFunc'; + +export function funcDataSender(tid: number, ipid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + startTs: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + argsetid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + depth: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve, reject): void => { + threadPool.submitProto( + QueryEnum.FuncData, + { + tid: tid, + ipid: ipid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean,isEmpty:boolean) => { + if (isEmpty) { + resolve(true); + }else { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): FuncStruct[] { + let outArr: FuncStruct[] = []; + let startTs = new Float64Array(buffers.startTs); + let dur = new Float64Array(buffers.dur); + let argsetid = new Int32Array(buffers.argsetid); + let depth = new Int32Array(buffers.depth); + let id = new Int32Array(buffers.id); + for (let i = 0; i < len; i++) { + outArr.push({ + startTs: startTs[i], + dur: dur[i], + argsetid: argsetid[i], + depth: depth[i], + id: id[i], + } as FuncStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessActualDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessActualDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..946d19b613e8ccbcda419359983c940c256f98d7 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessActualDataReceiver.ts @@ -0,0 +1,125 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import { processFrameList } from '../utils/AllMemoryCache'; + +export const chartProcessActualDataSql = (args: any): string => { + return ` + SELECT + (a.ts - ${args.recordStartNS}) AS ts, + a.dur, + ${args.pid} as pid, + a.id, + a.vsync AS name, + a.type, + a.flag AS jankTag, + a.dst AS dstSlice, + a.depth + FROM frame_slice AS a + WHERE a.type = 0 + AND a.flag <> 2 + AND a.ipid in (select p.ipid from process AS p where p.pid = ${args.pid}) + ORDER BY a.ipid;`; +}; + +export const chartProcessActualProtoDataSql = (args: any): string => { + return ` + SELECT + (a.ts - ${args.recordStartNS}) AS ts, + a.dur, + ${args.pid} as pid, + a.id, + a.vsync AS name, + a.type, + a.flag AS jankTag, + a.dst AS dstSlice, + a.depth, + (a.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)}) + (a.depth * ${ args.width }) AS px + FROM frame_slice AS a + WHERE a.type = 0 + AND a.flag <> 2 + AND a.ipid in (select p.ipid from process AS p where p.pid = ${args.pid}) + AND (a.ts - ${args.recordStartNS}) + dur >= ${Math.floor(args.startNS)} + + AND (a.ts - ${args.recordStartNS}) <= ${Math.floor(args.endNS)} + group by px + ORDER BY a.ipid;`; +}; + + +export function processActualDataReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + if (!processFrameList.has(`${data.params.pid}_actual`)) { + let sql = chartProcessActualDataSql(data.params); + processFrameList.set(`${data.params.pid}_actual`, proc(sql)); + } + arrayBufferHandler(data, processFrameList.get(`${data.params.pid}_actual`)!, true); + } else { + let sql = chartProcessActualProtoDataSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let ts = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.ts); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let pid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.pid); + let id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); + let name = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.name); + let type = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.type); + let jank_tag = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.jank_tag); + let dst_slice = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.dst_slice); + let depth = new Uint16Array(transfer ? res.length : data.params.sharedArrayBuffers.depth); + for (let index = 0; index < res.length; index++) { + let itemData = res[index]; + data.params.trafic === TraficEnum.ProtoBuffer && (itemData = itemData.processJanksActualData); + if (!itemData.dur || itemData.dur < 0) { + continue; + } + dur[index] = itemData.dur; + ts[index] = itemData.ts; + pid[index] = itemData.pid; + id[index] = itemData.id; + name[index] = itemData.name; + type[index] = itemData.type; + jank_tag[index] = itemData.jankTag; + dst_slice[index] = itemData.dstSlice; + depth[index] = itemData.depth; + } + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + dur: dur.buffer, + ts: ts.buffer, + pid: pid.buffer, + id: id.buffer, + name: name.buffer, + type: type.buffer, + jank_tag: jank_tag.buffer, + dst_slice: dst_slice.buffer, + depth: depth.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer + ? [dur.buffer, ts.buffer, pid.buffer, type.buffer, id.buffer, name.buffer, jank_tag.buffer, dst_slice.buffer, depth.buffer] + : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessActualDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessActualDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..13888197af73ef533d29cee66e9ee435d9820180 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessActualDataSender.ts @@ -0,0 +1,81 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { JankStruct } from '../../ui-worker/ProcedureWorkerJank'; + +export function processActualDataSender(pid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + name: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + pid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + type: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + ts: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + jank_tag: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + dst_slice: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + depth: new SharedArrayBuffer(Uint16Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve, reject) => { + threadPool.submitProto( + QueryEnum.processActualData, + { + pid: pid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): JankStruct[] { + let outArr: JankStruct[] = []; + let name = new Int32Array(buffers.name); + let pid = new Int32Array(buffers.pid); + let type = new Int32Array(buffers.type); + let id = new Int32Array(buffers.id); + let ts = new Float64Array(buffers.ts); + let dur = new Float64Array(buffers.dur); + let jank_tag = new Int32Array(buffers.jank_tag); + let dst_slice = new Int32Array(buffers.dst_slice); + let depth = new Uint16Array(buffers.depth); + for (let i = 0; i < len; i++) { + outArr.push({ + name: name[i], + pid: pid[i], + type: type[i], + id: id[i], + ts: ts[i], + dur: dur[i], + jank_tag: jank_tag[i], + dst_slice: dst_slice[i], + depth: depth[i], + } as unknown as JankStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c33b5c95e7edf8000d88e3817ebbb4fac9c61f0 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessDataReceiver.ts @@ -0,0 +1,94 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import { filterDataByGroupLayer, filterDataByLayer } from '../utils/DataFilter'; +import {processList} from "../utils/AllMemoryCache"; + +const sqlNormal = (args: any): string => { + return `select ta.cpu, + max(dur) as dur, + ts - ${ + args.recordStartNS + } as startTime, + ((ts - ${args.recordStartNS}) / (${Math.floor( + (args.endNS - args.startNS) / args.width + )})) + (ta.cpu * ${args.width}) AS px + from thread_state ta + where ta.cpu is not null + and pid = ${args.pid} + and startTime + dur >= ${Math.floor(args.startNS)} + and startTime <= ${Math.floor(args.endNS)} + group by px;`; +}; + +const sqlMem = (args: any): string => { + return `select ta.cpu, + dur as dur, + ts - ${args.recordStartNS} as startTime + from thread_state ta + where ta.cpu is not null + and pid = ${args.pid};`; +}; + +export function processDataReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + if (!processList.has(data.params.pid)) { + processList.set(data.params.pid, proc(sqlMem(data.params))); + } + let res = filterDataByLayer( + processList.get(data.params.pid) || [], + 'cpu', + 'startTime', + 'dur', + data.params.startNS, + data.params.endNS, + data.params.width + ); + arrayBufferHandler(data, res, true); + return; + } else { + let transfer = data.params.trafic !== TraficEnum.SharedArrayBuffer; + let sql = sqlNormal(data.params); + let res: any[] = proc(sql); + arrayBufferHandler(data, res, transfer); + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let startTime = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTime); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let cpu = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.cpu); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processData); + startTime[i] = it.startTime; + dur[i] = it.dur; + cpu[i] = it.cpu; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startTime: startTime.buffer, + dur: dur.buffer, + cpu: cpu.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [startTime.buffer, dur.buffer, cpu.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..2271fac17d2c1965fd23e1e40985f40da99c3353 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessDataSender.ts @@ -0,0 +1,64 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { ProcessStruct } from '../../ui-worker/ProcedureWorkerProcess'; + +export function processDataSender(pid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + cpu: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT), + value: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.ProcessData, + { + pid: pid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + t: new Date().getTime(), + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): ProcessStruct[] { + let outArr: ProcessStruct[] = []; + let cpu = new Uint8Array(buffers.cpu); + let startTime = new Float64Array(buffers.startTime); + let dur = new Float64Array(buffers.dur); + for (let i = 0; i < len; i++) { + outArr.push({ + cpu: cpu[i], + dur: dur[i], + startTime: startTime[i], + } as ProcessStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessDeliverInputEventDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessDeliverInputEventDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..13f10c9f0d09f765518680afe6eac3785896a3c9 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessDeliverInputEventDataReceiver.ts @@ -0,0 +1,124 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; + +export const chartProcessDeliverInputEventDataSql = (args: any): string => { + return ` + select + c.ts-${args.recordStartNS} as startTs, + c.dur, + c.argsetid, + tid, + P.pid, + is_main_thread as isMainThread, + c.callid as trackId, + c.parent_id as parentId, + c.id, + c.cookie, + c.depth, + ((c.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px, + c.name as funName, + A.name as threadName + from thread A + left join callstack C on A.id = C.callid + left join process P on P.id = A.ipid + where startTs not null and cookie not null + and c.name ='deliverInputEvent' + and tid = ${args.tid} + and startTs + dur >= ${Math.floor(args.startNS)} + and startTs <= ${Math.floor(args.endNS)} + group by px; + `; +}; + +export function processDeliverInputEventDataReceiver(data: any, proc: Function): void { + let sql = chartProcessDeliverInputEventDataSql(data.params); + let res = proc(sql); + switch (data.params.trafic) { + case TraficEnum.SharedArrayBuffer: + arrayBufferHandler(data, res, false); + break; + case TraficEnum.ProtoBuffer: + arrayBufferHandler(data, res, true); + break; + case TraficEnum.TransferArrayBuffer: + arrayBufferHandler(data, res, true); + break; + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let tid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.tid); + let pid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.pid); + let is_main_thread = new Int8Array(transfer ? res.length : data.params.sharedArrayBuffers.is_main_thread); + let track_id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.track_id); + let startTs = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTs); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let parent_id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.parent_id); + let id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); + let cookie = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.cookie); + let depth = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.depth); + let argsetid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.argsetid); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processInputEventData); + tid[i] = it.tid; + dur[i] = it.dur; + is_main_thread[i] = it.isMainThread; + track_id[i] = it.trackId; + startTs[i] = it.startTs; + pid[i] = it.pid; + parent_id[i] = it.parentId; + id[i] = it.id; + cookie[i] = it.cookie; + depth[i] = it.depth; + argsetid[i] = it.argsetid; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + tid: tid.buffer, + dur: dur.buffer, + is_main_thread: is_main_thread.buffer, + track_id: track_id.buffer, + startTs: startTs.buffer, + pid: pid.buffer, + parent_id: parent_id.buffer, + id: id.buffer, + cookie: cookie.buffer, + depth: depth.buffer, + argsetid: argsetid.buffer, + } + : {}, + len: res.length, + }, + transfer + ? [ + tid.buffer, + dur.buffer, + is_main_thread.buffer, + track_id.buffer, + startTs.buffer, + pid.buffer, + parent_id.buffer, + id.buffer, + cookie.buffer, + depth.buffer, + argsetid.buffer, + ] + : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessDeliverInputEventDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessDeliverInputEventDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..279d4e0efa2c9dc861d458755c2512be05187330 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessDeliverInputEventDataSender.ts @@ -0,0 +1,97 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { FuncStruct } from '../../ui-worker/ProcedureWorkerFunc'; + +export function processDeliverInputEventDataSender(tid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + tid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + pid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + is_main_thread: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + track_id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + startTs: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + parent_id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + cookie: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + depth: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + argsetid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve) => { + threadPool.submitProto( + QueryEnum.processDeliverInputEventData, + { + tid: tid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number) => { + switch (trafic) { + case TraficEnum.SharedArrayBuffer: + resolve(arrayBufferHandler(row.sharedArrayBuffers, len)); + break; + case TraficEnum.ProtoBuffer: + resolve(arrayBufferHandler(res, len)); + break; + case TraficEnum.TransferArrayBuffer: + resolve(arrayBufferHandler(res, len)); + break; + } + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): FuncStruct[] { + let outArr: FuncStruct[] = []; + let tid = new Int32Array(buffers.tid); + let pid = new Int32Array(buffers.pid); + let is_main_thread = new Int8Array(buffers.is_main_thread); + let track_id = new Int32Array(buffers.track_id); + let startTs = new Float64Array(buffers.startTs); + let dur = new Float64Array(buffers.dur); + let parent_id = new Int32Array(buffers.tid); + let id = new Int32Array(buffers.id); + let cookie = new Int32Array(buffers.cookie); + let depth = new Int32Array(buffers.depth); + let argsetid = new Int32Array(buffers.argsetid); + for (let i = 0; i < len; i++) { + outArr.push({ + tid: tid[i], + pid: pid[i], + is_main_thread: is_main_thread[i], + track_id: track_id[i], + startTs: startTs[i], + dur: dur[i], + parent_id: parent_id[i], + id: id[i], + cookie: cookie[i], + depth: depth[i], + argsetid: argsetid[i], + } as unknown as FuncStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessExpectedDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessExpectedDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..8295cd86bed40a53da72c67f3198027bce1a3a09 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessExpectedDataReceiver.ts @@ -0,0 +1,109 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import { processFrameList } from '../utils/AllMemoryCache'; +import { filterDataByGroup } from '../utils/DataFilter'; + +export const chartProcessExpectedDataSql = (args: any): string => { + return ` + SELECT + (a.ts - ${args.recordStartNS}) AS ts, + a.dur, + ${args.pid} as pid, + a.id, + a.vsync as name, + a.type, + a.depth + FROM frame_slice AS a + WHERE a.type = 1 + and (a.flag <> 2 or a.flag is null) + and a.ipid in (select p.ipid from process AS p where p.pid = ${args.pid}) + ORDER BY a.ipid`; +}; + +export const chartProcessExpectedProtoDataSql = (args: any): string => { + return ` + SELECT + (a.ts - ${args.recordStartNS}) AS ts, + a.dur, + ${args.pid} as pid, + a.id, + a.vsync as name, + a.type, + a.depth, + (a.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)}) + (a.depth * ${ args.width }) AS px + FROM frame_slice AS a + WHERE a.type = 1 + and (a.flag <> 2 or a.flag is null) + and a.ipid in (select p.ipid from process AS p where p.pid = ${args.pid}) + and (a.ts - ${args.recordStartNS} + a.dur) >= ${Math.floor(args.startNS)} + and (a.ts - ${args.recordStartNS}) <= ${Math.floor(args.endNS)} + group by px + ORDER BY a.ipid;`; +}; + +export function processExpectedDataReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + if (!processFrameList.has(`${data.params.pid}_expected`)) { + let sql = chartProcessExpectedDataSql(data.params); + processFrameList.set(`${data.params.pid}_expected`, proc(sql)); + } + arrayBufferHandler(data, processFrameList.get(`${data.params.pid}_expected`)!, true); + } else { + let sql = chartProcessExpectedProtoDataSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let ts = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.ts); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let pid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.pid); + let id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); + let name = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.name); + let type = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.type); + let depth = new Uint16Array(transfer ? res.length : data.params.sharedArrayBuffers.depth); + for (let index = 0; index < res.length; index++) { + let itemData = res[index]; + data.params.trafic === TraficEnum.ProtoBuffer && (itemData = itemData.processJanksFramesData); + dur[index] = itemData.dur; + ts[index] = itemData.ts; + pid[index] = itemData.pid; + id[index] = itemData.id; + name[index] = itemData.name; + type[index] = itemData.type; + depth[index] = itemData.depth; + } + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + dur: dur.buffer, + ts: ts.buffer, + pid: pid.buffer, + id: id.buffer, + name: name.buffer, + type: name.buffer, + depth: depth.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [dur.buffer, ts.buffer, pid.buffer, type.buffer, id.buffer, name.buffer, depth.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessExpectedDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessExpectedDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2b2bf818b93bd20fb978da6e933ab15a310f630 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessExpectedDataSender.ts @@ -0,0 +1,75 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { JankStruct } from '../../ui-worker/ProcedureWorkerJank'; + +export function processExpectedDataSender(pid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + name: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + pid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + type: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + ts: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + depth: new SharedArrayBuffer(Uint16Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve, reject) => { + threadPool.submitProto( + QueryEnum.processExpectedData, + { + pid: pid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): JankStruct[] { + let outArr: JankStruct[] = []; + let name = new Int32Array(buffers.name); + let pid = new Int32Array(buffers.pid); + let type = new Int32Array(buffers.type); + let id = new Int32Array(buffers.id); + let ts = new Float64Array(buffers.ts); + let dur = new Float64Array(buffers.dur); + let depth = new Uint16Array(buffers.depth); + for (let i = 0; i < len; i++) { + outArr.push({ + name: name[i], + pid: pid[i], + type: type[i], + id: id[i], + ts: ts[i], + dur: dur[i], + depth: depth[i], + } as unknown as JankStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessMemDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessMemDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..600cc23a18a728afbeb2262aa40e5cbfe516ee14 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessMemDataReceiver.ts @@ -0,0 +1,71 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; +import { filterData } from '../utils/DataFilter'; +import {memList} from "../utils/AllMemoryCache"; + +export const chartProcessMemDataSql = (args: any): string => { + return ` + select + filter_id as trackId, + value, + c.ts - ${args.recordStartNS} as startTime, + ts + from process_measure c, + trace_range tb + where filter_id = ${args.trackId};`; +}; + +export function processMemDataReceiver(data: any, proc: Function): void { + let res: any[], list: any[]; + if (!memList.has(data.params.trackId)) { + list = proc(chartProcessMemDataSql(data.params)); + memList.set(data.params.trackId, list); + } else { + list = memList.get(data.params.trackId) || []; + } + res = list; + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer); +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let startTime = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTime); + let ts = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.ts); + let value = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.value); + let track_id = new Uint8Array(transfer ? res.length : data.params.sharedArrayBuffers.track_id); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processMemData); + ts[i] = it.ts; + startTime[i] = it.startTime; + track_id[i] = it.trackId; + value[i] = it.value; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + ts: ts.buffer, + startTime: startTime.buffer, + value: value.buffer, + track_id: track_id.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [ts.buffer, startTime.buffer, value.buffer, track_id.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessMemDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessMemDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..847efa5cdcea62cbad28140da0c40c44f312dee8 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessMemDataSender.ts @@ -0,0 +1,66 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { ProcessMemStruct } from '../../ui-worker/ProcedureWorkerMem'; + +export function processMemDataSender(trackId: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + track_id: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT), + value: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + ts: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.ProcessMemData, + { + trackId: trackId, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean): void => { + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): ProcessMemStruct[] { + let outArr: ProcessMemStruct[] = []; + let track_id = new Uint8Array(buffers.track_id); + let value = new Int32Array(buffers.value); + let startTime = new Float64Array(buffers.startTime); + let ts = new Float64Array(buffers.ts); + for (let i = 0; i < len; i++) { + outArr.push({ + track_id: track_id[i], + value: value[i], + startTime: startTime[i], + ts: ts[i], + } as unknown as ProcessMemStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessSoInitDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessSoInitDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..a7b118529c85380ee7b0a0e97e1b3b8041231b0a --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessSoInitDataReceiver.ts @@ -0,0 +1,86 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; + +export const chartProcessSoInitDataSql = (args: any): string => { + return ` + select + A.depth, + P.pid, + T.tid, + A.call_id as itid, + (A.start_time - B.start_ts) as startTime, + (A.end_time - A.start_time) as dur, + A.id, + A.so_name as soName +from static_initalize A,trace_range B +left join process P on A.ipid = P.ipid +left join thread T on A.call_id = T.itid +where P.pid = ${args.pid};`; +}; + +export function processSoInitDataReceiver(data: any, proc: Function): void { + let sql = chartProcessSoInitDataSql(data.params); + let res = proc(sql); + switch (data.params.trafic) { + case TraficEnum.SharedArrayBuffer: + arrayBufferHandler(data, res, false); + break; + case TraficEnum.ProtoBuffer: + arrayBufferHandler(data, res, true); + break; + case TraficEnum.TransferArrayBuffer: + arrayBufferHandler(data, res, true); + break; + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let startTs = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTs); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let pid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.pid); + let tid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.tid); + let itid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.itid); + let depth = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.depth); + let id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processSoInitData); + dur[i] = it.dur || 0; + startTs[i] = it.startTime || 0; + pid[i] = it.pid || 0; + tid[i] = it.tid || 0; + itid[i] = it.itid || 0; + depth[i] = it.depth || 0; + id[i] = it.id || 0; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + dur: dur.buffer, + startTs: startTs.buffer, + pid: pid.buffer, + tid: tid.buffer, + itid: itid.buffer, + depth: depth.buffer, + id: id.buffer, + } + : {}, + len: res.length, + }, + transfer ? [dur.buffer, startTs.buffer, pid.buffer, tid.buffer, itid.buffer, depth.buffer, id.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessSoInitDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessSoInitDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..58a40d3a555a36675e177a81d3a04301fc3c44e5 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessSoInitDataSender.ts @@ -0,0 +1,85 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { SoStruct } from '../../ui-worker/ProcedureWorkerSoInit'; + +export function processSoInitDataSender(pid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + depth: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + pid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + tid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + itid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + startTs: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.ProcessSoInitData, + { + pid: pid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number): void => { + switch (trafic) { + case TraficEnum.SharedArrayBuffer: + resolve(arrayBufferHandler(row.sharedArrayBuffers, len)); + break; + case TraficEnum.ProtoBuffer: + resolve(arrayBufferHandler(res, len)); + break; + case TraficEnum.TransferArrayBuffer: + resolve(arrayBufferHandler(res, len)); + break; + } + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): SoStruct[] { + let outArr: SoStruct[] = []; + let id = new Int32Array(buffers.id); + let depth = new Int32Array(buffers.depth); + let pid = new Int32Array(buffers.pid); + let tid = new Int32Array(buffers.tid); + let itid = new Int32Array(buffers.itid); + let startTs = new Float64Array(buffers.startTs); + let dur = new Float64Array(buffers.dur); + for (let i = 0; i < len; i++) { + outArr.push({ + id: id[i], + depth: depth[i], + pid: pid[i], + tid: tid[i], + itid: itid[i], + startTs: startTs[i], + dur: dur[i], + } as unknown as SoStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessStartupDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ProcessStartupDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae9de6e9bb0b6db146e13f8deb84c975d187a762 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessStartupDataReceiver.ts @@ -0,0 +1,84 @@ +// 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 { TraficEnum } from '../utils/QueryEnum'; + +export const chartProcessStartupDataSql = (args: any): string => { + return ` + select P.pid, + A.tid, + A.call_id as itid, + (case when A.start_time < ${args.recordStartNS} then 0 else (A.start_time - ${args.recordStartNS}) end) as startTime, + (case + when A.start_time < ${args.recordStartNS} then (A.end_time - ${args.recordStartNS}) + when A.end_time = -1 then 0 + else (A.end_time - A.start_time) end) as dur, + A.start_name as startName + from app_startup A + left join process P on A.ipid = P.ipid + where P.pid = ${args.pid} + order by start_name;`; +}; + +export function processStartupDataReceiver(data: any, proc: Function): void { + let sql = chartProcessStartupDataSql(data.params); + let res = proc(sql); + switch (data.params.trafic) { + case TraficEnum.SharedArrayBuffer: + arrayBufferHandler(data, res, false); + break; + case TraficEnum.ProtoBuffer: + arrayBufferHandler(data, res, true); + break; + case TraficEnum.TransferArrayBuffer: + arrayBufferHandler(data, res, true); + break; + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean): void { + let startTs = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTime); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let pid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.pid); + let tid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.tid); + let itid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.itid); + let startName = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.startName); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processStartupData); + dur[i] = it.dur || 0; + startTs[i] = it.startTime || 0; + pid[i] = it.pid || 0; + tid[i] = it.tid || 0; + itid[i] = it.itid || 0; + startName[i] = it.startName || 0; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + dur: dur.buffer, + startTs: startTs.buffer, + pid: pid.buffer, + tid: tid.buffer, + itid: itid.buffer, + startName: startName.buffer, + } + : {}, + len: res.length, + transfer: transfer, + }, + transfer ? [dur.buffer, startTs.buffer, pid.buffer, tid.buffer, itid.buffer] : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ProcessStartupDataSender.ts b/ide/src/trace/database/data-trafic/process/ProcessStartupDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..f23788e3bce00ad21cb619d693294d3bec228b42 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ProcessStartupDataSender.ts @@ -0,0 +1,86 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { AppStartupStruct } from '../../ui-worker/ProcedureWorkerAppStartup'; + +export function processStartupDataSender(pid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.ProtoBuffer; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + startName: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + pid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + tid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + itid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + startTs: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve) => { + threadPool.submitProto( + QueryEnum.ProcessStartupData, + { + pid: pid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + t: Date.now(), + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number) => { + switch (trafic) { + case TraficEnum.SharedArrayBuffer: + resolve(arrayBufferHandler(row.sharedArrayBuffers, len)); + break; + case TraficEnum.ProtoBuffer: + resolve(arrayBufferHandler(res, len)); + break; + case TraficEnum.TransferArrayBuffer: + resolve(arrayBufferHandler(res, len)); + break; + } + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): AppStartupStruct[] { + let outArr: AppStartupStruct[] = []; + let startName = new Int32Array(buffers.startName); + let pid = new Int32Array(buffers.pid); + let tid = new Int32Array(buffers.tid); + let itid = new Int32Array(buffers.itid); + let startTs = new Float64Array(buffers.startTs); + let dur = new Float64Array(buffers.dur); + for (let i = 0; i < len; i++) { + outArr.push({ + startName: startName[i], + pid: pid[i], + tid: tid[i], + itid: itid[i], + startTs: startTs[i], + dur: dur[i], + } as unknown as AppStartupStruct); + } + return outArr; +} + +function protoBufferHandler(res: ArrayBuffer, len: number): AppStartupStruct[] { + return []; +} diff --git a/ide/src/trace/database/data-trafic/process/ThreadDataReceiver.ts b/ide/src/trace/database/data-trafic/process/ThreadDataReceiver.ts new file mode 100644 index 0000000000000000000000000000000000000000..84906a29fe4ea3cb8fc5c77e9ee4230224e1551a --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ThreadDataReceiver.ts @@ -0,0 +1,133 @@ +// 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 { threadStateList } from "../utils/AllMemoryCache"; +import { filterDataByGroup } from "../utils/DataFilter"; +import { TraficEnum, threadStateToNumber } from "../utils/QueryEnum"; + +export const chartThreadDataSql = (args: any) => { + return `select B.cpu + , max(B.dur) AS dur + , B.itid AS id + , B.tid AS tid + , B.state + , B.pid + , B.ts - ${args.recordStartNS} AS startTime + , ifnull(B.arg_setid, -1) AS argSetId + , ((B.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from thread_state AS B + where B.tid = ${args.tid} + and B.pid = ${args.pid} + and B.state != 'Running' + and startTime + dur >= ${Math.floor(args.startNS)} + and startTime <= ${Math.floor(args.endNS)} + group by px + union all + select B.cpu + , max(B.dur) AS dur + , B.itid AS id + , B.tid AS tid + , B.state + , B.pid + , B.ts - ${args.recordStartNS} AS startTime + , ifnull(B.arg_setid, -1) AS argSetId + , ((B.ts - ${args.recordStartNS}) / (${Math.floor((args.endNS - args.startNS) / args.width)})) AS px + from thread_state AS B + where B.tid = ${args.tid} + and B.pid = ${args.pid} + and B.state = 'Running' + and startTime + dur >= ${Math.floor(args.startNS)} + and startTime <= ${Math.floor(args.endNS)} + group by px; + ;`; +}; + +export const sqlMem = (args: any): string => { + return `select B.cpu + , B.dur AS dur + , B.itid AS id + , B.tid AS tid + , B.state + , B.pid + , B.ts - ${args.recordStartNS} AS startTime + , ifnull(B.arg_setid, -1) AS argSetId + from thread_state AS B + where B.tid = ${args.tid} + and B.pid = ${args.pid};`; +} + +export function threadDataReceiver(data: any, proc: Function): void { + if (data.params.trafic === TraficEnum.Memory) { + let key = `${data.params.pid}${data.params.tid}`; + if (!threadStateList.has(key)) { + threadStateList.set(key, proc(sqlMem(data.params))); + } + let array = threadStateList.get(key) || []; + let res = filterDataByGroup( + array, + 'startTime', + 'dur', data.params.startNS, data.params.endNS, data.params.width, undefined,(a) => a.state === 'Running'); + arrayBufferHandler(data, res, true,array.length === 0); + return; + } else { + let sql = chartThreadDataSql(data.params); + let res = proc(sql); + arrayBufferHandler(data, res, data.params.trafic !== TraficEnum.SharedArrayBuffer,false); + } +} + +function arrayBufferHandler(data: any, res: any[], transfer: boolean,isEmpty:boolean): void { + let startTime = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.startTime); + let dur = new Float64Array(transfer ? res.length : data.params.sharedArrayBuffers.dur); + let cpu = new Int8Array(transfer ? res.length : data.params.sharedArrayBuffers.cpu); + let id = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.id); + let tid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.tid); + let state = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.state); + let pid = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.pid); + let argSetID = new Int32Array(transfer ? res.length : data.params.sharedArrayBuffers.argSetID); + res.forEach((it, i) => { + data.params.trafic === TraficEnum.ProtoBuffer && (it = it.processThreadData); + startTime[i] = it.startTime; + dur[i] = it.dur; + cpu[i] = it.cpu; + id[i] = it.id; + tid[i] = it.tid; + state[i] = threadStateToNumber(it.state); + pid[i] = it.pid; + argSetID[i] = it.argSetId; + }); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: transfer + ? { + startTime: startTime.buffer, + dur: dur.buffer, + cpu: cpu.buffer, + id: id.buffer, + tid: tid.buffer, + state: state.buffer, + pid: pid.buffer, + argSetID: argSetID.buffer, + } + : {}, + len: res.length, + transfer: transfer, + isEmpty:isEmpty, + }, + transfer + ? [startTime.buffer, dur.buffer, cpu.buffer, id.buffer, tid.buffer, state.buffer, pid.buffer, argSetID.buffer] + : [] + ); +} diff --git a/ide/src/trace/database/data-trafic/process/ThreadDataSender.ts b/ide/src/trace/database/data-trafic/process/ThreadDataSender.ts new file mode 100644 index 0000000000000000000000000000000000000000..92a4cf0fd428484927965cab39e1c4a69b813233 --- /dev/null +++ b/ide/src/trace/database/data-trafic/process/ThreadDataSender.ts @@ -0,0 +1,82 @@ +// 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 { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, threadStateToString, TraficEnum } from '../utils/QueryEnum'; +import { threadPool } from '../../SqlLite'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { ThreadStruct } from '../../ui-worker/ProcedureWorkerThread'; + +export function threadDataSender(tid: number, pid: number, row: TraceRow): Promise { + let trafic: number = TraficEnum.Memory; + let width = row.clientWidth - CHART_OFFSET_LEFT; + if ((trafic === TraficEnum.SharedArrayBuffer) && !row.sharedArrayBuffers) { + row.sharedArrayBuffers = { + startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT), + cpu: new SharedArrayBuffer(Int8Array.BYTES_PER_ELEMENT * MAX_COUNT), + id: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + tid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + state: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + pid: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + argSetID: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT), + }; + } + return new Promise((resolve): void => { + threadPool.submitProto( + QueryEnum.ThreadData, + { + pid: pid, + tid: tid, + startNS: TraceRow.range?.startNS || 0, + endNS: TraceRow.range?.endNS || 0, + recordStartNS: window.recordStartNS, + recordEndNS: window.recordEndNS, + width: width, + trafic: trafic, + sharedArrayBuffers: row.sharedArrayBuffers, + }, + (res: any, len: number, transfer: boolean,isEmpty:boolean): void => { + if (isEmpty) { + resolve(true); + }else{ + resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len)); + } + } + ); + }); +} + +function arrayBufferHandler(buffers: any, len: number): ThreadStruct[] { + let outArr: ThreadStruct[] = []; + let startTime = new Float64Array(buffers.startTime); + let dur = new Float64Array(buffers.dur); + let cpu = new Int8Array(buffers.cpu); + let id = new Int32Array(buffers.id); + let tid = new Int32Array(buffers.tid); + let state = new Int32Array(buffers.state); + let pid = new Int32Array(buffers.pid); + let argSetID = new Int32Array(buffers.argSetID); + for (let i = 0; i < len; i++) { + outArr.push({ + startTime: startTime[i], + dur: dur[i], + cpu: cpu[i], + id: id[i], + tid: tid[i], + state: threadStateToString(state[i]), + pid: pid[i], + argSetID: argSetID[i], + } as ThreadStruct); + } + return outArr; +} diff --git a/ide/src/trace/database/data-trafic/utils/AllMemoryCache.ts b/ide/src/trace/database/data-trafic/utils/AllMemoryCache.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c2ac323deee2bd83b34916bd203218fa6efa21c --- /dev/null +++ b/ide/src/trace/database/data-trafic/utils/AllMemoryCache.ts @@ -0,0 +1,69 @@ +// 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 { hiPerfCallChartClearCache } from '../hiperf/HiperfCallChartReceiver'; +import { nativeMemoryCacheClear } from '../NativeMemoryDataReceiver'; +import { resetVmTracker } from '../VmTrackerDataReceiver'; +import { resetVM } from '../VirtualMemoryDataReceiver'; +import { resetAbilityMonitor } from '../AbilityMonitorReceiver'; +import { resetAbility } from '../VmTrackerDataReceiver'; +//cpu 泳道 memory 缓存 +export const cpuList: Map> = new Map(); +//clock 泳道 memory 模式缓存 +export const clockList: Map> = new Map(); +//cpu freq 泳道 memory模式缓存 +export const cpuFreqList: Map> = new Map(); +//cpu freq limit 泳道 memory模式缓存 +export const cpuFreqLimitList: Map> = new Map(); +//cpu state 泳道 memory模式缓存 +export const cpuStateList: Map> = new Map(); +//thread call stack 泳道图 memory 模式缓存 +export const threadCallStackList: Map> = new Map(); +//irq 泳道图 memory 模式缓存 +export const lrqList: Map> = new Map(); +//进程 泳道图 memory 模式缓存 +export const processList: Map> = new Map(); +//进程内存 泳道图 memory 模式缓存数据 +export const memList: Map> = new Map(); +//线程状态 泳道图 memory 模式缓存 +export const threadStateList: Map> = new Map(); +//进程下卡顿丢帧 泳道图 memory 模式缓存 +export const processFrameList: Map> = new Map(); +export function clearMemoryCache(data: any, proc: Function) { + cpuList.clear(); + clockList.clear(); + cpuFreqList.clear(); + cpuFreqLimitList.clear(); + cpuStateList.clear(); + threadCallStackList.clear(); + lrqList.clear(); + processList.clear(); + memList.clear(); + threadStateList.clear(); + processFrameList.clear(); + hiPerfCallChartClearCache(true); + nativeMemoryCacheClear(); + resetVmTracker(); + resetAbilityMonitor(); + resetAbility(); + resetVM(); + (self as unknown as Worker).postMessage( + { + id: data.id, + action: data.action, + results: 'ok', + len: 0, + transfer: [], + }, + [] + ); +} diff --git a/ide/src/trace/database/data-trafic/utils/DataFilter.ts b/ide/src/trace/database/data-trafic/utils/DataFilter.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d81bc4630f4bfbb645b1ca4e449713af64dfe9c --- /dev/null +++ b/ide/src/trace/database/data-trafic/utils/DataFilter.ts @@ -0,0 +1,178 @@ +/* + * 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. + */ +export function filterData( + list: any[], + startKey: string, + durKey: string, + startNS: number, + endNS: number, + width: number +): any[] { + let pns = (endNS - startNS) / width; //每个像素多少ns + let slice = findRange(list, {startKey, durKey, startNS, endNS}); + let sum = 0; + for (let i = 0; i < slice.length; i++) { + if (i === slice.length - 1) { + if (slice[i][durKey] === undefined || slice[i][durKey] === null) { + slice[i][durKey] = (endNS || 0) - (slice[i][startKey] || 0); + } + } else { + if (slice[i][durKey] === undefined || slice[i][durKey] === null) { + slice[i][durKey] = (slice[i + 1][startKey] || 0) - (slice[i][startKey] || 0); + } + } + if (slice[i][durKey] >= pns || slice.length < 100) { + slice[i].v = true; + } else { + if (i > 0) { + let c = slice[i][startKey] - slice[i - 1][startKey] - slice[i - 1][durKey]; + if (c < pns && sum < pns) { + sum += c + slice[i - 1][durKey]; + slice[i].v = false; + } else { + slice[i].v = true; + sum = 0; + } + } + } + } + return slice.filter((it) => it.v); +} + +export function filterDataByLayer( + list: any[], + layerKey: string, + startKey: string, + durKey: string, + startNS: number, + endNS: number, + width: number +): any[] { + let pns = (endNS - startNS) / width; //每个像素多少ns + let sliceArray = findRange(list, {startKey, durKey, startNS, endNS}); + let groups = groupBy(sliceArray, layerKey); + let res: any[] = []; + Reflect.ownKeys(groups).map((key: any) => { + let slice = groups[key] as any[]; + if (slice.length > 0) { + let sum = 0; + for (let i = 0; i < slice.length; i++) { + if (i === slice.length - 1) { + if (slice[i][durKey] === undefined || slice[i][durKey] === null) { + slice[i][durKey] = (endNS || 0) - (slice[i][startKey] || 0); + } + } else { + if (slice[i][durKey] === undefined || slice[i][durKey] === null) { + slice[i][durKey] = (slice[i + 1][startKey] || 0) - (slice[i][startKey] || 0); + } + } + if (slice[i][durKey] >= pns || slice.length < 100) { + slice[i].v = true; + } else { + if (i > 0) { + let c = slice[i][startKey] - slice[i - 1][startKey] - slice[i - 1][durKey]; + if (c < pns && sum < pns) { + sum += c + slice[i - 1][durKey]; + slice[i].v = false; + } else { + slice[i].v = true; + sum = 0; + } + } + } + } + res.push(...slice.filter((it) => it.v)); + } + }); + return res; +} + +export function filterDataByGroup( + list: any[], + startKey: string, + durKey: string, + startNS: number, + endNS: number, + width: number, + valueKey?: string, + filter?: (a: any) => boolean): any[] { + let arr = findRange(list, {startKey, durKey, startNS, endNS}) + arr = arr.map((it) => { + it.px = Math.floor(it[startKey] / ((endNS - startNS) / width)); + return it; + }); + let group = groupBy(arr, 'px'); + let res: Set = new Set(); + Reflect.ownKeys(group).map((key: any): void => { + let arr = group[key] as any[]; + if (arr.length > 0) { + res.add(arr.reduce((p, c) => (p[durKey] > c[durKey]) ? p : c)); + if (valueKey) { + res.add(arr.reduce((p, c) => (p[valueKey] > c[valueKey]) ? p : c)); + } + if (filter) { + let filterArr = arr.filter(a => filter(a)); + if (filterArr && filterArr.length > 0) { + res.add(filterArr.reduce((p, c) => (p[durKey] > c[durKey]) ? p : c)); + } + } + } + }); + return [...res]; +} + +export function filterDataByGroupLayer( + list: any[], + layerKey: string, + startKey: string, + durKey: string, + startNS: number, + endNS: number, + width: number +): any[] { + let arr = findRange(list, {startKey, durKey, startNS, endNS}); + arr = arr.map((it) => { + it.px = Math.floor(it[startKey] / ((endNS - startNS) / width) + it[layerKey] * width); + //设置临时变量durTmp 用于参与计算,分组后有dur为-1的数据按最长宽度显示 + it.durTmp = it[durKey] === -1 ? (endNS - it[startKey]) : it[durKey]; + return it; + }); + let group = groupBy(arr, 'px'); + let res: any[] = []; + Reflect.ownKeys(group).map((key: any) => { + let childArray = (group[key] as any[]).reduce((p, c) => (p.durTmp > c.durTmp) ? p : c); + res.push(childArray); + }); + return res; +} + +function groupBy(array: Array, key: string): any { + return array.reduce((pre, current, index, arr) => { + (pre[current[key]] = pre[current[key]] || []).push(current); + return pre; + }, {}); +} + +function findRange( + fullData: Array, + condition: { + startKey: string; + startNS: number; + durKey: string; + endNS: number; + } +): Array { + return fullData.filter(it => it[condition.startKey] + it[condition.durKey] >= condition.startNS && it[condition.startKey] <= condition.endNS); +} diff --git a/ide/src/trace/database/data-trafic/utils/ExecProtoForWorker.ts b/ide/src/trace/database/data-trafic/utils/ExecProtoForWorker.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ba5537b4b4e37c89ffcb011653689e5773f423e --- /dev/null +++ b/ide/src/trace/database/data-trafic/utils/ExecProtoForWorker.ts @@ -0,0 +1,146 @@ +/* + * 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 { QueryEnum } from './QueryEnum'; +import { cpuDataReceiver, searchDataHandler } from '../CpuDataReceiver'; +import { processDataReceiver } from '../process/ProcessDataReceiver'; +import { threadDataReceiver } from '../process//ThreadDataReceiver'; +import { funcDataReceiver } from '../process//FuncDataReceiver'; +import { hiperfCpuDataReceiver } from '../hiperf/HiperfCpuDataReceiver'; +import { hiperfProcessDataReceiver } from '../hiperf/HiperfProcessDataReceiver'; +import { hiperfThreadDataReceiver } from '../hiperf/HiperfThreadDataReceiver'; +import { cpuStateReceiver } from '../cpu/CpuStateReceiver'; +import { cpuFreqLimitReceiver } from '../cpu/CpuFreqLimitDataReceiver'; +import { clockDataReceiver } from '../ClockDataReceiver'; +import { irqDataReceiver } from '../IrqDataReceiver'; +import { processExpectedDataReceiver } from '../process/ProcessExpectedDataReceiver'; +import { processActualDataReceiver } from '../process//ProcessActualDataReceiver'; +import { hiPerfCallChartDataHandler, hiPerfCallStackCacheHandler } from '../hiperf/HiperfCallChartReceiver'; +import { virtualMemoryDataReceiver } from '../VirtualMemoryDataReceiver'; +import { processMemDataReceiver } from '../process//ProcessMemDataReceiver'; +import { processStartupDataReceiver } from '../process//ProcessStartupDataReceiver'; +import { processSoInitDataReceiver } from '../process//ProcessSoInitDataReceiver'; +import { processDeliverInputEventDataReceiver } from '../process//ProcessDeliverInputEventDataReceiver'; + +import { + dmaDataReceiver, + gpuDataReceiver, + gpuMemoryDataReceiver, + gpuResourceDataReceiver, + gpuTotalDataReceiver, + gpuWindowDataReceiver, + purgeableDataReceiver, + sMapsDataReceiver, + shmDataReceiver, + abilityDmaDataReceiver, + abilityGpuMemoryDataReceiver, + abilityPurgeableDataReceiver, +} from '../VmTrackerDataReceiver'; +import { + abilityBytesInTraceDataReceiver, + abilityBytesOutTraceDataReceiver, + abilityMemoryUsedDataReceiver, + abilityPacketInTraceDataReceiver, + abilityPacketsOutTraceDataReceiver, + cpuAbilityMonitorDataReceiver, + cpuAbilitySystemDataReceiver, + cpuAbilityUserDataReceiver, + abilityBytesReadDataReceiver, + abilityBytesWrittenDataReceiver, + abilityReadOpsDataReceiver, + abilityWrittenOpsDataReceiver, +} from '../AbilityMonitorReceiver'; +import { hiSysEventDataReceiver } from '../HiSysEventDataReceiver'; +import { logDataReceiver } from '../LogDataReceiver'; +import { cpuProfilerDataReceiver } from '../ArkTsReceiver'; +import { frameActualReceiver, frameExpectedReceiver } from '../FrameJanksReceiver'; +import { diskIoReceiver, eBPFVmReceiver, fileSystemDataReceiver } from '../EBPFReceiver'; +import { nativeMemoryDataHandler } from '../NativeMemoryDataReceiver'; +import { frameAnimationReceiver, frameDynamicReceiver, frameSpacingReceiver } from '../FrameDynamicEffectReceiver'; +import { + energySysEventReceiver, + hiSysEnergyAnomalyDataReceiver, hiSysEnergyPowerReceiver, + hiSysEnergyStateReceiver +} from '../EnergySysEventReceiver'; +import {clearMemoryCache} from "./AllMemoryCache"; +import { cpuFreqDataReceiver } from '../cpu/CpuFreqDataReceiver'; +const traficHandlers: Map = new Map([]); +export const execProtoForWorker = (data: any, proc: Function): void => traficHandlers.get(data.name)?.(data, proc); + +traficHandlers.set(QueryEnum.ClearMemoryCache, clearMemoryCache); +traficHandlers.set(QueryEnum.CpuData, cpuDataReceiver); +traficHandlers.set(QueryEnum.SearchCpuData, searchDataHandler); +traficHandlers.set(QueryEnum.CpuFreqData, cpuFreqDataReceiver); +traficHandlers.set(QueryEnum.CpuStateData, cpuStateReceiver); +traficHandlers.set(QueryEnum.CpuFreqLimitData, cpuFreqLimitReceiver); +traficHandlers.set(QueryEnum.ProcessData, processDataReceiver); +traficHandlers.set(QueryEnum.ThreadData, threadDataReceiver); +traficHandlers.set(QueryEnum.FuncData, funcDataReceiver); +traficHandlers.set(QueryEnum.HiperfCallChart, hiPerfCallChartDataHandler); +traficHandlers.set(QueryEnum.HiperfCallStack, hiPerfCallStackCacheHandler); +traficHandlers.set(QueryEnum.HiperfCpuData, hiperfCpuDataReceiver); +traficHandlers.set(QueryEnum.HiperfProcessData, hiperfProcessDataReceiver); +traficHandlers.set(QueryEnum.HiperfThreadData, hiperfThreadDataReceiver); +traficHandlers.set(QueryEnum.NativeMemoryChartCacheNormal, nativeMemoryDataHandler); +traficHandlers.set(QueryEnum.NativeMemoryChartCacheStatistic, nativeMemoryDataHandler); +traficHandlers.set(QueryEnum.NativeMemoryChartData, nativeMemoryDataHandler); +traficHandlers.set(QueryEnum.ClockData, clockDataReceiver); +traficHandlers.set(QueryEnum.IrqData, irqDataReceiver); +traficHandlers.set(QueryEnum.VirtualMemoryData, virtualMemoryDataReceiver); +traficHandlers.set(QueryEnum.ProcessMemData, processMemDataReceiver); +traficHandlers.set(QueryEnum.ProcessStartupData, processStartupDataReceiver); +traficHandlers.set(QueryEnum.ProcessSoInitData, processSoInitDataReceiver); +traficHandlers.set(QueryEnum.processExpectedData, processExpectedDataReceiver); +traficHandlers.set(QueryEnum.processActualData, processActualDataReceiver); +traficHandlers.set(QueryEnum.processDeliverInputEventData, processDeliverInputEventDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerSmapsData, sMapsDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerDmaData, dmaDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerGpuMemoryData, gpuMemoryDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerGpuData, gpuDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerGpuResourceData, gpuResourceDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerGpuTotalData, gpuTotalDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerGpuWindowData, gpuWindowDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerShmData, shmDataReceiver); +traficHandlers.set(QueryEnum.VmTrackerPurgeableData, purgeableDataReceiver); +traficHandlers.set(QueryEnum.AbilityMemoryUsedData, abilityMemoryUsedDataReceiver); +traficHandlers.set(QueryEnum.CpuAbilityUserData, cpuAbilityUserDataReceiver); +traficHandlers.set(QueryEnum.CpuAbilitySystemData, cpuAbilitySystemDataReceiver); +traficHandlers.set(QueryEnum.CpuAbilityMonitorData, cpuAbilityMonitorDataReceiver); +traficHandlers.set(QueryEnum.AbilityBytesReadData, abilityBytesReadDataReceiver); +traficHandlers.set(QueryEnum.AbilityBytesWrittenData, abilityBytesWrittenDataReceiver); +traficHandlers.set(QueryEnum.AbilityReadOpsData, abilityReadOpsDataReceiver); +traficHandlers.set(QueryEnum.AbilityWrittenOpsData, abilityWrittenOpsDataReceiver); +traficHandlers.set(QueryEnum.AbilityBytesInTraceData, abilityBytesInTraceDataReceiver); +traficHandlers.set(QueryEnum.AbilityBytesOutTraceData, abilityBytesOutTraceDataReceiver); +traficHandlers.set(QueryEnum.AbilityPacketInTraceData, abilityPacketInTraceDataReceiver); +traficHandlers.set(QueryEnum.AbilityPacketsOutTraceData, abilityPacketsOutTraceDataReceiver); +traficHandlers.set(QueryEnum.AbilityPurgeableData, abilityPurgeableDataReceiver); +traficHandlers.set(QueryEnum.AbilityDmaData, abilityDmaDataReceiver); +traficHandlers.set(QueryEnum.AbilityGpuMemoryData, abilityGpuMemoryDataReceiver); +traficHandlers.set(QueryEnum.HiSysEventData, hiSysEventDataReceiver); +traficHandlers.set(QueryEnum.HilogData, logDataReceiver); +traficHandlers.set(QueryEnum.FileSystemData, fileSystemDataReceiver); +traficHandlers.set(QueryEnum.DiskIoData, diskIoReceiver); +traficHandlers.set(QueryEnum.EBPFVm, eBPFVmReceiver); +traficHandlers.set(QueryEnum.CpuProfilerData, cpuProfilerDataReceiver); +traficHandlers.set(QueryEnum.FrameExpectedData, frameExpectedReceiver); +traficHandlers.set(QueryEnum.FrameActualData, frameActualReceiver); +traficHandlers.set(QueryEnum.EnergyAnomalyData, hiSysEnergyAnomalyDataReceiver); +traficHandlers.set(QueryEnum.EnergyStateData, hiSysEnergyStateReceiver); +traficHandlers.set(QueryEnum.EnergyPowerData, hiSysEnergyPowerReceiver); +traficHandlers.set(QueryEnum.FrameAnimationData, frameAnimationReceiver); +traficHandlers.set(QueryEnum.FrameDynamicData, frameDynamicReceiver); +traficHandlers.set(QueryEnum.FrameSpacingData, frameSpacingReceiver); +traficHandlers.set(QueryEnum.EnergySystemData, energySysEventReceiver); diff --git a/ide/src/trace/database/data-trafic/utils/QueryEnum.ts b/ide/src/trace/database/data-trafic/utils/QueryEnum.ts new file mode 100644 index 0000000000000000000000000000000000000000..88484a72f7c6ada362658833f6d2cdba45cd62e9 --- /dev/null +++ b/ide/src/trace/database/data-trafic/utils/QueryEnum.ts @@ -0,0 +1,104 @@ +// 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. + +export const CHART_OFFSET_LEFT = 248; +export enum QueryEnum { + ClearMemoryCache = -1, + CpuData = 0, + CpuStateData = 1, + CpuFreqData = 2, + CpuFreqLimitData = 3, + ClockData = 4, + IrqData = 5, + ProcessData = 6, + ProcessMemData = 7, + ProcessStartupData = 8, + ProcessSoInitData = 9, + HiSysEventData = 10, + HilogData = 11, + VirtualMemoryData = 12, + EnergySystemData = 13, + EnergyStateData = 14, + EnergyAnomalyData = 15, + FrameExpectedData = 16, + FrameActualData = 17, + FrameAnimationData = 18, + FrameDynamicData = 19, + FrameSpacingData = 20, + EnergyPowerData = 47, + FileSystemData = 48, + DiskIoData = 49, + EBPFVm = 50, + VmTrackerSmapsData = 81, + VmTrackerDmaData = 82, + VmTrackerGpuMemoryData = 83, + VmTrackerGpuData = 84, + VmTrackerGpuResourceData = 85, + VmTrackerGpuTotalData = 86, + VmTrackerGpuWindowData = 87, + VmTrackerShmData = 88, + VmTrackerPurgeableData = 89, + AbilityMemoryUsedData = 90, + CpuAbilityUserData = 91, + CpuAbilitySystemData = 92, + CpuAbilityMonitorData = 93, + AbilityBytesReadData = 94, + AbilityBytesWrittenData = 95, + AbilityReadOpsData = 96, + AbilityWrittenOpsData = 97, + AbilityBytesInTraceData = 98, + AbilityBytesOutTraceData = 99, + AbilityPacketInTraceData = 100, + AbilityPacketsOutTraceData = 101, + AbilityCachedFilesData, + AbilityCompressedData, + AbilityPurgeableData = 151, + AbilityGpuMemoryData = 152, + AbilityDmaData = 153, + ThreadData = 30, + FuncData = 31, + HiperfCpuData = 200, + HiperfProcessData = 201, + HiperfThreadData = 202, + HiperfCallChart = 203, + HiperfCallStack = 204, + NativeMemoryChartData = 205, + NativeMemoryChartCacheNormal = 206, + NativeMemoryChartCacheStatistic = 207, + processExpectedData = 26, + processActualData = 27, + processDeliverInputEventData = 28, + HeapTimelineData = 160, + HeapSnapshotData = 161, + CpuProfilerData = 162, + SearchCpuData = 163, +} +export const MAX_COUNT = 2000; +export enum TraficEnum { + Memory, + SharedArrayBuffer, + TransferArrayBuffer, + ProtoBuffer, +} + +export function threadStateToNumber(state: string): number { + return threadStateArray.findIndex((it) => it === state); +} +export function threadStateToString(state: number): string { + if (state === -1) { + return ''; + } else { + return threadStateArray[state]; + } +} +const threadStateArray = ['D-NIO', 'DK-NIO', 'D-IO', 'DK-IO', 'D', 'DK', 'R', 'R+', 'R-B', 'I', 'Running', 'S']; diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.ts index a2586d99e1cafa014fb8bcd232a65057ec030d6a..e5dc6cf772f6cbb864e9b88caf92ad4927682432 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerFileSystem.ts @@ -80,223 +80,240 @@ export class ProcedureLogicWorkerFileSystem extends LogicHandler { this.initCallchains(); break; case 'fileSystem-queryCallchains': - let callChains = convertJSON(data.params.list) || []; - this.dataCache.clearEBpf(); - this.initCallChainTopDown(callChains); - // @ts-ignore - self.postMessage({ - id: data.id, - action: 'fileSystem-init', - results: [], - }); + this.fileSystemQueryCallchains(data); break; case 'fileSystem-queryFileSamples': - this.handlerMap.get('fileSystem').samplesList = convertJSON(data.params.list) || []; - let fsResults; - if (this.isAnalysis) { - this.isAnalysis = false; - self.postMessage({ - id: this.currentEventId, - action: data.action, - results: this.fileSystemAnalysis(FS_TYPE, this.handlerMap.get('fileSystem').samplesList), - }); - } else { - if (this.lib) { - let samplesList = this.fileSystemAnalysis( - FS_TYPE, - this.handlerMap.get('fileSystem').samplesList, - this.lib - ); - this.handlerMap.get('fileSystem').freshCurrentCallChains(samplesList, this.isTopDown); - fsResults = this.handlerMap.get('fileSystem').allProcess; - this.lib = undefined; - } else if (this.symbol) { - let samplesList = this.fileSystemAnalysis( - FS_TYPE, - this.handlerMap.get('fileSystem').samplesList, - this.symbol - ); - this.handlerMap.get('fileSystem').freshCurrentCallChains(samplesList, this.isTopDown); - fsResults = this.handlerMap.get('fileSystem').allProcess; - this.symbol = undefined; - } else { - fsResults = this.handlerMap.get('fileSystem').resolvingAction([ - { - funcName: 'getCallChainsBySampleIds', - funcArgs: [this.isTopDown], - }, - ]); - } - self.postMessage({ - id: this.currentEventId, - action: data.action, - results: fsResults, - }); - } - + this.fileSystemQueryFileSamples(data); break; case 'fileSystem-queryIoSamples': - this.handlerMap.get('io').samplesList = convertJSON(data.params.list) || []; - let ioResults; - if (this.isAnalysis) { - this.isAnalysis = false; - self.postMessage({ - id: this.currentEventId, - action: data.action, - results: this.fileSystemAnalysis(BIO_TYPE, this.handlerMap.get('io').samplesList), - }); - } else { - if (this.lib) { - let samplesList = this.fileSystemAnalysis(BIO_TYPE, this.handlerMap.get('io').samplesList, this.lib); - this.handlerMap.get('io').freshCurrentCallChains(samplesList, this.isTopDown); - ioResults = this.handlerMap.get('io').allProcess; - this.lib = undefined; - } else if (this.symbol) { - let samplesList = this.fileSystemAnalysis(BIO_TYPE, this.handlerMap.get('io').samplesList, this.symbol); - this.handlerMap.get('io').freshCurrentCallChains(samplesList, this.isTopDown); - ioResults = this.handlerMap.get('io').allProcess; - this.symbol = undefined; - } else { - ioResults = this.handlerMap.get('io').resolvingAction([ - { - funcName: 'getCallChainsBySampleIds', - funcArgs: [this.isTopDown], - }, - ]); - } - self.postMessage({ - id: this.currentEventId, - action: data.action, - results: ioResults, - }); - } - + this.fileSystemQueryIoSamples(data); break; case 'fileSystem-queryVirtualMemorySamples': - this.handlerMap.get('virtualMemory').samplesList = convertJSON(data.params.list) || []; - let vmResults; - if (this.isAnalysis) { - this.isAnalysis = false; - self.postMessage({ - id: this.currentEventId, - action: data.action, - results: this.fileSystemAnalysis(PF_TYPE, this.handlerMap.get('virtualMemory').samplesList), - }); - } else { - if (this.lib) { - let samplesList = this.fileSystemAnalysis( - PF_TYPE, - this.handlerMap.get('virtualMemory').samplesList, - this.lib - ); - this.handlerMap.get('virtualMemory').freshCurrentCallChains(samplesList, this.isTopDown); - vmResults = this.handlerMap.get('virtualMemory').allProcess; - this.lib = undefined; - } else if (this.symbol) { - let samplesList = this.fileSystemAnalysis( - PF_TYPE, - this.handlerMap.get('virtualMemory').samplesList, - this.symbol - ); - this.handlerMap.get('virtualMemory').freshCurrentCallChains(samplesList, this.isTopDown); - vmResults = this.handlerMap.get('virtualMemory').allProcess; - this.symbol = undefined; - } else { - vmResults = this.handlerMap.get('virtualMemory').resolvingAction([ - { - funcName: 'getCallChainsBySampleIds', - funcArgs: [this.isTopDown], - }, - ]); - } - self.postMessage({ - id: this.currentEventId, - action: data.action, - results: vmResults, - }); - } + this.fileSystemQueryVirtualMemorySamples(data); break; case 'fileSystem-action': - if (data.params) { - this.isTopDown = false; - this.handlerMap.get(data.params.callType).isHideEvent = false; - this.handlerMap.get(data.params.callType).isHideThread = false; - let filter = data.params.args.filter((item: any) => item.funcName == 'getCurrentDataFromDb'); - // 从lib层跳转 - let libFilter = data.params.args.filter((item: any): boolean => item.funcName === 'showLibLevelData'); - // 从fun层跳转 - let funFilter = data.params.args.filter((item: any): boolean => item.funcName === 'showFunLevelData'); - let callChainsFilter = data.params.args.filter( - (item: any): boolean => item.funcName === 'getCallChainsBySampleIds' - ); - callChainsFilter.length > 0 ? (this.isTopDown = callChainsFilter[0].funcArgs[0]) : (this.isTopDown = true); - if (libFilter.length !== 0) { - this.lib = { - libId: libFilter[0].funcArgs[0], - libName: libFilter[0].funcArgs[1], - }; - } else if (funFilter.length !== 0) { - this.symbol = { - symbolId: funFilter[0].funcArgs[0], - symbolName: funFilter[0].funcArgs[1], - }; - } - if (filter.length == 0) { - // @ts-ignore - self.postMessage({ - id: data.id, - action: data.action, - results: this.handlerMap.get(data.params.callType).resolvingAction(data.params.args), - }); - } else { - if (data.params.isAnalysis) { - this.isAnalysis = true; - } - this.handlerMap.get(data.params.callType).resolvingAction(data.params.args); - } - } + this.fileSystemAction(data); break; case 'fileSystem-queryStack': - let res = this.getStacksByCallchainId(data.params.callchainId); - self.postMessage({ - id: data.id, - action: data.action, - results: res, - }); + this.fileSystemQueryStack(data); break; case 'fileSystem-queryFileSysEvents': - if (data.params.list) { - let res = convertJSON(data.params.list) || []; - postMessage(data.id, data.action, this.supplementFileSysEvents(res, this.tab)); - } else { - this.tab = data.params.tab; - this.queryFileSysEvents(data.params.leftNs, data.params.rightNs, data.params.typeArr, data.params.tab); - } + this.fileSystemQueryFileSysEvents(data); break; case 'fileSystem-queryVMEvents': - if (data.params.list) { - let res = convertJSON(data.params.list) || []; - postMessage(data.id, data.action, this.supplementVMEvents(res)); - } else { - this.queryVMEvents(data.params.leftNs, data.params.rightNs, data.params.typeArr); - } + this.fileSystemQueryVMEvents(data); break; case 'fileSystem-queryIOEvents': - if (data.params.list) { - let res = convertJSON(data.params.list) || []; - postMessage(data.id, data.action, this.supplementIoEvents(res)); - } else { - this.queryIOEvents(data.params.leftNs, data.params.rightNs, data.params.diskIOipids); - } + this.fileSystemQueryIOEvents(data); break; case 'fileSystem-reset': - this.handlerMap.get('fileSystem').isHideEvent = false; - this.handlerMap.get('fileSystem').isHideThread = false; + this.fileSystemReset(); + break; } } } - clearAll(): void { + private fileSystemQueryCallchains(data: any): void { + let callChains = convertJSON(data.params.list) || []; + this.dataCache.clearEBpf(); + this.initCallChainTopDown(callChains); + // @ts-ignore + self.postMessage({ + id: data.id, + action: 'fileSystem-init', + results: [], + }); + } + private fileSystemQueryFileSamples(data: any): void { + this.handlerMap.get('fileSystem').samplesList = convertJSON(data.params.list) || []; + let fsResults; + if (this.isAnalysis) { + this.isAnalysis = false; + self.postMessage({ + id: this.currentEventId, + action: data.action, + results: this.fileSystemAnalysis(FS_TYPE, this.handlerMap.get('fileSystem').samplesList), + }); + } else { + if (this.lib) { + let samplesList = this.fileSystemAnalysis(FS_TYPE, this.handlerMap.get('fileSystem').samplesList, this.lib); + this.handlerMap.get('fileSystem').freshCurrentCallChains(samplesList, this.isTopDown); + fsResults = this.handlerMap.get('fileSystem').allProcess; + this.lib = undefined; + } else if (this.symbol) { + let samplesList = this.fileSystemAnalysis(FS_TYPE, this.handlerMap.get('fileSystem').samplesList, this.symbol); + this.handlerMap.get('fileSystem').freshCurrentCallChains(samplesList, this.isTopDown); + fsResults = this.handlerMap.get('fileSystem').allProcess; + this.symbol = undefined; + } else { + fsResults = this.handlerMap.get('fileSystem').resolvingAction([ + { + funcName: 'getCallChainsBySampleIds', + funcArgs: [this.isTopDown], + }, + ]); + } + self.postMessage({ + id: this.currentEventId, + action: data.action, + results: fsResults, + }); + } + } + private fileSystemQueryIoSamples(data: any): void { + this.handlerMap.get('io').samplesList = convertJSON(data.params.list) || []; + let ioResults; + if (this.isAnalysis) { + this.isAnalysis = false; + self.postMessage({ + id: this.currentEventId, + action: data.action, + results: this.fileSystemAnalysis(BIO_TYPE, this.handlerMap.get('io').samplesList), + }); + } else { + if (this.lib) { + let samplesList = this.fileSystemAnalysis(BIO_TYPE, this.handlerMap.get('io').samplesList, this.lib); + this.handlerMap.get('io').freshCurrentCallChains(samplesList, this.isTopDown); + ioResults = this.handlerMap.get('io').allProcess; + this.lib = undefined; + } else if (this.symbol) { + let samplesList = this.fileSystemAnalysis(BIO_TYPE, this.handlerMap.get('io').samplesList, this.symbol); + this.handlerMap.get('io').freshCurrentCallChains(samplesList, this.isTopDown); + ioResults = this.handlerMap.get('io').allProcess; + this.symbol = undefined; + } else { + ioResults = this.handlerMap.get('io').resolvingAction([ + { + funcName: 'getCallChainsBySampleIds', + funcArgs: [this.isTopDown], + }, + ]); + } + self.postMessage({ + id: this.currentEventId, + action: data.action, + results: ioResults, + }); + } + } + private fileSystemQueryVirtualMemorySamples(data: any): void { + this.handlerMap.get('virtualMemory').samplesList = convertJSON(data.params.list) || []; + let vmResults; + if (this.isAnalysis) { + this.isAnalysis = false; + self.postMessage({ + id: this.currentEventId, + action: data.action, + results: this.fileSystemAnalysis(PF_TYPE, this.handlerMap.get('virtualMemory').samplesList), + }); + } else { + if (this.lib) { + let samplesList = this.fileSystemAnalysis(PF_TYPE, this.handlerMap.get('virtualMemory').samplesList, this.lib); + this.handlerMap.get('virtualMemory').freshCurrentCallChains(samplesList, this.isTopDown); + vmResults = this.handlerMap.get('virtualMemory').allProcess; + this.lib = undefined; + } else if (this.symbol) { + let samplesList = this.fileSystemAnalysis( + PF_TYPE, + this.handlerMap.get('virtualMemory').samplesList, + this.symbol + ); + this.handlerMap.get('virtualMemory').freshCurrentCallChains(samplesList, this.isTopDown); + vmResults = this.handlerMap.get('virtualMemory').allProcess; + this.symbol = undefined; + } else { + vmResults = this.handlerMap.get('virtualMemory').resolvingAction([ + { + funcName: 'getCallChainsBySampleIds', + funcArgs: [this.isTopDown], + }, + ]); + } + self.postMessage({ + id: this.currentEventId, + action: data.action, + results: vmResults, + }); + } + } + private fileSystemAction(data: any): void { + if (data.params) { + this.isTopDown = false; + this.handlerMap.get(data.params.callType).isHideEvent = false; + this.handlerMap.get(data.params.callType).isHideThread = false; + let filter = data.params.args.filter((item: any) => item.funcName == 'getCurrentDataFromDb'); + // 从lib层跳转 + let libFilter = data.params.args.filter((item: any): boolean => item.funcName === 'showLibLevelData'); + // 从fun层跳转 + let funFilter = data.params.args.filter((item: any): boolean => item.funcName === 'showFunLevelData'); + let callChainsFilter = data.params.args.filter( + (item: any): boolean => item.funcName === 'getCallChainsBySampleIds' + ); + callChainsFilter.length > 0 ? (this.isTopDown = callChainsFilter[0].funcArgs[0]) : (this.isTopDown = true); + if (libFilter.length !== 0) { + this.lib = { + libId: libFilter[0].funcArgs[0], + libName: libFilter[0].funcArgs[1], + }; + } else if (funFilter.length !== 0) { + this.symbol = { + symbolId: funFilter[0].funcArgs[0], + symbolName: funFilter[0].funcArgs[1], + }; + } + if (filter.length == 0) { + // @ts-ignore + self.postMessage({ + id: data.id, + action: data.action, + results: this.handlerMap.get(data.params.callType).resolvingAction(data.params.args), + }); + } else { + if (data.params.isAnalysis) { + this.isAnalysis = true; + } + this.handlerMap.get(data.params.callType).resolvingAction(data.params.args); + } + } + } + private fileSystemQueryStack(data: any): void { + let res = this.getStacksByCallchainId(data.params.callchainId); + self.postMessage({ + id: data.id, + action: data.action, + results: res, + }); + } + private fileSystemQueryFileSysEvents(data: any): void { + if (data.params.list) { + let res = convertJSON(data.params.list) || []; + postMessage(data.id, data.action, this.supplementFileSysEvents(res, this.tab)); + } else { + this.tab = data.params.tab; + this.queryFileSysEvents(data.params.leftNs, data.params.rightNs, data.params.typeArr, data.params.tab); + } + } + private fileSystemQueryVMEvents(data: any): void { + if (data.params.list) { + let res = convertJSON(data.params.list) || []; + postMessage(data.id, data.action, this.supplementVMEvents(res)); + } else { + this.queryVMEvents(data.params.leftNs, data.params.rightNs, data.params.typeArr); + } + } + private fileSystemQueryIOEvents(data: any): void { + if (data.params.list) { + let res = convertJSON(data.params.list) || []; + postMessage(data.id, data.action, this.supplementIoEvents(res)); + } else { + this.queryIOEvents(data.params.leftNs, data.params.rightNs, data.params.diskIOipids); + } + } + private fileSystemReset(): void { + this.handlerMap.get('fileSystem').isHideEvent = false; + this.handlerMap.get('fileSystem').isHideThread = false; + } + public clearAll(): void { this.dataCache.clearEBpf(); for (let key of this.handlerMap.keys()) { if (this.handlerMap.get(key).clear) { @@ -305,14 +322,24 @@ export class ProcedureLogicWorkerFileSystem extends LogicHandler { } this.handlerMap.clear(); } - queryFileSysEvents(leftNs: number, rightNs: number, typeArr: Array, tab: string): void { let types: string = Array.from(typeArr).join(','); let sql: string = ''; if (tab === 'events') { - sql = ` - select - A.callchain_id as callchainId, + sql = this.queryFileSysEventsSQL1(types); + } else if (tab === 'history') { + sql = this.queryFileSysEventsSQL2(types); + } else { + sql = this.queryFileSysEventsSQL3(rightNs); + } + this.queryData(this.currentEventId, 'fileSystem-queryFileSysEvents', sql, { + $leftNS: leftNs, + $rightNS: rightNs, + }); + } + + private queryFileSysEventsSQL1(types: string): string { + return `select A.callchain_id as callchainId, (A.start_ts - B.start_ts) as startTs, dur, A.type, @@ -326,37 +353,27 @@ export class ProcedureLogicWorkerFileSystem extends LogicHandler { fd, file_id as fileId, error_code as error - from file_system_sample A,trace_range B + from file_system_sample A, trace_range B left join process C on A.ipid = C.id left join thread D on A.itid = D.id - where A.type in (${types}) - and( - (A.end_ts - B.start_ts) between $leftNS and $rightNS - ) - order by A.end_ts; - `; - } else if (tab === 'history') { - sql = ` - select - A.callchain_id as callchainId, - (A.start_ts - B.start_ts) as startTs, - dur, - fd, - A.type, - A.file_id as fileId, - ifnull(C.name,'Process') || '[' || C.pid || ']' as process - from file_system_sample A,trace_range B + where A.type in (${types}) and( (A.end_ts - B.start_ts) between $leftNS and $rightNS ) + order by A.end_ts;`; + } + private queryFileSysEventsSQL2(types: string): string { + return `select A.callchain_id as callchainId, + (A.start_ts - B.start_ts) as startTs, + dur, + fd, + A.type, + A.file_id as fileId, + ifnull(C.name,'Process') || '[' || C.pid || ']' as process + from file_system_sample A, trace_range B left join process C on A.ipid = C.id - where A.type in (${types}) - and fd not null - and( - (A.start_ts - B.start_ts) between $leftNS and $rightNS - ) - order by A.end_ts; - `; - } else { - sql = ` - select TB.callchain_id as callchainId, + where A.type in (${types}) and fd not null and( (A.start_ts - B.start_ts) between $leftNS and $rightNS ) + order by A.end_ts;`; + } + private queryFileSysEventsSQL3(rightNs: number): string { + return `select TB.callchain_id as callchainId, (TB.start_ts - TR.start_ts) as startTs, (${rightNs} - TB.start_ts) as dur, TB.fd, @@ -364,26 +381,19 @@ export class ProcedureLogicWorkerFileSystem extends LogicHandler { TB.file_id as fileId, ifnull(TC.name, 'Process') || '[' || TC.pid || ']' as process from ( - select fd,ipid, + select fd, ipid, max(case when type = 0 then A.end_ts else 0 end) as openTs, max(case when type = 1 then A.end_ts else 0 end) as closeTs from file_system_sample A - where type in (0, 1) and A.end_ts between $leftNS and $rightNS group by fd,ipid + where type in (0, 1) and A.end_ts between $leftNS and $rightNS group by fd, ipid ) TA left join file_system_sample TB on TA.fd = TB.fd and TA.ipid = TB.ipid and TA.openTs = TB.end_ts left join process TC on TB.ipid = TC.ipid left join trace_range TR where startTs not null and TB.fd not null and TA.closeTs < TA.openTs - order by TB.end_ts; `; - } - this.queryData(this.currentEventId, 'fileSystem-queryFileSysEvents', sql, { - $leftNS: leftNs, - $rightNS: rightNs, - }); + order by TB.end_ts;`; } - queryVMEvents(leftNs: number, rightNs: number, typeArr: Array): void { - let types = Array.from(typeArr).join(','); let sql = `select A.callchain_id as callchainId, (A.start_ts - B.start_ts) as startTs, @@ -742,13 +752,12 @@ where s.end_ts between ${selectionParam.leftNs} + t.start_ts and ${selectionPara ); } - freshCurrentCallChains(samples: FileSample[], isTopDown: boolean): void { + private freshCurrentCallChains(samples: FileSample[], isTopDown: boolean): void { this.currentTreeMapData = {}; this.currentTreeList = []; this.allProcess = []; this.dataSource = []; let totalCount = 0; - samples.forEach((sample: FileSample): void => { totalCount += sample.dur; let callChains = this.createThreadAndType(sample); @@ -769,38 +778,45 @@ where s.end_ts between ${selectionParam.leftNs} + t.start_ts and ${selectionPara this.merageChildrenByIndex(root, callChains, topIndex, sample, isTopDown); } }); + let rootMerageMap = this.mergeNodeData(totalCount); + this.handleCurrentTreeList(totalCount); + this.allProcess = Object.values(rootMerageMap); + } + private mergeNodeData(totalCount: number): Map { let rootMerageMap: any = {}; - // @ts-ignore - Object.values(this.currentTreeMapData).forEach((merageData: any): void => { - if (rootMerageMap[merageData.pid] === undefined) { + Object.values(this.currentTreeMapData).forEach((mergeData: any): void => { + if (rootMerageMap[mergeData.pid] === undefined) { let fileMerageBean = new FileMerageBean(); //新增进程的节点数据 fileMerageBean.canCharge = false; fileMerageBean.isProcess = true; - fileMerageBean.symbolName = merageData.processName; + fileMerageBean.symbolName = mergeData.processName; fileMerageBean.symbol = fileMerageBean.symbolName; - fileMerageBean.children.push(merageData); - fileMerageBean.initChildren.push(merageData); - fileMerageBean.dur = merageData.dur; - fileMerageBean.count = merageData.count; + fileMerageBean.children.push(mergeData); + fileMerageBean.initChildren.push(mergeData); + fileMerageBean.dur = mergeData.dur; + fileMerageBean.count = mergeData.count; fileMerageBean.total = totalCount; - fileMerageBean.tsArray = [...merageData.tsArray]; - fileMerageBean.durArray = [...merageData.durArray]; - rootMerageMap[merageData.pid] = fileMerageBean; + fileMerageBean.tsArray = [...mergeData.tsArray]; + fileMerageBean.durArray = [...mergeData.durArray]; + rootMerageMap[mergeData.pid] = fileMerageBean; } else { - rootMerageMap[merageData.pid].children.push(merageData); - rootMerageMap[merageData.pid].initChildren.push(merageData); - rootMerageMap[merageData.pid].dur += merageData.dur; - rootMerageMap[merageData.pid].count += merageData.count; - rootMerageMap[merageData.pid].total = totalCount; - for (const ts of merageData.tsArray) { - rootMerageMap[merageData.pid].tsArray.push(ts); + rootMerageMap[mergeData.pid].children.push(mergeData); + rootMerageMap[mergeData.pid].initChildren.push(mergeData); + rootMerageMap[mergeData.pid].dur += mergeData.dur; + rootMerageMap[mergeData.pid].count += mergeData.count; + rootMerageMap[mergeData.pid].total = totalCount; + for (const ts of mergeData.tsArray) { + rootMerageMap[mergeData.pid].tsArray.push(ts); } - for (const dur of merageData.durArray) { - rootMerageMap[merageData.pid].durArray.push(dur); + for (const dur of mergeData.durArray) { + rootMerageMap[mergeData.pid].durArray.push(dur); } } - merageData.parentNode = rootMerageMap[merageData.pid]; //子节点添加父节点的引用 + mergeData.parentNode = rootMerageMap[mergeData.pid]; //子节点添加父节点的引用 }); + return rootMerageMap; + } + private handleCurrentTreeList(totalCount: number) { let id = 0; this.currentTreeList.forEach((currentNode: any): void => { currentNode.total = totalCount; @@ -817,10 +833,7 @@ where s.end_ts between ${selectionParam.leftNs} + t.start_ts and ${selectionPara currentNode.parentId = currentNode.parentNode.id; } }); - // @ts-ignore - this.allProcess = Object.values(rootMerageMap); } - createThreadAndType(sample: FileSample): FileCallChain[] { let typeCallChain = new FileCallChain(); typeCallChain.callChainId = sample.callChainId; @@ -906,76 +919,11 @@ where s.end_ts between ${selectionParam.leftNs} + t.start_ts and ${selectionPara currentNode.symbolName = `${currentNode.symbol} (${currentNode.libName})`; } } - resolvingAction(params: any[]): FileMerageBean[] { + public resolvingAction(params: any[]): FileMerageBean[] { if (params.length > 0) { params.forEach((paramItem: any): void => { if (paramItem.funcName && paramItem.funcArgs) { - switch (paramItem.funcName) { - case 'getCallChainsBySampleIds': - this.freshCurrentCallChains(this.samplesList, paramItem.funcArgs[0]); - break; - case 'getCurrentDataFromDb': - if (paramItem.funcArgs[1]) { - let funcArgs = paramItem.funcArgs[1]; - let sql = ''; - if (funcArgs.processId !== undefined) { - sql += `and p.pid = ${funcArgs.processId}`; - } - if (funcArgs.typeId !== undefined) { - sql += ` and s.type = ${funcArgs.typeId}`; - } - if (funcArgs.threadId !== undefined) { - sql += ` and h.tid = ${funcArgs.threadId}`; - } - this.queryCallChainsSamples(paramItem.funcArgs[0], sql); - } else { - this.queryCallChainsSamples(paramItem.funcArgs[0]); - } - break; - case 'hideSystemLibrary': - merageBeanDataSplit.hideSystemLibrary(this.allProcess, this.splitMapData); - break; - case 'hideNumMaxAndMin': - merageBeanDataSplit.hideNumMaxAndMin( - this.allProcess, - this.splitMapData, - paramItem.funcArgs[0], - paramItem.funcArgs[1] - ); - break; - case 'hideThread': - this.isHideThread = paramItem.funcArgs[0]; - break; - case 'hideEvent': - this.isHideEvent = paramItem.funcArgs[0]; - break; - case 'splitAllProcess': - merageBeanDataSplit.splitAllProcess(this.allProcess, this.splitMapData, paramItem.funcArgs[0]); - break; - case 'resetAllNode': - merageBeanDataSplit.resetAllNode(this.allProcess, this.currentTreeList, this.searchValue); - break; - case 'resotreAllNode': - merageBeanDataSplit.resotreAllNode(this.splitMapData, paramItem.funcArgs[0]); - break; - case 'clearSplitMapData': - this.clearSplitMapData(paramItem.funcArgs[0]); - break; - case 'splitTree': - merageBeanDataSplit.splitTree( - this.splitMapData, - this.allProcess, - paramItem.funcArgs[0], - paramItem.funcArgs[1], - paramItem.funcArgs[2], - this.currentTreeList, - this.searchValue - ); - break; - case 'setSearchValue': - this.searchValue = paramItem.funcArgs[0]; - break; - } + this.handleDataByFuncName(paramItem.funcName, paramItem.funcArgs); } }); this.dataSource = this.allProcess.filter((process: FileMerageBean): boolean => { @@ -984,7 +932,69 @@ where s.end_ts between ${selectionParam.leftNs} + t.start_ts and ${selectionPara } return this.dataSource; } - + private handleDataByFuncName(funcName: any, args: any): void { + switch (funcName) { + case 'getCallChainsBySampleIds': + this.freshCurrentCallChains(this.samplesList, args[0]); + break; + case 'getCurrentDataFromDb': + this.getCurrentDataFromDb(args); + break; + case 'hideSystemLibrary': + merageBeanDataSplit.hideSystemLibrary(this.allProcess, this.splitMapData); + break; + case 'hideNumMaxAndMin': + merageBeanDataSplit.hideNumMaxAndMin(this.allProcess, this.splitMapData, args[0], args[1]); + break; + case 'hideThread': + this.isHideThread = args[0]; + break; + case 'hideEvent': + this.isHideEvent = args[0]; + break; + case 'splitAllProcess': + merageBeanDataSplit.splitAllProcess(this.allProcess, this.splitMapData, args[0]); + break; + case 'resetAllNode': + merageBeanDataSplit.resetAllNode(this.allProcess, this.currentTreeList, this.searchValue); + break; + case 'resotreAllNode': + merageBeanDataSplit.resotreAllNode(this.splitMapData, args[0]); + break; + case 'clearSplitMapData': + this.clearSplitMapData(args[0]); + break; + case 'splitTree': + let map = this.splitMapData; + let list = this.currentTreeList; + merageBeanDataSplit.splitTree(map, this.allProcess, args[0], args[1], args[2], list, this.searchValue); + break; + case 'setSearchValue': + this.searchValue = args[0]; + break; + } + } + private getCurrentDataFromDb(args: Array): void { + if (args[1]) { + let sql = this.setSQLCondition(args[1]); + this.queryCallChainsSamples(args[0], sql); + } else { + this.queryCallChainsSamples(args[0]); + } + } + private setSQLCondition(funcArgs: any): string { + let sql = ''; + if (funcArgs.processId !== undefined) { + sql += `and p.pid = ${funcArgs.processId}`; + } + if (funcArgs.typeId !== undefined) { + sql += ` and s.type = ${funcArgs.typeId}`; + } + if (funcArgs.threadId !== undefined) { + sql += ` and h.tid = ${funcArgs.threadId}`; + } + return sql; + } clearAll() { this.samplesList = []; this.splitMapData = {}; diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts index 1478332ce78e59e83b9f1603e27bd768f7061729..2732626a5dd7dd883aa8e0188c4e52a760c6138b 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerNativeNemory.ts @@ -42,7 +42,7 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { isStatistic: boolean = false; boxRangeNativeHook: Array = []; clearBoxSelectionData: boolean = false; - nativeMemoryArgs?: Map; + nmArgs?: Map; private dataCache = DataCache.getInstance(); isHideThread: boolean = false; private currentSelectIPid: number = 1; @@ -52,153 +52,34 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { if (data && data.type) { switch (data.type) { case 'native-memory-init': - this.clearAll(); - if (data.params.isRealtime) { - this.realTimeDif = data.params.realTimeDif; - } - this.initNMFrameData(); + this.nmInit(data.params); break; case 'native-memory-queryNMFrameData': - let arr = convertJSON(data.params.list) || []; - this.initNMStack(arr); - arr = []; - self.postMessage({ - id: data.id, - action: 'native-memory-init', - results: [], - }); + this.nmQueryNMFrameData(data); break; case 'native-memory-queryCallchainsSamples': - this.searchValue = ''; - if (data.params.list) { - let callchainsSamples = convertJSON(data.params.list) || []; - this.queryAllCallchainsSamples = callchainsSamples; - this.freshCurrentCallchains(callchainsSamples, true); - // @ts-ignore - self.postMessage({ - id: data.id, - action: data.action, - results: this.allThreads, - }); - } else { - this.queryCallchainsSamples( - 'native-memory-queryCallchainsSamples', - data.params.leftNs, - data.params.rightNs, - data.params.types - ); - } + this.nmQueryCallchainsSamples(data); break; case 'native-memory-queryStatisticCallchainsSamples': - this.searchValue = ''; - if (data.params.list) { - let samples = convertJSON(data.params.list) || []; - this.queryAllCallchainsSamples = samples; - this.freshCurrentCallchains(samples, true); - // @ts-ignore - self.postMessage({ - id: data.id, - action: data.action, - results: this.allThreads, - }); - } else { - this.queryStatisticCallchainsSamples( - 'native-memory-queryStatisticCallchainsSamples', - data.params.leftNs, - data.params.rightNs, - data.params.types - ); - } + this.nmQueryStatisticCallchainsSamples(data); break; case 'native-memory-queryAnalysis': - if (data.params.list) { - let samples = convertJSON(data.params.list) || []; - this.queryAllCallchainsSamples = samples; - self.postMessage({ - id: data.id, - action: data.action, - results: this.combineStatisticAndCallChain(samples), - }); - } else { - if (data.params.isStatistic) { - this.isStatistic = true; - this.queryStatisticCallchainsSamples( - 'native-memory-queryAnalysis', - data.params.leftNs, - data.params.rightNs, - data.params.types - ); - } else { - this.isStatistic = false; - this.queryCallchainsSamples( - 'native-memory-queryAnalysis', - data.params.leftNs, - data.params.rightNs, - data.params.types - ); - } - } + this.nmQueryAnalysis(data); break; case 'native-memory-queryNativeHookEvent': - if (data.params) { - if (data.params.list) { - this.boxRangeNativeHook = convertJSON(data.params.list); - if (this.nativeMemoryArgs?.get('refresh')) { - this.clearBoxSelectionData = this.boxRangeNativeHook.length > 100_0000; - } - this.supplementNativeHoodData(); - postMessage(data.id, data.action, this.resolvingActionNativeMemory(this.nativeMemoryArgs!), 50_0000); - if (this.clearBoxSelectionData) { - this.boxRangeNativeHook = []; - } - } else if (data.params.get('refresh') || this.boxRangeNativeHook.length === 0) { - this.nativeMemoryArgs = data.params; - let leftNs = data.params.get('leftNs'); - let rightNs = data.params.get('rightNs'); - let types = data.params.get('types'); - this.boxRangeNativeHook = []; - this.queryNativeHookEvent(leftNs, rightNs, types); - } else { - this.nativeMemoryArgs = data.params; - postMessage(data.id, data.action, this.resolvingActionNativeMemory(this.nativeMemoryArgs!), 50_0000); - if (this.clearBoxSelectionData) { - this.boxRangeNativeHook = []; - } - } - } + this.nmQueryNativeHookEvent(data); break; case 'native-memory-action': - if (data.params) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.resolvingAction(data.params), - }); - } + this.nmAction(data); break; case 'native-memory-calltree-action': - if (data.params) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.resolvingNMCallAction(data.params), - }); - } + this.nmCalltreeAction(data); break; case 'native-memory-init-responseType': - this.initResponseTypeList(data.params); - self.postMessage({ - id: data.id, - action: data.action, - results: [], - }); + this.nmInitResponseType(data); break; case 'native-memory-get-responseType': - self.postMessage({ - id: data.id, - action: data.action, - results: this.responseTypes, - }); + this.nmGetResponseType(data); break; case 'native-memory-reset': this.isHideThread = false; @@ -208,15 +89,163 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { } } } - + private nmInit(params: any): void { + this.clearAll(); + if (params.isRealtime) { + this.realTimeDif = params.realTimeDif; + } + this.initNMFrameData(); + } + private nmQueryNMFrameData(data: any): void { + let arr = convertJSON(data.params.list) || []; + this.initNMStack(arr); + arr = []; + self.postMessage({ + id: data.id, + action: 'native-memory-init', + results: [], + }); + } + private nmQueryCallchainsSamples(data: any): void { + this.searchValue = ''; + if (data.params.list) { + let callchainsSamples = convertJSON(data.params.list) || []; + this.queryAllCallchainsSamples = callchainsSamples; + this.freshCurrentCallchains(callchainsSamples, true); + // @ts-ignore + self.postMessage({ + id: data.id, + action: data.action, + results: this.allThreads, + }); + } else { + this.queryCallchainsSamples( + 'native-memory-queryCallchainsSamples', + data.params.leftNs, + data.params.rightNs, + data.params.types + ); + } + } + private nmQueryStatisticCallchainsSamples(data: any): void { + this.searchValue = ''; + if (data.params.list) { + let samples = convertJSON(data.params.list) || []; + this.queryAllCallchainsSamples = samples; + this.freshCurrentCallchains(samples, true); + // @ts-ignore + self.postMessage({ + id: data.id, + action: data.action, + results: this.allThreads, + }); + } else { + this.queryStatisticCallchainsSamples( + 'native-memory-queryStatisticCallchainsSamples', + data.params.leftNs, + data.params.rightNs, + data.params.types + ); + } + } + private nmQueryAnalysis(data: any): void { + if (data.params.list) { + let samples = convertJSON(data.params.list) || []; + this.queryAllCallchainsSamples = samples; + self.postMessage({ + id: data.id, + action: data.action, + results: this.combineStatisticAndCallChain(samples), + }); + } else { + if (data.params.isStatistic) { + this.isStatistic = true; + this.queryStatisticCallchainsSamples( + 'native-memory-queryAnalysis', + data.params.leftNs, + data.params.rightNs, + data.params.types + ); + } else { + this.isStatistic = false; + this.queryCallchainsSamples( + 'native-memory-queryAnalysis', + data.params.leftNs, + data.params.rightNs, + data.params.types + ); + } + } + } + private nmQueryNativeHookEvent(data: any): void { + if (data.params) { + if (data.params.list) { + this.boxRangeNativeHook = convertJSON(data.params.list); + if (this.nmArgs?.get('refresh')) { + this.clearBoxSelectionData = this.boxRangeNativeHook.length > 100_0000; + } + this.supplementNativeHoodData(); + postMessage(data.id, data.action, this.resolvingActionNativeMemory(this.nmArgs!), 50_0000); + if (this.clearBoxSelectionData) { + this.boxRangeNativeHook = []; + } + } else if (data.params.get('refresh') || this.boxRangeNativeHook.length === 0) { + this.nmArgs = data.params; + let leftNs = data.params.get('leftNs'); + let rightNs = data.params.get('rightNs'); + let types = data.params.get('types'); + this.boxRangeNativeHook = []; + this.queryNativeHookEvent(leftNs, rightNs, types); + } else { + this.nmArgs = data.params; + postMessage(data.id, data.action, this.resolvingActionNativeMemory(this.nmArgs!), 50_0000); + if (this.clearBoxSelectionData) { + this.boxRangeNativeHook = []; + } + } + } + } + private nmAction(data: any): void { + if (data.params) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.resolvingAction(data.params), + }); + } + } + private nmCalltreeAction(data: any): void { + if (data.params) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.resolvingNMCallAction(data.params), + }); + } + } + private nmInitResponseType(data: any): void { + this.initResponseTypeList(data.params); + self.postMessage({ + id: data.id, + action: data.action, + results: [], + }); + } + private nmGetResponseType(data: any): void { + self.postMessage({ + id: data.id, + action: data.action, + results: this.responseTypes, + }); + } queryNativeHookEvent(leftNs: number, rightNs: number, types: Array): void { 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'); + let libId = this.nmArgs?.get('filterResponseType'); + let allocType = this.nmArgs?.get('filterAllocType'); + let eventType = this.nmArgs?.get('filterEventType'); if (libId !== undefined && libId !== -1) { condition = `${condition} and last_lib_id = ${libId}`; // filter lib } @@ -529,7 +558,7 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { this.currentTreeList.length = 0; this.responseTypes.length = 0; this.boxRangeNativeHook = []; - this.nativeMemoryArgs?.clear(); + this.nmArgs?.clear(); this.isHideThread = false; } @@ -607,29 +636,13 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { const analysisSampleList: Array = []; const applyAllocSamples: Array = []; const applyMmapSamples: Array = []; - for (const sample of samples) { const count = this.isStatistic ? sample.count : 1; const analysisSample = new AnalysisSample(sample.id, sample.heapSize, count, sample.eventType, sample.startTs); - if (this.isStatistic) { - analysisSample.releaseCount = sample.freeCount; - analysisSample.releaseSize = sample.freeSize; - switch (sample.subTypeId) { - case 1: - analysisSample.subType = 'MmapEvent'; - break; - case 2: - analysisSample.subType = 'FILE_PAGE_MSG'; - break; - case 3: - analysisSample.subType = 'MEMORY_USING_MSG'; - break; - default: - analysisSample.subType = this.dataCache.dataDict.get(sample.subTypeId); - } + this.setStatisticSubType(analysisSample, sample); } else { - let subType = undefined; + let subType: string | undefined; if (sample.subTypeId) { subType = this.dataCache.dataDict.get(sample.subTypeId); } @@ -639,7 +652,6 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { analysisSample.threadName = sample.threadName; analysisSample.subType = subType; } - if (['FreeEvent', 'MunmapEvent'].includes(sample.eventType)) { if (sample.eventType === 'FreeEvent') { this.setApplyIsRelease(analysisSample, applyAllocSamples); @@ -654,23 +666,45 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { applyMmapSamples.push(analysisSample); } } - - const filePath = this.dataCache.dataDict.get(sample.lastLibId)!; - let libName = ''; - if (filePath) { - const path = filePath.split('/'); - libName = path[path.length - 1]; - } - const symbolName = this.dataCache.dataDict.get(sample.lastSymbolId) || libName + ' (' + sample.addr + ')'; - analysisSample.libId = sample.lastLibId || -1; - analysisSample.libName = libName || 'Unknown'; - analysisSample.symbolId = sample.lastSymbolId || -1; - analysisSample.symbolName = symbolName || 'Unknown';; - analysisSampleList.push(analysisSample); + let s = this.setAnalysisSampleArgs(analysisSample, sample); + analysisSampleList.push(s); } return analysisSampleList; } + private setStatisticSubType(analysisSample: AnalysisSample, sample: NativeHookStatistics): void { + analysisSample.releaseCount = sample.freeCount; + analysisSample.releaseSize = sample.freeSize; + switch (sample.subTypeId) { + case 1: + analysisSample.subType = 'MmapEvent'; + break; + case 2: + analysisSample.subType = 'FILE_PAGE_MSG'; + break; + case 3: + analysisSample.subType = 'MEMORY_USING_MSG'; + break; + default: + analysisSample.subType = this.dataCache.dataDict.get(sample.subTypeId); + } + } + + private setAnalysisSampleArgs(analysisSample: AnalysisSample, sample: NativeHookStatistics): AnalysisSample { + const filePath = this.dataCache.dataDict.get(sample.lastLibId)!; + let libName = ''; + if (filePath) { + const path = filePath.split('/'); + libName = path[path.length - 1]; + } + const symbolName = this.dataCache.dataDict.get(sample.lastSymbolId) || libName + ' (' + sample.addr + ')'; + analysisSample.libId = sample.lastLibId || -1; + analysisSample.libName = libName || 'Unknown'; + analysisSample.symbolId = sample.lastSymbolId || -1; + analysisSample.symbolName = symbolName || 'Unknown'; + return analysisSample; + } + setApplyIsRelease(sample: AnalysisSample, arr: Array): void { let idx = arr.length - 1; for (idx; idx >= 0; idx--) { @@ -683,7 +717,7 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { } } - freshCurrentCallchains(samples: NativeHookStatistics[], isTopDown: boolean): void { + private freshCurrentCallchains(samples: NativeHookStatistics[], isTopDown: boolean): void { this.currentTreeMapData = {}; this.currentTreeList = []; let totalSize = 0; @@ -721,6 +755,11 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { } } }); + let rootMerageMap = this.mergeNodeData(totalCount, totalSize); + this.handleCurrentTreeList(totalCount, totalSize); + this.allThreads = Object.values(rootMerageMap) as NativeHookCallInfo[]; + } + private mergeNodeData(totalCount: number, totalSize: number): Map { let rootMerageMap: any = {}; // @ts-ignore let threads = Object.values(this.currentTreeMapData); @@ -761,6 +800,9 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { } merageData.parentNode = rootMerageMap[merageData.tid]; //子节点添加父节点的引用 }); + return rootMerageMap; + } + private handleCurrentTreeList(totalCount: number, totalSize: number): void { let id = 0; this.currentTreeList.forEach((nmTreeNode: any): void => { nmTreeNode.totalCount = totalCount; @@ -778,11 +820,8 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { nmTreeNode.parentId = nmTreeNode.parentNode.id; } }); - this.allThreads = Object.values(rootMerageMap) as NativeHookCallInfo[]; } - - groupCallchainSample(paramMap: Map): void { - let groupMap: any = {}; + private groupCallchainSample(paramMap: Map): void { let filterAllocType = paramMap.get('filterAllocType'); let filterEventType = paramMap.get('filterEventType'); let filterResponseType = paramMap.get('filterResponseType'); @@ -804,22 +843,35 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { this.currentSamples = this.queryAllCallchainsSamples; return; } - let filter = this.queryAllCallchainsSamples.filter((item: NativeHookStatistics): boolean => { + let filter = this.dataFilter( + libTree, + filterAnalysis, + filterAllocType, + leftNs, + rightNs, + nativeHookType, + filterResponseType, + filterEventType, + statisticsSelection + ); + let groupMap = this.setGroupMap(filter, filterAllocType, nativeHookType); + this.currentSamples = Object.values(groupMap); + } + private dataFilter( + libTree: any, + filterAnalysis: any, + filterAllocType: string, + leftNs: number, + rightNs: number, + nativeHookType: string, + filterResponseType: number, + filterEventType: string, + statisticsSelection: StatisticsSelection[] + ): NativeHookStatistics[] { + return this.queryAllCallchainsSamples.filter((item: NativeHookStatistics): boolean => { let filterAllocation = true; if (nativeHookType === 'native-hook') { - if (filterAllocType === '1') { - filterAllocation = - item.startTs >= leftNs && - item.startTs <= rightNs && - (item.endTs > rightNs || item.endTs === 0 || item.endTs === null); - } else if (filterAllocType === '2') { - filterAllocation = - item.startTs >= leftNs && - item.startTs <= rightNs && - item.endTs <= rightNs && - item.endTs != 0 && - item.endTs != null; - } + filterAllocation = this.setFilterAllocation(item, filterAllocType, filterAllocation, leftNs, rightNs); } else { if (filterAllocType === '1') { filterAllocation = item.heapSize > item.freeSize; @@ -827,12 +879,10 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { filterAllocation = item.heapSize === item.freeSize; } } - let filterThread = true; if (filterAnalysis && filterAnalysis.tid) { filterThread = item.tid === filterAnalysis.tid; } - let filterLastLib = true; if (libTree) { filterLastLib = this.filterExpressionSample(item, libTree); @@ -840,16 +890,38 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { } else { filterLastLib = filterResponseType === -1 ? true : filterResponseType === item.lastLibId; } - let filterFunction = true; if (filterAnalysis && filterAnalysis.symbolId) { filterFunction = filterAnalysis.symbolId === item.lastSymbolId; } - let filterNative = this.getTypeFromIndex(parseInt(filterEventType), item, statisticsSelection); - return filterAllocation && filterNative && filterLastLib && filterThread && filterFunction; }); + } + private setFilterAllocation( + item: any, + filterAllocType: string, + filterAllocation: boolean, + leftNs: number, + rightNs: number + ): boolean { + if (filterAllocType === '1') { + filterAllocation = + item.startTs >= leftNs && + item.startTs <= rightNs && + (item.endTs > rightNs || item.endTs === 0 || item.endTs === null); + } else if (filterAllocType === '2') { + filterAllocation = + item.startTs >= leftNs && + item.startTs <= rightNs && + item.endTs <= rightNs && + item.endTs != 0 && + item.endTs != null; + } + return filterAllocation; + } + private setGroupMap(filter: Array, filterAllocType: string, nativeHookType: string): Map { + let groupMap: any = {}; filter.forEach((sample: NativeHookStatistics): void => { let currentNode = groupMap[sample.tid + '-' + sample.eventId] || new NativeHookStatistics(); if (currentNode.count === 0) { @@ -871,8 +943,7 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { } groupMap[sample.tid + '-' + sample.eventId] = currentNode; }); - // @ts-ignore - this.currentSamples = Object.values(groupMap); + return groupMap; } private filterExpressionSample(sample: NativeHookStatistics, expressStruct: NativeMemoryExpression): boolean { @@ -981,55 +1052,10 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { resolvingNMCallAction(params: any[]): NativeHookCallInfo[] { if (params.length > 0) { params.forEach((item: any): void => { - if (item.funcName && item.funcArgs) { - switch (item.funcName) { - case 'hideThread': - this.isHideThread = item.funcArgs[0]; - break; - case 'groupCallchainSample': - this.groupCallchainSample(item.funcArgs[0] as Map); - break; - case 'getCallChainsBySampleIds': - this.freshCurrentCallchains(this.currentSamples, item.funcArgs[0]); - break; - case 'hideSystemLibrary': - merageBeanDataSplit.hideSystemLibrary(this.allThreads, this.splitMapData); - break; - case 'hideNumMaxAndMin': - merageBeanDataSplit.hideNumMaxAndMin( - this.allThreads, - this.splitMapData, - item.funcArgs[0], - item.funcArgs[1] - ); - break; - case 'splitAllProcess': - merageBeanDataSplit.splitAllProcess(this.allThreads, this.splitMapData, item.funcArgs[0]); - break; - case 'resetAllNode': - merageBeanDataSplit.resetAllNode(this.allThreads, this.currentTreeList, this.searchValue); - break; - case 'resotreAllNode': - merageBeanDataSplit.resotreAllNode(this.splitMapData, item.funcArgs[0]); - break; - case 'splitTree': - merageBeanDataSplit.splitTree( - this.splitMapData, - this.allThreads, - item.funcArgs[0], - item.funcArgs[1], - item.funcArgs[2], - this.currentTreeList, - this.searchValue - ); - break; - case 'setSearchValue': - this.searchValue = item.funcArgs[0]; - break; - case 'clearSplitMapData': - this.clearSplitMapData(item.funcArgs[0]); - break; - } + let funcName = item.funcName; + let args = item.funcArgs; + if (funcName && args) { + this.handleDataByFuncName(funcName, args); } }); } @@ -1037,6 +1063,51 @@ export class ProcedureLogicWorkerNativeMemory extends LogicHandler { return thread.children && thread.children.length > 0; }); } + handleDataByFuncName(funcName: any, args: any): void { + switch (funcName) { + case 'hideThread': + this.isHideThread = args[0]; + break; + case 'groupCallchainSample': + this.groupCallchainSample(args[0] as Map); + break; + case 'getCallChainsBySampleIds': + this.freshCurrentCallchains(this.currentSamples, args[0]); + break; + case 'hideSystemLibrary': + merageBeanDataSplit.hideSystemLibrary(this.allThreads, this.splitMapData); + break; + case 'hideNumMaxAndMin': + merageBeanDataSplit.hideNumMaxAndMin(this.allThreads, this.splitMapData, args[0], args[1]); + break; + case 'splitAllProcess': + merageBeanDataSplit.splitAllProcess(this.allThreads, this.splitMapData, args[0]); + break; + case 'resetAllNode': + merageBeanDataSplit.resetAllNode(this.allThreads, this.currentTreeList, this.searchValue); + break; + case 'resotreAllNode': + merageBeanDataSplit.resotreAllNode(this.splitMapData, args[0]); + break; + case 'splitTree': + merageBeanDataSplit.splitTree( + this.splitMapData, + this.allThreads, + args[0], + args[1], + args[2], + this.currentTreeList, + this.searchValue + ); + break; + case 'setSearchValue': + this.searchValue = args[0]; + break; + case 'clearSplitMapData': + this.clearSplitMapData(args[0]); + break; + } + } } export class NativeHookStatistics { diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts index 6beb4bf3156b37109f173dcd95cd0c4a9fcef0bf..30e3f374c27be519516c623a3b4999697b3159e0 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerPerf.ts @@ -15,7 +15,6 @@ import { LogicHandler, ChartStruct, convertJSON, DataCache, HiPerfSymbol } from './ProcedureLogicWorkerCommon'; import { PerfBottomUpStruct } from '../../bean/PerfBottomUpStruct'; -import { HiPerfChartFrame } from '../../bean/PerfStruct'; const systemRuleName: string = '/system/'; const numRuleName: string = '/max/min/'; @@ -52,164 +51,190 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { this.initPerfFiles(); break; case 'perf-queryPerfFiles': - let files = convertJSON(data.params.list) || []; - files.forEach((file: any) => { - this.filesData[file.fileId] = this.filesData[file.fileId] || []; - PerfFile.setFileName(file); - this.filesData[file.fileId].push(file); - }); - this.initPerfThreads(); + this.perfQueryPerfFiles(data.params.list); break; case 'perf-queryPerfThread': - let threads = convertJSON(data.params.list) || []; - threads.forEach((thread: any): void => { - this.threadData[thread.tid] = thread; - }); - this.initPerfCalls(); + this.perfQueryPerfThread(data.params.list); break; case 'perf-queryPerfCalls': - let perfCalls = convertJSON(data.params.list) || []; - if (perfCalls.length !== 0) { - perfCalls.forEach((perfCall: any): void => { - this.dataCache.perfCallChainMap.set(perfCall.sampleId, perfCall); - }); - } - this.initPerfCallchains(); + this.perfQueryPerfCalls(data.params.list); break; case 'perf-queryPerfCallchains': - let arr = convertJSON(data.params.list) || []; - this.initPerfCallChainTopDown(arr); - // @ts-ignore - self.postMessage({ - id: data.id, - action: data.action, - results: this.dataCache.perfCallChainMap, - }); + this.perfQueryPerfCallchains(data); break; case 'perf-queryCallchainsGroupSample': - this.samplesData = convertJSON(data.params.list) || []; - let result; - if (this.isAnalysis) { - result = this.resolvingAction([ - { - funcName: 'combineAnalysisCallChain', - funcArgs: [true], - }, - ]); - } else if (this.isPerfBottomUp) { - result = this.resolvingAction([ - { - funcName: 'getBottomUp', - funcArgs: [true], - }, - ]); - } else { - if (this.lib) { - let libData = this.combineCallChainForAnalysis(this.lib); - this.freshPerfCallchains(libData, this.isTopDown); - result = this.allProcess; - this.lib = undefined; - } else if (this.symbol) { - let funData = this.combineCallChainForAnalysis(this.symbol); - this.freshPerfCallchains(funData, this.isTopDown); - result = this.allProcess; - this.symbol = undefined; - } else { - result = this.resolvingAction([ - { - funcName: 'getCallChainsBySampleIds', - funcArgs: [this.isTopDown], - }, - ]); - } - } - self.postMessage({ - id: data.id, - action: data.action, - results: result, - }); + this.perfQueryCallchainsGroupSample(data); break; case 'perf-action': - if (data.params) { - let filter = data.params.filter((item: any): boolean => item.funcName === 'getCurrentDataFromDb'); - // 从lib层跳转 - let libFilter = data.params.filter((item: any): boolean => item.funcName === 'showLibLevelData'); - // 从fun层跳转 - let funFilter = data.params.filter((item: any): boolean => item.funcName === 'showFunLevelData'); - // lib或者fun层Invert - let callChainsFilter = data.params.filter( - (item: any): boolean => item.funcName === 'getCallChainsBySampleIds' - ); - let isHideSystemSoFilter = data.params.filter( - (item: any): boolean => item.funcName === 'hideSystemLibrary' - ); - let hideThreadFilter = data.params.filter((item: any): boolean => item.funcName === 'hideThread'); - let hideThreadStateFilter = data.params.filter((item: any): boolean => item.funcName === 'hideThreadState'); - let result; - callChainsFilter.length > 0 ? (this.isTopDown = callChainsFilter[0].funcArgs[0]) : (this.isTopDown = true); - if (libFilter.length !== 0) { - this.lib = { - libId: libFilter[0].funcArgs[0], - libName: libFilter[0].funcArgs[1], - }; - } else if (funFilter.length !== 0) { - this.symbol = { - symbolId: funFilter[0].funcArgs[0], - symbolName: funFilter[0].funcArgs[1], - }; - } - - if (filter.length === 0) { - if (this.lib) { - if ( - callChainsFilter.length > 0 || - isHideSystemSoFilter.length > 0 || - hideThreadFilter.length > 0 || - hideThreadStateFilter.length > 0 - ) { - this.samplesData = this.combineCallChainForAnalysis(this.lib); - result = this.resolvingAction(data.params); - } else { - let libData = this.combineCallChainForAnalysis(this.lib); - this.freshPerfCallchains(libData, this.isTopDown); - result = this.allProcess; - this.lib = undefined; - } - } else if (this.symbol) { - if ( - callChainsFilter.length > 0 || - isHideSystemSoFilter.length > 0 || - hideThreadFilter.length > 0 || - hideThreadStateFilter.length > 0 - ) { - this.samplesData = this.combineCallChainForAnalysis(this.symbol); - result = this.resolvingAction(data.params); - } else { - let funData = this.combineCallChainForAnalysis(this.symbol); - this.freshPerfCallchains(funData, this.isTopDown); - result = this.allProcess; - this.symbol = undefined; - } - } else { - result = this.resolvingAction(data.params); - } - self.postMessage({ - id: data.id, - action: data.action, - results: result, - }); - } else { - this.resolvingAction(data.params); - } - } + this.perfAction(data); break; case 'perf-reset': - this.isHideThread = false; - this.isHideThreadState = false; + this.perfReset(); } } } - + private perfQueryPerfFiles(list: Array): void { + let files = convertJSON(list) || []; + files.forEach((file: any) => { + this.filesData[file.fileId] = this.filesData[file.fileId] || []; + PerfFile.setFileName(file); + this.filesData[file.fileId].push(file); + }); + this.initPerfThreads(); + } + private perfQueryPerfThread(list: Array): void { + let threads = convertJSON(list) || []; + threads.forEach((thread: any): void => { + this.threadData[thread.tid] = thread; + }); + this.initPerfCalls(); + } + private perfQueryPerfCalls(list: Array): void { + let perfCalls = convertJSON(list) || []; + if (perfCalls.length !== 0) { + perfCalls.forEach((perfCall: any): void => { + this.dataCache.perfCallChainMap.set(perfCall.sampleId, perfCall); + }); + } + this.initPerfCallchains(); + } + private perfQueryPerfCallchains(data: any): void { + let arr = convertJSON(data.params.list) || []; + this.initPerfCallChainTopDown(arr); + // @ts-ignore + self.postMessage({ + id: data.id, + action: data.action, + results: this.dataCache.perfCallChainMap, + }); + } + private perfQueryCallchainsGroupSample(data: any): void { + this.samplesData = convertJSON(data.params.list) || []; + let result; + if (this.isAnalysis) { + result = this.resolvingAction([ + { + funcName: 'combineAnalysisCallChain', + funcArgs: [true], + }, + ]); + } else if (this.isPerfBottomUp) { + result = this.resolvingAction([ + { + funcName: 'getBottomUp', + funcArgs: [true], + }, + ]); + } else { + if (this.lib) { + let libData = this.combineCallChainForAnalysis(this.lib); + this.freshPerfCallchains(libData, this.isTopDown); + result = this.allProcess; + this.lib = undefined; + } else if (this.symbol) { + let funData = this.combineCallChainForAnalysis(this.symbol); + this.freshPerfCallchains(funData, this.isTopDown); + result = this.allProcess; + this.symbol = undefined; + } else { + result = this.resolvingAction([ + { + funcName: 'getCallChainsBySampleIds', + funcArgs: [this.isTopDown], + }, + ]); + } + } + self.postMessage({ + id: data.id, + action: data.action, + results: result, + }); + if (this.isAnalysis) { + this.isAnalysis = false; + } + } + private perfAction(data: any): void { + if (data.params) { + let filter = data.params.filter((item: any): boolean => item.funcName === 'getCurrentDataFromDb'); + let libFilter = data.params.filter((item: any): boolean => item.funcName === 'showLibLevelData'); + let funFilter = data.params.filter((item: any): boolean => item.funcName === 'showFunLevelData'); + if (libFilter.length !== 0) { + this.setLib(libFilter); + } + if (funFilter.length !== 0) { + this.setSymbol(funFilter); + } + let result = this.calReturnData(data.params); + if (filter.length === 0) { + self.postMessage({ + id: data.id, + action: data.action, + results: result, + }); + } else { + this.resolvingAction(data.params); + } + } + } + private perfReset(): void { + this.isHideThread = false; + this.isHideThreadState = false; + } + private setLib(libFilter: any): void { + this.lib = { + libId: libFilter[0].funcArgs[0], + libName: libFilter[0].funcArgs[1], + }; + } + private setSymbol(funFilter: any): void { + this.symbol = { + symbolId: funFilter[0].funcArgs[0], + symbolName: funFilter[0].funcArgs[1], + }; + } + private calReturnData(params: any): Array { + let result; + let callChainsFilter = params.filter((item: any): boolean => item.funcName === 'getCallChainsBySampleIds'); + callChainsFilter.length > 0 ? (this.isTopDown = callChainsFilter[0].funcArgs[0]) : (this.isTopDown = true); + let isHideSystemSoFilter = params.filter((item: any): boolean => item.funcName === 'hideSystemLibrary'); + let hideThreadFilter = params.filter((item: any): boolean => item.funcName === 'hideThread'); + let hideThreadStateFilter = params.filter((item: any): boolean => item.funcName === 'hideThreadState'); + if (this.lib) { + if ( + callChainsFilter.length > 0 || + isHideSystemSoFilter.length > 0 || + hideThreadFilter.length > 0 || + hideThreadStateFilter.length > 0 + ) { + this.samplesData = this.combineCallChainForAnalysis(this.lib); + result = this.resolvingAction(params); + } else { + let libData = this.combineCallChainForAnalysis(this.lib); + this.freshPerfCallchains(libData, this.isTopDown); + result = this.allProcess; + this.lib = undefined; + } + } else if (this.symbol) { + if ( + callChainsFilter.length > 0 || + isHideSystemSoFilter.length > 0 || + hideThreadFilter.length > 0 || + hideThreadStateFilter.length > 0 + ) { + this.samplesData = this.combineCallChainForAnalysis(this.symbol); + result = this.resolvingAction(params); + } else { + let funData = this.combineCallChainForAnalysis(this.symbol); + this.freshPerfCallchains(funData, this.isTopDown); + result = this.allProcess; + this.symbol = undefined; + } + } else { + result = this.resolvingAction(params); + } + return result; + } initPerfFiles(): void { this.clearAll(); this.queryData( @@ -259,35 +284,13 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { {} ); } - /** * * @param selectionParam * @param sql 从饼图进程或者线程层点击进入Perf Profile时传入 */ private getCurrentDataFromDb(selectionParam: any, sql?: string): void { - let filterSql = ''; - if (sql) { - const cpus = selectionParam.perfAll ? [] : selectionParam.perfCpus; - const cpuFilter = cpus.length > 0 ? ` and s.cpu_id in (${cpus.join(',')}) ` : ''; - let arg = `${sql}${cpuFilter}`.substring(3); - filterSql = `and ${arg}`; - } else { - const cpus = selectionParam.perfAll ? [] : selectionParam.perfCpus; - const processes = selectionParam.perfAll ? [] : selectionParam.perfProcess; - const threads = selectionParam.perfAll ? [] : selectionParam.perfThread; - - if (cpus.length !== 0 || processes.length !== 0 || threads.length !== 0) { - const cpuFilter = cpus.length > 0 ? `or s.cpu_id in (${cpus.join(',')}) ` : ''; - const processFilter = processes.length > 0 ? `or thread.process_id in (${processes.join(',')}) ` : ''; - const threadFilter = threads.length > 0 ? `or s.thread_id in (${threads.join(',')})` : ''; - let arg = `${cpuFilter}${processFilter}${threadFilter}`.substring(3); - filterSql = ` and (${arg})`; - } - } - let eventTypeId = selectionParam.perfEventTypeId; - const eventTypeFilter = eventTypeId !== undefined ? ` and s.event_type_id = ${eventTypeId}` : ''; - filterSql += eventTypeFilter; + let filterSql = this.setFilterSql(selectionParam, sql); this.queryData( this.currentEventId, 'perf-queryCallchainsGroupSample', @@ -299,17 +302,16 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { p.event_count as eventCount, p.ts as ts, p.event_type_id as eventTypeId - from ( - select callchain_id, s.thread_id, s.event_type_id, thread_state, process_id, + from (select callchain_id, s.thread_id, s.event_type_id, thread_state, process_id, count(callchain_id) as count,SUM(event_count) as event_count, group_concat(s.timestamp_trace - t.start_ts,',') as ts - from perf_sample s, trace_range t - left join perf_thread thread on s.thread_id = thread.thread_id - where timestamp_trace between ${selectionParam.leftNs} + t.start_ts + from perf_sample s, trace_range t + left join perf_thread thread on s.thread_id = thread.thread_id + where timestamp_trace between ${selectionParam.leftNs} + t.start_ts and ${selectionParam.rightNs} + t.start_ts and callchain_id != -1 and s.thread_id != 0 ${filterSql} - group by callchain_id, s.thread_id, thread_state, process_id) p`, + group by callchain_id, s.thread_id, thread_state, process_id) p`, { $startTime: selectionParam.leftNs, $endTime: selectionParam.rightNs, @@ -317,6 +319,30 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { } ); } + private setFilterSql(selectionParam: any, sql?: string): string { + let filterSql = ''; + if (sql) { + const cpus = selectionParam.perfAll ? [] : selectionParam.perfCpus; + const cpuFilter = cpus.length > 0 ? ` and s.cpu_id in (${cpus.join(',')}) ` : ''; + let arg = `${sql}${cpuFilter}`.substring(3); + filterSql = `and ${arg}`; + } else { + const cpus = selectionParam.perfAll ? [] : selectionParam.perfCpus; + const processes = selectionParam.perfAll ? [] : selectionParam.perfProcess; + const threads = selectionParam.perfAll ? [] : selectionParam.perfThread; + if (cpus.length !== 0 || processes.length !== 0 || threads.length !== 0) { + const cpuFilter = cpus.length > 0 ? `or s.cpu_id in (${cpus.join(',')}) ` : ''; + const processFilter = processes.length > 0 ? `or thread.process_id in (${processes.join(',')}) ` : ''; + const threadFilter = threads.length > 0 ? `or s.thread_id in (${threads.join(',')})` : ''; + let arg = `${cpuFilter}${processFilter}${threadFilter}`.substring(3); + filterSql = ` and (${arg})`; + } + } + let eventTypeId = selectionParam.perfEventTypeId; + const eventTypeFilter = eventTypeId !== undefined ? ` and s.event_type_id = ${eventTypeId}` : ''; + filterSql += eventTypeFilter; + return filterSql; + } clearAll(): void { this.filesData = {}; @@ -393,12 +419,11 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { } } - freshPerfCallchains(perfCountSamples: PerfCountSample[], isTopDown: boolean): void { + private freshPerfCallchains(perfCountSamples: PerfCountSample[], isTopDown: boolean): void { this.currentTreeMapData = {}; this.currentTreeList = []; let totalSamplesCount = 0; let totalEventCount = 0; - perfCountSamples.forEach((perfSample): void => { totalSamplesCount += perfSample.count; totalEventCount += perfSample.eventCount; @@ -414,12 +439,16 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { this.currentTreeMapData[symbolName + perfSample.pid] = perfRootNode; this.currentTreeList.push(perfRootNode); } - PerfCallChainMerageData.merageCallChainSample(perfRootNode, perfCallChains[topIndex], perfSample, false); this.mergeChildrenByIndex(perfRootNode, perfCallChains, topIndex, perfSample, isTopDown); } } }); + let rootMerageMap = this.mergeNodeData(totalEventCount, totalSamplesCount); + this.handleCurrentTreeList(totalEventCount, totalSamplesCount); + this.allProcess = Object.values(rootMerageMap); + } + private mergeNodeData(totalEventCount: number, totalSamplesCount: number): Map { let rootMerageMap: any = {}; // @ts-ignore Object.values(this.currentTreeMapData).forEach((merageData: any): void => { @@ -454,6 +483,9 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { } merageData.parentNode = rootMerageMap[merageData.pid]; //子节点添加父节点的引用 }); + return rootMerageMap; + } + private handleCurrentTreeList(totalEventCount: number, totalSamplesCount: number): void { let id = 0; this.currentTreeList.forEach((perfTreeNode: any): void => { perfTreeNode.total = totalSamplesCount; @@ -470,8 +502,6 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { perfTreeNode.parentId = perfTreeNode.parentNode.id; } }); - // @ts-ignore - this.allProcess = Object.values(rootMerageMap); } mergeChildrenByIndex( @@ -489,7 +519,7 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { let node: PerfCallChainMerageData; if ( currentNode.initChildren.filter((child: PerfCallChainMerageData): boolean => { - let name: number| string | undefined = callChainDataList[index].name; + let name: number | string | undefined = callChainDataList[index].name; if (typeof name === 'number') { name = this.dataCache.dataDict.get(name); } @@ -698,70 +728,13 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { } }); } - resolvingAction(params: any[]): PerfCallChainMerageData[] | PerfAnalysisSample[] | PerfBottomUpStruct[] { if (params.length > 0) { for (let item of params) { if (item.funcName && item.funcArgs) { - switch (item.funcName) { - case 'getCallChainsBySampleIds': - this.freshPerfCallchains(this.samplesData, item.funcArgs[0]); - break; - case 'getCurrentDataFromDb': - if (item.funcArgs[1]) { - let funcArgs = item.funcArgs[1]; - let sql = ''; - if (funcArgs.processId !== undefined) { - sql += `and thread.process_id = ${funcArgs.processId}`; - } - if (funcArgs.threadId !== undefined) { - sql += ` and s.thread_id = ${funcArgs.threadId}`; - } - this.getCurrentDataFromDb(item.funcArgs[0], sql); - } else { - this.getCurrentDataFromDb(item.funcArgs[0]); - } - break; - case 'hideSystemLibrary': - this.hideSystemLibrary(); - break; - case 'hideThread': - this.isHideThread = item.funcArgs[0]; - break; - case 'hideThreadState': - this.isHideThreadState = item.funcArgs[0]; - break; - case 'hideNumMaxAndMin': - this.hideNumMaxAndMin(item.funcArgs[0], item.funcArgs[1]); - break; - case 'splitAllProcess': - this.splitAllProcess(item.funcArgs[0]); - break; - case 'resetAllNode': - this.resetAllNode(this.allProcess); - break; - case 'resotreAllNode': - this.resetAllSymbol(item.funcArgs[0]); - break; - case 'clearSplitMapData': - this.clearSplitMapData(item.funcArgs[0]); - break; - case 'splitTree': - this.splitPerfTree(this.allProcess, item.funcArgs[0], item.funcArgs[1], item.funcArgs[2]); - break; - case 'setSearchValue': - this.searchValue = item.funcArgs[0]; - break; - case 'setCombineCallChain': - this.isAnalysis = true; - break; - case 'setPerfBottomUp': - this.isPerfBottomUp = true; - break; - case 'combineAnalysisCallChain': - return this.combineCallChainForAnalysis(); - case 'getBottomUp': - return this.getBottomUp(); + let result = this.handleDataByFuncName(item.funcName, item.funcArgs); + if (result) { + return result; } } } @@ -771,6 +744,70 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { } return this.dataSource; } + private queryDataFromDb(funcArgs: any): void { + if (funcArgs[1]) { + let sql = ''; + if (funcArgs[1].processId !== undefined) { + sql += `and thread.process_id = ${funcArgs[1].processId}`; + } + if (funcArgs[1].threadId !== undefined) { + sql += ` and s.thread_id = ${funcArgs[1].threadId}`; + } + this.getCurrentDataFromDb(funcArgs[0], sql); + } else { + this.getCurrentDataFromDb(funcArgs[0]); + } + } + private handleDataByFuncName(funcName: string, funcArgs: any): Array | undefined { + switch (funcName) { + case 'getCallChainsBySampleIds': + this.freshPerfCallchains(this.samplesData, funcArgs[0]); + break; + case 'getCurrentDataFromDb': + this.queryDataFromDb(funcArgs); + break; + case 'hideSystemLibrary': + this.hideSystemLibrary(); + break; + case 'hideThread': + this.isHideThread = funcArgs[0]; + break; + case 'hideThreadState': + this.isHideThreadState = funcArgs[0]; + break; + case 'hideNumMaxAndMin': + this.hideNumMaxAndMin(funcArgs[0], funcArgs[1]); + break; + case 'splitAllProcess': + this.splitAllProcess(funcArgs[0]); + break; + case 'resetAllNode': + this.resetAllNode(this.allProcess); + break; + case 'resotreAllNode': + this.resetAllSymbol(funcArgs[0]); + break; + case 'clearSplitMapData': + this.clearSplitMapData(funcArgs[0]); + break; + case 'splitTree': + this.splitPerfTree(this.allProcess, funcArgs[0], funcArgs[1], funcArgs[2]); + break; + case 'setSearchValue': + this.searchValue = funcArgs[0]; + break; + case 'setCombineCallChain': + this.isAnalysis = true; + break; + case 'setPerfBottomUp': + this.isPerfBottomUp = true; + break; + case 'combineAnalysisCallChain': + return this.combineCallChainForAnalysis(); + case 'getBottomUp': + return this.getBottomUp(); + } + } combineCallChainForAnalysis(obj?: any): PerfAnalysisSample[] { let sampleCallChainList: Array = []; @@ -802,9 +839,6 @@ export class ProcedureLogicWorkerPerf extends LogicHandler { sampleCallChainList.push(analysisSample); } } - if (this.isAnalysis) { - this.isAnalysis = false; - } return sampleCallChainList; } diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts index f431c5b0e49f1b732e648420dc0cb9d7cbe5456a..be76a4811b7c827256a6b62b9fd1368a398c6d1b 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSPT.ts @@ -14,7 +14,6 @@ */ import { convertJSON, LogicHandler } from './ProcedureLogicWorkerCommon'; -import { SliceGroup } from '../../bean/StateProcessThread'; export class ProcedureLogicWorkerSPT extends LogicHandler { threadSlice: Array = []; @@ -29,52 +28,66 @@ export class ProcedureLogicWorkerSPT extends LogicHandler { if (data && data.type) { switch (data.type) { case 'spt-init': - if (data.params.list) { - this.threadSlice = convertJSON(data.params.list); - self.postMessage({ - id: this.currentEventId, - action: 'spt-init', - results: [], - }); - } else { - this.getThreadState(); - } + this.sptInit(data); break; case 'spt-getPTS': - self.postMessage({ - id: this.currentEventId, - action: 'spt-getPTS', - results: this.getPTSData(data.params.leftNs, data.params.rightNs, data.params.cpus), - }); + this.sptGetPTS(data.params); break; case 'spt-getSPT': - self.postMessage({ - id: this.currentEventId, - action: 'spt-getSPT', - results: this.getSPTData(data.params.leftNs, data.params.rightNs, data.params.cpus), - }); + this.sptGetSPT(data.params); break; case 'spt-getCpuPriority': - self.postMessage({ - id: this.currentEventId, - action: 'spt-getCpuPriority', - results: this.threadSlice, - }); + this.sptGetCpuPriority(); break; case 'spt-getCpuPriorityByTime': - const result = this.threadSlice.filter((item: ThreadSlice) => { - return !(item.endTs! < data.params.leftNs || item.startTs! > data.params.rightNs); - }); - self.postMessage({ - id: this.currentEventId, - action: 'spt-getCpuPriorityByTime', - results: result, - }); + this.sptGetCpuPriorityByTime(data.params); break; } } } - + private sptInit(data: any): void { + if (data.params.list) { + this.threadSlice = convertJSON(data.params.list); + self.postMessage({ + id: this.currentEventId, + action: 'spt-init', + results: [], + }); + } else { + this.getThreadState(); + } + } + private sptGetPTS(params: any): void { + self.postMessage({ + id: this.currentEventId, + action: 'spt-getPTS', + results: this.getPTSData(params.leftNs, params.rightNs, params.cpus), + }); + } + private sptGetSPT(params: any): void { + self.postMessage({ + id: this.currentEventId, + action: 'spt-getSPT', + results: this.getSPTData(params.leftNs, params.rightNs, params.cpus), + }); + } + private sptGetCpuPriority(): void { + self.postMessage({ + id: this.currentEventId, + action: 'spt-getCpuPriority', + results: this.threadSlice, + }); + } + private sptGetCpuPriorityByTime(params: any): void { + const result = this.threadSlice.filter((item: ThreadSlice) => { + return !(item.endTs! < params.leftNs || item.startTs! > params.rightNs); + }); + self.postMessage({ + id: this.currentEventId, + action: 'spt-getCpuPriorityByTime', + results: result, + }); + } queryData(queryName: string, sql: string, args: any) { self.postMessage({ id: this.currentEventId, @@ -105,7 +118,7 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; ); } - getPTSData(ptsLeftNs: number, ptsRightNs: number, cpus: Array) { + private 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!) && @@ -113,17 +126,8 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; ); let group: any = {}; ptsFilter.forEach((slice) => { - let item = { - title: `S-${slice.state}`, - count: 1, - state: slice.state, - tid: slice.tid, - pid: slice.pid, - minDuration: slice.dur || 0, - maxDuration: slice.dur || 0, - wallDuration: slice.dur || 0, - avgDuration: `${slice.dur}`, - }; + let title = `S-${slice.state}`; + let item = this.setStateData(slice, title); if (group[`${slice.pid}`]) { let process = group[`${slice.pid}`]; process.count += 1; @@ -149,47 +153,66 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; thread.children.push(item); } } else { - process.children.push({ - title: `T-${slice.tid}`, - count: 1, - pid: slice.pid, - tid: slice.tid, - minDuration: slice.dur || 0, - maxDuration: slice.dur || 0, - wallDuration: slice.dur || 0, - avgDuration: `${slice.dur}`, - children: [item], - }); + let processChild = this.setThreadData(slice, item); + process.children.push(processChild); } } else { - group[`${slice.pid}`] = { - title: `P-${slice.pid}`, + group[`${slice.pid}`] = this.setProcessData(slice, item); + } + }); + return Object.values(group); + } + private setStateData(slice: ThreadSlice, title: string): any { + return { + title: title, + count: 1, + state: slice.state, + tid: slice.tid, + pid: slice.pid, + minDuration: slice.dur || 0, + maxDuration: slice.dur || 0, + wallDuration: slice.dur || 0, + avgDuration: `${slice.dur}`, + }; + } + private setProcessData(slice: ThreadSlice, item: any): any { + return { + title: `P-${slice.pid}`, + count: 1, + pid: slice.pid, + minDuration: slice.dur || 0, + maxDuration: slice.dur || 0, + wallDuration: slice.dur || 0, + avgDuration: `${slice.dur}`, + children: [ + { + title: `T-${slice.tid}`, count: 1, pid: slice.pid, + tid: slice.tid, minDuration: slice.dur || 0, maxDuration: slice.dur || 0, wallDuration: slice.dur || 0, avgDuration: `${slice.dur}`, - children: [ - { - title: `T-${slice.tid}`, - count: 1, - pid: slice.pid, - tid: slice.tid, - minDuration: slice.dur || 0, - maxDuration: slice.dur || 0, - wallDuration: slice.dur || 0, - avgDuration: `${slice.dur}`, - children: [item], - }, - ], - }; - } - }); - return Object.values(group); + children: [item], + }, + ], + }; } - - getSPTData(sptLeftNs: number, sptRightNs: number, cpus: Array) { + private setThreadData(slice: ThreadSlice, item: any): any { + return { + title: `T-${slice.tid}`, + count: 1, + pid: slice.pid, + tid: slice.tid, + minDuration: slice.dur || 0, + maxDuration: slice.dur || 0, + wallDuration: slice.dur || 0, + avgDuration: `${slice.dur}`, + children: [item], + }; + } + private getSPTData(sptLeftNs: number, sptRightNs: number, cpus: Array): any { let sptFilter = this.threadSlice.filter( (it) => Math.max(sptLeftNs, it.startTs!) < Math.min(sptRightNs, it.startTs! + it.dur!) && @@ -209,42 +232,7 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; avgDuration: `${slice.dur}`, }; if (group[`${slice.state}`]) { - let state = group[`${slice.state}`]; - state.count += 1; - state.wallDuration += slice.dur; - state.minDuration = Math.min(state.minDuration, slice.dur!); - state.maxDuration = Math.max(state.maxDuration, slice.dur!); - state.avgDuration = (state.wallDuration / state.count).toFixed(2); - let process = state.children.find((child: any) => child.title === `P-${slice.pid}`); - if (process) { - process.count += 1; - process.wallDuration += slice.dur; - process.minDuration = Math.min(process.minDuration, slice.dur!); - process.maxDuration = Math.max(process.maxDuration, slice.dur!); - process.avgDuration = (process.wallDuration / process.count).toFixed(2); - let thread = process.children.find((child: any) => child.title === `T-${slice.tid}`); - if (thread) { - thread.count += 1; - thread.wallDuration += slice.dur; - thread.minDuration = Math.min(thread.minDuration, slice.dur!); - thread.maxDuration = Math.max(thread.maxDuration, slice.dur!); - thread.avgDuration = (thread.wallDuration / thread.count).toFixed(2); - } else { - process.children.push(item); - } - } else { - state.children.push({ - title: `P-${slice.pid}`, - count: 1, - state: slice.state, - pid: slice.pid, - minDuration: slice.dur || 0, - maxDuration: slice.dur || 0, - wallDuration: slice.dur || 0, - avgDuration: `${slice.dur}`, - children: [item], - }); - } + this.setSPTData(group, slice, item); } else { group[`${slice.state}`] = { title: `S-${slice.state}`, @@ -272,6 +260,44 @@ from thread_state,trace_range where dur > 0 and (ts - start_ts) >= 0; }); return Object.values(group); } + private setSPTData(group: any, slice: ThreadSlice, item: any): void { + let state = group[`${slice.state}`]; + state.count += 1; + state.wallDuration += slice.dur; + state.minDuration = Math.min(state.minDuration, slice.dur!); + state.maxDuration = Math.max(state.maxDuration, slice.dur!); + state.avgDuration = (state.wallDuration / state.count).toFixed(2); + let process = state.children.find((child: any) => child.title === `P-${slice.pid}`); + if (process) { + process.count += 1; + process.wallDuration += slice.dur; + process.minDuration = Math.min(process.minDuration, slice.dur!); + process.maxDuration = Math.max(process.maxDuration, slice.dur!); + process.avgDuration = (process.wallDuration / process.count).toFixed(2); + let thread = process.children.find((child: any) => child.title === `T-${slice.tid}`); + if (thread) { + thread.count += 1; + thread.wallDuration += slice.dur; + thread.minDuration = Math.min(thread.minDuration, slice.dur!); + thread.maxDuration = Math.max(thread.maxDuration, slice.dur!); + thread.avgDuration = (thread.wallDuration / thread.count).toFixed(2); + } else { + process.children.push(item); + } + } else { + state.children.push({ + title: `P-${slice.pid}`, + count: 1, + state: slice.state, + pid: slice.pid, + minDuration: slice.dur || 0, + maxDuration: slice.dur || 0, + wallDuration: slice.dur || 0, + avgDuration: `${slice.dur}`, + children: [item], + }); + } + } } export class ThreadSlice { diff --git a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.ts b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.ts index 607eccebfbbbfd758bb678008e587210e232e06b..ab1e346a09654a4bc3f6c0d9210a9770071ec598 100644 --- a/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.ts +++ b/ide/src/trace/database/logic-worker/ProcedureLogicWorkerSchedulingAnalysis.ts @@ -50,219 +50,259 @@ export class ProcedureLogicWorkerSchedulingAnalysis extends LogicHandler { this.startTs = this.endTs - this.totalDur; } if (data && data.type) { - switch (data.type) { - case 'scheduling-clearData': - this.clearAll(); - self.postMessage({ - id: data.id, - action: data.action, - results: [], - }); - break; - case 'scheduling-initFreqData': - if (data.params.list) { - this.groupFreqByCpu(convertJSON(data.params.list) || []); - self.postMessage({ - id: data.id, - action: data.action, - results: [], - }); - } else { - this.getCpuFrequency('scheduling-initFreqData'); - } - break; - case 'scheduling-getProcessAndThread': - if (data.params.list) { - let arr = convertJSON(data.params.list) || []; - this.handleProcessThread(arr); - self.postMessage({ - id: data.id, - action: data.action, - results: [], - }); - } else { - this.getProcessAndThread(); - } - break; - case 'scheduling-getCpuIdle0': - if (data.params.list) { - let arr = convertJSON(data.params.list) || []; - this.handleCPUIdle0Map(arr); - self.postMessage({ - id: data.id, - action: data.action, - results: [], - }); - } else { - this.getCpuIdle0(); - } - break; - case 'scheduling-getCpuUsage': - if (data.params.list) { - let arr = convertJSON(data.params.list) || []; - self.postMessage({ - id: data.id, - action: data.action, - results: arr, - }); - arr = []; - } else { - this.getCpuUsage(); - } - break; - case 'scheduling-CPU Frequency': - if (this.cpuAnalysisMap.has('freq')) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.cpuAnalysisMap.get('freq') || [], - }); - } else { - if (data.params.list) { - let res = this.computeCpuMeasureDur(convertJSON(data.params.list) || [], 'freq'); - this.cpuAnalysisMap.set('freq', res); - self.postMessage({ - id: data.id, - action: data.action, - results: res, - }); - } else { - this.getCpuFrequency('scheduling-CPU Frequency'); - } - } - break; - case 'scheduling-CPU Frequency Thread': - if (data.params.list) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.handlerFreqThreadData(convertJSON(data.params.list) || []), - }); - } else { - this.cpu = data.params.cpu; - this.freq = data.params.freq; - this.getThreadStateByCpu(data.params.cpu); - } - break; - case 'scheduling-CPU Idle': - if (this.cpuAnalysisMap.has('idle')) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.cpuAnalysisMap.get('idle') || [], - }); - } else { - if (data.params.list) { - let res = this.computeCpuMeasureDur(convertJSON(data.params.list) || []); - this.cpuAnalysisMap.set('idle', res); - self.postMessage({ - id: data.id, - action: data.action, - results: res, - }); - } else { - this.getCpuIdle(); - } - } - break; - case 'scheduling-CPU Irq': - if (this.cpuAnalysisMap.has('irq')) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.cpuAnalysisMap.get('irq') || [], - }); - } else { - if (data.params.list) { - let res = this.groupIrgDataByCpu(convertJSON(data.params.list) || []); - this.cpuAnalysisMap.set('irq', res); - self.postMessage({ - id: data.id, - action: data.action, - results: res, - }); - } else { - this.getCpuIrq(); - } - } - break; - case 'scheduling-Thread CpuUsage': - if (data.params.list) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.handlerThreadCpuUsageData(convertJSON(data.params.list) || []), - }); - } else { - this.bigCores = data.params.bigCores || []; - this.midCores = data.params.midCores || []; - this.smallCores = data.params.smallCores || []; - this.queryThreadCpuUsage( - data.params.bigCores || [], - data.params.midCores || [], - data.params.smallCores || [] - ); - } - break; - case 'scheduling-Thread RunTime': - if (data.params.list) { - let arr = convertJSON(data.params.list) || []; - self.postMessage({ - id: data.id, - action: data.action, - results: arr.map((it) => { - it.maxDurationStr = getProbablyTime(it.maxDuration); - it.pName = this.processMap.get(it.pid) || 'null'; - it.tName = this.threadMap.get(it.tid) || 'null'; - return it; - }), - }); - } else { - this.queryThreadRunTime(data.params.cpuMax); - } - break; - case 'scheduling-Process ThreadCount': - if (data.params.list) { - self.postMessage({ - id: data.id, - action: data.action, - results: convertJSON(data.params.list) || [], - }); - } else { - this.queryProcessThreadCount(); - } - break; - case 'scheduling-Process SwitchCount': - if (data.params.list) { - let arr = convertJSON(data.params.list) || []; - self.postMessage({ - id: data.id, - action: data.action, - results: arr.map((it) => { - it.pName = this.processMap.get(it.pid) || 'null'; - it.tName = this.threadMap.get(it.tid) || 'null'; - return it; - }), - }); - } else { - this.queryProcessSwitchCount(); - } - break; - case 'scheduling-Thread Freq': - if (data.params.list) { - self.postMessage({ - id: data.id, - action: data.action, - results: this.handlerThreadFreqData(convertJSON(data.params.list) || []), - }); - } else { - this.queryThreadStateByTid(data.params.tid); - } - break; + this.handleDataByType(data); + } + } + private handleDataByType(data: any): void { + switch (data.type) { + case 'scheduling-clearData': + this.schedulingClearData(data); + break; + case 'scheduling-initFreqData': + this.schedulingInitFreqData(data); + break; + case 'scheduling-getProcessAndThread': + this.schedulinGetProcessAndThread(data); + break; + case 'scheduling-getCpuIdle0': + this.schedulingGetCpuIdle0(data); + break; + case 'scheduling-getCpuUsage': + this.schedulingGetCpuUsage(data); + break; + case 'scheduling-CPU Frequency': + this.schedulingCPUFrequency(data); + break; + case 'scheduling-CPU Frequency Thread': + this.schedulingCPUFrequencyThread(data); + break; + case 'scheduling-CPU Idle': + this.schedulingCPUIdle(data); + break; + case 'scheduling-CPU Irq': + this.schedulingCPUIrq(data); + break; + case 'scheduling-Thread CpuUsage': + this.schedulingThreadCpuUsage(data); + break; + case 'scheduling-Thread RunTime': + this.schedulingThreadRunTime(data); + break; + case 'scheduling-Process ThreadCount': + this.schedulingProcessThreadCount(data); + break; + case 'scheduling-Process SwitchCount': + this.schedulingProcessSwitchCount(data); + break; + case 'scheduling-Thread Freq': + this.schedulingThreadFreq(data); + break; + } + } + private schedulingClearData(data: any): void { + this.clearAll(); + self.postMessage({ + id: data.id, + action: data.action, + results: [], + }); + } + private schedulingInitFreqData(data: any): void { + if (data.params.list) { + this.groupFreqByCpu(convertJSON(data.params.list) || []); + self.postMessage({ + id: data.id, + action: data.action, + results: [], + }); + } else { + this.getCpuFrequency('scheduling-initFreqData'); + } + } + private schedulinGetProcessAndThread(data: any): void { + if (data.params.list) { + let arr = convertJSON(data.params.list) || []; + this.handleProcessThread(arr); + self.postMessage({ + id: data.id, + action: data.action, + results: [], + }); + } else { + this.getProcessAndThread(); + } + } + private schedulingGetCpuIdle0(data: any): void { + if (data.params.list) { + let arr = convertJSON(data.params.list) || []; + this.handleCPUIdle0Map(arr); + self.postMessage({ + id: data.id, + action: data.action, + results: [], + }); + } else { + this.getCpuIdle0(); + } + } + private schedulingGetCpuUsage(data: any): void { + if (data.params.list) { + let arr = convertJSON(data.params.list) || []; + self.postMessage({ + id: data.id, + action: data.action, + results: arr, + }); + arr = []; + } else { + this.getCpuUsage(); + } + } + private schedulingCPUFrequency(data: any): void { + if (this.cpuAnalysisMap.has('freq')) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.cpuAnalysisMap.get('freq') || [], + }); + } else { + if (data.params.list) { + let res = this.computeCpuMeasureDur(convertJSON(data.params.list) || [], 'freq'); + this.cpuAnalysisMap.set('freq', res); + self.postMessage({ + id: data.id, + action: data.action, + results: res, + }); + } else { + this.getCpuFrequency('scheduling-CPU Frequency'); } } } - + private schedulingCPUFrequencyThread(data: any): void { + if (data.params.list) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.handlerFreqThreadData(convertJSON(data.params.list) || []), + }); + } else { + this.cpu = data.params.cpu; + this.freq = data.params.freq; + this.getThreadStateByCpu(data.params.cpu); + } + } + private schedulingCPUIdle(data: any): void { + if (this.cpuAnalysisMap.has('idle')) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.cpuAnalysisMap.get('idle') || [], + }); + } else { + if (data.params.list) { + let res = this.computeCpuMeasureDur(convertJSON(data.params.list) || []); + this.cpuAnalysisMap.set('idle', res); + self.postMessage({ + id: data.id, + action: data.action, + results: res, + }); + } else { + this.getCpuIdle(); + } + } + } + private schedulingCPUIrq(data: any): void { + if (this.cpuAnalysisMap.has('irq')) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.cpuAnalysisMap.get('irq') || [], + }); + } else { + if (data.params.list) { + let res = this.groupIrgDataByCpu(convertJSON(data.params.list) || []); + this.cpuAnalysisMap.set('irq', res); + self.postMessage({ + id: data.id, + action: data.action, + results: res, + }); + } else { + this.getCpuIrq(); + } + } + } + private schedulingThreadCpuUsage(data: any): void { + if (data.params.list) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.handlerThreadCpuUsageData(convertJSON(data.params.list) || []), + }); + } else { + this.bigCores = data.params.bigCores || []; + this.midCores = data.params.midCores || []; + this.smallCores = data.params.smallCores || []; + this.queryThreadCpuUsage(data.params.bigCores || [], data.params.midCores || [], data.params.smallCores || []); + } + } + private schedulingThreadRunTime(data: any): void { + if (data.params.list) { + let arr = convertJSON(data.params.list) || []; + self.postMessage({ + id: data.id, + action: data.action, + results: arr.map((it) => { + it.maxDurationStr = getProbablyTime(it.maxDuration); + it.pName = this.processMap.get(it.pid) || 'null'; + it.tName = this.threadMap.get(it.tid) || 'null'; + return it; + }), + }); + } else { + this.queryThreadRunTime(data.params.cpuMax); + } + } + private schedulingProcessThreadCount(data: any): void { + if (data.params.list) { + self.postMessage({ + id: data.id, + action: data.action, + results: convertJSON(data.params.list) || [], + }); + } else { + this.queryProcessThreadCount(); + } + } + private schedulingProcessSwitchCount(data: any): void { + if (data.params.list) { + let arr = convertJSON(data.params.list) || []; + self.postMessage({ + id: data.id, + action: data.action, + results: arr.map((it) => { + it.pName = this.processMap.get(it.pid) || 'null'; + it.tName = this.threadMap.get(it.tid) || 'null'; + return it; + }), + }); + } else { + this.queryProcessSwitchCount(); + } + } + private schedulingThreadFreq(data: any): void { + if (data.params.list) { + self.postMessage({ + id: data.id, + action: data.action, + results: this.handlerThreadFreqData(convertJSON(data.params.list) || []), + }); + } else { + this.queryThreadStateByTid(data.params.tid); + } + } getProcessAndThread() { this.queryData( this.currentEventId, @@ -367,12 +407,12 @@ where cmf.name = 'cpu_idle' and value != 0 SELECT callid AS cpu, CASE WHEN cat = 'ipi' THEN 'irq' ELSE cat END AS block, CASE WHEN cat = 'ipi' THEN 'IPI' || name ELSE name END AS value, - sum( dur ) sum, - min( dur ) min, - max( dur ) max, - avg( dur ) avg + sum( dur ) sum, + min( dur ) min, + max( dur ) max, + avg( dur ) avg FROM - irq + irq WHERE cat = 'ipi' OR cat = 'softirq' @@ -521,7 +561,7 @@ where cpu not null getEffectiveFrequencyDur(m: CpuMeasure) { let arr = this.cpuIdle0Map.get(m.cpu) || []; - let filterArr = []; + let filterArr: CpuMeasure[] = []; for (let it of arr) { if (Math.min(m.ts + m.dur, it.ts + it.dur) - Math.max(m.ts, it.ts) > 0) { filterArr.push(it); @@ -568,8 +608,52 @@ where cpu not null this.cpuFreqMap = map; } + private filterMap(map: Map>, key: number): Map { + return map.get(key)!.reduce((group: any, ca) => { + const { value } = ca; + if (group[value]) { + group[value].sum = group[value].sum + ca.dur; + group[value].min = group[value].min < ca.dur ? group[value].min : ca.dur; + group[value].max = group[value].max > ca.dur ? group[value].max : ca.dur; + group[value].count = group[value].count + 1; + group[value].avg = (group[value].sum / group[value].count).toFixed(2); + } else { + group[value] = { + cpu: ca.cpu, + value: ca.value, + sum: ca.dur, + min: ca.dur, + max: ca.dur, + avg: ca.dur, + count: 1, + ratio: '', + block: ca.block, + }; + } + return group; + }, {}); + } + private setTargetMapValue(cpuArr: Array, sumMap: Map, key: number) { + return cpuArr.map((cpuAnalysisBean) => { + return { + cpu: cpuAnalysisBean.cpu, + value: cpuAnalysisBean.value, + sum: cpuAnalysisBean.sum, + sumTimeStr: getProbablyTime(cpuAnalysisBean.sum), + min: getProbablyTime(cpuAnalysisBean.min), + minValue: cpuAnalysisBean.min, + max: getProbablyTime(cpuAnalysisBean.max), + maxValue: cpuAnalysisBean.max, + avgValue: cpuAnalysisBean.avg, + avg: getProbablyTime(cpuAnalysisBean.avg), + count: cpuAnalysisBean.count, + ratio: ((cpuAnalysisBean.sum / (sumMap.get(key) || 1)) * 100).toFixed(2), + block: cpuAnalysisBean.block, + } as any; + }); + } //根据查询的数据,加工出CPU调度分析所需要展示的相关数据 - computeCpuMeasureDur(arr: Array, type?: string) { + private computeCpuMeasureDur(arr: Array, type?: string): Map { //首先计算 每个频点的持续时间,并根据Cpu来分组 let map: Map> = new Map>(); let sumMap: Map = new Map(); @@ -594,30 +678,7 @@ where cpu not null //再根据频点值进行分组求和 let target: Map = new Map(); for (let key of map.keys()) { - let obj = map.get(key)!.reduce((group: any, ca) => { - const { value } = ca; - if (group[value]) { - group[value].sum = group[value].sum + ca.dur; - group[value].min = group[value].min < ca.dur ? group[value].min : ca.dur; - group[value].max = group[value].max > ca.dur ? group[value].max : ca.dur; - group[value].count = group[value].count + 1; - group[value].avg = (group[value].sum / group[value].count).toFixed(2); - } else { - group[value] = { - cpu: ca.cpu, - value: ca.value, - sum: ca.dur, - min: ca.dur, - max: ca.dur, - avg: ca.dur, - count: 1, - ratio: '', - block: ca.block, - }; - } - return group; - }, {}); - // @ts-ignore + let obj = this.filterMap(map, key); let cpuArr = (Object.values(obj) as CpuAnalysis[]) .sort((a, b) => { if (type === 'freq') { @@ -627,31 +688,13 @@ where cpu not null } }) .slice(0, 20); - target.set( - key, - cpuArr.map((cpuAnalysisBean) => { - return { - cpu: cpuAnalysisBean.cpu, - value: cpuAnalysisBean.value, - sum: cpuAnalysisBean.sum, - sumTimeStr: getProbablyTime(cpuAnalysisBean.sum), - min: getProbablyTime(cpuAnalysisBean.min), - minValue: cpuAnalysisBean.min, - max: getProbablyTime(cpuAnalysisBean.max), - maxValue: cpuAnalysisBean.max, - avgValue: cpuAnalysisBean.avg, - avg: getProbablyTime(cpuAnalysisBean.avg), - count: cpuAnalysisBean.count, - ratio: ((cpuAnalysisBean.sum / (sumMap.get(key) || 1)) * 100).toFixed(2), - block: cpuAnalysisBean.block, - } as any; - }) - ); + let value = this.setTargetMapValue(cpuArr, sumMap, key); + target.set(key, value); } return target; } - handlerFreqThreadData(arr: FreqThread[]) { + private handlerFreqThreadData(arr: FreqThread[]) { let cpuFreqArr: CpuMeasure[] = (this.cpuFreqMap.get(this.cpu) || []).filter((it) => it.value === this.freq); let map: Map< number, @@ -689,27 +732,19 @@ where cpu not null }) .slice(0, 20); } - - //加工Top20线程大中小核占用率数据 - handlerThreadCpuUsageData(arr: Array) { - let sumBig = 0, - sumMid = 0, - sumSmall = 0; - let reduceObj = arr.reduce((group: any, item) => { + private filterThreadCpuUsageArr(arr: any, sumBig: number, sumMid: number, sumSmall: number) { + return arr.reduce((group: any, item: any) => { const { tid } = item; let tidObj: any = group[`${tid}`]; let cpuType: string = 'mid'; - // @ts-ignore if (this.bigCores.includes(item.cpu)) { cpuType = 'big'; sumBig += item.total; } - // @ts-ignore if (this.midCores.includes(item.cpu)) { cpuType = 'mid'; sumMid += item.total; } - // @ts-ignore if (this.smallCores.includes(item.cpu)) { cpuType = 'small'; sumSmall += item.total; @@ -735,6 +770,13 @@ where cpu not null } return group; }, {}); + } + //加工Top20线程大中小核占用率数据 + private handlerThreadCpuUsageData(arr: Array) { + let sumBig = 0; + let sumMid = 0; + let sumSmall = 0; + let reduceObj = this.filterThreadCpuUsageArr(arr, sumBig, sumMid, sumSmall); // @ts-ignore let source: any[] = Object.values(reduceObj) as any[]; for (let obj of source) { @@ -752,15 +794,37 @@ where cpu not null map.set('small', source.sort((a, b) => b.small - a.small).slice(0, 20)); return map; } + private filterThreadFreqData(arr: any, sumDur: number): any { + return arr.reduce((group: any, tf: { freqArr: any }) => { + for (let fa of tf.freqArr) { + const { cpu, freq } = fa; + if (group[`${cpu}-${freq}`]) { + group[`${cpu}-${freq}`].time = group[`${cpu}-${freq}`].time + fa.dur; + group[`${cpu}-${freq}`].timeStr = getProbablyTime(group[`${cpu}-${freq}`].time); + group[`${cpu}-${freq}`].ratio = ((group[`${cpu}-${freq}`].time / sumDur) * 100).toFixed(2); + } else { + group[`${cpu}-${freq}`] = { + freq: freq, + cpu: cpu, + time: fa.dur, + timeStr: getProbablyTime(fa.dur), + ratio: ((fa.dur / sumDur) * 100).toFixed(2), + totalDur: sumDur, + }; + } + } + return group; + }, {}); + } - handlerThreadFreqData( + private handlerThreadFreqData( arr: { cpu: number; dur: number; ts: number; freqArr: { cpu: number; freq: number; dur: number }[]; }[] - ) { + ): Array { let sumDur: number = 0; arr.map((it) => { it.freqArr = []; @@ -783,33 +847,13 @@ where cpu not null sumDur += it.dur; return it; }); - let obj: any = arr.reduce((group: any, tf) => { - for (let fa of tf.freqArr) { - const { cpu, freq } = fa; - if (group[`${cpu}-${freq}`]) { - group[`${cpu}-${freq}`].time = group[`${cpu}-${freq}`].time + fa.dur; - group[`${cpu}-${freq}`].timeStr = getProbablyTime(group[`${cpu}-${freq}`].time); - group[`${cpu}-${freq}`].ratio = ((group[`${cpu}-${freq}`].time / sumDur) * 100).toFixed(2); - } else { - group[`${cpu}-${freq}`] = { - freq: freq, - cpu: cpu, - time: fa.dur, - timeStr: getProbablyTime(fa.dur), - ratio: ((fa.dur / sumDur) * 100).toFixed(2), - totalDur: sumDur, - }; - } - } - return group; - }, {}); + let obj: any = this.filterThreadFreqData(arr, sumDur); let target: { cpu: number; freq: number; time: number; ratio: string; totalDur: number; - // @ts-ignore }[] = Object.values(obj); return target.sort((a, b) => b.time - a.time); } diff --git a/ide/src/trace/database/sql/Ability.sql.ts b/ide/src/trace/database/sql/Ability.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..9dd6c81f0735b7b2d937b6a1d72fa11353c98694 --- /dev/null +++ b/ide/src/trace/database/sql/Ability.sql.ts @@ -0,0 +1,573 @@ +/* + * 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 { + GpuMemory, + GpuMemoryComparison, + SystemCpuSummary, + SystemDiskIOSummary, + SystemNetworkSummary +} from "../../bean/AbilityMonitor"; +import {query} from "../SqlLite"; +import {CpuAbilityMonitorStruct} from "../ui-worker/ProcedureWorkerCpuAbility"; +import {MemoryAbilityMonitorStruct} from "../ui-worker/ProcedureWorkerMemoryAbility"; +import {DiskAbilityMonitorStruct} from "../ui-worker/ProcedureWorkerDiskIoAbility"; +import {NetworkAbilityMonitorStruct} from "../ui-worker/ProcedureWorkerNetworkAbility"; +import type {SnapshotStruct} from "../ui-worker/ProcedureWorkerSnapshot"; + +export const getTabCpuAbilityData = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabCpuAbilityData', + `SELECT + ( n.ts - TR.start_ts ) AS startTime, + n.dur AS duration, + n.total_load AS totalLoad, + n.user_load AS userLoad, + n.system_load AS systemLoad, + n.process_num AS threads + FROM + cpu_usage AS n, + trace_range AS TR + WHERE + ( n.ts - TR.start_ts ) >= ifnull(( + SELECT + ( usage.ts - TR.start_ts ) + FROM + cpu_usage usage, + trace_range TR + WHERE + ( usage.ts - TR.start_ts ) <= $leftNS + ORDER BY + usage.ts DESC + LIMIT 1 + ),0) + AND ( n.ts - TR.start_ts ) <= $rightNS + ORDER BY + startTime ASC; + `, + { $leftNS: leftNs, $rightNS: rightNs } + ); +export const getTabMemoryAbilityData = ( + leftNs: number, + rightNs: number +): Promise< + Array<{ + startTime: number; + value: string; + name: string; + }> +> => + query( + 'getTabMemoryAbilityData', + `SELECT + m.ts AS startTime, + GROUP_CONCAT( IFNULL( m.value, 0 ) ) AS value, + GROUP_CONCAT( f.name ) AS name + FROM + sys_mem_measure AS m + INNER JOIN sys_event_filter AS f ON m.filter_id = f.id + AND (f.name = 'sys.mem.total' + or f.name = 'sys.mem.free' + or f.name = 'sys.mem.buffers' + or f.name = 'sys.mem.cached' + or f.name = 'sys.mem.shmem' + or f.name = 'sys.mem.slab' + or f.name = 'sys.mem.swap.total' + or f.name = 'sys.mem.swap.free' + or f.name = 'sys.mem.mapped' + or f.name = 'sys.mem.vmalloc.used' + or f.name = 'sys.mem.page.tables' + or f.name = 'sys.mem.kernel.stack' + or f.name = 'sys.mem.active' + or f.name = 'sys.mem.inactive' + or f.name = 'sys.mem.unevictable' + or f.name = 'sys.mem.vmalloc.total' + or f.name = 'sys.mem.slab.unreclaimable' + or f.name = 'sys.mem.cma.total' + or f.name = 'sys.mem.cma.free' + or f.name = 'sys.mem.kernel.reclaimable' + or f.name = 'sys.mem.zram' + ) + AND m.ts >= ifnull(( + SELECT + m.ts AS startTime + FROM + sys_mem_measure AS m + INNER JOIN sys_event_filter AS f ON m.filter_id = f.id + AND m.ts <= $leftNS + AND (f.name = 'sys.mem.total' + or f.name = 'sys.mem.kernel.stack' + or f.name = 'sys.mem.free' + or f.name = 'sys.mem.swap.free' + or f.name = 'sys.mem.cma.free' + or f.name = 'sys.mem.inactive' + or f.name = 'sys.mem.buffers' + or f.name = 'sys.mem.cached' + or f.name = 'sys.mem.shmem' + or f.name = 'sys.mem.slab' + or f.name = 'sys.mem.swap.total' + or f.name = 'sys.mem.vmalloc.used' + or f.name = 'sys.mem.page.tables' + or f.name = 'sys.mem.active' + or f.name = 'sys.mem.unevictable' + or f.name = 'sys.mem.vmalloc.total' + or f.name = 'sys.mem.slab.unreclaimable' + or f.name = 'sys.mem.cma.total' + or f.name = 'sys.mem.mapped' + or f.name = 'sys.mem.kernel.reclaimable' + or f.name = 'sys.mem.zram' + ) + ORDER BY + m.ts DESC + LIMIT 1 + ),0) + AND m.ts <= $rightNS GROUP BY m.ts;`, + { $leftNS: leftNs, $rightNS: rightNs } + ); +export const getTabNetworkAbilityData = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabNetworkAbilityData', + `SELECT + ( n.ts - TR.start_ts ) AS startTime, + n.dur AS duration, + n.rx AS dataReceived, + n.tx_speed AS dataReceivedSec, + n.tx AS dataSend, + n.rx_speed AS dataSendSec, + n.packet_in AS packetsIn, + n.packet_in_sec AS packetsInSec, + n.packet_out AS packetsOut, + n.packet_out_sec AS packetsOutSec + FROM + network AS n, + trace_range AS TR + WHERE + ( n.ts - TR.start_ts ) >= ifnull(( + SELECT + ( nn.ts - T.start_ts ) AS startTime + FROM + network nn, + trace_range T + WHERE + ( nn.ts - T.start_ts ) <= $leftNS + ORDER BY + nn.ts DESC + LIMIT 1 + ),0) + AND ( n.ts - TR.start_ts ) <= $rightNS + ORDER BY + startTime ASC`, + { $leftNS: leftNs, $rightNS: rightNs } + ); +export const getTabDiskAbilityData = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabDiskAbilityData', + `SELECT + ( n.ts - TR.start_ts ) AS startTime, + n.dur AS duration, + n.rd AS dataRead, + n.rd_speed AS dataReadSec, + n.wr AS dataWrite, + n.wr_speed AS dataWriteSec, + n.rd_count AS readsIn, + n.rd_count_speed AS readsInSec, + n.wr_count AS writeOut, + n.wr_count_speed AS writeOutSec + FROM + diskio AS n, + trace_range AS TR + WHERE + ( n.ts - TR.start_ts ) >= ifnull(( + SELECT + ( nn.ts - T.start_ts ) AS startTime + FROM + diskio AS nn, + trace_range AS T + WHERE + ( nn.ts - T.start_ts ) <= $leftNS + ORDER BY + nn.ts DESC + LIMIT 1 + ),0) + AND ( n.ts - TR.start_ts ) <= $rightNS + ORDER BY + startTime ASC; + `, + { $leftNS: leftNs, $rightNS: rightNs } + ); + +export const queryCpuAbilityData = (): Promise> => + query( + 'queryCpuAbilityData', + `select + (t.total_load) as value, + (t.ts - TR.start_ts) as startNS + from cpu_usage t, trace_range AS TR;` + ); + +export const queryCpuAbilityUserData = (): Promise> => + query( + 'queryCpuAbilityUserData', + `select + t.user_load as value, + (t.ts - TR.start_ts) as startNS + from cpu_usage t, trace_range AS TR;` + ); + +export const queryCpuAbilitySystemData = (): Promise> => + query( + 'queryCpuAbilitySystemData', + `select + t.system_load as value, + (t.ts - TR.start_ts) as startNS + from cpu_usage t, trace_range AS TR;` + ); + +export const queryMemoryUsedAbilityData = (id: string): Promise> => + query( + 'queryMemoryUsedAbilityData', + `select + t.value as value, + (t.ts - TR.start_ts) as startNS + from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, + { $id: id } + ); + +export const queryCachedFilesAbilityData = (id: string): Promise> => + query( + 'queryCachedFilesAbilityData', + `select + t.value as value, + (t.ts - TR.start_ts) as startNS + from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, + { $id: id } + ); + + +export const queryCompressedAbilityData = (id: string): Promise> => + query( + 'queryCompressedAbilityData', + `select + t.value as value, + (t.ts - TR.start_ts) as startNS + from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, + { $id: id } + ); + +export const querySwapUsedAbilityData = (id: string): Promise> => + query( + 'querySwapUsedAbilityData', + `select + t.value as value, + (t.ts - TR.start_ts) as startNS + from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`, + { $id: id } + ); + +export const queryBytesReadAbilityData = (): Promise> => + query( + 'queryBytesReadAbilityData', + `select + t.rd_speed as value, + (t.ts - TR.start_ts) as startNS + from diskio t, trace_range AS TR;` + ); + +export const queryBytesWrittenAbilityData = (): Promise> => + query( + 'queryBytesWrittenAbilityData', + `select + t.wr_speed as value, + (t.ts - TR.start_ts) as startNS + from diskio t, trace_range AS TR;` + ); + +export const queryReadAbilityData = (): Promise> => + query( + 'queryReadAbilityData', + `select + t.rd_count_speed as value, + (t.ts - TR.start_ts) as startNS + from diskio t, trace_range AS TR;` + ); + +export const queryWrittenAbilityData = (): Promise> => + query( + 'queryWrittenAbilityData', + `select + t.wr_count_speed as value, + (t.ts - TR.start_ts) as startNS + from diskio t, trace_range AS TR;` + ); + +export const queryBytesInAbilityData = (): Promise> => + query( + 'queryBytesInAbilityData', + `select + t.tx_speed as value, + (t.ts - TR.start_ts) as startNS + from network t, trace_range AS TR;` + ); + +export const queryBytesOutAbilityData = (): Promise> => + query( + 'queryBytesOutAbilityData', + `select + t.rx_speed as value, + (t.ts - TR.start_ts) as startNS + from network t, trace_range AS TR;` + ); + +export const queryPacketsInAbilityData = (): Promise> => + query( + 'queryPacketsInAbilityData', + `select + t.packet_in_sec as value, + (t.ts - TR.start_ts) as startNS + from network t, trace_range AS TR;` + ); + +export const queryPacketsOutAbilityData = (): Promise> => + query( + 'queryPacketsOutAbilityData', + `select + t.packet_out_sec as value, + (t.ts - TR.start_ts) as startNS + from network t, trace_range AS TR;` + ); +export const queryAbilityExits = (): Promise> => + query( + 'queryAbilityExits', + `select + event_name + from stat s + where s.event_name in ('trace_diskio','trace_network', 'trace_cpu_usage','sys_memory') + and s.stat_type ='received' and s.count > 0` + ); +export const queryCPuAbilityMaxData = (): Promise> => + query( + 'queryCPuAbilityMaxData', + `select ifnull(max(total_load),0) as totalLoad, + ifnull(max(user_load),0) as userLoad, + ifnull(max(system_load),0) as systemLoad + from cpu_usage` + ); +// Ability Monitor SkiaGpuMemory泳道图 +export const queryGpuMemoryAbilityData = (): Promise> => + query( + 'queryGpuMemoryAbilityData', + `SELECT + (A.ts - B.start_ts) as startNs, + sum(A.used_gpu_size) as value + FROM memory_process_gpu A,trace_range B + WHERE A.ts < B.end_ts + GROUP by A.ts + LIMIT 1;` + ); + +// Ability Monitor Dma泳道图 +export const queryDmaAbilityData = (): Promise> => + query( + 'queryDmaAbilityData', + `SELECT + (A.ts - B.start_ts) as startNs, + sum(A.size) as value, + E.data as expTaskComm, + A.flag as flag + FROM memory_dma A,trace_range B + left join data_dict as E on E.id=A.exp_task_comm_id + WHERE + A.flag = 0 + AND A.ts < B.end_ts + GROUP by A.ts + LIMIT 1;` + ); +// Ability Monitor Purgeable泳道图 +export const queryPurgeableSysData = (isPin?: boolean): Promise> => { + const pinCondition = isPin ? ' AND a.ref_count > 0' : ''; + const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')"; + return query( + 'queryPurgeableSysData', + `SELECT + startNs, + sum( value ) AS value + FROM + ( + SELECT + m.ts - tr.start_ts AS startNs, + sum( m.value ) AS value + FROM + sys_mem_measure m, + trace_range tr + LEFT JOIN sys_event_filter f ON f.id = m.filter_id + WHERE + m.ts < tr.end_ts + AND f.name IN ${names} + GROUP BY + m.ts UNION ALL + SELECT + a.ts - tr.start_ts AS startNs, + sum( a.size ) AS value + FROM + memory_ashmem a, + trace_range tr + WHERE + a.ts < tr.end_ts + AND a.flag = 0 + ${pinCondition} + GROUP BY + a.ts + ) + GROUP BY startNs + LIMIT 1` + ); +}; + +//Ability Monitor Purgeable 框选 tab页 +export const querySysPurgeableTab = ( + leftNs: number, + rightNs: number, + dur: number, + isPin?: boolean +): Promise> => { + let pinsql = isPin ? ' AND ref_count > 0' : ''; + const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')"; + return query( + 'querySysPurgeableTab', + `SELECT name, MAX( size ) AS maxSize,MIN( size ) AS minSize,AVG( size ) AS avgSize + FROM + (SELECT + 'ShmPurg' AS name, + ts - tr.start_ts AS startTs, + SUM( size ) AS size + FROM + memory_ashmem, + trace_range tr + WHERE flag = 0 + ${pinsql} + GROUP BY ts UNION + SELECT + CASE + WHEN + f.name = 'sys.mem.active.purg' THEN + 'ActivePurg' + WHEN f.name = 'sys.mem.inactive.purg' THEN + 'InActivePurg' ELSE 'PinedPurg' + END AS name, + m.ts - tr.start_ts AS startTs, + m.value AS size + FROM + sys_mem_measure m, + trace_range tr + LEFT JOIN sys_event_filter f ON f.id = m.filter_id + WHERE + f.name IN ${names} + ), + trace_range tr + WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs + GROUP BY name` + ); +}; + +//Ability Monitor Purgeable 点选 tab页 +export const querySysPurgeableSelectionTab = (startNs: number, isPin?: boolean): Promise> => { + const pinSql = isPin ? ' AND ref_count > 0' : ''; + const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')"; + return query( + 'querySysPurgeableSelectionTab', + `SELECT + ( CASE WHEN f.name = 'sys.mem.active.purg' THEN 'ActivePurg' WHEN f.name = 'sys.mem.inactive.purg' THEN 'InActivePurg' ELSE 'PinedPurg' END ) AS name, + m.value AS value + FROM + sys_mem_measure m, + trace_range tr + LEFT JOIN sys_event_filter f ON f.id = m.filter_id + WHERE + f.name IN ${names} + AND m.ts - tr.start_ts = ${startNs} + UNION + SELECT + 'ShmPurg' AS name, + SUM( size ) AS value + FROM + memory_ashmem, + trace_range tr + WHERE + memory_ashmem.ts - tr.start_ts = ${startNs} + AND flag=0 + ${pinSql} + GROUP BY ts` + ); +}; +//Ability Monitor SkiaGpuMemory 框选 +export const getTabGpuMemoryAbilityData = (leftNs: number, rightNs: number, dur: number): Promise> => + query( + 'getTabGpuMemoryAbilityData', + `SELECT (S.ts-TR.start_ts) as startNs, + gpu_name_id as gpuNameId, + MAX(S.used_gpu_size) as maxSize, + MIN(S.used_gpu_size) as minSize, + Avg(S.used_gpu_size) as avgSize, + E.pid as processId, + E.name as processName + from trace_range as TR,memory_process_gpu as S + left join process as E on E.ipid=S.ipid + WHERE + $leftNS <= startNs + ${dur} + and + $rightNS >= startNs + GROUP by + E.pid ,S.gpu_name_id + `, + { $leftNS: leftNs, $rightNS: rightNs } + ); +//Ability Monitor SkiaGpuMemory 点选 +export const getTabGpuMemoryAbilityClickData = (startNs: number): Promise> => + query( + 'getTabGpuMemoryAbilityClickData', + `SELECT + (S.ts-TR.start_ts) as startNs, + S.used_gpu_size as size, + E.pid as processId, + E.name as processName, + A.data as gpuName + from trace_range as TR,memory_process_gpu as S + left join process as E on E.ipid=S.ipid + left join data_dict as A on A.id=S.gpu_name_id + WHERE + startNs = ${startNs} + `, + { $startNs: startNs } + ); +//Ability Monitor Gpu Memory 点选比较 +export const getTabGpuMemoryComparisonData = (startNs: number): Promise> => + query( + 'getTabGpuMemoryComparisonData', + `SELECT + (S.ts-TR.start_ts) as startNs, + sum(S.used_gpu_size) as value, + E.pid as processId, + S.gpu_name_id as gpuNameId, + E.name as processName + from trace_range as TR,memory_process_gpu as S + left join process as E on E.ipid=S.ipid + WHERE + startNs = ${startNs} + GROUP by + E.pid, S.gpu_name_id + `, + { $startNs: startNs } + ); + + diff --git a/ide/src/trace/database/sql/Clock.sql.ts b/ide/src/trace/database/sql/Clock.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff2cd1731e82d43caf113a157048fb296f59a32b --- /dev/null +++ b/ide/src/trace/database/sql/Clock.sql.ts @@ -0,0 +1,82 @@ +/* + * 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 {query} from "../SqlLite"; +import {ClockStruct} from "../ui-worker/ProcedureWorkerClock"; + +export const queryClockData = (): Promise< + Array<{ + name: string; + num: number; + srcname: string; + }> +> => + query( + 'queryClockData', + ` + select name || ' Frequency' name, COUNT(*) num, name srcname +from (select id, name + from clock_event_filter + where type = 'clock_set_rate') +group by name +union +select name || ' State' name, COUNT(*) num, name srcname +from (select id, name + from clock_event_filter + where type != 'clock_set_rate') +group by name; +` + ); + +export const queryClockFrequency = (clockName: string): Promise> => + query( + 'queryClockFrequency', + `with freq as ( select measure.filter_id, measure.ts, measure.type, measure.value from clock_event_filter +left join measure +where clock_event_filter.name = $clockName and clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id +order by measure.ts) +select freq.filter_id as filterId,freq.ts - r.start_ts as startNS,freq.type,freq.value from freq,trace_range r order by startNS`, + { $clockName: clockName } + ); + +export const queryClockState = (clockName: string): Promise> => + query( + 'queryClockState', + `with state as ( +select filter_id, ts, endts, endts-ts as dur, type, value from +(select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value from clock_event_filter,trace_range +left join measure +where clock_event_filter.name = $clockName and clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id +order by measure.ts)) +select s.filter_id as filterId,s.ts-r.start_ts as startNS,s.type,s.value,s.dur from state s,trace_range r`, + { $clockName: clockName } + ); +export const queryBootTime = (): Promise> => + query( + 'queryBootTime', + `select CS.ts -TR.start_ts as ts ,clock_name from clock_snapshot as CS ,trace_range as TR + where clock_name = 'boottime'`, + {} + ); +export const queryScreenState = (): Promise> => + query( + 'queryScreenState', + `select m.type, m.ts-r.start_ts as startNS, value, filter_id as filterId from measure m,trace_range r where filter_id in (select id from process_measure_filter where name = 'ScreenState') order by startNS; +` + ); +export const queryRealTime = (): Promise< + Array<{ + ts: number; + }> +> => query('queryRealTime', `select CS.ts as ts from clock_snapshot as CS where clock_name = 'realtime';`); diff --git a/ide/src/trace/database/sql/Cpu.sql.ts b/ide/src/trace/database/sql/Cpu.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..10b8e8fe1f68991e3183867a52bcd50b77bbb19b --- /dev/null +++ b/ide/src/trace/database/sql/Cpu.sql.ts @@ -0,0 +1,698 @@ +/* + * 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 { KeyPathStruct } from "../../bean/KeyPathStruct"; +import { CpuStruct } from "../ui-worker/cpu/ProcedureWorkerCPU"; +import { query } from "../SqlLite"; +import { CpuUsage, Freq } from "../../bean/CpuUsage"; +import { Counter } from "../../bean/BoxSelection"; +import { CpuFreqStruct } from "../ui-worker/ProcedureWorkerFreq"; +import { CpuFreqLimitsStruct } from "../ui-worker/cpu/ProcedureWorkerCpuFreqLimits"; +import { CpuFreqRowLimit } from "../../component/chart/SpFreqChart"; + +export const queryCpuKeyPathData = (threads: Array): Promise> => { + const sqlArray: Array = []; + sqlArray.push(` 1 = 0`); + for (const thread of threads) { + sqlArray.push(` or (tid = ${thread.tid} and ts in (${thread.tsArray}))`); + } + let sql = sqlArray.join(' '); + return query( + 'queryCpuKeyPathData', + `SELECT B.pid as processId, + B.cpu, + B.tid, + B.itid as id, + B.dur AS dur, + B.ts - T.start_ts AS startTime, + B.arg_setid as argSetID, + 1 as isKeyPath + from thread_state AS B + left join trace_range as T + where ${sql}` + ); +}; +export const getCpuUtilizationRate = ( + startNS: number, + endNS: number +): Promise< + Array<{ + cpu: number; + ro: number; + rate: number; + }> +> => + query( + 'getCpuUtilizationRate', + ` + with cpu as ( + select + cpu, + ts, + dur, + (case when ro < 99 then ro else 99 end) as ro , + (case when ro < 99 then stime+ro*cell else stime + 99 * cell end) as st, + (case when ro < 99 then stime + (ro+1)*cell else etime end) as et + from ( + select + cpu, + ts, + A.dur, + ((ts+A.dur)-D.start_ts)/((D.end_ts-D.start_ts)/100) as ro, + D.start_ts as stime, + D.end_ts etime, + (D.end_ts-D.start_ts)/100 as cell + from + sched_slice A + left join + trace_range D + left join + thread B on A.itid = B.id + where + tid != 0 + and (A.ts) + between D.start_ts and D.end_ts)) + select cpu,ro, + sum(case + when ts <= st and ts + dur <= et then (ts + dur - st) + when ts <= st and ts + dur > et then et-st + when ts > st and ts + dur <= et then dur + when ts > st and ts + dur > et then et - ts end)/cast(et-st as float) as rate + from cpu + group by cpu,ro;`, + {} + ); +export const getTabCpuUsage = (cpus: Array, leftNs: number, rightNs: number): Promise> => + query( + 'getTabCpuUsage', + ` + select + cpu, + sum(case + when (A.ts - B.start_ts) < $leftNS + then (A.ts - B.start_ts + A.dur - $leftNS) + when (A.ts - B.start_ts) >= $leftNS + and (A.ts - B.start_ts + A.dur) <= $rightNS + then A.dur + when (A.ts - B.start_ts + A.dur) > $rightNS + then ($rightNS - (A.ts - B.start_ts)) end) / cast($rightNS - $leftNS as float) as usage + from + thread_state A, + trace_range B + where + (A.ts - B.start_ts) > 0 and A.dur > 0 + and + cpu in (${cpus.join(',')}) + and + (A.ts - B.start_ts + A.dur) > $leftNS + and + (A.ts - B.start_ts) < $rightNS + group by + cpu`, + { $leftNS: leftNs, $rightNS: rightNs } + ); + +export const getTabCpuFreq = (cpus: Array, leftNs: number, rightNs: number): Promise> => + query( + 'getTabCpuFreq', + ` + select + cpu, + value, + (ts - tr.start_ts) as startNs + from + measure m, + trace_range tr + inner join + cpu_measure_filter t + on + m.filter_id = t.id + where + (name = 'cpufreq' or name='cpu_frequency') + and + cpu in (${cpus.join(',')}) + and + startNs > 0 + and + startNs < $rightNS + --order by startNs + `, + { $leftNS: leftNs, $rightNS: rightNs } + ); + + +export const getTabCounters = (processFilterIds: Array, virtualFilterIds: Array, startTime: number) => { + let processSql = `select + t1.filter_id as trackId, + t2.name, + value, + t1.ts - t3.start_ts as startTime + from + process_measure t1 + left join + process_measure_filter t2 + on + t1.filter_id = t2.id + left join + trace_range t3 + where + filter_id in (${processFilterIds.join(',')}) + and + startTime <= ${startTime}`; + let virtualSql = `select + t1.filter_id as trackId, + t2.name, + value, + t1.ts - t3.start_ts as startTime + from + sys_mem_measure t1 + left join + sys_event_filter t2 + on + t1.filter_id = t2.id + left join + trace_range t3 + where + filter_id in (${virtualFilterIds.join(',')}) + and + startTime <= ${startTime}`; + let sql = ''; + if (processFilterIds.length > 0 && virtualFilterIds.length > 0) { + sql = `${processSql} union ${virtualSql}`; + } else { + if (processFilterIds.length > 0) { + sql = processSql; + } else { + sql = virtualSql; + } + } + return query('getTabCounters', sql, {}); +}; +export const getTabCpuByProcess = (cpus: Array, leftNS: number, rightNS: number) => + query( + 'getTabCpuByProcess', + ` + select + B.pid as pid, + sum(B.dur) as wallDuration, + avg(B.dur) as avgDuration, + count(B.tid) as occurrences + from + thread_state AS B + left join + trace_range AS TR + where + B.cpu in (${cpus.join(',')}) + and + not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS )) + group by + B.pid + order by + wallDuration desc;`, + { $rightNS: rightNS, $leftNS: leftNS } + ); +export const getTabCpuByThread = (cpus: Array, leftNS: number, rightNS: number) => + query( + 'getTabCpuByThread', + ` + select + TS.pid as pid, + TS.tid as tid, + TS.cpu, + sum( min(${rightNS},(TS.ts - TR.start_ts + TS.dur)) - max(${leftNS},TS.ts - TR.start_ts)) wallDuration, + count(TS.tid) as occurrences + from + thread_state AS TS + left join + trace_range AS TR + where + TS.cpu in (${cpus.join(',')}) + and + not ((TS.ts - TR.start_ts + TS.dur < $leftNS) or (TS.ts - TR.start_ts > $rightNS)) + group by + TS.cpu, + TS.pid, + TS.tid + order by + wallDuration desc;`, + { $rightNS: rightNS, $leftNS: leftNS } + ); +export const queryCpuData = (cpu: number, startNS: number, endNS: number): Promise> => + query( + 'queryCpuData', + ` + SELECT + B.pid as processId, + B.cpu, + B.tid, + B.itid as id, + B.dur, + B.ts - TR.start_ts AS startTime, + B.arg_setid as argSetID +from thread_state AS B + left join trace_range AS TR +where B.itid is not null + and + B.cpu = $cpu + and + startTime between $startNS and $endNS;`, + { + $cpu: cpu, + $startNS: startNS, + $endNS: endNS, + } + ); + +export const queryCpuFreq = (): Promise> => + query( + 'queryCpuFreq', + ` + select + cpu,id as filterId + from + cpu_measure_filter + where + (name='cpufreq' or name='cpu_frequency') + order by cpu; + ` + ); + +export const queryCpuFreqData = (cpu: number): Promise> => + query( + 'queryCpuFreqData', + ` + select + cpu, + value, + ifnull(dur,tb.end_ts - c.ts) dur, + ts-tb.start_ts as startNS + from + measure c, + trace_range tb + inner join + cpu_measure_filter t + on + c.filter_id = t.id + where + (name = 'cpufreq' or name='cpu_frequency') + and + cpu= $cpu + --order by ts; + `, + { $cpu: cpu } + ); + +export const queryCpuMax = (): Promise> => + query( + 'queryCpuMax', + ` + select + cpu + from + sched_slice + order by + cpu + desc limit 1;` + ); + +export const queryCpuDataCount = () => + query('queryCpuDataCount', 'select count(1) as count,cpu from thread_state where cpu not null group by cpu'); + +export const queryCpuCount = (): Promise> => + query( + 'queryCpuCount', + ` + select max(cpuCount) cpuCount from +(select ifnull((max(cpu) + 1),0) cpuCount from cpu_measure_filter where name in ('cpu_frequency','cpu_idle') + union all + select ifnull((max(callid)+1),0) cpuCount from irq +) A;` + ); + +export const queryCpuSchedSlice = (): Promise> => + query( + 'queryCpuSchedSlice', + ` + select (ts - start_ts) as ts, + itid, + end_state as endState, + priority + from sched_slice,trace_range;` + ); + +export const queryCpuStateFilter = (): Promise> => + query( + 'queryCpuStateFilter', + `select cpu,id as filterId from cpu_measure_filter where name = 'cpu_idle' order by cpu;`, + {} + ); + +export const queryCpuState = (cpuFilterId: number): Promise> => + query( + 'queryCpuState', + ` + select (A.ts - B.start_ts) as startTs,ifnull(dur,B.end_ts - A.ts) dur, + value + from measure A,trace_range B + where filter_id = $filterId;`, + { $filterId: cpuFilterId } + ); + +export const queryCpuMaxFreq = (): Promise> => + query( + 'queryCpuMaxFreq', + ` + select + max(value) as maxFreq + from + measure c + inner join + cpu_measure_filter t + on + c.filter_id = t.id + where + (name = 'cpufreq' or name='cpu_frequency');` + ); +export const queryTraceCpu = (): Promise< + Array<{ + tid: string; + pid: string; + cpu: string; + dur: string; + min_freq: string; + max_freq: string; + avg_frequency: string; + }> +> => + query( + 'queryTraceCpu', + `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 + ` + ); + +export const queryTraceCpuTop = (): Promise< + Array<{ + tid: string; + pid: string; + cpu: string; + duration: string; + min_freq: string; + max_freq: string; + avg_frequency: string; + sumNum: string; + }> +> => + query( + 'queryTraceCpuTop', + `SELECT + ipid AS pid, + itid AS tid, + group_concat(cpu, ',') AS cpu, + group_concat(dur, ',') AS dur, + group_concat(avg_frequency, ',') AS avg_frequency, + group_concat(min_freq, ',') AS min_freq, + group_concat(max_freq, ',') AS max_freq, + 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; + ` + ); +export const queryCpuFreqUsageData = ( + Ids: Array +): Promise< + Array<{ + startNS: number; + filter_id: number; + value: number; + dur: number + }> +> => + query( + 'queryCpuFreqUsageData', + `select + value, + ifnull(dur,tb.end_ts - c.ts) dur, + ts-tb.start_ts as startNS, + filter_id + from + measure c, + trace_range tb + where + c.filter_id in (${Ids.join(',')}) + ` + ); + +export const queryCpuFreqFilterId = (): Promise< + Array<{ + id: number; + cpu: number + }> +> => + query( + 'queryCpuFreqFilterId', + ` + select + id, + cpu + from + cpu_measure_filter + where + name='cpufreq' + or + name='cpu_frequency' + ` + ); +export const searchCpuData = (keyword: string): Promise> => { + let id = parseInt(keyword); + let sql = ` + select B.pid as processId, + B.cpu, + B.tid, + 'cpu' as type, + B.itid as id, + B.dur as dur, + B.ts - TR.start_ts as startTime, + B.arg_setid as argSetID +from thread_state AS B, trace_range TR + left join process p on B.pid = p.pid + left join thread t on B.itid = t.itid +where B.cpu not null and B.ts between TR.start_ts and TR.end_ts + and ( + t.name like '%${keyword}%' + or B.tid = ${Number.isNaN(id) ? -1 : id} + or B.pid = ${Number.isNaN(id) ? -1 : id} + or p.name like '%${keyword}%' + ) +order by startTime;`; + return query('searchCpuData', sql, {}); +}; +export const getTabPaneCounterSampleData = ( + leftNs: number, + rightNs: number, + cpuStateFilterIds: Array +): Promise> => { + let str = ''; + if (cpuStateFilterIds.length > 0) { + str = ` and filter_id in (${cpuStateFilterIds.join(',')})`; + } + return query( + 'getTabPaneCounterSampleData', + ` + select value, filter_id as filterId, ts, f.cpu + from measure left join cpu_measure_filter as f on f.id=filter_id + where + ts <= $rightNs${str} order by ts asc; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); +}; +export const queryJsCpuProfilerConfig = (): Promise> => + query('queryJsCpuProfilerConfig', `SELECT pid, type, enable_cpu_Profiler as enableCpuProfiler FROM js_config`); +export const queryJsCpuProfilerData = (): Promise> => + query('queryJsCpuProfilerData', `SELECT 1 WHERE EXISTS(select 1 from js_cpu_profiler_node)`); +export const querySystemCallsTop = (): Promise< + Array<{ + tid: string; + pid: string; + funName: string; + frequency: string; + minDur: string; + maxDur: string; + avgDur: string; + }> +> => + query( + 'querySystemCallsTop', + `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` + ); +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 getCpuLimitFreqBoxSelect = ( + arr: Array<{ + maxFilterId: string; + minFilterId: string; + cpu: string; + }>, + rightNS: number +): Promise> => { + let ids = []; + let condition = `(case`; + for (let item of arr) { + condition = `${condition} when filter_id in (${item.maxFilterId}, ${item.minFilterId}) then ${item.cpu}`; + ids.push(item.maxFilterId, item.minFilterId); + } + condition = `${condition} else -1 end) as cpu`; + let sql = ` + select + ts - T.start_ts as startNs, + dur, + max(value) as max, + min(value) as min, + ${condition} + from measure,trace_range T + where filter_id in (${ids.join(',')}) + and ts - T.start_ts < ${rightNS} + group by ts + `; + console.log(sql); + return query('getCpuLimitFreqBoxSelect', sql, {}); +}; +export const getCpuLimitFreq = (maxId: number, minId: number, cpu: number): Promise> => + query( + 'getCpuLimitFreq', + ` + select ts - T.start_ts as startNs, + dur, + max(value) as max, + min(value) as min, + $cpu as cpu + from measure,trace_range T where filter_id in ($maxId,$minId) group by ts +`, + { $maxId: maxId, $minId: minId, $cpu: cpu } + ); +export const getCpuLimitFreqId = (): Promise> => + query( + 'getCpuMaxMinFreqId', + ` + select cpu,MAX(iif(name = 'cpu_frequency_limits_max',id,0)) as maxFilterId,MAX(iif(name = 'cpu_frequency_limits_min',id,0)) as minFilterId from cpu_measure_filter where name in ('cpu_frequency_limits_max','cpu_frequency_limits_min') group by cpu +`, + {} + ); + +export const getCpuLimitFreqMax = (filterIds: string): Promise> => { + return query( + 'getCpuLimitFreqMax', + ` + select max(value) as maxValue,filter_id as filterId from measure where filter_id in (${filterIds}) group by filter_id +`, + {} + ); +}; \ No newline at end of file diff --git a/ide/src/trace/database/sql/Dma.sql.ts b/ide/src/trace/database/sql/Dma.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..be120467a7b23e6f5a03ee55529409376b1b0816 --- /dev/null +++ b/ide/src/trace/database/sql/Dma.sql.ts @@ -0,0 +1,178 @@ +/* + * 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. + */ +// VM Tracker Dma泳道图 +import {Dma, DmaComparison} from "../../bean/AbilityMonitor"; +import {query} from "../SqlLite"; +import {SnapshotStruct} from "../ui-worker/ProcedureWorkerSnapshot"; + +export const queryDmaSampsData = (process: number): Promise> => + query( + 'queryDmaSampsData', + `SELECT + (A.ts - B.start_ts) as startNs, + sum(A.size) as value, + A.flag as flag, + A.ipid as ipid, + E.data as expTaskComm + FROM memory_dma A,trace_range B + left join data_dict as E on E.id=A.exp_task_comm_id + WHERE + A.flag = 0 + AND $pid = A.ipid + AND A.ts < B.end_ts + GROUP by A.ts;`, + { $pid: process } + ); + +export const queryisExistsDmaData = (process: number): Promise> => + query( + 'queryisExistsDmaData', + `SELECT EXISTS ( + SELECT 1 + FROM memory_dma A,trace_range B + left join data_dict as E on E.id=A.exp_task_comm_id + WHERE A.flag = 0 + AND $pid = A.ipid + AND A.ts < B.end_ts + GROUP by A.ts + ) AS data_exists`, + { $pid: process } + ); + +//Ability Monitor Dma 框选 +export const getTabDmaAbilityData = (leftNs: number, rightNs: number, dur: number): Promise> => + query( + 'getTabDmaAbilityData', + `SELECT (S.ts-TR.start_ts) as startNs, + MAX(S.size) as maxSize, + MIN(S.size) as minSize, + Avg(S.size) as avgSize, + E.pid as processId, + E.name as processName + from trace_range as TR,memory_dma as S + left join process as E on E.ipid=S.ipid + WHERE + $leftNS <= startNs + ${dur} and $rightNS >= startNs + and flag = 0 + GROUP by E.pid + `, + { $leftNS: leftNs, $rightNS: rightNs } + ); + +//VM Tracker Dma 框选 +export const getTabDmaVmTrackerData = ( + leftNs: number, + rightNs: number, + processId: number, + dur: number +): Promise> => + query( + 'getTabDmaVmTrackerData', + `SELECT (S.ts-TR.start_ts) as startNs, + MAX(S.size) as maxSize, + MIN(S.size) as minSize, + Avg(S.size) as avgSize + from trace_range as TR,memory_dma as S + left join data_dict as C on C.id=S.exp_task_comm_id + where + $leftNS <= startNs + ${dur} and $rightNS >= startNs + and flag = 0 + and + $pid = S.ipid + `, + { $leftNS: leftNs, $rightNS: rightNs, $pid: processId } + ); + +//Ability Monitor Dma 点选 +export const getTabDmaAbilityClickData = (startNs: number): Promise> => + query( + 'getTabDmaAbilityClickData', + `SELECT + (S.ts-TR.start_ts) as startNs, + S.fd as fd, + S.size as size, + S.ino as ino, + S.exp_pid as expPid, + buf_name_id as bufName, + exp_name_id as expName, + exp_task_comm_id as expTaskComm, + E.pid as processId, + E.name as processName, + S.flag as flag + from trace_range as TR,memory_dma as S + left join process as E on E.ipid=S.ipid + WHERE + startNs = ${startNs} + `, + { $startNs: startNs } + ); + +//VM Tracker Dma 点选 +export const getTabDmaVMTrackerClickData = (startNs: number, processId: number): Promise> => + query( + 'getTabDmaVMTrackerClickData', + `SELECT + (S.ts-TR.start_ts) as startNs, + S.fd as fd, + S.size as size, + S.ino as ino, + S.exp_pid as expPid, + buf_name_id as bufName, + exp_name_id as expName, + exp_task_comm_id as expTaskComm, + S.flag as flag + from trace_range as TR,memory_dma as S + WHERE + startNs = ${startNs} + AND + $pid = S.ipid + `, + { $startNs: startNs, $pid: processId } + ); + +//Ability Monitor Dma 点选比较 +export const getTabDmaAbilityComparisonData = (startNs: number): Promise> => + query( + 'getTabDmaAbilityComparisonData', + `SELECT + (S.ts-TR.start_ts) as startNs, + sum(S.size) as value, + E.pid as processId, + E.name as processName + from trace_range as TR,memory_dma as S + left join process as E on E.ipid=S.ipid + WHERE + startNs = ${startNs} + GROUP by + E.pid + `, + { $startNs: startNs } + ); + +//VM Tracker Dma 点选比较 +export const getTabDmaVmTrackerComparisonData = (startNs: number, processId: number): Promise> => + query( + 'getTabDmaVmTrackerComparisonData', + `SELECT + (S.ts-TR.start_ts) as startNs, + sum(S.size) as value + from trace_range as TR,memory_dma as S + WHERE + startNs = ${startNs} + AND + $pid = S.ipid + `, + { $startNs: startNs, $pid: processId } + ); \ No newline at end of file diff --git a/ide/src/trace/database/sql/Func.sql.ts b/ide/src/trace/database/sql/Func.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..38816624632324af6e8aaebf09cc5788b63807bc --- /dev/null +++ b/ide/src/trace/database/sql/Func.sql.ts @@ -0,0 +1,415 @@ +/* + * 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 { FuncNameCycle } from "../../bean/BinderProcessThread"; +import { query } from "../SqlLite"; +import { FuncStruct } from "../ui-worker/ProcedureWorkerFunc"; +import { SearchFuncBean } from "../../bean/SearchFuncBean"; +import { SelectionData } from "../../bean/BoxSelection"; +import { HeapTraceFunctionInfo } from "../../../js-heap/model/DatabaseStruct"; + +export const queryLoopFuncNameCycle = ( + funcName: string, + tIds: string, + leftNS: number, + rightNS: number +): Promise> => + query( + 'queryLoopFuncNameCycle', + ` + SELECT + c.name AS funcName, + c.ts - r.start_ts AS cycleStartTime, + 0 AS cycleDur, + c.id, + t.tid, + p.pid + FROM + callstack c, trace_range r + LEFT JOIN + thread t + ON + c.callid = t.id + LEFT JOIN + process p + ON + t.ipid = p.id + WHERE + c.name = '${funcName}' + AND + t.tid = ${tIds} + AND NOT + ((cycleStartTime < ${leftNS}) + OR + (cycleStartTime > ${rightNS})) + `, + { + $funcName: funcName, + $tIds: tIds, + $leftNS: leftNS, + $rightNS: rightNS, + } + ); + +export const querySingleFuncNameCycle = ( + funcName: string, + tIds: string, + leftNS: number, + rightNS: number +): Promise> => + query( + 'querySingleFuncNameCycle', + ` + SELECT + c.name AS funcName, + c.ts - r.start_ts AS cycleStartTime, + c.dur AS cycleDur, + c.id, + t.tid, + p.pid, + c.ts - r.start_ts + c.dur AS endTime + FROM + callstack c, trace_range r + LEFT JOIN + thread t + ON + c.callid = t.id + LEFT JOIN + process p + ON + t.ipid = p.id + WHERE + c.name = '${funcName}' + AND + t.tid = ${tIds} + AND NOT + ((cycleStartTime < ${leftNS}) + OR + (endTime > ${rightNS})) + `, + { + $funcName: funcName, + $tIds: tIds, + $leftNS: leftNS, + $rightNS: rightNS, + } + ); +export const queryAllFuncNames = (): Promise> => { + return query( + 'queryAllFuncNames', + ` + select id,name from callstack;` + ); +}; +export const queryProcessAsyncFunc = (_funName?: string): Promise> => + query( + 'queryProcessAsyncFunc', + ` +select tid, + P.pid, + A.name as threadName, + is_main_thread, + c.callid as track_id, + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.parent_id, + c.id, + c.cookie, + c.depth, + c.argsetid +from thread A,trace_range D +left join callstack C on A.id = C.callid +left join process P on P.id = A.ipid +where startTs not null and cookie not null ${_funName ? 'funName=$funName' : ''};`, + { + funName: _funName, + } + ); + +export const getFunDataByTid = (tid: number, ipid: number): Promise> => + query( + 'getFunDataByTid', + ` + select + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.argsetid, + c.depth, + c.id as id, + A.itid as itid, + A.ipid as ipid +from thread A,trace_range D +left join callstack C on A.id = C.callid +where startTs not null and c.cookie is null and tid = $tid and A.ipid = $ipid`, + { $tid: tid, $ipid: ipid } + ); +export const getMaxDepthByTid = (): Promise> => + query( + 'getMaxDepthByTid', + ` + select +tid, +ipid, + MAX(c.depth + 1) as maxDepth +from thread A +left join callstack C on A.id = C.callid +where c.ts not null and c.cookie is null group by tid,ipid`, + {} + ); +export const querySearchFuncData = ( + funcName: string, + tIds: number, + leftNS: number, + rightNS: number +): Promise> => + query( + 'querySearchFuncData', + ` + select + c.ts - r.start_ts as startTime, + c.dur + from + callstack c + left join + thread t + on + c.callid = t.id + left join + process p + on + t.ipid = p.id + left join + trace_range r + where + c.name like '${funcName}%' + and + t.tid = ${tIds} + and + not ((startTime < ${leftNS}) or (startTime > ${rightNS})); + ` + ); +export const querySearchRowFuncData = ( + funcName: string, + tIds: number, + leftNS: number, + rightNS: number +): Promise> => + query( + 'querySearchRowFuncData', + ` + select + c.name as funName, + c.ts - r.start_ts as startTime, + t.tid, + t.name as threadName, + 'func' as type + from + callstack c + left join + thread t + on + c.callid = t.id + left join + process p + on + t.ipid = p.id + left join + trace_range r + where + c.name like '${funcName}' + and + t.tid = ${tIds} + and + not ((startTime < ${leftNS}) or (startTime > ${rightNS})); + `, + { $search: funcName } + ); +export const getTabSlicesAsyncFunc = ( + asyncNames: Array, + asyncPid: Array, + leftNS: number, + rightNS: number +): Promise> => + query( + 'getTabSlicesAsyncFunc', + ` + select + c.name as name, + sum(c.dur) as wallDuration, + avg(c.dur) as avgDuration, + count(c.name) as occurrences + from + thread A, trace_range D + left join + callstack C + on + A.id = C.callid + left join process P on P.id = A.ipid + where + C.ts > 0 + and + c.dur >= -1 + and + c.cookie not null + and + P.pid in (${asyncPid.join(',')}) + and + c.name in (${asyncNames.map((it) => "'" + it + "'").join(',')}) + and + not ((C.ts - D.start_ts + C.dur < $leftNS) or (C.ts - D.start_ts > $rightNS)) + group by + c.name + order by + wallDuration desc;`, + { $leftNS: leftNS, $rightNS: rightNS } + ); +export const querySearchFunc = (search: string): Promise> => + query( + 'querySearchFunc', + ` + select c.cookie, + c.id, + c.name as funName, + c.ts - r.start_ts as startTime, + c.dur, + c.depth, + t.tid, + t.name as threadName, + p.pid, + c.argsetid, + 'func' as type + from callstack c left join thread t on c.callid = t.id left join process p on t.ipid = p.id + left join trace_range r + where c.name like '%${search}%' and startTime > 0; + `, + { $search: search } + ); + +export const querySceneSearchFunc = (search: string, processList: Array): Promise> => + query( + 'querySearchFunc', + ` + select c.cookie, + c.id, + c.name as funName, + c.ts - r.start_ts as startTime, + c.dur, + c.depth, + t.tid, + t.name as threadName, + p.pid, + c.argsetid, + 'func' as type + from callstack c left join thread t on c.callid = t.id left join process p on t.ipid = p.id + left join trace_range r + where c.name like '%${search}%' ESCAPE '\\' and startTime > 0 and p.pid in (${processList.join(',')}); + `, + { $search: search } + ); +export const queryHeapFunction = (fileId: number): Promise> => + query( + 'queryHeapFunction', + `SELECT function_index as index ,function_id as id ,name,script_name as scriptName,script_id as scriptId,line,column + FROM js_heap_trace_function_info WHERE file_id = ${fileId}` + ); +export const queryHeapTraceNode = (fileId: number): Promise> => + query( + 'queryHeapTraceNode', + `SELECT F.name, + F.script_name as scriptName, + F.script_id as scriptId, + F.column, + F.line, + N.id, + N.function_info_index as functionInfoIndex, + N.parent_id as parentId, + N.count, + N.size, + IFNULL( S.live_count, 0 ) AS liveCount, + IFNULL( S.live_size, 0 ) AS liveSize + FROM + js_heap_trace_node N + LEFT JOIN ( + SELECT + trace_node_id as traceNodeId, + SUM( self_size ) AS liveSize, + count( * ) AS liveCount + FROM + js_heap_nodes + WHERE + file_id = ${fileId} + AND trace_node_id != 0 + GROUP BY + trace_node_id + ) S ON N.id = S.trace_node_id + LEFT JOIN js_heap_trace_function_info F ON (F.file_id = N.file_id + AND F.function_index = N.function_info_index) + WHERE + N.file_id = ${fileId} + ORDER BY + N.id` + ); +export const queryTaskPoolOtherRelationData = ( + ids: Array, + tid: number +): Promise< + Array +> => { + let sqlStr = `select + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.argsetid, + c.depth, + c.id as id, + A.itid as itid, + A.ipid as ipid + from thread A,trace_range D + left join callstack C on A.id = C.callid + where startTs not null and c.cookie is null and tid = $tid and c.id in (${ids.join(',')})`; + return query('queryTaskPoolOtherRelationData', sqlStr, { $ids: ids, $tid: tid }); +}; + +export const queryTaskPoolRelationData = ( + ids: Array, + tids: Array +): Promise< + Array +> => { + const sqlArray: Array = []; + if (ids.length > 0) { + for (let index = 0; index < ids.length; index++) { + if (index !== 0) { + sqlArray.push(`or`); + } + sqlArray.push(`( tid = ${tids[index]} and c.id = ${ids[index]})`); + } + } + let sql = sqlArray.join(' '); + let sqlStr = `select + c.ts-D.start_ts as startTs, + c.dur, + c.name as funName, + c.argsetid, + c.depth, + c.id as id, + A.itid as itid, + A.ipid as ipid + from thread A,trace_range D + left join callstack C on A.id = C.callid + where startTs not null and c.cookie is null and (${sql})`; + return query('queryTaskPoolRelationData', sqlStr); +}; \ No newline at end of file diff --git a/ide/src/trace/database/sql/Gpu.sql.ts b/ide/src/trace/database/sql/Gpu.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..ced201410e01828e3cba7e0f4ba26fcfd85747d2 --- /dev/null +++ b/ide/src/trace/database/sql/Gpu.sql.ts @@ -0,0 +1,250 @@ +/* + * 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. + */ +// VM Tracker Gpu Resourcet泳道图 +import type {SnapshotStruct} from "../ui-worker/ProcedureWorkerSnapshot"; +import {query} from "../SqlLite"; + +export const queryGpuResourceData = (categoryNameId: number): Promise> => + query( + 'queryGpuResourceData', + `SELECT + subquery1.startNs, + IFNULL(subquery1.totalSize, 0) as aSize, + IFNULL(subquery2.size, 0) as bSize, + (IFNULL(subquery1.totalSize, 0) - IFNULL(subquery2.size, 0)) AS value + FROM + (SELECT (ts - start_ts) AS startNs,SUM(total_size) AS totalSize + FROM memory_profile, trace_range + WHERE ts between start_ts and end_ts + GROUP BY ts) AS subquery1 + LEFT JOIN + (SELECT (ts - start_ts) AS startNs, SUM(size) AS size + FROM memory_window_gpu, trace_range + WHERE ts between start_ts and end_ts + AND category_name_id = ${categoryNameId} + GROUP BY ts) AS subquery2 + ON subquery1.startNs = subquery2.startNs` + ); +export const queryisExistsGpuResourceData = (categoryNameId: number): Promise> => + query( + 'queryisExistsGpuResourceData', + `SELECT EXISTS ( + SELECT 1 + FROM + (SELECT (ts - start_ts) AS startNs + FROM memory_profile, trace_range + WHERE ts between start_ts and end_ts + GROUP BY ts) AS subquery1 + LEFT JOIN + (SELECT (ts - start_ts) AS startNs + FROM memory_window_gpu, trace_range + WHERE ts between start_ts and end_ts + AND category_name_id = ${categoryNameId} + GROUP BY ts) AS subquery2 + ON subquery1.startNs = subquery2.startNs + ) AS data_exists + ` + ); + +// VM Tracker Gpu Resource Tab页 +export const queryGpuResourceTabData = ( + startNs: number +): Promise> => + query( + 'queryGpuResourceTabData', + `SELECT (ts - start_ts) as startNs, channel_id as channelId, sum(total_size) as totalSize + FROM memory_profile, trace_range + WHERE (ts - start_ts) = ${startNs} + GROUP by ts, channelId` + ); + + +export const queryGpuTotalType = (): Promise> => + query( + 'queryGpuTotalType', + ` + select distinct module_name_id id,data + from memory_window_gpu A, trace_range TR left join data_dict B on A.module_name_id = B.id + where window_name_id = 0 + and A.ts < TR.end_ts + ` + ); + +export const queryGpuDataByTs = ( + ts: number, + window: number, + module: number | null +): Promise< + Array<{ + windowNameId: number; + windowId: number; + moduleId: number; + categoryId: number; + size: number; + }> +> => { + let condition = + module === null + ? `and window_name_id = ${window}` + : `and window_name_id = ${window} and module_name_id = ${module}`; + let sql = `select window_name_id as windowNameId, + window_id as windowId, + module_name_id as moduleId, + category_name_id as categoryId, + size + from memory_window_gpu, trace_range + where ts - start_ts = ${ts} ${condition} + `; + return query('queryGpuDataByTs', sql); +}; + +export const queryGpuTotalData = (moduleId: number | null): Promise> => { + let moduleCondition = moduleId === null ? '' : `and module_name_id = ${moduleId}`; + let sql = ` + select (ts - start_ts) startNs, sum(size) value + from memory_window_gpu,trace_range + where window_name_id = 0 ${moduleCondition} + and ts< end_ts + group by ts; + `; + return query('queryGpuTotalData', sql); +}; + +// GL 或 Graph 泳道图 +export const queryGpuData = (ipid: number, name: string): Promise> => { + let sql = ` + select (ts - start_ts) startNs,sum(value) value + from process_measure, trace_range + where filter_id = ( + select id + from process_measure_filter + where name = ${name} and ipid = ${ipid} + ) + and ts between start_ts and end_ts + group by ts; + `; + return query('queryGpuData', sql); +}; +// 判断VM Tracker Gl或 Graph泳道图是否有数据 +export const queryisExistsGpuData = ( + ipid: number, + name: string +): Promise> => { + let sql = ` + SELECT EXISTS ( + SELECT 1 + FROM process_measure, trace_range + WHERE filter_id = ( + SELECT id + FROM process_measure_filter + WHERE name = ${name} AND ipid = ${ipid} + ) + AND ts BETWEEN start_ts AND end_ts + ) AS data_exists; + `; + return query('queryGpuData', sql); +}; + +// GL 或 Graph 框选Tab页 +export const queryGpuDataTab = ( + ipid: number, + leftNs: number, + rightNs: number, + interval: number, + name: string +): Promise> => { + let sql = ` + select (ts - start_ts) startTs,sum(value) * 1024 size + from process_measure, trace_range + where filter_id = ( + select id + from process_measure_filter + where name = ${name} and ipid = ${ipid} + ) + and not ((startTs + ${interval} < ${leftNs}) or (startTs > ${rightNs})) + group by ts; + `; + return query('queryGpuGLDataByRange', sql); +}; + +export const queryGpuDataByRange = ( + leftNs: number, + rightNs: number, + interval: number +): Promise< + Array<{ + startTs: number; + windowId: number; + moduleId: number; + categoryId: number; + avgSize: number; + maxSize: number; + minSize: number; + }> +> => { + let sql = `select (ts - start_ts) startTs, + window_name_id windowId, + module_name_id moduleId, + category_name_id categoryId, + avg(size) avgSize, + max(size) maxSize, + min(size) minSize + from memory_window_gpu,trace_range + where not ((startTs + ${interval} < ${leftNs}) or (startTs > ${rightNs})) + group by window_name_id,module_name_id,category_name_id + order by avgSize DESC; + `; + return query('queryGpuWindowData', sql); +}; + +export const queryGpuWindowData = ( + windowId: number, + moduleId: number | null +): Promise> => { + let moduleCondition = moduleId === null ? '' : `and module_name_id = ${moduleId}`; + let sql = ` + select (ts - start_ts) startNs, sum(size) value + from memory_window_gpu,trace_range + where window_name_id = ${windowId} ${moduleCondition} + and ts < end_ts + group by ts; + `; + return query('queryGpuWindowData', sql); +}; + +export const queryGpuWindowType = (): Promise> => + query( + 'queryGpuWindowType', + ` + select distinct A.window_name_id as id,B.data, null as pid +from memory_window_gpu A, trace_range tr left join data_dict B on A.window_name_id = B.id +where window_name_id != 0 +and A.ts < tr.end_ts +union all +select distinct A.module_name_id id, B.data, A.window_name_id pid +from memory_window_gpu A, trace_range TR left join data_dict B on A.module_name_id = B.id +where window_name_id != 0 +and A.ts < TR.end_ts + ` + ); +export const queryGpuDur = (id: number): Promise => + query( + 'queryGpuDur', + ` + SELECT dur AS gpu_dur + FROM gpu_slice + WHERE frame_row = $id;`, + { $id: id } + ); \ No newline at end of file diff --git a/ide/src/trace/database/sql/Irq.sql.ts b/ide/src/trace/database/sql/Irq.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..96cf6e1c08778c106b2b81c8f6090f0f4d944b6b --- /dev/null +++ b/ide/src/trace/database/sql/Irq.sql.ts @@ -0,0 +1,80 @@ +/* + * 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 {query} from "../SqlLite"; +import {IrqStruct} from "../ui-worker/ProcedureWorkerIrq"; + +export const queryIrqList = (): Promise> => + query('queryIrqList', `select cat as name,callid as cpu from irq where cat!= 'ipi' group by cat,callid`); + +export const queryAllIrqNames = (): Promise> => { + return query( + 'queryAllIrqNames', + `select id,case when cat = 'ipi' then 'IPI' || name else name end as ipiName, name from irq;` + ); +}; +export const queryIrqData = (callid: number, cat: string): Promise> => { + let sqlSoftIrq = ` + select i.ts - t.start_ts as startNS,i.dur,i.name,i.depth,argsetid as argSetId,i.id from irq i, +trace_range t where i.callid = ${callid} and i.cat = 'softirq' + `; + let sqlIrq = ` + select i.ts - t.start_ts as startNS,i.dur, + case when i.cat = 'ipi' then 'IPI' || i.name else i.name end as name, + i.depth, + argsetid as argSetId, + i.id + from irq i,trace_range t + where i.callid = ${callid} and ((i.cat = 'irq' and i.flag ='1') or i.cat = 'ipi') + `; + return query('queryIrqData', cat === 'irq' ? sqlIrq : sqlSoftIrq, {}); +}; + +export const queryIrqDataBoxSelect = (callIds: Array, startNS: number, endNS: number): Promise> => { + let sqlIrq = ` +select case when i.cat = 'ipi' then 'IPI' || i.name else i.name end as irqName, + sum(dur) as wallDuration, + max(dur) as maxDuration, + count(1) as count, + avg(ifnull(dur, 0)) as avgDuration +from irq i, + trace_range t +where ((i.cat = 'irq' and i.flag = '1') or i.cat = 'ipi') + and callid in (${callIds.join(',')}) + and max(i.ts - t.start_ts, ${startNS}) <= min(i.ts - t.start_ts + dur, ${endNS}) +group by irqName; + `; + return query('queryIrqDataBoxSelect', callIds.length > 0 ? sqlIrq : '', {}); +}; + +export const querySoftIrqDataBoxSelect = ( + callIds: Array, + startNS: number, + endNS: number +): Promise> => { + let sqlIrq = ` +select i.name as irqName, + sum(dur) as wallDuration, + max(dur) as maxDuration, + count(1) as count, + avg(ifnull(dur, 0)) as avgDuration +from irq i, + trace_range t +where callid in (${callIds.join(',')}) + and i.cat = 'softirq' + and max(i.ts - t.start_ts, ${startNS}) <= min(i.ts - t.start_ts + dur, ${endNS}) +group by irqName; + `; + return query('querySoftIrqDataBoxSelect', callIds.length > 0 ? sqlIrq : '', {}); +}; \ No newline at end of file diff --git a/ide/src/trace/database/sql/Janks.sql.ts b/ide/src/trace/database/sql/Janks.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..e62de9559dc3677e1a5bd552d2c1d2d9cd2866c9 --- /dev/null +++ b/ide/src/trace/database/sql/Janks.sql.ts @@ -0,0 +1,213 @@ +/* + * 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 {JanksStruct} from "../../bean/JanksStruct"; +import {query} from "../SqlLite"; + +export const queryExpectedFrameDate = (): Promise> => + query( + 'queryExpectedFrameDate', + ` + SELECT + sf.id, + 'frameTime' as frame_type, + fs.ipid, + fs.vsync as name, + fs.dur as app_dur, + (sf.ts + sf.dur - fs.ts) as dur, + (fs.ts - TR.start_ts) AS ts, + fs.type, + fs.flag, + pro.pid, + pro.name as cmdline, + (sf.ts - TR.start_ts) AS rs_ts, + sf.vsync AS rs_vsync, + sf.dur AS rs_dur, + sf.ipid AS rs_ipid, + proc.pid AS rs_pid, + proc.name AS rs_name + FROM frame_slice AS fs + LEFT JOIN process AS pro ON pro.id = fs.ipid + LEFT JOIN frame_slice AS sf ON fs.dst = sf.id + LEFT JOIN process AS proc ON proc.id = sf.ipid + LEFT JOIN trace_range TR + WHERE fs.dst IS NOT NULL + AND fs.type = 1 + UNION + SELECT + -1 as id, + 'frameTime' as frame_type, + fs.ipid, + fs.vsync as name, + fs.dur as app_dur, + fs.dur, + (fs.ts - TR.start_ts) AS ts, + fs.type, + fs.flag, + pro.pid, + pro.name as cmdline, + NULL AS rs_ts, + NULL AS rs_vsync, + NULL AS rs_dur, + NULL AS rs_ipid, + NULL AS rs_pid, + NULL AS rs_name + FROM frame_slice AS fs + LEFT JOIN process AS pro ON pro.id = fs.ipid + LEFT JOIN trace_range TR + WHERE fs.dst IS NULL + AND pro.name NOT LIKE '%render_service%' + AND fs.type = 1 + ORDER BY ts;` + ); +export const queryJumpJanksData = (processId: number, vsync: number): Promise> => + query( + 'queryJumpJanksData', + ` + SELECT + fs.id, + fs.ts - TR.start_ts as ts, + fs.vsync AS name, + fs.type, + fs.dur, + 0 as depth, + 'app' as frame_type, + fs.src as src_slice, + fs.flag as jank_tag, + fs.dst as dst_slice, + p.pid, + p.name AS cmdline + FROM frame_slice AS fs, trace_range as TR + LEFT JOIN process AS p ON fs.ipid = p.ipid + WHERE fs.type = 0 and p.pid = $processId and fs.vsync = $vsync;`,{ $processId: processId, $vsync: vsync } + ); +export const queryAllJankProcess = (): Promise< + Array<{ + pid: number; + }> +> => + query( + 'queryAllJankProcess', + ` + SELECT DISTINCT p.pid + FROM frame_slice AS a + LEFT JOIN process AS p ON a.ipid = p.ipid + ` + ); +export const queryAllActualData = (): Promise> => + query( + 'queryAllActualData', + ` + SELECT + a.id, + (a.ts - TR.start_ts) AS ts, + a.vsync AS name, + a.type, + a.dur, + a.src AS src_slice, + a.flag AS jank_tag, + a.dst AS dst_slice, + p.pid, + p.name AS cmdline, + (case when p.name like '%render_service' then 'render_service' else 'app' end) as frame_type + FROM frame_slice AS a, trace_range AS TR + LEFT JOIN process AS p ON a.ipid = p.ipid + WHERE a.type = 0 + AND a.flag <> 2 + ORDER BY a.ipid, ts;` + ); +export const queryActualFrameDate = (): Promise> => + query( + 'queryActualFrameDate', + `SELECT + sf.id, + 'frameTime' as frame_type, + fs.ipid, + fs.vsync as name, + fs.dur as app_dur, + (sf.ts + sf.dur - fs.ts) as dur, + (fs.ts - TR.start_ts) AS ts, + fs.type, + (case when (sf.flag == 1 or fs.flag == 1 ) then 1 when (sf.flag == 3 or fs.flag == 3 ) then 3 else 0 end) as jank_tag, + pro.pid, + pro.name as cmdline, + (sf.ts - TR.start_ts) AS rs_ts, + sf.vsync AS rs_vsync, + sf.dur AS rs_dur, + sf.ipid AS rs_ipid, + proc.pid AS rs_pid, + proc.name AS rs_name + FROM frame_slice AS fs + LEFT JOIN process AS pro ON pro.id = fs.ipid + LEFT JOIN frame_slice AS sf ON fs.dst = sf.id + LEFT JOIN process AS proc ON proc.id = sf.ipid + LEFT JOIN trace_range TR + WHERE fs.dst IS NOT NULL + AND fs.type = 0 + AND fs.flag <> 2 + UNION + SELECT + -1 as id, + 'frameTime' as frame_type, + fs.ipid, + fs.vsync as name, + fs.dur as app_dur, + fs.dur, + (fs.ts - TR.start_ts) AS ts, + fs.type, + fs.flag as jank_tag, + pro.pid, + pro.name as cmdline, + NULL AS rs_ts, + NULL AS rs_vsync, + NULL AS rs_dur, + NULL AS rs_ipid, + NULL AS rs_pid, + NULL AS rs_name + FROM frame_slice AS fs + LEFT JOIN process AS pro ON pro.id = fs.ipid + LEFT JOIN trace_range TR + WHERE fs.dst IS NULL + AND pro.name NOT LIKE '%render_service%' + AND fs.type = 0 + AND fs.flag <> 2 + ORDER BY ts;` + ); +export const querySelectRangeData = ( + allPid: Array, + leftNs: number, + rightNs: number): Promise> => + query( + 'querySelectRangeData', + ` + SELECT + a.id, + (a.ts - TR.start_ts) AS startTs, + a.vsync AS name, + a.type, + a.dur, + a.src AS src_slice, + a.flag AS jank_tag, + a.dst AS dst_slice, + p.pid, + p.name AS cmdline, + (case when p.name like '%render_service' then 'render_service' else 'app' end) as frame_type + FROM frame_slice AS a, trace_range AS TR + LEFT JOIN process AS p ON a.ipid = p.ipid + WHERE a.type = 0 + AND a.flag <> 2 + AND startTs + dur >= ${leftNs} + AND startTs <= ${rightNs} + AND p.pid IN (${allPid.join(',')});` + ); \ No newline at end of file diff --git a/ide/src/trace/database/sql/Memory.sql.ts b/ide/src/trace/database/sql/Memory.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..40d52376954d60cc7221c280d979c442c3312c61 --- /dev/null +++ b/ide/src/trace/database/sql/Memory.sql.ts @@ -0,0 +1,469 @@ +/* + * 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. + */ +// VM Tracker Gpu Memory泳道图 +import type {SnapshotStruct} from "../ui-worker/ProcedureWorkerSnapshot"; +import {query} from "../SqlLite"; +import {GpuMemory, GpuMemoryComparison} from "../../bean/AbilityMonitor"; +import type {MemoryConfig} from "../../bean/MemoryConfig"; + +export const queryGpuMemoryData = (processId: number): Promise> => + query( + 'queryGpuMemorySampsData', + `SELECT + (A.ts - B.start_ts) as startNs, + sum(A.used_gpu_size) as value, + A.ipid as ipid + FROM memory_process_gpu A,trace_range B + WHERE + $pid = A.ipid + AND A.ts < B.end_ts + GROUP by A.ts;`, + { $pid: processId } + ); + +// 判断VM Tracker Gpu Memory泳道图是否有数据 +export const queryisExistsGpuMemoryData = (processId: number): Promise> => + query( + 'queryisExistsGpuMemoryData', + `SELECT EXISTS ( + SELECT 1 + FROM memory_process_gpu A, trace_range B + WHERE $pid = A.ipid + AND A.ts < B.end_ts + GROUP BY A.ts + ) AS data_exists`, + { $pid: processId } + ); +//VM Tracker SkiaGpuMemory 框选 +export const getTabGpuMemoryData = ( + leftNs: number, + rightNs: number, + processId: number, + dur: number +): Promise> => + query( + 'getTabGpuMemoryData', + `SELECT + (S.ts-TR.start_ts) as startNs, + gpu_name_id as gpuNameId, + T.tid as threadId, + T.name as threadName, + MAX(S.used_gpu_size) as maxSize, + MIN(S.used_gpu_size) as minSize, + Avg(S.used_gpu_size) as avgSize + from trace_range as TR,memory_process_gpu as S + left join thread as T on T.itid=S.itid + where + $leftNS <= startNs + ${dur} + and + $rightNS >= startNs + and + $pid = S.ipid + group by gpu_name_id,threadId + `, + { $leftNS: leftNs, $rightNS: rightNs, $pid: processId } + ); +//VM Tracker SkiaGpuMemory 点选 +export const getTabGpuMemoryVMTrackerClickData = (startNs: number, processId: number): Promise> => + query( + 'getTabGpuMemoryVMTrackerClickData', + `SELECT + (S.ts-TR.start_ts) as startNs, + S.used_gpu_size as size, + T.tid as threadId, + T.name as threadName, + A.data as gpuName + from trace_range as TR,memory_process_gpu as S + left join thread as T on T.itid=S.itid + left join data_dict as A on A.id=S.gpu_name_id + WHERE + startNs = ${startNs} + AND + $pid = S.ipid + `, + { $startNs: startNs, $pid: processId } + ); + +//VM Tracker Gpu Memory 点选比较 +export const getTabGpuMemoryVmTrackerComparisonData = ( + startNs: number, + processId: number +): Promise> => + query( + 'getTabGpuMemoryVmTrackerComparisonData', + `SELECT + (S.ts-TR.start_ts) as startNs, + sum(S.used_gpu_size) as value, + T.tid as threadId, + T.name as threadName, + S.gpu_name_id as gpuNameId + from trace_range as TR,memory_process_gpu as S + left join thread as T on T.itid=S.itid + WHERE + startNs = ${startNs} + AND + $pid = S.ipid + `, + { $startNs: startNs, $pid: processId } + ); +export const queryMemFilterIdMaxValue = (): Promise> => { + return query( + 'queryMemFilterIdMaxValue', + `select filter_id as filterId,max(value) maxValue from process_measure group by filter_id;` + ); +}; +export const getTabVirtualMemoryType = (startTime: number, endTime: number): Promise> => + query( + 'getTabVirtualMemoryType', + ` + SELECT type from paged_memory_sample s,trace_range t + WHERE s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts group by type`, + { $startTime: startTime, $endTime: endTime }, + 'exec' + ); +export const queryNativeMemoryRealTime = (): Promise> => + query( + 'queryNativeMemoryRealTime', + `select cs.ts,cs.clock_name from datasource_clockid dc left join clock_snapshot cs on dc.clock_id = cs.clock_id where data_source_name = 'memory-plugin' or data_source_name = 'nativehook' +`, + {} + ); +export const queryJsMemoryData = (): Promise> => + query('queryJsMemoryData', `SELECT 1 WHERE EXISTS(SELECT 1 FROM js_heap_nodes)`); + +export const queryVmTrackerShmData = (iPid: number): Promise> => + query( + 'queryVmTrackerShmData', + `SELECT (A.ts - B.start_ts) as startNs, + sum(A.size) as value + FROM + memory_ashmem A,trace_range B + where + A.ipid = ${iPid} + AND A.ts < B.end_ts + and + flag = 0 + GROUP by A.ts`, + {} + ); +export const queryVmTrackerShmSelectionData = (startNs: number, ipid: number): Promise> => + query( + 'queryVmTrackerShmSelectionData', + `SELECT (A.ts - B.start_ts) as startNS,A.ipid, + A.fd,A.size,A.adj,A.ashmem_name_id as name, + A.ashmem_id as id,A.time,A.purged,A.ref_count as count, + A.flag + FROM memory_ashmem A,trace_range B + where startNS = ${startNs} and ipid = ${ipid};`, + {} + ); +export const queryMemoryConfig = (): Promise> => + query( + 'queryMemoryConfiig', + `SELECT ipid as iPid, process.pid AS pid, + process.name AS processName, + (SELECT value FROM trace_config WHERE trace_source = 'memory_config' AND key = 'sample_interval') AS interval + FROM + trace_config + LEFT JOIN process ON value = ipid + WHERE + trace_source = 'memory_config' + AND key = 'ipid' + ;` + ); +// VM Tracker Purgeable泳道图 +export const queryPurgeableProcessData = (ipid: number, isPin?: boolean): Promise> => { + const pinSql = isPin ? ' AND a.ref_count > 0' : ''; + const names = isPin ? " ('mem.purg_pin')" : "('mem.purg_sum')"; + return query( + 'queryPurgeableProcessData', + `SELECT startNs, sum( value ) AS value + FROM + (SELECT + m.ts - tr.start_ts AS startNs, + sum(m.value) AS value + FROM + process_measure m, + trace_range tr + LEFT JOIN process_measure_filter f ON f.id = m.filter_id + WHERE + m.ts < tr.end_ts + AND f.name = ${names} + AND f.ipid = ${ipid} + GROUP BY m.ts + UNION ALL + SELECT + a.ts - tr.start_ts AS startNs, + sum( a.pss ) AS value + FROM + memory_ashmem a, + trace_range tr + WHERE + a.ts < tr.end_ts + AND a.flag = 0 + AND a.ipid = ${ipid} + ${pinSql} + GROUP BY a.ts) + GROUP BY startNs` + ); +}; +export const queryVirtualMemory = (): Promise> => + query('queryVirtualMemory', `select id,name from sys_event_filter where type='sys_virtual_memory_filter'`); +export const queryVirtualMemoryData = (filterId: number): Promise> => + query( + 'queryVirtualMemoryData', + `select ts-${ + (window as any).recordStartNS + } as startTime,value,filter_id as filterID from sys_mem_measure where filter_id=$filter_id`, + { $filter_id: filterId } + ); +export const queryTraceMemory = (): Promise< + Array<{ + maxNum: string; + minNum: string; + avgNum: string; + name: string; + processName: string; + }> +> => + query( + 'queryTraceMemory', + ` + 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` + ); + +export const queryTraceMemoryTop = (): Promise< + Array<{ + maxNum: string; + minNum: string; + avgNum: string; + name: string; + processName: string; + }> +> => + query( + 'queryTraceMemoryTop', + ` + 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` + ); + +export const queryTraceMemoryUnAgg = (): Promise< + Array<{ + processName: string; + name: string; + value: string; + ts: string; + }> +> => + query( + 'queryTraceMemoryUnAgg', + ` + 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` + ); +export const queryMemoryMaxData = (memoryName: string): Promise> => + query( + 'queryMemoryMaxData', + `SELECT ifnull(max(m.value),0) as maxValue, + filter_id + from sys_mem_measure m + WHERE m.filter_id = + (SELECT id FROM sys_event_filter WHERE name = $memoryName) +`, + { $memoryName: memoryName } + ); +export const getTabPaneVirtualMemoryStatisticsData = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabPaneVirtualMemoryStatisticsData', + ` + select p.pid, + t.tid, + ifnull(p.name,'Process') as pname, + ifnull(t.name,'Thread') as tname, + f.type, + f.ipid, + f.itid, + count(f.ipid) as count, + sum(dur) as allDuration, + min(dur) as minDuration, + max(dur) as maxDuration, + avg(dur) as avgDuration + from paged_memory_sample as f left join process as p on f.ipid=p.ipid left join thread as t on f.itid=t.itid + where f.end_ts >= $leftNs + and f.end_ts <= $rightNs + group by f.type,f.ipid,f.itid + order by f.type; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); +export const getFileSysVirtualMemoryChartData = (): Promise> => + query( + 'getFileSysVirtualMemoryChartData', + ` + select + (A.start_ts -B.start_ts) as startNS, + (A.end_ts - B.start_ts) as endNS, + dur as dur + from paged_memory_sample A,trace_range B + where startNS > 0 + order by A.start_ts;`, + {}, + 'exec' + ); +export const hasFileSysData = (): Promise> => + query( + 'hasFileSysData', + ` + select + fsCount, + vmCount, + ioCount from + (select count(1) as fsCount from file_system_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) ) + ,(select count(1) as vmCount from paged_memory_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) ) + ,(select count(1) as ioCount from bio_latency_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) ); + `, + {} + ); +export const queryEbpfSamplesCount = (startTime: number, endTime: number, ipids: number[]): Promise> => + query( + 'queryEbpfSamplesCount', + ` + select +fsCount, + vmCount from +(select count(1) as fsCount from file_system_sample s,trace_range t where s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts ${ + ipids.length > 0 ? `and s.ipid in (${ipids.join(',')})` : '' + }) +,(select count(1) as vmCount from paged_memory_sample s,trace_range t where s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts ${ + ipids.length > 0 ? `and s.ipid in (${ipids.join(',')})` : '' + }); +`, + { $startTime: startTime, $endTime: endTime } + ); +export const queryisExistsShmData = (iPid: number): Promise> => + query( + 'queryisExistsShmData', + `SELECT EXISTS ( + SELECT 1 + FROM memory_ashmem A,trace_range B + where A.ipid = ${iPid} + AND A.ts < B.end_ts + AND flag = 0 + GROUP BY A.ts + ) AS data_exists`, + {} + ); +export const queryVmTrackerShmSizeData = ( + leftNs: number, + rightNs: number, + iPid: number, + dur: number +): Promise> => + query( + 'queryVmTrackerShmSizeData', + `SELECT ( A.ts - B.start_ts ) AS startNS, + A.flag, + avg( A.size ) AS avg, + max( A.size ) AS max, + min( A.size ) AS min, + sum( A.size ) AS sum + FROM + memory_ashmem A, + trace_range B + WHERE + startNS <= ${rightNs} and (startNS+ ${dur}) >=${leftNs} + AND ipid = ${iPid}`, + {} + ); +export const queryisExistsPurgeableData = (ipid: number, isPin?: boolean): Promise> => { + const pinSql = isPin ? ' AND a.ref_count > 0' : ''; + const names = isPin ? " ('mem.purg_pin')" : "('mem.purg_sum')"; + return query( + 'queryisExistsPurgeableData', + `SELECT EXISTS ( + SELECT 1 + FROM + (SELECT 1 + FROM + process_measure m, + trace_range tr + LEFT JOIN process_measure_filter f ON f.id = m.filter_id + WHERE + m.ts < tr.end_ts + AND f.name = ${names} + AND f.ipid = ${ipid} + UNION ALL + SELECT 1 + FROM + memory_ashmem a, + trace_range tr + WHERE + a.ts < tr.end_ts + AND a.flag = 0 + AND a.ipid = ${ipid} + ${pinSql}) + ) AS data_exists` + ); +}; \ No newline at end of file diff --git a/ide/src/trace/database/sql/NativeHook.sql.ts b/ide/src/trace/database/sql/NativeHook.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..b173065179f27f9b38793782789043c681dd214b --- /dev/null +++ b/ide/src/trace/database/sql/NativeHook.sql.ts @@ -0,0 +1,234 @@ +/* + * 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 {query} from "../SqlLite"; +import {NativeHookMalloc, NativeHookProcess, NativeHookSampleQueryInfo} from "../../bean/NativeHook"; + +export const queryNativeHookResponseTypes = ( + leftNs: number, + rightNs: number, + types: Array, + isStatistic: boolean +): Promise> => { + const table = isStatistic ? 'native_hook_statistic' : 'native_hook'; + const tsKey = isStatistic ? 'ts' : 'start_ts'; + const type = isStatistic ? 'type' : 'event_type'; + return query( + 'queryNativeHookResponseTypes', + ` + select + distinct last_lib_id as lastLibId, + data_dict.data as value + from + ${table} A ,trace_range B + left join data_dict on A.last_lib_id = data_dict.id + where + A.${tsKey} - B.start_ts + between ${leftNs} and ${rightNs} and A.${type} in (${types.join(',')}); + `, + { $leftNs: leftNs, $rightNs: rightNs, $types: types } + ); +}; +export const queryNativeHookStatistics = ( + leftNs: number, + rightNs: number, + ipid: number +): Promise> => + query( + 'queryNativeHookStatistics', + ` + select + event_type as eventType, + sub_type_id as subTypeId, + max(heap_size) as max, + sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte, + sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount, + sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte, + sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount + from + native_hook A, + trace_range B + where + (A.start_ts - B.start_ts) between ${leftNs} and ${rightNs} + and (event_type = 'AllocEvent' or event_type = 'MmapEvent') + and ipid = ${ipid} + group by event_type;`, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const queryNativeHookStatisticsMalloc = ( + leftNs: number, + rightNs: number, + ipid: number +): Promise> => + query( + 'queryNativeHookStatisticsMalloc', + ` + select + event_type as eventType, + heap_size as heapSize, + sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte, + sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount, + sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte, + sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount + from + native_hook A, + trace_range B + where + (A.start_ts - B.start_ts) between ${leftNs} and ${rightNs} + and + (event_type = 'AllocEvent' or event_type = 'MmapEvent') + and + sub_type_id is null + and ipid = ${ipid} + group by + event_type, + heap_size + order by heap_size desc + `, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const queryNativeHookStatisticsSubType = ( + leftNs: number, + rightNs: number, + ipid: number +): Promise> => + query( + 'queryNativeHookStatisticsSubType', + ` + select + event_type as eventType, + sub_type_id as subTypeId, + max(heap_size) as max, + sum(case when ((NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte, + sum(case when ((NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount, + sum(case when ((NH.end_ts - TR.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte, + sum(case when ((NH.end_ts - TR.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount + from + native_hook NH, + trace_range TR + where + (NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs} + and + (event_type = 'MmapEvent') + and ipid = ${ipid} + group by + event_type,sub_type_id; + `, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const queryNativeHookSubType = (leftNs: number, rightNs: number, ipid: number): Promise> => + query( + 'queryNativeHookSubType', + `select distinct( + case when sub_type_id is null then -1 else sub_type_id end +) as subTypeId, +(case when sub_type_id is null then 'Other MmapEvent' else DD.data end) as subType + from + native_hook NH, + trace_range TR + left join data_dict DD on NH.sub_type_id = DD.id +where event_type = 'MmapEvent' and + (NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs} + and ipid = ${ipid} + `, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const queryNativeHookStatisticSubType = (leftNs: number, rightNs: number, ipid: number): Promise> => + query( + 'queryNativeHookStatisticSubType', + `SELECT DISTINCT + CASE + WHEN type = 3 AND sub_type_id NOT NULL THEN sub_type_id + ELSE type + END AS subTypeId, + CASE + WHEN type = 2 THEN 'FILE_PAGE_MSG' + WHEN type = 3 AND sub_type_id NOT NULL THEN D.data + WHEN type = 3 THEN 'MEMORY_USING_MSG' + ELSE 'Other MmapEvent' + END AS subType + FROM + native_hook_statistic NHS + LEFT JOIN data_dict D ON NHS.sub_type_id = D.id, + trace_range TR + WHERE + NHS.type >= 1 AND + (NHS.ts - TR.start_ts) between ${leftNs} and ${rightNs} + AND ipid = ${ipid} + `, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const queryNativeHookStatisticsCount = (): Promise> => + query('queryNativeHookStatisticsCount', `select count(1) num from native_hook_statistic`, {}); + +export const queryNativeHookProcess = (table: string): Promise> => { + let sql = ` + select + distinct ${table}.ipid, + pid, + name + from + ${table} + left join + process p + on + ${table}.ipid = p.id + `; + return query('queryNativeHookProcess', sql, {}); +}; + +export const queryNativeHookSnapshotTypes = (ipid: number): Promise> => + query( + 'queryNativeHookSnapshotTypes', + ` +select + event_type as eventType, + data as subType + from + native_hook left join data_dict on native_hook.sub_type_id = data_dict.id + where + (event_type = 'AllocEvent' or event_type = 'MmapEvent') + and ipid = ${ipid} + group by + event_type,data;`, + {} + ); + +export const queryAllHookData = (rightNs: number, ipid: number): Promise> => + query( + 'queryAllHookData', + ` + select + callchain_id as eventId, + event_type as eventType, + data as subType, + addr, + heap_size as growth, + (n.start_ts - t.start_ts) as startTs, + (n.end_ts - t.start_ts) as endTs + from + native_hook n left join data_dict on n.sub_type_id = data_dict.id, + trace_range t + where + (event_type = 'AllocEvent' or event_type = 'MmapEvent') + and ipid = ${ipid} + and + n.start_ts between t.start_ts and ${rightNs} + t.start_ts`, + { $rightNs: rightNs } + ); \ No newline at end of file diff --git a/ide/src/trace/database/sql/Perf.sql.ts b/ide/src/trace/database/sql/Perf.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..929eaccde0fc4449f864b32230b7dd0e20841f3b --- /dev/null +++ b/ide/src/trace/database/sql/Perf.sql.ts @@ -0,0 +1,463 @@ +/* + * 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 {PerfCmdLine, PerfFile, PerfSample, PerfStack, PerfThread} from "../../bean/PerfProfile"; +import {query} from "../SqlLite"; +import {GpuCountBean, SearchGpuFuncBean} from "../../bean/GpufreqBean"; +import {HiSysEventStruct} from "../ui-worker/ProcedureWorkerHiSysEvent"; +import {TaskTabStruct} from "../../component/trace/sheet/task/TabPaneTaskFrames"; + +export const queryPerfFiles = (): Promise> => + query('queryPerfFiles', `select file_id as fileId,symbol,path from perf_files`, {}); + +export const queryPerfCallChainName = (): Promise> => + query('queryPerfCallChainName', `select callchain_id,depth,name from perf_callchain`, {}); + +export const queryPerfProcess = (): Promise> => + query( + 'queryPerfThread', + `select process_id as pid,thread_name as processName from perf_thread where process_id = thread_id`, + {} + ); + +export const queryPerfThread = (): Promise> => + query( + 'queryPerfThread', + `select a.thread_id as tid, + a.thread_name as threadName, + a.process_id as pid, + b.thread_name as processName +from perf_thread a + left join (select distinct process_id, thread_name from perf_thread where process_id = thread_id) b + on a.process_id = b.process_id +order by pid;`, + {} + ); +export const queryPerfSampleListByTimeRange = ( + leftNs: number, + rightNs: number, + cpus: Array, + processes: Array, + threads: Array, + eventTypeId?: number +): Promise> => { + let sql = ` +select A.callchain_id as sampleId, + A.thread_id as tid, + C.thread_name as threadName, + A.thread_state as state, + C.process_id as pid, + (timestamp_trace - R.start_ts) as time, + cpu_id as core +from perf_sample A,trace_range R +left join perf_thread C on A.thread_id = C.thread_id +where time >= $leftNs and time <= $rightNs and A.thread_id != 0 + `; + if (eventTypeId !== undefined) { + sql = `${sql} and event_type_id = ${eventTypeId}`; + } + if (cpus.length != 0 || processes.length != 0 || threads.length != 0) { + let arg1 = cpus.length > 0 ? `or core in (${cpus.join(',')}) ` : ''; + let arg2 = processes.length > 0 ? `or pid in (${processes.join(',')}) ` : ''; + let arg3 = threads.length > 0 ? `or tid in (${threads.join(',')})` : ''; + let arg = `${arg1}${arg2}${arg3}`.substring(3); + sql = `${sql} and (${arg})`; + } + return query('queryPerfSampleListByTimeRange', sql, { + $leftNs: leftNs, + $rightNs: rightNs, + }); +}; + +export const queryPerfSampleIdsByTimeRange = ( + leftNs: number, + rightNs: number, + cpus: Array, + processes: Array, + threads: Array +): Promise> => { + let sql = ` +select A.callchain_id as sampleId +from perf_sample A,trace_range R +left join perf_thread C on A.thread_id = C.thread_id +where (timestamp_trace - R.start_ts) >= $leftNs and (timestamp_trace - R.start_ts) <= $rightNs and A.thread_id != 0 + `; + if (cpus.length != 0 || processes.length != 0 || threads.length != 0) { + let arg1 = cpus.length > 0 ? `or A.cpu_id in (${cpus.join(',')}) ` : ''; + let arg2 = processes.length > 0 ? `or C.process_id in (${processes.join(',')}) ` : ''; + let arg3 = threads.length > 0 ? `or A.thread_id in (${threads.join(',')})` : ''; + let arg = `${arg1}${arg2}${arg3}`.substring(3); + sql = `${sql} and (${arg})`; + } + return query('queryPerfSampleIdsByTimeRange', sql, { + $leftNs: leftNs, + $rightNs: rightNs, + }); +}; + +export const queryPerfSampleCallChain = (sampleId: number): Promise> => + query( + 'queryPerfSampleCallChain', + ` + select + callchain_id as callChainId, + callchain_id as sampleId, + file_id as fileId, + symbol_id as symbolId, + vaddr_in_file as vaddrInFile, + name as symbol +from perf_callchain where callchain_id = $sampleId; + `, + { $sampleId: sampleId } + ); + +export const queryPerfCmdline = (): Promise> => + query( + 'queryPerfCmdline', + ` + select report_value from perf_report where report_type = 'cmdline' + `, + {} + ); +export const queryPerfEventType = (): Promise> => + query( + 'queryPerfEventType', + ` + select id,report_value as report from perf_report where id in ( +select distinct event_type_id from perf_sample); + `, + {} + ); +/** + * HiPerf + */ +export const queryHiPerfEventList = (): Promise> => + query('queryHiPerfEventList', `select id,report_value from perf_report where report_type='config_name'`, {}); +export const queryHiPerfEventListData = (eventTypeId: number): Promise> => + query( + 'queryHiPerfEventListData', + ` + select s.callchain_id, + (s.timestamp_trace-t.start_ts) startNS + from perf_sample s,trace_range t + where + event_type_id=${eventTypeId} + and s.thread_id != 0 + and s.callchain_id != -1; +`, + { $eventTypeId: eventTypeId } + ); +export const queryHiPerfEventData = (eventTypeId: number, cpu: number): Promise> => + query( + 'queryHiPerfEventList', + ` + select s.callchain_id, + (s.timestamp_trace-t.start_ts) startNS + from perf_sample s,trace_range t + where + event_type_id=${eventTypeId} + and cpu_id=${cpu} + and s.thread_id != 0 + and s.callchain_id != -1; +`, + { $eventTypeId: eventTypeId, $cpu: cpu } + ); +export const queryHiPerfCpuData = (cpu: number): Promise> => + query( + 'queryHiPerfCpuData', + ` + select s.callchain_id, + (s.timestamp_trace-t.start_ts) startNS, event_count, event_type_id + from perf_sample s,trace_range t + where + cpu_id=${cpu} + and s.thread_id != 0;`, + { $cpu: cpu } + ); +export const queryHiPerfCpuMergeData = (): Promise> => + query( + 'queryHiPerfCpuData', + `select s.callchain_id,(s.timestamp_trace-t.start_ts) startNS, event_count, event_type_id from perf_sample s,trace_range t +where s.thread_id != 0;`, + {} + ); +export const queryHiPerfCpuMergeData2 = (): Promise> => + query( + 'queryHiPerfCpuData2', + `select distinct cpu_id from perf_sample where thread_id != 0 order by cpu_id desc;`, + {} + ); + +export const queryHiPerfProcessData = (pid: number): Promise> => + query( + 'queryHiPerfProcessData', + ` +SELECT sp.callchain_id, + th.thread_name, + th.thread_id tid, + th.process_id pid, + sp.timestamp_trace - tr.start_ts startNS, + event_count, + event_type_id +from perf_sample sp, + trace_range tr + left join perf_thread th on th.thread_id = sp.thread_id +where pid = ${pid} and sp.thread_id != 0 `, + { $pid: pid } + ); + +export const queryHiPerfThreadData = (tid: number): Promise> => + query( + 'queryHiPerfThreadData', + ` +SELECT sp.callchain_id, + th.thread_name, + th.thread_id tid, + th.process_id pid, + sp.timestamp_trace - tr.start_ts startNS, + event_count, + event_type_id +from perf_sample sp, + trace_range tr + left join perf_thread th on th.thread_id = sp.thread_id +where tid = ${tid} and sp.thread_id != 0 ;`, + { $tid: tid } + ); +export const getGpufreqDataCut = ( + tIds: string, + funcName: string, + leftNS: number, + rightNS: number, + single: boolean, + loop: boolean +): Promise> => { + let queryCondition: string = ''; + if (single) { + queryCondition += `select s.funName,s.startTime,s.dur,s.startTime+s.dur as endTime,s.depth,s.tid,s.threadName,s.pid from state s + where endTime between ${leftNS} and ${rightNS}`; + } + if (loop) { + queryCondition += `select s.funName,s.startTime,s.loopEndTime-s.startTime as dur,s.loopEndTime as endTime,s.depth,s.tid,s.threadName,s.pid from state s + where endTime between ${leftNS} and ${rightNS} `; + } + return query( + 'getGpufreqDataCut', + ` + with state as + (select + * + from + (select + c.name as funName, + c.ts - r.start_ts as startTime, + c.dur, + lead(c.ts - r.start_ts, 1, null) over( order by c.ts - r.start_ts) loopEndTime, + c.depth, + t.tid, + t.name as threadName, + p.pid + from + callstack c + left join + thread t on c.callid = t.id + left join + process p on t.ipid = p.id + left join + trace_range r + where + c.name like '%${funcName}%' + and + tid = '${tIds}' + and + startTime between ${leftNS} and ${rightNS})) + ${queryCondition} + `, + { $search: funcName } + ); +}; +export const getGpufreqData = (leftNS: number, rightNS: number, earliest: boolean): Promise> => { + let queryCondition: string = ''; + if (!earliest) { + queryCondition += ` where not ((s.ts - r.start_ts + ifnull(s.dur,0) < ${leftNS}) or (s.ts - r.start_ts > ${rightNS}))`; + } + return query( + 'getGpufreqData', + ` + with state as + (select + name, + filter_id, + ts, + endts, + endts-ts as dur, + type, + value + from + (select + measure.filter_id, + clock_event_filter.name, + measure.ts, + lead(ts, 1, null) over( order by measure.ts) endts, + measure.type, + measure.value + from + clock_event_filter, + trace_range + left join + measure + where + clock_event_filter.name = 'gpufreq' + and + clock_event_filter.type = 'clock_set_rate' + and + clock_event_filter.id = measure.filter_id + order by measure.ts) + where + endts is not null + ) + select + s.name as thread, + s.filter_id as filterId, + s.value/1000000 as freq, + s.value*s.dur as count, + s.value, + s.ts, + s.ts-r.start_ts as startNS, + s.dur, + s.endts- r.start_ts as endTime + from + state s, + trace_range r + ${queryCondition} + order by ts + `, + { $leftNS: leftNS, $rightNS: rightNS } + ); +}; +export const queryHiSysEventTabData = (leftNs: number, rightNs: number): Promise> => + query( + 'queryHiSysEventTabData', + `SELECT S.id, + D2.data AS domain, + D.data AS eventName, + type AS eventType, + time_zone AS tz, + pid, + tid, + uid, + info, + level, + seq, + contents, + S.ts - TR.start_ts AS startTs, + 1 AS dur, + CASE + WHEN level = 'MINOR' THEN + 0 + WHEN level = 'CRITICAL' THEN + 1 + END AS depth + FROM hisys_all_event AS S ,trace_range AS TR + LEFT JOIN data_dict AS D on S.event_name_id = D.id + LEFT JOIN data_dict AS D2 on S.domain_id = D2.id + WHERE S.id is not null + and startTs >= ${Math.floor(leftNs)} + and startTs <= ${Math.floor(rightNs)} + ORDER BY S.ts` + ); +export const queryHiSysEventData = (): Promise> => + query( + 'queryHiSysEventData', + `SELECT l.ts - tr.start_ts as startNs FROM hisys_all_event AS l, trace_range tr WHERE startNs > 0 LIMIT 1` + ); +export const queryHiPerfProcessCount = ( + leftNs: number, + rightNs: number, + cpus: Array, + threads: Array, + processes: Array +): Promise> => { + let str = ''; + if (processes.length > 0) { + str = ` and C.process_id in (${processes.join(',')})`; + } + if (threads.length > 0) { + str = ` and A.thread_id in (${threads.join(',')}) `; + } + if (processes.length > 0 && threads.length > 0) { + str = ` and (C.process_id in (${processes.join(',')}) or A.thread_id in (${threads.join(',')}))`; + } + if (cpus.length > 0) { + str = ` and A.cpu_id in (${cpus.join(',')})`; + } + if (cpus.length > 0 && processes.length > 0) { + str = ` and (C.process_id in (${processes.join(',')}) or A.cpu_id in (${cpus.join(',')}))`; + } + return query( + 'queryHiPerfProcessCount', + ` + select C.process_id as pid, + (A.timestamp_trace - R.start_ts) as time, + C.thread_name as threadName, + A.thread_id as tid, + A.id, + A.callchain_id + from perf_sample A,trace_range R + left join perf_thread C on A.thread_id = C.thread_id and A.thread_id != 0 + where time >= $leftNs and time <= $rightNs and A.callchain_id > 0 + ${str} + `, + { $leftNs: leftNs, $rightNs: rightNs } + ); +}; +export const queryTransferList = (): Promise> => + query('queryTransferList', `select id, report_value as cmdStr from perf_report where report_type = 'config_name'`); +export const queryConcurrencyTask = ( + itid: number, + selectStartTime: number, + selectEndTime: number +): Promise => + query( + 'queryConcurrencyTask', + `SELECT thread.tid, + thread.ipid, + callstack.name AS funName, + callstack.ts AS startTs, + (case when callstack.dur = -1 then (SELECT end_ts FROM trace_range) else callstack.dur end) as dur, + callstack.id, + task_pool.priority, + task_pool.allocation_task_row AS allocationTaskRow, + task_pool.execute_task_row AS executeTaskRow, + task_pool.return_task_row AS returnTaskRow, + task_pool.execute_id AS executeId + FROM thread + LEFT JOIN callstack ON thread.id = callstack.callid + LEFT JOIN task_pool ON callstack.id = task_pool.execute_task_row + WHERE ipid in (SELECT thread.ipid + FROM thread + WHERE thread.itid = $itid) + AND thread.name = 'TaskWorkThread' + AND callstack.name LIKE 'H:Task Perform:%' + AND -- 左包含 + (($selectStartTime <= callstack.ts AND $selectEndTime > callstack.ts) + OR -- 右包含 + ($selectStartTime < callstack.ts + callstack.dur AND $selectEndTime >= callstack.ts + callstack.dur) + OR -- 包含 + ($selectStartTime >= callstack.ts AND $selectEndTime <= callstack.ts + + (case when callstack.dur = -1 then (SELECT end_ts FROM trace_range) else callstack.dur end)) + OR -- 被包含 + ($selectStartTime <= callstack.ts AND $selectEndTime >= callstack.ts + callstack.dur)) + ORDER BY callstack.ts;`, + { $itid: itid, $selectStartTime: selectStartTime, $selectEndTime: selectEndTime } + ); \ No newline at end of file diff --git a/ide/src/trace/database/sql/ProcessThread.sql.ts b/ide/src/trace/database/sql/ProcessThread.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..f641a2947d491c9bbd5f1577a11d11c49439f49a --- /dev/null +++ b/ide/src/trace/database/sql/ProcessThread.sql.ts @@ -0,0 +1,1273 @@ +/* + * 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 { BinderItem } from "../../bean/BinderProcessThread"; +import { query } from "../SqlLite"; +import { SelectionData } from "../../bean/BoxSelection"; +import { ThreadStruct } from "../ui-worker/ProcedureWorkerThread"; +import { WakeupBean } from "../../bean/WakeupBean"; +import { SPTChild } from "../../bean/StateProcessThread"; +import { BinderArgBean } from "../../bean/BinderArgBean"; +import { ProcessMemStruct } from "../ui-worker/ProcedureWorkerMem"; +import { AppStartupStruct } from "../ui-worker/ProcedureWorkerAppStartup"; +import { SoStruct } from "../ui-worker/ProcedureWorkerSoInit"; +import { LiveProcess, ProcessHistory } from "../../bean/AbilityMonitor"; +import { EnergyAnomalyStruct } from "../ui-worker/ProcedureWorkerEnergyAnomaly"; + +export const queryBinderByThreadId = ( + pIds: number[], + tIds: Array, + leftNS: number, + rightNS: number +): Promise> => + query( + 'queryBinderByThreadId', + ` + SELECT + c.name, + 1 AS count, + c.ts - r.start_ts AS ts, + c.dur, + c.ts - r.start_ts AS startTime, + c.ts - r.start_ts + c.dur AS endTime, + t.tid, + p.pid + FROM + callstack c, trace_range r + LEFT JOIN + thread t + ON + c.callid = t.id + LEFT JOIN + process p + ON + t.ipid = p.id + WHERE + c.name in ('binder transaction', 'binder async rcv', 'binder reply', 'binder transaction async') + AND + t.tid in (${tIds.join(',')}) + AND + p.pid in (${pIds.join(',')}) + AND NOT + ((startTime < ${leftNS}) + OR + (endTime > ${rightNS})) + `, + { + $pIds: pIds, + $tIds: tIds, + $leftNS: leftNS, + $rightNS: rightNS, + } + ); +export const getTabBindersCount = ( + pIds: number[], + tIds: number[], + leftNS: number, + rightNS: number +): Promise> => + query( + 'getTabBindersCount', + ` + SELECT + c.name, + c.dur, + 1 AS count, + c.ts, + c.ts - r.start_ts AS startTime, + c.ts -r.start_ts + c.dur AS endTime, + t.tid, + p.pid + FROM + callstack c, trace_range r + LEFT JOIN + thread t + ON + c.callid = t.id + LEFT JOIN + process p + ON + t.ipid = p.id + WHERE + c.name in ('binder transaction', 'binder async rcv', 'binder reply', 'binder transaction async') + AND + t.tid in (${tIds.join(',')}) + AND + p.pid in (${pIds.join(',')}) + AND NOT + ((startTime < ${leftNS}) + OR + (endTime > ${rightNS})); + `, + { + $pIds: pIds, + $tIds: tIds, + $leftNS: leftNS, + $rightNS: rightNS, + } + ); + +export const queryLoopCutData = ( + funcName: string, + tIds: string, + leftStartNs: number, + rightEndNs: number +): Promise> => + query( + 'queryLoopCutData', + ` + select + c.id, + c.name, + c.ts as cycleStartTime, + c.depth, + t.tid, + p.pid + from callstack c + left join + thread t on c.callid = t.id + left join + process p on t.ipid = p.id + where + c.name = '${funcName}' + and + t.tid = '${tIds}' + and + not ((c.ts < $leftStartNs) or (c.ts > $rightEndNs)) + order by + c.ts + `, + { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs } + ); + +export const querySingleCutData = ( + funcName: string, + tIds: string, + leftStartNs: number, + rightEndNs: number +): Promise> => + query( + 'querySingleCutData', + ` + select + c.id, + c.name, + c.ts as cycleStartTime, + c.ts + c.dur as cycleEndTime, + c.depth, + t.tid, + p.pid, + c.dur + from + callstack c + left join + thread t on c.callid = t.id + left join + process p on t.ipid = p.id + left join + trace_range r + where + c.name = '${funcName}' + and + t.tid = '${tIds}' + and + not ((c.ts < $leftStartNs) or (c.ts + ifnull(c.dur, 0) > $rightEndNs)) + `, + { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs } + ); + +export const querySchedThreadStates = ( + tIds: Array, + leftStartNs: number, + rightEndNs: number +): Promise> => + query( + 'getTabThreadStates', + ` + select + B.id, + B.pid, + B.tid, + B.state, + B.type, + B.dur, + B.ts, + B.dur + B.ts as endTs + from + thread_state AS B + where + B.tid in (${tIds.join(',')}) + and + not ((B.ts + ifnull(B.dur,0) < $leftStartNs) or (B.ts > $rightEndNs)) + order by + B.pid; + `, + { $leftStartNs: leftStartNs, $rightEndNs: rightEndNs } + ); +// 框选区域内sleeping的时间 +export const getTabSleepingTime = (tIds: Array, leftNS: number, rightNS: number): Promise> => + query( + 'getTabRunningPersent', + ` + select + B.pid, + B.tid, + B.state, + B.cpu, + B.dur, + B.ts + from + thread_state AS B + left join + trace_range AS TR + where + B.tid in (${tIds.join(',')}) + and + B.state='Sleeping' + and + not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) + order by + ts;`, + { $leftNS: leftNS, $rightNS: rightNS } + ); +export const getTabThreadStatesCpu = (tIds: Array, leftNS: number, rightNS: number): Promise> => { + let sql = ` +select + B.pid, + B.tid, + B.cpu, + sum( min(${rightNS},(B.ts - TR.start_ts + B.dur)) - max(${leftNS},B.ts - TR.start_ts)) wallDuration +from thread_state as B +left join trace_range as TR +where cpu notnull + and B.tid in (${tIds.join(',')}) + and not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) +group by B.tid, B.pid, B.cpu;`; + return query('getTabThreadStatesCpu', sql, { + $leftNS: leftNS, + $rightNS: rightNS, + }); +}; + +// 框选区域内running的时间 +export const getTabRunningPersent = (tIds: Array, leftNS: number, rightNS: number): Promise> => + query( + 'getTabRunningPersent', + ` + select + B.pid, + B.tid, + B.state, + B.cpu, + B.dur, + B.ts + from + thread_state AS B + left join + trace_range AS TR + where + B.tid in (${tIds.join(',')}) + and + B.state='Running' + and + not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) + order by + ts;`, + { $leftNS: leftNS, $rightNS: rightNS } + ); +export const queryThreadData = (tid: number, pid: number): Promise> => + query( + 'queryThreadData', + ` + select + B.itid as id + , B.tid + , B.cpu + , B.ts - TR.start_ts AS startTime + , B.dur + , B.state + , B.pid + , B.arg_setid as argSetID +from thread_state AS B + left join trace_range AS TR +where B.tid = $tid and B.pid = $pid;`, + { $tid: tid, $pid: pid } + ); +export const queryThreadNearData = (itid: number, startTime: number): Promise> => + query( + 'queryThreadNearData', + ` +select itid,tid,pid,cpu,state,arg_setid as argSetID,dur,max((A.ts - B.start_ts)) as startTime +from thread_state A,trace_range B +where itid = ${itid} +and (A.ts - B.start_ts) < ${startTime} and A.ts > B.start_ts +union +select itid,tid,pid,cpu,state,arg_setid as argSetID,dur,min((A.ts - B.start_ts)) as startTime +from thread_state A,trace_range B +where itid = ${itid} +and (A.ts - B.start_ts) > ${startTime} and A.ts < B.end_ts; + `, + {} + ); +export const queryThreadWakeUpFrom = (itid: number, startTime: number): Promise> => { + let sql = ` +select (A.ts - B.start_ts) as ts, + A.tid, + A.itid, + A.pid, + A.cpu, + A.dur, + A.arg_setid as argSetID +from thread_state A,trace_range B +where A.state = 'Running' +and A.itid = (select wakeup_from from instant where ts = ${startTime} and ref = ${itid} limit 1) +and (A.ts - B.start_ts) < (${startTime} - B.start_ts) +order by ts desc limit 1 + `; + return query('queryThreadWakeUpFrom', sql, {}); +}; + + +export const queryRunnableTimeByRunning = (tid: number, startTime: number): Promise> => { + let sql = ` +select ts from thread_state,trace_range where ts + dur -start_ts = ${startTime} and state = 'R' and tid=${tid} limit 1 + `; + return query('queryRunnableTimeByRunning', sql, {}); +}; + +export const queryProcess = (): Promise< + Array<{ + pid: number | null; + processName: string | null; + }> +> => + query( + 'queryProcess', + ` + SELECT + pid, processName + FROM + temp_query_process where pid != 0` + ); + +export const queryProcessByTable = (): Promise< + Array<{ + pid: number | null; + processName: string | null; + }> +> => + query( + 'queryProcessByTable', + ` + SELECT + pid, name as processName + FROM + process where pid != 0` + ); + +export const getTabBoxChildData = ( + leftNs: number, + rightNs: number, + cpus: number[], + state: string | undefined, + processId: number | undefined, + threadId: number | undefined +): Promise> => { + let condition = ` + ${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, + IP.pid as processId, + A.name as thread, + B.state as state, + A.tid as threadId, + B.dur as duration, + B.ts - TR.start_ts as startNs, + B.cpu, + C.priority + from + thread_state AS B + left join + thread as A + on + B.itid = A.itid + left join + process AS IP + on + A.ipid = IP.ipid + left join + trace_range AS TR + left join + sched_slice as C + on + B.itid = C.itid + and + C.ts = B.ts + where + B.dur > 0 + and + IP.pid not null + and + not ((B.ts - TR.start_ts + B.dur < ${leftNs}) or (B.ts - TR.start_ts > ${rightNs})) ${condition}; + `; + return query('getTabBoxChildData', sql, {}); +}; +export const getTabStartups = (ids: Array, leftNS: number, rightNS: number): Promise> => { + let sql = ` +select + P.pid, + P.name as process, + (A.start_time - B.start_ts) as startTs, + (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur, + A.start_name as startName +from app_startup A,trace_range B +left join process P on A.ipid = P.ipid +where P.pid in (${ids.join(',')}) +and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS})) +order by start_name;`; + return query('getTabStartups', sql, {}); +}; + +export const getTabStaticInit = (ids: Array, leftNS: number, rightNS: number): Promise> => { + let sql = ` +select + P.pid, + P.name as process, + (A.start_time - B.start_ts) as startTs, + (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur, + A.so_name as soName +from static_initalize A,trace_range B +left join process P on A.ipid = P.ipid +where P.pid in (${ids.join(',')}) +and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS})) +order by dur desc;`; + return query('getTabStaticInit', sql, {}); +}; + +export const queryBinderArgsByArgset = (argset: number): Promise> => + query( + 'queryBinderArgsByArgset', + ` + select + * + from + args_view + where + argset = $argset;`, + { $argset: argset } + ); + +export const queryProcessData = (pid: number, startNS: number, endNS: number): Promise> => + query( + 'queryProcessData', + ` + select ta.cpu, + dur, + ts-${(window as any).recordStartNS} as startTime +from thread_state ta +where ta.cpu is not null and pid=$pid and startTime between $startNS and $endNS;`, + { + $pid: pid, + $startNS: startNS, + $endNS: endNS, + } + ); + +export const queryProcessMem = (): Promise> => + query( + 'queryProcessMem', + ` + select + process_measure_filter.id as trackId, + process_measure_filter.name as trackName, + ipid as upid, + process.pid, + process.name as processName + from + process_measure_filter + join + process using (ipid) + order by trackName;` + ); + +export const queryProcessThreadDataCount = (): Promise> => + query( + `queryProcessThreadDataCount`, + `select pid,count(id) as count + from thread_state + where ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} group by pid;`, + {} + ); + +export const queryProcessFuncDataCount = (): Promise> => + query( + `queryProcessFuncDataCount`, + `select + P.pid, + count(tid) as count + from callstack C + left join thread A on A.id = C.callid + left join process AS P on P.id = A.ipid + where C.ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} + group by pid;`, + {} + ); + +export const queryProcessMemDataCount = (): Promise> => + query( + `queryProcessMemDataCount`, + `select + p.pid as pid, count(value) count + from process_measure c + left join process_measure_filter f on f.id = c.filter_id + left join process p on p.ipid = f.ipid +where f.id not NULL and value>0 + and c.ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} +group by p.pid`, + {} + ); + +export const queryProcessMemData = (trackId: number): Promise> => + query( + 'queryProcessMemData', + ` + select + c.type, + ts, + value, + filter_id as track_id, + c.ts-tb.start_ts startTime + from + process_measure c, + trace_range tb + where + filter_id = $id;`, + { $id: trackId } + ); + +export const queryThreads = (): Promise> => + query('queryThreads', `select id,tid,(ifnull(name,'Thread') || '(' || tid || ')') name from thread where id != 0;`); + +export const queryDataDICT = (): Promise> => query('queryDataDICT', `select * from data_dict;`); + +export const queryAppStartupProcessIds = (): Promise> => + query( + 'queryAppStartupProcessIds', + ` + SELECT pid FROM process + WHERE ipid IN ( + SELECT ipid FROM app_startup + UNION + SELECT t.ipid FROM app_startup a LEFT JOIN thread t ON a.call_id = t.itid +);` + ); + +export const queryTaskPoolProcessIds = (): Promise> => + query( + 'queryAppStartupProcessIds', + `SELECT pid +FROM + process +WHERE + ipid IN ( + SELECT DISTINCT + ( ipid ) + FROM + thread + WHERE + itid IN ( SELECT DISTINCT ( callid ) FROM callstack WHERE name LIKE 'H:Task%' ) + AND name = 'TaskWorkThread' + )` + ); + +export const queryProcessContentCount = (): Promise> => + query(`queryProcessContentCount`, `select pid,switch_count,thread_count,slice_count,mem_count from process;`); +export const queryProcessThreadsByTable = (): Promise> => + query( + 'queryProcessThreadsByTable', + ` + select p.pid as pid,p.ipid as upid,t.tid as tid,p.name as processName,t.name as threadName,t.switch_count as switchCount from thread t left join process p on t.ipid = p.id where t.tid != 0; + ` + ); +export const queryProcessThreads = (): Promise> => + query( + 'queryProcessThreads', + ` + select + the_tracks.ipid as upid, + the_tracks.itid as utid, + total_dur as hasSched, + process.pid as pid, + thread.tid as tid, + process.name as processName, + thread.switch_count as switchCount, + thread.name as threadName + from ( + select ipid,itid from sched_slice group by itid + ) the_tracks + left join (select itid,sum(dur) as total_dur from thread_state where state != 'S' group by itid) using(itid) + left join thread using(itid) + left join process using(ipid) + order by total_dur desc,the_tracks.ipid,the_tracks.itid;`, + {} + ); +export const queryStartupPidArray = (): Promise> => + query( + 'queryStartupPidArray', + ` + select distinct pid +from app_startup A,trace_range B left join process P on A.ipid = p.ipid +where A.start_time between B.start_ts and B.end_ts;`, + {} + ); + +export const queryProcessStartup = (pid: number): Promise> => + query( + 'queryProcessStartup', + ` + select + P.pid, + A.tid, + A.call_id as itid, + (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs, + (case + when A.start_time < B.start_ts then (A.end_time - B.start_ts) + when A.end_time = -1 then 0 + else (A.end_time - A.start_time) end) as dur, + A.start_name as startName +from app_startup A,trace_range B +left join process P on A.ipid = P.ipid +where P.pid = $pid +order by start_name;`, + { $pid: pid } + ); + +export const queryProcessAllAppStartup = (pids: Array): Promise> => + query( + 'queryProcessStartup', + ` + select + P.pid, + A.tid, + A.call_id as itid, + (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs, + (case + when A.start_time < B.start_ts then (A.end_time - B.start_ts) + when A.end_time = -1 then 0 + else (A.end_time - A.start_time) end) as dur, + A.start_name as startName +from app_startup A,trace_range B +left join process P on A.ipid = P.ipid +where P.pid in(${pids.join(',')}) +order by start_name;`, + { $pid: pids } + ); + +export const querySingleAppStartupsName = (pid: number): Promise> => + query( + 'queryAllAppStartupsName', + `select name from process + where pid=$pid`, + { $pid: pid } + ); + +export const queryProcessSoMaxDepth = (): Promise> => + query( + 'queryProcessSoMaxDepth', + `select p.pid,max(depth) maxDepth +from static_initalize S,trace_range B left join process p on S.ipid = p.ipid +where S.start_time between B.start_ts and B.end_ts +group by p.pid;`, + {} + ); +export const queryAllThreadName = (): Promise> => { + return query( + 'queryAllThreadName', + ` + select name,tid from thread;` + ); +}; + +export const queryAllProcessNames = (): Promise> => { + return query( + 'queryAllProcessNames', + ` + select id, name, pid from process;` + ); +}; + +export const queryProcessSoInitData = (pid: number): Promise> => + query( + 'queryProcessSoInitData', + ` + select + P.pid, + T.tid, + A.call_id as itid, + (A.start_time - B.start_ts) as startTs, + (A.end_time - A.start_time) as dur, + A.so_name as soName, + A.depth +from static_initalize A,trace_range B +left join process P on A.ipid = P.ipid +left join thread T on A.call_id = T.itid +where P.pid = $pid;`, + { $pid: pid } + ); + +export const queryThreadAndProcessName = (): Promise> => + query( + 'queryThreadAndProcessName', + ` + select tid id,name,'t' type from thread +union all +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', + `This is the interval from when the task became eligible to run +(e.g.because of notifying a wait queue it was a suspended on) to when it started running.` + ); + +export const queryThreadWakeUp = (itid: number, startTime: number, dur: number): Promise> => + query( + 'queryThreadWakeUp', + ` +select TA.tid,min(TA.ts - TR.start_ts) as ts,TA.pid,TA.dur,TA.state,TA.cpu,TA.itid,TA.arg_setid as argSetID +from + (select min(ts) as wakeTs,ref as itid from instant,trace_range + where name = 'sched_wakeup' + and wakeup_from = $itid + and ts > start_ts + $startTime + and ts < start_ts + $startTime + $dur + group by ref + ) TW +left join thread_state TA on TW.itid = TA.itid +left join trace_range TR +where TA.ts > TW.wakeTs +group by TA.tid,TA.pid; + `, + { $itid: itid, $startTime: startTime, $dur: dur } + ); + +export const getTabRunningPercent = ( + tIds: Array, + leftNS: number, + rightNS: number +): Promise< + Array<{ + pid: number; + tid: number; + cpu: number; + dur: number; + ts: number; + process: string; + thread: string; + }> +> => + query( + 'getTabRunningPercent', + ` + select + B.pid, + B.tid, + B.cpu, + B.dur, + B.ts + from + thread_state AS B + left join + trace_range AS TR + where + B.tid in (${tIds.join(',')}) + and + B.state='Running' + and + not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS})) + order by ts + ` + ); +//VM Purgeable 点选 tab页 +export const queryProcessPurgeableSelectionTab = ( + startNs: number, + ipid: number, + isPin?: boolean +): Promise> => { + const condition = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'"; + const pinSql = isPin ? ' AND ref_count > 0' : ''; + return query( + 'queryProcessPurgeableSelectionTab', + `SELECT + ( CASE WHEN f.name = 'mem.purg_pin' THEN 'PinedPurg' ELSE 'TotalPurg' END ) AS name, + SUM( m.value ) AS value + FROM + process_measure m, + trace_range tr + left join process_measure_filter f on f.id = m.filter_id + WHERE + f.name = ${condition} + AND m.ts - tr.start_ts = ${startNs} + AND f.ipid = ${ipid} + GROUP BY m.ts + UNION + SELECT + 'ShmPurg' AS name, + SUM( pss ) AS size + FROM + memory_ashmem, + trace_range tr + WHERE + ipid = ${ipid} + AND ts - tr.start_ts = ${startNs} + AND flag = 0 + ${pinSql} + GROUP BY ts` + ); +}; +/////////////////////////////////////////////// +//VM Purgeable 框选 tab页 +export const queryProcessPurgeableTab = ( + leftNs: number, + rightNs: number, + dur: number, + ipid: number, + isPin?: boolean +): Promise> => { + const pinSql = isPin ? ' AND ref_count > 0' : ''; + let filterSql = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'"; + return query( + 'queryProcessPurgeableTab', + `SELECT name, MAX(size) AS maxSize, MIN(size) AS minSize, AVG(size) AS avgSize + FROM + (SELECT + 'ShmPurg' AS name, ts - tr.start_ts AS startTs, SUM( pss ) AS size + FROM + memory_ashmem, + trace_range tr + WHERE + ipid = ${ipid} + AND flag = 0 + ${pinSql} + GROUP BY ts + UNION + SELECT + CASE + WHEN f.name = 'mem.purg_pin' THEN + 'PinedPurg' ELSE 'TotalPurg' + END AS name, + m.ts - tr.start_ts AS startTs, + sum( m.value ) AS size + FROM + process_measure m, + trace_range tr + LEFT JOIN process_measure_filter f ON f.id = m.filter_id + WHERE f.name = ${filterSql} + AND f.ipid = ${ipid} + GROUP BY m.ts + ) combined_data, trace_range tr + WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs + GROUP BY name` + ); +}; +export const getTabPowerDetailsData = ( + leftNs: number, + rightNs: number +): Promise< + Array<{ + startNS: number; + eventName: string; + appKey: string; + eventValue: string; + }> +> => + query( + 'getTabPowerDetailsData', + `SELECT + ( S.ts - TR.start_ts ) AS startNS, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + where + D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN') + and + D2.data in ('APPNAME') + GROUP BY + S.serial, + APP.app_key, + D.data, + D2.data + UNION + SELECT + ( S.ts - TR.start_ts ) AS startNS, + D1.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D1 ON D1.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + where + D1.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN') + and + D2.data in ('CHARGE','BACKGROUND_TIME','SCREEN_ON_TIME','SCREEN_OFF_TIME','LOAD','USAGE','DURATION','CAMERA_ID', + 'FOREGROUND_COUNT','BACKGROUND_COUNT','SCREEN_ON_COUNT','SCREEN_OFF_COUNT','COUNT','UID','FOREGROUND_DURATION', + 'FOREGROUND_ENERGY','BACKGROUND_DURATION','BACKGROUND_ENERGY','SCREEN_ON_DURATION','SCREEN_ON_ENERGY', + 'SCREEN_OFF_DURATION','SCREEN_OFF_ENERGY','ENERGY') + and + (S.ts - TR.start_ts) >= $leftNS + and (S.ts - TR.start_ts) <= $rightNS + GROUP BY + S.serial, + APP.app_key, + D1.data, + D2.data + ORDER BY + eventName;`, + { $leftNS: leftNs, $rightNS: rightNs } + ); + +export const getTabPowerBatteryData = ( + rightNs: number +): Promise< + Array<{ + ts: number; + eventName: string; + appKey: string; + eventValue: string; + }> +> => + query( + 'getTabPowerBatteryData', + `select + MAX(S.ts) as ts, + D.data as eventName, + D2.data as appKey, + group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as eventValue + from + trace_range AS TR, + hisys_event_measure as S + left join + data_dict as D + on + D.id=S.name_id + left join + app_name as APP + on + APP.id=S.key_id + left join + data_dict as D2 + on + D2.id=APP.app_key + where + D.data = 'POWER_IDE_BATTERY' + and D2.data in ('GAS_GAUGE','CHARGE','SCREEN','LEVEL','CURRENT','CAPACITY','UID') + and (S.ts - TR.start_ts) >= 0 + and (S.ts - TR.start_ts) <= $rightNS + group by APP.app_key,D.data,D2.data;`, + { $rightNS: rightNs } + ); +export const queryPowerData = (): Promise< + Array<{ + id: number; + startNS: number; + eventName: string; + appKey: string; + eventValue: string; + }> +> => + query( + 'queryPowerData', + `SELECT + S.id, + ( S.ts - TR.start_ts ) AS startNS, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D + ON D.id = S.name_id + LEFT JOIN app_name AS APP + ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 + ON D2.id = APP.app_key + where + D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN') + and + D2.data in ('BACKGROUND_ENERGY','FOREGROUND_ENERGY','SCREEN_ON_ENERGY','SCREEN_OFF_ENERGY','ENERGY','APPNAME') + GROUP BY + S.serial, + APP.app_key, + D.data, + D2.data + ORDER BY + eventName;`, + {} + ); +export const getTabLiveProcessData = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabLiveProcessData', + `SELECT + process.id as processId, + process.name as processName, + process.ppid as responsibleProcess, + process.uud as userName, + process.usag as cpu, + process.threadN as threads, + process.pss as memory, + process.cpu_time as cpuTime, + process.disk_reads as diskReads, + process.disk_writes as diskWrite + FROM + ( + SELECT + tt.process_id AS id, + tt.process_name AS name, + tt.parent_process_id AS ppid, + tt.uid as uud, + tt.cpu_usage as usag, + tt.thread_num AS threadN, + mt.maxTT - TR.start_ts as endTs, + tt.pss_info as pss, + tt.cpu_time, + tt.disk_reads, + tt.disk_writes + FROM + live_process tt + LEFT JOIN trace_range AS TR + LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT + from live_process re GROUP BY re.process_name, re.process_id ) mt + on mt.idd = tt.process_id where endTs >= $rightNS + GROUP BY + tt.process_name, + tt.process_id + ) process ;`, + { $leftNS: leftNs, $rightNS: rightNs } + ); + +export const getTabProcessHistoryData = ( + leftNs: number, + rightNs: number, + processId: number | undefined, + threadId: number | undefined +): Promise> => + query( + 'getTabProcessHistoryData', + `SELECT + process.id as processId, + process.isD as alive, + process.startTS as firstSeen, + process.endTs as lastSeen, + process.name as processName, + process.ppid as responsibleProcess, + process.uuid as userName, + process.cpu_time as cpuTime, + 0 as pss + FROM + ( + SELECT + tt.process_id AS id, + tt.process_name AS name, + tt.parent_process_id AS ppid, + tt.uid AS uuid, + tt.cpu_time, + (mt.minTT - TR.start_ts ) AS startTS, + mt.maxTT - TR.start_ts as endTs, + (mt.maxTT - TR.start_ts - $rightNS) > 0 as isD + FROM + live_process tt + LEFT JOIN trace_range AS TR + LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT + from live_process re GROUP BY re.process_name, re.process_id ) mt + on mt.idd = tt.process_id + GROUP BY + tt.process_name, + tt.process_id + ) process;`, + { + $leftNS: leftNs, + $rightNS: rightNs, + $processID: processId, + $threadID: threadId, + } + ); +export const getTabSlices = ( + funTids: Array, + pids: Array, + leftNS: number, + rightNS: number +): Promise> => + query( + 'getTabSlices', + ` + select + c.name as name, + sum(c.dur) as wallDuration, + avg(c.dur) as avgDuration, + count(c.name) as occurrences + from + thread T, trace_range TR + left join process P on T.ipid = P.id + left join + callstack C + on + T.id = C.callid + where + C.ts > 0 + and + c.dur >= 0 + and + T.tid in (${funTids.join(',')}) + and + P.pid in (${pids.join(',')}) + and + c.cookie is null + and + not ((C.ts - TR.start_ts + C.dur < $leftNS) or (C.ts - TR.start_ts > $rightNS)) + group by + c.name + order by + wallDuration desc;`, + { $leftNS: leftNS, $rightNS: rightNS } + ); +export const getTabThreadStates = (tIds: Array, leftNS: number, rightNS: number): Promise> => + query( + 'getTabThreadStates', + ` + select + B.pid, + B.tid, + B.state, + sum(B.dur) as wallDuration, + avg(ifnull(B.dur,0)) as avgDuration, + count(B.tid) as occurrences + from + thread_state AS B + left join + trace_range AS TR + where + B.tid in (${tIds.join(',')}) + and + not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS)) + group by + B.pid, B.tid, B.state + order by + wallDuration desc;`, + { $leftNS: leftNS, $rightNS: rightNS } + ); + +// 查询线程状态详细信息 +export const getTabThreadStatesDetail = (tIds: Array, leftNS: number, rightNS: number): Promise> => + query( + 'getTabThreadStates', + `select + B.pid, + B.tid, + B.state, + B.ts, + B.dur + from + thread_state AS B + left join + trace_range AS TR + where + B.tid in (${tIds.join(',')}) + and + not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS)) + order by ts;`, + { $leftNS: leftNS, $rightNS: rightNS } + ); +export const queryAnomalyDetailedData = (leftNs: number, rightNs: number): Promise> => + query( + 'queryAnomalyDetailedData', + `select + S.ts, + D.data as eventName, + D2.data as appKey, + group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as Value + from trace_range AS TR,hisys_event_measure as S + left join data_dict as D on D.id=S.name_id + left join app_name as APP on APP.id=S.key_id + left join data_dict as D2 on D2.id=APP.app_key + where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_ALARM_WAKEUP','ANOMALY_KERNEL_WAKELOCK', + 'ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_CPU_ENERGY','ANOMALY_WAKEUP') + and D2.data in ('APPNAME') + and (S.ts - TR.start_ts) >= $leftNS + and (S.ts - TR.start_ts) <= $rightNS + group by S.serial,APP.app_key,D.data,D2.data + union + select + S.ts, + D.data as eventName, + D2.data as appKey, + group_concat((case when S.type == 1 then S.string_value else S.int_value end), ',') as Value + from trace_range AS TR,hisys_event_measure as S + left join data_dict as D on D.id = S.name_id + left join app_name as APP on APP.id = S.key_id + left join data_dict as D2 on D2.id = APP.app_key + where D.data in ('ANOMALY_SCREEN_OFF_ENERGY', 'ANOMALY_ALARM_WAKEUP', 'ANOMALY_KERNEL_WAKELOCK', + 'ANOMALY_RUNNINGLOCK', 'ANORMALY_APP_ENERGY', 'ANOMALY_GNSS_ENERGY', 'ANOMALY_CPU_HIGH_FREQUENCY', 'ANOMALY_CPU_ENERGY', 'ANOMALY_WAKEUP') + and D2.data not in ('pid_', 'tid_', 'type_', 'tz_', 'uid_', 'domain_', 'id_', 'level_', 'info_', 'tag_', 'APPNAME') + and (S.ts - TR.start_ts) >= $leftNS + and (S.ts - TR.start_ts) <= $rightNS + group by S.serial, APP.app_key, D.data, D2.data;`, + { $leftNS: leftNs, $rightNS: rightNs } + ); + +export const queryBySelectExecute = ( + executeId: string, + itid: number +): Promise< + Array<{ + tid: number; + allocation_task_row: number; + execute_task_row: number; + return_task_row: number; + priority: number; + }> +> => { + let sqlStr = `SELECT thread.tid, + task_pool.allocation_task_row, + task_pool.execute_task_row, + task_pool.return_task_row, + task_pool.priority + FROM task_pool + LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row + LEFT JOIN thread ON thread.id = callstack.callid + WHERE task_pool.execute_id = $executeId AND task_pool.execute_itid = $itid; + `; + return query('queryBySelectExecute', sqlStr, { $executeId: executeId, $itid: itid }); +}; \ No newline at end of file diff --git a/ide/src/trace/database/sql/Sdk.sql.ts b/ide/src/trace/database/sql/Sdk.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..220d253a74247dca5735d5c497c7a6fb8d5df5ed --- /dev/null +++ b/ide/src/trace/database/sql/Sdk.sql.ts @@ -0,0 +1,100 @@ +/* + * 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 {query} from "../SqlLite"; +import {CounterStruct} from "../ui-worker/ProduceWorkerSdkCounter"; +import {CounterSummary, SdkSliceSummary} from "../../bean/SdkSummary"; +import {SdkSliceStruct} from "../ui-worker/ProduceWorkerSdkSlice"; + +export const querySdkCount = (sql: string, componentId: number, args?: any): Promise> => + query('querySdkCount', sql, args, 'exec-sdk-' + componentId); + +export const querySdkCounterData = ( + sql: string, + counter_id: number, + componentId: number +): Promise> => + query('querySdkCounterData', sql, { $counter_id: counter_id }, 'exec-sdk-' + componentId); + +export const getTabSdkCounterData = ( + sqlStr: string, + startTime: number, + leftNs: number, + rightNs: number, + counters: Array, + componentId: number +): Promise> => + query( + 'getTabSdkCounterData', + sqlStr, + { + $startTime: startTime, + $leftNs: leftNs, + $rightNs: rightNs, + $counters: counters, + }, + 'exec-sdk-' + componentId + ); + +export const getTabSdkCounterLeftData = ( + sqlStr: string, + leftNs: number, + counters: Array, + componentId: number +): Promise> => + query( + 'getTabSdkCounterLeftData', + sqlStr, + { + $leftNs: leftNs, + $counters: counters, + }, + 'exec-sdk-' + componentId + ); + +export const getTabSdkSliceData = ( + sqlStr: string, + startTime: number, + leftNs: number, + rightNs: number, + slices: Array, + componentId: number +): Promise> => + query( + 'getTabSdkSliceData', + sqlStr, + { + $startTime: startTime, + $leftNs: leftNs, + $rightNs: rightNs, + $slices: slices, + }, + 'exec-sdk-' + componentId + ); + +export const querySdkSliceData = ( + sqlStr: string, + column_id: number, + startNS: number, + endNS: number, + componentId: number +): Promise> => + query( + 'querySdkSliceData', + sqlStr, + { $column_id: column_id, $startNS: startNS, $endNS: endNS }, + 'exec-sdk-' + componentId + ); +export const queryCounterMax = (sqlStr: string, counter_id: number, componentId: number): Promise> => + query('queryCounterMax', sqlStr, { $counter_id: counter_id }, 'exec-sdk-' + componentId); diff --git a/ide/src/trace/database/sql/Smaps.sql.ts b/ide/src/trace/database/sql/Smaps.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..b07780ccdd528fb62156669c946cb14c1a74e23d --- /dev/null +++ b/ide/src/trace/database/sql/Smaps.sql.ts @@ -0,0 +1,161 @@ +/* + * 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 {query} from "../SqlLite"; +import {Smaps} from "../../bean/SmapsStruct"; + +export const querySmapsExits = (): Promise> => + query( + 'querySmapsExits', + `select + event_name + from stat s + where s.event_name = 'trace_smaps' + and s.stat_type ='received' and s.count > 0` + ); + +export const querySmapsData = (columnName: string): Promise> => + query( + 'querySmapsCounterData', + `SELECT (A.timestamp - B.start_ts) as startNs, sum(${columnName}) * 1024 as value, $columnName as name FROM smaps A,trace_range B WHERE A.timestamp < B.end_ts GROUP by A.timestamp;`, + { $columnName: columnName } + ); + +export const querySmapsDataMax = (columnName: string): Promise> => + query( + 'querySmapsDataMax', + ` + SELECT (A.timestamp - B.start_ts) as startNS,sum(${columnName}) as max_value FROM smaps A,trace_range B GROUP by A.timestamp order by max_value desc LIMIT 1` + ); + +export const getTabSmapsMaxSize = (leftNs: number, rightNs: number, dur: number): Promise> => + query( + 'getTabSmapsMaxRss', + ` +SELECT (A.timestamp - B.start_ts) as startNS, sum(virtaul_size) *1024 as max_value FROM smaps A,trace_range B where startNS <= $rightNs and (startNS+$dur)>=$leftNs`, + { $rightNs: rightNs, $leftNs: leftNs, $dur: dur } + ); + +export const getTabSmapsData = (leftNs: number, rightNs: number, dur: number): Promise> => + query( + 'getTabSmapsData', + ` + SELECT + (A.timestamp - t.start_ts) AS startNs, + start_addr as startAddr, + end_addr as endAddr, + A.type, + resident_size * 1024 AS rss, + protection_id as pid, + pss * 1024 as pss,virtaul_size * 1024 AS size,reside,A.path_id AS path, + shared_clean * 1024 as sharedClean,shared_dirty * 1024 as sharedDirty,private_clean * 1024 as privateClean, + private_dirty * 1024 as privateDirty,swap * 1024 as swap,swap_pss * 1024 as swapPss + FROM smaps A, + trace_range AS t + WHERE (startNs) <= $rightNs and (startNs+$dur) >=$leftNs`, + { $rightNs: rightNs, $leftNs: leftNs, $dur: dur }, + 'exec' + ); +export const getTabSmapsSampleData = (leftNs: number): Promise> => + query( + 'getTabSmapsSampleData', + ` + SELECT + (A.timestamp - t.start_ts) AS startNs, + start_addr as startAddr, + end_addr as endAddr, + A.type, + resident_size * 1024 AS rss, + protection_id as pid, + pss * 1024 as pss,virtaul_size * 1024 AS size,reside,A.path_id AS path, + shared_clean * 1024 as sharedClean,shared_dirty * 1024 as sharedDirty,private_clean * 1024 as privateClean, + private_dirty * 1024 as privateDirty,swap * 1024 as swap,swap_pss * 1024 as swapPss + FROM smaps A, + trace_range AS t + WHERE (startNs) = ${leftNs}`, + { $leftNs: leftNs }, + 'exec' + ); +// VM Tracker Smaps Record Tab页 +export const querySmapsRecordTabData = ( + startNs: number, + ipid: number, + pixelmapId: number, + typeId: number +): Promise> => + query( + 'querySmapsRecordTabData', + `select 'RenderServiceCpu' as name, IFNULL(sum(mem_size), 0) as size from memory_rs_image, trace_range tr + where ipid = ${ipid} and (ts - tr.start_ts) = ${startNs} and type_id = ${pixelmapId} + union all + select 'SkiaCpu' as name, total_size as size from memory_cpu,trace_range + where (ts - start_ts) = ${startNs} + union all + select 'GLESHostCache' as name, 0 + union all + select 'VirtaulSize' as name, sum(virtaul_size) * 1024 as size from smaps, trace_range + where type = ${typeId} and (timeStamp - start_ts) = ${startNs}` + ); + +export const getTabSmapsStatisticMaxSize = (rightNs: number): Promise> => + query( + 'getTabSmapsStatisticMaxRss', + ` +SELECT (A.timestamp - B.start_ts) as startNS, sum(virtaul_size) * 1024 as max_value FROM smaps A,trace_range B where startNS = $rightNs`, + { $rightNs: rightNs } + ); + +export const getTabSmapsStatisticData = (rightNs: number): Promise> => + query( + 'getTabSmapsStatisticData', + `SELECT + (A.timestamp - t.start_ts) AS startNs, + start_addr as startAddr, + end_addr as endAddr, + A.type, + sum(resident_size) * 1024 AS rss, + protection_id as pid, + count(A.path_id) as count, + sum(pss) * 1024 as pss ,sum(virtaul_size) * 1024 AS size,sum(reside) as reside,A.path_id AS path, + sum(shared_clean) * 1024 as sharedClean,sum(shared_dirty) * 1024 as sharedDirty,sum(private_clean) * 1024 as privateClean,sum(private_dirty) * 1024 as privateDirty, + sum(swap) * 1024 as swap,sum(swap_pss) * 1024 as swapPss + FROM smaps A, + trace_range AS t + WHERE (startNs) =$rightNs + group by type,path`, + { $rightNs: rightNs }, + 'exec' + ); + +export const getTabSmapsStatisticSelectData = (leftNs: number, rightNs: number, dur: number): Promise> => + query( + 'getTabSmapsStatisticData', + `SELECT + (A.timestamp - t.start_ts) AS startNs, + start_addr as startAddr, + end_addr as endAddr, + A.type, + sum(resident_size) * 1024 AS rss, + protection_id as pid, + count(A.path_id) as count, + sum(pss) * 1024 as pss ,sum(virtaul_size) * 1024 AS size,sum(reside) as reside,A.path_id AS path, + sum(shared_clean) * 1024 as sharedClean,sum(shared_dirty) * 1024 as sharedDirty,sum(private_clean) * 1024 as privateClean,sum(private_dirty) * 1024 as privateDirty, + sum(swap) * 1024 as swap,sum(swap_pss) * 1024 as swapPss + FROM smaps A, + trace_range AS t + WHERE (startNs) <=$rightNs and (startNs+$dur)>=$leftNs + group by type,path`, + { $rightNs: rightNs, $leftNs: leftNs, $dur: dur }, + 'exec' + ); \ No newline at end of file diff --git a/ide/src/trace/database/sql/SqlLite.sql.ts b/ide/src/trace/database/sql/SqlLite.sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..5baa6cffb9bfc83ec839ec60671f9e2fe9db6fd9 --- /dev/null +++ b/ide/src/trace/database/sql/SqlLite.sql.ts @@ -0,0 +1,1354 @@ +/* + * 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 {FpsStruct} from "../ui-worker/ProcedureWorkerFPS"; +import {Counter, Fps} from "../../bean/BoxSelection"; +import { + NativeEvent, + NativeEventHeap, +} from "../../bean/NativeHook"; +import {HeapTreeDataBean} from "../logic-worker/ProcedureLogicWorkerCommon"; +import {EnergyAnomalyStruct} from "../ui-worker/ProcedureWorkerEnergyAnomaly"; +import {SystemDetailsEnergy} from "../../bean/EnergyStruct"; +import {EnergyStateStruct} from "../ui-worker/ProcedureWorkerEnergyState"; +import {FileInfo} from "../../../js-heap/model/UiStruct"; +import {HeapEdge, HeapLocation, HeapNode, HeapSample} from "../../../js-heap/model/DatabaseStruct"; +import {TaskTabStruct} from "../../component/trace/sheet/task/TabPaneTaskFrames"; +import type {FrameAnimationStruct} from "../ui-worker/ProcedureWorkerFrameAnimation"; +import type {FrameDynamicStruct} from "../ui-worker/ProcedureWorkerFrameDynamic"; +import type {FrameSpacingStruct} from "../ui-worker/ProcedureWorkerFrameSpacing"; +import type {DeviceStruct} from "../../bean/FrameComponentBean"; +import {LogStruct} from "../ui-worker/ProcedureWorkerLog"; +import {query} from "../SqlLite"; + +export const queryEventCountMap = (): Promise< + Array<{ + eventName: string; + count: number; + }> +> => query('queryEventCountMap', `select event_name as eventName,count from stat where stat_type = 'received';`); + +export const queryTotalTime = (): Promise> => + query( + 'queryTotalTime', + ` + select + start_ts as recordStartNS,end_ts as recordEndNS,end_ts-start_ts as total + from + trace_range;` + ); +export const getFps = () => + query( + 'getFps', + ` + select + distinct(ts-tb.start_ts) as startNS, fps + from + hidump c ,trace_range tb + where + startNS >= 0 + --order by startNS; + `, + {} + ); + +export const getTabFps = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabFps', + ` + select + distinct(ts-tb.start_ts) as startNS, + fps + from + hidump c, + trace_range tb + where + startNS <= $rightNS + and + startNS >= 0 + --order by startNS; + `, + { $leftNS: leftNs, $rightNS: rightNs } + ); + + +export const getTabVirtualCounters = (virtualFilterIds: Array, startTime: number) => + query( + 'getTabVirtualCounters', + ` + select + table1.filter_id as trackId, + table2.name, + value, + table1.ts - table3.start_ts as startTime + from + sys_mem_measure table1 + left join + sys_event_filter table2 + on + table1.filter_id = table2.id + left join + trace_range table3 + where + filter_id in (${virtualFilterIds.join(',')}) + and + startTime <= $startTime + `, + { $startTime: startTime } + ); + +export const queryAllSoInitNames = (): Promise> => { + return query( + 'queryAllSoInitNames', + ` + select id,so_name as name from static_initalize;` + ); +}; + +export const queryAllSrcSlices = (): Promise> => { + return query( + 'queryAllSrcSlices', + ` + select src,id from frame_slice;` + ); +}; + +/*-------------------------------------------------------------------------------------*/ +export const queryHeapGroupByEvent = (type: string): Promise> => { + let sql1 = ` + select + event_type as eventType, + sum(heap_size) as sumHeapSize + from native_hook + where event_type = 'AllocEvent' or event_type = 'MmapEvent' + group by event_type + `; + let sql2 = ` + select (case when type = 0 then 'AllocEvent' else 'MmapEvent' end) eventType, + sum(apply_size) sumHeapSize + from native_hook_statistic + group by eventType; + `; + return query('queryHeapGroupByEvent', type === 'native_hook' ? sql1 : sql2, {}); +}; + +export const queryAllHeapByEvent = (): Promise> => + query( + 'queryAllHeapByEvent', + ` + select * from ( + select h.start_ts - t.start_ts as startTime, + h.heap_size as heapSize, + h.event_type as eventType +from native_hook h ,trace_range t +where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts +and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent') +union +select h.end_ts - t.start_ts as startTime, + h.heap_size as heapSize, + (case when h.event_type = 'AllocEvent' then 'FreeEvent' else 'MunmapEvent' end) as eventType +from native_hook h ,trace_range t +where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts +and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent') +and h.end_ts not null ) order by startTime; +`, + {} + ); + +export const queryHeapAllData = ( + startTs: number, + endTs: number, + ipids: Array +): Promise> => + query( + 'queryHeapAllData', + ` + select + h.start_ts - t.start_ts as startTs, + h.end_ts - t.start_ts as endTs, + h.heap_size as heapSize, + h.event_type as eventType, + h.callchain_id as eventId + from + native_hook h + inner join + trace_range t + where + event_type = 'AllocEvent' + and + ipid in (${ipids.join(',')}) + and + (h.start_ts - t.start_ts between ${startTs} and ${endTs} or h.end_ts - t.start_ts between ${startTs} and ${endTs})`, + { ipids: ipids, $startTs: startTs, $endTs: endTs } + ); + + + + + +export const querySelectTraceStats = (): Promise< + Array<{ + event_name: string; + stat_type: string; + count: number; + source: string; + serverity: string; + }> +> => query('querySelectTraceStats', 'select event_name,stat_type,count,source,serverity from stat'); + +export const queryCustomizeSelect = (sql: string): Promise> => query('queryCustomizeSelect', sql); + +export const queryDistributedTerm = (): Promise< + Array<{ + threadId: string; + threadName: string; + processId: string; + processName: string; + funName: string; + dur: string; + ts: string; + chainId: string; + spanId: string; + parentSpanId: string; + flag: string; + trace_name: string; + }> +> => + query( + 'queryDistributedTerm', + ` + 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` + ); +export const queryTraceTaskName = (): Promise< + Array<{ + id: string; + pid: string; + process_name: string; + thread_name: string; + }> +> => + query( + 'queryTraceTaskName', + ` + 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` + ); + +export const queryTraceMetaData = (): Promise< + Array<{ + name: string; + valueText: string; + }> +> => + query( + 'queryTraceMetaData', + ` + 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` + ); + +export const querySystemCalls = (): Promise< + Array<{ + frequency: string; + minDur: number; + maxDur: number; + avgDur: number; + funName: string; + }> +> => + query( + 'querySystemCalls', + ` + 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` + ); + +export const queryNetWorkMaxData = (): Promise> => + query( + 'queryNetWorkMaxData', + `select + ifnull(max(tx_speed),0) as maxIn, + ifnull(max(rx_speed),0) as maxOut, + ifnull(max(packet_in_sec),0) as maxPacketIn, + ifnull(max(packet_in_sec),0) as maxPacketOut + from network` + ); + +export const queryDiskIoMaxData = (): Promise> => + query( + 'queryDiskIoMaxData', + `select + ifnull(max(rd_speed),0) as bytesRead, + ifnull(max(wr_speed),0) as bytesWrite, + ifnull(max(rd_count_speed),0) as readOps, + ifnull(max(wr_count_speed),0) as writeOps + from diskio` + ); +export const queryStartTime = (): Promise> => query('queryStartTime', `SELECT start_ts FROM trace_range`); +export const queryBinderBySliceId = (id: number): Promise> => + query( + 'queryBinderBySliceId', + `select c.ts-D.start_ts as startTs, + c.dur, + t.tid,p.pid,c.depth,c.argsetid,c.name as funName,c.cookie + from callstack c,trace_range D + left join thread t on c.callid = t.id + left join process p on p.id = t.ipid +where cat = 'binder' and c.id = $id;`, + { $id: id } + ); + +export const queryThreadByItid = (itid: number, ts: number): Promise> => + query( + 'queryThreadByItid', + `select tid,pid,c.dur,c.depth,c.name +from thread t left join process p on t.ipid = p.ipid +left join callstack c on t.itid = c.callid +where itid = $itid and c.ts = $ts;`, + { $itid: itid, $ts: ts } + ); +export const queryBinderByArgsId = (id: number, startTime: number, isNext: boolean): Promise> => { + let sql = ` +select c.ts - D.start_ts as startTs, + c.dur, + t.tid, + p.pid, + c.depth, + c.argsetid, + c.name as funName, + c.cookie + from callstack c,trace_range D + left join thread t on c.callid = t.id + left join process p on p.id = t.ipid +where cat = 'binder' and c.argsetid = $id`; + if (isNext) { + sql += ' and c.ts > $startTime + D.start_ts'; + } else { + sql += ' and c.ts < $startTime + D.start_ts'; + } + return query('queryBinderByArgsId', sql, { + $id: id, + $startTime: startTime, + }); +}; + +export const getTabPaneFilesystemStatisticsFather = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabPaneFilesystemStatisticsFather', + ` + select SUM(dur) as allDuration, + count(f.type) as count, + min(dur) as minDuration, + max(dur) as maxDuration, + round(avg(dur),2) as avgDuration, + p.name, + f.type, + p.pid, + sum(ifnull(size,0)) as size + from file_system_sample as f + left join process as p on f.ipid=p.ipid + where f.start_ts >= $leftNs + and end_ts <= $rightNs + group by f.type; + `, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const getTabPaneFilesystemStatisticsChild = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabPaneFilesystemStatisticsChild', + ` + select SUM(dur) as allDuration, + count(f.type) as count, + min(dur) as minDuration, + max(dur) as maxDuration, + round(avg(dur),2) as avgDuration, + p.name, + p.pid, + f.type, + sum(ifnull(size,0)) as size + from file_system_sample as f left join process as p on f.ipid=p.ipid + where f.start_ts >= $leftNs + and end_ts <= $rightNs + group by f.type, f.ipid; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const getTabPaneFilesystemStatisticsAll = (leftNs: number, rightNs: number): Promise> => + query( + 'getTabPaneFilesystemStatisticsAll', + ` + select SUM(dur) as allDuration, + count(type) as count, + min(dur) as minDuration, + max(dur) as maxDuration, + round(avg(dur),2) as avgDuration, + type + from file_system_sample + where start_ts >= $leftNs + and end_ts <= $rightNs; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const getTabPaneFilesystemStatistics = (leftNs: number, rightNs: number, types: number[]): Promise> => + query( + 'getTabPaneFilesystemStatistics', + ` + select p.pid, + ifnull(p.name,'Process') as name, + f.type, + count(f.ipid) as count, + sum(ifnull(size,0)) as size, + sum(case when f.type = 2 then ifnull(size,0) else 0 end) as logicalReads, + sum(case when f.type = 3 then ifnull(size,0) else 0 end) as logicalWrites, + sum(case when f.type != 2 and f.type != 3 then ifnull(size,0) else 0 end) as otherFile, + sum(dur) as allDuration, + min(dur) as minDuration, + max(dur) as maxDuration, + avg(dur) as avgDuration + from file_system_sample as f left join process as p on f.ipid=p.ipid + where end_ts >= $leftNs + and end_ts <= $rightNs + and f.type in (${types.join(',')}) + group by f.type,f.ipid + order by f.type; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); + +export const getTabPaneIOTierStatisticsData = ( + leftNs: number, + rightNs: number, + diskIOipids: Array +): Promise> => { + let str = ''; + if (diskIOipids.length > 0) { + str = ` and i.ipid in (${diskIOipids.join(',')})`; + } + return query( + 'getTabPaneIOTierStatisticsData', + ` + select p.pid, + ifnull(p.name,'Process') as pname, + i.tier, + i.ipid, + path_id as path, + count(i.ipid) as count, + sum(latency_dur) as allDuration, + min(latency_dur) as minDuration, + max(latency_dur) as maxDuration, + avg(latency_dur) as avgDuration + from bio_latency_sample as i left join process as p on i.ipid=p.ipid + where i.start_ts+latency_dur >= $leftNs + and i.start_ts+latency_dur <= $rightNs + ${str} + group by i.tier,i.ipid,i.path_id + order by i.tier; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); +}; + +export const getTabPaneFrequencySampleData = ( + leftNs: number, + rightNs: number, + cpuFreqFilterIds: Array +): Promise> => { + let str = ''; + if (cpuFreqFilterIds.length > 0) { + str = ` and filter_id in (${cpuFreqFilterIds.join(',')})`; + } + return query( + 'getTabPaneFrequencySampleData', + ` + select value, filter_id as filterId, ts, f.cpu + from measure left join cpu_measure_filter as f on f.id=filter_id + where + ts <= $rightNs${str} order by ts asc; +`, + { $leftNs: leftNs, $rightNs: rightNs } + ); +}; + +export const getFileSysChartDataByType = (type: number): Promise> => + query( + 'getFileSysChartData', + ` + select + (A.start_ts -B.start_ts) as startNS, + (A.end_ts - B.start_ts) as endNS, + dur + from file_system_sample A,trace_range B + where type = $type and startNS > 0;`, + { $type: type }, + 'exec' + ); + +export const getDiskIOProcess = (): Promise> => + query( + 'getDiskIOProcess', + ` + select name,B.ipid,pid + from (select distinct ipid from bio_latency_sample A,trace_range B where A.start_ts between B.start_ts and B.end_ts) A + left join process B on A.ipid = B.ipid;`, + {} + ); + +export const getDiskIOLatencyChartDataByProcess = ( + all: boolean, + ipid: number, + typeArr: Array +): Promise> => + query( + 'getDiskIOLatencyChartDataByProcess', + ` + select + (A.start_ts -B.start_ts) as startNS, + (A.start_ts - B.start_ts + A.latency_dur) as endNS, + latency_dur as dur + from bio_latency_sample A,trace_range B + where type in (${typeArr.join(',')}) and startNS > 0 + ${all ? '' : 'and ipid = ' + ipid} + order by A.start_ts;`, + {}, + 'exec' + ); + +export const queryAnomalyData = (): Promise> => + query( + 'queryAnomalyData', + `select + S.id, + (S.ts - TR.start_ts) as startNS, + D.data as eventName, + D2.data as appKey, + (case when S.type==1 then group_concat(S.string_value,',') else group_concat(S.int_value,',') end) as Value + from trace_range AS TR,hisys_event_measure as S + left join data_dict as D on D.id=S.name_id + left join app_name as APP on APP.id=S.key_id + left join data_dict as D2 on D2.id=APP.app_key + where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_KERNEL_WAKELOCK','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_WAKEUP') + or (D.data in ('ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_ENERGY','ANOMALY_ALARM_WAKEUP') and D2.data in ("APPNAME")) + group by S.serial,D.data` + ); + +export const querySystemLocationData = (): Promise< + Array<{ + ts: string; + eventName: string; + appKey: string; + Value: string; + }> +> => + query( + 'querySystemLocationData', + `SELECT + ( S.ts - TR.start_ts ) AS ts, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + WHERE + D.data = 'GNSS_STATE' AND D2.data = 'STATE' + GROUP BY + S.serial, + APP.app_key, + D.data, + D2.data;` + ); + +export const querySystemLockData = (): Promise< + Array<{ + ts: string; + eventName: string; + appKey: string; + Value: string; + }> +> => + query( + 'querySystemLockData', + `SELECT + ( S.ts - TR.start_ts ) AS ts, + D.data AS eventName, + D2.data AS appKey, + group_concat(( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + WHERE + ( D.data = 'POWER_RUNNINGLOCK' AND D2.data in ('TAG','MESSAGE')) + GROUP BY + S.serial;` + ); + +export const querySystemAllData = (): Promise< + Array<{ + id: number; + eventName: string; + eventValue: string; + }> +> => + query( + 'querySystemAllData', + `SELECT + S.id, + D.data AS eventName, + contents AS eventValue + FROM + trace_range AS TR, + hisys_all_event AS S + LEFT JOIN data_dict AS D ON S.event_name_id = D.id + LEFT JOIN data_dict AS D2 ON S.domain_id = D2.id + WHERE + eventName IN ( 'POWER_RUNNINGLOCK', 'GNSS_STATE', 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' );` + ); + +export const querySystemSchedulerData = (): Promise< + Array<{ + startNs: string; + eventName: string; + appKey: string; + Value: string; + }> +> => + query( + 'querySystemSchedulerData', + `SELECT + ( S.ts - TR.start_ts ) AS startNs, + D.data AS eventName, + group_concat(D2.data, ',') AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + WHERE + D.data IN ( 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' ) AND D2.data in ('NAME','TYPE','WORKID') + GROUP BY + S.serial;` + ); + +export const querySystemDetailsData = (rightNs: number, eventName: string): Promise> => + query( + 'querySystemDetailsData', + `SELECT + ( S.ts - TR.start_ts ) AS ts, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + WHERE + D.data in ($eventName) + AND + D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') + AND + (S.ts - TR.start_ts) <= $rightNS + GROUP BY + S.serial, + APP.app_key, + D.data, + D2.data;`, + { $rightNS: rightNs, $eventName: eventName } + ); + +export const querySystemWorkData = (rightNs: number): Promise> => + query( + 'querySystemWorkData', + `SELECT + ( S.ts - TR.start_ts ) AS ts, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D + ON D.id = S.name_id + LEFT JOIN app_name AS APP + ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 + ON D2.id = APP.app_key + WHERE + D.data in ("WORK_REMOVE", "WORK_STOP", "WORK_ADD", "WORK_START") + and + D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') + and (S.ts - TR.start_ts) <= $rightNS + GROUP BY + S.serial, + APP.app_key, + D.data, + D2.data;`, + { $rightNS: rightNs } + ); + +export const queryMaxPowerValue = ( + appName: string +): Promise< + Array<{ + maxValue: number; + }> +> => + query( + 'queryMaxPowerValue', + `SELECT + max( item ) AS maxValue + FROM + ( + SELECT + sum( energy + background_energy + screen_on_energy + screen_off_energy + foreground_energy ) AS item + FROM + energy + WHERE + app_name = $appName + GROUP BY + startNs);`, + { $appName: appName } + ); + +export const queryMaxStateValue = ( + eventName: string +): Promise< + Array<{ + type: string; + maxValue: number; + }> +> => + query( + 'queryMaxStateValue', + `select + D.data as type, + max(S.int_value) as maxValue + from trace_range AS TR,hisys_event_measure as S + left join data_dict as D on D.id=S.name_id + left join app_name as APP on APP.id=S.key_id + left join data_dict as D2 on D2.id=APP.app_key + where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end) + and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME') + group by APP.app_key,D.data,D2.data;`, + { $eventName: eventName } + ); + +export const queryStateData = (eventName: string): Promise> => + query( + 'queryStateData', + `select + (S.ts-TR.start_ts) as startNs, + D.data as type, + D2.data as appKey, + S.int_value as value + from trace_range AS TR,hisys_event_measure as S + left join data_dict as D on D.id=S.name_id + left join app_name as APP on APP.id=S.key_id + left join data_dict as D2 on D2.id=APP.app_key + where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end) + and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME') + group by S.serial,APP.app_key,D.data,D2.data;`, + { $eventName: eventName } + ); + +export const queryEnergyAppName = (): Promise< + Array<{ + string_value: string | null; + }> +> => + query( + 'queryEnergyAppName', + ` + SELECT + DISTINCT hisys_event_measure.string_value from data_dict + left join app_name on app_name.app_key=data_dict.id + left join hisys_event_measure on hisys_event_measure.key_id = app_name.id + where data_dict.data = "APPNAME"` + ); + +export const getTabIoCompletionTimesType = (startTime: number, endTime: number): Promise> => + query( + 'getTabIoCompletionTimesType', + ` + SELECT tier from bio_latency_sample s,trace_range t + WHERE s.start_ts + s.latency_dur between $startTime + t.start_ts and $endTime + t.start_ts group by tier`, + { $startTime: startTime, $endTime: endTime }, + 'exec' + ); + +export const queryEnergyEventExits = (): Promise> => + query( + 'queryEnergyEventExits', + `select + event_name + from stat s + where s.event_name = 'trace_hisys_event' + and s.stat_type ='received' and s.count > 0` + ); + +export const querySysLockDetailsData = (rightNs: number, eventName: string): Promise> => + query( + 'querySysLockDetailsData', + `SELECT + ( S.ts - TR.start_ts ) AS ts, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + WHERE + D.data in ($eventName) + AND + D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') + AND + (S.ts - TR.start_ts) <= $rightNS + GROUP BY + S.serial, APP.app_key, D.data, D2.data;`, + { $rightNS: rightNs, $eventName: eventName } + ); + +export const queryStateInitValue = (eventName: string, keyName: string): Promise> => + query( + 'queryStateInitValue', + `select + 0 as startNs, + $eventName as type, + '' as appKey, + (case $keyName + when 'brightness' then device_state.brightness + when 'wifi' then device_state.wifi + when 'bt_state' then device_state.bt_state + when 'location' then device_state.location + else 0 end) as value + from device_state;`, + { $eventName: eventName, $keyName: keyName } + ); + +export const querySysLocationDetailsData = (rightNs: number, eventName: string): Promise> => + query( + 'querySysLocationDetailsData', + `SELECT + ( S.ts - TR.start_ts ) AS ts, + D.data AS eventName, + D2.data AS appKey, + group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue + FROM + trace_range AS TR, + hisys_event_measure AS S + LEFT JOIN data_dict AS D ON D.id = S.name_id + LEFT JOIN app_name AS APP ON APP.id = S.key_id + LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key + WHERE + D.data in ($eventName) + and + D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL') + and (S.ts - TR.start_ts) <= $rightNS + GROUP BY + S.serial, + APP.app_key, + D.data, + D2.data;`, + { $rightNS: rightNs, $eventName: eventName } + ); +export const queryConfigEnergyAppName = (): Promise< + Array<{ + process_name: string; + }> +> => + query( + 'queryConfigEnergyAppName', + ` + SELECT value from trace_config where trace_source = 'hisys_event' and key = 'process_name'` + ); + +export const queryAllExpectedData = (): Promise> => + query( + 'queryAllExpectedData', + ` + SELECT + a.id, + (a.ts - TR.start_ts) AS ts, + a.vsync as name, + a.type, + a.dur, + p.pid, + p.name as cmdline + FROM frame_slice AS a, trace_range AS TR + LEFT JOIN process AS p ON a.ipid = p.ipid + WHERE a.type = 1 + and (a.flag <> 2 or a.flag is null) + ORDER BY a.ipid,ts;` + ); + +export const queryFlowsData = (src_slice: Array): Promise> => + query( + 'queryFlowsData', + ` + SELECT fs.vsync AS name, + p.pid, + p.name AS cmdline, + fs.type + FROM frame_slice AS fs + LEFT JOIN process AS p ON fs.ipid = p.ipid + WHERE fs.type = 0 + AND fs.id IN (${src_slice.join(',')});` + ); + +export const queryPrecedingData = (dst_slice: string): Promise> => + query( + 'queryFlowsData', + ` + SELECT a.vsync AS name, + p.pid, + p.name AS cmdline, + a.type + FROM frame_slice AS a + LEFT JOIN process AS p ON a.ipid = p.ipid + WHERE a.type = 0 + AND a.id = $dst_slice;`, + { $dst_slice: dst_slice } + ); + +export const queryFrameTimeData = (): Promise> => + query( + 'queryFrameTimeData', + ` + SELECT DISTINCT p.pid + FROM frame_slice AS a + LEFT JOIN process AS p + ON a.ipid = p.ipid;` + ); + +export const queryAllSnapshotNames = (): Promise> => + query( + 'queryAllSnapshotNames', + `SELECT f.id, + f.file_name AS name + FROM + js_heap_files f, + trace_range t + WHERE + ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' ) + OR f.file_name = 'Timeline'` + ); +export const queryHeapFile = (): Promise> => + query( + 'queryHeapFile', + `SELECT f.id, + f.file_name AS name, + f.start_time - t.start_ts AS startTs, + f.end_time - t.start_ts AS endTs, + f.self_size AS size, + c.pid + FROM + js_heap_files f, + trace_range t, + js_config c + WHERE + ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' ) + OR f.file_name = 'Timeline'` + ); + +export const queryHeapInfo = (fileId: number): Promise> => + query( + 'queryHeapInfo', + `SELECT file_id as fileId, key, type, int_value as intValue, str_value as strValue + FROM js_heap_info WHERE file_id = ${fileId}` + ); + +export const queryHeapNode = (fileId: number): Promise> => + query( + 'queryHeapNode', + `SELECT node_index as nodeIndex,type,name as nameIdx,id,self_size as selfSize,edge_count as edgeCount,trace_node_id as traceNodeId,detachedness + FROM js_heap_nodes WHERE file_id = ${fileId}` + ); + +export const queryHeapEdge = (fileId: number): Promise> => + query( + 'queryHeapEdge', + `SELECT edge_index as edgeIndex,type,name_or_index as nameOrIndex,to_node as nodeId,from_node_id as fromNodeId,to_node_id as toNodeId + FROM js_heap_edges WHERE file_id = ${fileId}` + ); +export const queryHeapSample = (fileId: number): Promise> => + query( + 'queryHeapSample', + `SELECT timestamp_us as timestamp , last_assigned_id as lastAssignedId, 0 as size + FROM js_heap_sample WHERE file_id = ${fileId}` + ); + +export const queryHeapLocation = (fileId: number): Promise> => + query( + 'queryHeapLocation', + `SELECT object_index as objectIndex,script_id as scriptId ,column + FROM js_heap_location WHERE file_id = ${fileId}` + ); + +export const queryHeapString = (fileId: number): Promise> => + query( + 'queryHeapString', + `SELECT string + FROM js_heap_string WHERE file_id = ${fileId}` + ); +export const queryTraceRange = (): Promise> => + query('queryTraceRange', `SELECT t.start_ts as startTs, t.end_ts as endTs FROM trace_range t`); + +export const queryBySelectAllocationOrReturn = ( + executeId: string, + itid: number +): Promise< + Array<{ + tid: number; + allocation_task_row: number; + execute_task_row: number; + return_task_row: number; + priority: number; + }> +> => { + let sqlStr = `SELECT thread.tid, + task_pool.allocation_task_row, + task_pool.execute_task_row, + task_pool.return_task_row, + task_pool.priority + FROM task_pool + LEFT JOIN callstack ON callstack.id = task_pool.execute_task_row + LEFT JOIN thread ON thread.id = callstack.callid + WHERE task_pool.execute_task_row IS NOT NULL AND task_pool.execute_id = $executeId + AND task_pool.allocation_itid = $itid; + `; + return query('queryBySelectAllocationOrReturn', sqlStr, { $executeId: executeId, $itid: itid }); +}; + +export const queryTaskListByExecuteTaskIds = ( + executeTaskIds: Array, + ipid: number +): Promise> => { + let sqlStr = ` + SELECT thread.ipid, + task_pool.allocation_task_row AS allocationTaskRow, + task_pool.execute_task_row AS executeTaskRow, + task_pool.return_task_row AS returnTaskRow, + task_pool.execute_id AS executeId, + task_pool.priority + FROM task_pool + LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row + LEFT JOIN thread ON thread.id = callstack.callid + WHERE task_pool.execute_id IN (${executeTaskIds.join(',')}) + AND thread.ipid = $ipid + AND task_pool.execute_task_row IS NOT NULL; + `; + return query('queryTaskListByExecuteTaskIds', sqlStr, { $executeTaskIds: executeTaskIds, $ipid: ipid }); +}; + +export const queryTaskPoolCallStack = (): Promise> => { + let sqlStr = `select * from callstack where name like 'H:Task%';`; + return query('queryTaskPoolCallStack', sqlStr, {}); +}; + +export const queryTaskPoolTotalNum = (itid: number) => + query( + 'queryTaskPoolTotalNum', + `SELECT thread.tid + FROM thread + LEFT JOIN callstack ON thread.id = callstack.callid + WHERE ipid in (SELECT thread.ipid + FROM thread + WHERE thread.itid = $itid) + AND thread.name = 'TaskWorkThread' + GROUP BY thread.tid;`, + { $itid: itid } + ); + +export const queryFrameAnimationData = (): Promise> => + query( + 'queryFrameAnimationData', + `SELECT a.id AS animationId, + 'Response delay' as status, + (CASE WHEN a.input_time NOT NULL + THEN ( a.input_time - R.start_ts ) + ELSE ( a.start_point - R.start_ts ) END + ) AS startTs, + (a.start_point - R.start_ts) AS endTs, + 0 AS frameInfo, + a.name AS name + FROM + animation AS a, + trace_range AS R + UNION + SELECT a.id AS animationId, + 'Completion delay' as status, + (CASE WHEN a.input_time NOT NULL + THEN ( a.input_time - R.start_ts ) + ELSE ( a.start_point - R.start_ts ) END + ) AS startTs, + (a.end_point - R.start_ts) AS endTs, + a.frame_info AS frameInfo, + a.name AS name + FROM + animation AS a, + trace_range AS R + ORDER BY + endTs;` + ); + +export const queryAnimationTimeRangeData = (): Promise> => + query( + 'queryAnimationTimeRangeData', + `SELECT 'Response delay' as status, + (CASE WHEN a.input_time NOT NULL + THEN ( a.input_time - R.start_ts ) + ELSE ( a.start_point - R.start_ts ) END + ) AS startTs, + (a.start_point - R.start_ts) AS endTs + FROM + animation AS a, + trace_range AS R + UNION + SELECT 'Completion delay' as status, + (CASE WHEN a.input_time NOT NULL + THEN ( a.input_time - R.start_ts ) + ELSE ( a.start_point - R.start_ts ) END + ) AS startTs, + (a.end_point - R.start_ts) AS endTs + FROM + animation AS a, + trace_range AS R + ORDER BY + endTs;` + ); + +export const queryFrameDynamicData = (): Promise => + query( + 'queryFrameDynamicData', + `SELECT + d.id, + d.x, + d.y, + d.width, + d.height, + d.alpha, + d.name AS appName, + (d.end_time - R.start_ts) AS ts + FROM + dynamic_frame AS d, + trace_range AS R + ORDER BY + d.end_time;` + ); + +export const queryDynamicIdAndNameData = (): Promise> => + query('queryDynamicIdAndNameData', `SELECT id, name AS appName FROM dynamic_frame;`); + +export const queryAnimationIdAndNameData = (): Promise< + Array<{ + id: number; + name: string; + info: string; + }> +> => query('queryAnimationIdAndNameData', `SELECT id, name, frame_info as info FROM animation;`); + +export const queryFrameApp = (): Promise< + Array<{ + name: string; + }> +> => + query( + 'queryFrameApp', + `SELECT + DISTINCT d.name + FROM + dynamic_frame AS d, + trace_range AS R + WHERE + d.end_time >= R.start_ts + AND + d.end_time <= R.end_ts;` + ); + +export const queryFrameSpacing = (): Promise> => + query( + 'queryFrameSpacing', + `SELECT + d.id, + d.width AS currentFrameWidth, + d.height AS currentFrameHeight, + d.name AS nameId, + (d.end_time - R.start_ts) AS currentTs, + d.x, + d.y + FROM + dynamic_frame AS d, + trace_range AS R + ORDER BY + d.end_time;` + ); + +export const queryPhysicalData = (): Promise> => + query( + 'queryPhysicalData', + `SELECT physical_width AS physicalWidth, + physical_height AS physicalHeight, + physical_frame_rate AS physicalFrameRate + FROM device_info;` + ); +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.ts - tr.start_ts as startNs FROM log AS l, trace_range tr WHERE startNs > 0 LIMIT 1;`, + ); + +export const queryMetric = (metricName: string): Promise> => + query('queryMetric', metricName, '', 'exec-metric'); + +export const queryExistFtrace = (): Promise> => + query( + 'queryExistFtrace', + `select 1 from thread_state + UNION + select 1 from args;` + ); + +export const queryTraceType = (): Promise< + Array<{ + value: string; + }> +> => + query( + 'queryTraceType', + `SELECT m.value + FROM + meta AS m + WHERE + m.name = 'source_type';` + ); + + +export const queryLogAllData = (oneDayTime: number, leftNs: number, rightNs: number): Promise> => + query( + 'queryLogAllData', + `SELECT + l.seq AS id, + CASE + WHEN l.ts < ${oneDayTime} THEN 0 + ELSE (l.ts - TR.start_ts) + END AS startTs, + CASE l.level + WHEN 'D' THEN 'Debug' + WHEN 'I' THEN 'Info' + WHEN 'W' THEN 'Warn' + WHEN 'E' THEN 'Error' + WHEN 'F' THEN 'Fatal' + END AS level, + l.tag AS tag, + l.context AS context, + (strftime( '%m-%d %H:%M:%S', l.origints / 1000000000, 'unixepoch', 'localtime' ) || '.' || printf('%03d', (l.origints / 1000000) % 1000)) AS originTime, + COALESCE(p.name, 'Process ' || l.pid) AS processName + FROM + log AS l + LEFT JOIN trace_range AS TR ON l.ts >= TR.start_ts + LEFT JOIN process AS p ON p.pid = l.pid + WHERE + startTs >= ${Math.floor(leftNs)} + AND startTs <= ${Math.floor(rightNs)} + ORDER BY + l.ts;`, + { $oneDayTime: oneDayTime } + ); \ No newline at end of file diff --git a/ide/src/trace/database/ui-worker/ProcedureWorker.ts b/ide/src/trace/database/ui-worker/ProcedureWorker.ts index 2d0ba1a0e80715aa8007faf9a1c3c18f34630e51..ca4ca03f317ec6e0e14558a9385dc8db3b9088e7 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorker.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorker.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CpuRender, EmptyRender } from './ProcedureWorkerCPU'; +import { CpuRender, EmptyRender } from './cpu/ProcedureWorkerCPU'; import { RequestMessage } from './ProcedureWorkerCommon'; import { FreqRender } from './ProcedureWorkerFreq'; import { ProcessRender } from './ProcedureWorkerProcess'; @@ -26,22 +26,22 @@ import { CpuAbilityRender } from './ProcedureWorkerCpuAbility'; import { MemoryAbilityRender } from './ProcedureWorkerMemoryAbility'; import { DiskIoAbilityRender } from './ProcedureWorkerDiskIoAbility'; import { NetworkAbilityRender } from './ProcedureWorkerNetworkAbility'; -import { HiperfCpuRender } from './ProcedureWorkerHiPerfCPU'; -import { HiperfProcessRender } from './ProcedureWorkerHiPerfProcess'; -import { HiperfThreadRender } from './ProcedureWorkerHiPerfThread'; -import { HiperfEventRender } from './ProcedureWorkerHiPerfEvent'; -import { HiperfReportRender } from './ProcedureWorkerHiPerfReport'; +import { HiperfCpuRender } from './hiperf/ProcedureWorkerHiPerfCPU'; +import { HiperfProcessRender } from './hiperf/ProcedureWorkerHiPerfProcess'; +import { HiperfThreadRender } from './hiperf/ProcedureWorkerHiPerfThread'; +import { HiperfEventRender } from './hiperf/ProcedureWorkerHiPerfEvent'; +import { HiperfReportRender } from './hiperf/ProcedureWorkerHiPerfReport'; import { VirtualMemoryRender } from './ProcedureWorkerVirtualMemory'; import { EBPFRender } from './ProcedureWorkerEBPF'; import { info } from '../../../log/Log'; import { SdkSliceRender } from './ProduceWorkerSdkSlice'; import { SdkCounterRender } from './ProduceWorkerSdkCounter'; -import { CpuStateRender } from './ProcedureWorkerCpuState'; +import { CpuStateRender } from './cpu/ProcedureWorkerCpuState'; import { EnergyAnomalyRender } from './ProcedureWorkerEnergyAnomaly'; import { EnergySystemRender } from './ProcedureWorkerEnergySystem'; import { EnergyPowerRender } from './ProcedureWorkerEnergyPower'; import { EnergyStateRender } from './ProcedureWorkerEnergyState'; -import { CpuFreqLimitRender } from './ProcedureWorkerCpuFreqLimits'; +import { CpuFreqLimitRender } from './cpu/ProcedureWorkerCpuFreqLimits'; import { ClockRender } from './ProcedureWorkerClock'; import { IrqRender } from './ProcedureWorkerIrq'; import { JankRender } from './ProcedureWorkerJank'; @@ -56,11 +56,11 @@ import { FrameSpacingRender } from './ProcedureWorkerFrameSpacing'; import { JsCpuProfilerRender } from './ProcedureWorkerCpuProfiler'; import { SnapshotRender } from './ProcedureWorkerSnapshot'; import { LogRender } from './ProcedureWorkerLog'; -import { HiPerfCallChartRender } from './ProcedureWorkerHiPerfCallChart'; +import { HiPerfCallChartRender } from './hiperf/ProcedureWorkerHiPerfCallChart'; import { HiSysEventRender } from './ProcedureWorkerHiSysEvent'; -import { HiperfCpuRender2 } from './ProcedureWorkerHiPerfCPU2'; -import { HiperfProcessRender2 } from './ProcedureWorkerHiPerfProcess2'; -import { HiperfThreadRender2 } from './ProcedureWorkerHiPerfThread2'; +import { HiperfCpuRender2 } from './hiperf/ProcedureWorkerHiPerfCPU2'; +import { HiperfProcessRender2 } from './hiperf/ProcedureWorkerHiPerfProcess2'; +import { HiperfThreadRender2 } from './hiperf/ProcedureWorkerHiPerfThread2'; import { AllAppStartupRender } from './ProcedureWorkerAllAppStartup'; import { FreqExtendRender } from './ProcedureWorkerFreqExtend'; import { BinderRender } from './procedureWorkerBinder'; diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerAllAppStartup.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerAllAppStartup.ts index 1733207444ef67bb084f6c699d81ef743a8be78c..b6a72695b0834ba646ea102e883a04aea5a0a9ad 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerAllAppStartup.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerAllAppStartup.ts @@ -16,7 +16,7 @@ import { BaseStruct, dataFilterHandler, drawString } from './ProcedureWorkerCommon'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { ColorUtils } from '../../component/trace/base/ColorUtils'; -import { querySingleAppStartupsName } from '../SqlLite'; +import {querySingleAppStartupsName} from "../sql/ProcessThread.sql"; export class AllAppStartupRender { renderMainThread( @@ -61,19 +61,12 @@ export class AllAppStartupRender { } } -const padding = 3; export class AllAppStartupStruct extends BaseStruct { static hoverStartupStruct: AllAppStartupStruct | undefined; static selectStartupStruct: AllAppStartupStruct | undefined; dur: number | undefined; - value: string | undefined; startTs: number | undefined; - pid: number | undefined; - process: string | undefined; - itid: number | undefined; - endItid: number | undefined; - tid: number | undefined; startName: number | undefined; stepName: string | undefined; @@ -102,8 +95,4 @@ export class AllAppStartupStruct extends BaseStruct { } } - static async getStartupName(pid: number): Promise { - let singleAppName = await querySingleAppStartupsName(pid); - return singleAppName[0].name; - } } diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts index a310d06954a61779d5a42c63b0c0b402ad98743a..173fc8c71986ab848f63f32885c0e7e88cf73413 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerCommon.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { CpuStruct, WakeupBean } from './ProcedureWorkerCPU'; +import { CpuStruct, WakeupBean } from './cpu/ProcedureWorkerCPU'; import { TraceRow } from '../../component/trace/base/TraceRow'; import { TimerShaftElement } from '../../component/trace/TimerShaftElement'; import { Flag } from '../../component/trace/timer-shaft/Flag'; @@ -49,10 +49,10 @@ export class RequestMessage { totalNS: any; slicesTime: | { - startTime: number | null; - endTime: number | null; - color: string | null; - } + startTime: number | null; + endTime: number | null; + color: string | null; + } | undefined; range: any; scale: any; @@ -65,9 +65,9 @@ export class RequestMessage { id: any; postMessage: | { - (message: any, targetOrigin: string, transfer?: Transferable[]): void; - (message: any, options?: WindowPostMessageOptions): void; - } + (message: any, targetOrigin: string, transfer?: Transferable[]): void; + (message: any, options?: WindowPostMessageOptions): void; + } | undefined; } @@ -493,7 +493,7 @@ export class Point { export enum LineType { brokenLine, bezierCurve, - StraightLine, + straightLine, } export class PairPoint { @@ -556,10 +556,10 @@ export function drawFlagLine( frame: any, slicesTime: | { - startTime: number | null | undefined; - endTime: number | null | undefined; - color: string | null | undefined; - } + startTime: number | null | undefined; + endTime: number | null | undefined; + color: string | null | undefined; + } | undefined ) { if (commonCtx) { @@ -761,108 +761,113 @@ export function drawSelectionRange(context: any, params: TraceRow) { ); context.globalAlpha = 1; } - // 绘制方法H:RSMainThread::DoComposition平均帧率的箭头指示线条 if (params._docompositionList?.length) { - const rateList: Array = [...new Set(params.docompositionList)]; - if (rateList.length >= 2) { - // 计算平均帧率 - let cutres: number = rateList[rateList.length - 1]! - rateList[0]!; - let avgFrameRate: string = (((rateList.length - 1) / cutres) * 1000000000).toFixed(1) + 'fps'; - - let avgRateStartX = Math.floor( - ns2x( - rateList[0]!, - TraceRow.range?.startNS ?? 0, - TraceRow.range?.endNS ?? 0, - TraceRow.range?.totalNS ?? 0, - params.frame - ) - ); - let avgRateEndX = Math.floor( - ns2x( - rateList[rateList.length - 1]!, - TraceRow.range?.startNS ?? 0, - TraceRow.range?.endNS ?? 0, - TraceRow.range?.totalNS ?? 0, - params.frame - ) - ); - const textWidth = context.measureText(avgFrameRate).width; - const textHeight = 25; - const padding = 5; - let textX = - Math.floor( - ns2x( - (rateList[0]! + rateList[rateList.length - 1]!) / 2, - TraceRow.range?.startNS ?? 0, - TraceRow.range?.endNS ?? 0, - TraceRow.range?.totalNS ?? 0, - params.frame - ) - ) - - textWidth / 2; - const textY = params.frame.y + 25; - - //左移到边界,不画线和文字 - if (avgRateStartX <= 0) { - avgRateStartX = -100; - } - if (avgRateEndX <= 0) { - avgRateEndX = -100; - } - if (textX <= 0) { - textX = -100; - } - //右移到边界,不画线和文字 - if (textX + textWidth / 2 >= params.frame.width) { - textX = params.frame.width + 100; - } - if (avgRateStartX >= params.frame.width) { - avgRateStartX = params.frame.width + 100; - } - if (avgRateEndX >= params.frame.width) { - avgRateEndX = params.frame.width + 100; - } - // 绘制文字背景矩形 - context.fillStyle = 'red'; - context.fillRect( - textX - padding, - textY - textHeight + padding, - textWidth + padding * 2, - textHeight - padding * 2 - ); - - context.lineWidth = 2; - context.strokeStyle = 'yellow'; - context.beginPath(); - context.moveTo(avgRateStartX, textY); - context.lineTo(avgRateEndX, textY); - context.stroke(); - - const arrowSize = 5.5; - const arrowHead = (x: number, y: number, direction: 'left' | 'right') => { - context.beginPath(); - const headX = x + (direction === 'left' ? arrowSize : -arrowSize); - const headY = y - arrowSize / 2; - context.moveTo(x, y); - context.lineTo(headX, headY); - context.lineTo(headX, y + arrowSize); - context.closePath(); - - context.fillStyle = 'yellow'; - context.fill(); - }; - arrowHead(avgRateStartX, textY - 1, 'left'); - arrowHead(avgRateEndX, textY - 1, 'right'); - - context.fillStyle = 'white'; - context.fillText(avgFrameRate, textX, textY - 8); + const frameRateList: Array = [...new Set(params.docompositionList)]; + if (frameRateList.length >= 2) { + changeFrameRatePoint(frameRateList, context, params) } } } } +// 转换起始点坐标 +function changeFrameRatePoint(rateList: Array, ctx: any, selectParams: TraceRow): void { + let avgRateStartX = Math.floor( + ns2x( + rateList[0]!, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + TraceRow.range?.totalNS ?? 0, + selectParams.frame + ) + ); + let avgRateEndX = Math.floor( + ns2x( + rateList[rateList.length - 1]!, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + TraceRow.range?.totalNS ?? 0, + selectParams.frame + ) + ); + drawAvgFrameRate(rateList, ctx, selectParams, avgRateStartX, avgRateEndX) +} + +// 计算平均帧率 +function calculateAvgRate(arr: Array) { + const CONVERT_SECONDS = 1000000000; + let cutres: number = (arr[arr.length - 1]! - arr[0]!); + let avgRate: string = ((arr.length - 1) / cutres * CONVERT_SECONDS).toFixed(1); + return avgRate; +} + +// 绘制平均帧率箭头指示线条 +function drawAvgFrameRate(arrList: Array, ctx: any, selectParams: TraceRow, startX: number, endX: number): void { + let avgFrameRate: string = calculateAvgRate(arrList) + 'fps'; + const textWidth = ctx.measureText(avgFrameRate).width; + const textHeight = 25; + const padding = 5; + const TEXT_WIDTH_HALF = 2; + let textX = Math.floor(ns2x( + (arrList[0]! + arrList[arrList.length - 1]!) / 2, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + TraceRow.range?.totalNS ?? 0, + selectParams.frame + )) - textWidth / TEXT_WIDTH_HALF; + const textY = selectParams.frame.y + 25; + if (startX <= 0) { + startX = -100; + } + if (endX <= 0) { + endX = -100; + } + if (textX <= 0) { + textX = -100; + } + const ADD_DISTANCE = 100; + if (textX + textWidth / 2 >= selectParams.frame.width) { + textX = selectParams.frame.width + ADD_DISTANCE; + } + if (startX >= selectParams.frame.width) { + startX = selectParams.frame.width + ADD_DISTANCE; + } + if (endX >= selectParams.frame.width) { + endX = selectParams.frame.width + ADD_DISTANCE; + } + const TEXT_RECT_PADDING = 2 + ctx.fillStyle = 'red'; + ctx.fillRect( + textX - padding, + textY - textHeight + padding, + textWidth + padding * TEXT_RECT_PADDING, + textHeight - padding * TEXT_RECT_PADDING + ); + ctx.lineWidth = 2; + ctx.strokeStyle = 'yellow'; + ctx.beginPath(); + ctx.moveTo(startX, textY); + ctx.lineTo(endX, textY); + ctx.stroke(); + const arrowSize = 5.5; + const arrowHead = (x: number, y: number, direction: 'left' | 'right') => { + ctx.beginPath(); + const headX = x + (direction === 'left' ? arrowSize : -arrowSize); + const headY = y - arrowSize / 2; + ctx.moveTo(x, y); + ctx.lineTo(headX, headY); + ctx.lineTo(headX, y + arrowSize); + ctx.closePath(); + ctx.fillStyle = 'yellow'; + ctx.fill(); + }; + arrowHead(startX, textY - 1, 'left'); + arrowHead(endX, textY - 1, 'right'); + ctx.fillStyle = 'white'; + ctx.fillText(avgFrameRate, textX, textY - 8); +} + export function drawWakeUp( wakeUpContext: CanvasRenderingContext2D | any, wake: WakeupBean | undefined | null, @@ -1001,7 +1006,7 @@ export function drawLinkLines( case LineType.bezierCurve: drawBezierCurve([newFirstNode, newSecondNode], maxWidth, context, percentage); break; - case LineType.StraightLine: + case LineType.straightLine: drawStraightLine([newFirstNode, newSecondNode], maxWidth, context); break; default: @@ -1231,7 +1236,6 @@ export function drawLoading( let loadingText = 'Loading...'; let loadingTextWidth = 0; -// let loadingBackground = "#eeeeee"; let loadingBackground = '#f1f1f1'; let loadingFont = 'bold 11pt Arial'; let loadingFontColor = '#696969'; @@ -1255,7 +1259,6 @@ export function drawLoadingFrame( ctx.fillRect(0, 1, firstPx, row.frame.height - 2); ctx.fillRect(lastPx, 1, row.frame.width - lastPx, row.frame.height - 2); ctx.fillStyle = loadingFontColor; - // ctx.font = loadingFont; if (firstPx > loadingTextWidth) { ctx.fillText(loadingText, (firstPx - loadingTextWidth) / 2, row.frame.height / 2); } @@ -1264,7 +1267,6 @@ export function drawLoadingFrame( } } ctx.closePath(); - // drawSingleVSync(this.canvasPanelCtx!, this.timerShaftEL?.canvas?.clientWidth || 0, canvasHeight); } export function drawString(ctx: CanvasRenderingContext2D, str: string, textPadding: number, frame: Rect, data: any) { diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerDiskIoAbility.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerDiskIoAbility.ts index 11f730df898320f34b91a31e1897ead4e9743c5e..7e06ac1e2a9f942f28d253d666488b9d9fcf5284 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerDiskIoAbility.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerDiskIoAbility.ts @@ -79,107 +79,6 @@ export class DiskIoAbilityRender extends Render { req.context.textBaseline = 'middle'; req.context.fillText(req.maxDiskRateName, 4, 5 + 9); } - - render(diskAbilityRequest: RequestMessage, diskIoAbilityList: Array, filter: Array) { - if (diskAbilityRequest.lazyRefresh) { - diskIoAbility( - diskIoAbilityList, - filter, - diskAbilityRequest.startNS, - diskAbilityRequest.endNS, - diskAbilityRequest.totalNS, - diskAbilityRequest.frame, - diskAbilityRequest.useCache || !diskAbilityRequest.range.refresh - ); - } else { - if (!diskAbilityRequest.useCache) { - diskIoAbility( - diskIoAbilityList, - filter, - diskAbilityRequest.startNS, - diskAbilityRequest.endNS, - diskAbilityRequest.totalNS, - diskAbilityRequest.frame, - false - ); - } - } - if (diskAbilityRequest.canvas) { - diskAbilityRequest.context.clearRect(0, 0, diskAbilityRequest.frame.width, diskAbilityRequest.frame.height); - let diskIoArr = filter; - if ( - diskIoArr.length > 0 && - !diskAbilityRequest.range.refresh && - !diskAbilityRequest.useCache && - diskAbilityRequest.lazyRefresh - ) { - drawLoading( - diskAbilityRequest.context, - diskAbilityRequest.startNS, - diskAbilityRequest.endNS, - diskAbilityRequest.totalNS, - diskAbilityRequest.frame, - diskIoArr[0].startNS, - diskIoArr[diskIoArr.length - 1].startNS + diskIoArr[diskIoArr.length - 1].dur - ); - } - diskAbilityRequest.context.beginPath(); - let maxDiskRate = diskAbilityRequest.params.maxDiskRate; - let maxDiskRateName = diskAbilityRequest.params.maxDiskRateName; - drawLines( - diskAbilityRequest.context, - diskAbilityRequest.xs, - diskAbilityRequest.frame.height, - diskAbilityRequest.lineColor - ); - DiskAbilityMonitorStruct.hoverDiskAbilityStruct = undefined; - if (diskAbilityRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - diskAbilityRequest.hoverX >= re.frame.x && - diskAbilityRequest.hoverX <= re.frame.x + re.frame.width && - diskAbilityRequest.hoverY >= re.frame.y && - diskAbilityRequest.hoverY <= re.frame.y + re.frame.height - ) { - DiskAbilityMonitorStruct.hoverDiskAbilityStruct = re; - break; - } - } - } - DiskAbilityMonitorStruct.selectDiskAbilityStruct = diskAbilityRequest.params.selectDiskAbilityStruct; - for (let re of filter) { - DiskAbilityMonitorStruct.draw(diskAbilityRequest.context, re, maxDiskRate, true); - } - drawSelection(diskAbilityRequest.context, diskAbilityRequest.params); - diskAbilityRequest.context.closePath(); - let textMetrics = diskAbilityRequest.context.measureText(maxDiskRateName); - diskAbilityRequest.context.globalAlpha = 0.8; - diskAbilityRequest.context.fillStyle = '#f0f0f0'; - diskAbilityRequest.context.fillRect(0, 5, textMetrics.width + 8, 18); - diskAbilityRequest.context.globalAlpha = 1; - diskAbilityRequest.context.fillStyle = '#333'; - diskAbilityRequest.context.textBaseline = 'middle'; - diskAbilityRequest.context.fillText(maxDiskRateName, 4, 5 + 9); - drawFlagLine( - diskAbilityRequest.context, - diskAbilityRequest.flagMoveInfo, - diskAbilityRequest.flagSelectedInfo, - diskAbilityRequest.startNS, - diskAbilityRequest.endNS, - diskAbilityRequest.totalNS, - diskAbilityRequest.frame, - diskAbilityRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: diskAbilityRequest.id, - type: diskAbilityRequest.type, - results: diskAbilityRequest.canvas ? undefined : filter, - hover: DiskAbilityMonitorStruct.hoverDiskAbilityStruct, - }); - } } export function diskIoAbility( diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyAnomaly.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyAnomaly.ts index 999d33632ba776c2c653e2153650293a373ba526..c424368ed249b23b0a2f048abbc08b09df242c5e 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyAnomaly.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyAnomaly.ts @@ -50,9 +50,9 @@ export class EnergyAnomalyRender extends PerfRender { req.appName, req.useCache || !TraceRow.range!.refresh ); - if(list.length > 0) { + if (list.length > 0) { filter.length = 0; - list.forEach(item => { + list.forEach((item) => { filter.push(item); }); } @@ -75,108 +75,7 @@ export class EnergyAnomalyRender extends PerfRender { req.context.closePath(); } - render(energyAnomalyRequest: RequestMessage, list: Array, filter: Array, dataList2: Array) { - if (energyAnomalyRequest.lazyRefresh) { - anomaly( - list, - filter, - energyAnomalyRequest.startNS, - energyAnomalyRequest.endNS, - energyAnomalyRequest.totalNS, - energyAnomalyRequest.frame, - energyAnomalyRequest.params.appName, - energyAnomalyRequest.useCache || !energyAnomalyRequest.range.refresh - ); - } else { - if (!energyAnomalyRequest.useCache) { - anomaly( - list, - filter, - energyAnomalyRequest.startNS, - energyAnomalyRequest.endNS, - energyAnomalyRequest.totalNS, - energyAnomalyRequest.frame, - energyAnomalyRequest.params.appName, - false - ); - } - } - if (energyAnomalyRequest.canvas) { - energyAnomalyRequest.context.clearRect( - 0, - 0, - energyAnomalyRequest.canvas.width, - energyAnomalyRequest.canvas.height - ); - let energyAnomlyArr = filter; - if ( - energyAnomlyArr.length > 0 && - !energyAnomalyRequest.range.refresh && - !energyAnomalyRequest.useCache && - energyAnomalyRequest.lazyRefresh - ) { - drawLoading( - energyAnomalyRequest.context, - energyAnomalyRequest.startNS, - energyAnomalyRequest.endNS, - energyAnomalyRequest.totalNS, - energyAnomalyRequest.frame, - energyAnomlyArr[0].startNS, - energyAnomlyArr[energyAnomlyArr.length - 1].startNS - ); - } - drawLines( - energyAnomalyRequest.context, - energyAnomalyRequest.xs, - energyAnomalyRequest.frame.height, - energyAnomalyRequest.lineColor - ); - energyAnomalyRequest.context.stroke(); - energyAnomalyRequest.context.beginPath(); - EnergyAnomalyStruct.hoverEnergyAnomalyStruct = undefined; - if (energyAnomalyRequest.isHover) { - let offset = 3; - for (let re of filter) { - if ( - re.frame && - energyAnomalyRequest.hoverX >= re.frame.x - offset && - energyAnomalyRequest.hoverX <= re.frame.x + re.frame.width + offset - ) { - EnergyAnomalyStruct.hoverEnergyAnomalyStruct = re; - break; - } - } - } else { - EnergyAnomalyStruct.hoverEnergyAnomalyStruct = energyAnomalyRequest.params.hoverStruct; - } - EnergyAnomalyStruct.selectEnergyAnomalyStruct = energyAnomalyRequest.params.selectEnergyAnomalyStruct; - energyAnomalyRequest.context.fillStyle = ColorUtils.FUNC_COLOR[0]; - energyAnomalyRequest.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; - for (let re of filter) { - EnergyAnomalyStruct.draw(energyAnomalyRequest.context, re); - } - drawLegend(energyAnomalyRequest); - drawSelection(energyAnomalyRequest.context, energyAnomalyRequest.params); - energyAnomalyRequest.context.closePath(); - drawFlagLine( - energyAnomalyRequest.context, - energyAnomalyRequest.flagMoveInfo, - energyAnomalyRequest.flagSelectedInfo, - energyAnomalyRequest.startNS, - energyAnomalyRequest.endNS, - energyAnomalyRequest.totalNS, - energyAnomalyRequest.frame, - energyAnomalyRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: energyAnomalyRequest.id, - type: energyAnomalyRequest.type, - results: energyAnomalyRequest.canvas ? undefined : filter, - hover: EnergyAnomalyStruct.hoverEnergyAnomalyStruct, - }); - } + render(energyAnomalyRequest: RequestMessage, list: Array, filter: Array, dataList2: Array) {} } export function drawLegend(req: any, isDark?: boolean) { diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyPower.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyPower.ts index a1bfbcedb7dfdac11198bebf06d023e5a80d65dc..bcfbe0c488f2f4a6c4ebcf5d66bed40b477f7649 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyPower.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyPower.ts @@ -73,110 +73,6 @@ export class EnergyPowerRender extends Render { let isDark = spApplication.hasAttribute('dark'); drawLegend(powerReq, isDark); } - - render(energyPowerRequest: RequestMessage, list: Array, filter: Array) { - if (energyPowerRequest.lazyRefresh) { - power( - list, - filter, - energyPowerRequest.startNS, - energyPowerRequest.endNS, - energyPowerRequest.totalNS, - energyPowerRequest.frame, - energyPowerRequest.useCache || !energyPowerRequest.range.refresh, - energyPowerRequest.params.maxPowerName - ); - } else { - if (!energyPowerRequest.useCache) { - power( - list, - filter, - energyPowerRequest.startNS, - energyPowerRequest.endNS, - energyPowerRequest.totalNS, - energyPowerRequest.frame, - false, - energyPowerRequest.params.maxPowerName - ); - } - } - if (energyPowerRequest.canvas) { - energyPowerRequest.context.clearRect(0, 0, energyPowerRequest.canvas.width, EnergyPowerStruct.rowHeight); - let arr = filter; - if ( - arr.length > 0 && - !energyPowerRequest.range.refresh && - !energyPowerRequest.useCache && - energyPowerRequest.lazyRefresh - ) { - drawLoading( - energyPowerRequest.context, - energyPowerRequest.startNS, - energyPowerRequest.endNS, - energyPowerRequest.totalNS, - energyPowerRequest.frame, - arr[0].startNS, - arr[arr.length - 1].startNS + arr[arr.length - 1].dur - ); - } - drawLines( - energyPowerRequest.context, - energyPowerRequest.xs, - energyPowerRequest.frame.height, - energyPowerRequest.lineColor - ); - energyPowerRequest.context.beginPath(); - EnergyPowerStruct.hoverEnergyPowerStruct = undefined; - if (energyPowerRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - energyPowerRequest.hoverX >= re.frame.x && - energyPowerRequest.hoverX <= re.frame.x + re.frame.width && - energyPowerRequest.hoverY >= re.frame.y && - energyPowerRequest.hoverY <= re.frame.y + re.frame.height - ) { - EnergyPowerStruct.hoverEnergyPowerStruct = re; - break; - } - } - } - EnergyPowerStruct.selectEnergyPowerStruct = energyPowerRequest.params.selectEnergyPowerStruct; - for (let index = 0; index < filter.length; index++) {} - energyPowerRequest.context.stroke(); - drawSelection(energyPowerRequest.context, energyPowerRequest.params); - energyPowerRequest.context.closePath(); - if (EnergyPowerStruct.maxPower != 0) { - let s = EnergyPowerStruct.maxPower + 'mAs'; - let textMetrics = energyPowerRequest.context.measureText(s); - energyPowerRequest.context.globalAlpha = 1.0; - energyPowerRequest.context.fillStyle = '#f0f0f0'; - energyPowerRequest.context.fillRect(0, 5, textMetrics.width + 8, 18); - energyPowerRequest.context.globalAlpha = 1; - energyPowerRequest.context.fillStyle = '#333'; - energyPowerRequest.context.textBaseline = 'middle'; - energyPowerRequest.context.fillText(s, 4, 5 + 9); - } - drawLegend(energyPowerRequest); - drawFlagLine( - energyPowerRequest.context, - energyPowerRequest.flagMoveInfo, - energyPowerRequest.flagSelectedInfo, - energyPowerRequest.startNS, - energyPowerRequest.endNS, - energyPowerRequest.totalNS, - energyPowerRequest.frame, - energyPowerRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: energyPowerRequest.id, - type: energyPowerRequest.type, - results: energyPowerRequest.canvas ? undefined : filter, - hover: EnergyPowerStruct.hoverEnergyPowerStruct, - }); - } } export function drawLegend(req: any, isDark?: boolean) { @@ -215,7 +111,7 @@ export function power( frame: any, use: boolean, appName: string -) { +): void { EnergyPowerStruct.maxPower = 0; list.length = 0; let firstData = []; @@ -240,7 +136,7 @@ export function power( list[list.length - 1].camera = item.camera === 0 ? list[list.length - 1].camera : item.camera; list[list.length - 1].bluetooth = item.bluetooth === 0 ? list[list.length - 1].bluetooth : item.bluetooth; list[list.length - 1].flashlight = item.flashlight === 0 ? list[list.length - 1].flashlight : item.flashlight; - list[list.length - 1].audio = item.audio ? list[list.length - 1].audio : item.audio; + list[list.length - 1].audio = item.audio === 0 ? list[list.length - 1].audio : item.audio; list[list.length - 1].wifiscan = item.wifiscan === 0 ? list[list.length - 1].wifiscan : item.wifiscan; } else { list.push(item); @@ -249,27 +145,38 @@ export function power( list.push(item); } }); - array.forEach((item) => { - if (list.indexOf(item) >= 0) { - EnergyPowerStruct.setPowerFrame(item, 5, startNS || 0, endNS || 0, totalNS || 0, frame); - let max = - (item.cpu || 0) + - (item.location || 0) + - (item.gpu || 0) + - (item.display || 0) + - (item.camera || 0) + - (item.bluetooth || 0) + - (item.flashlight || 0) + - (item.audio || 0) + - (item.wifiscan || 0); - if (max > EnergyPowerStruct.maxPower) { - EnergyPowerStruct.maxPower = max; - } - } - }); + computeMaxPower(array, list, startNS, endNS, totalNS, frame); } } +function computeMaxPower( + array: Array, + list: Array, + startNS: number, + endNS: number, + totalNS: number, + frame: any +): void { + array.forEach((item) => { + if (list.indexOf(item) >= 0) { + EnergyPowerStruct.setPowerFrame(item, 5, startNS || 0, endNS || 0, totalNS || 0, frame); + let max = + (item.cpu || 0) + + (item.location || 0) + + (item.gpu || 0) + + (item.display || 0) + + (item.camera || 0) + + (item.bluetooth || 0) + + (item.flashlight || 0) + + (item.audio || 0) + + (item.wifiscan || 0); + if (max > EnergyPowerStruct.maxPower) { + EnergyPowerStruct.maxPower = max; + } + } + }); +} + export class EnergyPowerStruct extends BaseStruct { static maxPower: number = 0; static maxPowerName: string = '0'; diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyState.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyState.ts index 895d6867dc3131684f565f606077c88393f369d5..a8599343cf5ddab4f7085b012db5701d23fd1e94 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyState.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergyState.ts @@ -73,119 +73,6 @@ export class EnergyStateRender extends Render { } req.context.closePath(); } - - render(energyStateRequest: RequestMessage, stateList: Array, filter: Array) { - if (energyStateRequest.lazyRefresh) { - state( - stateList, - filter, - energyStateRequest.startNS, - energyStateRequest.endNS, - energyStateRequest.totalNS, - energyStateRequest.frame, - energyStateRequest.useCache || !energyStateRequest.range.refresh - ); - } else { - if (!energyStateRequest.useCache) { - state( - stateList, - filter, - energyStateRequest.startNS, - energyStateRequest.endNS, - energyStateRequest.totalNS, - energyStateRequest.frame, - false - ); - } - } - if (energyStateRequest.canvas) { - energyStateRequest.context.clearRect(0, 0, energyStateRequest.canvas.width, energyStateRequest.canvas.height); - let energyStateArr = filter; - if ( - energyStateArr.length > 0 && - !energyStateRequest.range.refresh && - !energyStateRequest.useCache && - energyStateRequest.lazyRefresh - ) { - drawLoading( - energyStateRequest.context, - energyStateRequest.startNS, - energyStateRequest.endNS, - energyStateRequest.totalNS, - energyStateRequest.frame, - energyStateArr[0].startNS, - energyStateArr[energyStateArr.length - 1].startNS + energyStateArr[energyStateArr.length - 1].dur - ); - } - drawLines( - energyStateRequest.context, - energyStateRequest.xs, - energyStateRequest.frame.height, - energyStateRequest.lineColor - ); - energyStateRequest.context.beginPath(); - EnergyStateStruct.maxState = energyStateRequest.params.maxState; - EnergyStateStruct.maxStateName = energyStateRequest.params.maxStateName; - drawLines( - energyStateRequest.context, - energyStateRequest.xs, - energyStateRequest.frame.height, - energyStateRequest.lineColor - ); - EnergyStateStruct.hoverEnergyStateStruct = undefined; - if (energyStateRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - energyStateRequest.hoverX >= re.frame.x && - energyStateRequest.hoverX <= re.frame.x + re.frame.width && - energyStateRequest.hoverY >= re.frame.y && - energyStateRequest.hoverY <= re.frame.y + re.frame.height - ) { - EnergyStateStruct.hoverEnergyStateStruct = re; - break; - } - } - } - EnergyStateStruct.selectEnergyStateStruct = energyStateRequest.params.selectEnergyStateStruct; - for (let re of filter) { - EnergyStateStruct.draw(energyStateRequest.context, re, 0, ''); - } - drawSelection(energyStateRequest.context, energyStateRequest.params); - energyStateRequest.context.closePath(); - if ( - EnergyStateStruct.maxStateName != 'enable' && - EnergyStateStruct.maxStateName != 'disable' && - EnergyStateStruct.maxStateName != '-1' - ) { - let s = EnergyStateStruct.maxStateName; - let textMetrics = energyStateRequest.context.measureText(s); - energyStateRequest.context.globalAlpha = 1.0; - energyStateRequest.context.fillStyle = '#f0f0f0'; - energyStateRequest.context.fillRect(0, 5, textMetrics.width + 8, 18); - energyStateRequest.context.fillStyle = '#333'; - energyStateRequest.context.textBaseline = 'middle'; - energyStateRequest.context.fillText(s, 4, 5 + 9); - } - drawFlagLine( - energyStateRequest.context, - energyStateRequest.flagMoveInfo, - energyStateRequest.flagSelectedInfo, - energyStateRequest.startNS, - energyStateRequest.endNS, - energyStateRequest.totalNS, - energyStateRequest.frame, - energyStateRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: energyStateRequest.id, - type: energyStateRequest.type, - results: energyStateRequest.canvas ? undefined : filter, - hover: EnergyStateStruct.hoverEnergyStateStruct, - }); - } } export function state( diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergySystem.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergySystem.ts index a9ad255cb5fa4eaca8df5b05fa27d9d9b1bcb296..26f15a49dfd0d0f5cfdca03d1ead583b5a4632a7 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerEnergySystem.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerEnergySystem.ts @@ -48,172 +48,56 @@ export class EnergySystemRender extends Render { req.useCache || !TraceRow.range!.refresh ); drawLoadingFrame(req.context, row.dataListCache, row); - req.context.beginPath(); - let find = false; - let energySystemData: any = {}; - for (let i = 0; i < systemFilter.length; i++) { - let energySysStruct = systemFilter[i]; - - EnergySystemStruct.draw(req.context, energySysStruct); - if (row.isHover && energySysStruct.frame && isFrameContainPoint(energySysStruct.frame, row.hoverX, row.hoverY)) { - EnergySystemStruct.hoverEnergySystemStruct = energySysStruct; - if (energySysStruct.type === 0) { - if (energySysStruct.count !== undefined) { - energySystemData.workScheduler = energySysStruct.count; - } else { - energySystemData.workScheduler = '0'; - } - } - if (energySysStruct.type === 1) { - if (energySysStruct.count !== undefined) { - energySystemData.power = energySysStruct.count + ''; - } else { - energySystemData.power = '0'; - } - } - - if (energySysStruct.type === 2) { - if (energySysStruct.count !== undefined) { - energySystemData.location = energySysStruct.count + ''; - } else { - energySystemData.location = '0'; - } - } - find = true; - } - } - if (!find && row.isHover) EnergySystemStruct.hoverEnergySystemStruct = undefined; - if (EnergySystemStruct.hoverEnergySystemStruct) { - EnergySystemStruct.hoverEnergySystemStruct!.workScheduler = - energySystemData.workScheduler === undefined ? '0' : energySystemData.workScheduler; - EnergySystemStruct.hoverEnergySystemStruct!.power = - energySystemData.power === undefined ? '0' : energySystemData.power; - EnergySystemStruct.hoverEnergySystemStruct!.location = - energySystemData.location === undefined ? '0' : energySystemData.location; - } - let spApplication = document.getElementsByTagName('sp-application')[0]; - let isDark = spApplication.hasAttribute('dark'); - drawLegend(req, isDark); - req.context.closePath(); + drawProcedureWorkerEnergy(req, systemFilter, row); } +} - render(energySysRequest: RequestMessage, list: Array, filter: Array) { - if (energySysRequest.lazyRefresh) { - system( - list, - filter, - energySysRequest.startNS, - energySysRequest.endNS, - energySysRequest.totalNS, - energySysRequest.frame, - energySysRequest.useCache || !energySysRequest.range.refresh - ); - } else { - if (!energySysRequest.useCache) { - system( - list, - filter, - energySysRequest.startNS, - energySysRequest.endNS, - energySysRequest.totalNS, - energySysRequest.frame, - false - ); - } - } - if (energySysRequest.canvas) { - energySysRequest.context.clearRect(0, 0, energySysRequest.canvas.width, energySysRequest.canvas.height); - let energySystemArr = filter; - if ( - energySystemArr.length > 0 && - !energySysRequest.range.refresh && - !energySysRequest.useCache && - energySysRequest.lazyRefresh - ) { - drawLoading( - energySysRequest.context, - energySysRequest.startNS, - energySysRequest.endNS, - energySysRequest.totalNS, - energySysRequest.frame, - energySystemArr[0].startNS, - energySystemArr[energySystemArr.length - 1].startNS + energySystemArr[energySystemArr.length - 1].dur - ); - } - drawLines( - energySysRequest.context, - energySysRequest.xs, - energySysRequest.frame.height, - energySysRequest.lineColor - ); - energySysRequest.context.beginPath(); - EnergySystemStruct.hoverEnergySystemStruct = undefined; - if (energySysRequest.isHover) { - let a: any = {}; - for (let filterElement of filter) { - if ( - filterElement.frame && - energySysRequest.hoverX >= filterElement.frame.x && - energySysRequest.hoverX <= filterElement.frame.x + filterElement.frame.width - ) { - EnergySystemStruct.hoverEnergySystemStruct = filterElement; - if (filterElement.type === 0) { - if (filterElement.count !== undefined) { - a.workScheduler = filterElement.count; - } else { - a.workScheduler = '0'; - } - } - if (filterElement.type === 1) { - if (filterElement.count !== undefined) { - a.power = filterElement.count + ''; - } else { - a.power = '0'; - } - } - - if (filterElement.type === 2) { - if (filterElement.count !== undefined) { - a.location = filterElement.count + ''; - } else { - a.location = '0'; - } - } - } +function drawProcedureWorkerEnergy(req: any, systemFilter: Array, row: TraceRow) { + req.context.beginPath(); + let find = false; + let energySystemData: any = {}; + for (let i = 0; i < systemFilter.length; i++) { + let energySysStruct = systemFilter[i]; + EnergySystemStruct.draw(req.context, energySysStruct); + if (row.isHover && energySysStruct.frame && isFrameContainPoint(energySysStruct.frame, row.hoverX, row.hoverY)) { + EnergySystemStruct.hoverEnergySystemStruct = energySysStruct; + if (energySysStruct.type === 0) { + if (energySysStruct.count !== undefined) { + energySystemData.workScheduler = energySysStruct.count; + } else { + energySystemData.workScheduler = '0'; } - if (EnergySystemStruct.hoverEnergySystemStruct) { - EnergySystemStruct.hoverEnergySystemStruct!.workScheduler = - a.workScheduler == undefined ? '0' : a.workScheduler; - EnergySystemStruct.hoverEnergySystemStruct!.power = a.power == undefined ? '0' : a.power; - EnergySystemStruct.hoverEnergySystemStruct!.location = a.location == undefined ? '0' : a.location; + } + if (energySysStruct.type === 1) { + if (energySysStruct.count !== undefined) { + energySystemData.power = energySysStruct.count + ''; + } else { + energySystemData.power = '0'; } } - EnergySystemStruct.selectEnergySystemStruct = energySysRequest.params.selectEnergySystemStruct; - for (let re of filter) { - EnergySystemStruct.draw(energySysRequest.context, re); + if (energySysStruct.type === 2) { + if (energySysStruct.count !== undefined) { + energySystemData.location = energySysStruct.count + ''; + } else { + energySystemData.location = '0'; + } } - drawLegend(energySysRequest); - drawSelection(energySysRequest.context, energySysRequest.params); - energySysRequest.context.closePath(); - drawFlagLine( - energySysRequest.context, - energySysRequest.flagMoveInfo, - energySysRequest.flagSelectedInfo, - energySysRequest.startNS, - energySysRequest.endNS, - energySysRequest.totalNS, - energySysRequest.frame, - energySysRequest.slicesTime - ); + find = true; } - // @ts-ignore - self.postMessage({ - id: energySysRequest.id, - type: energySysRequest.type, - results: energySysRequest.canvas ? undefined : filter, - hover: EnergySystemStruct.hoverEnergySystemStruct, - }); } + if (!find && row.isHover) EnergySystemStruct.hoverEnergySystemStruct = undefined; + if (EnergySystemStruct.hoverEnergySystemStruct) { + EnergySystemStruct.hoverEnergySystemStruct!.workScheduler = + energySystemData.workScheduler === undefined ? '0' : energySystemData.workScheduler; + EnergySystemStruct.hoverEnergySystemStruct!.power = + energySystemData.power === undefined ? '0' : energySystemData.power; + EnergySystemStruct.hoverEnergySystemStruct!.location = + energySystemData.location === undefined ? '0' : energySystemData.location; + } + let spApplication = document.getElementsByTagName('sp-application')[0]; + let isDark = spApplication.hasAttribute('dark'); + drawLegend(req, isDark); + req.context.closePath(); } export function drawLegend(req: RequestMessage | any, isDark?: boolean) { @@ -253,7 +137,10 @@ export function systemData(data: Array, startNS: number, endNS: number, tot if (systemItem.count == 0) { systemItem.dur = 0; } - if ((systemItem.startNs || 0) + (systemItem.dur || 0) > (startNS || 0) && (systemItem.startNs || 0) < (endNS || 0)) { + if ( + (systemItem.startNs || 0) + (systemItem.dur || 0) > (startNS || 0) && + (systemItem.startNs || 0) < (endNS || 0) + ) { EnergySystemStruct.setSystemFrame(systemItem, 10, startNS || 0, endNS || 0, totalNS || 0, frame); } } @@ -272,7 +159,7 @@ export function system( let lockData: any = []; let locationData: any = []; let workData: any = []; - res.forEach(item => { + res.forEach((item) => { if (item.dataType === 1) { lockData.push(item); } else if (item.dataType === 2) { diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerFPS.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerFPS.ts index 27fc1073503d576890aaa2bbfac0bed4a8ae44a4..50486fb2a91c1095e1549e0654e5df758adc8631 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerFPS.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerFPS.ts @@ -68,89 +68,6 @@ export class FpsRender extends Render { req.context.textBaseline = 'middle'; req.context.fillText(maxFps, 4, 5 + 9); } - - render(fpsRequest: RequestMessage, list: Array, filter: Array) { - if (fpsRequest.lazyRefresh) { - fps( - list, - filter, - fpsRequest.startNS, - fpsRequest.endNS, - fpsRequest.totalNS, - fpsRequest.frame, - fpsRequest.useCache || !fpsRequest.range.refresh - ); - } else { - if (!fpsRequest.useCache) { - fps(list, filter, fpsRequest.startNS, fpsRequest.endNS, fpsRequest.totalNS, fpsRequest.frame, false); - } - } - if (fpsRequest.canvas) { - fpsRequest.context.clearRect(0, 0, fpsRequest.frame.width, fpsRequest.frame.height); - let fpsArr = filter; - if (fpsArr.length > 0 && !fpsRequest.range.refresh && !fpsRequest.useCache && fpsRequest.lazyRefresh) { - drawLoading( - fpsRequest.context, - fpsRequest.startNS, - fpsRequest.endNS, - fpsRequest.totalNS, - fpsRequest.frame, - fpsArr[0].startNS, - fpsArr[fpsArr.length - 1].startNS + fpsArr[fpsArr.length - 1].dur - ); - } - fpsRequest.context.beginPath(); - drawLines(fpsRequest.context, fpsRequest.xs, fpsRequest.frame.height, fpsRequest.lineColor); - FpsStruct.hoverFpsStruct = undefined; - if (fpsRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - fpsRequest.hoverX >= re.frame.x && - fpsRequest.hoverX <= re.frame.x + re.frame.width && - fpsRequest.hoverY >= re.frame.y && - fpsRequest.hoverY <= re.frame.y + re.frame.height - ) { - FpsStruct.hoverFpsStruct = re; - break; - } - } - } else { - FpsStruct.hoverFpsStruct = fpsRequest.params.hoverFpsStruct; - } - for (let re of filter) { - FpsStruct.draw(fpsRequest.context, re); - } - drawSelection(fpsRequest.context, fpsRequest.params); - fpsRequest.context.closePath(); - let maxFps = FpsStruct.maxFps + 'FPS'; - let fpsTextMetrics = fpsRequest.context.measureText(maxFps); - fpsRequest.context.globalAlpha = 0.8; - fpsRequest.context.fillStyle = '#f0f0f0'; - fpsRequest.context.fillRect(0, 5, fpsTextMetrics.width + 8, 18); - fpsRequest.context.globalAlpha = 1; - fpsRequest.context.fillStyle = '#333'; - fpsRequest.context.textBaseline = 'middle'; - fpsRequest.context.fillText(maxFps, 4, 5 + 9); - drawFlagLine( - fpsRequest.context, - fpsRequest.flagMoveInfo, - fpsRequest.flagSelectedInfo, - fpsRequest.startNS, - fpsRequest.endNS, - fpsRequest.totalNS, - fpsRequest.frame, - fpsRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: fpsRequest.id, - type: fpsRequest.type, - results: fpsRequest.canvas ? undefined : filter, - hover: FpsStruct.hoverFpsStruct, - }); - } } export function fps( diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerFunc.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerFunc.ts index 885f539f69aedb2956393519f15885fde83b3943..7d6f7ef2ea5e2e1d28b77a0c6fd4a140ee061fe4 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerFunc.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerFunc.ts @@ -174,7 +174,9 @@ export class FuncStruct extends BaseFuncStruct { ctx.fillStyle = ColorUtils.funcTextColor(textColor); drawString(ctx, `${data.funName || ''}`, 5, data.frame, data); } - if (data === FuncStruct.selectFuncStruct) { + if (data.callid == FuncStruct.selectFuncStruct?.callid&& + data.startTs == FuncStruct.selectFuncStruct?.startTs&& + data.depth == FuncStruct.selectFuncStruct?.depth) { ctx.strokeStyle = '#000'; ctx.lineWidth = 2; ctx.strokeRect(data.frame.x, data.frame.y + 1, data.frame.width, miniHeight - padding * 2 - 2); diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerMem.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerMem.ts index 77af65da0d873b2862fd3fa46958a69a8aeed388..1dce4e00cb7ee5b4062dbd04472b8cb3aa8817f1 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerMem.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerMem.ts @@ -30,7 +30,7 @@ import { mem, drawLoadingFrame, } from './ProcedureWorkerCommon'; -import { CpuStruct } from './ProcedureWorkerCPU'; +import { CpuStruct } from './cpu/ProcedureWorkerCPU'; import { ProcessMemStruct as BaseProcessMemStruct } from '../../bean/ProcessMemStruct'; export class MemRender extends Render { renderMainThread( @@ -69,80 +69,6 @@ export class MemRender extends Render { } req.context.closePath(); } - - render(memRequest: RequestMessage, memList: Array, filter: Array): void { - if (memRequest.lazyRefresh) { - mem( - memList, - filter, - memRequest.startNS, - memRequest.endNS, - memRequest.totalNS, - memRequest.frame, - memRequest.useCache || !memRequest.range.refresh - ); - } else { - if (!memRequest.useCache) { - mem(memList, filter, memRequest.startNS, memRequest.endNS, memRequest.totalNS, memRequest.frame, false); - } - } - if (memRequest.canvas) { - memRequest.context.clearRect(0, 0, memRequest.frame.width, memRequest.frame.height); - let arr = filter; - if (arr.length > 0 && !memRequest.range.refresh && !memRequest.useCache && memRequest.lazyRefresh) { - drawLoading( - memRequest.context, - memRequest.startNS, - memRequest.endNS, - memRequest.totalNS, - memRequest.frame, - arr[0].startTime, - arr[arr.length - 1].startTime + arr[arr.length - 1].dur - ); - } - memRequest.context.beginPath(); - drawLines(memRequest.context, memRequest.xs, memRequest.frame.height, memRequest.lineColor); - ProcessMemStruct.hoverProcessMemStruct = undefined; - if (memRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - memRequest.hoverX >= re.frame.x && - memRequest.hoverX <= re.frame.x + re.frame.width && - memRequest.hoverY >= re.frame.y && - memRequest.hoverY <= re.frame.y + re.frame.height - ) { - ProcessMemStruct.hoverProcessMemStruct = re; - break; - } - } - } else { - ProcessMemStruct.hoverProcessMemStruct = memRequest.params.hoverProcessMemStruct; - } - for (let re of filter) { - ProcessMemStruct.draw(memRequest.context, re); - } - drawSelection(memRequest.context, memRequest.params); - memRequest.context.closePath(); - drawFlagLine( - memRequest.context, - memRequest.flagMoveInfo, - memRequest.flagSelectedInfo, - memRequest.startNS, - memRequest.endNS, - memRequest.totalNS, - memRequest.frame, - memRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: memRequest.id, - type: memRequest.type, - results: memRequest.canvas ? undefined : filter, - hover: ProcessMemStruct.hoverProcessMemStruct, - }); - } } export class ProcessMemStruct extends BaseProcessMemStruct { diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerMemoryAbility.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerMemoryAbility.ts index 5ced3f6126f530463891cc4ff5b044edf71ac3ac..aa0da0683f0d2b743f5d1d36cae538af60bec770 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerMemoryAbility.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerMemoryAbility.ts @@ -79,113 +79,6 @@ export class MemoryAbilityRender extends Render { req.context.textBaseline = 'middle'; req.context.fillText(req.maxMemoryByteName, 4, 5 + 9); } - - render(memoryAbilityRequest: RequestMessage, list: Array, filter: Array): void { - if (memoryAbilityRequest.lazyRefresh) { - memoryAbility( - list, - filter, - memoryAbilityRequest.startNS, - memoryAbilityRequest.endNS, - memoryAbilityRequest.totalNS, - memoryAbilityRequest.frame, - memoryAbilityRequest.useCache || !memoryAbilityRequest.range.refresh - ); - } else { - if (!memoryAbilityRequest.useCache) { - memoryAbility( - list, - filter, - memoryAbilityRequest.startNS, - memoryAbilityRequest.endNS, - memoryAbilityRequest.totalNS, - memoryAbilityRequest.frame, - false - ); - } - } - if (memoryAbilityRequest.canvas) { - memoryAbilityRequest.context.clearRect(0, 0, memoryAbilityRequest.frame.width, memoryAbilityRequest.frame.height); - let memoryAbilityArr = filter; - if ( - memoryAbilityArr.length > 0 && - !memoryAbilityRequest.range.refresh && - !memoryAbilityRequest.useCache && - memoryAbilityRequest.lazyRefresh - ) { - drawLoading( - memoryAbilityRequest.context, - memoryAbilityRequest.startNS, - memoryAbilityRequest.endNS, - memoryAbilityRequest.totalNS, - memoryAbilityRequest.frame, - memoryAbilityArr[0].startNS, - memoryAbilityArr[memoryAbilityArr.length - 1].startNS + memoryAbilityArr[memoryAbilityArr.length - 1].dur - ); - } - memoryAbilityRequest.context.beginPath(); - MemoryAbilityMonitorStruct.maxMemoryByte = memoryAbilityRequest.params.maxMemoryByte; - MemoryAbilityMonitorStruct.maxMemoryByteName = memoryAbilityRequest.params.maxMemoryByteName; - drawLines( - memoryAbilityRequest.context, - memoryAbilityRequest.xs, - memoryAbilityRequest.frame.height, - memoryAbilityRequest.lineColor - ); - MemoryAbilityMonitorStruct.hoverMemoryAbilityStruct = undefined; - if (memoryAbilityRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - memoryAbilityRequest.hoverX >= re.frame.x && - memoryAbilityRequest.hoverX <= re.frame.x + re.frame.width && - memoryAbilityRequest.hoverY >= re.frame.y && - memoryAbilityRequest.hoverY <= re.frame.y + re.frame.height - ) { - MemoryAbilityMonitorStruct.hoverMemoryAbilityStruct = re; - break; - } - } - } - MemoryAbilityMonitorStruct.selectMemoryAbilityStruct = memoryAbilityRequest.params.selectMemoryAbilityStruct; - for (let re of filter) { - MemoryAbilityMonitorStruct.draw( - memoryAbilityRequest.context, - re, - MemoryAbilityMonitorStruct.maxMemoryByte, - true - ); - } - drawSelection(memoryAbilityRequest.context, memoryAbilityRequest.params); - memoryAbilityRequest.context.closePath(); - let s = MemoryAbilityMonitorStruct.maxMemoryByteName; - let textMetrics = memoryAbilityRequest.context.measureText(s); - memoryAbilityRequest.context.globalAlpha = 0.8; - memoryAbilityRequest.context.fillStyle = '#f0f0f0'; - memoryAbilityRequest.context.fillRect(0, 5, textMetrics.width + 8, 18); - memoryAbilityRequest.context.globalAlpha = 1; - memoryAbilityRequest.context.fillStyle = '#333'; - memoryAbilityRequest.context.textBaseline = 'middle'; - memoryAbilityRequest.context.fillText(s, 4, 5 + 9); - drawFlagLine( - memoryAbilityRequest.context, - memoryAbilityRequest.flagMoveInfo, - memoryAbilityRequest.flagSelectedInfo, - memoryAbilityRequest.startNS, - memoryAbilityRequest.endNS, - memoryAbilityRequest.totalNS, - memoryAbilityRequest.frame, - memoryAbilityRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: memoryAbilityRequest.id, - type: memoryAbilityRequest.type, - results: memoryAbilityRequest.canvas ? undefined : filter, - hover: MemoryAbilityMonitorStruct.hoverMemoryAbilityStruct, - }); - } } export function memoryAbility( diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerProcess.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerProcess.ts index c826292db3bd35de5994c26c64b391f93bbf9476..243c897d8aedbcb634c8cd66000a8c2ec25cce68 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerProcess.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerProcess.ts @@ -26,7 +26,7 @@ import { Render, RequestMessage, } from './ProcedureWorkerCommon'; -import { CpuStruct } from './ProcedureWorkerCPU'; +import { CpuStruct } from './cpu/ProcedureWorkerCPU'; import { TraceRow } from '../../component/trace/base/TraceRow'; export class ProcessRender extends Render { @@ -54,69 +54,6 @@ export class ProcessRender extends Render { req.context.fill(path); req.context.closePath(); } - - render(processReq: RequestMessage, list: Array, filter: Array) { - if (processReq.lazyRefresh) { - proc( - list, - filter, - processReq.startNS, - processReq.endNS, - processReq.totalNS, - processReq.frame, - processReq.useCache || !processReq.range.refresh - ); - } else { - if (!processReq.useCache) { - proc(list, filter, processReq.startNS, processReq.endNS, processReq.totalNS, processReq.frame, false); - } - } - if (processReq.canvas) { - processReq.context.clearRect(0, 0, processReq.frame.width, processReq.frame.height); - let arr = filter; - if (arr.length > 0 && !processReq.range.refresh && !processReq.useCache && processReq.lazyRefresh) { - drawLoading( - processReq.context, - processReq.startNS, - processReq.endNS, - processReq.totalNS, - processReq.frame, - arr[0].startTime, - arr[arr.length - 1].startTime + arr[arr.length - 1].dur - ); - } - processReq.context.beginPath(); - CpuStruct.cpuCount = processReq.params.cpuCount; - drawLines(processReq.context, processReq.xs, processReq.frame.height, processReq.lineColor); - let path = new Path2D(); - let miniHeight: number = 0; - miniHeight = Math.round((processReq.frame.height - CpuStruct.cpuCount * 2) / CpuStruct.cpuCount); - processReq.context.fillStyle = ColorUtils.colorForTid(processReq.params.pid || 0); - for (let re of filter) { - ProcessStruct.draw(processReq.context, path, re, miniHeight); - } - processReq.context.fill(path); - drawSelection(processReq.context, processReq.params); - processReq.context.closePath(); - drawFlagLine( - processReq.context, - processReq.flagMoveInfo, - processReq.flagSelectedInfo, - processReq.startNS, - processReq.endNS, - processReq.totalNS, - processReq.frame, - processReq.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: processReq.id, - type: processReq.type, - results: processReq.canvas ? undefined : filter, - hover: undefined, - }); - } } export function proc( processList: Array, diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerTimeline.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerTimeline.ts index ef5cd6a618a4eb97ce0e75480573030fabc6a9e7..33b44b8ed10905c8fe13baf7823c0bf2b994c799 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerTimeline.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerTimeline.ts @@ -27,38 +27,6 @@ let offsetLeft: number = 0; export class TimelineRender extends Render { renderMainThread(req: any, row: TraceRow) {} - render(req: RequestMessage, list: Array, filter: Array) { - timeline( - req.canvas, - req.context, - req.startNS, - req.endNS, - req.totalNS, - req.frame, - req.params.keyPressCode, - req.params.keyUpCode, - req.params.mouseDown, - req.params.mouseUp, - req.params.mouseMove, - req.params.mouseOut, - req.params.offsetLeft, - req.params.offsetTop, - (a: any) => { - //@ts-ignore - self.postMessage({ - id: 'timeline', - type: 'timeline-range-changed', - results: a, - }); - } - ); - // @ts-ignore - self.postMessage({ - id: req.id, - type: req.type, - results: null, - }); - } } export function timeline( @@ -469,6 +437,33 @@ export class RangeRuler extends Graph { } } + scaleSetting(): void { + let l20 = (this.range.endNS - this.range.startNS) / 20; + let min = 0; + let max = 0; + let weight = 0; + for (let index = 0; index < this.scales.length; index++) { + if (this.scales[index] > l20) { + if (index > 0) { + min = this.scales[index - 1]; + } else { + min = 0; + } + max = this.scales[index]; + weight = ((l20 - min) * 1.0) / (max - min); + if (weight > 0.243) { + this.scale = max; + } else { + this.scale = min; + } + break; + } + } + if (this.scale == 0) { + this.scale = this.scales[0]; + } + } + draw(discardNotify: boolean = false): void { this.c.clearRect(this.frame.x - markPadding, this.frame.y, this.frame.width + markPadding * 2, this.frame.height); this.c.beginPath(); @@ -485,30 +480,7 @@ export class RangeRuler extends Graph { this.range.endX = this.rangeRect.x + this.rangeRect.width; this.range.startNS = (this.range.startX * this.range.totalNS) / (this.frame.width || 0); this.range.endNS = (this.range.endX * this.range.totalNS) / (this.frame.width || 0); - let l20 = (this.range.endNS - this.range.startNS) / 20; - let min = 0; - let max = 0; - let weight = 0; - for (let index = 0; index < this.scales.length; index++) { - if (this.scales[index] > l20) { - if (index > 0) { - min = this.scales[index - 1]; - } else { - min = 0; - } - max = this.scales[index]; - weight = ((l20 - min) * 1.0) / (max - min); - if (weight > 0.243) { - this.scale = max; - } else { - this.scale = min; - } - break; - } - } - if (this.scale == 0) { - this.scale = this.scales[0]; - } + this.scaleSetting(); let tmpNs = 0; let timeLineYu = this.range.startNS % this.scale; let timeLineRealW = (this.scale * this.frame.width) / (this.range.endNS - this.range.startNS); @@ -596,6 +568,43 @@ export class RangeRuler extends Graph { this.movingMark = null; } + movingRange(maxX: number, x: number): void { + let result = x - this.mouseDownOffsetX; + let mA = result + this.markAX; + let mB = result + this.markBX; + if (mA >= 0 && mA <= maxX) { + this.markA.frame.x = mA; + } else if (mA < 0) { + this.markA.frame.x = 0; + } else { + this.markA.frame.x = maxX; + } + this.markA.inspectionFrame.x = this.markA.frame.x - markPadding; + if (mB >= 0 && mB <= maxX) { + this.markB.frame.x = mB; + } else if (mB < 0) { + this.markB.frame.x = 0; + } else { + this.markB.frame.x = maxX; + } + this.markB.inspectionFrame.x = this.markB.frame.x - markPadding; + requestAnimationFrame(() => this.draw()); + } + + movingNewRange(maxX: number, x: number): void { + this.markA.frame.x = this.mouseDownOffsetX; + this.markA.inspectionFrame.x = this.mouseDownOffsetX - markPadding; + if (x >= 0 && x <= maxX) { + this.markB.frame.x = x; + } else if (x < 0) { + this.markB.frame.x = 0; + } else { + this.markB.frame.x = maxX; + } + this.markB.inspectionFrame.x = this.markB.frame.x - markPadding; + requestAnimationFrame(() => this.draw()); + } + mouseMove(ev: MouseEvent) { let x = ev.offsetX - (offsetLeft || 0); let y = ev.offsetY - (offsetTop || 0); @@ -627,38 +636,9 @@ export class RangeRuler extends Graph { requestAnimationFrame(() => this.draw()); } if (this.isMovingRange && this.isMouseDown) { - let result = x - this.mouseDownOffsetX; - let mA = result + this.markAX; - let mB = result + this.markBX; - if (mA >= 0 && mA <= maxX) { - this.markA.frame.x = mA; - } else if (mA < 0) { - this.markA.frame.x = 0; - } else { - this.markA.frame.x = maxX; - } - this.markA.inspectionFrame.x = this.markA.frame.x - markPadding; - if (mB >= 0 && mB <= maxX) { - this.markB.frame.x = mB; - } else if (mB < 0) { - this.markB.frame.x = 0; - } else { - this.markB.frame.x = maxX; - } - this.markB.inspectionFrame.x = this.markB.frame.x - markPadding; - requestAnimationFrame(() => this.draw()); + this.movingRange(maxX, x); } else if (this.isNewRange) { - this.markA.frame.x = this.mouseDownOffsetX; - this.markA.inspectionFrame.x = this.mouseDownOffsetX - markPadding; - if (x >= 0 && x <= maxX) { - this.markB.frame.x = x; - } else if (x < 0) { - this.markB.frame.x = 0; - } else { - this.markB.frame.x = maxX; - } - this.markB.inspectionFrame.x = this.markB.frame.x - markPadding; - requestAnimationFrame(() => this.draw()); + this.movingNewRange(maxX, x); } } @@ -679,7 +659,52 @@ export class RangeRuler extends Graph { this.markB.inspectionFrame.x = this.markB.frame.x - markPadding; } - keyPress(ev: KeyboardEvent) { + keyPressInW(): void { + let animW = () => { + if (this.scale === 50) return; + this.range.startNS += (this.centerXPercentage * this.currentDuration * 2 * this.scale) / this.p; + this.range.endNS -= ((1 - this.centerXPercentage) * this.currentDuration * 2 * this.scale) / this.p; + this.fillX(); + this.draw(); + this.pressFrameId = requestAnimationFrame(animW); + }; + this.pressFrameId = requestAnimationFrame(animW); + } + keyPressInS(): void { + let animS = () => { + if (this.range.startNS <= 0 && this.range.endNS >= this.range.totalNS) return; + this.range.startNS -= (this.centerXPercentage * this.currentDuration * 2 * this.scale) / this.p; + this.range.endNS += ((1 - this.centerXPercentage) * this.currentDuration * 2 * this.scale) / this.p; + this.fillX(); + this.draw(); + this.pressFrameId = requestAnimationFrame(animS); + }; + this.pressFrameId = requestAnimationFrame(animS); + } + keyPressInA(): void { + let animA = () => { + if (this.range.startNS == 0) return; + let s = (this.scale / this.p) * this.currentDuration; + this.range.startNS -= s; + this.range.endNS -= s; + this.fillX(); + this.draw(); + this.pressFrameId = requestAnimationFrame(animA); + }; + this.pressFrameId = requestAnimationFrame(animA); + } + keyPressInD(): void { + let animD = () => { + if (this.range.endNS >= this.range.totalNS) return; + this.range.startNS += (this.scale / this.p) * this.currentDuration; + this.range.endNS += (this.scale / this.p) * this.currentDuration; + this.fillX(); + this.draw(); + this.pressFrameId = requestAnimationFrame(animD); + }; + this.pressFrameId = requestAnimationFrame(animD); + } + keyPress(ev: KeyboardEvent): void { if (this.animaStartTime === undefined) { this.animaStartTime = new Date().getTime(); } @@ -691,54 +716,79 @@ export class RangeRuler extends Graph { this.isPress = true; switch (ev.key.toLocaleLowerCase()) { case 'w': - let animW = () => { - if (this.scale === 50) return; - this.range.startNS += (this.centerXPercentage * this.currentDuration * 2 * this.scale) / this.p; - this.range.endNS -= ((1 - this.centerXPercentage) * this.currentDuration * 2 * this.scale) / this.p; - this.fillX(); - this.draw(); - this.pressFrameId = requestAnimationFrame(animW); - }; - this.pressFrameId = requestAnimationFrame(animW); + this.keyPressInW(); break; case 's': - let animS = () => { - if (this.range.startNS <= 0 && this.range.endNS >= this.range.totalNS) return; - this.range.startNS -= (this.centerXPercentage * this.currentDuration * 2 * this.scale) / this.p; - this.range.endNS += ((1 - this.centerXPercentage) * this.currentDuration * 2 * this.scale) / this.p; - this.fillX(); - this.draw(); - this.pressFrameId = requestAnimationFrame(animS); - }; - this.pressFrameId = requestAnimationFrame(animS); + this.keyPressInS(); break; case 'a': - let animA = () => { - if (this.range.startNS == 0) return; - let s = (this.scale / this.p) * this.currentDuration; - this.range.startNS -= s; - this.range.endNS -= s; - this.fillX(); - this.draw(); - this.pressFrameId = requestAnimationFrame(animA); - }; - this.pressFrameId = requestAnimationFrame(animA); + this.keyPressInA(); break; case 'd': - let animD = () => { - if (this.range.endNS >= this.range.totalNS) return; - this.range.startNS += (this.scale / this.p) * this.currentDuration; - this.range.endNS += (this.scale / this.p) * this.currentDuration; - this.fillX(); - this.draw(); - this.pressFrameId = requestAnimationFrame(animD); - }; - this.pressFrameId = requestAnimationFrame(animD); + this.keyPressInD(); break; } } + keyUpInW(startTime: number): void { + let animW = () => { + if (this.scale === 50) return; + let dur = new Date().getTime() - startTime; + this.range.startNS += (this.centerXPercentage * 100 * this.scale) / this.p; + this.range.endNS -= ((1 - this.centerXPercentage) * 100 * this.scale) / this.p; + this.fillX(); + this.draw(); + if (dur < 300) { + requestAnimationFrame(animW); + } + }; + requestAnimationFrame(animW); + } + keyUpInS(startTime: number): void { + let animS = () => { + if (this.range.startNS <= 0 && this.range.endNS >= this.range.totalNS) return; + let dur = new Date().getTime() - startTime; + this.range.startNS -= (this.centerXPercentage * 100 * this.scale) / this.p; + this.range.endNS += ((1 - this.centerXPercentage) * 100 * this.scale) / this.p; + this.fillX(); + this.draw(); + if (dur < 300) { + requestAnimationFrame(animS); + } + }; + requestAnimationFrame(animS); + } + keyUpInA(startTime: number): void { + let animA = () => { + if (this.range.startNS <= 0) return; + let dur = new Date().getTime() - startTime; + let s = (this.scale * 80) / this.p; + this.range.startNS -= s; + this.range.endNS -= s; + this.fillX(); + this.draw(); + if (dur < 300) { + requestAnimationFrame(animA); + } + }; + animA(); + } + keyUpInD(startTime: number): void { + let animD = () => { + if (this.range.endNS >= this.range.totalNS) return; + let dur = new Date().getTime() - startTime; + let s = (this.scale * 80) / this.p; + this.range.startNS += s; + this.range.endNS += s; + this.fillX(); + this.draw(); + if (dur < 300) { + requestAnimationFrame(animD); + } + }; + animD(); + } - keyUp(ev: KeyboardEvent) { + keyUp(ev: KeyboardEvent): void { this.animaStartTime = undefined; this.isPress = false; if (this.pressFrameId != -1) { @@ -747,62 +797,16 @@ export class RangeRuler extends Graph { let startTime = new Date().getTime(); switch (ev.key) { case 'w': - let animW = () => { - if (this.scale === 50) return; - let dur = new Date().getTime() - startTime; - this.range.startNS += (this.centerXPercentage * 100 * this.scale) / this.p; - this.range.endNS -= ((1 - this.centerXPercentage) * 100 * this.scale) / this.p; - this.fillX(); - this.draw(); - if (dur < 300) { - requestAnimationFrame(animW); - } - }; - requestAnimationFrame(animW); + this.keyUpInW.call(this, startTime); break; case 's': - let animS = () => { - if (this.range.startNS <= 0 && this.range.endNS >= this.range.totalNS) return; - let dur = new Date().getTime() - startTime; - this.range.startNS -= (this.centerXPercentage * 100 * this.scale) / this.p; - this.range.endNS += ((1 - this.centerXPercentage) * 100 * this.scale) / this.p; - this.fillX(); - this.draw(); - if (dur < 300) { - requestAnimationFrame(animS); - } - }; - requestAnimationFrame(animS); + this.keyUpInS.call(this, startTime); break; case 'a': - let animA = () => { - if (this.range.startNS <= 0) return; - let dur = new Date().getTime() - startTime; - let s = (this.scale * 80) / this.p; - this.range.startNS -= s; - this.range.endNS -= s; - this.fillX(); - this.draw(); - if (dur < 300) { - requestAnimationFrame(animA); - } - }; - animA(); + this.keyUpInA.call(this, startTime); break; case 'd': - let animD = () => { - if (this.range.endNS >= this.range.totalNS) return; - let dur = new Date().getTime() - startTime; - let s = (this.scale * 80) / this.p; - this.range.startNS += s; - this.range.endNS += s; - this.fillX(); - this.draw(); - if (dur < 300) { - requestAnimationFrame(animD); - } - }; - animD(); + this.keyUpInD.call(this, startTime); break; } } diff --git a/ide/src/trace/database/ui-worker/ProcedureWorkerVirtualMemory.ts b/ide/src/trace/database/ui-worker/ProcedureWorkerVirtualMemory.ts index 9ecda7ed1ed8242eb5e3d20e04a760d0e3e24ec7..ef59f057b93e350107c9ecb0581989e5af7804ee 100644 --- a/ide/src/trace/database/ui-worker/ProcedureWorkerVirtualMemory.ts +++ b/ide/src/trace/database/ui-worker/ProcedureWorkerVirtualMemory.ts @@ -59,98 +59,6 @@ export class VirtualMemoryRender extends Render { if (!find && row.isHover) VirtualMemoryStruct.hoverStruct = undefined; req.context.closePath(); } - - render(virtualMemoryRequest: RequestMessage, virtualMemoryList: Array, filter: Array) { - if (virtualMemoryRequest.lazyRefresh) { - mem( - virtualMemoryList, - filter, - virtualMemoryRequest.startNS, - virtualMemoryRequest.endNS, - virtualMemoryRequest.totalNS, - virtualMemoryRequest.frame, - virtualMemoryRequest.useCache || !virtualMemoryRequest.range.refresh - ); - } else { - if (!virtualMemoryRequest.useCache) { - mem( - virtualMemoryList, - filter, - virtualMemoryRequest.startNS, - virtualMemoryRequest.endNS, - virtualMemoryRequest.totalNS, - virtualMemoryRequest.frame, - false - ); - } - } - if (virtualMemoryRequest.canvas) { - virtualMemoryRequest.context.clearRect(0, 0, virtualMemoryRequest.frame.width, virtualMemoryRequest.frame.height); - let arr = filter; - if ( - arr.length > 0 && - !virtualMemoryRequest.range.refresh && - !virtualMemoryRequest.useCache && - virtualMemoryRequest.lazyRefresh - ) { - drawLoading( - virtualMemoryRequest.context, - virtualMemoryRequest.startNS, - virtualMemoryRequest.endNS, - virtualMemoryRequest.totalNS, - virtualMemoryRequest.frame, - arr[0].startTime, - arr[arr.length - 1].startTime + arr[arr.length - 1].dur - ); - } - virtualMemoryRequest.context.beginPath(); - drawLines( - virtualMemoryRequest.context, - virtualMemoryRequest.xs, - virtualMemoryRequest.frame.height, - virtualMemoryRequest.lineColor - ); - VirtualMemoryStruct.hoverStruct = undefined; - if (virtualMemoryRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - virtualMemoryRequest.hoverX >= re.frame.x && - virtualMemoryRequest.hoverX <= re.frame.x + re.frame.width && - virtualMemoryRequest.hoverY >= re.frame.y && - virtualMemoryRequest.hoverY <= re.frame.y + re.frame.height - ) { - VirtualMemoryStruct.hoverStruct = re; - break; - } - } - } else { - VirtualMemoryStruct.hoverStruct = virtualMemoryRequest.params.hoverStruct; - } - for (let re of filter) { - VirtualMemoryStruct.draw(virtualMemoryRequest.context, re); - } - drawSelection(virtualMemoryRequest.context, virtualMemoryRequest.params); - virtualMemoryRequest.context.closePath(); - drawFlagLine( - virtualMemoryRequest.context, - virtualMemoryRequest.flagMoveInfo, - virtualMemoryRequest.flagSelectedInfo, - virtualMemoryRequest.startNS, - virtualMemoryRequest.endNS, - virtualMemoryRequest.totalNS, - virtualMemoryRequest.frame, - virtualMemoryRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: virtualMemoryRequest.id, - type: virtualMemoryRequest.type, - results: virtualMemoryRequest.canvas ? undefined : filter, - hover: VirtualMemoryStruct.hoverStruct, - }); - } } export class VirtualMemoryStruct extends BaseStruct { diff --git a/ide/src/trace/database/ui-worker/ProduceWorkerSdkCounter.ts b/ide/src/trace/database/ui-worker/ProduceWorkerSdkCounter.ts index fcb5c8d4567fa21cd3afdd9d9e9d02ed8349ee08..cd6a95df4426253d68330c752fb28f9f533ebdd4 100644 --- a/ide/src/trace/database/ui-worker/ProduceWorkerSdkCounter.ts +++ b/ide/src/trace/database/ui-worker/ProduceWorkerSdkCounter.ts @@ -73,107 +73,6 @@ export class SdkCounterRender extends Render { req.context.fillText(maxCounterName, 4, 5 + 9); } - render(sdkCounterRequest: RequestMessage, list: Array, filter: Array): void { - if (sdkCounterRequest.lazyRefresh) { - this.counter( - list, - filter, - sdkCounterRequest.startNS, - sdkCounterRequest.endNS, - sdkCounterRequest.totalNS, - sdkCounterRequest.frame, - sdkCounterRequest.useCache || !sdkCounterRequest.range.refresh - ); - } else { - if (!sdkCounterRequest.useCache) { - this.counter( - list, - filter, - sdkCounterRequest.startNS, - sdkCounterRequest.endNS, - sdkCounterRequest.totalNS, - sdkCounterRequest.frame, - false - ); - } - } - if (sdkCounterRequest.canvas) { - sdkCounterRequest.context.clearRect(0, 0, sdkCounterRequest.frame.width, sdkCounterRequest.frame.height); - let sdkCounterArr = filter; - if ( - sdkCounterArr.length > 0 && - !sdkCounterRequest.range.refresh && - !sdkCounterRequest.useCache && - sdkCounterRequest.lazyRefresh - ) { - drawLoading( - sdkCounterRequest.context, - sdkCounterRequest.startNS, - sdkCounterRequest.endNS, - sdkCounterRequest.totalNS, - sdkCounterRequest.frame, - sdkCounterArr[0].startNS, - sdkCounterArr[sdkCounterArr.length - 1].startNS + sdkCounterArr[sdkCounterArr.length - 1].dur - ); - } - sdkCounterRequest.context.beginPath(); - let maxCounter = sdkCounterRequest.params.maxCounter; - let maxCounterName = sdkCounterRequest.params.maxCounterName; - drawLines( - sdkCounterRequest.context, - sdkCounterRequest.xs, - sdkCounterRequest.frame.height, - sdkCounterRequest.lineColor - ); - CounterStruct.hoverCounterStruct = undefined; - if (sdkCounterRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - sdkCounterRequest.hoverX >= re.frame.x && - sdkCounterRequest.hoverX <= re.frame.x + re.frame.width && - sdkCounterRequest.hoverY >= re.frame.y && - sdkCounterRequest.hoverY <= re.frame.y + re.frame.height - ) { - CounterStruct.hoverCounterStruct = re; - break; - } - } - } - CounterStruct.selectCounterStruct = sdkCounterRequest.params.selectCounterStruct; - for (let re of filter) { - CounterStruct.draw(sdkCounterRequest.context, re, maxCounter); - } - drawSelection(sdkCounterRequest.context, sdkCounterRequest.params); - sdkCounterRequest.context.closePath(); - let textMetrics = sdkCounterRequest.context.measureText(maxCounterName); - sdkCounterRequest.context.globalAlpha = 0.8; - sdkCounterRequest.context.fillStyle = '#f0f0f0'; - sdkCounterRequest.context.fillRect(0, 5, textMetrics.width + 8, 18); - sdkCounterRequest.context.globalAlpha = 1; - sdkCounterRequest.context.fillStyle = '#333'; - sdkCounterRequest.context.textBaseline = 'middle'; - sdkCounterRequest.context.fillText(maxCounterName, 4, 5 + 9); - drawFlagLine( - sdkCounterRequest.context, - sdkCounterRequest.flagMoveInfo, - sdkCounterRequest.flagSelectedInfo, - sdkCounterRequest.startNS, - sdkCounterRequest.endNS, - sdkCounterRequest.totalNS, - sdkCounterRequest.frame, - sdkCounterRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: sdkCounterRequest.id, - type: sdkCounterRequest.type, - results: sdkCounterRequest.canvas ? undefined : filter, - hover: CounterStruct.hoverCounterStruct, - }); - } - counter( sdkCounterList: Array, sdkCounterFilters: Array, diff --git a/ide/src/trace/database/ui-worker/ProduceWorkerSdkSlice.ts b/ide/src/trace/database/ui-worker/ProduceWorkerSdkSlice.ts index f7abd77b40c5ba42620c77b86f1315047546af7f..d0e244c5367329ef4befd3ef02056451479571e0 100644 --- a/ide/src/trace/database/ui-worker/ProduceWorkerSdkSlice.ts +++ b/ide/src/trace/database/ui-worker/ProduceWorkerSdkSlice.ts @@ -26,7 +26,6 @@ import { drawSelection, } from './ProcedureWorkerCommon'; import { TraceRow } from '../../component/trace/base/TraceRow'; -import { CounterStruct } from './ProduceWorkerSdkCounter'; export class SdkSliceRender extends Render { renderMainThread( @@ -67,99 +66,6 @@ export class SdkSliceRender extends Render { req.context.closePath(); } - render(sdkSliceRequest: RequestMessage, sdkList: Array, filter: Array): void { - if (sdkSliceRequest.lazyRefresh) { - this.sdkSlice( - sdkList, - filter, - sdkSliceRequest.startNS, - sdkSliceRequest.endNS, - sdkSliceRequest.totalNS, - sdkSliceRequest.frame, - sdkSliceRequest.useCache || !sdkSliceRequest.range.refresh - ); - } else { - if (!sdkSliceRequest.useCache) { - this.sdkSlice( - sdkList, - filter, - sdkSliceRequest.startNS, - sdkSliceRequest.endNS, - sdkSliceRequest.totalNS, - sdkSliceRequest.frame, - false - ); - } - } - if (sdkSliceRequest.canvas) { - sdkSliceRequest.context.clearRect(0, 0, sdkSliceRequest.canvas.width, sdkSliceRequest.canvas.height); - let sdkSliceArr = filter; - if ( - sdkSliceArr.length > 0 && - !sdkSliceRequest.range.refresh && - !sdkSliceRequest.useCache && - sdkSliceRequest.lazyRefresh - ) { - drawLoading( - sdkSliceRequest.context, - sdkSliceRequest.startNS, - sdkSliceRequest.endNS, - sdkSliceRequest.totalNS, - sdkSliceRequest.frame, - sdkSliceArr[0].startNS, - sdkSliceArr[sdkSliceArr.length - 1].startNS + sdkSliceArr[sdkSliceArr.length - 1].dur - ); - } - sdkSliceRequest.context.beginPath(); - SdkSliceStruct.maxSdkSlice = sdkSliceRequest.params.maxSdkSlice; - SdkSliceStruct.maxSdkSliceName = sdkSliceRequest.params.maxSdkSliceName; - drawLines(sdkSliceRequest.context, sdkSliceRequest.xs, sdkSliceRequest.frame.height, sdkSliceRequest.lineColor); - SdkSliceStruct.hoverSdkSliceStruct = undefined; - if (sdkSliceRequest.isHover) { - for (let re of filter) { - if ( - re.frame && - sdkSliceRequest.hoverX >= re.frame.x && - sdkSliceRequest.hoverX <= re.frame.x + re.frame.width && - sdkSliceRequest.hoverY >= re.frame.y && - sdkSliceRequest.hoverY <= re.frame.y + re.frame.height - ) { - SdkSliceStruct.hoverSdkSliceStruct = re; - break; - } - } - } - SdkSliceStruct.selectSdkSliceStruct = sdkSliceRequest.params.selectSdkSliceStruct; - for (let re of filter) { - SdkSliceStruct.draw(sdkSliceRequest.context, re); - } - drawSelection(sdkSliceRequest.context, sdkSliceRequest.params); - sdkSliceRequest.context.closePath(); - sdkSliceRequest.context.globalAlpha = 0.8; - sdkSliceRequest.context.fillStyle = '#f0f0f0'; - sdkSliceRequest.context.globalAlpha = 1; - sdkSliceRequest.context.fillStyle = '#333'; - sdkSliceRequest.context.textBaseline = 'middle'; - drawFlagLine( - sdkSliceRequest.context, - sdkSliceRequest.flagMoveInfo, - sdkSliceRequest.flagSelectedInfo, - sdkSliceRequest.startNS, - sdkSliceRequest.endNS, - sdkSliceRequest.totalNS, - sdkSliceRequest.frame, - sdkSliceRequest.slicesTime - ); - } - // @ts-ignore - self.postMessage({ - id: sdkSliceRequest.id, - type: sdkSliceRequest.type, - results: sdkSliceRequest.canvas ? undefined : filter, - hover: SdkSliceStruct.hoverSdkSliceStruct, - }); - } - sdkSlice( sdkList: Array, sdkSliceFilters: Array, diff --git a/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCPU.ts b/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCPU.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8d4af1c2d4e9dd33e3fd50615183edab8ca56b3 --- /dev/null +++ b/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCPU.ts @@ -0,0 +1,457 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { + BaseStruct, + dataFilterHandler, + drawFlagLine, + drawLines, + drawLoading, + drawLoadingFrame, + drawSelection, + drawWakeUp, + drawWakeUpList, + Render, + RequestMessage, +} from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { SpSystemTrace } from '../../../component/SpSystemTrace'; + +export class EmptyRender extends Render { + renderMainThread(req: any, row: TraceRow): void { + drawLoadingFrame(req.context, [], row); + } + render(cpuReqMessage: RequestMessage, list: Array, filter: Array): void { + if (cpuReqMessage.canvas) { + cpuReqMessage.context.clearRect(0, 0, cpuReqMessage.frame.width, cpuReqMessage.frame.height); + cpuReqMessage.context.beginPath(); + drawLines(cpuReqMessage.context, cpuReqMessage.xs, cpuReqMessage.frame.height, cpuReqMessage.lineColor); + drawSelection(cpuReqMessage.context, cpuReqMessage.params); + cpuReqMessage.context.closePath(); + drawFlagLine( + cpuReqMessage.context, + cpuReqMessage.flagMoveInfo, + cpuReqMessage.flagSelectedInfo, + cpuReqMessage.startNS, + cpuReqMessage.endNS, + cpuReqMessage.totalNS, + cpuReqMessage.frame, + cpuReqMessage.slicesTime + ); + } + // @ts-ignore + self.postMessage({ + id: cpuReqMessage.id, + type: cpuReqMessage.type, + results: cpuReqMessage.canvas ? undefined : filter, + hover: null, + }); + } +} + +export class CpuRender { + renderMainThread( + req: { + ctx: CanvasRenderingContext2D; + useCache: boolean; + type: string; + translateY: number; + }, + row: TraceRow + ) { + let cpuList = row.dataList; + let cpuFilter = row.dataListCache; + dataFilterHandler(cpuList, cpuFilter, { + startKey: 'startTime', + durKey: 'dur', + startNS: TraceRow.range?.startNS ?? 0, + endNS: TraceRow.range?.endNS ?? 0, + totalNS: TraceRow.range?.totalNS ?? 0, + frame: row.frame, + paddingTop: 5, + useCache: req.useCache || !(TraceRow.range?.refresh ?? false), + }); + drawLoadingFrame(req.ctx, cpuFilter, row); + req.ctx.beginPath(); + req.ctx.font = '11px sans-serif'; + cpuFilter.forEach((re) => { + re.translateY = req.translateY; + CpuStruct.draw(req.ctx, re, req.translateY); + }); + req.ctx.closePath(); + let currentCpu = parseInt(req.type!.replace('cpu-data-', '')); + drawWakeUp( + req.ctx, + CpuStruct.wakeupBean, + TraceRow.range!.startNS, + TraceRow.range!.endNS, + TraceRow.range!.totalNS, + row.frame, + req.type == `cpu-data-${CpuStruct.selectCpuStruct?.cpu || 0}` ? CpuStruct.selectCpuStruct : undefined, + currentCpu, + true + ); + for (let i = 0; i < SpSystemTrace.wakeupList.length; i++) { + if (i + 1 == SpSystemTrace.wakeupList.length) { + return; + } + drawWakeUpList( + req.ctx, + SpSystemTrace.wakeupList[i + 1], + TraceRow.range!.startNS, + TraceRow.range!.endNS, + TraceRow.range!.totalNS, + row.frame, + req.type == `cpu-data-${SpSystemTrace.wakeupList[i]?.cpu || 0}` ? SpSystemTrace.wakeupList[i] : undefined, + currentCpu, + true + ); + } + } + + render(cpuReq: RequestMessage, list: Array, filter: Array, translateY: number) { + if (cpuReq.lazyRefresh) { + this.cpu( + list, + filter, + cpuReq.startNS, + cpuReq.endNS, + cpuReq.totalNS, + cpuReq.frame, + cpuReq.useCache || !cpuReq.range.refresh + ); + } else { + if (!cpuReq.useCache) { + this.cpu(list, filter, cpuReq.startNS, cpuReq.endNS, cpuReq.totalNS, cpuReq.frame, false); + } + } + if (cpuReq.canvas) { + cpuReq.context.clearRect(0, 0, cpuReq.frame.width, cpuReq.frame.height); + let arr = filter; + if (arr.length > 0 && !cpuReq.range.refresh && !cpuReq.useCache && cpuReq.lazyRefresh) { + drawLoading( + cpuReq.context, + cpuReq.startNS, + cpuReq.endNS, + cpuReq.totalNS, + cpuReq.frame, + arr[0].startTime, + arr[arr.length - 1].startTime + arr[arr.length - 1].dur + ); + } + cpuReq.context.beginPath(); + drawLines(cpuReq.context, cpuReq.xs, cpuReq.frame.height, cpuReq.lineColor); + CpuStruct.hoverCpuStruct = undefined; + if (cpuReq.isHover) { + for (let re of filter) { + if ( + re.frame && + cpuReq.hoverX >= re.frame.x && + cpuReq.hoverX <= re.frame.x + re.frame.width && + cpuReq.hoverY >= re.frame.y && + cpuReq.hoverY <= re.frame.y + re.frame.height + ) { + CpuStruct.hoverCpuStruct = re; + break; + } + } + } else { + CpuStruct.hoverCpuStruct = cpuReq.params.hoverCpuStruct; + } + CpuStruct.selectCpuStruct = cpuReq.params.selectCpuStruct; + cpuReq.context.font = '11px sans-serif'; + for (let re of filter) { + CpuStruct.draw(cpuReq.context, re, translateY); + } + drawSelection(cpuReq.context, cpuReq.params); + cpuReq.context.closePath(); + drawFlagLine( + cpuReq.context, + cpuReq.flagMoveInfo, + cpuReq.flagSelectedInfo, + cpuReq.startNS, + cpuReq.endNS, + cpuReq.totalNS, + cpuReq.frame, + cpuReq.slicesTime + ); + } + // @ts-ignore + self.postMessage({ + id: cpuReq.id, + type: cpuReq.type, + results: cpuReq.canvas ? undefined : filter, + hover: CpuStruct.hoverCpuStruct, + }); + } + + cpu( + cpuList: Array, + cpuRes: Array, + startNS: number, + endNS: number, + totalNS: number, + frame: any, + use: boolean + ): void { + if (use && cpuRes.length > 0) { + let pns = (endNS - startNS) / frame.width; + let y = frame.y + 5; + let height = frame.height - 10; + for (let i = 0, len = cpuRes.length; i < len; i++) { + let it = cpuRes[i]; + if ((it.startTime || 0) + (it.dur || 0) > startNS && (it.startTime || 0) < endNS) { + if (!cpuRes[i].frame) { + cpuRes[i].frame = {}; + cpuRes[i].frame.y = y; + cpuRes[i].frame.height = height; + } + CpuStruct.setCpuFrame(cpuRes[i], pns, startNS, endNS, frame); + } else { + cpuRes[i].frame = null; + } + } + return; + } + if (cpuList) { + cpuRes.length = 0; + let pns = (endNS - startNS) / frame.width; //每个像素多少ns + let y = frame.y + 5; + let height = frame.height - 10; + let left = 0, + right = 0; + for (let i = 0, j = cpuList.length - 1, ib = true, jb = true; i < cpuList.length, j >= 0; i++, j--) { + if (cpuList[j].startTime <= endNS && jb) { + right = j; + jb = false; + } + if (cpuList[i].startTime + cpuList[i].dur >= startNS && ib) { + left = i; + ib = false; + } + if (!ib && !jb) { + break; + } + } + let slice = cpuList.slice(left, right + 1); + let sum = 0; + for (let i = 0; i < slice.length; i++) { + if (!slice[i].frame) { + slice[i].frame = {}; + slice[i].frame.y = y; + slice[i].frame.height = height; + } + if (slice[i].dur >= pns) { + slice[i].v = true; + CpuStruct.setCpuFrame(slice[i], pns, startNS, endNS, frame); + } else { + if (i > 0) { + let c = slice[i].startTime - slice[i - 1].startTime - slice[i - 1].dur; + if (c < pns && sum < pns) { + sum += c + slice[i - 1].dur; + slice[i].v = false; + } else { + slice[i].v = true; + CpuStruct.setCpuFrame(slice[i], pns, startNS, endNS, frame); + sum = 0; + } + } + } + } + cpuRes.push(...slice.filter((it) => it.v)); + } + } +} + +export class CpuStruct extends BaseStruct { + static cpuCount: number = 1; //最大cpu数量 + static hoverCpuStruct: CpuStruct | undefined; + static selectCpuStruct: CpuStruct | undefined; + static wakeupBean: WakeupBean | null | undefined = null; + cpu: number | undefined; + dur: number | undefined; + end_state: string | undefined; + state: string | undefined; + id: number | undefined; + tid: number | undefined; + name: string | undefined; + priority: number | undefined; + processCmdLine: string | undefined; + processId: number | undefined; + processName: string | undefined; + displayProcess: string | undefined; + displayThread: string | undefined; + measurePWidth: number = 0; + measureTWidth: number = 0; + startTime: number | undefined; + argSetID: number | undefined; + type: string | undefined; + v: boolean = false; + nofinish: boolean = false; + ts: number | undefined; + itid: number | undefined; + process: string | undefined; + pid: number | undefined; + thread: string | undefined; + isKeyPath?: number; + + static draw(ctx: CanvasRenderingContext2D, data: CpuStruct, translateY: number): void { + if (data.frame) { + let width = data.frame.width || 0; + if (data.tid === CpuStruct.hoverCpuStruct?.tid || !CpuStruct.hoverCpuStruct) { + ctx.globalAlpha = 1; + ctx.fillStyle = ColorUtils.colorForTid((data.processId || 0) > 0 ? data.processId || 0 : data.tid || 0); + } else if (data.processId === CpuStruct.hoverCpuStruct?.processId) { + ctx.globalAlpha = 0.6; + ctx.fillStyle = ColorUtils.colorForTid((data.processId || 0) > 0 ? data.processId || 0 : data.tid || 0); + } else { + ctx.globalAlpha = 1; + ctx.fillStyle = '#e0e0e0'; + } + ctx.fillRect(data.frame.x, data.frame.y, width, data.frame.height); + ctx.globalAlpha = 1; + let textFillWidth = width - textPadding * 2; + if (textFillWidth > 3) { + if (data.displayProcess === undefined) { + data.displayProcess = `${data.processName || 'Process'} [${data.processId}]`; + data.measurePWidth = ctx.measureText(data.displayProcess).width; + } + if (data.displayThread === undefined) { + data.displayThread = `${data.name || 'Thread'} [${data.tid}] [Prio:${data.priority || 0}]`; + data.measureTWidth = ctx.measureText(data.displayThread).width; + } + let processCharWidth = Math.round(data.measurePWidth / data.displayProcess.length); + let threadCharWidth = Math.round(data.measureTWidth / data.displayThread.length); + ctx.fillStyle = ColorUtils.funcTextColor( + ColorUtils.colorForTid((data.processId || 0) > 0 ? data.processId || 0 : data.tid || 0) + ); + let y = data.frame.height / 2 + data.frame.y; + if (data.measurePWidth < textFillWidth) { + let x1 = Math.floor(width / 2 - data.measurePWidth / 2 + data.frame.x + textPadding); + ctx.textBaseline = 'bottom'; + ctx.fillText(data.displayProcess, x1, y, textFillWidth); + } else { + if (textFillWidth >= processCharWidth) { + let chatNum = textFillWidth / processCharWidth; + let x1 = data.frame.x + textPadding; + ctx.textBaseline = 'bottom'; + if (chatNum < 2) { + ctx.fillText(data.displayProcess.substring(0, 1), x1, y, textFillWidth); + } else { + ctx.fillText(data.displayProcess.substring(0, chatNum - 1) + '...', x1, y, textFillWidth); + } + } + } + ctx.fillStyle = ColorUtils.funcTextColor( + ColorUtils.colorForTid((data.processId || 0) > 0 ? data.processId || 0 : data.tid || 0) + ); + ctx.font = '9px sans-serif'; + if (data.measureTWidth < textFillWidth) { + ctx.textBaseline = 'top'; + let x2 = Math.floor(width / 2 - data.measureTWidth / 2 + data.frame.x + textPadding); + ctx.fillText(data.displayThread, x2, y + 2, textFillWidth); + } else { + if (textFillWidth >= threadCharWidth) { + let chatNum = textFillWidth / threadCharWidth; + let x1 = data.frame.x + textPadding; + ctx.textBaseline = 'top'; + if (chatNum < 2) { + ctx.fillText(data.displayThread.substring(0, 1), x1, y + 2, textFillWidth); + } else { + ctx.fillText(data.displayThread.substring(0, chatNum - 1) + '...', x1, y + 2, textFillWidth); + } + } + } + } + if (data.nofinish && width > 4) { + ctx.fillStyle = '#fff'; + let ruptureWidth = 4; + let ruptureNode = 8; + ctx.moveTo(data.frame.x + data.frame.width - 1, data.frame.y); + for (let i = 1; i <= ruptureNode; i++) { + ctx.lineTo( + data.frame.x + data.frame.width - 1 - (i % 2 == 0 ? 0 : ruptureWidth), + data.frame.y + (data.frame.height / ruptureNode) * i + ); + } + ctx.closePath(); + ctx.fill(); + } + if (data.isKeyPath) { + const gradient = ctx.createLinearGradient(0, 0, 0, 40); + gradient.addColorStop(0, '#000000'); + gradient.addColorStop(0.5, '#0000FF'); + gradient.addColorStop(1, '#FF0000'); + ctx.strokeStyle = gradient; + ctx.lineWidth = 4; + ctx.strokeRect(data.frame.x, data.frame.y - 2, width - 2, data.frame.height + 2); + } + if (CpuStruct.selectCpuStruct && CpuStruct.equals(CpuStruct.selectCpuStruct, data)) { + ctx.strokeStyle = '#232c5d'; + ctx.lineWidth = 2; + ctx.strokeRect(data.frame.x, data.frame.y, width - 2, data.frame.height); + } + } + } + + static setCpuFrame(cpuNode: any, pns: number, startNS: number, endNS: number, frame: any): void { + if ((cpuNode.startTime || 0) < startNS) { + cpuNode.frame.x = 0; + } else { + cpuNode.frame.x = Math.floor(((cpuNode.startTime || 0) - startNS) / pns); + } + if ((cpuNode.startTime || 0) + (cpuNode.dur || 0) > endNS) { + cpuNode.frame.width = frame.width - cpuNode.frame.x; + } else { + cpuNode.frame.width = Math.ceil( + ((cpuNode.startTime || 0) + (cpuNode.dur || 0) - startNS) / pns - cpuNode.frame.x + ); + } + if (cpuNode.frame.width < 1) { + cpuNode.frame.width = 1; + } + } + + static equals(d1: CpuStruct, d2: CpuStruct): boolean { + return ( + d1 && + d2 && + d1.cpu === d2.cpu && + d1.tid === d2.tid && + d1.processId === d2.processId && + d1.startTime === d2.startTime && + d1.dur === d2.dur + ); + } +} + +export class WakeupBean { + wakeupTime: number | undefined; + cpu: number | undefined; + process: string | undefined; + pid: number | undefined; + thread: string | undefined; + dur: number | null | undefined; + tid: number | undefined; + schedulingLatency: number | undefined; + ts: number | undefined; + schedulingDesc: string | undefined; + itid: number | undefined; + state: string | undefined; + argSetID: number | undefined; +} + +const textPadding = 2; diff --git a/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits.ts b/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4d55d8a9c7db659f1b8a64c5c690a07049a7acd --- /dev/null +++ b/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCpuFreqLimits.ts @@ -0,0 +1,180 @@ +/* + * 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 { + BaseStruct, + dataFilterHandler, + drawLoading, + isFrameContainPoint, + ns2x, + drawLines, + Render, + drawFlagLine, + RequestMessage, + drawSelection, drawLoadingFrame, +} from '../ProcedureWorkerCommon'; +import { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { convertJSON } from '../../logic-worker/ProcedureLogicWorkerCommon'; + +export class CpuFreqLimitRender extends Render { + renderMainThread( + cpuFreqLimitReq: { + useCache: boolean; + context: CanvasRenderingContext2D; + cpu: number; + type: string; + maxFreq: number; + maxFreqName: string; + }, + row: TraceRow + ) { + let list = row.dataList; + let filter = row.dataListCache; + dataFilterHandler(list, filter, { + startKey: 'startNs', + durKey: 'dur', + startNS: TraceRow.range?.startNS ?? 0, + endNS: TraceRow.range?.endNS ?? 0, + totalNS: TraceRow.range?.totalNS ?? 0, + frame: row.frame, + paddingTop: 5, + useCache: cpuFreqLimitReq.useCache || !(TraceRow.range?.refresh ?? false), + }); + drawLoadingFrame(cpuFreqLimitReq.context, filter, row); + cpuFreqLimitReq.context.beginPath(); + let maxFreq = cpuFreqLimitReq.maxFreq; + let maxFreqName = cpuFreqLimitReq.maxFreqName; + if (row.isHover) { + for (let re of filter) { + if (re.frame && isFrameContainPoint(re.frame, row.hoverX, row.hoverY)) { + CpuFreqLimitsStruct.hoverCpuFreqLimitsStruct = re; + break; + } + } + } + for (let re of filter) { + CpuFreqLimitsStruct.draw(cpuFreqLimitReq.context, re, maxFreq); + } + cpuFreqLimitReq.context.closePath(); + let s = maxFreqName; + let textMetrics = cpuFreqLimitReq.context.measureText(s); + cpuFreqLimitReq.context.globalAlpha = 0.8; + cpuFreqLimitReq.context.fillStyle = '#f0f0f0'; + cpuFreqLimitReq.context.fillRect(0, 5, textMetrics.width + 8, 18); + cpuFreqLimitReq.context.globalAlpha = 1; + cpuFreqLimitReq.context.fillStyle = '#333'; + cpuFreqLimitReq.context.textBaseline = 'middle'; + cpuFreqLimitReq.context.fillText(s, 4, 5 + 9); + } +} + +export class CpuFreqLimitsStruct extends BaseStruct { + static hoverCpuFreqLimitsStruct: CpuFreqLimitsStruct | undefined; + static selectCpuFreqLimitsStruct: CpuFreqLimitsStruct | undefined; + static minAlpha = 0.4; + static maxAlpha = 0.8; + startNs: number | undefined; + dur: number = 0; + max: number | undefined; + min: number | undefined; + cpu: number = 0; + + static draw(ctx: CanvasRenderingContext2D, data: CpuFreqLimitsStruct, maxFreq: number) { + if (data.frame) { + let width = data.frame.width || 0; + let drawMaxHeight: number = Math.floor(((data.max || 0) * (data.frame.height || 0)) / maxFreq); + let drawMinHeight: number = Math.floor(((data.min || 0) * (data.frame.height || 0)) / maxFreq); + let index = data.cpu || 0; + index += 2; + ctx.fillStyle = ColorUtils.colorForTid(index); + ctx.strokeStyle = ColorUtils.colorForTid(index); + if ( + data === CpuFreqLimitsStruct.hoverCpuFreqLimitsStruct || + data === CpuFreqLimitsStruct.selectCpuFreqLimitsStruct + ) { + ctx.lineWidth = 1; + ctx.globalAlpha = this.minAlpha; + this.drawArcLine(ctx, data, drawMaxHeight, drawMaxHeight - drawMinHeight); + ctx.globalAlpha = this.maxAlpha; + this.drawArcLine(ctx, data, drawMinHeight, drawMinHeight); + } else { + ctx.globalAlpha = this.minAlpha; + ctx.lineWidth = 1; + ctx.fillRect( + data.frame.x, + data.frame.y + data.frame.height - drawMaxHeight, + width, + drawMaxHeight - drawMinHeight + ); + ctx.globalAlpha = this.maxAlpha; + ctx.fillRect(data.frame.x, data.frame.y + data.frame.height - drawMinHeight, width, drawMinHeight); + } + } + ctx.globalAlpha = 1.0; + ctx.lineWidth = 1; + } + + static drawArcLine( + ctx: CanvasRenderingContext2D, + data: CpuFreqLimitsStruct, + yStartHeight: number, + drawHeight: number + ) { + if (data.frame) { + let width = data.frame.width || 0; + ctx.fillRect(data.frame.x, data.frame.y + data.frame.height - yStartHeight, width, drawHeight); + ctx.globalAlpha = this.maxAlpha; + ctx.beginPath(); + ctx.arc(data.frame.x, data.frame.y + data.frame.height - yStartHeight, 3, 0, 2 * Math.PI, true); + ctx.fill(); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(data.frame.x + 3, data.frame.y + data.frame.height - yStartHeight); + ctx.lineWidth = 3; + ctx.lineTo(data.frame.x + width, data.frame.y + data.frame.height - yStartHeight); + ctx.stroke(); + } + } + + static setFreqLimitFrame( + freqLimitNode: any, + padding: number, + startNS: number, + endNS: number, + totalNS: number, + frame: any + ) { + let x1: number, x2: number; + if ((freqLimitNode.startNs || 0) < startNS) { + x1 = 0; + } else { + x1 = ns2x(freqLimitNode.startNs || 0, startNS, endNS, totalNS, frame); + } + if ((freqLimitNode.startNs || 0) + (freqLimitNode.dur || 0) > endNS) { + x2 = frame.width; + } else { + x2 = ns2x((freqLimitNode.startNs || 0) + (freqLimitNode.dur || 0), startNS, endNS, totalNS, frame); + } + let cpuFreqLimitsGetV: number = x2 - x1 <= 1 ? 1 : x2 - x1; + if (!freqLimitNode.frame) { + freqLimitNode.frame = {}; + } + freqLimitNode.frame.x = Math.floor(x1); + freqLimitNode.frame.y = frame.y + padding; + freqLimitNode.frame.width = Math.ceil(cpuFreqLimitsGetV); + freqLimitNode.frame.height = Math.floor(frame.height - padding * 2); + } +} diff --git a/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCpuState.ts b/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCpuState.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7ac406b46ff0521d567141d62ebc6de00b41cdb --- /dev/null +++ b/ide/src/trace/database/ui-worker/cpu/ProcedureWorkerCpuState.ts @@ -0,0 +1,244 @@ +/* + * 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 { + BaseStruct, + dataFilterHandler, + drawFlagLine, + drawLines, + drawLoading, + drawLoadingFrame, + drawSelection, + drawWakeUp, + ns2x, + PerfRender, + Render, + RequestMessage, +} from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { convertJSON } from '../../logic-worker/ProcedureLogicWorkerCommon'; + +export class CpuStateRender extends PerfRender { + renderMainThread( + req: { + useCache: boolean; + cpuStateContext: CanvasRenderingContext2D; + type: string; + cpu: number; + }, + cpuStateRow: TraceRow + ): void { + let list = cpuStateRow.dataList; + let filter = cpuStateRow.dataListCache; + dataFilterHandler(list, filter, { + startKey: 'startTs', + durKey: 'dur', + startNS: TraceRow.range?.startNS ?? 0, + endNS: TraceRow.range?.endNS ?? 0, + totalNS: TraceRow.range?.totalNS ?? 0, + frame: cpuStateRow.frame, + paddingTop: 5, + useCache: req.useCache || !(TraceRow.range?.refresh ?? false), + }); + drawLoadingFrame(req.cpuStateContext, filter, cpuStateRow); + let path = new Path2D(); + let find = false; + let offset = 3; + let heights = [4, 12, 21, 30]; + for (let re of filter) { + re.height = heights[(re as any).value]; + CpuStateStruct.draw(req.cpuStateContext, path, re); + if (cpuStateRow.isHover) { + if ( + re.frame && + cpuStateRow.hoverX >= re.frame.x - offset && + cpuStateRow.hoverX <= re.frame.x + re.frame.width + offset + ) { + CpuStateStruct.hoverStateStruct = re; + find = true; + } + } + } + if (!find && cpuStateRow.isHover) { + CpuStateStruct.hoverStateStruct = undefined; + } + req.cpuStateContext.fill(path); + } + + render(cpuStateReq: RequestMessage, list: Array, filter: Array, dataList2: Array) {} + + setFrameByArr(cpuStateRes: any[], startNS: number, endNS: number, totalNS: number, frame: any, arr2: any[]) { + let list: any[] = arr2; + cpuStateRes.length = 0; + let pns = (endNS - startNS) / frame.width; + let y = frame.y + 5; + let frameHeight = frame.height - 10; + let left = 0, + right = 0; + for (let i = 0, j = list.length - 1, ib = true, jb = true; i < list.length, j >= 0; i++, j--) { + if (list[j].startTs <= endNS && jb) { + right = j; + jb = false; + } + if (list[i].startTs + list[i].dur >= startNS && ib) { + left = i; + ib = false; + } + if (!ib && !jb) { + break; + } + } + let slice = list.slice(left, right + 1); + let sum = 0; + for (let i = 0; i < slice.length; i++) { + if (!slice[i].frame) { + slice[i].frame = {}; + slice[i].frame.y = y; + slice[i].frame.height = frameHeight; + } + if (slice[i].dur >= pns) { + slice[i].v = true; + CpuStateStruct.setFrame(slice[i], 5, startNS, endNS, totalNS, frame); + } else { + if (i > 0) { + let c = slice[i].startTs - slice[i - 1].startTs - slice[i - 1].dur; + if (c < pns && sum < pns) { + sum += c + slice[i - 1].dur; + slice[i].v = false; + } else { + slice[i].v = true; + CpuStateStruct.setFrame(slice[i], 5, startNS, endNS, totalNS, frame); + sum = 0; + } + } + } + } + cpuStateRes.push(...slice.filter((it) => it.v)); + } + + setFrameByFilter(cpuStateRes: any[], startNS: number, endNS: number, totalNS: number, frame: any) { + for (let i = 0, len = cpuStateRes.length; i < len; i++) { + if ( + (cpuStateRes[i].startTs || 0) + (cpuStateRes[i].dur || 0) >= startNS && + (cpuStateRes[i].startTs || 0) <= endNS + ) { + CpuStateStruct.setFrame(cpuStateRes[i], 5, startNS, endNS, totalNS, frame); + } else { + cpuStateRes[i].frame = null; + } + } + } + + cpuState( + arr: any[], + arr2: any[], + type: string, + cpuStateRes: any[], + cpu: number, + startNS: number, + endNS: number, + totalNS: number, + frame: any, + use: boolean + ) { + if (use && cpuStateRes.length > 0) { + this.setFrameByFilter(cpuStateRes, startNS, endNS, totalNS, frame); + return; + } + cpuStateRes.length = 0; + if (arr) { + this.setFrameByArr(cpuStateRes, startNS, endNS, totalNS, frame, arr2); + } + } +} + +export class CpuStateStruct extends BaseStruct { + static hoverStateStruct: CpuStateStruct | undefined; + static selectStateStruct: CpuStateStruct | undefined; + dur: number | undefined; + value: string | undefined; + startTs: number | undefined; + height: number | undefined; + cpu: number | undefined; + + static draw(ctx: CanvasRenderingContext2D, path: Path2D, data: CpuStateStruct) { + if (data.frame) { + let chartColor = ColorUtils.colorForTid(data.cpu!); + ctx.font = '11px sans-serif'; + ctx.fillStyle = chartColor; + ctx.strokeStyle = chartColor; + ctx.globalAlpha = 0.6; + if (data === CpuStateStruct.hoverStateStruct || data === CpuStateStruct.selectStateStruct) { + path.rect(data.frame.x, 35 - (data.height || 0), data.frame.width, data.height || 0); + ctx.lineWidth = 1; + ctx.globalAlpha = 1.0; + ctx.beginPath(); + ctx.arc(data.frame.x, 35 - (data.height || 0), 3, 0, 2 * Math.PI, true); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(data.frame.x + 3, 35 - (data.height || 0)); + ctx.lineWidth = 3; + ctx.lineTo(data.frame.x + data.frame.width, 35 - (data.height || 0)); + ctx.stroke(); + ctx.lineWidth = 1; + ctx.globalAlpha = 0.6; + ctx.fillRect(data.frame.x, 35 - (data.height || 0), data.frame.width, data.height || 0); + } else { + ctx.globalAlpha = 0.6; + ctx.fillRect(data.frame.x, 35 - (data.height || 0), data.frame.width, data.height || 0); + } + } + } + + static setCpuFrame(cpuStateNode: any, pns: number, startNS: number, endNS: number, frame: any) { + if ((cpuStateNode.startTime || 0) < startNS) { + cpuStateNode.frame.x = 0; + } else { + cpuStateNode.frame.x = Math.floor(((cpuStateNode.startTs || 0) - startNS) / pns); + } + if ((cpuStateNode.startTime || 0) + (cpuStateNode.dur || 0) > endNS) { + cpuStateNode.frame.width = frame.width - cpuStateNode.frame.x; + } else { + cpuStateNode.frame.width = Math.ceil( + ((cpuStateNode.startTs || 0) + (cpuStateNode.dur || 0) - startNS) / pns - cpuStateNode.frame.x + ); + } + if (cpuStateNode.frame.width < 1) { + cpuStateNode.frame.width = 1; + } + } + static setFrame(cpuStateNode: any, padding: number, startNS: number, endNS: number, totalNS: number, frame: any) { + let x1: number, x2: number; + if ((cpuStateNode.startTs || 0) < startNS) { + x1 = 0; + } else { + x1 = ns2x(cpuStateNode.startTs || 0, startNS, endNS, totalNS, frame); + } + if ((cpuStateNode.startTs || 0) + (cpuStateNode.dur || 0) > endNS) { + x2 = frame.width; + } else { + x2 = ns2x((cpuStateNode.startTs || 0) + (cpuStateNode.dur || 0), startNS, endNS, totalNS, frame); + } + let cpuStateGetV: number = x2 - x1 <= 1 ? 1 : x2 - x1; + if (!cpuStateNode.frame) { + cpuStateNode.frame = {}; + } + cpuStateNode.frame.x = Math.ceil(x1); + cpuStateNode.frame.y = frame.y + padding; + cpuStateNode.frame.width = Math.floor(cpuStateGetV); + cpuStateNode.frame.height = cpuStateNode.height; + } +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU.ts new file mode 100644 index 0000000000000000000000000000000000000000..2dfbe956f102e978934c04d6617347e869c8570d --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU.ts @@ -0,0 +1,80 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { HiPerfStruct, hiPerf, PerfRender, RequestMessage } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfCpuRender extends PerfRender { + renderMainThread(req: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = req.scale > 30_000_000; + if (list && row.dataList2.length == 0) { + let drawType = row.drawType; + let usage = row.drawType === -2; + let event = drawType; + row.dataList2 = HiPerfCpuStruct.groupBy10MS(list, req.intervalPerf, req.maxCpu, usage, event); + } + hiPerf( + groupBy10MS || row.drawType === -2 || row.drawType === -1 + ? list + : list.filter((it) => it.event_type_id === row.drawType), + row.dataList2, + filter, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + row.frame, + groupBy10MS, + req.useCache || (TraceRow.range?.refresh ?? false) + ); + req.context.beginPath(); + req.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + req.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let find = false; + let offset = groupBy10MS ? 0 : 3; + for (let re of filter) { + if ( + row.isHover && + re.frame && + row.hoverX >= re.frame.x - offset && + row.hoverX <= re.frame.x + re.frame.width + offset + ) { + HiPerfCpuStruct.hoverStruct = re; + find = true; + } + HiPerfCpuStruct.draw(req.context, normalPath, specPath, re, groupBy10MS); + } + if (!find && row.isHover) HiPerfCpuStruct.hoverStruct = undefined; + if (groupBy10MS) { + req.context.fill(normalPath); + } else { + req.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(req.context, specPath); + } + req.context.closePath(); + } + + render(hiPerfCpuRequest: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +export class HiPerfCpuStruct extends HiPerfStruct { + static hoverStruct: HiPerfCpuStruct | undefined; + static selectStruct: HiPerfCpuStruct | undefined; + + cpu: number | undefined; +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU2.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU2.ts new file mode 100644 index 0000000000000000000000000000000000000000..e007711490e0bc0161550b95931ac8ab64c3a1b1 --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCPU2.ts @@ -0,0 +1,69 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { HiPerfStruct, hiPerf, PerfRender, RequestMessage, hiPerf2, drawLoadingFrame } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfCpuRender2 extends PerfRender { + renderMainThread(req: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = req.scale > 30_000_000; + let textMetrics; + if (!groupBy10MS) { + req.context.font = 'normal 12px Arial'; + textMetrics = req.context.measureText('🄿'); + } + hiPerf2(filter, TraceRow.range?.startNS ?? 0, TraceRow.range?.endNS ?? 0, row.frame); + drawLoadingFrame(req.context, filter, row); + req.context.beginPath(); + req.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + req.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + // let specPath = new Path2D(); + let find = false; + let offset = groupBy10MS ? 0 : 3; + for (let re of filter) { + if ( + row.isHover && + re.frame && + row.hoverX >= re.frame.x - offset && + row.hoverX <= re.frame.x + re.frame.width + offset + ) { + HiPerfCpuStruct.hoverStruct = re; + find = true; + } + HiPerfCpuStruct.draw(req.context, normalPath, normalPath, re, groupBy10MS, textMetrics); + } + if (!find && row.isHover) HiPerfCpuStruct.hoverStruct = undefined; + if (groupBy10MS) { + req.context.fill(normalPath); + } else { + req.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(req.context, normalPath); + } + req.context.closePath(); + } + + render(hiPerfCpuRequest: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +export class HiPerfCpuStruct extends HiPerfStruct { + static hoverStruct: HiPerfCpuStruct | undefined; + static selectStruct: HiPerfCpuStruct | undefined; + + cpu: number | undefined; +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCallChart.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCallChart.ts new file mode 100644 index 0000000000000000000000000000000000000000..c8c0425aa4b3a10a0eb17e0fe6dde4f9132cccc7 --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfCallChart.ts @@ -0,0 +1,205 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { + BaseStruct, + type Rect, + ns2x, + drawString, + Render, + isFrameContainPoint, + drawLoadingFrame, +} from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; +import { HiPerfChartFrame } from '../../../bean/PerfStruct'; + +export class HiPerfCallChartRender extends Render { + renderMainThread(req: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + hiperf( + list, + filter, + TraceRow.range!.startNS, + TraceRow.range!.endNS, + TraceRow.range!.totalNS, + row.frame, + req.useCache || !TraceRow.range!.refresh, + row.funcExpand + ); + drawLoadingFrame(req.context, filter, row); + req.context.beginPath(); + let find = false; + let offset = 5; + for (let re of filter) { + HiPerfCallChartStruct.draw(req.context, re); + if (row.isHover) { + if ( + re.endTime - re.startTime === 0 || + re.endTime - re.startTime == null || + re.endTime - re.startTime === undefined + ) { + if ( + re.frame && + row.hoverX >= re.frame.x - offset && + row.hoverX <= re.frame.x + re.frame.width + offset && + row.hoverY >= re.frame.y && + row.hoverY <= re.frame.y + re.frame.height + ) { + HiPerfCallChartStruct.hoverPerfCallCutStruct = re; + find = true; + } + } else { + if (re.frame && isFrameContainPoint(re.frame, row.hoverX, row.hoverY)) { + HiPerfCallChartStruct.hoverPerfCallCutStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfCallChartStruct.hoverPerfCallCutStruct = undefined; + } + } + req.context.closePath(); + } +} + +// 火焰图数据模板 +let padding = 1; +export class HiPerfCallChartStruct extends BaseStruct { + static selectStruct: HiPerfCallChartStruct | undefined; + static hoverPerfCallCutStruct: HiPerfCallChartStruct | undefined; + id: number = 0; + name: string = ''; + startTime: number = 0; + endTime: number = 0; + eventCount: number = 0; + depth: number = 0; + fileId: number = 0; + symbolId: number = 0; + children!: Array; + isSelect: boolean = false; + totalTime: number = 0; + callchain_id: number = 0; + selfDur: number = 0; + + static setPerfFrame(hiPerfNode: any, startNS: number, endNS: number, totalNS: number, frame: Rect): void { + let x1: number, x2: number; + if ((hiPerfNode.startTime || 0) > startNS && (hiPerfNode.startTime || 0) < endNS) { + x1 = ns2x(hiPerfNode.startTime || 0, startNS, endNS, totalNS, frame); + } else { + x1 = 0; + } + if ( + (hiPerfNode.startTime || 0) + (hiPerfNode.totalTime || 0) > startNS && + (hiPerfNode.startTime || 0) + (hiPerfNode.totalTime || 0) < endNS + ) { + x2 = ns2x((hiPerfNode.startTime || 0) + (hiPerfNode.totalTime || 0), startNS, endNS, totalNS, frame); + } else { + x2 = frame.width; + } + if (!hiPerfNode.frame) { + hiPerfNode.frame = {}; + } + let getV: number = x2 - x1 < 1 ? 1 : x2 - x1; + hiPerfNode.frame.x = Math.floor(x1); + hiPerfNode.frame.y = hiPerfNode.depth * 20; + hiPerfNode.frame.width = Math.ceil(getV); + hiPerfNode.frame.height = 20; + } + + static draw(ctx: CanvasRenderingContext2D, data: HiPerfCallChartStruct): void { + if (data.frame) { + if (data.endTime - data.startTime === undefined || data.endTime - data.startTime === null) { + } else { + ctx.globalAlpha = 1; + if (data.name === '(program)') { + ctx.fillStyle = '#ccc'; + } else if (data.name === '(idle)') { + ctx.fillStyle = '#f0f0f0'; + } else { + ctx.fillStyle = ColorUtils.FUNC_COLOR[ColorUtils.hashFunc(data.name || '', 0, ColorUtils.FUNC_COLOR.length)]; + } + let miniHeight = 20; + if (HiPerfCallChartStruct.hoverPerfCallCutStruct && data === HiPerfCallChartStruct.hoverPerfCallCutStruct) { + ctx.globalAlpha = 0.7; + } + ctx.fillRect(data.frame.x, data.frame.y, data.frame.width, miniHeight - padding * 2); + if (data.frame.width > 8) { + ctx.lineWidth = 1; + ctx.fillStyle = '#fff'; + ctx.textBaseline = 'middle'; + drawString(ctx, `${data.name || ''}`, 4, data.frame, data); + } + if (data === HiPerfCallChartStruct.selectStruct) { + ctx.strokeStyle = '#000'; + ctx.lineWidth = 2; + ctx.strokeRect(data.frame.x + 1, data.frame.y + 1, data.frame.width - 2, miniHeight - padding * 2 - 2); + } + } + } + } +} + +export function hiperf( + list: Array, + filter: Array, + startNS: number, + endNS: number, + totalNS: number, + frame: Rect, + use: boolean, + expand: boolean +): void { + if (use && filter.length > 0) { + for (let i = 0, len = filter.length; i < len; i++) { + if ( + filter[i].totalTime > 0 && + (filter[i].startTime || 0) + (filter[i].totalTime || 0) >= startNS && + (filter[i].startTime || 0) <= endNS + ) { + HiPerfCallChartStruct.setPerfFrame(filter[i], startNS, endNS, totalNS, frame); + } else { + filter[i].frame = null; + } + } + return; + } + filter.length = 0; + if (list) { + let groups = list + .filter( + (it) => + it.totalTime > 0 && + (it.startTime ?? 0) + (it.totalTime ?? 0) >= startNS && + (it.startTime ?? 0) <= endNS && + ((!expand && it.depth === 0) || expand) + ) + .map((it) => { + HiPerfCallChartStruct.setPerfFrame(it, startNS, endNS, totalNS, frame); + return it; + }) + .reduce((pre, current) => { + (pre[`${current.frame.x}-${current.depth}`] = pre[`${current.frame.x}-${current.depth}`] || []).push(current); + return pre; + }, {}); + Reflect.ownKeys(groups).map((kv) => { + // 从小到大排序 + let arr = groups[kv].sort((a: HiPerfChartFrame, b: HiPerfChartFrame) => b.totalTime - a.totalTime); + filter.push(arr[0]); + }); + } +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfEvent.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfEvent.ts new file mode 100644 index 0000000000000000000000000000000000000000..9acc579d8d56f6a2c3d5f9bd63f92b80e420801a --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfEvent.ts @@ -0,0 +1,132 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { hiPerf, HiPerfStruct, PerfRender, RequestMessage } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfEventRender extends PerfRender { + renderMainThread(hiPerfEventReq: any, row: TraceRow): void { + let list = row.dataList; + let list2 = row.dataList2; + let filter = row.dataListCache; + let groupBy10MS = hiPerfEventReq.scale > 30_000_000; + if (list && row.dataList2.length === 0) { + row.dataList2 = HiPerfEventStruct.eventGroupBy10MS(list, hiPerfEventReq.intervalPerf, hiPerfEventReq.type); + } + hiPerf( + list, + list2, + filter, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + row.frame, + groupBy10MS, + hiPerfEventReq.useCache || (TraceRow.range?.refresh ?? false) + ); + drawHiPerfEvent(hiPerfEventReq, groupBy10MS, filter, row); + } + + render(hiPerfEventRequest: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +function drawHiPerfEvent( + hiPerfEventReq: any, + groupBy10MS: boolean, + filter: HiPerfEventStruct[], + row: TraceRow +) { + hiPerfEventReq.context.beginPath(); + hiPerfEventReq.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + hiPerfEventReq.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let offset = groupBy10MS ? 0 : 3; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let find = false; + for (let re of filter) { + HiPerfEventStruct.draw(hiPerfEventReq.context, normalPath, specPath, re, groupBy10MS); + if (row.isHover) { + if (re.frame && row.hoverX >= re.frame.x - offset && row.hoverX <= re.frame.x + re.frame.width + offset) { + HiPerfEventStruct.hoverStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfEventStruct.hoverStruct = undefined; + } + if (groupBy10MS) { + hiPerfEventReq.context.fill(normalPath); + } else { + hiPerfEventReq.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(hiPerfEventReq.context, specPath); + } + let maxEvent = HiPerfEventStruct.maxEvent!.get(hiPerfEventReq.type!) || 0; + let textMetrics = hiPerfEventReq.context.measureText(maxEvent); + hiPerfEventReq.context.globalAlpha = 0.8; + hiPerfEventReq.context.fillStyle = '#f0f0f0'; + hiPerfEventReq.context.fillRect(0, 5, textMetrics.width + 8, 18); + hiPerfEventReq.context.globalAlpha = 1; + hiPerfEventReq.context.fillStyle = '#333'; + hiPerfEventReq.context.textBaseline = 'middle'; + hiPerfEventReq.context.fillText(maxEvent, 4, 5 + 9); + hiPerfEventReq.context.stroke(); + hiPerfEventReq.context.closePath(); +} + +export class HiPerfEventStruct extends HiPerfStruct { + static hoverStruct: HiPerfEventStruct | undefined; + static selectStruct: HiPerfEventStruct | undefined; + + static maxEvent: Map | undefined = new Map(); + sum: number | undefined; + max: number | undefined; + + static eventGroupBy10MS(array: Array, intervalPerf: number, type: string): Array { + let obj = array + .map((hiPerfDataItem) => { + hiPerfDataItem.timestamp_group = Math.trunc(hiPerfDataItem.startNS / 1_000_000_0) * 1_000_000_0; + return hiPerfDataItem; + }) + .reduce((pre, current) => { + (pre[current['timestamp_group']] = pre[current['timestamp_group']] || []).push(current); + return pre; + }, {}); + let eventArr: any[] = []; + let max = 0; + for (let aKey in obj) { + let sum = obj[aKey].reduce((pre: any, cur: any) => { + return pre + cur.event_count; + }, 0); + if (sum > max) max = sum; + let ns = parseInt(aKey); + eventArr.push({ + startNS: ns, + dur: 1_000_000_0, + height: 0, + sum: sum, + }); + } + if (typeof HiPerfEventStruct.maxEvent!.get(type) === 'undefined') { + HiPerfEventStruct.maxEvent!.set(type, max); + } + eventArr.map((it) => { + it.height = Math.floor((40 * it.sum) / max); + it.max = max; + return it; + }); + return eventArr; + } +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess.ts new file mode 100644 index 0000000000000000000000000000000000000000..32604b8905df4a8087e8beb662359d6b425e1a45 --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess.ts @@ -0,0 +1,77 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { hiPerf, HiPerfStruct, PerfRender, RequestMessage } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfProcessRender extends PerfRender { + renderMainThread(hiPerfProcessReq: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = hiPerfProcessReq.scale > 30_000_000; + if (list && row.dataList2.length === 0) { + let drawType = row.drawType; + let usage = row.drawType === -2; + let event = drawType; + row.dataList2 = HiPerfProcessStruct.groupBy10MS(list, hiPerfProcessReq.intervalPerf, undefined, usage, event); + } + hiPerf( + groupBy10MS || row.drawType === -2 || row.drawType === -1 + ? list + : list.filter((it) => it.event_type_id === row.drawType), + row.dataList2, + filter, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + row.frame, + groupBy10MS, + hiPerfProcessReq.useCache || (TraceRow.range?.refresh ?? false) + ); + hiPerfProcessReq.context.beginPath(); + hiPerfProcessReq.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + hiPerfProcessReq.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let offset = groupBy10MS ? 0 : 3; + let find = false; + for (let re of filter) { + HiPerfProcessStruct.draw(hiPerfProcessReq.context, normalPath, specPath, re, groupBy10MS); + if (row.isHover) { + if (re.frame && row.hoverX >= re.frame.x - offset && row.hoverX <= re.frame.x + re.frame.width + offset) { + HiPerfProcessStruct.hoverStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfProcessStruct.hoverStruct = undefined; + } + if (groupBy10MS) { + hiPerfProcessReq.context.fill(normalPath); + } else { + hiPerfProcessReq.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(hiPerfProcessReq.context, specPath); + } + hiPerfProcessReq.context.closePath(); + } + + render(hiPerfProcessRequest: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +export class HiPerfProcessStruct extends HiPerfStruct { + static hoverStruct: HiPerfProcessStruct | undefined; + static selectStruct: HiPerfProcessStruct | undefined; +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess2.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess2.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c1479e4ee31213d0072b741d77ddc0f09ce95cb --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfProcess2.ts @@ -0,0 +1,66 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { drawLoadingFrame, hiPerf, hiPerf2, HiPerfStruct, PerfRender, RequestMessage } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfProcessRender2 extends PerfRender { + renderMainThread(req: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = req.scale > 30_000_000; + let textMetrics; + if (!groupBy10MS) { + req.context.font = 'normal 12px Arial'; + textMetrics = req.context.measureText('🄿'); + } + hiPerf2(filter, TraceRow.range?.startNS ?? 0, TraceRow.range?.endNS ?? 0, row.frame); + drawLoadingFrame(req.context, filter, row); + req.context.beginPath(); + req.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + req.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let offset = groupBy10MS ? 0 : 3; + let find = false; + for (let re of filter) { + HiPerfProcessStruct.draw(req.context, normalPath, specPath, re, groupBy10MS, textMetrics); + if (row.isHover) { + if (re.frame && row.hoverX >= re.frame.x - offset && row.hoverX <= re.frame.x + re.frame.width + offset) { + HiPerfProcessStruct.hoverStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfProcessStruct.hoverStruct = undefined; + } + if (groupBy10MS) { + req.context.fill(normalPath); + } else { + req.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(req.context, specPath); + } + req.context.closePath(); + } + + render(hiPerfProcessRequest: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +export class HiPerfProcessStruct extends HiPerfStruct { + static hoverStruct: HiPerfProcessStruct | undefined; + static selectStruct: HiPerfProcessStruct | undefined; +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfReport.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfReport.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bc24248485dd515d302af65220018f829d06a33 --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfReport.ts @@ -0,0 +1,194 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { HiPerfStruct, PerfRender, type RequestMessage } from '../ProcedureWorkerCommon'; + +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfReportRender extends PerfRender { + renderMainThread(hiPerfReportReq: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = hiPerfReportReq.scale > 30_000_000; + if (list && row.dataList2.length === 0) { + row.dataList2 = HiPerfReportStruct.reportGroupBy10MS(list, hiPerfReportReq.intervalPerf); + } + HiPerfReport( + list, + row.dataList2, + hiPerfReportReq.type!, + filter, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + TraceRow.range?.totalNS ?? 0, + row.frame, + groupBy10MS, + hiPerfReportReq.intervalPerf, + hiPerfReportReq.useCache || (TraceRow.range?.refresh ?? false) + ); + hiPerfReportReq.context.beginPath(); + hiPerfReportReq.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + hiPerfReportReq.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let offset = groupBy10MS ? 0 : 3; + let find = false; + for (let re of filter) { + HiPerfReportStruct.draw(hiPerfReportReq.context, normalPath, specPath, re, groupBy10MS); + if (row.isHover) { + if (re.frame && row.hoverX >= re.frame.x - offset && row.hoverX <= re.frame.x + re.frame.width + offset) { + HiPerfReportStruct.hoverStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfReportStruct.hoverStruct = undefined; + } + if (groupBy10MS) { + hiPerfReportReq.context.fill(normalPath); + } else { + hiPerfReportReq.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(hiPerfReportReq.context, specPath); + } + hiPerfReportReq.context.closePath(); + } + + render(hiPerfReportRequest: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +function setFrameByfilter(startNS: number, endNS: number, frame: any, hiPerfFilters: Array): void { + let pns = (endNS - startNS) / frame.width; + let y = frame.y; + for (let i = 0; i < hiPerfFilters.length; i++) { + let hiPerfData = hiPerfFilters[i]; + if ((hiPerfData.startNS || 0) + (hiPerfData.dur || 0) > startNS && (hiPerfData.startNS || 0) < endNS) { + if (!hiPerfData.frame) { + hiPerfData.frame = {}; + hiPerfData.frame.y = y; + } + hiPerfData.frame.height = hiPerfData.height; + HiPerfReportStruct.setFrame(hiPerfData, pns, startNS, endNS, frame); + } else { + hiPerfData.frame = null; + } + } +} + +function setFrameByArr( + groupBy10MS: boolean, + arr2: any, + arr: Array, + hiPerfFilters: Array, + startNS: number, + endNS: number, + frame: any +): void { + let list: Array = groupBy10MS ? arr2 : arr; + let pns = (endNS - startNS) / frame.width; + let y = frame.y; + list + .filter((it) => (it.startNS || 0) + (it.dur || 0) > startNS && (it.startNS || 0) < endNS) + .map((it) => { + if (!it.frame) { + it.frame = {}; + it.frame.y = y; + } + it.frame.height = it.height; + HiPerfReportStruct.setFrame(it, pns, startNS, endNS, frame); + return it; + }) + .reduce((pre, current, index, arr) => { + if (!pre[`${current.frame.x}`]) { + pre[`${current.frame.x}`] = []; + pre[`${current.frame.x}`].push(current); + if (groupBy10MS) { + hiPerfFilters.push(current); + } else { + if (hiPerfFilters.length === 0) { + hiPerfFilters.push(current); + } + if ( + hiPerfFilters[hiPerfFilters.length - 1] && + Math.abs(current.frame.x - hiPerfFilters[hiPerfFilters.length - 1].frame.x) > 4 + ) { + hiPerfFilters.push(current); + } + } + } + return pre; + }, {}); +} + +export function HiPerfReport( + arr: Array, + arr2: any, + type: string, + hiPerfFilters: Array, + startNS: number, + endNS: number, + totalNS: number, + frame: any, + groupBy10MS: boolean, + intervalPerf: number, + use: boolean +): void { + if (use && hiPerfFilters.length > 0) { + setFrameByfilter(endNS, startNS, frame, hiPerfFilters); + return; + } + hiPerfFilters.length = 0; + if (arr) { + setFrameByArr(groupBy10MS, arr2, arr, hiPerfFilters, startNS, endNS, frame); + } +} + +export class HiPerfReportStruct extends HiPerfStruct { + static hoverStruct: HiPerfReportStruct | undefined; + static selectStruct: HiPerfReportStruct | undefined; + + static reportGroupBy10MS(array: Array, intervalPerf: number): Array { + let obj = array + .map((it) => { + it.timestamp_group = Math.trunc(it.startNS / 1_000_000_0) * 1_000_000_0; + return it; + }) + .reduce((pre, current) => { + (pre[current['timestamp_group']] = pre[current['timestamp_group']] || []).push(current); + return pre; + }, {}); + let reportArr: any[] = []; + let max = 0; + for (let aKey in obj) { + let sum = obj[aKey].reduce((pre: any, cur: any) => { + return pre + cur.event_count; + }, 0); + if (sum > max) max = sum; + let ns = parseInt(aKey); + reportArr.push({ + startNS: ns, + dur: 1_000_000_0, + height: 0, + sum: sum, + }); + } + reportArr.map((it) => { + it.height = Math.floor((40 * it.sum) / max); + return it; + }); + return reportArr; + } +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfThread.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfThread.ts new file mode 100644 index 0000000000000000000000000000000000000000..e313515c594b63b0f4d36edea194f44113697564 --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfThread.ts @@ -0,0 +1,77 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { hiPerf, HiPerfStruct, PerfRender, RequestMessage } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfThreadRender extends PerfRender { + renderMainThread(hiPerfThreadReq: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = hiPerfThreadReq.scale > 30_000_000; + if (list && row.dataList2.length === 0) { + let drawType = row.drawType; + let usage = row.drawType === -2; + let event = drawType; + row.dataList2 = HiPerfThreadStruct.groupBy10MS(list, hiPerfThreadReq.intervalPerf, undefined, usage, event); + } + hiPerf( + groupBy10MS || row.drawType === -2 || row.drawType === -1 + ? list + : list.filter((it) => it.event_type_id === row.drawType), + row.dataList2, + filter, + TraceRow.range?.startNS ?? 0, + TraceRow.range?.endNS ?? 0, + row.frame, + groupBy10MS, + hiPerfThreadReq.useCache || (TraceRow.range?.refresh ?? false) + ); + hiPerfThreadReq.context.beginPath(); + hiPerfThreadReq.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + hiPerfThreadReq.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let offset = groupBy10MS ? 0 : 3; + let find = false; + for (let re of filter) { + HiPerfThreadStruct.draw(hiPerfThreadReq.context, normalPath, specPath, re, groupBy10MS); + if (row.isHover) { + if (re.frame && row.hoverX >= re.frame.x - offset && row.hoverX <= re.frame.x + re.frame.width + offset) { + HiPerfThreadStruct.hoverStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfThreadStruct.hoverStruct = undefined; + } + if (groupBy10MS) { + hiPerfThreadReq.context.fill(normalPath); + } else { + hiPerfThreadReq.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(hiPerfThreadReq.context, specPath); + } + hiPerfThreadReq.context.closePath(); + } + + render(req: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +export class HiPerfThreadStruct extends HiPerfStruct { + static hoverStruct: HiPerfThreadStruct | undefined; + static selectStruct: HiPerfThreadStruct | undefined; +} diff --git a/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfThread2.ts b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfThread2.ts new file mode 100644 index 0000000000000000000000000000000000000000..8512a51b5e875962a1eb58b61e619f1bee3e8fc8 --- /dev/null +++ b/ide/src/trace/database/ui-worker/hiperf/ProcedureWorkerHiPerfThread2.ts @@ -0,0 +1,66 @@ +/* + * 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 { ColorUtils } from '../../../component/trace/base/ColorUtils'; +import { drawLoadingFrame, hiPerf, hiPerf2, HiPerfStruct, PerfRender, RequestMessage } from '../ProcedureWorkerCommon'; +import { TraceRow } from '../../../component/trace/base/TraceRow'; + +export class HiperfThreadRender2 extends PerfRender { + renderMainThread(req: any, row: TraceRow): void { + let list = row.dataList; + let filter = row.dataListCache; + let groupBy10MS = req.scale > 30_000_000; + let textMetrics; + if (!groupBy10MS) { + req.context.font = 'normal 12px Arial'; + textMetrics = req.context.measureText('🄿'); + } + hiPerf2(filter, TraceRow.range?.startNS ?? 0, TraceRow.range?.endNS ?? 0, row.frame); + drawLoadingFrame(req.context, filter, row); + req.context.beginPath(); + req.context.fillStyle = ColorUtils.FUNC_COLOR[0]; + req.context.strokeStyle = ColorUtils.FUNC_COLOR[0]; + let normalPath = new Path2D(); + let specPath = new Path2D(); + let offset = groupBy10MS ? 0 : 3; + let find = false; + for (let re of filter) { + HiPerfThreadStruct.draw(req.context, normalPath, specPath, re, groupBy10MS, textMetrics); + if (row.isHover) { + if (re.frame && row.hoverX >= re.frame.x - offset && row.hoverX <= re.frame.x + re.frame.width + offset) { + HiPerfThreadStruct.hoverStruct = re; + find = true; + } + } + } + if (!find && row.isHover) { + HiPerfThreadStruct.hoverStruct = undefined; + } + if (groupBy10MS) { + req.context.fill(normalPath); + } else { + req.context.stroke(normalPath); + HiPerfStruct.drawSpecialPath(req.context, specPath); + } + req.context.closePath(); + } + + render(req: RequestMessage, list: Array, filter: Array, dataList2: Array): void {} +} + +export class HiPerfThreadStruct extends HiPerfStruct { + static hoverStruct: HiPerfThreadStruct | undefined; + static selectStruct: HiPerfThreadStruct | undefined; +} diff --git a/ide/src/trace/proto/SphBaseData.js b/ide/src/trace/proto/SphBaseData.js deleted file mode 100644 index 6bdf65b4eacb60cd47ec467b4aead186f6399aa1..0000000000000000000000000000000000000000 --- a/ide/src/trace/proto/SphBaseData.js +++ /dev/null @@ -1,14053 +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. - -/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ -"use strict"; - -var $protobuf = require("protobufjs/minimal"); - -// Common aliases -var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); - -$root.SphCpuData = (function () { - - /** - * Properties of a SphCpuData. - * @exports ISphCpuData - * @interface ISphCpuData - * @property {number|null} [processId] SphCpuData processId - * @property {number|null} [cpu] SphCpuData cpu - * @property {number|null} [tid] SphCpuData tid - * @property {number|null} [id] SphCpuData id - * @property {number|Long|null} [dur] SphCpuData dur - * @property {number|Long|null} [startTime] SphCpuData startTime - */ - - /** - * Constructs a new SphCpuData. - * @exports SphCpuData - * @classdesc Represents a SphCpuData. - * @implements ISphCpuData - * @constructor - * @param {ISphCpuData=} [properties] Properties to set - */ - function SphCpuData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphCpuData processId. - * @member {number} processId - * @memberof SphCpuData - * @instance - */ - SphCpuData.prototype.processId = 0; - - /** - * SphCpuData cpu. - * @member {number} cpu - * @memberof SphCpuData - * @instance - */ - SphCpuData.prototype.cpu = 0; - - /** - * SphCpuData tid. - * @member {number} tid - * @memberof SphCpuData - * @instance - */ - SphCpuData.prototype.tid = 0; - - /** - * SphCpuData id. - * @member {number} id - * @memberof SphCpuData - * @instance - */ - SphCpuData.prototype.id = 0; - - /** - * SphCpuData dur. - * @member {number|Long} dur - * @memberof SphCpuData - * @instance - */ - SphCpuData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuData startTime. - * @member {number|Long} startTime - * @memberof SphCpuData - * @instance - */ - SphCpuData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphCpuData instance using the specified properties. - * @function create - * @memberof SphCpuData - * @static - * @param {ISphCpuData=} [properties] Properties to set - * @returns {SphCpuData} SphCpuData instance - */ - SphCpuData.create = function create(properties) { - return new SphCpuData(properties); - }; - - /** - * Encodes the specified SphCpuData message. Does not implicitly {@link SphCpuData.verify|verify} messages. - * @function encode - * @memberof SphCpuData - * @static - * @param {ISphCpuData} message SphCpuData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.processId != null && Object.hasOwnProperty.call(message, "processId")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.processId); - if (message.cpu != null && Object.hasOwnProperty.call(message, "cpu")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.cpu); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.tid); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.id); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.dur); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.startTime); - return writer; - }; - - /** - * Encodes the specified SphCpuData message, length delimited. Does not implicitly {@link SphCpuData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphCpuData - * @static - * @param {ISphCpuData} message SphCpuData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphCpuData message from the specified reader or buffer. - * @function decode - * @memberof SphCpuData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphCpuData} SphCpuData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphCpuData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.processId = reader.int32(); - break; - } - case 2: { - message.cpu = reader.int32(); - break; - } - case 3: { - message.tid = reader.int32(); - break; - } - case 4: { - message.id = reader.int32(); - break; - } - case 5: { - message.dur = reader.int64(); - break; - } - case 6: { - message.startTime = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphCpuData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphCpuData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphCpuData} SphCpuData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphCpuData message. - * @function verify - * @memberof SphCpuData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphCpuData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.processId != null && message.hasOwnProperty("processId")) - if (!$util.isInteger(message.processId)) - return "processId: integer expected"; - if (message.cpu != null && message.hasOwnProperty("cpu")) - if (!$util.isInteger(message.cpu)) - return "cpu: integer expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid)) - return "tid: integer expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - return null; - }; - - /** - * Creates a SphCpuData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphCpuData - * @static - * @param {Object.} object Plain object - * @returns {SphCpuData} SphCpuData - */ - SphCpuData.fromObject = function fromObject(object) { - if (object instanceof $root.SphCpuData) - return object; - var message = new $root.SphCpuData(); - if (object.processId != null) - message.processId = object.processId | 0; - if (object.cpu != null) - message.cpu = object.cpu | 0; - if (object.tid != null) - message.tid = object.tid | 0; - if (object.id != null) - message.id = object.id | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphCpuData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphCpuData - * @static - * @param {SphCpuData} message SphCpuData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphCpuData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.processId = 0; - object.cpu = 0; - object.tid = 0; - object.id = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - } - if (message.processId != null && message.hasOwnProperty("processId")) - object.processId = message.processId; - if (message.cpu != null && message.hasOwnProperty("cpu")) - object.cpu = message.cpu; - if (message.tid != null && message.hasOwnProperty("tid")) - object.tid = message.tid; - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - return object; - }; - - /** - * Converts this SphCpuData to JSON. - * @function toJSON - * @memberof SphCpuData - * @instance - * @returns {Object.} JSON object - */ - SphCpuData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphCpuData - * @function getTypeUrl - * @memberof SphCpuData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphCpuData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphCpuData"; - }; - - return SphCpuData; -})(); - -$root.SphCpuFreqData = (function () { - - /** - * Properties of a SphCpuFreqData. - * @exports ISphCpuFreqData - * @interface ISphCpuFreqData - * @property {number|null} [cpu] SphCpuFreqData cpu - * @property {number|null} [value] SphCpuFreqData value - * @property {number|Long|null} [dur] SphCpuFreqData dur - * @property {number|Long|null} [startNs] SphCpuFreqData startNs - */ - - /** - * Constructs a new SphCpuFreqData. - * @exports SphCpuFreqData - * @classdesc Represents a SphCpuFreqData. - * @implements ISphCpuFreqData - * @constructor - * @param {ISphCpuFreqData=} [properties] Properties to set - */ - function SphCpuFreqData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphCpuFreqData cpu. - * @member {number} cpu - * @memberof SphCpuFreqData - * @instance - */ - SphCpuFreqData.prototype.cpu = 0; - - /** - * SphCpuFreqData value. - * @member {number} value - * @memberof SphCpuFreqData - * @instance - */ - SphCpuFreqData.prototype.value = 0; - - /** - * SphCpuFreqData dur. - * @member {number|Long} dur - * @memberof SphCpuFreqData - * @instance - */ - SphCpuFreqData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuFreqData startNs. - * @member {number|Long} startNs - * @memberof SphCpuFreqData - * @instance - */ - SphCpuFreqData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphCpuFreqData instance using the specified properties. - * @function create - * @memberof SphCpuFreqData - * @static - * @param {ISphCpuFreqData=} [properties] Properties to set - * @returns {SphCpuFreqData} SphCpuFreqData instance - */ - SphCpuFreqData.create = function create(properties) { - return new SphCpuFreqData(properties); - }; - - /** - * Encodes the specified SphCpuFreqData message. Does not implicitly {@link SphCpuFreqData.verify|verify} messages. - * @function encode - * @memberof SphCpuFreqData - * @static - * @param {ISphCpuFreqData} message SphCpuFreqData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuFreqData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.cpu != null && Object.hasOwnProperty.call(message, "cpu")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.cpu); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.value); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.dur); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.startNs); - return writer; - }; - - /** - * Encodes the specified SphCpuFreqData message, length delimited. Does not implicitly {@link SphCpuFreqData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphCpuFreqData - * @static - * @param {ISphCpuFreqData} message SphCpuFreqData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuFreqData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphCpuFreqData message from the specified reader or buffer. - * @function decode - * @memberof SphCpuFreqData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphCpuFreqData} SphCpuFreqData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuFreqData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphCpuFreqData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.cpu = reader.int32(); - break; - } - case 2: { - message.value = reader.int32(); - break; - } - case 3: { - message.dur = reader.int64(); - break; - } - case 4: { - message.startNs = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphCpuFreqData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphCpuFreqData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphCpuFreqData} SphCpuFreqData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuFreqData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphCpuFreqData message. - * @function verify - * @memberof SphCpuFreqData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphCpuFreqData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.cpu != null && message.hasOwnProperty("cpu")) - if (!$util.isInteger(message.cpu)) - return "cpu: integer expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - return null; - }; - - /** - * Creates a SphCpuFreqData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphCpuFreqData - * @static - * @param {Object.} object Plain object - * @returns {SphCpuFreqData} SphCpuFreqData - */ - SphCpuFreqData.fromObject = function fromObject(object) { - if (object instanceof $root.SphCpuFreqData) - return object; - var message = new $root.SphCpuFreqData(); - if (object.cpu != null) - message.cpu = object.cpu | 0; - if (object.value != null) - message.value = object.value | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphCpuFreqData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphCpuFreqData - * @static - * @param {SphCpuFreqData} message SphCpuFreqData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphCpuFreqData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.cpu = 0; - object.value = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - } - if (message.cpu != null && message.hasOwnProperty("cpu")) - object.cpu = message.cpu; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - return object; - }; - - /** - * Converts this SphCpuFreqData to JSON. - * @function toJSON - * @memberof SphCpuFreqData - * @instance - * @returns {Object.} JSON object - */ - SphCpuFreqData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphCpuFreqData - * @function getTypeUrl - * @memberof SphCpuFreqData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphCpuFreqData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphCpuFreqData"; - }; - - return SphCpuFreqData; -})(); - -$root.SphProcessData = (function () { - - /** - * Properties of a SphProcessData. - * @exports ISphProcessData - * @interface ISphProcessData - * @property {number|null} [cpu] SphProcessData cpu - * @property {number|Long|null} [dur] SphProcessData dur - * @property {number|Long|null} [startTime] SphProcessData startTime - */ - - /** - * Constructs a new SphProcessData. - * @exports SphProcessData - * @classdesc Represents a SphProcessData. - * @implements ISphProcessData - * @constructor - * @param {ISphProcessData=} [properties] Properties to set - */ - function SphProcessData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessData cpu. - * @member {number} cpu - * @memberof SphProcessData - * @instance - */ - SphProcessData.prototype.cpu = 0; - - /** - * SphProcessData dur. - * @member {number|Long} dur - * @memberof SphProcessData - * @instance - */ - SphProcessData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessData startTime. - * @member {number|Long} startTime - * @memberof SphProcessData - * @instance - */ - SphProcessData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphProcessData instance using the specified properties. - * @function create - * @memberof SphProcessData - * @static - * @param {ISphProcessData=} [properties] Properties to set - * @returns {SphProcessData} SphProcessData instance - */ - SphProcessData.create = function create(properties) { - return new SphProcessData(properties); - }; - - /** - * Encodes the specified SphProcessData message. Does not implicitly {@link SphProcessData.verify|verify} messages. - * @function encode - * @memberof SphProcessData - * @static - * @param {ISphProcessData} message SphProcessData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.cpu != null && Object.hasOwnProperty.call(message, "cpu")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.cpu); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startTime); - return writer; - }; - - /** - * Encodes the specified SphProcessData message, length delimited. Does not implicitly {@link SphProcessData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessData - * @static - * @param {ISphProcessData} message SphProcessData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessData} SphProcessData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.cpu = reader.int32(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.startTime = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessData} SphProcessData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessData message. - * @function verify - * @memberof SphProcessData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.cpu != null && message.hasOwnProperty("cpu")) - if (!$util.isInteger(message.cpu)) - return "cpu: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - return null; - }; - - /** - * Creates a SphProcessData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessData} SphProcessData - */ - SphProcessData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessData) - return object; - var message = new $root.SphProcessData(); - if (object.cpu != null) - message.cpu = object.cpu | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphProcessData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessData - * @static - * @param {SphProcessData} message SphProcessData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.cpu = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - } - if (message.cpu != null && message.hasOwnProperty("cpu")) - object.cpu = message.cpu; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - return object; - }; - - /** - * Converts this SphProcessData to JSON. - * @function toJSON - * @memberof SphProcessData - * @instance - * @returns {Object.} JSON object - */ - SphProcessData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessData - * @function getTypeUrl - * @memberof SphProcessData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessData"; - }; - - return SphProcessData; -})(); - -$root.SphCpuFreqLimitData = (function () { - - /** - * Properties of a SphCpuFreqLimitData. - * @exports ISphCpuFreqLimitData - * @interface ISphCpuFreqLimitData - * @property {number|null} [max] SphCpuFreqLimitData max - * @property {number|null} [min] SphCpuFreqLimitData min - * @property {number|null} [value] SphCpuFreqLimitData value - * @property {number|Long|null} [dur] SphCpuFreqLimitData dur - * @property {number|Long|null} [startNs] SphCpuFreqLimitData startNs - */ - - /** - * Constructs a new SphCpuFreqLimitData. - * @exports SphCpuFreqLimitData - * @classdesc Represents a SphCpuFreqLimitData. - * @implements ISphCpuFreqLimitData - * @constructor - * @param {ISphCpuFreqLimitData=} [properties] Properties to set - */ - function SphCpuFreqLimitData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphCpuFreqLimitData max. - * @member {number} max - * @memberof SphCpuFreqLimitData - * @instance - */ - SphCpuFreqLimitData.prototype.max = 0; - - /** - * SphCpuFreqLimitData min. - * @member {number} min - * @memberof SphCpuFreqLimitData - * @instance - */ - SphCpuFreqLimitData.prototype.min = 0; - - /** - * SphCpuFreqLimitData value. - * @member {number} value - * @memberof SphCpuFreqLimitData - * @instance - */ - SphCpuFreqLimitData.prototype.value = 0; - - /** - * SphCpuFreqLimitData dur. - * @member {number|Long} dur - * @memberof SphCpuFreqLimitData - * @instance - */ - SphCpuFreqLimitData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuFreqLimitData startNs. - * @member {number|Long} startNs - * @memberof SphCpuFreqLimitData - * @instance - */ - SphCpuFreqLimitData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphCpuFreqLimitData instance using the specified properties. - * @function create - * @memberof SphCpuFreqLimitData - * @static - * @param {ISphCpuFreqLimitData=} [properties] Properties to set - * @returns {SphCpuFreqLimitData} SphCpuFreqLimitData instance - */ - SphCpuFreqLimitData.create = function create(properties) { - return new SphCpuFreqLimitData(properties); - }; - - /** - * Encodes the specified SphCpuFreqLimitData message. Does not implicitly {@link SphCpuFreqLimitData.verify|verify} messages. - * @function encode - * @memberof SphCpuFreqLimitData - * @static - * @param {ISphCpuFreqLimitData} message SphCpuFreqLimitData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuFreqLimitData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.max != null && Object.hasOwnProperty.call(message, "max")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.max); - if (message.min != null && Object.hasOwnProperty.call(message, "min")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.min); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.value); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.dur); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.startNs); - return writer; - }; - - /** - * Encodes the specified SphCpuFreqLimitData message, length delimited. Does not implicitly {@link SphCpuFreqLimitData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphCpuFreqLimitData - * @static - * @param {ISphCpuFreqLimitData} message SphCpuFreqLimitData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuFreqLimitData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphCpuFreqLimitData message from the specified reader or buffer. - * @function decode - * @memberof SphCpuFreqLimitData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphCpuFreqLimitData} SphCpuFreqLimitData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuFreqLimitData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphCpuFreqLimitData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.max = reader.int32(); - break; - } - case 2: { - message.min = reader.int32(); - break; - } - case 3: { - message.value = reader.int32(); - break; - } - case 4: { - message.dur = reader.int64(); - break; - } - case 5: { - message.startNs = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphCpuFreqLimitData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphCpuFreqLimitData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphCpuFreqLimitData} SphCpuFreqLimitData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuFreqLimitData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphCpuFreqLimitData message. - * @function verify - * @memberof SphCpuFreqLimitData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphCpuFreqLimitData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.max != null && message.hasOwnProperty("max")) - if (!$util.isInteger(message.max)) - return "max: integer expected"; - if (message.min != null && message.hasOwnProperty("min")) - if (!$util.isInteger(message.min)) - return "min: integer expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - return null; - }; - - /** - * Creates a SphCpuFreqLimitData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphCpuFreqLimitData - * @static - * @param {Object.} object Plain object - * @returns {SphCpuFreqLimitData} SphCpuFreqLimitData - */ - SphCpuFreqLimitData.fromObject = function fromObject(object) { - if (object instanceof $root.SphCpuFreqLimitData) - return object; - var message = new $root.SphCpuFreqLimitData(); - if (object.max != null) - message.max = object.max | 0; - if (object.min != null) - message.min = object.min | 0; - if (object.value != null) - message.value = object.value | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphCpuFreqLimitData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphCpuFreqLimitData - * @static - * @param {SphCpuFreqLimitData} message SphCpuFreqLimitData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphCpuFreqLimitData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.max = 0; - object.min = 0; - object.value = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - } - if (message.max != null && message.hasOwnProperty("max")) - object.max = message.max; - if (message.min != null && message.hasOwnProperty("min")) - object.min = message.min; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - return object; - }; - - /** - * Converts this SphCpuFreqLimitData to JSON. - * @function toJSON - * @memberof SphCpuFreqLimitData - * @instance - * @returns {Object.} JSON object - */ - SphCpuFreqLimitData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphCpuFreqLimitData - * @function getTypeUrl - * @memberof SphCpuFreqLimitData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphCpuFreqLimitData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphCpuFreqLimitData"; - }; - - return SphCpuFreqLimitData; -})(); - -$root.SphCpuStateData = (function () { - - /** - * Properties of a SphCpuStateData. - * @exports ISphCpuStateData - * @interface ISphCpuStateData - * @property {number|null} [value] SphCpuStateData value - * @property {number|Long|null} [dur] SphCpuStateData dur - * @property {number|Long|null} [startTs] SphCpuStateData startTs - */ - - /** - * Constructs a new SphCpuStateData. - * @exports SphCpuStateData - * @classdesc Represents a SphCpuStateData. - * @implements ISphCpuStateData - * @constructor - * @param {ISphCpuStateData=} [properties] Properties to set - */ - function SphCpuStateData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphCpuStateData value. - * @member {number} value - * @memberof SphCpuStateData - * @instance - */ - SphCpuStateData.prototype.value = 0; - - /** - * SphCpuStateData dur. - * @member {number|Long} dur - * @memberof SphCpuStateData - * @instance - */ - SphCpuStateData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuStateData startTs. - * @member {number|Long} startTs - * @memberof SphCpuStateData - * @instance - */ - SphCpuStateData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphCpuStateData instance using the specified properties. - * @function create - * @memberof SphCpuStateData - * @static - * @param {ISphCpuStateData=} [properties] Properties to set - * @returns {SphCpuStateData} SphCpuStateData instance - */ - SphCpuStateData.create = function create(properties) { - return new SphCpuStateData(properties); - }; - - /** - * Encodes the specified SphCpuStateData message. Does not implicitly {@link SphCpuStateData.verify|verify} messages. - * @function encode - * @memberof SphCpuStateData - * @static - * @param {ISphCpuStateData} message SphCpuStateData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuStateData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.value); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startTs); - return writer; - }; - - /** - * Encodes the specified SphCpuStateData message, length delimited. Does not implicitly {@link SphCpuStateData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphCpuStateData - * @static - * @param {ISphCpuStateData} message SphCpuStateData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuStateData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphCpuStateData message from the specified reader or buffer. - * @function decode - * @memberof SphCpuStateData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphCpuStateData} SphCpuStateData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuStateData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphCpuStateData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.value = reader.int32(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.startTs = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphCpuStateData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphCpuStateData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphCpuStateData} SphCpuStateData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuStateData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphCpuStateData message. - * @function verify - * @memberof SphCpuStateData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphCpuStateData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - return null; - }; - - /** - * Creates a SphCpuStateData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphCpuStateData - * @static - * @param {Object.} object Plain object - * @returns {SphCpuStateData} SphCpuStateData - */ - SphCpuStateData.fromObject = function fromObject(object) { - if (object instanceof $root.SphCpuStateData) - return object; - var message = new $root.SphCpuStateData(); - if (object.value != null) - message.value = object.value | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphCpuStateData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphCpuStateData - * @static - * @param {SphCpuStateData} message SphCpuStateData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphCpuStateData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.value = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - } - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - return object; - }; - - /** - * Converts this SphCpuStateData to JSON. - * @function toJSON - * @memberof SphCpuStateData - * @instance - * @returns {Object.} JSON object - */ - SphCpuStateData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphCpuStateData - * @function getTypeUrl - * @memberof SphCpuStateData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphCpuStateData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphCpuStateData"; - }; - - return SphCpuStateData; -})(); - -$root.SphProcessMemData = (function () { - - /** - * Properties of a SphProcessMemData. - * @exports ISphProcessMemData - * @interface ISphProcessMemData - * @property {number|null} [trackId] SphProcessMemData trackId - * @property {number|null} [value] SphProcessMemData value - * @property {number|Long|null} [startTime] SphProcessMemData startTime - * @property {number|Long|null} [ts] SphProcessMemData ts - */ - - /** - * Constructs a new SphProcessMemData. - * @exports SphProcessMemData - * @classdesc Represents a SphProcessMemData. - * @implements ISphProcessMemData - * @constructor - * @param {ISphProcessMemData=} [properties] Properties to set - */ - function SphProcessMemData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessMemData trackId. - * @member {number} trackId - * @memberof SphProcessMemData - * @instance - */ - SphProcessMemData.prototype.trackId = 0; - - /** - * SphProcessMemData value. - * @member {number} value - * @memberof SphProcessMemData - * @instance - */ - SphProcessMemData.prototype.value = 0; - - /** - * SphProcessMemData startTime. - * @member {number|Long} startTime - * @memberof SphProcessMemData - * @instance - */ - SphProcessMemData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessMemData ts. - * @member {number|Long} ts - * @memberof SphProcessMemData - * @instance - */ - SphProcessMemData.prototype.ts = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphProcessMemData instance using the specified properties. - * @function create - * @memberof SphProcessMemData - * @static - * @param {ISphProcessMemData=} [properties] Properties to set - * @returns {SphProcessMemData} SphProcessMemData instance - */ - SphProcessMemData.create = function create(properties) { - return new SphProcessMemData(properties); - }; - - /** - * Encodes the specified SphProcessMemData message. Does not implicitly {@link SphProcessMemData.verify|verify} messages. - * @function encode - * @memberof SphProcessMemData - * @static - * @param {ISphProcessMemData} message SphProcessMemData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessMemData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.trackId != null && Object.hasOwnProperty.call(message, "trackId")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.trackId); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.value); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startTime); - if (message.ts != null && Object.hasOwnProperty.call(message, "ts")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.ts); - return writer; - }; - - /** - * Encodes the specified SphProcessMemData message, length delimited. Does not implicitly {@link SphProcessMemData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessMemData - * @static - * @param {ISphProcessMemData} message SphProcessMemData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessMemData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessMemData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessMemData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessMemData} SphProcessMemData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessMemData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessMemData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.trackId = reader.int32(); - break; - } - case 2: { - message.value = reader.int32(); - break; - } - case 3: { - message.startTime = reader.int64(); - break; - } - case 4: { - message.ts = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessMemData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessMemData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessMemData} SphProcessMemData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessMemData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessMemData message. - * @function verify - * @memberof SphProcessMemData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessMemData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.trackId != null && message.hasOwnProperty("trackId")) - if (!$util.isInteger(message.trackId)) - return "trackId: integer expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.ts != null && message.hasOwnProperty("ts")) - if (!$util.isInteger(message.ts) && !(message.ts && $util.isInteger(message.ts.low) && $util.isInteger(message.ts.high))) - return "ts: integer|Long expected"; - return null; - }; - - /** - * Creates a SphProcessMemData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessMemData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessMemData} SphProcessMemData - */ - SphProcessMemData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessMemData) - return object; - var message = new $root.SphProcessMemData(); - if (object.trackId != null) - message.trackId = object.trackId | 0; - if (object.value != null) - message.value = object.value | 0; - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.ts != null) - if ($util.Long) - (message.ts = $util.Long.fromValue(object.ts)).unsigned = false; - else if (typeof object.ts === "string") - message.ts = parseInt(object.ts, 10); - else if (typeof object.ts === "number") - message.ts = object.ts; - else if (typeof object.ts === "object") - message.ts = new $util.LongBits(object.ts.low >>> 0, object.ts.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphProcessMemData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessMemData - * @static - * @param {SphProcessMemData} message SphProcessMemData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessMemData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.trackId = 0; - object.value = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ts = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ts = options.longs === String ? "0" : 0; - } - if (message.trackId != null && message.hasOwnProperty("trackId")) - object.trackId = message.trackId; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.ts != null && message.hasOwnProperty("ts")) - if (typeof message.ts === "number") - object.ts = options.longs === String ? String(message.ts) : message.ts; - else - object.ts = options.longs === String ? $util.Long.prototype.toString.call(message.ts) : options.longs === Number ? new $util.LongBits(message.ts.low >>> 0, message.ts.high >>> 0).toNumber() : message.ts; - return object; - }; - - /** - * Converts this SphProcessMemData to JSON. - * @function toJSON - * @memberof SphProcessMemData - * @instance - * @returns {Object.} JSON object - */ - SphProcessMemData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessMemData - * @function getTypeUrl - * @memberof SphProcessMemData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessMemData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessMemData"; - }; - - return SphProcessMemData; -})(); - -$root.SphProcessSoInitData = (function () { - - /** - * Properties of a SphProcessSoInitData. - * @exports ISphProcessSoInitData - * @interface ISphProcessSoInitData - * @property {number|null} [depth] SphProcessSoInitData depth - * @property {number|null} [pid] SphProcessSoInitData pid - * @property {number|null} [tid] SphProcessSoInitData tid - * @property {number|null} [itid] SphProcessSoInitData itid - * @property {number|Long|null} [startTime] SphProcessSoInitData startTime - * @property {number|Long|null} [dur] SphProcessSoInitData dur - * @property {number|null} [id] SphProcessSoInitData id - */ - - /** - * Constructs a new SphProcessSoInitData. - * @exports SphProcessSoInitData - * @classdesc Represents a SphProcessSoInitData. - * @implements ISphProcessSoInitData - * @constructor - * @param {ISphProcessSoInitData=} [properties] Properties to set - */ - function SphProcessSoInitData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessSoInitData depth. - * @member {number} depth - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.depth = 0; - - /** - * SphProcessSoInitData pid. - * @member {number} pid - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.pid = 0; - - /** - * SphProcessSoInitData tid. - * @member {number} tid - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.tid = 0; - - /** - * SphProcessSoInitData itid. - * @member {number} itid - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.itid = 0; - - /** - * SphProcessSoInitData startTime. - * @member {number|Long} startTime - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessSoInitData dur. - * @member {number|Long} dur - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessSoInitData id. - * @member {number} id - * @memberof SphProcessSoInitData - * @instance - */ - SphProcessSoInitData.prototype.id = 0; - - /** - * Creates a new SphProcessSoInitData instance using the specified properties. - * @function create - * @memberof SphProcessSoInitData - * @static - * @param {ISphProcessSoInitData=} [properties] Properties to set - * @returns {SphProcessSoInitData} SphProcessSoInitData instance - */ - SphProcessSoInitData.create = function create(properties) { - return new SphProcessSoInitData(properties); - }; - - /** - * Encodes the specified SphProcessSoInitData message. Does not implicitly {@link SphProcessSoInitData.verify|verify} messages. - * @function encode - * @memberof SphProcessSoInitData - * @static - * @param {ISphProcessSoInitData} message SphProcessSoInitData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessSoInitData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.depth); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pid); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.tid); - if (message.itid != null && Object.hasOwnProperty.call(message, "itid")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.itid); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.startTime); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.dur); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 7, wireType 0 =*/56).int32(message.id); - return writer; - }; - - /** - * Encodes the specified SphProcessSoInitData message, length delimited. Does not implicitly {@link SphProcessSoInitData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessSoInitData - * @static - * @param {ISphProcessSoInitData} message SphProcessSoInitData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessSoInitData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessSoInitData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessSoInitData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessSoInitData} SphProcessSoInitData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessSoInitData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessSoInitData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.depth = reader.int32(); - break; - } - case 2: { - message.pid = reader.int32(); - break; - } - case 3: { - message.tid = reader.int32(); - break; - } - case 4: { - message.itid = reader.int32(); - break; - } - case 5: { - message.startTime = reader.int64(); - break; - } - case 6: { - message.dur = reader.int64(); - break; - } - case 7: { - message.id = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessSoInitData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessSoInitData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessSoInitData} SphProcessSoInitData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessSoInitData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessSoInitData message. - * @function verify - * @memberof SphProcessSoInitData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessSoInitData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid)) - return "tid: integer expected"; - if (message.itid != null && message.hasOwnProperty("itid")) - if (!$util.isInteger(message.itid)) - return "itid: integer expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - return null; - }; - - /** - * Creates a SphProcessSoInitData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessSoInitData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessSoInitData} SphProcessSoInitData - */ - SphProcessSoInitData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessSoInitData) - return object; - var message = new $root.SphProcessSoInitData(); - if (object.depth != null) - message.depth = object.depth | 0; - if (object.pid != null) - message.pid = object.pid | 0; - if (object.tid != null) - message.tid = object.tid | 0; - if (object.itid != null) - message.itid = object.itid | 0; - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.id != null) - message.id = object.id | 0; - return message; - }; - - /** - * Creates a plain object from a SphProcessSoInitData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessSoInitData - * @static - * @param {SphProcessSoInitData} message SphProcessSoInitData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessSoInitData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.depth = 0; - object.pid = 0; - object.tid = 0; - object.itid = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - object.id = 0; - } - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.tid != null && message.hasOwnProperty("tid")) - object.tid = message.tid; - if (message.itid != null && message.hasOwnProperty("itid")) - object.itid = message.itid; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - return object; - }; - - /** - * Converts this SphProcessSoInitData to JSON. - * @function toJSON - * @memberof SphProcessSoInitData - * @instance - * @returns {Object.} JSON object - */ - SphProcessSoInitData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessSoInitData - * @function getTypeUrl - * @memberof SphProcessSoInitData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessSoInitData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessSoInitData"; - }; - - return SphProcessSoInitData; -})(); - -$root.SphProcessStartupData = (function () { - - /** - * Properties of a SphProcessStartupData. - * @exports ISphProcessStartupData - * @interface ISphProcessStartupData - * @property {number|null} [pid] SphProcessStartupData pid - * @property {number|null} [tid] SphProcessStartupData tid - * @property {number|null} [itid] SphProcessStartupData itid - * @property {number|Long|null} [startTime] SphProcessStartupData startTime - * @property {number|Long|null} [dur] SphProcessStartupData dur - * @property {number|null} [startName] SphProcessStartupData startName - */ - - /** - * Constructs a new SphProcessStartupData. - * @exports SphProcessStartupData - * @classdesc Represents a SphProcessStartupData. - * @implements ISphProcessStartupData - * @constructor - * @param {ISphProcessStartupData=} [properties] Properties to set - */ - function SphProcessStartupData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessStartupData pid. - * @member {number} pid - * @memberof SphProcessStartupData - * @instance - */ - SphProcessStartupData.prototype.pid = 0; - - /** - * SphProcessStartupData tid. - * @member {number} tid - * @memberof SphProcessStartupData - * @instance - */ - SphProcessStartupData.prototype.tid = 0; - - /** - * SphProcessStartupData itid. - * @member {number} itid - * @memberof SphProcessStartupData - * @instance - */ - SphProcessStartupData.prototype.itid = 0; - - /** - * SphProcessStartupData startTime. - * @member {number|Long} startTime - * @memberof SphProcessStartupData - * @instance - */ - SphProcessStartupData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessStartupData dur. - * @member {number|Long} dur - * @memberof SphProcessStartupData - * @instance - */ - SphProcessStartupData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessStartupData startName. - * @member {number} startName - * @memberof SphProcessStartupData - * @instance - */ - SphProcessStartupData.prototype.startName = 0; - - /** - * Creates a new SphProcessStartupData instance using the specified properties. - * @function create - * @memberof SphProcessStartupData - * @static - * @param {ISphProcessStartupData=} [properties] Properties to set - * @returns {SphProcessStartupData} SphProcessStartupData instance - */ - SphProcessStartupData.create = function create(properties) { - return new SphProcessStartupData(properties); - }; - - /** - * Encodes the specified SphProcessStartupData message. Does not implicitly {@link SphProcessStartupData.verify|verify} messages. - * @function encode - * @memberof SphProcessStartupData - * @static - * @param {ISphProcessStartupData} message SphProcessStartupData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessStartupData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.pid); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.tid); - if (message.itid != null && Object.hasOwnProperty.call(message, "itid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.itid); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.startTime); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.dur); - if (message.startName != null && Object.hasOwnProperty.call(message, "startName")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.startName); - return writer; - }; - - /** - * Encodes the specified SphProcessStartupData message, length delimited. Does not implicitly {@link SphProcessStartupData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessStartupData - * @static - * @param {ISphProcessStartupData} message SphProcessStartupData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessStartupData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessStartupData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessStartupData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessStartupData} SphProcessStartupData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessStartupData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessStartupData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.pid = reader.int32(); - break; - } - case 2: { - message.tid = reader.int32(); - break; - } - case 3: { - message.itid = reader.int32(); - break; - } - case 4: { - message.startTime = reader.int64(); - break; - } - case 5: { - message.dur = reader.int64(); - break; - } - case 6: { - message.startName = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessStartupData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessStartupData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessStartupData} SphProcessStartupData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessStartupData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessStartupData message. - * @function verify - * @memberof SphProcessStartupData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessStartupData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid)) - return "tid: integer expected"; - if (message.itid != null && message.hasOwnProperty("itid")) - if (!$util.isInteger(message.itid)) - return "itid: integer expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.startName != null && message.hasOwnProperty("startName")) - if (!$util.isInteger(message.startName)) - return "startName: integer expected"; - return null; - }; - - /** - * Creates a SphProcessStartupData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessStartupData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessStartupData} SphProcessStartupData - */ - SphProcessStartupData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessStartupData) - return object; - var message = new $root.SphProcessStartupData(); - if (object.pid != null) - message.pid = object.pid | 0; - if (object.tid != null) - message.tid = object.tid | 0; - if (object.itid != null) - message.itid = object.itid | 0; - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.startName != null) - message.startName = object.startName | 0; - return message; - }; - - /** - * Creates a plain object from a SphProcessStartupData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessStartupData - * @static - * @param {SphProcessStartupData} message SphProcessStartupData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessStartupData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.pid = 0; - object.tid = 0; - object.itid = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - object.startName = 0; - } - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.tid != null && message.hasOwnProperty("tid")) - object.tid = message.tid; - if (message.itid != null && message.hasOwnProperty("itid")) - object.itid = message.itid; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.startName != null && message.hasOwnProperty("startName")) - object.startName = message.startName; - return object; - }; - - /** - * Converts this SphProcessStartupData to JSON. - * @function toJSON - * @memberof SphProcessStartupData - * @instance - * @returns {Object.} JSON object - */ - SphProcessStartupData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessStartupData - * @function getTypeUrl - * @memberof SphProcessStartupData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessStartupData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessStartupData"; - }; - - return SphProcessStartupData; -})(); - -$root.SphClockData = (function () { - - /** - * Properties of a SphClockData. - * @exports ISphClockData - * @interface ISphClockData - * @property {number|null} [filterId] SphClockData filterId - * @property {number|null} [value] SphClockData value - * @property {number|Long|null} [startNs] SphClockData startNs - */ - - /** - * Constructs a new SphClockData. - * @exports SphClockData - * @classdesc Represents a SphClockData. - * @implements ISphClockData - * @constructor - * @param {ISphClockData=} [properties] Properties to set - */ - function SphClockData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphClockData filterId. - * @member {number} filterId - * @memberof SphClockData - * @instance - */ - SphClockData.prototype.filterId = 0; - - /** - * SphClockData value. - * @member {number} value - * @memberof SphClockData - * @instance - */ - SphClockData.prototype.value = 0; - - /** - * SphClockData startNs. - * @member {number|Long} startNs - * @memberof SphClockData - * @instance - */ - SphClockData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphClockData instance using the specified properties. - * @function create - * @memberof SphClockData - * @static - * @param {ISphClockData=} [properties] Properties to set - * @returns {SphClockData} SphClockData instance - */ - SphClockData.create = function create(properties) { - return new SphClockData(properties); - }; - - /** - * Encodes the specified SphClockData message. Does not implicitly {@link SphClockData.verify|verify} messages. - * @function encode - * @memberof SphClockData - * @static - * @param {ISphClockData} message SphClockData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphClockData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.filterId != null && Object.hasOwnProperty.call(message, "filterId")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.filterId); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.value); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startNs); - return writer; - }; - - /** - * Encodes the specified SphClockData message, length delimited. Does not implicitly {@link SphClockData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphClockData - * @static - * @param {ISphClockData} message SphClockData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphClockData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphClockData message from the specified reader or buffer. - * @function decode - * @memberof SphClockData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphClockData} SphClockData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphClockData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphClockData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.filterId = reader.int32(); - break; - } - case 2: { - message.value = reader.int32(); - break; - } - case 3: { - message.startNs = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphClockData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphClockData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphClockData} SphClockData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphClockData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphClockData message. - * @function verify - * @memberof SphClockData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphClockData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.filterId != null && message.hasOwnProperty("filterId")) - if (!$util.isInteger(message.filterId)) - return "filterId: integer expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value)) - return "value: integer expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - return null; - }; - - /** - * Creates a SphClockData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphClockData - * @static - * @param {Object.} object Plain object - * @returns {SphClockData} SphClockData - */ - SphClockData.fromObject = function fromObject(object) { - if (object instanceof $root.SphClockData) - return object; - var message = new $root.SphClockData(); - if (object.filterId != null) - message.filterId = object.filterId | 0; - if (object.value != null) - message.value = object.value | 0; - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphClockData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphClockData - * @static - * @param {SphClockData} message SphClockData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphClockData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.filterId = 0; - object.value = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - } - if (message.filterId != null && message.hasOwnProperty("filterId")) - object.filterId = message.filterId; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - return object; - }; - - /** - * Converts this SphClockData to JSON. - * @function toJSON - * @memberof SphClockData - * @instance - * @returns {Object.} JSON object - */ - SphClockData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphClockData - * @function getTypeUrl - * @memberof SphClockData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphClockData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphClockData"; - }; - - return SphClockData; -})(); - -$root.SphIrqData = (function () { - - /** - * Properties of a SphIrqData. - * @exports ISphIrqData - * @interface ISphIrqData - * @property {number|Long|null} [startNs] SphIrqData startNs - * @property {number|Long|null} [dur] SphIrqData dur - * @property {number|null} [depth] SphIrqData depth - * @property {number|null} [argSetId] SphIrqData argSetId - * @property {number|null} [id] SphIrqData id - */ - - /** - * Constructs a new SphIrqData. - * @exports SphIrqData - * @classdesc Represents a SphIrqData. - * @implements ISphIrqData - * @constructor - * @param {ISphIrqData=} [properties] Properties to set - */ - function SphIrqData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphIrqData startNs. - * @member {number|Long} startNs - * @memberof SphIrqData - * @instance - */ - SphIrqData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphIrqData dur. - * @member {number|Long} dur - * @memberof SphIrqData - * @instance - */ - SphIrqData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphIrqData depth. - * @member {number} depth - * @memberof SphIrqData - * @instance - */ - SphIrqData.prototype.depth = 0; - - /** - * SphIrqData argSetId. - * @member {number} argSetId - * @memberof SphIrqData - * @instance - */ - SphIrqData.prototype.argSetId = 0; - - /** - * SphIrqData id. - * @member {number} id - * @memberof SphIrqData - * @instance - */ - SphIrqData.prototype.id = 0; - - /** - * Creates a new SphIrqData instance using the specified properties. - * @function create - * @memberof SphIrqData - * @static - * @param {ISphIrqData=} [properties] Properties to set - * @returns {SphIrqData} SphIrqData instance - */ - SphIrqData.create = function create(properties) { - return new SphIrqData(properties); - }; - - /** - * Encodes the specified SphIrqData message. Does not implicitly {@link SphIrqData.verify|verify} messages. - * @function encode - * @memberof SphIrqData - * @static - * @param {ISphIrqData} message SphIrqData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphIrqData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startNs); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.depth); - if (message.argSetId != null && Object.hasOwnProperty.call(message, "argSetId")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.argSetId); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.id); - return writer; - }; - - /** - * Encodes the specified SphIrqData message, length delimited. Does not implicitly {@link SphIrqData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphIrqData - * @static - * @param {ISphIrqData} message SphIrqData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphIrqData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphIrqData message from the specified reader or buffer. - * @function decode - * @memberof SphIrqData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphIrqData} SphIrqData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphIrqData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphIrqData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startNs = reader.int64(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.depth = reader.int32(); - break; - } - case 4: { - message.argSetId = reader.int32(); - break; - } - case 5: { - message.id = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphIrqData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphIrqData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphIrqData} SphIrqData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphIrqData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphIrqData message. - * @function verify - * @memberof SphIrqData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphIrqData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - if (message.argSetId != null && message.hasOwnProperty("argSetId")) - if (!$util.isInteger(message.argSetId)) - return "argSetId: integer expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - return null; - }; - - /** - * Creates a SphIrqData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphIrqData - * @static - * @param {Object.} object Plain object - * @returns {SphIrqData} SphIrqData - */ - SphIrqData.fromObject = function fromObject(object) { - if (object instanceof $root.SphIrqData) - return object; - var message = new $root.SphIrqData(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.depth != null) - message.depth = object.depth | 0; - if (object.argSetId != null) - message.argSetId = object.argSetId | 0; - if (object.id != null) - message.id = object.id | 0; - return message; - }; - - /** - * Creates a plain object from a SphIrqData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphIrqData - * @static - * @param {SphIrqData} message SphIrqData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphIrqData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - object.depth = 0; - object.argSetId = 0; - object.id = 0; - } - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - if (message.argSetId != null && message.hasOwnProperty("argSetId")) - object.argSetId = message.argSetId; - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - return object; - }; - - /** - * Converts this SphIrqData to JSON. - * @function toJSON - * @memberof SphIrqData - * @instance - * @returns {Object.} JSON object - */ - SphIrqData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphIrqData - * @function getTypeUrl - * @memberof SphIrqData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphIrqData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphIrqData"; - }; - - return SphIrqData; -})(); - -$root.SphHiSysEventData = (function () { - - /** - * Properties of a SphHiSysEventData. - * @exports ISphHiSysEventData - * @interface ISphHiSysEventData - * @property {number|null} [id] SphHiSysEventData id - * @property {number|Long|null} [ts] SphHiSysEventData ts - * @property {number|null} [pid] SphHiSysEventData pid - * @property {number|null} [tid] SphHiSysEventData tid - * @property {number|null} [uid] SphHiSysEventData uid - * @property {string|null} [seq] SphHiSysEventData seq - * @property {number|null} [depth] SphHiSysEventData depth - * @property {number|Long|null} [dur] SphHiSysEventData dur - */ - - /** - * Constructs a new SphHiSysEventData. - * @exports SphHiSysEventData - * @classdesc Represents a SphHiSysEventData. - * @implements ISphHiSysEventData - * @constructor - * @param {ISphHiSysEventData=} [properties] Properties to set - */ - function SphHiSysEventData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphHiSysEventData id. - * @member {number} id - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.id = 0; - - /** - * SphHiSysEventData ts. - * @member {number|Long} ts - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.ts = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiSysEventData pid. - * @member {number} pid - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.pid = 0; - - /** - * SphHiSysEventData tid. - * @member {number} tid - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.tid = 0; - - /** - * SphHiSysEventData uid. - * @member {number} uid - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.uid = 0; - - /** - * SphHiSysEventData seq. - * @member {string} seq - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.seq = ""; - - /** - * SphHiSysEventData depth. - * @member {number} depth - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.depth = 0; - - /** - * SphHiSysEventData dur. - * @member {number|Long} dur - * @memberof SphHiSysEventData - * @instance - */ - SphHiSysEventData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphHiSysEventData instance using the specified properties. - * @function create - * @memberof SphHiSysEventData - * @static - * @param {ISphHiSysEventData=} [properties] Properties to set - * @returns {SphHiSysEventData} SphHiSysEventData instance - */ - SphHiSysEventData.create = function create(properties) { - return new SphHiSysEventData(properties); - }; - - /** - * Encodes the specified SphHiSysEventData message. Does not implicitly {@link SphHiSysEventData.verify|verify} messages. - * @function encode - * @memberof SphHiSysEventData - * @static - * @param {ISphHiSysEventData} message SphHiSysEventData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiSysEventData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.id); - if (message.ts != null && Object.hasOwnProperty.call(message, "ts")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.ts); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pid); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.tid); - if (message.uid != null && Object.hasOwnProperty.call(message, "uid")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.uid); - if (message.seq != null && Object.hasOwnProperty.call(message, "seq")) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.seq); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 7, wireType 0 =*/56).int32(message.depth); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 8, wireType 0 =*/64).int64(message.dur); - return writer; - }; - - /** - * Encodes the specified SphHiSysEventData message, length delimited. Does not implicitly {@link SphHiSysEventData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphHiSysEventData - * @static - * @param {ISphHiSysEventData} message SphHiSysEventData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiSysEventData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphHiSysEventData message from the specified reader or buffer. - * @function decode - * @memberof SphHiSysEventData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphHiSysEventData} SphHiSysEventData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiSysEventData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphHiSysEventData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int32(); - break; - } - case 2: { - message.ts = reader.int64(); - break; - } - case 3: { - message.pid = reader.int32(); - break; - } - case 4: { - message.tid = reader.int32(); - break; - } - case 5: { - message.uid = reader.int32(); - break; - } - case 6: { - message.seq = reader.string(); - break; - } - case 7: { - message.depth = reader.int32(); - break; - } - case 8: { - message.dur = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphHiSysEventData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphHiSysEventData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphHiSysEventData} SphHiSysEventData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiSysEventData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphHiSysEventData message. - * @function verify - * @memberof SphHiSysEventData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphHiSysEventData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.ts != null && message.hasOwnProperty("ts")) - if (!$util.isInteger(message.ts) && !(message.ts && $util.isInteger(message.ts.low) && $util.isInteger(message.ts.high))) - return "ts: integer|Long expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid)) - return "tid: integer expected"; - if (message.uid != null && message.hasOwnProperty("uid")) - if (!$util.isInteger(message.uid)) - return "uid: integer expected"; - if (message.seq != null && message.hasOwnProperty("seq")) - if (!$util.isString(message.seq)) - return "seq: string expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - return null; - }; - - /** - * Creates a SphHiSysEventData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphHiSysEventData - * @static - * @param {Object.} object Plain object - * @returns {SphHiSysEventData} SphHiSysEventData - */ - SphHiSysEventData.fromObject = function fromObject(object) { - if (object instanceof $root.SphHiSysEventData) - return object; - var message = new $root.SphHiSysEventData(); - if (object.id != null) - message.id = object.id | 0; - if (object.ts != null) - if ($util.Long) - (message.ts = $util.Long.fromValue(object.ts)).unsigned = false; - else if (typeof object.ts === "string") - message.ts = parseInt(object.ts, 10); - else if (typeof object.ts === "number") - message.ts = object.ts; - else if (typeof object.ts === "object") - message.ts = new $util.LongBits(object.ts.low >>> 0, object.ts.high >>> 0).toNumber(); - if (object.pid != null) - message.pid = object.pid | 0; - if (object.tid != null) - message.tid = object.tid | 0; - if (object.uid != null) - message.uid = object.uid | 0; - if (object.seq != null) - message.seq = String(object.seq); - if (object.depth != null) - message.depth = object.depth | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphHiSysEventData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphHiSysEventData - * @static - * @param {SphHiSysEventData} message SphHiSysEventData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphHiSysEventData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.id = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ts = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ts = options.longs === String ? "0" : 0; - object.pid = 0; - object.tid = 0; - object.uid = 0; - object.seq = ""; - object.depth = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - } - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.ts != null && message.hasOwnProperty("ts")) - if (typeof message.ts === "number") - object.ts = options.longs === String ? String(message.ts) : message.ts; - else - object.ts = options.longs === String ? $util.Long.prototype.toString.call(message.ts) : options.longs === Number ? new $util.LongBits(message.ts.low >>> 0, message.ts.high >>> 0).toNumber() : message.ts; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.tid != null && message.hasOwnProperty("tid")) - object.tid = message.tid; - if (message.uid != null && message.hasOwnProperty("uid")) - object.uid = message.uid; - if (message.seq != null && message.hasOwnProperty("seq")) - object.seq = message.seq; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - return object; - }; - - /** - * Converts this SphHiSysEventData to JSON. - * @function toJSON - * @memberof SphHiSysEventData - * @instance - * @returns {Object.} JSON object - */ - SphHiSysEventData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphHiSysEventData - * @function getTypeUrl - * @memberof SphHiSysEventData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphHiSysEventData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphHiSysEventData"; - }; - - return SphHiSysEventData; -})(); - -$root.SphLogData = (function () { - - /** - * Properties of a SphLogData. - * @exports ISphLogData - * @interface ISphLogData - * @property {number|null} [id] SphLogData id - * @property {number|null} [pid] SphLogData pid - * @property {number|null} [tid] SphLogData tid - * @property {number|Long|null} [startTs] SphLogData startTs - * @property {number|null} [depth] SphLogData depth - * @property {number|Long|null} [dur] SphLogData dur - */ - - /** - * Constructs a new SphLogData. - * @exports SphLogData - * @classdesc Represents a SphLogData. - * @implements ISphLogData - * @constructor - * @param {ISphLogData=} [properties] Properties to set - */ - function SphLogData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphLogData id. - * @member {number} id - * @memberof SphLogData - * @instance - */ - SphLogData.prototype.id = 0; - - /** - * SphLogData pid. - * @member {number} pid - * @memberof SphLogData - * @instance - */ - SphLogData.prototype.pid = 0; - - /** - * SphLogData tid. - * @member {number} tid - * @memberof SphLogData - * @instance - */ - SphLogData.prototype.tid = 0; - - /** - * SphLogData startTs. - * @member {number|Long} startTs - * @memberof SphLogData - * @instance - */ - SphLogData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphLogData depth. - * @member {number} depth - * @memberof SphLogData - * @instance - */ - SphLogData.prototype.depth = 0; - - /** - * SphLogData dur. - * @member {number|Long} dur - * @memberof SphLogData - * @instance - */ - SphLogData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphLogData instance using the specified properties. - * @function create - * @memberof SphLogData - * @static - * @param {ISphLogData=} [properties] Properties to set - * @returns {SphLogData} SphLogData instance - */ - SphLogData.create = function create(properties) { - return new SphLogData(properties); - }; - - /** - * Encodes the specified SphLogData message. Does not implicitly {@link SphLogData.verify|verify} messages. - * @function encode - * @memberof SphLogData - * @static - * @param {ISphLogData} message SphLogData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphLogData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.id); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.pid); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.tid); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.startTs); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.depth); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.dur); - return writer; - }; - - /** - * Encodes the specified SphLogData message, length delimited. Does not implicitly {@link SphLogData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphLogData - * @static - * @param {ISphLogData} message SphLogData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphLogData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphLogData message from the specified reader or buffer. - * @function decode - * @memberof SphLogData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphLogData} SphLogData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphLogData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphLogData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int32(); - break; - } - case 2: { - message.pid = reader.int32(); - break; - } - case 3: { - message.tid = reader.int32(); - break; - } - case 4: { - message.startTs = reader.int64(); - break; - } - case 5: { - message.depth = reader.int32(); - break; - } - case 6: { - message.dur = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphLogData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphLogData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphLogData} SphLogData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphLogData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphLogData message. - * @function verify - * @memberof SphLogData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphLogData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid)) - return "tid: integer expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - return null; - }; - - /** - * Creates a SphLogData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphLogData - * @static - * @param {Object.} object Plain object - * @returns {SphLogData} SphLogData - */ - SphLogData.fromObject = function fromObject(object) { - if (object instanceof $root.SphLogData) - return object; - var message = new $root.SphLogData(); - if (object.id != null) - message.id = object.id | 0; - if (object.pid != null) - message.pid = object.pid | 0; - if (object.tid != null) - message.tid = object.tid | 0; - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.depth != null) - message.depth = object.depth | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphLogData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphLogData - * @static - * @param {SphLogData} message SphLogData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphLogData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.id = 0; - object.pid = 0; - object.tid = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - object.depth = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - } - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.tid != null && message.hasOwnProperty("tid")) - object.tid = message.tid; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - return object; - }; - - /** - * Converts this SphLogData to JSON. - * @function toJSON - * @memberof SphLogData - * @instance - * @returns {Object.} JSON object - */ - SphLogData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphLogData - * @function getTypeUrl - * @memberof SphLogData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphLogData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphLogData"; - }; - - return SphLogData; -})(); - -$root.SphVirtualMemData = (function () { - - /** - * Properties of a SphVirtualMemData. - * @exports ISphVirtualMemData - * @interface ISphVirtualMemData - * @property {number|Long|null} [startTime] SphVirtualMemData startTime - * @property {number|null} [filterId] SphVirtualMemData filterId - * @property {number|Long|null} [value] SphVirtualMemData value - * @property {number|null} [duration] SphVirtualMemData duration - * @property {number|Long|null} [maxValue] SphVirtualMemData maxValue - * @property {number|null} [delta] SphVirtualMemData delta - */ - - /** - * Constructs a new SphVirtualMemData. - * @exports SphVirtualMemData - * @classdesc Represents a SphVirtualMemData. - * @implements ISphVirtualMemData - * @constructor - * @param {ISphVirtualMemData=} [properties] Properties to set - */ - function SphVirtualMemData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphVirtualMemData startTime. - * @member {number|Long} startTime - * @memberof SphVirtualMemData - * @instance - */ - SphVirtualMemData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphVirtualMemData filterId. - * @member {number} filterId - * @memberof SphVirtualMemData - * @instance - */ - SphVirtualMemData.prototype.filterId = 0; - - /** - * SphVirtualMemData value. - * @member {number|Long} value - * @memberof SphVirtualMemData - * @instance - */ - SphVirtualMemData.prototype.value = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphVirtualMemData duration. - * @member {number} duration - * @memberof SphVirtualMemData - * @instance - */ - SphVirtualMemData.prototype.duration = 0; - - /** - * SphVirtualMemData maxValue. - * @member {number|Long} maxValue - * @memberof SphVirtualMemData - * @instance - */ - SphVirtualMemData.prototype.maxValue = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphVirtualMemData delta. - * @member {number} delta - * @memberof SphVirtualMemData - * @instance - */ - SphVirtualMemData.prototype.delta = 0; - - /** - * Creates a new SphVirtualMemData instance using the specified properties. - * @function create - * @memberof SphVirtualMemData - * @static - * @param {ISphVirtualMemData=} [properties] Properties to set - * @returns {SphVirtualMemData} SphVirtualMemData instance - */ - SphVirtualMemData.create = function create(properties) { - return new SphVirtualMemData(properties); - }; - - /** - * Encodes the specified SphVirtualMemData message. Does not implicitly {@link SphVirtualMemData.verify|verify} messages. - * @function encode - * @memberof SphVirtualMemData - * @static - * @param {ISphVirtualMemData} message SphVirtualMemData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphVirtualMemData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startTime); - if (message.filterId != null && Object.hasOwnProperty.call(message, "filterId")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.filterId); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.value); - if (message.duration != null && Object.hasOwnProperty.call(message, "duration")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.duration); - if (message.maxValue != null && Object.hasOwnProperty.call(message, "maxValue")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.maxValue); - if (message.delta != null && Object.hasOwnProperty.call(message, "delta")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.delta); - return writer; - }; - - /** - * Encodes the specified SphVirtualMemData message, length delimited. Does not implicitly {@link SphVirtualMemData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphVirtualMemData - * @static - * @param {ISphVirtualMemData} message SphVirtualMemData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphVirtualMemData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphVirtualMemData message from the specified reader or buffer. - * @function decode - * @memberof SphVirtualMemData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphVirtualMemData} SphVirtualMemData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphVirtualMemData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphVirtualMemData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startTime = reader.int64(); - break; - } - case 2: { - message.filterId = reader.int32(); - break; - } - case 3: { - message.value = reader.int64(); - break; - } - case 4: { - message.duration = reader.int32(); - break; - } - case 5: { - message.maxValue = reader.int64(); - break; - } - case 6: { - message.delta = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphVirtualMemData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphVirtualMemData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphVirtualMemData} SphVirtualMemData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphVirtualMemData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphVirtualMemData message. - * @function verify - * @memberof SphVirtualMemData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphVirtualMemData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.filterId != null && message.hasOwnProperty("filterId")) - if (!$util.isInteger(message.filterId)) - return "filterId: integer expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value) && !(message.value && $util.isInteger(message.value.low) && $util.isInteger(message.value.high))) - return "value: integer|Long expected"; - if (message.duration != null && message.hasOwnProperty("duration")) - if (!$util.isInteger(message.duration)) - return "duration: integer expected"; - if (message.maxValue != null && message.hasOwnProperty("maxValue")) - if (!$util.isInteger(message.maxValue) && !(message.maxValue && $util.isInteger(message.maxValue.low) && $util.isInteger(message.maxValue.high))) - return "maxValue: integer|Long expected"; - if (message.delta != null && message.hasOwnProperty("delta")) - if (!$util.isInteger(message.delta)) - return "delta: integer expected"; - return null; - }; - - /** - * Creates a SphVirtualMemData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphVirtualMemData - * @static - * @param {Object.} object Plain object - * @returns {SphVirtualMemData} SphVirtualMemData - */ - SphVirtualMemData.fromObject = function fromObject(object) { - if (object instanceof $root.SphVirtualMemData) - return object; - var message = new $root.SphVirtualMemData(); - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.filterId != null) - message.filterId = object.filterId | 0; - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = false; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); - if (object.duration != null) - message.duration = object.duration | 0; - if (object.maxValue != null) - if ($util.Long) - (message.maxValue = $util.Long.fromValue(object.maxValue)).unsigned = false; - else if (typeof object.maxValue === "string") - message.maxValue = parseInt(object.maxValue, 10); - else if (typeof object.maxValue === "number") - message.maxValue = object.maxValue; - else if (typeof object.maxValue === "object") - message.maxValue = new $util.LongBits(object.maxValue.low >>> 0, object.maxValue.high >>> 0).toNumber(); - if (object.delta != null) - message.delta = object.delta | 0; - return message; - }; - - /** - * Creates a plain object from a SphVirtualMemData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphVirtualMemData - * @static - * @param {SphVirtualMemData} message SphVirtualMemData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphVirtualMemData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - object.filterId = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - object.duration = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.maxValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.maxValue = options.longs === String ? "0" : 0; - object.delta = 0; - } - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.filterId != null && message.hasOwnProperty("filterId")) - object.filterId = message.filterId; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; - if (message.duration != null && message.hasOwnProperty("duration")) - object.duration = message.duration; - if (message.maxValue != null && message.hasOwnProperty("maxValue")) - if (typeof message.maxValue === "number") - object.maxValue = options.longs === String ? String(message.maxValue) : message.maxValue; - else - object.maxValue = options.longs === String ? $util.Long.prototype.toString.call(message.maxValue) : options.longs === Number ? new $util.LongBits(message.maxValue.low >>> 0, message.maxValue.high >>> 0).toNumber() : message.maxValue; - if (message.delta != null && message.hasOwnProperty("delta")) - object.delta = message.delta; - return object; - }; - - /** - * Converts this SphVirtualMemData to JSON. - * @function toJSON - * @memberof SphVirtualMemData - * @instance - * @returns {Object.} JSON object - */ - SphVirtualMemData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphVirtualMemData - * @function getTypeUrl - * @memberof SphVirtualMemData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphVirtualMemData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphVirtualMemData"; - }; - - return SphVirtualMemData; -})(); - -$root.SphEnergyData = (function () { - - /** - * Properties of a SphEnergyData. - * @exports ISphEnergyData - * @interface ISphEnergyData - * @property {number|null} [id] SphEnergyData id - * @property {number|Long|null} [startNs] SphEnergyData startNs - * @property {string|null} [eventName] SphEnergyData eventName - * @property {string|null} [appKey] SphEnergyData appKey - * @property {string|null} [eventValue] SphEnergyData eventValue - */ - - /** - * Constructs a new SphEnergyData. - * @exports SphEnergyData - * @classdesc Represents a SphEnergyData. - * @implements ISphEnergyData - * @constructor - * @param {ISphEnergyData=} [properties] Properties to set - */ - function SphEnergyData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphEnergyData id. - * @member {number} id - * @memberof SphEnergyData - * @instance - */ - SphEnergyData.prototype.id = 0; - - /** - * SphEnergyData startNs. - * @member {number|Long} startNs - * @memberof SphEnergyData - * @instance - */ - SphEnergyData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphEnergyData eventName. - * @member {string} eventName - * @memberof SphEnergyData - * @instance - */ - SphEnergyData.prototype.eventName = ""; - - /** - * SphEnergyData appKey. - * @member {string} appKey - * @memberof SphEnergyData - * @instance - */ - SphEnergyData.prototype.appKey = ""; - - /** - * SphEnergyData eventValue. - * @member {string} eventValue - * @memberof SphEnergyData - * @instance - */ - SphEnergyData.prototype.eventValue = ""; - - /** - * Creates a new SphEnergyData instance using the specified properties. - * @function create - * @memberof SphEnergyData - * @static - * @param {ISphEnergyData=} [properties] Properties to set - * @returns {SphEnergyData} SphEnergyData instance - */ - SphEnergyData.create = function create(properties) { - return new SphEnergyData(properties); - }; - - /** - * Encodes the specified SphEnergyData message. Does not implicitly {@link SphEnergyData.verify|verify} messages. - * @function encode - * @memberof SphEnergyData - * @static - * @param {ISphEnergyData} message SphEnergyData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphEnergyData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.id); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.startNs); - if (message.eventName != null && Object.hasOwnProperty.call(message, "eventName")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.eventName); - if (message.appKey != null && Object.hasOwnProperty.call(message, "appKey")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.appKey); - if (message.eventValue != null && Object.hasOwnProperty.call(message, "eventValue")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message.eventValue); - return writer; - }; - - /** - * Encodes the specified SphEnergyData message, length delimited. Does not implicitly {@link SphEnergyData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphEnergyData - * @static - * @param {ISphEnergyData} message SphEnergyData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphEnergyData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphEnergyData message from the specified reader or buffer. - * @function decode - * @memberof SphEnergyData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphEnergyData} SphEnergyData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphEnergyData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphEnergyData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int32(); - break; - } - case 2: { - message.startNs = reader.int64(); - break; - } - case 3: { - message.eventName = reader.string(); - break; - } - case 4: { - message.appKey = reader.string(); - break; - } - case 5: { - message.eventValue = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphEnergyData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphEnergyData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphEnergyData} SphEnergyData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphEnergyData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphEnergyData message. - * @function verify - * @memberof SphEnergyData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphEnergyData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.eventName != null && message.hasOwnProperty("eventName")) - if (!$util.isString(message.eventName)) - return "eventName: string expected"; - if (message.appKey != null && message.hasOwnProperty("appKey")) - if (!$util.isString(message.appKey)) - return "appKey: string expected"; - if (message.eventValue != null && message.hasOwnProperty("eventValue")) - if (!$util.isString(message.eventValue)) - return "eventValue: string expected"; - return null; - }; - - /** - * Creates a SphEnergyData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphEnergyData - * @static - * @param {Object.} object Plain object - * @returns {SphEnergyData} SphEnergyData - */ - SphEnergyData.fromObject = function fromObject(object) { - if (object instanceof $root.SphEnergyData) - return object; - var message = new $root.SphEnergyData(); - if (object.id != null) - message.id = object.id | 0; - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.eventName != null) - message.eventName = String(object.eventName); - if (object.appKey != null) - message.appKey = String(object.appKey); - if (object.eventValue != null) - message.eventValue = String(object.eventValue); - return message; - }; - - /** - * Creates a plain object from a SphEnergyData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphEnergyData - * @static - * @param {SphEnergyData} message SphEnergyData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphEnergyData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.id = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - object.eventName = ""; - object.appKey = ""; - object.eventValue = ""; - } - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.eventName != null && message.hasOwnProperty("eventName")) - object.eventName = message.eventName; - if (message.appKey != null && message.hasOwnProperty("appKey")) - object.appKey = message.appKey; - if (message.eventValue != null && message.hasOwnProperty("eventValue")) - object.eventValue = message.eventValue; - return object; - }; - - /** - * Converts this SphEnergyData to JSON. - * @function toJSON - * @memberof SphEnergyData - * @instance - * @returns {Object.} JSON object - */ - SphEnergyData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphEnergyData - * @function getTypeUrl - * @memberof SphEnergyData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphEnergyData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphEnergyData"; - }; - - return SphEnergyData; -})(); - -$root.SphFrameData = (function () { - - /** - * Properties of a SphFrameData. - * @exports ISphFrameData - * @interface ISphFrameData - * @property {number|null} [id] SphFrameData id - * @property {string|null} [frameType] SphFrameData frameType - * @property {number|null} [ipid] SphFrameData ipid - * @property {number|null} [name] SphFrameData name - * @property {number|Long|null} [appDur] SphFrameData appDur - * @property {number|Long|null} [dur] SphFrameData dur - * @property {number|Long|null} [ts] SphFrameData ts - * @property {string|null} [type] SphFrameData type - * @property {number|null} [jankTag] SphFrameData jankTag - * @property {number|null} [pid] SphFrameData pid - * @property {string|null} [cmdline] SphFrameData cmdline - * @property {number|Long|null} [rsTs] SphFrameData rsTs - * @property {number|null} [rsVsync] SphFrameData rsVsync - * @property {number|Long|null} [rsDur] SphFrameData rsDur - * @property {number|null} [rsIpid] SphFrameData rsIpid - * @property {number|null} [rsPid] SphFrameData rsPid - * @property {number|null} [rsName] SphFrameData rsName - */ - - /** - * Constructs a new SphFrameData. - * @exports SphFrameData - * @classdesc Represents a SphFrameData. - * @implements ISphFrameData - * @constructor - * @param {ISphFrameData=} [properties] Properties to set - */ - function SphFrameData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphFrameData id. - * @member {number} id - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.id = 0; - - /** - * SphFrameData frameType. - * @member {string} frameType - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.frameType = ""; - - /** - * SphFrameData ipid. - * @member {number} ipid - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.ipid = 0; - - /** - * SphFrameData name. - * @member {number} name - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.name = 0; - - /** - * SphFrameData appDur. - * @member {number|Long} appDur - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.appDur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameData dur. - * @member {number|Long} dur - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameData ts. - * @member {number|Long} ts - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.ts = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameData type. - * @member {string} type - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.type = ""; - - /** - * SphFrameData jankTag. - * @member {number} jankTag - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.jankTag = 0; - - /** - * SphFrameData pid. - * @member {number} pid - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.pid = 0; - - /** - * SphFrameData cmdline. - * @member {string} cmdline - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.cmdline = ""; - - /** - * SphFrameData rsTs. - * @member {number|Long} rsTs - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.rsTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameData rsVsync. - * @member {number} rsVsync - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.rsVsync = 0; - - /** - * SphFrameData rsDur. - * @member {number|Long} rsDur - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.rsDur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameData rsIpid. - * @member {number} rsIpid - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.rsIpid = 0; - - /** - * SphFrameData rsPid. - * @member {number} rsPid - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.rsPid = 0; - - /** - * SphFrameData rsName. - * @member {number} rsName - * @memberof SphFrameData - * @instance - */ - SphFrameData.prototype.rsName = 0; - - /** - * Creates a new SphFrameData instance using the specified properties. - * @function create - * @memberof SphFrameData - * @static - * @param {ISphFrameData=} [properties] Properties to set - * @returns {SphFrameData} SphFrameData instance - */ - SphFrameData.create = function create(properties) { - return new SphFrameData(properties); - }; - - /** - * Encodes the specified SphFrameData message. Does not implicitly {@link SphFrameData.verify|verify} messages. - * @function encode - * @memberof SphFrameData - * @static - * @param {ISphFrameData} message SphFrameData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.id); - if (message.frameType != null && Object.hasOwnProperty.call(message, "frameType")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.frameType); - if (message.ipid != null && Object.hasOwnProperty.call(message, "ipid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.ipid); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.name); - if (message.appDur != null && Object.hasOwnProperty.call(message, "appDur")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.appDur); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.dur); - if (message.ts != null && Object.hasOwnProperty.call(message, "ts")) - writer.uint32(/* id 7, wireType 0 =*/56).int64(message.ts); - if (message.type != null && Object.hasOwnProperty.call(message, "type")) - writer.uint32(/* id 8, wireType 2 =*/66).string(message.type); - if (message.jankTag != null && Object.hasOwnProperty.call(message, "jankTag")) - writer.uint32(/* id 9, wireType 0 =*/72).int32(message.jankTag); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 10, wireType 0 =*/80).int32(message.pid); - if (message.cmdline != null && Object.hasOwnProperty.call(message, "cmdline")) - writer.uint32(/* id 11, wireType 2 =*/90).string(message.cmdline); - if (message.rsTs != null && Object.hasOwnProperty.call(message, "rsTs")) - writer.uint32(/* id 12, wireType 0 =*/96).int64(message.rsTs); - if (message.rsVsync != null && Object.hasOwnProperty.call(message, "rsVsync")) - writer.uint32(/* id 13, wireType 0 =*/104).int32(message.rsVsync); - if (message.rsDur != null && Object.hasOwnProperty.call(message, "rsDur")) - writer.uint32(/* id 14, wireType 0 =*/112).int64(message.rsDur); - if (message.rsIpid != null && Object.hasOwnProperty.call(message, "rsIpid")) - writer.uint32(/* id 15, wireType 0 =*/120).int32(message.rsIpid); - if (message.rsPid != null && Object.hasOwnProperty.call(message, "rsPid")) - writer.uint32(/* id 16, wireType 0 =*/128).int32(message.rsPid); - if (message.rsName != null && Object.hasOwnProperty.call(message, "rsName")) - writer.uint32(/* id 17, wireType 0 =*/136).int32(message.rsName); - return writer; - }; - - /** - * Encodes the specified SphFrameData message, length delimited. Does not implicitly {@link SphFrameData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphFrameData - * @static - * @param {ISphFrameData} message SphFrameData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphFrameData message from the specified reader or buffer. - * @function decode - * @memberof SphFrameData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphFrameData} SphFrameData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphFrameData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int32(); - break; - } - case 2: { - message.frameType = reader.string(); - break; - } - case 3: { - message.ipid = reader.int32(); - break; - } - case 4: { - message.name = reader.int32(); - break; - } - case 5: { - message.appDur = reader.int64(); - break; - } - case 6: { - message.dur = reader.int64(); - break; - } - case 7: { - message.ts = reader.int64(); - break; - } - case 8: { - message.type = reader.string(); - break; - } - case 9: { - message.jankTag = reader.int32(); - break; - } - case 10: { - message.pid = reader.int32(); - break; - } - case 11: { - message.cmdline = reader.string(); - break; - } - case 12: { - message.rsTs = reader.int64(); - break; - } - case 13: { - message.rsVsync = reader.int32(); - break; - } - case 14: { - message.rsDur = reader.int64(); - break; - } - case 15: { - message.rsIpid = reader.int32(); - break; - } - case 16: { - message.rsPid = reader.int32(); - break; - } - case 17: { - message.rsName = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphFrameData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphFrameData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphFrameData} SphFrameData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphFrameData message. - * @function verify - * @memberof SphFrameData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphFrameData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.frameType != null && message.hasOwnProperty("frameType")) - if (!$util.isString(message.frameType)) - return "frameType: string expected"; - if (message.ipid != null && message.hasOwnProperty("ipid")) - if (!$util.isInteger(message.ipid)) - return "ipid: integer expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isInteger(message.name)) - return "name: integer expected"; - if (message.appDur != null && message.hasOwnProperty("appDur")) - if (!$util.isInteger(message.appDur) && !(message.appDur && $util.isInteger(message.appDur.low) && $util.isInteger(message.appDur.high))) - return "appDur: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.ts != null && message.hasOwnProperty("ts")) - if (!$util.isInteger(message.ts) && !(message.ts && $util.isInteger(message.ts.low) && $util.isInteger(message.ts.high))) - return "ts: integer|Long expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isString(message.type)) - return "type: string expected"; - if (message.jankTag != null && message.hasOwnProperty("jankTag")) - if (!$util.isInteger(message.jankTag)) - return "jankTag: integer expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.cmdline != null && message.hasOwnProperty("cmdline")) - if (!$util.isString(message.cmdline)) - return "cmdline: string expected"; - if (message.rsTs != null && message.hasOwnProperty("rsTs")) - if (!$util.isInteger(message.rsTs) && !(message.rsTs && $util.isInteger(message.rsTs.low) && $util.isInteger(message.rsTs.high))) - return "rsTs: integer|Long expected"; - if (message.rsVsync != null && message.hasOwnProperty("rsVsync")) - if (!$util.isInteger(message.rsVsync)) - return "rsVsync: integer expected"; - if (message.rsDur != null && message.hasOwnProperty("rsDur")) - if (!$util.isInteger(message.rsDur) && !(message.rsDur && $util.isInteger(message.rsDur.low) && $util.isInteger(message.rsDur.high))) - return "rsDur: integer|Long expected"; - if (message.rsIpid != null && message.hasOwnProperty("rsIpid")) - if (!$util.isInteger(message.rsIpid)) - return "rsIpid: integer expected"; - if (message.rsPid != null && message.hasOwnProperty("rsPid")) - if (!$util.isInteger(message.rsPid)) - return "rsPid: integer expected"; - if (message.rsName != null && message.hasOwnProperty("rsName")) - if (!$util.isInteger(message.rsName)) - return "rsName: integer expected"; - return null; - }; - - /** - * Creates a SphFrameData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphFrameData - * @static - * @param {Object.} object Plain object - * @returns {SphFrameData} SphFrameData - */ - SphFrameData.fromObject = function fromObject(object) { - if (object instanceof $root.SphFrameData) - return object; - var message = new $root.SphFrameData(); - if (object.id != null) - message.id = object.id | 0; - if (object.frameType != null) - message.frameType = String(object.frameType); - if (object.ipid != null) - message.ipid = object.ipid | 0; - if (object.name != null) - message.name = object.name | 0; - if (object.appDur != null) - if ($util.Long) - (message.appDur = $util.Long.fromValue(object.appDur)).unsigned = false; - else if (typeof object.appDur === "string") - message.appDur = parseInt(object.appDur, 10); - else if (typeof object.appDur === "number") - message.appDur = object.appDur; - else if (typeof object.appDur === "object") - message.appDur = new $util.LongBits(object.appDur.low >>> 0, object.appDur.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.ts != null) - if ($util.Long) - (message.ts = $util.Long.fromValue(object.ts)).unsigned = false; - else if (typeof object.ts === "string") - message.ts = parseInt(object.ts, 10); - else if (typeof object.ts === "number") - message.ts = object.ts; - else if (typeof object.ts === "object") - message.ts = new $util.LongBits(object.ts.low >>> 0, object.ts.high >>> 0).toNumber(); - if (object.type != null) - message.type = String(object.type); - if (object.jankTag != null) - message.jankTag = object.jankTag | 0; - if (object.pid != null) - message.pid = object.pid | 0; - if (object.cmdline != null) - message.cmdline = String(object.cmdline); - if (object.rsTs != null) - if ($util.Long) - (message.rsTs = $util.Long.fromValue(object.rsTs)).unsigned = false; - else if (typeof object.rsTs === "string") - message.rsTs = parseInt(object.rsTs, 10); - else if (typeof object.rsTs === "number") - message.rsTs = object.rsTs; - else if (typeof object.rsTs === "object") - message.rsTs = new $util.LongBits(object.rsTs.low >>> 0, object.rsTs.high >>> 0).toNumber(); - if (object.rsVsync != null) - message.rsVsync = object.rsVsync | 0; - if (object.rsDur != null) - if ($util.Long) - (message.rsDur = $util.Long.fromValue(object.rsDur)).unsigned = false; - else if (typeof object.rsDur === "string") - message.rsDur = parseInt(object.rsDur, 10); - else if (typeof object.rsDur === "number") - message.rsDur = object.rsDur; - else if (typeof object.rsDur === "object") - message.rsDur = new $util.LongBits(object.rsDur.low >>> 0, object.rsDur.high >>> 0).toNumber(); - if (object.rsIpid != null) - message.rsIpid = object.rsIpid | 0; - if (object.rsPid != null) - message.rsPid = object.rsPid | 0; - if (object.rsName != null) - message.rsName = object.rsName | 0; - return message; - }; - - /** - * Creates a plain object from a SphFrameData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphFrameData - * @static - * @param {SphFrameData} message SphFrameData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphFrameData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.id = 0; - object.frameType = ""; - object.ipid = 0; - object.name = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.appDur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.appDur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ts = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ts = options.longs === String ? "0" : 0; - object.type = ""; - object.jankTag = 0; - object.pid = 0; - object.cmdline = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.rsTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.rsTs = options.longs === String ? "0" : 0; - object.rsVsync = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.rsDur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.rsDur = options.longs === String ? "0" : 0; - object.rsIpid = 0; - object.rsPid = 0; - object.rsName = 0; - } - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.frameType != null && message.hasOwnProperty("frameType")) - object.frameType = message.frameType; - if (message.ipid != null && message.hasOwnProperty("ipid")) - object.ipid = message.ipid; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.appDur != null && message.hasOwnProperty("appDur")) - if (typeof message.appDur === "number") - object.appDur = options.longs === String ? String(message.appDur) : message.appDur; - else - object.appDur = options.longs === String ? $util.Long.prototype.toString.call(message.appDur) : options.longs === Number ? new $util.LongBits(message.appDur.low >>> 0, message.appDur.high >>> 0).toNumber() : message.appDur; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.ts != null && message.hasOwnProperty("ts")) - if (typeof message.ts === "number") - object.ts = options.longs === String ? String(message.ts) : message.ts; - else - object.ts = options.longs === String ? $util.Long.prototype.toString.call(message.ts) : options.longs === Number ? new $util.LongBits(message.ts.low >>> 0, message.ts.high >>> 0).toNumber() : message.ts; - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.jankTag != null && message.hasOwnProperty("jankTag")) - object.jankTag = message.jankTag; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.cmdline != null && message.hasOwnProperty("cmdline")) - object.cmdline = message.cmdline; - if (message.rsTs != null && message.hasOwnProperty("rsTs")) - if (typeof message.rsTs === "number") - object.rsTs = options.longs === String ? String(message.rsTs) : message.rsTs; - else - object.rsTs = options.longs === String ? $util.Long.prototype.toString.call(message.rsTs) : options.longs === Number ? new $util.LongBits(message.rsTs.low >>> 0, message.rsTs.high >>> 0).toNumber() : message.rsTs; - if (message.rsVsync != null && message.hasOwnProperty("rsVsync")) - object.rsVsync = message.rsVsync; - if (message.rsDur != null && message.hasOwnProperty("rsDur")) - if (typeof message.rsDur === "number") - object.rsDur = options.longs === String ? String(message.rsDur) : message.rsDur; - else - object.rsDur = options.longs === String ? $util.Long.prototype.toString.call(message.rsDur) : options.longs === Number ? new $util.LongBits(message.rsDur.low >>> 0, message.rsDur.high >>> 0).toNumber() : message.rsDur; - if (message.rsIpid != null && message.hasOwnProperty("rsIpid")) - object.rsIpid = message.rsIpid; - if (message.rsPid != null && message.hasOwnProperty("rsPid")) - object.rsPid = message.rsPid; - if (message.rsName != null && message.hasOwnProperty("rsName")) - object.rsName = message.rsName; - return object; - }; - - /** - * Converts this SphFrameData to JSON. - * @function toJSON - * @memberof SphFrameData - * @instance - * @returns {Object.} JSON object - */ - SphFrameData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphFrameData - * @function getTypeUrl - * @memberof SphFrameData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphFrameData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphFrameData"; - }; - - return SphFrameData; -})(); - -$root.SphFrameAnimationData = (function () { - - /** - * Properties of a SphFrameAnimationData. - * @exports ISphFrameAnimationData - * @interface ISphFrameAnimationData - * @property {number|null} [animationId] SphFrameAnimationData animationId - * @property {number|null} [status] SphFrameAnimationData status - * @property {number|Long|null} [startTs] SphFrameAnimationData startTs - * @property {number|Long|null} [endTs] SphFrameAnimationData endTs - * @property {string|null} [name] SphFrameAnimationData name - */ - - /** - * Constructs a new SphFrameAnimationData. - * @exports SphFrameAnimationData - * @classdesc Represents a SphFrameAnimationData. - * @implements ISphFrameAnimationData - * @constructor - * @param {ISphFrameAnimationData=} [properties] Properties to set - */ - function SphFrameAnimationData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphFrameAnimationData animationId. - * @member {number} animationId - * @memberof SphFrameAnimationData - * @instance - */ - SphFrameAnimationData.prototype.animationId = 0; - - /** - * SphFrameAnimationData status. - * @member {number} status - * @memberof SphFrameAnimationData - * @instance - */ - SphFrameAnimationData.prototype.status = 0; - - /** - * SphFrameAnimationData startTs. - * @member {number|Long} startTs - * @memberof SphFrameAnimationData - * @instance - */ - SphFrameAnimationData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameAnimationData endTs. - * @member {number|Long} endTs - * @memberof SphFrameAnimationData - * @instance - */ - SphFrameAnimationData.prototype.endTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameAnimationData name. - * @member {string} name - * @memberof SphFrameAnimationData - * @instance - */ - SphFrameAnimationData.prototype.name = ""; - - /** - * Creates a new SphFrameAnimationData instance using the specified properties. - * @function create - * @memberof SphFrameAnimationData - * @static - * @param {ISphFrameAnimationData=} [properties] Properties to set - * @returns {SphFrameAnimationData} SphFrameAnimationData instance - */ - SphFrameAnimationData.create = function create(properties) { - return new SphFrameAnimationData(properties); - }; - - /** - * Encodes the specified SphFrameAnimationData message. Does not implicitly {@link SphFrameAnimationData.verify|verify} messages. - * @function encode - * @memberof SphFrameAnimationData - * @static - * @param {ISphFrameAnimationData} message SphFrameAnimationData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameAnimationData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.animationId != null && Object.hasOwnProperty.call(message, "animationId")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.animationId); - if (message.status != null && Object.hasOwnProperty.call(message, "status")) - writer.uint32(/* id 2, wireType 0 =*/16).int32(message.status); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startTs); - if (message.endTs != null && Object.hasOwnProperty.call(message, "endTs")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.endTs); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message.name); - return writer; - }; - - /** - * Encodes the specified SphFrameAnimationData message, length delimited. Does not implicitly {@link SphFrameAnimationData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphFrameAnimationData - * @static - * @param {ISphFrameAnimationData} message SphFrameAnimationData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameAnimationData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphFrameAnimationData message from the specified reader or buffer. - * @function decode - * @memberof SphFrameAnimationData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphFrameAnimationData} SphFrameAnimationData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameAnimationData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphFrameAnimationData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.animationId = reader.int32(); - break; - } - case 2: { - message.status = reader.int32(); - break; - } - case 3: { - message.startTs = reader.int64(); - break; - } - case 4: { - message.endTs = reader.int64(); - break; - } - case 5: { - message.name = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphFrameAnimationData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphFrameAnimationData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphFrameAnimationData} SphFrameAnimationData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameAnimationData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphFrameAnimationData message. - * @function verify - * @memberof SphFrameAnimationData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphFrameAnimationData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.animationId != null && message.hasOwnProperty("animationId")) - if (!$util.isInteger(message.animationId)) - return "animationId: integer expected"; - if (message.status != null && message.hasOwnProperty("status")) - if (!$util.isInteger(message.status)) - return "status: integer expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.endTs != null && message.hasOwnProperty("endTs")) - if (!$util.isInteger(message.endTs) && !(message.endTs && $util.isInteger(message.endTs.low) && $util.isInteger(message.endTs.high))) - return "endTs: integer|Long expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - return null; - }; - - /** - * Creates a SphFrameAnimationData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphFrameAnimationData - * @static - * @param {Object.} object Plain object - * @returns {SphFrameAnimationData} SphFrameAnimationData - */ - SphFrameAnimationData.fromObject = function fromObject(object) { - if (object instanceof $root.SphFrameAnimationData) - return object; - var message = new $root.SphFrameAnimationData(); - if (object.animationId != null) - message.animationId = object.animationId | 0; - if (object.status != null) - message.status = object.status | 0; - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.endTs != null) - if ($util.Long) - (message.endTs = $util.Long.fromValue(object.endTs)).unsigned = false; - else if (typeof object.endTs === "string") - message.endTs = parseInt(object.endTs, 10); - else if (typeof object.endTs === "number") - message.endTs = object.endTs; - else if (typeof object.endTs === "object") - message.endTs = new $util.LongBits(object.endTs.low >>> 0, object.endTs.high >>> 0).toNumber(); - if (object.name != null) - message.name = String(object.name); - return message; - }; - - /** - * Creates a plain object from a SphFrameAnimationData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphFrameAnimationData - * @static - * @param {SphFrameAnimationData} message SphFrameAnimationData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphFrameAnimationData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.animationId = 0; - object.status = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.endTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.endTs = options.longs === String ? "0" : 0; - object.name = ""; - } - if (message.animationId != null && message.hasOwnProperty("animationId")) - object.animationId = message.animationId; - if (message.status != null && message.hasOwnProperty("status")) - object.status = message.status; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.endTs != null && message.hasOwnProperty("endTs")) - if (typeof message.endTs === "number") - object.endTs = options.longs === String ? String(message.endTs) : message.endTs; - else - object.endTs = options.longs === String ? $util.Long.prototype.toString.call(message.endTs) : options.longs === Number ? new $util.LongBits(message.endTs.low >>> 0, message.endTs.high >>> 0).toNumber() : message.endTs; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - return object; - }; - - /** - * Converts this SphFrameAnimationData to JSON. - * @function toJSON - * @memberof SphFrameAnimationData - * @instance - * @returns {Object.} JSON object - */ - SphFrameAnimationData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphFrameAnimationData - * @function getTypeUrl - * @memberof SphFrameAnimationData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphFrameAnimationData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphFrameAnimationData"; - }; - - return SphFrameAnimationData; -})(); - -$root.SphFrameDynamicData = (function () { - - /** - * Properties of a SphFrameDynamicData. - * @exports ISphFrameDynamicData - * @interface ISphFrameDynamicData - * @property {number|null} [id] SphFrameDynamicData id - * @property {string|null} [x] SphFrameDynamicData x - * @property {string|null} [y] SphFrameDynamicData y - * @property {string|null} [width] SphFrameDynamicData width - * @property {string|null} [height] SphFrameDynamicData height - * @property {string|null} [alpha] SphFrameDynamicData alpha - * @property {number|Long|null} [ts] SphFrameDynamicData ts - * @property {string|null} [appName] SphFrameDynamicData appName - */ - - /** - * Constructs a new SphFrameDynamicData. - * @exports SphFrameDynamicData - * @classdesc Represents a SphFrameDynamicData. - * @implements ISphFrameDynamicData - * @constructor - * @param {ISphFrameDynamicData=} [properties] Properties to set - */ - function SphFrameDynamicData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphFrameDynamicData id. - * @member {number} id - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.id = 0; - - /** - * SphFrameDynamicData x. - * @member {string} x - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.x = ""; - - /** - * SphFrameDynamicData y. - * @member {string} y - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.y = ""; - - /** - * SphFrameDynamicData width. - * @member {string} width - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.width = ""; - - /** - * SphFrameDynamicData height. - * @member {string} height - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.height = ""; - - /** - * SphFrameDynamicData alpha. - * @member {string} alpha - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.alpha = ""; - - /** - * SphFrameDynamicData ts. - * @member {number|Long} ts - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.ts = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameDynamicData appName. - * @member {string} appName - * @memberof SphFrameDynamicData - * @instance - */ - SphFrameDynamicData.prototype.appName = ""; - - /** - * Creates a new SphFrameDynamicData instance using the specified properties. - * @function create - * @memberof SphFrameDynamicData - * @static - * @param {ISphFrameDynamicData=} [properties] Properties to set - * @returns {SphFrameDynamicData} SphFrameDynamicData instance - */ - SphFrameDynamicData.create = function create(properties) { - return new SphFrameDynamicData(properties); - }; - - /** - * Encodes the specified SphFrameDynamicData message. Does not implicitly {@link SphFrameDynamicData.verify|verify} messages. - * @function encode - * @memberof SphFrameDynamicData - * @static - * @param {ISphFrameDynamicData} message SphFrameDynamicData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameDynamicData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.id); - if (message.x != null && Object.hasOwnProperty.call(message, "x")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.x); - if (message.y != null && Object.hasOwnProperty.call(message, "y")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.y); - if (message.width != null && Object.hasOwnProperty.call(message, "width")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.width); - if (message.height != null && Object.hasOwnProperty.call(message, "height")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message.height); - if (message.alpha != null && Object.hasOwnProperty.call(message, "alpha")) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.alpha); - if (message.ts != null && Object.hasOwnProperty.call(message, "ts")) - writer.uint32(/* id 7, wireType 0 =*/56).int64(message.ts); - if (message.appName != null && Object.hasOwnProperty.call(message, "appName")) - writer.uint32(/* id 8, wireType 2 =*/66).string(message.appName); - return writer; - }; - - /** - * Encodes the specified SphFrameDynamicData message, length delimited. Does not implicitly {@link SphFrameDynamicData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphFrameDynamicData - * @static - * @param {ISphFrameDynamicData} message SphFrameDynamicData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameDynamicData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphFrameDynamicData message from the specified reader or buffer. - * @function decode - * @memberof SphFrameDynamicData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphFrameDynamicData} SphFrameDynamicData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameDynamicData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphFrameDynamicData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int32(); - break; - } - case 2: { - message.x = reader.string(); - break; - } - case 3: { - message.y = reader.string(); - break; - } - case 4: { - message.width = reader.string(); - break; - } - case 5: { - message.height = reader.string(); - break; - } - case 6: { - message.alpha = reader.string(); - break; - } - case 7: { - message.ts = reader.int64(); - break; - } - case 8: { - message.appName = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphFrameDynamicData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphFrameDynamicData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphFrameDynamicData} SphFrameDynamicData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameDynamicData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphFrameDynamicData message. - * @function verify - * @memberof SphFrameDynamicData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphFrameDynamicData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.x != null && message.hasOwnProperty("x")) - if (!$util.isString(message.x)) - return "x: string expected"; - if (message.y != null && message.hasOwnProperty("y")) - if (!$util.isString(message.y)) - return "y: string expected"; - if (message.width != null && message.hasOwnProperty("width")) - if (!$util.isString(message.width)) - return "width: string expected"; - if (message.height != null && message.hasOwnProperty("height")) - if (!$util.isString(message.height)) - return "height: string expected"; - if (message.alpha != null && message.hasOwnProperty("alpha")) - if (!$util.isString(message.alpha)) - return "alpha: string expected"; - if (message.ts != null && message.hasOwnProperty("ts")) - if (!$util.isInteger(message.ts) && !(message.ts && $util.isInteger(message.ts.low) && $util.isInteger(message.ts.high))) - return "ts: integer|Long expected"; - if (message.appName != null && message.hasOwnProperty("appName")) - if (!$util.isString(message.appName)) - return "appName: string expected"; - return null; - }; - - /** - * Creates a SphFrameDynamicData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphFrameDynamicData - * @static - * @param {Object.} object Plain object - * @returns {SphFrameDynamicData} SphFrameDynamicData - */ - SphFrameDynamicData.fromObject = function fromObject(object) { - if (object instanceof $root.SphFrameDynamicData) - return object; - var message = new $root.SphFrameDynamicData(); - if (object.id != null) - message.id = object.id | 0; - if (object.x != null) - message.x = String(object.x); - if (object.y != null) - message.y = String(object.y); - if (object.width != null) - message.width = String(object.width); - if (object.height != null) - message.height = String(object.height); - if (object.alpha != null) - message.alpha = String(object.alpha); - if (object.ts != null) - if ($util.Long) - (message.ts = $util.Long.fromValue(object.ts)).unsigned = false; - else if (typeof object.ts === "string") - message.ts = parseInt(object.ts, 10); - else if (typeof object.ts === "number") - message.ts = object.ts; - else if (typeof object.ts === "object") - message.ts = new $util.LongBits(object.ts.low >>> 0, object.ts.high >>> 0).toNumber(); - if (object.appName != null) - message.appName = String(object.appName); - return message; - }; - - /** - * Creates a plain object from a SphFrameDynamicData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphFrameDynamicData - * @static - * @param {SphFrameDynamicData} message SphFrameDynamicData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphFrameDynamicData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.id = 0; - object.x = ""; - object.y = ""; - object.width = ""; - object.height = ""; - object.alpha = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ts = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ts = options.longs === String ? "0" : 0; - object.appName = ""; - } - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.x != null && message.hasOwnProperty("x")) - object.x = message.x; - if (message.y != null && message.hasOwnProperty("y")) - object.y = message.y; - if (message.width != null && message.hasOwnProperty("width")) - object.width = message.width; - if (message.height != null && message.hasOwnProperty("height")) - object.height = message.height; - if (message.alpha != null && message.hasOwnProperty("alpha")) - object.alpha = message.alpha; - if (message.ts != null && message.hasOwnProperty("ts")) - if (typeof message.ts === "number") - object.ts = options.longs === String ? String(message.ts) : message.ts; - else - object.ts = options.longs === String ? $util.Long.prototype.toString.call(message.ts) : options.longs === Number ? new $util.LongBits(message.ts.low >>> 0, message.ts.high >>> 0).toNumber() : message.ts; - if (message.appName != null && message.hasOwnProperty("appName")) - object.appName = message.appName; - return object; - }; - - /** - * Converts this SphFrameDynamicData to JSON. - * @function toJSON - * @memberof SphFrameDynamicData - * @instance - * @returns {Object.} JSON object - */ - SphFrameDynamicData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphFrameDynamicData - * @function getTypeUrl - * @memberof SphFrameDynamicData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphFrameDynamicData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphFrameDynamicData"; - }; - - return SphFrameDynamicData; -})(); - -$root.SphFrameSpacingData = (function () { - - /** - * Properties of a SphFrameSpacingData. - * @exports ISphFrameSpacingData - * @interface ISphFrameSpacingData - * @property {number|null} [id] SphFrameSpacingData id - * @property {string|null} [x] SphFrameSpacingData x - * @property {string|null} [y] SphFrameSpacingData y - * @property {string|null} [currentFrameWidth] SphFrameSpacingData currentFrameWidth - * @property {string|null} [currentFrameHeight] SphFrameSpacingData currentFrameHeight - * @property {number|Long|null} [currentTs] SphFrameSpacingData currentTs - * @property {string|null} [nameId] SphFrameSpacingData nameId - */ - - /** - * Constructs a new SphFrameSpacingData. - * @exports SphFrameSpacingData - * @classdesc Represents a SphFrameSpacingData. - * @implements ISphFrameSpacingData - * @constructor - * @param {ISphFrameSpacingData=} [properties] Properties to set - */ - function SphFrameSpacingData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphFrameSpacingData id. - * @member {number} id - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.id = 0; - - /** - * SphFrameSpacingData x. - * @member {string} x - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.x = ""; - - /** - * SphFrameSpacingData y. - * @member {string} y - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.y = ""; - - /** - * SphFrameSpacingData currentFrameWidth. - * @member {string} currentFrameWidth - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.currentFrameWidth = ""; - - /** - * SphFrameSpacingData currentFrameHeight. - * @member {string} currentFrameHeight - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.currentFrameHeight = ""; - - /** - * SphFrameSpacingData currentTs. - * @member {number|Long} currentTs - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.currentTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphFrameSpacingData nameId. - * @member {string} nameId - * @memberof SphFrameSpacingData - * @instance - */ - SphFrameSpacingData.prototype.nameId = ""; - - /** - * Creates a new SphFrameSpacingData instance using the specified properties. - * @function create - * @memberof SphFrameSpacingData - * @static - * @param {ISphFrameSpacingData=} [properties] Properties to set - * @returns {SphFrameSpacingData} SphFrameSpacingData instance - */ - SphFrameSpacingData.create = function create(properties) { - return new SphFrameSpacingData(properties); - }; - - /** - * Encodes the specified SphFrameSpacingData message. Does not implicitly {@link SphFrameSpacingData.verify|verify} messages. - * @function encode - * @memberof SphFrameSpacingData - * @static - * @param {ISphFrameSpacingData} message SphFrameSpacingData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameSpacingData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.id); - if (message.x != null && Object.hasOwnProperty.call(message, "x")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.x); - if (message.y != null && Object.hasOwnProperty.call(message, "y")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.y); - if (message.currentFrameWidth != null && Object.hasOwnProperty.call(message, "currentFrameWidth")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.currentFrameWidth); - if (message.currentFrameHeight != null && Object.hasOwnProperty.call(message, "currentFrameHeight")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message.currentFrameHeight); - if (message.currentTs != null && Object.hasOwnProperty.call(message, "currentTs")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.currentTs); - if (message.nameId != null && Object.hasOwnProperty.call(message, "nameId")) - writer.uint32(/* id 7, wireType 2 =*/58).string(message.nameId); - return writer; - }; - - /** - * Encodes the specified SphFrameSpacingData message, length delimited. Does not implicitly {@link SphFrameSpacingData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphFrameSpacingData - * @static - * @param {ISphFrameSpacingData} message SphFrameSpacingData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphFrameSpacingData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphFrameSpacingData message from the specified reader or buffer. - * @function decode - * @memberof SphFrameSpacingData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphFrameSpacingData} SphFrameSpacingData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameSpacingData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphFrameSpacingData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int32(); - break; - } - case 2: { - message.x = reader.string(); - break; - } - case 3: { - message.y = reader.string(); - break; - } - case 4: { - message.currentFrameWidth = reader.string(); - break; - } - case 5: { - message.currentFrameHeight = reader.string(); - break; - } - case 6: { - message.currentTs = reader.int64(); - break; - } - case 7: { - message.nameId = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphFrameSpacingData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphFrameSpacingData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphFrameSpacingData} SphFrameSpacingData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphFrameSpacingData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphFrameSpacingData message. - * @function verify - * @memberof SphFrameSpacingData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphFrameSpacingData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.x != null && message.hasOwnProperty("x")) - if (!$util.isString(message.x)) - return "x: string expected"; - if (message.y != null && message.hasOwnProperty("y")) - if (!$util.isString(message.y)) - return "y: string expected"; - if (message.currentFrameWidth != null && message.hasOwnProperty("currentFrameWidth")) - if (!$util.isString(message.currentFrameWidth)) - return "currentFrameWidth: string expected"; - if (message.currentFrameHeight != null && message.hasOwnProperty("currentFrameHeight")) - if (!$util.isString(message.currentFrameHeight)) - return "currentFrameHeight: string expected"; - if (message.currentTs != null && message.hasOwnProperty("currentTs")) - if (!$util.isInteger(message.currentTs) && !(message.currentTs && $util.isInteger(message.currentTs.low) && $util.isInteger(message.currentTs.high))) - return "currentTs: integer|Long expected"; - if (message.nameId != null && message.hasOwnProperty("nameId")) - if (!$util.isString(message.nameId)) - return "nameId: string expected"; - return null; - }; - - /** - * Creates a SphFrameSpacingData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphFrameSpacingData - * @static - * @param {Object.} object Plain object - * @returns {SphFrameSpacingData} SphFrameSpacingData - */ - SphFrameSpacingData.fromObject = function fromObject(object) { - if (object instanceof $root.SphFrameSpacingData) - return object; - var message = new $root.SphFrameSpacingData(); - if (object.id != null) - message.id = object.id | 0; - if (object.x != null) - message.x = String(object.x); - if (object.y != null) - message.y = String(object.y); - if (object.currentFrameWidth != null) - message.currentFrameWidth = String(object.currentFrameWidth); - if (object.currentFrameHeight != null) - message.currentFrameHeight = String(object.currentFrameHeight); - if (object.currentTs != null) - if ($util.Long) - (message.currentTs = $util.Long.fromValue(object.currentTs)).unsigned = false; - else if (typeof object.currentTs === "string") - message.currentTs = parseInt(object.currentTs, 10); - else if (typeof object.currentTs === "number") - message.currentTs = object.currentTs; - else if (typeof object.currentTs === "object") - message.currentTs = new $util.LongBits(object.currentTs.low >>> 0, object.currentTs.high >>> 0).toNumber(); - if (object.nameId != null) - message.nameId = String(object.nameId); - return message; - }; - - /** - * Creates a plain object from a SphFrameSpacingData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphFrameSpacingData - * @static - * @param {SphFrameSpacingData} message SphFrameSpacingData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphFrameSpacingData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.id = 0; - object.x = ""; - object.y = ""; - object.currentFrameWidth = ""; - object.currentFrameHeight = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.currentTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.currentTs = options.longs === String ? "0" : 0; - object.nameId = ""; - } - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.x != null && message.hasOwnProperty("x")) - object.x = message.x; - if (message.y != null && message.hasOwnProperty("y")) - object.y = message.y; - if (message.currentFrameWidth != null && message.hasOwnProperty("currentFrameWidth")) - object.currentFrameWidth = message.currentFrameWidth; - if (message.currentFrameHeight != null && message.hasOwnProperty("currentFrameHeight")) - object.currentFrameHeight = message.currentFrameHeight; - if (message.currentTs != null && message.hasOwnProperty("currentTs")) - if (typeof message.currentTs === "number") - object.currentTs = options.longs === String ? String(message.currentTs) : message.currentTs; - else - object.currentTs = options.longs === String ? $util.Long.prototype.toString.call(message.currentTs) : options.longs === Number ? new $util.LongBits(message.currentTs.low >>> 0, message.currentTs.high >>> 0).toNumber() : message.currentTs; - if (message.nameId != null && message.hasOwnProperty("nameId")) - object.nameId = message.nameId; - return object; - }; - - /** - * Converts this SphFrameSpacingData to JSON. - * @function toJSON - * @memberof SphFrameSpacingData - * @instance - * @returns {Object.} JSON object - */ - SphFrameSpacingData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphFrameSpacingData - * @function getTypeUrl - * @memberof SphFrameSpacingData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphFrameSpacingData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphFrameSpacingData"; - }; - - return SphFrameSpacingData; -})(); - -$root.SphEbpfData = (function () { - - /** - * Properties of a SphEbpfData. - * @exports ISphEbpfData - * @interface ISphEbpfData - * @property {number|Long|null} [startNs] SphEbpfData startNs - * @property {number|Long|null} [endNs] SphEbpfData endNs - * @property {number|Long|null} [dur] SphEbpfData dur - * @property {number|Long|null} [size] SphEbpfData size - */ - - /** - * Constructs a new SphEbpfData. - * @exports SphEbpfData - * @classdesc Represents a SphEbpfData. - * @implements ISphEbpfData - * @constructor - * @param {ISphEbpfData=} [properties] Properties to set - */ - function SphEbpfData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphEbpfData startNs. - * @member {number|Long} startNs - * @memberof SphEbpfData - * @instance - */ - SphEbpfData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphEbpfData endNs. - * @member {number|Long} endNs - * @memberof SphEbpfData - * @instance - */ - SphEbpfData.prototype.endNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphEbpfData dur. - * @member {number|Long} dur - * @memberof SphEbpfData - * @instance - */ - SphEbpfData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphEbpfData size. - * @member {number|Long} size - * @memberof SphEbpfData - * @instance - */ - SphEbpfData.prototype.size = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphEbpfData instance using the specified properties. - * @function create - * @memberof SphEbpfData - * @static - * @param {ISphEbpfData=} [properties] Properties to set - * @returns {SphEbpfData} SphEbpfData instance - */ - SphEbpfData.create = function create(properties) { - return new SphEbpfData(properties); - }; - - /** - * Encodes the specified SphEbpfData message. Does not implicitly {@link SphEbpfData.verify|verify} messages. - * @function encode - * @memberof SphEbpfData - * @static - * @param {ISphEbpfData} message SphEbpfData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphEbpfData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startNs); - if (message.endNs != null && Object.hasOwnProperty.call(message, "endNs")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.endNs); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.dur); - if (message.size != null && Object.hasOwnProperty.call(message, "size")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.size); - return writer; - }; - - /** - * Encodes the specified SphEbpfData message, length delimited. Does not implicitly {@link SphEbpfData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphEbpfData - * @static - * @param {ISphEbpfData} message SphEbpfData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphEbpfData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphEbpfData message from the specified reader or buffer. - * @function decode - * @memberof SphEbpfData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphEbpfData} SphEbpfData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphEbpfData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphEbpfData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startNs = reader.int64(); - break; - } - case 2: { - message.endNs = reader.int64(); - break; - } - case 3: { - message.dur = reader.int64(); - break; - } - case 4: { - message.size = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphEbpfData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphEbpfData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphEbpfData} SphEbpfData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphEbpfData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphEbpfData message. - * @function verify - * @memberof SphEbpfData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphEbpfData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.endNs != null && message.hasOwnProperty("endNs")) - if (!$util.isInteger(message.endNs) && !(message.endNs && $util.isInteger(message.endNs.low) && $util.isInteger(message.endNs.high))) - return "endNs: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.size != null && message.hasOwnProperty("size")) - if (!$util.isInteger(message.size) && !(message.size && $util.isInteger(message.size.low) && $util.isInteger(message.size.high))) - return "size: integer|Long expected"; - return null; - }; - - /** - * Creates a SphEbpfData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphEbpfData - * @static - * @param {Object.} object Plain object - * @returns {SphEbpfData} SphEbpfData - */ - SphEbpfData.fromObject = function fromObject(object) { - if (object instanceof $root.SphEbpfData) - return object; - var message = new $root.SphEbpfData(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.endNs != null) - if ($util.Long) - (message.endNs = $util.Long.fromValue(object.endNs)).unsigned = false; - else if (typeof object.endNs === "string") - message.endNs = parseInt(object.endNs, 10); - else if (typeof object.endNs === "number") - message.endNs = object.endNs; - else if (typeof object.endNs === "object") - message.endNs = new $util.LongBits(object.endNs.low >>> 0, object.endNs.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.size != null) - if ($util.Long) - (message.size = $util.Long.fromValue(object.size)).unsigned = false; - else if (typeof object.size === "string") - message.size = parseInt(object.size, 10); - else if (typeof object.size === "number") - message.size = object.size; - else if (typeof object.size === "object") - message.size = new $util.LongBits(object.size.low >>> 0, object.size.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphEbpfData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphEbpfData - * @static - * @param {SphEbpfData} message SphEbpfData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphEbpfData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.endNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.endNs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.size = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.size = options.longs === String ? "0" : 0; - } - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.endNs != null && message.hasOwnProperty("endNs")) - if (typeof message.endNs === "number") - object.endNs = options.longs === String ? String(message.endNs) : message.endNs; - else - object.endNs = options.longs === String ? $util.Long.prototype.toString.call(message.endNs) : options.longs === Number ? new $util.LongBits(message.endNs.low >>> 0, message.endNs.high >>> 0).toNumber() : message.endNs; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.size != null && message.hasOwnProperty("size")) - if (typeof message.size === "number") - object.size = options.longs === String ? String(message.size) : message.size; - else - object.size = options.longs === String ? $util.Long.prototype.toString.call(message.size) : options.longs === Number ? new $util.LongBits(message.size.low >>> 0, message.size.high >>> 0).toNumber() : message.size; - return object; - }; - - /** - * Converts this SphEbpfData to JSON. - * @function toJSON - * @memberof SphEbpfData - * @instance - * @returns {Object.} JSON object - */ - SphEbpfData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphEbpfData - * @function getTypeUrl - * @memberof SphEbpfData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphEbpfData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphEbpfData"; - }; - - return SphEbpfData; -})(); - -$root.SphTrackerData = (function () { - - /** - * Properties of a SphTrackerData. - * @exports ISphTrackerData - * @interface ISphTrackerData - * @property {number|Long|null} [startNs] SphTrackerData startNs - * @property {number|Long|null} [value] SphTrackerData value - */ - - /** - * Constructs a new SphTrackerData. - * @exports SphTrackerData - * @classdesc Represents a SphTrackerData. - * @implements ISphTrackerData - * @constructor - * @param {ISphTrackerData=} [properties] Properties to set - */ - function SphTrackerData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphTrackerData startNs. - * @member {number|Long} startNs - * @memberof SphTrackerData - * @instance - */ - SphTrackerData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphTrackerData value. - * @member {number|Long} value - * @memberof SphTrackerData - * @instance - */ - SphTrackerData.prototype.value = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphTrackerData instance using the specified properties. - * @function create - * @memberof SphTrackerData - * @static - * @param {ISphTrackerData=} [properties] Properties to set - * @returns {SphTrackerData} SphTrackerData instance - */ - SphTrackerData.create = function create(properties) { - return new SphTrackerData(properties); - }; - - /** - * Encodes the specified SphTrackerData message. Does not implicitly {@link SphTrackerData.verify|verify} messages. - * @function encode - * @memberof SphTrackerData - * @static - * @param {ISphTrackerData} message SphTrackerData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphTrackerData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startNs); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.value); - return writer; - }; - - /** - * Encodes the specified SphTrackerData message, length delimited. Does not implicitly {@link SphTrackerData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphTrackerData - * @static - * @param {ISphTrackerData} message SphTrackerData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphTrackerData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphTrackerData message from the specified reader or buffer. - * @function decode - * @memberof SphTrackerData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphTrackerData} SphTrackerData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphTrackerData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphTrackerData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startNs = reader.int64(); - break; - } - case 2: { - message.value = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphTrackerData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphTrackerData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphTrackerData} SphTrackerData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphTrackerData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphTrackerData message. - * @function verify - * @memberof SphTrackerData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphTrackerData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value) && !(message.value && $util.isInteger(message.value.low) && $util.isInteger(message.value.high))) - return "value: integer|Long expected"; - return null; - }; - - /** - * Creates a SphTrackerData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphTrackerData - * @static - * @param {Object.} object Plain object - * @returns {SphTrackerData} SphTrackerData - */ - SphTrackerData.fromObject = function fromObject(object) { - if (object instanceof $root.SphTrackerData) - return object; - var message = new $root.SphTrackerData(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = false; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphTrackerData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphTrackerData - * @static - * @param {SphTrackerData} message SphTrackerData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphTrackerData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - } - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; - return object; - }; - - /** - * Converts this SphTrackerData to JSON. - * @function toJSON - * @memberof SphTrackerData - * @instance - * @returns {Object.} JSON object - */ - SphTrackerData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphTrackerData - * @function getTypeUrl - * @memberof SphTrackerData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphTrackerData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphTrackerData"; - }; - - return SphTrackerData; -})(); - -$root.SphAbilityData = (function () { - - /** - * Properties of a SphAbilityData. - * @exports ISphAbilityData - * @interface ISphAbilityData - * @property {number|Long|null} [value] SphAbilityData value - * @property {number|Long|null} [startNs] SphAbilityData startNs - * @property {number|null} [dur] SphAbilityData dur - */ - - /** - * Constructs a new SphAbilityData. - * @exports SphAbilityData - * @classdesc Represents a SphAbilityData. - * @implements ISphAbilityData - * @constructor - * @param {ISphAbilityData=} [properties] Properties to set - */ - function SphAbilityData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphAbilityData value. - * @member {number|Long} value - * @memberof SphAbilityData - * @instance - */ - SphAbilityData.prototype.value = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphAbilityData startNs. - * @member {number|Long} startNs - * @memberof SphAbilityData - * @instance - */ - SphAbilityData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphAbilityData dur. - * @member {number} dur - * @memberof SphAbilityData - * @instance - */ - SphAbilityData.prototype.dur = 0; - - /** - * Creates a new SphAbilityData instance using the specified properties. - * @function create - * @memberof SphAbilityData - * @static - * @param {ISphAbilityData=} [properties] Properties to set - * @returns {SphAbilityData} SphAbilityData instance - */ - SphAbilityData.create = function create(properties) { - return new SphAbilityData(properties); - }; - - /** - * Encodes the specified SphAbilityData message. Does not implicitly {@link SphAbilityData.verify|verify} messages. - * @function encode - * @memberof SphAbilityData - * @static - * @param {ISphAbilityData} message SphAbilityData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphAbilityData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.value); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.startNs); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.dur); - return writer; - }; - - /** - * Encodes the specified SphAbilityData message, length delimited. Does not implicitly {@link SphAbilityData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphAbilityData - * @static - * @param {ISphAbilityData} message SphAbilityData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphAbilityData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphAbilityData message from the specified reader or buffer. - * @function decode - * @memberof SphAbilityData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphAbilityData} SphAbilityData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphAbilityData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphAbilityData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.value = reader.int64(); - break; - } - case 2: { - message.startNs = reader.int64(); - break; - } - case 3: { - message.dur = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphAbilityData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphAbilityData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphAbilityData} SphAbilityData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphAbilityData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphAbilityData message. - * @function verify - * @memberof SphAbilityData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphAbilityData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isInteger(message.value) && !(message.value && $util.isInteger(message.value.low) && $util.isInteger(message.value.high))) - return "value: integer|Long expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur)) - return "dur: integer expected"; - return null; - }; - - /** - * Creates a SphAbilityData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphAbilityData - * @static - * @param {Object.} object Plain object - * @returns {SphAbilityData} SphAbilityData - */ - SphAbilityData.fromObject = function fromObject(object) { - if (object instanceof $root.SphAbilityData) - return object; - var message = new $root.SphAbilityData(); - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = false; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.dur != null) - message.dur = object.dur | 0; - return message; - }; - - /** - * Creates a plain object from a SphAbilityData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphAbilityData - * @static - * @param {SphAbilityData} message SphAbilityData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphAbilityData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - object.dur = 0; - } - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.dur != null && message.hasOwnProperty("dur")) - object.dur = message.dur; - return object; - }; - - /** - * Converts this SphAbilityData to JSON. - * @function toJSON - * @memberof SphAbilityData - * @instance - * @returns {Object.} JSON object - */ - SphAbilityData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphAbilityData - * @function getTypeUrl - * @memberof SphAbilityData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphAbilityData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphAbilityData"; - }; - - return SphAbilityData; -})(); - -$root.SphHiperfData = (function () { - - /** - * Properties of a SphHiperfData. - * @exports ISphHiperfData - * @interface ISphHiperfData - * @property {number|Long|null} [startNs] SphHiperfData startNs - * @property {number|Long|null} [eventCount] SphHiperfData eventCount - * @property {number|Long|null} [sampleCount] SphHiperfData sampleCount - * @property {number|Long|null} [eventTypeId] SphHiperfData eventTypeId - * @property {number|Long|null} [callchainId] SphHiperfData callchainId - */ - - /** - * Constructs a new SphHiperfData. - * @exports SphHiperfData - * @classdesc Represents a SphHiperfData. - * @implements ISphHiperfData - * @constructor - * @param {ISphHiperfData=} [properties] Properties to set - */ - function SphHiperfData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphHiperfData startNs. - * @member {number|Long} startNs - * @memberof SphHiperfData - * @instance - */ - SphHiperfData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfData eventCount. - * @member {number|Long} eventCount - * @memberof SphHiperfData - * @instance - */ - SphHiperfData.prototype.eventCount = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfData sampleCount. - * @member {number|Long} sampleCount - * @memberof SphHiperfData - * @instance - */ - SphHiperfData.prototype.sampleCount = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfData eventTypeId. - * @member {number|Long} eventTypeId - * @memberof SphHiperfData - * @instance - */ - SphHiperfData.prototype.eventTypeId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfData callchainId. - * @member {number|Long} callchainId - * @memberof SphHiperfData - * @instance - */ - SphHiperfData.prototype.callchainId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphHiperfData instance using the specified properties. - * @function create - * @memberof SphHiperfData - * @static - * @param {ISphHiperfData=} [properties] Properties to set - * @returns {SphHiperfData} SphHiperfData instance - */ - SphHiperfData.create = function create(properties) { - return new SphHiperfData(properties); - }; - - /** - * Encodes the specified SphHiperfData message. Does not implicitly {@link SphHiperfData.verify|verify} messages. - * @function encode - * @memberof SphHiperfData - * @static - * @param {ISphHiperfData} message SphHiperfData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiperfData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startNs); - if (message.eventCount != null && Object.hasOwnProperty.call(message, "eventCount")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.eventCount); - if (message.sampleCount != null && Object.hasOwnProperty.call(message, "sampleCount")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.sampleCount); - if (message.eventTypeId != null && Object.hasOwnProperty.call(message, "eventTypeId")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.eventTypeId); - if (message.callchainId != null && Object.hasOwnProperty.call(message, "callchainId")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.callchainId); - return writer; - }; - - /** - * Encodes the specified SphHiperfData message, length delimited. Does not implicitly {@link SphHiperfData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphHiperfData - * @static - * @param {ISphHiperfData} message SphHiperfData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiperfData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphHiperfData message from the specified reader or buffer. - * @function decode - * @memberof SphHiperfData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphHiperfData} SphHiperfData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiperfData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphHiperfData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startNs = reader.int64(); - break; - } - case 2: { - message.eventCount = reader.int64(); - break; - } - case 3: { - message.sampleCount = reader.int64(); - break; - } - case 4: { - message.eventTypeId = reader.int64(); - break; - } - case 5: { - message.callchainId = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphHiperfData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphHiperfData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphHiperfData} SphHiperfData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiperfData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphHiperfData message. - * @function verify - * @memberof SphHiperfData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphHiperfData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.eventCount != null && message.hasOwnProperty("eventCount")) - if (!$util.isInteger(message.eventCount) && !(message.eventCount && $util.isInteger(message.eventCount.low) && $util.isInteger(message.eventCount.high))) - return "eventCount: integer|Long expected"; - if (message.sampleCount != null && message.hasOwnProperty("sampleCount")) - if (!$util.isInteger(message.sampleCount) && !(message.sampleCount && $util.isInteger(message.sampleCount.low) && $util.isInteger(message.sampleCount.high))) - return "sampleCount: integer|Long expected"; - if (message.eventTypeId != null && message.hasOwnProperty("eventTypeId")) - if (!$util.isInteger(message.eventTypeId) && !(message.eventTypeId && $util.isInteger(message.eventTypeId.low) && $util.isInteger(message.eventTypeId.high))) - return "eventTypeId: integer|Long expected"; - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (!$util.isInteger(message.callchainId) && !(message.callchainId && $util.isInteger(message.callchainId.low) && $util.isInteger(message.callchainId.high))) - return "callchainId: integer|Long expected"; - return null; - }; - - /** - * Creates a SphHiperfData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphHiperfData - * @static - * @param {Object.} object Plain object - * @returns {SphHiperfData} SphHiperfData - */ - SphHiperfData.fromObject = function fromObject(object) { - if (object instanceof $root.SphHiperfData) - return object; - var message = new $root.SphHiperfData(); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.eventCount != null) - if ($util.Long) - (message.eventCount = $util.Long.fromValue(object.eventCount)).unsigned = false; - else if (typeof object.eventCount === "string") - message.eventCount = parseInt(object.eventCount, 10); - else if (typeof object.eventCount === "number") - message.eventCount = object.eventCount; - else if (typeof object.eventCount === "object") - message.eventCount = new $util.LongBits(object.eventCount.low >>> 0, object.eventCount.high >>> 0).toNumber(); - if (object.sampleCount != null) - if ($util.Long) - (message.sampleCount = $util.Long.fromValue(object.sampleCount)).unsigned = false; - else if (typeof object.sampleCount === "string") - message.sampleCount = parseInt(object.sampleCount, 10); - else if (typeof object.sampleCount === "number") - message.sampleCount = object.sampleCount; - else if (typeof object.sampleCount === "object") - message.sampleCount = new $util.LongBits(object.sampleCount.low >>> 0, object.sampleCount.high >>> 0).toNumber(); - if (object.eventTypeId != null) - if ($util.Long) - (message.eventTypeId = $util.Long.fromValue(object.eventTypeId)).unsigned = false; - else if (typeof object.eventTypeId === "string") - message.eventTypeId = parseInt(object.eventTypeId, 10); - else if (typeof object.eventTypeId === "number") - message.eventTypeId = object.eventTypeId; - else if (typeof object.eventTypeId === "object") - message.eventTypeId = new $util.LongBits(object.eventTypeId.low >>> 0, object.eventTypeId.high >>> 0).toNumber(); - if (object.callchainId != null) - if ($util.Long) - (message.callchainId = $util.Long.fromValue(object.callchainId)).unsigned = false; - else if (typeof object.callchainId === "string") - message.callchainId = parseInt(object.callchainId, 10); - else if (typeof object.callchainId === "number") - message.callchainId = object.callchainId; - else if (typeof object.callchainId === "object") - message.callchainId = new $util.LongBits(object.callchainId.low >>> 0, object.callchainId.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphHiperfData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphHiperfData - * @static - * @param {SphHiperfData} message SphHiperfData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphHiperfData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.eventCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.eventCount = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.sampleCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.sampleCount = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.eventTypeId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.eventTypeId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.callchainId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.callchainId = options.longs === String ? "0" : 0; - } - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.eventCount != null && message.hasOwnProperty("eventCount")) - if (typeof message.eventCount === "number") - object.eventCount = options.longs === String ? String(message.eventCount) : message.eventCount; - else - object.eventCount = options.longs === String ? $util.Long.prototype.toString.call(message.eventCount) : options.longs === Number ? new $util.LongBits(message.eventCount.low >>> 0, message.eventCount.high >>> 0).toNumber() : message.eventCount; - if (message.sampleCount != null && message.hasOwnProperty("sampleCount")) - if (typeof message.sampleCount === "number") - object.sampleCount = options.longs === String ? String(message.sampleCount) : message.sampleCount; - else - object.sampleCount = options.longs === String ? $util.Long.prototype.toString.call(message.sampleCount) : options.longs === Number ? new $util.LongBits(message.sampleCount.low >>> 0, message.sampleCount.high >>> 0).toNumber() : message.sampleCount; - if (message.eventTypeId != null && message.hasOwnProperty("eventTypeId")) - if (typeof message.eventTypeId === "number") - object.eventTypeId = options.longs === String ? String(message.eventTypeId) : message.eventTypeId; - else - object.eventTypeId = options.longs === String ? $util.Long.prototype.toString.call(message.eventTypeId) : options.longs === Number ? new $util.LongBits(message.eventTypeId.low >>> 0, message.eventTypeId.high >>> 0).toNumber() : message.eventTypeId; - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (typeof message.callchainId === "number") - object.callchainId = options.longs === String ? String(message.callchainId) : message.callchainId; - else - object.callchainId = options.longs === String ? $util.Long.prototype.toString.call(message.callchainId) : options.longs === Number ? new $util.LongBits(message.callchainId.low >>> 0, message.callchainId.high >>> 0).toNumber() : message.callchainId; - return object; - }; - - /** - * Converts this SphHiperfData to JSON. - * @function toJSON - * @memberof SphHiperfData - * @instance - * @returns {Object.} JSON object - */ - SphHiperfData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphHiperfData - * @function getTypeUrl - * @memberof SphHiperfData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphHiperfData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphHiperfData"; - }; - - return SphHiperfData; -})(); - -$root.SphHiperfCallChartData = (function () { - - /** - * Properties of a SphHiperfCallChartData. - * @exports ISphHiperfCallChartData - * @interface ISphHiperfCallChartData - * @property {number|Long|null} [callchainId] SphHiperfCallChartData callchainId - * @property {number|Long|null} [startTs] SphHiperfCallChartData startTs - * @property {number|Long|null} [eventCount] SphHiperfCallChartData eventCount - * @property {number|Long|null} [threadId] SphHiperfCallChartData threadId - * @property {number|Long|null} [cpuId] SphHiperfCallChartData cpuId - * @property {number|Long|null} [eventTypeId] SphHiperfCallChartData eventTypeId - */ - - /** - * Constructs a new SphHiperfCallChartData. - * @exports SphHiperfCallChartData - * @classdesc Represents a SphHiperfCallChartData. - * @implements ISphHiperfCallChartData - * @constructor - * @param {ISphHiperfCallChartData=} [properties] Properties to set - */ - function SphHiperfCallChartData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphHiperfCallChartData callchainId. - * @member {number|Long} callchainId - * @memberof SphHiperfCallChartData - * @instance - */ - SphHiperfCallChartData.prototype.callchainId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallChartData startTs. - * @member {number|Long} startTs - * @memberof SphHiperfCallChartData - * @instance - */ - SphHiperfCallChartData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallChartData eventCount. - * @member {number|Long} eventCount - * @memberof SphHiperfCallChartData - * @instance - */ - SphHiperfCallChartData.prototype.eventCount = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallChartData threadId. - * @member {number|Long} threadId - * @memberof SphHiperfCallChartData - * @instance - */ - SphHiperfCallChartData.prototype.threadId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallChartData cpuId. - * @member {number|Long} cpuId - * @memberof SphHiperfCallChartData - * @instance - */ - SphHiperfCallChartData.prototype.cpuId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallChartData eventTypeId. - * @member {number|Long} eventTypeId - * @memberof SphHiperfCallChartData - * @instance - */ - SphHiperfCallChartData.prototype.eventTypeId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphHiperfCallChartData instance using the specified properties. - * @function create - * @memberof SphHiperfCallChartData - * @static - * @param {ISphHiperfCallChartData=} [properties] Properties to set - * @returns {SphHiperfCallChartData} SphHiperfCallChartData instance - */ - SphHiperfCallChartData.create = function create(properties) { - return new SphHiperfCallChartData(properties); - }; - - /** - * Encodes the specified SphHiperfCallChartData message. Does not implicitly {@link SphHiperfCallChartData.verify|verify} messages. - * @function encode - * @memberof SphHiperfCallChartData - * @static - * @param {ISphHiperfCallChartData} message SphHiperfCallChartData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiperfCallChartData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.callchainId != null && Object.hasOwnProperty.call(message, "callchainId")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.callchainId); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.startTs); - if (message.eventCount != null && Object.hasOwnProperty.call(message, "eventCount")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.eventCount); - if (message.threadId != null && Object.hasOwnProperty.call(message, "threadId")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.threadId); - if (message.cpuId != null && Object.hasOwnProperty.call(message, "cpuId")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.cpuId); - if (message.eventTypeId != null && Object.hasOwnProperty.call(message, "eventTypeId")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.eventTypeId); - return writer; - }; - - /** - * Encodes the specified SphHiperfCallChartData message, length delimited. Does not implicitly {@link SphHiperfCallChartData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphHiperfCallChartData - * @static - * @param {ISphHiperfCallChartData} message SphHiperfCallChartData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiperfCallChartData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphHiperfCallChartData message from the specified reader or buffer. - * @function decode - * @memberof SphHiperfCallChartData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphHiperfCallChartData} SphHiperfCallChartData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiperfCallChartData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphHiperfCallChartData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.callchainId = reader.int64(); - break; - } - case 2: { - message.startTs = reader.int64(); - break; - } - case 3: { - message.eventCount = reader.int64(); - break; - } - case 4: { - message.threadId = reader.int64(); - break; - } - case 5: { - message.cpuId = reader.int64(); - break; - } - case 6: { - message.eventTypeId = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphHiperfCallChartData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphHiperfCallChartData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphHiperfCallChartData} SphHiperfCallChartData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiperfCallChartData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphHiperfCallChartData message. - * @function verify - * @memberof SphHiperfCallChartData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphHiperfCallChartData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (!$util.isInteger(message.callchainId) && !(message.callchainId && $util.isInteger(message.callchainId.low) && $util.isInteger(message.callchainId.high))) - return "callchainId: integer|Long expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.eventCount != null && message.hasOwnProperty("eventCount")) - if (!$util.isInteger(message.eventCount) && !(message.eventCount && $util.isInteger(message.eventCount.low) && $util.isInteger(message.eventCount.high))) - return "eventCount: integer|Long expected"; - if (message.threadId != null && message.hasOwnProperty("threadId")) - if (!$util.isInteger(message.threadId) && !(message.threadId && $util.isInteger(message.threadId.low) && $util.isInteger(message.threadId.high))) - return "threadId: integer|Long expected"; - if (message.cpuId != null && message.hasOwnProperty("cpuId")) - if (!$util.isInteger(message.cpuId) && !(message.cpuId && $util.isInteger(message.cpuId.low) && $util.isInteger(message.cpuId.high))) - return "cpuId: integer|Long expected"; - if (message.eventTypeId != null && message.hasOwnProperty("eventTypeId")) - if (!$util.isInteger(message.eventTypeId) && !(message.eventTypeId && $util.isInteger(message.eventTypeId.low) && $util.isInteger(message.eventTypeId.high))) - return "eventTypeId: integer|Long expected"; - return null; - }; - - /** - * Creates a SphHiperfCallChartData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphHiperfCallChartData - * @static - * @param {Object.} object Plain object - * @returns {SphHiperfCallChartData} SphHiperfCallChartData - */ - SphHiperfCallChartData.fromObject = function fromObject(object) { - if (object instanceof $root.SphHiperfCallChartData) - return object; - var message = new $root.SphHiperfCallChartData(); - if (object.callchainId != null) - if ($util.Long) - (message.callchainId = $util.Long.fromValue(object.callchainId)).unsigned = false; - else if (typeof object.callchainId === "string") - message.callchainId = parseInt(object.callchainId, 10); - else if (typeof object.callchainId === "number") - message.callchainId = object.callchainId; - else if (typeof object.callchainId === "object") - message.callchainId = new $util.LongBits(object.callchainId.low >>> 0, object.callchainId.high >>> 0).toNumber(); - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.eventCount != null) - if ($util.Long) - (message.eventCount = $util.Long.fromValue(object.eventCount)).unsigned = false; - else if (typeof object.eventCount === "string") - message.eventCount = parseInt(object.eventCount, 10); - else if (typeof object.eventCount === "number") - message.eventCount = object.eventCount; - else if (typeof object.eventCount === "object") - message.eventCount = new $util.LongBits(object.eventCount.low >>> 0, object.eventCount.high >>> 0).toNumber(); - if (object.threadId != null) - if ($util.Long) - (message.threadId = $util.Long.fromValue(object.threadId)).unsigned = false; - else if (typeof object.threadId === "string") - message.threadId = parseInt(object.threadId, 10); - else if (typeof object.threadId === "number") - message.threadId = object.threadId; - else if (typeof object.threadId === "object") - message.threadId = new $util.LongBits(object.threadId.low >>> 0, object.threadId.high >>> 0).toNumber(); - if (object.cpuId != null) - if ($util.Long) - (message.cpuId = $util.Long.fromValue(object.cpuId)).unsigned = false; - else if (typeof object.cpuId === "string") - message.cpuId = parseInt(object.cpuId, 10); - else if (typeof object.cpuId === "number") - message.cpuId = object.cpuId; - else if (typeof object.cpuId === "object") - message.cpuId = new $util.LongBits(object.cpuId.low >>> 0, object.cpuId.high >>> 0).toNumber(); - if (object.eventTypeId != null) - if ($util.Long) - (message.eventTypeId = $util.Long.fromValue(object.eventTypeId)).unsigned = false; - else if (typeof object.eventTypeId === "string") - message.eventTypeId = parseInt(object.eventTypeId, 10); - else if (typeof object.eventTypeId === "number") - message.eventTypeId = object.eventTypeId; - else if (typeof object.eventTypeId === "object") - message.eventTypeId = new $util.LongBits(object.eventTypeId.low >>> 0, object.eventTypeId.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphHiperfCallChartData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphHiperfCallChartData - * @static - * @param {SphHiperfCallChartData} message SphHiperfCallChartData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphHiperfCallChartData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.callchainId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.callchainId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.eventCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.eventCount = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.threadId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.threadId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.cpuId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.cpuId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.eventTypeId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.eventTypeId = options.longs === String ? "0" : 0; - } - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (typeof message.callchainId === "number") - object.callchainId = options.longs === String ? String(message.callchainId) : message.callchainId; - else - object.callchainId = options.longs === String ? $util.Long.prototype.toString.call(message.callchainId) : options.longs === Number ? new $util.LongBits(message.callchainId.low >>> 0, message.callchainId.high >>> 0).toNumber() : message.callchainId; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.eventCount != null && message.hasOwnProperty("eventCount")) - if (typeof message.eventCount === "number") - object.eventCount = options.longs === String ? String(message.eventCount) : message.eventCount; - else - object.eventCount = options.longs === String ? $util.Long.prototype.toString.call(message.eventCount) : options.longs === Number ? new $util.LongBits(message.eventCount.low >>> 0, message.eventCount.high >>> 0).toNumber() : message.eventCount; - if (message.threadId != null && message.hasOwnProperty("threadId")) - if (typeof message.threadId === "number") - object.threadId = options.longs === String ? String(message.threadId) : message.threadId; - else - object.threadId = options.longs === String ? $util.Long.prototype.toString.call(message.threadId) : options.longs === Number ? new $util.LongBits(message.threadId.low >>> 0, message.threadId.high >>> 0).toNumber() : message.threadId; - if (message.cpuId != null && message.hasOwnProperty("cpuId")) - if (typeof message.cpuId === "number") - object.cpuId = options.longs === String ? String(message.cpuId) : message.cpuId; - else - object.cpuId = options.longs === String ? $util.Long.prototype.toString.call(message.cpuId) : options.longs === Number ? new $util.LongBits(message.cpuId.low >>> 0, message.cpuId.high >>> 0).toNumber() : message.cpuId; - if (message.eventTypeId != null && message.hasOwnProperty("eventTypeId")) - if (typeof message.eventTypeId === "number") - object.eventTypeId = options.longs === String ? String(message.eventTypeId) : message.eventTypeId; - else - object.eventTypeId = options.longs === String ? $util.Long.prototype.toString.call(message.eventTypeId) : options.longs === Number ? new $util.LongBits(message.eventTypeId.low >>> 0, message.eventTypeId.high >>> 0).toNumber() : message.eventTypeId; - return object; - }; - - /** - * Converts this SphHiperfCallChartData to JSON. - * @function toJSON - * @memberof SphHiperfCallChartData - * @instance - * @returns {Object.} JSON object - */ - SphHiperfCallChartData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphHiperfCallChartData - * @function getTypeUrl - * @memberof SphHiperfCallChartData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphHiperfCallChartData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphHiperfCallChartData"; - }; - - return SphHiperfCallChartData; -})(); - -$root.SphHiperfCallStackData = (function () { - - /** - * Properties of a SphHiperfCallStackData. - * @exports ISphHiperfCallStackData - * @interface ISphHiperfCallStackData - * @property {number|Long|null} [callchainId] SphHiperfCallStackData callchainId - * @property {number|Long|null} [fileId] SphHiperfCallStackData fileId - * @property {number|Long|null} [depth] SphHiperfCallStackData depth - * @property {number|Long|null} [symbolId] SphHiperfCallStackData symbolId - * @property {number|Long|null} [name] SphHiperfCallStackData name - */ - - /** - * Constructs a new SphHiperfCallStackData. - * @exports SphHiperfCallStackData - * @classdesc Represents a SphHiperfCallStackData. - * @implements ISphHiperfCallStackData - * @constructor - * @param {ISphHiperfCallStackData=} [properties] Properties to set - */ - function SphHiperfCallStackData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphHiperfCallStackData callchainId. - * @member {number|Long} callchainId - * @memberof SphHiperfCallStackData - * @instance - */ - SphHiperfCallStackData.prototype.callchainId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallStackData fileId. - * @member {number|Long} fileId - * @memberof SphHiperfCallStackData - * @instance - */ - SphHiperfCallStackData.prototype.fileId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallStackData depth. - * @member {number|Long} depth - * @memberof SphHiperfCallStackData - * @instance - */ - SphHiperfCallStackData.prototype.depth = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallStackData symbolId. - * @member {number|Long} symbolId - * @memberof SphHiperfCallStackData - * @instance - */ - SphHiperfCallStackData.prototype.symbolId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHiperfCallStackData name. - * @member {number|Long} name - * @memberof SphHiperfCallStackData - * @instance - */ - SphHiperfCallStackData.prototype.name = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphHiperfCallStackData instance using the specified properties. - * @function create - * @memberof SphHiperfCallStackData - * @static - * @param {ISphHiperfCallStackData=} [properties] Properties to set - * @returns {SphHiperfCallStackData} SphHiperfCallStackData instance - */ - SphHiperfCallStackData.create = function create(properties) { - return new SphHiperfCallStackData(properties); - }; - - /** - * Encodes the specified SphHiperfCallStackData message. Does not implicitly {@link SphHiperfCallStackData.verify|verify} messages. - * @function encode - * @memberof SphHiperfCallStackData - * @static - * @param {ISphHiperfCallStackData} message SphHiperfCallStackData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiperfCallStackData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.callchainId != null && Object.hasOwnProperty.call(message, "callchainId")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.callchainId); - if (message.fileId != null && Object.hasOwnProperty.call(message, "fileId")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.fileId); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.depth); - if (message.symbolId != null && Object.hasOwnProperty.call(message, "symbolId")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.symbolId); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.name); - return writer; - }; - - /** - * Encodes the specified SphHiperfCallStackData message, length delimited. Does not implicitly {@link SphHiperfCallStackData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphHiperfCallStackData - * @static - * @param {ISphHiperfCallStackData} message SphHiperfCallStackData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHiperfCallStackData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphHiperfCallStackData message from the specified reader or buffer. - * @function decode - * @memberof SphHiperfCallStackData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphHiperfCallStackData} SphHiperfCallStackData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiperfCallStackData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphHiperfCallStackData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.callchainId = reader.int64(); - break; - } - case 2: { - message.fileId = reader.int64(); - break; - } - case 3: { - message.depth = reader.int64(); - break; - } - case 4: { - message.symbolId = reader.int64(); - break; - } - case 5: { - message.name = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphHiperfCallStackData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphHiperfCallStackData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphHiperfCallStackData} SphHiperfCallStackData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHiperfCallStackData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphHiperfCallStackData message. - * @function verify - * @memberof SphHiperfCallStackData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphHiperfCallStackData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (!$util.isInteger(message.callchainId) && !(message.callchainId && $util.isInteger(message.callchainId.low) && $util.isInteger(message.callchainId.high))) - return "callchainId: integer|Long expected"; - if (message.fileId != null && message.hasOwnProperty("fileId")) - if (!$util.isInteger(message.fileId) && !(message.fileId && $util.isInteger(message.fileId.low) && $util.isInteger(message.fileId.high))) - return "fileId: integer|Long expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth) && !(message.depth && $util.isInteger(message.depth.low) && $util.isInteger(message.depth.high))) - return "depth: integer|Long expected"; - if (message.symbolId != null && message.hasOwnProperty("symbolId")) - if (!$util.isInteger(message.symbolId) && !(message.symbolId && $util.isInteger(message.symbolId.low) && $util.isInteger(message.symbolId.high))) - return "symbolId: integer|Long expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isInteger(message.name) && !(message.name && $util.isInteger(message.name.low) && $util.isInteger(message.name.high))) - return "name: integer|Long expected"; - return null; - }; - - /** - * Creates a SphHiperfCallStackData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphHiperfCallStackData - * @static - * @param {Object.} object Plain object - * @returns {SphHiperfCallStackData} SphHiperfCallStackData - */ - SphHiperfCallStackData.fromObject = function fromObject(object) { - if (object instanceof $root.SphHiperfCallStackData) - return object; - var message = new $root.SphHiperfCallStackData(); - if (object.callchainId != null) - if ($util.Long) - (message.callchainId = $util.Long.fromValue(object.callchainId)).unsigned = false; - else if (typeof object.callchainId === "string") - message.callchainId = parseInt(object.callchainId, 10); - else if (typeof object.callchainId === "number") - message.callchainId = object.callchainId; - else if (typeof object.callchainId === "object") - message.callchainId = new $util.LongBits(object.callchainId.low >>> 0, object.callchainId.high >>> 0).toNumber(); - if (object.fileId != null) - if ($util.Long) - (message.fileId = $util.Long.fromValue(object.fileId)).unsigned = false; - else if (typeof object.fileId === "string") - message.fileId = parseInt(object.fileId, 10); - else if (typeof object.fileId === "number") - message.fileId = object.fileId; - else if (typeof object.fileId === "object") - message.fileId = new $util.LongBits(object.fileId.low >>> 0, object.fileId.high >>> 0).toNumber(); - if (object.depth != null) - if ($util.Long) - (message.depth = $util.Long.fromValue(object.depth)).unsigned = false; - else if (typeof object.depth === "string") - message.depth = parseInt(object.depth, 10); - else if (typeof object.depth === "number") - message.depth = object.depth; - else if (typeof object.depth === "object") - message.depth = new $util.LongBits(object.depth.low >>> 0, object.depth.high >>> 0).toNumber(); - if (object.symbolId != null) - if ($util.Long) - (message.symbolId = $util.Long.fromValue(object.symbolId)).unsigned = false; - else if (typeof object.symbolId === "string") - message.symbolId = parseInt(object.symbolId, 10); - else if (typeof object.symbolId === "number") - message.symbolId = object.symbolId; - else if (typeof object.symbolId === "object") - message.symbolId = new $util.LongBits(object.symbolId.low >>> 0, object.symbolId.high >>> 0).toNumber(); - if (object.name != null) - if ($util.Long) - (message.name = $util.Long.fromValue(object.name)).unsigned = false; - else if (typeof object.name === "string") - message.name = parseInt(object.name, 10); - else if (typeof object.name === "number") - message.name = object.name; - else if (typeof object.name === "object") - message.name = new $util.LongBits(object.name.low >>> 0, object.name.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphHiperfCallStackData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphHiperfCallStackData - * @static - * @param {SphHiperfCallStackData} message SphHiperfCallStackData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphHiperfCallStackData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.callchainId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.callchainId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.fileId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.fileId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.depth = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.depth = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.symbolId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.symbolId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.name = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.name = options.longs === String ? "0" : 0; - } - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (typeof message.callchainId === "number") - object.callchainId = options.longs === String ? String(message.callchainId) : message.callchainId; - else - object.callchainId = options.longs === String ? $util.Long.prototype.toString.call(message.callchainId) : options.longs === Number ? new $util.LongBits(message.callchainId.low >>> 0, message.callchainId.high >>> 0).toNumber() : message.callchainId; - if (message.fileId != null && message.hasOwnProperty("fileId")) - if (typeof message.fileId === "number") - object.fileId = options.longs === String ? String(message.fileId) : message.fileId; - else - object.fileId = options.longs === String ? $util.Long.prototype.toString.call(message.fileId) : options.longs === Number ? new $util.LongBits(message.fileId.low >>> 0, message.fileId.high >>> 0).toNumber() : message.fileId; - if (message.depth != null && message.hasOwnProperty("depth")) - if (typeof message.depth === "number") - object.depth = options.longs === String ? String(message.depth) : message.depth; - else - object.depth = options.longs === String ? $util.Long.prototype.toString.call(message.depth) : options.longs === Number ? new $util.LongBits(message.depth.low >>> 0, message.depth.high >>> 0).toNumber() : message.depth; - if (message.symbolId != null && message.hasOwnProperty("symbolId")) - if (typeof message.symbolId === "number") - object.symbolId = options.longs === String ? String(message.symbolId) : message.symbolId; - else - object.symbolId = options.longs === String ? $util.Long.prototype.toString.call(message.symbolId) : options.longs === Number ? new $util.LongBits(message.symbolId.low >>> 0, message.symbolId.high >>> 0).toNumber() : message.symbolId; - if (message.name != null && message.hasOwnProperty("name")) - if (typeof message.name === "number") - object.name = options.longs === String ? String(message.name) : message.name; - else - object.name = options.longs === String ? $util.Long.prototype.toString.call(message.name) : options.longs === Number ? new $util.LongBits(message.name.low >>> 0, message.name.high >>> 0).toNumber() : message.name; - return object; - }; - - /** - * Converts this SphHiperfCallStackData to JSON. - * @function toJSON - * @memberof SphHiperfCallStackData - * @instance - * @returns {Object.} JSON object - */ - SphHiperfCallStackData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphHiperfCallStackData - * @function getTypeUrl - * @memberof SphHiperfCallStackData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphHiperfCallStackData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphHiperfCallStackData"; - }; - - return SphHiperfCallStackData; -})(); - -$root.SphProcessThreadData = (function () { - - /** - * Properties of a SphProcessThreadData. - * @exports ISphProcessThreadData - * @interface ISphProcessThreadData - * @property {number|null} [cpu] SphProcessThreadData cpu - * @property {number|Long|null} [dur] SphProcessThreadData dur - * @property {number|Long|null} [id] SphProcessThreadData id - * @property {number|Long|null} [tid] SphProcessThreadData tid - * @property {string|null} [state] SphProcessThreadData state - * @property {number|Long|null} [pid] SphProcessThreadData pid - * @property {number|Long|null} [startTime] SphProcessThreadData startTime - * @property {number|Long|null} [argSetId] SphProcessThreadData argSetId - */ - - /** - * Constructs a new SphProcessThreadData. - * @exports SphProcessThreadData - * @classdesc Represents a SphProcessThreadData. - * @implements ISphProcessThreadData - * @constructor - * @param {ISphProcessThreadData=} [properties] Properties to set - */ - function SphProcessThreadData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessThreadData cpu. - * @member {number} cpu - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.cpu = 0; - - /** - * SphProcessThreadData dur. - * @member {number|Long} dur - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessThreadData id. - * @member {number|Long} id - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.id = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessThreadData tid. - * @member {number|Long} tid - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.tid = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessThreadData state. - * @member {string} state - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.state = ""; - - /** - * SphProcessThreadData pid. - * @member {number|Long} pid - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.pid = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessThreadData startTime. - * @member {number|Long} startTime - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessThreadData argSetId. - * @member {number|Long} argSetId - * @memberof SphProcessThreadData - * @instance - */ - SphProcessThreadData.prototype.argSetId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphProcessThreadData instance using the specified properties. - * @function create - * @memberof SphProcessThreadData - * @static - * @param {ISphProcessThreadData=} [properties] Properties to set - * @returns {SphProcessThreadData} SphProcessThreadData instance - */ - SphProcessThreadData.create = function create(properties) { - return new SphProcessThreadData(properties); - }; - - /** - * Encodes the specified SphProcessThreadData message. Does not implicitly {@link SphProcessThreadData.verify|verify} messages. - * @function encode - * @memberof SphProcessThreadData - * @static - * @param {ISphProcessThreadData} message SphProcessThreadData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessThreadData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.cpu != null && Object.hasOwnProperty.call(message, "cpu")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.cpu); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.id); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.tid); - if (message.state != null && Object.hasOwnProperty.call(message, "state")) - writer.uint32(/* id 5, wireType 2 =*/42).string(message.state); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.pid); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 7, wireType 0 =*/56).int64(message.startTime); - if (message.argSetId != null && Object.hasOwnProperty.call(message, "argSetId")) - writer.uint32(/* id 8, wireType 0 =*/64).int64(message.argSetId); - return writer; - }; - - /** - * Encodes the specified SphProcessThreadData message, length delimited. Does not implicitly {@link SphProcessThreadData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessThreadData - * @static - * @param {ISphProcessThreadData} message SphProcessThreadData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessThreadData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessThreadData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessThreadData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessThreadData} SphProcessThreadData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessThreadData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessThreadData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.cpu = reader.int32(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.id = reader.int64(); - break; - } - case 4: { - message.tid = reader.int64(); - break; - } - case 5: { - message.state = reader.string(); - break; - } - case 6: { - message.pid = reader.int64(); - break; - } - case 7: { - message.startTime = reader.int64(); - break; - } - case 8: { - message.argSetId = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessThreadData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessThreadData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessThreadData} SphProcessThreadData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessThreadData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessThreadData message. - * @function verify - * @memberof SphProcessThreadData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessThreadData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.cpu != null && message.hasOwnProperty("cpu")) - if (!$util.isInteger(message.cpu)) - return "cpu: integer expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) - return "id: integer|Long expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid) && !(message.tid && $util.isInteger(message.tid.low) && $util.isInteger(message.tid.high))) - return "tid: integer|Long expected"; - if (message.state != null && message.hasOwnProperty("state")) - if (!$util.isString(message.state)) - return "state: string expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid) && !(message.pid && $util.isInteger(message.pid.low) && $util.isInteger(message.pid.high))) - return "pid: integer|Long expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.argSetId != null && message.hasOwnProperty("argSetId")) - if (!$util.isInteger(message.argSetId) && !(message.argSetId && $util.isInteger(message.argSetId.low) && $util.isInteger(message.argSetId.high))) - return "argSetId: integer|Long expected"; - return null; - }; - - /** - * Creates a SphProcessThreadData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessThreadData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessThreadData} SphProcessThreadData - */ - SphProcessThreadData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessThreadData) - return object; - var message = new $root.SphProcessThreadData(); - if (object.cpu != null) - message.cpu = object.cpu | 0; - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.id != null) - if ($util.Long) - (message.id = $util.Long.fromValue(object.id)).unsigned = false; - else if (typeof object.id === "string") - message.id = parseInt(object.id, 10); - else if (typeof object.id === "number") - message.id = object.id; - else if (typeof object.id === "object") - message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(); - if (object.tid != null) - if ($util.Long) - (message.tid = $util.Long.fromValue(object.tid)).unsigned = false; - else if (typeof object.tid === "string") - message.tid = parseInt(object.tid, 10); - else if (typeof object.tid === "number") - message.tid = object.tid; - else if (typeof object.tid === "object") - message.tid = new $util.LongBits(object.tid.low >>> 0, object.tid.high >>> 0).toNumber(); - if (object.state != null) - message.state = String(object.state); - if (object.pid != null) - if ($util.Long) - (message.pid = $util.Long.fromValue(object.pid)).unsigned = false; - else if (typeof object.pid === "string") - message.pid = parseInt(object.pid, 10); - else if (typeof object.pid === "number") - message.pid = object.pid; - else if (typeof object.pid === "object") - message.pid = new $util.LongBits(object.pid.low >>> 0, object.pid.high >>> 0).toNumber(); - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.argSetId != null) - if ($util.Long) - (message.argSetId = $util.Long.fromValue(object.argSetId)).unsigned = false; - else if (typeof object.argSetId === "string") - message.argSetId = parseInt(object.argSetId, 10); - else if (typeof object.argSetId === "number") - message.argSetId = object.argSetId; - else if (typeof object.argSetId === "object") - message.argSetId = new $util.LongBits(object.argSetId.low >>> 0, object.argSetId.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphProcessThreadData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessThreadData - * @static - * @param {SphProcessThreadData} message SphProcessThreadData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessThreadData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.cpu = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.id = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.id = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.tid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.tid = options.longs === String ? "0" : 0; - object.state = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.pid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.pid = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.argSetId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.argSetId = options.longs === String ? "0" : 0; - } - if (message.cpu != null && message.hasOwnProperty("cpu")) - object.cpu = message.cpu; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.id != null && message.hasOwnProperty("id")) - if (typeof message.id === "number") - object.id = options.longs === String ? String(message.id) : message.id; - else - object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber() : message.id; - if (message.tid != null && message.hasOwnProperty("tid")) - if (typeof message.tid === "number") - object.tid = options.longs === String ? String(message.tid) : message.tid; - else - object.tid = options.longs === String ? $util.Long.prototype.toString.call(message.tid) : options.longs === Number ? new $util.LongBits(message.tid.low >>> 0, message.tid.high >>> 0).toNumber() : message.tid; - if (message.state != null && message.hasOwnProperty("state")) - object.state = message.state; - if (message.pid != null && message.hasOwnProperty("pid")) - if (typeof message.pid === "number") - object.pid = options.longs === String ? String(message.pid) : message.pid; - else - object.pid = options.longs === String ? $util.Long.prototype.toString.call(message.pid) : options.longs === Number ? new $util.LongBits(message.pid.low >>> 0, message.pid.high >>> 0).toNumber() : message.pid; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.argSetId != null && message.hasOwnProperty("argSetId")) - if (typeof message.argSetId === "number") - object.argSetId = options.longs === String ? String(message.argSetId) : message.argSetId; - else - object.argSetId = options.longs === String ? $util.Long.prototype.toString.call(message.argSetId) : options.longs === Number ? new $util.LongBits(message.argSetId.low >>> 0, message.argSetId.high >>> 0).toNumber() : message.argSetId; - return object; - }; - - /** - * Converts this SphProcessThreadData to JSON. - * @function toJSON - * @memberof SphProcessThreadData - * @instance - * @returns {Object.} JSON object - */ - SphProcessThreadData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessThreadData - * @function getTypeUrl - * @memberof SphProcessThreadData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessThreadData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessThreadData"; - }; - - return SphProcessThreadData; -})(); - -$root.SphProcessFuncData = (function () { - - /** - * Properties of a SphProcessFuncData. - * @exports ISphProcessFuncData - * @interface ISphProcessFuncData - * @property {number|Long|null} [startTs] SphProcessFuncData startTs - * @property {number|Long|null} [dur] SphProcessFuncData dur - * @property {number|Long|null} [argsetid] SphProcessFuncData argsetid - * @property {number|null} [depth] SphProcessFuncData depth - * @property {number|Long|null} [id] SphProcessFuncData id - * @property {number|null} [itid] SphProcessFuncData itid - * @property {number|null} [ipid] SphProcessFuncData ipid - */ - - /** - * Constructs a new SphProcessFuncData. - * @exports SphProcessFuncData - * @classdesc Represents a SphProcessFuncData. - * @implements ISphProcessFuncData - * @constructor - * @param {ISphProcessFuncData=} [properties] Properties to set - */ - function SphProcessFuncData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessFuncData startTs. - * @member {number|Long} startTs - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessFuncData dur. - * @member {number|Long} dur - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessFuncData argsetid. - * @member {number|Long} argsetid - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.argsetid = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessFuncData depth. - * @member {number} depth - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.depth = 0; - - /** - * SphProcessFuncData id. - * @member {number|Long} id - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.id = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessFuncData itid. - * @member {number} itid - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.itid = 0; - - /** - * SphProcessFuncData ipid. - * @member {number} ipid - * @memberof SphProcessFuncData - * @instance - */ - SphProcessFuncData.prototype.ipid = 0; - - /** - * Creates a new SphProcessFuncData instance using the specified properties. - * @function create - * @memberof SphProcessFuncData - * @static - * @param {ISphProcessFuncData=} [properties] Properties to set - * @returns {SphProcessFuncData} SphProcessFuncData instance - */ - SphProcessFuncData.create = function create(properties) { - return new SphProcessFuncData(properties); - }; - - /** - * Encodes the specified SphProcessFuncData message. Does not implicitly {@link SphProcessFuncData.verify|verify} messages. - * @function encode - * @memberof SphProcessFuncData - * @static - * @param {ISphProcessFuncData} message SphProcessFuncData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessFuncData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startTs); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.argsetid != null && Object.hasOwnProperty.call(message, "argsetid")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.argsetid); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.depth); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.id); - if (message.itid != null && Object.hasOwnProperty.call(message, "itid")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.itid); - if (message.ipid != null && Object.hasOwnProperty.call(message, "ipid")) - writer.uint32(/* id 7, wireType 0 =*/56).int32(message.ipid); - return writer; - }; - - /** - * Encodes the specified SphProcessFuncData message, length delimited. Does not implicitly {@link SphProcessFuncData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessFuncData - * @static - * @param {ISphProcessFuncData} message SphProcessFuncData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessFuncData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessFuncData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessFuncData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessFuncData} SphProcessFuncData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessFuncData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessFuncData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startTs = reader.int64(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.argsetid = reader.int64(); - break; - } - case 4: { - message.depth = reader.int32(); - break; - } - case 5: { - message.id = reader.int64(); - break; - } - case 6: { - message.itid = reader.int32(); - break; - } - case 7: { - message.ipid = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessFuncData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessFuncData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessFuncData} SphProcessFuncData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessFuncData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessFuncData message. - * @function verify - * @memberof SphProcessFuncData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessFuncData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.argsetid != null && message.hasOwnProperty("argsetid")) - if (!$util.isInteger(message.argsetid) && !(message.argsetid && $util.isInteger(message.argsetid.low) && $util.isInteger(message.argsetid.high))) - return "argsetid: integer|Long expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) - return "id: integer|Long expected"; - if (message.itid != null && message.hasOwnProperty("itid")) - if (!$util.isInteger(message.itid)) - return "itid: integer expected"; - if (message.ipid != null && message.hasOwnProperty("ipid")) - if (!$util.isInteger(message.ipid)) - return "ipid: integer expected"; - return null; - }; - - /** - * Creates a SphProcessFuncData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessFuncData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessFuncData} SphProcessFuncData - */ - SphProcessFuncData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessFuncData) - return object; - var message = new $root.SphProcessFuncData(); - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.argsetid != null) - if ($util.Long) - (message.argsetid = $util.Long.fromValue(object.argsetid)).unsigned = false; - else if (typeof object.argsetid === "string") - message.argsetid = parseInt(object.argsetid, 10); - else if (typeof object.argsetid === "number") - message.argsetid = object.argsetid; - else if (typeof object.argsetid === "object") - message.argsetid = new $util.LongBits(object.argsetid.low >>> 0, object.argsetid.high >>> 0).toNumber(); - if (object.depth != null) - message.depth = object.depth | 0; - if (object.id != null) - if ($util.Long) - (message.id = $util.Long.fromValue(object.id)).unsigned = false; - else if (typeof object.id === "string") - message.id = parseInt(object.id, 10); - else if (typeof object.id === "number") - message.id = object.id; - else if (typeof object.id === "object") - message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(); - if (object.itid != null) - message.itid = object.itid | 0; - if (object.ipid != null) - message.ipid = object.ipid | 0; - return message; - }; - - /** - * Creates a plain object from a SphProcessFuncData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessFuncData - * @static - * @param {SphProcessFuncData} message SphProcessFuncData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessFuncData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.argsetid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.argsetid = options.longs === String ? "0" : 0; - object.depth = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.id = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.id = options.longs === String ? "0" : 0; - object.itid = 0; - object.ipid = 0; - } - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.argsetid != null && message.hasOwnProperty("argsetid")) - if (typeof message.argsetid === "number") - object.argsetid = options.longs === String ? String(message.argsetid) : message.argsetid; - else - object.argsetid = options.longs === String ? $util.Long.prototype.toString.call(message.argsetid) : options.longs === Number ? new $util.LongBits(message.argsetid.low >>> 0, message.argsetid.high >>> 0).toNumber() : message.argsetid; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - if (message.id != null && message.hasOwnProperty("id")) - if (typeof message.id === "number") - object.id = options.longs === String ? String(message.id) : message.id; - else - object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber() : message.id; - if (message.itid != null && message.hasOwnProperty("itid")) - object.itid = message.itid; - if (message.ipid != null && message.hasOwnProperty("ipid")) - object.ipid = message.ipid; - return object; - }; - - /** - * Converts this SphProcessFuncData to JSON. - * @function toJSON - * @memberof SphProcessFuncData - * @instance - * @returns {Object.} JSON object - */ - SphProcessFuncData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessFuncData - * @function getTypeUrl - * @memberof SphProcessFuncData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessFuncData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessFuncData"; - }; - - return SphProcessFuncData; -})(); - -$root.SphProcessInputEventData = (function () { - - /** - * Properties of a SphProcessInputEventData. - * @exports ISphProcessInputEventData - * @interface ISphProcessInputEventData - * @property {number|Long|null} [startTs] SphProcessInputEventData startTs - * @property {number|Long|null} [dur] SphProcessInputEventData dur - * @property {number|Long|null} [argsetid] SphProcessInputEventData argsetid - * @property {number|null} [tid] SphProcessInputEventData tid - * @property {number|null} [pid] SphProcessInputEventData pid - * @property {number|null} [isMainThread] SphProcessInputEventData isMainThread - * @property {number|null} [trackId] SphProcessInputEventData trackId - * @property {number|null} [parentId] SphProcessInputEventData parentId - * @property {number|null} [id] SphProcessInputEventData id - * @property {number|null} [cookie] SphProcessInputEventData cookie - * @property {number|null} [depth] SphProcessInputEventData depth - */ - - /** - * Constructs a new SphProcessInputEventData. - * @exports SphProcessInputEventData - * @classdesc Represents a SphProcessInputEventData. - * @implements ISphProcessInputEventData - * @constructor - * @param {ISphProcessInputEventData=} [properties] Properties to set - */ - function SphProcessInputEventData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessInputEventData startTs. - * @member {number|Long} startTs - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessInputEventData dur. - * @member {number|Long} dur - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessInputEventData argsetid. - * @member {number|Long} argsetid - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.argsetid = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessInputEventData tid. - * @member {number} tid - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.tid = 0; - - /** - * SphProcessInputEventData pid. - * @member {number} pid - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.pid = 0; - - /** - * SphProcessInputEventData isMainThread. - * @member {number} isMainThread - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.isMainThread = 0; - - /** - * SphProcessInputEventData trackId. - * @member {number} trackId - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.trackId = 0; - - /** - * SphProcessInputEventData parentId. - * @member {number} parentId - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.parentId = 0; - - /** - * SphProcessInputEventData id. - * @member {number} id - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.id = 0; - - /** - * SphProcessInputEventData cookie. - * @member {number} cookie - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.cookie = 0; - - /** - * SphProcessInputEventData depth. - * @member {number} depth - * @memberof SphProcessInputEventData - * @instance - */ - SphProcessInputEventData.prototype.depth = 0; - - /** - * Creates a new SphProcessInputEventData instance using the specified properties. - * @function create - * @memberof SphProcessInputEventData - * @static - * @param {ISphProcessInputEventData=} [properties] Properties to set - * @returns {SphProcessInputEventData} SphProcessInputEventData instance - */ - SphProcessInputEventData.create = function create(properties) { - return new SphProcessInputEventData(properties); - }; - - /** - * Encodes the specified SphProcessInputEventData message. Does not implicitly {@link SphProcessInputEventData.verify|verify} messages. - * @function encode - * @memberof SphProcessInputEventData - * @static - * @param {ISphProcessInputEventData} message SphProcessInputEventData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessInputEventData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startTs); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.argsetid != null && Object.hasOwnProperty.call(message, "argsetid")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.argsetid); - if (message.tid != null && Object.hasOwnProperty.call(message, "tid")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.tid); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.pid); - if (message.isMainThread != null && Object.hasOwnProperty.call(message, "isMainThread")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.isMainThread); - if (message.trackId != null && Object.hasOwnProperty.call(message, "trackId")) - writer.uint32(/* id 7, wireType 0 =*/56).int32(message.trackId); - if (message.parentId != null && Object.hasOwnProperty.call(message, "parentId")) - writer.uint32(/* id 8, wireType 0 =*/64).int32(message.parentId); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 9, wireType 0 =*/72).int32(message.id); - if (message.cookie != null && Object.hasOwnProperty.call(message, "cookie")) - writer.uint32(/* id 10, wireType 0 =*/80).int32(message.cookie); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 11, wireType 0 =*/88).int32(message.depth); - return writer; - }; - - /** - * Encodes the specified SphProcessInputEventData message, length delimited. Does not implicitly {@link SphProcessInputEventData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessInputEventData - * @static - * @param {ISphProcessInputEventData} message SphProcessInputEventData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessInputEventData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessInputEventData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessInputEventData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessInputEventData} SphProcessInputEventData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessInputEventData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessInputEventData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startTs = reader.int64(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.argsetid = reader.int64(); - break; - } - case 4: { - message.tid = reader.int32(); - break; - } - case 5: { - message.pid = reader.int32(); - break; - } - case 6: { - message.isMainThread = reader.int32(); - break; - } - case 7: { - message.trackId = reader.int32(); - break; - } - case 8: { - message.parentId = reader.int32(); - break; - } - case 9: { - message.id = reader.int32(); - break; - } - case 10: { - message.cookie = reader.int32(); - break; - } - case 11: { - message.depth = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessInputEventData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessInputEventData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessInputEventData} SphProcessInputEventData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessInputEventData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessInputEventData message. - * @function verify - * @memberof SphProcessInputEventData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessInputEventData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.argsetid != null && message.hasOwnProperty("argsetid")) - if (!$util.isInteger(message.argsetid) && !(message.argsetid && $util.isInteger(message.argsetid.low) && $util.isInteger(message.argsetid.high))) - return "argsetid: integer|Long expected"; - if (message.tid != null && message.hasOwnProperty("tid")) - if (!$util.isInteger(message.tid)) - return "tid: integer expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.isMainThread != null && message.hasOwnProperty("isMainThread")) - if (!$util.isInteger(message.isMainThread)) - return "isMainThread: integer expected"; - if (message.trackId != null && message.hasOwnProperty("trackId")) - if (!$util.isInteger(message.trackId)) - return "trackId: integer expected"; - if (message.parentId != null && message.hasOwnProperty("parentId")) - if (!$util.isInteger(message.parentId)) - return "parentId: integer expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.cookie != null && message.hasOwnProperty("cookie")) - if (!$util.isInteger(message.cookie)) - return "cookie: integer expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - return null; - }; - - /** - * Creates a SphProcessInputEventData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessInputEventData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessInputEventData} SphProcessInputEventData - */ - SphProcessInputEventData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessInputEventData) - return object; - var message = new $root.SphProcessInputEventData(); - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.argsetid != null) - if ($util.Long) - (message.argsetid = $util.Long.fromValue(object.argsetid)).unsigned = false; - else if (typeof object.argsetid === "string") - message.argsetid = parseInt(object.argsetid, 10); - else if (typeof object.argsetid === "number") - message.argsetid = object.argsetid; - else if (typeof object.argsetid === "object") - message.argsetid = new $util.LongBits(object.argsetid.low >>> 0, object.argsetid.high >>> 0).toNumber(); - if (object.tid != null) - message.tid = object.tid | 0; - if (object.pid != null) - message.pid = object.pid | 0; - if (object.isMainThread != null) - message.isMainThread = object.isMainThread | 0; - if (object.trackId != null) - message.trackId = object.trackId | 0; - if (object.parentId != null) - message.parentId = object.parentId | 0; - if (object.id != null) - message.id = object.id | 0; - if (object.cookie != null) - message.cookie = object.cookie | 0; - if (object.depth != null) - message.depth = object.depth | 0; - return message; - }; - - /** - * Creates a plain object from a SphProcessInputEventData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessInputEventData - * @static - * @param {SphProcessInputEventData} message SphProcessInputEventData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessInputEventData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.argsetid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.argsetid = options.longs === String ? "0" : 0; - object.tid = 0; - object.pid = 0; - object.isMainThread = 0; - object.trackId = 0; - object.parentId = 0; - object.id = 0; - object.cookie = 0; - object.depth = 0; - } - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.argsetid != null && message.hasOwnProperty("argsetid")) - if (typeof message.argsetid === "number") - object.argsetid = options.longs === String ? String(message.argsetid) : message.argsetid; - else - object.argsetid = options.longs === String ? $util.Long.prototype.toString.call(message.argsetid) : options.longs === Number ? new $util.LongBits(message.argsetid.low >>> 0, message.argsetid.high >>> 0).toNumber() : message.argsetid; - if (message.tid != null && message.hasOwnProperty("tid")) - object.tid = message.tid; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.isMainThread != null && message.hasOwnProperty("isMainThread")) - object.isMainThread = message.isMainThread; - if (message.trackId != null && message.hasOwnProperty("trackId")) - object.trackId = message.trackId; - if (message.parentId != null && message.hasOwnProperty("parentId")) - object.parentId = message.parentId; - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.cookie != null && message.hasOwnProperty("cookie")) - object.cookie = message.cookie; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - return object; - }; - - /** - * Converts this SphProcessInputEventData to JSON. - * @function toJSON - * @memberof SphProcessInputEventData - * @instance - * @returns {Object.} JSON object - */ - SphProcessInputEventData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessInputEventData - * @function getTypeUrl - * @memberof SphProcessInputEventData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessInputEventData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessInputEventData"; - }; - - return SphProcessInputEventData; -})(); - -$root.SphProcessJanksFramesData = (function () { - - /** - * Properties of a SphProcessJanksFramesData. - * @exports ISphProcessJanksFramesData - * @interface ISphProcessJanksFramesData - * @property {number|Long|null} [ts] SphProcessJanksFramesData ts - * @property {number|Long|null} [dur] SphProcessJanksFramesData dur - * @property {number|null} [pid] SphProcessJanksFramesData pid - * @property {number|null} [id] SphProcessJanksFramesData id - * @property {number|null} [name] SphProcessJanksFramesData name - * @property {number|null} [type] SphProcessJanksFramesData type - * @property {number|null} [depth] SphProcessJanksFramesData depth - */ - - /** - * Constructs a new SphProcessJanksFramesData. - * @exports SphProcessJanksFramesData - * @classdesc Represents a SphProcessJanksFramesData. - * @implements ISphProcessJanksFramesData - * @constructor - * @param {ISphProcessJanksFramesData=} [properties] Properties to set - */ - function SphProcessJanksFramesData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessJanksFramesData ts. - * @member {number|Long} ts - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.ts = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessJanksFramesData dur. - * @member {number|Long} dur - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessJanksFramesData pid. - * @member {number} pid - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.pid = 0; - - /** - * SphProcessJanksFramesData id. - * @member {number} id - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.id = 0; - - /** - * SphProcessJanksFramesData name. - * @member {number} name - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.name = 0; - - /** - * SphProcessJanksFramesData type. - * @member {number} type - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.type = 0; - - /** - * SphProcessJanksFramesData depth. - * @member {number} depth - * @memberof SphProcessJanksFramesData - * @instance - */ - SphProcessJanksFramesData.prototype.depth = 0; - - /** - * Creates a new SphProcessJanksFramesData instance using the specified properties. - * @function create - * @memberof SphProcessJanksFramesData - * @static - * @param {ISphProcessJanksFramesData=} [properties] Properties to set - * @returns {SphProcessJanksFramesData} SphProcessJanksFramesData instance - */ - SphProcessJanksFramesData.create = function create(properties) { - return new SphProcessJanksFramesData(properties); - }; - - /** - * Encodes the specified SphProcessJanksFramesData message. Does not implicitly {@link SphProcessJanksFramesData.verify|verify} messages. - * @function encode - * @memberof SphProcessJanksFramesData - * @static - * @param {ISphProcessJanksFramesData} message SphProcessJanksFramesData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessJanksFramesData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.ts != null && Object.hasOwnProperty.call(message, "ts")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.ts); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pid); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.id); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.name); - if (message.type != null && Object.hasOwnProperty.call(message, "type")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.type); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 7, wireType 0 =*/56).int32(message.depth); - return writer; - }; - - /** - * Encodes the specified SphProcessJanksFramesData message, length delimited. Does not implicitly {@link SphProcessJanksFramesData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessJanksFramesData - * @static - * @param {ISphProcessJanksFramesData} message SphProcessJanksFramesData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessJanksFramesData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessJanksFramesData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessJanksFramesData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessJanksFramesData} SphProcessJanksFramesData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessJanksFramesData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessJanksFramesData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.ts = reader.int64(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.pid = reader.int32(); - break; - } - case 4: { - message.id = reader.int32(); - break; - } - case 5: { - message.name = reader.int32(); - break; - } - case 6: { - message.type = reader.int32(); - break; - } - case 7: { - message.depth = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessJanksFramesData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessJanksFramesData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessJanksFramesData} SphProcessJanksFramesData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessJanksFramesData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessJanksFramesData message. - * @function verify - * @memberof SphProcessJanksFramesData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessJanksFramesData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.ts != null && message.hasOwnProperty("ts")) - if (!$util.isInteger(message.ts) && !(message.ts && $util.isInteger(message.ts.low) && $util.isInteger(message.ts.high))) - return "ts: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isInteger(message.name)) - return "name: integer expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isInteger(message.type)) - return "type: integer expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - return null; - }; - - /** - * Creates a SphProcessJanksFramesData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessJanksFramesData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessJanksFramesData} SphProcessJanksFramesData - */ - SphProcessJanksFramesData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessJanksFramesData) - return object; - var message = new $root.SphProcessJanksFramesData(); - if (object.ts != null) - if ($util.Long) - (message.ts = $util.Long.fromValue(object.ts)).unsigned = false; - else if (typeof object.ts === "string") - message.ts = parseInt(object.ts, 10); - else if (typeof object.ts === "number") - message.ts = object.ts; - else if (typeof object.ts === "object") - message.ts = new $util.LongBits(object.ts.low >>> 0, object.ts.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.pid != null) - message.pid = object.pid | 0; - if (object.id != null) - message.id = object.id | 0; - if (object.name != null) - message.name = object.name | 0; - if (object.type != null) - message.type = object.type | 0; - if (object.depth != null) - message.depth = object.depth | 0; - return message; - }; - - /** - * Creates a plain object from a SphProcessJanksFramesData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessJanksFramesData - * @static - * @param {SphProcessJanksFramesData} message SphProcessJanksFramesData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessJanksFramesData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ts = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ts = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - object.pid = 0; - object.id = 0; - object.name = 0; - object.type = 0; - object.depth = 0; - } - if (message.ts != null && message.hasOwnProperty("ts")) - if (typeof message.ts === "number") - object.ts = options.longs === String ? String(message.ts) : message.ts; - else - object.ts = options.longs === String ? $util.Long.prototype.toString.call(message.ts) : options.longs === Number ? new $util.LongBits(message.ts.low >>> 0, message.ts.high >>> 0).toNumber() : message.ts; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - return object; - }; - - /** - * Converts this SphProcessJanksFramesData to JSON. - * @function toJSON - * @memberof SphProcessJanksFramesData - * @instance - * @returns {Object.} JSON object - */ - SphProcessJanksFramesData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessJanksFramesData - * @function getTypeUrl - * @memberof SphProcessJanksFramesData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessJanksFramesData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessJanksFramesData"; - }; - - return SphProcessJanksFramesData; -})(); - -$root.SphProcessJanksActualData = (function () { - - /** - * Properties of a SphProcessJanksActualData. - * @exports ISphProcessJanksActualData - * @interface ISphProcessJanksActualData - * @property {number|Long|null} [ts] SphProcessJanksActualData ts - * @property {number|Long|null} [dur] SphProcessJanksActualData dur - * @property {number|null} [pid] SphProcessJanksActualData pid - * @property {number|null} [id] SphProcessJanksActualData id - * @property {number|null} [name] SphProcessJanksActualData name - * @property {number|null} [type] SphProcessJanksActualData type - * @property {number|null} [jankTag] SphProcessJanksActualData jankTag - * @property {number|null} [dstSlice] SphProcessJanksActualData dstSlice - * @property {number|null} [depth] SphProcessJanksActualData depth - */ - - /** - * Constructs a new SphProcessJanksActualData. - * @exports SphProcessJanksActualData - * @classdesc Represents a SphProcessJanksActualData. - * @implements ISphProcessJanksActualData - * @constructor - * @param {ISphProcessJanksActualData=} [properties] Properties to set - */ - function SphProcessJanksActualData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphProcessJanksActualData ts. - * @member {number|Long} ts - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.ts = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessJanksActualData dur. - * @member {number|Long} dur - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphProcessJanksActualData pid. - * @member {number} pid - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.pid = 0; - - /** - * SphProcessJanksActualData id. - * @member {number} id - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.id = 0; - - /** - * SphProcessJanksActualData name. - * @member {number} name - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.name = 0; - - /** - * SphProcessJanksActualData type. - * @member {number} type - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.type = 0; - - /** - * SphProcessJanksActualData jankTag. - * @member {number} jankTag - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.jankTag = 0; - - /** - * SphProcessJanksActualData dstSlice. - * @member {number} dstSlice - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.dstSlice = 0; - - /** - * SphProcessJanksActualData depth. - * @member {number} depth - * @memberof SphProcessJanksActualData - * @instance - */ - SphProcessJanksActualData.prototype.depth = 0; - - /** - * Creates a new SphProcessJanksActualData instance using the specified properties. - * @function create - * @memberof SphProcessJanksActualData - * @static - * @param {ISphProcessJanksActualData=} [properties] Properties to set - * @returns {SphProcessJanksActualData} SphProcessJanksActualData instance - */ - SphProcessJanksActualData.create = function create(properties) { - return new SphProcessJanksActualData(properties); - }; - - /** - * Encodes the specified SphProcessJanksActualData message. Does not implicitly {@link SphProcessJanksActualData.verify|verify} messages. - * @function encode - * @memberof SphProcessJanksActualData - * @static - * @param {ISphProcessJanksActualData} message SphProcessJanksActualData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessJanksActualData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.ts != null && Object.hasOwnProperty.call(message, "ts")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.ts); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.dur); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.pid); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 4, wireType 0 =*/32).int32(message.id); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.name); - if (message.type != null && Object.hasOwnProperty.call(message, "type")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.type); - if (message.jankTag != null && Object.hasOwnProperty.call(message, "jankTag")) - writer.uint32(/* id 7, wireType 0 =*/56).int32(message.jankTag); - if (message.dstSlice != null && Object.hasOwnProperty.call(message, "dstSlice")) - writer.uint32(/* id 8, wireType 0 =*/64).int32(message.dstSlice); - if (message.depth != null && Object.hasOwnProperty.call(message, "depth")) - writer.uint32(/* id 9, wireType 0 =*/72).int32(message.depth); - return writer; - }; - - /** - * Encodes the specified SphProcessJanksActualData message, length delimited. Does not implicitly {@link SphProcessJanksActualData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphProcessJanksActualData - * @static - * @param {ISphProcessJanksActualData} message SphProcessJanksActualData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphProcessJanksActualData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphProcessJanksActualData message from the specified reader or buffer. - * @function decode - * @memberof SphProcessJanksActualData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphProcessJanksActualData} SphProcessJanksActualData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessJanksActualData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphProcessJanksActualData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.ts = reader.int64(); - break; - } - case 2: { - message.dur = reader.int64(); - break; - } - case 3: { - message.pid = reader.int32(); - break; - } - case 4: { - message.id = reader.int32(); - break; - } - case 5: { - message.name = reader.int32(); - break; - } - case 6: { - message.type = reader.int32(); - break; - } - case 7: { - message.jankTag = reader.int32(); - break; - } - case 8: { - message.dstSlice = reader.int32(); - break; - } - case 9: { - message.depth = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphProcessJanksActualData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphProcessJanksActualData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphProcessJanksActualData} SphProcessJanksActualData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphProcessJanksActualData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphProcessJanksActualData message. - * @function verify - * @memberof SphProcessJanksActualData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphProcessJanksActualData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.ts != null && message.hasOwnProperty("ts")) - if (!$util.isInteger(message.ts) && !(message.ts && $util.isInteger(message.ts.low) && $util.isInteger(message.ts.high))) - return "ts: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id)) - return "id: integer expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isInteger(message.name)) - return "name: integer expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isInteger(message.type)) - return "type: integer expected"; - if (message.jankTag != null && message.hasOwnProperty("jankTag")) - if (!$util.isInteger(message.jankTag)) - return "jankTag: integer expected"; - if (message.dstSlice != null && message.hasOwnProperty("dstSlice")) - if (!$util.isInteger(message.dstSlice)) - return "dstSlice: integer expected"; - if (message.depth != null && message.hasOwnProperty("depth")) - if (!$util.isInteger(message.depth)) - return "depth: integer expected"; - return null; - }; - - /** - * Creates a SphProcessJanksActualData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphProcessJanksActualData - * @static - * @param {Object.} object Plain object - * @returns {SphProcessJanksActualData} SphProcessJanksActualData - */ - SphProcessJanksActualData.fromObject = function fromObject(object) { - if (object instanceof $root.SphProcessJanksActualData) - return object; - var message = new $root.SphProcessJanksActualData(); - if (object.ts != null) - if ($util.Long) - (message.ts = $util.Long.fromValue(object.ts)).unsigned = false; - else if (typeof object.ts === "string") - message.ts = parseInt(object.ts, 10); - else if (typeof object.ts === "number") - message.ts = object.ts; - else if (typeof object.ts === "object") - message.ts = new $util.LongBits(object.ts.low >>> 0, object.ts.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.pid != null) - message.pid = object.pid | 0; - if (object.id != null) - message.id = object.id | 0; - if (object.name != null) - message.name = object.name | 0; - if (object.type != null) - message.type = object.type | 0; - if (object.jankTag != null) - message.jankTag = object.jankTag | 0; - if (object.dstSlice != null) - message.dstSlice = object.dstSlice | 0; - if (object.depth != null) - message.depth = object.depth | 0; - return message; - }; - - /** - * Creates a plain object from a SphProcessJanksActualData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphProcessJanksActualData - * @static - * @param {SphProcessJanksActualData} message SphProcessJanksActualData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphProcessJanksActualData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ts = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ts = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - object.pid = 0; - object.id = 0; - object.name = 0; - object.type = 0; - object.jankTag = 0; - object.dstSlice = 0; - object.depth = 0; - } - if (message.ts != null && message.hasOwnProperty("ts")) - if (typeof message.ts === "number") - object.ts = options.longs === String ? String(message.ts) : message.ts; - else - object.ts = options.longs === String ? $util.Long.prototype.toString.call(message.ts) : options.longs === Number ? new $util.LongBits(message.ts.low >>> 0, message.ts.high >>> 0).toNumber() : message.ts; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - if (message.id != null && message.hasOwnProperty("id")) - object.id = message.id; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.jankTag != null && message.hasOwnProperty("jankTag")) - object.jankTag = message.jankTag; - if (message.dstSlice != null && message.hasOwnProperty("dstSlice")) - object.dstSlice = message.dstSlice; - if (message.depth != null && message.hasOwnProperty("depth")) - object.depth = message.depth; - return object; - }; - - /** - * Converts this SphProcessJanksActualData to JSON. - * @function toJSON - * @memberof SphProcessJanksActualData - * @instance - * @returns {Object.} JSON object - */ - SphProcessJanksActualData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphProcessJanksActualData - * @function getTypeUrl - * @memberof SphProcessJanksActualData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphProcessJanksActualData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphProcessJanksActualData"; - }; - - return SphProcessJanksActualData; -})(); - -$root.SphNativeMemoryNormalData = (function () { - - /** - * Properties of a SphNativeMemoryNormalData. - * @exports ISphNativeMemoryNormalData - * @interface ISphNativeMemoryNormalData - * @property {number|Long|null} [startTime] SphNativeMemoryNormalData startTime - * @property {number|Long|null} [heapSize] SphNativeMemoryNormalData heapSize - * @property {number|Long|null} [eventType] SphNativeMemoryNormalData eventType - * @property {number|Long|null} [ipid] SphNativeMemoryNormalData ipid - */ - - /** - * Constructs a new SphNativeMemoryNormalData. - * @exports SphNativeMemoryNormalData - * @classdesc Represents a SphNativeMemoryNormalData. - * @implements ISphNativeMemoryNormalData - * @constructor - * @param {ISphNativeMemoryNormalData=} [properties] Properties to set - */ - function SphNativeMemoryNormalData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphNativeMemoryNormalData startTime. - * @member {number|Long} startTime - * @memberof SphNativeMemoryNormalData - * @instance - */ - SphNativeMemoryNormalData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryNormalData heapSize. - * @member {number|Long} heapSize - * @memberof SphNativeMemoryNormalData - * @instance - */ - SphNativeMemoryNormalData.prototype.heapSize = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryNormalData eventType. - * @member {number|Long} eventType - * @memberof SphNativeMemoryNormalData - * @instance - */ - SphNativeMemoryNormalData.prototype.eventType = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryNormalData ipid. - * @member {number|Long} ipid - * @memberof SphNativeMemoryNormalData - * @instance - */ - SphNativeMemoryNormalData.prototype.ipid = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphNativeMemoryNormalData instance using the specified properties. - * @function create - * @memberof SphNativeMemoryNormalData - * @static - * @param {ISphNativeMemoryNormalData=} [properties] Properties to set - * @returns {SphNativeMemoryNormalData} SphNativeMemoryNormalData instance - */ - SphNativeMemoryNormalData.create = function create(properties) { - return new SphNativeMemoryNormalData(properties); - }; - - /** - * Encodes the specified SphNativeMemoryNormalData message. Does not implicitly {@link SphNativeMemoryNormalData.verify|verify} messages. - * @function encode - * @memberof SphNativeMemoryNormalData - * @static - * @param {ISphNativeMemoryNormalData} message SphNativeMemoryNormalData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphNativeMemoryNormalData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.startTime); - if (message.heapSize != null && Object.hasOwnProperty.call(message, "heapSize")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.heapSize); - if (message.eventType != null && Object.hasOwnProperty.call(message, "eventType")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.eventType); - if (message.ipid != null && Object.hasOwnProperty.call(message, "ipid")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.ipid); - return writer; - }; - - /** - * Encodes the specified SphNativeMemoryNormalData message, length delimited. Does not implicitly {@link SphNativeMemoryNormalData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphNativeMemoryNormalData - * @static - * @param {ISphNativeMemoryNormalData} message SphNativeMemoryNormalData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphNativeMemoryNormalData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphNativeMemoryNormalData message from the specified reader or buffer. - * @function decode - * @memberof SphNativeMemoryNormalData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphNativeMemoryNormalData} SphNativeMemoryNormalData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphNativeMemoryNormalData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphNativeMemoryNormalData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.startTime = reader.int64(); - break; - } - case 2: { - message.heapSize = reader.int64(); - break; - } - case 3: { - message.eventType = reader.int64(); - break; - } - case 4: { - message.ipid = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphNativeMemoryNormalData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphNativeMemoryNormalData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphNativeMemoryNormalData} SphNativeMemoryNormalData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphNativeMemoryNormalData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphNativeMemoryNormalData message. - * @function verify - * @memberof SphNativeMemoryNormalData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphNativeMemoryNormalData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.heapSize != null && message.hasOwnProperty("heapSize")) - if (!$util.isInteger(message.heapSize) && !(message.heapSize && $util.isInteger(message.heapSize.low) && $util.isInteger(message.heapSize.high))) - return "heapSize: integer|Long expected"; - if (message.eventType != null && message.hasOwnProperty("eventType")) - if (!$util.isInteger(message.eventType) && !(message.eventType && $util.isInteger(message.eventType.low) && $util.isInteger(message.eventType.high))) - return "eventType: integer|Long expected"; - if (message.ipid != null && message.hasOwnProperty("ipid")) - if (!$util.isInteger(message.ipid) && !(message.ipid && $util.isInteger(message.ipid.low) && $util.isInteger(message.ipid.high))) - return "ipid: integer|Long expected"; - return null; - }; - - /** - * Creates a SphNativeMemoryNormalData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphNativeMemoryNormalData - * @static - * @param {Object.} object Plain object - * @returns {SphNativeMemoryNormalData} SphNativeMemoryNormalData - */ - SphNativeMemoryNormalData.fromObject = function fromObject(object) { - if (object instanceof $root.SphNativeMemoryNormalData) - return object; - var message = new $root.SphNativeMemoryNormalData(); - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.heapSize != null) - if ($util.Long) - (message.heapSize = $util.Long.fromValue(object.heapSize)).unsigned = false; - else if (typeof object.heapSize === "string") - message.heapSize = parseInt(object.heapSize, 10); - else if (typeof object.heapSize === "number") - message.heapSize = object.heapSize; - else if (typeof object.heapSize === "object") - message.heapSize = new $util.LongBits(object.heapSize.low >>> 0, object.heapSize.high >>> 0).toNumber(); - if (object.eventType != null) - if ($util.Long) - (message.eventType = $util.Long.fromValue(object.eventType)).unsigned = false; - else if (typeof object.eventType === "string") - message.eventType = parseInt(object.eventType, 10); - else if (typeof object.eventType === "number") - message.eventType = object.eventType; - else if (typeof object.eventType === "object") - message.eventType = new $util.LongBits(object.eventType.low >>> 0, object.eventType.high >>> 0).toNumber(); - if (object.ipid != null) - if ($util.Long) - (message.ipid = $util.Long.fromValue(object.ipid)).unsigned = false; - else if (typeof object.ipid === "string") - message.ipid = parseInt(object.ipid, 10); - else if (typeof object.ipid === "number") - message.ipid = object.ipid; - else if (typeof object.ipid === "object") - message.ipid = new $util.LongBits(object.ipid.low >>> 0, object.ipid.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphNativeMemoryNormalData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphNativeMemoryNormalData - * @static - * @param {SphNativeMemoryNormalData} message SphNativeMemoryNormalData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphNativeMemoryNormalData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.heapSize = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.heapSize = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.eventType = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.eventType = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ipid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ipid = options.longs === String ? "0" : 0; - } - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.heapSize != null && message.hasOwnProperty("heapSize")) - if (typeof message.heapSize === "number") - object.heapSize = options.longs === String ? String(message.heapSize) : message.heapSize; - else - object.heapSize = options.longs === String ? $util.Long.prototype.toString.call(message.heapSize) : options.longs === Number ? new $util.LongBits(message.heapSize.low >>> 0, message.heapSize.high >>> 0).toNumber() : message.heapSize; - if (message.eventType != null && message.hasOwnProperty("eventType")) - if (typeof message.eventType === "number") - object.eventType = options.longs === String ? String(message.eventType) : message.eventType; - else - object.eventType = options.longs === String ? $util.Long.prototype.toString.call(message.eventType) : options.longs === Number ? new $util.LongBits(message.eventType.low >>> 0, message.eventType.high >>> 0).toNumber() : message.eventType; - if (message.ipid != null && message.hasOwnProperty("ipid")) - if (typeof message.ipid === "number") - object.ipid = options.longs === String ? String(message.ipid) : message.ipid; - else - object.ipid = options.longs === String ? $util.Long.prototype.toString.call(message.ipid) : options.longs === Number ? new $util.LongBits(message.ipid.low >>> 0, message.ipid.high >>> 0).toNumber() : message.ipid; - return object; - }; - - /** - * Converts this SphNativeMemoryNormalData to JSON. - * @function toJSON - * @memberof SphNativeMemoryNormalData - * @instance - * @returns {Object.} JSON object - */ - SphNativeMemoryNormalData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphNativeMemoryNormalData - * @function getTypeUrl - * @memberof SphNativeMemoryNormalData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphNativeMemoryNormalData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphNativeMemoryNormalData"; - }; - - return SphNativeMemoryNormalData; -})(); - -$root.SphNativeMemoryStatisticData = (function () { - - /** - * Properties of a SphNativeMemoryStatisticData. - * @exports ISphNativeMemoryStatisticData - * @interface ISphNativeMemoryStatisticData - * @property {number|Long|null} [callchainId] SphNativeMemoryStatisticData callchainId - * @property {number|Long|null} [startTs] SphNativeMemoryStatisticData startTs - * @property {number|Long|null} [applyCount] SphNativeMemoryStatisticData applyCount - * @property {number|Long|null} [applySize] SphNativeMemoryStatisticData applySize - * @property {number|Long|null} [releaseCount] SphNativeMemoryStatisticData releaseCount - * @property {number|Long|null} [releaseSize] SphNativeMemoryStatisticData releaseSize - * @property {number|Long|null} [ipid] SphNativeMemoryStatisticData ipid - * @property {number|Long|null} [type] SphNativeMemoryStatisticData type - */ - - /** - * Constructs a new SphNativeMemoryStatisticData. - * @exports SphNativeMemoryStatisticData - * @classdesc Represents a SphNativeMemoryStatisticData. - * @implements ISphNativeMemoryStatisticData - * @constructor - * @param {ISphNativeMemoryStatisticData=} [properties] Properties to set - */ - function SphNativeMemoryStatisticData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphNativeMemoryStatisticData callchainId. - * @member {number|Long} callchainId - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.callchainId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData startTs. - * @member {number|Long} startTs - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData applyCount. - * @member {number|Long} applyCount - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.applyCount = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData applySize. - * @member {number|Long} applySize - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.applySize = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData releaseCount. - * @member {number|Long} releaseCount - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.releaseCount = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData releaseSize. - * @member {number|Long} releaseSize - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.releaseSize = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData ipid. - * @member {number|Long} ipid - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.ipid = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphNativeMemoryStatisticData type. - * @member {number|Long} type - * @memberof SphNativeMemoryStatisticData - * @instance - */ - SphNativeMemoryStatisticData.prototype.type = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphNativeMemoryStatisticData instance using the specified properties. - * @function create - * @memberof SphNativeMemoryStatisticData - * @static - * @param {ISphNativeMemoryStatisticData=} [properties] Properties to set - * @returns {SphNativeMemoryStatisticData} SphNativeMemoryStatisticData instance - */ - SphNativeMemoryStatisticData.create = function create(properties) { - return new SphNativeMemoryStatisticData(properties); - }; - - /** - * Encodes the specified SphNativeMemoryStatisticData message. Does not implicitly {@link SphNativeMemoryStatisticData.verify|verify} messages. - * @function encode - * @memberof SphNativeMemoryStatisticData - * @static - * @param {ISphNativeMemoryStatisticData} message SphNativeMemoryStatisticData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphNativeMemoryStatisticData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.callchainId != null && Object.hasOwnProperty.call(message, "callchainId")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.callchainId); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.startTs); - if (message.applyCount != null && Object.hasOwnProperty.call(message, "applyCount")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.applyCount); - if (message.applySize != null && Object.hasOwnProperty.call(message, "applySize")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.applySize); - if (message.releaseCount != null && Object.hasOwnProperty.call(message, "releaseCount")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.releaseCount); - if (message.releaseSize != null && Object.hasOwnProperty.call(message, "releaseSize")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.releaseSize); - if (message.ipid != null && Object.hasOwnProperty.call(message, "ipid")) - writer.uint32(/* id 7, wireType 0 =*/56).int64(message.ipid); - if (message.type != null && Object.hasOwnProperty.call(message, "type")) - writer.uint32(/* id 8, wireType 0 =*/64).int64(message.type); - return writer; - }; - - /** - * Encodes the specified SphNativeMemoryStatisticData message, length delimited. Does not implicitly {@link SphNativeMemoryStatisticData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphNativeMemoryStatisticData - * @static - * @param {ISphNativeMemoryStatisticData} message SphNativeMemoryStatisticData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphNativeMemoryStatisticData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphNativeMemoryStatisticData message from the specified reader or buffer. - * @function decode - * @memberof SphNativeMemoryStatisticData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphNativeMemoryStatisticData} SphNativeMemoryStatisticData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphNativeMemoryStatisticData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphNativeMemoryStatisticData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.callchainId = reader.int64(); - break; - } - case 2: { - message.startTs = reader.int64(); - break; - } - case 3: { - message.applyCount = reader.int64(); - break; - } - case 4: { - message.applySize = reader.int64(); - break; - } - case 5: { - message.releaseCount = reader.int64(); - break; - } - case 6: { - message.releaseSize = reader.int64(); - break; - } - case 7: { - message.ipid = reader.int64(); - break; - } - case 8: { - message.type = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphNativeMemoryStatisticData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphNativeMemoryStatisticData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphNativeMemoryStatisticData} SphNativeMemoryStatisticData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphNativeMemoryStatisticData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphNativeMemoryStatisticData message. - * @function verify - * @memberof SphNativeMemoryStatisticData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphNativeMemoryStatisticData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (!$util.isInteger(message.callchainId) && !(message.callchainId && $util.isInteger(message.callchainId.low) && $util.isInteger(message.callchainId.high))) - return "callchainId: integer|Long expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.applyCount != null && message.hasOwnProperty("applyCount")) - if (!$util.isInteger(message.applyCount) && !(message.applyCount && $util.isInteger(message.applyCount.low) && $util.isInteger(message.applyCount.high))) - return "applyCount: integer|Long expected"; - if (message.applySize != null && message.hasOwnProperty("applySize")) - if (!$util.isInteger(message.applySize) && !(message.applySize && $util.isInteger(message.applySize.low) && $util.isInteger(message.applySize.high))) - return "applySize: integer|Long expected"; - if (message.releaseCount != null && message.hasOwnProperty("releaseCount")) - if (!$util.isInteger(message.releaseCount) && !(message.releaseCount && $util.isInteger(message.releaseCount.low) && $util.isInteger(message.releaseCount.high))) - return "releaseCount: integer|Long expected"; - if (message.releaseSize != null && message.hasOwnProperty("releaseSize")) - if (!$util.isInteger(message.releaseSize) && !(message.releaseSize && $util.isInteger(message.releaseSize.low) && $util.isInteger(message.releaseSize.high))) - return "releaseSize: integer|Long expected"; - if (message.ipid != null && message.hasOwnProperty("ipid")) - if (!$util.isInteger(message.ipid) && !(message.ipid && $util.isInteger(message.ipid.low) && $util.isInteger(message.ipid.high))) - return "ipid: integer|Long expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isInteger(message.type) && !(message.type && $util.isInteger(message.type.low) && $util.isInteger(message.type.high))) - return "type: integer|Long expected"; - return null; - }; - - /** - * Creates a SphNativeMemoryStatisticData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphNativeMemoryStatisticData - * @static - * @param {Object.} object Plain object - * @returns {SphNativeMemoryStatisticData} SphNativeMemoryStatisticData - */ - SphNativeMemoryStatisticData.fromObject = function fromObject(object) { - if (object instanceof $root.SphNativeMemoryStatisticData) - return object; - var message = new $root.SphNativeMemoryStatisticData(); - if (object.callchainId != null) - if ($util.Long) - (message.callchainId = $util.Long.fromValue(object.callchainId)).unsigned = false; - else if (typeof object.callchainId === "string") - message.callchainId = parseInt(object.callchainId, 10); - else if (typeof object.callchainId === "number") - message.callchainId = object.callchainId; - else if (typeof object.callchainId === "object") - message.callchainId = new $util.LongBits(object.callchainId.low >>> 0, object.callchainId.high >>> 0).toNumber(); - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.applyCount != null) - if ($util.Long) - (message.applyCount = $util.Long.fromValue(object.applyCount)).unsigned = false; - else if (typeof object.applyCount === "string") - message.applyCount = parseInt(object.applyCount, 10); - else if (typeof object.applyCount === "number") - message.applyCount = object.applyCount; - else if (typeof object.applyCount === "object") - message.applyCount = new $util.LongBits(object.applyCount.low >>> 0, object.applyCount.high >>> 0).toNumber(); - if (object.applySize != null) - if ($util.Long) - (message.applySize = $util.Long.fromValue(object.applySize)).unsigned = false; - else if (typeof object.applySize === "string") - message.applySize = parseInt(object.applySize, 10); - else if (typeof object.applySize === "number") - message.applySize = object.applySize; - else if (typeof object.applySize === "object") - message.applySize = new $util.LongBits(object.applySize.low >>> 0, object.applySize.high >>> 0).toNumber(); - if (object.releaseCount != null) - if ($util.Long) - (message.releaseCount = $util.Long.fromValue(object.releaseCount)).unsigned = false; - else if (typeof object.releaseCount === "string") - message.releaseCount = parseInt(object.releaseCount, 10); - else if (typeof object.releaseCount === "number") - message.releaseCount = object.releaseCount; - else if (typeof object.releaseCount === "object") - message.releaseCount = new $util.LongBits(object.releaseCount.low >>> 0, object.releaseCount.high >>> 0).toNumber(); - if (object.releaseSize != null) - if ($util.Long) - (message.releaseSize = $util.Long.fromValue(object.releaseSize)).unsigned = false; - else if (typeof object.releaseSize === "string") - message.releaseSize = parseInt(object.releaseSize, 10); - else if (typeof object.releaseSize === "number") - message.releaseSize = object.releaseSize; - else if (typeof object.releaseSize === "object") - message.releaseSize = new $util.LongBits(object.releaseSize.low >>> 0, object.releaseSize.high >>> 0).toNumber(); - if (object.ipid != null) - if ($util.Long) - (message.ipid = $util.Long.fromValue(object.ipid)).unsigned = false; - else if (typeof object.ipid === "string") - message.ipid = parseInt(object.ipid, 10); - else if (typeof object.ipid === "number") - message.ipid = object.ipid; - else if (typeof object.ipid === "object") - message.ipid = new $util.LongBits(object.ipid.low >>> 0, object.ipid.high >>> 0).toNumber(); - if (object.type != null) - if ($util.Long) - (message.type = $util.Long.fromValue(object.type)).unsigned = false; - else if (typeof object.type === "string") - message.type = parseInt(object.type, 10); - else if (typeof object.type === "number") - message.type = object.type; - else if (typeof object.type === "object") - message.type = new $util.LongBits(object.type.low >>> 0, object.type.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphNativeMemoryStatisticData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphNativeMemoryStatisticData - * @static - * @param {SphNativeMemoryStatisticData} message SphNativeMemoryStatisticData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphNativeMemoryStatisticData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.callchainId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.callchainId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.applyCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.applyCount = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.applySize = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.applySize = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.releaseCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.releaseCount = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.releaseSize = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.releaseSize = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.ipid = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.ipid = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.type = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.type = options.longs === String ? "0" : 0; - } - if (message.callchainId != null && message.hasOwnProperty("callchainId")) - if (typeof message.callchainId === "number") - object.callchainId = options.longs === String ? String(message.callchainId) : message.callchainId; - else - object.callchainId = options.longs === String ? $util.Long.prototype.toString.call(message.callchainId) : options.longs === Number ? new $util.LongBits(message.callchainId.low >>> 0, message.callchainId.high >>> 0).toNumber() : message.callchainId; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.applyCount != null && message.hasOwnProperty("applyCount")) - if (typeof message.applyCount === "number") - object.applyCount = options.longs === String ? String(message.applyCount) : message.applyCount; - else - object.applyCount = options.longs === String ? $util.Long.prototype.toString.call(message.applyCount) : options.longs === Number ? new $util.LongBits(message.applyCount.low >>> 0, message.applyCount.high >>> 0).toNumber() : message.applyCount; - if (message.applySize != null && message.hasOwnProperty("applySize")) - if (typeof message.applySize === "number") - object.applySize = options.longs === String ? String(message.applySize) : message.applySize; - else - object.applySize = options.longs === String ? $util.Long.prototype.toString.call(message.applySize) : options.longs === Number ? new $util.LongBits(message.applySize.low >>> 0, message.applySize.high >>> 0).toNumber() : message.applySize; - if (message.releaseCount != null && message.hasOwnProperty("releaseCount")) - if (typeof message.releaseCount === "number") - object.releaseCount = options.longs === String ? String(message.releaseCount) : message.releaseCount; - else - object.releaseCount = options.longs === String ? $util.Long.prototype.toString.call(message.releaseCount) : options.longs === Number ? new $util.LongBits(message.releaseCount.low >>> 0, message.releaseCount.high >>> 0).toNumber() : message.releaseCount; - if (message.releaseSize != null && message.hasOwnProperty("releaseSize")) - if (typeof message.releaseSize === "number") - object.releaseSize = options.longs === String ? String(message.releaseSize) : message.releaseSize; - else - object.releaseSize = options.longs === String ? $util.Long.prototype.toString.call(message.releaseSize) : options.longs === Number ? new $util.LongBits(message.releaseSize.low >>> 0, message.releaseSize.high >>> 0).toNumber() : message.releaseSize; - if (message.ipid != null && message.hasOwnProperty("ipid")) - if (typeof message.ipid === "number") - object.ipid = options.longs === String ? String(message.ipid) : message.ipid; - else - object.ipid = options.longs === String ? $util.Long.prototype.toString.call(message.ipid) : options.longs === Number ? new $util.LongBits(message.ipid.low >>> 0, message.ipid.high >>> 0).toNumber() : message.ipid; - if (message.type != null && message.hasOwnProperty("type")) - if (typeof message.type === "number") - object.type = options.longs === String ? String(message.type) : message.type; - else - object.type = options.longs === String ? $util.Long.prototype.toString.call(message.type) : options.longs === Number ? new $util.LongBits(message.type.low >>> 0, message.type.high >>> 0).toNumber() : message.type; - return object; - }; - - /** - * Converts this SphNativeMemoryStatisticData to JSON. - * @function toJSON - * @memberof SphNativeMemoryStatisticData - * @instance - * @returns {Object.} JSON object - */ - SphNativeMemoryStatisticData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphNativeMemoryStatisticData - * @function getTypeUrl - * @memberof SphNativeMemoryStatisticData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphNativeMemoryStatisticData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphNativeMemoryStatisticData"; - }; - - return SphNativeMemoryStatisticData; -})(); - -$root.SphHeapFilesData = (function () { - - /** - * Properties of a SphHeapFilesData. - * @exports ISphHeapFilesData - * @interface ISphHeapFilesData - * @property {number|Long|null} [id] SphHeapFilesData id - * @property {string|null} [name] SphHeapFilesData name - * @property {number|Long|null} [startTs] SphHeapFilesData startTs - * @property {number|Long|null} [endTs] SphHeapFilesData endTs - * @property {number|Long|null} [size] SphHeapFilesData size - * @property {number|null} [pid] SphHeapFilesData pid - */ - - /** - * Constructs a new SphHeapFilesData. - * @exports SphHeapFilesData - * @classdesc Represents a SphHeapFilesData. - * @implements ISphHeapFilesData - * @constructor - * @param {ISphHeapFilesData=} [properties] Properties to set - */ - function SphHeapFilesData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphHeapFilesData id. - * @member {number|Long} id - * @memberof SphHeapFilesData - * @instance - */ - SphHeapFilesData.prototype.id = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHeapFilesData name. - * @member {string} name - * @memberof SphHeapFilesData - * @instance - */ - SphHeapFilesData.prototype.name = ""; - - /** - * SphHeapFilesData startTs. - * @member {number|Long} startTs - * @memberof SphHeapFilesData - * @instance - */ - SphHeapFilesData.prototype.startTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHeapFilesData endTs. - * @member {number|Long} endTs - * @memberof SphHeapFilesData - * @instance - */ - SphHeapFilesData.prototype.endTs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHeapFilesData size. - * @member {number|Long} size - * @memberof SphHeapFilesData - * @instance - */ - SphHeapFilesData.prototype.size = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphHeapFilesData pid. - * @member {number} pid - * @memberof SphHeapFilesData - * @instance - */ - SphHeapFilesData.prototype.pid = 0; - - /** - * Creates a new SphHeapFilesData instance using the specified properties. - * @function create - * @memberof SphHeapFilesData - * @static - * @param {ISphHeapFilesData=} [properties] Properties to set - * @returns {SphHeapFilesData} SphHeapFilesData instance - */ - SphHeapFilesData.create = function create(properties) { - return new SphHeapFilesData(properties); - }; - - /** - * Encodes the specified SphHeapFilesData message. Does not implicitly {@link SphHeapFilesData.verify|verify} messages. - * @function encode - * @memberof SphHeapFilesData - * @static - * @param {ISphHeapFilesData} message SphHeapFilesData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHeapFilesData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.id); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.name); - if (message.startTs != null && Object.hasOwnProperty.call(message, "startTs")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startTs); - if (message.endTs != null && Object.hasOwnProperty.call(message, "endTs")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.endTs); - if (message.size != null && Object.hasOwnProperty.call(message, "size")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.size); - if (message.pid != null && Object.hasOwnProperty.call(message, "pid")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.pid); - return writer; - }; - - /** - * Encodes the specified SphHeapFilesData message, length delimited. Does not implicitly {@link SphHeapFilesData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphHeapFilesData - * @static - * @param {ISphHeapFilesData} message SphHeapFilesData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphHeapFilesData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphHeapFilesData message from the specified reader or buffer. - * @function decode - * @memberof SphHeapFilesData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphHeapFilesData} SphHeapFilesData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHeapFilesData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphHeapFilesData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int64(); - break; - } - case 2: { - message.name = reader.string(); - break; - } - case 3: { - message.startTs = reader.int64(); - break; - } - case 4: { - message.endTs = reader.int64(); - break; - } - case 5: { - message.size = reader.int64(); - break; - } - case 6: { - message.pid = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphHeapFilesData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphHeapFilesData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphHeapFilesData} SphHeapFilesData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphHeapFilesData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphHeapFilesData message. - * @function verify - * @memberof SphHeapFilesData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphHeapFilesData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) - return "id: integer|Long expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (!$util.isInteger(message.startTs) && !(message.startTs && $util.isInteger(message.startTs.low) && $util.isInteger(message.startTs.high))) - return "startTs: integer|Long expected"; - if (message.endTs != null && message.hasOwnProperty("endTs")) - if (!$util.isInteger(message.endTs) && !(message.endTs && $util.isInteger(message.endTs.low) && $util.isInteger(message.endTs.high))) - return "endTs: integer|Long expected"; - if (message.size != null && message.hasOwnProperty("size")) - if (!$util.isInteger(message.size) && !(message.size && $util.isInteger(message.size.low) && $util.isInteger(message.size.high))) - return "size: integer|Long expected"; - if (message.pid != null && message.hasOwnProperty("pid")) - if (!$util.isInteger(message.pid)) - return "pid: integer expected"; - return null; - }; - - /** - * Creates a SphHeapFilesData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphHeapFilesData - * @static - * @param {Object.} object Plain object - * @returns {SphHeapFilesData} SphHeapFilesData - */ - SphHeapFilesData.fromObject = function fromObject(object) { - if (object instanceof $root.SphHeapFilesData) - return object; - var message = new $root.SphHeapFilesData(); - if (object.id != null) - if ($util.Long) - (message.id = $util.Long.fromValue(object.id)).unsigned = false; - else if (typeof object.id === "string") - message.id = parseInt(object.id, 10); - else if (typeof object.id === "number") - message.id = object.id; - else if (typeof object.id === "object") - message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(); - if (object.name != null) - message.name = String(object.name); - if (object.startTs != null) - if ($util.Long) - (message.startTs = $util.Long.fromValue(object.startTs)).unsigned = false; - else if (typeof object.startTs === "string") - message.startTs = parseInt(object.startTs, 10); - else if (typeof object.startTs === "number") - message.startTs = object.startTs; - else if (typeof object.startTs === "object") - message.startTs = new $util.LongBits(object.startTs.low >>> 0, object.startTs.high >>> 0).toNumber(); - if (object.endTs != null) - if ($util.Long) - (message.endTs = $util.Long.fromValue(object.endTs)).unsigned = false; - else if (typeof object.endTs === "string") - message.endTs = parseInt(object.endTs, 10); - else if (typeof object.endTs === "number") - message.endTs = object.endTs; - else if (typeof object.endTs === "object") - message.endTs = new $util.LongBits(object.endTs.low >>> 0, object.endTs.high >>> 0).toNumber(); - if (object.size != null) - if ($util.Long) - (message.size = $util.Long.fromValue(object.size)).unsigned = false; - else if (typeof object.size === "string") - message.size = parseInt(object.size, 10); - else if (typeof object.size === "number") - message.size = object.size; - else if (typeof object.size === "object") - message.size = new $util.LongBits(object.size.low >>> 0, object.size.high >>> 0).toNumber(); - if (object.pid != null) - message.pid = object.pid | 0; - return message; - }; - - /** - * Creates a plain object from a SphHeapFilesData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphHeapFilesData - * @static - * @param {SphHeapFilesData} message SphHeapFilesData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphHeapFilesData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.id = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.id = options.longs === String ? "0" : 0; - object.name = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.endTs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.endTs = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.size = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.size = options.longs === String ? "0" : 0; - object.pid = 0; - } - if (message.id != null && message.hasOwnProperty("id")) - if (typeof message.id === "number") - object.id = options.longs === String ? String(message.id) : message.id; - else - object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber() : message.id; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.startTs != null && message.hasOwnProperty("startTs")) - if (typeof message.startTs === "number") - object.startTs = options.longs === String ? String(message.startTs) : message.startTs; - else - object.startTs = options.longs === String ? $util.Long.prototype.toString.call(message.startTs) : options.longs === Number ? new $util.LongBits(message.startTs.low >>> 0, message.startTs.high >>> 0).toNumber() : message.startTs; - if (message.endTs != null && message.hasOwnProperty("endTs")) - if (typeof message.endTs === "number") - object.endTs = options.longs === String ? String(message.endTs) : message.endTs; - else - object.endTs = options.longs === String ? $util.Long.prototype.toString.call(message.endTs) : options.longs === Number ? new $util.LongBits(message.endTs.low >>> 0, message.endTs.high >>> 0).toNumber() : message.endTs; - if (message.size != null && message.hasOwnProperty("size")) - if (typeof message.size === "number") - object.size = options.longs === String ? String(message.size) : message.size; - else - object.size = options.longs === String ? $util.Long.prototype.toString.call(message.size) : options.longs === Number ? new $util.LongBits(message.size.low >>> 0, message.size.high >>> 0).toNumber() : message.size; - if (message.pid != null && message.hasOwnProperty("pid")) - object.pid = message.pid; - return object; - }; - - /** - * Converts this SphHeapFilesData to JSON. - * @function toJSON - * @memberof SphHeapFilesData - * @instance - * @returns {Object.} JSON object - */ - SphHeapFilesData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphHeapFilesData - * @function getTypeUrl - * @memberof SphHeapFilesData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphHeapFilesData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphHeapFilesData"; - }; - - return SphHeapFilesData; -})(); - -$root.SphCpuProfilerData = (function () { - - /** - * Properties of a SphCpuProfilerData. - * @exports ISphCpuProfilerData - * @interface ISphCpuProfilerData - * @property {number|Long|null} [id] SphCpuProfilerData id - * @property {number|Long|null} [functionId] SphCpuProfilerData functionId - * @property {number|Long|null} [startTime] SphCpuProfilerData startTime - * @property {number|Long|null} [endTime] SphCpuProfilerData endTime - * @property {number|Long|null} [dur] SphCpuProfilerData dur - * @property {number|Long|null} [nameId] SphCpuProfilerData nameId - * @property {number|Long|null} [urlId] SphCpuProfilerData urlId - * @property {number|Long|null} [line] SphCpuProfilerData line - * @property {number|Long|null} [column] SphCpuProfilerData column - * @property {number|Long|null} [hitCount] SphCpuProfilerData hitCount - * @property {number|Long|null} [childrenString] SphCpuProfilerData childrenString - * @property {number|Long|null} [parentId] SphCpuProfilerData parentId - */ - - /** - * Constructs a new SphCpuProfilerData. - * @exports SphCpuProfilerData - * @classdesc Represents a SphCpuProfilerData. - * @implements ISphCpuProfilerData - * @constructor - * @param {ISphCpuProfilerData=} [properties] Properties to set - */ - function SphCpuProfilerData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphCpuProfilerData id. - * @member {number|Long} id - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.id = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData functionId. - * @member {number|Long} functionId - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.functionId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData startTime. - * @member {number|Long} startTime - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.startTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData endTime. - * @member {number|Long} endTime - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.endTime = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData dur. - * @member {number|Long} dur - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.dur = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData nameId. - * @member {number|Long} nameId - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.nameId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData urlId. - * @member {number|Long} urlId - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.urlId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData line. - * @member {number|Long} line - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.line = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData column. - * @member {number|Long} column - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.column = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData hitCount. - * @member {number|Long} hitCount - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.hitCount = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData childrenString. - * @member {number|Long} childrenString - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.childrenString = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuProfilerData parentId. - * @member {number|Long} parentId - * @memberof SphCpuProfilerData - * @instance - */ - SphCpuProfilerData.prototype.parentId = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * Creates a new SphCpuProfilerData instance using the specified properties. - * @function create - * @memberof SphCpuProfilerData - * @static - * @param {ISphCpuProfilerData=} [properties] Properties to set - * @returns {SphCpuProfilerData} SphCpuProfilerData instance - */ - SphCpuProfilerData.create = function create(properties) { - return new SphCpuProfilerData(properties); - }; - - /** - * Encodes the specified SphCpuProfilerData message. Does not implicitly {@link SphCpuProfilerData.verify|verify} messages. - * @function encode - * @memberof SphCpuProfilerData - * @static - * @param {ISphCpuProfilerData} message SphCpuProfilerData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuProfilerData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.id != null && Object.hasOwnProperty.call(message, "id")) - writer.uint32(/* id 1, wireType 0 =*/8).int64(message.id); - if (message.functionId != null && Object.hasOwnProperty.call(message, "functionId")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.functionId); - if (message.startTime != null && Object.hasOwnProperty.call(message, "startTime")) - writer.uint32(/* id 3, wireType 0 =*/24).int64(message.startTime); - if (message.endTime != null && Object.hasOwnProperty.call(message, "endTime")) - writer.uint32(/* id 4, wireType 0 =*/32).int64(message.endTime); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 5, wireType 0 =*/40).int64(message.dur); - if (message.nameId != null && Object.hasOwnProperty.call(message, "nameId")) - writer.uint32(/* id 6, wireType 0 =*/48).int64(message.nameId); - if (message.urlId != null && Object.hasOwnProperty.call(message, "urlId")) - writer.uint32(/* id 7, wireType 0 =*/56).int64(message.urlId); - if (message.line != null && Object.hasOwnProperty.call(message, "line")) - writer.uint32(/* id 8, wireType 0 =*/64).int64(message.line); - if (message.column != null && Object.hasOwnProperty.call(message, "column")) - writer.uint32(/* id 9, wireType 0 =*/72).int64(message.column); - if (message.hitCount != null && Object.hasOwnProperty.call(message, "hitCount")) - writer.uint32(/* id 10, wireType 0 =*/80).int64(message.hitCount); - if (message.childrenString != null && Object.hasOwnProperty.call(message, "childrenString")) - writer.uint32(/* id 11, wireType 0 =*/88).int64(message.childrenString); - if (message.parentId != null && Object.hasOwnProperty.call(message, "parentId")) - writer.uint32(/* id 12, wireType 0 =*/96).int64(message.parentId); - return writer; - }; - - /** - * Encodes the specified SphCpuProfilerData message, length delimited. Does not implicitly {@link SphCpuProfilerData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphCpuProfilerData - * @static - * @param {ISphCpuProfilerData} message SphCpuProfilerData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuProfilerData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphCpuProfilerData message from the specified reader or buffer. - * @function decode - * @memberof SphCpuProfilerData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphCpuProfilerData} SphCpuProfilerData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuProfilerData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphCpuProfilerData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.id = reader.int64(); - break; - } - case 2: { - message.functionId = reader.int64(); - break; - } - case 3: { - message.startTime = reader.int64(); - break; - } - case 4: { - message.endTime = reader.int64(); - break; - } - case 5: { - message.dur = reader.int64(); - break; - } - case 6: { - message.nameId = reader.int64(); - break; - } - case 7: { - message.urlId = reader.int64(); - break; - } - case 8: { - message.line = reader.int64(); - break; - } - case 9: { - message.column = reader.int64(); - break; - } - case 10: { - message.hitCount = reader.int64(); - break; - } - case 11: { - message.childrenString = reader.int64(); - break; - } - case 12: { - message.parentId = reader.int64(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphCpuProfilerData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphCpuProfilerData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphCpuProfilerData} SphCpuProfilerData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuProfilerData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphCpuProfilerData message. - * @function verify - * @memberof SphCpuProfilerData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphCpuProfilerData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.id != null && message.hasOwnProperty("id")) - if (!$util.isInteger(message.id) && !(message.id && $util.isInteger(message.id.low) && $util.isInteger(message.id.high))) - return "id: integer|Long expected"; - if (message.functionId != null && message.hasOwnProperty("functionId")) - if (!$util.isInteger(message.functionId) && !(message.functionId && $util.isInteger(message.functionId.low) && $util.isInteger(message.functionId.high))) - return "functionId: integer|Long expected"; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (!$util.isInteger(message.startTime) && !(message.startTime && $util.isInteger(message.startTime.low) && $util.isInteger(message.startTime.high))) - return "startTime: integer|Long expected"; - if (message.endTime != null && message.hasOwnProperty("endTime")) - if (!$util.isInteger(message.endTime) && !(message.endTime && $util.isInteger(message.endTime.low) && $util.isInteger(message.endTime.high))) - return "endTime: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur) && !(message.dur && $util.isInteger(message.dur.low) && $util.isInteger(message.dur.high))) - return "dur: integer|Long expected"; - if (message.nameId != null && message.hasOwnProperty("nameId")) - if (!$util.isInteger(message.nameId) && !(message.nameId && $util.isInteger(message.nameId.low) && $util.isInteger(message.nameId.high))) - return "nameId: integer|Long expected"; - if (message.urlId != null && message.hasOwnProperty("urlId")) - if (!$util.isInteger(message.urlId) && !(message.urlId && $util.isInteger(message.urlId.low) && $util.isInteger(message.urlId.high))) - return "urlId: integer|Long expected"; - if (message.line != null && message.hasOwnProperty("line")) - if (!$util.isInteger(message.line) && !(message.line && $util.isInteger(message.line.low) && $util.isInteger(message.line.high))) - return "line: integer|Long expected"; - if (message.column != null && message.hasOwnProperty("column")) - if (!$util.isInteger(message.column) && !(message.column && $util.isInteger(message.column.low) && $util.isInteger(message.column.high))) - return "column: integer|Long expected"; - if (message.hitCount != null && message.hasOwnProperty("hitCount")) - if (!$util.isInteger(message.hitCount) && !(message.hitCount && $util.isInteger(message.hitCount.low) && $util.isInteger(message.hitCount.high))) - return "hitCount: integer|Long expected"; - if (message.childrenString != null && message.hasOwnProperty("childrenString")) - if (!$util.isInteger(message.childrenString) && !(message.childrenString && $util.isInteger(message.childrenString.low) && $util.isInteger(message.childrenString.high))) - return "childrenString: integer|Long expected"; - if (message.parentId != null && message.hasOwnProperty("parentId")) - if (!$util.isInteger(message.parentId) && !(message.parentId && $util.isInteger(message.parentId.low) && $util.isInteger(message.parentId.high))) - return "parentId: integer|Long expected"; - return null; - }; - - /** - * Creates a SphCpuProfilerData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphCpuProfilerData - * @static - * @param {Object.} object Plain object - * @returns {SphCpuProfilerData} SphCpuProfilerData - */ - SphCpuProfilerData.fromObject = function fromObject(object) { - if (object instanceof $root.SphCpuProfilerData) - return object; - var message = new $root.SphCpuProfilerData(); - if (object.id != null) - if ($util.Long) - (message.id = $util.Long.fromValue(object.id)).unsigned = false; - else if (typeof object.id === "string") - message.id = parseInt(object.id, 10); - else if (typeof object.id === "number") - message.id = object.id; - else if (typeof object.id === "object") - message.id = new $util.LongBits(object.id.low >>> 0, object.id.high >>> 0).toNumber(); - if (object.functionId != null) - if ($util.Long) - (message.functionId = $util.Long.fromValue(object.functionId)).unsigned = false; - else if (typeof object.functionId === "string") - message.functionId = parseInt(object.functionId, 10); - else if (typeof object.functionId === "number") - message.functionId = object.functionId; - else if (typeof object.functionId === "object") - message.functionId = new $util.LongBits(object.functionId.low >>> 0, object.functionId.high >>> 0).toNumber(); - if (object.startTime != null) - if ($util.Long) - (message.startTime = $util.Long.fromValue(object.startTime)).unsigned = false; - else if (typeof object.startTime === "string") - message.startTime = parseInt(object.startTime, 10); - else if (typeof object.startTime === "number") - message.startTime = object.startTime; - else if (typeof object.startTime === "object") - message.startTime = new $util.LongBits(object.startTime.low >>> 0, object.startTime.high >>> 0).toNumber(); - if (object.endTime != null) - if ($util.Long) - (message.endTime = $util.Long.fromValue(object.endTime)).unsigned = false; - else if (typeof object.endTime === "string") - message.endTime = parseInt(object.endTime, 10); - else if (typeof object.endTime === "number") - message.endTime = object.endTime; - else if (typeof object.endTime === "object") - message.endTime = new $util.LongBits(object.endTime.low >>> 0, object.endTime.high >>> 0).toNumber(); - if (object.dur != null) - if ($util.Long) - (message.dur = $util.Long.fromValue(object.dur)).unsigned = false; - else if (typeof object.dur === "string") - message.dur = parseInt(object.dur, 10); - else if (typeof object.dur === "number") - message.dur = object.dur; - else if (typeof object.dur === "object") - message.dur = new $util.LongBits(object.dur.low >>> 0, object.dur.high >>> 0).toNumber(); - if (object.nameId != null) - if ($util.Long) - (message.nameId = $util.Long.fromValue(object.nameId)).unsigned = false; - else if (typeof object.nameId === "string") - message.nameId = parseInt(object.nameId, 10); - else if (typeof object.nameId === "number") - message.nameId = object.nameId; - else if (typeof object.nameId === "object") - message.nameId = new $util.LongBits(object.nameId.low >>> 0, object.nameId.high >>> 0).toNumber(); - if (object.urlId != null) - if ($util.Long) - (message.urlId = $util.Long.fromValue(object.urlId)).unsigned = false; - else if (typeof object.urlId === "string") - message.urlId = parseInt(object.urlId, 10); - else if (typeof object.urlId === "number") - message.urlId = object.urlId; - else if (typeof object.urlId === "object") - message.urlId = new $util.LongBits(object.urlId.low >>> 0, object.urlId.high >>> 0).toNumber(); - if (object.line != null) - if ($util.Long) - (message.line = $util.Long.fromValue(object.line)).unsigned = false; - else if (typeof object.line === "string") - message.line = parseInt(object.line, 10); - else if (typeof object.line === "number") - message.line = object.line; - else if (typeof object.line === "object") - message.line = new $util.LongBits(object.line.low >>> 0, object.line.high >>> 0).toNumber(); - if (object.column != null) - if ($util.Long) - (message.column = $util.Long.fromValue(object.column)).unsigned = false; - else if (typeof object.column === "string") - message.column = parseInt(object.column, 10); - else if (typeof object.column === "number") - message.column = object.column; - else if (typeof object.column === "object") - message.column = new $util.LongBits(object.column.low >>> 0, object.column.high >>> 0).toNumber(); - if (object.hitCount != null) - if ($util.Long) - (message.hitCount = $util.Long.fromValue(object.hitCount)).unsigned = false; - else if (typeof object.hitCount === "string") - message.hitCount = parseInt(object.hitCount, 10); - else if (typeof object.hitCount === "number") - message.hitCount = object.hitCount; - else if (typeof object.hitCount === "object") - message.hitCount = new $util.LongBits(object.hitCount.low >>> 0, object.hitCount.high >>> 0).toNumber(); - if (object.childrenString != null) - if ($util.Long) - (message.childrenString = $util.Long.fromValue(object.childrenString)).unsigned = false; - else if (typeof object.childrenString === "string") - message.childrenString = parseInt(object.childrenString, 10); - else if (typeof object.childrenString === "number") - message.childrenString = object.childrenString; - else if (typeof object.childrenString === "object") - message.childrenString = new $util.LongBits(object.childrenString.low >>> 0, object.childrenString.high >>> 0).toNumber(); - if (object.parentId != null) - if ($util.Long) - (message.parentId = $util.Long.fromValue(object.parentId)).unsigned = false; - else if (typeof object.parentId === "string") - message.parentId = parseInt(object.parentId, 10); - else if (typeof object.parentId === "number") - message.parentId = object.parentId; - else if (typeof object.parentId === "object") - message.parentId = new $util.LongBits(object.parentId.low >>> 0, object.parentId.high >>> 0).toNumber(); - return message; - }; - - /** - * Creates a plain object from a SphCpuProfilerData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphCpuProfilerData - * @static - * @param {SphCpuProfilerData} message SphCpuProfilerData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphCpuProfilerData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.id = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.id = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.functionId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.functionId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.endTime = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.endTime = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.dur = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.dur = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.nameId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.nameId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.urlId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.urlId = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.line = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.line = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.column = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.column = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.hitCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.hitCount = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.childrenString = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.childrenString = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.parentId = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.parentId = options.longs === String ? "0" : 0; - } - if (message.id != null && message.hasOwnProperty("id")) - if (typeof message.id === "number") - object.id = options.longs === String ? String(message.id) : message.id; - else - object.id = options.longs === String ? $util.Long.prototype.toString.call(message.id) : options.longs === Number ? new $util.LongBits(message.id.low >>> 0, message.id.high >>> 0).toNumber() : message.id; - if (message.functionId != null && message.hasOwnProperty("functionId")) - if (typeof message.functionId === "number") - object.functionId = options.longs === String ? String(message.functionId) : message.functionId; - else - object.functionId = options.longs === String ? $util.Long.prototype.toString.call(message.functionId) : options.longs === Number ? new $util.LongBits(message.functionId.low >>> 0, message.functionId.high >>> 0).toNumber() : message.functionId; - if (message.startTime != null && message.hasOwnProperty("startTime")) - if (typeof message.startTime === "number") - object.startTime = options.longs === String ? String(message.startTime) : message.startTime; - else - object.startTime = options.longs === String ? $util.Long.prototype.toString.call(message.startTime) : options.longs === Number ? new $util.LongBits(message.startTime.low >>> 0, message.startTime.high >>> 0).toNumber() : message.startTime; - if (message.endTime != null && message.hasOwnProperty("endTime")) - if (typeof message.endTime === "number") - object.endTime = options.longs === String ? String(message.endTime) : message.endTime; - else - object.endTime = options.longs === String ? $util.Long.prototype.toString.call(message.endTime) : options.longs === Number ? new $util.LongBits(message.endTime.low >>> 0, message.endTime.high >>> 0).toNumber() : message.endTime; - if (message.dur != null && message.hasOwnProperty("dur")) - if (typeof message.dur === "number") - object.dur = options.longs === String ? String(message.dur) : message.dur; - else - object.dur = options.longs === String ? $util.Long.prototype.toString.call(message.dur) : options.longs === Number ? new $util.LongBits(message.dur.low >>> 0, message.dur.high >>> 0).toNumber() : message.dur; - if (message.nameId != null && message.hasOwnProperty("nameId")) - if (typeof message.nameId === "number") - object.nameId = options.longs === String ? String(message.nameId) : message.nameId; - else - object.nameId = options.longs === String ? $util.Long.prototype.toString.call(message.nameId) : options.longs === Number ? new $util.LongBits(message.nameId.low >>> 0, message.nameId.high >>> 0).toNumber() : message.nameId; - if (message.urlId != null && message.hasOwnProperty("urlId")) - if (typeof message.urlId === "number") - object.urlId = options.longs === String ? String(message.urlId) : message.urlId; - else - object.urlId = options.longs === String ? $util.Long.prototype.toString.call(message.urlId) : options.longs === Number ? new $util.LongBits(message.urlId.low >>> 0, message.urlId.high >>> 0).toNumber() : message.urlId; - if (message.line != null && message.hasOwnProperty("line")) - if (typeof message.line === "number") - object.line = options.longs === String ? String(message.line) : message.line; - else - object.line = options.longs === String ? $util.Long.prototype.toString.call(message.line) : options.longs === Number ? new $util.LongBits(message.line.low >>> 0, message.line.high >>> 0).toNumber() : message.line; - if (message.column != null && message.hasOwnProperty("column")) - if (typeof message.column === "number") - object.column = options.longs === String ? String(message.column) : message.column; - else - object.column = options.longs === String ? $util.Long.prototype.toString.call(message.column) : options.longs === Number ? new $util.LongBits(message.column.low >>> 0, message.column.high >>> 0).toNumber() : message.column; - if (message.hitCount != null && message.hasOwnProperty("hitCount")) - if (typeof message.hitCount === "number") - object.hitCount = options.longs === String ? String(message.hitCount) : message.hitCount; - else - object.hitCount = options.longs === String ? $util.Long.prototype.toString.call(message.hitCount) : options.longs === Number ? new $util.LongBits(message.hitCount.low >>> 0, message.hitCount.high >>> 0).toNumber() : message.hitCount; - if (message.childrenString != null && message.hasOwnProperty("childrenString")) - if (typeof message.childrenString === "number") - object.childrenString = options.longs === String ? String(message.childrenString) : message.childrenString; - else - object.childrenString = options.longs === String ? $util.Long.prototype.toString.call(message.childrenString) : options.longs === Number ? new $util.LongBits(message.childrenString.low >>> 0, message.childrenString.high >>> 0).toNumber() : message.childrenString; - if (message.parentId != null && message.hasOwnProperty("parentId")) - if (typeof message.parentId === "number") - object.parentId = options.longs === String ? String(message.parentId) : message.parentId; - else - object.parentId = options.longs === String ? $util.Long.prototype.toString.call(message.parentId) : options.longs === Number ? new $util.LongBits(message.parentId.low >>> 0, message.parentId.high >>> 0).toNumber() : message.parentId; - return object; - }; - - /** - * Converts this SphCpuProfilerData to JSON. - * @function toJSON - * @memberof SphCpuProfilerData - * @instance - * @returns {Object.} JSON object - */ - SphCpuProfilerData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphCpuProfilerData - * @function getTypeUrl - * @memberof SphCpuProfilerData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphCpuProfilerData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphCpuProfilerData"; - }; - - return SphCpuProfilerData; -})(); - -$root.SphCpuAbilityData = (function () { - - /** - * Properties of a SphCpuAbilityData. - * @exports ISphCpuAbilityData - * @interface ISphCpuAbilityData - * @property {string|null} [value] SphCpuAbilityData value - * @property {number|Long|null} [startNs] SphCpuAbilityData startNs - * @property {number|null} [dur] SphCpuAbilityData dur - */ - - /** - * Constructs a new SphCpuAbilityData. - * @exports SphCpuAbilityData - * @classdesc Represents a SphCpuAbilityData. - * @implements ISphCpuAbilityData - * @constructor - * @param {ISphCpuAbilityData=} [properties] Properties to set - */ - function SphCpuAbilityData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphCpuAbilityData value. - * @member {string} value - * @memberof SphCpuAbilityData - * @instance - */ - SphCpuAbilityData.prototype.value = ""; - - /** - * SphCpuAbilityData startNs. - * @member {number|Long} startNs - * @memberof SphCpuAbilityData - * @instance - */ - SphCpuAbilityData.prototype.startNs = $util.Long ? $util.Long.fromBits(0, 0, false) : 0; - - /** - * SphCpuAbilityData dur. - * @member {number} dur - * @memberof SphCpuAbilityData - * @instance - */ - SphCpuAbilityData.prototype.dur = 0; - - /** - * Creates a new SphCpuAbilityData instance using the specified properties. - * @function create - * @memberof SphCpuAbilityData - * @static - * @param {ISphCpuAbilityData=} [properties] Properties to set - * @returns {SphCpuAbilityData} SphCpuAbilityData instance - */ - SphCpuAbilityData.create = function create(properties) { - return new SphCpuAbilityData(properties); - }; - - /** - * Encodes the specified SphCpuAbilityData message. Does not implicitly {@link SphCpuAbilityData.verify|verify} messages. - * @function encode - * @memberof SphCpuAbilityData - * @static - * @param {ISphCpuAbilityData} message SphCpuAbilityData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuAbilityData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.value); - if (message.startNs != null && Object.hasOwnProperty.call(message, "startNs")) - writer.uint32(/* id 2, wireType 0 =*/16).int64(message.startNs); - if (message.dur != null && Object.hasOwnProperty.call(message, "dur")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.dur); - return writer; - }; - - /** - * Encodes the specified SphCpuAbilityData message, length delimited. Does not implicitly {@link SphCpuAbilityData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphCpuAbilityData - * @static - * @param {ISphCpuAbilityData} message SphCpuAbilityData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphCpuAbilityData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphCpuAbilityData message from the specified reader or buffer. - * @function decode - * @memberof SphCpuAbilityData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphCpuAbilityData} SphCpuAbilityData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuAbilityData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphCpuAbilityData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.value = reader.string(); - break; - } - case 2: { - message.startNs = reader.int64(); - break; - } - case 3: { - message.dur = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphCpuAbilityData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphCpuAbilityData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphCpuAbilityData} SphCpuAbilityData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphCpuAbilityData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphCpuAbilityData message. - * @function verify - * @memberof SphCpuAbilityData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphCpuAbilityData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isString(message.value)) - return "value: string expected"; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (!$util.isInteger(message.startNs) && !(message.startNs && $util.isInteger(message.startNs.low) && $util.isInteger(message.startNs.high))) - return "startNs: integer|Long expected"; - if (message.dur != null && message.hasOwnProperty("dur")) - if (!$util.isInteger(message.dur)) - return "dur: integer expected"; - return null; - }; - - /** - * Creates a SphCpuAbilityData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphCpuAbilityData - * @static - * @param {Object.} object Plain object - * @returns {SphCpuAbilityData} SphCpuAbilityData - */ - SphCpuAbilityData.fromObject = function fromObject(object) { - if (object instanceof $root.SphCpuAbilityData) - return object; - var message = new $root.SphCpuAbilityData(); - if (object.value != null) - message.value = String(object.value); - if (object.startNs != null) - if ($util.Long) - (message.startNs = $util.Long.fromValue(object.startNs)).unsigned = false; - else if (typeof object.startNs === "string") - message.startNs = parseInt(object.startNs, 10); - else if (typeof object.startNs === "number") - message.startNs = object.startNs; - else if (typeof object.startNs === "object") - message.startNs = new $util.LongBits(object.startNs.low >>> 0, object.startNs.high >>> 0).toNumber(); - if (object.dur != null) - message.dur = object.dur | 0; - return message; - }; - - /** - * Creates a plain object from a SphCpuAbilityData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphCpuAbilityData - * @static - * @param {SphCpuAbilityData} message SphCpuAbilityData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphCpuAbilityData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.value = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startNs = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.startNs = options.longs === String ? "0" : 0; - object.dur = 0; - } - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.startNs != null && message.hasOwnProperty("startNs")) - if (typeof message.startNs === "number") - object.startNs = options.longs === String ? String(message.startNs) : message.startNs; - else - object.startNs = options.longs === String ? $util.Long.prototype.toString.call(message.startNs) : options.longs === Number ? new $util.LongBits(message.startNs.low >>> 0, message.startNs.high >>> 0).toNumber() : message.startNs; - if (message.dur != null && message.hasOwnProperty("dur")) - object.dur = message.dur; - return object; - }; - - /** - * Converts this SphCpuAbilityData to JSON. - * @function toJSON - * @memberof SphCpuAbilityData - * @instance - * @returns {Object.} JSON object - */ - SphCpuAbilityData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphCpuAbilityData - * @function getTypeUrl - * @memberof SphCpuAbilityData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphCpuAbilityData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphCpuAbilityData"; - }; - - return SphCpuAbilityData; -})(); - -$root.SphData = (function () { - - /** - * Properties of a SphData. - * @exports ISphData - * @interface ISphData - * @property {ISphCpuData|null} [cpuData] SphData cpuData - * @property {ISphCpuStateData|null} [cpuStateData] SphData cpuStateData - * @property {ISphCpuFreqData|null} [cpuFreqData] SphData cpuFreqData - * @property {ISphCpuFreqLimitData|null} [cpuFreqLimitData] SphData cpuFreqLimitData - * @property {ISphClockData|null} [clockData] SphData clockData - * @property {ISphIrqData|null} [irqData] SphData irqData - * @property {ISphProcessData|null} [processData] SphData processData - * @property {ISphProcessMemData|null} [processMemData] SphData processMemData - * @property {ISphProcessStartupData|null} [processStartupData] SphData processStartupData - * @property {ISphProcessSoInitData|null} [processSoInitData] SphData processSoInitData - * @property {ISphHiSysEventData|null} [hiSysEventData] SphData hiSysEventData - * @property {ISphLogData|null} [logData] SphData logData - * @property {ISphVirtualMemData|null} [virtualMemData] SphData virtualMemData - * @property {ISphEnergyData|null} [energyData] SphData energyData - * @property {ISphFrameData|null} [frameData] SphData frameData - * @property {ISphFrameAnimationData|null} [frameAnimationData] SphData frameAnimationData - * @property {ISphFrameDynamicData|null} [frameDynamicData] SphData frameDynamicData - * @property {ISphFrameSpacingData|null} [frameSpacingData] SphData frameSpacingData - * @property {ISphEbpfData|null} [ebpfData] SphData ebpfData - * @property {ISphTrackerData|null} [trackerData] SphData trackerData - * @property {ISphAbilityData|null} [abilityData] SphData abilityData - * @property {ISphProcessThreadData|null} [processThreadData] SphData processThreadData - * @property {ISphProcessFuncData|null} [processFuncData] SphData processFuncData - * @property {ISphHiperfData|null} [hiperfData] SphData hiperfData - * @property {ISphHiperfCallChartData|null} [hiperfCallChartData] SphData hiperfCallChartData - * @property {ISphHiperfCallStackData|null} [hiperfCallStackData] SphData hiperfCallStackData - * @property {ISphProcessJanksFramesData|null} [processJanksFramesData] SphData processJanksFramesData - * @property {ISphProcessJanksActualData|null} [processJanksActualData] SphData processJanksActualData - * @property {ISphProcessInputEventData|null} [processInputEventData] SphData processInputEventData - * @property {ISphHeapFilesData|null} [heapFilesData] SphData heapFilesData - * @property {ISphCpuProfilerData|null} [cpuProfilerData] SphData cpuProfilerData - * @property {ISphNativeMemoryNormalData|null} [nativeMemoryNormal] SphData nativeMemoryNormal - * @property {ISphNativeMemoryStatisticData|null} [nativeMemoryStatistic] SphData nativeMemoryStatistic - * @property {ISphCpuAbilityData|null} [cpuAbilityData] SphData cpuAbilityData - */ - - /** - * Constructs a new SphData. - * @exports SphData - * @classdesc Represents a SphData. - * @implements ISphData - * @constructor - * @param {ISphData=} [properties] Properties to set - */ - function SphData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SphData cpuData. - * @member {ISphCpuData|null|undefined} cpuData - * @memberof SphData - * @instance - */ - SphData.prototype.cpuData = null; - - /** - * SphData cpuStateData. - * @member {ISphCpuStateData|null|undefined} cpuStateData - * @memberof SphData - * @instance - */ - SphData.prototype.cpuStateData = null; - - /** - * SphData cpuFreqData. - * @member {ISphCpuFreqData|null|undefined} cpuFreqData - * @memberof SphData - * @instance - */ - SphData.prototype.cpuFreqData = null; - - /** - * SphData cpuFreqLimitData. - * @member {ISphCpuFreqLimitData|null|undefined} cpuFreqLimitData - * @memberof SphData - * @instance - */ - SphData.prototype.cpuFreqLimitData = null; - - /** - * SphData clockData. - * @member {ISphClockData|null|undefined} clockData - * @memberof SphData - * @instance - */ - SphData.prototype.clockData = null; - - /** - * SphData irqData. - * @member {ISphIrqData|null|undefined} irqData - * @memberof SphData - * @instance - */ - SphData.prototype.irqData = null; - - /** - * SphData processData. - * @member {ISphProcessData|null|undefined} processData - * @memberof SphData - * @instance - */ - SphData.prototype.processData = null; - - /** - * SphData processMemData. - * @member {ISphProcessMemData|null|undefined} processMemData - * @memberof SphData - * @instance - */ - SphData.prototype.processMemData = null; - - /** - * SphData processStartupData. - * @member {ISphProcessStartupData|null|undefined} processStartupData - * @memberof SphData - * @instance - */ - SphData.prototype.processStartupData = null; - - /** - * SphData processSoInitData. - * @member {ISphProcessSoInitData|null|undefined} processSoInitData - * @memberof SphData - * @instance - */ - SphData.prototype.processSoInitData = null; - - /** - * SphData hiSysEventData. - * @member {ISphHiSysEventData|null|undefined} hiSysEventData - * @memberof SphData - * @instance - */ - SphData.prototype.hiSysEventData = null; - - /** - * SphData logData. - * @member {ISphLogData|null|undefined} logData - * @memberof SphData - * @instance - */ - SphData.prototype.logData = null; - - /** - * SphData virtualMemData. - * @member {ISphVirtualMemData|null|undefined} virtualMemData - * @memberof SphData - * @instance - */ - SphData.prototype.virtualMemData = null; - - /** - * SphData energyData. - * @member {ISphEnergyData|null|undefined} energyData - * @memberof SphData - * @instance - */ - SphData.prototype.energyData = null; - - /** - * SphData frameData. - * @member {ISphFrameData|null|undefined} frameData - * @memberof SphData - * @instance - */ - SphData.prototype.frameData = null; - - /** - * SphData frameAnimationData. - * @member {ISphFrameAnimationData|null|undefined} frameAnimationData - * @memberof SphData - * @instance - */ - SphData.prototype.frameAnimationData = null; - - /** - * SphData frameDynamicData. - * @member {ISphFrameDynamicData|null|undefined} frameDynamicData - * @memberof SphData - * @instance - */ - SphData.prototype.frameDynamicData = null; - - /** - * SphData frameSpacingData. - * @member {ISphFrameSpacingData|null|undefined} frameSpacingData - * @memberof SphData - * @instance - */ - SphData.prototype.frameSpacingData = null; - - /** - * SphData ebpfData. - * @member {ISphEbpfData|null|undefined} ebpfData - * @memberof SphData - * @instance - */ - SphData.prototype.ebpfData = null; - - /** - * SphData trackerData. - * @member {ISphTrackerData|null|undefined} trackerData - * @memberof SphData - * @instance - */ - SphData.prototype.trackerData = null; - - /** - * SphData abilityData. - * @member {ISphAbilityData|null|undefined} abilityData - * @memberof SphData - * @instance - */ - SphData.prototype.abilityData = null; - - /** - * SphData processThreadData. - * @member {ISphProcessThreadData|null|undefined} processThreadData - * @memberof SphData - * @instance - */ - SphData.prototype.processThreadData = null; - - /** - * SphData processFuncData. - * @member {ISphProcessFuncData|null|undefined} processFuncData - * @memberof SphData - * @instance - */ - SphData.prototype.processFuncData = null; - - /** - * SphData hiperfData. - * @member {ISphHiperfData|null|undefined} hiperfData - * @memberof SphData - * @instance - */ - SphData.prototype.hiperfData = null; - - /** - * SphData hiperfCallChartData. - * @member {ISphHiperfCallChartData|null|undefined} hiperfCallChartData - * @memberof SphData - * @instance - */ - SphData.prototype.hiperfCallChartData = null; - - /** - * SphData hiperfCallStackData. - * @member {ISphHiperfCallStackData|null|undefined} hiperfCallStackData - * @memberof SphData - * @instance - */ - SphData.prototype.hiperfCallStackData = null; - - /** - * SphData processJanksFramesData. - * @member {ISphProcessJanksFramesData|null|undefined} processJanksFramesData - * @memberof SphData - * @instance - */ - SphData.prototype.processJanksFramesData = null; - - /** - * SphData processJanksActualData. - * @member {ISphProcessJanksActualData|null|undefined} processJanksActualData - * @memberof SphData - * @instance - */ - SphData.prototype.processJanksActualData = null; - - /** - * SphData processInputEventData. - * @member {ISphProcessInputEventData|null|undefined} processInputEventData - * @memberof SphData - * @instance - */ - SphData.prototype.processInputEventData = null; - - /** - * SphData heapFilesData. - * @member {ISphHeapFilesData|null|undefined} heapFilesData - * @memberof SphData - * @instance - */ - SphData.prototype.heapFilesData = null; - - /** - * SphData cpuProfilerData. - * @member {ISphCpuProfilerData|null|undefined} cpuProfilerData - * @memberof SphData - * @instance - */ - SphData.prototype.cpuProfilerData = null; - - /** - * SphData nativeMemoryNormal. - * @member {ISphNativeMemoryNormalData|null|undefined} nativeMemoryNormal - * @memberof SphData - * @instance - */ - SphData.prototype.nativeMemoryNormal = null; - - /** - * SphData nativeMemoryStatistic. - * @member {ISphNativeMemoryStatisticData|null|undefined} nativeMemoryStatistic - * @memberof SphData - * @instance - */ - SphData.prototype.nativeMemoryStatistic = null; - - /** - * SphData cpuAbilityData. - * @member {ISphCpuAbilityData|null|undefined} cpuAbilityData - * @memberof SphData - * @instance - */ - SphData.prototype.cpuAbilityData = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * SphData event. - * @member {"cpuData"|"cpuStateData"|"cpuFreqData"|"cpuFreqLimitData"|"clockData"|"irqData"|"processData"|"processMemData"|"processStartupData"|"processSoInitData"|"hiSysEventData"|"logData"|"virtualMemData"|"energyData"|"frameData"|"frameAnimationData"|"frameDynamicData"|"frameSpacingData"|"ebpfData"|"trackerData"|"abilityData"|"processThreadData"|"processFuncData"|"hiperfData"|"hiperfCallChartData"|"hiperfCallStackData"|"processJanksFramesData"|"processJanksActualData"|"processInputEventData"|"heapFilesData"|"cpuProfilerData"|"nativeMemoryNormal"|"nativeMemoryStatistic"|"cpuAbilityData"|undefined} event - * @memberof SphData - * @instance - */ - Object.defineProperty(SphData.prototype, "event", { - get: $util.oneOfGetter($oneOfFields = ["cpuData", "cpuStateData", "cpuFreqData", "cpuFreqLimitData", "clockData", "irqData", "processData", "processMemData", "processStartupData", "processSoInitData", "hiSysEventData", "logData", "virtualMemData", "energyData", "frameData", "frameAnimationData", "frameDynamicData", "frameSpacingData", "ebpfData", "trackerData", "abilityData", "processThreadData", "processFuncData", "hiperfData", "hiperfCallChartData", "hiperfCallStackData", "processJanksFramesData", "processJanksActualData", "processInputEventData", "heapFilesData", "cpuProfilerData", "nativeMemoryNormal", "nativeMemoryStatistic", "cpuAbilityData"]), - set: $util.oneOfSetter($oneOfFields) - }); - - /** - * Creates a new SphData instance using the specified properties. - * @function create - * @memberof SphData - * @static - * @param {ISphData=} [properties] Properties to set - * @returns {SphData} SphData instance - */ - SphData.create = function create(properties) { - return new SphData(properties); - }; - - /** - * Encodes the specified SphData message. Does not implicitly {@link SphData.verify|verify} messages. - * @function encode - * @memberof SphData - * @static - * @param {ISphData} message SphData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.cpuData != null && Object.hasOwnProperty.call(message, "cpuData")) - $root.SphCpuData.encode(message.cpuData, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.cpuStateData != null && Object.hasOwnProperty.call(message, "cpuStateData")) - $root.SphCpuStateData.encode(message.cpuStateData, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.cpuFreqData != null && Object.hasOwnProperty.call(message, "cpuFreqData")) - $root.SphCpuFreqData.encode(message.cpuFreqData, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.cpuFreqLimitData != null && Object.hasOwnProperty.call(message, "cpuFreqLimitData")) - $root.SphCpuFreqLimitData.encode(message.cpuFreqLimitData, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.clockData != null && Object.hasOwnProperty.call(message, "clockData")) - $root.SphClockData.encode(message.clockData, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.irqData != null && Object.hasOwnProperty.call(message, "irqData")) - $root.SphIrqData.encode(message.irqData, writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim(); - if (message.processData != null && Object.hasOwnProperty.call(message, "processData")) - $root.SphProcessData.encode(message.processData, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); - if (message.processMemData != null && Object.hasOwnProperty.call(message, "processMemData")) - $root.SphProcessMemData.encode(message.processMemData, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); - if (message.processStartupData != null && Object.hasOwnProperty.call(message, "processStartupData")) - $root.SphProcessStartupData.encode(message.processStartupData, writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim(); - if (message.processSoInitData != null && Object.hasOwnProperty.call(message, "processSoInitData")) - $root.SphProcessSoInitData.encode(message.processSoInitData, writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); - if (message.hiSysEventData != null && Object.hasOwnProperty.call(message, "hiSysEventData")) - $root.SphHiSysEventData.encode(message.hiSysEventData, writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim(); - if (message.logData != null && Object.hasOwnProperty.call(message, "logData")) - $root.SphLogData.encode(message.logData, writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim(); - if (message.virtualMemData != null && Object.hasOwnProperty.call(message, "virtualMemData")) - $root.SphVirtualMemData.encode(message.virtualMemData, writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim(); - if (message.energyData != null && Object.hasOwnProperty.call(message, "energyData")) - $root.SphEnergyData.encode(message.energyData, writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim(); - if (message.frameData != null && Object.hasOwnProperty.call(message, "frameData")) - $root.SphFrameData.encode(message.frameData, writer.uint32(/* id 15, wireType 2 =*/122).fork()).ldelim(); - if (message.frameAnimationData != null && Object.hasOwnProperty.call(message, "frameAnimationData")) - $root.SphFrameAnimationData.encode(message.frameAnimationData, writer.uint32(/* id 16, wireType 2 =*/130).fork()).ldelim(); - if (message.frameDynamicData != null && Object.hasOwnProperty.call(message, "frameDynamicData")) - $root.SphFrameDynamicData.encode(message.frameDynamicData, writer.uint32(/* id 17, wireType 2 =*/138).fork()).ldelim(); - if (message.frameSpacingData != null && Object.hasOwnProperty.call(message, "frameSpacingData")) - $root.SphFrameSpacingData.encode(message.frameSpacingData, writer.uint32(/* id 18, wireType 2 =*/146).fork()).ldelim(); - if (message.ebpfData != null && Object.hasOwnProperty.call(message, "ebpfData")) - $root.SphEbpfData.encode(message.ebpfData, writer.uint32(/* id 19, wireType 2 =*/154).fork()).ldelim(); - if (message.trackerData != null && Object.hasOwnProperty.call(message, "trackerData")) - $root.SphTrackerData.encode(message.trackerData, writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); - if (message.abilityData != null && Object.hasOwnProperty.call(message, "abilityData")) - $root.SphAbilityData.encode(message.abilityData, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); - if (message.processThreadData != null && Object.hasOwnProperty.call(message, "processThreadData")) - $root.SphProcessThreadData.encode(message.processThreadData, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); - if (message.processFuncData != null && Object.hasOwnProperty.call(message, "processFuncData")) - $root.SphProcessFuncData.encode(message.processFuncData, writer.uint32(/* id 23, wireType 2 =*/186).fork()).ldelim(); - if (message.hiperfData != null && Object.hasOwnProperty.call(message, "hiperfData")) - $root.SphHiperfData.encode(message.hiperfData, writer.uint32(/* id 24, wireType 2 =*/194).fork()).ldelim(); - if (message.hiperfCallChartData != null && Object.hasOwnProperty.call(message, "hiperfCallChartData")) - $root.SphHiperfCallChartData.encode(message.hiperfCallChartData, writer.uint32(/* id 25, wireType 2 =*/202).fork()).ldelim(); - if (message.hiperfCallStackData != null && Object.hasOwnProperty.call(message, "hiperfCallStackData")) - $root.SphHiperfCallStackData.encode(message.hiperfCallStackData, writer.uint32(/* id 26, wireType 2 =*/210).fork()).ldelim(); - if (message.processJanksFramesData != null && Object.hasOwnProperty.call(message, "processJanksFramesData")) - $root.SphProcessJanksFramesData.encode(message.processJanksFramesData, writer.uint32(/* id 27, wireType 2 =*/218).fork()).ldelim(); - if (message.processJanksActualData != null && Object.hasOwnProperty.call(message, "processJanksActualData")) - $root.SphProcessJanksActualData.encode(message.processJanksActualData, writer.uint32(/* id 28, wireType 2 =*/226).fork()).ldelim(); - if (message.processInputEventData != null && Object.hasOwnProperty.call(message, "processInputEventData")) - $root.SphProcessInputEventData.encode(message.processInputEventData, writer.uint32(/* id 29, wireType 2 =*/234).fork()).ldelim(); - if (message.heapFilesData != null && Object.hasOwnProperty.call(message, "heapFilesData")) - $root.SphHeapFilesData.encode(message.heapFilesData, writer.uint32(/* id 30, wireType 2 =*/242).fork()).ldelim(); - if (message.cpuProfilerData != null && Object.hasOwnProperty.call(message, "cpuProfilerData")) - $root.SphCpuProfilerData.encode(message.cpuProfilerData, writer.uint32(/* id 31, wireType 2 =*/250).fork()).ldelim(); - if (message.nativeMemoryNormal != null && Object.hasOwnProperty.call(message, "nativeMemoryNormal")) - $root.SphNativeMemoryNormalData.encode(message.nativeMemoryNormal, writer.uint32(/* id 32, wireType 2 =*/258).fork()).ldelim(); - if (message.nativeMemoryStatistic != null && Object.hasOwnProperty.call(message, "nativeMemoryStatistic")) - $root.SphNativeMemoryStatisticData.encode(message.nativeMemoryStatistic, writer.uint32(/* id 33, wireType 2 =*/266).fork()).ldelim(); - if (message.cpuAbilityData != null && Object.hasOwnProperty.call(message, "cpuAbilityData")) - $root.SphCpuAbilityData.encode(message.cpuAbilityData, writer.uint32(/* id 34, wireType 2 =*/274).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified SphData message, length delimited. Does not implicitly {@link SphData.verify|verify} messages. - * @function encodeDelimited - * @memberof SphData - * @static - * @param {ISphData} message SphData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SphData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a SphData message from the specified reader or buffer. - * @function decode - * @memberof SphData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {SphData} SphData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SphData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - message.cpuData = $root.SphCpuData.decode(reader, reader.uint32()); - break; - } - case 2: { - message.cpuStateData = $root.SphCpuStateData.decode(reader, reader.uint32()); - break; - } - case 3: { - message.cpuFreqData = $root.SphCpuFreqData.decode(reader, reader.uint32()); - break; - } - case 4: { - message.cpuFreqLimitData = $root.SphCpuFreqLimitData.decode(reader, reader.uint32()); - break; - } - case 5: { - message.clockData = $root.SphClockData.decode(reader, reader.uint32()); - break; - } - case 6: { - message.irqData = $root.SphIrqData.decode(reader, reader.uint32()); - break; - } - case 7: { - message.processData = $root.SphProcessData.decode(reader, reader.uint32()); - break; - } - case 8: { - message.processMemData = $root.SphProcessMemData.decode(reader, reader.uint32()); - break; - } - case 9: { - message.processStartupData = $root.SphProcessStartupData.decode(reader, reader.uint32()); - break; - } - case 10: { - message.processSoInitData = $root.SphProcessSoInitData.decode(reader, reader.uint32()); - break; - } - case 11: { - message.hiSysEventData = $root.SphHiSysEventData.decode(reader, reader.uint32()); - break; - } - case 12: { - message.logData = $root.SphLogData.decode(reader, reader.uint32()); - break; - } - case 13: { - message.virtualMemData = $root.SphVirtualMemData.decode(reader, reader.uint32()); - break; - } - case 14: { - message.energyData = $root.SphEnergyData.decode(reader, reader.uint32()); - break; - } - case 15: { - message.frameData = $root.SphFrameData.decode(reader, reader.uint32()); - break; - } - case 16: { - message.frameAnimationData = $root.SphFrameAnimationData.decode(reader, reader.uint32()); - break; - } - case 17: { - message.frameDynamicData = $root.SphFrameDynamicData.decode(reader, reader.uint32()); - break; - } - case 18: { - message.frameSpacingData = $root.SphFrameSpacingData.decode(reader, reader.uint32()); - break; - } - case 19: { - message.ebpfData = $root.SphEbpfData.decode(reader, reader.uint32()); - break; - } - case 20: { - message.trackerData = $root.SphTrackerData.decode(reader, reader.uint32()); - break; - } - case 21: { - message.abilityData = $root.SphAbilityData.decode(reader, reader.uint32()); - break; - } - case 22: { - message.processThreadData = $root.SphProcessThreadData.decode(reader, reader.uint32()); - break; - } - case 23: { - message.processFuncData = $root.SphProcessFuncData.decode(reader, reader.uint32()); - break; - } - case 24: { - message.hiperfData = $root.SphHiperfData.decode(reader, reader.uint32()); - break; - } - case 25: { - message.hiperfCallChartData = $root.SphHiperfCallChartData.decode(reader, reader.uint32()); - break; - } - case 26: { - message.hiperfCallStackData = $root.SphHiperfCallStackData.decode(reader, reader.uint32()); - break; - } - case 27: { - message.processJanksFramesData = $root.SphProcessJanksFramesData.decode(reader, reader.uint32()); - break; - } - case 28: { - message.processJanksActualData = $root.SphProcessJanksActualData.decode(reader, reader.uint32()); - break; - } - case 29: { - message.processInputEventData = $root.SphProcessInputEventData.decode(reader, reader.uint32()); - break; - } - case 30: { - message.heapFilesData = $root.SphHeapFilesData.decode(reader, reader.uint32()); - break; - } - case 31: { - message.cpuProfilerData = $root.SphCpuProfilerData.decode(reader, reader.uint32()); - break; - } - case 32: { - message.nativeMemoryNormal = $root.SphNativeMemoryNormalData.decode(reader, reader.uint32()); - break; - } - case 33: { - message.nativeMemoryStatistic = $root.SphNativeMemoryStatisticData.decode(reader, reader.uint32()); - break; - } - case 34: { - message.cpuAbilityData = $root.SphCpuAbilityData.decode(reader, reader.uint32()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a SphData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof SphData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {SphData} SphData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SphData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a SphData message. - * @function verify - * @memberof SphData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SphData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.cpuData != null && message.hasOwnProperty("cpuData")) { - properties.event = 1; - { - var error = $root.SphCpuData.verify(message.cpuData); - if (error) - return "cpuData." + error; - } - } - if (message.cpuStateData != null && message.hasOwnProperty("cpuStateData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphCpuStateData.verify(message.cpuStateData); - if (error) - return "cpuStateData." + error; - } - } - if (message.cpuFreqData != null && message.hasOwnProperty("cpuFreqData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphCpuFreqData.verify(message.cpuFreqData); - if (error) - return "cpuFreqData." + error; - } - } - if (message.cpuFreqLimitData != null && message.hasOwnProperty("cpuFreqLimitData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphCpuFreqLimitData.verify(message.cpuFreqLimitData); - if (error) - return "cpuFreqLimitData." + error; - } - } - if (message.clockData != null && message.hasOwnProperty("clockData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphClockData.verify(message.clockData); - if (error) - return "clockData." + error; - } - } - if (message.irqData != null && message.hasOwnProperty("irqData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphIrqData.verify(message.irqData); - if (error) - return "irqData." + error; - } - } - if (message.processData != null && message.hasOwnProperty("processData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessData.verify(message.processData); - if (error) - return "processData." + error; - } - } - if (message.processMemData != null && message.hasOwnProperty("processMemData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessMemData.verify(message.processMemData); - if (error) - return "processMemData." + error; - } - } - if (message.processStartupData != null && message.hasOwnProperty("processStartupData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessStartupData.verify(message.processStartupData); - if (error) - return "processStartupData." + error; - } - } - if (message.processSoInitData != null && message.hasOwnProperty("processSoInitData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessSoInitData.verify(message.processSoInitData); - if (error) - return "processSoInitData." + error; - } - } - if (message.hiSysEventData != null && message.hasOwnProperty("hiSysEventData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphHiSysEventData.verify(message.hiSysEventData); - if (error) - return "hiSysEventData." + error; - } - } - if (message.logData != null && message.hasOwnProperty("logData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphLogData.verify(message.logData); - if (error) - return "logData." + error; - } - } - if (message.virtualMemData != null && message.hasOwnProperty("virtualMemData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphVirtualMemData.verify(message.virtualMemData); - if (error) - return "virtualMemData." + error; - } - } - if (message.energyData != null && message.hasOwnProperty("energyData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphEnergyData.verify(message.energyData); - if (error) - return "energyData." + error; - } - } - if (message.frameData != null && message.hasOwnProperty("frameData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphFrameData.verify(message.frameData); - if (error) - return "frameData." + error; - } - } - if (message.frameAnimationData != null && message.hasOwnProperty("frameAnimationData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphFrameAnimationData.verify(message.frameAnimationData); - if (error) - return "frameAnimationData." + error; - } - } - if (message.frameDynamicData != null && message.hasOwnProperty("frameDynamicData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphFrameDynamicData.verify(message.frameDynamicData); - if (error) - return "frameDynamicData." + error; - } - } - if (message.frameSpacingData != null && message.hasOwnProperty("frameSpacingData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphFrameSpacingData.verify(message.frameSpacingData); - if (error) - return "frameSpacingData." + error; - } - } - if (message.ebpfData != null && message.hasOwnProperty("ebpfData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphEbpfData.verify(message.ebpfData); - if (error) - return "ebpfData." + error; - } - } - if (message.trackerData != null && message.hasOwnProperty("trackerData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphTrackerData.verify(message.trackerData); - if (error) - return "trackerData." + error; - } - } - if (message.abilityData != null && message.hasOwnProperty("abilityData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphAbilityData.verify(message.abilityData); - if (error) - return "abilityData." + error; - } - } - if (message.processThreadData != null && message.hasOwnProperty("processThreadData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessThreadData.verify(message.processThreadData); - if (error) - return "processThreadData." + error; - } - } - if (message.processFuncData != null && message.hasOwnProperty("processFuncData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessFuncData.verify(message.processFuncData); - if (error) - return "processFuncData." + error; - } - } - if (message.hiperfData != null && message.hasOwnProperty("hiperfData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphHiperfData.verify(message.hiperfData); - if (error) - return "hiperfData." + error; - } - } - if (message.hiperfCallChartData != null && message.hasOwnProperty("hiperfCallChartData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphHiperfCallChartData.verify(message.hiperfCallChartData); - if (error) - return "hiperfCallChartData." + error; - } - } - if (message.hiperfCallStackData != null && message.hasOwnProperty("hiperfCallStackData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphHiperfCallStackData.verify(message.hiperfCallStackData); - if (error) - return "hiperfCallStackData." + error; - } - } - if (message.processJanksFramesData != null && message.hasOwnProperty("processJanksFramesData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessJanksFramesData.verify(message.processJanksFramesData); - if (error) - return "processJanksFramesData." + error; - } - } - if (message.processJanksActualData != null && message.hasOwnProperty("processJanksActualData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessJanksActualData.verify(message.processJanksActualData); - if (error) - return "processJanksActualData." + error; - } - } - if (message.processInputEventData != null && message.hasOwnProperty("processInputEventData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphProcessInputEventData.verify(message.processInputEventData); - if (error) - return "processInputEventData." + error; - } - } - if (message.heapFilesData != null && message.hasOwnProperty("heapFilesData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphHeapFilesData.verify(message.heapFilesData); - if (error) - return "heapFilesData." + error; - } - } - if (message.cpuProfilerData != null && message.hasOwnProperty("cpuProfilerData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphCpuProfilerData.verify(message.cpuProfilerData); - if (error) - return "cpuProfilerData." + error; - } - } - if (message.nativeMemoryNormal != null && message.hasOwnProperty("nativeMemoryNormal")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphNativeMemoryNormalData.verify(message.nativeMemoryNormal); - if (error) - return "nativeMemoryNormal." + error; - } - } - if (message.nativeMemoryStatistic != null && message.hasOwnProperty("nativeMemoryStatistic")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphNativeMemoryStatisticData.verify(message.nativeMemoryStatistic); - if (error) - return "nativeMemoryStatistic." + error; - } - } - if (message.cpuAbilityData != null && message.hasOwnProperty("cpuAbilityData")) { - if (properties.event === 1) - return "event: multiple values"; - properties.event = 1; - { - var error = $root.SphCpuAbilityData.verify(message.cpuAbilityData); - if (error) - return "cpuAbilityData." + error; - } - } - return null; - }; - - /** - * Creates a SphData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof SphData - * @static - * @param {Object.} object Plain object - * @returns {SphData} SphData - */ - SphData.fromObject = function fromObject(object) { - if (object instanceof $root.SphData) - return object; - var message = new $root.SphData(); - if (object.cpuData != null) { - if (typeof object.cpuData !== "object") - throw TypeError(".SphData.cpuData: object expected"); - message.cpuData = $root.SphCpuData.fromObject(object.cpuData); - } - if (object.cpuStateData != null) { - if (typeof object.cpuStateData !== "object") - throw TypeError(".SphData.cpuStateData: object expected"); - message.cpuStateData = $root.SphCpuStateData.fromObject(object.cpuStateData); - } - if (object.cpuFreqData != null) { - if (typeof object.cpuFreqData !== "object") - throw TypeError(".SphData.cpuFreqData: object expected"); - message.cpuFreqData = $root.SphCpuFreqData.fromObject(object.cpuFreqData); - } - if (object.cpuFreqLimitData != null) { - if (typeof object.cpuFreqLimitData !== "object") - throw TypeError(".SphData.cpuFreqLimitData: object expected"); - message.cpuFreqLimitData = $root.SphCpuFreqLimitData.fromObject(object.cpuFreqLimitData); - } - if (object.clockData != null) { - if (typeof object.clockData !== "object") - throw TypeError(".SphData.clockData: object expected"); - message.clockData = $root.SphClockData.fromObject(object.clockData); - } - if (object.irqData != null) { - if (typeof object.irqData !== "object") - throw TypeError(".SphData.irqData: object expected"); - message.irqData = $root.SphIrqData.fromObject(object.irqData); - } - if (object.processData != null) { - if (typeof object.processData !== "object") - throw TypeError(".SphData.processData: object expected"); - message.processData = $root.SphProcessData.fromObject(object.processData); - } - if (object.processMemData != null) { - if (typeof object.processMemData !== "object") - throw TypeError(".SphData.processMemData: object expected"); - message.processMemData = $root.SphProcessMemData.fromObject(object.processMemData); - } - if (object.processStartupData != null) { - if (typeof object.processStartupData !== "object") - throw TypeError(".SphData.processStartupData: object expected"); - message.processStartupData = $root.SphProcessStartupData.fromObject(object.processStartupData); - } - if (object.processSoInitData != null) { - if (typeof object.processSoInitData !== "object") - throw TypeError(".SphData.processSoInitData: object expected"); - message.processSoInitData = $root.SphProcessSoInitData.fromObject(object.processSoInitData); - } - if (object.hiSysEventData != null) { - if (typeof object.hiSysEventData !== "object") - throw TypeError(".SphData.hiSysEventData: object expected"); - message.hiSysEventData = $root.SphHiSysEventData.fromObject(object.hiSysEventData); - } - if (object.logData != null) { - if (typeof object.logData !== "object") - throw TypeError(".SphData.logData: object expected"); - message.logData = $root.SphLogData.fromObject(object.logData); - } - if (object.virtualMemData != null) { - if (typeof object.virtualMemData !== "object") - throw TypeError(".SphData.virtualMemData: object expected"); - message.virtualMemData = $root.SphVirtualMemData.fromObject(object.virtualMemData); - } - if (object.energyData != null) { - if (typeof object.energyData !== "object") - throw TypeError(".SphData.energyData: object expected"); - message.energyData = $root.SphEnergyData.fromObject(object.energyData); - } - if (object.frameData != null) { - if (typeof object.frameData !== "object") - throw TypeError(".SphData.frameData: object expected"); - message.frameData = $root.SphFrameData.fromObject(object.frameData); - } - if (object.frameAnimationData != null) { - if (typeof object.frameAnimationData !== "object") - throw TypeError(".SphData.frameAnimationData: object expected"); - message.frameAnimationData = $root.SphFrameAnimationData.fromObject(object.frameAnimationData); - } - if (object.frameDynamicData != null) { - if (typeof object.frameDynamicData !== "object") - throw TypeError(".SphData.frameDynamicData: object expected"); - message.frameDynamicData = $root.SphFrameDynamicData.fromObject(object.frameDynamicData); - } - if (object.frameSpacingData != null) { - if (typeof object.frameSpacingData !== "object") - throw TypeError(".SphData.frameSpacingData: object expected"); - message.frameSpacingData = $root.SphFrameSpacingData.fromObject(object.frameSpacingData); - } - if (object.ebpfData != null) { - if (typeof object.ebpfData !== "object") - throw TypeError(".SphData.ebpfData: object expected"); - message.ebpfData = $root.SphEbpfData.fromObject(object.ebpfData); - } - if (object.trackerData != null) { - if (typeof object.trackerData !== "object") - throw TypeError(".SphData.trackerData: object expected"); - message.trackerData = $root.SphTrackerData.fromObject(object.trackerData); - } - if (object.abilityData != null) { - if (typeof object.abilityData !== "object") - throw TypeError(".SphData.abilityData: object expected"); - message.abilityData = $root.SphAbilityData.fromObject(object.abilityData); - } - if (object.processThreadData != null) { - if (typeof object.processThreadData !== "object") - throw TypeError(".SphData.processThreadData: object expected"); - message.processThreadData = $root.SphProcessThreadData.fromObject(object.processThreadData); - } - if (object.processFuncData != null) { - if (typeof object.processFuncData !== "object") - throw TypeError(".SphData.processFuncData: object expected"); - message.processFuncData = $root.SphProcessFuncData.fromObject(object.processFuncData); - } - if (object.hiperfData != null) { - if (typeof object.hiperfData !== "object") - throw TypeError(".SphData.hiperfData: object expected"); - message.hiperfData = $root.SphHiperfData.fromObject(object.hiperfData); - } - if (object.hiperfCallChartData != null) { - if (typeof object.hiperfCallChartData !== "object") - throw TypeError(".SphData.hiperfCallChartData: object expected"); - message.hiperfCallChartData = $root.SphHiperfCallChartData.fromObject(object.hiperfCallChartData); - } - if (object.hiperfCallStackData != null) { - if (typeof object.hiperfCallStackData !== "object") - throw TypeError(".SphData.hiperfCallStackData: object expected"); - message.hiperfCallStackData = $root.SphHiperfCallStackData.fromObject(object.hiperfCallStackData); - } - if (object.processJanksFramesData != null) { - if (typeof object.processJanksFramesData !== "object") - throw TypeError(".SphData.processJanksFramesData: object expected"); - message.processJanksFramesData = $root.SphProcessJanksFramesData.fromObject(object.processJanksFramesData); - } - if (object.processJanksActualData != null) { - if (typeof object.processJanksActualData !== "object") - throw TypeError(".SphData.processJanksActualData: object expected"); - message.processJanksActualData = $root.SphProcessJanksActualData.fromObject(object.processJanksActualData); - } - if (object.processInputEventData != null) { - if (typeof object.processInputEventData !== "object") - throw TypeError(".SphData.processInputEventData: object expected"); - message.processInputEventData = $root.SphProcessInputEventData.fromObject(object.processInputEventData); - } - if (object.heapFilesData != null) { - if (typeof object.heapFilesData !== "object") - throw TypeError(".SphData.heapFilesData: object expected"); - message.heapFilesData = $root.SphHeapFilesData.fromObject(object.heapFilesData); - } - if (object.cpuProfilerData != null) { - if (typeof object.cpuProfilerData !== "object") - throw TypeError(".SphData.cpuProfilerData: object expected"); - message.cpuProfilerData = $root.SphCpuProfilerData.fromObject(object.cpuProfilerData); - } - if (object.nativeMemoryNormal != null) { - if (typeof object.nativeMemoryNormal !== "object") - throw TypeError(".SphData.nativeMemoryNormal: object expected"); - message.nativeMemoryNormal = $root.SphNativeMemoryNormalData.fromObject(object.nativeMemoryNormal); - } - if (object.nativeMemoryStatistic != null) { - if (typeof object.nativeMemoryStatistic !== "object") - throw TypeError(".SphData.nativeMemoryStatistic: object expected"); - message.nativeMemoryStatistic = $root.SphNativeMemoryStatisticData.fromObject(object.nativeMemoryStatistic); - } - if (object.cpuAbilityData != null) { - if (typeof object.cpuAbilityData !== "object") - throw TypeError(".SphData.cpuAbilityData: object expected"); - message.cpuAbilityData = $root.SphCpuAbilityData.fromObject(object.cpuAbilityData); - } - return message; - }; - - /** - * Creates a plain object from a SphData message. Also converts values to other types if specified. - * @function toObject - * @memberof SphData - * @static - * @param {SphData} message SphData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SphData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.cpuData != null && message.hasOwnProperty("cpuData")) { - object.cpuData = $root.SphCpuData.toObject(message.cpuData, options); - if (options.oneofs) - object.event = "cpuData"; - } - if (message.cpuStateData != null && message.hasOwnProperty("cpuStateData")) { - object.cpuStateData = $root.SphCpuStateData.toObject(message.cpuStateData, options); - if (options.oneofs) - object.event = "cpuStateData"; - } - if (message.cpuFreqData != null && message.hasOwnProperty("cpuFreqData")) { - object.cpuFreqData = $root.SphCpuFreqData.toObject(message.cpuFreqData, options); - if (options.oneofs) - object.event = "cpuFreqData"; - } - if (message.cpuFreqLimitData != null && message.hasOwnProperty("cpuFreqLimitData")) { - object.cpuFreqLimitData = $root.SphCpuFreqLimitData.toObject(message.cpuFreqLimitData, options); - if (options.oneofs) - object.event = "cpuFreqLimitData"; - } - if (message.clockData != null && message.hasOwnProperty("clockData")) { - object.clockData = $root.SphClockData.toObject(message.clockData, options); - if (options.oneofs) - object.event = "clockData"; - } - if (message.irqData != null && message.hasOwnProperty("irqData")) { - object.irqData = $root.SphIrqData.toObject(message.irqData, options); - if (options.oneofs) - object.event = "irqData"; - } - if (message.processData != null && message.hasOwnProperty("processData")) { - object.processData = $root.SphProcessData.toObject(message.processData, options); - if (options.oneofs) - object.event = "processData"; - } - if (message.processMemData != null && message.hasOwnProperty("processMemData")) { - object.processMemData = $root.SphProcessMemData.toObject(message.processMemData, options); - if (options.oneofs) - object.event = "processMemData"; - } - if (message.processStartupData != null && message.hasOwnProperty("processStartupData")) { - object.processStartupData = $root.SphProcessStartupData.toObject(message.processStartupData, options); - if (options.oneofs) - object.event = "processStartupData"; - } - if (message.processSoInitData != null && message.hasOwnProperty("processSoInitData")) { - object.processSoInitData = $root.SphProcessSoInitData.toObject(message.processSoInitData, options); - if (options.oneofs) - object.event = "processSoInitData"; - } - if (message.hiSysEventData != null && message.hasOwnProperty("hiSysEventData")) { - object.hiSysEventData = $root.SphHiSysEventData.toObject(message.hiSysEventData, options); - if (options.oneofs) - object.event = "hiSysEventData"; - } - if (message.logData != null && message.hasOwnProperty("logData")) { - object.logData = $root.SphLogData.toObject(message.logData, options); - if (options.oneofs) - object.event = "logData"; - } - if (message.virtualMemData != null && message.hasOwnProperty("virtualMemData")) { - object.virtualMemData = $root.SphVirtualMemData.toObject(message.virtualMemData, options); - if (options.oneofs) - object.event = "virtualMemData"; - } - if (message.energyData != null && message.hasOwnProperty("energyData")) { - object.energyData = $root.SphEnergyData.toObject(message.energyData, options); - if (options.oneofs) - object.event = "energyData"; - } - if (message.frameData != null && message.hasOwnProperty("frameData")) { - object.frameData = $root.SphFrameData.toObject(message.frameData, options); - if (options.oneofs) - object.event = "frameData"; - } - if (message.frameAnimationData != null && message.hasOwnProperty("frameAnimationData")) { - object.frameAnimationData = $root.SphFrameAnimationData.toObject(message.frameAnimationData, options); - if (options.oneofs) - object.event = "frameAnimationData"; - } - if (message.frameDynamicData != null && message.hasOwnProperty("frameDynamicData")) { - object.frameDynamicData = $root.SphFrameDynamicData.toObject(message.frameDynamicData, options); - if (options.oneofs) - object.event = "frameDynamicData"; - } - if (message.frameSpacingData != null && message.hasOwnProperty("frameSpacingData")) { - object.frameSpacingData = $root.SphFrameSpacingData.toObject(message.frameSpacingData, options); - if (options.oneofs) - object.event = "frameSpacingData"; - } - if (message.ebpfData != null && message.hasOwnProperty("ebpfData")) { - object.ebpfData = $root.SphEbpfData.toObject(message.ebpfData, options); - if (options.oneofs) - object.event = "ebpfData"; - } - if (message.trackerData != null && message.hasOwnProperty("trackerData")) { - object.trackerData = $root.SphTrackerData.toObject(message.trackerData, options); - if (options.oneofs) - object.event = "trackerData"; - } - if (message.abilityData != null && message.hasOwnProperty("abilityData")) { - object.abilityData = $root.SphAbilityData.toObject(message.abilityData, options); - if (options.oneofs) - object.event = "abilityData"; - } - if (message.processThreadData != null && message.hasOwnProperty("processThreadData")) { - object.processThreadData = $root.SphProcessThreadData.toObject(message.processThreadData, options); - if (options.oneofs) - object.event = "processThreadData"; - } - if (message.processFuncData != null && message.hasOwnProperty("processFuncData")) { - object.processFuncData = $root.SphProcessFuncData.toObject(message.processFuncData, options); - if (options.oneofs) - object.event = "processFuncData"; - } - if (message.hiperfData != null && message.hasOwnProperty("hiperfData")) { - object.hiperfData = $root.SphHiperfData.toObject(message.hiperfData, options); - if (options.oneofs) - object.event = "hiperfData"; - } - if (message.hiperfCallChartData != null && message.hasOwnProperty("hiperfCallChartData")) { - object.hiperfCallChartData = $root.SphHiperfCallChartData.toObject(message.hiperfCallChartData, options); - if (options.oneofs) - object.event = "hiperfCallChartData"; - } - if (message.hiperfCallStackData != null && message.hasOwnProperty("hiperfCallStackData")) { - object.hiperfCallStackData = $root.SphHiperfCallStackData.toObject(message.hiperfCallStackData, options); - if (options.oneofs) - object.event = "hiperfCallStackData"; - } - if (message.processJanksFramesData != null && message.hasOwnProperty("processJanksFramesData")) { - object.processJanksFramesData = $root.SphProcessJanksFramesData.toObject(message.processJanksFramesData, options); - if (options.oneofs) - object.event = "processJanksFramesData"; - } - if (message.processJanksActualData != null && message.hasOwnProperty("processJanksActualData")) { - object.processJanksActualData = $root.SphProcessJanksActualData.toObject(message.processJanksActualData, options); - if (options.oneofs) - object.event = "processJanksActualData"; - } - if (message.processInputEventData != null && message.hasOwnProperty("processInputEventData")) { - object.processInputEventData = $root.SphProcessInputEventData.toObject(message.processInputEventData, options); - if (options.oneofs) - object.event = "processInputEventData"; - } - if (message.heapFilesData != null && message.hasOwnProperty("heapFilesData")) { - object.heapFilesData = $root.SphHeapFilesData.toObject(message.heapFilesData, options); - if (options.oneofs) - object.event = "heapFilesData"; - } - if (message.cpuProfilerData != null && message.hasOwnProperty("cpuProfilerData")) { - object.cpuProfilerData = $root.SphCpuProfilerData.toObject(message.cpuProfilerData, options); - if (options.oneofs) - object.event = "cpuProfilerData"; - } - if (message.nativeMemoryNormal != null && message.hasOwnProperty("nativeMemoryNormal")) { - object.nativeMemoryNormal = $root.SphNativeMemoryNormalData.toObject(message.nativeMemoryNormal, options); - if (options.oneofs) - object.event = "nativeMemoryNormal"; - } - if (message.nativeMemoryStatistic != null && message.hasOwnProperty("nativeMemoryStatistic")) { - object.nativeMemoryStatistic = $root.SphNativeMemoryStatisticData.toObject(message.nativeMemoryStatistic, options); - if (options.oneofs) - object.event = "nativeMemoryStatistic"; - } - if (message.cpuAbilityData != null && message.hasOwnProperty("cpuAbilityData")) { - object.cpuAbilityData = $root.SphCpuAbilityData.toObject(message.cpuAbilityData, options); - if (options.oneofs) - object.event = "cpuAbilityData"; - } - return object; - }; - - /** - * Converts this SphData to JSON. - * @function toJSON - * @memberof SphData - * @instance - * @returns {Object.} JSON object - */ - SphData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SphData - * @function getTypeUrl - * @memberof SphData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SphData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/SphData"; - }; - - return SphData; -})(); - -$root.BatchSphData = (function () { - - /** - * Properties of a BatchSphData. - * @exports IBatchSphData - * @interface IBatchSphData - * @property {Array.|null} [values] BatchSphData values - */ - - /** - * Constructs a new BatchSphData. - * @exports BatchSphData - * @classdesc Represents a BatchSphData. - * @implements IBatchSphData - * @constructor - * @param {IBatchSphData=} [properties] Properties to set - */ - function BatchSphData(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BatchSphData values. - * @member {Array.} values - * @memberof BatchSphData - * @instance - */ - BatchSphData.prototype.values = $util.emptyArray; - - /** - * Creates a new BatchSphData instance using the specified properties. - * @function create - * @memberof BatchSphData - * @static - * @param {IBatchSphData=} [properties] Properties to set - * @returns {BatchSphData} BatchSphData instance - */ - BatchSphData.create = function create(properties) { - return new BatchSphData(properties); - }; - - /** - * Encodes the specified BatchSphData message. Does not implicitly {@link BatchSphData.verify|verify} messages. - * @function encode - * @memberof BatchSphData - * @static - * @param {IBatchSphData} message BatchSphData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BatchSphData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.values != null && message.values.length) - for (var i = 0; i < message.values.length; ++i) - $root.SphData.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; - - /** - * Encodes the specified BatchSphData message, length delimited. Does not implicitly {@link BatchSphData.verify|verify} messages. - * @function encodeDelimited - * @memberof BatchSphData - * @static - * @param {IBatchSphData} message BatchSphData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - BatchSphData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - - /** - * Decodes a BatchSphData message from the specified reader or buffer. - * @function decode - * @memberof BatchSphData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {BatchSphData} BatchSphData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BatchSphData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.BatchSphData(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: { - if (!(message.values && message.values.length)) - message.values = []; - message.values.push($root.SphData.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** - * Decodes a BatchSphData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof BatchSphData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {BatchSphData} BatchSphData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - BatchSphData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - - /** - * Verifies a BatchSphData message. - * @function verify - * @memberof BatchSphData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - BatchSphData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.values != null && message.hasOwnProperty("values")) { - if (!Array.isArray(message.values)) - return "values: array expected"; - for (var i = 0; i < message.values.length; ++i) { - var error = $root.SphData.verify(message.values[i]); - if (error) - return "values." + error; - } - } - return null; - }; - - /** - * Creates a BatchSphData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof BatchSphData - * @static - * @param {Object.} object Plain object - * @returns {BatchSphData} BatchSphData - */ - BatchSphData.fromObject = function fromObject(object) { - if (object instanceof $root.BatchSphData) - return object; - var message = new $root.BatchSphData(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".BatchSphData.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".BatchSphData.values: object expected"); - message.values[i] = $root.SphData.fromObject(object.values[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a BatchSphData message. Also converts values to other types if specified. - * @function toObject - * @memberof BatchSphData - * @static - * @param {BatchSphData} message BatchSphData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BatchSphData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.SphData.toObject(message.values[j], options); - } - return object; - }; - - /** - * Converts this BatchSphData to JSON. - * @function toJSON - * @memberof BatchSphData - * @instance - * @returns {Object.} JSON object - */ - BatchSphData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for BatchSphData - * @function getTypeUrl - * @memberof BatchSphData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - BatchSphData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/BatchSphData"; - }; - - return BatchSphData; -})(); - -module.exports = $root; diff --git a/ide/test/base-ui/chart/scatter/LitChartScatter.test.ts b/ide/test/base-ui/chart/scatter/LitChartScatter.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..17f15189179a140681f2fae8f625c31a5b42f8b2 --- /dev/null +++ b/ide/test/base-ui/chart/scatter/LitChartScatter.test.ts @@ -0,0 +1,29 @@ +/* + * 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 { LitChartScatter } from '../../../../src/base-ui/chart/scatter/LitChartScatter'; +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); +describe('LitChartScatter Test',()=>{ + it('LitChartScatterTest01 ', function () { + let litChartScatter = new LitChartScatter(); + expect(litChartScatter).not.toBeUndefined(); + }); +}) \ No newline at end of file diff --git a/trace_streamer/src/table/ftrace/process_filter_table.h b/ide/test/base-ui/untils/CSVFormater.test.ts similarity index 41% rename from trace_streamer/src/table/ftrace/process_filter_table.h rename to ide/test/base-ui/untils/CSVFormater.test.ts index c78e545555c9ab3a817cc4194c74c05bd7eaef37..24436cf6d9aea4aa0192ec30103413ff91e7765f 100644 --- a/trace_streamer/src/table/ftrace/process_filter_table.h +++ b/ide/test/base-ui/untils/CSVFormater.test.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,31 +13,28 @@ * limitations under the License. */ -#ifndef PROCESS_FILTER_TABLE_H -#define PROCESS_FILTER_TABLE_H +import { JSONToCSV } from '../../../src/base-ui/utils/CSVFormater'; -#include "table_base.h" -#include "trace_data_cache.h" - -namespace SysTuning { -namespace TraceStreamer { -class ProcessFilterTable : public TableBase { -public: - explicit ProcessFilterTable(const TraceDataCache* dataCache); - ~ProcessFilterTable() override; - std::unique_ptr CreateCursor() override; - -private: - class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache* dataCache, TableBase* table); - ~Cursor() override; - int32_t Column(int32_t col) const override; - - private: - const ProcessMeasureFilter& processFilterObj_; +describe('JSONToCSV Test', () => { + it('JSONToCSVTest01', () => { + const data = [ + { name: 'John', age: 30, city: 'New York' }, + { name: 'Alice', age: 25, city: 'San Francisco' }, + ]; + const Obj = { + data: data, + showLabel: true, + fileName: 'TestExport', + columns: { + title: ['Name', 'Age', 'City'], + key: ['name', 'age', 'city'], + formatter: undefined, + }, }; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // PROCESS_FILTER_TABLE_H + const mockSaveCsvFile = jest.fn(); + JSONToCSV.saveCsvFile = mockSaveCsvFile; + JSONToCSV.setCsvData(Obj); + expect(mockSaveCsvFile).toHaveBeenCalled(); + expect(mockSaveCsvFile).toHaveBeenCalledWith('TestExport.csv', expect.any(String)); + }); +}); \ No newline at end of file diff --git a/ide/test/base-ui/untils/ExcelFormater.test.ts b/ide/test/base-ui/untils/ExcelFormater.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4aff4a344517837560ae266712aa610db1027d98 --- /dev/null +++ b/ide/test/base-ui/untils/ExcelFormater.test.ts @@ -0,0 +1,93 @@ +/* + * 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 { ExcelFormater } from '../../../src/base-ui/utils/ExcelFormater'; + +describe('ExcelFormater', () => { + it('ExcelFormaterTest01', function () { + const s = 'Hello, {name}!'; + const c = { name: 'Alice' }; + const result = ExcelFormater.format(s, c); + expect(result).toBe('Hello, Alice!'); + }); + it('ExcelFormaterTest02 ', function () { + const columns = [ + { getAttribute: (attr: string) => (attr === 'data-index' ? 'name' : 'Name') }, + { getAttribute: (attr: string) => (attr === 'data-index' ? 'age' : 'Age') }, + ]; + const data = { name: 'Alice', age: 30 }; + const result = ExcelFormater.createExcelRow(columns, data); + expect(result).toContain(''); + expect(result).toContain('Alice'); + expect(result).toContain('30'); + }); + it('ExcelFormaterTest03 ', function () { + const columns = [ + { getAttribute: (attr: string) => (attr === 'data-index' ? 'parent' : 'Parent') }, + ]; + const data = { + parent: 'Parent 1', + children: [ + { child: 'Child 1' }, + { child: 'Child 2' }, + ], + }; + const result = ExcelFormater.createExcelRow(columns, data); + expect(result).toContain(''); + expect(result).toContain('Parent 1'); + expect(result).toContain('Parent 1'); + }); + it('ExcelFormaterTest04 ', function () { + const baseStr = 'path/to/image.jpg'; + const result = ExcelFormater.addImage(baseStr); + expect(result).toContain(''); + expect(result).toContain(`
`); + }); + it('ExcelFormaterTest05 ', function () { + const columns = [ + { getAttribute: (attr: string) => (attr === 'data-index' ? 'name' : 'Name'), title: 'Name' }, + { getAttribute: (attr: string) => (attr === 'data-index' ? 'age' : 'Age'), title: 'Age' }, + ]; + const dataSource = [ + { name: 'Alice', age: 30 }, + { name: 'Bob', age: 40 }, + ]; + const result = ExcelFormater.createTableData(columns, dataSource); + expect(result).toContain(''); + expect(result).toContain('Name'); + expect(result).toContain('Age'); + expect(result).toContain(''); + expect(result).toContain('Alice'); + expect(result).toContain('30'); + expect(result).toContain(''); + expect(result).toContain('Bob'); + expect(result).toContain('40'); + }); + it('ExcelFormaterTest06 ', function () { + const columns = ['Name', 'Age']; + const result = ExcelFormater.createTHead(columns); + expect(result).toContain(''); + expect(result).toContain('Name'); + expect(result).toContain('Age'); + }); + it('ExcelFormaterTest07 ', function () { + const columns = ['Name', 'Age']; + const data = { name: 'Alice', age: 30 }; + const result = ExcelFormater.createTableRow(columns, data); + expect(result).toContain(''); + expect(result).toContain('undefinedundefined'); + expect(result).toContain('undefinedundefined'); + }); +}); \ No newline at end of file diff --git a/ide/test/statistics/util/SpStatisticsHttpUtil.test.ts b/ide/test/statistics/util/SpStatisticsHttpUtil.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ff1c6e913cfa24ab74cf42aa4298d2d5ee9863d --- /dev/null +++ b/ide/test/statistics/util/SpStatisticsHttpUtil.test.ts @@ -0,0 +1,78 @@ +/* + * 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 { SpStatisticsHttpUtil } from '../../../src/statistics/util/SpStatisticsHttpUtil'; + +describe('SpStatisticsHttpUtil Test', () => { + let originalXMLHttpRequest; + let mockXMLHttpRequest; + let originalFetch; + let mockFetch; + + beforeAll(() => { + // Mock XMLHttpRequest + originalXMLHttpRequest = global.XMLHttpRequest; + mockXMLHttpRequest = jest.fn(() => ({ + open: jest.fn(), + send: jest.fn(), + status: 200, + getResponseHeader: (header) => { + if (header === 'request_info') { + return 'mocked_request_info'; + } + }, + })); + global.XMLHttpRequest = mockXMLHttpRequest; + + // Mock fetch + originalFetch = global.fetch; + mockFetch = jest.fn(() => + Promise.resolve({ + text: () => Promise.resolve('1000'), + }) + ); + global.fetch = mockFetch; + + Object.defineProperty(window, 'location', { + value: { + protocol: 'https:', + host: 'example.com', + }, + }); + }); + afterAll(() => { + global.XMLHttpRequest = originalXMLHttpRequest; + global.fetch = originalFetch; + }); + afterEach(() => { + mockXMLHttpRequest.mockClear(); + mockFetch.mockClear(); + }); + it('SpStatisticsHttpUtilTest01', () => { + const serverInfo = SpStatisticsHttpUtil.getRequestServerInfo(); + expect(serverInfo).toBe('mocked_request_info'); + }); + it('SpStatisticsHttpUtilTest02', async () => { + await SpStatisticsHttpUtil.getServerTime(); + expect(mockFetch).toHaveBeenCalledWith('https://mocked_request_info/serverTime'); + expect(SpStatisticsHttpUtil.serverTime).toBe(0); + }); + it('SpStatisticsHttpUtilTest03', async () => { + SpStatisticsHttpUtil.pauseRetry = true; + await SpStatisticsHttpUtil.getServerTime(); + expect(mockFetch).not.toHaveBeenCalled(); + expect(SpStatisticsHttpUtil.serverTime).toBe(1000); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/bean/AbilityMonitor.test.ts b/ide/test/trace/bean/AbilityMonitor.test.ts index 57d66e07532f6c0f30d1bd9bffd851846ba5ef24..0f5cb1ae46245f7bdb90a3a61d1672e230cd2452 100644 --- a/ide/test/trace/bean/AbilityMonitor.test.ts +++ b/ide/test/trace/bean/AbilityMonitor.test.ts @@ -22,8 +22,6 @@ import { SystemMemorySummary, Dma } from '../../../src/trace/bean/AbilityMonitor'; -import '@babel/preset-typescript'; -import '@babel/plugin-proposal-optional-chaining'; jest.mock('../../../src/trace/bean/NativeHook', () => { return {}; diff --git a/ide/test/trace/component/chart/SpFrameTimeChart.test.ts b/ide/test/trace/component/chart/SpFrameTimeChart.test.ts index c8d3bea2deb33033c44798317334cf86a7412cd7..74d9b3b6880f71e943c001dd1d76b37045c40af2 100644 --- a/ide/test/trace/component/chart/SpFrameTimeChart.test.ts +++ b/ide/test/trace/component/chart/SpFrameTimeChart.test.ts @@ -208,7 +208,6 @@ describe('SpFrameTimeChart Test', () => { }, TraceRow.skeleton() ); - // expect(spFrameTimeChart.flagConfig?.AnimationAnalysis).toEqual('Enabled'); }); it('TabPaneFramesTest03', function () { expect(spFrameTimeChart.frameNoExpandTimeOut()).toBeTruthy(); diff --git a/ide/test/trace/component/setting/SpAllocations.test.ts b/ide/test/trace/component/setting/SpAllocations.test.ts index b8b4a7e128ccb4b3e4b66dd3064b7135ed808033..506a15b03c56f62aa28a06ebb353aa5cbbf506ae 100644 --- a/ide/test/trace/component/setting/SpAllocations.test.ts +++ b/ide/test/trace/component/setting/SpAllocations.test.ts @@ -100,7 +100,7 @@ describe('SpAllocations Test', () => { }); it('SpAllocations test13', function () { let spAllocations = document.querySelector('#sp') as SpAllocations; - expect(spAllocations.statistics_interval).toEqual(0); + expect(spAllocations.statistics_interval).toEqual(10); }); it('SpAllocations test14', function () { let spAllocations = document.querySelector('#sp') as SpAllocations; diff --git a/ide/test/trace/component/setting/SpRecordSetting.test.ts b/ide/test/trace/component/setting/SpRecordSetting.test.ts index ef5db38a0e0402f83b801f456db0dbe157645b01..edaa86f4b876faed12a8a3dbb49dc0cddd9102f9 100644 --- a/ide/test/trace/component/setting/SpRecordSetting.test.ts +++ b/ide/test/trace/component/setting/SpRecordSetting.test.ts @@ -59,7 +59,7 @@ describe('SpRecordSetting Test', () => { it('SpRecordSettingTest09', function (){ let spEle = document.querySelector('#setting') as SpRecordSetting; spEle.outputPath = spEle.shadowRoot?.querySelector('#trace_path') as HTMLInputElement; - spEle.outputPath.value = 'long_trace/' + spEle.outputPath.value = 'long_trace' expect(spEle.longOutPath).toEqual('/data/local/tmp/long_trace/'); }) it('SpRecordSettingTest10', function (){ diff --git a/ide/test/trace/component/trace/base/TraceRowConfig.test.ts b/ide/test/trace/component/trace/base/TraceRowConfig.test.ts index 24408b97b5dad860787949d9ef897640b1a711d4..4c9f622fe4713b66880df3b62cb2641135b3bd9b 100644 --- a/ide/test/trace/component/trace/base/TraceRowConfig.test.ts +++ b/ide/test/trace/component/trace/base/TraceRowConfig.test.ts @@ -14,19 +14,187 @@ */ import { TraceRowConfig } from '../../../../../src/trace/component/trace/base/TraceRowConfig'; +import '../../../../../src/trace/component/trace/base/TraceRowConfig'; import { TraceRow } from '../../../../../src/trace/component/trace/base/TraceRow'; -import { SpApplication } from '../../../../../src/trace/SpApplication'; +import '../../../../../src/trace/component/trace/base/TraceRow'; +import { BaseStruct } from '../../../../../src/trace/bean/BaseStruct'; +import '../../../../../src/trace/bean/BaseStruct'; +import { LitCheckBox } from "../../../../../src/base-ui/checkbox/LitCheckBox"; + +jest.mock('../../../../../src/trace/database/ui-worker/ProcedureWorkerCPU', () => { + return { + CpuStruct: { + wakeupBean: undefined + } + } +}); +jest.mock('../../../../../src/trace/component/trace/TimerShaftElement', () => { +}); describe('TraceRowConfig Test', () => { - document.body.innerHTML = `
- -
- -
-
`; - let traceRowConfig = document.querySelector('#config') as TraceRowConfig; + document.body.innerHTML = `
+
`; + + let spSystemTrace = document.querySelector('sp-system-trace'); + let shadowRoot = spSystemTrace.attachShadow({mode: 'open'}); + let rowsPaneDiv = document.createElement('div'); + rowsPaneDiv.classList.add('rows-pane'); + let traceRow = TraceRow.skeleton(); + traceRow.setAttribute('row-parent-id', ''); + traceRow.addTemplateTypes('Memory'); + shadowRoot.appendChild(rowsPaneDiv); + rowsPaneDiv.appendChild(traceRow); + + let nodes = [{ + children: [ + { + children: [ + { + children: [], + depth: 3, + id: 3, + isCheck: true, + nodeName: "Cpu chart", + scene: [] + } + ], + depth: 2, + id: 2, + isCheck: false, + nodeName: "Cpu", + parent: { + id: 1, nodeName: 'Cpu', children: [], depth: 1, isCheck: false, + scene: [] + }, + scene: [] + } + ], + depth: 1, + id: 1, + isCheck: false, + nodeName: "Cpu", + scene: [] + }] + + let json = { + "subsystems": [ + { + "subsystem": "Cpu", + "components": [ + { + "component": "Cpu", + "charts": [ + { + "chartName": "Cpu", + "chartId": "" + } + ] + } + ] + } + ] + } + + let traceRowConfig = document.querySelector('#config'); it('TraceRowConfig Test01', () => { - expect(traceRowConfig.init).toBeUndefined(); + traceRowConfig.init(); + expect(traceRowConfig.selectTypeList.length).toBe(0); + }); + + it('TraceRowConfig Test02', () => { + traceRowConfig.init(); + let checkBox = new LitCheckBox; + checkBox.checked = true; + let node = { + children: [], + depth: 3, + id: 6, + isCheck: true, + nodeName: "Cpu", + scene: [] + } + traceRowConfig.displayRow(node, checkBox); + console.log('traceRowConfig.subsystemSelectList',traceRowConfig.subsystemSelectList) + expect(traceRowConfig.subsystemSelectList.length).toBe(2) + }); + it('TraceRowConfig Test03', () => { + traceRowConfig.init(); + let checkBox = new LitCheckBox; + let node = { + children: [], + depth: 3, + id: 6, + isCheck: false, + nodeName: "Cpu", + scene: [] + } + traceRowConfig.displayRow(node, checkBox); + expect(traceRowConfig.subsystemSelectList.length).toBe(0) + }); + + + it('TraceRowConfig Test04', () => { + expect(traceRowConfig.refreshSelectList(nodes)).toBeUndefined(); + }); + + it('TraceRowConfig Test05', () => { + traceRowConfig.init() + let favoriteRow = new TraceRow; + traceRowConfig.spSystemTrace.collectRows = [favoriteRow]; + traceRowConfig.spSystemTrace.rowsPaneEL = jest.fn(); + traceRowConfig.spSystemTrace.rowsPaneEL.scroll = jest.fn(() => true); + traceRowConfig.spSystemTrace.canvasPanel = jest.fn(); + traceRowConfig.spSystemTrace.refreshFavoriteCanvas = jest.fn(() => true); + traceRowConfig.spSystemTrace.refreshCanvas = jest.fn(() => true); + traceRowConfig.resetChartTable(); + expect(traceRowConfig.traceRowList.length).toBe(1); + }); + + it('TraceRowConfig Test06', () => { + traceRowConfig.refreshNodes(nodes); + expect(nodes[0].isCheck).toBeTruthy(); + }); + + it('TraceRowConfig Test07', () => { + traceRowConfig.clearSearchAndFlag(); + expect(traceRowConfig.spSystemTrace.hoverFlag ).toBeUndefined(); + }); + + it('TraceRowConfig Test08', () => { + traceRowConfig.expandedNodeList = new Set([1, 2, 3]); + traceRowConfig.changeNode(1); + expect(traceRowConfig.expandedNodeList.has(1)).toBeFalsy() + }); + + it('TraceRowConfig Test09', () => { + traceRowConfig.expandedNodeList = new Set([2, 3]); + traceRowConfig.changeNode(1); + expect(traceRowConfig.expandedNodeList.has(1)).toBeTruthy(); + }); + + it('TraceRowConfig Test10', () => { + traceRowConfig.treeNodes = []; + traceRowConfig.loadTempConfig(JSON.stringify(json)); + expect(traceRowConfig.treeNodes.length).toBe(2); + }); + + it('TraceRowConfig Test11', () => { + let node = { + children: [], + depth: 3, + id: 6, + isCheck: false, + nodeName: "Cpu", + scene: [], + parent: { + id: 8, nodeName: 'Cpu', children: [], depth: 2, isCheck: false, + scene: [] + }, + } + traceRowConfig.setParentSelect(node, false); + expect(node.isCheck).toBeFalsy(); + traceRowConfig.setParentSelect(node, true); + expect(node.parent.isCheck).toBeTruthy(); }); }); diff --git a/ide/test/trace/component/trace/sheet/binder/TabPaneBinder.test.ts b/ide/test/trace/component/trace/sheet/binder/TabPaneBinder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec4b5f4f9a796f02c6cf8825f85e1466bf5bff70 --- /dev/null +++ b/ide/test/trace/component/trace/sheet/binder/TabPaneBinder.test.ts @@ -0,0 +1,77 @@ +/* + * 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 { TabPaneBinders } from '../../../../../../src/trace/component/trace/sheet/binder/TabPaneBinders'; +import { LitTable } from '../../../../../../src/base-ui/table/lit-table'; +import { queryBinderByThreadId } from '../../../../../../src/trace/database/SqlLite'; +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); +const sqlite = require('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/component/trace/base/TraceRow', () => { + return {}; +}); +jest.mock('../../../../../../src/base-ui/table/lit-table'); +describe('TabPaneBinders Test', () => { + let tabPaneBinders; + let threadBindersTbl; + beforeEach(() => { + jest.clearAllMocks(); + tabPaneBinders = new TabPaneBinders(); + threadBindersTbl = new LitTable(); + tabPaneBinders['threadBindersTbl'] = threadBindersTbl; + }); + it('TabPaneBindersTest01', () => { + const data = [ + { + pid: undefined, + tid: undefined, + title: 'P-undefined', + totalCount: undefined, + children: [ + { + binderAsyncRcvCount: 0, + binderReplyCount: 0, + binderTransactionAsyncCount: 0, + binderTransactionCount: 0, + pid: undefined, + tid: undefined, + title: 'T-undefined', + totalCount: undefined + } + ] + } + ]; + queryBinderByThreadId.mockResolvedValue(data); + const threadStatesParam = { + threadIds: [1, 2], + processIds: [1, 2], + leftNs: 0, + rightNs: 100 + }; + tabPaneBinders.initBinderData(threadStatesParam); + tabPaneBinders.data = data; + expect(tabPaneBinders.data).toBeUndefined(); + expect(queryBinderByThreadId).toHaveBeenCalledWith([1, 2], [1, 2], 0, 100); + expect(threadBindersTbl.recycleDataSource).toEqual([]); + expect(tabPaneBinders['threadBindersTblSource']).toEqual([]); + expect(threadBindersTbl.loading).toBe(true); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/component/trace/sheet/binder/TabPaneBinderDataCut.test.ts b/ide/test/trace/component/trace/sheet/binder/TabPaneBinderDataCut.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8c8a75fc6387c1b679474f9a33cb2124f26d80c --- /dev/null +++ b/ide/test/trace/component/trace/sheet/binder/TabPaneBinderDataCut.test.ts @@ -0,0 +1,178 @@ +/* + * 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 { TabPaneBinderDataCut } from '../../../../../../src/trace/component/trace/sheet/binder/TabPaneBinderDataCut'; +import { LitTable } from '../../../../../../src/base-ui/table/lit-table'; + +const sqlite = require('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/component/trace/sheet/SheetUtils', () => { +}); +jest.mock('../../../../../../src/trace/component/trace/base/TraceRow', () => { + return {}; +}); +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); +describe('TabPaneBinderDataCut Test', () => { + let tabPaneBinderDataCut = new TabPaneBinderDataCut(); + tabPaneBinderDataCut.threadBindersTbl = jest.fn(() => { + return new LitTable(); + }); + let threadIdInput = document.createElement('input'); + threadIdInput.value = 'threadIdInput'; + let threadFuncInput = document.createElement('input'); + threadFuncInput.value = 'threadFuncInput'; + let threadStatesParam = { + cpus: [], + threadIds: [1, 2, 3], + trackIds: [23, 56, 77], + funTids: [675, 75], + heapIds: [11, 223], + processIds: [114, 23], + nativeMemory: [], + leftNs: 12222, + rightNs: 654233, + hasFps: false, + statisticsSelectData: undefined + }; + let binderItem = [{ + title: 'test title', + name: 'name', + count: 2, + ts: 2536, + dur: 3666, + startTime: 3655, + endTime: 83663, + tid: 363, + pid: 523, + cycleDur: 366, + cycleStartTime: 3652, + funcName: 'funcName', + id: 12, + thread: 'thread', + process: 'process', + totalCount: 12, + idx: 366 + }]; + + let bindGroup = [{ + title: 'title', + count: 3, + totalCount: 3, + binderAsyncRcvCount: 2, + binderReplyCount: 6, + binderTransactionAsyncCount: 2, + binderTransactionCount: 1, + tid: 5, + pid: 36, + thread: 'thread', + process: 'process', + name: 'name', + cycleStartTime: 1222, + cycleDur: 366, + id: 65, + children: [], + type: 'loop', + status: false, + idx: 2, + isSelected: true + }] + tabPaneBinderDataCut.data = threadStatesParam; + let loopFuncNameCycle = sqlite.queryLoopFuncNameCycle; + let loopFuncNameCycleData = [{ + funcName: 'funcName', + cycleStartTime: 1233, + cycleDur: 0, + id: 123, + tid: 254, + pid: 258 + }]; + loopFuncNameCycle.mockResolvedValue(loopFuncNameCycleData); + + let queryBinder = sqlite.queryBinderByThreadId; + let binderData = [{ + name: 'test', + count: 1, + ts: 2533, + dur: 563, + startTime: 22554, + endTime: 2633333, + tid: 122, + pid: 36 + }]; + queryBinder.mockResolvedValue(binderData); + + let querySingle = sqlite.querySingleFuncNameCycle; + let querySingleData = [{ + funcName: 'funcName', + cycleStartTime: 2553, + cycleDur: 36633, + id: 253, + tid: 366, + pid: 369, + endTime: 366922 + }]; + querySingle.mockResolvedValue(querySingleData); + + it('TabPaneBinderDataCutTest01 ', async () => { + tabPaneBinderDataCut.dataLoopCut(threadIdInput, threadFuncInput); + expect(tabPaneBinderDataCut.threadBindersTbl.loading).toBeTruthy(); + }); + + it('TabPaneBinderDataCutTest02 ', async () => { + tabPaneBinderDataCut.dataSingleCut(threadIdInput, threadFuncInput); + expect(tabPaneBinderDataCut.currentThreadId).toEqual(''); + }); + + it('TabPaneBinderDataCutTest03 ', async () => { + tabPaneBinderDataCut.verifyInputIsEmpty('', '', threadIdInput, threadFuncInput); + expect(tabPaneBinderDataCut.threadBindersTbl.loading).toBeFalsy(); + }); + + it('TabPaneBinderDataCutTest04 ', async () => { + expect(tabPaneBinderDataCut.completionCycleName(binderItem, 'loop').length).toBe(0); + }); + + it('TabPaneBinderDataCutTest05 ', async () => { + expect(tabPaneBinderDataCut.transferToTreeData(binderItem).length).toBe(1); + }); + + it('TabPaneBinderDataCutTest06 ', async () => { + expect(tabPaneBinderDataCut.addCycleNumber(bindGroup)[0].title).toEqual('title'); + }); + + it('TabPaneBinderDataCutTest07 ', async () => { + expect(tabPaneBinderDataCut.timeUnitConversion(bindGroup).length).toEqual(1); + }); + + it('TabPaneBinderDataCutTest08 ', async () => { + expect(tabPaneBinderDataCut.binderWithCountList(bindGroup).length).not.toBeUndefined(); + }); + + it('TabPaneBinderDataCutTest09 ', async () => { + expect(tabPaneBinderDataCut.findThreadByThreadId(bindGroup, 5)).not.toBeUndefined(); + }); + + it('TabPaneBinderDataCutTest10 ', async () => { + tabPaneBinderDataCut.clearCycleRange(); + expect(tabPaneBinderDataCut.cycleAStartRangeDIV.value).toEqual(''); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/component/trace/sheet/cpu/TabPaneCounterSample.test.ts b/ide/test/trace/component/trace/sheet/cpu/TabPaneCounterSample.test.ts index c10a8772b1d8e8f7ead3280dab72d50805e20cae..c2f49db6444b1af39ef83d2462eeff61055a2436 100644 --- a/ide/test/trace/component/trace/sheet/cpu/TabPaneCounterSample.test.ts +++ b/ide/test/trace/component/trace/sheet/cpu/TabPaneCounterSample.test.ts @@ -117,8 +117,4 @@ describe('TabPaneCounterSample Test', () => { tabPane.tbl.recycleDataSource = jest.fn(() => dataArray); expect((tabPane.data = dataArray)).toBeTruthy(); }); - - // it('TabPaneCounterSampleTest02', function () { - // expect(tabPaneCounterSample.initElements()).toBeUndefined(); - // }); }); diff --git a/ide/test/trace/component/trace/sheet/gpufreq/tabPaneGpufreqDataCut.test.ts b/ide/test/trace/component/trace/sheet/gpufreq/tabPaneGpufreqDataCut.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ae3ceb947dc75c7e6fd5b319fb63a1503209093 --- /dev/null +++ b/ide/test/trace/component/trace/sheet/gpufreq/tabPaneGpufreqDataCut.test.ts @@ -0,0 +1,150 @@ +/* + * 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 { TabPaneGpufreqDataCut } from '../../../../../../src/trace/component/trace/sheet/gpufreq/tabPaneGpufreqDataCut'; +import '../../../../../../src/trace/component/trace/sheet/gpufreq/tabPaneGpufreqDataCut'; +import { LitTable } from '../../../../../../src/base-ui/table/lit-table'; +import '../../../../../../src/base-ui/table/lit-table'; +import { SpSegmentationChart } from "../../../../../../src/trace/component/chart/SpSegmentationChart"; + +jest.mock('../../../../../../src/trace/component/trace/base/TraceRow', () => { + return {}; +}); + +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); + +const sqlite = require('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/database/SqlLite'); + +describe('TabPaneSchedSwitch Test', () => { + let threadStatesParam = { + cpus: [], + threadIds: [1, 2, 3], + trackIds: [23, 56, 77], + funTids: [675, 75], + heapIds: [11, 223], + processIds: [114, 23], + nativeMemory: [], + leftNs: 12222, + rightNs: 654233, + hasFps: false, + statisticsSelectData: undefined, + } + + let dataCut = [{ + funName: 'funName', + startTime: 0, + dur: 2155, + endTime: 0, + depth: 2, + threadName: '', + pid: 5256 + }] + + let initData = [{ + filterId: '12', + freq: 'freq', + count: '4', + value: '45', + ts: '2255', + startNS: '4455', + dur: '58547', + endTime: '1255858', + thread: 'thread', + parentIndex: 0, + leve: 0, + name: 'name' + }] + + let gpufreq = sqlite.getGpufreqData; + let gpufreqData = [{ + filterId: '12', + freq: 'freq', + count: '4', + value: '45', + ts: '2255', + startNS: '4455', + dur: '58547', + endTime: '1255858', + thread: 'thread', + parentIndex: 0, + leve: 0, + name: 'name' + }]; + gpufreq.mockResolvedValue(gpufreqData); + + let dataFreqCut = sqlite.getGpufreqDataCut; + let gpufreqCut = [{ + funName: 'funName', + startTime: 0, + dur: 2155, + endTime: 0, + depth: 2, + threadName: '', + pid: 5256 + }]; + dataFreqCut.mockResolvedValue(gpufreqCut); + + let gpufreqDataCut = new TabPaneGpufreqDataCut(); + gpufreqDataCut.threadStatesTbl = jest.fn(() => { + return new LitTable(); + }); + it('TabPaneSchedSwitchTest01', function () { + gpufreqDataCut.data = threadStatesParam; + expect(gpufreqDataCut.threadStatesTbl.loading).toBeTruthy(); + }); + + it('TabPaneSchedSwitchTest02', function () { + gpufreqDataCut.data = threadStatesParam; + gpufreqDataCut.validationFun('', '', '', '', '', '', ''); + expect(gpufreqDataCut._threadId.getAttribute('placeholder')).toEqual('Please input thread id'); + }); + + it('TabPaneSchedSwitchTest03', function () { + gpufreqDataCut.data = threadStatesParam; + gpufreqDataCut.validationFun('1', 'name', '1px solid red', '1px solid green', 'placeholder', 'placeholder', 'single'); + expect(gpufreqDataCut._threadId.getAttribute('placeholder')).toEqual('placeholder'); + }); + + it('TabPaneSchedSwitchTest04', function () { + gpufreqDataCut.data = threadStatesParam; + gpufreqDataCut.validationFun('1', 'name', '1px solid red', '1px solid green', 'placeholder', 'thread function placeholder', 'loop'); + expect(gpufreqDataCut._threadFunc.getAttribute('placeholder')).toEqual('thread function placeholder'); + }); + + it('TabPaneSchedSwitchTest05', function () { + gpufreqDataCut.filterData(initData, dataCut, initData); + expect(gpufreqDataCut.threadStatesTbl.loading).toBeFalsy(); + }); + + it('TabPaneSchedSwitchTest06', function () { + expect(gpufreqDataCut.segmentationData(initData[0], dataCut,1).length).toBe(0); + }); + + it('TabPaneSchedSwitchTest07', function () { + SpSegmentationChart.setChartData = jest.fn(); + expect(gpufreqDataCut.createTree(initData)).not.toBeUndefined(); + }); + + it('TabPaneSchedSwitchTest08', function () { + expect(gpufreqDataCut.updateValueMap(initData[0], 0, '', {}, 1)).toBeUndefined(); + }); +}); diff --git a/ide/test/trace/component/trace/sheet/gpufreq/tabPaneGpufreqUsage.test.ts b/ide/test/trace/component/trace/sheet/gpufreq/tabPaneGpufreqUsage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f558d62c7093c07d51302b313fba9535ed7a371 --- /dev/null +++ b/ide/test/trace/component/trace/sheet/gpufreq/tabPaneGpufreqUsage.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. + */ + +import { TabPaneGpufreq } from '../../../../../../src/trace/component/trace/sheet/gpufreq/tabPaneGpufreqUsage'; +import { LitTable } from '../../../../../../src/base-ui/table/lit-table'; + +jest.mock('../../../../../../src/trace/component/trace/base/TraceRow', () => { + return {}; +}); + +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); + +const sqlite = require('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/database/SqlLite'); + +describe('tabPaneGpufreqUsage Test', () => { + let tabGpuFreq = new TabPaneGpufreq(); + tabGpuFreq.threadStatesTbl = jest.fn(() => { + return new LitTable(); + }); + let gpuCountBean = { + filterId: '12', + freq: 'freq', + count: '4', + value: '45', + ts: '2255', + startNS: '4455', + dur: '58547', + endTime: '1255858', + thread: 'thread', + parentIndex: 0, + leve: 0, + name: 'name', + leftNs: 48555, + rightNs: 58555 + } + let threadStatesParam = { + cpus: [], + threadIds: [1, 2, 3], + trackIds: [23, 56, 77], + funTids: [675, 75], + heapIds: [11, 223], + processIds: [114, 23], + nativeMemory: [], + leftNs: 12222, + rightNs: 654233, + hasFps: false, + statisticsSelectData: undefined, + } + + let gpufreq = sqlite.getGpufreqData; + let gpufreqData = [{ + filterId: '12', + freq: 'freq', + count: '4', + value: '45', + ts: '2255', + startNS: '4455', + dur: '58547', + endTime: '1255858', + thread: 'thread', + parentIndex: 0, + leve: 0, + name: 'name' + }]; + gpufreq.mockResolvedValue(gpufreqData); + + it('tabPaneGpufreqUsageTest01', function () { + tabGpuFreq.data = threadStatesParam; + expect(tabGpuFreq.threadStatesTbl.loading).toBeTruthy(); + }); + + it('tabPaneGpufreqUsageTest02', function () { + expect(tabGpuFreq.createTree([gpuCountBean])).not.toBeUndefined(); + }); + + it('tabPaneGpufreqUsageTest03', function () { + expect(tabGpuFreq.updateValueMap(gpuCountBean, '', {})).toBeUndefined(); + }); +}); diff --git a/ide/test/trace/component/trace/sheet/hi-sysevent/TabPaneHisysEvents.test.ts b/ide/test/trace/component/trace/sheet/hi-sysevent/TabPaneHisysEvents.test.ts index e7c5b5e118e3976c5e7a030ca8c3263a21a8efc9..903474261ccc5b2620010d0387a06cdb8d1e0923 100644 --- a/ide/test/trace/component/trace/sheet/hi-sysevent/TabPaneHisysEvents.test.ts +++ b/ide/test/trace/component/trace/sheet/hi-sysevent/TabPaneHisysEvents.test.ts @@ -94,6 +94,7 @@ describe('TabPaneHisysEvents Test', () => { }); it('TabPaneHisysEvents03', () => { let tabPaneHisysEvents = new TabPaneHisysEvents(); + tabPaneHisysEvents.refreshEventsTitle = jest.fn(); expect(tabPaneHisysEvents.updateData()).toBeUndefined(); }); it('TabPaneHisysEvents04', () => { diff --git a/ide/test/trace/component/trace/sheet/hilog/TabPaneHilogs.test.ts b/ide/test/trace/component/trace/sheet/hilog/TabPaneHilogs.test.ts index 263cd19b6b203c01296816cff7eb680abc95a876..af431569542ad3ce15f326f982b7b93490c54173 100644 --- a/ide/test/trace/component/trace/sheet/hilog/TabPaneHilogs.test.ts +++ b/ide/test/trace/component/trace/sheet/hilog/TabPaneHilogs.test.ts @@ -167,7 +167,5 @@ describe('TabPaneHilogs Test', (): void => { sheetEl!.systemLogFlag = undefined; hiLogsTab.initTabSheetEl(htmlElement, sheetEl); hiLogsTab.data = logsData; - // hiLogsTab.refreshTable(); - // expect(hiLogsTab.isFilterLog(logsData)).toBeFalsy(); }); }); diff --git a/ide/test/trace/component/trace/sheet/irq/TabPaneIrqCounter.test.ts b/ide/test/trace/component/trace/sheet/irq/TabPaneIrqCounter.test.ts index d53a6a3d62dc8fd63955186d46d9ab7127364f2d..2f3685d9f9948df8e512be4212b465bce5f64cb1 100644 --- a/ide/test/trace/component/trace/sheet/irq/TabPaneIrqCounter.test.ts +++ b/ide/test/trace/component/trace/sheet/irq/TabPaneIrqCounter.test.ts @@ -15,12 +15,14 @@ import { TabPaneIrqCounter } from '../../../../../../src/trace/component/trace/sheet/irq/TabPaneIrqCounter'; import { IrqStruct } from '../../../../../../src/trace/database/ui-worker/ProcedureWorkerIrq'; -import { querySoftIrqDataBoxSelect } from "../../../../../../src/trace/database/SqlLite"; -// @ts-ignore jest.mock('../../../../../../src/trace/component/trace/base/TraceRow', () => { return {}; }); - +jest.mock('../../../../../../src/trace/component/trace/sheet/SheetUtils', () => { + return { + initSort: ()=>{} + }; +}); const sqlite = require('../../../../../../src/trace/database/SqlLite'); jest.mock('../../../../../../src/trace/database/SqlLite'); diff --git a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.test.ts b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.test.ts index ed87f11fc7ea1578d0b21a08d1cbd5f3ebb6fb48..1088587994bf942625ad70b03165f6d3a88f02e8 100644 --- a/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.test.ts +++ b/ide/test/trace/component/trace/sheet/native-memory/TabPaneNMSampleList.test.ts @@ -13,18 +13,9 @@ * limitations under the License. */ -// @ts-ignore import { TabPaneNMSampleList } from '../../../../../../src/trace/component/trace/sheet/native-memory/TabPaneNMSampleList'; -jest.mock('../../../../../../src/base-ui/table/lit-table.js', () => { - return { - recycleDataSource: () => {}, - }; -}); -// @ts-ignore -import { NativeHookSampleQueryInfo, NativeHookSamplerInfo } from '../../../../../../src/trace/bean/NativeHook'; -// @ts-ignore -import { NativeMemory } from '../../../../../../src/trace/bean/NativeHook'; -// @ts-ignore +import { NativeHookSamplerInfo, NativeMemory } from '../../../../../../src/trace/bean/NativeHook'; +import { NativeHookSampleQueryInfo } from '../../../../../../src/trace/bean/NativeHook'; jest.mock('../../../../../../src/trace/component/trace/base/TraceRow', () => { return {}; }); @@ -59,7 +50,6 @@ describe('TabPaneNMSampleList Test', () => { }, ]; TabPaneNMSampleList.filterSelect = '0'; - tabPaneNMSampleList.currentSelection = jest.fn(() => true); let dat = { cpus: [], @@ -258,6 +248,10 @@ describe('TabPaneNMSampleList Test', () => { }, ]; TabPaneNMSampleList.filterSelect = '0'; + TabPaneNMSampleList.sampleTbl!.meauseTreeRowElement = jest.fn(() => { + return []; + }); + TabPaneNMSampleList.sampleTbl!.recycleDataSource = jest.fn(() => []); expect(tabPaneNMSampleList.filterAllList()).toBeUndefined(); }); @@ -282,6 +276,10 @@ describe('TabPaneNMSampleList Test', () => { }, ]; TabPaneNMSampleList.filterSelect = '1'; + TabPaneNMSampleList.sampleTbl!.meauseTreeRowElement = jest.fn(() => { + return []; + }); + TabPaneNMSampleList.sampleTbl!.recycleDataSource = jest.fn(() => []); expect(tabPaneNMSampleList.filterAllList()).toBeUndefined(); }); @@ -306,6 +304,10 @@ describe('TabPaneNMSampleList Test', () => { }, ]; TabPaneNMSampleList.filterSelect = '1'; + TabPaneNMSampleList.sampleTbl!.meauseTreeRowElement = jest.fn(() => { + return []; + }); + TabPaneNMSampleList.sampleTbl!.recycleDataSource = jest.fn(() => []); expect(tabPaneNMSampleList.filterAllList()).toBeUndefined(); }); @@ -330,6 +332,10 @@ describe('TabPaneNMSampleList Test', () => { }, ]; TabPaneNMSampleList.filterSelect = '2'; + TabPaneNMSampleList.sampleTbl!.meauseTreeRowElement = jest.fn(() => { + return []; + }); + TabPaneNMSampleList.sampleTbl!.recycleDataSource = jest.fn(() => []); expect(tabPaneNMSampleList.filterAllList()).toBeUndefined(); }); @@ -354,6 +360,10 @@ describe('TabPaneNMSampleList Test', () => { }, ]; TabPaneNMSampleList.filterSelect = '2'; + TabPaneNMSampleList.sampleTbl!.meauseTreeRowElement = jest.fn(() => { + return []; + }); + TabPaneNMSampleList.sampleTbl!.recycleDataSource = jest.fn(() => []); expect(tabPaneNMSampleList.filterAllList()).toBeUndefined(); }); }); diff --git a/ide/test/trace/component/trace/sheet/schedswitch/TabPaneSchedSwitch.test.ts b/ide/test/trace/component/trace/sheet/schedswitch/TabPaneSchedSwitch.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8a222735754c79dc63a044a8f89464393a007bd --- /dev/null +++ b/ide/test/trace/component/trace/sheet/schedswitch/TabPaneSchedSwitch.test.ts @@ -0,0 +1,204 @@ +/* + * 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 '../../../../../../src/base-ui/table/lit-table'; +import { TabPaneSchedSwitch } from '../../../../../../src/trace/component/trace/sheet/schedswitch/TabPaneSchedSwitch'; + +jest.mock('../../../../../../src/trace/component/trace/sheet/SheetUtils', () => { + return {}; +}); + +window.ResizeObserver = + window.ResizeObserver || + jest.fn().mockImplementation(() => ({ + disconnect: jest.fn(), + observe: jest.fn(), + unobserve: jest.fn(), + })); + +const sqlite = require('../../../../../../src/trace/database/SqlLite'); +jest.mock('../../../../../../src/trace/database/SqlLite'); + +describe('TabPaneSchedSwitch Test', () => { + let threadStatesParam = { + cpus: [], + threadIds: [1, 2, 3], + trackIds: [23, 56, 77], + funTids: [675, 75], + heapIds: [11, 223], + processIds: [114, 23], + nativeMemory: [], + leftNs: 12222, + rightNs: 654233, + hasFps: false, + statisticsSelectData: undefined, + } + let single = sqlite.querySingleCutData; + let singleCutData = [ + { + id: 12, + name: 'name', + cycleStartTime: 25, + cycleEndTime: 25877, + depth: 2, + tid: 25, + pid: 12, + dur: 2544 + } + ]; + single.mockResolvedValue(singleCutData); + + let threadState = sqlite.querySchedThreadStates; + let threadStateData = [ + { + id: 12, + pid: 15, + tid: 589, + state: "test", + type: "test", + dur: 15552, + ts: 526, + endTs: 63965 + } + ]; + threadState.mockResolvedValue(threadStateData); + + let loopCut = sqlite.queryLoopCutData; + let loopCutData = [ + { + id: 12, + pid: 15, + tid: 589, + name: "name", + cycleStartTime: 526, + depth: 1 + } + ]; + loopCut.mockResolvedValue(loopCutData); + + let tabPaneSchedSwitch = new TabPaneSchedSwitch(); + tabPaneSchedSwitch.schedSwitchTbl = jest.fn(() => { + return new LitTable(); + }); + it('TabPaneSchedSwitchTest01', function () { + tabPaneSchedSwitch.data = threadStatesParam; + expect(tabPaneSchedSwitch.schedSwitchTbl.loading).toBeFalsy(); + }); + + it('TabPaneSchedSwitchTest02', function () { + tabPaneSchedSwitch.queryCycleRangeData() + expect(tabPaneSchedSwitch.histogramSource.length).toBe(1); + }); + + it('TabPaneSchedSwitchTest03', function () { + let data = { + title: 'title', + count: 6, + cycleNum: 1, + state: 'state', + tid: 122, + pid: 58, + thread: 'thread', + process: 'process', + cycleStartTime: 254, + duration: 2573, + level: 'thread', + children: [], + }; + let customEvent = new CustomEvent('click', { + bubbles: true, + cancelable: true, + detail: {data: data} + }); + tabPaneSchedSwitch.schedSwitchTbl.clearAllSelection = jest.fn(); + tabPaneSchedSwitch.schedSwitchTbl.setCurrentSelection = jest.fn(); + tabPaneSchedSwitch.clickTreeRowEvent(customEvent); + expect(tabPaneSchedSwitch.cycleALeftInput.value).toEqual(''); + }); + + it('TabPaneSchedSwitchTest04', function () { + let firstInput = document.createElement('input'); + firstInput.value = '11'; + let secondInput = document.createElement('input'); + secondInput.value = '22'; + let thirdInput = document.createElement('input'); + let fourInput = document.createElement('input'); + tabPaneSchedSwitch.checkInputRangeFn(firstInput, secondInput, thirdInput, fourInput, '2', '36'); + expect(tabPaneSchedSwitch.getAttribute('isQueryButton')).toEqual(''); + }); + + it('TabPaneSchedSwitchTest05', function () { + tabPaneSchedSwitch.data = threadStatesParam; + tabPaneSchedSwitch.queryCutInfoFn('Single'); + expect(tabPaneSchedSwitch.threadIdInput.getAttribute('placeholder')).toEqual('Please input thread id'); + }); + + it('TabPaneSchedSwitchTest06', function () { + tabPaneSchedSwitch.data = threadStatesParam; + tabPaneSchedSwitch.threadIdInput.value = '12'; + tabPaneSchedSwitch.funcNameInput.value = 'name'; + tabPaneSchedSwitch.queryCutInfoFn('Single'); + expect(tabPaneSchedSwitch.getAttribute('isSingleButton')).toEqual(''); + }); + + it('TabPaneSchedSwitchTest07', function () { + tabPaneSchedSwitch.data = threadStatesParam; + tabPaneSchedSwitch.threadIdInput.value = '12'; + tabPaneSchedSwitch.funcNameInput.value = 'name'; + tabPaneSchedSwitch.queryCutInfoFn('Loop'); + expect(tabPaneSchedSwitch.getAttribute('isLoopButton')).toEqual(''); + }); + + it('TabPaneSchedSwitchTest08', function () { + let groupItem = [{ + count: 0, + cycleNum: 1, + duration: 125, + isHover: false, + isSelected: false, + cycle: 0, + level: '', + pid: -1, + process: '', + state: '', + status: false, + thread: '', + tid: -1, + title: '', + ts: '', + cycleStartTime: 152, + children: [] + }]; + expect(tabPaneSchedSwitch.addCycleNumber(groupItem)).toBeUndefined(); + }); + + it('TabPaneSchedSwitchTest09', function () { + let data = [{ + title: 'title', + count: 6, + cycleNum: 1, + state: 'state', + tid: 122, + pid: 58, + thread: 'thread', + process: 'process', + cycleStartTime: 254, + duration: 2573, + level: 'cycle', + children: [], + }]; + expect(tabPaneSchedSwitch.clickTreeTitleFn(data)).toBeUndefined(); + }); +}); diff --git a/ide/test/trace/database/data-trafic/AbilityMonitorReceiver.test.ts b/ide/test/trace/database/data-trafic/AbilityMonitorReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea2f3046a4975fb350678bb4f3bc88a3dc00bb33 --- /dev/null +++ b/ide/test/trace/database/data-trafic/AbilityMonitorReceiver.test.ts @@ -0,0 +1,105 @@ +/* + * 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 { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { + abilityBytesInTraceDataProtoSql, abilityBytesInTraceDataReceiver, + abilityBytesOutTraceDataProtoSql, abilityBytesOutTraceDataReceiver, + abilityBytesReadDataProtoSql, abilityBytesReadDataReceiver, + abilityBytesWrittenDataProtoSql, abilityBytesWrittenDataReceiver, + abilityMemoryDataProtoSql, abilityMemoryUsedDataReceiver, + abilityPacketInDataProtoSql, abilityPacketInTraceDataReceiver, + abilityPacketsOutDataProtoSql, abilityPacketsOutTraceDataReceiver, + abilityReadOpsDataProtoSql, abilityReadOpsDataReceiver, + abilityWrittenOpsDataProtoSql, abilityWrittenOpsDataReceiver, + cpuAbilityMonitorDataProtoSql, cpuAbilityMonitorDataReceiver, + cpuAbilitySystemDataProtoSql, cpuAbilitySystemDataReceiver, + cpuAbilityUserDataProtoSql, cpuAbilityUserDataReceiver +} from '../../../../src/trace/database/data-trafic/AbilityMonitorReceiver'; + +describe('AbilityMonitorReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + proc = jest.fn((sql) => [ + {abilityData: {id: 4, startNs: 4.4, pid: 40, tid: 400, dur: 40000, depth: 4}}, + {abilityData: {id: 5, startNs: 5.5, pid: 50, tid: 500, dur: 50000, depth: 5}}, + ]); + }); + it('AbilityMonitorReceiverTest01', () => { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(cpuAbilityMonitorDataProtoSql(args)).toBeTruthy(); + expect(cpuAbilityUserDataProtoSql(args)).toBeTruthy(); + expect(cpuAbilitySystemDataProtoSql(args)).toBeTruthy(); + expect(abilityMemoryDataProtoSql(args)).toBeTruthy(); + expect(abilityBytesReadDataProtoSql(args)).toBeTruthy(); + expect(abilityBytesWrittenDataProtoSql(args)).toBeTruthy(); + expect(abilityReadOpsDataProtoSql(args)).toBeTruthy(); + expect(abilityWrittenOpsDataProtoSql(args)).toBeTruthy(); + expect(abilityBytesInTraceDataProtoSql(args)).toBeTruthy(); + expect(abilityBytesOutTraceDataProtoSql(args)).toBeTruthy(); + expect(abilityPacketInDataProtoSql(args)).toBeTruthy(); + expect(abilityPacketsOutDataProtoSql(args)).toBeTruthy(); + }); + it('AbilityMonitorReceiverTest02', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + abilityMemoryUsedDataReceiver(data, proc); + abilityBytesReadDataReceiver(data, proc); + abilityBytesWrittenDataReceiver(data, proc); + abilityReadOpsDataReceiver(data, proc); + abilityWrittenOpsDataReceiver(data, proc); + abilityBytesInTraceDataReceiver(data, proc); + abilityBytesOutTraceDataReceiver(data, proc); + abilityPacketInTraceDataReceiver(data, proc); + abilityPacketsOutTraceDataReceiver(data, proc); + + expect(mockPostMessage).toHaveBeenCalledTimes(9); + }); + it('AbilityMonitorReceiverTest03', () => { + let cpuAbilityData = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + let cpuAbilityProc = jest.fn((sql) => [ + {cpuAbilityData: {id: 4, startNs: 4.4, pid: 40, tid: 400, dur: 40000, depth: 4}}, + {cpuAbilityData: {id: 5, startNs: 5.5, pid: 50, tid: 500, dur: 50000, depth: 5}}, + ]); + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + cpuAbilityMonitorDataReceiver(cpuAbilityData, cpuAbilityProc); + cpuAbilityUserDataReceiver(cpuAbilityData, cpuAbilityProc); + cpuAbilitySystemDataReceiver(cpuAbilityData, cpuAbilityProc); + expect(mockPostMessage).toHaveBeenCalledTimes(3); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/AbilityMonitorSender.test.ts b/ide/test/trace/database/data-trafic/AbilityMonitorSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3dad0349ddca4aab0fa97ce86631ad0430b57764 --- /dev/null +++ b/ide/test/trace/database/data-trafic/AbilityMonitorSender.test.ts @@ -0,0 +1,191 @@ + +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { + cpuAbilityUserDataSender, + abilityMemoryUsedDataSender, + abilityBytesReadDataSender, + abilityBytesInTraceDataSender +} from '../../../../src/trace/database/data-trafic/AbilityMonitorSender'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { DiskAbilityMonitorStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerDiskIoAbility'; +import { NetworkAbilityMonitorStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerNetworkAbility'; +import { CpuAbilityMonitorStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerCpuAbility'; +import { MemoryAbilityMonitorStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerMemoryAbility'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('AbilityMonitorSender Test', () => { + let traceRowData = [{ + dur: 992876684, + frame: + {x: 16, y: 5, width: 17, height: 30}, + startNS: 992876648, + value: 6 + }] + let useTraceRowData = [{ + dur: 992876684, + frame: + {x: 16, y: 5, width: 17, height: 30}, + startNS: 992876648, + value: 2.62424483040067 + }] + let sysTraceRowData = [{ + dur: 992876684, + frame: + {x: 16, y: 5, width: 17, height: 30}, + startNS: 992876648, + value: 3.47458875272988 + }] + let memoryUsedData = [{ + dur: 4999371877, + frame: + {x: 68, y: 5, width: 83, height: 30}, + startNS: 4137882089, + value: 2012096 + }] + let bytesReadData = [{ + dur: 996109517, + frame: + {x: 16, y: 5, width: 17, height: 30}, + startNS: 1000118147, + value: 4 + }] + let bytesInTraceRowData = [{ + dur: 999981768, + frame: + {x: 16, y: 5, width: 18, height: 30}, + startNS: 1025721817, + value: 24 + }] + it('AbilityMonitorSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(traceRowData, traceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + cpuAbilityUserDataSender(traceRow,'CpuAbilityMonitorData').then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest02', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(useTraceRowData, useTraceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + cpuAbilityUserDataSender(traceRow,'CpuAbilityUserData').then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest03', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(sysTraceRowData, sysTraceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + cpuAbilityUserDataSender(traceRow,'CpuAbilitySystemData').then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest04', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(memoryUsedData, memoryUsedData.length, true); + }); + let memoryUsedTraceRow = TraceRow.skeleton(); + abilityMemoryUsedDataSender('2241',memoryUsedTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest05', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(memoryUsedData, memoryUsedData.length, true); + }); + let memoryUsedTraceRow = TraceRow.skeleton(); + abilityMemoryUsedDataSender('2241',memoryUsedTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest06', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesReadData, bytesReadData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesReadDataSender(traceRow,'AbilityBytesReadData').then(res => { + expect(Array.isArray(res)).toBe(true); + }); + }); + it('AbilityMonitorSenderTest07', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesReadData, bytesReadData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesReadDataSender(traceRow,'AbilityBytesWrittenData').then(res => { + expect(Array.isArray(res)).toBe(true); + }); + }); + it('AbilityMonitorSenderTest08', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesReadData, bytesReadData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesReadDataSender(traceRow,'AbilityReadOpsData').then(res => { + expect(Array.isArray(res)).toBe(true); + }); + }); + it('AbilityMonitorSenderTest08', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesReadData, bytesReadData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesReadDataSender(traceRow,'AbilityWrittenOpsData').then(res => { + expect(Array.isArray(res)).toBe(true); + }); + }); + it('AbilityMonitorSenderTest09', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesInTraceRowData, bytesInTraceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesInTraceDataSender(traceRow, 'AbilityBytesInTraceData').then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest10', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesInTraceRowData, bytesInTraceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesInTraceDataSender(traceRow, 'AbilityBytesOutTraceData').then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest11', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesInTraceRowData, bytesInTraceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesInTraceDataSender(traceRow, 'AbilityPacketInTraceData').then(res => { + expect(res).toHaveLength(1); + }); + }); + it('AbilityMonitorSenderTest12', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(bytesInTraceRowData, bytesInTraceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + abilityBytesInTraceDataSender(traceRow, 'AbilityPacketsOutTraceData').then(res => { + expect(res).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ArkTsReceiver.test.ts b/ide/test/trace/database/data-trafic/ArkTsReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cddbdc0195b8a7fda6b3e2dabef8a82cdabb0147 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ArkTsReceiver.test.ts @@ -0,0 +1,53 @@ +/* + * 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 { + cpuProfilerDataReceiver, + initCallChainDataSql, + queryChartDataSqlMem +} from '../../../../src/trace/database/data-trafic/ArkTsReceiver'; +import { DataCache, JsProfilerSymbol } from '../../../../src/trace/database/logic-worker/ProcedureLogicWorkerCommon'; + +describe('ArkTsReceiver Test', () => { + let data = { + id: "d460ac73-bcff-4021-9680-f4672b083e25", + name: 162, + action: "exec-proto", + params: { + startNS: 0, + endNS: 30108564984, + recordStartNS: 203639463442, + recordEndNS: 233748028426, + width: 507, + trafic: 3 + } + } + it('ArkTsReceiverTest01', () => { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(initCallChainDataSql(args)).toBeTruthy(); + expect(queryChartDataSqlMem(args)).toBeTruthy(); + }); + it('ArkTsReceiverTest02', () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(cpuProfilerDataReceiver(data,()=>{ + return 0 + })).toBeUndefined() + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ArkTsSender.test.ts b/ide/test/trace/database/data-trafic/ArkTsSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0849e2a92da5ba33a5a7dcc3daf45a76de4f406 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ArkTsSender.test.ts @@ -0,0 +1,43 @@ +/* + * 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 { cpuProfilerDataSender } from '../../../../src/trace/database/data-trafic/ArkTsSender'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { JsCpuProfilerStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerCpuProfiler'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('cpuProfilerDataSender Test', () => { + let cpuProfilerData = { + column: [25, 30], + depth: [0, 1], + samplesIds: [[1, 2], [3, 4]], + childrenIds: [[5, 6], [7, 8]], + maxDepth: 5, + }; + it('cpuProfilerDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(cpuProfilerData, 1, true); + }); + let cpuProfilerDataTraceRow = TraceRow.skeleton(); + cpuProfilerDataSender(cpuProfilerDataTraceRow).then(result => { + expect(result).toBeTruthy(); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ClockDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ClockDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b45dc39dc8142446aa9bd989a3b2b97f05e28fe4 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ClockDataReceiver.test.ts @@ -0,0 +1,87 @@ +/* + * 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 { + chartClockDataSql, + chartClockDataSqlMem, + clockDataReceiver +} from '../../../../src/trace/database/data-trafic/ClockDataReceiver'; +import { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; + +describe('ClockDataReceiver Test', () => { + let data; + let proc; + beforeEach(() => { + data = { + id: 'bfcedc13-f545-434e-9914-c7823f1a6c17', + name: 4, + action: 'exec-proto', + params: { + clockName: 'cluster0_temp', + sqlType: 'clockFrequency', + startNS: 0, + endNS: 9427688540, + totalNS: 9427688540, + recordStartNS: 4049847357191, + recordEndNS: 4059275045731, + t: 1703747964987, + width: 491, + trafic: 2, + } + }; + proc = jest.fn((sql) => [ + {ClockData: {filterId: 89, startNs: 197364063, type: 'measure', value: 48000, dur: 230475000, px: 11}}, + {ClockData: {filterId: 0, startNs: 197364063, type: 'measure', value: 48000, dur: 230475000, px: 11}}, + ]); + }); + it('ClockDataReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10, + sqlType: 'clockFrequency' + }; + expect(chartClockDataSql(args)).toBeTruthy(); + expect(chartClockDataSqlMem(args)).toBeTruthy(); + }); + it('ClockDataReceiverTest02 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10, + sqlType: 'screenState' + }; + expect(chartClockDataSql(args)).toBeTruthy(); + expect(chartClockDataSqlMem(args)).toBeTruthy(); + }); + it('hiSysEventDataReceiverTest03 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10, + sqlType: 'clockState' + }; + expect(chartClockDataSql(args)).toBeTruthy(); + expect(chartClockDataSqlMem(args)).toBeTruthy(); + }); + it('hiSysEventDataReceiverTest04', () => { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + clockDataReceiver(data,proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ClockDataSender.test.ts b/ide/test/trace/database/data-trafic/ClockDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..03108865f116b1f5af7fe420b867afa145b0e1e8 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ClockDataSender.test.ts @@ -0,0 +1,48 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { ClockStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerClock'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { clockDataSender } from '../../../../src/trace/database/data-trafic/ClockDataSender'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('ClockDataSender Test',()=>{ + let clockData = [{ + filterId: 89, + value: 48000, + startNS: 197364063, + dur: 230475000, + type: "measure", + delta: 0, + frame: { + y: 5, + height: 30, + x: 11, + width: 14 + } + }] + it('ClockDataSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(clockData, clockData.length, true); + }); + let clockTraceRow = TraceRow.skeleton(); + clockDataSender( '','screenState',clockTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}) \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuDataReceiver.test.ts b/ide/test/trace/database/data-trafic/CpuDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..705f36e305037af9382469211feabd0bd8ebc8c9 --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuDataReceiver.test.ts @@ -0,0 +1,97 @@ +/* + * 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 { + chartCpuDataProtoSql, + chartCpuDataProtoSqlMem, cpuDataReceiver +} from '../../../../src/trace/database/data-trafic/CpuDataReceiver'; + +describe('CpuDataReceiver Test', () => { + let data; + let proc; + let data2; + beforeEach(() => { + data = { + id: 'b1ba1ace-8f2b-4ce4-b27e-7a3bf2ff8499', + name: 0, + action: 'exec-proto', + params: { + cpu: 0, + startNS: 0, + endNS: 74946716780, + recordStartNS: 1395573006744, + recordEndNS: 1470519723524, + width: 491, + t: 1703729410566, + trafic: 0, + sharedArrayBuffers: { + processId: {}, + id: {}, + tid: {}, + cpu: {}, + dur: {}, + startTime: {}, + argSetId: {} + } + } + }; + data2 = { + id: 'b1ba1ace-8f2b-4ce4-b27e-7a3bf2ff8499', + name: 0, + action: 'exec-proto', + params: { + cpu: 0, + startNS: 0, + endNS: 74946716780, + recordStartNS: 1395573006744, + recordEndNS: 1470519723524, + width: 491, + t: 1703729410566, + trafic: 1, + sharedArrayBuffers: { + processId: {}, + id: {}, + tid: {}, + cpu: {}, + dur: {}, + startTime: {}, + argSetId: {} + } + } + }; + proc = jest.fn((sql) => [ + {CpuData: {id: 4, startTime: 4.4, processId: 40, tid: 400, cpu: 0, argSetId: 1, dur: 40000}}, + {CpuData: {id: 5, startTime: 5.5, processId: 50, tid: 500, cpu: 0, argSetId: 2, dur: 50000}}, + ]); + }); + it('CpuDataReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10, + cpu:0, + }; + expect(chartCpuDataProtoSql(args)).toBeTruthy(); + expect(chartCpuDataProtoSqlMem(args)).toBeTruthy(); + }); + it('CpuDataReceiverTest02 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + cpuDataReceiver(data, proc); + cpuDataReceiver(data2,proc) + expect(mockPostMessage).toHaveBeenCalledTimes(2); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuDataSender.test.ts b/ide/test/trace/database/data-trafic/CpuDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..01a67bb215c83b43badd78f0aa4be615224fa6cb --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuDataSender.test.ts @@ -0,0 +1,56 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { CpuStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerCPU'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { cpuDataSender } from '../../../../src/trace/database/data-trafic/CpuDataSender'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('CpuDataSender Test', () => { + let CpuData = [{ + processId: 182, + cpu: 0, + tid: 182, + id: 76, + dur: 198041, + startTime: 667008776, + end_state: 'S', + priority: 4294967295, + processName: 'sugov:0', + processCmdLine: 'sugov:0', + name: 'sugov:0', + type: 'thread', + frame: { + y: 5, + height: 30, + x: 4, + width: 1 + }, + translateY: 0 + }]; + it('CpuDataSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(CpuData, CpuData.length, true); + }); + let CpuDataTraceRow = TraceRow.skeleton(); + cpuDataSender(QueryEnum.CpuData, CpuDataTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuFreqDataReceiver.test.ts b/ide/test/trace/database/data-trafic/CpuFreqDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f869e5d1aa3b446e28e60158ae48259d9dc7cdc6 --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuFreqDataReceiver.test.ts @@ -0,0 +1,62 @@ +/* + * 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 { + chartCpuFreqDataSql, + chartCpuFreqDataSqlMem, cpuFreqDataReceiver +} from '../../../../src/trace/database/data-trafic/CpuFreqDataReceiver'; + +describe('CpuFreqDataReceiver Test',()=>{ + let data; + let proc; + + beforeEach(() => { + data = { + id: "6a41c242-3e3e-4c3f-82f3-eab7102f0e9f", + name: 2, + action: "exec-proto", + params: { + cpu: 0, + startNS: 0, + endNS: 9427688540, + recordStartNS: 4049847357191, + recordEndNS: 4059275045731, + t: 1703754730919, + width: 549, + trafic: 2 + } + }; + proc = jest.fn((sql) => [ + {cpuFreqData: {cpu: 4, value: 826000, dur: 0, startNs: 8252840103}}, + {cpuFreqData: {cpu: 4, value: 826000, dur: 0, startNs: 8252840103}}, + ]); + }); + it('CpuFreqDataReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartCpuFreqDataSql (args)).toBeTruthy(); + expect(chartCpuFreqDataSqlMem (args)).toBeTruthy(); + }); + it('CpuFreqDataReceiverTest02 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + cpuFreqDataReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}) \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuFreqDataSender.test.ts b/ide/test/trace/database/data-trafic/CpuFreqDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfb8d9974bfbca43f0083203fcced68e5d35d762 --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuFreqDataSender.test.ts @@ -0,0 +1,47 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { CpuFreqStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerFreq'; +import { cpuFreqDataSender } from '../../../../src/trace/database/data-trafic/CpuFreqDataSender'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('CpuFreqDataSender Test', () => { + let CpuFreqData = [{ + cpu: 1, + value: 884000, + dur: -1, + startNS: 9400191145, + frame: { + y: 5, + height: 30, + x: 547, + width: 1 + } + }]; + it('CpuFreqDataSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(CpuFreqData, CpuFreqData.length, true); + }); + let cpuFreqDataTraceRow = TraceRow.skeleton(); + cpuFreqDataSender(QueryEnum.CpuData, cpuFreqDataTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuFreqLimitDataReceiver.test.ts b/ide/test/trace/database/data-trafic/CpuFreqLimitDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..495b3dfd34a5a9cb7da74c6862e46138d3ebf6ec --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuFreqLimitDataReceiver.test.ts @@ -0,0 +1,62 @@ +/* + * 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 { + chartCpuFreqLimitDataSql, + chartCpuFreqLimitDataSqlMem, cpuFreqLimitReceiver +} from '../../../../src/trace/database/data-trafic/CpuFreqLimitDataReceiver'; + +describe('CpuFreqLimitDataReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + id: '6a41c242-3e3e-4c3f-82f3-eab7102f0e9f', + name: 2, + action: 'exec-proto', + params: { + cpu: 0, + startNS: 0, + endNS: 9427688540, + recordStartNS: 4049847357191, + recordEndNS: 4059275045731, + t: 1703754730919, + width: 549, + trafic: 2 + } + }; + proc = jest.fn((sql:any) => [ + {cpuFreqLimitData: {cpu: 4, value: 826000, dur: 0, startNs: 8252840103}}, + {cpuFreqLimitData: {cpu: 4, value: 826000, dur: 0, startNs: 8252840103}}, + ]); + }); + it('CpuFreqLimitDataReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartCpuFreqLimitDataSql(args)).toBeTruthy(); + expect(chartCpuFreqLimitDataSqlMem(args)).toBeTruthy(); + }); + it('CpuFreqLimitDataReceiverTest02 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + cpuFreqLimitReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuFreqLimitDataSender.test.ts b/ide/test/trace/database/data-trafic/CpuFreqLimitDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..568c9e14fa9233eed87c364e16602f3840ff7ac9 --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuFreqLimitDataSender.test.ts @@ -0,0 +1,50 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { CpuFreqLimitsStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerCpuFreqLimits'; +import { cpuFreqLimitSender } from '../../../../src/trace/database/data-trafic/CpuFreqLimitDataSender'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe(' CpuFreqLimitDataSender Test', () => { + let CpuFreqLimitData = [{ + cpu: 1, + value: 884000, + dur: -1, + startNS: 9400191145, + frame: { + y: 5, + height: 30, + x: 547, + width: 1 + } + }]; + it(' CpuFreqLimitDataSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(CpuFreqLimitData, CpuFreqLimitData.length, true); + }); + let CpuFreqLimitDataTraceRow = TraceRow.skeleton(); + let maxId = 0; + let minId = 0; + let cpu = 1; + cpuFreqLimitSender(maxId,minId,QueryEnum.CpuFreqLimitData, CpuFreqLimitDataTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/trace_streamer/src/table/ebpf/ebpf_process_maps_table.h b/ide/test/trace/database/data-trafic/CpuStateReceiver.test.ts similarity index 31% rename from trace_streamer/src/table/ebpf/ebpf_process_maps_table.h rename to ide/test/trace/database/data-trafic/CpuStateReceiver.test.ts index 2cb0f0db5fc8d7990e931d3bd5cdea9dd90c79fe..2d78e0cca56420b307cc994226af9de157242b08 100644 --- a/trace_streamer/src/table/ebpf/ebpf_process_maps_table.h +++ b/ide/test/trace/database/data-trafic/CpuStateReceiver.test.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -12,41 +12,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef EBPF_PROCESS_MAPS_TABLE_H -#define EBPF_PROCESS_MAPS_TABLE_H -#include "table_base.h" -#include "trace_stdtype.h" +import { + chartCpuStateDataSql, + chartCpuStateDataSqlMem, cpuStateReceiver +} from '../../../../src/trace/database/data-trafic/CpuStateReceiver'; -namespace SysTuning { -namespace TraceStreamer { -class EbpfProcessMapsTable : public TableBase { -public: - explicit EbpfProcessMapsTable(const TraceDataCache* dataCache); - ~EbpfProcessMapsTable() override; - std::unique_ptr CreateCursor() override; - -private: - int64_t GetSize() override - { - return dataCache_->GetConstEbpfProcessMaps().Size(); +describe('CpuStateReceiver Test', () => { + let data = { + id: '55348b85-5aa9-4e99-86fc-acb2d6f438fe', + name: 1, + action: 'exec-proto', + params: { + startTs: 1, + filterId: 3, + startNS: 0, + endNS: 9427688540, + recordStartNS: 4049847357191, + recordEndNS: 4059275045731, + width: 491, + trafic: 2, } - void GetOrbyes(FilterConstraints& profc, EstimatedIndexInfo& proei) override; - void FilterByConstraint(FilterConstraints& profc, - double& profilterCost, - size_t prorowCount, - uint32_t procurrenti) override; - - class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache* dataCache, TableBase* table); - ~Cursor() override; - int32_t Column(int32_t column) const override; - - private: - const EbpfProcessMaps& ebpfProcessMapsObj_; + }; + let CpuStateData = [{ + value: 0, + dur: 193229, + height: 4, + startTs: 6992644791, + cpu: 1, + frame: { + y: 5, + height: 30, + x: 364, + width: 1 + } + }] + it('CpuStateReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10, + filterId: 1, }; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // EBPF_PROCESS_MAPS_TABLE_H + expect(chartCpuStateDataSql(args)).toBeTruthy(); + expect(chartCpuStateDataSqlMem(args)).toBeTruthy(); + }); + it('CpuStateReceiverTest02 ', function () { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(cpuStateReceiver(data, () => { + return CpuStateData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/CpuStateSender.test.ts b/ide/test/trace/database/data-trafic/CpuStateSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ced3f794f996638649442de985a5ea5b33506d5a --- /dev/null +++ b/ide/test/trace/database/data-trafic/CpuStateSender.test.ts @@ -0,0 +1,47 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { cpuStateSender } from '../../../../src/trace/database/data-trafic/CpuStateSender'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { CpuStateStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerCpuState'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('CpuStateSender Test', () => { + let cpuStateData = [{ + value: 0, + dur: 193229, + height: 4, + startTs: 6992644791, + cpu: 1, + frame: { + y: 5, + height: 30, + x: 364, + width: 1 + } + }] + it('CpuStateSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(cpuStateData, cpuStateData.length, true); + }); + let filterId = 1; + let CpustataDataTraceRow = TraceRow.skeleton(); + cpuStateSender(filterId,CpustataDataTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/DataFilter.test.ts b/ide/test/trace/database/data-trafic/DataFilter.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc77b5c7832a7d8d7f9028d79d66d76cd7e7f854 --- /dev/null +++ b/ide/test/trace/database/data-trafic/DataFilter.test.ts @@ -0,0 +1,90 @@ +/* + * 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 { + filterData, + filterDataByGroup, + filterDataByGroupLayer, + filterDataByLayer +} from '../../../../src/trace/database/data-trafic/DataFilter'; + +describe('DataFilter Test', () => { + it('DataFilterTest01', () => { + let list = [ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000}, + ]; + let startKey = 'startKey'; + let durKey = 'durKey'; + let startNS = 0; + let endNS = 2000; + let width = 100; + let result = filterData(list, startKey, durKey, startNS, endNS, width); + expect(result).toEqual([ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000, v: true}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000, v: true}, + ]); + }); + it('DataFilterTest02', () => { + let list = [ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000}, + ]; + let layerKey = 'layerKey'; + let startKey = 'startKey'; + let durKey = 'durKey'; + let startNS = 0; + let endNS = 2000; + let width = 100; + let result = filterDataByLayer(list, layerKey, startKey, durKey, startNS, endNS, width); + expect(result).toEqual([ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000, v: true}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000, v: true}, + ]); + }); + it('DataFilterTest03', () => { + let list = [ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000}, + ]; + let startKey = 'startKey'; + let durKey = 'durKey'; + let startNS = 0; + let endNS = 2000; + let width = 100; + let result = filterDataByGroup(list, startKey, durKey, startNS, endNS, width, null); + expect(result).toEqual([ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000, px: 0,}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000, px: 5,}, + ]); + }); + it('DataFilterTest0304', () => { + let list = [ + {layerKey: 1, startKey: 0, durKey: 100, startNS: 0, endNS: 1000}, + {layerKey: 2, startKey: 100, durKey: 200, startNS: 1001, endNS: 2000}, + ]; + let layerKey = 'layerKey'; + let startKey = 'startKey'; + let durKey = 'durKey'; + let startNS = 0; + let endNS = 2000; + let width = 100; + let result = filterDataByGroupLayer(list, layerKey, startKey, durKey, startNS, endNS, width); + expect(result).toEqual([ + {startKey: 0, durKey: 100, startNS: 0, endNS: 1000, px: 100, durTmp: undefined, layerKey: 1,}, + {startKey: 100, durKey: 200, startNS: 1001, endNS: 2000, px: 205, durTmp: undefined, layerKey: 2,}, + ]); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/EBPFReceiver.test.ts b/ide/test/trace/database/data-trafic/EBPFReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..566d06af4df139b7a5ee5ad5ce53066d273f2552 --- /dev/null +++ b/ide/test/trace/database/data-trafic/EBPFReceiver.test.ts @@ -0,0 +1,81 @@ +/* + * 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 { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { + diskIoDataGroupBy10MSProtoSql, + diskIoDataProtoSql, + diskIoReceiver, + eBPFVmDataGroupBy10MSProtoSql, + eBPFVmDataProtoSql, + eBPFVmReceiver, + fileSystemDataGroupBy10MSProtoSql, + fileSystemDataProtoSql, + fileSystemDataReceiver +} from '../../../../src/trace/database/data-trafic/EBPFReceiver'; + +describe('EBPFReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + typeArr:[] + }, + }; + proc = jest.fn((sql) => [ + {EBPFVm: {startNs: 440000000, endNs: 450000000, size: 4, px: 172}}, + {EBPFVm: {startNs: 450000000, endNs: 460000000, size: 3, px: 176}}, + ]); + }); + it('EBPFReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10, + typeArr:[] + }; + expect(fileSystemDataGroupBy10MSProtoSql(args)).toBeTruthy(); + expect(fileSystemDataProtoSql(args)).toBeTruthy(); + expect(diskIoDataGroupBy10MSProtoSql (args)).toBeTruthy(); + expect(diskIoDataProtoSql (args)).toBeTruthy(); + expect(eBPFVmDataGroupBy10MSProtoSql (args)).toBeTruthy(); + expect(eBPFVmDataProtoSql (args)).toBeTruthy(); + }); + it('EBPFReceiverTest02 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + fileSystemDataReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('EBPFReceiverTest03 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + diskIoReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('EBPFReceiverTest04 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + eBPFVmReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/EBPFSender.test.ts b/ide/test/trace/database/data-trafic/EBPFSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd28322da4cba1a5a8ac2fa41025f6abd8f896e1 --- /dev/null +++ b/ide/test/trace/database/data-trafic/EBPFSender.test.ts @@ -0,0 +1,77 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { EBPFChartStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerEBPF'; +import { + diskIoSender, + fileSystemSender, + fileSysVMSender +} from '../../../../src/trace/database/data-trafic/EBPFSender.js'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('EBPFSender Test', () => { + let EBPFData = [{ + size: 3, + dur: null, + endNS: 1070000000, + startNS: 1060000000, + height: 1, + frame: { + y: 0, + height: 1, + x: 403, + width: 4 + }, + group10Ms: true, + }]; + it('EBPFSenderTest01 ', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(EBPFData, EBPFData.length, true); + }); + let type = 1; + let scale = 1; + let fileSystemTraceRow = TraceRow.skeleton(); + fileSystemSender(type, scale, fileSystemTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); + it('EBPFSenderTest02 ', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(EBPFData, EBPFData.length, true); + }); + let scale = 1; + let all = true; + let ipid = 5; + let typeArr = [1, 2, 3, 4]; + let DiskIoDataTraceRow = TraceRow.skeleton(); + diskIoSender(all, ipid, typeArr, scale, DiskIoDataTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); + it('EBPFSenderTest03 ', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(EBPFData, EBPFData.length, true); + }); + let scale = 1; + let DiskIoDataTraceRow = TraceRow.skeleton(); + fileSysVMSender(scale, DiskIoDataTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/EnergySysEventReceiver.test.ts b/ide/test/trace/database/data-trafic/EnergySysEventReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f602032e63ba0ea2f4f8227eddc8158eccb5f817 --- /dev/null +++ b/ide/test/trace/database/data-trafic/EnergySysEventReceiver.test.ts @@ -0,0 +1,226 @@ +/* + * 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 { + systemDataSql, + chartEnergyAnomalyDataSql, + queryPowerValueSql, + queryStateDataSql, + queryStateProtoDataSql, + energySysEventReceiver, + hiSysEnergyAnomalyDataReceiver, + hiSysEnergyStateReceiver, + hiSysEnergyPowerReceiver +} from '../../../../src/trace/database/data-trafic/EnergySysEventReceiver'; +import { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; + +describe('EnergySysEventReceiver Test', () => { + let data; + let proc; + beforeEach(() => { + data = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + proc = jest.fn((sql) => [ + {energyData: {id: 1, startNs: 4.4, eventName: '', appKey: '', eventValue: ''}}, + {energyData: {id: 2, startNs: 5.5, eventName: '', appKey: '', eventValue: ''}}, + {energyData: {id: 3, startNs: 5.5, eventName: '', appKey: '', eventValue: ''}}, + {energyData: {id: 4, startNs: 5.5, eventName: '', appKey: '', eventValue: ''}}, + {energyData: {id: 5, startNs: 5.5, eventName: '', appKey: '', eventValue: ''}}, + ]); + }); + it('EnergySysEventReceiverTest01', () => { + let args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(systemDataSql(args)).toBeTruthy(); + expect(chartEnergyAnomalyDataSql(args)).toBeTruthy(); + expect(queryPowerValueSql(args)).toBeTruthy(); + expect(queryStateDataSql(args)).toBeTruthy(); + expect(queryStateProtoDataSql(args)).toBeTruthy(); + }); + it('EnergySysEventReceiverTest02', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiSysEnergyAnomalyDataReceiver(data, proc); + hiSysEnergyPowerReceiver(data, proc); + hiSysEnergyStateReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(3); + }); + it('EnergySysEventReceiverTest03', () => { + let systemData = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + let systemEventvalue = { + 'LOG_LEVEL': 2, + 'MESSAGE': 'token=548210734912', + 'NAME': 'backGround', + 'PID': 4192, + 'STATE': 1, + 'TAG': 'DUBAI_TAG_RUNNINGLOCK_ADD', + 'TYPE': 1, + 'UID': 20010034 + }; + let systemEventvalueJson = JSON.stringify(systemEventvalue); + let systemProc = jest.fn((sql) => [ + { + energyData: { + id: 1, + startNs: 4.4, + eventName: 'POWER_RUNNINGLOCK', + appKey: '1', + eventValue: systemEventvalueJson + } + }, + ]); + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + energySysEventReceiver(systemData, systemProc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('EnergySysEventReceiverTest04', () => { + let systemData = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + let systemEventvalue = { + 'LOG_LEVEL': 2, + 'MESSAGE': 'token=548210734912', + 'NAME': 'backGround', + 'PID': 4192, + 'STATE': 1, + 'TAG': 'DUBAI_TAG_RUNNINGLOCK', + 'TYPE': 1, + 'UID': 20010034 + }; + let systemEventvalueJson = JSON.stringify(systemEventvalue); + let systemProc = jest.fn((sql) => [ + { + energyData: { + id: 1, + startNs: 4.4, + eventName: 'POWER_RUNNINGLOCK', + appKey: '1', + eventValue: systemEventvalueJson + } + }, + ]); + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + energySysEventReceiver(systemData, systemProc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('EnergySysEventReceiverTest05', () => { + let systemData = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + let systemEventvalue = { + 'LOG_LEVEL': 2, + 'MESSAGE': 'token=548210734912', + 'NAME': 'backGround', + 'PID': 4192, + 'STATE': 'stop', + 'TAG': 'DUBAI_TAG_RUNNINGLOCK', + 'TYPE': 1, + 'UID': 20010034 + }; + let systemEventvalueJson = JSON.stringify(systemEventvalue); + let systemProc = jest.fn((sql) => [ + {energyData: {id: 1, startNs: 4.4, eventName: 'GNSS_STATE', appKey: '1', eventValue: systemEventvalueJson}}, + ]); + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + energySysEventReceiver(systemData, systemProc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('EnergySysEventReceiverTest06', () => { + let systemData = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + let systemEventvalue = { + 'LOG_LEVEL': 2, + 'MESSAGE': 'token=548210734912', + 'NAME': 'backGround', + 'PID': 4192, + 'STATE': 'stop', + 'TAG': 'DUBAI_TAG_RUNNINGLOCK', + 'TYPE': 1, + 'UID': 20010034 + }; + let systemEventvalueJson = JSON.stringify(systemEventvalue); + let systemProc = jest.fn((sql) => [ + {energyData: {id: 1, startNs: 4.4, eventName: 'GNSS_STATE', appKey: '1', eventValue: systemEventvalueJson}}, + ]); + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + energySysEventReceiver(systemData, systemProc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('EnergySysEventReceiverTest07', () => { + let systemData = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + let systemEventvalue = { + 'LOG_LEVEL': 2, + 'MESSAGE': 'token=548210734912', + 'NAME': 'WORK_START', + 'PID': 4192, + 'STATE': 'stop', + 'TAG': 'DUBAI_TAG_RUNNINGLOCK', + 'TYPE': 1, + 'UID': 20010034 + }; + let systemEventvalueJson = JSON.stringify(systemEventvalue); + let systemProc = jest.fn((sql) => [ + {energyData: {id: 1, startNs: 4.4, eventName: 'WORK_START', appKey: '1', eventValue: systemEventvalueJson}}, + ]); + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + energySysEventReceiver(systemData, systemProc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/EnergySysEventSender.test.ts b/ide/test/trace/database/data-trafic/EnergySysEventSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a1ad269b47520a9e6869c35d42ce0e4ea344deb --- /dev/null +++ b/ide/test/trace/database/data-trafic/EnergySysEventSender.test.ts @@ -0,0 +1,119 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { + energySysEventSender, + hiSysEnergyAnomalyDataSender, + hiSysEnergyPowerSender, + hiSysEnergyStateSender +} from '../../../../src/trace/database/data-trafic/EnergySysEventSender'; +import { EnergySystemStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerEnergySystem'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { EnergyAnomalyStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerEnergyAnomaly'; +import { EnergyPowerStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerEnergyPower'; +import { EnergyStateStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerEnergyState'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('EnergySysEventSender Test', () => { + let systemData = [{ + count: 2, + dataType: 1, + dur: 1320000, + frame: + {x: 70, y: 45, width: 11, height: 10}, + id: 73, + startNs: 8930000, + token: 546680714, + type: 1 + }] + + let anomalyData = [ + { + id: 126, + startNs: 2384000000, + eventName: "ANOMALY_SCREEN_OFF_ENERGY", + appKey: "APPNAME", + eventValue: "bt_switch" + }, + { + id: 127, + startNs: 2385000000, + eventName: "ANOMALY_SCREEN_OFF_ENERGY", + appKey: "APPNAME", + eventValue: "bt_switch" + }] + + let powerData = [{ + appKey: "APPNAME", + eventName: "POWER_IDE_BLUETOOTH", + eventValue: "bt_switch", + id: 8940, + startNS: 111015000000 + }] + + let stateData = [{ + dur: 3000000, + frame: {x: 394, y: 5, width: 1, height: 30}, + id: 5807, + startNs: 49686000000, + type: "WIFI_EVENT_RECEIVED", + value: 4 + }] + + it('EnergySysEventSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(systemData, systemData.length, true); + }); + let systemTraceRow = TraceRow.skeleton(); + energySysEventSender(systemTraceRow).then(result => { + expect(result).toHaveLength(1); + }) + }); + + it('EnergySysEventSenderTest02', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(anomalyData, anomalyData.length, true); + }); + let anomalyTraceRow = TraceRow.skeleton(); + hiSysEnergyAnomalyDataSender(anomalyTraceRow).then(result => { + expect(result).toHaveLength(2); + }) + }); + + it('EnergySysEventSenderTest03', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(powerData, powerData.length, true); + }); + let powerTraceRow = TraceRow.skeleton(); + hiSysEnergyPowerSender(powerTraceRow).then(result => { + expect(Array.isArray(result)).toBe(true); + }) + }); + + it('EnergySysEventSenderTest04', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(stateData, stateData.length, true); + }); + let eventName = ['WIFI_EVENT_RECEIVED']; + let stateTraceRow = TraceRow.skeleton(); + hiSysEnergyStateSender(eventName, 0, stateTraceRow).then(result => { + expect(result).toHaveLength(1); + }) + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/FrameDynamicEffectReceiver.test.ts b/ide/test/trace/database/data-trafic/FrameDynamicEffectReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9a60e8ded0c61e173364ff4364c2bb1e350549b --- /dev/null +++ b/ide/test/trace/database/data-trafic/FrameDynamicEffectReceiver.test.ts @@ -0,0 +1,104 @@ +/* + * 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 { + frameAnimationReceiver, + frameDynamicReceiver, + frameSpacingReceiver +} from '../../../../src/trace/database/data-trafic/FrameDynamicEffectReceiver'; + +describe('FrameDynamicEffectReceiver Test', () => { + let data = { + action: "exec-proto", + id: "1", + name: 18, + params: { + recordStartNS: 4049847357191, + recordEndNS: 4059275045731, + startNS: 0, + t: 1703474011224, + width: 1407, + trafic: 3 + } + }; + let animationData = [{ + frameAnimationData: { + depth: 0, + dur: 79379165, + endTs: 1451353646, + name: "H:APP_LIST_FLING, com.tencent.mm", + startTs: 1371974481 + } + }] + let dynamicData = [{ + frameDynamicData: { + alpha: "0.08", + appName: "WindowScene_mm37", + height: "1119", + ts: 179994792, + width: "543", + x: "513", + y: "1017" + } + }, { + frameDynamicData: { + alpha: "0.26", + appName: "WindowScene_mm37", + height: "1293", + ts: 196844792, + width: "627", + x: "459", + y: "938" + } + }] + let frameSpacingData = [{ + frameSpacingData: { + currentFrameHeight: "1119", + currentFrameWidth: "543", + currentTs: 179994792, + frameSpacingResult: 0, + nameId: "WindowScene_mm37", + preFrameHeight: 0, + preFrameWidth: 0, + preTs: 0, + preX: 0, + preY: 0, + x: "513", + y: "1017" + } + }] + it('FrameDynamicEffectReceiverTest01', function () { + const mockCallback = jest.fn(() => animationData); + const mockPostMessage = jest.fn(); + (self as unknown as Worker).postMessage = mockPostMessage; + frameAnimationReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('FrameDynamicEffectReceiverTest02', function () { + const mockCallback = jest.fn(() => dynamicData); + const mockPostMessage = jest.fn(); + (self as unknown as Worker).postMessage = mockPostMessage; + frameDynamicReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + it('FrameDynamicEffectReceiverTest03', function () { + let mockCallback = jest.fn(() => frameSpacingData); + (self as unknown as Worker).postMessage = jest.fn(); + frameSpacingReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/FrameDynamicEffectSender.test.ts b/ide/test/trace/database/data-trafic/FrameDynamicEffectSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcb780fa893c3d0ef896a7ab3d50311eaf16207b --- /dev/null +++ b/ide/test/trace/database/data-trafic/FrameDynamicEffectSender.test.ts @@ -0,0 +1,121 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { FrameAnimationStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerFrameAnimation'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { + frameAnimationSender, + frameDynamicSender, + frameSpacingSender +} from '../../../../src/trace/database/data-trafic/FrameDynamicEffectSender'; +import { FrameDynamicStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerFrameDynamic'; +import { FrameSpacingStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerFrameSpacing'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('FrameDynamicEffectSender Test', () => { + let animationData = [ + { + animationId: 0, + depth: 0, + dur: 79379165, + endTs: 1451353646, + frame: {x: 204, y: 2, width: 12, height: 16}, + frameInfo: "0", + name: "H:APP_LIST_FLING, com.tencent.mm", + startTs: 1371974481, + status: "Response delay", + textMetricsWidth: 120.1328125 + }, + { + animationId: 0, + depth: 1, + dur: 2606938539, + endTs: 3978913020, + frame: {x: 204, y: 22, width: 389, height: 16}, + frameInfo: "0:89.55", + name: "H:APP_LIST_FLING, com.tencent.mm", + startTs: 1371974481, + status: "Completion delay", + textMetricsWidth: 137.76171875 + }] + + let dynamicCurveData = [{ + alpha: 1, + appName: "WindowScene_mm37", + frame: {x: 295, y: 97, width: 0, height: 100}, + groupId: 1371974481, + height: 2772, + id: 100, + ts: 1979229687, + typeValue: 0, + width: 1344, + x: 0, + y: 0 + }] + + let frameSpacingData = [{ + currentFrameHeight: 2772, + currentFrameWidth: 1344, + currentTs: 3295268229, + frame: {x: 491, y: 137, width: 0, height: 0}, + frameSpacingResult: 0, + groupId: 1371974481, + id: 218, + nameId: "WindowScene_mm37", + physicalHeight: 2772, + physicalWidth: 1344, + preFrameHeight: 2772, + preFrameWidth: 1344, + preTs: 3281170312, + preX: 0, + preY: 0, + x: 0, + y: 0 + }] + it('FrameDynamicEffectSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(animationData, animationData.length, true); + }); + let animationTraceRow = TraceRow.skeleton(); + frameAnimationSender(animationTraceRow).then(result => { + expect(result).toHaveLength(2); + }); + }); + + it('FrameDynamicEffectSenderTest02', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(dynamicCurveData, dynamicCurveData.length, true); + }); + let frameDynamicTraceRow = TraceRow.skeleton(); + frameDynamicSender(frameDynamicTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); + + it('FrameDynamicEffectSenderTest03', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(frameSpacingData, frameSpacingData.length, true); + }); + let frameSpacingTraceRow = TraceRow.skeleton(); + frameSpacingSender(1255, 5255, frameSpacingTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(Array.isArray(result)).toBe(true); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/FrameJanksReceiver.test.ts b/ide/test/trace/database/data-trafic/FrameJanksReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..659a6a1e4749e24e89767f1ab5c0a08c2595996f --- /dev/null +++ b/ide/test/trace/database/data-trafic/FrameJanksReceiver.test.ts @@ -0,0 +1,94 @@ +/* + * 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 { + frameActualReceiver, + frameExpectedReceiver +} from "../../../../src/trace/database/data-trafic/FrameJanksReceiver"; + +describe('FrameJanksReceiver Test', () => { + let data = { + action: "exec-proto", + id: "5", + name: 16, + params: { + endNS: 8711323000, + queryEnum: 16, + recordEndNS: 512261248000, + recordStartNS: 503549925000, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703484466189, + trafic: 3, + width: 1407 + } + } + + let expectData = { + frameData: { + appDur: 16634548, + cmdline: "com.huawei.wx", + depth: 2, + dur: 33269438, + frameType: "frameTime", + id: 1007, + ipid: 135, + jankTag: -1, + name: 2299, + pid: 3104, + rsDur: 16634548, + rsIpid: 15, + rsPid: 994, + rsTs: 4996898311, + rsVsync: 1279, + ts: 4980263421, + type: "1" + } + } + + let actualData = { + frameData: { + appDur: 1697000, + cmdline: "com.ohos.launch", + depth: 0, + dur: 24662000, + frameType: "frameTime", + id: 918, + ipid: 19, + name: 2280, + pid: 2128, + rsDur: 11082000, + rsIpid: 15, + rsPid: 994, + rsTs: 4681218000, + rsVsync: 1260, + ts: 4667638000, + type: "0" + } + } + it('FrameJanksReceiverTest01', function () { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(frameExpectedReceiver(data, () => { + return expectData; + })).toBeUndefined(); + }); + + it('FrameJanksReceiverTest02', function () { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(frameActualReceiver(data, () => { + return actualData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/FrameJanksSender.test.ts b/ide/test/trace/database/data-trafic/FrameJanksSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0f75a746b7b8e0427283c41c2cb142f9619e674 --- /dev/null +++ b/ide/test/trace/database/data-trafic/FrameJanksSender.test.ts @@ -0,0 +1,90 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { frameJanksSender } from '../../../../src/trace/database/data-trafic/FrameJanksSender'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { JanksStruct } from '../../../../src/trace/bean/JanksStruct'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('FrameJanksSender Test', () => { + let expectedData = [{ + app_dur: 16603333, + cmdline: "com.ohos.launch", + depth: 0, + dur: 16603333, + frame: {x: 167, y: 0, width: 3, height: 20}, + frame_type: "frameTime", + id: 157, + ipid: 19, + jank_tag: 65535, + name: 2087, + pid: 2128, + rs_dur: 16603333, + rs_ipid: 15, + rs_name: "swapper", + rs_pid: 994, + rs_ts: 1038812193, + rs_vsync: 1080, + ts: 1038812193 + }] + + let actualData = [{ + app_dur: 3403000, + cmdline: "com.ohos.launch", + depth: 0, + dur: 17569000, + frame: {x: 739, y: 0, width: 3, height: 20}, + frame_type: "frameTime", + id: 898, + ipid: 19, + jank_tag: 0, + name: 2275, + pid: 2128, + rs_dur: 1192000, + rs_ipid: 15, + rs_name: "swapper", + rs_pid: 994, + rs_ts: 4598062000, + rs_vsync: 1255, + ts: 4581685000, + type: "0" + }] + + it('FrameJanksSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(expectedData, expectedData.length, true); + }); + let expectedTraceRow = TraceRow.skeleton(); + frameJanksSender(QueryEnum.FrameExpectedData, expectedTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); + + it('FrameJanksSenderTest02', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(actualData, actualData.length, true); + }); + let actualTraceRow = TraceRow.skeleton(); + frameJanksSender(QueryEnum.FrameActualData, actualTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(Array.isArray(result)).toBe(true); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/FuncDataReceiver.test.ts b/ide/test/trace/database/data-trafic/FuncDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4c559c27e331a9fca30cc73b5359962b25f70e4 --- /dev/null +++ b/ide/test/trace/database/data-trafic/FuncDataReceiver.test.ts @@ -0,0 +1,83 @@ +/* + * 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 { + chartFuncDataSql, + chartFuncDataSqlMem, + funcDataReceiver +} from '../../../../src/trace/database/data-trafic/FuncDataReceiver'; + +describe('FuncDataReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + id: '55febc1a-1eea-4c9f-ad29-33cd10b95b39', + name: 31, + action: 'exec-proto', + params: { + tid: 8182, + ipid: 52, + startNS: 0, + endNS: 9427688540, + recordStartNS: 4049847357191, + recordEndNS: 4059275045731, + width: 549, + trafic: 0 + } + }; + proc = jest.fn((sql: any) => [ + { + FuncData: { + startTs: 129966146, + dur: 0, + argsetid: 2128, + depth: 0, + id: 1090, + px: 7, + durTmp: 0 + } + }, + { + FuncData: { + startTs: 155282292, + dur: 0, + argsetid: 3260, + depth: 0, + id: 1778, + px: 9, + durTmp: 0 + } + }, + ]); + }); + it('FuncDataReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartFuncDataSql(args)).toBeTruthy(); + expect(chartFuncDataSqlMem(args)).toBeTruthy(); + }); + it('FuncDataReceiverTest02 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + funcDataReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/FuncDataSender.test.ts b/ide/test/trace/database/data-trafic/FuncDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fb17a43f204283f76710fb115b97d4350aa79bc --- /dev/null +++ b/ide/test/trace/database/data-trafic/FuncDataSender.test.ts @@ -0,0 +1,51 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { FuncStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerFunc'; +import { funcDataSender } from '../../../../src/trace/database/data-trafic/FuncDataSender'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('FuncDataSender Test',()=>{ + let FuncData = [{ + startTs: 111552604, + dur: 0, + argsetid: 1462, + depth: 0, + id: 633, + itid: 120, + ipid: 52, + funName: "binder transaction async", + frame: { + x: 6, + y: 0, + width: 1, + height: 20 + } + }] + it('FuncDataSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(FuncData, FuncData.length, true); + }); + let tid = 1; + let ipid = 52; + let FuncDataTraceRow = TraceRow.skeleton(); + funcDataSender(tid,ipid,FuncDataTraceRow).then(res=>{ + expect(res).toHaveLength(1); + }) + }); +}) \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/HiSysEventDataReciver.test.ts b/ide/test/trace/database/data-trafic/HiSysEventDataReciver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..442030e25c9da6daf412821b057dd52ed1c09398 --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiSysEventDataReciver.test.ts @@ -0,0 +1,55 @@ +/* + * 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 { + hiSysEventDataReceiver, + chartHiSysEventDataSql +} from '../../../../src/trace/database/data-trafic/HiSysEventDataReceiver'; +import { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; + +describe('hiSysEventDataReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + proc = jest.fn((sql) => [ + {hiSysEventData: {id: 4, ts: 4.4, pid: 40, tid: 400, seq: 0.4, uid: 4000, dur: 40000, depth: 4}}, + {hiSysEventData: {id: 5, ts: 5.5, pid: 50, tid: 500, seq: 0.5, uid: 5000, dur: 50000, depth: 5}}, + ]); + }); + it('hiSysEventDataReceiverTest01', () => { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartHiSysEventDataSql(args)).toBeTruthy(); + }); + it('hiSysEventDataReceiverTest02', () => { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiSysEventDataReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/HiSysEventDataSender.test.ts b/ide/test/trace/database/data-trafic/HiSysEventDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a38e9889dd6c915b69d076c3f8d5e168ae5e0fa --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiSysEventDataSender.test.ts @@ -0,0 +1,57 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { HiSysEventStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerHiSysEvent'; +import { hiSysEventDataSender } from '../../../../src/trace/database/data-trafic/HiSysEventDataSender'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('hiSysEventDataSender Test', () => { + let hiSysEventData = [{ + id: 808, + ts: 78977000000, + pid: 491, + tid: 2591, + uid: 6696, + dur: 1, + depth: 0, + seq: -1, + domain: 'MULTIMODALINPUT', + eventName: 'TARGET_POINTER_EVENT_SUCCESS', + info: '', + level: 'MINOR', + contents: '{"AGENT_WINDOWID":16,"EVENTTYPE":131072,"FD":33,"MSG":"The window manager successfully update target pointer","PID":4192,"TARGET_WINDOWID":16}', + frame: { + y: 10, + height: 20, + x: 168, + width: 1 + }, + v: true + }]; + it('hiSysEventDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(hiSysEventData, hiSysEventData.length, true); + }); + let hiSysEventTraceRow = TraceRow.skeleton(); + hiSysEventDataSender(QueryEnum.HiSysEventData, hiSysEventTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/HiperfCallChartReceiver.test.ts b/ide/test/trace/database/data-trafic/HiperfCallChartReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5b7e18eeb62fd9708dc7f20af29db0cbab901e53 --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfCallChartReceiver.test.ts @@ -0,0 +1,73 @@ +// 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 { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { + chartHiperfCallChartDataSql, + hiPerfCallChartDataHandler, hiPerfCallStackCacheHandler +} from '../../../../src/trace/database/data-trafic/HiperfCallChartReceiver'; + +describe('HiperfCallChartReceiver Test', () => { + let data; + let proc; + let data2; + beforeEach(() => { + data = { + id: "817fccf0-76a8-41f3-86d6-6282b1208b58", + name: 203, + action: "exec-proto", + params: { + recordStartNS: 1395573006744, + trafic: 2, + isCache: true + } + }; + data2 = { + id: "817fccf0-76a8-41f3-86d6-6282b1208b58", + name: 203, + action: "exec-proto", + params: { + recordStartNS: 1395573006744, + trafic: 2, + isCache: false + } + }; + proc = jest.fn((sql) => [ + {HiperfCallChartData: {callchainId: 4, startTs: 4.4, eventCount: 40, threadId: 400, cpuId: 40000, eventTypeId: 4}}, + {HiperfCallChartData: {callchainId: 5, startTs: 5.5, eventCount: 50, threadId: 500, cpuId: 50000, eventTypeId: 5}}, + ]); + }); + it('HiperfCallChartReceiver01', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartHiperfCallChartDataSql(args)).toBeTruthy(); + }); + it('HiperfCallChartReceiver02', () => { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiPerfCallChartDataHandler(data, proc); + hiPerfCallChartDataHandler(data2, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('HiperfCallChartReceiver03', () => { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiPerfCallStackCacheHandler(data, proc); + hiPerfCallStackCacheHandler(data2, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/HiperfCpuDataReceiver.test.ts b/ide/test/trace/database/data-trafic/HiperfCpuDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0437a8acb0f3c727cd7fa341a877e6e5fb5b99ee --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfCpuDataReceiver.test.ts @@ -0,0 +1,65 @@ +/* + * 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 { + chartHiperfCpuData10MSProtoSql, + chartHiperfCpuDataProtoSql, hiperfCpuDataReceiver +} from '../../../../src/trace/database/data-trafic/HiperfCpuDataReceiver'; + +describe(' HiperfCpuDataReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + id: '87cc16a3-5dc7-4202-9ac9-4f038b2979ee', + name: 200, + action: 'exec-proto', + params: { + cpu: -1, + scale: 2000000000, + maxCpuCount: 4, + drawType: -2, + intervalPerf: 1, + startNS: 0, + endNS: 30230251246, + recordStartNS: 1596201782236, + recordEndNS: 1626432033482, + width: 549, + trafic: 3 + } + }; + proc = jest.fn((sql: any) => [ + {hiperfData: {startNs: 5600000000, eventCount: 58513886, sampleCount: 42, callchainId: 2279}}, + {hiperfData: {startNs: 5630000000, eventCount: 60359281, sampleCount: 36, callchainId: 5147}} + ]); + }); + it('HiperfCpuDataReceiverTest01 ', function () { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartHiperfCpuData10MSProtoSql(args)).toBeTruthy(); + expect(chartHiperfCpuDataProtoSql(args)).toBeTruthy(); + }); + it('HiperfCpuDataReceiverTest02 ', function () { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiperfCpuDataReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/HiperfCpuDataSender.test.ts b/ide/test/trace/database/data-trafic/HiperfCpuDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f0c84b58300a97025ed8ea504638a64d350f289 --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfCpuDataSender.test.ts @@ -0,0 +1,54 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { HiPerfCpuStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerHiPerfCPU'; +import { hiperfCpuDataSender } from '../../../../src/trace/database/data-trafic/HiperfCpuDataSender'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('HiperfCpuDataSender Test',()=>{ + let HiperfCpuData = [{ + startNS: 0, + eventCount: 26655990, + sampleCount: 63, + event_type_id: 0, + callchain_id: 3, + height: 63, + dur: 10000000, + frame: { + y: 0, + height: 63, + x: 0, + width: 1 + } + }] + it('HiperfCpuDataTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(HiperfCpuData, HiperfCpuData.length, true); + }); + let cpu = -1; + let drawType = -2; + let maxCpuCount = 4; + let intervalPerf = 1; + let scale = 2000000000; + let HiperfCpuDataTraceRow = TraceRow.skeleton(); + hiperfCpuDataSender(cpu,drawType,maxCpuCount,intervalPerf,scale,HiperfCpuDataTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); +}) + diff --git a/ide/test/trace/database/data-trafic/HiperfProcessDataReceiver.test.ts b/ide/test/trace/database/data-trafic/HiperfProcessDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..02c6103b27a19cc818776c48d4d73ce2348da768 --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfProcessDataReceiver.test.ts @@ -0,0 +1,87 @@ +/* + * 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 { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { + chartHiperfProcessData10MSProtoSql, + chartHiperfProcessDataProtoSql, + hiperfProcessDataReceiver, +} from '../../../../src/trace/database/data-trafic/HiperfProcessDataReceiver'; + +describe('HiperfProcess Test', () => { + let data1; + let data2; + let proc1; + let proc2; + + beforeEach(() => { + data1 = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: {}, + drawType: -2, + endNS: 49171193732, + intervalPerf: 1, + maxCpuCount: -1, + pid: 11, + recordEndNS: 30418971157414, + recordStartNS: 30369799963682, + scale: 2000000000, + startNS: 0, + width: 1407, + }, + }; + data2 = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: {}, + drawType: -2, + endNS: 10360520695.855345, + intervalPerf: 1, + maxCpuCount: -1, + pid: 11, + recordEndNS: 30418971157414, + recordStartNS: 30369799963682, + scale: 20000000, + startNS: 9901354882.564587, + width: 888, + }, + }; + proc1 = jest.fn((sql) => [ + { hiperfData: { callchainId: 262, eventCount: 14, eventTypeId: 1, sampleCount: 1, startNs: 130000000 } }, + { hiperfData: { callchainId: 422, eventCount: 24, eventTypeId: 2, sampleCount: 1, startNs: 170000000 } }, + ]); + proc2 = jest.fn((sql) => [ + { hiperfData: { callchainId: 12515, eventCount: 191077, eventTypeId: 1, sampleCount: 1, startNs: 10017921673 } }, + { hiperfData: { callchainId: 94, eventCount: 140815, eventTypeId: 1, sampleCount: 1, startNs: 10022069465 } }, + ]); + }); + it('HiperfProcessReceiverTest01', () => { + expect(chartHiperfProcessData10MSProtoSql(data1.params)).toBeTruthy(); + expect(chartHiperfProcessDataProtoSql(data2.params)).toBeTruthy(); + }); + it('HiperfProcessReceiverTest02', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiperfProcessDataReceiver(data1, proc1); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('HiperfProcessReceiverTest03', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiperfProcessDataReceiver(data2, proc2); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ide/test/trace/database/data-trafic/HiperfProcessDataSender.test.ts b/ide/test/trace/database/data-trafic/HiperfProcessDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..987e0ef39494048d303bd64c89adbcde04fa6064 --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfProcessDataSender.test.ts @@ -0,0 +1,54 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { hiperfProcessDataSender } from '../../../../src/trace/database/data-trafic/HiperfProcessDataSender'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { HiPerfProcessStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerHiPerfProcess'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('HiperfProcessSender Test', () => { + let traceRowData = [ + { + dur: 10000000, + frame: { x: 2, y: 0, width: 1, height: 4 }, + startNS: 170000000, + callchain_id: 422, + event_count: 24, + event_type_id: 2, + height: 4, + sampleCount: 1, + }, + { + dur: 10000000, + frame: { x: 2, y: 0, width: 2, height: 8 }, + startNS: 180000000, + callchain_id: 262, + event_count: 40, + event_type_id: 1, + height: 8, + sampleCount: 2, + }, + ]; + it('HiperfProcessSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(traceRowData, traceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + hiperfProcessDataSender(11, -2, 1, 2000000000, traceRow).then((res) => { + expect(res).toHaveLength(2); + }); + }); +}); diff --git a/ide/test/trace/database/data-trafic/HiperfThreadDataReceiver.test.ts b/ide/test/trace/database/data-trafic/HiperfThreadDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..87f87797750b1750800252258558221f0bc02549 --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfThreadDataReceiver.test.ts @@ -0,0 +1,87 @@ +/* + * 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 { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { + chartHiperfThreadData10MSProtoSql, + chartHiperfThreadDataProtoSql, + hiperfThreadDataReceiver, +} from '../../../../src/trace/database/data-trafic/HiperfThreadDataReceiver'; + +describe('HiperfThread Test', () => { + let data1; + let data2; + let proc1; + let proc2; + + beforeEach(() => { + data1 = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: {}, + drawType: -2, + endNS: 49171193732, + intervalPerf: 1, + maxCpuCount: -1, + recordEndNS: 30418971157414, + recordStartNS: 30369799963682, + scale: 2000000000, + startNS: 0, + tid: 28917, + width: 841, + }, + }; + data2 = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: {}, + drawType: -2, + endNS: 38843292896.21842, + intervalPerf: 1, + maxCpuCount: -1, + recordEndNS: 30418971157414, + recordStartNS: 30369799963682, + scale: 20000000, + startNS: 38410507602.73825, + tid: 28917, + width: 841, + }, + }; + proc1 = jest.fn((sql) => [ + { hiperfData: { callchainId: 12, eventCount: 3603585, sampleCount: 11, startNs: 0 } }, + { hiperfData: { callchainId: 128, eventCount: 728632, sampleCount: 1, startNs: 70000000 } }, + ]); + proc2 = jest.fn((sql) => [ + { hiperfData: { callchainId: 1114, eventCount: 106450, sampleCount: 1, startNs: 38427936069 } }, + { hiperfData: { callchainId: 94, eventCount: 140815, sampleCount: 1, startNs: 38428328069 } }, + ]); + }); + it('HiperfThreadReceiverTest01', () => { + expect(chartHiperfThreadData10MSProtoSql(data1.params)).toBeTruthy(); + expect(chartHiperfThreadDataProtoSql(data2.params)).toBeTruthy(); + }); + it('HiperfThreadReceiverTest02', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiperfThreadDataReceiver(data1, proc1); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it('HiperfThreadReceiverTest03', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + hiperfThreadDataReceiver(data2, proc2); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ide/test/trace/database/data-trafic/HiperfThreadDataSender.test.ts b/ide/test/trace/database/data-trafic/HiperfThreadDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c6d6ee182266aacaa0fcd297ef6ecf3052823fe --- /dev/null +++ b/ide/test/trace/database/data-trafic/HiperfThreadDataSender.test.ts @@ -0,0 +1,54 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { hiperfThreadDataSender } from '../../../../src/trace/database/data-trafic/HiperfThreadDataSender'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { HiPerfThreadStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerHiPerfThread'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('HiperfThreadSender Test', () => { + let traceRowData = [ + { + dur: 10000000, + frame: { x: 0, y: 0, width: 1, height: 44 }, + startNS: 0, + callchain_id: 12, + event_count: 3603585, + event_type_id: 0, + height: 44, + sampleCount: 11, + }, + { + dur: 10000000, + frame: { x: 1, y: 0, width: 1, height: 4 }, + startNS: 70000000, + callchain_id: 128, + event_count: 728632, + event_type_id: 0, + height: 4, + sampleCount: 1, + }, + ]; + it('HiperfThreadSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(traceRowData, traceRowData.length, true); + }); + let traceRow = TraceRow.skeleton(); + hiperfThreadDataSender(28917, -2, 1, 2000000000, traceRow).then((res) => { + expect(res).toHaveLength(2); + }); + }); +}); diff --git a/ide/test/trace/database/data-trafic/IrqDataReceiver.test.ts b/ide/test/trace/database/data-trafic/IrqDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1595a9d8331b56d8b1f6395d7155e5670965d059 --- /dev/null +++ b/ide/test/trace/database/data-trafic/IrqDataReceiver.test.ts @@ -0,0 +1,104 @@ +/* + * 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 { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; +import { + chartIrqDataSql, + chartIrqDataSqlMem, + irqDataReceiver, +} from '../../../../src/trace/database/data-trafic/IrqDataReceiver'; + +describe('IrqReceiver Test', () => { + let data1; + let data2; + let proc; + + beforeEach(() => { + data1 = { + params: { + trafic: TraficEnum.ProtoBuffer, + cpu: 0, + endNS: 19473539059, + name: 'irq', + recordEndNS: 30167849973030, + recordStartNS: 30148376433971, + startNS: 0, + t: 1703665514720, + width: 708, + sharedArrayBuffers: {}, + }, + }; + data2 = { + params: { + trafic: TraficEnum.Memory, + cpu: 0, + endNS: 19473539059, + name: 'irq', + recordEndNS: 30167849973030, + recordStartNS: 30148376433971, + startNS: 0, + t: 1703665514720, + width: 708, + sharedArrayBuffers: {}, + }, + }; + proc = jest.fn((sql) => [ + { irqData: { argSetId: 74, dur: 3646, id: 74, startNs: 4255208 } }, + { irqData: { argSetId: 400, dur: 3125, id: 397, startNs: 38229687 } }, + ]); + }); + test('IrqReceiverTest01', () => { + const args = { + trafic: TraficEnum.ProtoBuffer, + cpu: 0, + endNS: 19473539059, + name: 'irq', + recordEndNS: 30167849973030, + recordStartNS: 30148376433971, + startNS: 0, + t: 1703665514720, + width: 708, + sharedArrayBuffers: {}, + }; + expect(chartIrqDataSql(args)).toBeTruthy(); + }); + test('IrqReceiverTest02', () => { + const args = { + trafic: TraficEnum.Memory, + cpu: 0, + endNS: 19473539059, + name: 'irq', + recordEndNS: 30167849973030, + recordStartNS: 30148376433971, + startNS: 0, + t: 1703665514720, + width: 708, + sharedArrayBuffers: {}, + }; + expect(chartIrqDataSqlMem(args)).toBeTruthy(); + }); + test('IrqReceiverTest03', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + irqDataReceiver(data1, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + test('IrqReceiverTest04', () => { + let mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + irqDataReceiver(data2, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ide/test/trace/database/data-trafic/IrqDataSender.test.ts b/ide/test/trace/database/data-trafic/IrqDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..17601767a184194334e3a272302231f939efa720 --- /dev/null +++ b/ide/test/trace/database/data-trafic/IrqDataSender.test.ts @@ -0,0 +1,52 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { irqDataSender } from '../../../../src/trace/database/data-trafic/IrqDataSender'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { IrqStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerIrq'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('irqDataSender Test', () => { + let IrqData = [ + { + argSetId: 74, + depth: 0, + dur: 3646, + frame: { x: 0, y: 5, width: 1, height: 30 }, + id: 74, + name: 'IPI', + startNS: 4255208, + }, + { + argSetId: 400, + depth: 0, + dur: 3125, + frame: { x: 1, y: 5, width: 1, height: 30 }, + id: 397, + name: 'IPI', + startNS: 38229687, + }, + ]; + it('IrqDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(IrqData, IrqData.length, true); + }); + let traceRow = TraceRow.skeleton(); + irqDataSender(0, 'irq', traceRow).then((res) => { + expect(res).toHaveLength(2); + }); + }); +}); diff --git a/ide/test/trace/database/data-trafic/LogDataReceiver.test.ts b/ide/test/trace/database/data-trafic/LogDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d637af456bd7153e5d2782b43055cffe10a6442 --- /dev/null +++ b/ide/test/trace/database/data-trafic/LogDataReceiver.test.ts @@ -0,0 +1,55 @@ +/* + * 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 { + logDataReceiver, + chartLogDataSql +} from '../../../../src/trace/database/data-trafic/LogDataReceiver'; +import { TraficEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; + +describe('logDataReceiver Test', () => { + let data; + let proc; + + beforeEach(() => { + data = { + params: { + trafic: TraficEnum.ProtoBuffer, + sharedArrayBuffers: { + id: new Uint16Array([1, 2, 3]), + }, + }, + }; + proc = jest.fn((sql) => [ + {logData: {id: 4, startTs: 4.4, pid: 40, tid: 400, dur: 40000, depth: 4}}, + {logData: {id: 5, startTs: 5.5, pid: 50, tid: 500, dur: 50000, depth: 5}}, + ]); + }); + it('logDataReceiverTest01', () => { + const args = { + recordStartNS: 1000, + endNS: 3000, + startNS: 2000, + width: 10 + }; + expect(chartLogDataSql(args)).toBeTruthy(); + }); + it('logDataReceiverTest02', () => { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + logDataReceiver(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/LogDataSender.test.ts b/ide/test/trace/database/data-trafic/LogDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..98f379ebdac2ab326c50d6de3cfbb7d19335edce --- /dev/null +++ b/ide/test/trace/database/data-trafic/LogDataSender.test.ts @@ -0,0 +1,54 @@ +/* + * 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 { LogDataSender } from '../../../../src/trace/database/data-trafic/LogDataSender'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { LogStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerLog'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { QueryEnum } from '../../../../src/trace/database/data-trafic/QueryEnum'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); +describe('LogDataSender Test', () => { + let logData = [{ + id: 4, + startTs: 162769475, + pid: 2082, + tid: 2082, + dur: 1, + depth: 1, + tag: 'C02c01/Init', + context: '[param_request.c:53]Can not get log level from param, keep the original loglevel.', + originTime: '08-06 15:43:19.954', + processName: 'hilog', + level: 'Info', + frame: { + 'x': 1, + 'y': 7, + 'width': 1, + 'height': 7 + } + }]; + it('LogDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(logData, logData.length, true); + }); + let logTraceRow = TraceRow.skeleton(); + LogDataSender(QueryEnum.HilogData, logTraceRow).then(res => { + expect(res).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/NativeMemoryDataReceiver.test.ts b/ide/test/trace/database/data-trafic/NativeMemoryDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f94640c3f6fc7e7155ced6cd5950d9e5ba66957 --- /dev/null +++ b/ide/test/trace/database/data-trafic/NativeMemoryDataReceiver.test.ts @@ -0,0 +1,74 @@ +/* + * 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 { + filterNativeMemoryChartData, + nativeMemoryDataHandler +} from '../../../../src/trace/database/data-trafic/NativeMemoryDataReceiver.js'; + +describe(' NativeMemoryDataReceiver Test', () => { + let data; + let proc; + const dataCache = { + normalCache: new Map(), + statisticsCache: new Map(), + }; + beforeEach(() => { + data = { + id: 'c07094fb-5340-4f1e-be9d-cd4071a77e24', + name: 206, + action: 'exec-proto', + params: { + totalNS: 108952700947, + recordStartNS: 8406282873525, + recordEndNS: 8515235574472, + model: 'native_hook', + processes: [ + 1 + ], + trafic: 1, + isCache: true + } + }; + proc = jest.fn((sql) => [ + {data: {id: 4, startTs: 4.4, pid: 40, tid: 400, dur: 40000, depth: 4}}, + {data: {id: 5, startTs: 5.5, pid: 50, tid: 500, dur: 50000, depth: 5}}, + ]); + }); + afterEach(() => { + dataCache.normalCache.clear(); + dataCache.statisticsCache.clear(); + }); + it(' NativeMemoryDataReceiver01', () => { + const mockPostMessage = jest.fn(); + global.postMessage = mockPostMessage; + nativeMemoryDataHandler(data, proc); + expect(mockPostMessage).toHaveBeenCalledTimes(1); + }); + it(' NativeMemoryDataReceiver02', () => { + const model = 'native_hook'; + const startNS = 0; + const endNS = 100; + const totalNS = 200; + const drawType = 0; + const frame = 1; + const key = 'testKey'; + const result = filterNativeMemoryChartData(model, startNS, endNS, totalNS, drawType, frame, key); + expect(result.startTime).toEqual([]); + expect(result.dur).toEqual([]); + expect(result.heapSize).toEqual([]); + expect(result.density).toEqual([]); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/NativeMemoryDataSender.test.ts b/ide/test/trace/database/data-trafic/NativeMemoryDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..33cd3d272e2510426d126e417bd163a8c3b8dcdb --- /dev/null +++ b/ide/test/trace/database/data-trafic/NativeMemoryDataSender.test.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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { + nativeMemoryChartDataCacheSender, + nativeMemoryChartDataSender +} from '../../../../src/trace/database/data-trafic/NativeMemoryDataSender'; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('NativeMemoryDataSender Test',()=>{ + let NativeMemoryData = [{ + startTime: 3384276048, + dur: 369027787, + heapsize: 17380280, + density: 193, + maxHeapSize: 58546932, + maxDensity: 4993, + minHeapSize: 0, + minDensity: 0, + frame: { + x: 17, + y: 5, + width: 2, + height: 30 + } + }] + it('NativeMemoryDataSenderTest01 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(NativeMemoryData, NativeMemoryData.length, true); + }); + let nativeMemoryChartDataTraceRow = TraceRow.skeleton(); + let setting = { + eventType: 0, + ipid: 1, + model: "native_hook", + drawType: 0 + } + nativeMemoryChartDataSender(nativeMemoryChartDataTraceRow,setting).then(res => { + expect(res).toHaveLength(1); + }); + }); + it('NativeMemoryDataSenderTest02 ', function () { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(NativeMemoryData, NativeMemoryData.length, true); + }); + let processes = [1]; + let model = 'native_hook'; + nativeMemoryChartDataCacheSender(processes,model).then(res => { + expect(res).toHaveLength(2); + }); + }); +}) \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessActualDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ProcessActualDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..10e1deb45ecd1dc05509e2c81864b73b8f6565d0 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessActualDataReceiver.test.ts @@ -0,0 +1,57 @@ +/* + * 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 { processActualDataReceiver } from '../../../../src/trace/database/data-trafic/ProcessActualDataReceiver'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessActualDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "5", + name: 27, + params: + { + endNS: 8711323000, + pid: 994, + recordEndNS: 512261248000, + recordStartNS: 503549925000, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703558234327, + trafic: 3, + width: 1407 + } + } + let actualData = [{ + processJanksActualData: { + dstSlice: -1, + dur: 6769000, + id: 1296, + name: 1336, + pid: 994, + ts: 5945218000 + } + }] + + it('ActualDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(processActualDataReceiver(data, () => { + return actualData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessActualDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessActualDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d651e753b5961e8133976cf8694e4caedf78fdbd --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessActualDataSender.test.ts @@ -0,0 +1,66 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { processActualDataSender } from '../../../../src/trace/database/data-trafic/ProcessActualDataSender'; +import { JankStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerJank'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessActualDataSender Test', () => { + let actualData = [ + { + cmdline: "com.ohos.launch", + depth: 0, + dst_slice: 506, + dur: 2273000, + frame: {x: 393, y: 0, width: 1, height: 20}, + frame_type: "app", + id: 502, + jank_tag: 0, + name: 2171, + pid: 2128, + src_slice: "", + ts: 2435796000, + type: 0 + }, + { + cmdline: "com.ohos.launch", + depth: 0, + dst_slice: 510, + dur: 2395000, + frame: {x: 395, y: 0, width: 1, height: 20}, + frame_type: "app", + id: 508, + jank_tag: 0, + name: 2172, + pid: 2128, + src_slice: "", + ts: 2452847000, + type: 0 + }] + it('ActualDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(actualData, actualData.length, true); + }); + let actualTraceRow = TraceRow.skeleton(); + processActualDataSender(2128, actualTraceRow).then(result => { + expect(result).toHaveLength(2); + }); + }); +}); \ No newline at end of file diff --git a/trace_streamer/src/rpc/http_socket.h b/ide/test/trace/database/data-trafic/ProcessDataReceiver.test.ts similarity index 36% rename from trace_streamer/src/rpc/http_socket.h rename to ide/test/trace/database/data-trafic/ProcessDataReceiver.test.ts index 03391c59c080d50bd1b345959c041bb10d94c45f..226698b1d50ae37f41382c7b98226e45f361ae2e 100644 --- a/trace_streamer/src/rpc/http_socket.h +++ b/ide/test/trace/database/data-trafic/ProcessDataReceiver.test.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,43 +13,47 @@ * limitations under the License. */ -#ifndef RPC_HTTPSOCKET_H -#define RPC_HTTPSOCKET_H +import { processDataReceiver } from '../../../../src/trace/database/data-trafic/ProcessDataReceiver'; -#include -namespace SysTuning { -namespace TraceStreamer { -class HttpSocket { -public: - HttpSocket() {} - HttpSocket(int32_t sockId, int32_t domain) : sockId_(sockId), domain_(domain) {} - ~HttpSocket(); +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); - bool CreateSocket(int32_t domain); - bool Bind(int32_t port); - bool Listen(int32_t maxConn); - bool Accept(HttpSocket& client); - bool Recv(void* data, size_t& len); - bool Send(const void* data, size_t len); - void Close(); - bool IsValid() const +describe('ProcessDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "6", + name: 6, + params: + { + endNS: 8711323000, + pid: 431, + recordEndNS: 512261248000, + recordStartNS: 503549925000, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703560455293, + trafic: 0, + width: 1407 + } + } + let processData = [ { - return sockId_ != INVALID_SOCKET; - } - int32_t GetFd() const + cpu: 1, + dur: 1136000, + startTime: 3650382000, + v: true, + }, { - return sockId_; + cpu: 1, + dur: 104000, + startTime: 3665355000 } - -private: - int32_t sockId_ = -1; - int32_t domain_ = 0; - using SOCKET = int32_t; -#if !is_mingw - const int32_t SOCKET_ERROR = -1; -#endif - const SOCKET INVALID_SOCKET = -1; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // RPC_HTTPSOCKET_H + ] + it('ProcessDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(processDataReceiver(data, () => { + return processData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6744fe74a9915aed4b170d46397d002f78c2dc1f --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessDataSender.test.ts @@ -0,0 +1,46 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { processDataSender } from "../../../../src/trace/database/data-trafic/ProcessDataSender"; +import { ProcessStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerProcess'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessDataSender Test', () => { + let processData = [ + { + cpu: 0, + dur: 140000, + startTime: 8339440000, + }, + { + cpu: 0, + dur: 138000, + startTime: 8355773000 + }] + it('ProcessDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(processData, processData.length, true); + }); + let processTraceRow = TraceRow.skeleton(); + processDataSender(994, processTraceRow).then(result => { + expect(result).toHaveLength(2); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessDeliverInputEventDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ProcessDeliverInputEventDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0edc355bb05ccca0ba6f0dd82a8aca23d01133f6 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessDeliverInputEventDataReceiver.test.ts @@ -0,0 +1,63 @@ +/* + * 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 { + processDeliverInputEventDataReceiver +} from '../../../../src/trace/database/data-trafic/ProcessDeliverInputEventDataReceiver'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('DeliverInputEventDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "52", + name: 28, + params: + { + endNS: 20000305000, + recordEndNS: 168778663166000, + recordStartNS: 168758662861000, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703561897634, + tid: "1298", + trafic: 3, + width: 1407 + } + } + let res = [ + { + processInputEventData: { + argsetid: -1, + cookie: 10350, + dur: 83000, + id: 41459, + isMainThread: 1, + parentId: -1, + pid: 1298, + startTs: 7379559000, + tid: 1298, + trackId: 14 + } + }] + it('DeliverInputEventDataReceiverTest01', async () => { + let mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + processDeliverInputEventDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessDeliverInputEventDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessDeliverInputEventDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e212df030b2af8021d599a29ac6140d94204518 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessDeliverInputEventDataSender.test.ts @@ -0,0 +1,53 @@ +/* + * 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 { threadPool } from '../../../../src/trace/database/SqlLite'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { FuncStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerFunc'; +import { + processDeliverInputEventDataSender +} from '../../../../src/trace/database/data-trafic/ProcessDeliverInputEventDataSender'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessDataSender Test', () => { + let inputEventData = [{ + argsetid: -1, + cookie: 684, + depth: 0, + dur: 781000, + frame: {x: 516, y: 0, width: 1, height: 20}, + funName: "deliverInputEvent", + id: 40814, + is_main_thread: 1, + parent_id: 7256, + pid: 7256, + startTs: 7340590000, + threadName: "ndroid.settings", + tid: 7256, + track_id: 136 + }] + it('ProcessDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(inputEventData, inputEventData.length, true); + }); + let inputEventTraceRow = TraceRow.skeleton(); + processDeliverInputEventDataSender(7256, inputEventTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessExpectedDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ProcessExpectedDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d243fe95f95a2fe9c47df4a3e2a33e66bc29d21 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessExpectedDataReceiver.test.ts @@ -0,0 +1,56 @@ +/* + * 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 { processExpectedDataReceiver } from '../../../../src/trace/database/data-trafic/ProcessExpectedDataReceiver'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessExpectedDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "966", + name: 26, + params: + { + endNS: 8711323000, + pid: 994, + recordEndNS: 512261248000, + recordStartNS: 503549925000, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703572989578, + trafic: 3, + width: 1407 + } + } + let expectedData = [{ + processJanksFramesData: { + dur: 16627734, + id: 415, + name: 1143, + pid: 994, + ts: 2086211199, + type: 1 + } + }] + it('ExpectedDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(processExpectedDataReceiver(data, () => { + return expectedData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessExpectedDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessExpectedDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe9fde8cc4ae1fa7fac3f181ef61ca2280f07299 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessExpectedDataSender.test.ts @@ -0,0 +1,47 @@ +/* + * 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 { processExpectedDataSender } from '../../../../src/trace/database/data-trafic/ProcessExpectedDataSender'; +import { TraceRow } from '../../../../src/trace/component/trace/base/TraceRow'; +import { JankStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerJank'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessExpectedDataSender Test', () => { + let expectedData = [{ + cmdline: "render_service", + depth: 0, + dur: 16627734, + frame: {x: 336, y: 0, width: 3, height: 20}, + frame_type: "render_service", + id: 415, + name: 1143, + pid: 994, + ts: 2086211199, + type: 1143 + }] + it('ExpectedDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(expectedData, expectedData.length, true); + }); + let expectedTraceRow = TraceRow.skeleton(); + processExpectedDataSender(994, expectedTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessMemDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ProcessMemDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0bf165c6279ba250ec41b2b52e7421eaa29e25a --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessMemDataReceiver.test.ts @@ -0,0 +1,54 @@ +/* + * 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 { processMemDataReceiver } from '../../../../src/trace/database/data-trafic/ProcessMemDataReceiver'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessMemDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "71", + name: 7, + params: + { + endNS: 20000305000, + recordEndNS: 168778663166000, + recordStartNS: 168758662861000, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703574363518, + trackId: 543, + trafic: 3, + width: 1407 + } + } + let memData = [{ + processMemData: { + startTime: 7578590000, + trackId: 545, + ts: 168766241451000, + value: 1728 + } + }] + it('ProcessMemDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(processMemDataReceiver(data, () => { + return memData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessMemDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessMemDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcd702df0341beda1f8f990731e464b91c863135 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessMemDataSender.test.ts @@ -0,0 +1,45 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { processMemDataSender } from '../../../../src/trace/database/data-trafic/ProcessMemDataSender'; +import { ProcessMemStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerMem'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessMemDataSender Test', () => { + let memData = [{ + delta: 0, + duration: 4077000, + frame: {x: 645, y: 5, width: 1, height: 30}, + maxValue: 5, + startTime: 9178680000, + track_id: 31, + ts: 168767841541000, + value: 3 + }] + it('ProcessMemDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(memData, memData.length, true); + }); + let memTraceRow = TraceRow.skeleton(); + processMemDataSender(543, memTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessSoInitDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ProcessSoInitDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0dc35354d7e509e331310191ba80c8b83aaf5adf --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessSoInitDataReceiver.test.ts @@ -0,0 +1,46 @@ +/* + * 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 { processSoInitDataReceiver } from '../../../../src/trace/database/data-trafic/ProcessSoInitDataReceiver'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessSoInitDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "81", + name: 8, + params: + { + endNS: 29372913537, + pid: 4794, + recordEndNS: 262379203084, + recordStartNS: 233006289547, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703581047560, + trafic: 3, + width: 1407 + } + } + it('SoInitDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(processSoInitDataReceiver(data, () => { + return []; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessSoInitDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessSoInitDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..988c528232725169d54bc10821e558b0f5c6683b --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessSoInitDataSender.test.ts @@ -0,0 +1,35 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { processSoInitDataSender } from '../../../../src/trace/database/data-trafic/ProcessSoInitDataSender'; +import { SoStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerSoInit'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessSoInitDataSender Test', () => { + it('ProcessSoInitDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback([], 0, true); + }); + let soInitTraceRow = TraceRow.skeleton(); + processSoInitDataSender(543, soInitTraceRow).then(result => { + expect(result).toHaveLength(0); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessStartupDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ProcessStartupDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6867993d623d35a8842ea56fa37a51c07a0c1bd3 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessStartupDataReceiver.test.ts @@ -0,0 +1,56 @@ +/* + * 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 { processStartupDataReceiver } from '../../../../src/trace/database/data-trafic/ProcessStartupDataReceiver'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessStartupDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "81", + name: 8, + params: + { + endNS: 29372913537, + pid: 4794, + recordEndNS: 262379203084, + recordStartNS: 233006289547, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703581047560, + trafic: 3, + width: 1407 + } + } + let startUpData = [{ + processStartupData: { + dur: 6055208, + itid: 76, + pid: 4794, + startName: 1, + startTime: 266994271, + tid: 4794 + } + }] + it('StartupDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(processStartupDataReceiver(data, () => { + return startUpData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ProcessStartupDataSender.test.ts b/ide/test/trace/database/data-trafic/ProcessStartupDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c6c976625396bc820ea079888cdb5901ce7d8ff --- /dev/null +++ b/ide/test/trace/database/data-trafic/ProcessStartupDataSender.test.ts @@ -0,0 +1,45 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { AppStartupStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerAppStartup'; +import { processStartupDataSender } from '../../../../src/trace/database/data-trafic/ProcessStartupDataSender'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ProcessStartupDataSender Test', () => { + let startupData = [{ + dur: 6055208, + endItid: 167, + frame: {y: 5, height: 20, x: 12, width: 2}, + itid: 76, + pid: 4794, + startName: 1, + startTs: 266994271, + tid: 4794 + }] + it('ProcessStartupDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(startupData, startupData.length, true); + }); + let startupTraceRow = TraceRow.skeleton(); + processStartupDataSender(4794, startupTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ThreadDataReceiver.test.ts b/ide/test/trace/database/data-trafic/ThreadDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a5794339a3caa5417221cc13d4c331de314e023 --- /dev/null +++ b/ide/test/trace/database/data-trafic/ThreadDataReceiver.test.ts @@ -0,0 +1,71 @@ +/* + * 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 { threadDataReceiver } from "../../../../src/trace/database/data-trafic/ThreadDataReceiver"; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ThreadDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "258", + name: 30, + params: + { + endNS: 29372913537, + pid: 1668, + recordEndNS: 262379203084, + recordStartNS: 233006289547, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703581047560, + trafic: 2, + width: 1407 + } + } + + let threadData = [ + { + argSetId: -1, + cpu: null, + dur: 2327000, + id: 16, + pid: 590, + px: 285, + startTime: 2029133000, + state: "D", + tid: 590 + }, + { + argSetId: -1, + cpu: 3, + dur: 14494000, + id: 6, + pid: 1668, + px: 1331, + startTime: 9464658000, + state: "Running", + tid: 1699 + } + ] + it('ThreadDataReceiverTest01', async () => { + (self as unknown as Worker).postMessage = jest.fn(() => true); + expect(threadDataReceiver(data, () => { + return threadData; + })).toBeUndefined(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/ThreadDataSender.test.ts b/ide/test/trace/database/data-trafic/ThreadDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..533a4ba7c2fb2ac9b8389c46fc7817144993983e --- /dev/null +++ b/ide/test/trace/database/data-trafic/ThreadDataSender.test.ts @@ -0,0 +1,47 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { threadDataSender } from '../../../../src/trace/database/data-trafic/ThreadDataSender'; +import { ThreadStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerThread'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('ThreadDataSender Test', () => { + let threadData = [{ + argSetID: -1, + cpu: 2, + dur: 496000, + frame: {y: 5, height: 20, x: 369, width: 1}, + id: 23, + pid: 1668, + startTime: 2629548000, + state: "Running", + tid: 1693, + translateY: 650 + }] + it('ThreadDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(threadData, threadData.length, true); + }); + let threadTraceRow = TraceRow.skeleton(); + threadDataSender(543, 12, threadTraceRow).then(result => { + expect(result).toHaveLength(1); + }); + }); +}); \ No newline at end of file diff --git a/trace_streamer/src/table/ebpf/ebpf_elf_table.h b/ide/test/trace/database/data-trafic/VirtualMemoryDataReceiver.test.ts similarity index 33% rename from trace_streamer/src/table/ebpf/ebpf_elf_table.h rename to ide/test/trace/database/data-trafic/VirtualMemoryDataReceiver.test.ts index 4158411af35ef6dbe620e6d99cbb7edb00e6dfad..d23f5c1845b022e1968fee9ce8fb0abe63fd284e 100644 --- a/trace_streamer/src/table/ebpf/ebpf_elf_table.h +++ b/ide/test/trace/database/data-trafic/VirtualMemoryDataReceiver.test.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -12,41 +12,47 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef EBPF_ELF_TABLE_H -#define EBPF_ELF_TABLE_H -#include "table_base.h" -#include "trace_stdtype.h" +import { virtualMemoryDataReceiver } from '../../../../src/trace/database/data-trafic/VirtualMemoryDataReceiver'; -namespace SysTuning { -namespace TraceStreamer { -class EbpfElfTable : public TableBase { -public: - explicit EbpfElfTable(const TraceDataCache* dataCache); - ~EbpfElfTable() override; - std::unique_ptr CreateCursor() override; +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); -private: - int64_t GetSize() override - { - return dataCache_->GetConstEbpfElf().Size(); - } - void GetOrbyes(FilterConstraints& elffc, EstimatedIndexInfo& elfei) override; - void FilterByConstraint(FilterConstraints& elffc, - double& elffilterCost, - size_t elfrowCount, - uint32_t elfcurrenti) override; - - class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache* dataCache, TableBase* table); - ~Cursor() override; - int32_t Column(int32_t column) const override; +describe('VirtualMemoryDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "30", + name: 12, + params: + { + endNS: 109726762483, + filterId: 6347, + recordEndNS: 490640100187894, + recordStartNS: 490530373425411, + sharedArrayBuffers: undefined, + startNS: 0, + t: 1703643817436, + trafic: 3, + width: 1407 + } + } - private: - const EbpfElf& ebpfElfObj_; - }; -}; -} // namespace TraceStreamer -} // namespace SysTuning -#endif // EBPF_ELF_TABLE_H + let vmData = [{ + virtualMemData: { + delta: -1, + duration: 252, + filterId: 6347, + maxValue: -1, + startTime: 19680640101, + value: 423440 + } + }] + it('VirtualMemoryReceiverTest01', async () => { + const mockCallback = jest.fn(() => vmData); + const mockPostMessage = jest.fn(); + (self as unknown as Worker).postMessage = mockPostMessage; + virtualMemoryDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/VirtualMemoryDataSender.test.ts b/ide/test/trace/database/data-trafic/VirtualMemoryDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3545f25fff08f39864a8258bdf91e9cbead02965 --- /dev/null +++ b/ide/test/trace/database/data-trafic/VirtualMemoryDataSender.test.ts @@ -0,0 +1,45 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { virtualMemoryDataSender } from '../../../../src/trace/database/data-trafic/VirtualMemoryDataSender'; +import { VirtualMemoryStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerVirtualMemory'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('VirtualMemoryDataSender Test', () => { + let resultVm = [{ + delta: -9, + duration: 4830101562, + filterID: 202, + frame: {x: 190, y: 5, width: 62, height: 30}, + maxValue: 144753, + startTime: 14850538539, + value: 124362 + }] + it('VirtualMemorySenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(resultVm, resultVm.length, true); + }); + let virtualMemoryTraceRow = TraceRow.skeleton(); + virtualMemoryDataSender(6346, virtualMemoryTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/VmTrackerDataReceiver.test.ts b/ide/test/trace/database/data-trafic/VmTrackerDataReceiver.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..69e533c02fa5f8dca267290715f2d3f21aad1a2b --- /dev/null +++ b/ide/test/trace/database/data-trafic/VmTrackerDataReceiver.test.ts @@ -0,0 +1,136 @@ +/* + * 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 { + abilityDmaDataReceiver, abilityGpuMemoryDataReceiver, + abilityPurgeableDataReceiver, + dmaDataReceiver, + gpuDataReceiver, + gpuMemoryDataReceiver, + gpuResourceDataReceiver, + gpuTotalDataReceiver, + gpuWindowDataReceiver, + purgeableDataReceiver, + shmDataReceiver, + sMapsDataReceiver +} from "../../../../src/trace/database/data-trafic/VmTrackerDataReceiver"; + +describe('VmTrackerDataReceiver Test', () => { + let data = { + action: "exec-proto", + id: "6", + name: 82, + params: { + endNs: 109726762483, + ipid: 1, + recordEndNS: 490640100187894, + recordStartNS: 490530373425411, + sharedArrayBuffers: undefined, + startNs: 0, + trafic: 3, + width: 1424 + } + }; + let res = [{ + trackerData: { + startNs: 4762581249, + value: 108232704 + } + }] + it('VmTrackerDataReceiverTest01', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + sMapsDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest02', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + dmaDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest03', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + gpuMemoryDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest04', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + gpuDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest05', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + gpuResourceDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest06', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + gpuTotalDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest07', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + gpuWindowDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest08', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + shmDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest09', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + purgeableDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest10', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + abilityPurgeableDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest11', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + abilityDmaDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); + + it('VmTrackerDataReceiverTest12', function () { + const mockCallback = jest.fn(() => res); + (self as unknown as Worker).postMessage = jest.fn(); + abilityGpuMemoryDataReceiver(data, mockCallback); + expect(mockCallback).toHaveBeenCalled(); + }); +}); \ No newline at end of file diff --git a/ide/test/trace/database/data-trafic/VmTrackerDataSender.test.ts b/ide/test/trace/database/data-trafic/VmTrackerDataSender.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9123ed13f4bbacb9c720f0cde8d7c355f02f1936 --- /dev/null +++ b/ide/test/trace/database/data-trafic/VmTrackerDataSender.test.ts @@ -0,0 +1,179 @@ +/* + * 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 '../../../../src/trace/component/trace/base/TraceRow'; +import { threadPool } from '../../../../src/trace/database/SqlLite'; +import { + abilityDmaDataSender, + abilityGpuMemoryDataSender, + abilityPurgeableDataSender, + dmaDataSender, + gpuGpuDataSender, + gpuMemoryDataSender, + gpuResourceDataSender, + gpuTotalDataSender, + gpuWindowDataSender, + purgeableDataSender, + shmDataSender, + sMapsDataSender +} from '../../../../src/trace/database/data-trafic/VmTrackerDataSender'; +import { SnapshotStruct } from '../../../../src/trace/database/ui-worker/ProcedureWorkerSnapshot'; + +jest.mock('../../../../src/trace/database/ui-worker/ProcedureWorker', () => { + return {}; +}); + +describe('VmTrackerDataSender Test', () => { + let data = [{ + dur: 1000000000, + endNs: 5762581249, + frame: {x: 61, y: 3, width: 13, height: 33}, + name: "SnapShot 1", + startNs: 4762581249, + textWidth: 54.6826171875, + value: 213135360 + }] + it('VmTrackerDataSenderTest01', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let sMapsTraceRow = TraceRow.skeleton(); + sMapsDataSender('dirty', sMapsTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest02', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let dmaTraceRow = TraceRow.skeleton(); + dmaDataSender(1, dmaTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest03', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let gpuMemoryTraceRow = TraceRow.skeleton(); + gpuMemoryDataSender(1, gpuMemoryTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest04', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let gpuResourceTraceRow = TraceRow.skeleton(); + gpuResourceDataSender(13, gpuResourceTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest05', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let gpuGpuTraceRow = TraceRow.skeleton(); + gpuGpuDataSender(13, "'mem.graph_pss'", gpuGpuTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest06', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let gpuTotalTraceRow = TraceRow.skeleton(); + gpuTotalDataSender(13, gpuTotalTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest07', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let gpuWindowTraceRow = TraceRow.skeleton(); + gpuWindowDataSender(13, 15, gpuWindowTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest08', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let shmTraceRow = TraceRow.skeleton(); + shmDataSender(13, shmTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest09', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let purgeableTraceRow = TraceRow.skeleton(); + purgeableDataSender(13, purgeableTraceRow).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest10', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let abilityPurgeablTraceRow = TraceRow.skeleton(); + abilityPurgeableDataSender(abilityPurgeablTraceRow, 1000000000, false).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest11', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let abilityDmaTraceRow = TraceRow.skeleton(); + abilityDmaDataSender(abilityDmaTraceRow, 1000000000).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); + + it('VmTrackerDataSenderTest12', () => { + threadPool.submitProto = jest.fn((query: number, params: any, callback: Function) => { + callback(data, data.length, true); + }); + let abilityGpuMemoryTraceRow = TraceRow.skeleton(); + abilityGpuMemoryDataSender(abilityGpuMemoryTraceRow, 1000000000).then(result => { + expect(result).toHaveLength(1); + expect(threadPool.submitProto).toHaveBeenCalled(); + }); + }); +}); \ No newline at end of file diff --git a/trace_streamer/BUILD.gn b/trace_streamer/BUILD.gn index 58094a4215e4dc8c22e1882a3c9e573b11d4424c..9cc95acb4ec12fe96139b052784335e69e2f5484 100644 --- a/trace_streamer/BUILD.gn +++ b/trace_streamer/BUILD.gn @@ -26,8 +26,6 @@ group("trace_streamer") { ] } else if (is_sdkdemo) { deps = [ "sdk/demo_sdk:trace_streamer_sdk_builtin" ] - } else if (is_dubai_sdk) { - deps = [ "sdk/dubai_sdk:trace_streamer_dubai_builtin" ] } else if (is_sdkdemo_test) { deps = [ "sdk/test:sdkunittest" ] } else if (use_wasm) { diff --git a/trace_streamer/build.sh b/trace_streamer/build.sh index b4af8bb1590ca68df534db1b6b1102b4fd5a1d13..d7b09fc6b6aaea06f96b17c35f898e9ab168baa1 100755 --- a/trace_streamer/build.sh +++ b/trace_streamer/build.sh @@ -38,7 +38,7 @@ usage="Usage: $basename $0 wasm/test/fuzz/protoc debug/release/clean" ./dl_tools.sh $gn_path -if { [ "$1" == "dubaisdk" ] || [ "$1" == "sdkdemo" ] || [ "$1" == "wasm" ] || [ "$1" == "test" ] || [ "$1" == "fuzz" ]; } && [ "$#" -ne 0 ];then +if { [ "$1" == "sdkdemo" ] || [ "$1" == "wasm" ] || [ "$1" == "test" ] || [ "$1" == "fuzz" ]; } && [ "$#" -ne 0 ];then TARGET_DIR=$1 if [[ $PARAMS == *"debug"* ]]; then TARGET_DIR=$1"_debug" @@ -85,9 +85,6 @@ if [ "$#" -ne "0" ];then if [ "$1" == "sdkdemo" ];then target="sdkdemo" fi - if [ "$1" == "dubaisdk" ];then - target="dubaisdk" - fi if [ "$1" == "sdkdemotest" ];then target="sdkdemotest" fi diff --git a/trace_streamer/build/ts.gni b/trace_streamer/build/ts.gni index 4332548dfe8702662a6b40f8bc7fc1368ad84dd0..4cfb52563e69674108301ae39c999088a6f9922f 100644 --- a/trace_streamer/build/ts.gni +++ b/trace_streamer/build/ts.gni @@ -26,13 +26,11 @@ if (is_independent_compile) { COMMON_LIBRARY = "//third_party/commonlibrary" } else { PERF_DIR = "//developtools" - with_ebpf_help_table = false clang_x64_folder = "clang_x64" is_test = false is_protoc = false is_spb = false is_sdkdemo = false - is_dubai_sdk = false is_sdkdemo_test = false use_wasm = false enable_ts_utest = false diff --git a/trace_streamer/build_operator.sh b/trace_streamer/build_operator.sh index 2768035019fde1e4df64bdcc5394d93076490d32..1745fa6b01a3f246ee753efc10199ea245b750a8 100755 --- a/trace_streamer/build_operator.sh +++ b/trace_streamer/build_operator.sh @@ -26,7 +26,7 @@ if [ "$#" -ge "7" ];then if [ "$target" != "trace" ] && [ "$target" != "linux" ] && [ "$target" != "windows" ] && [ "$target" != "macx" ] && [ "$target" != "trace_streamer" ] && [ "$target" != "wasm" ] && [ "$target" != "test" ] && [ "$target" != "spb" ] && [ "$target" != "fuzz" ] && - [ "$target" != "protoc" ] && [ "$target" != "sdkdemo" ] && [ "$target" != "dubaisdk" ] && [ "$target" != "sdkdemotest" ];then + [ "$target" != "protoc" ] && [ "$target" != "sdkdemo" ] && [ "$target" != "sdkdemotest" ];then echo "failed" exit fi diff --git a/trace_streamer/doc/cloc.md b/trace_streamer/doc/cloc.md index d26aedcf3469397652a4d0d570f2e08b77d939de..28443c92b07eec3698f59f1867e1e4d34ca1e965 100644 --- a/trace_streamer/doc/cloc.md +++ b/trace_streamer/doc/cloc.md @@ -1,5 +1,5 @@ # 关于本目录下自研代码统计 可以使用下面的命令命令统计本目录下的代码。 ``` -cloc . --exclude-dir=protos,dubai_sdk,third_party,emsdk,prebuilts,out,tmp +cloc . --exclude-dir=protos,third_party,emsdk,prebuilts,out,tmp ``` \ No newline at end of file diff --git a/trace_streamer/gn/BUILD.gn b/trace_streamer/gn/BUILD.gn index 24ea372364b767793426f548ee3382a081368fb4..28ba290908fa2137f19aaa7ebc18b839727d0a60 100644 --- a/trace_streamer/gn/BUILD.gn +++ b/trace_streamer/gn/BUILD.gn @@ -140,9 +140,6 @@ config("default") { if (is_linux) { cflags += [ "-D is_linux" ] } - if (with_ebpf_help_table) { - cflags += [ "-D WITH_EBPF_HELP" ] - } } config("symbols") { diff --git a/trace_streamer/gn/CONFIG.gn b/trace_streamer/gn/CONFIG.gn index 5360d850653dafebbe61527ca258b696a63e7eb4..a81681b65aece8381b796e4637ebc526436523b1 100644 --- a/trace_streamer/gn/CONFIG.gn +++ b/trace_streamer/gn/CONFIG.gn @@ -14,11 +14,9 @@ is_win = false is_linux = false is_mac = false is_protoc = false -with_ebpf_help_table = false is_mingw = false with_libunwind = false is_sdkdemo = false -is_dubai_sdk = false is_sdkdemo_test = false is_spb = false target_cpu = "x64" @@ -29,7 +27,6 @@ declare_args() { wasm_use_thread = false is_test = false is_sdkdemo = false - is_dubai_sdk = false is_sdkdemo_test = false testonly = false is_fuzz = false @@ -62,9 +59,6 @@ if (target == "wasm") { } else if (target == "sdkdemo") { is_sdkdemo = true use_wasm = true -} else if (target == "dubaisdk") { - is_dubai_sdk = true - use_wasm = true } else if (target == "sdkdemotest") { is_sdkdemo_test = true testonly = true @@ -100,9 +94,6 @@ if (!is_debug) { hiperf_default_configs -= [ "//gn:symbols" ] hiperf_default_configs += [ "//gn:release" ] } -if (is_debug) { - with_ebpf_help_table = true -} set_defaults("ohos_source_set") { configs = default_configs diff --git a/trace_streamer/gn/wasm.gni b/trace_streamer/gn/wasm.gni index ebab4ca133c90c5d59665c3cdc28bfa067907691..e181f0f569097abd9e23e58c6c813a06af2d3f67 100644 --- a/trace_streamer/gn/wasm.gni +++ b/trace_streamer/gn/wasm.gni @@ -47,6 +47,8 @@ template("wasm_lib") { "-s", "USE_ZLIB=1", "-lworkerfs.js", # For FS.filesystems.WORKERFS + "-s", + "ASSERTIONS=1", ] if (wasm_use_thread) { _target_ldflags += [ diff --git a/trace_streamer/prebuilts/patch_hiperf/unique_fd.h b/trace_streamer/prebuilts/patch_hiperf/unique_fd.h index 36ca3046e06ada2ae5399903ee0bb05372d63f1b..f6210a31c0cc60afe5d71074d004b8da97710b68 100644 --- a/trace_streamer/prebuilts/patch_hiperf/unique_fd.h +++ b/trace_streamer/prebuilts/patch_hiperf/unique_fd.h @@ -46,7 +46,6 @@ bool operator<(const int& lhs, const UniqueFdAddDeletor& rhs); template class UniqueFdAddDeletor final { - friend bool operator==(const int& lhs, const UniqueFdAddDeletor& rhs); friend bool operator!=(const int& lhs, const UniqueFdAddDeletor& rhs); diff --git a/trace_streamer/sdk/demo_sdk/BUILD.gn b/trace_streamer/sdk/demo_sdk/BUILD.gn index 200454d52aba606b41336d2f471128e6a7a9260e..4fb1796825fcc8fe4780d2821ceaad21e55fcbb5 100644 --- a/trace_streamer/sdk/demo_sdk/BUILD.gn +++ b/trace_streamer/sdk/demo_sdk/BUILD.gn @@ -57,19 +57,18 @@ ohos_source_set("trace_streamer_sdk") { subsystem_name = "trace_streamer" part_name = "trace_streamer_sdk" sources = [ - "rpc/http_socket.cpp", "rpc/rpc_server.cpp", "rpc/rpc_server.h", "sdk/sdk_data_parser.cpp", "sdk/sdk_data_parser.h", "sdk/ts_sdk_api.cpp", "sdk/ts_sdk_api.h", + "table/demo_meta_table.cpp", + "table/demo_meta_table.h", "table/gpu_counter_object_table.cpp", "table/gpu_counter_object_table.h", "table/gpu_counter_table.cpp", "table/gpu_counter_table.h", - "table/meta_table.cpp", - "table/meta_table.h", "table/slice_object_table.cpp", "table/slice_object_table.h", "table/slice_table.cpp", @@ -106,6 +105,7 @@ ohos_source_set("trace_streamer_sdk") { "${THIRD_PARTY}/sqlite/include", "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/json/single_include/nlohmann", + "${THIRD_PARTY}/bounds_checking_function/include", ] if (!use_wasm) { include_dirs += [ diff --git a/trace_streamer/sdk/demo_sdk/rpc/http_server.cpp b/trace_streamer/sdk/demo_sdk/rpc/http_server.cpp deleted file mode 100644 index 3694e873cd4c05df28616d6fe890980c598417f1..0000000000000000000000000000000000000000 --- a/trace_streamer/sdk/demo_sdk/rpc/http_server.cpp +++ /dev/null @@ -1,387 +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. - */ - -#include "http_server.h" -#include -#include -#include -#include -#ifdef _WIN32 -#include -#else -#include -#include -#endif -#include "log.h" -#include "string_to_numerical.h" -namespace SysTuning { -namespace TraceStreamer { -void HttpServer::RegisterRpcFunction(RpcServer* rpc) -{ - rpcFunctions_.clear(); - - using std::placeholders::_1; - using std::placeholders::_2; - using std::placeholders::_3; - - auto parsedata = std::bind(&RpcServer::ParseData, rpc, _1, _2, _3); - rpcFunctions_["/parsedata"] = parsedata; - - auto parsedataover = std::bind(&RpcServer::ParseDataOver, rpc, _1, _2, _3); - rpcFunctions_["/parsedataover"] = parsedataover; - - auto sqlquery = std::bind(&RpcServer::SqlQuery, rpc, _1, _2, _3); - rpcFunctions_["/sqlquery"] = sqlquery; - - auto sqloperate = std::bind(&RpcServer::SqlOperate, rpc, _1, _2, _3); - rpcFunctions_["/sqloperate"] = sqloperate; - - auto reset = std::bind(&RpcServer::Reset, rpc, _1, _2, _3); - rpcFunctions_["/reset"] = reset; -} - -#ifdef _WIN32 -void HttpServer::Run(int32_t port) -{ - WSADATA ws{}; - if (WSAStartup(MAKEWORD(WS_VERSION_FIRST, WS_VERSION_SEC), &ws) != 0) { - return; - } - if (!CreateSocket(port)) { - return; - } - WSAEVENT events[COUNT_SOCKET]; - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - if ((events[i] = WSACreateEvent()) == WSA_INVALID_EVENT) { - TS_LOGE("WSACreateEvent error %d", WSAGetLastError()); - return; - } - WSAEventSelect(sockets_[i].GetFd(), events[i], FD_ACCEPT | FD_CLOSE); - } - - while (!isExit_) { - ClearDeadClientThread(); - - int32_t index = WSAWaitForMultipleEvents(COUNT_SOCKET, events, false, pollTimeOut_, false); - if (index == WSA_WAIT_FAILED) { - TS_LOGE("WSAWaitForMultipleEvents error %d", WSAGetLastError()); - break; - } else if (index == WSA_WAIT_TIMEOUT) { - continue; - } - - index = index - WSA_WAIT_EVENT_0; - WSANETWORKEVENTS event; - WSAEnumNetworkEvents(sockets_[index].GetFd(), events[index], &event); - if (event.lNetworkEvents & FD_ACCEPT) { - if (event.iErrorCode[FD_ACCEPT_BIT] != 0) { - continue; - } - - std::unique_ptr client = std::make_unique(); - if (sockets_[index].Accept(client->sock_)) { - client->thread_ = std::thread(&HttpServer::ProcessClient, this, std::ref(client->sock_)); - clientThreads_.push_back(std::move(client)); - } else { - TS_LOGE("http socket accept error"); - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - } - } - - for (const auto& it : clientThreads_) { - if (it->thread_.joinable()) { - it->sock_.Close(); - it->thread_.join(); - } - } - clientThreads_.clear(); - - WSACleanup(); -} -#else -void HttpServer::Run(int32_t port) -{ - if (SIG_ERR == signal(SIGPIPE, SIG_IGN)) { - return; - } - - if (!CreateSocket(port)) { - return; - } - TS_LOGI("http server running"); - struct pollfd fds[COUNT_SOCKET]; - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - fds[i] = {sockets_[i].GetFd(), POLLIN, 0}; - } - while (!isExit_) { - ClearDeadClientThread(); - if (poll(fds, sizeof(fds) / sizeof(pollfd), pollTimeOut_) <= 0) { - continue; // try again - } - - for (int32_t i = 0; i < 1; i++) { - if (fds[i].revents != POLLIN) { - continue; - } - std::unique_ptr client = std::make_unique(); - if (sockets_[i].Accept(client->sock_)) { - client->thread_ = std::thread(&HttpServer::ProcessClient, this, std::ref(client->sock_)); - clientThreads_.push_back(std::move(client)); - } else { - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - } - } - - for (const auto& it : clientThreads_) { - if (it->thread_.joinable()) { - it->sock_.Close(); - it->thread_.join(); - } - } - clientThreads_.clear(); - - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - sockets_[i].Close(); - } - TS_LOGI("http server exit"); -} -#endif - -void HttpServer::Exit() -{ - isExit_ = true; - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - sockets_[i].Close(); - } -} - -bool HttpServer::CreateSocket(int32_t port) -{ - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - if (!sockets_[i].CreateSocket(i == 0 ? AF_INET : AF_INET6)) { - TS_LOGE("Create http socket error"); - return false; - } - if (!sockets_[i].Bind(port)) { - TS_LOGE("bind http socket error"); - return false; - } - if (!sockets_[i].Listen(SOMAXCONN)) { - TS_LOGE("listen http socket error"); - return false; - } - } - - return true; -} - -void HttpServer::ClearDeadClientThread() -{ - for (auto it = clientThreads_.begin(); it != clientThreads_.end();) { - if (it->get()->sock_.GetFd() != -1) { - it++; - continue; - } - if (it->get()->thread_.joinable()) { - it->get()->thread_.join(); - } - it = clientThreads_.erase(it); - } -} - -#ifdef _WIN32 -void HttpServer::ProcessClient(HttpSocket& client) -{ - std::vector recvBuf(MAXLEN_REQUEST); - size_t recvLen = recvBuf.size(); - size_t recvPos = 0; - RequestST reqST; - WSAEVENT recvEvent = WSACreateEvent(); - if (recvEvent == WSA_INVALID_EVENT) { - TS_LOGE("WSACreateEvent error %d", WSAGetLastError()); - return; - } - WSAEventSelect(client.GetFd(), recvEvent, FD_READ | FD_CLOSE); - while (!isExit_) { - int32_t index = WSAWaitForMultipleEvents(1, &recvEvent, false, pollTimeOut_, false); - if (index == WSA_WAIT_FAILED) { - TS_LOGE("WSAWaitForMultipleEvents error %d", WSAGetLastError()); - break; - } else if (index == WSA_WAIT_TIMEOUT) { - if (reqST.stat != RequstParseStat::INIT) { - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - recvPos = 0; - recvLen = recvBuf.size(); - } - continue; - } - - WSANETWORKEVENTS event; - WSAEnumNetworkEvents(client.GetFd(), recvEvent, &event); - if (event.lNetworkEvents & FD_READ) { - if (event.iErrorCode[FD_READ_BIT] != 0) { - continue; - } - if (!client.Recv(recvBuf.data() + recvPos, recvLen)) { - break; - } - recvPos += recvLen; - ParseRequest(recvBuf.data(), recvPos, reqST); - recvLen = recvBuf.size() - recvPos; - if (reqST.stat == RequstParseStat::RECVING) { - continue; - } - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - } else if (event.lNetworkEvents & FD_CLOSE) { - TS_LOGI("client close socket(%d)", client.GetFd()); - break; - } - } - TS_LOGI("recive client thread exit. socket(%d)", client.GetFd()); - - client.Close(); -} -#else -void HttpServer::ProcessClient(HttpSocket& client) -{ - std::vector recvBuf(MAXLEN_REQUEST); - size_t recvLen = recvBuf.size(); - size_t recvPos = 0; - RequestST reqST; - - struct pollfd fd = {client.GetFd(), POLLIN, 0}; - while (!isExit_) { - int32_t pollRet = poll(&fd, sizeof(fd) / sizeof(pollfd), pollTimeOut_); - if (pollRet < 0) { - TS_LOGE("poll client socket(%d) error: %d:%s", client.GetFd(), errno, strerror(errno)); - break; - } - if (pollRet == 0) { - if (reqST.stat != RequstParseStat::INIT) { - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - recvPos = 0; - recvLen = recvBuf.size(); - } - continue; - } - if (!client.Recv(recvBuf.data() + recvPos, recvLen)) { - TS_LOGI("client exit"); - break; - } - recvPos += recvLen; - ParseRequest(recvBuf.data(), recvPos, reqST); - recvLen = recvBuf.size() - recvPos; - if (reqST.stat == RequstParseStat::RECVING) { - continue; - } - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - } - TS_LOGI("recive client thread exit. socket(%d)", client.GetFd()); - - client.Close(); - TS_LOGI("thread exit"); -} -#endif - -void HttpServer::ProcessRequest(HttpSocket& client, RequestST& request) {} - -void HttpServer::ParseRequest(const uint8_t* requst, size_t& len, RequestST& httpReq) -{ - std::string_view reqStr(reinterpret_cast(requst), len); - size_t bodyPos = reqStr.find("\r\n\r\n"); - if (bodyPos == 0) { - len = 0; - httpReq.stat = RequstParseStat::BAD; - return; - } else if (bodyPos == std::string_view::npos) { - httpReq.stat = RequstParseStat::RECVING; - return; - } - std::string_view header = reqStr.substr(0, bodyPos); - bodyPos += strlen("\r\n\r\n"); - httpReq.bodyLen = reqStr.size() - bodyPos; - - std::vector headerlines = StringSplit(header, "\r\n"); - // at least 1 line in headerlines, such as "GET /parsedata HTTP/1.1" - std::vector requestItems = StringSplit(headerlines[0], " "); - const size_t indexHttpMethod = 0; - const size_t indexHttpUri = 1; - const size_t indexHttpVersion = 2; - const size_t countRequestItems = 3; - if (requestItems.size() != countRequestItems || requestItems[indexHttpVersion] != "HTTP/1.1") { - len = 0; - httpReq.stat = RequstParseStat::BAD; - return; - } - httpReq.method = requestItems[indexHttpMethod]; - httpReq.uri = requestItems[indexHttpUri]; - - for (size_t i = 1; i < headerlines.size(); i++) { - size_t tagPos = headerlines[i].find(":"); - if (tagPos == std::string_view::npos) { - len = 0; - httpReq.stat = RequstParseStat::BAD; - return; - } - std::string_view tag = headerlines[i].substr(0, tagPos); - if (strncasecmp(tag.data(), "Content-Length", tag.size()) == 0) { - std::string value(headerlines[i].data() + tagPos + strlen(":"), - headerlines[i].size() - tagPos - strlen(":")); - size_t conterntLen = atoi(value.c_str()); - if (conterntLen > httpReq.bodyLen) { - httpReq.stat = RequstParseStat::RECVING; - return; - } else if (conterntLen < httpReq.bodyLen) { - httpReq.bodyLen = conterntLen; - } - } - } - - if (httpReq.bodyLen > 0) { - httpReq.body = (requst + bodyPos); - } - httpReq.stat = RequstParseStat::OK; - len -= (bodyPos + httpReq.bodyLen); - return; -} - -std::vector HttpServer::StringSplit(std::string_view source, std::string_view split) -{ - std::vector result; - if (!split.empty()) { - size_t pos = 0; - while ((pos = source.find(split)) != std::string_view::npos) { - // split - std::string_view token = source.substr(0, pos); - if (!token.empty()) { - result.push_back(token); - } - source = source.substr(pos + split.size(), source.size() - token.size() - split.size()); - } - } - // add last token - if (!source.empty()) { - result.push_back(source); - } - return result; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/sdk/demo_sdk/rpc/http_server.h b/trace_streamer/sdk/demo_sdk/rpc/http_server.h deleted file mode 100644 index 6e47a50004186e90f014e7ed2bebdbea862f432f..0000000000000000000000000000000000000000 --- a/trace_streamer/sdk/demo_sdk/rpc/http_server.h +++ /dev/null @@ -1,74 +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. - */ - -#ifndef RPC_HTTPD_H -#define RPC_HTTPD_H - -#include -#include -#include -#include -#include -#include "http_socket.h" -#include "rpc_server.h" -namespace SysTuning { -namespace TraceStreamer { -class HttpServer { -public: - void RegisterRpcFunction(RpcServer* rpc); - void Run(int32_t port = 9001); - void Exit(); - - static constexpr size_t MAXLEN_REQUEST = 2 * 1024 + 1024 * 1024; // header 2K + body 1M - -private: - struct ClientThread { - HttpSocket sock_; - std::thread thread_; - }; - - enum RequstParseStat { INIT = 0, OK, BAD, RECVING }; - - struct RequestST { - int32_t stat = RequstParseStat::INIT; - std::string method; - std::string uri; - const uint8_t* body; - size_t bodyLen; - }; - - bool CreateSocket(int32_t port); - void ProcessClient(HttpSocket& client); - static void ProcessRequest(HttpSocket& client, RequestST& request); - static void ParseRequest(const uint8_t* requst, size_t& len, RequestST& httpReq); - void ClearDeadClientThread(); - static std::vector StringSplit(std::string_view source, std::string_view split); - - static const int32_t COUNT_SOCKET = 1; - HttpSocket sockets_[COUNT_SOCKET]; // ipv4 and ipv6 - std::atomic_bool isExit_ = {false}; - std::vector> clientThreads_; - using RpcFunction = std::function; - std::map rpcFunctions_; - const int32_t pollTimeOut_ = 1000; -#ifdef _WIN32 - const uint32_t WS_VERSION_FIRST = 2; - const uint32_t WS_VERSION_SEC = 2; -#endif -}; -} // namespace TraceStreamer -} // namespace SysTuning - -#endif // RPC_HTTPD_H diff --git a/trace_streamer/sdk/demo_sdk/rpc/http_socket.cpp b/trace_streamer/sdk/demo_sdk/rpc/http_socket.cpp deleted file mode 100644 index 51c327ddbea5dbcf2179ee9063ba258c9296eb38..0000000000000000000000000000000000000000 --- a/trace_streamer/sdk/demo_sdk/rpc/http_socket.cpp +++ /dev/null @@ -1,173 +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. - */ - -#include "http_socket.h" -#include -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#endif -#include "log.h" -namespace SysTuning { -namespace TraceStreamer { -HttpSocket::~HttpSocket() -{ - Close(); -} -bool HttpSocket::CreateSocket(int32_t domain) -{ - SOCKET sockId = socket(domain, SOCK_STREAM, 0); - if (sockId == INVALID_SOCKET) { - TS_LOGE("CreateSocket socket error, domain %d: %d:%s", domain, errno, strerror(errno)); - return false; - } - sockId_ = sockId; - if (domain == AF_INET || domain == AF_INET6) { - int32_t enable = 1; - if (setsockopt(sockId, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&enable), sizeof(enable)) == - SOCKET_ERROR) { - Close(); - return false; - } - if (domain == AF_INET6) { - if (setsockopt(sockId, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&enable), sizeof(enable)) == - SOCKET_ERROR) { - Close(); - return false; - } - } - } - domain_ = domain; - TS_LOGI("CreateSocket socket ok, socket %d domain %d", sockId_, domain); - return true; -} - -bool HttpSocket::Bind(int32_t port) -{ - if (sockId_ == INVALID_SOCKET) { - TS_LOGE("the socket not created"); - return false; - } - - if (domain_ == AF_INET) { - struct sockaddr_in addr; - std::fill(reinterpret_cast(&addr), reinterpret_cast(&addr) + sizeof(addr), 0); - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htons(INADDR_ANY); - addr.sin_port = htons(static_cast(port)); - if (bind(sockId_, reinterpret_cast(&addr), sizeof(addr)) == -1) { - TS_LOGE("bind ipv4 socket error, port %d: %d:%s", port, errno, strerror(errno)); - return false; - } - } else if (domain_ == AF_INET6) { - struct sockaddr_in6 addr; - std::fill(reinterpret_cast(&addr), reinterpret_cast(&addr) + sizeof(addr), 0); - addr.sin6_family = AF_INET6; - addr.sin6_addr = in6addr_any; - addr.sin6_port = htons(static_cast(port)); - if (bind(sockId_, reinterpret_cast(&addr), sizeof(addr)) == -1) { - TS_LOGE("bind ipv6 socket error, port %d: %d:%s", port, errno, strerror(errno)); - return false; - } - } else { - return false; - } - TS_LOGI("bind socket ok, port %d", port); - return true; -} - -bool HttpSocket::Listen(int32_t maxConn) -{ - if (listen(sockId_, maxConn) == SOCKET_ERROR) { - TS_LOGE("listen socket error: %d:%s", errno, strerror(errno)); - return false; - } - TS_LOGI("listen socket ok, maxConn %d", maxConn); - return true; -} - -bool HttpSocket::Accept(HttpSocket& client) -{ - int32_t clientId = accept(sockId_, nullptr, nullptr); - if (clientId == INVALID_SOCKET) { - TS_LOGE("accept socket error: %d:%s", errno, strerror(errno)); - return false; - } - - client.domain_ = domain_; - client.sockId_ = clientId; - TS_LOGI("accept client socket id %d domain %d", clientId, domain_); - return true; -} - -bool HttpSocket::Recv(void* data, size_t& len) -{ -#ifdef _WIN32 - ssize_t recvLen = recv(sockId_, static_cast(data), len, 0); -#else - ssize_t recvLen = recv(sockId_, data, len, 0); -#endif - if (recvLen == SOCKET_ERROR) { - if (errno == EAGAIN) { - recvLen = 0; - } else { - TS_LOGE("recv from socket(%d) error: %d:%s", sockId_, errno, strerror(errno)); - return false; - } - } else if (recvLen == 0) { - TS_LOGI("client socket(%d) closed", sockId_); - return false; - } - len = recvLen; - TS_LOGD("Recv from socket(%d) len %zu", sockId_, len); - return true; -} - -bool HttpSocket::Send(const void* data, size_t len) -{ -#ifdef _WIN32 - ssize_t sendLen = send(sockId_, static_cast(data), len, 0); -#else - ssize_t sendLen = send(sockId_, data, len, 0); -#endif - if (sendLen == SOCKET_ERROR) { - TS_LOGE("send to socket(%d) error: %d:%s", sockId_, errno, strerror(errno)); - return false; - } - TS_LOGI("send to socket(%d) len %zu", sockId_, len); - return true; -} - -void HttpSocket::Close() -{ - if (sockId_ == INVALID_SOCKET) { - return; - } - TS_LOGI("close socket(%d)", sockId_); -#ifdef _WIN32 - if (closesocket(sockId_) == SOCKET_ERROR) { -#else - if (close(sockId_) == SOCKET_ERROR) { -#endif - TS_LOGE("close socket(%d) error: %d:%s", sockId_, errno, strerror(errno)); - } - sockId_ = INVALID_SOCKET; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/sdk/demo_sdk/sdk/sdk_data_parser.h b/trace_streamer/sdk/demo_sdk/sdk/sdk_data_parser.h index 5994ecaae140da02061e2f482c29fce31318092f..a47879ae0ac60169b47fd21788fdf9caaf959cd8 100644 --- a/trace_streamer/sdk/demo_sdk/sdk/sdk_data_parser.h +++ b/trace_streamer/sdk/demo_sdk/sdk/sdk_data_parser.h @@ -34,7 +34,7 @@ class SDKDataParser : public HtracePluginTimeParser { public: using TraceRangeCallbackFunction = std::function; using QueryResultCallbackFunction = std::function; - SDKDataParser(TraceDataCache* dataCache); + explicit SDKDataParser(TraceDataCache* dataCache); ~SDKDataParser(){}; // third_party diff --git a/trace_streamer/sdk/demo_sdk/table/meta_table.cpp b/trace_streamer/sdk/demo_sdk/table/demo_meta_table.cpp similarity index 82% rename from trace_streamer/sdk/demo_sdk/table/meta_table.cpp rename to trace_streamer/sdk/demo_sdk/table/demo_meta_table.cpp index 91652d41b1a830c21e8db13a2c07492ae136fc7c..a36b5cb2f7e0730a9a27d1e324ab3dd8df4ea9bc 100644 --- a/trace_streamer/sdk/demo_sdk/table/meta_table.cpp +++ b/trace_streamer/sdk/demo_sdk/table/demo_meta_table.cpp @@ -19,28 +19,28 @@ namespace SysTuning { namespace TraceStreamer { enum class Index : int32_t { NAMEINDEX = 0, VALUE }; -MetaTable::MetaTable(const TraceDataCache* dataCache) : TableBase(dataCache) +DemoMetaTable::DemoMetaTable(const TraceDataCache* dataCache) : TableBase(dataCache) { tableColumn_.push_back(TableBase::ColumnInfo("name", "TEXT")); tableColumn_.push_back(TableBase::ColumnInfo("value", "TEXT")); tablePriKey_.push_back("name"); } -MetaTable::~MetaTable() {} +DemoMetaTable::~DemoMetaTable() {} -std::unique_ptr MetaTable::CreateCursor() +std::unique_ptr DemoMetaTable::CreateCursor() { return std::make_unique(dataCache_, this); } -MetaTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) +DemoMetaTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) : TableBase::Cursor(dataCache, table, MetaDataItem::METADATA_ITEM_MAX) { } -MetaTable::Cursor::~Cursor() {} +DemoMetaTable::Cursor::~Cursor() {} -int32_t MetaTable::Cursor::Column(int32_t column) const +int32_t DemoMetaTable::Cursor::Column(int32_t column) const { switch (static_cast(column)) { case Index::NAMEINDEX: diff --git a/trace_streamer/src/table/base/meta_table.h b/trace_streamer/sdk/demo_sdk/table/demo_meta_table.h similarity index 83% rename from trace_streamer/src/table/base/meta_table.h rename to trace_streamer/sdk/demo_sdk/table/demo_meta_table.h index 91484d952ebca863d1ece01ea321f3b118cc5def..7647a4a18d70c5949aa1bfc01725e2ad3dc48ace 100644 --- a/trace_streamer/src/table/base/meta_table.h +++ b/trace_streamer/sdk/demo_sdk/table/demo_meta_table.h @@ -13,18 +13,18 @@ * limitations under the License. */ -#ifndef META_TABLE_H -#define META_TABLE_H +#ifndef DEMO_META_TABLE_H +#define DEMO_META_TABLE_H #include "table_base.h" #include "trace_data_cache.h" namespace SysTuning { namespace TraceStreamer { -class MetaTable : public TableBase { +class DemoMetaTable : public TableBase { public: - explicit MetaTable(const TraceDataCache* dataCache); - ~MetaTable() override; + explicit DemoMetaTable(const TraceDataCache* dataCache); + ~DemoMetaTable() override; std::unique_ptr CreateCursor() override; private: @@ -37,4 +37,4 @@ private: }; } // namespace TraceStreamer } // namespace SysTuning -#endif // META_TABLE_H +#endif // DEMO_META_TABLE_H diff --git a/trace_streamer/sdk/demo_sdk/table/table_base.cpp b/trace_streamer/sdk/demo_sdk/table/table_base.cpp index f7e9832a18a7d0738aa6d969a523a0ccecce2778..95ee289f54a6380ced777bdf897dc9450286fd80 100644 --- a/trace_streamer/sdk/demo_sdk/table/table_base.cpp +++ b/trace_streamer/sdk/demo_sdk/table/table_base.cpp @@ -20,11 +20,6 @@ #include "log.h" -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) - namespace SysTuning { namespace TraceStreamer { struct TableContext { @@ -51,9 +46,9 @@ void TableBase::TableRegister(sqlite3& db, TraceDataCache* cache, const std::str auto createFn = [](sqlite3* xdb, void* pAux, int32_t argc, const char* const* argv, sqlite3_vtab** ppVTab, char** pzErr) { - UNUSED(argc); - UNUSED(argv); - UNUSED(pzErr); + Unused(argc); + Unused(argv); + Unused(pzErr); auto xdesc = static_cast(pAux); auto table = xdesc->tmplate(xdesc->dataCache); table->name_ = xdesc->tableName; diff --git a/trace_streamer/sdk/demo_sdk/table/table_base.h b/trace_streamer/sdk/demo_sdk/table/table_base.h index 532bcf26d7b722b8e699a28a0d89482e157c1d38..c5be2b37eec0fdb579c58839ddbea7b4209b0eb2 100644 --- a/trace_streamer/sdk/demo_sdk/table/table_base.h +++ b/trace_streamer/sdk/demo_sdk/table/table_base.h @@ -26,10 +26,6 @@ #include "sqlite3.h" #include "trace_data_cache.h" -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) namespace SysTuning { namespace TraceStreamer { class TableBase; @@ -79,8 +75,8 @@ public: virtual int32_t RowId(sqlite3_int64* id); virtual int32_t Filter(const FilterConstraints& fc, sqlite3_value** argv) { - UNUSED(fc); - UNUSED(argv); + Unused(fc); + Unused(argv); return 0; } virtual int32_t Column(int32_t n) const = 0; @@ -120,8 +116,8 @@ protected: // needs to correspond to Cursor::Filter() virtual void EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei) { - UNUSED(fc); - UNUSED(ei); + Unused(fc); + Unused(ei); } virtual std::unique_ptr CreateCursor() = 0; int32_t Open(sqlite3_vtab_cursor** ppCursor); diff --git a/trace_streamer/src/BUILD.gn b/trace_streamer/src/BUILD.gn index 2ea4d50ed2e72f695bd1451d30822a8d50dc0657..a2338a1ec2a2690bf674341c4d8ed9be06ad7e4a 100644 --- a/trace_streamer/src/BUILD.gn +++ b/trace_streamer/src/BUILD.gn @@ -99,8 +99,6 @@ ohos_source_set("trace_streamer_source") { sources = [ "cfg/trace_streamer_config.cpp", "rpc/ffrt_converter.cpp", - "rpc/http_server.cpp", - "rpc/http_socket.cpp", "rpc/rpc_server.cpp", "trace_streamer/trace_streamer_filters.cpp", "trace_streamer/trace_streamer_selector.cpp", @@ -126,6 +124,16 @@ ohos_source_set("trace_streamer_source") { "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/nonlinux", "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/innerkits/unwinder/include", ] + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (use_wasm) { include_dirs += [ "../prebuilts/emsdk/emsdk/emscripten/cache/sysroot/include" ] diff --git a/trace_streamer/src/base/index_map.cpp b/trace_streamer/src/base/index_map.cpp index eabc4ed296858b69202d0d3ca794f421f0b41a38..a41305c2bb96fa9e0a5a08a786c30cd4051e2f45 100644 --- a/trace_streamer/src/base/index_map.cpp +++ b/trace_streamer/src/base/index_map.cpp @@ -44,9 +44,9 @@ void IndexMap::CovertToIndexMap() void IndexMap::Print() { for (auto itor = rowIndex_.begin(); itor != rowIndex_.end(); itor++) { - fprintf(stdout, "%d,", *itor); + (void)fprintf(stdout, "%d,", *itor); } - fflush(stdout); + (void)fflush(stdout); } void IndexMap::Sort() {} diff --git a/trace_streamer/src/base/log.cpp b/trace_streamer/src/base/log.cpp index 9869d003be16916f87eb67699d09e5e92637842a..25caca60a5853aa53acaf8f198b5570c39ccd5a3 100644 --- a/trace_streamer/src/base/log.cpp +++ b/trace_streamer/src/base/log.cpp @@ -17,7 +17,7 @@ bool g_cleanMode = false; enum LogLevel g_curLogLevel = LOG_ERROR; -bool SetLogLevel(std::string level) +bool SetLogLevel(const std::string& level) { if (level == "D" || level == "DEBUG") { g_curLogLevel = LOG_DEBUG; diff --git a/trace_streamer/src/base/log.h b/trace_streamer/src/base/log.h index 5912131b4c1d0d43f5020a149ef6a7f1b973fe34..11bfcb6b7c59fb5ea9afeca5ab9cb4b9ec71202f 100644 --- a/trace_streamer/src/base/log.h +++ b/trace_streamer/src/base/log.h @@ -29,7 +29,7 @@ } while (0) enum LogLevel { LOG_DEBUG = 0, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL, LOG_OFF }; extern enum LogLevel g_curLogLevel; -bool SetLogLevel(std::string level); +bool SetLogLevel(const std::string& level); #define LOGWITHLEVEL(level, motify, fmt, ...) \ do { \ if (level >= g_curLogLevel) { \ diff --git a/trace_streamer/src/base/sqlite_ext/sqlite_ext_funcs.cpp b/trace_streamer/src/base/sqlite_ext/sqlite_ext_funcs.cpp index 2f125f13706d19604521ecfc48d327674ea2f3f3..9aedc509420349cdc04b9dc88db7963e23b9ac88 100644 --- a/trace_streamer/src/base/sqlite_ext/sqlite_ext_funcs.cpp +++ b/trace_streamer/src/base/sqlite_ext/sqlite_ext_funcs.cpp @@ -146,6 +146,8 @@ TSSqlValue SqliteValueToTSSqlValue(sqlite3_value* value) sqlValue.bytesValue = sqlite3_value_blob(value); sqlValue.bytesCount = static_cast(sqlite3_value_bytes(value)); break; + default: + TS_LOGE("type is not in scope"); } return sqlValue; } @@ -236,7 +238,7 @@ void BuildJson(sqlite3_context* ctx, int32_t argc, sqlite3_value** argv) return; } std::unique_ptr data = std::make_unique(raw.size()); - memcpy_s(data.get(), raw.size(), raw.data(), raw.size()); + (void)memcpy_s(data.get(), raw.size(), raw.data(), raw.size()); sqlite3_result_blob(ctx, data.release(), static_cast(raw.size()), free); } @@ -310,7 +312,7 @@ void RepeatedFieldFinal(sqlite3_context* ctx) } std::unique_ptr data = std::make_unique(raw.size()); - memcpy_s(data.get(), raw.size(), raw.data(), raw.size()); + (void)memcpy_s(data.get(), raw.size(), raw.data(), raw.size()); sqlite3_result_blob(ctx, data.release(), static_cast(raw.size()), free); } @@ -332,7 +334,7 @@ void RepeatedJsonFinal(sqlite3_context* ctx) } std::unique_ptr data = std::make_unique(raw.size()); - memcpy_s(data.get(), raw.size(), raw.data(), raw.size()); + (void)memcpy_s(data.get(), raw.size(), raw.data(), raw.size()); sqlite3_result_blob(ctx, data.release(), static_cast(raw.size()), free); } void ts_create_extend_function(sqlite3* db) diff --git a/trace_streamer/src/base/ts_common.h b/trace_streamer/src/base/ts_common.h index 690f5ede6e28a47f104f7b08d0d73d07a4995300..8e3b3a8013a627d7ba376326467b7d862a9d6247 100644 --- a/trace_streamer/src/base/ts_common.h +++ b/trace_streamer/src/base/ts_common.h @@ -240,6 +240,11 @@ public: private: std::atomic_flag valueCAS_{0}; }; +template +void Unused(const T& expr) +{ + static_cast(expr); +} } // namespace TraceStreamer } // namespace SysTuning #endif diff --git a/trace_streamer/src/filter/BUILD.gn b/trace_streamer/src/filter/BUILD.gn index aae32c16a4e56071310f25ac7e5cced7a7998486..994896a21f43e0953d62d3c421a6c15c3fffbc61 100644 --- a/trace_streamer/src/filter/BUILD.gn +++ b/trace_streamer/src/filter/BUILD.gn @@ -52,8 +52,6 @@ ohos_source_set("filter") { "slice_filter.h", "stat_filter.cpp", "stat_filter.h", - "symbols_filter.cpp", - "symbols_filter.h", "system_event_measure_filter.cpp", "system_event_measure_filter.h", "task_pool_filter.cpp", @@ -107,7 +105,16 @@ ohos_source_set("filter") { "../proto_reader/include", ".", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (is_mingw || is_mac) { include_dirs += [ "${THIRD_PARTY}/elfutils/libelf" ] } diff --git a/trace_streamer/src/filter/animation_filter.cpp b/trace_streamer/src/filter/animation_filter.cpp index 3b6e8830487ce0c8aad5896594736a56ffd252a0..fa4cb4826934162c0b4b92a4c0215d83a691f057 100644 --- a/trace_streamer/src/filter/animation_filter.cpp +++ b/trace_streamer/src/filter/animation_filter.cpp @@ -211,13 +211,9 @@ void AnimationFilter::UpdateDynamicFrameInfo() { std::smatch matcheLine; std::regex framePixPattern(R"((\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)\s+Alpha:\s+-*(\d+\.\d+))"); - uint64_t curStackRow; - uint64_t curFrameRow; for (const auto& it : callStackRowMap_) { - curStackRow = it.first; - curFrameRow = it.second; // update dynamicFrame pix, eg:H:RSUniRender::Process:[xxx] (0, 0, 1344, 2772) Alpha: 1.00 - auto nameDataIndex = callStackSlice_->NamesData()[curStackRow]; + auto nameDataIndex = callStackSlice_->NamesData()[it.first]; const std::string& curStackName = traceDataCache_->GetDataFromDict(nameDataIndex); const std::string& funcArgs = curStackName.substr(frameBeginCmd_.size()); if (!std::regex_search(funcArgs, matcheLine, framePixPattern)) { @@ -225,9 +221,9 @@ void AnimationFilter::UpdateDynamicFrameInfo() continue; } dynamicFrame_->UpdatePosition( - curFrameRow, matcheLine, + it.second, matcheLine, traceDataCache_->GetDataIndex((matcheLine[DYNAMICFRAME_MATCH_LAST].str()))); // alpha - UpdateDynamicEndTime(curFrameRow, curStackRow); + UpdateDynamicEndTime(it.second, it.first); } TS_LOGI("UpdateDynamicFrame (%zu) endTime and pos finish", callStackRowMap_.size()); // this can only be cleared by the UpdateDynamicFrameInfo function diff --git a/trace_streamer/src/filter/app_start_filter.cpp b/trace_streamer/src/filter/app_start_filter.cpp index 0d5eb3aa6318757e55d625bb85e9b90208d5d0ed..29bc755adbdc2e75377210b38c28e48e3b5e1864 100644 --- a/trace_streamer/src/filter/app_start_filter.cpp +++ b/trace_streamer/src/filter/app_start_filter.cpp @@ -271,14 +271,14 @@ void APPStartupFilter::ParserSoInitalization() auto it = mMaxTimeAndDepthWithPid.find(pid); if (it == mMaxTimeAndDepthWithPid.end()) { mMaxTimeAndDepthWithPid.insert(std::make_pair(pid, std::map{{endTime, 0}})); - traceDataCache_->GetStaticInitalizationData()->AppendNewData(pid, tid, callId, startTime, endTime, - sliceData.NamesData()[i], depth); + traceDataCache_->GetSoStaticInitalizationData()->AppendNewData(pid, tid, callId, startTime, endTime, + sliceData.NamesData()[i], depth); continue; } else { CalcDepthByTimeStamp(it, depth, endTime, startTime); - traceDataCache_->GetStaticInitalizationData()->AppendNewData(threadData[callId].internalPid_, - threadData[callId].tid_, callId, startTime, - endTime, sliceData.NamesData()[i], depth); + traceDataCache_->GetSoStaticInitalizationData()->AppendNewData( + threadData[callId].internalPid_, threadData[callId].tid_, callId, startTime, endTime, + sliceData.NamesData()[i], depth); } } } diff --git a/trace_streamer/src/filter/args_filter.cpp b/trace_streamer/src/filter/args_filter.cpp index 9cb68bfbf5e752d5ce56d134c646a0e3977839f3..6a45b80612ca26cf3276ce8aa2ba81b0f86a367d 100644 --- a/trace_streamer/src/filter/args_filter.cpp +++ b/trace_streamer/src/filter/args_filter.cpp @@ -22,13 +22,13 @@ namespace SysTuning { namespace TraceStreamer { ArgsFilter::ArgsFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) : FilterBase(dataCache, filter) { - (void)traceDataCache_->GetDataTypeData()->AppendNewDataType(BASE_DATA_TYPE_INT, + (void)traceDataCache_->GetDataTypeData()->UpdateNewDataType(BASE_DATA_TYPE_INT, traceDataCache_->GetDataIndex("int32_t")); - (void)traceDataCache_->GetDataTypeData()->AppendNewDataType(BASE_DATA_TYPE_STRING, + (void)traceDataCache_->GetDataTypeData()->UpdateNewDataType(BASE_DATA_TYPE_STRING, traceDataCache_->GetDataIndex("string")); - (void)traceDataCache_->GetDataTypeData()->AppendNewDataType(BASE_DATA_TYPE_DOUBLE, + (void)traceDataCache_->GetDataTypeData()->UpdateNewDataType(BASE_DATA_TYPE_DOUBLE, traceDataCache_->GetDataIndex("double")); - (void)traceDataCache_->GetDataTypeData()->AppendNewDataType(BASE_DATA_TYPE_BOOLEAN, + (void)traceDataCache_->GetDataTypeData()->UpdateNewDataType(BASE_DATA_TYPE_BOOLEAN, traceDataCache_->GetDataIndex("boolean")); } diff --git a/trace_streamer/src/filter/binder_filter.cpp b/trace_streamer/src/filter/binder_filter.cpp index 4a00c2f89d136c085da6f06f01997fdc72c57176..ee83aa9157fd676d27f00db8aa4a1d0cc192e837 100644 --- a/trace_streamer/src/filter/binder_filter.cpp +++ b/trace_streamer/src/filter/binder_filter.cpp @@ -159,17 +159,17 @@ void BinderFilter::TransactionAllocBuf(int64_t ts, uint32_t pid, uint64_t dataSi args.AppendArg(dataSizeId_, BASE_DATA_TYPE_INT, dataSize); args.AppendArg(dataOffsetSizeId_, BASE_DATA_TYPE_INT, offsetsSize); (void)streamFilters_->sliceFilter_->AddArgs(pid, binderCatalogId_, transSliceId_, args); - UNUSED(ts); + Unused(ts); } void BinderFilter::TractionLock(int64_t ts, uint32_t pid, const std::string& tag) { - UNUSED(tag); + Unused(tag); lastEventTs_[pid] = ts; (void)streamFilters_->sliceFilter_->BeginBinder(ts, pid, binderCatalogId_, lockTryId_); } void BinderFilter::TractionLocked(int64_t ts, uint32_t pid, const std::string& tag) { - UNUSED(tag); + Unused(tag); if (!lastEventTs_.count(pid)) { streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_BINDER_TRANSACTION_LOCKED, STAT_EVENT_NOTMATCH); return; @@ -181,7 +181,7 @@ void BinderFilter::TractionLocked(int64_t ts, uint32_t pid, const std::string& t } void BinderFilter::TractionUnlock(int64_t ts, uint32_t pid, const std::string& tag) { - UNUSED(tag); + Unused(tag); if (!lastEventTs_.count(pid)) { streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_BINDER_TRANSACTION_UNLOCK, STAT_EVENT_NOTMATCH); return; diff --git a/trace_streamer/src/filter/cpu_filter.cpp b/trace_streamer/src/filter/cpu_filter.cpp index 04371b4a7060ca95386f2645e1faa823a85f10bd..7ce0eca2e68dbecd88b9e3b4ac2925f86c0106b2 100644 --- a/trace_streamer/src/filter/cpu_filter.cpp +++ b/trace_streamer/src/filter/cpu_filter.cpp @@ -158,7 +158,7 @@ bool CpuFilter::InsertBlockedReasonEvent(uint64_t ts, } bool CpuFilter::InsertProcessExitEvent(uint64_t ts, uint64_t cpu, uint32_t pid) { - UNUSED(cpu); + Unused(cpu); auto thread = traceDataCache_->GetThreadData(static_cast(pid)); if (thread) { thread->endT_ = ts; diff --git a/trace_streamer/src/filter/filter_base.h b/trace_streamer/src/filter/filter_base.h index 16e6238ccc86c36a8813764c42e317de64230849..7f75e55d17483454b85df64d28c2494fad1d31cd 100644 --- a/trace_streamer/src/filter/filter_base.h +++ b/trace_streamer/src/filter/filter_base.h @@ -19,11 +19,6 @@ #include "trace_data_cache.h" #include "trace_streamer_filters.h" -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) - namespace SysTuning { namespace TraceStreamer { class FilterBase { diff --git a/trace_streamer/src/filter/frame_filter.cpp b/trace_streamer/src/filter/frame_filter.cpp index 3822f80b215fc8a51b91917273c9c2abc6cfd6f1..dab63fb78fd31cba88d2f88c1cc14e6b8238b1b0 100644 --- a/trace_streamer/src/filter/frame_filter.cpp +++ b/trace_streamer/src/filter/frame_filter.cpp @@ -16,7 +16,7 @@ #include #include #include "log.h" -#define ISINVALIDU32(value) (value == INVALID_UINT32) +#define ISINVALIDU32(value) ((value) == INVALID_UINT32) namespace SysTuning { namespace TraceStreamer { FrameFilter::FrameFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) : FilterBase(dataCache, filter) @@ -84,7 +84,6 @@ bool FrameFilter::BeginRSTransactionData(uint64_t ts, uint32_t itid, uint32_t fr std::unordered_map> frameMap; dstRenderSlice_.emplace(std::make_pair(itid, std::move(frameMap))); } - // dstRenderSlice_.at(itid).insert(std::make_pair(franeNum, frame->second.begin())); dstRenderSlice_[itid][franeNum] = frame->second[0]; return true; } diff --git a/trace_streamer/src/filter/measure_filter.cpp b/trace_streamer/src/filter/measure_filter.cpp index 30e56c688bb0e031cbaa8f5a689811410fcb098f..fa8391184d33477bd6d1eade761505955c7c08b0 100644 --- a/trace_streamer/src/filter/measure_filter.cpp +++ b/trace_streamer/src/filter/measure_filter.cpp @@ -35,11 +35,12 @@ bool MeasureFilter::AppendNewMeasureData(uint64_t internalTid, DataIndex nameInd } else { auto row = traceDataCache_->GetMeasureData()->AppendMeasureData(0, timeStamp, value, filterId); // if the filterId ever exists - if (filterIdToRow_.count(filterId)) { - traceDataCache_->GetMeasureData()->SetDur(filterIdToRow_.at(filterId), timeStamp); - filterIdToRow_.at(filterId) = row; + auto filterIdToRow = traceDataCache_->GetMeasureData()->GetFilterIdToRow(); + if (filterIdToRow->count(filterId)) { + traceDataCache_->GetMeasureData()->SetDur(filterIdToRow->at(filterId), timeStamp); + filterIdToRow->at(filterId) = row; } else { - filterIdToRow_.insert(std::make_pair(filterId, row)); + filterIdToRow->insert(std::make_pair(filterId, row)); } } return value != 0; @@ -61,18 +62,9 @@ void MeasureFilter::AddCertainFilterId(uint64_t internalTid, DataIndex nameIndex { tidStreamIdFilterIdMap_.Insert(internalTid, nameIndex, filterId); - if (filterType_ == E_THREADMEASURE_FILTER) { - traceDataCache_->GetThreadMeasureFilterData()->AppendNewFilter(filterId, static_cast(nameIndex), - internalTid); - } else if (filterType_ == E_THREAD_FILTER) { - traceDataCache_->GetThreadFilterData()->AppendNewFilter(filterId, static_cast(nameIndex), - internalTid); - } else if (filterType_ == E_PROCESS_MEASURE_FILTER) { + if (filterType_ == E_PROCESS_MEASURE_FILTER) { traceDataCache_->GetProcessMeasureFilterData()->AppendNewFilter( static_cast(filterId), static_cast(nameIndex), static_cast(internalTid)); - } else if (filterType_ == E_PROCESS_FILTER_FILTER) { - traceDataCache_->GetProcessFilterData()->AppendNewFilter( - static_cast(filterId), static_cast(nameIndex), static_cast(internalTid)); } else if (filterType_ == E_CPU_MEASURE_FILTER) { traceDataCache_->GetCpuMeasuresData()->AppendNewFilter(filterId, static_cast(nameIndex), internalTid); } else if (filterType_ == E_CLOCK_RATE_FILTER) { @@ -95,10 +87,5 @@ void MeasureFilter::AddCertainFilterId(uint64_t internalTid, DataIndex nameIndex static_cast(nameIndex), internalTid); } } -void MeasureFilter::Clear() -{ - tidStreamIdFilterIdMap_.Clear(); - filterIdToRow_.clear(); -} } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/filter/measure_filter.h b/trace_streamer/src/filter/measure_filter.h index c8df03d61f284b19ddc7ef9471cccedfddae519f..ea13da6e6687d2b84a280f1f5c27624968e301db 100644 --- a/trace_streamer/src/filter/measure_filter.h +++ b/trace_streamer/src/filter/measure_filter.h @@ -28,10 +28,7 @@ namespace SysTuning { namespace TraceStreamer { enum FilterType { - E_THREADMEASURE_FILTER, - E_THREAD_FILTER, E_PROCESS_MEASURE_FILTER, - E_PROCESS_FILTER_FILTER, E_CPU_MEASURE_FILTER, E_CLOCK_RATE_FILTER, E_CLOCK_ENABLE_FILTER, @@ -49,31 +46,23 @@ public: ~MeasureFilter() override; bool AppendNewMeasureData(uint64_t internalTid, DataIndex nameIndex, uint64_t timeStamp, int64_t value); uint32_t GetOrCreateFilterId(uint64_t internalTid, DataIndex nameIndex); - void Clear(); private: void AddCertainFilterId(uint64_t internalTid, DataIndex nameIndex, uint64_t filterId); DoubleMap tidStreamIdFilterIdMap_; FilterType filterType_; - const std::map filterTypeValue = {{E_THREADMEASURE_FILTER, "thread_measure_filter"}, - {E_THREAD_FILTER, "thread_measure"}, - {E_PROCESS_MEASURE_FILTER, "process_measure_filter"}, - {E_PROCESS_FILTER_FILTER, "process_filter"}, - {E_CPU_MEASURE_FILTER, "cpu_measure_filter"}, - {E_CLOCK_RATE_FILTER, "clock_rate_filter"}, - {E_CLOCK_ENABLE_FILTER, "clock_enable_filter"}, - {E_CLOCK_DISABLE_FILTER, "clock_disable_filter"}, - {E_CLK_RATE_FILTER, "clk_rate_filter"}, - {E_CLK_ENABLE_FILTER, "clk_enable_filter"}, - {E_CLK_DISABLE_FILTER, "clk_disable_filter"}}; + const std::map filterTypeValue = { + {E_PROCESS_MEASURE_FILTER, "process_measure_filter"}, {E_CPU_MEASURE_FILTER, "cpu_measure_filter"}, + {E_CLOCK_RATE_FILTER, "clock_rate_filter"}, {E_CLOCK_ENABLE_FILTER, "clock_enable_filter"}, + {E_CLOCK_DISABLE_FILTER, "clock_disable_filter"}, {E_CLK_RATE_FILTER, "clk_rate_filter"}, + {E_CLK_ENABLE_FILTER, "clk_enable_filter"}, {E_CLK_DISABLE_FILTER, "clk_disable_filter"}}; const DataIndex clockSetRateDataIndex_ = traceDataCache_->GetDataIndex("clock_set_rate"); const DataIndex clockEnableDataIndex_ = traceDataCache_->GetDataIndex("clock_enable"); const DataIndex clockDisableDataIndex_ = traceDataCache_->GetDataIndex("clock_disable"); const DataIndex clkSetRateDataIndex_ = traceDataCache_->GetDataIndex("clk_set_rate"); const DataIndex clkEnableDataIndex_ = traceDataCache_->GetDataIndex("clk_enable"); const DataIndex clkDisableDataIndex_ = traceDataCache_->GetDataIndex("clk_disable"); - std::map filterIdToRow_ = {}; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/filter/native_hook_filter.cpp b/trace_streamer/src/filter/native_hook_filter.cpp index 1702e860e8a2de55a554e16b689f6c84523bfebb..f0071a32f3dd7690325808119722f3ea4f783f52 100644 --- a/trace_streamer/src/filter/native_hook_filter.cpp +++ b/trace_streamer/src/filter/native_hook_filter.cpp @@ -586,17 +586,17 @@ std::tuple NativeHookFilter::GetNeedUpdateProcessMapsAddrRan return std::make_tuple(start, end); } -inline void NativeHookFilter::FillOfflineSymbolizationFrames( +void NativeHookFilter::FillOfflineSymbolizationFrames( std::map>>::iterator mapItor) { auto curCacheIpid = mapItor->second->back(); stackIdToCallChainIdMap_.insert(std::make_pair(mapItor->first, ++callChainId_)); auto framesInfo = OfflineSymbolization(mapItor->second); uint16_t depth = 0; - uint64_t filePathIndex = INVALID_UINT64; if (isSingleProcData_) { curCacheIpid = SINGLE_PROC_IPID; } + uint64_t filePathIndex; for (auto itor = framesInfo->rbegin(); itor != framesInfo->rend(); itor++) { // Note that the filePathId here is provided for the end side. Not a true TS internal index dictionary. auto frameInfo = itor->get(); @@ -776,6 +776,9 @@ void NativeHookFilter::ParseSymbolTableEvent(std::unique_ptr auto symEntrySize = reader->sym_entry_size(); auto symTable = reader->sym_table(); + if (symEntrySize == 0) { + return; + } auto size = symTable.Size() / symEntrySize; if (symEntrySize == ELF32_SYM) { UpdateSymbolTablePtrAndStValueToSymAddrMap(reinterpret_cast(symTable.Data()), size, reader); diff --git a/trace_streamer/src/filter/native_hook_filter.h b/trace_streamer/src/filter/native_hook_filter.h index 90e3e60d230ddaf9a0229837ad055cd9dab95256..3404130ca1ad50c2269a03f7582f9fa6677e8664 100644 --- a/trace_streamer/src/filter/native_hook_filter.h +++ b/trace_streamer/src/filter/native_hook_filter.h @@ -85,7 +85,7 @@ public: CommHookData& GetCommHookData(); ProfilerPluginData* GetHookPluginData(); void SerializeHookCommDataToString(); - bool IsSingleProcData() + const bool IsSingleProcData() { return isSingleProcData_; } @@ -113,7 +113,7 @@ private: void UpdateSymbolTablePtrAndStValueToSymAddrMap(T* firstSymbolAddr, const int size, std::shared_ptr reader); - void FillOfflineSymbolizationFrames(std::map>>::iterator itor); + void FillOfflineSymbolizationFrames(std::map>>::iterator mapItor); void ReparseStacksWithAddrRange(uint64_t start, uint64_t end); void ReparseStacksWithDifferentMeans(); void CompressStackAndFrames(uint64_t row, ProtoReader::RepeatedDataAreaIterator frames); @@ -129,6 +129,13 @@ private: void UpdateFilePathIndexToCallStackRowMap(size_t row, DataIndex filePathIndex); private: + // first key is addr, second key is size, value is set in db + // mmap update anonymous memory tag always use the anonMmapData_ value + DoubleMap>> anonMmapData_; + std::unique_ptr hookPluginData_ = nullptr; + DoubleMap ipidToSymIdToSymIndex_; + DoubleMap ipidToFilePathIdToFileIndex_; + DoubleMap> ipidToFrameIdToFrameBytes_; std::unordered_map>> filePathIndexToFrameTableRowMap_ = {}; std::multimap> tsToMainEventsMap_ = {}; std::map>> reparseStackIdToFramesMap_ = @@ -136,14 +143,11 @@ private: std::map>> allStackIdToFramesMap_ = {}; std::map>> stackIdToFramesMap_ = {}; std::map callChainIdToStackHashValueMap_ = {}; - DoubleMap> ipidToFrameIdToFrameBytes_; std::unordered_map> stackHashValueToFramesHashMap_ = {}; std::unordered_map> frameHashToFrameInfoMap_ = {}; std::unordered_map threadNameIdToThreadNameIndex_ = {}; std::unordered_map> callIdToLastCallerPathIndex_ = {}; std::unordered_map functionNameIndexToVaddr_ = {}; - DoubleMap ipidToSymIdToSymIndex_; - DoubleMap ipidToFilePathIdToFileIndex_; std::unordered_map stackHashValueToCallChainIdMap_ = {}; std::unordered_map itidToThreadNameId_ = {}; std::unordered_map stackIdToCallChainIdMap_ = {}; @@ -153,9 +157,6 @@ private: std::deque vaddrs_ = {}; // munmap update anonymous or named memory tag always use the last addrToMmapTag_ value std::unordered_map addrToMmapTag_ = {}; - // first key is addr, second key is size, value is set in db - // mmap update anonymous memory tag always use the anonMmapData_ value - DoubleMap>> anonMmapData_; std::hash hashFun_; bool isOfflineSymbolizationMode_ = false; bool isCallStackCompressedMode_ = false; @@ -164,7 +165,6 @@ private: const size_t MAX_CACHE_SIZE = 200000; uint32_t callChainId_ = 0; CommHookData commHookData_; - std::unique_ptr hookPluginData_ = nullptr; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/filter/offline_symbolization_filter.h b/trace_streamer/src/filter/offline_symbolization_filter.h index 9b8ace7d1d38243a03f8d339defac991120d0f61..ec309ca2b2b14dd41405d3374bd141932c7e1edb 100644 --- a/trace_streamer/src/filter/offline_symbolization_filter.h +++ b/trace_streamer/src/filter/offline_symbolization_filter.h @@ -15,6 +15,7 @@ #ifndef OFFLINE_SYMBOLIZATION_FILTER_H #define OFFLINE_SYMBOLIZATION_FILTER_H +#include "double_map.h" #ifndef is_linux #include "dfx_nonlinux_define.h" #else @@ -67,18 +68,20 @@ public: protected: enum SYSTEM_ENTRY_VALUE { ELF32_SYM = 16, ELF64_SYM = 24 }; using StartAddrToMapsInfoType = std::map>; + DoubleMap filePathIdAndStValueToSymAddr_; + DoubleMap, uint64_t, const uint8_t*> + symbolTablePtrAndStValueToSymAddr_; // first is ipid, second is startAddr, third is MapsInfo ptr DoubleMap> ipidToStartAddrToMapsInfoMap_; + // first is ipid, second is ip, third is FrameInfo + DoubleMap> ipidToIpToFrameInfo_; DoubleMap> ipidTofilePathIdToSymbolTableMap_; std::unordered_map> filePathIdToImportSymbolTableMap_ = {}; - DoubleMap filePathIdAndStValueToSymAddr_; - DoubleMap, uint64_t, const uint8_t*> - symbolTablePtrAndStValueToSymAddr_; + using IpToFrameInfoType = std::map>; - // first is ipid, second is ip, third is FrameInfo - DoubleMap> ipidToIpToFrameInfo_; + std::vector> segs_ = {}; const uint32_t SINGLE_PROC_IPID = 0; bool isSingleProcData_ = true; diff --git a/trace_streamer/src/filter/perf_data_filter.cpp b/trace_streamer/src/filter/perf_data_filter.cpp index a0e5a4abbec29774cb85234c506154744dba5aa8..a5467655c9e41041af1800671178eff06f64999f 100644 --- a/trace_streamer/src/filter/perf_data_filter.cpp +++ b/trace_streamer/src/filter/perf_data_filter.cpp @@ -64,7 +64,7 @@ void PerfDataFilter::Finish() auto filePath = traceDataCache_->GetPerfFilesData()->FilePaths(); auto sambols = traceDataCache_->GetPerfFilesData()->Symbols(); uint64_t flag = 1; - flag = ~(flag << 63); + flag = ~(flag << FLAG_SHIFT_LEFT); for (auto i = 0; i < size; i++) { if (fileIds[i] == INVALID_UINT64) { auto nameIndex = traceDataCache_->GetDataIndex("@0x" + base::number(ips[i], base::INTEGER_RADIX_TYPE_HEX)); diff --git a/trace_streamer/src/filter/perf_data_filter.h b/trace_streamer/src/filter/perf_data_filter.h index 733f6eab3afa71b1542b3e5511c7fa3ad1b9ee8c..8b85efa75e8cfc3de2c70904ceb9c882edc271d4 100644 --- a/trace_streamer/src/filter/perf_data_filter.h +++ b/trace_streamer/src/filter/perf_data_filter.h @@ -24,6 +24,7 @@ #include "trace_streamer_filters.h" namespace SysTuning { namespace TraceStreamer { +constexpr int FLAG_SHIFT_LEFT = 63; class PerfDataFilter : private FilterBase { public: PerfDataFilter(TraceDataCache*, const TraceStreamerFilters*); diff --git a/trace_streamer/src/filter/process_filter.cpp b/trace_streamer/src/filter/process_filter.cpp index e3afcb85fd82fc6e85a56761e12fde069028d9ed..e16b6026d442d8f6d9d2195ee526ba4c33d3dfc6 100644 --- a/trace_streamer/src/filter/process_filter.cpp +++ b/trace_streamer/src/filter/process_filter.cpp @@ -81,7 +81,7 @@ uint32_t ProcessFilter::UpdateOrCreateThreadWithPidAndName(uint32_t tid, uint32_ uint32_t ProcessFilter::GetOrCreateThreadWithPid(uint32_t tid, uint32_t pid) { TraceStdtype::Thread* thread = nullptr; - uint32_t internalTid = INVALID_ID; + uint32_t internalTid; if (pid == 0) { internalTid = GetInternalTid(tid); } else { diff --git a/trace_streamer/src/filter/slice_filter.cpp b/trace_streamer/src/filter/slice_filter.cpp index b2ad46d32ce9ce60215fa80a896bcc1fb3322163..a76e3d84c10aa3af655a35bfa8dd34844a1ddf7c 100644 --- a/trace_streamer/src/filter/slice_filter.cpp +++ b/trace_streamer/src/filter/slice_filter.cpp @@ -438,7 +438,7 @@ uint64_t SliceFilter::StartAsyncSlice(uint64_t timeStamp, uint64_t cookie, DataIndex nameIndex) { - UNUSED(pid); + Unused(pid); InternalPid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(timeStamp, threadGroupId); auto lastFilterId = asyncEventMap_.Find(internalTid, cookie, nameIndex); @@ -466,7 +466,7 @@ uint64_t SliceFilter::FinishAsyncSlice(uint64_t timeStamp, uint64_t cookie, DataIndex nameIndex) { - UNUSED(pid); + Unused(pid); InternalPid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(timeStamp, threadGroupId); auto lastFilterId = asyncEventMap_.Find(internalTid, cookie, nameIndex); auto slices = traceDataCache_->GetInternalSlicesData(); diff --git a/trace_streamer/src/filter/task_pool_filter.h b/trace_streamer/src/filter/task_pool_filter.h index 5143eb63d3ba11618d5985fe9a0e5aa006f39987..a15cf9b5400ca2f61f02b7e5fb108d397c2c91bf 100644 --- a/trace_streamer/src/filter/task_pool_filter.h +++ b/trace_streamer/src/filter/task_pool_filter.h @@ -19,7 +19,7 @@ #include #include #include - +#include "double_map.h" #include "filter_base.h" #include "string_help.h" #include "trace_data_cache.h" diff --git a/trace_streamer/src/main.cpp b/trace_streamer/src/main.cpp index 93d5076132770fcb78185fe28f6586e35558aa1b..1f1ba810f661ccfb8795cfb56ad5b2bc4ecfeff5 100644 --- a/trace_streamer/src/main.cpp +++ b/trace_streamer/src/main.cpp @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include #include #include @@ -28,7 +28,6 @@ #include "codec_cov.h" #include "file.h" #include "filter/slice_filter.h" -#include "http_server.h" #include "log.h" #include "metrics.h" #include "parser/bytrace_parser/bytrace_event_parser.h" @@ -106,7 +105,7 @@ void PrintInformation() } void PrintVersion() { - fprintf(stderr, "version %s\n", g_traceStreamerVersion.c_str()); + (void)fprintf(stderr, "version %s\n", g_traceStreamerVersion.c_str()); } bool ReadAndParser(SysTuning::TraceStreamer::TraceStreamerSelector& ta, int fd) @@ -220,8 +219,8 @@ int ExportDatabase(TraceStreamerSelector& ts, const std::string& sqliteFilePath) (std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())) .count(); endTime += 1; // for any exception of endTime == startTime - fprintf(stdout, "ExportDuration:\t%u ms\n", static_cast(endTime - startTime)); - fprintf(stdout, "ExportSpeed:\t%.2f MB/s\n", (g_loadSize / (endTime - startTime)) / 1E3); + (void)fprintf(stdout, "ExportDuration:\t%u ms\n", static_cast(endTime - startTime)); + (void)fprintf(stdout, "ExportSpeed:\t%.2f MB/s\n", (g_loadSize / (endTime - startTime)) / 1E3); return 0; } bool LongTraceExportDatabase(TraceStreamerSelector& ts, const std::string& sqliteFilePath) @@ -256,10 +255,6 @@ struct TraceExportOption { bool closeMutiThread = false; uint8_t parserThreadNum = INVALID_UINT8; }; -struct HttpOption { - bool enable = false; - int port = 9001; -}; bool SetDumpFileType(char** argv, const std::string& dumpFileType, TraceExportOption& traceExportOption) { if (dumpFileType == "perf") { @@ -274,11 +269,11 @@ bool SetDumpFileType(char** argv, const std::string& dumpFileType, TraceExportOp } return true; } -int CheckFinal(char** argv, TraceExportOption& traceExportOption, HttpOption& httpOption) +int CheckFinal(char** argv, TraceExportOption& traceExportOption) { if (((traceExportOption.traceFilePath.empty() && traceExportOption.longTraceDir.empty()) || (!traceExportOption.interactiveState && traceExportOption.sqliteFilePath.empty())) && - !httpOption.enable && !traceExportOption.separateFile && traceExportOption.metricsIndex.empty() && + !traceExportOption.separateFile && traceExportOption.metricsIndex.empty() && traceExportOption.sqlOperatorFilePath.empty() && traceExportOption.outputFilePath.empty() && traceExportOption.dumpFileType == DumpFileType::UNKONW_TYPE) { ShowHelpInfo(argv[0]); @@ -296,7 +291,7 @@ bool CheckArgc(int argc, char** argv, int curArgNum) return true; } -int CheckArgs(int argc, char** argv, TraceExportOption& traceExportOption, HttpOption& httpOption) +int CheckArgs(int argc, char** argv, TraceExportOption& traceExportOption) { for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-e")) { @@ -352,19 +347,12 @@ int CheckArgs(int argc, char** argv, TraceExportOption& traceExportOption, HttpO !strcmp(argv[i], "--version")) { PrintVersion(); return 1; - } else if (!strcmp(argv[i], "-h")) { - httpOption.enable = true; - continue; - } else if (!strcmp(argv[i], "-p")) { - TS_CHECK_TRUE_RET(CheckArgc(argc, argv, ++i), 1); - httpOption.port = std::stoi(argv[i]); - continue; } traceExportOption.traceFilePath = std::string(argv[i]); auto strVec = SplitStringToVec(traceExportOption.traceFilePath, "."); traceExportOption.outputFilePath = strVec.front() + "_ReadableText.txt"; } - return CheckFinal(argv, traceExportOption, httpOption); + return CheckFinal(argv, traceExportOption); } bool GetLongTraceFilePaths(const TraceExportOption& traceExportOption, std::map& seqToFilePathMap) { @@ -485,21 +473,13 @@ int main(int argc, char** argv) return 1; } TraceExportOption tsOption; - HttpOption httpOption; - int ret = CheckArgs(argc, argv, tsOption, httpOption); + int ret = CheckArgs(argc, argv, tsOption); if (ret) { if (!tsOption.sqliteFilePath.empty()) { ExportStatusToLog(tsOption.sqliteFilePath, GetAnalysisResult()); } return 0; } - if (httpOption.enable) { - RpcServer rpcServer; - HttpServer httpServer; - httpServer.RegisterRpcFunction(&rpcServer); - httpServer.Run(httpOption.port); - return 0; - } TraceStreamerSelector ts; ts.EnableMetaTable(tsOption.exportMetaTable); ts.EnableFileSave(tsOption.separateFile); @@ -539,8 +519,8 @@ int main(int argc, char** argv) metaData->SetTraceDataSize(g_loadSize); while (true) { auto values = ts.SearchData(); - std::string symbolsPath = "default"; if (!values.empty()) { + std::string symbolsPath = "default"; ts.ReloadSymbolFiles(symbolsPath, values); } else { return 0; diff --git a/trace_streamer/src/metrics/metrics.h b/trace_streamer/src/metrics/metrics.h index cf0ea7daed1125ee7579a3cb3614912b035ed300..8c351e3447d851d65bd4276687d1938e10fd3697 100644 --- a/trace_streamer/src/metrics/metrics.h +++ b/trace_streamer/src/metrics/metrics.h @@ -84,7 +84,7 @@ public: using ResultCallBack = std::function; void ParserJson(const std::string& metrics, std::string& result); void PrintMetricsResult(uint32_t metricsIndex, ResultCallBack callback); - auto GetMetricsMap() + const auto GetMetricsMap() { return initMetricsMap_; } diff --git a/trace_streamer/src/parser/BUILD.gn b/trace_streamer/src/parser/BUILD.gn index dbfc8a6575dcceedbaef097b68e7c94e12f1de89..82a44251bff5cc11be24672c3c7b7ced933bc7be 100644 --- a/trace_streamer/src/parser/BUILD.gn +++ b/trace_streamer/src/parser/BUILD.gn @@ -59,7 +59,16 @@ ohos_source_set("parser") { "${THIRD_PARTY}/bounds_checking_function/include", "${THIRD_PARTY}/json/single_include/nlohmann", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.cpp b/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.cpp index 3d5637331f1bb3ec8ae16fa499e293266ae9854e..2e088ed2df919a7c426b709583ba13b09d646215 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.cpp +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.cpp @@ -51,71 +51,128 @@ BytraceEventParser::BytraceEventParser(TraceDataCache* dataCache, const TraceStr { printEventParser_.SetTraceType(TRACE_FILETYPE_BY_TRACE); eventToFunctionMap_ = { - {config_.eventNameMap_.at(TRACE_EVENT_SCHED_SWITCH), - bind(&BytraceEventParser::SchedSwitchEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_SCHED_BLOCKED_REASON), - bind(&BytraceEventParser::BlockedReason, this, std::placeholders::_1, std::placeholders::_2)}, {config_.eventNameMap_.at(TRACE_EVENT_TASK_RENAME), bind(&BytraceEventParser::TaskRenameEvent, this, std::placeholders::_1, std::placeholders::_2)}, {config_.eventNameMap_.at(TRACE_EVENT_TASK_NEWTASK), bind(&BytraceEventParser::TaskNewtaskEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_TRACING_MARK_WRITE), - bind(&BytraceEventParser::TracingMarkWriteOrPrintEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_PRINT), - bind(&BytraceEventParser::TracingMarkWriteOrPrintEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_SWITCH), + bind(&BytraceEventParser::SchedSwitchEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_BLOCKED_REASON), + bind(&BytraceEventParser::BlockedReason, this, std::placeholders::_1, std::placeholders::_2)}, {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP), bind(&BytraceEventParser::SchedWakeupEvent, this, std::placeholders::_1, std::placeholders::_2)}, {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKING), bind(&BytraceEventParser::SchedWakingEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_CPU_IDLE), - bind(&BytraceEventParser::CpuIdleEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_CPU_FREQUENCY), - bind(&BytraceEventParser::CpuFrequencyEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_CPU_FREQUENCY_LIMITS), - bind(&BytraceEventParser::CpuFrequencyLimitsEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_START), - bind(&BytraceEventParser::WorkqueueExecuteStartEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_END), - bind(&BytraceEventParser::WorkqueueExecuteEndEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_CLOCK_SET_RATE), - bind(&BytraceEventParser::SetRateEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_CLOCK_ENABLE), - bind(&BytraceEventParser::ClockEnableEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_CLOCK_DISABLE), - bind(&BytraceEventParser::ClockDisableEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_SET_VOLTAGE), - bind(&BytraceEventParser::RegulatorSetVoltageEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE), - bind(&BytraceEventParser::RegulatorSetVoltageCompleteEvent, this, std::placeholders::_1, - std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_DISABLE), - bind(&BytraceEventParser::RegulatorDisableEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE), - bind(&BytraceEventParser::RegulatorDisableCompleteEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP_NEW), + bind(&BytraceEventParser::SchedWakeupEvent, this, std::placeholders::_1, std::placeholders::_2)}, + {config_.eventNameMap_.at(TRACE_EVENT_PROCESS_EXIT), + bind(&BytraceEventParser::ProcessExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, {config_.eventNameMap_.at(TRACE_EVENT_IPI_ENTRY), bind(&BytraceEventParser::IpiEntryEvent, this, std::placeholders::_1, std::placeholders::_2)}, {config_.eventNameMap_.at(TRACE_EVENT_IPI_EXIT), bind(&BytraceEventParser::IpiExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_IRQ_HANDLER_ENTRY), - bind(&BytraceEventParser::IrqHandlerEntryEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_IRQ_HANDLER_EXIT), - bind(&BytraceEventParser::IrqHandlerExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_RAISE), - bind(&BytraceEventParser::SoftIrqRaiseEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_ENTRY), - bind(&BytraceEventParser::SoftIrqEntryEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_EXIT), - bind(&BytraceEventParser::SoftIrqExitEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION), - bind(&BytraceEventParser::BinderTransaction, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION_RECEIVED), - bind(&BytraceEventParser::BinderTransactionReceived, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION_ALLOC_BUF), - bind(&BytraceEventParser::BinderTransactionAllocBufEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_SCHED_WAKEUP_NEW), - bind(&BytraceEventParser::SchedWakeupEvent, this, std::placeholders::_1, std::placeholders::_2)}, - {config_.eventNameMap_.at(TRACE_EVENT_PROCESS_EXIT), - bind(&BytraceEventParser::ProcessExitEvent, this, std::placeholders::_1, std::placeholders::_2)}}; + }; + InterruptEventInitialization(); + ClockEventInitialization(); + CpuEventInitialization(); + RegulatorEventInitialization(); + BinderEventInitialization(); + StackEventsInitialization(); +} + +void BytraceEventParser::InterruptEventInitialization() +{ + // Interrupt and soft interrupt event initialization + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_IRQ_HANDLER_ENTRY), + bind(&BytraceEventParser::IrqHandlerEntryEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_IRQ_HANDLER_EXIT), + bind(&BytraceEventParser::IrqHandlerExitEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_RAISE), + bind(&BytraceEventParser::SoftIrqRaiseEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_ENTRY), + bind(&BytraceEventParser::SoftIrqEntryEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_SOFTIRQ_EXIT), + bind(&BytraceEventParser::SoftIrqExitEvent, this, std::placeholders::_1, std::placeholders::_2)); +} + +void BytraceEventParser::ClockEventInitialization() +{ + // Clock event initialization + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_CLOCK_SET_RATE), + bind(&BytraceEventParser::SetRateEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_CLOCK_ENABLE), + bind(&BytraceEventParser::ClockEnableEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_CLOCK_DISABLE), + bind(&BytraceEventParser::ClockDisableEvent, this, std::placeholders::_1, std::placeholders::_2)); +} + +void BytraceEventParser::CpuEventInitialization() +{ + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_CPU_IDLE), + bind(&BytraceEventParser::CpuIdleEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_CPU_FREQUENCY), + bind(&BytraceEventParser::CpuFrequencyEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_CPU_FREQUENCY_LIMITS), + bind(&BytraceEventParser::CpuFrequencyLimitsEvent, this, std::placeholders::_1, std::placeholders::_2)); +} + +void BytraceEventParser::RegulatorEventInitialization() +{ + // Initialize regulator related events + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_SET_VOLTAGE), + bind(&BytraceEventParser::RegulatorSetVoltageEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace(config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE), + bind(&BytraceEventParser::RegulatorSetVoltageCompleteEvent, this, std::placeholders::_1, + std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_DISABLE), + bind(&BytraceEventParser::RegulatorDisableEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE), + bind(&BytraceEventParser::RegulatorDisableCompleteEvent, this, std::placeholders::_1, std::placeholders::_2)); +} + +void BytraceEventParser::BinderEventInitialization() +{ + // Binder event initialization + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION), + bind(&BytraceEventParser::BinderTransaction, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION_RECEIVED), + bind(&BytraceEventParser::BinderTransactionReceived, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_BINDER_TRANSACTION_ALLOC_BUF), + bind(&BytraceEventParser::BinderTransactionAllocBufEvent, this, std::placeholders::_1, std::placeholders::_2)); +} + +void BytraceEventParser::StackEventsInitialization() +{ + // Call stack Events + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_TRACING_MARK_WRITE), + bind(&BytraceEventParser::TracingMarkWriteOrPrintEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_PRINT), + bind(&BytraceEventParser::TracingMarkWriteOrPrintEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_START), + bind(&BytraceEventParser::WorkqueueExecuteStartEvent, this, std::placeholders::_1, std::placeholders::_2)); + eventToFunctionMap_.emplace( + config_.eventNameMap_.at(TRACE_EVENT_WORKQUEUE_EXECUTE_END), + bind(&BytraceEventParser::WorkqueueExecuteEndEvent, this, std::placeholders::_1, std::placeholders::_2)); } bool BytraceEventParser::SchedSwitchEvent(const ArgsMap& args, const BytraceLine& line) const @@ -224,7 +281,7 @@ bool BytraceEventParser::TaskNewtaskEvent(const ArgsMap& args, const BytraceLine bool BytraceEventParser::TracingMarkWriteOrPrintEvent(const ArgsMap& args, const BytraceLine& line) { - UNUSED(args); + Unused(args); return printEventParser_.ParsePrintEvent(line.task, line.ts, line.pid, line.argsStr.c_str(), line); } // prefer to use waking, unless no waking, can use wakeup @@ -250,7 +307,7 @@ bool BytraceEventParser::SchedWakeupEvent(const ArgsMap& args, const BytraceLine instants->AppendInstantEventData(line.ts, schedWakeupName_, internalTid, wakeupFromPid); std::optional targetCpu = base::StrToInt(args.at("target_cpu")); if (targetCpu.has_value()) { - traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_SCHED_WAKEUP, targetCpu.value(), wakeupFromPid); + traceDataCache_->GetRawData()->AppendRawData(line.ts, RAW_SCHED_WAKEUP, targetCpu.value(), wakeupFromPid); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKEUP, STAT_EVENT_RECEIVED); } return true; @@ -279,8 +336,7 @@ bool BytraceEventParser::SchedWakingEvent(const ArgsMap& args, const BytraceLine instants->AppendInstantEventData(line.ts, schedWakingName_, internalTid, wakeupFromPid); std::optional targetCpu = base::StrToInt(args.at("target_cpu")); if (targetCpu.has_value()) { - traceDataCache_->GetRawData()->AppendRawData(0, line.ts, RAW_SCHED_WAKING, targetCpu.value(), - internalTidWakeup); + traceDataCache_->GetRawData()->AppendRawData(line.ts, RAW_SCHED_WAKING, targetCpu.value(), internalTidWakeup); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_WAKING, STAT_EVENT_RECEIVED); } @@ -387,7 +443,7 @@ bool BytraceEventParser::CpuFrequencyLimitsEvent(const ArgsMap& args, const Bytr bool BytraceEventParser::WorkqueueExecuteStartEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); + Unused(args); auto splitStr = GetFunctionName(line.argsStr, "function "); auto splitStrIndex = traceDataCache_->GetDataIndex(splitStr); size_t result = @@ -404,7 +460,7 @@ bool BytraceEventParser::WorkqueueExecuteStartEvent(const ArgsMap& args, const B bool BytraceEventParser::WorkqueueExecuteEndEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); + Unused(args); if (streamFilters_->sliceFilter_->EndSlice(line.ts, line.pid, 0, workQueueId_)) { streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_END, STAT_EVENT_RECEIVED); return true; @@ -486,16 +542,16 @@ bool BytraceEventParser::ClockDisableEvent(const ArgsMap& args, const BytraceLin bool BytraceEventParser::RegulatorSetVoltageEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); - UNUSED(line); + Unused(args); + Unused(line); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE, STAT_EVENT_RECEIVED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE, STAT_EVENT_NOTSUPPORTED); return true; } bool BytraceEventParser::RegulatorSetVoltageCompleteEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); - UNUSED(line); + Unused(args); + Unused(line); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, STAT_EVENT_RECEIVED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, STAT_EVENT_NOTSUPPORTED); @@ -503,16 +559,16 @@ bool BytraceEventParser::RegulatorSetVoltageCompleteEvent(const ArgsMap& args, c } bool BytraceEventParser::RegulatorDisableEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); - UNUSED(line); + Unused(args); + Unused(line); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE, STAT_EVENT_RECEIVED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE, STAT_EVENT_NOTSUPPORTED); return true; } bool BytraceEventParser::RegulatorDisableCompleteEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); - UNUSED(line); + Unused(args); + Unused(line); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, STAT_EVENT_RECEIVED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, STAT_EVENT_NOTSUPPORTED); return true; @@ -520,14 +576,14 @@ bool BytraceEventParser::RegulatorDisableCompleteEvent(const ArgsMap& args, cons bool BytraceEventParser::IpiEntryEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); + Unused(args); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IPI_ENTRY, STAT_EVENT_RECEIVED); streamFilters_->irqFilter_->IpiHandlerEntry(line.ts, line.cpu, traceDataCache_->GetDataIndex(line.argsStr)); return true; } bool BytraceEventParser::IpiExitEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); + Unused(args); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_IPI_EXIT, STAT_EVENT_RECEIVED); streamFilters_->irqFilter_->IpiHandlerExit(line.ts, line.cpu); return true; @@ -559,8 +615,8 @@ bool BytraceEventParser::IrqHandlerExitEvent(const ArgsMap& args, const BytraceL } bool BytraceEventParser::SoftIrqRaiseEvent(const ArgsMap& args, const BytraceLine& line) const { - UNUSED(args); - UNUSED(line); + Unused(args); + Unused(line); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_SOFTIRQ_RAISE, STAT_EVENT_RECEIVED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_SOFTIRQ_RAISE, STAT_EVENT_NOTSUPPORTED); return true; diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.h b/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.h index 9e1a83c5a002747ad64e1792311cf3220520bdf5..78d2dff39900d63504f1afc3a539ba1582d0d31f 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.h +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_event_parser.h @@ -79,6 +79,12 @@ private: bool BinderTransactionReceived(const ArgsMap& args, const BytraceLine& line) const; bool BinderTransactionAllocBufEvent(const ArgsMap& args, const BytraceLine& line) const; void GetDataSegArgs(BytraceLine& bufLine, ArgsMap& args, uint32_t& tgid) const; + void InterruptEventInitialization(); + void ClockEventInitialization(); + void CpuEventInitialization(); + void RegulatorEventInitialization(); + void BinderEventInitialization(); + void StackEventsInitialization(); std::map eventToFunctionMap_ = {}; const uint32_t MIN_SCHED_SWITCH_ARGS_COUNT = 6; 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 5e86ab0f95972141b801305f850df6000ef1e80f..f491f03eb1936fbada08fcf3f9b87f4e559db77b 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.cpp @@ -28,11 +28,6 @@ BytraceHilogParser::~BytraceHilogParser() = default; bool BytraceHilogParser::HilogTimeStrToTimestamp(std::string& timeStr, uint64_t& timeStamp) const { - 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 nsec; std::string usecStr; @@ -56,8 +51,7 @@ bool BytraceHilogParser::HilogTimeStrToTimestamp(std::string& timeStr, uint64_t& if (optionalYear.has_value()) { timeInfo.tm_year = optionalYear.value() - TM_YEAR_FROM; } else { - time_t tmNow; - tmNow = time(nullptr); + auto tmNow = time(nullptr); tm* ptmNow = localtime(&tmNow); timeInfo.tm_year = ptmNow->tm_year; } diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h index 59d3858e69b7a9a6a80d38e1624a1c9072c341ee..09bdf93404b1540c1043d44a0b16b2f07fd6d187 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_hilog_parser.h @@ -24,6 +24,11 @@ namespace SysTuning { namespace TraceStreamer { +constexpr uint64_t MS_TO_NS = 1e6; +constexpr uint64_t US_TO_NS = 1e3; +constexpr uint32_t TM_YEAR_FROM = 1900; +constexpr uint32_t MS_FORMAT_LEN = 3; +constexpr uint32_t US_FORMAT_LEN = 6; class BytraceHilogParser : public EventParserBase { public: BytraceHilogParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters); diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp index 466d2bbfe421a5ee83b5657efee41dd6b3333891..5cc2172bccd0deab414f891c7440b983e7c09d0c 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.cpp @@ -27,8 +27,8 @@ namespace SysTuning { namespace TraceStreamer { BytraceParser::BytraceParser(TraceDataCache* dataCache, const TraceStreamerFilters* filters, TraceFileType fileType) - : fileType_(fileType), - ParserBase(filters), + : ParserBase(filters), + fileType_(fileType), traceDataCache_(dataCache), eventParser_(std::make_unique(dataCache, filters)), hilogParser_(std::make_unique(dataCache, filters)), diff --git a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h index 324b48d5755d87f782a5f1210e7dccd2b73a16ff..a73a3d7c4164bdf19e428e39b8516d1c9ed8372e 100644 --- a/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h +++ b/trace_streamer/src/parser/bytrace_parser/bytrace_parser.h @@ -117,15 +117,14 @@ private: bool UpdateSplitPos(); private: - using ArgsMap = std::unordered_map; - bool isParsingOver_ = false; + TraceFileType fileType_ = TRACE_FILETYPE_BY_TRACE; TraceDataCache* traceDataCache_; std::unique_ptr eventParser_; std::unique_ptr hilogParser_; std::unique_ptr hiSysEventParser_; + bool isParsingOver_ = false; 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+):)"); - const std::string script_ = R"()"; size_t parsedTraceValidLines_ = 0; size_t parsedTraceInvalidLines_ = 0; @@ -148,7 +147,6 @@ private: bool isFirstLine_ = true; bool isHtmlTrace_ = false; bool isHtmlTraceContent_ = false; - TraceFileType fileType_ = TRACE_FILETYPE_BY_TRACE; int64_t seq_ = 1; uint64_t curFileOffset_ = 0; uint32_t curDataSize_ = 0; diff --git a/trace_streamer/src/parser/ebpf_parser/BUILD.gn b/trace_streamer/src/parser/ebpf_parser/BUILD.gn index 5bb61778bccca89b2aeb9b15cce485de1e9b8742..81b1ea633c67111202be05a37d07973ce0945f8a 100644 --- a/trace_streamer/src/parser/ebpf_parser/BUILD.gn +++ b/trace_streamer/src/parser/ebpf_parser/BUILD.gn @@ -43,6 +43,16 @@ ohos_source_set("ebpf_parser_src") { "${THIRD_PARTY}/sqlite/include", "${THIRD_PARTY}/bounds_checking_function/include", ] + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (is_mingw || is_mac) { include_dirs += [ "${THIRD_PARTY}/elfutils/libelf" ] } diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_base.h b/trace_streamer/src/parser/ebpf_parser/ebpf_base.h index 610a07b7558ae872c7e16cef2a1da756991b4dd9..152465aa85ef3af9fef98864f0c14236135c83d7 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_base.h +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_base.h @@ -19,7 +19,7 @@ #include #include "double_map.h" #include "ebpf_data_reader.h" -#include "ebpf_stdtype.h" +#include "ebpf_data_structure.h" #include "event_parser_base.h" #include "string_help.h" #include "string_to_numerical.h" diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.cpp b/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.cpp index 3d8adb170000b1084833c96c73a408abe5cc25b6..6ce7be3024fa3b86f4b79e0641bcc792d22e1f0f 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.cpp +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.cpp @@ -32,7 +32,7 @@ EbpfDataParser::~EbpfDataParser() static_cast(ebpfAllEventEndTime_)); } -bool EbpfDataParser::Init(const std::deque dequeBuffer, uint64_t size) +bool EbpfDataParser::Init(const std::deque& dequeBuffer, uint64_t size) { streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_EBPF, STAT_EVENT_RECEIVED); if (!ebpfDataReader_->InitEbpfData(dequeBuffer, size)) { diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.h b/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.h index 654313065b919e99d9c064805a34c177b09a3ce2..f6cebaf7c548a9e41056bd294a605a56c2955960 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.h +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_data_parser.h @@ -17,7 +17,7 @@ #include "bio_latency_data_parser.h" #include "ebpf_data_reader.h" #include "ebpf_splitter.h" -#include "ebpf_stdtype.h" +#include "ebpf_data_structure.h" #include "file_system_data_parser.h" #include "paged_memory_data_parser.h" #include "trace_data/trace_data_cache.h" @@ -55,7 +55,7 @@ public: } private: - bool Init(const std::deque dequeBuffer, uint64_t size); + bool Init(const std::deque& dequeBuffer, uint64_t size); std::unique_ptr ebpfDataReader_; uint64_t ebpfAllEventStartTime_ = std::numeric_limits::max(); uint64_t ebpfAllEventEndTime_ = 0; diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.cpp b/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.cpp index 0ef8b3f9afa9c0dff367b41025d7c9401e094603..9d4071b9ee753d9957379367b4e9170ab6dd2352 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.cpp +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.cpp @@ -134,19 +134,6 @@ bool EbpfDataReader::ReadItemEventMaps(const uint8_t* buffer, uint32_t size) } auto procMapsAddr = reinterpret_cast(buffer); pidAndStartAddrToMapsAddr_.Insert(procMapsAddr->pid, procMapsAddr->start, procMapsAddr); -#if WITH_EBPF_HELP - if ((procMapsAddr->fileNameLen > size - sizeof(MapsFixedHeader)) || !procMapsAddr->fileNameLen) { - TS_LOGE("maps fileNameLen error!!!"); - return false; - } - auto fileNameAddr = const_cast(reinterpret_cast(procMapsAddr + 1)); - fileNameAddr[procMapsAddr->fileNameLen - 1] = '\0'; - auto fileNameIndex = traceDataCache_->GetDataIndex(fileNameAddr); - - // add proc Maps Data - traceDataCache_->GetEbpfProcessMaps()->AppendNewData(procMapsAddr->start, procMapsAddr->end, procMapsAddr->offset, - procMapsAddr->pid, procMapsAddr->fileNameLen, fileNameIndex); -#endif return true; } template @@ -211,45 +198,7 @@ void EbpfDataReader::UpdateElfPathIndexToElfAddrMap(const ElfEventFixedHeader* e fileNameAddr[elfAddr->fileNameLen - 1] = '\0'; fileNameIndex = traceDataCache_->GetDataIndex(std::string(fileNameAddr)); elfPathIndexToElfFixedHeaderAddr_.insert(std::make_pair(fileNameIndex, elfAddr)); - -#if WITH_EBPF_HELP - // add Elf symbol Data - traceDataCache_->GetEbpfElf()->AppendNewData(elfId_, elfAddr->textVaddr, elfAddr->textOffset, elfAddr->strTabLen, - elfAddr->symTabLen, elfAddr->fileNameLen, elfAddr->symEntLen, - fileNameIndex); -#endif -} - -#if WITH_EBPF_HELP -template -void EbpfDataReader::AppendSymbolsToTable(T* firstSymbolAddr, const int size) -{ - for (auto i = 0; i < size; i++) { - auto symAddr = firstSymbolAddr + i; - if ((symAddr->st_info & STT_FUNC) && symAddr->st_value) { - traceDataCache_->GetEbpfElfSymbol()->AppendNewData(elfId_, symAddr->st_name, symAddr->st_value, - symAddr->st_size); - } - } -} -void EbpfDataReader::UpdateEbpfElfSymbolTable(const ElfEventFixedHeader* elfAddr, uint32_t size) -{ - if (size < sizeof(ElfEventFixedHeader) + elfAddr->strTabLen + elfAddr->symTabLen + elfAddr->fileNameLen) { - TS_LOGE("elf addr size error!!!"); - return; - } - auto symEntLen = elfAddr->symEntLen; - if (symEntLen == ELF32_SYM) { - AppendSymbolsToTable( - reinterpret_cast(reinterpret_cast(elfAddr + 1) + elfAddr->strTabLen), - elfAddr->symTabLen / symEntLen); - } else { - AppendSymbolsToTable( - reinterpret_cast(reinterpret_cast(elfAddr + 1) + elfAddr->strTabLen), - elfAddr->symTabLen / symEntLen); - } } -#endif bool EbpfDataReader::ReadItemSymbolInfo(const uint8_t* buffer, uint32_t size) { @@ -260,10 +209,6 @@ bool EbpfDataReader::ReadItemSymbolInfo(const uint8_t* buffer, uint32_t size) auto elfAddr = reinterpret_cast(buffer); UpdateElfAddrAndStValueToSymAddrMap(elfAddr, size); UpdateElfPathIndexToElfAddrMap(elfAddr, size); -#if WITH_EBPF_HELP - UpdateEbpfElfSymbolTable(elfAddr, size); - elfId_++; -#endif return true; } diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.h b/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.h index 20ad38a35d4c6286753e6692b8c5338137522ca2..ce38a823b4adba57db235b793024930d2cb1aa9a 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.h +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_data_reader.h @@ -21,7 +21,7 @@ #include #endif #include -#include "ebpf_stdtype.h" +#include "ebpf_data_structure.h" #include "event_parser_base.h" #include "process_filter.h" #include "quatra_map.h" @@ -63,11 +63,7 @@ private: void UpdateElfAddrAndStValueToSymAddrMap(const ElfEventFixedHeader* elfAddr, uint32_t size); void ReadKernelSymAddrMap(const KernelSymbolInfoHeader* elfAddr, uint32_t size); void UpdateElfPathIndexToElfAddrMap(const ElfEventFixedHeader* elfAddr, uint32_t size); -#if WITH_EBPF_HELP - template - void AppendSymbolsToTable(T* firstSymbolAddr, const int size); - void UpdateEbpfElfSymbolTable(const ElfEventFixedHeader* elfAddr, uint32_t size); -#endif + public: uint64_t maxKernelAddr_ = 0; uint64_t minKernelAddr_ = std::numeric_limits::max(); @@ -78,9 +74,6 @@ private: uint64_t unresolvedLen_ = 0; EbpfDataHeader* ebpfDataHeader_; uint8_t* startAddr_ = nullptr; -#if WITH_EBPF_HELP - uint64_t elfId_ = 0; -#endif std::multimap endTsToFsFixedHeader_ = {}; std::multimap endTsToPagedMemoryFixedHeader_ = {}; std::multimap endTsToBIOFixedHeader_ = {}; diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_stdtype.h b/trace_streamer/src/parser/ebpf_parser/ebpf_data_structure.h similarity index 100% rename from trace_streamer/src/parser/ebpf_parser/ebpf_stdtype.h rename to trace_streamer/src/parser/ebpf_parser/ebpf_data_structure.h diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.cpp b/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.cpp index fdbc017a2f8674d47b2b22b708c4c36fb7c231b7..7ac414796575d8e2d368dee95b5c7563258ae2ad 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.cpp +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.cpp @@ -55,7 +55,6 @@ bool EbpfSplitter::SplitEbpfHeader(std::deque& dequeBuffer) bool EbpfSplitter::AddAndSplitEbpfData(std::deque& dequeBuffer) { - if (!splitEbpfHeader_) { HtraceSplitResult ebpfHtraceHead = {.type = (int32_t)SplitDataDataType::SPLIT_FILE_DATA, .buffer = {.address = reinterpret_cast(&profilerHeader_), diff --git a/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.h b/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.h index a795b3578dbb07ee1d05ac64f8e4c98a125655e6..604ea10d3c150899662c386757515013b6443e08 100644 --- a/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.h +++ b/trace_streamer/src/parser/ebpf_parser/ebpf_splitter.h @@ -21,7 +21,7 @@ #include #endif #include -#include "ebpf_stdtype.h" +#include "ebpf_data_structure.h" #include "event_parser_base.h" #include "process_filter.h" #include "quatra_map.h" diff --git a/trace_streamer/src/parser/ebpf_parser/paged_memory_data_parser.h b/trace_streamer/src/parser/ebpf_parser/paged_memory_data_parser.h index e68991d139da645e8d1ccd2383801415d6e7adeb..7abbba2c9a9533d85795931653d9b4fe85111bc2 100644 --- a/trace_streamer/src/parser/ebpf_parser/paged_memory_data_parser.h +++ b/trace_streamer/src/parser/ebpf_parser/paged_memory_data_parser.h @@ -17,7 +17,7 @@ #include "clock_filter_ex.h" #include "ebpf_base.h" #include "ebpf_data_reader.h" -#include "ebpf_stdtype.h" +#include "ebpf_data_structure.h" #include "event_parser_base.h" #include "htrace_plugin_time_parser.h" diff --git a/trace_streamer/src/parser/hiperf_parser/BUILD.gn b/trace_streamer/src/parser/hiperf_parser/BUILD.gn index 0a54394f5347dae10ff11c6d77e0b5b6ce0229b2..f621b6bf1738ffc9726dd643686ffeb25d5d71f7 100644 --- a/trace_streamer/src/parser/hiperf_parser/BUILD.gn +++ b/trace_streamer/src/parser/hiperf_parser/BUILD.gn @@ -64,6 +64,16 @@ ohos_source_set("hiperf_parser_src") { "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/nonlinux", "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/innerkits/unwinder/include", ] + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] include_dirs += [ "${THIRD_PARTY}/libunwind/include" ] if (is_mingw || is_mac) { include_dirs += [ "${THIRD_PARTY}/libbpf/include/uapi" ] 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 b848eb277fae8cecce7f3730e3f92f89cdcdfcbf..3f39cf8c3f1e32a7025d7e272afe9fceaf8627bd 100644 --- a/trace_streamer/src/parser/hiperf_parser/perf_data_parser.cpp +++ b/trace_streamer/src/parser/hiperf_parser/perf_data_parser.cpp @@ -32,7 +32,7 @@ PerfDataParser::PerfDataParser(TraceDataCache* dataCache, const TraceStreamerFil { SymbolsFile::onRecording_ = false; } -uint64_t PerfDataParser::InitPerfDataAndLoad(const std::deque dequeBuffer, +uint64_t PerfDataParser::InitPerfDataAndLoad(const std::deque& dequeBuffer, uint64_t size, uint64_t offset, bool isSplitFile, @@ -139,7 +139,6 @@ bool PerfDataParser::SplitPerfParsingHead(const std::deque& dequeBuffer return false; } - uint64_t lengthRemain = size; std::copy_n(dequeBuffer.begin(), sizeof(perf_file_header), reinterpret_cast(&perfHeader_)); if (memcmp(perfHeader_.magic, PERF_MAGIC, sizeof(perfHeader_.magic))) { @@ -164,8 +163,6 @@ bool PerfDataParser::SplitPerfParsingHead(const std::deque& dequeBuffer .type = (int32_t)SplitDataDataType::SPLIT_FILE_DATA, .buffer = {.address = reinterpret_cast(&perfHeader_), .size = sizeof(perf_file_header)}}; splitResult_.emplace_back(perfHead); - - lengthRemain -= sizeof(perf_file_header); processedLen += sizeof(perf_file_header); splitState_ = SplitPerfState::WAIT_FOR_ATTR; return true; 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 35bdc9c3e80a6ae73a8e32dcc76957e4bc6ec2d3..74653caca241630f22f9d7a6e5df54320c98dffa 100644 --- a/trace_streamer/src/parser/hiperf_parser/perf_data_parser.h +++ b/trace_streamer/src/parser/hiperf_parser/perf_data_parser.h @@ -53,7 +53,7 @@ class PerfDataParser : public EventParserBase, public HtracePluginTimeParser { public: PerfDataParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx); ~PerfDataParser(); - uint64_t InitPerfDataAndLoad(const std::deque dequeBuffer, + uint64_t InitPerfDataAndLoad(const std::deque& dequeBuffer, uint64_t size, uint64_t offset, bool isSplitFile, diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn b/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn index 54d77d20280b0237c864bce2e1cd7e1fffbfd7c9..07e2e3fd1930494ecc8de3a127e32f0f0d76e174 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn +++ b/trace_streamer/src/parser/htrace_pbreader_parser/BUILD.gn @@ -79,6 +79,16 @@ ohos_source_set("htrace_pbreader_parser_src") { "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/nonlinux", "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/innerkits/unwinder/include", ] + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (is_mingw || is_mac) { include_dirs += [ "${THIRD_PARTY}/elfutils/libelf", diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_clock_detail_parser.cpp b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_clock_detail_parser.cpp index 99203728b68c3554d2dd69110e2fdbd27f888b3d..0e5e0b5444216b36c40cf75e190e32c1f2cd386b 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_clock_detail_parser.cpp +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_clock_detail_parser.cpp @@ -18,7 +18,6 @@ #include "measure_filter.h" #include "process_filter.h" #include "stat_filter.h" -#include "symbols_filter.h" #include namespace SysTuning { 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 95ed4602fa196eda49401acb1b8af818a169ae31..a3e420bf143fa741b19747158b4716aaa7ed8f04 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 @@ -36,7 +36,6 @@ #include "signal.pbreader.h" #include "slice_filter.h" #include "stat_filter.h" -#include "symbols_filter.h" #include "system_event_measure_filter.h" #include "task.pbreader.h" #include "thread_state_flag.h" @@ -493,7 +492,7 @@ bool HtraceEventParser::SchedWakeupEvent(const EventInfo& event) const instants->AppendInstantEventData(event.timeStamp_, schedWakeupName_, internalTid, wakeupFromPid); streamFilters_->cpuFilter_->InsertWakeupEvent(event.timeStamp_, internalTid); uint32_t targetCpu = msg.target_cpu(); - traceDataCache_->GetRawData()->AppendRawData(0, event.timeStamp_, RAW_SCHED_WAKEUP, targetCpu, internalTid); + traceDataCache_->GetRawData()->AppendRawData(event.timeStamp_, RAW_SCHED_WAKEUP, targetCpu, internalTid); return true; } bool HtraceEventParser::SchedWakeupNewEvent(const EventInfo& event) const @@ -507,7 +506,7 @@ bool HtraceEventParser::SchedWakeupNewEvent(const EventInfo& event) const instants->AppendInstantEventData(event.timeStamp_, schedWakeupNewName_, internalTid, wakeupFromPid); streamFilters_->cpuFilter_->InsertWakeupEvent(event.timeStamp_, internalTid); uint32_t targetCpu = msg.target_cpu(); - traceDataCache_->GetRawData()->AppendRawData(0, event.timeStamp_, RAW_SCHED_WAKEUP, targetCpu, internalTid); + traceDataCache_->GetRawData()->AppendRawData(event.timeStamp_, RAW_SCHED_WAKEUP, targetCpu, internalTid); return true; } bool HtraceEventParser::SchedWakingEvent(const EventInfo& event) const @@ -521,7 +520,7 @@ bool HtraceEventParser::SchedWakingEvent(const EventInfo& event) const streamFilters_->cpuFilter_->InsertWakeupEvent(event.timeStamp_, internalTid, true); instants->AppendInstantEventData(event.timeStamp_, schedWakingName_, internalTid, wakeupFromPid); uint32_t targetCpu = msg.target_cpu(); - traceDataCache_->GetRawData()->AppendRawData(0, event.timeStamp_, RAW_SCHED_WAKING, targetCpu, wakeupFromPid); + traceDataCache_->GetRawData()->AppendRawData(event.timeStamp_, RAW_SCHED_WAKING, targetCpu, wakeupFromPid); return true; } bool HtraceEventParser::CpuIdleEvent(const EventInfo& event) const @@ -545,7 +544,7 @@ bool HtraceEventParser::CpuIdleEvent(const EventInfo& event) const config_.GetStateValue(newStateValue.value())); // Add cpu_idle event to raw_data_table - traceDataCache_->GetRawData()->AppendRawData(0, event.timeStamp_, RAW_CPU_IDLE, eventCpuValue.value(), 0); + traceDataCache_->GetRawData()->AppendRawData(event.timeStamp_, RAW_CPU_IDLE, eventCpuValue.value(), 0); return true; } bool HtraceEventParser::CpuFrequencyEvent(const EventInfo& event) const @@ -590,9 +589,9 @@ bool HtraceEventParser::SuspendResumeEvent(const EventInfo& event) const int32_t val = msg.val(); uint32_t start = msg.start(); std::string action = msg.action().ToStdString(); - UNUSED(val); - UNUSED(start); - UNUSED(action); + Unused(val); + Unused(start); + Unused(action); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SUSPEND_RESUME, STAT_EVENT_NOTSUPPORTED); return true; } @@ -600,7 +599,7 @@ bool HtraceEventParser::WorkqueueExecuteStartEvent(const EventInfo& event) const { ProtoReader::WorkqueueExecuteStartFormat_Reader msg(event.detail_); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_START, STAT_EVENT_RECEIVED); - auto funcNameIndex = streamFilters_->symbolsFilter_->GetFunc(msg.function()); + auto funcNameIndex = traceDataCache_->GetSymbolsData()->GetFunc(msg.function()); size_t result = INVALID_UINT32; const auto& taskName = traceDataCache_->GetDataFromDict(event.taskNameIndex_); if (funcNameIndex == INVALID_UINT64) { @@ -754,23 +753,6 @@ bool HtraceEventParser::OomScoreAdjUpdate(const EventInfo& event) const return true; } -bool HtraceEventParser::SignalGenerateEvent(const EventInfo& event) const -{ - streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_BLOCK_BIO_BACKMERGE, STAT_EVENT_RECEIVED); - ProtoReader::SignalGenerateFormat_Reader msg(event.detail_); - InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThreadWithName(event.timeStamp_, msg.pid(), - msg.comm().ToStdString()); - streamFilters_->threadFilter_->AppendNewMeasureData(internalTid, signalGenerateId_, event.timeStamp_, msg.sig()); - return true; -} -bool HtraceEventParser::SignalDeleverEvent(const EventInfo& event) const -{ - streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_BLOCK_BIO_BACKMERGE, STAT_EVENT_RECEIVED); - ProtoReader::SignalDeliverFormat_Reader msg(event.detail_); - InternalTid internalTid = streamFilters_->processFilter_->UpdateOrCreateThread(event.timeStamp_, event.tgid_); - streamFilters_->threadFilter_->AppendNewMeasureData(internalTid, signalDeliverId_, event.timeStamp_, msg.sig()); - return true; -} void HtraceEventParser::FilterAllEventsReader() { #ifdef SUPPORTTHREAD @@ -853,7 +835,6 @@ void HtraceEventParser::ProtoReaderDealEvent(EventInfo* eventInfo) void HtraceEventParser::Clear() { const_cast(streamFilters_)->FilterClear(); - streamFilters_->symbolsFilter_->Clear(); streamFilters_->sysEventMemMeasureFilter_->Clear(); streamFilters_->sysEventVMemMeasureFilter_->Clear(); printEventParser_.Finish(); diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.h b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.h index 881e1f884784d6afff30c1b87a846909457c2328..b11ddd0b81b74c0b62882d69c13b690f6f735b3c 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.h +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_event_parser/htrace_event_parser.h @@ -100,8 +100,6 @@ private: bool SysEnterEvent(const EventInfo& event) const; bool SysExitEvent(const EventInfo& event) const; bool OomScoreAdjUpdate(const EventInfo& event) const; - bool SignalGenerateEvent(const EventInfo& event) const; - bool SignalDeleverEvent(const EventInfo& event) const; using FuncCall = std::function; std::map eventToFunctionMap_ = {}; std::unordered_set tids_ = {}; diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_js_memory_parser.h b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_js_memory_parser.h index 4b6deab448a27810f676d06545e9222ece3290f0..4a9d37c3d52ceec5d4930c9ac219da455d5767a7 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_js_memory_parser.h +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_js_memory_parser.h @@ -122,7 +122,7 @@ private: uint32_t nodeFileId_ = INVALID_UINT32; uint32_t nodeCount_ = 0; bool hasCpuProfiler_ = false; - SnapShotData snapShotData_; + SnapShotData snapShotData_ = {}; bool curTypeIsCpuProfile_ = false; }; } // namespace TraceStreamer diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_mem_parser.cpp b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_mem_parser.cpp index 1b0dcc51b8c6c2947be419cb212538c9dc792d96..2e38a6742567fc4c01a26427d7806c6ed50afa91 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_mem_parser.cpp +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_mem_parser.cpp @@ -21,7 +21,6 @@ #include "memory_plugin_result.pbreader.h" #include "process_filter.h" #include "stat_filter.h" -#include "symbols_filter.h" #include "system_event_measure_filter.h" namespace SysTuning { diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.cpp b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.cpp index 38a9a53f3cbb597af8ed521917483969a978c0b7..320335edf781a14e5b01f498e38e23795b5449b6 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.cpp +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.cpp @@ -55,7 +55,7 @@ HtraceParser::HtraceParser(TraceDataCache* dataCache, const TraceStreamerFilters dataSegArray_ = std::make_unique(1); } } -void HtraceParser::ParserFileSO(std::string& directory, std::vector& relativeFilePaths) +void HtraceParser::ParserFileSO(std::string& directory, const std::vector& relativeFilePaths) { for (const auto& filePath : relativeFilePaths) { auto absoluteFilePath = filePath.substr(directory.length()); @@ -606,12 +606,13 @@ bool HtraceParser::ParseDataRecursively(std::deque::iterator& packagesB #endif } } + std::string bufferLine; while (true) { if (!hasGotSegLength_) { if (currentLength < packetSegLength) { break; } - std::string bufferLine(packagesBegin, packagesBegin + packetSegLength); + bufferLine.assign(packagesBegin, packagesBegin + packetSegLength); const uint32_t* len = reinterpret_cast(bufferLine.data()); nextLength_ = *len; lenBuffer_ = bufferLine; @@ -626,7 +627,7 @@ bool HtraceParser::ParseDataRecursively(std::deque::iterator& packagesB if (currentLength < nextLength_) { break; } - std::string bufferLine(packagesBegin, packagesBegin + nextLength_); + bufferLine.assign(packagesBegin, packagesBegin + nextLength_); ParseTraceDataItem(bufferLine); hasGotSegLength_ = false; packagesBegin += nextLength_; @@ -718,7 +719,7 @@ bool HtraceParser::InitProfilerTraceFileHeader() return false; } uint8_t buffer[packetHeaderLength]; - (void)memset_s(buffer, packetHeaderLength, 0, packetHeaderLength); + (void)memset_s(buffer, sizeof(buffer), 0, sizeof(buffer)); int32_t i = 0; for (auto it = packagesBuffer_.begin(); it != packagesBuffer_.begin() + packetHeaderLength; ++it, ++i) { buffer[i] = *it; diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.h b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.h index 03ee05f1bf9eca62fb9064d360c234e66e77f0c2..9ffb4f9c08dc075aeaaa4d01dd7d3bab770e8b7c 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.h +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_parser.h @@ -61,7 +61,7 @@ public: bool ReparseSymbolFilesAndResymbolization(std::string& symbolsPath, std::vector& symbolsPaths); void WaitForParserEnd(); void EnableFileSeparate(bool enabled); - void ParserFileSO(std::string& directory, std::vector& relativeFilePaths); + void ParserFileSO(std::string& directory, const std::vector& relativeFilePaths); void TraceDataSegmentEnd(bool isSplitFile); void StoreTraceDataSegment(std::unique_ptr bufferStr, size_t size, int32_t isFinish); const auto& GetTraceDataHtrace() @@ -163,9 +163,9 @@ private: std::unique_ptr jsMemoryParser_; std::unique_ptr perfDataParser_; std::unique_ptr ebpfDataParser_; + std::unique_ptr dataSegArray_; std::atomic filterThreadStarted_{false}; const int32_t maxSegArraySize = 10000; - std::unique_ptr dataSegArray_; int32_t rawDataHead_ = 0; bool toExit_ = false; bool exited_ = false; diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.cpp b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.cpp index b433edcfcb129910b6a2e0036088013b0371604d..0dbd003aae9f5ed4d57ea5874aac064e970fcc74 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.cpp +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.cpp @@ -90,7 +90,7 @@ void HtraceProcessParser::Finish() traceDataCache_->GetLiveProcessData()->AppendNewData( (*itor)->ts_, dur, (*itor)->processInfo_->pid, (*itor)->processInfo_->name, (*itor)->processInfo_->ppid, (*itor)->processInfo_->uid, std::to_string((*itor)->processInfo_->uid), (*itor)->cpuUsageData_->cpuUsage, - (*itor)->pssInfo_->pssInfo, (*itor)->cpuUsageData_->cpu_time_ms_, (*itor)->cpuUsageData_->threadSum, + (*itor)->pssInfo_->pssInfo, (*itor)->cpuUsageData_->cpuTimeMs, (*itor)->cpuUsageData_->threadSum, (*itor)->diskio_->wbytes, (*itor)->diskio_->rbytes); } liveProcessData_.clear(); diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.h b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.h index f9b1b5ddf778986c5eec7d11872d633f44682bd2..121d4f7cc21ade7bafeba927003b818ee34375d7 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.h +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_process_parser.h @@ -60,13 +60,13 @@ public: int32_t pssInfo; }; struct CpuInfo { - CpuInfo(double cpuUsage, int32_t threadSum, uint64_t cpu_time_ms) - : cpuUsage(cpuUsage), threadSum(threadSum), cpu_time_ms_(cpu_time_ms) + CpuInfo(double cpuUsage, int32_t threadSum, uint64_t cpuTimeMs) + : cpuUsage(cpuUsage), threadSum(threadSum), cpuTimeMs(cpuTimeMs) { } double cpuUsage; int32_t threadSum; - uint64_t cpu_time_ms_; + uint64_t cpuTimeMs; }; struct ProcessInfo { ProcessInfo(int32_t pid, const std::string& name, int32_t ppid, int32_t uid) diff --git a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_symbols_detail_parser.cpp b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_symbols_detail_parser.cpp index 08d5f337cbd8f627230f6d8fa30c50349f486b3a..8fb6ac953d02df3ceef9ef7b96e186a4d63a3338 100644 --- a/trace_streamer/src/parser/htrace_pbreader_parser/htrace_symbols_detail_parser.cpp +++ b/trace_streamer/src/parser/htrace_pbreader_parser/htrace_symbols_detail_parser.cpp @@ -14,13 +14,12 @@ */ #include "htrace_symbols_detail_parser.h" #include "htrace_event_parser.h" -#include "symbols_filter.h" namespace SysTuning { namespace TraceStreamer { HtraceSymbolsDetailParser::HtraceSymbolsDetailParser(TraceDataCache* dataCache, const TraceStreamerFilters* ctx) : streamFilters_(ctx), traceDataCache_(dataCache) { - UNUSED(traceDataCache_); + Unused(traceDataCache_); if (!streamFilters_) { TS_LOGF("streamFilters_ should not be null"); return; @@ -39,8 +38,8 @@ void HtraceSymbolsDetailParser::Parse(ProtoReader::BytesView tracePacket) } for (auto i = reader.symbols_detail(); i; ++i) { ProtoReader::SymbolsDetailMsg_Reader reader(i->ToBytes()); - streamFilters_->symbolsFilter_->RegisterFunc(reader.symbol_addr(), - traceDataCache_->GetDataIndex(reader.symbol_name().ToStdString())); + traceDataCache_->GetSymbolsData()->UpdateSymbol( + reader.symbol_addr(), traceDataCache_->GetDataIndex(reader.symbol_name().ToStdString())); } } } // namespace TraceStreamer diff --git a/trace_streamer/src/parser/rawtrace_parser/BUILD.gn b/trace_streamer/src/parser/rawtrace_parser/BUILD.gn index bd143085d01bec1e47e49d6a7fb9a46ac123470c..89974950dd7618619e77d199792638138ef235aa 100755 --- a/trace_streamer/src/parser/rawtrace_parser/BUILD.gn +++ b/trace_streamer/src/parser/rawtrace_parser/BUILD.gn @@ -33,6 +33,16 @@ config("rawtrace_parser_comm") { "${PERF_DIR}/profiler/device/plugins/ftrace_plugin/include", "${COMMON_LIBRARY}/c_utils/base/include", ] + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] } ohos_source_set("rawtrace_parser_src") { diff --git a/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.cpp b/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.cpp index c8ad2ccbf39119d212dcee2c5ee1c6af91811e0d..35a815b3ae563ad2b1f5d1372fbb4a642029591e 100644 --- a/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.cpp +++ b/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.cpp @@ -25,7 +25,6 @@ #include "process_filter.h" #include "slice_filter.h" #include "stat_filter.h" -#include "symbols_filter.h" #include "system_event_measure_filter.h" #include "ftrace_event_processor.h" #include "string_to_numerical.h" @@ -168,7 +167,6 @@ bool CpuDetailParser::FilterAllEvents(FtraceCpuDetailMsg& cpuDetail, bool isFini void CpuDetailParser::Clear() { const_cast(streamFilters_)->FilterClear(); - streamFilters_->symbolsFilter_->Clear(); streamFilters_->sysEventMemMeasureFilter_->Clear(); streamFilters_->sysEventVMemMeasureFilter_->Clear(); printEventParser_.Finish(); @@ -210,7 +208,6 @@ bool CpuDetailParser::SchedBlockReasonEvent(const RawTraceEventInfo& event) { auto reasonMsg = event.msgPtr->sched_blocked_reason_format(); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SCHED_BLOCKED_REASON, STAT_EVENT_RECEIVED); - uint32_t ioWait = reasonMsg.io_wait(); auto caller = traceDataCache_->GetDataIndex( std::string_view("0x" + SysTuning::base::number(reasonMsg.caller(), SysTuning::base::INTEGER_RADIX_TYPE_HEX))); auto itid = streamFilters_->processFilter_->UpdateOrCreateThread(event.msgPtr->timestamp(), reasonMsg.pid()); @@ -232,7 +229,7 @@ bool CpuDetailParser::SchedWakeupEvent(const RawTraceEventInfo& event) const streamFilters_->processFilter_->UpdateOrCreateThread(event.msgPtr->timestamp(), eventTid_); instants->AppendInstantEventData(event.msgPtr->timestamp(), schedWakeupIndex_, internalTid, wakeupFromPid); streamFilters_->cpuFilter_->InsertWakeupEvent(event.msgPtr->timestamp(), internalTid); - traceDataCache_->GetRawData()->AppendRawData(0, event.msgPtr->timestamp(), RAW_SCHED_WAKEUP, wakeupMsg.target_cpu(), + traceDataCache_->GetRawData()->AppendRawData(event.msgPtr->timestamp(), RAW_SCHED_WAKEUP, wakeupMsg.target_cpu(), internalTid); return true; } @@ -246,8 +243,8 @@ bool CpuDetailParser::SchedWakingEvent(const RawTraceEventInfo& event) const auto wakeupFromPid = streamFilters_->processFilter_->UpdateOrCreateThread(event.msgPtr->timestamp(), eventTid_); streamFilters_->cpuFilter_->InsertWakeupEvent(event.msgPtr->timestamp(), internalTid, true); instants->AppendInstantEventData(event.msgPtr->timestamp(), schedWakingIndex_, internalTid, wakeupFromPid); - traceDataCache_->GetRawData()->AppendRawData(0, event.msgPtr->timestamp(), RAW_SCHED_WAKING, - wakeingMsg.target_cpu(), wakeupFromPid); + traceDataCache_->GetRawData()->AppendRawData(event.msgPtr->timestamp(), RAW_SCHED_WAKING, wakeingMsg.target_cpu(), + wakeupFromPid); return true; } bool CpuDetailParser::SchedWakeupNewEvent(const RawTraceEventInfo& event) const @@ -260,8 +257,8 @@ bool CpuDetailParser::SchedWakeupNewEvent(const RawTraceEventInfo& event) const auto wakeupFromPid = streamFilters_->processFilter_->UpdateOrCreateThread(event.msgPtr->timestamp(), eventTid_); instants->AppendInstantEventData(event.msgPtr->timestamp(), schedWakeupNewIndex_, internalTid, wakeupFromPid); streamFilters_->cpuFilter_->InsertWakeupEvent(event.msgPtr->timestamp(), internalTid); - traceDataCache_->GetRawData()->AppendRawData(0, event.msgPtr->timestamp(), RAW_SCHED_WAKEUP, - wakeupNewMsg.target_cpu(), internalTid); + traceDataCache_->GetRawData()->AppendRawData(event.msgPtr->timestamp(), RAW_SCHED_WAKEUP, wakeupNewMsg.target_cpu(), + internalTid); return true; } bool CpuDetailParser::ProcessExitEvent(const RawTraceEventInfo& event) const @@ -395,7 +392,7 @@ bool CpuDetailParser::CpuIdleEvent(const RawTraceEventInfo& event) const config_.GetStateValue(newState.value())); // Add cpu_idle event to raw_data_table - traceDataCache_->GetRawData()->AppendRawData(0, event.msgPtr->timestamp(), RAW_CPU_IDLE, eventCpu.value(), 0); + traceDataCache_->GetRawData()->AppendRawData(event.msgPtr->timestamp(), RAW_CPU_IDLE, eventCpu.value(), 0); return true; } bool CpuDetailParser::CpuFrequencyEvent(const RawTraceEventInfo& event) const @@ -437,9 +434,9 @@ bool CpuDetailParser::SuspendResumeEvent(const RawTraceEventInfo& event) const int32_t val = resumeMsg.val(); uint32_t start = resumeMsg.start(); std::string action = resumeMsg.action(); - UNUSED(val); - UNUSED(start); - UNUSED(action); + Unused(val); + Unused(start); + Unused(action); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_SUSPEND_RESUME, STAT_EVENT_NOTSUPPORTED); return true; } @@ -447,7 +444,7 @@ bool CpuDetailParser::WorkqueueExecuteStartEvent(const RawTraceEventInfo& event) { auto executeStartMsg = event.msgPtr->workqueue_execute_start_format(); streamFilters_->statFilter_->IncreaseStat(TRACE_EVENT_WORKQUEUE_EXECUTE_START, STAT_EVENT_RECEIVED); - auto funcNameIndex = streamFilters_->symbolsFilter_->GetFunc(executeStartMsg.function()); + auto funcNameIndex = traceDataCache_->GetSymbolsData()->GetFunc(executeStartMsg.function()); size_t result = INVALID_UINT32; if (funcNameIndex == INVALID_UINT64) { std::string addrStr = "0x" + base::number(executeStartMsg.function(), base::INTEGER_RADIX_TYPE_HEX); @@ -557,14 +554,14 @@ bool CpuDetailParser::ClockDisableEvent(const RawTraceEventInfo& event) const } bool CpuDetailParser::RegulatorSetVoltageEvent(const RawTraceEventInfo& event) const { - UNUSED(event); + Unused(event); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE, STAT_EVENT_NOTSUPPORTED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE, STAT_EVENT_RECEIVED); return true; } bool CpuDetailParser::RegulatorSetVoltageCompleteEvent(const RawTraceEventInfo& event) const { - UNUSED(event); + Unused(event); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, STAT_EVENT_NOTSUPPORTED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_SET_VOLTAGE_COMPLETE, STAT_EVENT_RECEIVED); @@ -572,14 +569,14 @@ bool CpuDetailParser::RegulatorSetVoltageCompleteEvent(const RawTraceEventInfo& } bool CpuDetailParser::RegulatorDisableEvent(const RawTraceEventInfo& event) const { - UNUSED(event); + Unused(event); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE, STAT_EVENT_NOTSUPPORTED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE, STAT_EVENT_RECEIVED); return true; } bool CpuDetailParser::RegulatorDisableCompleteEvent(const RawTraceEventInfo& event) const { - UNUSED(event); + Unused(event); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, STAT_EVENT_NOTSUPPORTED); traceDataCache_->GetStatAndInfo()->IncreaseStat(TRACE_EVENT_REGULATOR_DISABLE_COMPLETE, STAT_EVENT_RECEIVED); return true; diff --git a/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.h b/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.h index d2203164753bd75298ecb295b4544e91afbd8b2f..bb546d1862a676ec2acf35c6dc13960561e2d67e 100644 --- a/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.h +++ b/trace_streamer/src/parser/rawtrace_parser/cpu_detail_parser.h @@ -75,14 +75,17 @@ private: private: using FuncCall = std::function; + const TraceStreamerFilters* streamFilters_; + TraceDataCache* traceDataCache_; + PrintEventParser printEventParser_; + uint32_t eventPid_ = INVALID_UINT32; uint32_t eventTid_ = INVALID_UINT32; uint64_t lastOverwrite_ = 0; - PrintEventParser printEventParser_; + std::deque> rawTraceEventList_ = {}; std::map eventToFunctionMap_ = {}; - const TraceStreamerFilters* streamFilters_; - TraceDataCache* traceDataCache_; + TraceStreamerConfig config_{}; const BuiltinClocks clock_ = TS_CLOCK_BOOTTIME; const DataIndex schedWakeupIndex_ = traceDataCache_->GetDataIndex("sched_wakeup"); diff --git a/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.cpp b/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.cpp index 86863f3a79e29a6f214cdcedad3ddab235eac36e..dbd7764c349a4a970683334efce66b13589048ce 100644 --- a/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.cpp +++ b/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.cpp @@ -61,9 +61,9 @@ bool ReadInfo(uint8_t* startPtr[], uint8_t* endPtr, void* outData, size_t outSiz namespace SysTuning { namespace TraceStreamer { FtraceProcessor::FtraceProcessor() + : fixedCharArrayRegex_(std::regex(R"(char \w+\[\d+\])")), + flexDataLocArrayRegex_(std::regex(R"(__data_loc [a-zA-Z_0-9 ]+\[\] \w+)")) { - fixedCharArrayRegex_ = std::regex(R"(char \w+\[\d+\])"); - flexDataLocArrayRegex_ = std::regex(R"(__data_loc [a-zA-Z_0-9 ]+\[\] \w+)"); } FtraceProcessor::~FtraceProcessor() @@ -97,7 +97,7 @@ bool FtraceProcessor::HandleHeaderPageFormat(const std::string& formatInfo) TS_CHECK_TRUE(HandleEventFormat(formatInfo, format), false, "handle events/header_page failed!"); bool commitExist = false; - for (auto& curField : format.fields) { + for (const auto& curField : format.fields) { if (curField.name == "timestamp") { pageHeaderFormat_.timestamp = curField; } else if (curField.name == "commit") { @@ -650,8 +650,7 @@ bool FtraceProcessor::HmParsePageData(FtraceCpuDetailMsg& cpuMsg, CpuDetailParse uint64_t timeStampBase = rmqData->timeStamp; RmqEntry* event; HmTraceHeader* header; - unsigned int evtSize; - unsigned int eventId; + EventFormat format = {}; cpuMsg.set_cpu(rmqData->coreId); @@ -661,13 +660,13 @@ bool FtraceProcessor::HmParsePageData(FtraceCpuDetailMsg& cpuMsg, CpuDetailParse auto endPtr = rmqData->data + rmqData->length; while (curPtr < endPtr) { event = (struct RmqEntry*)curPtr; - evtSize = event->size; + auto evtSize = event->size; if (evtSize == 0U) { break; } header = reinterpret_cast(event->data); - eventId = header->commonType; + auto eventId = header->commonType; if (!GetEventFormatById(eventId, format)) { curPtr += RmqEntryTotalSize(evtSize); TS_LOGD("mark.debug. evtId = %u evtSize = %u", eventId, evtSize); diff --git a/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.h b/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.h index 2389f6854453e5c9fbed67df62ee57f14e5925bc..8ab2720d2f3eeeb70d2d9e6dc82d15c6a4a9fb31 100644 --- a/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.h +++ b/trace_streamer/src/parser/rawtrace_parser/ftrace_processor.h @@ -37,11 +37,11 @@ public: bool SetupEvent(const std::string& desc); - bool HandlePage(FtraceCpuDetailMsg& cpuDetailMsg, + bool HandlePage(FtraceCpuDetailMsg& cpuMsg, CpuDetailParser& cpuDetailParser, uint8_t page[], size_t size = FTRACE_PAGE_SIZE); - bool HmParsePageData(FtraceCpuDetailMsg& cpuDetailMsg, CpuDetailParser& cpuDetailParser, uint8_t*& data); + bool HmParsePageData(FtraceCpuDetailMsg& cpuMsg, CpuDetailParser& cpuDetailParser, uint8_t*& data); bool HandleTgids(const std::string& tgids); bool HandleCmdlines(const std::string& cmdlines); @@ -64,7 +64,7 @@ public: bool HandleTimeExtend(const FtraceEventHeader& eventHeader); bool HandleTimeStamp(const FtraceEventHeader& eventHeader); bool HandleDataRecord(const FtraceEventHeader& eventHeader, - FtraceCpuDetailMsg& cpuDetailMsg, + FtraceCpuDetailMsg& cpuMsg, CpuDetailParser& cpuDetailParser); bool HandleFtraceEvent(FtraceEvent& ftraceEvent, uint8_t data[], size_t dataSize, const EventFormat& format); diff --git a/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.cpp b/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.cpp index 7c3ebf0584460843816b6f34551e6c1cc37f4075..14b818d21705dd89ec11fdde52b7adbfa5c8f6c1 100644 --- a/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.cpp +++ b/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.cpp @@ -15,7 +15,6 @@ #include "kernel_symbols_processor.h" #include "log.h" -#include "symbols_filter.h" #include "string_help.h" #include "string_to_numerical.h" @@ -71,7 +70,7 @@ bool KernelSymbolsProcessor::HandleKallSyms(const std::string& kallsyms) symbol.name = symbol.name.substr(0, symbol.name.size() - (sizeof(".cfi") - 1)); } if (IsValidKernelSymbol(symbol)) { - streamFilters_->symbolsFilter_->RegisterFunc(symbol.addr, traceDataCache_->GetDataIndex(symbol.name)); + traceDataCache_->GetSymbolsData()->UpdateSymbol(symbol.addr, traceDataCache_->GetDataIndex(symbol.name)); } } return true; diff --git a/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.h b/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.h index 49a0eecef3034a0f89d0aab470e35502e7332353..252bd954628480051a0978ed559d2839170e1a2a 100644 --- a/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.h +++ b/trace_streamer/src/parser/rawtrace_parser/kernel_symbols_processor.h @@ -41,8 +41,8 @@ private: static bool IsValidKernelSymbol(const KernelSymbol& symbol); private: - const TraceStreamerFilters* streamFilters_; TraceDataCache* traceDataCache_; + const TraceStreamerFilters* streamFilters_; }; } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/parser/rawtrace_parser/rawtrace_parser.h b/trace_streamer/src/parser/rawtrace_parser/rawtrace_parser.h index 0987fdb549e8d021dec7ca62994fdf69a7137a6c..4eb01a640834dcd0a212961dc0912cf8f1fbfc1d 100644 --- a/trace_streamer/src/parser/rawtrace_parser/rawtrace_parser.h +++ b/trace_streamer/src/parser/rawtrace_parser/rawtrace_parser.h @@ -32,7 +32,7 @@ public: void WaitForParserEnd(); private: - bool ParseDataRecursively(std::deque::iterator& packagesBegin); + bool ParseDataRecursively(std::deque::iterator& packagesCurIter); void ParseTraceDataItem(const std::string& buffer) override; bool ParseCpuRawData(uint32_t cpuId, const std::string& buffer); bool HmParseCpuRawData(const std::string& buffer); @@ -43,15 +43,15 @@ private: void UpdateTraceMinRange(); private: + std::unique_ptr cpuDetail_ = nullptr; + std::unique_ptr cpuDetailParser_ = nullptr; + std::unique_ptr ftraceProcessor_ = nullptr; + std::unique_ptr ksymsProcessor_ = nullptr; TraceDataCache* traceDataCache_; bool hasGotHeader_ = false; - uint8_t fileType_; + uint8_t fileType_ = 0; uint8_t restCommDataCnt_ = 0; uint32_t cpuCoreMax_ = 0; - std::unique_ptr ftraceProcessor_ = nullptr; - std::unique_ptr ksymsProcessor_ = nullptr; - std::unique_ptr cpuDetail_ = nullptr; - std::unique_ptr cpuDetailParser_ = nullptr; const std::string eventEndCmd_ = "print fmt:"; }; } // namespace TraceStreamer diff --git a/trace_streamer/src/proto_reader/include/proto_reader.h b/trace_streamer/src/proto_reader/include/proto_reader.h index 6dae463e0f341fe9cfb518b005d99c7b082dec83..b46babe261bc14bb4b08a7d8af597e255ef5cf03 100644 --- a/trace_streamer/src/proto_reader/include/proto_reader.h +++ b/trace_streamer/src/proto_reader/include/proto_reader.h @@ -157,7 +157,7 @@ public: } } else { // kFixed32 or kFixed64 auto step = fixedTypeToSizeMap_.at(wireType); - memcpy_s(¤tValue_, sizeof(cppType), currentReadAddr_, sizeof(cppType)); + (void)memcpy_s(¤tValue_, sizeof(cppType), currentReadAddr_, sizeof(cppType)); currentReadAddr_ += step; } diff --git a/trace_streamer/src/proto_reader/include/proto_reader_help.h b/trace_streamer/src/proto_reader/include/proto_reader_help.h index ee5a1962c23976b074c6efff91df8699cc65f384..a1852a9e0c249f569183d02aa541043638b1ea60 100644 --- a/trace_streamer/src/proto_reader/include/proto_reader_help.h +++ b/trace_streamer/src/proto_reader/include/proto_reader_help.h @@ -22,6 +22,7 @@ namespace SysTuning { namespace ProtoReader { +constexpr int DATA_AREA_ID = 3; class BytesView { public: BytesView() : data_(nullptr), size_(0) {} @@ -72,7 +73,7 @@ enum class ProtoWireType : uint8_t { inline uint32_t CreateTagVarInt(uint32_t DataAreaId) { - return (DataAreaId << 3) | static_cast(ProtoWireType::kVarInt); + return (DataAreaId << DATA_AREA_ID) | static_cast(ProtoWireType::kVarInt); } inline char Lowercase(char c) diff --git a/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.cpp b/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.cpp index 47eafe71cbe6f57fea56a1d7164a872437da4da6..0a354a26321f0beda82a84136202a056ed693ad3 100644 --- a/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.cpp +++ b/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.cpp @@ -105,7 +105,6 @@ void ProtoReaderGenerator::ParserDependencies() for (const Descriptor* descriptor : vDescriptor_) { for (int32_t i = 0; i < descriptor->field_count(); ++i) { - if (descriptor->field(i)->type() == FieldDescriptor::TYPE_MESSAGE) { if (!publicImports_.count(descriptor->field(i)->message_type()->file())) { referencedMessages_.insert(descriptor->field(i)->message_type()); diff --git a/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.h b/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.h index f46aa502604b7114df9e94b6b8e7db0890bc1a2b..c7ae60558a9eb3df9717b36ff33ab892dfdee704 100644 --- a/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.h +++ b/trace_streamer/src/proto_reader/protoc_plugin/proto_reader_plugin.h @@ -80,7 +80,7 @@ private: } } template - std::string GetDescriptorClass(const T* descriptor) + const std::string GetDescriptorClass(const T* descriptor) { std::string name = GetDescriptorName(descriptor); size_t pos = name.find("."); diff --git a/trace_streamer/src/rpc/ffrt_converter.cpp b/trace_streamer/src/rpc/ffrt_converter.cpp index d90d51e3f805f6324aaa64c84c813400c51e46e4..46020599cb10a86a3e47aabce80b5150a14c188c 100644 --- a/trace_streamer/src/rpc/ffrt_converter.cpp +++ b/trace_streamer/src/rpc/ffrt_converter.cpp @@ -32,8 +32,8 @@ bool FfrtConverter::RecoverTraceAndGenerateNewFile(const std::string& ffrtFileNa TypeFfrtPid result = ClassifyLogsForFfrtWorker(lines); ConvertFfrtThreadToFfrtTask(lines, result); SupplementFfrtBlockAndWakeInfo(lines); - for (auto line : lines) { - outFile << line << std::endl; + for (const std::string& lineergodic : lines) { + outFile << lineergodic << std::endl; } return true; } @@ -368,7 +368,7 @@ FfrtConverter::TypeFfrtPid FfrtConverter::ClassifyLogsForFfrtWorker(vector& results) std::unique_ptr result = std::make_unique(MAX_LEN); for (int line = 0; line < results.size(); line++) { auto log = results[line]; + int32_t pid; + size_t beginPos; + long long gid; + size_t endPos; if (log.find("FFBK[") != std::string::npos) { - auto pid = ExtractProcessId(log); - auto beginPos = log.rfind("|"); - auto gid = stoll(log.substr(beginPos + 1)); + pid = ExtractProcessId(log); + beginPos = log.rfind("|"); + gid = stoll(log.substr(beginPos + 1)); if (taskWak.find(pid) == taskWak.end()) { taskWak[pid] = {}; } @@ -544,15 +548,15 @@ void FfrtConverter::SupplementFfrtBlockAndWakeInfo(vector& results) memset_s(result.get(), MAX_LEN, 0, MAX_LEN); } taskWak[pid][gid].state = "block"; - auto endPos = results[line].rfind('|'); + endPos = results[line].rfind('|'); results[line] = results[line].substr(0, endPos); if (!readyEndLog.empty()) { results[line] = readyEndLog + results[line]; } } else if (log.find("FFWK|") != std::string::npos) { - auto pid = ExtractProcessId(log); - auto beginPos = log.rfind('|'); - auto gid = stoll(log.substr(beginPos + 1)); + pid = ExtractProcessId(log); + beginPos = log.rfind('|'); + gid = stoll(log.substr(beginPos + 1)); if (taskWak.find(pid) != taskWak.end() && taskWak[pid].find(gid) != taskWak[pid].end()) { auto timestamp = ExtractTimeStr(log); auto cpuId = ExtractCpuId(log); @@ -582,10 +586,9 @@ void FfrtConverter::SupplementFfrtBlockAndWakeInfo(vector& results) taskWak[pid][gid].prevWakeLog = log; } } else if (log.find("FFRT::[") != std::string::npos) { - auto pid = ExtractProcessId(log); - long long gid; - auto beginPos = log.rfind('|'); - auto endPos = log.find_first_of('\n', beginPos + 1); + pid = ExtractProcessId(log); + beginPos = log.rfind('|'); + endPos = log.find_first_of('\n', beginPos + 1); if (beginPos != std::string::npos && endPos != std::string::npos && IsDigit(log.substr(beginPos + 1, endPos - beginPos - 1))) { gid = stoll(log.substr(beginPos + 1, endPos - beginPos - 1)); @@ -596,8 +599,8 @@ void FfrtConverter::SupplementFfrtBlockAndWakeInfo(vector& results) if (taskWak[pid][gid].state == "ready") { auto timestamp = ExtractTimeStr(log); auto cpuId = ExtractCpuId(log); - auto endPos = log.rfind('\n'); - auto beginPos = log.find_last_of('\n', endPos - 1); + endPos = log.rfind('\n'); + beginPos = log.find_last_of('\n', endPos - 1); auto switchLog = log.substr(beginPos + 1, endPos); beginPos = switchLog.find("next_comm="); endPos = switchLog.find("next_pid"); diff --git a/trace_streamer/src/rpc/ffrt_converter.h b/trace_streamer/src/rpc/ffrt_converter.h index cbd1391cf1a0858ebb1fac76cc6b7571b7072c13..2e219ba890f0ecf400054e2ab3a515056f5b4c3b 100644 --- a/trace_streamer/src/rpc/ffrt_converter.h +++ b/trace_streamer/src/rpc/ffrt_converter.h @@ -71,14 +71,14 @@ private: const std::string& label, const long long gid, const int tid, - const std::string& tname, + const std::string& threadName, const int prio); std::string MakeEndFakeLog(const std::string& mark, const int pid, const std::string& label, const long long gid, const int tid, - const std::string& tname, + const std::string& threadName, const int prio); std::string ReplaceSchedSwitchLog(std::string& fakeLog, const std::string& mark, diff --git a/trace_streamer/src/rpc/http_server.cpp b/trace_streamer/src/rpc/http_server.cpp deleted file mode 100644 index ceb8a6c02af74e15908218fbe651c608ed77f85e..0000000000000000000000000000000000000000 --- a/trace_streamer/src/rpc/http_server.cpp +++ /dev/null @@ -1,463 +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. - */ - -#include "http_server.h" -#include -#include -#include -#include // for macx -#include -#ifdef _WIN32 -#include -#else -#include -#include -#endif -#include "log.h" -#include "string_to_numerical.h" -namespace SysTuning { -namespace TraceStreamer { -void HttpServer::RegisterRpcFunction(RpcServer* rpc) -{ - rpcFunctions_.clear(); - - using std::placeholders::_1; - using std::placeholders::_2; - using std::placeholders::_3; - - auto parsedataover = std::bind(&RpcServer::ParseDataOver, rpc, _1, _2, _3); - rpcFunctions_["/parsedataover"] = parsedataover; - - auto sqlquery = std::bind(&RpcServer::SqlQuery, rpc, _1, _2, _3); - rpcFunctions_["/sqlquery"] = sqlquery; - - auto sqloperate = std::bind(&RpcServer::SqlOperate, rpc, _1, _2, _3); - rpcFunctions_["/sqloperate"] = sqloperate; - - auto reset = std::bind(&RpcServer::Reset, rpc, _1, _2, _3); - rpcFunctions_["/reset"] = reset; -} - -void HttpServer::CloseAllThreads() const -{ - for (const auto& it : clientThreads_) { - if (it->thread_.joinable()) { - it->thread_.join(); - it->sock_.Close(); - } - } -} - -#ifdef _WIN32 -void HttpServer::Run(int32_t port) -{ - WSADATA ws{}; - if (WSAStartup(MAKEWORD(WS_VERSION_FIRST, WS_VERSION_SEC), &ws) != 0) { - return; - } - if (!CreateSocket(port)) { - return; - } - WSAEVENT events[COUNT_SOCKET]; - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - if ((events[i] = WSACreateEvent()) == WSA_INVALID_EVENT) { - TS_LOGE("WSACreateEvent error %d", WSAGetLastError()); - return; - } - WSAEventSelect(sockets_[i].GetFd(), events[i], FD_ACCEPT | FD_CLOSE); - } - - while (!isExit_) { - ClearDeadClientThread(); - - int32_t index = WSAWaitForMultipleEvents(COUNT_SOCKET, events, false, pollTimeOut_, false); - if (index == WSA_WAIT_FAILED) { - TS_LOGE("WSAWaitForMultipleEvents error %d", WSAGetLastError()); - break; - } else if (index == WSA_WAIT_TIMEOUT) { - continue; - } - - index = index - WSA_WAIT_EVENT_0; - WSANETWORKEVENTS event; - WSAEnumNetworkEvents(sockets_[index].GetFd(), events[index], &event); - if (event.lNetworkEvents & FD_ACCEPT) { - if (event.iErrorCode[FD_ACCEPT_BIT] != 0) { - continue; - } - - std::unique_ptr client = std::make_unique(); - if (sockets_[index].Accept(client->sock_)) { - client->thread_ = std::thread(&HttpServer::ProcessClient, this, std::ref(client->sock_)); - clientThreads_.push_back(std::move(client)); - } else { - TS_LOGE("http socket accept error"); - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - } - } - CloseAllThreads(); - clientThreads_.clear(); - - WSACleanup(); -} -#else -void HttpServer::Run(int32_t port) -{ - if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { - return; - } - - if (!CreateSocket(port)) { - return; - } - TS_LOGI("http server running"); - pollfd fds[COUNT_SOCKET]; - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - fds[i] = {sockets_[i].GetFd(), POLLIN, 0}; - } - while (!isExit_) { - ClearDeadClientThread(); - if (poll(fds, sizeof(fds) / sizeof(pollfd), pollTimeOut_) <= 0) { - continue; // try again - } - - for (int32_t i = 0; i < 1; i++) { - if (fds[i].revents != POLLIN) { - continue; - } - std::unique_ptr client = std::make_unique(); - if (sockets_[i].Accept(client->sock_)) { - client->thread_ = std::thread(&HttpServer::ProcessClient, this, std::ref(client->sock_)); - clientThreads_.push_back(std::move(client)); - } else { - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - } - } - CloseAllThreads(); - clientThreads_.clear(); - - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - sockets_[i].Close(); - } - TS_LOGI("http server exit"); -} -#endif - -void HttpServer::Exit() -{ - isExit_ = true; - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - sockets_[i].Close(); - } -} - -bool HttpServer::CreateSocket(int32_t port) -{ - for (int32_t i = 0; i < COUNT_SOCKET; i++) { - if (!sockets_[i].CreateSocket(i == 0 ? AF_INET : AF_INET6)) { - TS_LOGE("Create http socket error"); - return false; - } - if (!sockets_[i].Bind(port)) { - TS_LOGE("bind http socket error"); - return false; - } - if (!sockets_[i].Listen(SOMAXCONN)) { - TS_LOGE("listen http socket error"); - return false; - } - } - - return true; -} - -void HttpServer::ClearDeadClientThread() -{ - for (auto it = clientThreads_.begin(); it != clientThreads_.end();) { - if (it->get()->sock_.GetFd() != -1) { - it++; - continue; - } - if (it->get()->thread_.joinable()) { - it->get()->thread_.join(); - } - it = clientThreads_.erase(it); - } -} - -bool HttpServer::ProcessAndParseReq(size_t& recvPos, - size_t& recvLen, - std::vector& recvBuf, - RequestST& reqST, - HttpSocket& client) -{ - if (!client.Recv(recvBuf.data() + recvPos, recvLen)) { - return false; - } - recvPos += recvLen; - ParseRequest(recvBuf.data(), recvPos, reqST); - recvLen = recvBuf.size() - recvPos; - if (reqST.stat == RequstParseStat::RECVING) { - return true; - } - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - return true; -} - -#ifdef _WIN32 -void HttpServer::ProcessClient(HttpSocket& client) -{ - std::vector recvBuf(MAXLEN_REQUEST); - size_t recvLen = recvBuf.size(); - size_t recvPos = 0; - RequestST reqST; - WSAEVENT recvEvent = WSACreateEvent(); - if (recvEvent == WSA_INVALID_EVENT) { - TS_LOGE("WSACreateEvent error %d", WSAGetLastError()); - return; - } - WSAEventSelect(client.GetFd(), recvEvent, FD_READ | FD_CLOSE); - while (!isExit_) { - int32_t index = WSAWaitForMultipleEvents(1, &recvEvent, false, pollTimeOut_, false); - if (index == WSA_WAIT_FAILED) { - TS_LOGE("WSAWaitForMultipleEvents error %d", WSAGetLastError()); - break; - } else if (index == WSA_WAIT_TIMEOUT) { - if (reqST.stat != RequstParseStat::INIT) { - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - recvPos = 0; - recvLen = recvBuf.size(); - } - continue; - } - - WSANETWORKEVENTS event; - WSAEnumNetworkEvents(client.GetFd(), recvEvent, &event); - if (event.lNetworkEvents & FD_READ) { - if (event.iErrorCode[FD_READ_BIT] != 0) { - continue; - } - if (!ProcessAndParseReq(recvPos, recvLen, recvBuf, reqST, client)) { - break; - } - } else if (event.lNetworkEvents & FD_CLOSE) { - TS_LOGI("client close socket(%d)", client.GetFd()); - break; - } - } - TS_LOGI("recive client thread exit. socket(%d)", client.GetFd()); - - client.Close(); -} -#else -void HttpServer::ProcessClient(HttpSocket& client) -{ - std::vector recvBuf(MAXLEN_REQUEST); - size_t recvLen = recvBuf.size(); - size_t recvPos = 0; - RequestST reqST; - - pollfd fd = {client.GetFd(), POLLIN, 0}; - while (!isExit_) { - int32_t pollRet = poll(&fd, sizeof(fd) / sizeof(pollfd), pollTimeOut_); - if (pollRet < 0) { - TS_LOGE("poll client socket(%d) error: %d:%s", client.GetFd(), errno, strerror(errno)); - break; - } - if (pollRet == 0) { - if (reqST.stat != RequstParseStat::INIT) { - ProcessRequest(client, reqST); - reqST.stat = RequstParseStat::INIT; - recvPos = 0; - recvLen = recvBuf.size(); - } - continue; - } - if (!ProcessAndParseReq(recvPos, recvLen, recvBuf, reqST, client)) { - break; - } - } - TS_LOGI("recive client thread exit. socket(%d)", client.GetFd()); - - client.Close(); - TS_LOGI("thread exit"); -} -#endif - -bool HttpServer::CheckStatAndCmd(HttpSocket& client, RequestST& request) -{ - if (request.stat == RequstParseStat::RECVING) { - TS_LOGE("http request data missing, client %d\n", client.GetFd()); - HttpResponse(client, "408 Request Time-out\r\n"); - return false; - } else if (request.stat != RequstParseStat::OK) { - TS_LOGE("bad http request, client %d\n", client.GetFd()); - HttpResponse(client, "400 Bad Request\r\n"); - return false; - } - if (request.method == "OPTIONS") { - HttpResponse(client, - "204 No Content\r\n" - "Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n" - "Access-Control-Allow-Headers: *\r\n" - "Access-Control-Max-Age: 86400\r\n"); - return false; - } else if (request.method != "POST" && request.method != "GET") { - TS_LOGE("method(%s) not allowed, client %d", request.method.c_str(), client.GetFd()); - HttpResponse(client, "405 Method Not Allowed\r\n"); - return false; - } - return true; -} - -void HttpServer::ProcessRequest(HttpSocket& client, RequestST& request) -{ - if (!CheckStatAndCmd(client, request)) { - return; - } - auto it = rpcFunctions_.find(request.uri); - if (it == rpcFunctions_.end()) { - TS_LOGE("http uri(%s) not found, client %d", request.uri.c_str(), client.GetFd()); - HttpResponse(client, "404 Not Found\r\n"); - return; - } - HttpResponse(client, "200 OK\r\n", true); - auto resultCallback = [&client](const std::string& result, int32_t) { - std::stringstream chunkLenbuff; - chunkLenbuff << std::hex << result.size() << "\r\n"; - if (!client.Send(chunkLenbuff.str().data(), chunkLenbuff.str().size())) { - TS_LOGE("send client socket(%d) error", client.GetFd()); - return; - } - if (!client.Send(result.data(), result.size())) { - TS_LOGE("send client socket(%d) error", client.GetFd()); - return; - } - if (!client.Send("\r\n", strlen("\r\n"))) { - TS_LOGE("send client socket(%d) error", client.GetFd()); - return; - } - }; - it->second(request.body, request.bodyLen, resultCallback); - if (!client.Send("0\r\n\r\n", strlen("0\r\n\r\n"))) { // chunk tail - TS_LOGE("send client socket(%d) error", client.GetFd()); - } -} - -void HttpServer::ParseRequest(const uint8_t* requst, size_t& len, RequestST& httpReq) -{ - std::string_view reqStr(reinterpret_cast(requst), len); - size_t bodyPos = reqStr.find("\r\n\r\n"); - if (bodyPos == 0) { - len = 0; - httpReq.stat = RequstParseStat::BAD; - return; - } else if (bodyPos == std::string_view::npos) { - httpReq.stat = RequstParseStat::RECVING; - return; - } - std::string_view header = reqStr.substr(0, bodyPos); - bodyPos += strlen("\r\n\r\n"); - httpReq.bodyLen = reqStr.size() - bodyPos; - - std::vector headerlines = StringSplit(header, "\r\n"); - // at least 1 line in headerlines, such as "GET /parsedata HTTP/1.1" - std::vector requestItems = StringSplit(headerlines[0], " "); - const size_t indexHttpMethod = 0; - const size_t indexHttpUri = 1; - const size_t indexHttpVersion = 2; - const size_t countRequestItems = 3; - if (requestItems.size() != countRequestItems || requestItems[indexHttpVersion] != "HTTP/1.1") { - len = 0; - httpReq.stat = RequstParseStat::BAD; - return; - } - httpReq.method = requestItems[indexHttpMethod]; - httpReq.uri = requestItems[indexHttpUri]; - - for (size_t i = 1; i < headerlines.size(); i++) { - size_t tagPos = headerlines[i].find(":"); - if (tagPos == std::string_view::npos) { - len = 0; - httpReq.stat = RequstParseStat::BAD; - return; - } - std::string_view tag = headerlines[i].substr(0, tagPos); - if (strncasecmp(tag.data(), "Content-Length", tag.size()) == 0) { - std::string value(headerlines[i].data() + tagPos + strlen(":"), - headerlines[i].size() - tagPos - strlen(":")); - size_t conterntLen = atoi(value.c_str()); - if (conterntLen > httpReq.bodyLen) { - httpReq.stat = RequstParseStat::RECVING; - return; - } else if (conterntLen < httpReq.bodyLen) { - httpReq.bodyLen = conterntLen; - } - } - } - - if (httpReq.bodyLen > 0) { - httpReq.body = (requst + bodyPos); - } - httpReq.stat = RequstParseStat::OK; - len -= (bodyPos + httpReq.bodyLen); - return; -} - -void HttpServer::HttpResponse(HttpSocket& client, const std::string& status, bool hasBody) -{ - std::string res; - const size_t maxLenResponse = 1024; - res.reserve(maxLenResponse); - res += "HTTP/1.1 "; - res += status; - - res += "Connection: Keep-Alive\r\n"; - if (hasBody) { - res += "Content-Type: application/json\r\n"; - res += "Transfer-Encoding: chunked\r\n"; - } - res += "\r\n"; - if (!client.Send(res.data(), res.size())) { - TS_LOGE("send client socket(%d) error", client.GetFd()); - } -} - -std::vector HttpServer::StringSplit(std::string_view source, std::string_view split) -{ - std::vector result; - if (!split.empty()) { - size_t pos = 0; - while ((pos = source.find(split)) != std::string_view::npos) { - // split - std::string_view token = source.substr(0, pos); - if (!token.empty()) { - result.push_back(token); - } - source = source.substr(pos + split.size(), source.size() - token.size() - split.size()); - } - } - // add last token - if (!source.empty()) { - result.push_back(source); - } - return result; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/rpc/http_server.h b/trace_streamer/src/rpc/http_server.h deleted file mode 100644 index bf04f04b96c52e76291c8daf5b8dd5835e2b53ea..0000000000000000000000000000000000000000 --- a/trace_streamer/src/rpc/http_server.h +++ /dev/null @@ -1,83 +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. - */ - -#ifndef RPC_HTTPD_H -#define RPC_HTTPD_H - -#include -#include -#include -#include -#include -#include "http_socket.h" -#include "rpc_server.h" -#include "ts_common.h" -namespace SysTuning { -namespace TraceStreamer { -class HttpServer { -public: - void RegisterRpcFunction(RpcServer* rpc); - void Run(int32_t port = 9001); - void Exit(); - - static constexpr size_t MAXLEN_REQUEST = 2 * 1024 + 1024 * 1024; // header 2K + body 1M - -private: - struct ClientThread { - HttpSocket sock_; - std::thread thread_; - }; - - enum RequstParseStat { INIT = 0, OK, BAD, RECVING }; - - struct RequestST { - int32_t stat = RequstParseStat::INIT; - std::string method; - std::string uri; - const uint8_t* body; - size_t bodyLen; - }; - - bool CreateSocket(int32_t port); - void ProcessClient(HttpSocket& client); - void ProcessRequest(HttpSocket& client, RequestST& request); - static void HttpResponse(HttpSocket& client, const std::string& status, bool hasBody = false); - static void ParseRequest(const uint8_t* requst, size_t& len, RequestST& httpReq); - void ClearDeadClientThread(); - static std::vector StringSplit(std::string_view source, std::string_view split); - bool CheckStatAndCmd(HttpSocket& client, RequestST& request); - void CloseAllThreads() const; - bool ProcessAndParseReq(size_t& recvPos, - size_t& recvLen, - std::vector& recvBuf, - RequestST& reqST, - HttpSocket& client); - - static const int32_t COUNT_SOCKET = 1; - HttpSocket sockets_[COUNT_SOCKET]; // ipv4 and ipv6 - std::atomic_bool isExit_ = {false}; - std::vector> clientThreads_; - using RpcFunction = std::function; - std::map rpcFunctions_; - const int32_t pollTimeOut_ = 1000; -#ifdef _WIN32 - const uint32_t WS_VERSION_FIRST = 2; - const uint32_t WS_VERSION_SEC = 2; -#endif -}; -} // namespace TraceStreamer -} // namespace SysTuning - -#endif // RPC_HTTPD_H diff --git a/trace_streamer/src/rpc/http_socket.cpp b/trace_streamer/src/rpc/http_socket.cpp deleted file mode 100644 index 22caafc01444fffe1f0170a3124ceccc14b3d972..0000000000000000000000000000000000000000 --- a/trace_streamer/src/rpc/http_socket.cpp +++ /dev/null @@ -1,173 +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. - */ - -#include "http_socket.h" -#include -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#endif -#include "log.h" -namespace SysTuning { -namespace TraceStreamer { -HttpSocket::~HttpSocket() -{ - Close(); -} -bool HttpSocket::CreateSocket(int32_t domain) -{ - SOCKET sockId = socket(domain, SOCK_STREAM, 0); - if (sockId == INVALID_SOCKET) { - TS_LOGE("CreateSocket socket error, domain %d: %d:%s", domain, errno, strerror(errno)); - return false; - } - sockId_ = sockId; - if (domain == AF_INET || domain == AF_INET6) { - int32_t enable = 1; - if (setsockopt(sockId, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&enable), sizeof(enable)) == - SOCKET_ERROR) { - Close(); - return false; - } - if (domain == AF_INET6) { - if (setsockopt(sockId, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&enable), sizeof(enable)) == - SOCKET_ERROR) { - Close(); - return false; - } - } - } - domain_ = domain; - TS_LOGI("CreateSocket socket ok, socket %d domain %d", sockId_, domain); - return true; -} - -bool HttpSocket::Bind(int32_t port) -{ - if (sockId_ == INVALID_SOCKET) { - TS_LOGE("the socket not created"); - return false; - } - - if (domain_ == AF_INET) { - sockaddr_in addr; - std::fill(reinterpret_cast(&addr), reinterpret_cast(&addr) + sizeof(addr), 0); - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htons(INADDR_ANY); - addr.sin_port = htons(static_cast(port)); - if (bind(sockId_, reinterpret_cast(&addr), sizeof(addr)) == -1) { - TS_LOGE("bind ipv4 socket error, port %d: %d:%s", port, errno, strerror(errno)); - return false; - } - } else if (domain_ == AF_INET6) { - sockaddr_in6 addr; - std::fill(reinterpret_cast(&addr), reinterpret_cast(&addr) + sizeof(addr), 0); - addr.sin6_family = AF_INET6; - addr.sin6_addr = in6addr_any; - addr.sin6_port = htons(static_cast(port)); - if (bind(sockId_, reinterpret_cast(&addr), sizeof(addr)) == -1) { - TS_LOGE("bind ipv6 socket error, port %d: %d:%s", port, errno, strerror(errno)); - return false; - } - } else { - return false; - } - TS_LOGI("bind socket ok, port %d", port); - return true; -} - -bool HttpSocket::Listen(int32_t maxConn) -{ - if (listen(sockId_, maxConn) == SOCKET_ERROR) { - TS_LOGE("listen socket error: %d:%s", errno, strerror(errno)); - return false; - } - TS_LOGI("listen socket ok, maxConn %d", maxConn); - return true; -} - -bool HttpSocket::Accept(HttpSocket& client) -{ - int32_t clientId = accept(sockId_, nullptr, nullptr); - if (clientId == INVALID_SOCKET) { - TS_LOGE("accept socket error: %d:%s", errno, strerror(errno)); - return false; - } - - client.domain_ = domain_; - client.sockId_ = clientId; - TS_LOGI("accept client socket id %d domain %d", clientId, domain_); - return true; -} - -bool HttpSocket::Recv(void* data, size_t& len) -{ -#ifdef _WIN32 - ssize_t recvLen = recv(sockId_, static_cast(data), len, 0); -#else - ssize_t recvLen = recv(sockId_, data, len, 0); -#endif - if (recvLen == SOCKET_ERROR) { - if (errno == EAGAIN) { - recvLen = 0; - } else { - TS_LOGE("recv from socket(%d) error: %d:%s", sockId_, errno, strerror(errno)); - return false; - } - } else if (recvLen == 0) { - TS_LOGI("client socket(%d) closed", sockId_); - return false; - } - len = recvLen; - TS_LOGD("Recv from socket(%d) len %zu", sockId_, len); - return true; -} - -bool HttpSocket::Send(const void* data, size_t len) -{ -#ifdef _WIN32 - ssize_t sendLen = send(sockId_, static_cast(data), len, 0); -#else - ssize_t sendLen = send(sockId_, data, len, 0); -#endif - if (sendLen == SOCKET_ERROR) { - TS_LOGE("send to socket(%d) error: %d:%s", sockId_, errno, strerror(errno)); - return false; - } - TS_LOGI("send to socket(%d) len %zu", sockId_, len); - return true; -} - -void HttpSocket::Close() -{ - if (sockId_ == INVALID_SOCKET) { - return; - } - TS_LOGI("close socket(%d)", sockId_); -#ifdef _WIN32 - if (closesocket(sockId_) == SOCKET_ERROR) { -#else - if (close(sockId_) == SOCKET_ERROR) { -#endif - TS_LOGE("close socket(%d) error: %d:%s", sockId_, errno, strerror(errno)); - } - sockId_ = INVALID_SOCKET; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/rpc/rpc_server.cpp b/trace_streamer/src/rpc/rpc_server.cpp index 2cac64e6902ae5a8d36e427bfa405c385ba9a99e..e2d83836f673ee405a73913b753b56b859ddb588 100644 --- a/trace_streamer/src/rpc/rpc_server.cpp +++ b/trace_streamer/src/rpc/rpc_server.cpp @@ -32,10 +32,6 @@ #include "ts_common.h" #include "version.h" -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) namespace SysTuning { namespace TraceStreamer { uint32_t g_fileLen = 0; @@ -209,7 +205,7 @@ bool RpcServer::GetTimeSnap(std::string dataString) return false; } uint8_t buffer[PACKET_HEADER_LENGTH]; - (void)memset_s(buffer, PACKET_HEADER_LENGTH, 0, PACKET_HEADER_LENGTH); + (void)memset_s(buffer, sizeof(buffer), 0, sizeof(buffer)); int32_t i = 0; for (auto it = dataString.begin(); it != dataString.begin() + PACKET_HEADER_LENGTH; ++it, ++i) { buffer[i] = *it; @@ -457,8 +453,8 @@ int32_t RpcServer::TraceStreamer_Init_ThirdParty_Config(const uint8_t* data, int bool RpcServer::ParseDataOver(const uint8_t* data, size_t len, ResultCallBack resultCallBack) { - UNUSED(data); - UNUSED(len); + Unused(data); + Unused(len); MetaData* metaData = ts_->GetMetaData(); metaData->SetSourceFileName("input stream mode"); metaData->SetOutputFileName("wasm mode"); @@ -519,8 +515,8 @@ void RpcServer::CancelSqlQuery() bool RpcServer::Reset(const uint8_t* data, size_t len, ResultCallBack resultCallBack) { - UNUSED(data); - UNUSED(len); + Unused(data); + Unused(len); TS_LOGI("RPC reset trace_streamer"); ts_->WaitForParserEnd(); diff --git a/trace_streamer/src/rpc/rpc_server.h b/trace_streamer/src/rpc/rpc_server.h index 41a4255165f5945aec53dce91edf4e9d9b55c4b6..7169c03d325e82635e3fb2a4014e8ebb41eda07e 100644 --- a/trace_streamer/src/rpc/rpc_server.h +++ b/trace_streamer/src/rpc/rpc_server.h @@ -64,7 +64,7 @@ public: uint32_t pageNum, SplitFileCallBack splitFileCallBack); bool GetTimeSnap(std::string dataString); - bool GetFfrtConvertStatus() + const bool GetFfrtConvertStatus() { return ffrtConvertEnabled_; }; diff --git a/trace_streamer/src/rpc/wasm_func.cpp b/trace_streamer/src/rpc/wasm_func.cpp index 5ea74a3198ade196d8955044c524082b4c0f85b0..584d8316d86743f1cbc3bce018788281c4963ee4 100644 --- a/trace_streamer/src/rpc/wasm_func.cpp +++ b/trace_streamer/src/rpc/wasm_func.cpp @@ -189,7 +189,7 @@ EMSCRIPTEN_KEEPALIVE void TraceStreamer_Set_Log_Level(uint32_t level) int32_t TraceStreamer_Plugin_Out_Filter(const char* pluginData, int32_t len, const std::string& componentName) { std::map::iterator itor = g_wasmTraceStreamer.g_thirdPartyConfig.begin(); - int32_t componentId = 0; + int32_t componentId; for (; itor != g_wasmTraceStreamer.g_thirdPartyConfig.end(); ++itor) { if (itor->second == componentName) { componentId = itor->first; diff --git a/trace_streamer/src/table/BUILD.gn b/trace_streamer/src/table/BUILD.gn index 03514a40b817837e9b79e16579c2835dbb355619..2a2eb77f0b67db103c6691ec049d3a87b3359fa8 100644 --- a/trace_streamer/src/table/BUILD.gn +++ b/trace_streamer/src/table/BUILD.gn @@ -28,7 +28,16 @@ ohos_source_set("table") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/base/BUILD.gn b/trace_streamer/src/table/base/BUILD.gn index 5608875284877d65227c5bdb0e3c27d77f2dd84a..ac002df11ca80d9c18be1efa430652a07e46f448 100644 --- a/trace_streamer/src/table/base/BUILD.gn +++ b/trace_streamer/src/table/base/BUILD.gn @@ -19,31 +19,20 @@ ohos_source_set("base_tables") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "args_table.cpp", - "args_table.h", "data_dict_table.cpp", - "data_dict_table.h", "data_type_table.cpp", - "data_type_table.h", "datasource_clockid_table.cpp", - "datasource_clockid_table.h", "device_info_table.cpp", - "device_info_table.h", "meta_table.cpp", - "meta_table.h", "range_table.cpp", - "range_table.h", "span_join.cpp", - "span_join.h", "stat_table.cpp", - "stat_table.h", "symbols_table.cpp", - "symbols_table.h", "table_base.cpp", - "table_base.h", "trace_config_table.cpp", - "trace_config_table.h", ] include_dirs = [ + "include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -53,7 +42,16 @@ ohos_source_set("base_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/base/args_table.h b/trace_streamer/src/table/base/include/args_table.h similarity index 100% rename from trace_streamer/src/table/base/args_table.h rename to trace_streamer/src/table/base/include/args_table.h diff --git a/trace_streamer/src/table/base/data_dict_table.h b/trace_streamer/src/table/base/include/data_dict_table.h similarity index 100% rename from trace_streamer/src/table/base/data_dict_table.h rename to trace_streamer/src/table/base/include/data_dict_table.h diff --git a/trace_streamer/src/table/base/data_type_table.h b/trace_streamer/src/table/base/include/data_type_table.h similarity index 100% rename from trace_streamer/src/table/base/data_type_table.h rename to trace_streamer/src/table/base/include/data_type_table.h diff --git a/trace_streamer/src/table/base/datasource_clockid_table.h b/trace_streamer/src/table/base/include/datasource_clockid_table.h similarity index 100% rename from trace_streamer/src/table/base/datasource_clockid_table.h rename to trace_streamer/src/table/base/include/datasource_clockid_table.h diff --git a/trace_streamer/src/table/base/device_info_table.h b/trace_streamer/src/table/base/include/device_info_table.h similarity index 100% rename from trace_streamer/src/table/base/device_info_table.h rename to trace_streamer/src/table/base/include/device_info_table.h diff --git a/trace_streamer/sdk/demo_sdk/table/meta_table.h b/trace_streamer/src/table/base/include/meta_table.h similarity index 100% rename from trace_streamer/sdk/demo_sdk/table/meta_table.h rename to trace_streamer/src/table/base/include/meta_table.h diff --git a/trace_streamer/src/table/base/range_table.h b/trace_streamer/src/table/base/include/range_table.h similarity index 100% rename from trace_streamer/src/table/base/range_table.h rename to trace_streamer/src/table/base/include/range_table.h diff --git a/trace_streamer/src/table/base/span_join.h b/trace_streamer/src/table/base/include/span_join.h similarity index 97% rename from trace_streamer/src/table/base/span_join.h rename to trace_streamer/src/table/base/include/span_join.h index 07e56cfee87be8e96ac132bd56acee0943ca2e6d..c15f6256454c478d2ab97d80410f14a5be548681 100644 --- a/trace_streamer/src/table/base/span_join.h +++ b/trace_streamer/src/table/base/include/span_join.h @@ -47,7 +47,7 @@ enum class PartitionState : int32_t { class SpanJoin : public TableBase { public: - SpanJoin(const TraceDataCache*); + explicit SpanJoin(const TraceDataCache*); ~SpanJoin() override{}; void Parse(const std::string& tablePartition, TableParse& tableParse); void GetTableField(const TableParse& tableParse, TableDesc& tableDesc); @@ -123,8 +123,8 @@ public: bool isSamepartitioning_ = false; private: - TableDesc tableFirstDesc_; - TableDesc tableSecondDesc_; + TableDesc tableFirstDesc_ = {}; + TableDesc tableSecondDesc_ = {}; std::unordered_map mTableColumnInfo_; }; diff --git a/trace_streamer/src/table/base/stat_table.h b/trace_streamer/src/table/base/include/stat_table.h similarity index 100% rename from trace_streamer/src/table/base/stat_table.h rename to trace_streamer/src/table/base/include/stat_table.h diff --git a/trace_streamer/src/table/base/symbols_table.h b/trace_streamer/src/table/base/include/symbols_table.h similarity index 100% rename from trace_streamer/src/table/base/symbols_table.h rename to trace_streamer/src/table/base/include/symbols_table.h diff --git a/trace_streamer/src/table/base/table_base.h b/trace_streamer/src/table/base/include/table_base.h similarity index 93% rename from trace_streamer/src/table/base/table_base.h rename to trace_streamer/src/table/base/include/table_base.h index 00bda2cd037184f5c5aeefc08d1ff380cb0ed74c..dcc99d9d4f49b5cd54f42b9f1025931b0fd119c8 100644 --- a/trace_streamer/src/table/base/table_base.h +++ b/trace_streamer/src/table/base/include/table_base.h @@ -25,10 +25,6 @@ #include "index_map.h" #include "sqlite3.h" #include "trace_data_cache.h" -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) namespace SysTuning { namespace TraceStreamer { class TableBase; @@ -69,14 +65,14 @@ public: virtual int32_t RowId(sqlite3_int64* id); virtual int32_t Filter(const FilterConstraints& fc, sqlite3_value** argv) { - UNUSED(fc); - UNUSED(argv); + Unused(fc); + Unused(argv); return 0; } virtual int32_t Column(int32_t n) const = 0; virtual void FilterId(unsigned char op, sqlite3_value* argv); virtual void FilterEnd(); - void SwapIndexFront(std::vector& cs, std::set& sId) + void SwapIndexFront(std::vector& cs, const std::set& sId) { uint32_t index = 0; for (size_t i = 0; i < cs.size(); i++) { @@ -124,10 +120,10 @@ protected: // needs to correspond to Cursor::Filter() virtual void FilterByConstraint(FilterConstraints& fc, double& filterCost, size_t rowCount, uint32_t currenti) { - UNUSED(fc); - UNUSED(filterCost); - UNUSED(rowCount); - UNUSED(currenti); + Unused(fc); + Unused(filterCost); + Unused(rowCount); + Unused(currenti); } virtual int64_t GetSize() @@ -137,8 +133,8 @@ protected: virtual void GetOrbyes(FilterConstraints& fc, EstimatedIndexInfo& ei) { - UNUSED(fc); - UNUSED(ei); + Unused(fc); + Unused(ei); } // needs to correspond to Cursor::Filter() virtual void EstimateFilterCost(FilterConstraints& fc, EstimatedIndexInfo& ei); diff --git a/trace_streamer/src/table/base/trace_config_table.h b/trace_streamer/src/table/base/include/trace_config_table.h similarity index 100% rename from trace_streamer/src/table/base/trace_config_table.h rename to trace_streamer/src/table/base/include/trace_config_table.h diff --git a/trace_streamer/src/table/base/span_join.cpp b/trace_streamer/src/table/base/span_join.cpp index 0db9644cc63cc95307db7959781d3d36990b8d0e..464f94d5b73d1b72f8bedb086ead0011287fab67 100644 --- a/trace_streamer/src/table/base/span_join.cpp +++ b/trace_streamer/src/table/base/span_join.cpp @@ -195,8 +195,7 @@ std::string SpanJoin::CaclSpan::GetSqlQuery() for (int32_t i = 0; i < desc_->cols.size(); i++) { columnNames.push_back(desc_->cols.at(i).name_); } - std::string str; - str = GetMergeColumns(columnNames); + auto str = GetMergeColumns(columnNames); std::string sql = "SELECT " + str + " FROM " + desc_->name + " ORDER BY " + desc_->partition + ", " + "ts;"; return sql; } diff --git a/trace_streamer/src/table/base/table_base.cpp b/trace_streamer/src/table/base/table_base.cpp index 2699cb2b2e98cdb6af70501ff19b4f0bcc950043..5600746cad9f4184c8a8e3a888e3639f00b1b9c5 100644 --- a/trace_streamer/src/table/base/table_base.cpp +++ b/trace_streamer/src/table/base/table_base.cpp @@ -20,11 +20,6 @@ #include "log.h" -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) - namespace SysTuning { namespace TraceStreamer { namespace { @@ -53,9 +48,9 @@ void TableBase::TableRegister(sqlite3& db, TraceDataCache* cache, const std::str auto createFn = [](sqlite3* xdb, void* pAux, int32_t argc, const char* const* argv, sqlite3_vtab** ppVTab, char** pzErr) { - UNUSED(argc); - UNUSED(argv); - UNUSED(pzErr); + Unused(argc); + Unused(argv); + Unused(pzErr); auto xdesc = static_cast(pAux); auto table = xdesc->tmplate(xdesc->dataCache); table->name_ = xdesc->tableName; diff --git a/trace_streamer/src/table/ebpf/BUILD.gn b/trace_streamer/src/table/ebpf/BUILD.gn index 16ff75b0b823bd01898e5e137cb1904a01bf2aa0..43aa532da980e613e03fa3a55adf8fe30f0000c2 100644 --- a/trace_streamer/src/table/ebpf/BUILD.gn +++ b/trace_streamer/src/table/ebpf/BUILD.gn @@ -22,15 +22,9 @@ ohos_source_set("ebpf_tables") { "ebpf_callstack_table.cpp", "file_system_sample_table.cpp", ] - if (with_ebpf_help_table) { - sources += [ - "ebpf_elf_symbol_table.cpp", - "ebpf_elf_table.cpp", - "ebpf_process_maps_table.cpp", - ] - } include_dirs = [ - "../base", + "include", + "../base/include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -41,7 +35,16 @@ ohos_source_set("ebpf_tables") { "${THIRD_PARTY}/bounds_checking_function/include", "${THIRD_PARTY}/json/single_include/nlohmann", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp b/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp deleted file mode 100644 index a89022c463d73d04e2cc72e0e386f6c267a0bbcd..0000000000000000000000000000000000000000 --- a/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.cpp +++ /dev/null @@ -1,114 +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. - */ -#include "ebpf_elf_symbol_table.h" - -namespace SysTuning { -namespace TraceStreamer { -enum class Index : int32_t { - ID = 0, - ELF_ID, - ST_NAME, - ST_VALUE, - ST_SIZE, -}; -EbpfElfSymbolTable::EbpfElfSymbolTable(const TraceDataCache* dataCache) : TableBase(dataCache) -{ - tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("elf_id", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("st_name", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("st_value", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("st_size", "INTEGER")); - tablePriKey_.push_back("id"); -} - -EbpfElfSymbolTable::~EbpfElfSymbolTable() {} - -void EbpfElfSymbolTable::FilterByConstraint(FilterConstraints& elffc, - double& elffilterCost, - size_t elfrowCount, - uint32_t elfcurrenti) -{ - // To use the EstimateFilterCost function in the TableBase parent class function to calculate the i-value of each - // for loop - const auto& elfc = elffc.GetConstraints()[elfcurrenti]; - switch (static_cast(elfc.col)) { - case Index::ID: { - if (CanFilterId(elfc.op, elfrowCount)) { - elffc.UpdateConstraint(elfcurrenti, true); - elffilterCost += 1; // id can position by 1 step - } else { - elffilterCost += elfrowCount; // scan all rows - } - break; - } - default: // other column - elffilterCost += elfrowCount; // scan all rows - break; - } -} - -std::unique_ptr EbpfElfSymbolTable::CreateCursor() -{ - return std::make_unique(dataCache_, this); -} - -EbpfElfSymbolTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstEbpfElfSymbol().Size())), - ebpfElfSymbolObj_(dataCache->GetConstEbpfElfSymbol()) -{ -} - -EbpfElfSymbolTable::Cursor::~Cursor() {} - -int32_t EbpfElfSymbolTable::Cursor::Column(int32_t column) const -{ - switch (static_cast(column)) { - case Index::ID: - sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.IdsData()[CurrentRow()])); - break; - case Index::ELF_ID: - sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.ElfIds()[CurrentRow()])); - break; - case Index::ST_NAME: - sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.StNames()[CurrentRow()])); - break; - case Index::ST_VALUE: - sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.StValues()[CurrentRow()])); - break; - case Index::ST_SIZE: - sqlite3_result_int64(context_, static_cast(ebpfElfSymbolObj_.StSizes()[CurrentRow()])); - break; - default: - TS_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} - -void EbpfElfSymbolTable::GetOrbyes(FilterConstraints& elffc, EstimatedIndexInfo& elfei) -{ - auto elforderbys = elffc.GetOrderBys(); - for (auto i = 0; i < elforderbys.size(); i++) { - switch (static_cast(elforderbys[i].iColumn)) { - case Index::ID: - break; - default: // other columns can be sorted by SQLite - elfei.isOrdered = false; - break; - } - } -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp b/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp deleted file mode 100644 index 6e9d78958cc7f4337327393486ef572dc0300b7e..0000000000000000000000000000000000000000 --- a/trace_streamer/src/table/ebpf/ebpf_elf_table.cpp +++ /dev/null @@ -1,145 +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. - */ -#include "ebpf_elf_table.h" - -namespace SysTuning { -namespace TraceStreamer { -enum class Index : int32_t { - ID = 0, - ELF_ID, - TEXT_VADDR, - TEXT_OFFSET, - STR_TAB_LEN, - SYM_TAB_LEN, - FILE_NAME_LEN, - SYM_ENT_LEN, - FILE_PATH_ID, -}; -EbpfElfTable::EbpfElfTable(const TraceDataCache* dataCache) : TableBase(dataCache) -{ - tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("elf_id", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("text_vaddr", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("text_offset", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("str_tab_len", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("sym_tab_len", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("file_name_len", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("sym_ent_len", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("file_path_id", "INTEGER")); - tablePriKey_.push_back("id"); -} - -EbpfElfTable::~EbpfElfTable() {} - -void EbpfElfTable::FilterByConstraint(FilterConstraints& elffc, - double& elffilterCost, - size_t elfrowCount, - uint32_t elfcurrenti) -{ - // To use the EstimateFilterCost function in the TableBase parent class function to calculate the i-value of each - // for loop - const auto& elfc = elffc.GetConstraints()[elfcurrenti]; - switch (static_cast(elfc.col)) { - case Index::ID: { - if (CanFilterId(elfc.op, elfrowCount)) { - elffc.UpdateConstraint(elfcurrenti, true); - elffilterCost += 1; // id can position by 1 step - } else { - elffilterCost += elfrowCount; // scan all rows - } - break; - } - default: // other column - elffilterCost += elfrowCount; // scan all rows - break; - } -} - -std::unique_ptr EbpfElfTable::CreateCursor() -{ - return std::make_unique(dataCache_, this); -} - -EbpfElfTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstEbpfElf().Size())), - ebpfElfObj_(dataCache->GetConstEbpfElf()) -{ -} - -EbpfElfTable::Cursor::~Cursor() {} - -int32_t EbpfElfTable::Cursor::Column(int32_t column) const -{ - switch (static_cast(column)) { - case Index::ID: - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.IdsData()[CurrentRow()])); - break; - case Index::ELF_ID: - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.ElfIds()[CurrentRow()])); - break; - case Index::TEXT_VADDR: - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.TextVaddrs()[CurrentRow()])); - break; - case Index::TEXT_OFFSET: - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.TextOffsets()[CurrentRow()])); - break; - case Index::STR_TAB_LEN: - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.StrTabLens()[CurrentRow()])); - break; - case Index::SYM_TAB_LEN: { - if (ebpfElfObj_.SymTabLens()[CurrentRow()] != INVALID_UINT32) { - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.SymTabLens()[CurrentRow()])); - } - break; - } - case Index::FILE_NAME_LEN: { - if (ebpfElfObj_.FileNameLens()[CurrentRow()] != INVALID_UINT32) { - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.FileNameLens()[CurrentRow()])); - } - break; - } - case Index::SYM_ENT_LEN: { - if (ebpfElfObj_.SymEntLens()[CurrentRow()] != INVALID_UINT32) { - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.SymEntLens()[CurrentRow()])); - } - break; - } - case Index::FILE_PATH_ID: { - if (ebpfElfObj_.FileNameIndexs()[CurrentRow()] != INVALID_UINT64) { - sqlite3_result_int64(context_, static_cast(ebpfElfObj_.FileNameIndexs()[CurrentRow()])); - } - break; - } - default: - TS_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} -void EbpfElfTable::GetOrbyes(FilterConstraints& elffc, EstimatedIndexInfo& elfei) -{ - auto elforderbys = elffc.GetOrderBys(); - for (auto i = 0; i < elforderbys.size(); i++) { - switch (static_cast(elforderbys[i].iColumn)) { - case Index::ID: - break; - default: // other columns can be sorted by SQLite - elfei.isOrdered = false; - break; - } - } -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp b/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp deleted file mode 100644 index d71faa3913ccdd0c404504428e2cd10a1247f953..0000000000000000000000000000000000000000 --- a/trace_streamer/src/table/ebpf/ebpf_process_maps_table.cpp +++ /dev/null @@ -1,134 +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. - */ -#include "ebpf_process_maps_table.h" - -namespace SysTuning { -namespace TraceStreamer { -enum class Index : int32_t { - ID = 0, - START_ADDR, - END_ADDR, - OFFSETS, - PID, - FILE_NAME_LEN, - FILE_PATH_ID, -}; -EbpfProcessMapsTable::EbpfProcessMapsTable(const TraceDataCache* dataCache) : TableBase(dataCache) -{ - tableColumn_.push_back(TableBase::ColumnInfo("id", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("start_addr", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("end_addr", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("offset", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("pid", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("file_path_len", "INTEGER")); - tableColumn_.push_back(TableBase::ColumnInfo("file_path_id", "INTEGER")); - tablePriKey_.push_back("id"); -} - -EbpfProcessMapsTable::~EbpfProcessMapsTable() {} - -void EbpfProcessMapsTable::FilterByConstraint(FilterConstraints& profc, - double& profilterCost, - size_t prorowCount, - uint32_t procurrenti) -{ - // To use the EstimateFilterCost function in the TableBase parent class function to calculate the i-value of each - // for loop - const auto& proc = profc.GetConstraints()[procurrenti]; - switch (static_cast(proc.col)) { - case Index::ID: { - if (CanFilterId(proc.op, prorowCount)) { - profc.UpdateConstraint(procurrenti, true); - profilterCost += 1; // id can position by 1 step - } else { - profilterCost += prorowCount; // scan all rows - } - break; - } - default: // other column - profilterCost += profilterCost; // scan all rows - break; - } -} - -std::unique_ptr EbpfProcessMapsTable::CreateCursor() -{ - return std::make_unique(dataCache_, this); -} - -EbpfProcessMapsTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstEbpfProcessMaps().Size())), - ebpfProcessMapsObj_(dataCache->GetConstEbpfProcessMaps()) -{ -} - -EbpfProcessMapsTable::Cursor::~Cursor() {} - -int32_t EbpfProcessMapsTable::Cursor::Column(int32_t column) const -{ - switch (static_cast(column)) { - case Index::ID: - sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.IdsData()[CurrentRow()])); - break; - case Index::START_ADDR: - sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Starts()[CurrentRow()])); - break; - case Index::END_ADDR: - sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Ends()[CurrentRow()])); - break; - case Index::OFFSETS: - sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Offsets()[CurrentRow()])); - break; - case Index::PID: { - if (ebpfProcessMapsObj_.Pids()[CurrentRow()] != INVALID_UINT32) { - sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.Pids()[CurrentRow()])); - } - break; - } - case Index::FILE_NAME_LEN: { - if (ebpfProcessMapsObj_.FileNameLens()[CurrentRow()] != INVALID_UINT32) { - sqlite3_result_int64(context_, static_cast(ebpfProcessMapsObj_.FileNameLens()[CurrentRow()])); - } - break; - } - case Index::FILE_PATH_ID: { - if (ebpfProcessMapsObj_.FileNameIndexs()[CurrentRow()] != INVALID_UINT64) { - sqlite3_result_int64(context_, - static_cast(ebpfProcessMapsObj_.FileNameIndexs()[CurrentRow()])); - } - break; - } - default: - TS_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} - -void EbpfProcessMapsTable::GetOrbyes(FilterConstraints& profc, EstimatedIndexInfo& proei) -{ - auto proorderbys = profc.GetOrderBys(); - for (auto i = 0; i < proorderbys.size(); i++) { - switch (static_cast(proorderbys[i].iColumn)) { - case Index::ID: - break; - default: // other columns can be sorted by SQLite - proei.isOrdered = false; - break; - } - } -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/table/ebpf/bio_latency_sample_table.h b/trace_streamer/src/table/ebpf/include/bio_latency_sample_table.h similarity index 98% rename from trace_streamer/src/table/ebpf/bio_latency_sample_table.h rename to trace_streamer/src/table/ebpf/include/bio_latency_sample_table.h index 9a7c7b65d97ce405f10a1931fd56e6819bb9e6a8..b0e4e10ebc486fee828677bfc6c5d077b885d564 100644 --- a/trace_streamer/src/table/ebpf/bio_latency_sample_table.h +++ b/trace_streamer/src/table/ebpf/include/bio_latency_sample_table.h @@ -17,7 +17,7 @@ #define BIO_LATENCY_SAMPLE_TABLE_H #include "table_base.h" -#include "trace_stdtype.h" +#include "ebpf_stdtype.h" namespace SysTuning { namespace TraceStreamer { diff --git a/trace_streamer/src/table/ebpf/ebpf_callstack_table.h b/trace_streamer/src/table/ebpf/include/ebpf_callstack_table.h similarity index 98% rename from trace_streamer/src/table/ebpf/ebpf_callstack_table.h rename to trace_streamer/src/table/ebpf/include/ebpf_callstack_table.h index 85de26f0d0b6b41b4f7bc1a6d963b6e81d5853af..dfabd3769c78c0e76b706aec5130349d4cc8c6c4 100644 --- a/trace_streamer/src/table/ebpf/ebpf_callstack_table.h +++ b/trace_streamer/src/table/ebpf/include/ebpf_callstack_table.h @@ -17,7 +17,7 @@ #define EBPF_CALLSTACK_TABLE_H #include "table_base.h" -#include "trace_stdtype.h" +#include "ebpf_stdtype.h" namespace SysTuning { namespace TraceStreamer { diff --git a/trace_streamer/src/table/ebpf/file_system_sample_table.h b/trace_streamer/src/table/ebpf/include/file_system_sample_table.h similarity index 98% rename from trace_streamer/src/table/ebpf/file_system_sample_table.h rename to trace_streamer/src/table/ebpf/include/file_system_sample_table.h index 44bb4c1d820de5559abcfbb45210dcd460d13974..c81ef554c4b77d507ac9c861207b177c8f09a913 100644 --- a/trace_streamer/src/table/ebpf/file_system_sample_table.h +++ b/trace_streamer/src/table/ebpf/include/file_system_sample_table.h @@ -17,7 +17,7 @@ #define FILE_SYSTEM_SAMPLE_TABLE_H #include "table_base.h" -#include "trace_stdtype.h" +#include "ebpf_stdtype.h" namespace SysTuning { namespace TraceStreamer { diff --git a/trace_streamer/src/table/ftrace/BUILD.gn b/trace_streamer/src/table/ftrace/BUILD.gn index c0104432fb3503bc4fe755bd7009af221736b5a1..166f9c03f3996451ae59a16cb817635cc06275a9 100644 --- a/trace_streamer/src/table/ftrace/BUILD.gn +++ b/trace_streamer/src/table/ftrace/BUILD.gn @@ -19,65 +19,35 @@ ohos_source_set("ftrace_tables") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "animation_table.cpp", - "animation_table.h", "app_startup_table.cpp", - "app_startup_table.h", "callstack_table.cpp", - "callstack_table.h", "clk_event_filter_table.cpp", - "clk_event_filter_table.h", "clock_event_filter_table.cpp", - "clock_event_filter_table.h", "clock_snapshot_table.cpp", - "clock_snapshot_table.h", "cpu_measure_filter_table.cpp", - "cpu_measure_filter_table.h", "dynamic_frame_table.cpp", - "dynamic_frame_table.h", "filter_table.cpp", - "filter_table.h", "frame_maps_table.cpp", - "frame_maps_table.h", "frame_slice_table.cpp", - "frame_slice_table.h", "gpu_slice_table.cpp", - "gpu_slice_table.h", "instants_table.cpp", - "instants_table.h", "irq_table.cpp", - "irq_table.h", - "measure_filter_table.cpp", - "measure_filter_table.h", "measure_table.cpp", - "measure_table.h", - "process_filter_table.cpp", - "process_filter_table.h", "process_measure_filter_table.cpp", - "process_measure_filter_table.h", "process_table.cpp", - "process_table.h", "raw_table.cpp", - "raw_table.h", "sched_slice_table.cpp", - "sched_slice_table.h", "so_static_initalization_table.cpp", - "so_static_initalization_table.h", "system_call_table.cpp", - "system_call_table.h", "system_event_filter_table.cpp", - "system_event_filter_table.h", "task_pool_table.cpp", - "task_pool_table.h", - "thread_filter_table.cpp", - "thread_filter_table.h", "thread_state_table.cpp", - "thread_state_table.h", "thread_table.cpp", - "thread_table.h", ] include_dirs = [ - "../base", + "../base/include", + "include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -87,6 +57,16 @@ ohos_source_set("ftrace_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] diff --git a/trace_streamer/src/table/ftrace/frame_maps_table.cpp b/trace_streamer/src/table/ftrace/frame_maps_table.cpp index 2a3d780701f97f4b9334b3f897114e7aea7f7bf7..2dbfef78fddffdad606ba3c6536a77353448f7bb 100644 --- a/trace_streamer/src/table/ftrace/frame_maps_table.cpp +++ b/trace_streamer/src/table/ftrace/frame_maps_table.cpp @@ -58,8 +58,8 @@ std::unique_ptr FrameMapsTable::CreateCursor() } FrameMapsTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstFameMapsData().Size())), - frameMapsObj_(dataCache->GetConstFameMapsData()) + : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstFrameMapsData().Size())), + frameMapsObj_(dataCache->GetConstFrameMapsData()) { } diff --git a/trace_streamer/src/table/ftrace/frame_slice_table.cpp b/trace_streamer/src/table/ftrace/frame_slice_table.cpp index a2a9040e463a9768dd73f828f7692fb8993d83a7..7322bb4b79c1c11d816ffd7635a1bc0e485fe26b 100644 --- a/trace_streamer/src/table/ftrace/frame_slice_table.cpp +++ b/trace_streamer/src/table/ftrace/frame_slice_table.cpp @@ -84,8 +84,8 @@ std::unique_ptr FrameSliceTable::CreateCursor() } FrameSliceTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstFameSliceData().Size())), - frameSliceObj_(dataCache->GetConstFameSliceData()) + : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstFrameSliceData().Size())), + frameSliceObj_(dataCache->GetConstFrameSliceData()) { } diff --git a/trace_streamer/src/table/ftrace/animation_table.h b/trace_streamer/src/table/ftrace/include/animation_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/animation_table.h rename to trace_streamer/src/table/ftrace/include/animation_table.h diff --git a/trace_streamer/src/table/ftrace/app_startup_table.h b/trace_streamer/src/table/ftrace/include/app_startup_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/app_startup_table.h rename to trace_streamer/src/table/ftrace/include/app_startup_table.h diff --git a/trace_streamer/src/table/ftrace/callstack_table.h b/trace_streamer/src/table/ftrace/include/callstack_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/callstack_table.h rename to trace_streamer/src/table/ftrace/include/callstack_table.h diff --git a/trace_streamer/src/table/ftrace/clk_event_filter_table.h b/trace_streamer/src/table/ftrace/include/clk_event_filter_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/clk_event_filter_table.h rename to trace_streamer/src/table/ftrace/include/clk_event_filter_table.h diff --git a/trace_streamer/src/table/ftrace/clock_event_filter_table.h b/trace_streamer/src/table/ftrace/include/clock_event_filter_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/clock_event_filter_table.h rename to trace_streamer/src/table/ftrace/include/clock_event_filter_table.h diff --git a/trace_streamer/src/table/ftrace/clock_snapshot_table.h b/trace_streamer/src/table/ftrace/include/clock_snapshot_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/clock_snapshot_table.h rename to trace_streamer/src/table/ftrace/include/clock_snapshot_table.h diff --git a/trace_streamer/src/table/ftrace/cpu_measure_filter_table.h b/trace_streamer/src/table/ftrace/include/cpu_measure_filter_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/cpu_measure_filter_table.h rename to trace_streamer/src/table/ftrace/include/cpu_measure_filter_table.h diff --git a/trace_streamer/src/table/ftrace/dynamic_frame_table.h b/trace_streamer/src/table/ftrace/include/dynamic_frame_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/dynamic_frame_table.h rename to trace_streamer/src/table/ftrace/include/dynamic_frame_table.h diff --git a/trace_streamer/src/table/ftrace/filter_table.h b/trace_streamer/src/table/ftrace/include/filter_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/filter_table.h rename to trace_streamer/src/table/ftrace/include/filter_table.h diff --git a/trace_streamer/src/table/ftrace/frame_maps_table.h b/trace_streamer/src/table/ftrace/include/frame_maps_table.h similarity index 96% rename from trace_streamer/src/table/ftrace/frame_maps_table.h rename to trace_streamer/src/table/ftrace/include/frame_maps_table.h index fbae67adba329372544f65d3b45ba8d0a1e5118c..f7da99d729c0b1fe0c517453fa68891207e603a9 100644 --- a/trace_streamer/src/table/ftrace/frame_maps_table.h +++ b/trace_streamer/src/table/ftrace/include/frame_maps_table.h @@ -30,7 +30,7 @@ public: private: int64_t GetSize() override { - return dataCache_->GetConstFameMapsData().Size(); + return dataCache_->GetConstFrameMapsData().Size(); } void GetOrbyes(FilterConstraints& mapfc, EstimatedIndexInfo& mapei) override; void FilterByConstraint(FilterConstraints& mapfc, diff --git a/trace_streamer/src/table/ftrace/frame_slice_table.h b/trace_streamer/src/table/ftrace/include/frame_slice_table.h similarity index 96% rename from trace_streamer/src/table/ftrace/frame_slice_table.h rename to trace_streamer/src/table/ftrace/include/frame_slice_table.h index 092cdb462654f81ca07b328dd5d68d79269fe293..cf44aacc55b96141d42ede0ed24d15f56204aba5 100644 --- a/trace_streamer/src/table/ftrace/frame_slice_table.h +++ b/trace_streamer/src/table/ftrace/include/frame_slice_table.h @@ -30,7 +30,7 @@ public: private: int64_t GetSize() override { - return dataCache_->GetConstFameSliceData().Size(); + return dataCache_->GetConstFrameSliceData().Size(); } void GetOrbyes(FilterConstraints& slicefc, EstimatedIndexInfo& sliceei) override; void FilterByConstraint(FilterConstraints& slicefc, diff --git a/trace_streamer/src/table/ftrace/gpu_slice_table.h b/trace_streamer/src/table/ftrace/include/gpu_slice_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/gpu_slice_table.h rename to trace_streamer/src/table/ftrace/include/gpu_slice_table.h diff --git a/trace_streamer/src/table/ftrace/instants_table.h b/trace_streamer/src/table/ftrace/include/instants_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/instants_table.h rename to trace_streamer/src/table/ftrace/include/instants_table.h diff --git a/trace_streamer/src/table/ftrace/irq_table.h b/trace_streamer/src/table/ftrace/include/irq_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/irq_table.h rename to trace_streamer/src/table/ftrace/include/irq_table.h diff --git a/trace_streamer/src/table/ftrace/measure_table.h b/trace_streamer/src/table/ftrace/include/measure_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/measure_table.h rename to trace_streamer/src/table/ftrace/include/measure_table.h diff --git a/trace_streamer/src/table/ftrace/process_measure_filter_table.h b/trace_streamer/src/table/ftrace/include/process_measure_filter_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/process_measure_filter_table.h rename to trace_streamer/src/table/ftrace/include/process_measure_filter_table.h diff --git a/trace_streamer/src/table/ftrace/process_table.h b/trace_streamer/src/table/ftrace/include/process_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/process_table.h rename to trace_streamer/src/table/ftrace/include/process_table.h diff --git a/trace_streamer/src/table/ftrace/raw_table.h b/trace_streamer/src/table/ftrace/include/raw_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/raw_table.h rename to trace_streamer/src/table/ftrace/include/raw_table.h diff --git a/trace_streamer/src/table/ftrace/sched_slice_table.h b/trace_streamer/src/table/ftrace/include/sched_slice_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/sched_slice_table.h rename to trace_streamer/src/table/ftrace/include/sched_slice_table.h diff --git a/trace_streamer/src/table/ftrace/so_static_initalization_table.h b/trace_streamer/src/table/ftrace/include/so_static_initalization_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/so_static_initalization_table.h rename to trace_streamer/src/table/ftrace/include/so_static_initalization_table.h diff --git a/trace_streamer/src/table/ftrace/system_call_table.h b/trace_streamer/src/table/ftrace/include/system_call_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/system_call_table.h rename to trace_streamer/src/table/ftrace/include/system_call_table.h diff --git a/trace_streamer/src/table/ftrace/system_event_filter_table.h b/trace_streamer/src/table/ftrace/include/system_event_filter_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/system_event_filter_table.h rename to trace_streamer/src/table/ftrace/include/system_event_filter_table.h diff --git a/trace_streamer/src/table/ftrace/task_pool_table.h b/trace_streamer/src/table/ftrace/include/task_pool_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/task_pool_table.h rename to trace_streamer/src/table/ftrace/include/task_pool_table.h diff --git a/trace_streamer/src/table/ftrace/thread_state_table.h b/trace_streamer/src/table/ftrace/include/thread_state_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/thread_state_table.h rename to trace_streamer/src/table/ftrace/include/thread_state_table.h diff --git a/trace_streamer/src/table/ftrace/thread_table.h b/trace_streamer/src/table/ftrace/include/thread_table.h similarity index 100% rename from trace_streamer/src/table/ftrace/thread_table.h rename to trace_streamer/src/table/ftrace/include/thread_table.h diff --git a/trace_streamer/src/table/ftrace/measure_filter_table.cpp b/trace_streamer/src/table/ftrace/measure_filter_table.cpp deleted file mode 100644 index c2855662d10fe5b0a62a91d26c42d1a8b6bdde4e..0000000000000000000000000000000000000000 --- a/trace_streamer/src/table/ftrace/measure_filter_table.cpp +++ /dev/null @@ -1,73 +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. - */ - -#include "measure_filter_table.h" - -namespace SysTuning { -namespace TraceStreamer { -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")); - tableColumn_.push_back(TableBase::ColumnInfo("type", "TEXT")); - tableColumn_.push_back(TableBase::ColumnInfo("name", "TEXT")); - tableColumn_.push_back(TableBase::ColumnInfo("itid", "INTEGER")); - tablePriKey_.push_back("id"); -} - -MeasureFilterTable::~MeasureFilterTable() {} - -std::unique_ptr MeasureFilterTable::CreateCursor() -{ - return std::make_unique(dataCache_, this); -} - -MeasureFilterTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstThreadMeasureFilterData().Size())) -{ -} - -MeasureFilterTable::Cursor::~Cursor() {} - -int32_t MeasureFilterTable::Cursor::Column(int32_t column) const -{ - switch (static_cast(column)) { - case Index::ID: - sqlite3_result_int64( - context_, - static_cast(dataCache_->GetConstThreadMeasureFilterData().FilterIdData()[CurrentRow()])); - break; - case Index::TYPE: - sqlite3_result_text(context_, "thread_measure_filter", STR_DEFAULT_LEN, nullptr); - break; - 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 Index::INTERNAL_TID: - sqlite3_result_int64( - context_, - static_cast(dataCache_->GetConstThreadMeasureFilterData().InternalTidData()[CurrentRow()])); - break; - default: - TS_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/table/ftrace/process_filter_table.cpp b/trace_streamer/src/table/ftrace/process_filter_table.cpp deleted file mode 100644 index 22a5739289fd113daf9703287b58b5b699ed9d54..0000000000000000000000000000000000000000 --- a/trace_streamer/src/table/ftrace/process_filter_table.cpp +++ /dev/null @@ -1,70 +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. - */ - -#include "process_filter_table.h" - -namespace SysTuning { -namespace TraceStreamer { -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")); - tableColumn_.push_back(TableBase::ColumnInfo("type", "TEXT")); - tableColumn_.push_back(TableBase::ColumnInfo("name", "TEXT")); - tableColumn_.push_back(TableBase::ColumnInfo("ipid", "INTEGER")); - tablePriKey_.push_back("id"); -} - -ProcessFilterTable::~ProcessFilterTable() {} - -std::unique_ptr ProcessFilterTable::CreateCursor() -{ - return std::make_unique(dataCache_, this); -} - -ProcessFilterTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstProcessFilterData().Size())), - processFilterObj_(dataCache->GetConstProcessFilterData()) -{ -} - -ProcessFilterTable::Cursor::~Cursor() {} - -int32_t ProcessFilterTable::Cursor::Column(int32_t col) const -{ - switch (static_cast(col)) { - case Index::ID: - sqlite3_result_int64(context_, static_cast(processFilterObj_.IdsData()[CurrentRow()])); - break; - case Index::TYPE: - sqlite3_result_text(context_, "process_filter", STR_DEFAULT_LEN, nullptr); - break; - 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 Index::INTERNAL_PID: - sqlite3_result_int64(context_, static_cast(processFilterObj_.UpidsData()[CurrentRow()])); - break; - default: - TS_LOGF("Unregistered column : %d", col); - break; - } - return SQLITE_OK; -} -} // namespace TraceStreamer -} // namespace SysTuning 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 6b9c7e38bb5df1048673d8fa16575f746db42682..9be821f6fd336d058bb21e689e0dd842807f50cd 100644 --- a/trace_streamer/src/table/ftrace/so_static_initalization_table.cpp +++ b/trace_streamer/src/table/ftrace/so_static_initalization_table.cpp @@ -39,8 +39,8 @@ std::unique_ptr SoStaticInitalizationTable::CreateCursor() } SoStaticInitalizationTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstStaticInitalizationData().Size())), - staticInitalizationObj_(dataCache->GetConstStaticInitalizationData()) + : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstSoStaticInitalizationData().Size())), + staticInitalizationObj_(dataCache->GetConstSoStaticInitalizationData()) { } diff --git a/trace_streamer/src/table/ftrace/thread_filter_table.cpp b/trace_streamer/src/table/ftrace/thread_filter_table.cpp deleted file mode 100644 index 067149b1e9e98ce2d7ba5d8c674f8779e00b67c8..0000000000000000000000000000000000000000 --- a/trace_streamer/src/table/ftrace/thread_filter_table.cpp +++ /dev/null @@ -1,71 +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. - */ - -#include "thread_filter_table.h" - -namespace SysTuning { -namespace TraceStreamer { -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")); - tableColumn_.push_back(TableBase::ColumnInfo("type", "TEXT")); - tableColumn_.push_back(TableBase::ColumnInfo("name", "TEXT")); - tableColumn_.push_back(TableBase::ColumnInfo("itid", "INTEGER")); - tablePriKey_.push_back("id"); -} - -ThreadFilterTable::~ThreadFilterTable() {} - -std::unique_ptr ThreadFilterTable::CreateCursor() -{ - return std::make_unique(dataCache_, this); -} - -ThreadFilterTable::Cursor::Cursor(const TraceDataCache* dataCache, TableBase* table) - : TableBase::Cursor(dataCache, table, static_cast(dataCache->GetConstThreadFilterData().Size())) -{ -} - -ThreadFilterTable::Cursor::~Cursor() {} - -int32_t ThreadFilterTable::Cursor::Column(int32_t column) const -{ - switch (static_cast(column)) { - case Index::ID: - sqlite3_result_int64(context_, static_cast( - dataCache_->GetConstThreadFilterData().FilterIdData()[CurrentRow()])); - break; - case Index::TYPE: - sqlite3_result_text(context_, "thread_filter", STR_DEFAULT_LEN, nullptr); - break; - 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 Index::INTERNAL_TID: - sqlite3_result_int64(context_, static_cast( - dataCache_->GetConstThreadFilterData().InternalTidData()[CurrentRow()])); - break; - default: - TS_LOGF("Unregistered column : %d", column); - break; - } - return SQLITE_OK; -} -} // namespace TraceStreamer -} // namespace SysTuning diff --git a/trace_streamer/src/table/hi_sysevent/BUILD.gn b/trace_streamer/src/table/hi_sysevent/BUILD.gn index 633830da9aca07b08933398847fa1cc23a200a0f..f3bee1e99a8d1f3a9f8e0fa29d5e8a449b50bd3e 100644 --- a/trace_streamer/src/table/hi_sysevent/BUILD.gn +++ b/trace_streamer/src/table/hi_sysevent/BUILD.gn @@ -19,16 +19,13 @@ ohos_source_set("hi_sysevent_tables") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "device_state_table.cpp", - "device_state_table.h", "sysevent_all_event_table.cpp", - "sysevent_all_event_table.h", "sysevent_measure_table.cpp", - "sysevent_measure_table.h", "sysevent_subkey_table.cpp", - "sysevent_subkey_table.h", ] include_dirs = [ - "../base", + "include", + "../base/include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -38,7 +35,16 @@ ohos_source_set("hi_sysevent_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/hi_sysevent/device_state_table.h b/trace_streamer/src/table/hi_sysevent/include/device_state_table.h similarity index 100% rename from trace_streamer/src/table/hi_sysevent/device_state_table.h rename to trace_streamer/src/table/hi_sysevent/include/device_state_table.h diff --git a/trace_streamer/src/table/hi_sysevent/sysevent_all_event_table.h b/trace_streamer/src/table/hi_sysevent/include/sysevent_all_event_table.h similarity index 100% rename from trace_streamer/src/table/hi_sysevent/sysevent_all_event_table.h rename to trace_streamer/src/table/hi_sysevent/include/sysevent_all_event_table.h diff --git a/trace_streamer/src/table/hi_sysevent/sysevent_measure_table.h b/trace_streamer/src/table/hi_sysevent/include/sysevent_measure_table.h similarity index 100% rename from trace_streamer/src/table/hi_sysevent/sysevent_measure_table.h rename to trace_streamer/src/table/hi_sysevent/include/sysevent_measure_table.h diff --git a/trace_streamer/src/table/hi_sysevent/sysevent_subkey_table.h b/trace_streamer/src/table/hi_sysevent/include/sysevent_subkey_table.h similarity index 100% rename from trace_streamer/src/table/hi_sysevent/sysevent_subkey_table.h rename to trace_streamer/src/table/hi_sysevent/include/sysevent_subkey_table.h diff --git a/trace_streamer/src/table/hiperf/BUILD.gn b/trace_streamer/src/table/hiperf/BUILD.gn index 7a27e01f5e40b392fba89c4cfab4d20ec428f342..ca2508bed8e3d6363c118aa89be9e7ad2fd88aca 100644 --- a/trace_streamer/src/table/hiperf/BUILD.gn +++ b/trace_streamer/src/table/hiperf/BUILD.gn @@ -19,19 +19,15 @@ ohos_source_set("hiperf_tables") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "perf_call_chain_table.cpp", - "perf_call_chain_table.h", "perf_files_table.cpp", - "perf_files_table.h", "perf_report_table.cpp", - "perf_report_table.h", "perf_sample_table.cpp", - "perf_sample_table.h", "perf_thread_table.cpp", - "perf_thread_table.h", ] include_dirs = [ - "../base", + "include", + "../base/include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -41,7 +37,16 @@ ohos_source_set("hiperf_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/hiperf/perf_call_chain_table.h b/trace_streamer/src/table/hiperf/include/perf_call_chain_table.h similarity index 100% rename from trace_streamer/src/table/hiperf/perf_call_chain_table.h rename to trace_streamer/src/table/hiperf/include/perf_call_chain_table.h diff --git a/trace_streamer/src/table/hiperf/perf_files_table.h b/trace_streamer/src/table/hiperf/include/perf_files_table.h similarity index 100% rename from trace_streamer/src/table/hiperf/perf_files_table.h rename to trace_streamer/src/table/hiperf/include/perf_files_table.h diff --git a/trace_streamer/src/table/hiperf/perf_report_table.h b/trace_streamer/src/table/hiperf/include/perf_report_table.h similarity index 100% rename from trace_streamer/src/table/hiperf/perf_report_table.h rename to trace_streamer/src/table/hiperf/include/perf_report_table.h diff --git a/trace_streamer/src/table/hiperf/perf_sample_table.h b/trace_streamer/src/table/hiperf/include/perf_sample_table.h similarity index 100% rename from trace_streamer/src/table/hiperf/perf_sample_table.h rename to trace_streamer/src/table/hiperf/include/perf_sample_table.h diff --git a/trace_streamer/src/table/hiperf/perf_thread_table.h b/trace_streamer/src/table/hiperf/include/perf_thread_table.h similarity index 100% rename from trace_streamer/src/table/hiperf/perf_thread_table.h rename to trace_streamer/src/table/hiperf/include/perf_thread_table.h diff --git a/trace_streamer/src/table/js_memory/BUILD.gn b/trace_streamer/src/table/js_memory/BUILD.gn index be58ffcf652333c9c15f6db9e0661677101bf5b8..549bed832882fd5eb5b61d05e6e40bf941191770 100644 --- a/trace_streamer/src/table/js_memory/BUILD.gn +++ b/trace_streamer/src/table/js_memory/BUILD.gn @@ -19,32 +19,21 @@ ohos_source_set("js_memory_tables") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "js_config_table.cpp", - "js_config_table.h", "js_cpu_profiler_node_table.cpp", - "js_cpu_profiler_node_table.h", "js_cpu_profiler_sample_table.cpp", - "js_cpu_profiler_sample_table.h", "js_heap_edges_table.cpp", - "js_heap_edges_table.h", "js_heap_files_table.cpp", - "js_heap_files_table.h", "js_heap_info_table.cpp", - "js_heap_info_table.h", "js_heap_location_table.cpp", - "js_heap_location_table.h", "js_heap_nodes_table.cpp", - "js_heap_nodes_table.h", "js_heap_sample_table.cpp", - "js_heap_sample_table.h", "js_heap_string_table.cpp", - "js_heap_string_table.h", "js_heap_trace_function_info_table.cpp", - "js_heap_trace_function_info_table.h", "js_heap_trace_node_table.cpp", - "js_heap_trace_node_table.h", ] include_dirs = [ - "../base", + "include", + "../base/include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -54,7 +43,16 @@ ohos_source_set("js_memory_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/js_memory/js_config_table.h b/trace_streamer/src/table/js_memory/include/js_config_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_config_table.h rename to trace_streamer/src/table/js_memory/include/js_config_table.h diff --git a/trace_streamer/src/table/js_memory/js_cpu_profiler_node_table.h b/trace_streamer/src/table/js_memory/include/js_cpu_profiler_node_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_cpu_profiler_node_table.h rename to trace_streamer/src/table/js_memory/include/js_cpu_profiler_node_table.h diff --git a/trace_streamer/src/table/js_memory/js_cpu_profiler_sample_table.h b/trace_streamer/src/table/js_memory/include/js_cpu_profiler_sample_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_cpu_profiler_sample_table.h rename to trace_streamer/src/table/js_memory/include/js_cpu_profiler_sample_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_edges_table.h b/trace_streamer/src/table/js_memory/include/js_heap_edges_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_edges_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_edges_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_files_table.h b/trace_streamer/src/table/js_memory/include/js_heap_files_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_files_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_files_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_info_table.h b/trace_streamer/src/table/js_memory/include/js_heap_info_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_info_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_info_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_location_table.h b/trace_streamer/src/table/js_memory/include/js_heap_location_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_location_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_location_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_nodes_table.h b/trace_streamer/src/table/js_memory/include/js_heap_nodes_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_nodes_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_nodes_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_sample_table.h b/trace_streamer/src/table/js_memory/include/js_heap_sample_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_sample_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_sample_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_string_table.h b/trace_streamer/src/table/js_memory/include/js_heap_string_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_string_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_string_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_trace_function_info_table.h b/trace_streamer/src/table/js_memory/include/js_heap_trace_function_info_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_trace_function_info_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_trace_function_info_table.h diff --git a/trace_streamer/src/table/js_memory/js_heap_trace_node_table.h b/trace_streamer/src/table/js_memory/include/js_heap_trace_node_table.h similarity index 100% rename from trace_streamer/src/table/js_memory/js_heap_trace_node_table.h rename to trace_streamer/src/table/js_memory/include/js_heap_trace_node_table.h diff --git a/trace_streamer/src/table/monitor/BUILD.gn b/trace_streamer/src/table/monitor/BUILD.gn index 554a5f5076072f2fadbad54638c26658a769ba14..4e2c619969d85ccb94ef96866b0ef72c8fe2077b 100644 --- a/trace_streamer/src/table/monitor/BUILD.gn +++ b/trace_streamer/src/table/monitor/BUILD.gn @@ -35,7 +35,8 @@ ohos_source_set("monitor_tables") { "smaps_table.cpp", ] include_dirs = [ - "../base", + "include", + "../base/include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -45,7 +46,16 @@ ohos_source_set("monitor_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/monitor/cpu_usage_info_table.h b/trace_streamer/src/table/monitor/include/cpu_usage_info_table.h similarity index 100% rename from trace_streamer/src/table/monitor/cpu_usage_info_table.h rename to trace_streamer/src/table/monitor/include/cpu_usage_info_table.h diff --git a/trace_streamer/src/table/monitor/disk_io_table.h b/trace_streamer/src/table/monitor/include/disk_io_table.h similarity index 100% rename from trace_streamer/src/table/monitor/disk_io_table.h rename to trace_streamer/src/table/monitor/include/disk_io_table.h diff --git a/trace_streamer/src/table/monitor/hidump_table.h b/trace_streamer/src/table/monitor/include/hidump_table.h similarity index 100% rename from trace_streamer/src/table/monitor/hidump_table.h rename to trace_streamer/src/table/monitor/include/hidump_table.h diff --git a/trace_streamer/src/table/monitor/live_process_table.h b/trace_streamer/src/table/monitor/include/live_process_table.h similarity index 100% rename from trace_streamer/src/table/monitor/live_process_table.h rename to trace_streamer/src/table/monitor/include/live_process_table.h diff --git a/trace_streamer/src/table/monitor/log_table.h b/trace_streamer/src/table/monitor/include/log_table.h similarity index 100% rename from trace_streamer/src/table/monitor/log_table.h rename to trace_streamer/src/table/monitor/include/log_table.h diff --git a/trace_streamer/src/table/monitor/memory_ashmem_table.h b/trace_streamer/src/table/monitor/include/memory_ashmem_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_ashmem_table.h rename to trace_streamer/src/table/monitor/include/memory_ashmem_table.h diff --git a/trace_streamer/src/table/monitor/memory_cpu_table.h b/trace_streamer/src/table/monitor/include/memory_cpu_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_cpu_table.h rename to trace_streamer/src/table/monitor/include/memory_cpu_table.h diff --git a/trace_streamer/src/table/monitor/memory_dma_table.h b/trace_streamer/src/table/monitor/include/memory_dma_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_dma_table.h rename to trace_streamer/src/table/monitor/include/memory_dma_table.h diff --git a/trace_streamer/src/table/monitor/memory_process_gpu_table.h b/trace_streamer/src/table/monitor/include/memory_process_gpu_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_process_gpu_table.h rename to trace_streamer/src/table/monitor/include/memory_process_gpu_table.h diff --git a/trace_streamer/src/table/monitor/memory_profile_table.h b/trace_streamer/src/table/monitor/include/memory_profile_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_profile_table.h rename to trace_streamer/src/table/monitor/include/memory_profile_table.h diff --git a/trace_streamer/src/table/monitor/memory_rs_image_table.h b/trace_streamer/src/table/monitor/include/memory_rs_image_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_rs_image_table.h rename to trace_streamer/src/table/monitor/include/memory_rs_image_table.h diff --git a/trace_streamer/src/table/monitor/memory_window_gpu_table.h b/trace_streamer/src/table/monitor/include/memory_window_gpu_table.h similarity index 100% rename from trace_streamer/src/table/monitor/memory_window_gpu_table.h rename to trace_streamer/src/table/monitor/include/memory_window_gpu_table.h diff --git a/trace_streamer/src/table/monitor/network_table.h b/trace_streamer/src/table/monitor/include/network_table.h similarity index 100% rename from trace_streamer/src/table/monitor/network_table.h rename to trace_streamer/src/table/monitor/include/network_table.h diff --git a/trace_streamer/src/table/monitor/paged_memory_sample_table.h b/trace_streamer/src/table/monitor/include/paged_memory_sample_table.h similarity index 100% rename from trace_streamer/src/table/monitor/paged_memory_sample_table.h rename to trace_streamer/src/table/monitor/include/paged_memory_sample_table.h diff --git a/trace_streamer/src/table/monitor/smaps_table.h b/trace_streamer/src/table/monitor/include/smaps_table.h similarity index 100% rename from trace_streamer/src/table/monitor/smaps_table.h rename to trace_streamer/src/table/monitor/include/smaps_table.h diff --git a/trace_streamer/src/table/native_hook/BUILD.gn b/trace_streamer/src/table/native_hook/BUILD.gn index 03f6ab9de3422e02245212af32a222a05e498d77..9785cc4578c92fc3f59115e24aaecb5ce52e36c8 100644 --- a/trace_streamer/src/table/native_hook/BUILD.gn +++ b/trace_streamer/src/table/native_hook/BUILD.gn @@ -19,15 +19,13 @@ ohos_source_set("native_hook_tables") { part_name = "${OHOS_PROFILER_PART_NAME}" sources = [ "native_hook_frame_table.cpp", - "native_hook_frame_table.h", "native_hook_statistic_table.cpp", - "native_hook_statistic_table.h", "native_hook_table.cpp", - "native_hook_table.h", ] include_dirs = [ - "../base", + "include", + "../base/include", "${THIRD_PARTY}/sqlite/include", "${SRC}/base", "../../parser", @@ -37,7 +35,16 @@ ohos_source_set("native_hook_tables") { "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", ] - + include_dirs += [ + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", + ] if (!is_independent_compile) { configs = [ "${TS_DIR}/gn:ts_config" ] } diff --git a/trace_streamer/src/table/native_hook/native_hook_frame_table.h b/trace_streamer/src/table/native_hook/include/native_hook_frame_table.h similarity index 100% rename from trace_streamer/src/table/native_hook/native_hook_frame_table.h rename to trace_streamer/src/table/native_hook/include/native_hook_frame_table.h diff --git a/trace_streamer/src/table/native_hook/native_hook_statistic_table.h b/trace_streamer/src/table/native_hook/include/native_hook_statistic_table.h similarity index 100% rename from trace_streamer/src/table/native_hook/native_hook_statistic_table.h rename to trace_streamer/src/table/native_hook/include/native_hook_statistic_table.h diff --git a/trace_streamer/src/table/native_hook/native_hook_table.h b/trace_streamer/src/table/native_hook/include/native_hook_table.h similarity index 100% rename from trace_streamer/src/table/native_hook/native_hook_table.h rename to trace_streamer/src/table/native_hook/include/native_hook_table.h diff --git a/trace_streamer/src/trace_data/BUILD.gn b/trace_streamer/src/trace_data/BUILD.gn index 6bb091d453e1bc9bdd8f06477dbb092bfa4c5308..121ff2ecaa5061f623ef6a3af0eb095b1b9a48da 100644 --- a/trace_streamer/src/trace_data/BUILD.gn +++ b/trace_streamer/src/trace_data/BUILD.gn @@ -30,8 +30,23 @@ ohos_source_set("trace_data") { "trace_data_cache_writer.h", "trace_data_db.cpp", "trace_data_db.h", - "trace_stdtype.cpp", - "trace_stdtype.h", + "trace_stdtype/base_stdtype.cpp", + "trace_stdtype/common_stdtype.cpp", + "trace_stdtype/ftrace/callstack_stdtype.cpp", + "trace_stdtype/ftrace/render_service_stdtype.cpp", + "trace_stdtype/ftrace/sched_stdtype.cpp", + "trace_stdtype/ftrace/syscall_stdtype.cpp", + "trace_stdtype/ftrace/template/animation_stdtype.cpp", + "trace_stdtype/ftrace/template/app_startup_stdtype.cpp", + "trace_stdtype/ftrace/template/task_pool_stdtype.cpp", + "trace_stdtype/hilog/hilog_stdtype.cpp", + "trace_stdtype/hiperf/hiperf_stdtype.cpp", + "trace_stdtype/hisysevent/hisysevent_stdtype.cpp", + "trace_stdtype/htrace/activity_monitor_stdtype.cpp", + "trace_stdtype/htrace/arkts_stdtype.cpp", + "trace_stdtype/htrace/ebpf_stdtype.cpp", + "trace_stdtype/htrace/native_memory_stdtype.cpp", + "trace_stdtype/measure/measure_stdtype.cpp", ] if (!is_independent_compile) { @@ -57,19 +72,27 @@ ohos_source_set("trace_data") { "${SRC}/base", "${SRC}/include", "${SRC}/table", - "${SRC}/table/base", - "${SRC}/table/ebpf", - "${SRC}/table/ftrace", - "${SRC}/table/hiperf", - "${SRC}/table/hi_sysevent", - "${SRC}/table/js_memory", - "${SRC}/table/monitor", - "${SRC}/table/native_hook", + "${SRC}/table/base/include", + "${SRC}/table/ebpf/include", + "${SRC}/table/ftrace/include", + "${SRC}/table/hiperf/include", + "${SRC}/table/hi_sysevent/include", + "${SRC}/table/js_memory/include", + "${SRC}/table/monitor/include", + "${SRC}/table/native_hook/include", ".", "${THIRD_PARTY}/protobuf/src", "${THIRD_PARTY}/bounds_checking_function/include", "${THIRD_PARTY}/json/single_include/nlohmann", "${THIRD_PARTY}/perf_include/hiviewdfx/faultloggerd/interfaces/nonlinux", + "${SRC}/trace_data/trace_stdtype", + "${SRC}/trace_data/trace_stdtype/ftrace", + "${SRC}/trace_data/trace_stdtype/ftrace/template", + "${SRC}/trace_data/trace_stdtype/hilog", + "${SRC}/trace_data/trace_stdtype/hiperf", + "${SRC}/trace_data/trace_stdtype/hisysevent", + "${SRC}/trace_data/trace_stdtype/htrace", + "${SRC}/trace_data/trace_stdtype/measure", ] deps = [ diff --git a/trace_streamer/src/trace_data/trace_data_cache.cpp b/trace_streamer/src/trace_data/trace_data_cache.cpp index 67672048da5a499f690386ca5bf97b3261f28850..ed21710be89e67cbf6fb0b578c10ae88e7e76bee 100644 --- a/trace_streamer/src/trace_data/trace_data_cache.cpp +++ b/trace_streamer/src/trace_data/trace_data_cache.cpp @@ -39,11 +39,6 @@ #include "disk_io_table.h" #include "dynamic_frame_table.h" #include "ebpf_callstack_table.h" -#if WITH_EBPF_HELP -#include "ebpf_elf_symbol_table.h" -#include "ebpf_elf_table.h" -#include "ebpf_process_maps_table.h" -#endif #include "file.h" #include "file_system_sample_table.h" #include "filter_table.h" @@ -67,7 +62,6 @@ #include "irq_table.h" #include "live_process_table.h" #include "log_table.h" -#include "measure_filter_table.h" #include "measure_table.h" #include "memory_ashmem_table.h" #include "memory_dma_table.h" @@ -83,13 +77,12 @@ #include "native_hook_statistic_table.h" #include "network_table.h" #include "paged_memory_sample_table.h" -#include "parser/ebpf_parser/ebpf_stdtype.h" +#include "parser/ebpf_parser/ebpf_data_structure.h" #include "perf_call_chain_table.h" #include "perf_files_table.h" #include "perf_report_table.h" #include "perf_sample_table.h" #include "perf_thread_table.h" -#include "process_filter_table.h" #include "process_measure_filter_table.h" #include "process_table.h" #include "range_table.h" @@ -109,7 +102,6 @@ #include "system_event_filter_table.h" #include "table_base.h" #include "task_pool_table.h" -#include "thread_filter_table.h" #include "thread_state_table.h" #include "thread_table.h" #include "trace_config_table.h" @@ -137,9 +129,6 @@ void TraceDataCache::InitDB() TableBase::TableDeclare(*db_, this, "callstack"); TableBase::TableDeclare(*db_, this, "thread"); TableBase::TableDeclare(*db_, this, "thread_state"); - TableBase::TableDeclare(*db_, this, "thread_filter"); - TableBase::TableDeclare(*db_, this, "process_filter"); - TableBase::TableDeclare(*db_, this, "measure_filter"); TableBase::TableDeclare(*db_, this, "irq"); TableBase::TableDeclare(*db_, this, "data_dict"); TableBase::TableDeclare(*db_, this, "raw"); @@ -192,11 +181,6 @@ void TraceDataCache::InitDB() TableBase::TableDeclare(*db_, this, "file_system_sample"); TableBase::TableDeclare(*db_, this, "ebpf_callstack"); TableBase::TableDeclare(*db_, this, "paged_memory_sample"); -#if WITH_EBPF_HELP - TableBase::TableDeclare(*db_, this, "ebpf_process_maps"); - TableBase::TableDeclare(*db_, this, "ebpf_elf"); - TableBase::TableDeclare(*db_, this, "ebpf_elf_symbol"); -#endif TableBase::TableDeclare(*db_, this, "app_name"); TableBase::TableDeclare(*db_, this, "hisys_event_measure"); TableBase::TableDeclare(*db_, this, "trace_config"); @@ -604,122 +588,38 @@ void TraceDataCache::ExportEbpfCallChaninText(uint32_t callChainId, std::string& void TraceDataCache::ClearAllPrevCacheData() { // ftrace plugin - rawData_.ClearPrevData(); - threadStateData_.ClearPrevData(); - instantsData_.ClearPrevData(); - filterData_.ClearPrevData(); - processMeasureFilterData_.ClearPrevData(); - clockEventFilterData_.ClearPrevData(); - clkEventFilterData_.ClearPrevData(); - processFilterData_.ClearPrevData(); - threadMeasureFilterData_.ClearPrevData(); - threadFilterData_.ClearPrevData(); - schedSliceData_.ClearPrevData(); - callstackData_.ClearPrevData(); - irqData_.ClearPrevData(); - measureData_.ClearPrevData(); - sysMemMeasureData_.ClearPrevData(); - processMeasureData_.ClearPrevData(); - cpuMeasureData_.ClearPrevData(); - taskPoolInfo_.ClearPrevData(); - appStartupData_.ClearPrevData(); - animation_.ClearPrevData(); - dynamicFrame_.ClearPrevData(); - rsImageDumpInfo_.ClearPrevData(); - // hilog plugin - hilogData_.ClearPrevData(); - // native_hook plugin - nativeHookData_.ClearPrevData(); - nativeHookFrameData_.ClearPrevData(); - nativeHookStatisticData_.ClearPrevData(); - // hidump plugin - hidumpData_.ClearPrevData(); - - // hisysevent plugin - sysEventNameIds_.ClearPrevData(); - sysEventMeasureData_.ClearPrevData(); - deviceStateData_.ClearPrevData(); - traceConfigData_.ClearPrevData(); - hiSysEventAllEventData_.ClearPrevData(); - - sysCallData_.ClearPrevData(); - sysEvent_.ClearPrevData(); - networkData_.ClearPrevData(); - networkDetailData_.ClearPrevData(); - cpuUsageData_.ClearPrevData(); - diskIOData_.ClearPrevData(); - liveProcessDetailData_.ClearPrevData(); - smapsData_.ClearPrevData(); - frameSliceData_.ClearPrevData(); - frameMapsData_.ClearPrevData(); - gpuSliceData_.ClearPrevData(); - staticInitalizationData_.ClearPrevData(); - ashMemData_.ClearPrevData(); - dmaMemData_.ClearPrevData(); - gpuProcessMemData_.ClearPrevData(); - gpuWindowMemData_.ClearPrevData(); - cpuDumpInfo_.ClearPrevData(); - profileMemInfo_.ClearPrevData(); + rawData_.ClearExportedData(); + threadStateData_.ClearExportedData(); + instantsData_.ClearExportedData(); + filterData_.ClearExportedData(); + processMeasureFilterData_.ClearExportedData(); + clockEventFilterData_.ClearExportedData(); + clkEventFilterData_.ClearExportedData(); + schedSliceData_.ClearExportedData(); + irqData_.ClearExportedData(); + measureData_.ClearExportedData(); + sysMemMeasureData_.ClearExportedData(); + processMeasureData_.ClearExportedData(); + cpuMeasureData_.ClearExportedData(); + sysCallData_.ClearExportedData(); } void TraceDataCache::UpdateAllPrevSize() { // ftrace plugin - rawData_.UpdatePrevSize(rawData_.Size()); - threadStateData_.UpdatePrevSize(threadStateData_.Size()); - instantsData_.UpdatePrevSize(instantsData_.Size()); - filterData_.UpdatePrevSize(filterData_.Size()); - processMeasureFilterData_.UpdatePrevSize(processMeasureFilterData_.Size()); - clockEventFilterData_.UpdatePrevSize(clockEventFilterData_.Size()); - clkEventFilterData_.UpdatePrevSize(clkEventFilterData_.Size()); - processFilterData_.UpdatePrevSize(processFilterData_.Size()); - threadMeasureFilterData_.UpdatePrevSize(threadMeasureFilterData_.Size()); - threadFilterData_.UpdatePrevSize(threadFilterData_.Size()); - schedSliceData_.UpdatePrevSize(schedSliceData_.Size()); - callstackData_.UpdatePrevSize(callstackData_.Size()); - irqData_.UpdatePrevSize(irqData_.Size()); - measureData_.UpdatePrevSize(measureData_.Size()); - sysMemMeasureData_.UpdatePrevSize(sysMemMeasureData_.Size()); - processMeasureData_.UpdatePrevSize(processMeasureData_.Size()); - cpuMeasureData_.UpdatePrevSize(cpuMeasureData_.Size()); - rsImageDumpInfo_.UpdatePrevSize(rsImageDumpInfo_.Size()); - animation_.UpdatePrevSize(animation_.Size()); - dynamicFrame_.UpdatePrevSize(dynamicFrame_.Size()); - taskPoolInfo_.UpdatePrevSize(taskPoolInfo_.Size()); - appStartupData_.UpdatePrevSize(appStartupData_.Size()); - // hilog plugin - hilogData_.UpdatePrevSize(hilogData_.Size()); - // native_hook plugin - nativeHookData_.UpdatePrevSize(nativeHookData_.Size()); - nativeHookFrameData_.UpdatePrevSize(nativeHookFrameData_.Size()); - nativeHookStatisticData_.UpdatePrevSize(nativeHookStatisticData_.Size()); - // hidump plugin - hidumpData_.UpdatePrevSize(hidumpData_.Size()); - - // hisysevent plugin - sysEventNameIds_.UpdatePrevSize(sysEventNameIds_.Size()); - sysEventMeasureData_.UpdatePrevSize(sysEventMeasureData_.Size()); - deviceStateData_.UpdatePrevSize(deviceStateData_.Size()); - traceConfigData_.UpdatePrevSize(traceConfigData_.Size()); - hiSysEventAllEventData_.UpdatePrevSize(hiSysEventAllEventData_.Size()); - - sysCallData_.UpdatePrevSize(sysCallData_.Size()); - sysEvent_.UpdatePrevSize(sysEvent_.Size()); - networkData_.UpdatePrevSize(networkData_.Size()); - networkDetailData_.UpdatePrevSize(networkDetailData_.Size()); - cpuUsageData_.UpdatePrevSize(cpuUsageData_.Size()); - diskIOData_.UpdatePrevSize(diskIOData_.Size()); - liveProcessDetailData_.UpdatePrevSize(liveProcessDetailData_.Size()); - smapsData_.UpdatePrevSize(smapsData_.Size()); - frameSliceData_.UpdatePrevSize(frameSliceData_.Size()); - frameMapsData_.UpdatePrevSize(frameMapsData_.Size()); - gpuSliceData_.UpdatePrevSize(gpuSliceData_.Size()); - staticInitalizationData_.UpdatePrevSize(staticInitalizationData_.Size()); - ashMemData_.UpdatePrevSize(ashMemData_.Size()); - dmaMemData_.UpdatePrevSize(dmaMemData_.Size()); - gpuProcessMemData_.UpdatePrevSize(gpuProcessMemData_.Size()); - gpuWindowMemData_.UpdatePrevSize(gpuWindowMemData_.Size()); - cpuDumpInfo_.UpdatePrevSize(cpuDumpInfo_.Size()); - profileMemInfo_.UpdatePrevSize(profileMemInfo_.Size()); + rawData_.UpdateReadySize(rawData_.Size()); + threadStateData_.UpdateReadySize(threadStateData_.Size()); + instantsData_.UpdateReadySize(instantsData_.Size()); + filterData_.UpdateReadySize(filterData_.Size()); + processMeasureFilterData_.UpdateReadySize(processMeasureFilterData_.Size()); + clockEventFilterData_.UpdateReadySize(clockEventFilterData_.Size()); + clkEventFilterData_.UpdateReadySize(clkEventFilterData_.Size()); + schedSliceData_.UpdateReadySize(schedSliceData_.Size()); + irqData_.UpdateReadySize(irqData_.Size()); + measureData_.UpdateReadySize(measureData_.Size()); + sysMemMeasureData_.UpdateReadySize(sysMemMeasureData_.Size()); + processMeasureData_.UpdateReadySize(processMeasureData_.Size()); + cpuMeasureData_.UpdateReadySize(cpuMeasureData_.Size()); + sysCallData_.UpdateReadySize(sysCallData_.Size()); } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_data_cache.h b/trace_streamer/src/trace_data/trace_data_cache.h index 1106f7f90751d8950654f87767f62b0a950140c0..15c8495566882c0f102269b44c490382da575fe4 100644 --- a/trace_streamer/src/trace_data/trace_data_cache.h +++ b/trace_streamer/src/trace_data/trace_data_cache.h @@ -54,11 +54,11 @@ public: private: void InitDB(); - void ExportPerfCallChaninText(uint32_t callChainId, std::string& buffLine); - void ExportHookCallChaninText(uint32_t callChainId, std::string& buffLine); + void ExportPerfCallChaninText(uint32_t callChainId, std::string& bufferLine); + void ExportHookCallChaninText(uint32_t callChainId, std::string& bufferLine); bool ExportHookDataReadableText(int32_t fd, std::string& bufferLine); bool ExportHookStatisticReadableText(int32_t fd, std::string& bufferLine); - using EbpfEventTypeMap = std::map; + using EbpfEventTypeMap = std::map; bool ExportEbpfFileSystemReadableText(int32_t fd, std::string& bufferLine, const EbpfEventTypeMap& ebpfEventTypeMap); diff --git a/trace_streamer/src/trace_data/trace_data_cache_base.h b/trace_streamer/src/trace_data/trace_data_cache_base.h index 97b9433bb5b72aaed9d6ef257b4a602b3b04ea41..2affc2a5d12f47bdfbf4992aeab2ff85598e755b 100644 --- a/trace_streamer/src/trace_data/trace_data_cache_base.h +++ b/trace_streamer/src/trace_data/trace_data_cache_base.h @@ -23,8 +23,23 @@ #include #include #include -#include "trace_stdtype.h" -#include "ts_common.h" +#include "activity_monitor_stdtype.h" +#include "animation_stdtype.h" +#include "app_startup_stdtype.h" +#include "arkts_stdtype.h" +#include "base_stdtype.h" +#include "callstack_stdtype.h" +#include "common_stdtype.h" +#include "ebpf_stdtype.h" +#include "hilog_stdtype.h" +#include "hiperf_stdtype.h" +#include "hisysevent_stdtype.h" +#include "measure_stdtype.h" +#include "native_memory_stdtype.h" +#include "render_service_stdtype.h" +#include "sched_stdtype.h" +#include "syscall_stdtype.h" +#include "task_pool_stdtype.h" namespace SysTuning { namespace TraceStreamer { using namespace TraceStdtype; @@ -103,9 +118,6 @@ public: ProcessMeasureFilter processMeasureFilterData_; ClockEventData clockEventFilterData_; ClkEventData clkEventFilterData_; - ProcessMeasureFilter processFilterData_; - ThreadMeasureFilter threadMeasureFilterData_; - ThreadMeasureFilter threadFilterData_; DataDict dataDict_; SchedSlice schedSliceData_; @@ -145,11 +157,6 @@ public: FileSystemSample fileSamplingTableData_; EbpfCallStackData ebpfCallStackData_; PagedMemorySampleData pagedMemorySampleData_; -#if WITH_EBPF_HELP - EbpfProcessMaps ebpfProcessMaps_; - EbpfElf ebpfElf_; - EbpfElfSymbol ebpfElfSymbol_; -#endif HiSysEventSubkeys sysEventNameIds_; HiSysEventMeasureData sysEventMeasureData_; HiSysEventDeviceStateData deviceStateData_; @@ -176,7 +183,7 @@ public: JsCpuProfilerSample jsCpuProfilerSampleData_; JsConfig jsConfigData_; AppStartup appStartupData_; - SoStaticInitalization staticInitalizationData_; + SoStaticInitalization soStaticInitalizationData_; Animation animation_; DeviceInfo deviceInfo_; DynamicFrame dynamicFrame_; diff --git a/trace_streamer/src/trace_data/trace_data_cache_reader.cpp b/trace_streamer/src/trace_data/trace_data_cache_reader.cpp index df45e6d6d291f0a2848854bee9eb9095009e5341..c77e134b196ef01702ec76d16b986e69d5025806 100644 --- a/trace_streamer/src/trace_data/trace_data_cache_reader.cpp +++ b/trace_streamer/src/trace_data/trace_data_cache_reader.cpp @@ -72,10 +72,6 @@ const Measure& TraceDataCacheReader::GetConstProcessMeasureData() const return processMeasureData_; } -const ThreadMeasureFilter& TraceDataCacheReader::GetConstThreadMeasureFilterData() const -{ - return threadMeasureFilterData_; -} const ThreadStateData& TraceDataCacheReader::GetConstThreadStateData() const { return threadStateData_; @@ -88,18 +84,10 @@ const CpuMeasureFilter& TraceDataCacheReader::GetConstCpuMeasureData() const { return cpuMeasureData_; } -const ThreadMeasureFilter& TraceDataCacheReader::GetConstThreadFilterData() const -{ - return threadFilterData_; -} const Instants& TraceDataCacheReader::GetConstInstantsData() const { return instantsData_; } -const ProcessMeasureFilter& TraceDataCacheReader::GetConstProcessFilterData() const -{ - return processFilterData_; -} const ProcessMeasureFilter& TraceDataCacheReader::GetConstProcessMeasureFilterData() const { return processMeasureFilterData_; @@ -283,20 +271,6 @@ const PagedMemorySampleData& TraceDataCacheReader::GetConstPagedMemorySampleData { return pagedMemorySampleData_; } -#if WITH_EBPF_HELP -const EbpfProcessMaps& TraceDataCacheReader::GetConstEbpfProcessMaps() const -{ - return ebpfProcessMaps_; -} -const EbpfElf& TraceDataCacheReader::GetConstEbpfElf() const -{ - return ebpfElf_; -} -const EbpfElfSymbol& TraceDataCacheReader::GetConstEbpfElfSymbol() const -{ - return ebpfElfSymbol_; -} -#endif const HiSysEventSubkeys& TraceDataCacheReader::GetConstHiSysEventSubkeysData() const { return sysEventNameIds_; @@ -335,11 +309,11 @@ const DataSourceClockIdData& TraceDataCacheReader::GetConstDataSourceClockIdData { return dataSourceClockIdData_; } -const FrameSlice& TraceDataCacheReader::GetConstFameSliceData() const +const FrameSlice& TraceDataCacheReader::GetConstFrameSliceData() const { return frameSliceData_; } -const FrameMaps& TraceDataCacheReader::GetConstFameMapsData() const +const FrameMaps& TraceDataCacheReader::GetConstFrameMapsData() const { return frameMapsData_; } @@ -351,9 +325,9 @@ const AppStartup& TraceDataCacheReader::GetConstAppStartupData() const { return appStartupData_; } -const SoStaticInitalization& TraceDataCacheReader::GetConstStaticInitalizationData() const +const SoStaticInitalization& TraceDataCacheReader::GetConstSoStaticInitalizationData() const { - return staticInitalizationData_; + return soStaticInitalizationData_; } const Animation& TraceDataCacheReader::GetConstAnimation() const { diff --git a/trace_streamer/src/trace_data/trace_data_cache_reader.h b/trace_streamer/src/trace_data/trace_data_cache_reader.h index 9b17dfc11a8a7e485ce20205176b98a01958bd50..4c9c1946b825cdef8961809c2ab12f916dcb922d 100644 --- a/trace_streamer/src/trace_data/trace_data_cache_reader.h +++ b/trace_streamer/src/trace_data/trace_data_cache_reader.h @@ -16,9 +16,24 @@ #ifndef TRACE_DATA_CACHE_READER_H #define TRACE_DATA_CACHE_READER_H -#include "log.h" +#include "activity_monitor_stdtype.h" +#include "animation_stdtype.h" +#include "app_startup_stdtype.h" +#include "arkts_stdtype.h" +#include "base_stdtype.h" +#include "callstack_stdtype.h" +#include "common_stdtype.h" +#include "ebpf_stdtype.h" +#include "hilog_stdtype.h" +#include "hiperf_stdtype.h" +#include "hisysevent_stdtype.h" +#include "measure_stdtype.h" +#include "native_memory_stdtype.h" +#include "render_service_stdtype.h" +#include "sched_stdtype.h" +#include "syscall_stdtype.h" +#include "task_pool_stdtype.h" #include "trace_data_cache_base.h" -#include "trace_stdtype.h" namespace SysTuning { namespace TraceStreamer { @@ -43,13 +58,10 @@ public: const Measure& GetConstMeasureData() const; const Measure& GetConstSysMemMeasureData() const; const Measure& GetConstProcessMeasureData() const; - const ThreadMeasureFilter& GetConstThreadMeasureFilterData() const; const ThreadStateData& GetConstThreadStateData() const; const SchedSlice& GetConstSchedSliceData() const; const CpuMeasureFilter& GetConstCpuMeasureData() const; - const ThreadMeasureFilter& GetConstThreadFilterData() const; const Instants& GetConstInstantsData() const; - const ProcessMeasureFilter& GetConstProcessFilterData() const; const ProcessMeasureFilter& GetConstProcessMeasureFilterData() const; const ClockEventData& GetConstClockEventFilterData() const; const ClkEventData& GetConstClkEventFilterData() const; @@ -81,11 +93,6 @@ public: const HiSysEventDeviceStateData& GetConstHiSysEventDeviceStateData() const; const EbpfCallStackData& GetConstEbpfCallStackData() const; const PagedMemorySampleData& GetConstPagedMemorySampleData() const; -#ifdef WITH_EBPF_HELP - const EbpfProcessMaps& GetConstEbpfProcessMaps() const; - const EbpfElf& GetConstEbpfElf() const; - const EbpfElfSymbol& GetConstEbpfElfSymbol() const; -#endif const HiSysEventSubkeys& GetConstHiSysEventSubkeysData() const; const HiSysEventMeasureData& GetConstHiSyseventMeasureData() const; const TraceConfig& GetConstTraceConfigData() const; @@ -94,8 +101,8 @@ public: const BioLatencySampleData& GetConstBioLatencySampleData() const; const ClockSnapshotData& GetConstClockSnapshotData() const; const DataSourceClockIdData& GetConstDataSourceClockIdData() const; - const FrameSlice& GetConstFameSliceData() const; - const FrameMaps& GetConstFameMapsData() const; + const FrameSlice& GetConstFrameSliceData() const; + const FrameMaps& GetConstFrameMapsData() const; const GPUSlice& GetConstGPUSliceData() const; const TaskPoolInfo& GetConstTaskPoolData() const; const JsHeapFiles& GetConstJsHeapFilesData() const; @@ -111,7 +118,7 @@ public: const JsCpuProfilerSample& GetConstJsCpuProfilerSampleData() const; const JsConfig& GetConstJsConfigData() const; const AppStartup& GetConstAppStartupData() const; - const SoStaticInitalization& GetConstStaticInitalizationData() const; + const SoStaticInitalization& GetConstSoStaticInitalizationData() const; const Animation& GetConstAnimation() const; const DeviceInfo& GetConstDeviceInfo() const; const DynamicFrame& GetConstDynamicFrame() const; diff --git a/trace_streamer/src/trace_data/trace_data_cache_writer.cpp b/trace_streamer/src/trace_data/trace_data_cache_writer.cpp index 2f12015a869fb2086a2979dcb34a7f68343b378b..4e644f8c57f203d288e86f223addbb430e605d1d 100644 --- a/trace_streamer/src/trace_data/trace_data_cache_writer.cpp +++ b/trace_streamer/src/trace_data/trace_data_cache_writer.cpp @@ -144,26 +144,11 @@ CpuMeasureFilter* TraceDataCacheWriter::GetCpuMeasuresData() return &cpuMeasureData_; } -ThreadMeasureFilter* TraceDataCacheWriter::GetThreadMeasureFilterData() -{ - return &threadMeasureFilterData_; -} - -ThreadMeasureFilter* TraceDataCacheWriter::GetThreadFilterData() -{ - return &threadFilterData_; -} - Instants* TraceDataCacheWriter::GetInstantsData() { return &instantsData_; } -ProcessMeasureFilter* TraceDataCacheWriter::GetProcessFilterData() -{ - return &processFilterData_; -} - ProcessMeasureFilter* TraceDataCacheWriter::GetProcessMeasureFilterData() { return &processMeasureFilterData_; @@ -286,20 +271,6 @@ PagedMemorySampleData* TraceDataCacheWriter::GetPagedMemorySampleData() { return &pagedMemorySampleData_; } -#if WITH_EBPF_HELP -EbpfProcessMaps* TraceDataCacheWriter::GetEbpfProcessMaps() -{ - return &ebpfProcessMaps_; -} -EbpfElf* TraceDataCacheWriter::GetEbpfElf() -{ - return &ebpfElf_; -} -EbpfElfSymbol* TraceDataCacheWriter::GetEbpfElfSymbol() -{ - return &ebpfElfSymbol_; -} -#endif HiSysEventSubkeys* TraceDataCacheWriter::GetHiSysEventSubkeysData() { return &sysEventNameIds_; @@ -406,9 +377,9 @@ AppStartup* TraceDataCacheWriter::GetAppStartupData() { return &appStartupData_; } -SoStaticInitalization* TraceDataCacheWriter::GetStaticInitalizationData() +SoStaticInitalization* TraceDataCacheWriter::GetSoStaticInitalizationData() { - return &staticInitalizationData_; + return &soStaticInitalizationData_; } Animation* TraceDataCacheWriter::GetAnimation() { @@ -460,9 +431,6 @@ void TraceDataCacheWriter::Clear() processMeasureFilterData_.Clear(); clockEventFilterData_.Clear(); clkEventFilterData_.Clear(); - processFilterData_.Clear(); - threadMeasureFilterData_.Clear(); - threadFilterData_.Clear(); dataDict_.Clear(); schedSliceData_.Clear(); @@ -511,16 +479,10 @@ void TraceDataCacheWriter::Clear() jsCpuProfilerSampleData_.Clear(); jsConfigData_.Clear(); appStartupData_.Clear(); - staticInitalizationData_.Clear(); + soStaticInitalizationData_.Clear(); animation_.Clear(); deviceInfo_.Clear(); dynamicFrame_.Clear(); - -#if WITH_EBPF_HELP - ebpfProcessMaps_.Clear(); - ebpfElf_.Clear(); - ebpfElfSymbol_.Clear(); -#endif sysEventNameIds_.Clear(); sysEventMeasureData_.Clear(); deviceStateData_.Clear(); diff --git a/trace_streamer/src/trace_data/trace_data_cache_writer.h b/trace_streamer/src/trace_data/trace_data_cache_writer.h index 912637b8287ba54df8752a72aefdce2f068542c9..71b371d7c56a6aebe72406f349d435fb1106b627 100644 --- a/trace_streamer/src/trace_data/trace_data_cache_writer.h +++ b/trace_streamer/src/trace_data/trace_data_cache_writer.h @@ -48,10 +48,7 @@ public: ThreadStateData* GetThreadStateData(); SchedSlice* GetSchedSliceData(); CpuMeasureFilter* GetCpuMeasuresData(); - ThreadMeasureFilter* GetThreadMeasureFilterData(); - ThreadMeasureFilter* GetThreadFilterData(); Instants* GetInstantsData(); - ProcessMeasureFilter* GetProcessFilterData(); ProcessMeasureFilter* GetProcessMeasureFilterData(); ClockEventData* GetClockEventFilterData(); ClkEventData* GetClkEventFilterData(); @@ -80,11 +77,6 @@ public: FileSystemSample* GetFileSystemSample(); EbpfCallStackData* GetEbpfCallStack(); PagedMemorySampleData* GetPagedMemorySampleData(); -#ifdef WITH_EBPF_HELP - EbpfProcessMaps* GetEbpfProcessMaps(); - EbpfElf* GetEbpfElf(); - EbpfElfSymbol* GetEbpfElfSymbol(); -#endif HiSysEventSubkeys* GetHiSysEventSubkeysData(); HiSysEventMeasureData* GetHiSysEventMeasureData(); HiSysEventDeviceStateData* GetHiSysEventDeviceStateData(); @@ -111,7 +103,7 @@ public: JsCpuProfilerSample* GetJsCpuProfilerSampleData(); JsConfig* GetJsConfigData(); AppStartup* GetAppStartupData(); - SoStaticInitalization* GetStaticInitalizationData(); + SoStaticInitalization* GetSoStaticInitalizationData(); Animation* GetAnimation(); DeviceInfo* GetDeviceInfo(); DynamicFrame* GetDynamicFrame(); diff --git a/trace_streamer/src/trace_data/trace_data_db.cpp b/trace_streamer/src/trace_data/trace_data_db.cpp index 9a6ec1a19760852ec1e7f17233e3d356ba2c15e9..a6fcf318238ee6ab2621f9d6707fa58246f4f72c 100644 --- a/trace_streamer/src/trace_data/trace_data_db.cpp +++ b/trace_streamer/src/trace_data/trace_data_db.cpp @@ -39,10 +39,6 @@ const int32_t ONCE_MAX_MB = 1024 * 1024 * 4; constexpr int32_t DEFAULT_LEN_ROW_STRING = 1024; enum class DBFiledType : uint8_t { INT = 0, TEXT }; -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) using namespace SysTuning::base; TraceDataDB::TraceDataDB() : db_(nullptr) @@ -98,7 +94,7 @@ void TraceDataDB::SendDatabase(ResultCallBack resultCallBack) resultCallBack(std::string((char*)data, DATABASE_BASE), SEND_CONTINUE); } close(fd); - remove(wasmDBName_.c_str()); + (void)remove(wasmDBName_.c_str()); wasmDBName_.clear(); } int32_t TraceDataDB::CreatEmptyBatchDB(const std::string& outputName) @@ -110,7 +106,7 @@ int32_t TraceDataDB::CreatEmptyBatchDB(const std::string& outputName) return 1; } auto ret = ftruncate(fd, 0); - UNUSED(ret); + Unused(ret); close(fd); } std::string attachSql("ATTACH DATABASE '" + outputName + "' AS systuning_export"); @@ -201,7 +197,7 @@ int32_t TraceDataDB::ExportDatabase(const std::string& outputName, ResultCallBac return 1; } auto ret = ftruncate(fd, 0); - UNUSED(ret); + Unused(ret); close(fd); } diff --git a/trace_streamer/src/trace_data/trace_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype.cpp deleted file mode 100644 index 96828737c39477f09fe8d1b6d2b13634e96e2a0f..0000000000000000000000000000000000000000 --- a/trace_streamer/src/trace_data/trace_stdtype.cpp +++ /dev/null @@ -1,3725 +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. - */ - -#include "trace_stdtype.h" -#include -#include -#include -#include -#include "string_to_numerical.h" -namespace SysTuning { -namespace TraceStdtype { -constexpr int32_t MAX_SIZE_LEN = 80; -constexpr uint8_t DEVICEINFO_MATCH_LAST = 2; -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) -void CpuCacheBase::SetDur(uint64_t index, uint64_t dur) -{ - durs_[index] = dur; -} -TableRowId ThreadStateData::AppendThreadState(InternalTime ts, - InternalTime dur, - InternalCpu cpu, - InternalTid itid, - TableRowId idState) -{ - timeStamps_.emplace_back(ts); - durations_.emplace_back(dur); - itids_.emplace_back(itid); - tids_.emplace_back(INVALID_UINT32); - pids_.emplace_back(INVALID_UINT32); - states_.emplace_back(idState); - cpus_.emplace_back(cpu); - argSetIds_.emplace_back(INVALID_UINT32); - return itids_.size() - 1; -} - -void ThreadStateData::SetDuration(TableRowId index, InternalTime dur) -{ - durations_[index] = dur; -} - -void ThreadStateData::SortAllRowByTs() -{ - std::deque timeStampsTemp; - timeStampsTemp = std::move(timeStamps_); - std::multimap timeStampsToIdMap = {}; - for (auto id = 0; id < timeStampsTemp.size(); ++id) { - timeStampsToIdMap.insert({timeStampsTemp[id], id}); - } - std::deque durationsTemp; - std::deque itidsTemp; - std::deque tidsTemp; - std::deque pidsTemp; - std::deque statesTemp; - std::deque cpusTemp; - std::deque argSetIdsTemp; - durationsTemp = std::move(durations_); - itidsTemp = std::move(itids_); - tidsTemp = std::move(tids_); - pidsTemp = std::move(pids_); - statesTemp = std::move(states_); - cpusTemp = std::move(cpus_); - argSetIdsTemp = std::move(argSetIds_); - for (auto itor = timeStampsToIdMap.begin(); itor != timeStampsToIdMap.end(); itor++) { - timeStamps_.emplace_back(timeStampsTemp[itor->second]); - durations_.emplace_back(durationsTemp[itor->second]); - itids_.emplace_back(itidsTemp[itor->second]); - tids_.emplace_back(tidsTemp[itor->second]); - pids_.emplace_back(pidsTemp[itor->second]); - states_.emplace_back(statesTemp[itor->second]); - cpus_.emplace_back(cpusTemp[itor->second]); - argSetIds_.emplace_back(argSetIdsTemp[itor->second]); - } -} -void DataDict::Finish() -{ - std::string::size_type pos(0); - for (auto i = 0; i < dataDict_.size(); i++) { - while ((pos = dataDict_[i].find("\"")) != std::string::npos) { - dataDict_[i].replace(pos, 1, "\'"); - } - while (!dataDict_[i].empty() && ((dataDict_[i].back() >= SPASCII_START && dataDict_[i].back() <= SPASCII_END) || - dataDict_[i].back() == '\r')) { - dataDict_[i].pop_back(); - } - } -} -TableRowId ThreadStateData::UpdateDuration(TableRowId index, InternalTime ts) -{ - if (durations_[index] == INVALID_TIME) { - durations_[index] = ts - timeStamps_[index]; - } - return itids_[index]; -} - -bool ThreadStateData::End(TableRowId index, InternalTime ts) -{ - if (durations_[index] == INVALID_TIME) { - durations_[index] = -1; - return false; - } - return true; -} -void ThreadStateData::UpdateState(TableRowId index, TableRowId idState) -{ - states_[index] = idState; -} -void ThreadStateData::SetArgSetId(TableRowId index, uint32_t setId) -{ - argSetIds_[index] = setId; -} - -void ThreadStateData::UpdateDuration(TableRowId index, InternalTime ts, TableRowId idState) -{ - durations_[index] = ts - timeStamps_[index]; - states_[index] = idState; -} - -void ThreadStateData::UpdateTidAndPid(TableRowId index, InternalTid tid, InternalTid pid) -{ - tids_[index] = tid; - pids_[index] = pid; -} - -TableRowId ThreadStateData::UpdateDuration(TableRowId index, InternalTime ts, InternalCpu cpu, TableRowId idState) -{ - cpus_[index] = cpu; - durations_[index] = ts - timeStamps_[index]; - states_[index] = idState; - return itids_[index]; -} - -size_t SchedSlice::AppendSchedSlice(uint64_t ts, - uint64_t dur, - uint64_t cpu, - uint32_t internalTid, - uint64_t endState, - uint64_t priority) -{ - timeStamps_.emplace_back(ts); - durs_.emplace_back(dur); - cpus_.emplace_back(cpu); - tsEnds_.emplace_back(0); - internalTids_.emplace_back(internalTid); - endStates_.emplace_back(endState); - priority_.emplace_back(priority); - argSets_.emplace_back(INVALID_UINT32); - internalPids_.emplace_back(INVALID_UINT32); - return Size() - 1; -} - -void SchedSlice::SetDuration(size_t index, uint64_t duration) -{ - durs_[index] = duration; - tsEnds_[index] = timeStamps_[index] + duration; -} - -void SchedSlice::Update(uint64_t index, uint64_t ts, uint64_t state) -{ - durs_[index] = ts - timeStamps_[index]; - endStates_[index] = state; -} - -void SchedSlice::UpdateEndState(uint64_t index, uint64_t state) -{ - endStates_[index] = state; -} - -void SchedSlice::UpdateArg(uint64_t index, uint32_t argsetId) -{ - argSets_[index] = argsetId; -} -size_t CallStack::AppendInternalAsyncSlice(uint64_t startT, - uint64_t durationNs, - InternalTid internalTid, - DataIndex cat, - uint16_t nameIdentify, - DataIndex name, - uint8_t depth, - uint64_t cookid, - const std::optional& parentId) -{ - AppendCommonInfo(startT, durationNs, internalTid); - AppendCallStack(cat, name, depth, parentId); - AppendDistributeInfo(); - cookies_.emplace_back(cookid); - ids_.emplace_back(ids_.size()); - identifys_.emplace_back(nameIdentify + depth); - return Size() - 1; -} -size_t CallStack::AppendInternalSlice(uint64_t startT, - uint64_t durationNs, - InternalTid internalTid, - DataIndex cat, - uint16_t nameIdentify, - DataIndex name, - uint8_t depth, - const std::optional& parentId) -{ - AppendCommonInfo(startT, durationNs, internalTid); - AppendCallStack(cat, name, depth, parentId); - identifys_.emplace_back(nameIdentify + depth); - ids_.emplace_back(ids_.size()); - cookies_.emplace_back(INVALID_UINT64); - AppendDistributeInfo(); - return Size() - 1; -} - -void CallStack::AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid) -{ - timeStamps_.emplace_back(startT); - durs_.emplace_back(durationNs); - callIds_.emplace_back(internalTid); -} -void CallStack::AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, std::optional parentId) -{ - parentIds_.emplace_back(parentId); - cats_.emplace_back(cat); - names_.emplace_back(name); - depths_.emplace_back(depth); -} -void CallStack::SetDistributeInfo(size_t index, - const std::string& chainId, - const std::string& spanId, - const std::string& parentSpanId, - const std::string& flag, - const std::string& args) -{ - chainIds_[index] = chainId; - spanIds_[index] = spanId; - parentSpanIds_[index] = parentSpanId; - flags_[index] = flag; - args_[index] = args; - argSet_[index] = INVALID_UINT32; -} -void CallStack::AppendDistributeInfo(const std::string& chainId, - const std::string& spanId, - const std::string& parentSpanId, - const std::string& flag, - const std::string& args) -{ - chainIds_.emplace_back(chainId); - spanIds_.emplace_back(spanId); - parentSpanIds_.emplace_back(parentSpanId); - flags_.emplace_back(flag); - args_.emplace_back(args); - argSet_.emplace_back(INVALID_UINT32); -} -void CallStack::AppendDistributeInfo() -{ - chainIds_.emplace_back(""); - spanIds_.emplace_back(""); - parentSpanIds_.emplace_back(""); - flags_.emplace_back(""); - args_.emplace_back(""); - argSet_.emplace_back(INVALID_UINT32); -} -void CallStack::SetDuration(size_t index, uint64_t timeStamp) -{ - durs_[index] = timeStamp - timeStamps_[index]; -} -void CallStack::SetDurationWithFlag(size_t index, uint64_t timeStamp) -{ - durs_[index] = timeStamp - timeStamps_[index]; - flags_[index] = "1"; -} - -void CallStack::SetFlag(size_t index, uint8_t flag) -{ - flags_[index] = std::to_string(flag); -} -void CallStack::SetDurationEx(size_t index, uint32_t dur) -{ - durs_[index] = dur; -} - -void CallStack::SetIrqDurAndArg(size_t index, uint64_t timeStamp, uint32_t argSetId) -{ - SetDuration(index, timeStamp); - argSet_[index] = argSetId; -} -void CallStack::SetTimeStamp(size_t index, uint64_t timeStamp) -{ - timeStamps_[index] = timeStamp; -} - -void CallStack::SetDepth(size_t index, uint8_t depth) -{ - depths_[index] = depth; -} -void CallStack::SetArgSetId(size_t index, uint32_t argSetId) -{ - argSet_[index] = argSetId; -} -const std::deque>& CallStack::ParentIdData() const -{ - return parentIds_; -} -const std::deque& CallStack::CatsData() const -{ - return cats_; -} -const std::deque& CallStack::IdentifysData() const -{ - return identifys_; -} -const std::deque& CallStack::NamesData() const -{ - return names_; -} -const std::deque& CallStack::Depths() const -{ - return depths_; -} -const std::deque& CallStack::Cookies() const -{ - return cookies_; -} -const std::deque& CallStack::CallIds() const -{ - return callIds_; -} -const std::deque& CallStack::ChainIds() const -{ - return chainIds_; -} -const std::deque& CallStack::SpanIds() const -{ - return spanIds_; -} -const std::deque& CallStack::ParentSpanIds() const -{ - return parentSpanIds_; -} -const std::deque& CallStack::Flags() const -{ - return flags_; -} -const std::deque& CallStack::ArgsData() const -{ - return args_; -} -const std::deque& CallStack::ArgSetIdsData() const -{ - return argSet_; -} - -size_t ArgSet::AppendNewArg(DataIndex nameId, BaseDataType dataType, int64_t value, size_t argSet) -{ - dataTypes_.emplace_back(dataType); - argset_.emplace_back(argSet); - ids_.emplace_back(Size()); - values_.emplace_back(value); - names_.emplace_back(nameId); - return Size() - 1; -} -const std::deque& ArgSet::DataTypes() const -{ - return dataTypes_; -} -const std::deque& ArgSet::ValuesData() const -{ - return values_; -} -const std::deque& ArgSet::ArgsData() const -{ - return argset_; -} -const std::deque& ArgSet::NamesData() const -{ - return names_; -} - -size_t SysMeasureFilter::AppendNewFilter(uint64_t filterId, DataIndex type, DataIndex nameId) -{ - ids_.emplace_back(filterId); - names_.emplace_back(nameId); - types_.emplace_back(type); - return ids_.size() - 1; -} -const std::deque& SysMeasureFilter::NamesData() const -{ - return names_; -} - -const std::deque& SysMeasureFilter::TypesData() const -{ - return types_; -} -size_t DataType::AppendNewDataType(BaseDataType dataType, DataIndex dataDescIndex) -{ - ids_.emplace_back(Size()); - dataTypes_.emplace_back(dataType); - descs_.emplace_back(dataDescIndex); - return Size() - 1; -} - -const std::deque& DataType::DataTypes() const -{ - return dataTypes_; -} -const std::deque& DataType::DataDesc() const -{ - return descs_; -} -size_t Filter::AppendNewFilterData(std::string type, std::string name, uint64_t sourceArgSetId) -{ - nameDeque_.emplace_back(name); - sourceArgSetId_.emplace_back(sourceArgSetId); - ids_.emplace_back(Size()); - typeDeque_.emplace_back(type); - return Size() - 1; -} - -size_t Measure::AppendMeasureData(uint32_t type, uint64_t timeStamp, int64_t value, uint32_t filterId) -{ - valuesDeque_.emplace_back(value); - filterIdDeque_.emplace_back(filterId); - typeDeque_.emplace_back(type); - timeStamps_.emplace_back(timeStamp); - durDeque_.emplace_back(INVALID_UINT64); - return Size() - 1; -} - -void Measure::SetDur(uint32_t row, uint64_t timeStamp) -{ - durDeque_[row] = timeStamp - timeStamps_[row]; -} -size_t Raw::AppendRawData(uint32_t id, uint64_t timeStamp, uint32_t name, uint32_t cpu, uint32_t internalTid) -{ - ids_.emplace_back(id); - timeStamps_.emplace_back(timeStamp); - nameDeque_.emplace_back(name); - cpuDeque_.emplace_back(cpu); - internalTids_.emplace_back(internalTid); - return Size() - 1; -} - -size_t ThreadMeasureFilter::AppendNewFilter(uint64_t filterId, uint32_t nameIndex, uint64_t internalTid) -{ - filterId_.emplace_back(filterId); - nameIndex_.emplace_back(nameIndex); - internalTids_.emplace_back(internalTid); - return Size() - 1; -} - -size_t Instants::AppendInstantEventData(uint64_t timeStamp, - DataIndex nameIndex, - int64_t internalTid, - int64_t wakeupFromInternalPid) -{ - internalTids_.emplace_back(internalTid); - timeStamps_.emplace_back(timeStamp); - NameIndexs_.emplace_back(nameIndex); - wakeupFromInternalPids_.emplace_back(wakeupFromInternalPid); - return Size() - 1; -} -size_t LogInfo::AppendNewLogInfo(uint64_t seq, - uint64_t timeStamp, - uint32_t pid, - uint32_t tid, - DataIndex level, - DataIndex tag, - DataIndex context, - uint64_t originTs) -{ - hilogLineSeqs_.emplace_back(seq); - timeStamps_.emplace_back(timeStamp); - pids_.emplace_back(pid); - tids_.emplace_back(tid); - levels_.emplace_back(level); - tags_.emplace_back(tag); - contexts_.emplace_back(context); - originTs_.emplace_back(originTs); - return Size() - 1; -} -const std::deque& LogInfo::HilogLineSeqs() const -{ - return hilogLineSeqs_; -} -const std::deque& LogInfo::Pids() const -{ - return pids_; -} -const std::deque& LogInfo::Tids() const -{ - return tids_; -} -const std::deque& LogInfo::Levels() const -{ - return levels_; -} -const std::deque& LogInfo::Tags() const -{ - return tags_; -} -const std::deque& LogInfo::Contexts() const -{ - return contexts_; -} -const std::deque& LogInfo::OriginTimeStamData() const -{ - return originTs_; -} -void NativeHookSampleBase::AppendNativeHookSampleBase(uint32_t callChainId, - uint32_t ipid, - uint32_t itid, - uint64_t timeStamp) -{ - ids_.emplace_back(id_++); - 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(id_++); - 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, - uint32_t ipid, - uint32_t itid, - std::string eventType, - DataIndex subType, - uint64_t timeStamp, - uint64_t endTimeStamp, - uint64_t duration, - uint64_t addr, - int64_t memSize) -{ - AppendNativeHookSampleBase(callChainId, ipid, itid, timeStamp); - eventTypes_.emplace_back(eventType); - subTypes_.emplace_back(subType); - endTimeStamps_.emplace_back(endTimeStamp); - durations_.emplace_back(duration); - addrs_.emplace_back(addr); - memSizes_.emplace_back(memSize); - if (eventType == ALLOC_EVET) { - countHeapSizes_ += memSize; - allMemSizes_.emplace_back(countHeapSizes_); - } else if (eventType == FREE_EVENT) { - countHeapSizes_ -= memSize; - allMemSizes_.emplace_back(countHeapSizes_); - } else if (eventType == MMAP_EVENT) { - countMmapSizes_ += memSize; - allMemSizes_.emplace_back(countMmapSizes_); - } else if (eventType == MUNMAP_EVENT) { - countMmapSizes_ -= memSize; - allMemSizes_.emplace_back(countMmapSizes_); - } - currentSizeDurs_.emplace_back(0); - 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; - durations_[row] = endTimeStamp - timeStamps_[row]; -} -void NativeHook::UpdateCurrentSizeDur(size_t row, uint64_t timeStamp) -{ - currentSizeDurs_[row] = timeStamp - timeStamps_[row]; -} -void NativeHook::UpdateMemMapSubType(uint64_t row, uint64_t tagId) -{ - if (row < subTypes_.size()) { - subTypes_[row] = tagId; - } else { - TS_LOGE("subTypes_ row is invalid!"); - } -} -const std::deque& NativeHook::EventTypes() const -{ - return eventTypes_; -} -const std::deque& NativeHook::SubTypes() const -{ - return subTypes_; -} -const std::deque& NativeHook::EndTimeStamps() const -{ - return endTimeStamps_; -} -const std::deque& NativeHook::Durations() const -{ - return durations_; -} -const std::deque& NativeHook::Addrs() const -{ - return addrs_; -} -const std::deque& NativeHook::MemSizes() const -{ - return memSizes_; -} -const std::deque& NativeHook::AllMemSizes() const -{ - return allMemSizes_; -} -const std::deque& NativeHook::CurrentSizeDurs() const -{ - return currentSizeDurs_; -} -size_t NativeHookFrame::AppendNewNativeHookFrame(uint32_t callChainId, - uint16_t depth, - uint64_t ip, - DataIndex symbolName, - DataIndex filePath, - uint64_t offset, - uint64_t symbolOffset, - const std::string& vaddr) -{ - callChainIds_.emplace_back(callChainId); - ips_.emplace_back(ip); - depths_.emplace_back(depth); - symbolNames_.emplace_back(symbolName); - filePaths_.emplace_back(filePath); - offsets_.emplace_back(offset); - symbolOffsets_.emplace_back(symbolOffset); - vaddrs_.emplace_back(vaddr); - return Size() - 1; -} -size_t NativeHookFrame::AppendNewNativeHookFrame(uint32_t callChainId, - uint16_t depth, - uint64_t ip, - DataIndex symbolName, - DataIndex filePath, - uint64_t offset, - uint64_t symbolOffset) -{ - callChainIds_.emplace_back(callChainId); - ips_.emplace_back(ip); - depths_.emplace_back(depth); - symbolNames_.emplace_back(symbolName); - filePaths_.emplace_back(filePath); - offsets_.emplace_back(offset); - symbolOffsets_.emplace_back(symbolOffset); - return Size() - 1; -} -void NativeHookFrame::UpdateSymbolIdToNameMap(uint64_t originSymbolId, uint64_t symbolId) -{ - symbolIdToSymbolName_.insert(std::make_pair(originSymbolId, symbolId)); -} -void NativeHookFrame::UpdateFrameInfo(size_t row, - DataIndex symbolIndex, - DataIndex filePathIndex, - uint64_t offset, - uint64_t symbolOffset) -{ - if (row >= Size()) { - TS_LOGE("The updated row does not exist!"); - return; - } - symbolNames_[row] = symbolIndex; - filePaths_[row] = filePathIndex; - offsets_[row] = offset; - symbolOffsets_[row] = symbolOffset; -} - -void NativeHookFrame::UpdateSymbolId() -{ - if (symbolIdToSymbolName_.empty()) { - return; - } - for (auto i = 0; i < Size(); ++i) { - auto symbolIt = symbolIdToSymbolName_.find(symbolNames_[i]); - if (symbolIt != symbolIdToSymbolName_.end()) { - symbolNames_[i] = symbolIt->second; - } - } -} -void NativeHookFrame::UpdateSymbolId(size_t index, DataIndex symbolId) -{ - if (index < Size()) { - symbolNames_[index] = symbolId; - } -} -void NativeHookFrame::UpdateFileId(std::map& filePathIdToFilePathName) -{ - if (filePathIdToFilePathName.empty()) { - return; - } - for (auto i = 0; i < Size(); ++i) { - auto symbolIt = filePathIdToFilePathName.find(filePaths_[i]); - if (symbolIt != filePathIdToFilePathName.end()) { - filePaths_[i] = symbolIt->second; - } - } -} -void NativeHookFrame::UpdateVaddrs(std::deque& vaddrs) -{ - vaddrs_.assign(vaddrs.begin(), vaddrs.end()); -} -const std::deque& NativeHookFrame::CallChainIds() const -{ - return callChainIds_; -} -const std::deque& NativeHookFrame::Depths() const -{ - return depths_; -} -const std::deque& NativeHookFrame::Ips() const -{ - return ips_; -} -const std::deque& NativeHookFrame::SymbolNames() const -{ - return symbolNames_; -} -const std::deque& NativeHookFrame::FilePaths() const -{ - return filePaths_; -} -const std::deque& NativeHookFrame::Offsets() const -{ - return offsets_; -} -const std::deque& NativeHookFrame::SymbolOffsets() const -{ - return symbolOffsets_; -} -const std::deque& NativeHookFrame::Vaddrs() const -{ - return vaddrs_; -} - -size_t NativeHookStatistic::AppendNewNativeHookStatistic(uint32_t ipid, - uint64_t timeStamp, - uint32_t callChainId, - uint32_t memoryType, - DataIndex subMemType, - uint64_t applyCount, - uint64_t releaseCount, - uint64_t applySize, - uint64_t releaseSize) -{ - AppendNativeHookSampleBase(callChainId, ipid, timeStamp); - memoryTypes_.emplace_back(memoryType); - applyCounts_.emplace_back(applyCount); - memSubTypes_.emplace_back(subMemType); - releaseCounts_.emplace_back(releaseCount); - applySizes_.emplace_back(applySize); - releaseSizes_.emplace_back(releaseSize); - return Size() - 1; -} - -const std::deque& NativeHookStatistic::MemoryTypes() const -{ - return memoryTypes_; -} -const std::deque& NativeHookStatistic::MemorySubTypes() const -{ - return memSubTypes_; -} -const std::deque& NativeHookStatistic::ApplyCounts() const -{ - return applyCounts_; -} -const std::deque& NativeHookStatistic::ReleaseCounts() const -{ - return releaseCounts_; -} -const std::deque& NativeHookStatistic::ApplySizes() const -{ - return applySizes_; -} -const std::deque& NativeHookStatistic::ReleaseSizes() const -{ - return releaseSizes_; -} -size_t Hidump::AppendNewHidumpInfo(uint64_t timeStamp, uint32_t fps) -{ - timeStamps_.emplace_back(timeStamp); - fpss_.emplace_back(fps); - return Size() - 1; -} -const std::deque& Hidump::Fpss() const -{ - return fpss_; -} - -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()); - 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(INVALID_UINT64); - return Size() - 1; -} -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_; -} -const std::deque& PerfCallChain::FileIds() const -{ - return fileIds_; -} -const std::deque& PerfCallChain::SymbolIds() const -{ - return symbolIds_; -} - -const std::deque& PerfCallChain::Names() const -{ - return names_; -} -void PerfCallChain::SetName(uint64_t index, DataIndex name) -{ - names_[index] = name; -} -void PerfCallChain::Clear() -{ - CacheBase::Clear(); - callChainIds_.clear(); - depths_.clear(); - ips_.clear(); - vaddrInFiles_.clear(); - fileIds_.clear(); - symbolIds_.clear(); - names_.clear(); -} -void PerfCallChain::UpdateSymbolId(size_t index, DataIndex symbolId) -{ - if (index < Size()) { - symbolIds_[index] = symbolId; - } -} -size_t PerfFiles::AppendNewPerfFiles(uint64_t fileIds, uint32_t serial, DataIndex symbols, DataIndex filePath) -{ - ids_.emplace_back(Size()); - fileIds_.emplace_back(fileIds); - serials_.emplace_back(serial); - symbols_.emplace_back(symbols); - filePaths_.emplace_back(filePath); - return Size() - 1; -} -const std::deque& PerfFiles::FileIds() const -{ - return fileIds_; -} - -const std::deque& PerfFiles::Serials() const -{ - return serials_; -} -const std::deque& PerfFiles::Symbols() const -{ - return symbols_; -} -const std::deque& PerfFiles::FilePaths() const -{ - return filePaths_; -} - -void PerfFiles::Clear() -{ - CacheBase::Clear(); - fileIds_.clear(); - serials_.clear(); - symbols_.clear(); - filePaths_.clear(); -} - -size_t PerfSample::AppendNewPerfSample(uint32_t sampleId, - uint64_t timeStamp, - uint32_t tid, - uint64_t eventCount, - uint64_t eventTypeId, - uint64_t timestampTrace, - uint64_t cpuId, - uint64_t threadState) -{ - ids_.emplace_back(Size()); - sampleIds_.emplace_back(sampleId); - timeStamps_.emplace_back(timeStamp); - tids_.emplace_back(tid); - eventCounts_.emplace_back(eventCount); - eventTypeIds_.emplace_back(eventTypeId); - timestampTraces_.emplace_back(timestampTrace); - cpuIds_.emplace_back(cpuId); - threadStates_.emplace_back(threadState); - return Size() - 1; -} -const std::deque& PerfSample::SampleIds() const -{ - return sampleIds_; -} -const std::deque& PerfSample::Tids() const -{ - return tids_; -} -const std::deque& PerfSample::EventCounts() const -{ - return eventCounts_; -} -const std::deque& PerfSample::EventTypeIds() const -{ - return eventTypeIds_; -} -const std::deque& PerfSample::TimestampTraces() const -{ - return timestampTraces_; -} -const std::deque& PerfSample::CpuIds() const -{ - return cpuIds_; -} -const std::deque& PerfSample::ThreadStates() const -{ - return threadStates_; -} - -void PerfSample::Clear() -{ - CacheBase::Clear(); - sampleIds_.clear(); - tids_.clear(); - eventCounts_.clear(); - eventTypeIds_.clear(); - timestampTraces_.clear(); - cpuIds_.clear(); - threadStates_.clear(); -} - -size_t PerfThread::AppendNewPerfThread(uint32_t pid, uint32_t tid, DataIndex threadName) -{ - ids_.emplace_back(Size()); - pids_.emplace_back(pid); - tids_.emplace_back(tid); - threadNames_.emplace_back(threadName); - return Size() - 1; -} -const std::deque& PerfThread::Pids() const -{ - return pids_; -} -const std::deque& PerfThread::Tids() const -{ - return tids_; -} -const std::deque& PerfThread::ThreadNames() const -{ - return threadNames_; -} -void PerfThread::Clear() -{ - CacheBase::Clear(); - tids_.clear(); - pids_.clear(); - threadNames_.clear(); -} -size_t PerfReport::AppendNewPerfReport(DataIndex type, DataIndex value) -{ - ids_.emplace_back(Size()); - types_.emplace_back(type); - values_.emplace_back(value); - return Size() - 1; -} -const std::deque& PerfReport::Types() const -{ - return types_; -} -const std::deque& PerfReport::Values() const -{ - return values_; -} -size_t ProcessMeasureFilter::AppendNewFilter(uint64_t id, DataIndex name, uint32_t internalPid) -{ - internalPids_.emplace_back(internalPid); - ids_.emplace_back(id); - names_.emplace_back(name); - return Size() - 1; -} -size_t ClockEventData::AppendNewFilter(uint64_t id, DataIndex type, DataIndex name, uint64_t cpu) -{ - cpus_.emplace_back(cpu); - ids_.emplace_back(id); - types_.emplace_back(type); - names_.emplace_back(name); - return Size() - 1; -} -size_t ClkEventData::AppendNewFilter(uint64_t id, uint64_t rate, DataIndex name, uint64_t cpu) -{ - ids_.emplace_back(id); - rates_.emplace_back(rate); - names_.emplace_back(name); - cpus_.emplace_back(cpu); - return Size() - 1; -} -size_t SysCall::AppendSysCallData(int64_t sysCallNum, DataIndex type, uint32_t ipid, uint64_t timeStamp, int64_t ret) -{ - sysCallNums_.emplace_back(sysCallNum); - types_.emplace_back(type); - ipids_.emplace_back(ipid); - timeStamps_.emplace_back(timeStamp); - rets_.emplace_back(ret); - return Size() - 1; -} -StatAndInfo::StatAndInfo() -{ - // sched_switch_received | sched_switch_not_match | sched_switch_not_not_supported etc. - for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { - event_[i] = config_.eventNameMap_.at(static_cast(i)); - } - for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { - stat_[j] = config_.eventErrorDescMap_.at(static_cast(j)); - } - - for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { - for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { - statSeverity_[i][j] = config_.eventParserStatSeverityDescMap_.at(static_cast(i)) - .at(static_cast(j)); - } - } - - for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { - for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { - statSeverityDesc_[i][j] = config_.serverityLevelDescMap_.at(statSeverity_[i][j]); - } - } - - for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { - for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { - statCount_[i][j] = 0; - } - } - clockid2ClockNameMap_ = { - {TS_CLOCK_UNKNOW, "unknown"}, {TS_CLOCK_BOOTTIME, "boottime"}, - {TS_CLOCK_REALTIME, "realtime"}, {TS_CLOCK_REALTIME_COARSE, "realtime_corse"}, - {TS_MONOTONIC, "monotonic"}, {TS_MONOTONIC_COARSE, "monotonic-coarse"}, - {TS_MONOTONIC_RAW, "monotonic-raw"}, - }; -} -void StatAndInfo::IncreaseStat(SupportedTraceEventType eventType, StatType type) -{ -#ifdef SUPPORTTHREAD - std::lock_guard lockGurand(spinlock_); -#endif - statCount_[eventType][type]++; -} -const uint32_t& StatAndInfo::GetValue(SupportedTraceEventType eventType, StatType type) const -{ - return statCount_[eventType][type]; -} -const std::string& StatAndInfo::GetEvent(SupportedTraceEventType eventType) const -{ - return event_[eventType]; -} -const std::string& StatAndInfo::GetStat(StatType type) const -{ - return stat_[type]; -} -const std::string& StatAndInfo::GetSeverityDesc(SupportedTraceEventType eventType, StatType type) const -{ - return statSeverityDesc_[eventType][type]; -} -const StatSeverityLevel& StatAndInfo::GetSeverity(SupportedTraceEventType eventType, StatType type) const -{ - return statSeverity_[eventType][type]; -} - -uint64_t SymbolsData::Size() const -{ - return addrs_.size(); -} -void SymbolsData::InsertSymbol(const DataIndex& name, const uint64_t& addr) -{ - addrs_.emplace_back(addr); - funcName_.emplace_back(name); -} -const std::deque& SymbolsData::GetConstFuncNames() const -{ - return funcName_; -} -const std::deque& SymbolsData::GetConstAddrs() const -{ - return addrs_; -} -MetaData::MetaData() -{ - columnNames_.resize(METADATA_ITEM_MAX); - values_.resize(METADATA_ITEM_MAX); - columnNames_[METADATA_ITEM_DATASIZE] = METADATA_ITEM_DATASIZE_COLNAME; - columnNames_[METADATA_ITEM_PARSETOOL_NAME] = METADATA_ITEM_PARSETOOL_NAME_COLNAME; - columnNames_[METADATA_ITEM_PARSERTOOL_VERSION] = METADATA_ITEM_PARSERTOOL_VERSION_COLNAME; - columnNames_[METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME] = METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME_COLNAME; - columnNames_[METADATA_ITEM_SOURCE_FILENAME] = METADATA_ITEM_SOURCE_FILENAME_COLNAME; - columnNames_[METADATA_ITEM_OUTPUT_FILENAME] = METADATA_ITEM_OUTPUT_FILENAME_COLNAME; - columnNames_[METADATA_ITEM_PARSERTIME] = METADATA_ITEM_PARSERTIME_COLNAME; - columnNames_[METADATA_ITEM_TRACE_DURATION] = METADATA_ITEM_TRACE_DURATION_COLNAME; - columnNames_[METADATA_ITEM_SOURCE_DATETYPE] = METADATA_ITEM_SOURCE_DATETYPE_COLNAME; - values_[METADATA_ITEM_PARSETOOL_NAME] = "trace_streamer"; -} -void MetaData::SetTraceType(const std::string& traceType) -{ - values_[METADATA_ITEM_SOURCE_DATETYPE] = traceType; -} -void MetaData::SetSourceFileName(const std::string& fileName) -{ - MetaData::values_[METADATA_ITEM_SOURCE_FILENAME] = fileName; -} -void MetaData::SetOutputFileName(const std::string& fileName) -{ - MetaData::values_[METADATA_ITEM_OUTPUT_FILENAME] = fileName; -} -void MetaData::SetParserToolVersion(const std::string& version) -{ - values_[METADATA_ITEM_PARSERTOOL_VERSION] = version; -} -void MetaData::SetParserToolPublishDateTime(const std::string& datetime) -{ - values_[METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME] = datetime; -} -void MetaData::SetTraceDataSize(uint64_t dataSize) -{ - std::stringstream ss; - ss << dataSize; - values_[METADATA_ITEM_DATASIZE] = ss.str(); - // Function 'time' may return error. It is not allowed to do anything that might fail inside the constructor. - time_t rawtime; - tm* timeinfo = nullptr; - void(time(&rawtime)); - timeinfo = localtime(&rawtime); - char buffer[MAX_SIZE_LEN]; - strftime(buffer, MAX_SIZE_LEN, "%Y-%m-%d %H:%M:%S", timeinfo); - values_[METADATA_ITEM_PARSERTIME].append(buffer); - // sometimes there will be a extra \n at last - values_[METADATA_ITEM_PARSERTIME].pop_back(); -} -void MetaData::SetTraceDuration(uint64_t dur) -{ - values_[METADATA_ITEM_TRACE_DURATION] = std::to_string(dur) + " s"; -} -const std::string& MetaData::Value(uint64_t row) const -{ - return values_[row]; -} -const std::string& MetaData::Name(uint64_t row) const -{ - return columnNames_[row]; -} -DataIndex DataDict::GetStringIndex(std::string_view str) -{ - auto itor = dataDictInnerMap_.find(str); - if (itor != dataDictInnerMap_.end()) { - return itor->second; - } - mutex_.lock(); - dataDict_.emplace_back(std::string(str)); - DataIndex stringIdentity = dataDict_.size() - 1; - dataDictInnerMap_.emplace(std::string_view(dataDict_.back()), stringIdentity); - mutex_.unlock(); - return stringIdentity; -} -DataIndex DataDict::GetStringIndexNoWrite(std::string_view str) const -{ - auto itor = dataDictInnerMap_.find(str); - if (itor != dataDictInnerMap_.end()) { - return itor->second; - } - return INVALID_UINT64; -} -size_t CpuUsageDetailData::AppendNewData(uint64_t newTimeStamp, - uint64_t dur, - double totalLoad, - double userLoad, - double systemLoad, - int64_t threads) -{ - timeStamps_.emplace_back(newTimeStamp); - durs_.emplace_back(dur); - totalLoad_.emplace_back(totalLoad); - userLoad_.emplace_back(userLoad); - systemLoad_.emplace_back(systemLoad); - threads_.emplace_back(threads); - return Size() - 1; -} -const std::deque& CpuUsageDetailData::Durs() const -{ - return durs_; -} -const std::deque& CpuUsageDetailData::TotalLoad() const -{ - return totalLoad_; -} -const std::deque& CpuUsageDetailData::UserLoad() const -{ - return userLoad_; -} -const std::deque& CpuUsageDetailData::SystemLoad() const -{ - return systemLoad_; -} -const std::deque& CpuUsageDetailData::Threads() const -{ - return threads_; -} -size_t LiveProcessDetailData::AppendNewData(uint64_t newTimeStamp, - uint64_t dur, - int32_t processID, - std::string processName, - int32_t parentProcessID, - int32_t uid, - std::string userName, - double cpuUsage, - int32_t pssInfo, - uint64_t cpuTime, - int32_t threads, - int64_t diskWrites, - int64_t diskReads) -{ - timeStamps_.emplace_back(newTimeStamp); - durs_.emplace_back(dur); - processID_.emplace_back(processID); - processName_.emplace_back(processName); - parentProcessID_.emplace_back(parentProcessID); - uid_.emplace_back(uid); - userName_.emplace_back(userName); - cpuUsage_.emplace_back(cpuUsage); - pssInfo_.emplace_back(pssInfo); - threads_.emplace_back(threads); - diskWrites_.emplace_back(diskWrites); - diskReads_.emplace_back(diskReads); - cpuTimes_.emplace_back(cpuTime); - return Size() - 1; -} -const std::deque& LiveProcessDetailData::Durs() const -{ - return durs_; -} -const std::deque& LiveProcessDetailData::ProcessID() const -{ - return processID_; -} -const std::deque& LiveProcessDetailData::ProcessName() const -{ - return processName_; -} -const std::deque& LiveProcessDetailData::ParentProcessID() const -{ - return parentProcessID_; -} -const std::deque& LiveProcessDetailData::Uid() const -{ - return uid_; -} -const std::deque& LiveProcessDetailData::UserName() const -{ - return userName_; -} -const std::deque& LiveProcessDetailData::CpuUsage() const -{ - return cpuUsage_; -} -const std::deque& LiveProcessDetailData::PssInfo() const -{ - return pssInfo_; -} -const std::deque& LiveProcessDetailData::Threads() const -{ - return threads_; -} -const std::deque& LiveProcessDetailData::DiskWrites() const -{ - return diskWrites_; -} -const std::deque& LiveProcessDetailData::DiskReads() const -{ - return diskReads_; -} - -const std::deque& LiveProcessDetailData::CpuTimes() const -{ - return cpuTimes_; -} - -size_t NetDetailData::AppendNewNetData(uint64_t newTimeStamp, - uint64_t tx, - uint64_t rx, - uint64_t dur, - double rxSpeed, - double txSpeed, - uint64_t packetIn, - double packetInSec, - uint64_t packetOut, - double packetOutSec, - const std::string& netType) -{ - timeStamps_.emplace_back(newTimeStamp); - txs_.emplace_back(tx); - rxs_.emplace_back(rx); - durs_.emplace_back(dur); - txSpeeds_.emplace_back(txSpeed); - rxSpeeds_.emplace_back(rxSpeed); - netTypes_.emplace_back(netType); - packetIn_.emplace_back(packetIn); - packetInSec_.emplace_back(packetInSec); - packetOut_.emplace_back(packetOut); - packetOutSec_.emplace_back(packetOutSec); - - return Size() - 1; -} -const std::deque& NetDetailData::Durs() const -{ - return durs_; -} -const std::deque& NetDetailData::RxSpeed() const -{ - return rxSpeeds_; -} -const std::deque& NetDetailData::TxSpeed() const -{ - return txSpeeds_; -} -const std::deque& NetDetailData::NetTypes() const -{ - return netTypes_; -} -const std::deque& NetDetailData::RxDatas() const -{ - return rxs_; -} -const std::deque& NetDetailData::TxDatas() const -{ - return txs_; -} -const std::deque& NetDetailData::PacketIn() const -{ - return packetIn_; -} -const std::deque& NetDetailData::PacketInSec() const -{ - return packetInSec_; -} -const std::deque& NetDetailData::PacketOut() const -{ - return packetOut_; -} -const std::deque& NetDetailData::PacketOutSec() const -{ - return packetOutSec_; -} - -void DiskIOData::AppendNewData(uint64_t ts, - uint64_t dur, - uint64_t rd, - uint64_t wr, - uint64_t rdPerSec, - uint64_t wrPerSec, - double rdCountPerSec, - double wrCountPerSec, - uint64_t rdCount, - uint64_t wrCount) -{ - timeStamps_.emplace_back(ts); - durs_.emplace_back(dur); - rdDatas_.emplace_back(rd); - wrDatas_.emplace_back(wr); - rdPerSec_.emplace_back(rdPerSec); - wrPerSec_.emplace_back(wrPerSec); - rdCountPerSec_.emplace_back(rdCountPerSec); - wrCountPerSec_.emplace_back(wrCountPerSec); - rdCountDatas_.emplace_back(rdCount); - wrCountDatas_.emplace_back(wrCount); -} -const std::deque& DiskIOData::Durs() const -{ - return durs_; -} -const std::deque& DiskIOData::RdDatas() const -{ - return rdDatas_; -} -const std::deque& DiskIOData::WrDatas() const -{ - return wrDatas_; -} -const std::deque& DiskIOData::RdSpeedDatas() const -{ - return rdPerSec_; -} -const std::deque& DiskIOData::WrSpeedDatas() const -{ - return wrPerSec_; -} - -const std::deque& DiskIOData::RdCountPerSecDatas() const -{ - return rdCountPerSec_; -} -const std::deque& DiskIOData::WrCountPerSecDatas() const -{ - return wrCountPerSec_; -} -const std::deque& DiskIOData::RdCountDatas() const -{ - return rdCountDatas_; -} -const std::deque& DiskIOData::WrCountDatas() const -{ - return wrCountDatas_; -} - -size_t FileSystemSample::AppendNewData(uint32_t callChainId, - uint16_t type, - uint32_t ipid, - uint32_t itid, - uint64_t startTs, - uint64_t endTs, - uint64_t dur, - DataIndex returnValue, - DataIndex errorCode, - size_t size, - int32_t fd, - DataIndex fileId, - DataIndex firstArgument, - DataIndex secondArgument, - DataIndex thirdArgument, - DataIndex fourthArgument) -{ - callChainIds_.emplace_back(callChainId); - types_.emplace_back(type); - ipids_.emplace_back(ipid); - itids_.emplace_back(itid); - startTs_.emplace_back(startTs); - endTs_.emplace_back(endTs); - durs_.emplace_back(dur); - returnValues_.emplace_back(returnValue); - errorCodes_.emplace_back(errorCode); - fds_.emplace_back(fd); - fileIds_.emplace_back(fileId); - Sizes_.emplace_back(size); - firstArguments_.emplace_back(firstArgument); - secondArguments_.emplace_back(secondArgument); - thirdArguments_.emplace_back(thirdArgument); - fourthArguments_.emplace_back(fourthArgument); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& FileSystemSample::CallChainIds() const -{ - return callChainIds_; -} -const std::deque& FileSystemSample::Types() const -{ - return types_; -} -const std::deque& FileSystemSample::Ipids() const -{ - return ipids_; -} -const std::deque& FileSystemSample::Itids() const -{ - return itids_; -} -const std::deque& FileSystemSample::StartTs() const -{ - return startTs_; -} -const std::deque& FileSystemSample::EndTs() const -{ - return endTs_; -} -const std::deque& FileSystemSample::Durs() const -{ - return durs_; -} -const std::deque& FileSystemSample::ReturnValues() const -{ - return returnValues_; -} -const std::deque& FileSystemSample::ErrorCodes() const -{ - return errorCodes_; -} -const std::deque& FileSystemSample::Fds() const -{ - return fds_; -} -const std::deque& FileSystemSample::FileIds() const -{ - return fileIds_; -} -const std::deque& FileSystemSample::Sizes() const -{ - return Sizes_; -} -const std::deque& FileSystemSample::FirstArguments() const -{ - return firstArguments_; -} -const std::deque& FileSystemSample::SecondArguments() const -{ - return secondArguments_; -} -const std::deque& FileSystemSample::ThirdArguments() const -{ - return thirdArguments_; -} -const std::deque& FileSystemSample::FourthArguments() const -{ - return fourthArguments_; -} - -size_t PagedMemorySampleData::AppendNewData(uint32_t callChainId, - uint16_t type, - uint32_t ipid, - uint64_t startTs, - uint64_t endTs, - uint64_t dur, - size_t size, - DataIndex addr, - uint32_t itid) -{ - callChainIds_.emplace_back(callChainId); - types_.emplace_back(type); - ipids_.emplace_back(ipid); - startTs_.emplace_back(startTs); - endTs_.emplace_back(endTs); - durs_.emplace_back(dur); - Sizes_.emplace_back(size); - addrs_.emplace_back(addr); - itids_.emplace_back(itid); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& PagedMemorySampleData::CallChainIds() const -{ - return callChainIds_; -} -const std::deque& PagedMemorySampleData::Types() const -{ - return types_; -} -const std::deque& PagedMemorySampleData::Ipids() const -{ - return ipids_; -} -const std::deque& PagedMemorySampleData::Itids() const -{ - return itids_; -} -const std::deque& PagedMemorySampleData::StartTs() const -{ - return startTs_; -} -const std::deque& PagedMemorySampleData::EndTs() const -{ - return endTs_; -} -const std::deque& PagedMemorySampleData::Durs() const -{ - return durs_; -} -const std::deque& PagedMemorySampleData::Sizes() const -{ - return Sizes_; -} -const std::deque& PagedMemorySampleData::Addr() const -{ - return addrs_; -} - -size_t EbpfCallStackData::AppendNewData(uint32_t callChainId, - uint32_t depth, - DataIndex ip, - DataIndex symbolId, - DataIndex filePathId, - uint64_t vaddr) -{ - callChainIds_.emplace_back(callChainId); - depths_.emplace_back(depth); - ips_.emplace_back(ip); - symbolIds_.emplace_back(symbolId); - filePathIds_.emplace_back(filePathId); - vaddrs_.emplace_back(vaddr); - ids_.emplace_back(Size()); - return Size() - 1; -} -void EbpfCallStackData::UpdateEbpfSymbolInfo(size_t row, DataIndex symbolId) -{ - if (row >= Size()) { - TS_LOGE("The updated row does not exist!"); - return; - } - symbolIds_[row] = symbolId; -} -const std::deque& EbpfCallStackData::CallChainIds() const -{ - return callChainIds_; -} -const std::deque& EbpfCallStackData::Depths() const -{ - return depths_; -} -const std::deque& EbpfCallStackData::Ips() const -{ - return ips_; -} -const std::deque& EbpfCallStackData::SymbolIds() const -{ - return symbolIds_; -} -const std::deque& EbpfCallStackData::FilePathIds() const -{ - return filePathIds_; -} -const std::deque& EbpfCallStackData::Vaddrs() const -{ - return vaddrs_; -} -#if WITH_EBPF_HELP -size_t EbpfProcessMaps::AppendNewData(uint64_t start, - uint64_t end, - uint32_t offset, - uint32_t pid, - uint32_t fileNameLen, - uint64_t fileNameIndex) -{ - starts_.emplace_back(start); - ends_.emplace_back(end); - offsets_.emplace_back(offset); - pids_.emplace_back(pid); - fileNameLens_.emplace_back(fileNameLen); - fileNameIndexs_.emplace_back(fileNameIndex); - ids_.emplace_back(Size()); - return Size() - 1; -} - -const std::deque& EbpfProcessMaps::Starts() const -{ - return starts_; -} -const std::deque& EbpfProcessMaps::Ends() const -{ - return ends_; -} -const std::deque& EbpfProcessMaps::Offsets() const -{ - return offsets_; -} -const std::deque& EbpfProcessMaps::Pids() const -{ - return pids_; -} -const std::deque& EbpfProcessMaps::FileNameLens() const -{ - return fileNameLens_; -} -const std::deque& EbpfProcessMaps::FileNameIndexs() const -{ - return fileNameIndexs_; -} - -size_t EbpfElf::AppendNewData(uint64_t elfId, - uint64_t textVaddr, - uint32_t textOffset, - uint32_t strTabLen, - uint32_t symTabLen, - uint32_t fileNameLen, - uint32_t symEntLen, - uint64_t fileNameIndex) -{ - elfIds_.emplace_back(elfId); - textVaddrs_.emplace_back(textVaddr); - textOffsets_.emplace_back(textOffset); - strTabLens_.emplace_back(strTabLen); - symTabLens_.emplace_back(symTabLen); - fileNameLens_.emplace_back(fileNameLen); - symEntLens_.emplace_back(symEntLen); - fileNameIndexs_.emplace_back(fileNameIndex); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& EbpfElf::ElfIds() const -{ - return elfIds_; -} -const std::deque& EbpfElf::TextVaddrs() const -{ - return textVaddrs_; -} -const std::deque& EbpfElf::TextOffsets() const -{ - return textOffsets_; -} -const std::deque& EbpfElf::StrTabLens() const -{ - return strTabLens_; -} -const std::deque& EbpfElf::SymTabLens() const -{ - return symTabLens_; -} -const std::deque& EbpfElf::FileNameLens() const -{ - return fileNameLens_; -} -const std::deque& EbpfElf::SymEntLens() const -{ - return symEntLens_; -} -const std::deque& EbpfElf::FileNameIndexs() const -{ - return fileNameIndexs_; -} - -size_t EbpfElfSymbol::AppendNewData(uint64_t elfId, uint32_t stName, uint64_t stValue, uint64_t stSize) -{ - elfIds_.emplace_back(elfId); - stNames_.emplace_back(stName); - stValues_.emplace_back(stValue); - stSizes_.emplace_back(stSize); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& EbpfElfSymbol::ElfIds() const -{ - return elfIds_; -} -const std::deque& EbpfElfSymbol::StNames() const -{ - return stNames_; -} -const std::deque& EbpfElfSymbol::StValues() const -{ - return stValues_; -} -const std::deque& EbpfElfSymbol::StSizes() const -{ - return stSizes_; -} -#endif -uint32_t HiSysEventSubkeys::AppendSysEventSubkey(DataIndex eventSource, DataIndex appName) -{ - sysEventNameIds_.emplace_back(eventSource); - subkeyNameIds_.emplace_back(appName); - ids_.emplace_back(subkeyNameIds_.size() - 1); - return Size() - 1; -} -const std::deque& HiSysEventSubkeys::SysEventNameId() const -{ - return sysEventNameIds_; -} -const std::deque& HiSysEventSubkeys::SysEventSubkeyId() const -{ - return subkeyNameIds_; -} - -void HiSysEventMeasureData::AppendData(uint64_t serial, - uint64_t ts, - uint32_t nameId, - uint32_t keyId, - int32_t type, - double numericValue, - DataIndex stringValue) -{ - serial_.emplace_back(serial); - ts_.emplace_back(ts); - nameFilterIds_.emplace_back(nameId); - appKeyFilterIds_.emplace_back(keyId); - types_.emplace_back(type); - numValues_.emplace_back(numericValue); - stringValues_.emplace_back(stringValue); - ids_.emplace_back(rowCount_); - rowCount_++; -} -const std::deque& HiSysEventMeasureData::Serial() const -{ - return serial_; -} -const std::deque& HiSysEventMeasureData::Ts() const -{ - return ts_; -} -const std::deque& HiSysEventMeasureData::NameFilterId() const -{ - return nameFilterIds_; -} -const std::deque& HiSysEventMeasureData::AppKeyFilterId() const -{ - return appKeyFilterIds_; -} -const std::deque& HiSysEventMeasureData::Type() const -{ - return types_; -} -const std::deque& HiSysEventMeasureData::NumValue() const -{ - return numValues_; -} -const std::deque& HiSysEventMeasureData::StringValue() const -{ - return stringValues_; -} -void HiSysEventDeviceStateData::AppendNewData(int32_t brightness, - int32_t btState, - int32_t location, - int32_t wifi, - int32_t streamDefault, - int32_t voiceCall, - int32_t music, - int32_t streamRing, - int32_t media, - int32_t voiceAssistant, - int32_t system, - int32_t alarm, - int32_t notification, - int32_t btSco, - int32_t enforcedAudible, - int32_t streamDtmf, - int32_t streamTts, - int32_t accessibility, - int32_t recording, - int32_t streamAll) -{ - brightness_.emplace_back(brightness); - btStates_.emplace_back(btState); - locations_.emplace_back(location); - wifis_.emplace_back(wifi); - streamDefaults_.emplace_back(streamDefault); - voiceCalls_.emplace_back(voiceCall); - musics_.emplace_back(music); - streamRings_.emplace_back(streamRing); - medias_.emplace_back(media); - voiceAssistants_.emplace_back(voiceAssistant); - systems_.emplace_back(system); - alarms_.emplace_back(alarm); - notifications_.emplace_back(notification); - btScos_.emplace_back(btSco); - enforcedAudibles_.emplace_back(enforcedAudible); - streamDtmfs_.emplace_back(streamDtmf); - streamTts_.emplace_back(streamTts); - accessibilitys_.emplace_back(accessibility); - recordings_.emplace_back(recording); - streamAlls_.emplace_back(streamAll); - ids_.emplace_back(rowCounts_); - rowCounts_++; -} -const std::deque& HiSysEventDeviceStateData::Brightness() const -{ - return brightness_; -} -const std::deque& HiSysEventDeviceStateData::BtState() const -{ - return btStates_; -} -const std::deque& HiSysEventDeviceStateData::Location() const -{ - return locations_; -} -const std::deque& HiSysEventDeviceStateData::Wifi() const -{ - return wifis_; -} -const std::deque& HiSysEventDeviceStateData::StreamDefault() const -{ - return streamDefaults_; -} -const std::deque& HiSysEventDeviceStateData::VoiceCall() const -{ - return voiceCalls_; -} -const std::deque& HiSysEventDeviceStateData::Music() const -{ - return musics_; -} -const std::deque& HiSysEventDeviceStateData::StreamRing() const -{ - return streamRings_; -} -const std::deque& HiSysEventDeviceStateData::Media() const -{ - return medias_; -} -const std::deque& HiSysEventDeviceStateData::VoiceAssistant() const -{ - return voiceAssistants_; -} -const std::deque& HiSysEventDeviceStateData::System() const -{ - return systems_; -} -const std::deque& HiSysEventDeviceStateData::Alarm() const -{ - return alarms_; -} -const std::deque& HiSysEventDeviceStateData::Notification() const -{ - return notifications_; -} -const std::deque& HiSysEventDeviceStateData::BtSco() const -{ - return btScos_; -} -const std::deque& HiSysEventDeviceStateData::EnforcedAudible() const -{ - return enforcedAudibles_; -} -const std::deque& HiSysEventDeviceStateData::StreamDtmf() const -{ - return streamDtmfs_; -} -const std::deque& HiSysEventDeviceStateData::StreamTts() const -{ - return streamTts_; -} -const std::deque& HiSysEventDeviceStateData::Accessibility() const -{ - return accessibilitys_; -} -const std::deque& HiSysEventDeviceStateData::Recordings() const -{ - return recordings_; -} -const std::deque& HiSysEventDeviceStateData::StreamAll() const -{ - return streamAlls_; -} -void TraceConfig::AppendNewData(std::string traceSource, std::string key, std::string value) -{ - traceSource_.emplace_back(traceSource); - key_.emplace_back(key); - value_.emplace_back(value); - ids_.emplace_back(rowCounts_); - rowCounts_++; -} -const std::deque& TraceConfig::TraceSource() const -{ - return traceSource_; -} -const std::deque& TraceConfig::Key() const -{ - return key_; -} -const std::deque& TraceConfig::Value() const -{ - return value_; -} -uint32_t HiSysEventAllEventData::AppendHiSysEventData(DataIndex domainId, - DataIndex eventNameId, - uint64_t timeStamp, - uint32_t type, - const std::string& timeZone, - uint32_t pid, - uint32_t tid, - uint32_t uid, - const std::string& level, - const std::string& tag, - const std::string& eventId, - uint64_t seq, - const std::string& info, - const std::string& content) -{ - domainIds_.emplace_back(domainId); - eventNameIds_.emplace_back(eventNameId); - timeStamps_.emplace_back(timeStamp); - types_.emplace_back(type); - timeZones_.emplace_back(timeZone); - pids_.emplace_back(pid); - tids_.emplace_back(tid); - uids_.emplace_back(uid); - levels_.emplace_back(level); - tags_.emplace_back(tag); - eventIds_.emplace_back(eventId); - seqs_.emplace_back(seq); - infos_.emplace_back(info); - contents_.emplace_back(content); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& HiSysEventAllEventData::DomainIds() const -{ - return domainIds_; -} -const std::deque& HiSysEventAllEventData::EventNameIds() const -{ - return eventNameIds_; -} -const std::deque& HiSysEventAllEventData::Types() const -{ - return types_; -} -const std::deque& HiSysEventAllEventData::TimeZones() const -{ - return timeZones_; -} -const std::deque& HiSysEventAllEventData::Pids() const -{ - return pids_; -} -const std::deque& HiSysEventAllEventData::Tids() const -{ - return tids_; -} -const std::deque& HiSysEventAllEventData::Uids() const -{ - return uids_; -} -const std::deque& HiSysEventAllEventData::Levels() const -{ - return levels_; -} -const std::deque& HiSysEventAllEventData::Tags() const -{ - return tags_; -} -const std::deque& HiSysEventAllEventData::EventIds() const -{ - return eventIds_; -} -const std::deque& HiSysEventAllEventData::Seqs() const -{ - return seqs_; -} -const std::deque& HiSysEventAllEventData::Infos() const -{ - return infos_; -} -const std::deque& HiSysEventAllEventData::Contents() const -{ - return contents_; -} -void SmapsData::AppendNewData(uint64_t timeStamp, - uint64_t ipid, - std::string startAddr, - std::string endAddr, - uint64_t dirty, - uint64_t swapper, - uint64_t rss, - uint64_t pss, - uint64_t size, - double reside, - DataIndex protectionId, - DataIndex pathId, - uint64_t sharedClean, - uint64_t sharedDirty, - uint64_t privateClean, - uint64_t privateDirty, - uint64_t swap, - uint64_t swapPss, - uint32_t type) -{ - timeStamps_.emplace_back(timeStamp); - ipids_.emplace_back(ipid); - startAddrs_.emplace_back(startAddr); - endAddrs_.emplace_back(endAddr); - dirtys_.emplace_back(dirty); - swappers_.emplace_back(swapper); - rss_.emplace_back(rss); - pss_.emplace_back(pss); - sizes_.emplace_back(size); - resides_.emplace_back(reside); - protectionIds_.emplace_back(protectionId); - pathIds_.emplace_back(pathId); - sharedClean_.emplace_back(sharedClean); - sharedDirty_.emplace_back(sharedDirty); - privateClean_.emplace_back(privateClean); - privateDirty_.emplace_back(privateDirty); - swap_.emplace_back(swap); - swapPss_.emplace_back(swapPss); - type_.emplace_back(type); - ids_.emplace_back(rowCount_); - rowCount_++; -} -const std::deque& SmapsData::TimeStamps() const -{ - return timeStamps_; -} -const std::deque& SmapsData::Ipids() const -{ - return ipids_; -} -const std::deque& SmapsData::StartAddrs() const -{ - return startAddrs_; -} -const std::deque& SmapsData::EndAddrs() const -{ - return endAddrs_; -} -const std::deque& SmapsData::Dirtys() const -{ - return dirtys_; -} -const std::deque& SmapsData::Swappers() const -{ - return swappers_; -} -const std::deque& SmapsData::Rss() const -{ - return rss_; -} -const std::deque& SmapsData::Pss() const -{ - return pss_; -} -const std::deque& SmapsData::Sizes() const -{ - return sizes_; -} -const std::deque& SmapsData::Resides() const -{ - return resides_; -} -const std::deque& SmapsData::ProtectionIds() const -{ - return protectionIds_; -} -const std::deque& SmapsData::PathIds() const -{ - return pathIds_; -} -const std::deque& SmapsData::SharedClean() const -{ - return sharedClean_; -} -const std::deque& SmapsData::SharedDirty() const -{ - return sharedDirty_; -} -const std::deque& SmapsData::PrivateClean() const -{ - return privateClean_; -} -const std::deque& SmapsData::PrivateDirty() const -{ - return privateDirty_; -} -const std::deque& SmapsData::Swap() const -{ - return swap_; -} -const std::deque& SmapsData::SwapPss() const -{ - return swapPss_; -} -const std::deque& SmapsData::Type() const -{ - return type_; -} -void BioLatencySampleData::AppendNewData(uint32_t callChainId, - uint64_t type, - uint32_t ipid, - uint32_t itid, - uint64_t startTs, - uint64_t endTs, - uint64_t latencyDur, - uint32_t tier, - uint64_t size, - uint64_t blockNumber, - uint64_t filePathId, - uint64_t durPer4k) -{ - callChainIds_.emplace_back(callChainId); - types_.emplace_back(type); - ipids_.emplace_back(ipid); - itids_.emplace_back(itid); - startTs_.emplace_back(startTs); - endTs_.emplace_back(endTs); - latencyDurs_.emplace_back(latencyDur); - tiers_.emplace_back(tier); - sizes_.emplace_back(size); - blockNumbers_.emplace_back(blockNumber); - filePathIds_.emplace_back(filePathId); - durPer4ks_.emplace_back(durPer4k); - ids_.emplace_back(rowCount_); - rowCount_++; -} -const std::deque& BioLatencySampleData::CallChainIds() const -{ - return callChainIds_; -} -const std::deque& BioLatencySampleData::Types() const -{ - return types_; -} -const std::deque& BioLatencySampleData::Ipids() const -{ - return ipids_; -} -const std::deque& BioLatencySampleData::Itids() const -{ - return itids_; -} -const std::deque& BioLatencySampleData::StartTs() const -{ - return startTs_; -} -const std::deque& BioLatencySampleData::EndTs() const -{ - return endTs_; -} -const std::deque& BioLatencySampleData::LatencyDurs() const -{ - return latencyDurs_; -} -const std::deque& BioLatencySampleData::Tiers() const -{ - return tiers_; -} -const std::deque& BioLatencySampleData::Sizes() const -{ - return sizes_; -} -const std::deque& BioLatencySampleData::BlockNumbers() const -{ - return blockNumbers_; -} -const std::deque& BioLatencySampleData::FilePathIds() const -{ - return filePathIds_; -} -const std::deque& BioLatencySampleData::DurPer4k() const -{ - return durPer4ks_; -} -DataSourceClockIdData::DataSourceClockIdData() - : dataSource2ClockIdMap_({{DATA_SOURCE_TYPE_TRACE, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_MEM, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_HILOG, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_NATIVEHOOK, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_FPS, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_NETWORK, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_DISKIO, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_CPU, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_PROCESS, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_HISYSEVENT, TS_CLOCK_UNKNOW}, - {DATA_SOURCE_TYPE_JSMEMORY, TS_CLOCK_UNKNOW}}), - dataSource2PluginNameMap_({ - {DATA_SOURCE_TYPE_TRACE, "ftrace-plugin"}, - {DATA_SOURCE_TYPE_MEM, "memory-plugin"}, - {DATA_SOURCE_TYPE_HILOG, "hilog-plugin"}, - {DATA_SOURCE_TYPE_NATIVEHOOK, "nativehook"}, - {DATA_SOURCE_TYPE_FPS, "hidump-plugin"}, - {DATA_SOURCE_TYPE_NETWORK, "network-plugin"}, - {DATA_SOURCE_TYPE_DISKIO, "diskio-plugin"}, - {DATA_SOURCE_TYPE_CPU, "cpu-plugin"}, - {DATA_SOURCE_TYPE_PROCESS, "process-plugin"}, - {DATA_SOURCE_TYPE_HISYSEVENT, "hisysevent-plugin"}, - {DATA_SOURCE_TYPE_JSMEMORY, "arkts-plugin"}, - }) -{ -} -void DataSourceClockIdData::Finish() -{ - for (auto i = dataSource2ClockIdMap_.begin(); i != dataSource2ClockIdMap_.end(); i++) { - if (i->second) { // ignore the empty datasource, for which the clockid is default TS_CLOCK_UNKNOW 0 - dataSourceNames_.emplace_back(dataSource2PluginNameMap_.at(i->first)); - clockIds_.emplace_back(i->second); - } - } -} -void DataSourceClockIdData::SetDataSourceClockId(DataSourceType source, uint32_t id) -{ - dataSource2ClockIdMap_.at(source) = id; -} -size_t FrameSlice::AppendFrame(uint64_t ts, uint32_t ipid, uint32_t itid, uint32_t vsyncId, uint64_t callStackSliceId) -{ - timeStamps_.emplace_back(ts); - ipids_.emplace_back(ipid); - internalTids_.emplace_back(itid); - vsyncIds_.emplace_back(vsyncId); - callStackIds_.emplace_back(callStackSliceId); - endTss_.emplace_back(INVALID_UINT64); - dsts_.emplace_back(INVALID_UINT64); - ids_.emplace_back(ids_.size()); - durs_.emplace_back(INVALID_UINT64); - types_.emplace_back(0); - flags_.emplace_back(INVALID_UINT8); - srcs_.emplace_back(""); - depths_.emplace_back(0); - frameNos_.emplace_back(0); - return Size() - 1; -} -size_t FrameSlice::AppendFrame(uint64_t ts, - uint32_t ipid, - uint32_t itid, - uint32_t vsyncId, - uint64_t callStackSliceId, - uint64_t end, - uint8_t type) -{ - auto row = AppendFrame(ts, ipid, itid, vsyncId, callStackSliceId); - SetEndTime(row, end); - SetType(row, type); - depths_.emplace_back(0); - frameNos_.emplace_back(0); - durs_[row] = end - ts; - return row; -} - -void FrameSlice::UpdateDepth() -{ - DoubleMap>> ipidAndTypesToVEndTime(nullptr); - for (auto row = 0; row < Size(); row++) { - if (flags_[row] == flagValue_) { - continue; - } - auto endTime = timeStamps_[row] + durs_[row]; - auto vEndTimes = ipidAndTypesToVEndTime.Find(ipids_[row], types_[row]); - auto depth = 0; - if (!vEndTimes) { - vEndTimes = std::make_shared>(); - vEndTimes->push_back(endTime); - ipidAndTypesToVEndTime.Insert(ipids_[row], types_[row], vEndTimes); - depths_[row] = depth; - continue; - } - for (; depth < vEndTimes->size(); depth++) { - if (timeStamps_[row] > vEndTimes->at(depth)) { - depths_[row] = depth; - vEndTimes->at(depth) = endTime; - break; - } - } - if (depth == vEndTimes->size()) { - depths_[row] = depth; - vEndTimes->push_back(endTime); - } - } -} - -void FrameSlice::SetEndTime(uint64_t row, uint64_t end) -{ - endTss_[row] = end; -} -void FrameSlice::SetType(uint64_t row, uint8_t type) -{ - types_[row] = type; -} -void FrameSlice::SetDst(uint64_t row, uint64_t dst) -{ - dsts_[row] = dst; -} - -void FrameSlice::SetSrcs(uint64_t row, const std::vector& fromSlices) -{ - std::string s = ""; - for (auto&& i : fromSlices) { - s += std::to_string(i) + ","; - } - s.pop_back(); - srcs_[row] = s; -} -void FrameSlice::SetFlags(uint64_t row, const uint32_t flags) -{ - flags_[row] = flags; -} -const std::deque FrameSlice::Ipids() const -{ - return ipids_; -} -const std::deque FrameSlice::VsyncIds() const -{ - return vsyncIds_; -} -const std::deque FrameSlice::CallStackIds() const -{ - return callStackIds_; -} -const std::deque FrameSlice::EndTss() const -{ - return endTss_; -} -const std::deque FrameSlice::Dsts() const -{ - return dsts_; -} -const std::deque FrameSlice::Durs() const -{ - return durs_; -} -const std::deque FrameSlice::Types() const -{ - return types_; -} -const std::deque FrameSlice::Flags() const -{ - return flags_; -} - -const std::deque FrameSlice::Depths() const -{ - return depths_; -} -const std::deque FrameSlice::FrameNos() const -{ - return frameNos_; -} -const std::deque& FrameSlice::Srcs() const -{ - return srcs_; -} -void FrameSlice::UpdateCallStackSliceId(uint64_t row, uint64_t callStackSliceId) -{ - callStackIds_[row] = callStackSliceId; -} -void FrameSlice::SetEndTimeAndFlag(uint64_t row, uint64_t ts, uint64_t expectDur, uint64_t expectEnd) -{ - UNUSED(expectDur); - durs_[row] = ts - timeStamps_[row]; - if (flags_[row] != abnormalStartEndTimeState_) { - flags_[row] = expectEnd >= ts ? 0 : 1; - } -} -void FrameSlice::Erase(uint64_t row) -{ - flags_[row] = invalidRow_; -} -size_t FrameMaps::AppendNew(FrameSlice* frameSlice, uint64_t src, uint64_t dst) -{ - timeStamps_.emplace_back(0); - ids_.emplace_back(ids_.size()); - srcs_.emplace_back(src); - dsts_.emplace_back(dst); - if (frameSlice->Types().at(dst) == FrameSlice::EXPECT_SLICE) { - uint64_t expRsStartTime = frameSlice->TimeStampData().at(dst); - uint64_t expUiEndTime = frameSlice->TimeStampData().at(src) + frameSlice->Durs().at(src); - if (std::abs(static_cast(expRsStartTime - expUiEndTime)) >= ONE_MILLION_NANOSECONDS) { - auto acturalRow = dst - 1; - frameSlice->SetFlags(acturalRow, FrameSlice::GetAbnormalStartEndTimeState()); - } - } - - return Size() - 1; -} -const std::deque& FrameMaps::SrcIndexs() const -{ - return srcs_; -} -const std::deque& FrameMaps::DstIndexs() const -{ - return dsts_; -} - -size_t GPUSlice::AppendNew(uint32_t frameRow, uint64_t dur) -{ - frameRows_.emplace_back(frameRow); - durs_.emplace_back(dur); - return Size() - 1; -} -const std::deque& GPUSlice::FrameRows() const -{ - return frameRows_; -} -const std::deque& GPUSlice::Durs() const -{ - return durs_; -} -size_t GPUSlice::Size() const -{ - return durs_.size(); -} - -size_t AppStartup::AppendNewData(uint32_t ipid, - uint32_t tid, - uint32_t callId, - uint64_t startTime, - uint64_t endTime, - uint32_t startName, - DataIndex packedName) -{ - ipids_.emplace_back(ipid); - tids_.emplace_back(tid); - callIds_.emplace_back(callId); - startTimes_.emplace_back(startTime); - endTimes_.emplace_back(endTime); - startNames_.emplace_back(startName); - packedNames_.emplace_back(packedName); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& AppStartup::Pids() const -{ - return ipids_; -} -const std::deque& AppStartup::Tids() const -{ - return tids_; -} -const std::deque& AppStartup::CallIds() const -{ - return callIds_; -} -const std::deque& AppStartup::StartTimes() const -{ - return startTimes_; -} -const std::deque& AppStartup::EndTimes() const -{ - return endTimes_; -} -const std::deque& AppStartup::StartNames() const -{ - return startNames_; -} -const std::deque& AppStartup::PackedNames() const -{ - return packedNames_; -} - -size_t SoStaticInitalization::AppendNewData(uint32_t ipid, - uint32_t tid, - uint32_t callId, - uint64_t startTime, - uint64_t endTime, - DataIndex soName, - uint32_t depth) -{ - ipids_.emplace_back(ipid); - tids_.emplace_back(tid); - callIds_.emplace_back(callId); - startTimes_.emplace_back(startTime); - endTimes_.emplace_back(endTime); - soNames_.emplace_back(soName); - depths_.emplace_back(depth); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& SoStaticInitalization::Pids() const -{ - return ipids_; -} -const std::deque& SoStaticInitalization::Tids() const -{ - return tids_; -} -const std::deque& SoStaticInitalization::CallIds() const -{ - return callIds_; -} -const std::deque& SoStaticInitalization::StartTimes() const -{ - return startTimes_; -} -const std::deque& SoStaticInitalization::EndTimes() const -{ - return endTimes_; -} -const std::deque& SoStaticInitalization::SoNames() const -{ - return soNames_; -} -const std::deque SoStaticInitalization::Depths() const -{ - return depths_; -} - -size_t JsHeapFiles::AppendNewData(uint32_t id, - std::string filePath, - uint64_t startTime, - uint64_t endTime, - uint64_t selfSizeCount) -{ - fileIds_.emplace_back(id); - filePaths_.emplace_back(filePath); - startTimes_.emplace_back(startTime); - endTimes_.emplace_back(endTime); - selfSizeCount_.emplace_back(selfSizeCount); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapFiles::IDs() const -{ - return fileIds_; -} -const std::deque& JsHeapFiles::FilePaths() const -{ - return filePaths_; -} -const std::deque& JsHeapFiles::StartTimes() const -{ - return startTimes_; -} -const std::deque& JsHeapFiles::EndTimes() const -{ - return endTimes_; -} - -const std::deque& JsHeapFiles::SelfSizeCount() const -{ - return selfSizeCount_; -} - -size_t JsHeapEdges::AppendNewData(uint32_t fileId, - uint32_t edgeIndex, - uint32_t type, - uint32_t nameOrIndex, - uint32_t toNode, - uint32_t fromNodeId, - uint32_t toNodeId) -{ - fileIds_.emplace_back(fileId); - edgeIndexs_.emplace_back(edgeIndex); - types_.emplace_back(type); - nameOrIndexs_.emplace_back(nameOrIndex); - toNodes_.emplace_back(toNode); - fromNodeIds_.emplace_back(fromNodeId); - toNodeIds_.emplace_back(toNodeId); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapEdges::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapEdges::EdgeIndexs() const -{ - return edgeIndexs_; -} -const std::deque& JsHeapEdges::Types() const -{ - return types_; -} -const std::deque& JsHeapEdges::NameOrIndexs() const -{ - return nameOrIndexs_; -} -const std::deque& JsHeapEdges::ToNodes() const -{ - return toNodes_; -} -const std::deque& JsHeapEdges::FromNodeIds() const -{ - return fromNodeIds_; -} -const std::deque& JsHeapEdges::ToNodeIds() const -{ - return toNodeIds_; -} - -size_t - JsHeapInfo::AppendNewData(uint32_t fileId, std::string key, uint32_t type, int32_t intValue, std::string strValue) -{ - fileIds_.emplace_back(fileId); - keys_.emplace_back(key); - types_.emplace_back(type); - intValues_.emplace_back(intValue); - strValues_.emplace_back(strValue); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapInfo::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapInfo::Keys() const -{ - return keys_; -} -const std::deque& JsHeapInfo::Types() const -{ - return types_; -} -const std::deque& JsHeapInfo::IntValues() const -{ - return intValues_; -} -const std::deque& JsHeapInfo::StrValues() const -{ - return strValues_; -} - -size_t JsHeapLocation::AppendNewData(uint32_t fileId, - uint32_t objectIndex, - uint32_t scriptId, - uint32_t line, - uint32_t column) -{ - fileIds_.emplace_back(fileId); - objectIndexs_.emplace_back(objectIndex); - scriptIds_.emplace_back(scriptId); - lines_.emplace_back(line); - columns_.emplace_back(column); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapLocation::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapLocation::ObjectIndexs() const -{ - return objectIndexs_; -} -const std::deque& JsHeapLocation::ScriptIds() const -{ - return scriptIds_; -} -const std::deque& JsHeapLocation::Lines() const -{ - return lines_; -} -const std::deque& JsHeapLocation::Columns() const -{ - return columns_; -} - -size_t JsHeapNodes::AppendNewData(uint32_t fileId, - uint32_t nodeIndex, - uint32_t type, - uint32_t name, - uint32_t id, - uint32_t selfSize, - uint32_t edgeCount, - uint32_t traceNodeId, - uint32_t detachedNess) -{ - fileIds_.emplace_back(fileId); - nodeIndexs_.emplace_back(nodeIndex); - types_.emplace_back(type); - names_.emplace_back(name); - nodeIds_.emplace_back(id); - selfSizes_.emplace_back(selfSize); - edgeCounts_.emplace_back(edgeCount); - traceNodeIds_.emplace_back(traceNodeId); - detachedNess_.emplace_back(detachedNess); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapNodes::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapNodes::NodeIndexs() const -{ - return nodeIndexs_; -} -const std::deque& JsHeapNodes::Types() const -{ - return types_; -} -const std::deque& JsHeapNodes::Names() const -{ - return names_; -} -const std::deque& JsHeapNodes::NodeIds() const -{ - return nodeIds_; -} -const std::deque& JsHeapNodes::SelfSizes() const -{ - return selfSizes_; -} -const std::deque& JsHeapNodes::EdgeCounts() const -{ - return edgeCounts_; -} -const std::deque& JsHeapNodes::TraceNodeIds() const -{ - return traceNodeIds_; -} -const std::deque& JsHeapNodes::DetachedNess() const -{ - return detachedNess_; -} - -size_t JsHeapSample::AppendNewData(uint32_t fileId, uint64_t timeStampUs, uint32_t lastAssignedId) -{ - fileIds_.emplace_back(fileId); - timeStampUs_.emplace_back(timeStampUs); - lastAssignedIds_.emplace_back(lastAssignedId); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapSample::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapSample::TimeStampUs() const -{ - return timeStampUs_; -} -const std::deque& JsHeapSample::LastAssignedIds() const -{ - return lastAssignedIds_; -} - -size_t JsHeapString::AppendNewData(uint32_t fileId, uint32_t fileIndex, std::string string) -{ - fileIds_.emplace_back(fileId); - fileIndexs_.emplace_back(fileIndex); - strings_.emplace_back(string); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapString::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapString::FileIndexs() const -{ - return fileIndexs_; -} -const std::deque& JsHeapString::Strings() const -{ - return strings_; -} - -size_t JsHeapTraceFuncInfo::AppendNewData(uint32_t fileId, - uint32_t functionIndex, - uint32_t functionId, - uint32_t name, - uint32_t scriptName, - uint32_t scriptId, - uint32_t line, - uint32_t column) -{ - fileIds_.emplace_back(fileId); - functionIndexs_.emplace_back(functionIndex); - functionIds_.emplace_back(functionId); - names_.emplace_back(name); - scriptNames_.emplace_back(scriptName); - scriptIds_.emplace_back(scriptId); - lines_.emplace_back(line); - columns_.emplace_back(column); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapTraceFuncInfo::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapTraceFuncInfo::FunctionIndexs() const -{ - return functionIndexs_; -} -const std::deque& JsHeapTraceFuncInfo::FunctionIds() const -{ - return functionIds_; -} -const std::deque& JsHeapTraceFuncInfo::Names() const -{ - return names_; -} -const std::deque& JsHeapTraceFuncInfo::ScriptNames() const -{ - return scriptNames_; -} -const std::deque& JsHeapTraceFuncInfo::ScriptIds() const -{ - return scriptIds_; -} -const std::deque& JsHeapTraceFuncInfo::Lines() const -{ - return lines_; -} -const std::deque& JsHeapTraceFuncInfo::Columns() const -{ - return columns_; -} - -size_t JsHeapTraceNode::AppendNewData(uint32_t fileId, - uint32_t traceNodeId, - uint32_t functionInfoIndex, - uint32_t count, - uint32_t size, - int32_t parentId) -{ - fileIds_.emplace_back(fileId); - traceNodeIds_.emplace_back(traceNodeId); - functionInfoIndexs_.emplace_back(functionInfoIndex); - counts_.emplace_back(count); - sizes_.emplace_back(size); - parentIds_.emplace_back(parentId); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsHeapTraceNode::FileIds() const -{ - return fileIds_; -} -const std::deque& JsHeapTraceNode::TraceNodeIDs() const -{ - return traceNodeIds_; -} -const std::deque& JsHeapTraceNode::FunctionInfoIndexs() const -{ - return functionInfoIndexs_; -} -const std::deque& JsHeapTraceNode::Counts() const -{ - return counts_; -} -const std::deque& JsHeapTraceNode::NodeSizes() const -{ - return sizes_; -} -const std::deque& JsHeapTraceNode::ParentIds() const -{ - return parentIds_; -} - -size_t JsCpuProfilerNode::AppendNewData(uint32_t functionId, - uint32_t functionName, - std::string scriptId, - uint32_t url, - uint32_t lineNumber, - uint32_t columnNumber, - uint32_t hitCount, - std::string children, - uint32_t parent) -{ - functionIds_.emplace_back(functionId); - functionNames_.emplace_back(functionName); - scriptIds_.emplace_back(scriptId); - urls_.emplace_back(url); - lineNumbers_.emplace_back(lineNumber); - columnNumbers_.emplace_back(columnNumber); - hitCounts_.emplace_back(hitCount); - children_.emplace_back(children); - parents_.emplace_back(parent); - ids_.emplace_back(Size()); - return Size() - 1; -} - -const std::deque& JsCpuProfilerNode::FunctionIds() const -{ - return functionIds_; -} -const std::deque& JsCpuProfilerNode::FunctionNames() const -{ - return functionNames_; -} -const std::deque& JsCpuProfilerNode::ScriptIds() const -{ - return scriptIds_; -} -const std::deque& JsCpuProfilerNode::Urls() const -{ - return urls_; -} -const std::deque& JsCpuProfilerNode::LineNumbers() const -{ - return lineNumbers_; -} -const std::deque& JsCpuProfilerNode::ColumnNumbers() const -{ - return columnNumbers_; -} -const std::deque& JsCpuProfilerNode::HitCounts() const -{ - return hitCounts_; -} -const std::deque& JsCpuProfilerNode::Children() const -{ - return children_; -} -const std::deque& JsCpuProfilerNode::Parents() const -{ - return parents_; -} - -size_t JsCpuProfilerSample::AppendNewData(uint32_t functionId, uint64_t startTime, uint64_t endTime, uint64_t dur) -{ - functionIds_.emplace_back(functionId); - startTimes_.emplace_back(startTime); - endTimes_.emplace_back(endTime); - durs_.emplace_back(dur); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsCpuProfilerSample::FunctionIds() const -{ - return functionIds_; -} -const std::deque& JsCpuProfilerSample::StartTimes() const -{ - return startTimes_; -} -const std::deque& JsCpuProfilerSample::EndTimes() const -{ - return endTimes_; -} -const std::deque& JsCpuProfilerSample::Durs() const -{ - return durs_; -} - -size_t JsConfig::AppendNewData(uint32_t pid, - uint64_t type, - uint32_t interval, - uint32_t captureNumericValue, - uint32_t trackAllocation, - uint32_t cpuProfiler, - uint32_t cpuProfilerInterval) -{ - pids_.emplace_back(pid); - types_.emplace_back(type); - intervals_.emplace_back(interval); - captureNumericValues_.emplace_back(captureNumericValue); - trackAllocations_.emplace_back(trackAllocation); - cpuProfilers_.emplace_back(cpuProfiler); - cpuProfilerIntervals_.emplace_back(cpuProfilerInterval); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& JsConfig::Pids() const -{ - return pids_; -} -const std::deque& JsConfig::Types() const -{ - return types_; -} -const std::deque& JsConfig::Intervals() const -{ - return intervals_; -} -const std::deque& JsConfig::CaptureNumericValue() const -{ - return captureNumericValues_; -} -const std::deque& JsConfig::TrackAllocations() const -{ - return trackAllocations_; -} -const std::deque& JsConfig::CpuProfiler() const -{ - return cpuProfilers_; -} -const std::deque& JsConfig::CpuProfilerInterval() const -{ - return cpuProfilerIntervals_; -} - -size_t TaskPoolInfo::AppendAllocationTaskData(uint32_t allocationTaskRow, - uint32_t allocationItid, - uint32_t executeId, - uint32_t priority, - uint32_t executeState) -{ - allocationTaskRows_.emplace_back(allocationTaskRow); - executeTaskRows_.emplace_back(INVALID_INT32); - returnTaskRows_.emplace_back(INVALID_INT32); - allocationItids_.emplace_back(allocationItid); - executeItids_.emplace_back(INVALID_INT32); - returnItids_.emplace_back(INVALID_INT32); - executeIds_.emplace_back(executeId); - prioritys_.emplace_back(priority); - executeStates_.emplace_back(executeState); - returnStates_.emplace_back(INVALID_INT32); - timeoutRows_.emplace_back(INVALID_INT32); - ids_.emplace_back(Size()); - return Size() - 1; -} -size_t TaskPoolInfo::AppendExecuteTaskData(uint32_t executeTaskRow, uint32_t executeItid, uint32_t executeId) -{ - allocationTaskRows_.emplace_back(INVALID_INT32); - executeTaskRows_.emplace_back(executeTaskRow); - returnTaskRows_.emplace_back(INVALID_INT32); - allocationItids_.emplace_back(INVALID_INT32); - executeItids_.emplace_back(executeItid); - returnItids_.emplace_back(INVALID_INT32); - executeIds_.emplace_back(executeId); - prioritys_.emplace_back(INVALID_INT32); - executeStates_.emplace_back(INVALID_INT32); - returnStates_.emplace_back(INVALID_INT32); - timeoutRows_.emplace_back(INVALID_INT32); - ids_.emplace_back(Size()); - return Size() - 1; -} -size_t TaskPoolInfo::AppendReturnTaskData(uint32_t returnTaskRow, - uint32_t returnItid, - uint32_t executeId, - uint32_t returnState) -{ - allocationTaskRows_.emplace_back(INVALID_INT32); - executeTaskRows_.emplace_back(INVALID_INT32); - returnTaskRows_.emplace_back(returnTaskRow); - allocationItids_.emplace_back(INVALID_INT32); - executeItids_.emplace_back(INVALID_INT32); - returnItids_.emplace_back(returnItid); - executeIds_.emplace_back(executeId); - prioritys_.emplace_back(INVALID_INT32); - executeStates_.emplace_back(INVALID_INT32); - returnStates_.emplace_back(returnState); - timeoutRows_.emplace_back(INVALID_INT32); - ids_.emplace_back(Size()); - return Size() - 1; -} -const std::deque& TaskPoolInfo::AllocationTaskRows() const -{ - return allocationTaskRows_; -} -const std::deque& TaskPoolInfo::ExecuteTaskRows() const -{ - return executeTaskRows_; -} -const std::deque& TaskPoolInfo::ReturnTaskRows() const -{ - return returnTaskRows_; -} -const std::deque& TaskPoolInfo::AllocationItids() const -{ - return allocationItids_; -} -const std::deque& TaskPoolInfo::ExecuteItids() const -{ - return executeItids_; -} -const std::deque& TaskPoolInfo::ReturnItids() const -{ - return returnItids_; -} -const std::deque& TaskPoolInfo::ExecuteIds() const -{ - return executeIds_; -} -const std::deque& TaskPoolInfo::Prioritys() const -{ - return prioritys_; -} -const std::deque& TaskPoolInfo::ExecuteStates() const -{ - return executeStates_; -} -const std::deque& TaskPoolInfo::ReturnStates() const -{ - return returnStates_; -} -const std::deque& TaskPoolInfo::TimeoutRows() const -{ - return timeoutRows_; -} -void TaskPoolInfo::UpdateAllocationTaskData(uint32_t index, - uint32_t allocationTaskRow, - uint32_t allocationItid, - uint32_t priority, - uint32_t executeState) -{ - if (index <= Size()) { - allocationTaskRows_[index] = allocationTaskRow; - allocationItids_[index] = allocationItid; - prioritys_[index] = priority; - executeStates_[index] = executeState; - } -} -void TaskPoolInfo::UpdateExecuteTaskData(uint32_t index, uint32_t executeTaskRow, uint32_t executeItid) -{ - if (index <= Size()) { - executeTaskRows_[index] = executeTaskRow; - executeItids_[index] = executeItid; - } -} -void TaskPoolInfo::UpdateReturnTaskData(uint32_t index, - uint32_t returnTaskRow, - uint32_t returnItid, - uint32_t returnState) -{ - if (index <= Size()) { - returnTaskRows_[index] = returnTaskRow; - returnItids_[index] = returnItid; - returnStates_[index] = returnState; - } -} -void TaskPoolInfo::AppendTimeoutRow(uint32_t index, uint32_t timeoutRow) -{ - if (index <= Size()) { - timeoutRows_[index] = timeoutRow; - } -} -TableRowId Animation::AppendAnimation(InternalTime inputTime, InternalTime startPoint, DataIndex nameIndex) -{ - inputTimes_.emplace_back(inputTime); - startPoints_.emplace_back(startPoint); - endPoins_.emplace_back(INVALID_TIME); - frameInfos_.emplace_back(INVALID_UINT64); - names_.emplace_back(nameIndex); - ids_.emplace_back(Size()); - return ids_.size() - 1; -} -void Animation::UpdateStartPoint(TableRowId index, InternalTime startPoint) -{ - if (index <= Size()) { - startPoints_[index] = startPoint; - } -} -void Animation::UpdateEndPoint(TableRowId index, InternalTime endPoint) -{ - if (index <= Size()) { - endPoins_[index] = endPoint; - } -} -void Animation::UpdateFrameInfo(TableRowId index, InternalTime frameInfo) -{ - if (index <= Size()) { - frameInfos_[index] = frameInfo; - } -} -size_t Animation::Size() const -{ - return ids_.size(); -} -const std::deque& Animation::InputTimes() const -{ - return inputTimes_; -} -const std::deque& Animation::StartPoints() const -{ - return startPoints_; -} -const std::deque& Animation::EndPoints() const -{ - return endPoins_; -} -const std::deque& Animation::FrameInfos() const -{ - return frameInfos_; -} -const std::deque& Animation::Names() const -{ - return names_; -} -const std::deque& Animation::IdsData() const -{ - return ids_; -} -void Animation::Clear() -{ - inputTimes_.clear(); - startPoints_.clear(); - endPoins_.clear(); - frameInfos_.clear(); - ids_.clear(); -} -uint32_t DeviceInfo::PhysicalWidth() const -{ - return physicalWidth_; -} -uint32_t DeviceInfo::PhysicalHeight() const -{ - return physicalHeight_; -} -uint32_t DeviceInfo::PhysicalFrameRate() const -{ - return physicalFrameRate_; -} -void DeviceInfo::UpdateWidthAndHeight(const std::smatch& matcheLine) -{ - if (matcheLine.size() > DEVICEINFO_MATCH_LAST) { - uint8_t matcheIndex = 0; - physicalWidth_ = base::StrToInt(matcheLine[++matcheIndex].str()).value(); - physicalHeight_ = base::StrToInt(matcheLine[++matcheIndex].str()).value(); - } -} -void DeviceInfo::UpdateFrameRate(uint32_t frameRate) -{ - physicalFrameRate_ = frameRate; -} -void DeviceInfo::Clear() -{ - physicalWidth_ = INVALID_UINT32; - physicalHeight_ = INVALID_UINT32; - physicalFrameRate_ = INVALID_UINT32; -} -TableRowId DynamicFrame::AppendDynamicFrame(DataIndex nameId) -{ - names_.emplace_back(nameId); - ids_.emplace_back(Size()); - xs_.emplace_back(INVALID_UINT32); - ys_.emplace_back(INVALID_UINT32); - widths_.emplace_back(INVALID_UINT32); - heights_.emplace_back(INVALID_UINT32); - alphas_.emplace_back(INVALID_UINT64); - endTimes_.emplace_back(INVALID_TIME); - return ids_.size() - 1; -} -void DynamicFrame::UpdateNameIndex(TableRowId index, DataIndex nameId) -{ - if (index <= Size()) { - names_[index] = nameId; - } -} -void DynamicFrame::UpdatePosition(TableRowId index, const std::smatch& matcheLine, DataIndex alpha) -{ - if (index <= Size() && matcheLine.size() > DYNAMICFRAME_MATCH_LAST) { - uint8_t matcheIndex = 0; - xs_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); - ys_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); - widths_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); - heights_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); - alphas_[index] = alpha; - } -} -void DynamicFrame::UpdateEndTime(TableRowId index, InternalTime endTime) -{ - if (index <= Size()) { - endTimes_[index] = endTime; - } -} -size_t DynamicFrame::Size() const -{ - return ids_.size(); -} -const std::deque& DynamicFrame::IdsData() const -{ - return ids_; -} -const std::deque& DynamicFrame::Xs() const -{ - return xs_; -} -const std::deque& DynamicFrame::Ys() const -{ - return ys_; -} -const std::deque& DynamicFrame::Widths() const -{ - return widths_; -} -const std::deque& DynamicFrame::Heights() const -{ - return heights_; -} -const std::deque& DynamicFrame::Alphas() const -{ - return alphas_; -} -const std::deque& DynamicFrame::Names() const -{ - return names_; -} -const std::deque& DynamicFrame::EndTimes() const -{ - return endTimes_; -} -void DynamicFrame::Clear() -{ - xs_.clear(); - ys_.clear(); - widths_.clear(); - heights_.clear(); - alphas_.clear(); - names_.clear(); - endTimes_.clear(); - ids_.clear(); -} - -void AshMemData::AppendNewData(InternalPid ipid, - uint64_t ts, - uint32_t adj, - uint32_t fd, - DataIndex ashmemNameId, - uint64_t size, - uint64_t pss, - uint32_t ashmemId, - uint64_t time, - uint64_t refCount, - uint64_t purged, - uint32_t flag) -{ - ipids_.emplace_back(ipid); - timeStamps_.emplace_back(ts); - adjs_.emplace_back(adj); - fds_.emplace_back(fd); - ashmemNameIds_.emplace_back(ashmemNameId); - sizes_.emplace_back(size); - psss_.emplace_back(pss); - ashmemIds_.emplace_back(ashmemId); - times_.emplace_back(time); - refCounts_.emplace_back(refCount); - purgeds_.emplace_back(purged); - flags_.emplace_back(flag); - ids_.emplace_back(rowCount_); - rowCount_++; -} -void AshMemData::SetFlag(uint64_t rowId, uint32_t flag) -{ - flags_[rowId] = flag; -} -const std::deque& AshMemData::Ipids() const -{ - return ipids_; -} -const std::deque& AshMemData::Adjs() const -{ - return adjs_; -} -const std::deque& AshMemData::Fds() const -{ - return fds_; -} -const std::deque& AshMemData::AshmemNameIds() const -{ - return ashmemNameIds_; -} -const std::deque& AshMemData::Sizes() const -{ - return sizes_; -} -const std::deque& AshMemData::Psss() const -{ - return psss_; -} -const std::deque& AshMemData::AshmemIds() const -{ - return ashmemIds_; -} -const std::deque& AshMemData::Times() const -{ - return times_; -} -const std::deque& AshMemData::RefCounts() const -{ - return refCounts_; -} -const std::deque& AshMemData::Purgeds() const -{ - return purgeds_; -} -const std::deque& AshMemData::Flags() const -{ - return flags_; -} - -void DmaMemData::AppendNewData(InternalPid ipid, - uint64_t ts, - uint32_t fd, - uint64_t size, - uint32_t ino, - uint32_t expPid, - DataIndex expTaskCommId, - DataIndex bufNameId, - DataIndex expNameId, - uint32_t flag) -{ - ipids_.emplace_back(ipid); - timeStamps_.emplace_back(ts); - fds_.emplace_back(fd); - sizes_.emplace_back(size); - inos_.emplace_back(ino); - expPids_.emplace_back(expPid); - expTaskCommIds_.emplace_back(expTaskCommId); - bufNameIds_.emplace_back(bufNameId); - expNameIds_.emplace_back(expNameId); - flags_.emplace_back(flag); - ids_.emplace_back(rowCount_); - rowCount_++; -} -void DmaMemData::SetFlag(uint64_t rowId, uint32_t flag) -{ - flags_[rowId] = flag; -} -const std::deque& DmaMemData::Ipids() const -{ - return ipids_; -} -const std::deque& DmaMemData::Fds() const -{ - return fds_; -} -const std::deque& DmaMemData::Sizes() const -{ - return sizes_; -} -const std::deque& DmaMemData::Inos() const -{ - return inos_; -} -const std::deque& DmaMemData::ExpPids() const -{ - return expPids_; -} -const std::deque& DmaMemData::ExpTaskCommIds() const -{ - return expTaskCommIds_; -} -const std::deque& DmaMemData::BufNameIds() const -{ - return bufNameIds_; -} -const std::deque& DmaMemData::ExpNameIds() const -{ - return expNameIds_; -} -const std::deque& DmaMemData::Flags() const -{ - return flags_; -} - -void GpuProcessMemData::AppendNewData(uint64_t ts, - DataIndex gpuNameId, - uint64_t allGpuSize, - std::string addr, - InternalPid ipid, - InternalPid itid, - uint64_t usedGpuSize) -{ - timeStamps_.emplace_back(ts); - gpuNameIds_.emplace_back(gpuNameId); - allGpuSizes_.emplace_back(allGpuSize); - addrs_.emplace_back(addr); - ipids_.emplace_back(ipid); - itids_.emplace_back(itid); - usedGpuSizes_.emplace_back(usedGpuSize); - ids_.emplace_back(rowCount_); - rowCount_++; -} -const std::deque& GpuProcessMemData::GpuNameIds() const -{ - return gpuNameIds_; -} -const std::deque& GpuProcessMemData::AllGpuSizes() const -{ - return allGpuSizes_; -} -const std::deque& GpuProcessMemData::Addrs() const -{ - return addrs_; -} -const std::deque& GpuProcessMemData::Ipids() const -{ - return ipids_; -} -const std::deque& GpuProcessMemData::Itids() const -{ - return itids_; -} -const std::deque& GpuProcessMemData::UsedGpuSizes() const -{ - return usedGpuSizes_; -} - -void GpuWindowMemData::AppendNewData(uint64_t ts, - DataIndex windowNameId, - uint64_t windowId, - DataIndex moduleNameId, - DataIndex categoryNameId, - uint64_t size, - uint32_t count, - uint64_t purgeableSize) -{ - timeStamps_.emplace_back(ts); - windowNameIds_.emplace_back(windowNameId); - windowIds_.emplace_back(windowId); - moduleNameIds_.emplace_back(moduleNameId); - categoryNameIds_.emplace_back(categoryNameId); - sizes_.emplace_back(size); - counts_.emplace_back(count); - purgeableSizes_.emplace_back(purgeableSize); - ipids_.emplace_back(INVALID_IPID); - ids_.emplace_back(rowCount_); - rowCount_++; -} -const std::deque& GpuWindowMemData::WindowNameIds() const -{ - return windowNameIds_; -} -const std::deque& GpuWindowMemData::WindowIds() const -{ - return windowIds_; -} -const std::deque& GpuWindowMemData::ModuleNameIds() const -{ - return moduleNameIds_; -} -const std::deque& GpuWindowMemData::CategoryNameIds() const -{ - return categoryNameIds_; -} -const std::deque& GpuWindowMemData::Sizes() const -{ - return sizes_; -} -const std::deque& GpuWindowMemData::Counts() const -{ - return counts_; -} -const std::deque& GpuWindowMemData::PurgeableSizes() const -{ - return purgeableSizes_; -} -const std::deque& GpuWindowMemData::Ipids() const -{ - return ipids_; -} -void GpuWindowMemData::RevicesIpid(const std::map& windowIdToIpidMap) -{ - for (auto i = 0; i < Size(); i++) { - if (windowIdToIpidMap.count(windowNameIds_[i])) { - ipids_[i] = windowIdToIpidMap.at(windowNameIds_[i]); - } - } -} - -void CpuDumpInfo::AppendNewData(uint64_t timestamp, uint64_t size) -{ - timeStamps_.emplace_back(timestamp); - totalSizes_.emplace_back(size); - ids_.emplace_back(Size()); -} -const std::deque& CpuDumpInfo::TotalSizes() const -{ - return totalSizes_; -} - -void ProfileMemInfo::AppendNewData(uint64_t timestamp, DataIndex channelIndex, uint64_t size) -{ - timeStamps_.emplace_back(timestamp); - totalSizes_.emplace_back(size); - channelIndexs_.emplace_back(channelIndex); - ids_.emplace_back(Size()); -} -const std::deque& ProfileMemInfo::ChannelIndexs() const -{ - return channelIndexs_; -} -const std::deque& ProfileMemInfo::TotalSizes() const -{ - return totalSizes_; -} -void RSImageDumpInfo::AppendNewData(uint64_t timestamp, - uint64_t memSize, - DataIndex typeIndex, - InternalPid ipid, - DataIndex name) -{ - timeStamps_.emplace_back(timestamp); - memSizes_.emplace_back(memSize); - typeIndexs_.emplace_back(typeIndex); - ipids_.emplace_back(ipid); - surfaceNameIndexs_.emplace_back(name); - ids_.emplace_back(Size()); -} -const std::deque& RSImageDumpInfo::MemSizes() const -{ - return memSizes_; -} -const std::deque& RSImageDumpInfo::TypeIndexs() const -{ - return typeIndexs_; -} -const std::deque& RSImageDumpInfo::Ipids() const -{ - return ipids_; -} -const std::deque& RSImageDumpInfo::SurfaceNameIndexs() const -{ - return surfaceNameIndexs_; -} -} // namespace TraceStdtype -} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype.h deleted file mode 100644 index 24fc86b3a446f43658cebcf1113b9a49454f0d09..0000000000000000000000000000000000000000 --- a/trace_streamer/src/trace_data/trace_stdtype.h +++ /dev/null @@ -1,3160 +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. - */ - -#ifndef TRACE_STDTYPE_H -#define TRACE_STDTYPE_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cfg/trace_streamer_config.h" -#include "double_map.h" -#include "log.h" -#include "ts_common.h" - -namespace SysTuning { -namespace TraceStdtype { -using namespace SysTuning::TraceCfg; -using namespace SysTuning::TraceStreamer; -constexpr uint32_t ONE_MILLION_NANOSECONDS = 1000000; -constexpr uint32_t BILLION_NANOSECONDS = 1000000000; -constexpr uint8_t DYNAMICFRAME_MATCH_LAST = 5; -class BatchCacheBase { -public: - void UpdatePrevSize(size_t size) - { - prevSize = size; - } - template - void EraseElements(T& deq, changedata&... args) - { - deq.erase(deq.begin(), deq.begin() + prevSize); - EraseElements(args...); - prevSize = 0; - } - template - void EraseElements(T1& deq) - { - deq.erase(deq.begin(), deq.begin() + prevSize); - } - -public: - size_t prevSize = 0; -}; -class CacheBase { -public: - size_t Size() const - { - return std::max(timeStamps_.size(), ids_.size()); - } - const std::deque& IdsData() const - { - return ids_; - } - const std::deque& TimeStampData() const - { - return timeStamps_; - } - const std::deque& InternalTidsData() const - { - return internalTids_; - } - virtual void Clear() - { - internalTids_.clear(); - timeStamps_.clear(); - ids_.clear(); - } - -public: - std::deque internalTids_ = {}; - std::deque timeStamps_ = {}; - std::deque ids_ = {}; - uint64_t id_ = 0; -}; - -class CpuCacheBase { -public: - const std::deque& DursData() const - { - return durs_; - } - - const std::deque& CpusData() const - { - return cpus_; - } - virtual void Clear() - { - durs_.clear(); - cpus_.clear(); - } - void SetDur(uint64_t index, uint64_t dur); - -public: - std::deque durs_; - std::deque cpus_; -}; -class Thread { -public: - explicit Thread(uint32_t t) : tid_(t) {} - InternalPid internalPid_ = INVALID_UINT32; - uint32_t tid_ = 0; - DataIndex nameIndex_ = 0; - InternalTime startT_ = 0; - InternalTime endT_ = 0; - uint32_t switchCount_ = 0; - uint32_t sliceSize_ = 0; - uint32_t cpuStatesCount_ = 0; -}; - -class Process { -public: - explicit Process(uint32_t p) : pid_(p) {} - std::string cmdLine_ = ""; - InternalTime startT_ = 0; - uint32_t pid_ = 0; - uint32_t memSize_ = 0; - uint32_t threadSize_ = 0; - uint32_t sliceSize_ = 0; - uint32_t switchCount_ = 0; - int32_t threadCount_ = -1; - uint32_t cpuStatesCount_ = 0; -}; - -class ThreadStateData : public BatchCacheBase { -public: - TableRowId - AppendThreadState(InternalTime ts, InternalTime dur, InternalCpu cpu, InternalTid itid, TableRowId idState); - void SetDuration(TableRowId index, InternalTime dur); - TableRowId UpdateDuration(TableRowId index, InternalTime ts); - bool End(TableRowId index, InternalTime ts); - void UpdateState(TableRowId index, TableRowId idState); - void SetArgSetId(TableRowId index, uint32_t setId); - void UpdateDuration(TableRowId index, InternalTime ts, TableRowId idState); - void UpdateTidAndPid(TableRowId index, InternalTid tid, InternalTid pid); - TableRowId UpdateDuration(TableRowId index, InternalTime ts, InternalCpu cpu, TableRowId idState); - void SortAllRowByTs(); - void Clear() - { - timeStamps_.clear(); - durations_.clear(); - itids_.clear(); - tids_.clear(); - pids_.clear(); - states_.clear(); - cpus_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, durations_, itids_, tids_, pids_, states_, cpus_); - } - uint32_t Size() const - { - return itids_.size(); - } - - const std::deque& TimeStamsData() const - { - return timeStamps_; - } - const std::deque& DursData() const - { - return durations_; - } - const std::deque& ItidsData() const - { - return itids_; - } - const std::deque& TidsData() const - { - return tids_; - } - const std::deque& PidsData() const - { - return pids_; - } - const std::deque& StatesData() const - { - return states_; - } - const std::deque& CpusData() const - { - return cpus_; - } - const std::deque& ArgSetsData() const - { - return argSetIds_; - } - -private: - std::deque timeStamps_; - std::deque durations_; - std::deque itids_; - std::deque tids_; - std::deque pids_; - std::deque states_; - std::deque cpus_; - std::deque argSetIds_; -}; - -class SchedSlice : public CacheBase, public CpuCacheBase, public BatchCacheBase { -public: - size_t AppendSchedSlice(uint64_t ts, - uint64_t dur, - uint64_t cpu, - uint32_t internalTid, - uint64_t endState, - uint64_t priority); - void SetDuration(size_t index, uint64_t duration); - void Update(uint64_t index, uint64_t ts, uint64_t state); - void UpdateEndState(uint64_t index, uint64_t state); - void UpdateArg(uint64_t index, uint32_t argsetId); - - const std::deque& EndStatesData() const - { - return endStates_; - } - - const std::deque& PriorityData() const - { - return priority_; - } - - const std::deque& ArgSetData() const - { - return argSets_; - } - const std::deque& TsEndData() const - { - return tsEnds_; - } - const std::deque& InternalPidsData() const - { - return internalPids_; - } - void ReviseInternalPid(uint32_t row, InternalPid ipid) - { - if (row < internalPids_.size()) { - internalPids_[row] = ipid; - } - } - void Clear() override - { - CacheBase::Clear(); - CpuCacheBase::Clear(); - endStates_.clear(); - priority_.clear(); - internalPids_.clear(); - tsEnds_.clear(); - } - void ClearPrevData() - { - EraseElements(internalTids_, timeStamps_, durs_, cpus_, endStates_, priority_, internalPids_, tsEnds_); - } - -private: - std::deque internalPids_ = {}; - std::deque tsEnds_ = {}; - std::deque endStates_ = {}; - std::deque priority_ = {}; - std::deque argSets_ = {}; -}; - -class CallStack : public CacheBase, public CpuCacheBase, public BatchCacheBase { -public: - size_t AppendInternalAsyncSlice(uint64_t startT, - uint64_t durationNs, - InternalTid internalTid, - DataIndex cat, - uint16_t nameIdentify, - DataIndex name, - uint8_t depth, - uint64_t cookid, - const std::optional& parentId); - size_t AppendInternalSlice(uint64_t startT, - uint64_t durationNs, - InternalTid internalTid, - DataIndex cat, - uint16_t nameIdentify, - DataIndex name, - uint8_t depth, - const std::optional& parentId); - void SetDistributeInfo(size_t index, - const std::string& chainId, - const std::string& spanId, - const std::string& parentSpanId, - const std::string& flag, - const std::string& args); - void AppendDistributeInfo(const std::string& chainId, - const std::string& spanId, - const std::string& parentSpanId, - const std::string& flag, - const std::string& args); - void AppendDistributeInfo(); - void SetDuration(size_t index, uint64_t timeStamp); - void SetDurationWithFlag(size_t index, uint64_t timeStamp); - void SetFlag(size_t index, uint8_t flag); - void SetDurationEx(size_t index, uint32_t dur); - void SetIrqDurAndArg(size_t index, uint64_t timeStamp, uint32_t argSetId); - void SetTimeStamp(size_t index, uint64_t timeStamp); - void SetDepth(size_t index, uint8_t depth); - void SetArgSetId(size_t index, uint32_t argSetId); - void Clear() override - { - CacheBase::Clear(); - CpuCacheBase::Clear(); - cats_.clear(); - cookies_.clear(); - callIds_.clear(); - names_.clear(); - depths_.clear(); - chainIds_.clear(); - spanIds_.clear(); - parentSpanIds_.clear(); - flags_.clear(); - args_.clear(); - argSet_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, durs_, cats_, cookies_, callIds_, names_, depths_, chainIds_, spanIds_, - parentSpanIds_, flags_, args_, argSet_); - } - const std::deque>& ParentIdData() const; - const std::deque& CatsData() const; - const std::deque& NamesData() const; - const std::deque& Depths() const; - const std::deque& Cookies() const; - const std::deque& CallIds() const; - const std::deque& IdentifysData() const; - const std::deque& ChainIds() const; - const std::deque& SpanIds() const; - const std::deque& ParentSpanIds() const; - const std::deque& Flags() const; - const std::deque& ArgsData() const; - const std::deque& ArgSetIdsData() const; - -private: - void AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid); - void AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, std::optional parentId); - -private: - std::deque> parentIds_; - std::deque cats_ = {}; - std::deque cookies_ = {}; - std::deque callIds_ = {}; - std::deque identifys_ = {}; - std::deque names_ = {}; - std::deque depths_ = {}; - - std::deque chainIds_ = {}; - std::deque spanIds_ = {}; - std::deque parentSpanIds_ = {}; - std::deque flags_ = {}; - std::deque args_ = {}; - std::deque argSet_ = {}; -}; - -class Filter : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewFilterData(std::string type, std::string name, uint64_t sourceArgSetId); - const std::deque& NameData() const - { - return nameDeque_; - } - const std::deque& TypeData() const - { - return typeDeque_; - } - const std::deque& SourceArgSetIdData() const - { - return sourceArgSetId_; - } - void Clear() override - { - CacheBase::Clear(); - nameDeque_.clear(); - typeDeque_.clear(); - sourceArgSetId_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, nameDeque_, typeDeque_, sourceArgSetId_); - } - -private: - std::deque nameDeque_ = {}; - std::deque typeDeque_ = {}; - std::deque sourceArgSetId_ = {}; -}; - -class Measure : public CacheBase, public BatchCacheBase { -public: - size_t AppendMeasureData(uint32_t type, uint64_t timeStamp, int64_t value, uint32_t filterId); - const std::deque& TypeData() const - { - return typeDeque_; - } - const std::deque& ValuesData() const - { - return valuesDeque_; - } - const std::deque& DursData() const - { - return durDeque_; - } - void SetDur(uint32_t row, uint64_t timeStamp); - const std::deque& FilterIdData() const - { - return filterIdDeque_; - } - void Clear() override - { - CacheBase::Clear(); - typeDeque_.clear(); - durDeque_.clear(); - valuesDeque_.clear(); - filterIdDeque_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, typeDeque_, durDeque_, valuesDeque_, filterIdDeque_); - } - -private: - std::deque typeDeque_ = {}; - std::deque durDeque_ = {}; - std::deque valuesDeque_ = {}; - std::deque filterIdDeque_ = {}; -}; - -class Raw : public CacheBase, public BatchCacheBase { -public: - size_t AppendRawData(uint32_t id, uint64_t timeStamp, uint32_t name, uint32_t cpu, uint32_t internalTid); - const std::deque& NameData() const - { - return nameDeque_; - } - const std::deque& CpuData() const - { - return cpuDeque_; - } - void Clear() override - { - CacheBase::Clear(); - nameDeque_.clear(); - cpuDeque_.clear(); - } - void ClearPrevData() - { - EraseElements(internalTids_, timeStamps_, ids_, nameDeque_, cpuDeque_); - } - -private: - std::deque nameDeque_ = {}; - std::deque cpuDeque_ = {}; -}; - -class ThreadMeasureFilter : public BatchCacheBase { -public: - size_t AppendNewFilter(uint64_t filterId, uint32_t nameIndex, uint64_t internalTid); - size_t Size() const - { - return filterId_.size(); - } - const std::deque& FilterIdData() const - { - return filterId_; - } - const std::deque& InternalTidData() const - { - return internalTids_; - } - const std::deque& NameIndexData() const - { - return nameIndex_; - } - void Clear() - { - filterId_.clear(); - internalTids_.clear(); - nameIndex_.clear(); - } - void ClearPrevData() - { - EraseElements(filterId_, internalTids_, nameIndex_); - } - -private: - std::deque filterId_ = {}; - std::deque internalTids_ = {}; - std::deque nameIndex_ = {}; -}; - -class CpuMeasureFilter : public CacheBase, public BatchCacheBase { -public: - inline size_t AppendNewFilter(uint64_t filterId, DataIndex name, uint32_t cpu) - { - ids_.emplace_back(filterId); - cpu_.emplace_back(cpu); - name_.emplace_back(name); - return Size() - 1; - } - - const std::deque& CpuData() const - { - return cpu_; - } - - const std::deque& NameData() const - { - return name_; - } - void Clear() override - { - CacheBase::Clear(); - cpu_.clear(); - name_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, cpu_, name_); - } - -private: - std::deque cpu_ = {}; - std::deque name_ = {}; -}; - -class Instants : public CacheBase, public BatchCacheBase { -public: - size_t AppendInstantEventData(uint64_t timeStamp, - DataIndex nameIndex, - int64_t internalTid, - int64_t wakeupFromInternalPid); - - const std::deque& NameIndexsData() const - { - return NameIndexs_; - } - const std::deque& WakeupFromPidsData() const - { - return wakeupFromInternalPids_; - } - void Clear() override - { - CacheBase::Clear(); - NameIndexs_.clear(); - wakeupFromInternalPids_.clear(); - } - void ClearPrevData() - { - EraseElements(internalTids_, timeStamps_, NameIndexs_, wakeupFromInternalPids_); - } - -private: - std::deque NameIndexs_; - std::deque wakeupFromInternalPids_; -}; - -class ProcessMeasureFilter : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewFilter(uint64_t id, DataIndex name, uint32_t internalPid); - - const std::deque& UpidsData() const - { - return internalPids_; - } - - const std::deque& NamesData() const - { - return names_; - } - void Clear() override - { - CacheBase::Clear(); - internalPids_.clear(); - names_.clear(); - } - void ClearPrevData() - { - EraseElements(internalTids_, ids_, internalPids_, names_); - } - -private: - std::deque internalPids_ = {}; - std::deque names_ = {}; -}; -class ClockEventData : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewFilter(uint64_t id, DataIndex type, DataIndex name, uint64_t cpu); - - const std::deque& CpusData() const - { - return cpus_; - } - - const std::deque& NamesData() const - { - return names_; - } - const std::deque& TypesData() const - { - return types_; - } - void Clear() override - { - CacheBase::Clear(); - cpus_.clear(); - names_.clear(); - types_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, cpus_, names_, types_); - } - -private: - std::deque cpus_ = {}; // in clock_set_rate event, it save cpu - std::deque names_ = {}; - std::deque types_ = {}; -}; -class ClkEventData : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewFilter(uint64_t id, uint64_t rate, DataIndex name, uint64_t cpu); - - const std::deque& NamesData() const - { - return names_; - } - const std::deque& RatesData() const - { - return rates_; - } - const std::deque& CpusData() const - { - return cpus_; - } - void Clear() override - { - CacheBase::Clear(); - names_.clear(); - rates_.clear(); - cpus_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, cpus_, names_, rates_); - } - -private: - std::deque names_; - std::deque rates_; - std::deque cpus_; -}; -class SysCall : public CacheBase, public BatchCacheBase { -public: - size_t AppendSysCallData(int64_t sysCallNum, DataIndex type, uint32_t ipid, uint64_t timeStamp, int64_t ret); - const std::deque& SysCallsData() const - { - return sysCallNums_; - } - const std::deque& TypesData() const - { - return types_; - } - const std::deque& IpidsData() const - { - return ipids_; - } - const std::deque& RetsData() const - { - return rets_; - } - void Clear() override - { - CacheBase::Clear(); - sysCallNums_.clear(); - types_.clear(); - ipids_.clear(); - rets_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, sysCallNums_, types_, ipids_, rets_); - } - -private: - std::deque sysCallNums_ = {}; - std::deque types_ = {}; - std::deque ipids_ = {}; - std::deque rets_ = {}; -}; -class ArgSet : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewArg(DataIndex nameId, BaseDataType dataType, int64_t value, size_t argSet); - const std::deque& DataTypes() const; - const std::deque& ValuesData() const; - const std::deque& ArgsData() const; - const std::deque& NamesData() const; - - void Clear() override - { - CacheBase::Clear(); - names_.clear(); - dataTypes_.clear(); - values_.clear(); - argset_.clear(); - } - void ClearPrevData() - { - EraseElements(names_, dataTypes_, values_, argset_); - } - -private: - std::deque names_ = {}; - std::deque dataTypes_ = {}; - std::deque values_ = {}; - std::deque argset_ = {}; -}; -class SysMeasureFilter : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewFilter(uint64_t filterId, DataIndex type, DataIndex nameId); - const std::deque& NamesData() const; - const std::deque& TypesData() const; - void Clear() override - { - CacheBase::Clear(); - types_.clear(); - names_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, types_, names_); - } - -private: - std::deque types_ = {}; - std::deque names_ = {}; -}; -class DataType : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewDataType(BaseDataType dataType, DataIndex dataDescIndex); - const std::deque& DataTypes() const; - const std::deque& DataDesc() const; - void Clear() override - { - CacheBase::Clear(); - dataTypes_.clear(); - descs_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, dataTypes_, descs_); - } - -private: - std::deque dataTypes_ = {}; - std::deque descs_ = {}; -}; -class LogInfo : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewLogInfo(uint64_t seq, - uint64_t timeStamp, - uint32_t pid, - uint32_t tid, - DataIndex level, - DataIndex tag, - DataIndex context, - uint64_t originTs); - const std::deque& HilogLineSeqs() const; - const std::deque& Pids() const; - const std::deque& Tids() const; - const std::deque& Levels() const; - const std::deque& Tags() const; - const std::deque& Contexts() const; - const std::deque& OriginTimeStamData() const; - void Clear() override - { - CacheBase::Clear(); - hilogLineSeqs_.clear(); - pids_.clear(); - levels_.clear(); - tags_.clear(); - contexts_.clear(); - originTs_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, hilogLineSeqs_, pids_, tids_, levels_, tags_, contexts_, originTs_); - } - -private: - std::deque hilogLineSeqs_ = {}; - std::deque pids_ = {}; - std::deque tids_ = {}; - std::deque levels_ = {}; - std::deque tags_ = {}; - std::deque contexts_ = {}; - std::deque originTs_ = {}; -}; -class NativeHookSampleBase : public CacheBase, public BatchCacheBase { -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(); - } - -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, - uint32_t itid, - std::string eventType, - DataIndex subType, - uint64_t timeStamp, - uint64_t endTimeStamp, - uint64_t duration, - uint64_t addr, - int64_t memSize); - void UpdateCallChainId(size_t row, uint32_t callChainId); - void UpdateEndTimeStampAndDuration(size_t row, uint64_t endTimeStamp); - void UpdateCurrentSizeDur(size_t row, uint64_t timeStamp); - void UpdateMemMapSubType(uint64_t row, uint64_t tagId); - const std::deque& EventTypes() const; - const std::deque& SubTypes() const; - const std::deque& EndTimeStamps() const; - const std::deque& Durations() const; - const std::deque& Addrs() const; - const std::deque& MemSizes() const; - const std::deque& AllMemSizes() const; - const std::deque& CurrentSizeDurs() const; - void Clear() override - { - NativeHookSampleBase::Clear(); - eventTypes_.clear(); - subTypes_.clear(); - endTimeStamps_.clear(); - durations_.clear(); - addrs_.clear(); - memSizes_.clear(); - allMemSizes_.clear(); - currentSizeDurs_.clear(); - } - void ClearPrevData() - { - auto clearSize = prevSize; - EraseElements(internalTids_, timeStamps_, ids_, callChainIds_, ipids_, lastCallerPathIndexs_, lastSymbolIndexs_, - eventTypes_, subTypes_, endTimeStamps_, durations_, addrs_, memSizes_, allMemSizes_, - currentSizeDurs_); - for (auto itor = addrToAllocEventRow_.begin(); itor != addrToAllocEventRow_.end();) { - if (itor->second < clearSize) { - itor = addrToAllocEventRow_.erase(itor); - } else { - itor->second -= clearSize; - itor++; - } - } - for (auto itor = addrToMmapEventRow_.begin(); itor != addrToMmapEventRow_.end();) { - if (itor->second < clearSize) { - itor = addrToMmapEventRow_.erase(itor); - } else { - itor->second -= clearSize; - itor++; - } - } - lastMallocEventRaw_ -= clearSize; - lastMmapEventRaw_ -= clearSize; - } - std::unordered_map* GetAddrToAllocEventRow() - { - return &addrToAllocEventRow_; - } - std::unordered_map* GetAddrToMmapEventRow() - { - return &addrToMmapEventRow_; - } - uint64_t& GetLastMallocEventRaw() - { - return lastMallocEventRaw_; - } - uint64_t& GetLastMmapEventRaw() - { - return lastMmapEventRaw_; - } - -private: - std::deque eventTypes_ = {}; - std::deque subTypes_ = {}; - std::deque endTimeStamps_ = {}; - std::deque durations_ = {}; - std::deque addrs_ = {}; - std::deque memSizes_ = {}; - std::deque allMemSizes_ = {}; - std::deque currentSizeDurs_ = {}; - int64_t countHeapSizes_ = 0; - int64_t countMmapSizes_ = 0; - const std::string ALLOC_EVET = "AllocEvent"; - const std::string FREE_EVENT = "FreeEvent"; - const std::string MMAP_EVENT = "MmapEvent"; - const std::string MUNMAP_EVENT = "MunmapEvent"; - std::unordered_map addrToAllocEventRow_ = {}; - std::unordered_map addrToMmapEventRow_ = {}; - uint64_t lastMallocEventRaw_ = INVALID_UINT64; - uint64_t lastMmapEventRaw_ = INVALID_UINT64; -}; - -class NativeHookFrame : public BatchCacheBase { -public: - size_t AppendNewNativeHookFrame(uint32_t callChainId, - uint16_t depth, - uint64_t ip, - DataIndex symbolName, - DataIndex filePath, - uint64_t offset, - uint64_t symbolOffset); - size_t AppendNewNativeHookFrame(uint32_t callChainId, - uint16_t depth, - uint64_t ip, - DataIndex symbolName, - DataIndex filePath, - uint64_t offset, - uint64_t symbolOffset, - const std::string& vaddr); - void UpdateFrameInfo(size_t row, - DataIndex symbolIndex, - DataIndex filePathIndex, - uint64_t offset, - uint64_t symbolOffset); - void UpdateSymbolIdToNameMap(uint64_t originSymbolId, uint64_t symbolId); - void UpdateSymbolId(); - void UpdateSymbolId(size_t index, DataIndex symbolId); - void UpdateFileId(std::map& filePathIdToFilePathName); - void UpdateVaddrs(std::deque& vaddrs); - const std::deque& CallChainIds() const; - const std::deque& Depths() const; - const std::deque& Ips() const; - const std::deque& SymbolNames() const; - const std::deque& FilePaths() const; - const std::deque& Offsets() const; - const std::deque& SymbolOffsets() const; - const std::deque& Vaddrs() const; - size_t Size() const - { - return callChainIds_.size(); - } - void Clear() - { - callChainIds_.clear(); - depths_.clear(); - ips_.clear(); - symbolNames_.clear(); - filePaths_.clear(); - offsets_.clear(); - symbolOffsets_.clear(); - vaddrs_.clear(); - } - void ClearPrevData() - { - EraseElements(callChainIds_, depths_, ips_, symbolNames_, filePaths_, offsets_, symbolOffsets_, vaddrs_); - } - -private: - std::deque callChainIds_ = {}; - std::deque depths_ = {}; - std::deque ips_ = {}; - std::deque symbolNames_ = {}; - std::deque filePaths_ = {}; - std::deque offsets_ = {}; - std::deque symbolOffsets_ = {}; - std::deque vaddrs_ = {}; - std::map symbolIdToSymbolName_ = {}; -}; - -class NativeHookStatistic : public NativeHookSampleBase { -public: - size_t AppendNewNativeHookStatistic(uint32_t ipid, - uint64_t timeStamp, - uint32_t callChainId, - uint32_t memoryType, - DataIndex subMemType, - uint64_t applyCount, - uint64_t releaseCount, - uint64_t applySize, - uint64_t releaseSize); - const std::deque& MemoryTypes() const; - const std::deque& MemorySubTypes() const; - const std::deque& ApplyCounts() const; - const std::deque& ReleaseCounts() const; - const std::deque& ApplySizes() const; - const std::deque& ReleaseSizes() const; - void Clear() override - { - NativeHookSampleBase::Clear(); - memoryTypes_.clear(); - applyCounts_.clear(); - releaseCounts_.clear(); - applySizes_.clear(); - releaseSizes_.clear(); - } - void ClearPrevData() - { - EraseElements(internalTids_, timeStamps_, ids_, callChainIds_, ipids_, lastCallerPathIndexs_, lastSymbolIndexs_, - memoryTypes_, applyCounts_, releaseCounts_, applySizes_, releaseSizes_); - } - -private: - std::deque memoryTypes_ = {}; - std::deque memSubTypes_ = {}; - std::deque applyCounts_ = {}; - std::deque releaseCounts_ = {}; - std::deque applySizes_ = {}; - std::deque releaseSizes_ = {}; -}; - -class Hidump : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewHidumpInfo(uint64_t timeStamp, uint32_t fps); - const std::deque& Fpss() const; - void Clear() - { - CacheBase::Clear(); - fpss_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, fpss_); - } - -private: - std::deque fpss_ = {}; -}; - -class PerfCallChain : public CacheBase { -public: - size_t AppendNewPerfCallChain(uint32_t callChainId, - uint32_t depth, - uint64_t ip, - uint64_t vaddrInFile, - uint64_t fileId, - uint64_t symbolId); - 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; - const std::deque& Names() const; - void SetName(uint64_t index, DataIndex name); - void UpdateSymbolId(size_t index, DataIndex symbolId); - void Clear() override; - -private: - std::deque callChainIds_ = {}; - std::deque depths_ = {}; - std::deque ips_ = {}; - std::deque vaddrInFiles_ = {}; - std::deque fileIds_ = {}; - std::deque symbolIds_ = {}; - std::deque names_ = {}; -}; - -class PerfFiles : public CacheBase { -public: - size_t AppendNewPerfFiles(uint64_t fileIds, uint32_t serial, DataIndex symbols, DataIndex filePath); - const std::deque& FileIds() const; - const std::deque& Symbols() const; - const std::deque& FilePaths() const; - const std::deque& Serials() const; - void Clear() override; - -private: - std::deque fileIds_ = {}; - std::deque serials_ = {}; - std::deque symbols_ = {}; - std::deque filePaths_ = {}; -}; - -class PerfSample : public CacheBase { -public: - size_t AppendNewPerfSample(uint32_t sampleId, - uint64_t timeStamp, - uint32_t tid, - uint64_t eventCount, - uint64_t eventTypeId, - uint64_t timestampTrace, - uint64_t cpuId, - uint64_t threadState); - const std::deque& SampleIds() const; - const std::deque& Tids() const; - const std::deque& EventCounts() const; - const std::deque& EventTypeIds() const; - const std::deque& TimestampTraces() const; - const std::deque& CpuIds() const; - const std::deque& ThreadStates() const; - void Clear() override; - -private: - std::deque sampleIds_ = {}; - std::deque tids_ = {}; - std::deque eventCounts_ = {}; - std::deque eventTypeIds_ = {}; - std::deque timestampTraces_ = {}; - std::deque cpuIds_ = {}; - std::deque threadStates_ = {}; -}; - -class PerfThread : public CacheBase { -public: - size_t AppendNewPerfThread(uint32_t pid, uint32_t tid, DataIndex threadName); - const std::deque& Pids() const; - const std::deque& Tids() const; - const std::deque& ThreadNames() const; - void Clear() override; - -private: - std::deque tids_ = {}; - std::deque pids_ = {}; - std::deque threadNames_ = {}; -}; - -class PerfReport : public CacheBase { -public: - size_t AppendNewPerfReport(DataIndex type, DataIndex value); - const std::deque& Types() const; - const std::deque& Values() const; - -private: - std::deque types_ = {}; - std::deque values_ = {}; -}; -class StatAndInfo { -public: - StatAndInfo(); - ~StatAndInfo() = default; - void IncreaseStat(SupportedTraceEventType eventType, StatType type); - const uint32_t& GetValue(SupportedTraceEventType eventType, StatType type) const; - const std::string& GetEvent(SupportedTraceEventType eventType) const; - const std::string& GetStat(StatType type) const; - const std::string& GetSeverityDesc(SupportedTraceEventType eventType, StatType type) const; - const StatSeverityLevel& GetSeverity(SupportedTraceEventType eventType, StatType type) const; - std::map clockid2ClockNameMap_ = {}; - -private: - uint32_t statCount_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; - std::string event_[TRACE_EVENT_MAX]; - std::string stat_[STAT_EVENT_MAX]; - std::string statSeverityDesc_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; - StatSeverityLevel statSeverity_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; - TraceStreamerConfig config_{}; -#ifdef SUPPORTTHREAD - SpinLock spinlock_; -#endif -}; -class SymbolsData : public BatchCacheBase { -public: - SymbolsData() = default; - ~SymbolsData() = default; - uint64_t Size() const; - void InsertSymbol(const DataIndex& name, const uint64_t& addr); - const std::deque& GetConstFuncNames() const; - const std::deque& GetConstAddrs() const; - void Clear() - { - addrs_.clear(); - funcName_.clear(); - } - -private: - std::deque addrs_ = {}; - std::deque funcName_ = {}; -}; -class DiskIOData : public CacheBase, public BatchCacheBase { -public: - DiskIOData() = default; - ~DiskIOData() = default; - void AppendNewData(uint64_t ts, - uint64_t dur, - uint64_t rd, - uint64_t wr, - uint64_t rdPerSec, - uint64_t wrPerSec, - double rdCountPerSec, - double wrCountPerSec, - uint64_t rdCount, - uint64_t wrCount); - const std::deque& Durs() const; - const std::deque& RdDatas() const; - const std::deque& WrDatas() const; - const std::deque& RdSpeedDatas() const; - const std::deque& WrSpeedDatas() const; - const std::deque& RdCountPerSecDatas() const; - const std::deque& WrCountPerSecDatas() const; - const std::deque& RdCountDatas() const; - const std::deque& WrCountDatas() const; - void Clear() - { - CacheBase::Clear(); - durs_.clear(); - rdDatas_.clear(); - wrDatas_.clear(); - wrPerSec_.clear(); - rdPerSec_.clear(); - wrCountPerSec_.clear(); - rdCountPerSec_.clear(); - rdCountDatas_.clear(); - wrCountDatas_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, durs_, rdDatas_, wrDatas_, wrPerSec_, rdPerSec_, wrCountPerSec_, rdCountPerSec_, - rdCountDatas_, wrCountDatas_); - } - -private: - std::deque durs_ = {}; - std::deque rdDatas_ = {}; - std::deque wrDatas_ = {}; - std::deque wrPerSec_ = {}; - std::deque rdPerSec_ = {}; - std::deque wrCountPerSec_ = {}; - std::deque rdCountPerSec_ = {}; - std::deque rdCountDatas_ = {}; - std::deque wrCountDatas_ = {}; -}; -class MetaData { -public: - MetaData(); - ~MetaData() = default; - void SetTraceType(const std::string& traceType); - void SetSourceFileName(const std::string& fileName); - void SetOutputFileName(const std::string& fileName); - void SetParserToolVersion(const std::string& version); - void SetParserToolPublishDateTime(const std::string& datetime); - void SetTraceDataSize(uint64_t dataSize); - void SetTraceDuration(uint64_t dur); - const std::string& Value(uint64_t row) const; - const std::string& Name(uint64_t row) const; - void Clear() - { - columnNames_.clear(); - values_.clear(); - } - -private: - const std::string METADATA_ITEM_DATASIZE_COLNAME = "datasize"; - const std::string METADATA_ITEM_PARSETOOL_NAME_COLNAME = "parse_tool"; - const std::string METADATA_ITEM_PARSERTOOL_VERSION_COLNAME = "tool_version"; - const std::string METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME_COLNAME = "tool_publish_time"; - const std::string METADATA_ITEM_SOURCE_FILENAME_COLNAME = "source_name"; - const std::string METADATA_ITEM_OUTPUT_FILENAME_COLNAME = "output_name"; - const std::string METADATA_ITEM_PARSERTIME_COLNAME = "runtime"; - const std::string METADATA_ITEM_TRACE_DURATION_COLNAME = "trace_duration"; - const std::string METADATA_ITEM_SOURCE_DATETYPE_COLNAME = "source_type"; - - std::deque columnNames_ = {}; - std::deque values_ = {}; -}; -class DataDict : public BatchCacheBase { -public: - size_t Size() const - { - return dataDict_.size(); - } - DataIndex GetStringIndex(std::string_view str); - DataIndex GetStringIndexNoWrite(std::string_view str) const; - const std::string& GetDataFromDict(DataIndex id) const - { - TS_ASSERT(id < dataDict_.size()); - return dataDict_[id]; - } - void Finish(); - void Clear() - { - dataDict_.clear(); - } - -public: - std::deque dataDict_; - std::unordered_map dataDictInnerMap_; - -private: - std::hash hashFun; - std::mutex mutex_; - const int8_t SPASCII_START = 0; - const int8_t SPASCII_END = 32; -}; -class NetDetailData : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewNetData(uint64_t newTimeStamp, - uint64_t tx, - uint64_t rx, - uint64_t dur, - double rxSpeed, - double txSpeed, - uint64_t packetIn, - double packetInSec, - uint64_t packetOut, - double packetOutSec, - const std::string& netType); - const std::deque& Durs() const; - const std::deque& RxSpeed() const; - const std::deque& TxSpeed() const; - const std::deque& NetTypes() const; - const std::deque& RxDatas() const; - const std::deque& TxDatas() const; - const std::deque& PacketIn() const; - const std::deque& PacketInSec() const; - const std::deque& PacketOut() const; - const std::deque& PacketOutSec() const; - void Clear() override - { - CacheBase::Clear(); - durs_.clear(); - rxSpeeds_.clear(); - txSpeeds_.clear(); - netTypes_.clear(); - packetIn_.clear(); - packetInSec_.clear(); - packetOut_.clear(); - packetOutSec_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, durs_, rxSpeeds_, txSpeeds_, netTypes_, packetIn_, packetInSec_, packetOut_, - packetOutSec_); - } - -private: - std::deque rxs_ = {}; - std::deque txs_ = {}; - std::deque durs_ = {}; - std::deque rxSpeeds_ = {}; - std::deque txSpeeds_ = {}; - std::deque packetIn_ = {}; - std::deque packetInSec_ = {}; - std::deque packetOut_ = {}; - std::deque packetOutSec_ = {}; - std::deque netTypes_ = {}; -}; -class LiveProcessDetailData : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewData(uint64_t newTimeStamp, - uint64_t dur, - int32_t processID, - std::string processName, - int32_t parentProcessID, - int32_t uid, - std::string userName, - double cpuUsage, - int32_t pssInfo, - uint64_t cpuTime, - int32_t threads, - int64_t diskWrites, - int64_t diskReads); - const std::deque& Durs() const; - const std::deque& ProcessID() const; - const std::deque& ProcessName() const; - const std::deque& ParentProcessID() const; - const std::deque& Uid() const; - const std::deque& UserName() const; - const std::deque& CpuUsage() const; - const std::deque& PssInfo() const; - const std::deque& Threads() const; - const std::deque& DiskWrites() const; - const std::deque& DiskReads() const; - const std::deque& CpuTimes() const; - void Clear() override - { - CacheBase::Clear(); - durs_.clear(); - processID_.clear(); - processName_.clear(); - parentProcessID_.clear(); - uid_.clear(); - userName_.clear(); - cpuUsage_.clear(); - pssInfo_.clear(); - threads_.clear(); - diskWrites_.clear(); - diskReads_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, durs_, processID_, processName_, parentProcessID_, uid_, userName_, cpuUsage_, - pssInfo_, threads_, diskWrites_, diskReads_); - } - -private: - std::deque durs_ = {}; - std::deque processID_ = {}; - std::deque processName_ = {}; - std::deque parentProcessID_ = {}; - std::deque uid_ = {}; - std::deque userName_ = {}; - std::deque cpuUsage_ = {}; - std::deque pssInfo_ = {}; - std::deque threads_ = {}; - std::deque diskWrites_ = {}; - std::deque diskReads_ = {}; - std::deque cpuTimes_ = {}; -}; -class CpuUsageDetailData : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewData(uint64_t newTimeStamp, - uint64_t dur, - double totalLoad, - double userLoad, - double systemLoad, - int64_t threads); - const std::deque& Durs() const; - const std::deque& TotalLoad() const; - const std::deque& UserLoad() const; - const std::deque& SystemLoad() const; - const std::deque& Threads() const; - void Clear() override - { - CacheBase::Clear(); - durs_.clear(); - totalLoad_.clear(); - userLoad_.clear(); - systemLoad_.clear(); - threads_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, durs_, totalLoad_, userLoad_, systemLoad_, threads_); - } - -private: - std::deque durs_ = {}; - std::deque totalLoad_ = {}; - std::deque userLoad_ = {}; - std::deque systemLoad_ = {}; - std::deque threads_ = {}; -}; -class FileSystemSample : public CacheBase { -public: - size_t AppendNewData(uint32_t callChainId, - uint16_t type, - uint32_t ipid, - uint32_t itid, - uint64_t startTs, - uint64_t endTs, - uint64_t dur, - DataIndex returnValue, - DataIndex errorCode, - size_t size, - int32_t fd, - DataIndex fileId, - DataIndex firstArgument, - DataIndex secondArgument, - DataIndex thirdArgument, - DataIndex fourthArgument); - const std::deque& CallChainIds() const; - const std::deque& Types() const; - const std::deque& Ipids() const; - const std::deque& Itids() const; - const std::deque& StartTs() const; - const std::deque& EndTs() const; - const std::deque& Durs() const; - const std::deque& ReturnValues() const; - const std::deque& ErrorCodes() const; - const std::deque& Fds() const; - const std::deque& FileIds() const; - const std::deque& Sizes() const; - const std::deque& FirstArguments() const; - const std::deque& SecondArguments() const; - const std::deque& ThirdArguments() const; - const std::deque& FourthArguments() const; - void Clear() override - { - CacheBase::Clear(); - callChainIds_.clear(); - types_.clear(); - ipids_.clear(); - itids_.clear(); - startTs_.clear(); - endTs_.clear(); - durs_.clear(); - returnValues_.clear(); - errorCodes_.clear(); - fds_.clear(); - Sizes_.clear(); - firstArguments_.clear(); - secondArguments_.clear(); - thirdArguments_.clear(); - fourthArguments_.clear(); - } - -private: - std::deque callChainIds_ = {}; - std::deque types_ = {}; - std::deque ipids_ = {}; - std::deque itids_ = {}; - std::deque startTs_ = {}; - std::deque endTs_ = {}; - std::deque durs_ = {}; - std::deque returnValues_ = {}; - std::deque errorCodes_ = {}; - std::deque fds_ = {}; - std::deque fileIds_ = {}; - std::deque Sizes_ = {}; - std::deque firstArguments_ = {}; - std::deque secondArguments_ = {}; - std::deque thirdArguments_ = {}; - std::deque fourthArguments_ = {}; -}; -class EbpfCallStackData : public CacheBase { -public: - size_t AppendNewData(uint32_t callChainId, - uint32_t depth, - DataIndex ip, - DataIndex symbolId, - DataIndex filePathId, - uint64_t vaddr); - void UpdateEbpfSymbolInfo(size_t row, DataIndex symbolId); - const std::deque& CallChainIds() const; - const std::deque& Depths() const; - const std::deque& Ips() const; - const std::deque& SymbolIds() const; - const std::deque& FilePathIds() const; - const std::deque& Vaddrs() const; - void Clear() override - { - CacheBase::Clear(); - callChainIds_.clear(); - depths_.clear(); - symbolIds_.clear(); - filePathIds_.clear(); - vaddrs_.clear(); - } - -private: - std::deque callChainIds_ = {}; - std::deque depths_ = {}; - std::deque ips_ = {}; - std::deque symbolIds_ = {}; - std::deque filePathIds_ = {}; - std::deque vaddrs_ = {}; -}; -class PagedMemorySampleData : public CacheBase { -public: - size_t AppendNewData(uint32_t callChainId, - uint16_t type, - uint32_t ipid, - uint64_t startTs, - uint64_t endTs, - uint64_t dur, - size_t size, - DataIndex addr, - uint32_t itid); - const std::deque& CallChainIds() const; - const std::deque& Types() const; - const std::deque& Ipids() const; - const std::deque& StartTs() const; - const std::deque& EndTs() const; - const std::deque& Durs() const; - const std::deque& Sizes() const; - const std::deque& Addr() const; - const std::deque& Itids() const; - void Clear() override - { - CacheBase::Clear(); - callChainIds_.clear(); - types_.clear(); - ipids_.clear(); - startTs_.clear(); - endTs_.clear(); - durs_.clear(); - Sizes_.clear(); - addrs_.clear(); - itids_.clear(); - } - -private: - std::deque callChainIds_ = {}; - std::deque types_ = {}; - std::deque ipids_ = {}; - std::deque startTs_ = {}; - std::deque endTs_ = {}; - std::deque durs_ = {}; - std::deque Sizes_ = {}; - std::deque addrs_ = {}; - std::deque itids_ = {}; -}; -#if WITH_EBPF_HELP -class EbpfProcessMaps : public CacheBase { -public: - size_t AppendNewData(uint64_t start, - uint64_t end, - uint32_t offset, - uint32_t pid, - uint32_t fileNameLen, - uint64_t fileNameIndex); - const std::deque& Starts() const; - const std::deque& Ends() const; - const std::deque& Offsets() const; - const std::deque& Pids() const; - const std::deque& FileNameLens() const; - const std::deque& FileNameIndexs() const; - void Clear() override - { - CacheBase::Clear(); - starts_.clear(); - ends_.clear(); - offsets_.clear(); - pids_.clear(); - fileNameLens_.clear(); - fileNameIndexs_.clear(); - } - -private: - std::deque starts_ = {}; - std::deque ends_ = {}; - std::deque offsets_ = {}; - std::deque pids_ = {}; - std::deque fileNameLens_ = {}; - std::deque fileNameIndexs_ = {}; -}; - -class EbpfElf : public CacheBase { -public: - size_t AppendNewData(uint64_t elfId, - uint64_t textVaddr, - uint32_t textOffset, - uint32_t strTabLen, - uint32_t symTabLen, - uint32_t fileNameLen, - uint32_t symEntLen, - uint64_t fileNameIndex); - const std::deque& ElfIds() const; - const std::deque& TextVaddrs() const; - const std::deque& TextOffsets() const; - const std::deque& StrTabLens() const; - const std::deque& SymTabLens() const; - const std::deque& FileNameLens() const; - const std::deque& SymEntLens() const; - const std::deque& FileNameIndexs() const; - - void Clear() override - { - CacheBase::Clear(); - elfIds_.clear(); - textVaddrs_.clear(); - textOffsets_.clear(); - strTabLens_.clear(); - symTabLens_.clear(); - fileNameLens_.clear(); - symEntLens_.clear(); - fileNameIndexs_.clear(); - } - -private: - std::deque elfIds_ = {}; - std::deque textVaddrs_ = {}; - std::deque textOffsets_ = {}; - std::deque strTabLens_ = {}; - std::deque symTabLens_ = {}; - std::deque fileNameLens_ = {}; - std::deque symEntLens_ = {}; - std::deque fileNameIndexs_ = {}; -}; - -class EbpfElfSymbol : public CacheBase { -public: - size_t AppendNewData(uint64_t elfId, uint32_t stName, uint64_t stValue, uint64_t stSize); - const std::deque& ElfIds() const; - const std::deque& StNames() const; - const std::deque& StValues() const; - const std::deque& StSizes() const; - - void Clear() override - { - CacheBase::Clear(); - elfIds_.clear(); - stNames_.clear(); - stValues_.clear(); - stSizes_.clear(); - } - -private: - std::deque elfIds_ = {}; - std::deque stNames_ = {}; - std::deque stValues_ = {}; - std::deque stSizes_ = {}; -}; -#endif -class HiSysEventSubkeys : public CacheBase, public BatchCacheBase { -public: - uint32_t AppendSysEventSubkey(DataIndex eventSource, DataIndex appName); - const std::deque& SysEventNameId() const; - const std::deque& SysEventSubkeyId() const; - void Clear() override - { - CacheBase::Clear(); - sysEventNameIds_.clear(); - subkeyNameIds_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, sysEventNameIds_, subkeyNameIds_); - } - -private: - std::deque sysEventNameIds_ = {}; - std::deque subkeyNameIds_ = {}; -}; -class HiSysEventMeasureData : public CacheBase, public BatchCacheBase { -public: - void AppendData(uint64_t serial, - uint64_t ts, - uint32_t nameId, - uint32_t keyId, - int32_t type, - double numericValue, - DataIndex stringValue); - const std::deque& Serial() const; - const std::deque& Ts() const; - const std::deque& NameFilterId() const; - const std::deque& AppKeyFilterId() const; - const std::deque& Type() const; - const std::deque& NumValue() const; - const std::deque& StringValue() const; - void Clear() override - { - CacheBase::Clear(); - serial_.clear(); - ts_.clear(); - nameFilterIds_.clear(); - appKeyFilterIds_.clear(); - types_.clear(); - numValues_.clear(); - stringValues_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, serial_, ts_, nameFilterIds_, appKeyFilterIds_, types_, numValues_, stringValues_); - } - -private: - std::deque serial_ = {}; - std::deque ts_ = {}; - std::deque nameFilterIds_ = {}; - std::deque appKeyFilterIds_ = {}; - std::deque types_ = {}; - std::deque numValues_ = {}; - std::deque stringValues_ = {}; - uint32_t rowCount_ = 0; -}; -class HiSysEventDeviceStateData : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(int32_t brightness, - int32_t btState, - int32_t location, - int32_t wifi, - int32_t streamDefault, - int32_t voiceCall, - int32_t music, - int32_t streamRing, - int32_t media, - int32_t voiceAssistant, - int32_t system, - int32_t alarm, - int32_t notification, - int32_t btSco, - int32_t enforcedAudible, - int32_t streamDtmf, - int32_t streamTts, - int32_t accessibility, - int32_t recording, - int32_t streamAll); - const std::deque& Brightness() const; - const std::deque& BtState() const; - const std::deque& Location() const; - const std::deque& Wifi() const; - const std::deque& StreamDefault() const; - const std::deque& VoiceCall() const; - const std::deque& Music() const; - const std::deque& StreamRing() const; - const std::deque& Media() const; - const std::deque& VoiceAssistant() const; - const std::deque& System() const; - const std::deque& Alarm() const; - const std::deque& Notification() const; - const std::deque& BtSco() const; - const std::deque& EnforcedAudible() const; - const std::deque& StreamDtmf() const; - const std::deque& StreamTts() const; - const std::deque& Accessibility() const; - const std::deque& Recordings() const; - const std::deque& StreamAll() const; - void Clear() override - { - CacheBase::Clear(); - brightness_.clear(); - btStates_.clear(); - locations_.clear(); - wifis_.clear(); - streamDefaults_.clear(); - voiceCalls_.clear(); - musics_.clear(); - streamRings_.clear(); - medias_.clear(); - voiceAssistants_.clear(); - systems_.clear(); - alarms_.clear(); - notifications_.clear(); - btScos_.clear(); - enforcedAudibles_.clear(); - streamDtmfs_.clear(); - streamTts_.clear(); - accessibilitys_.clear(); - recordings_.clear(); - streamAlls_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, brightness_, btStates_, locations_, wifis_, streamDefaults_, voiceCalls_, musics_, - streamRings_, medias_, voiceAssistants_, systems_, alarms_, notifications_, btScos_, - enforcedAudibles_, streamDtmfs_, streamTts_, accessibilitys_, recordings_, streamAlls_); - } - -private: - std::deque stringValues_ = {}; - std::deque brightness_ = {}; - std::deque btStates_ = {}; - std::deque locations_ = {}; - std::deque wifis_ = {}; - std::deque streamDefaults_ = {}; - std::deque voiceCalls_ = {}; - std::deque musics_ = {}; - std::deque streamRings_ = {}; - std::deque medias_ = {}; - std::deque voiceAssistants_ = {}; - std::deque systems_ = {}; - std::deque alarms_ = {}; - std::deque notifications_ = {}; - std::deque btScos_ = {}; - std::deque enforcedAudibles_ = {}; - std::deque streamDtmfs_ = {}; - std::deque streamTts_ = {}; - std::deque accessibilitys_ = {}; - std::deque recordings_ = {}; - std::deque streamAlls_ = {}; - uint32_t rowCounts_ = 0; -}; -class TraceConfig : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(std::string traceSource, std::string key, std::string value); - const std::deque& TraceSource() const; - const std::deque& Key() const; - const std::deque& Value() const; - void Clear() override - { - CacheBase::Clear(); - traceSource_.clear(); - key_.clear(); - value_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, traceSource_, key_, value_); - } - -private: - std::deque traceSource_ = {}; - std::deque key_ = {}; - std::deque value_ = {}; - uint32_t rowCounts_ = 0; -}; -class HiSysEventAllEventData : public CacheBase, public BatchCacheBase { -public: - uint32_t AppendHiSysEventData(DataIndex domainId, - DataIndex eventNameId, - uint64_t timeStamp, - uint32_t type, - const std::string& timeZone, - uint32_t pid, - uint32_t tid, - uint32_t uid, - const std::string& level, - const std::string& tag, - const std::string& eventId, - uint64_t seq, - const std::string& info, - const std::string& content); - const std::deque& DomainIds() const; - const std::deque& EventNameIds() const; - const std::deque& Types() const; - const std::deque& TimeZones() const; - const std::deque& Pids() const; - const std::deque& Tids() const; - const std::deque& Uids() const; - const std::deque& Levels() const; - const std::deque& Tags() const; - const std::deque& EventIds() const; - const std::deque& Seqs() const; - const std::deque& Infos() const; - const std::deque& Contents() const; - void Clear() override - { - CacheBase::Clear(); - domainIds_.clear(); - eventNameIds_.clear(); - types_.clear(); - timeZones_.clear(); - pids_.clear(); - tids_.clear(); - uids_.clear(); - levels_.clear(); - tags_.clear(); - eventIds_.clear(); - seqs_.clear(); - infos_.clear(); - contents_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, domainIds_, eventNameIds_, types_, timeZones_, pids_, tids_, uids_, levels_, - tags_, eventIds_, seqs_, infos_, contents_); - } - -private: - std::deque domainIds_ = {}; - std::deque eventNameIds_ = {}; - std::deque types_ = {}; - std::deque timeZones_ = {}; - std::deque pids_ = {}; - std::deque tids_ = {}; - std::deque uids_ = {}; - std::deque levels_ = {}; - std::deque tags_ = {}; - std::deque eventIds_ = {}; - std::deque seqs_ = {}; - std::deque infos_ = {}; - std::deque contents_ = {}; -}; -class SmapsData : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(uint64_t timeStamp, - uint64_t ipid, - std::string startAddr, - std::string endAddr, - uint64_t dirty, - uint64_t swapper, - uint64_t rss, - uint64_t pss, - uint64_t size, - double reside, - DataIndex protectionId, - DataIndex pathId, - uint64_t sharedClean, - uint64_t sharedDirty, - uint64_t privateClean, - uint64_t privateDirty, - uint64_t swap, - uint64_t swapPss, - uint32_t type); - const std::deque& Id() const; - const std::deque& TimeStamps() const; - const std::deque& Ipids() const; - const std::deque& StartAddrs() const; - const std::deque& EndAddrs() const; - const std::deque& Dirtys() const; - const std::deque& Swappers() const; - const std::deque& Rss() const; - const std::deque& Pss() const; - const std::deque& Sizes() const; - const std::deque& Resides() const; - const std::deque& ProtectionIds() const; - const std::deque& PathIds() const; - const std::deque& SharedClean() const; - const std::deque& SharedDirty() const; - const std::deque& PrivateClean() const; - const std::deque& PrivateDirty() const; - const std::deque& Swap() const; - const std::deque& SwapPss() const; - const std::deque& Type() const; - void Clear() override - { - CacheBase::Clear(); - ipids_.clear(); - startAddrs_.clear(); - endAddrs_.clear(); - dirtys_.clear(); - swappers_.clear(); - rss_.clear(); - pss_.clear(); - sizes_.clear(); - resides_.clear(); - protectionIds_.clear(); - pathIds_.clear(); - sharedClean_.clear(); - sharedDirty_.clear(); - privateClean_.clear(); - privateDirty_.clear(); - swap_.clear(); - swapPss_.clear(); - type_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, ipids_, startAddrs_, endAddrs_, dirtys_, swappers_, rss_, pss_, sizes_, - resides_, protectionIds_, pathIds_, sharedClean_, sharedDirty_, privateClean_, privateDirty_, - swap_, swapPss_, type_); - } - -private: - std::deque ipids_ = {}; - std::deque startAddrs_ = {}; - std::deque endAddrs_ = {}; - std::deque dirtys_ = {}; - std::deque swappers_ = {}; - std::deque rss_ = {}; - std::deque pss_ = {}; - std::deque sizes_ = {}; - std::deque resides_ = {}; - std::deque protectionIds_ = {}; - std::deque pathIds_ = {}; - std::deque sharedClean_ = {}; - std::deque sharedDirty_ = {}; - std::deque privateClean_ = {}; - std::deque privateDirty_ = {}; - std::deque swap_ = {}; - std::deque swapPss_ = {}; - std::deque type_ = {}; - uint32_t rowCount_ = 0; -}; -class BioLatencySampleData : public CacheBase { -public: - void AppendNewData(uint32_t callChainId, - uint64_t type, - uint32_t ipid, - uint32_t itid, - uint64_t startTs, - uint64_t endTs, - uint64_t latencyDur, - uint32_t tier, - uint64_t size, - uint64_t blockNumber, - uint64_t filePathId, - uint64_t durPer4k); - const std::deque& CallChainIds() const; - const std::deque& Types() const; - const std::deque& Ipids() const; - const std::deque& Itids() const; - const std::deque& StartTs() const; - const std::deque& EndTs() const; - const std::deque& LatencyDurs() const; - const std::deque& Tiers() const; - const std::deque& Sizes() const; - const std::deque& BlockNumbers() const; - const std::deque& FilePathIds() const; - const std::deque& DurPer4k() const; - void Clear() override - { - CacheBase::Clear(); - callChainIds_.clear(); - types_.clear(); - ipids_.clear(); - itids_.clear(); - startTs_.clear(); - endTs_.clear(); - latencyDurs_.clear(); - tiers_.clear(); - sizes_.clear(); - blockNumbers_.clear(); - filePathIds_.clear(); - durPer4ks_.clear(); - } - -private: - std::deque callChainIds_ = {}; - std::deque types_ = {}; - std::deque ipids_ = {}; - std::deque itids_ = {}; - std::deque startTs_ = {}; - std::deque endTs_ = {}; - std::deque latencyDurs_ = {}; - std::deque tiers_ = {}; - std::deque sizes_ = {}; - std::deque blockNumbers_ = {}; - std::deque filePathIds_ = {}; - std::deque durPer4ks_ = {}; - uint32_t rowCount_ = 0; -}; -class ClockSnapshotData { -public: - size_t AppendNewSnapshot(uint8_t clockId, uint64_t ts, const std::string& name) - { - clockIds_.emplace_back(clockId); - ts_.emplace_back(ts); - names_.emplace_back(name); - return ts_.size(); - } - size_t Size() const - { - return ts_.size(); - } - const std::deque& ClockIds() const - { - return clockIds_; - } - const std::deque& Ts() const - { - return ts_; - } - const std::deque& Names() const - { - return names_; - } - -private: - std::deque clockIds_ = {}; - std::deque ts_ = {}; - std::deque names_ = {}; -}; -class DataSourceClockIdData { -public: - DataSourceClockIdData(); - size_t AppendNewDataSourceClockId(const std::string& dataSoruceName, uint8_t clockId) - { - dataSourceNames_.emplace_back(dataSoruceName); - clockIds_.emplace_back(clockId); - return dataSourceNames_.size(); - } - size_t Size() const - { - return dataSourceNames_.size(); - } - const std::deque& ClockIds() const - { - return clockIds_; - } - const std::deque& Names() const - { - return dataSourceNames_; - } - void SetDataSourceClockId(DataSourceType source, uint32_t id); - void Finish(); - -private: - std::deque dataSourceNames_ = {}; - std::deque clockIds_ = {}; - std::map dataSource2ClockIdMap_ = {}; - std::map dataSource2PluginNameMap_ = {}; -}; - -class FrameSlice : public CacheBase, public BatchCacheBase { -public: - size_t AppendFrame(uint64_t ts, uint32_t ipid, uint32_t itid, uint32_t vsyncId, uint64_t callStackSliceId); - size_t AppendFrame(uint64_t ts, - uint32_t ipid, - uint32_t itid, - uint32_t vsyncId, - uint64_t callStackSliceId, - uint64_t end, - uint8_t type); - void SetEndTime(uint64_t row, uint64_t end); - void SetType(uint64_t row, uint8_t type); - void SetDst(uint64_t row, uint64_t dst); - void SetSrcs(uint64_t row, const std::vector& fromSlices); - void SetFlags(uint64_t row, const uint32_t flags); - void UpdateDepth(); - const std::deque Ipids() const; - const std::deque VsyncIds() const; - const std::deque CallStackIds() const; - const std::deque EndTss() const; - const std::deque Dsts() const; - const std::deque Durs() const; - const std::deque Types() const; - const std::deque Flags() const; - const std::deque Depths() const; - const std::deque FrameNos() const; - const std::deque& Srcs() const; - void UpdateCallStackSliceId(uint64_t row, uint64_t callStackSliceId); - void SetEndTimeAndFlag(uint64_t row, uint64_t ts, uint64_t expectDur, uint64_t expectEnd); - void Erase(uint64_t row); - static uint32_t GetAbnormalStartEndTimeState() - { - return abnormalStartEndTimeState_; - } - void ClearPrevData() - { - EraseElements(internalTids_, timeStamps_, ids_, ipids_, dsts_, srcs_, vsyncIds_, callStackIds_, endTss_, durs_, - types_, flags_, depths_, frameNos_); - } - -public: - typedef enum FrameSliceType { ACTURAL_SLICE, EXPECT_SLICE } FrameSliceType; - -private: - std::deque ipids_ = {}; - std::deque dsts_ = {}; - std::deque srcs_ = {}; - std::deque vsyncIds_ = {}; - std::deque callStackIds_ = {}; - std::deque endTss_ = {}; - std::deque durs_ = {}; - std::deque types_ = {}; - std::deque flags_ = {}; - std::deque depths_ = {}; - std::deque frameNos_ = {}; - const uint32_t invalidRow_ = 2; - static const uint32_t abnormalStartEndTimeState_ = 3; - const uint8_t flagValue_ = 2; -}; -class FrameMaps : public CacheBase, public BatchCacheBase { -public: - size_t AppendNew(FrameSlice* frameSlice, uint64_t src, uint64_t dst); - const std::deque& SrcIndexs() const; - const std::deque& DstIndexs() const; - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, srcs_, dsts_); - } - -private: - std::deque srcs_ = {}; - std::deque dsts_ = {}; -}; - -class AppStartup : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewData(uint32_t ipid, - uint32_t tid, - uint32_t callId, - uint64_t startTime, - uint64_t endTime, - uint32_t startName, - DataIndex packedName); - const std::deque& Pids() const; - const std::deque& Tids() const; - const std::deque& CallIds() const; - const std::deque& StartTimes() const; - const std::deque& EndTimes() const; - const std::deque& StartNames() const; - const std::deque& PackedNames() const; - - void Clear() override - { - CacheBase::Clear(); - ipids_.clear(); - tids_.clear(); - callIds_.clear(); - startTimes_.clear(); - endTimes_.clear(); - startNames_.clear(); - packedNames_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, ipids_, tids_, callIds_, startTimes_, endTimes_, startNames_, packedNames_); - } - -private: - std::deque ipids_ = {}; - std::deque tids_ = {}; - std::deque callIds_ = {}; - std::deque startTimes_ = {}; - std::deque endTimes_ = {}; - std::deque startNames_ = {}; - std::deque packedNames_ = {}; -}; - -class SoStaticInitalization : public CacheBase, public BatchCacheBase { -public: - size_t AppendNewData(uint32_t ipid, - uint32_t tid, - uint32_t callId, - uint64_t startTime, - uint64_t endTime, - DataIndex soName, - uint32_t depth); - const std::deque& Pids() const; - const std::deque& Tids() const; - const std::deque& CallIds() const; - const std::deque& StartTimes() const; - const std::deque& EndTimes() const; - const std::deque& SoNames() const; - const std::deque Depths() const; - - void Clear() override - { - CacheBase::Clear(); - ipids_.clear(); - tids_.clear(); - callIds_.clear(); - startTimes_.clear(); - endTimes_.clear(); - soNames_.clear(); - depths_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, ipids_, tids_, callIds_, startTimes_, endTimes_, soNames_, depths_); - } - -private: - std::deque ipids_ = {}; - std::deque tids_ = {}; - std::deque callIds_ = {}; - std::deque startTimes_ = {}; - std::deque endTimes_ = {}; - std::deque soNames_ = {}; - std::deque depths_ = {}; -}; - -class JsHeapFiles : public CacheBase { -public: - size_t - AppendNewData(uint32_t id, std::string filePath, uint64_t startTime, uint64_t endTime, uint64_t selfSizeCount); - const std::deque& IDs() const; - const std::deque& FilePaths() const; - const std::deque& StartTimes() const; - const std::deque& EndTimes() const; - const std::deque& SelfSizeCount() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - filePaths_.clear(); - startTimes_.clear(); - endTimes_.clear(); - selfSizeCount_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque filePaths_ = {}; - std::deque startTimes_ = {}; - std::deque endTimes_ = {}; - std::deque selfSizeCount_ = {}; -}; - -class JsHeapEdges : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, - uint32_t edgeIndex, - uint32_t type, - uint32_t nameOrIndex, - uint32_t toNode, - uint32_t fromNodeId, - uint32_t toNodeId); - const std::deque& FileIds() const; - const std::deque& EdgeIndexs() const; - const std::deque& Types() const; - const std::deque& NameOrIndexs() const; - const std::deque& ToNodes() const; - const std::deque& FromNodeIds() const; - const std::deque& ToNodeIds() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - edgeIndexs_.clear(); - types_.clear(); - nameOrIndexs_.clear(); - toNodes_.clear(); - fromNodeIds_.clear(); - toNodeIds_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque edgeIndexs_ = {}; - std::deque types_ = {}; - std::deque nameOrIndexs_ = {}; - std::deque toNodes_ = {}; - std::deque fromNodeIds_ = {}; - std::deque toNodeIds_ = {}; -}; - -class JsHeapInfo : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, std::string key, uint32_t type, int32_t intValue, std::string strValue); - const std::deque& FileIds() const; - const std::deque& Keys() const; - const std::deque& Types() const; - const std::deque& IntValues() const; - const std::deque& StrValues() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - keys_.clear(); - types_.clear(); - intValues_.clear(); - strValues_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque keys_ = {}; - std::deque types_ = {}; - std::deque intValues_ = {}; - std::deque strValues_ = {}; -}; - -class JsHeapLocation : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, uint32_t objectIndex, uint32_t scriptId, uint32_t line, uint32_t column); - const std::deque& FileIds() const; - const std::deque& ObjectIndexs() const; - const std::deque& ScriptIds() const; - const std::deque& Lines() const; - const std::deque& Columns() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - objectIndexs_.clear(); - scriptIds_.clear(); - lines_.clear(); - columns_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque objectIndexs_ = {}; - std::deque scriptIds_ = {}; - std::deque lines_ = {}; - std::deque columns_ = {}; -}; - -class JsHeapNodes : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, - uint32_t nodeIndex, - uint32_t type, - uint32_t name, - uint32_t id, - uint32_t selfSize, - uint32_t edgeCount, - uint32_t traceNodeId, - uint32_t detachedNess); - const std::deque& FileIds() const; - const std::deque& NodeIndexs() const; - const std::deque& Types() const; - const std::deque& Names() const; - const std::deque& NodeIds() const; - const std::deque& SelfSizes() const; - const std::deque& EdgeCounts() const; - const std::deque& TraceNodeIds() const; - const std::deque& DetachedNess() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - nodeIndexs_.clear(); - types_.clear(); - names_.clear(); - nodeIds_.clear(); - selfSizes_.clear(); - edgeCounts_.clear(); - traceNodeIds_.clear(); - detachedNess_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque nodeIndexs_ = {}; - std::deque types_ = {}; - std::deque names_ = {}; - std::deque nodeIds_ = {}; - std::deque selfSizes_ = {}; - std::deque edgeCounts_ = {}; - std::deque traceNodeIds_ = {}; - std::deque detachedNess_ = {}; -}; - -class JsHeapSample : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, uint64_t timeStampUs, uint32_t lastAssignedId); - const std::deque& FileIds() const; - const std::deque& TimeStampUs() const; - const std::deque& LastAssignedIds() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - timeStampUs_.clear(); - lastAssignedIds_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque timeStampUs_ = {}; - std::deque lastAssignedIds_ = {}; -}; - -class JsHeapString : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, uint32_t fileIndex, std::string string); - const std::deque& FileIds() const; - const std::deque& FileIndexs() const; - const std::deque& Strings() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - fileIndexs_.clear(); - strings_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque fileIndexs_ = {}; - std::deque strings_ = {}; -}; - -class JsHeapTraceFuncInfo : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, - uint32_t functionIndex, - uint32_t functionId, - uint32_t name, - uint32_t scriptName, - uint32_t scriptId, - uint32_t line, - uint32_t column); - const std::deque& FileIds() const; - const std::deque& FunctionIndexs() const; - const std::deque& FunctionIds() const; - const std::deque& Names() const; - const std::deque& ScriptNames() const; - const std::deque& ScriptIds() const; - const std::deque& Lines() const; - const std::deque& Columns() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - functionIndexs_.clear(); - functionIds_.clear(); - names_.clear(); - scriptNames_.clear(); - scriptIds_.clear(); - lines_.clear(); - columns_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque functionIndexs_ = {}; - std::deque functionIds_ = {}; - std::deque names_ = {}; - std::deque scriptNames_ = {}; - std::deque scriptIds_ = {}; - std::deque lines_ = {}; - std::deque columns_ = {}; -}; - -class JsHeapTraceNode : public CacheBase { -public: - size_t AppendNewData(uint32_t fileId, - uint32_t traceNodeId, - uint32_t functionInfoIndex, - uint32_t count, - uint32_t size, - int32_t parentId); - const std::deque& FileIds() const; - const std::deque& TraceNodeIDs() const; - const std::deque& FunctionInfoIndexs() const; - const std::deque& Counts() const; - const std::deque& NodeSizes() const; - const std::deque& ParentIds() const; - void Clear() override - { - CacheBase::Clear(); - fileIds_.clear(); - traceNodeIds_.clear(); - functionInfoIndexs_.clear(); - counts_.clear(); - sizes_.clear(); - parentIds_.clear(); - } - -private: - std::deque fileIds_ = {}; - std::deque traceNodeIds_ = {}; - std::deque functionInfoIndexs_ = {}; - std::deque counts_ = {}; - std::deque sizes_ = {}; - std::deque parentIds_ = {}; -}; - -class JsConfig : public CacheBase { -public: - size_t AppendNewData(uint32_t pid, - uint64_t type, - uint32_t interval, - uint32_t captureNumericValue, - uint32_t trackAllocation, - uint32_t cpuProfiler, - uint32_t cpuProfilerInterval); - const std::deque& Pids() const; - const std::deque& Types() const; - const std::deque& Intervals() const; - const std::deque& CaptureNumericValue() const; - const std::deque& TrackAllocations() const; - const std::deque& CpuProfiler() const; - const std::deque& CpuProfilerInterval() const; - void Clear() override - { - CacheBase::Clear(); - pids_.clear(); - types_.clear(); - intervals_.clear(); - captureNumericValues_.clear(); - trackAllocations_.clear(); - cpuProfilers_.clear(); - cpuProfilerIntervals_.clear(); - } - -private: - std::deque pids_ = {}; - std::deque types_ = {}; - std::deque intervals_ = {}; - std::deque captureNumericValues_ = {}; - std::deque trackAllocations_ = {}; - std::deque cpuProfilers_ = {}; - std::deque cpuProfilerIntervals_ = {}; -}; - -class JsCpuProfilerNode : public CacheBase { -public: - size_t AppendNewData(uint32_t functionId, - uint32_t functionName, - std::string scriptId, - uint32_t url, - uint32_t lineNumber, - uint32_t columnNumber, - uint32_t hitCount, - std::string children, - uint32_t parent); - const std::deque& FunctionIds() const; - const std::deque& FunctionNames() const; - const std::deque& ScriptIds() const; - const std::deque& Urls() const; - const std::deque& LineNumbers() const; - const std::deque& ColumnNumbers() const; - const std::deque& HitCounts() const; - const std::deque& Children() const; - const std::deque& Parents() const; - void Clear() override - { - CacheBase::Clear(); - functionIds_.clear(); - functionNames_.clear(); - scriptIds_.clear(); - urls_.clear(); - lineNumbers_.clear(); - columnNumbers_.clear(); - hitCounts_.clear(); - children_.clear(); - parents_.clear(); - } - -private: - std::deque functionIds_ = {}; - std::deque functionNames_ = {}; - std::deque scriptIds_ = {}; - std::deque urls_ = {}; - std::deque lineNumbers_ = {}; - std::deque columnNumbers_ = {}; - std::deque hitCounts_ = {}; - std::deque children_ = {}; - std::deque parents_ = {}; -}; - -class JsCpuProfilerSample : public CacheBase { -public: - size_t AppendNewData(uint32_t functionId, uint64_t startTime, uint64_t endTime, uint64_t dur); - const std::deque& FunctionIds() const; - const std::deque& StartTimes() const; - const std::deque& EndTimes() const; - const std::deque& Durs() const; - void Clear() override - { - CacheBase::Clear(); - functionIds_.clear(); - startTimes_.clear(); - endTimes_.clear(); - durs_.clear(); - } - -private: - std::deque functionIds_ = {}; - std::deque startTimes_ = {}; - std::deque endTimes_ = {}; - std::deque durs_ = {}; -}; - -class GPUSlice : public BatchCacheBase { -public: - size_t AppendNew(uint32_t frameRow, uint64_t dur); - const std::deque& FrameRows() const; - const std::deque& Durs() const; - size_t Size() const; - void ClearPrevData() - { - EraseElements(frameRows_, durs_); - } - -private: - std::deque frameRows_ = {}; - std::deque durs_ = {}; -}; - -class TaskPoolInfo : public CacheBase, public BatchCacheBase { -public: - size_t AppendAllocationTaskData(uint32_t allocationTaskRow, - uint32_t allocationItid, - uint32_t executeId, - uint32_t priority, - uint32_t executeState); - size_t AppendExecuteTaskData(uint32_t executeTaskRow, uint32_t executeItid, uint32_t executeId); - size_t AppendReturnTaskData(uint32_t returnTaskRow, uint32_t returnItid, uint32_t executeId, uint32_t returnState); - void UpdateAllocationTaskData(uint32_t index, - uint32_t allocationTaskRow, - uint32_t allocationItid, - uint32_t priority, - uint32_t executeState); - void UpdateExecuteTaskData(uint32_t index, uint32_t executeTaskRow, uint32_t executeItid); - void UpdateReturnTaskData(uint32_t index, uint32_t returnTaskRow, uint32_t returnItid, uint32_t returnState); - void AppendTimeoutRow(uint32_t index, uint32_t timeoutRow); - - const std::deque& AllocationTaskRows() const; - const std::deque& ExecuteTaskRows() const; - const std::deque& ReturnTaskRows() const; - const std::deque& AllocationItids() const; - const std::deque& ExecuteItids() const; - const std::deque& ReturnItids() const; - const std::deque& ExecuteIds() const; - const std::deque& Prioritys() const; - const std::deque& ExecuteStates() const; - const std::deque& ReturnStates() const; - const std::deque& TimeoutRows() const; - void Clear() override - { - CacheBase::Clear(); - allocationTaskRows_.clear(); - executeTaskRows_.clear(); - returnTaskRows_.clear(); - allocationItids_.clear(); - executeItids_.clear(); - returnItids_.clear(); - executeIds_.clear(); - prioritys_.clear(); - executeStates_.clear(); - returnStates_.clear(); - timeoutRows_.clear(); - } - void ClearPrevData() - { - EraseElements(ids_, allocationTaskRows_, executeTaskRows_, returnTaskRows_, allocationItids_, executeItids_, - returnItids_, executeIds_, prioritys_, executeStates_, returnStates_, timeoutRows_); - } - -private: - std::deque allocationTaskRows_ = {}; - std::deque executeTaskRows_ = {}; - std::deque returnTaskRows_ = {}; - std::deque allocationItids_ = {}; - std::deque executeItids_ = {}; - std::deque returnItids_ = {}; - std::deque executeIds_ = {}; - std::deque prioritys_ = {}; - std::deque executeStates_ = {}; - std::deque returnStates_ = {}; - std::deque timeoutRows_ = {}; -}; -class Animation : public BatchCacheBase { -public: - TableRowId AppendAnimation(InternalTime inputTime, InternalTime startPoint, DataIndex nameIndex); - void UpdateStartPoint(TableRowId index, InternalTime startPoint); - void UpdateEndPoint(TableRowId index, InternalTime endPoint); - void UpdateFrameInfo(TableRowId index, InternalTime frameInfo); - size_t Size() const; - const std::deque& InputTimes() const; - const std::deque& StartPoints() const; - const std::deque& EndPoints() const; - const std::deque& FrameInfos() const; - const std::deque& Names() const; - const std::deque& IdsData() const; - void Clear(); - void ClearPrevData() - { - EraseElements(inputTimes_, startPoints_, endPoins_, frameInfos_, names_, ids_); - } - -private: - std::deque inputTimes_ = {}; - std::deque startPoints_ = {}; - std::deque endPoins_ = {}; - std::deque frameInfos_ = {}; - std::deque names_ = {}; - std::deque ids_ = {}; -}; -class DeviceInfo { -public: - uint32_t PhysicalWidth() const; - uint32_t PhysicalHeight() const; - uint32_t PhysicalFrameRate() const; - void UpdateWidthAndHeight(const std::smatch& matcheLine); - void UpdateFrameRate(uint32_t frameRate); - - void Clear(); - -private: - uint32_t physicalWidth_ = INVALID_UINT32; - uint32_t physicalHeight_ = INVALID_UINT32; - uint32_t physicalFrameRate_ = INVALID_UINT32; -}; -class DynamicFrame : public BatchCacheBase { -public: - TableRowId AppendDynamicFrame(DataIndex nameId); - void UpdateNameIndex(TableRowId index, DataIndex nameId); - void UpdatePosition(TableRowId index, const std::smatch& matcheLine, DataIndex alpha); - void UpdateEndTime(TableRowId index, InternalTime endTime); - - size_t Size() const; - const std::deque& IdsData() const; - const std::deque& Xs() const; - const std::deque& Ys() const; - const std::deque& Widths() const; - const std::deque& Heights() const; - const std::deque& Alphas() const; - const std::deque& Names() const; - const std::deque& EndTimes() const; - void Clear(); - void ClearPrevData() - { - EraseElements(xs_, ys_, widths_, heights_, alphas_, names_, endTimes_, ids_); - } - -private: - std::deque xs_ = {}; - std::deque ys_ = {}; - std::deque widths_ = {}; - std::deque heights_ = {}; - std::deque alphas_ = {}; - std::deque names_ = {}; - std::deque endTimes_ = {}; - std::deque ids_ = {}; -}; - -class AshMemData : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(InternalPid ipid, - uint64_t ts, - uint32_t adj, - uint32_t fd, - DataIndex ashmemNameId, - uint64_t size, - uint64_t pss, - uint32_t ashmemId, - uint64_t time, - uint64_t refCount, - uint64_t purged, - uint32_t flag); - const std::deque& Ipids() const; - const std::deque& Adjs() const; - const std::deque& Fds() const; - const std::deque& AshmemNameIds() const; - const std::deque& Sizes() const; - const std::deque& Psss() const; - const std::deque& AshmemIds() const; - const std::deque& Times() const; - const std::deque& RefCounts() const; - const std::deque& Purgeds() const; - const std::deque& Flags() const; - void Clear() override - { - CacheBase::Clear(); - ipids_.clear(); - adjs_.clear(); - fds_.clear(); - ashmemNameIds_.clear(); - sizes_.clear(); - psss_.clear(); - ashmemIds_.clear(); - times_.clear(); - refCounts_.clear(); - purgeds_.clear(); - flags_.clear(); - } - void SetFlag(uint64_t rowId, uint32_t flag); - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, ipids_, adjs_, fds_, ashmemNameIds_, sizes_, psss_, ashmemIds_, times_, - refCounts_, purgeds_, flags_); - } - -private: - std::deque ipids_ = {}; - std::deque adjs_ = {}; - std::deque fds_ = {}; - std::deque ashmemNameIds_ = {}; - std::deque sizes_ = {}; - std::deque psss_ = {}; - std::deque ashmemIds_ = {}; - std::deque times_ = {}; - std::deque refCounts_ = {}; - std::deque purgeds_ = {}; - std::deque flags_ = {}; - uint32_t rowCount_ = 0; -}; - -class DmaMemData : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(InternalPid ipid, - uint64_t ts, - uint32_t fd, - uint64_t size, - uint32_t ino, - uint32_t expPid, - DataIndex expTaskCommId, - DataIndex bufNameId, - DataIndex expNameId, - uint32_t flag); - const std::deque& Ipids() const; - const std::deque& Fds() const; - const std::deque& Sizes() const; - const std::deque& Inos() const; - const std::deque& ExpPids() const; - const std::deque& ExpTaskCommIds() const; - const std::deque& BufNameIds() const; - const std::deque& ExpNameIds() const; - const std::deque& Flags() const; - void Clear() override - { - CacheBase::Clear(); - ipids_.clear(); - fds_.clear(); - sizes_.clear(); - inos_.clear(); - expPids_.clear(); - expTaskCommIds_.clear(); - bufNameIds_.clear(); - expNameIds_.clear(); - flags_.clear(); - } - void SetFlag(uint64_t rowId, uint32_t flag); - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, ipids_, fds_, sizes_, inos_, expPids_, expTaskCommIds_, bufNameIds_, - expNameIds_, flags_); - } - -private: - std::deque ipids_ = {}; - std::deque fds_ = {}; - std::deque sizes_ = {}; - std::deque inos_ = {}; - std::deque expPids_ = {}; - std::deque expTaskCommIds_ = {}; - std::deque bufNameIds_ = {}; - std::deque expNameIds_ = {}; - std::deque flags_ = {}; - uint32_t rowCount_ = 0; -}; - -class GpuProcessMemData : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(uint64_t ts, - DataIndex gpuNameId, - uint64_t allGpuSize, - std::string addr, - InternalPid ipid, - InternalPid itid, - uint64_t usedGpuSize); - const std::deque& GpuNameIds() const; - const std::deque& AllGpuSizes() const; - const std::deque& Addrs() const; - const std::deque& Ipids() const; - const std::deque& Itids() const; - const std::deque& UsedGpuSizes() const; - void Clear() override - { - CacheBase::Clear(); - gpuNameIds_.clear(); - allGpuSizes_.clear(); - addrs_.clear(); - ipids_.clear(); - itids_.clear(); - usedGpuSizes_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, gpuNameIds_, allGpuSizes_, addrs_, ipids_, itids_, usedGpuSizes_); - } - -private: - std::deque gpuNameIds_ = {}; - std::deque allGpuSizes_ = {}; - std::deque addrs_ = {}; - std::deque ipids_ = {}; - std::deque itids_ = {}; - std::deque usedGpuSizes_ = {}; - uint32_t rowCount_ = 0; -}; - -class GpuWindowMemData : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(uint64_t ts, - DataIndex windowNameId, - uint64_t windowId, - DataIndex moduleNameId, - DataIndex categoryNameId, - uint64_t size, - uint32_t count, - uint64_t purgeableSize); - void RevicesIpid(const std::map& windowIdToIpidMap); - const std::deque& WindowNameIds() const; - const std::deque& WindowIds() const; - const std::deque& ModuleNameIds() const; - const std::deque& CategoryNameIds() const; - const std::deque& Sizes() const; - const std::deque& Counts() const; - const std::deque& PurgeableSizes() const; - const std::deque& Ipids() const; - void Clear() override - { - CacheBase::Clear(); - windowNameIds_.clear(); - windowIds_.clear(); - moduleNameIds_.clear(); - categoryNameIds_.clear(); - sizes_.clear(); - counts_.clear(); - purgeableSizes_.clear(); - ipids_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, windowNameIds_, windowIds_, moduleNameIds_, categoryNameIds_, sizes_, counts_, - purgeableSizes_, ipids_); - } - -private: - std::deque windowNameIds_ = {}; - std::deque windowIds_ = {}; - std::deque moduleNameIds_ = {}; - std::deque categoryNameIds_ = {}; - std::deque sizes_ = {}; - std::deque counts_ = {}; - std::deque purgeableSizes_ = {}; - std::deque ipids_ = {}; - uint32_t rowCount_ = 0; -}; -class CpuDumpInfo : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(uint64_t timestamp, uint64_t size); - const std::deque& TotalSizes() const; - void Clear() override - { - CacheBase::Clear(); - totalSizes_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, totalSizes_); - } - -private: - std::deque totalSizes_ = {}; -}; -class ProfileMemInfo : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(uint64_t timestamp, DataIndex channelIndex, uint64_t size); - const std::deque& ChannelIndexs() const; - const std::deque& TotalSizes() const; - void Clear() override - { - CacheBase::Clear(); - channelIndexs_.clear(); - totalSizes_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, channelIndexs_, totalSizes_); - } - -private: - std::deque channelIndexs_ = {}; - std::deque totalSizes_ = {}; -}; -class RSImageDumpInfo : public CacheBase, public BatchCacheBase { -public: - void AppendNewData(uint64_t timestamp, uint64_t memSize, DataIndex typeIndex, InternalPid ipid, DataIndex name); - const std::deque& MemSizes() const; - const std::deque& TypeIndexs() const; - const std::deque& Ipids() const; - const std::deque& SurfaceNameIndexs() const; - void Clear() override - { - CacheBase::Clear(); - memSizes_.clear(); - typeIndexs_.clear(); - ipids_.clear(); - surfaceNameIndexs_.clear(); - } - void ClearPrevData() - { - EraseElements(timeStamps_, ids_, memSizes_, typeIndexs_, ipids_, surfaceNameIndexs_); - } - -private: - std::deque memSizes_ = {}; - std::deque typeIndexs_ = {}; - std::deque ipids_ = {}; - std::deque surfaceNameIndexs_ = {}; -}; -} // namespace TraceStdtype -} // namespace SysTuning - -#endif // TRACE_STDTYPE_H diff --git a/trace_streamer/src/table/ftrace/thread_filter_table.h b/trace_streamer/src/trace_data/trace_stdtype/base_stdtype.cpp similarity index 49% rename from trace_streamer/src/table/ftrace/thread_filter_table.h rename to trace_streamer/src/trace_data/trace_stdtype/base_stdtype.cpp index 17c44b6b09ba36a9bd1f91f76e25561181204480..57ddc052bf21152c5d3292833756bc629f44c9b4 100644 --- a/trace_streamer/src/table/ftrace/thread_filter_table.h +++ b/trace_streamer/src/trace_data/trace_stdtype/base_stdtype.cpp @@ -13,29 +13,37 @@ * limitations under the License. */ -#ifndef THREAD_FILTER_TABLE_H -#define THREAD_FILTER_TABLE_H - -#include "table_base.h" -#include "trace_data_cache.h" - +#include "base_stdtype.h" namespace SysTuning { -namespace TraceStreamer { -class ThreadFilterTable : public TableBase { -public: - explicit ThreadFilterTable(const TraceDataCache* dataCache); - ~ThreadFilterTable() override; - std::unique_ptr CreateCursor() override; +namespace TraceStdtype { +size_t CacheBase::Size() const +{ + return std::max(timeStamps_.size(), ids_.size()); +} +const std::deque& CacheBase::IdsData() const +{ + return ids_; +} +const std::deque& CacheBase::TimeStampData() const +{ + return timeStamps_; +} +const std::deque& CacheBase::InternalTidsData() const +{ + return internalTids_; +} -private: - class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache* dataCache, TableBase* table); - ~Cursor() override; - int32_t Column(int32_t column) const override; - }; -}; -} // namespace TraceStreamer +const std::deque& CpuCacheBase::DursData() const +{ + return durs_; +} +const std::deque& CpuCacheBase::CpusData() const +{ + return cpus_; +} +void CpuCacheBase::SetDur(uint64_t index, uint64_t dur) +{ + durs_[index] = dur; +} +} // namespace TraceStdtype } // namespace SysTuning - -#endif // THREAD_FILTER_TABLE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/base_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/base_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..0c6964a3eba05dad04b6ae71566206944df42002 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/base_stdtype.h @@ -0,0 +1,91 @@ +/* + * 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 BASE_STDTYPE_H +#define BASE_STDTYPE_H + +#include +#include "log.h" +#include "ts_common.h" + +namespace SysTuning { +namespace TraceStdtype { +constexpr uint32_t ONE_MILLION_NANOSECONDS = 1000000; +constexpr uint32_t BILLION_NANOSECONDS = 1000000000; +constexpr uint8_t DYNAMICFRAME_MATCH_LAST = 5; +class CacheBase { +public: + size_t Size() const; + const std::deque& IdsData() const; + const std::deque& TimeStampData() const; + const std::deque& InternalTidsData() const; + virtual void Clear() + { + internalTids_.clear(); + timeStamps_.clear(); + ids_.clear(); + id_ = 0; + } + +public: + std::deque internalTids_ = {}; + std::deque timeStamps_ = {}; + std::deque ids_ = {}; + uint64_t id_ = 0; +}; + +class CpuCacheBase { +public: + const std::deque& DursData() const; + const std::deque& CpusData() const; + virtual void Clear() + { + durs_.clear(); + cpus_.clear(); + } + void SetDur(uint64_t index, uint64_t dur); + +public: + std::deque durs_; + std::deque cpus_; +}; + +class BatchCacheBase { +public: + virtual void UpdateReadySize(size_t size) + { + readySize_ = size; + } + virtual void ClearExportedData() = 0; + template + void EraseElements(T& deq, changedata&... args) + { + deq.erase(deq.begin(), deq.begin() + readySize_); + EraseElements(args...); + readySize_ = 0; + } + template + void EraseElements(T1& deq) + { + deq.erase(deq.begin(), deq.begin() + readySize_); + } + +public: + size_t readySize_ = 0; +}; +} // namespace TraceStdtype +} // namespace SysTuning + +#endif // BASE_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/common_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/common_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da515b693b6373a1365675b02b1b56b886d79416 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/common_stdtype.cpp @@ -0,0 +1,319 @@ +/* + * 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 "common_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +MetaData::MetaData() +{ + columnNames_.resize(METADATA_ITEM_MAX); + values_.resize(METADATA_ITEM_MAX); + columnNames_[METADATA_ITEM_DATASIZE] = METADATA_ITEM_DATASIZE_COLNAME; + columnNames_[METADATA_ITEM_PARSETOOL_NAME] = METADATA_ITEM_PARSETOOL_NAME_COLNAME; + columnNames_[METADATA_ITEM_PARSERTOOL_VERSION] = METADATA_ITEM_PARSERTOOL_VERSION_COLNAME; + columnNames_[METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME] = METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME_COLNAME; + columnNames_[METADATA_ITEM_SOURCE_FILENAME] = METADATA_ITEM_SOURCE_FILENAME_COLNAME; + columnNames_[METADATA_ITEM_OUTPUT_FILENAME] = METADATA_ITEM_OUTPUT_FILENAME_COLNAME; + columnNames_[METADATA_ITEM_PARSERTIME] = METADATA_ITEM_PARSERTIME_COLNAME; + columnNames_[METADATA_ITEM_TRACE_DURATION] = METADATA_ITEM_TRACE_DURATION_COLNAME; + columnNames_[METADATA_ITEM_SOURCE_DATETYPE] = METADATA_ITEM_SOURCE_DATETYPE_COLNAME; + values_[METADATA_ITEM_PARSETOOL_NAME] = "trace_streamer"; +} +void MetaData::SetTraceType(const std::string& traceType) +{ + values_[METADATA_ITEM_SOURCE_DATETYPE] = traceType; +} +void MetaData::SetSourceFileName(const std::string& fileName) +{ + MetaData::values_[METADATA_ITEM_SOURCE_FILENAME] = fileName; +} +void MetaData::SetOutputFileName(const std::string& fileName) +{ + MetaData::values_[METADATA_ITEM_OUTPUT_FILENAME] = fileName; +} +void MetaData::SetParserToolVersion(const std::string& version) +{ + values_[METADATA_ITEM_PARSERTOOL_VERSION] = version; +} +void MetaData::SetParserToolPublishDateTime(const std::string& datetime) +{ + values_[METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME] = datetime; +} +void MetaData::SetTraceDataSize(uint64_t dataSize) +{ + std::stringstream ss; + ss << dataSize; + values_[METADATA_ITEM_DATASIZE] = ss.str(); + // Function 'time' may return error. It is not allowed to do anything that might fail inside the constructor. + time_t rawtime; + tm* timeinfo = nullptr; + (void)time(&rawtime); + timeinfo = localtime(&rawtime); + char buffer[MAX_SIZE_LEN]; + (void)strftime(buffer, MAX_SIZE_LEN, "%Y-%m-%d %H:%M:%S", timeinfo); + values_[METADATA_ITEM_PARSERTIME].append(buffer); + // sometimes there will be a extra \n at last + values_[METADATA_ITEM_PARSERTIME].pop_back(); +} +void MetaData::SetTraceDuration(uint64_t dur) +{ + values_[METADATA_ITEM_TRACE_DURATION] = std::to_string(dur) + " s"; +} +const std::string& MetaData::Value(uint64_t row) const +{ + return values_[row]; +} +const std::string& MetaData::Name(uint64_t row) const +{ + return columnNames_[row]; +} +DataIndex DataDict::GetStringIndex(std::string_view str) +{ + auto itor = dataDictInnerMap_.find(str); + if (itor != dataDictInnerMap_.end()) { + return itor->second; + } + mutex_.lock(); + dataDict_.emplace_back(std::string(str)); + DataIndex stringIdentity = dataDict_.size() - 1; + dataDictInnerMap_.emplace(std::string_view(dataDict_.back()), stringIdentity); + mutex_.unlock(); + return stringIdentity; +} +DataIndex DataDict::GetStringIndexNoWrite(std::string_view str) const +{ + auto itor = dataDictInnerMap_.find(str); + if (itor != dataDictInnerMap_.end()) { + return itor->second; + } + return INVALID_UINT64; +} +void DataDict::Finish() +{ + std::string::size_type pos; + for (auto i = 0; i < dataDict_.size(); i++) { + while ((pos = dataDict_[i].find("\"")) != std::string::npos) { + dataDict_[i].replace(pos, 1, "\'"); + } + while (!dataDict_[i].empty() && ((dataDict_[i].back() >= SPASCII_START && dataDict_[i].back() <= SPASCII_END) || + dataDict_[i].back() == '\r')) { + dataDict_[i].pop_back(); + } + } +} + +DataSourceClockIdData::DataSourceClockIdData() + : dataSource2ClockIdMap_({{DATA_SOURCE_TYPE_TRACE, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_MEM, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_HILOG, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_NATIVEHOOK, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_FPS, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_NETWORK, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_DISKIO, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_CPU, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_PROCESS, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_HISYSEVENT, TS_CLOCK_UNKNOW}, + {DATA_SOURCE_TYPE_JSMEMORY, TS_CLOCK_UNKNOW}}), + dataSource2PluginNameMap_({ + {DATA_SOURCE_TYPE_TRACE, "ftrace-plugin"}, + {DATA_SOURCE_TYPE_MEM, "memory-plugin"}, + {DATA_SOURCE_TYPE_HILOG, "hilog-plugin"}, + {DATA_SOURCE_TYPE_NATIVEHOOK, "nativehook"}, + {DATA_SOURCE_TYPE_FPS, "hidump-plugin"}, + {DATA_SOURCE_TYPE_NETWORK, "network-plugin"}, + {DATA_SOURCE_TYPE_DISKIO, "diskio-plugin"}, + {DATA_SOURCE_TYPE_CPU, "cpu-plugin"}, + {DATA_SOURCE_TYPE_PROCESS, "process-plugin"}, + {DATA_SOURCE_TYPE_HISYSEVENT, "hisysevent-plugin"}, + {DATA_SOURCE_TYPE_JSMEMORY, "arkts-plugin"}, + }) +{ +} +void DataSourceClockIdData::Finish() +{ + for (auto i = dataSource2ClockIdMap_.begin(); i != dataSource2ClockIdMap_.end(); i++) { + if (i->second) { // ignore the empty datasource, for which the clockid is default TS_CLOCK_UNKNOW 0 + dataSourceNames_.emplace_back(dataSource2PluginNameMap_.at(i->first)); + clockIds_.emplace_back(i->second); + } + } +} +void DataSourceClockIdData::SetDataSourceClockId(DataSourceType source, uint32_t id) +{ + dataSource2ClockIdMap_.at(source) = id; +} + +StatAndInfo::StatAndInfo() +{ + // sched_switch_received | sched_switch_not_match | sched_switch_not_not_supported etc. + for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + event_[i] = config_.eventNameMap_.at(static_cast(i)); + } + for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + stat_[j] = config_.eventErrorDescMap_.at(static_cast(j)); + } + + for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + statSeverity_[i][j] = config_.eventParserStatSeverityDescMap_.at(static_cast(i)) + .at(static_cast(j)); + } + } + + for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + statSeverityDesc_[i][j] = config_.serverityLevelDescMap_.at(statSeverity_[i][j]); + } + } + + for (int32_t i = TRACE_EVENT_START; i < TRACE_EVENT_MAX; i++) { + for (int32_t j = STAT_EVENT_START; j < STAT_EVENT_MAX; j++) { + statCount_[i][j] = 0; + } + } + clockid2ClockNameMap_ = { + {TS_CLOCK_UNKNOW, "unknown"}, {TS_CLOCK_BOOTTIME, "boottime"}, + {TS_CLOCK_REALTIME, "realtime"}, {TS_CLOCK_REALTIME_COARSE, "realtime_corse"}, + {TS_MONOTONIC, "monotonic"}, {TS_MONOTONIC_COARSE, "monotonic-coarse"}, + {TS_MONOTONIC_RAW, "monotonic-raw"}, + }; +} +void StatAndInfo::IncreaseStat(SupportedTraceEventType eventType, StatType type) +{ +#ifdef SUPPORTTHREAD + std::lock_guard lockGurand(spinlock_); +#endif + statCount_[eventType][type]++; +} +const uint32_t& StatAndInfo::GetValue(SupportedTraceEventType eventType, StatType type) const +{ + return statCount_[eventType][type]; +} +const std::string& StatAndInfo::GetEvent(SupportedTraceEventType eventType) const +{ + return event_[eventType]; +} +const std::string& StatAndInfo::GetStat(StatType type) const +{ + return stat_[type]; +} +const std::string& StatAndInfo::GetSeverityDesc(SupportedTraceEventType eventType, StatType type) const +{ + return statSeverityDesc_[eventType][type]; +} +const StatSeverityLevel& StatAndInfo::GetSeverity(SupportedTraceEventType eventType, StatType type) const +{ + return statSeverity_[eventType][type]; +} + +uint64_t SymbolsData::Size() const +{ + return addrs_.size(); +} +void SymbolsData::UpdateSymbol(uint64_t addr, DataIndex funcNameDictIndex) +{ + if (symbolsMap_.find(addr) == symbolsMap_.end()) { + symbolsMap_.insert(std::make_pair(addr, funcNameDictIndex)); + addrs_.emplace_back(addr); + funcName_.emplace_back(funcNameDictIndex); + } else { + symbolsMap_.at(addr) = funcNameDictIndex; + } +} +const DataIndex& SymbolsData::GetFunc(uint64_t addr) const +{ + if (symbolsMap_.find(addr) == symbolsMap_.end()) { + auto lastAddr = symbolsMap_.lower_bound(addr); + if (lastAddr == symbolsMap_.end()) { + return INVALID_UINT64; + } + return lastAddr->second; + } else { + return symbolsMap_.at(addr); + } +} +const std::deque& SymbolsData::GetConstFuncNames() const +{ + return funcName_; +} +const std::deque& SymbolsData::GetConstAddrs() const +{ + return addrs_; +} + +void DataType::UpdateNewDataType(BaseDataType dataType, DataIndex dataDescIndex) +{ + if (typeToDesc_.count(dataType) == 0) { + dataTypes_.emplace_back(dataType); + descs_.emplace_back(dataDescIndex); + } +} +const std::deque& DataType::DataTypes() const +{ + return dataTypes_; +} +const std::deque& DataType::DataDesc() const +{ + return descs_; +} + +size_t ArgSet::AppendNewArg(DataIndex nameId, BaseDataType dataType, int64_t value, size_t argSet) +{ + dataTypes_.emplace_back(dataType); + argset_.emplace_back(argSet); + ids_.emplace_back(id_++); + values_.emplace_back(value); + names_.emplace_back(nameId); + return Size() - 1; +} +const std::deque& ArgSet::DataTypes() const +{ + return dataTypes_; +} +const std::deque& ArgSet::ValuesData() const +{ + return values_; +} +const std::deque& ArgSet::ArgsData() const +{ + return argset_; +} +const std::deque& ArgSet::NamesData() const +{ + return names_; +} + +void TraceConfig::AppendNewData(std::string traceSource, std::string key, std::string value) +{ + traceSource_.emplace_back(traceSource); + key_.emplace_back(key); + value_.emplace_back(value); + ids_.emplace_back(rowCounts_); + rowCounts_++; +} +const std::deque& TraceConfig::TraceSource() const +{ + return traceSource_; +} +const std::deque& TraceConfig::Key() const +{ + return key_; +} +const std::deque& TraceConfig::Value() const +{ + return value_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/common_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/common_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..bc598120305f008c14e417fb042d334f99eaa0fe --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/common_stdtype.h @@ -0,0 +1,303 @@ +/* + * 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 COMMON_STDTYPE_H +#define COMMON_STDTYPE_H + +#include +#include +#include +#include "base_stdtype.h" +#include "cfg/trace_streamer_config.h" + +namespace SysTuning { +namespace TraceStdtype { +using namespace SysTuning::TraceCfg; +using namespace SysTuning::TraceStreamer; +constexpr int32_t MAX_SIZE_LEN = 80; +class Thread { +public: + explicit Thread(uint32_t t) : tid_(t) {} + InternalPid internalPid_ = INVALID_UINT32; + uint32_t tid_ = 0; + DataIndex nameIndex_ = 0; + InternalTime startT_ = 0; + InternalTime endT_ = 0; + uint32_t switchCount_ = 0; + uint32_t sliceSize_ = 0; + uint32_t cpuStatesCount_ = 0; +}; + +class Process { +public: + explicit Process(uint32_t p) : pid_(p) {} + std::string cmdLine_ = ""; + InternalTime startT_ = 0; + uint32_t pid_ = 0; + uint32_t memSize_ = 0; + uint32_t threadSize_ = 0; + uint32_t sliceSize_ = 0; + uint32_t switchCount_ = 0; + int32_t threadCount_ = -1; + uint32_t cpuStatesCount_ = 0; +}; + +class DataDict { +public: + size_t Size() const + { + return dataDict_.size(); + } + DataIndex GetStringIndex(std::string_view str); + DataIndex GetStringIndexNoWrite(std::string_view str) const; + const std::string& GetDataFromDict(DataIndex id) const + { + TS_ASSERT(id < dataDict_.size()); + return dataDict_[id]; + } + void Finish(); + void Clear() + { + dataDict_.clear(); + } + +public: + std::deque dataDict_; + std::unordered_map dataDictInnerMap_; + +private: + std::hash hashFun; + std::mutex mutex_; + const int8_t SPASCII_START = 0; + const int8_t SPASCII_END = 32; +}; + +class MetaData { +public: + MetaData(); + ~MetaData() = default; + void SetTraceType(const std::string& traceType); + void SetSourceFileName(const std::string& fileName); + void SetOutputFileName(const std::string& fileName); + void SetParserToolVersion(const std::string& version); + void SetParserToolPublishDateTime(const std::string& datetime); + void SetTraceDataSize(uint64_t dataSize); + void SetTraceDuration(uint64_t dur); + const std::string& Value(uint64_t row) const; + const std::string& Name(uint64_t row) const; + void Clear() + { + columnNames_.clear(); + values_.clear(); + } + +private: + const std::string METADATA_ITEM_DATASIZE_COLNAME = "datasize"; + const std::string METADATA_ITEM_PARSETOOL_NAME_COLNAME = "parse_tool"; + const std::string METADATA_ITEM_PARSERTOOL_VERSION_COLNAME = "tool_version"; + const std::string METADATA_ITEM_PARSERTOOL_PUBLISH_DATETIME_COLNAME = "tool_publish_time"; + const std::string METADATA_ITEM_SOURCE_FILENAME_COLNAME = "source_name"; + const std::string METADATA_ITEM_OUTPUT_FILENAME_COLNAME = "output_name"; + const std::string METADATA_ITEM_PARSERTIME_COLNAME = "runtime"; + const std::string METADATA_ITEM_TRACE_DURATION_COLNAME = "trace_duration"; + const std::string METADATA_ITEM_SOURCE_DATETYPE_COLNAME = "source_type"; + std::deque columnNames_ = {}; + std::deque values_ = {}; +}; + +class ClockSnapshotData { +public: + size_t AppendNewSnapshot(uint8_t clockId, uint64_t ts, const std::string& name) + { + clockIds_.emplace_back(clockId); + ts_.emplace_back(ts); + names_.emplace_back(name); + return ts_.size(); + } + size_t Size() const + { + return ts_.size(); + } + const std::deque& ClockIds() const + { + return clockIds_; + } + const std::deque& Ts() const + { + return ts_; + } + const std::deque& Names() const + { + return names_; + } + +private: + std::deque clockIds_ = {}; + std::deque ts_ = {}; + std::deque names_ = {}; +}; + +class DataSourceClockIdData { +public: + DataSourceClockIdData(); + size_t AppendNewDataSourceClockId(const std::string& dataSoruceName, uint8_t clockId) + { + dataSourceNames_.emplace_back(dataSoruceName); + clockIds_.emplace_back(clockId); + return dataSourceNames_.size(); + } + size_t Size() const + { + return dataSourceNames_.size(); + } + const std::deque& ClockIds() const + { + return clockIds_; + } + const std::deque& Names() const + { + return dataSourceNames_; + } + void SetDataSourceClockId(DataSourceType source, uint32_t id); + void Finish(); + +private: + std::deque dataSourceNames_ = {}; + std::deque clockIds_ = {}; + std::map dataSource2ClockIdMap_ = {}; + std::map dataSource2PluginNameMap_ = {}; +}; + +class StatAndInfo { +public: + StatAndInfo(); + ~StatAndInfo() = default; + void IncreaseStat(SupportedTraceEventType eventType, StatType type); + const uint32_t& GetValue(SupportedTraceEventType eventType, StatType type) const; + const std::string& GetEvent(SupportedTraceEventType eventType) const; + const std::string& GetStat(StatType type) const; + const std::string& GetSeverityDesc(SupportedTraceEventType eventType, StatType type) const; + const StatSeverityLevel& GetSeverity(SupportedTraceEventType eventType, StatType type) const; + std::map clockid2ClockNameMap_ = {}; + +private: + uint32_t statCount_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; + std::string event_[TRACE_EVENT_MAX]; + std::string stat_[STAT_EVENT_MAX]; + std::string statSeverityDesc_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; + StatSeverityLevel statSeverity_[TRACE_EVENT_MAX][STAT_EVENT_MAX]; + TraceStreamerConfig config_{}; +#ifdef SUPPORTTHREAD + SpinLock spinlock_; +#endif +}; + +class SymbolsData { +public: + SymbolsData() = default; + ~SymbolsData() = default; + uint64_t Size() const; + void UpdateSymbol(uint64_t addr, DataIndex funcNameDictIndex); + const DataIndex& GetFunc(uint64_t addr) const; + const std::deque& GetConstFuncNames() const; + const std::deque& GetConstAddrs() const; + void Clear() + { + addrs_.clear(); + funcName_.clear(); + symbolsMap_.clear(); + } + +private: + std::deque addrs_ = {}; + std::deque funcName_ = {}; + std::map symbolsMap_ = {}; +}; + +class DataType { +public: + void UpdateNewDataType(BaseDataType dataType, DataIndex dataDescIndex); + const std::deque& DataTypes() const; + const std::deque& DataDesc() const; + size_t Size() const + { + return typeToDesc_.size(); + } + void Clear() + { + dataTypes_.clear(); + descs_.clear(); + typeToDesc_.clear(); + } + +private: + std::deque dataTypes_ = {}; + std::deque descs_ = {}; + std::unordered_map typeToDesc_ = {}; +}; + +class ArgSet : public CacheBase, public BatchCacheBase { +public: + size_t AppendNewArg(DataIndex nameId, BaseDataType dataType, int64_t value, size_t argSet); + const std::deque& DataTypes() const; + const std::deque& ValuesData() const; + const std::deque& ArgsData() const; + const std::deque& NamesData() const; + + void Clear() override + { + CacheBase::Clear(); + names_.clear(); + dataTypes_.clear(); + values_.clear(); + argset_.clear(); + } + void ClearExportedData() override + { + EraseElements(ids_, names_, dataTypes_, values_, argset_); + } + +private: + std::deque names_ = {}; + std::deque dataTypes_ = {}; + std::deque values_ = {}; + std::deque argset_ = {}; +}; + +// memory-plugin and hisysevent update this +class TraceConfig : public CacheBase { +public: + void AppendNewData(std::string traceSource, std::string key, std::string value); + const std::deque& TraceSource() const; + const std::deque& Key() const; + const std::deque& Value() const; + void Clear() override + { + CacheBase::Clear(); + traceSource_.clear(); + key_.clear(); + value_.clear(); + } + +private: + std::deque traceSource_ = {}; + std::deque key_ = {}; + std::deque value_ = {}; + uint32_t rowCounts_ = 0; +}; +} // namespace TraceStdtype +} // namespace SysTuning + +#endif // COMMON_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/callstack_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/ftrace/callstack_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d474786d17de1b3af32ab860112253a16766fe4 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/callstack_stdtype.cpp @@ -0,0 +1,194 @@ +/* + * 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 "callstack_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t CallStack::AppendInternalAsyncSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + uint16_t nameIdentify, + DataIndex name, + uint8_t depth, + uint64_t cookid, + const std::optional& parentId) +{ + AppendCommonInfo(startT, durationNs, internalTid); + AppendCallStack(cat, name, depth, parentId); + AppendDistributeInfo(); + cookies_.emplace_back(cookid); + ids_.emplace_back(id_++); + identifys_.emplace_back(nameIdentify + depth); + return Size() - 1; +} +size_t CallStack::AppendInternalSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + uint16_t nameIdentify, + DataIndex name, + uint8_t depth, + const std::optional& parentId) +{ + AppendCommonInfo(startT, durationNs, internalTid); + AppendCallStack(cat, name, depth, parentId); + identifys_.emplace_back(nameIdentify + depth); + ids_.emplace_back(id_++); + cookies_.emplace_back(INVALID_UINT64); + AppendDistributeInfo(); + return Size() - 1; +} + +void CallStack::AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid) +{ + timeStamps_.emplace_back(startT); + durs_.emplace_back(durationNs); + callIds_.emplace_back(internalTid); +} +void CallStack::AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, std::optional parentId) +{ + parentIds_.emplace_back(parentId); + cats_.emplace_back(cat); + names_.emplace_back(name); + depths_.emplace_back(depth); +} +void CallStack::SetDistributeInfo(size_t index, + const std::string& chainId, + const std::string& spanId, + const std::string& parentSpanId, + const std::string& flag, + const std::string& args) +{ + chainIds_[index] = chainId; + spanIds_[index] = spanId; + parentSpanIds_[index] = parentSpanId; + flags_[index] = flag; + args_[index] = args; + argSet_[index] = INVALID_UINT32; +} +void CallStack::AppendDistributeInfo(const std::string& chainId, + const std::string& spanId, + const std::string& parentSpanId, + const std::string& flag, + const std::string& args) +{ + chainIds_.emplace_back(chainId); + spanIds_.emplace_back(spanId); + parentSpanIds_.emplace_back(parentSpanId); + flags_.emplace_back(flag); + args_.emplace_back(args); + argSet_.emplace_back(INVALID_UINT32); +} +void CallStack::AppendDistributeInfo() +{ + chainIds_.emplace_back(""); + spanIds_.emplace_back(""); + parentSpanIds_.emplace_back(""); + flags_.emplace_back(""); + args_.emplace_back(""); + argSet_.emplace_back(INVALID_UINT32); +} +void CallStack::SetDuration(size_t index, uint64_t timeStamp) +{ + durs_[index] = timeStamp - timeStamps_[index]; +} +void CallStack::SetDurationWithFlag(size_t index, uint64_t timeStamp) +{ + durs_[index] = timeStamp - timeStamps_[index]; + flags_[index] = "1"; +} + +void CallStack::SetFlag(size_t index, uint8_t flag) +{ + flags_[index] = std::to_string(flag); +} +void CallStack::SetDurationEx(size_t index, uint32_t dur) +{ + durs_[index] = dur; +} + +void CallStack::SetIrqDurAndArg(size_t index, uint64_t timeStamp, uint32_t argSetId) +{ + SetDuration(index, timeStamp); + argSet_[index] = argSetId; +} +void CallStack::SetTimeStamp(size_t index, uint64_t timeStamp) +{ + timeStamps_[index] = timeStamp; +} + +void CallStack::SetDepth(size_t index, uint8_t depth) +{ + depths_[index] = depth; +} +void CallStack::SetArgSetId(size_t index, uint32_t argSetId) +{ + argSet_[index] = argSetId; +} +const std::deque>& CallStack::ParentIdData() const +{ + return parentIds_; +} +const std::deque& CallStack::CatsData() const +{ + return cats_; +} +const std::deque& CallStack::IdentifysData() const +{ + return identifys_; +} +const std::deque& CallStack::NamesData() const +{ + return names_; +} +const std::deque& CallStack::Depths() const +{ + return depths_; +} +const std::deque& CallStack::Cookies() const +{ + return cookies_; +} +const std::deque& CallStack::CallIds() const +{ + return callIds_; +} +const std::deque& CallStack::ChainIds() const +{ + return chainIds_; +} +const std::deque& CallStack::SpanIds() const +{ + return spanIds_; +} +const std::deque& CallStack::ParentSpanIds() const +{ + return parentSpanIds_; +} +const std::deque& CallStack::Flags() const +{ + return flags_; +} +const std::deque& CallStack::ArgsData() const +{ + return args_; +} +const std::deque& CallStack::ArgSetIdsData() const +{ + return argSet_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/callstack_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/callstack_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..4c79cddac9f000d0d14d9243386546c5bd08d106 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/callstack_stdtype.h @@ -0,0 +1,118 @@ +/* + * 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 CALLSTACK_STDTYPE_H +#define CALLSTACK_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class CallStack : public CacheBase, public CpuCacheBase, public BatchCacheBase { +public: + size_t AppendInternalAsyncSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + uint16_t nameIdentify, + DataIndex name, + uint8_t depth, + uint64_t cookid, + const std::optional& parentId); + size_t AppendInternalSlice(uint64_t startT, + uint64_t durationNs, + InternalTid internalTid, + DataIndex cat, + uint16_t nameIdentify, + DataIndex name, + uint8_t depth, + const std::optional& parentId); + void SetDistributeInfo(size_t index, + const std::string& chainId, + const std::string& spanId, + const std::string& parentSpanId, + const std::string& flag, + const std::string& args); + void AppendDistributeInfo(const std::string& chainId, + const std::string& spanId, + const std::string& parentSpanId, + const std::string& flag, + const std::string& args); + void AppendDistributeInfo(); + void SetDuration(size_t index, uint64_t timeStamp); + void SetDurationWithFlag(size_t index, uint64_t timeStamp); + void SetFlag(size_t index, uint8_t flag); + void SetDurationEx(size_t index, uint32_t dur); + void SetIrqDurAndArg(size_t index, uint64_t timeStamp, uint32_t argSetId); + void SetTimeStamp(size_t index, uint64_t timeStamp); + void SetDepth(size_t index, uint8_t depth); + void SetArgSetId(size_t index, uint32_t argSetId); + void Clear() override + { + CacheBase::Clear(); + CpuCacheBase::Clear(); + cats_.clear(); + cookies_.clear(); + callIds_.clear(); + names_.clear(); + depths_.clear(); + chainIds_.clear(); + spanIds_.clear(); + parentSpanIds_.clear(); + flags_.clear(); + args_.clear(); + argSet_.clear(); + } + void ClearExportedData() override + { + EraseElements(timeStamps_, ids_, durs_, cats_, cookies_, callIds_, names_, depths_, chainIds_, spanIds_, + parentSpanIds_, flags_, args_, argSet_); + } + const std::deque>& ParentIdData() const; + const std::deque& CatsData() const; + const std::deque& NamesData() const; + const std::deque& Depths() const; + const std::deque& Cookies() const; + const std::deque& CallIds() const; + const std::deque& IdentifysData() const; + const std::deque& ChainIds() const; + const std::deque& SpanIds() const; + const std::deque& ParentSpanIds() const; + const std::deque& Flags() const; + const std::deque& ArgsData() const; + const std::deque& ArgSetIdsData() const; + +private: + void AppendCommonInfo(uint64_t startT, uint64_t durationNs, InternalTid internalTid); + void AppendCallStack(DataIndex cat, DataIndex name, uint8_t depth, std::optional parentId); + +private: + std::deque> parentIds_; + std::deque cats_ = {}; + std::deque cookies_ = {}; + std::deque callIds_ = {}; + std::deque identifys_ = {}; + std::deque names_ = {}; + std::deque depths_ = {}; + + std::deque chainIds_ = {}; + std::deque spanIds_ = {}; + std::deque parentSpanIds_ = {}; + std::deque flags_ = {}; + std::deque args_ = {}; + std::deque argSet_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // CALLSTACK_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/render_service_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/ftrace/render_service_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa5b708f25fe18276fcfdb1ae39023b8f593d961 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/render_service_stdtype.cpp @@ -0,0 +1,219 @@ +/* + * 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 "render_service_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t FrameSlice::AppendFrame(uint64_t ts, uint32_t ipid, uint32_t itid, uint32_t vsyncId, uint64_t callStackSliceId) +{ + timeStamps_.emplace_back(ts); + ipids_.emplace_back(ipid); + internalTids_.emplace_back(itid); + vsyncIds_.emplace_back(vsyncId); + callStackIds_.emplace_back(callStackSliceId); + endTss_.emplace_back(INVALID_UINT64); + dsts_.emplace_back(INVALID_UINT64); + ids_.emplace_back(ids_.size()); + durs_.emplace_back(INVALID_UINT64); + types_.emplace_back(0); + flags_.emplace_back(INVALID_UINT8); + srcs_.emplace_back(""); + depths_.emplace_back(0); + frameNos_.emplace_back(0); + return Size() - 1; +} +size_t FrameSlice::AppendFrame(uint64_t ts, + uint32_t ipid, + uint32_t itid, + uint32_t vsyncId, + uint64_t callStackSliceId, + uint64_t end, + uint8_t type) +{ + auto row = AppendFrame(ts, ipid, itid, vsyncId, callStackSliceId); + SetEndTime(row, end); + SetType(row, type); + depths_.emplace_back(0); + frameNos_.emplace_back(0); + durs_[row] = end - ts; + return row; +} + +void FrameSlice::UpdateDepth() +{ + DoubleMap>> ipidAndTypesToVEndTime(nullptr); + for (auto row = 0; row < Size(); row++) { + if (flags_[row] == flagValue_) { + continue; + } + auto endTime = timeStamps_[row] + durs_[row]; + auto vEndTimes = ipidAndTypesToVEndTime.Find(ipids_[row], types_[row]); + auto depth = 0; + if (!vEndTimes) { + vEndTimes = std::make_shared>(); + vEndTimes->push_back(endTime); + ipidAndTypesToVEndTime.Insert(ipids_[row], types_[row], vEndTimes); + depths_[row] = depth; + continue; + } + for (; depth < vEndTimes->size(); depth++) { + if (timeStamps_[row] > vEndTimes->at(depth)) { + depths_[row] = depth; + vEndTimes->at(depth) = endTime; + break; + } + } + if (depth == vEndTimes->size()) { + depths_[row] = depth; + vEndTimes->push_back(endTime); + } + } +} + +void FrameSlice::SetEndTime(uint64_t row, uint64_t end) +{ + endTss_[row] = end; +} +void FrameSlice::SetType(uint64_t row, uint8_t type) +{ + types_[row] = type; +} +void FrameSlice::SetDst(uint64_t row, uint64_t dst) +{ + dsts_[row] = dst; +} + +void FrameSlice::SetSrcs(uint64_t row, const std::vector& fromSlices) +{ + std::string s = ""; + for (auto&& i : fromSlices) { + s += std::to_string(i) + ","; + } + s.pop_back(); + srcs_[row] = s; +} +void FrameSlice::SetFlags(uint64_t row, const uint32_t flags) +{ + flags_[row] = flags; +} +const std::deque FrameSlice::Ipids() const +{ + return ipids_; +} +const std::deque FrameSlice::VsyncIds() const +{ + return vsyncIds_; +} +const std::deque FrameSlice::CallStackIds() const +{ + return callStackIds_; +} +const std::deque FrameSlice::EndTss() const +{ + return endTss_; +} +const std::deque FrameSlice::Dsts() const +{ + return dsts_; +} +const std::deque FrameSlice::Durs() const +{ + return durs_; +} +const std::deque FrameSlice::Types() const +{ + return types_; +} +const std::deque FrameSlice::Flags() const +{ + return flags_; +} + +const std::deque FrameSlice::Depths() const +{ + return depths_; +} +const std::deque FrameSlice::FrameNos() const +{ + return frameNos_; +} +const std::deque& FrameSlice::Srcs() const +{ + return srcs_; +} +void FrameSlice::UpdateCallStackSliceId(uint64_t row, uint64_t callStackSliceId) +{ + callStackIds_[row] = callStackSliceId; +} +void FrameSlice::SetEndTimeAndFlag(uint64_t row, uint64_t ts, uint64_t expectDur, uint64_t expectEnd) +{ + Unused(expectDur); + durs_[row] = ts - timeStamps_[row]; + if (flags_[row] != abnormalStartEndTimeState_) { + flags_[row] = expectEnd >= ts ? 0 : 1; + } +} +void FrameSlice::Erase(uint64_t row) +{ + flags_[row] = invalidRow_; +} + +size_t GPUSlice::AppendNew(uint32_t frameRow, uint64_t dur) +{ + frameRows_.emplace_back(frameRow); + durs_.emplace_back(dur); + return Size() - 1; +} +const std::deque& GPUSlice::FrameRows() const +{ + return frameRows_; +} +const std::deque& GPUSlice::Durs() const +{ + return durs_; +} +size_t GPUSlice::Size() const +{ + return durs_.size(); +} + +size_t FrameMaps::AppendNew(FrameSlice* frameSlice, uint64_t src, uint64_t dst) +{ + timeStamps_.emplace_back(0); + ids_.emplace_back(ids_.size()); + srcs_.emplace_back(src); + dsts_.emplace_back(dst); + if (frameSlice->Types().at(dst) == FrameSlice::EXPECT_SLICE) { + uint64_t expRsStartTime = frameSlice->TimeStampData().at(dst); + uint64_t expUiEndTime = frameSlice->TimeStampData().at(src) + frameSlice->Durs().at(src); + if (std::abs(static_cast(expRsStartTime - expUiEndTime)) >= ONE_MILLION_NANOSECONDS) { + auto acturalRow = dst - 1; + frameSlice->SetFlags(acturalRow, FrameSlice::GetAbnormalStartEndTimeState()); + } + } + + return Size() - 1; +} +const std::deque& FrameMaps::SrcIndexs() const +{ + return srcs_; +} +const std::deque& FrameMaps::DstIndexs() const +{ + return dsts_; +} + +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/render_service_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/render_service_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..1302ec9b61491845387b03e0ceb8304779fcd5d3 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/render_service_stdtype.h @@ -0,0 +1,115 @@ +/* + * 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 RENDER_SERVICE_STDTYPE_H +#define RENDER_SERVICE_STDTYPE_H +#include +#include +#include "base_stdtype.h" +#include "double_map.h" + +namespace SysTuning { +namespace TraceStdtype { +using namespace SysTuning::TraceStreamer; +class FrameSlice : public CacheBase, public BatchCacheBase { +public: + size_t AppendFrame(uint64_t ts, uint32_t ipid, uint32_t itid, uint32_t vsyncId, uint64_t callStackSliceId); + size_t AppendFrame(uint64_t ts, + uint32_t ipid, + uint32_t itid, + uint32_t vsyncId, + uint64_t callStackSliceId, + uint64_t end, + uint8_t type); + void SetEndTime(uint64_t row, uint64_t end); + void SetType(uint64_t row, uint8_t type); + void SetDst(uint64_t row, uint64_t dst); + void SetSrcs(uint64_t row, const std::vector& fromSlices); + void SetFlags(uint64_t row, const uint32_t flags); + void UpdateDepth(); + const std::deque Ipids() const; + const std::deque VsyncIds() const; + const std::deque CallStackIds() const; + const std::deque EndTss() const; + const std::deque Dsts() const; + const std::deque Durs() const; + const std::deque Types() const; + const std::deque Flags() const; + const std::deque Depths() const; + const std::deque FrameNos() const; + const std::deque& Srcs() const; + void UpdateCallStackSliceId(uint64_t row, uint64_t callStackSliceId); + void SetEndTimeAndFlag(uint64_t row, uint64_t ts, uint64_t expectDur, uint64_t expectEnd); + void Erase(uint64_t row); + static uint32_t GetAbnormalStartEndTimeState() + { + return abnormalStartEndTimeState_; + } + void ClearExportedData() override + { + EraseElements(internalTids_, timeStamps_, ids_, ipids_, dsts_, srcs_, vsyncIds_, callStackIds_, endTss_, durs_, + types_, flags_, depths_, frameNos_); + } + +public: + typedef enum FrameSliceType { ACTURAL_SLICE, EXPECT_SLICE } FrameSliceType; + +private: + std::deque ipids_ = {}; + std::deque dsts_ = {}; + std::deque srcs_ = {}; + std::deque vsyncIds_ = {}; + std::deque callStackIds_ = {}; + std::deque endTss_ = {}; + std::deque durs_ = {}; + std::deque types_ = {}; + std::deque flags_ = {}; + std::deque depths_ = {}; + std::deque frameNos_ = {}; + const uint32_t invalidRow_ = 2; + static const uint32_t abnormalStartEndTimeState_ = 3; + const uint8_t flagValue_ = 2; +}; + +class GPUSlice : public BatchCacheBase { +public: + size_t AppendNew(uint32_t frameRow, uint64_t dur); + const std::deque& FrameRows() const; + const std::deque& Durs() const; + size_t Size() const; + void ClearExportedData() override + { + EraseElements(frameRows_, durs_); + } + +private: + std::deque frameRows_ = {}; + std::deque durs_ = {}; +}; + +class FrameMaps : public CacheBase { +public: + size_t AppendNew(FrameSlice* frameSlice, uint64_t src, uint64_t dst); + const std::deque& SrcIndexs() const; + const std::deque& DstIndexs() const; + +private: + std::deque srcs_ = {}; + std::deque dsts_ = {}; +}; + +} // namespace TraceStdtype +} // namespace SysTuning +#endif // RENDER_SERVICE_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/sched_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/ftrace/sched_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a8d2b26ce32fd404971a5f3e07f8b80a52cda1b --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/sched_stdtype.cpp @@ -0,0 +1,183 @@ +/* + * 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 "sched_stdtype.h" +namespace SysTuning { +namespace TraceStdtype { +TableRowId ThreadStateData::AppendThreadState(InternalTime ts, + InternalTime dur, + InternalCpu cpu, + InternalTid itid, + TableRowId idState) +{ + timeStamps_.emplace_back(ts); + durations_.emplace_back(dur); + itids_.emplace_back(itid); + tids_.emplace_back(INVALID_UINT32); + pids_.emplace_back(INVALID_UINT32); + states_.emplace_back(idState); + cpus_.emplace_back(cpu); + argSetIds_.emplace_back(INVALID_UINT32); + return itids_.size() - 1; +} + +void ThreadStateData::SetDuration(TableRowId index, InternalTime dur) +{ + durations_[index] = dur; +} + +void ThreadStateData::SortAllRowByTs() +{ + std::deque timeStampsTemp; + timeStampsTemp = std::move(timeStamps_); + std::multimap timeStampsToIdMap = {}; + for (auto id = 0; id < timeStampsTemp.size(); ++id) { + timeStampsToIdMap.insert({timeStampsTemp[id], id}); + } + std::deque durationsTemp; + std::deque itidsTemp; + std::deque tidsTemp; + std::deque pidsTemp; + std::deque statesTemp; + std::deque cpusTemp; + std::deque argSetIdsTemp; + durationsTemp = std::move(durations_); + itidsTemp = std::move(itids_); + tidsTemp = std::move(tids_); + pidsTemp = std::move(pids_); + statesTemp = std::move(states_); + cpusTemp = std::move(cpus_); + argSetIdsTemp = std::move(argSetIds_); + for (auto itor = timeStampsToIdMap.begin(); itor != timeStampsToIdMap.end(); itor++) { + timeStamps_.emplace_back(timeStampsTemp[itor->second]); + durations_.emplace_back(durationsTemp[itor->second]); + itids_.emplace_back(itidsTemp[itor->second]); + tids_.emplace_back(tidsTemp[itor->second]); + pids_.emplace_back(pidsTemp[itor->second]); + states_.emplace_back(statesTemp[itor->second]); + cpus_.emplace_back(cpusTemp[itor->second]); + argSetIds_.emplace_back(argSetIdsTemp[itor->second]); + } +} + +TableRowId ThreadStateData::UpdateDuration(TableRowId index, InternalTime ts) +{ + if (durations_[index] == INVALID_TIME) { + durations_[index] = ts - timeStamps_[index]; + } + return itids_[index]; +} + +bool ThreadStateData::End(TableRowId index, InternalTime ts) +{ + if (durations_[index] == INVALID_TIME) { + durations_[index] = -1; + return false; + } + return true; +} +void ThreadStateData::UpdateState(TableRowId index, TableRowId idState) +{ + states_[index] = idState; +} +void ThreadStateData::SetArgSetId(TableRowId index, uint32_t setId) +{ + argSetIds_[index] = setId; +} + +void ThreadStateData::UpdateDuration(TableRowId index, InternalTime ts, TableRowId idState) +{ + durations_[index] = ts - timeStamps_[index]; + states_[index] = idState; +} + +void ThreadStateData::UpdateTidAndPid(TableRowId index, InternalTid tid, InternalTid pid) +{ + tids_[index] = tid; + pids_[index] = pid; +} + +TableRowId ThreadStateData::UpdateDuration(TableRowId index, InternalTime ts, InternalCpu cpu, TableRowId idState) +{ + cpus_[index] = cpu; + durations_[index] = ts - timeStamps_[index]; + states_[index] = idState; + return itids_[index]; +} + +size_t SchedSlice::AppendSchedSlice(uint64_t ts, + uint64_t dur, + uint64_t cpu, + uint32_t internalTid, + uint64_t endState, + uint64_t priority) +{ + timeStamps_.emplace_back(ts); + durs_.emplace_back(dur); + cpus_.emplace_back(cpu); + tsEnds_.emplace_back(0); + internalTids_.emplace_back(internalTid); + endStates_.emplace_back(endState); + priority_.emplace_back(priority); + argSets_.emplace_back(INVALID_UINT32); + internalPids_.emplace_back(INVALID_UINT32); + return Size() - 1; +} + +void SchedSlice::SetDuration(size_t index, uint64_t duration) +{ + durs_[index] = duration; + tsEnds_[index] = timeStamps_[index] + duration; +} + +void SchedSlice::Update(uint64_t index, uint64_t ts, uint64_t state) +{ + durs_[index] = ts - timeStamps_[index]; + endStates_[index] = state; +} + +void SchedSlice::UpdateEndState(uint64_t index, uint64_t state) +{ + endStates_[index] = state; +} + +void SchedSlice::UpdateArg(uint64_t index, uint32_t argsetId) +{ + argSets_[index] = argsetId; +} + +size_t Raw::AppendRawData(uint64_t timeStamp, uint32_t name, uint32_t cpu, uint32_t internalTid) +{ + ids_.emplace_back(id_++); + timeStamps_.emplace_back(timeStamp); + nameDeque_.emplace_back(name); + cpuDeque_.emplace_back(cpu); + internalTids_.emplace_back(internalTid); + return Size() - 1; +} + +size_t Instants::AppendInstantEventData(uint64_t timeStamp, + DataIndex nameIndex, + int64_t internalTid, + int64_t wakeupFromInternalPid) +{ + internalTids_.emplace_back(internalTid); + timeStamps_.emplace_back(timeStamp); + NameIndexs_.emplace_back(nameIndex); + wakeupFromInternalPids_.emplace_back(wakeupFromInternalPid); + return Size() - 1; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/sched_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/sched_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..eaef50ed41aca7522a23659825ab8c4c6b75714c --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/sched_stdtype.h @@ -0,0 +1,220 @@ +/* + * 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 SCHED_STDTYPE_H +#define SCHED_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class ThreadStateData : public BatchCacheBase { +public: + TableRowId + AppendThreadState(InternalTime ts, InternalTime dur, InternalCpu cpu, InternalTid itid, TableRowId idState); + void SetDuration(TableRowId index, InternalTime dur); + TableRowId UpdateDuration(TableRowId index, InternalTime ts); + bool End(TableRowId index, InternalTime ts); + void UpdateState(TableRowId index, TableRowId idState); + void SetArgSetId(TableRowId index, uint32_t setId); + void UpdateDuration(TableRowId index, InternalTime ts, TableRowId idState); + void UpdateTidAndPid(TableRowId index, InternalTid tid, InternalTid pid); + TableRowId UpdateDuration(TableRowId index, InternalTime ts, InternalCpu cpu, TableRowId idState); + void SortAllRowByTs(); + void Clear() + { + timeStamps_.clear(); + durations_.clear(); + itids_.clear(); + tids_.clear(); + pids_.clear(); + states_.clear(); + cpus_.clear(); + } + void ClearExportedData() override + { + EraseElements(timeStamps_, durations_, itids_, tids_, pids_, states_, cpus_); + } + uint32_t Size() const + { + return itids_.size(); + } + + const std::deque& TimeStamsData() const + { + return timeStamps_; + } + const std::deque& DursData() const + { + return durations_; + } + const std::deque& ItidsData() const + { + return itids_; + } + const std::deque& TidsData() const + { + return tids_; + } + const std::deque& PidsData() const + { + return pids_; + } + const std::deque& StatesData() const + { + return states_; + } + const std::deque& CpusData() const + { + return cpus_; + } + const std::deque& ArgSetsData() const + { + return argSetIds_; + } + +private: + std::deque timeStamps_; + std::deque durations_; + std::deque itids_; + std::deque tids_; + std::deque pids_; + std::deque states_; + std::deque cpus_; + std::deque argSetIds_; +}; + +class SchedSlice : public CacheBase, public CpuCacheBase, public BatchCacheBase { +public: + size_t AppendSchedSlice(uint64_t ts, + uint64_t dur, + uint64_t cpu, + uint32_t internalTid, + uint64_t endState, + uint64_t priority); + void SetDuration(size_t index, uint64_t duration); + void Update(uint64_t index, uint64_t ts, uint64_t state); + void UpdateEndState(uint64_t index, uint64_t state); + void UpdateArg(uint64_t index, uint32_t argsetId); + + const std::deque& EndStatesData() const + { + return endStates_; + } + + const std::deque& PriorityData() const + { + return priority_; + } + + const std::deque& ArgSetData() const + { + return argSets_; + } + const std::deque& TsEndData() const + { + return tsEnds_; + } + const std::deque& InternalPidsData() const + { + return internalPids_; + } + void ReviseInternalPid(uint32_t row, InternalPid ipid) + { + if (row < internalPids_.size()) { + internalPids_[row] = ipid; + } + } + void Clear() override + { + CacheBase::Clear(); + CpuCacheBase::Clear(); + endStates_.clear(); + priority_.clear(); + internalPids_.clear(); + tsEnds_.clear(); + } + void ClearExportedData() override + { + EraseElements(internalTids_, timeStamps_, durs_, cpus_, endStates_, priority_, internalPids_, tsEnds_); + } + +private: + std::deque internalPids_ = {}; + std::deque tsEnds_ = {}; + std::deque endStates_ = {}; + std::deque priority_ = {}; + std::deque argSets_ = {}; +}; +class Raw : public CacheBase, public BatchCacheBase { +public: + size_t AppendRawData(uint64_t timeStamp, uint32_t name, uint32_t cpu, uint32_t internalTid); + const std::deque& NameData() const + { + return nameDeque_; + } + const std::deque& CpuData() const + { + return cpuDeque_; + } + void Clear() override + { + CacheBase::Clear(); + nameDeque_.clear(); + cpuDeque_.clear(); + } + void ClearExportedData() override + { + EraseElements(internalTids_, timeStamps_, ids_, nameDeque_, cpuDeque_); + } + +private: + std::deque nameDeque_ = {}; + std::deque cpuDeque_ = {}; +}; + +class Instants : public CacheBase, public BatchCacheBase { +public: + size_t AppendInstantEventData(uint64_t timeStamp, + DataIndex nameIndex, + int64_t internalTid, + int64_t wakeupFromInternalPid); + + const std::deque& NameIndexsData() const + { + return NameIndexs_; + } + const std::deque& WakeupFromPidsData() const + { + return wakeupFromInternalPids_; + } + void Clear() override + { + CacheBase::Clear(); + NameIndexs_.clear(); + wakeupFromInternalPids_.clear(); + } + void ClearExportedData() override + { + EraseElements(internalTids_, timeStamps_, NameIndexs_, wakeupFromInternalPids_); + } + +private: + std::deque NameIndexs_; + std::deque wakeupFromInternalPids_; +}; +} // namespace TraceStdtype +} // namespace SysTuning + +#endif // SCHED_STDTYPE_H diff --git a/trace_streamer/src/filter/symbols_filter.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/syscall_stdtype.cpp similarity index 51% rename from trace_streamer/src/filter/symbols_filter.h rename to trace_streamer/src/trace_data/trace_stdtype/ftrace/syscall_stdtype.cpp index 3d9a4524208c6d106728cf78509c07500e60ead7..f99f9d9ce326738ff6359abfb1b5efc192c069a3 100644 --- a/trace_streamer/src/filter/symbols_filter.h +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/syscall_stdtype.cpp @@ -12,31 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef SYMBOLS_FILTER_H -#define SYMBOLS_FILTER_H - -#include -#include "filter_base.h" -#include "trace_data_cache.h" -#include "trace_streamer_filters.h" +#include "syscall_stdtype.h" namespace SysTuning { -namespace TraceStreamer { -class SymbolsFilter : private FilterBase { -public: - SymbolsFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter); - ~SymbolsFilter() override; - - void RegisterFunc(uint64_t addr, DataIndex funcNameDictIndex); - - const DataIndex& GetFunc(uint64_t addr) const; - void Clear(); - -private: - std::map symbolsMap_ = {}; -}; -} // namespace TraceStreamer +namespace TraceStdtype { +size_t SysCall::AppendSysCallData(int64_t sysCallNum, DataIndex type, uint32_t ipid, uint64_t timeStamp, int64_t ret) +{ + sysCallNums_.emplace_back(sysCallNum); + types_.emplace_back(type); + ipids_.emplace_back(ipid); + timeStamps_.emplace_back(timeStamp); + rets_.emplace_back(ret); + return Size() - 1; +} +} // namespace TraceStdtype } // namespace SysTuning - -#endif // SLICE_FILTER_H diff --git a/trace_streamer/sdk/demo_sdk/rpc/http_socket.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/syscall_stdtype.h similarity index 38% rename from trace_streamer/sdk/demo_sdk/rpc/http_socket.h rename to trace_streamer/src/trace_data/trace_stdtype/ftrace/syscall_stdtype.h index 39bf9849c368309b90aec74919d83293acb416d0..be9a7ab016c68f475c0a788665e0692beddae308 100644 --- a/trace_streamer/sdk/demo_sdk/rpc/http_socket.h +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/syscall_stdtype.h @@ -13,41 +13,50 @@ * limitations under the License. */ -#ifndef RPC_HTTPSOCKET_H -#define RPC_HTTPSOCKET_H +#ifndef SYSCALL_STDTYPE_H +#define SYSCALL_STDTYPE_H +#include "base_stdtype.h" -#include namespace SysTuning { -namespace TraceStreamer { -class HttpSocket { +namespace TraceStdtype { +class SysCall : public CacheBase, public BatchCacheBase { public: - HttpSocket() {} - HttpSocket(int32_t sockId, int32_t domain) : sockId_(sockId), domain_(domain) {} - ~HttpSocket(); - - bool CreateSocket(int32_t domain); - bool Bind(int32_t port); - bool Listen(int32_t maxConn); - bool Accept(HttpSocket& client); - bool Recv(void* data, size_t& len); - bool Send(const void* data, size_t len); - void Close(); - bool IsValid() const + size_t AppendSysCallData(int64_t sysCallNum, DataIndex type, uint32_t ipid, uint64_t timeStamp, int64_t ret); + const std::deque& SysCallsData() const + { + return sysCallNums_; + } + const std::deque& TypesData() const + { + return types_; + } + const std::deque& IpidsData() const + { + return ipids_; + } + const std::deque& RetsData() const + { + return rets_; + } + void Clear() override { - return sockId_ != INVALID_SOCKET; + CacheBase::Clear(); + sysCallNums_.clear(); + types_.clear(); + ipids_.clear(); + rets_.clear(); } - int32_t GetFd() const + void ClearExportedData() override { - return sockId_; + EraseElements(timeStamps_, sysCallNums_, types_, ipids_, rets_); } private: - int32_t sockId_ = -1; - int32_t domain_ = 0; - using SOCKET = int32_t; - const int32_t SOCKET_ERROR = -1; - const SOCKET INVALID_SOCKET = -1; + std::deque sysCallNums_ = {}; + std::deque types_ = {}; + std::deque ipids_ = {}; + std::deque rets_ = {}; }; -} // namespace TraceStreamer +} // namespace TraceStdtype } // namespace SysTuning -#endif // RPC_HTTPSOCKET_H +#endif // SYSCALL_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/animation_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/animation_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..417a94a203d14f39f70e117aa302719b7ea739f2 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/animation_stdtype.cpp @@ -0,0 +1,198 @@ +/* + * 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 "animation_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +TableRowId Animation::AppendAnimation(InternalTime inputTime, InternalTime startPoint, DataIndex nameIndex) +{ + inputTimes_.emplace_back(inputTime); + startPoints_.emplace_back(startPoint); + endPoins_.emplace_back(INVALID_TIME); + frameInfos_.emplace_back(INVALID_UINT64); + names_.emplace_back(nameIndex); + ids_.emplace_back(Size()); + return ids_.size() - 1; +} +void Animation::UpdateStartPoint(TableRowId index, InternalTime startPoint) +{ + if (index <= Size()) { + startPoints_[index] = startPoint; + } +} +void Animation::UpdateEndPoint(TableRowId index, InternalTime endPoint) +{ + if (index <= Size()) { + endPoins_[index] = endPoint; + } +} +void Animation::UpdateFrameInfo(TableRowId index, InternalTime frameInfo) +{ + if (index <= Size()) { + frameInfos_[index] = frameInfo; + } +} +size_t Animation::Size() const +{ + return ids_.size(); +} +const std::deque& Animation::InputTimes() const +{ + return inputTimes_; +} +const std::deque& Animation::StartPoints() const +{ + return startPoints_; +} +const std::deque& Animation::EndPoints() const +{ + return endPoins_; +} +const std::deque& Animation::FrameInfos() const +{ + return frameInfos_; +} +const std::deque& Animation::Names() const +{ + return names_; +} +const std::deque& Animation::IdsData() const +{ + return ids_; +} +void Animation::Clear() +{ + inputTimes_.clear(); + startPoints_.clear(); + endPoins_.clear(); + frameInfos_.clear(); + ids_.clear(); +} + +uint32_t DeviceInfo::PhysicalWidth() const +{ + return physicalWidth_; +} +uint32_t DeviceInfo::PhysicalHeight() const +{ + return physicalHeight_; +} +uint32_t DeviceInfo::PhysicalFrameRate() const +{ + return physicalFrameRate_; +} +void DeviceInfo::UpdateWidthAndHeight(const std::smatch& matcheLine) +{ + if (matcheLine.size() > DEVICEINFO_MATCH_LAST) { + uint8_t matcheIndex = 0; + physicalWidth_ = base::StrToInt(matcheLine[++matcheIndex].str()).value(); + physicalHeight_ = base::StrToInt(matcheLine[++matcheIndex].str()).value(); + } +} +void DeviceInfo::UpdateFrameRate(uint32_t frameRate) +{ + physicalFrameRate_ = frameRate; +} +void DeviceInfo::Clear() +{ + physicalWidth_ = INVALID_UINT32; + physicalHeight_ = INVALID_UINT32; + physicalFrameRate_ = INVALID_UINT32; +} + +TableRowId DynamicFrame::AppendDynamicFrame(DataIndex nameId) +{ + names_.emplace_back(nameId); + ids_.emplace_back(Size()); + xs_.emplace_back(INVALID_UINT32); + ys_.emplace_back(INVALID_UINT32); + widths_.emplace_back(INVALID_UINT32); + heights_.emplace_back(INVALID_UINT32); + alphas_.emplace_back(INVALID_UINT64); + endTimes_.emplace_back(INVALID_TIME); + return ids_.size() - 1; +} +void DynamicFrame::UpdateNameIndex(TableRowId index, DataIndex nameId) +{ + if (index <= Size()) { + names_[index] = nameId; + } +} +void DynamicFrame::UpdatePosition(TableRowId index, const std::smatch& matcheLine, DataIndex alpha) +{ + if (index <= Size() && matcheLine.size() > DYNAMICFRAME_MATCH_LAST) { + uint8_t matcheIndex = 0; + xs_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); + ys_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); + widths_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); + heights_[index] = base::StrToInt(matcheLine[++matcheIndex].str()).value(); + alphas_[index] = alpha; + } +} +void DynamicFrame::UpdateEndTime(TableRowId index, InternalTime endTime) +{ + if (index <= Size()) { + endTimes_[index] = endTime; + } +} +size_t DynamicFrame::Size() const +{ + return ids_.size(); +} +const std::deque& DynamicFrame::IdsData() const +{ + return ids_; +} +const std::deque& DynamicFrame::Xs() const +{ + return xs_; +} +const std::deque& DynamicFrame::Ys() const +{ + return ys_; +} +const std::deque& DynamicFrame::Widths() const +{ + return widths_; +} +const std::deque& DynamicFrame::Heights() const +{ + return heights_; +} +const std::deque& DynamicFrame::Alphas() const +{ + return alphas_; +} +const std::deque& DynamicFrame::Names() const +{ + return names_; +} +const std::deque& DynamicFrame::EndTimes() const +{ + return endTimes_; +} +void DynamicFrame::Clear() +{ + xs_.clear(); + ys_.clear(); + widths_.clear(); + heights_.clear(); + alphas_.clear(); + names_.clear(); + endTimes_.clear(); + ids_.clear(); +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/animation_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/animation_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..d75eede809dc000afe3ef5fb8f90787a46771007 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/animation_stdtype.h @@ -0,0 +1,94 @@ +/* + * 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 ANIMATION_STDTYPE_H +#define ANIMATION_STDTYPE_H +#include +#include "base_stdtype.h" +#include "string_to_numerical.h" + +namespace SysTuning { +namespace TraceStdtype { +constexpr uint8_t DEVICEINFO_MATCH_LAST = 2; +class Animation { +public: + TableRowId AppendAnimation(InternalTime inputTime, InternalTime startPoint, DataIndex nameIndex); + void UpdateStartPoint(TableRowId index, InternalTime startPoint); + void UpdateEndPoint(TableRowId index, InternalTime endPoint); + void UpdateFrameInfo(TableRowId index, InternalTime frameInfo); + size_t Size() const; + const std::deque& InputTimes() const; + const std::deque& StartPoints() const; + const std::deque& EndPoints() const; + const std::deque& FrameInfos() const; + const std::deque& Names() const; + const std::deque& IdsData() const; + void Clear(); + +private: + std::deque inputTimes_ = {}; + std::deque startPoints_ = {}; + std::deque endPoins_ = {}; + std::deque frameInfos_ = {}; + std::deque names_ = {}; + std::deque ids_ = {}; +}; + +class DeviceInfo { +public: + uint32_t PhysicalWidth() const; + uint32_t PhysicalHeight() const; + uint32_t PhysicalFrameRate() const; + void UpdateWidthAndHeight(const std::smatch& matcheLine); + void UpdateFrameRate(uint32_t frameRate); + void Clear(); + +private: + uint32_t physicalWidth_ = INVALID_UINT32; + uint32_t physicalHeight_ = INVALID_UINT32; + uint32_t physicalFrameRate_ = INVALID_UINT32; +}; + +class DynamicFrame { +public: + TableRowId AppendDynamicFrame(DataIndex nameId); + void UpdateNameIndex(TableRowId index, DataIndex nameId); + void UpdatePosition(TableRowId index, const std::smatch& matcheLine, DataIndex alpha); + void UpdateEndTime(TableRowId index, InternalTime endTime); + + size_t Size() const; + const std::deque& IdsData() const; + const std::deque& Xs() const; + const std::deque& Ys() const; + const std::deque& Widths() const; + const std::deque& Heights() const; + const std::deque& Alphas() const; + const std::deque& Names() const; + const std::deque& EndTimes() const; + void Clear(); + +private: + std::deque xs_ = {}; + std::deque ys_ = {}; + std::deque widths_ = {}; + std::deque heights_ = {}; + std::deque alphas_ = {}; + std::deque names_ = {}; + std::deque endTimes_ = {}; + std::deque ids_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // ANIMATION_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/app_startup_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/app_startup_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e8b29ea2cde7ddf4992f4c8419bc3c21495819f --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/app_startup_stdtype.cpp @@ -0,0 +1,113 @@ +/* + * 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 "app_startup_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t AppStartup::AppendNewData(uint32_t ipid, + uint32_t tid, + uint32_t callId, + uint64_t startTime, + uint64_t endTime, + uint32_t startName, + DataIndex packedName) +{ + ipids_.emplace_back(ipid); + tids_.emplace_back(tid); + callIds_.emplace_back(callId); + startTimes_.emplace_back(startTime); + endTimes_.emplace_back(endTime); + startNames_.emplace_back(startName); + packedNames_.emplace_back(packedName); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& AppStartup::Pids() const +{ + return ipids_; +} +const std::deque& AppStartup::Tids() const +{ + return tids_; +} +const std::deque& AppStartup::CallIds() const +{ + return callIds_; +} +const std::deque& AppStartup::StartTimes() const +{ + return startTimes_; +} +const std::deque& AppStartup::EndTimes() const +{ + return endTimes_; +} +const std::deque& AppStartup::StartNames() const +{ + return startNames_; +} +const std::deque& AppStartup::PackedNames() const +{ + return packedNames_; +} + +size_t SoStaticInitalization::AppendNewData(uint32_t ipid, + uint32_t tid, + uint32_t callId, + uint64_t startTime, + uint64_t endTime, + DataIndex soName, + uint32_t depth) +{ + ipids_.emplace_back(ipid); + tids_.emplace_back(tid); + callIds_.emplace_back(callId); + startTimes_.emplace_back(startTime); + endTimes_.emplace_back(endTime); + soNames_.emplace_back(soName); + depths_.emplace_back(depth); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& SoStaticInitalization::Pids() const +{ + return ipids_; +} +const std::deque& SoStaticInitalization::Tids() const +{ + return tids_; +} +const std::deque& SoStaticInitalization::CallIds() const +{ + return callIds_; +} +const std::deque& SoStaticInitalization::StartTimes() const +{ + return startTimes_; +} +const std::deque& SoStaticInitalization::EndTimes() const +{ + return endTimes_; +} +const std::deque& SoStaticInitalization::SoNames() const +{ + return soNames_; +} +const std::deque SoStaticInitalization::Depths() const +{ + return depths_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/app_startup_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/app_startup_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..6a6af8a21764a8ceecce836cceeeb2751a011b89 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/app_startup_stdtype.h @@ -0,0 +1,101 @@ +/* + * 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 APP_STARTUP_STDTYPE_H +#define APP_STARTUP_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class AppStartup : public CacheBase { +public: + size_t AppendNewData(uint32_t ipid, + uint32_t tid, + uint32_t callId, + uint64_t startTime, + uint64_t endTime, + uint32_t startName, + DataIndex packedName); + const std::deque& Pids() const; + const std::deque& Tids() const; + const std::deque& CallIds() const; + const std::deque& StartTimes() const; + const std::deque& EndTimes() const; + const std::deque& StartNames() const; + const std::deque& PackedNames() const; + + void Clear() override + { + CacheBase::Clear(); + ipids_.clear(); + tids_.clear(); + callIds_.clear(); + startTimes_.clear(); + endTimes_.clear(); + startNames_.clear(); + packedNames_.clear(); + } + +private: + std::deque ipids_ = {}; + std::deque tids_ = {}; + std::deque callIds_ = {}; + std::deque startTimes_ = {}; + std::deque endTimes_ = {}; + std::deque startNames_ = {}; + std::deque packedNames_ = {}; +}; + +class SoStaticInitalization : public CacheBase { +public: + size_t AppendNewData(uint32_t ipid, + uint32_t tid, + uint32_t callId, + uint64_t startTime, + uint64_t endTime, + DataIndex soName, + uint32_t depth); + const std::deque& Pids() const; + const std::deque& Tids() const; + const std::deque& CallIds() const; + const std::deque& StartTimes() const; + const std::deque& EndTimes() const; + const std::deque& SoNames() const; + const std::deque Depths() const; + + void Clear() override + { + CacheBase::Clear(); + ipids_.clear(); + tids_.clear(); + callIds_.clear(); + startTimes_.clear(); + endTimes_.clear(); + soNames_.clear(); + depths_.clear(); + } + +private: + std::deque ipids_ = {}; + std::deque tids_ = {}; + std::deque callIds_ = {}; + std::deque startTimes_ = {}; + std::deque endTimes_ = {}; + std::deque soNames_ = {}; + std::deque depths_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // APP_STARTUP_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/task_pool_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/task_pool_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b77f04b4319314c3fe88bf4cbca2eed34955a9db --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/task_pool_stdtype.cpp @@ -0,0 +1,156 @@ +/* + * 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 "task_pool_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t TaskPoolInfo::AppendAllocationTaskData(uint32_t allocationTaskRow, + uint32_t allocationItid, + uint32_t executeId, + uint32_t priority, + uint32_t executeState) +{ + allocationTaskRows_.emplace_back(allocationTaskRow); + executeTaskRows_.emplace_back(INVALID_INT32); + returnTaskRows_.emplace_back(INVALID_INT32); + allocationItids_.emplace_back(allocationItid); + executeItids_.emplace_back(INVALID_INT32); + returnItids_.emplace_back(INVALID_INT32); + executeIds_.emplace_back(executeId); + prioritys_.emplace_back(priority); + executeStates_.emplace_back(executeState); + returnStates_.emplace_back(INVALID_INT32); + timeoutRows_.emplace_back(INVALID_INT32); + ids_.emplace_back(Size()); + return Size() - 1; +} +size_t TaskPoolInfo::AppendExecuteTaskData(uint32_t executeTaskRow, uint32_t executeItid, uint32_t executeId) +{ + allocationTaskRows_.emplace_back(INVALID_INT32); + executeTaskRows_.emplace_back(executeTaskRow); + returnTaskRows_.emplace_back(INVALID_INT32); + allocationItids_.emplace_back(INVALID_INT32); + executeItids_.emplace_back(executeItid); + returnItids_.emplace_back(INVALID_INT32); + executeIds_.emplace_back(executeId); + prioritys_.emplace_back(INVALID_INT32); + executeStates_.emplace_back(INVALID_INT32); + returnStates_.emplace_back(INVALID_INT32); + timeoutRows_.emplace_back(INVALID_INT32); + ids_.emplace_back(Size()); + return Size() - 1; +} +size_t TaskPoolInfo::AppendReturnTaskData(uint32_t returnTaskRow, + uint32_t returnItid, + uint32_t executeId, + uint32_t returnState) +{ + allocationTaskRows_.emplace_back(INVALID_INT32); + executeTaskRows_.emplace_back(INVALID_INT32); + returnTaskRows_.emplace_back(returnTaskRow); + allocationItids_.emplace_back(INVALID_INT32); + executeItids_.emplace_back(INVALID_INT32); + returnItids_.emplace_back(returnItid); + executeIds_.emplace_back(executeId); + prioritys_.emplace_back(INVALID_INT32); + executeStates_.emplace_back(INVALID_INT32); + returnStates_.emplace_back(returnState); + timeoutRows_.emplace_back(INVALID_INT32); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& TaskPoolInfo::AllocationTaskRows() const +{ + return allocationTaskRows_; +} +const std::deque& TaskPoolInfo::ExecuteTaskRows() const +{ + return executeTaskRows_; +} +const std::deque& TaskPoolInfo::ReturnTaskRows() const +{ + return returnTaskRows_; +} +const std::deque& TaskPoolInfo::AllocationItids() const +{ + return allocationItids_; +} +const std::deque& TaskPoolInfo::ExecuteItids() const +{ + return executeItids_; +} +const std::deque& TaskPoolInfo::ReturnItids() const +{ + return returnItids_; +} +const std::deque& TaskPoolInfo::ExecuteIds() const +{ + return executeIds_; +} +const std::deque& TaskPoolInfo::Prioritys() const +{ + return prioritys_; +} +const std::deque& TaskPoolInfo::ExecuteStates() const +{ + return executeStates_; +} +const std::deque& TaskPoolInfo::ReturnStates() const +{ + return returnStates_; +} +const std::deque& TaskPoolInfo::TimeoutRows() const +{ + return timeoutRows_; +} +void TaskPoolInfo::UpdateAllocationTaskData(uint32_t index, + uint32_t allocationTaskRow, + uint32_t allocationItid, + uint32_t priority, + uint32_t executeState) +{ + if (index <= Size()) { + allocationTaskRows_[index] = allocationTaskRow; + allocationItids_[index] = allocationItid; + prioritys_[index] = priority; + executeStates_[index] = executeState; + } +} +void TaskPoolInfo::UpdateExecuteTaskData(uint32_t index, uint32_t executeTaskRow, uint32_t executeItid) +{ + if (index <= Size()) { + executeTaskRows_[index] = executeTaskRow; + executeItids_[index] = executeItid; + } +} +void TaskPoolInfo::UpdateReturnTaskData(uint32_t index, + uint32_t returnTaskRow, + uint32_t returnItid, + uint32_t returnState) +{ + if (index <= Size()) { + returnTaskRows_[index] = returnTaskRow; + returnItids_[index] = returnItid; + returnStates_[index] = returnState; + } +} +void TaskPoolInfo::AppendTimeoutRow(uint32_t index, uint32_t timeoutRow) +{ + if (index <= Size()) { + timeoutRows_[index] = timeoutRow; + } +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/task_pool_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/task_pool_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..2c139209056c9ed2aef7218b56a442b6a43cdeb8 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/ftrace/template/task_pool_stdtype.h @@ -0,0 +1,82 @@ +/* + * 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 TASK_POOL_STDTYPE_H +#define TASK_POOL_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class TaskPoolInfo : public CacheBase { +public: + size_t AppendAllocationTaskData(uint32_t allocationTaskRow, + uint32_t allocationItid, + uint32_t executeId, + uint32_t priority, + uint32_t executeState); + size_t AppendExecuteTaskData(uint32_t executeTaskRow, uint32_t executeItid, uint32_t executeId); + size_t AppendReturnTaskData(uint32_t returnTaskRow, uint32_t returnItid, uint32_t executeId, uint32_t returnState); + void UpdateAllocationTaskData(uint32_t index, + uint32_t allocationTaskRow, + uint32_t allocationItid, + uint32_t priority, + uint32_t executeState); + void UpdateExecuteTaskData(uint32_t index, uint32_t executeTaskRow, uint32_t executeItid); + void UpdateReturnTaskData(uint32_t index, uint32_t returnTaskRow, uint32_t returnItid, uint32_t returnState); + void AppendTimeoutRow(uint32_t index, uint32_t timeoutRow); + + const std::deque& AllocationTaskRows() const; + const std::deque& ExecuteTaskRows() const; + const std::deque& ReturnTaskRows() const; + const std::deque& AllocationItids() const; + const std::deque& ExecuteItids() const; + const std::deque& ReturnItids() const; + const std::deque& ExecuteIds() const; + const std::deque& Prioritys() const; + const std::deque& ExecuteStates() const; + const std::deque& ReturnStates() const; + const std::deque& TimeoutRows() const; + void Clear() override + { + CacheBase::Clear(); + allocationTaskRows_.clear(); + executeTaskRows_.clear(); + returnTaskRows_.clear(); + allocationItids_.clear(); + executeItids_.clear(); + returnItids_.clear(); + executeIds_.clear(); + prioritys_.clear(); + executeStates_.clear(); + returnStates_.clear(); + timeoutRows_.clear(); + } + +private: + std::deque allocationTaskRows_ = {}; + std::deque executeTaskRows_ = {}; + std::deque returnTaskRows_ = {}; + std::deque allocationItids_ = {}; + std::deque executeItids_ = {}; + std::deque returnItids_ = {}; + std::deque executeIds_ = {}; + std::deque prioritys_ = {}; + std::deque executeStates_ = {}; + std::deque returnStates_ = {}; + std::deque timeoutRows_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // TASK_POOL_STDTYPE_H diff --git a/trace_streamer/src/filter/symbols_filter.cpp b/trace_streamer/src/trace_data/trace_stdtype/hilog/hilog_stdtype.cpp similarity index 33% rename from trace_streamer/src/filter/symbols_filter.cpp rename to trace_streamer/src/trace_data/trace_stdtype/hilog/hilog_stdtype.cpp index ba9497b4d5d3dc1b7ea562478832db1cdf73d0a7..7a81bc8fb95ec740285a8177ca1630e47560e4ea 100644 --- a/trace_streamer/src/filter/symbols_filter.cpp +++ b/trace_streamer/src/trace_data/trace_stdtype/hilog/hilog_stdtype.cpp @@ -12,50 +12,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "symbols_filter.h" -#include -#include -#include - -#include "log.h" -#include "measure_filter.h" -#include "process_filter.h" -#include "ts_common.h" +#include "hilog_stdtype.h" namespace SysTuning { -namespace TraceStreamer { -SymbolsFilter::SymbolsFilter(TraceDataCache* dataCache, const TraceStreamerFilters* filter) - : FilterBase(dataCache, filter) +namespace TraceStdtype { +size_t LogInfo::AppendNewLogInfo(uint64_t seq, + uint64_t timeStamp, + uint32_t pid, + uint32_t tid, + DataIndex level, + DataIndex tag, + DataIndex context, + uint64_t originTs) { + hilogLineSeqs_.emplace_back(seq); + timeStamps_.emplace_back(timeStamp); + pids_.emplace_back(pid); + tids_.emplace_back(tid); + levels_.emplace_back(level); + tags_.emplace_back(tag); + contexts_.emplace_back(context); + originTs_.emplace_back(originTs); + return Size() - 1; } - -SymbolsFilter::~SymbolsFilter() = default; -void SymbolsFilter::RegisterFunc(uint64_t addr, DataIndex funcNameDictIndex) +const std::deque& LogInfo::HilogLineSeqs() const { - if (symbolsMap_.find(addr) == symbolsMap_.end()) { - symbolsMap_.insert(std::make_pair(addr, funcNameDictIndex)); - traceDataCache_->GetSymbolsData()->InsertSymbol(funcNameDictIndex, addr); - } else { - symbolsMap_.at(addr) = funcNameDictIndex; - } + return hilogLineSeqs_; } - -const DataIndex& SymbolsFilter::GetFunc(uint64_t addr) const +const std::deque& LogInfo::Pids() const +{ + return pids_; +} +const std::deque& LogInfo::Tids() const +{ + return tids_; +} +const std::deque& LogInfo::Levels() const +{ + return levels_; +} +const std::deque& LogInfo::Tags() const +{ + return tags_; +} +const std::deque& LogInfo::Contexts() const { - if (symbolsMap_.find(addr) == symbolsMap_.end()) { - auto lastAddr = symbolsMap_.lower_bound(addr); - if (lastAddr == symbolsMap_.end()) { - return INVALID_UINT64; - } - return lastAddr->second; - } else { - return symbolsMap_.at(addr); - } + return contexts_; } -void SymbolsFilter::Clear() +const std::deque& LogInfo::OriginTimeStamData() const { - symbolsMap_.clear(); + return originTs_; } -} // namespace TraceStreamer +} // namespace TraceStdtype } // namespace SysTuning diff --git a/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.h b/trace_streamer/src/trace_data/trace_stdtype/hilog/hilog_stdtype.h similarity index 33% rename from trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.h rename to trace_streamer/src/trace_data/trace_stdtype/hilog/hilog_stdtype.h index 8af16a923f4b2f63465f085d0e0eedc836fc7d30..fddcd9ab67e4b29ce8683771c5379d9b8cd2f8fa 100644 --- a/trace_streamer/src/table/ebpf/ebpf_elf_symbol_table.h +++ b/trace_streamer/src/trace_data/trace_stdtype/hilog/hilog_stdtype.h @@ -12,41 +12,50 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef EBPF_ELF_SYMBOL_TABLE_H -#define EBPF_ELF_SYMBOL_TABLE_H -#include "table_base.h" -#include "trace_stdtype.h" +#ifndef HILOG_STDTYPE_H +#define HILOG_STDTYPE_H +#include "base_stdtype.h" namespace SysTuning { -namespace TraceStreamer { -class EbpfElfSymbolTable : public TableBase { +namespace TraceStdtype { +class LogInfo : public CacheBase { public: - explicit EbpfElfSymbolTable(const TraceDataCache* dataCache); - ~EbpfElfSymbolTable() override; - std::unique_ptr CreateCursor() override; - -private: - int64_t GetSize() override + size_t AppendNewLogInfo(uint64_t seq, + uint64_t timeStamp, + uint32_t pid, + uint32_t tid, + DataIndex level, + DataIndex tag, + DataIndex context, + uint64_t originTs); + const std::deque& HilogLineSeqs() const; + const std::deque& Pids() const; + const std::deque& Tids() const; + const std::deque& Levels() const; + const std::deque& Tags() const; + const std::deque& Contexts() const; + const std::deque& OriginTimeStamData() const; + void Clear() override { - return dataCache_->GetConstEbpfElfSymbol().Size(); + CacheBase::Clear(); + hilogLineSeqs_.clear(); + pids_.clear(); + levels_.clear(); + tags_.clear(); + contexts_.clear(); + originTs_.clear(); } - void GetOrbyes(FilterConstraints& elffc, EstimatedIndexInfo& elfei) override; - void FilterByConstraint(FilterConstraints& elffc, - double& elffilterCost, - size_t elfrowCount, - uint32_t elfcurrenti) override; - class Cursor : public TableBase::Cursor { - public: - explicit Cursor(const TraceDataCache* dataCache, TableBase* table); - ~Cursor() override; - int32_t Column(int32_t column) const override; - - private: - const EbpfElfSymbol& ebpfElfSymbolObj_; - }; +private: + std::deque hilogLineSeqs_ = {}; + std::deque pids_ = {}; + std::deque tids_ = {}; + std::deque levels_ = {}; + std::deque tags_ = {}; + std::deque contexts_ = {}; + std::deque originTs_ = {}; }; -} // namespace TraceStreamer +} // namespace TraceStdtype } // namespace SysTuning -#endif // EBPF_ELF_SYMBOL_TABLE_H +#endif // HILOG_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/hiperf/hiperf_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/hiperf/hiperf_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1ce914216ab840641fd0a4fa741605d7f39128a --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/hiperf/hiperf_stdtype.cpp @@ -0,0 +1,226 @@ +/* + * 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 "hiperf_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +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()); + 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(INVALID_UINT64); + return Size() - 1; +} +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_; +} +const std::deque& PerfCallChain::FileIds() const +{ + return fileIds_; +} +const std::deque& PerfCallChain::SymbolIds() const +{ + return symbolIds_; +} + +const std::deque& PerfCallChain::Names() const +{ + return names_; +} +void PerfCallChain::SetName(uint64_t index, DataIndex name) +{ + names_[index] = name; +} +void PerfCallChain::Clear() +{ + CacheBase::Clear(); + callChainIds_.clear(); + depths_.clear(); + ips_.clear(); + vaddrInFiles_.clear(); + fileIds_.clear(); + symbolIds_.clear(); + names_.clear(); +} +void PerfCallChain::UpdateSymbolId(size_t index, DataIndex symbolId) +{ + if (index < Size()) { + symbolIds_[index] = symbolId; + } +} +size_t PerfFiles::AppendNewPerfFiles(uint64_t fileIds, uint32_t serial, DataIndex symbols, DataIndex filePath) +{ + ids_.emplace_back(Size()); + fileIds_.emplace_back(fileIds); + serials_.emplace_back(serial); + symbols_.emplace_back(symbols); + filePaths_.emplace_back(filePath); + return Size() - 1; +} +const std::deque& PerfFiles::FileIds() const +{ + return fileIds_; +} + +const std::deque& PerfFiles::Serials() const +{ + return serials_; +} +const std::deque& PerfFiles::Symbols() const +{ + return symbols_; +} +const std::deque& PerfFiles::FilePaths() const +{ + return filePaths_; +} + +void PerfFiles::Clear() +{ + CacheBase::Clear(); + fileIds_.clear(); + serials_.clear(); + symbols_.clear(); + filePaths_.clear(); +} + +size_t PerfSample::AppendNewPerfSample(uint32_t sampleId, + uint64_t timeStamp, + uint32_t tid, + uint64_t eventCount, + uint64_t eventTypeId, + uint64_t timestampTrace, + uint64_t cpuId, + uint64_t threadState) +{ + ids_.emplace_back(Size()); + sampleIds_.emplace_back(sampleId); + timeStamps_.emplace_back(timeStamp); + tids_.emplace_back(tid); + eventCounts_.emplace_back(eventCount); + eventTypeIds_.emplace_back(eventTypeId); + timestampTraces_.emplace_back(timestampTrace); + cpuIds_.emplace_back(cpuId); + threadStates_.emplace_back(threadState); + return Size() - 1; +} +const std::deque& PerfSample::SampleIds() const +{ + return sampleIds_; +} +const std::deque& PerfSample::Tids() const +{ + return tids_; +} +const std::deque& PerfSample::EventCounts() const +{ + return eventCounts_; +} +const std::deque& PerfSample::EventTypeIds() const +{ + return eventTypeIds_; +} +const std::deque& PerfSample::TimestampTraces() const +{ + return timestampTraces_; +} +const std::deque& PerfSample::CpuIds() const +{ + return cpuIds_; +} +const std::deque& PerfSample::ThreadStates() const +{ + return threadStates_; +} + +void PerfSample::Clear() +{ + CacheBase::Clear(); + sampleIds_.clear(); + tids_.clear(); + eventCounts_.clear(); + eventTypeIds_.clear(); + timestampTraces_.clear(); + cpuIds_.clear(); + threadStates_.clear(); +} + +size_t PerfThread::AppendNewPerfThread(uint32_t pid, uint32_t tid, DataIndex threadName) +{ + ids_.emplace_back(Size()); + pids_.emplace_back(pid); + tids_.emplace_back(tid); + threadNames_.emplace_back(threadName); + return Size() - 1; +} +const std::deque& PerfThread::Pids() const +{ + return pids_; +} +const std::deque& PerfThread::Tids() const +{ + return tids_; +} +const std::deque& PerfThread::ThreadNames() const +{ + return threadNames_; +} +void PerfThread::Clear() +{ + CacheBase::Clear(); + tids_.clear(); + pids_.clear(); + threadNames_.clear(); +} +size_t PerfReport::AppendNewPerfReport(DataIndex type, DataIndex value) +{ + ids_.emplace_back(Size()); + types_.emplace_back(type); + values_.emplace_back(value); + return Size() - 1; +} +const std::deque& PerfReport::Types() const +{ + return types_; +} +const std::deque& PerfReport::Values() const +{ + return values_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/hiperf/hiperf_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/hiperf/hiperf_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..cd6c9ab13b0cbdff5b0f76c4cc523d275b764fa1 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/hiperf/hiperf_stdtype.h @@ -0,0 +1,122 @@ +/* + * 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 HIPERF_STDTYPE_H +#define HIPERF_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class PerfCallChain : public CacheBase { +public: + size_t AppendNewPerfCallChain(uint32_t callChainId, + uint32_t depth, + uint64_t ip, + uint64_t vaddrInFile, + uint64_t fileId, + uint64_t symbolId); + 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; + const std::deque& Names() const; + void SetName(uint64_t index, DataIndex name); + void UpdateSymbolId(size_t index, DataIndex symbolId); + void Clear() override; + +private: + std::deque callChainIds_ = {}; + std::deque depths_ = {}; + std::deque ips_ = {}; + std::deque vaddrInFiles_ = {}; + std::deque fileIds_ = {}; + std::deque symbolIds_ = {}; + std::deque names_ = {}; +}; + +class PerfFiles : public CacheBase { +public: + size_t AppendNewPerfFiles(uint64_t fileIds, uint32_t serial, DataIndex symbols, DataIndex filePath); + const std::deque& FileIds() const; + const std::deque& Symbols() const; + const std::deque& FilePaths() const; + const std::deque& Serials() const; + void Clear() override; + +private: + std::deque fileIds_ = {}; + std::deque serials_ = {}; + std::deque symbols_ = {}; + std::deque filePaths_ = {}; +}; + +class PerfSample : public CacheBase { +public: + size_t AppendNewPerfSample(uint32_t sampleId, + uint64_t timeStamp, + uint32_t tid, + uint64_t eventCount, + uint64_t eventTypeId, + uint64_t timestampTrace, + uint64_t cpuId, + uint64_t threadState); + const std::deque& SampleIds() const; + const std::deque& Tids() const; + const std::deque& EventCounts() const; + const std::deque& EventTypeIds() const; + const std::deque& TimestampTraces() const; + const std::deque& CpuIds() const; + const std::deque& ThreadStates() const; + void Clear() override; + +private: + std::deque sampleIds_ = {}; + std::deque tids_ = {}; + std::deque eventCounts_ = {}; + std::deque eventTypeIds_ = {}; + std::deque timestampTraces_ = {}; + std::deque cpuIds_ = {}; + std::deque threadStates_ = {}; +}; + +class PerfThread : public CacheBase { +public: + size_t AppendNewPerfThread(uint32_t pid, uint32_t tid, DataIndex threadName); + const std::deque& Pids() const; + const std::deque& Tids() const; + const std::deque& ThreadNames() const; + void Clear() override; + +private: + std::deque tids_ = {}; + std::deque pids_ = {}; + std::deque threadNames_ = {}; +}; + +class PerfReport : public CacheBase { +public: + size_t AppendNewPerfReport(DataIndex type, DataIndex value); + const std::deque& Types() const; + const std::deque& Values() const; + +private: + std::deque types_ = {}; + std::deque values_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // HIPERF_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/hisysevent/hisysevent_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/hisysevent/hisysevent_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..262b1d2c6273b07d4c65c7acfaa2efa19a989407 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/hisysevent/hisysevent_stdtype.cpp @@ -0,0 +1,291 @@ +/* + * 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 "hisysevent_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +uint32_t HiSysEventSubkeys::AppendSysEventSubkey(DataIndex eventSource, DataIndex appName) +{ + sysEventNameIds_.emplace_back(eventSource); + subkeyNameIds_.emplace_back(appName); + ids_.emplace_back(subkeyNameIds_.size() - 1); + return Size() - 1; +} +const std::deque& HiSysEventSubkeys::SysEventNameId() const +{ + return sysEventNameIds_; +} +const std::deque& HiSysEventSubkeys::SysEventSubkeyId() const +{ + return subkeyNameIds_; +} + +void HiSysEventMeasureData::AppendData(uint64_t serial, + uint64_t ts, + uint32_t nameId, + uint32_t keyId, + int32_t type, + double numericValue, + DataIndex stringValue) +{ + serial_.emplace_back(serial); + ts_.emplace_back(ts); + nameFilterIds_.emplace_back(nameId); + appKeyFilterIds_.emplace_back(keyId); + types_.emplace_back(type); + numValues_.emplace_back(numericValue); + stringValues_.emplace_back(stringValue); + ids_.emplace_back(rowCount_); + rowCount_++; +} +const std::deque& HiSysEventMeasureData::Serial() const +{ + return serial_; +} +const std::deque& HiSysEventMeasureData::Ts() const +{ + return ts_; +} +const std::deque& HiSysEventMeasureData::NameFilterId() const +{ + return nameFilterIds_; +} +const std::deque& HiSysEventMeasureData::AppKeyFilterId() const +{ + return appKeyFilterIds_; +} +const std::deque& HiSysEventMeasureData::Type() const +{ + return types_; +} +const std::deque& HiSysEventMeasureData::NumValue() const +{ + return numValues_; +} +const std::deque& HiSysEventMeasureData::StringValue() const +{ + return stringValues_; +} +void HiSysEventDeviceStateData::AppendNewData(int32_t brightness, + int32_t btState, + int32_t location, + int32_t wifi, + int32_t streamDefault, + int32_t voiceCall, + int32_t music, + int32_t streamRing, + int32_t media, + int32_t voiceAssistant, + int32_t system, + int32_t alarm, + int32_t notification, + int32_t btSco, + int32_t enforcedAudible, + int32_t streamDtmf, + int32_t streamTts, + int32_t accessibility, + int32_t recording, + int32_t streamAll) +{ + brightness_.emplace_back(brightness); + btStates_.emplace_back(btState); + locations_.emplace_back(location); + wifis_.emplace_back(wifi); + streamDefaults_.emplace_back(streamDefault); + voiceCalls_.emplace_back(voiceCall); + musics_.emplace_back(music); + streamRings_.emplace_back(streamRing); + medias_.emplace_back(media); + voiceAssistants_.emplace_back(voiceAssistant); + systems_.emplace_back(system); + alarms_.emplace_back(alarm); + notifications_.emplace_back(notification); + btScos_.emplace_back(btSco); + enforcedAudibles_.emplace_back(enforcedAudible); + streamDtmfs_.emplace_back(streamDtmf); + streamTts_.emplace_back(streamTts); + accessibilitys_.emplace_back(accessibility); + recordings_.emplace_back(recording); + streamAlls_.emplace_back(streamAll); + ids_.emplace_back(rowCounts_); + rowCounts_++; +} +const std::deque& HiSysEventDeviceStateData::Brightness() const +{ + return brightness_; +} +const std::deque& HiSysEventDeviceStateData::BtState() const +{ + return btStates_; +} +const std::deque& HiSysEventDeviceStateData::Location() const +{ + return locations_; +} +const std::deque& HiSysEventDeviceStateData::Wifi() const +{ + return wifis_; +} +const std::deque& HiSysEventDeviceStateData::StreamDefault() const +{ + return streamDefaults_; +} +const std::deque& HiSysEventDeviceStateData::VoiceCall() const +{ + return voiceCalls_; +} +const std::deque& HiSysEventDeviceStateData::Music() const +{ + return musics_; +} +const std::deque& HiSysEventDeviceStateData::StreamRing() const +{ + return streamRings_; +} +const std::deque& HiSysEventDeviceStateData::Media() const +{ + return medias_; +} +const std::deque& HiSysEventDeviceStateData::VoiceAssistant() const +{ + return voiceAssistants_; +} +const std::deque& HiSysEventDeviceStateData::System() const +{ + return systems_; +} +const std::deque& HiSysEventDeviceStateData::Alarm() const +{ + return alarms_; +} +const std::deque& HiSysEventDeviceStateData::Notification() const +{ + return notifications_; +} +const std::deque& HiSysEventDeviceStateData::BtSco() const +{ + return btScos_; +} +const std::deque& HiSysEventDeviceStateData::EnforcedAudible() const +{ + return enforcedAudibles_; +} +const std::deque& HiSysEventDeviceStateData::StreamDtmf() const +{ + return streamDtmfs_; +} +const std::deque& HiSysEventDeviceStateData::StreamTts() const +{ + return streamTts_; +} +const std::deque& HiSysEventDeviceStateData::Accessibility() const +{ + return accessibilitys_; +} +const std::deque& HiSysEventDeviceStateData::Recordings() const +{ + return recordings_; +} +const std::deque& HiSysEventDeviceStateData::StreamAll() const +{ + return streamAlls_; +} + +uint32_t HiSysEventAllEventData::AppendHiSysEventData(DataIndex domainId, + DataIndex eventNameId, + uint64_t timeStamp, + uint32_t type, + const std::string& timeZone, + uint32_t pid, + uint32_t tid, + uint32_t uid, + const std::string& level, + const std::string& tag, + const std::string& eventId, + uint64_t seq, + const std::string& info, + const std::string& content) +{ + domainIds_.emplace_back(domainId); + eventNameIds_.emplace_back(eventNameId); + timeStamps_.emplace_back(timeStamp); + types_.emplace_back(type); + timeZones_.emplace_back(timeZone); + pids_.emplace_back(pid); + tids_.emplace_back(tid); + uids_.emplace_back(uid); + levels_.emplace_back(level); + tags_.emplace_back(tag); + eventIds_.emplace_back(eventId); + seqs_.emplace_back(seq); + infos_.emplace_back(info); + contents_.emplace_back(content); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& HiSysEventAllEventData::DomainIds() const +{ + return domainIds_; +} +const std::deque& HiSysEventAllEventData::EventNameIds() const +{ + return eventNameIds_; +} +const std::deque& HiSysEventAllEventData::Types() const +{ + return types_; +} +const std::deque& HiSysEventAllEventData::TimeZones() const +{ + return timeZones_; +} +const std::deque& HiSysEventAllEventData::Pids() const +{ + return pids_; +} +const std::deque& HiSysEventAllEventData::Tids() const +{ + return tids_; +} +const std::deque& HiSysEventAllEventData::Uids() const +{ + return uids_; +} +const std::deque& HiSysEventAllEventData::Levels() const +{ + return levels_; +} +const std::deque& HiSysEventAllEventData::Tags() const +{ + return tags_; +} +const std::deque& HiSysEventAllEventData::EventIds() const +{ + return eventIds_; +} +const std::deque& HiSysEventAllEventData::Seqs() const +{ + return seqs_; +} +const std::deque& HiSysEventAllEventData::Infos() const +{ + return infos_; +} +const std::deque& HiSysEventAllEventData::Contents() const +{ + return contents_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/hisysevent/hisysevent_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/hisysevent/hisysevent_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..ba5a7dcc728ddaaa113e54faae937cbdc2875108 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/hisysevent/hisysevent_stdtype.h @@ -0,0 +1,233 @@ +/* + * 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 HISYSEVENT_STDTYPE_H +#define HISYSEVENT_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class HiSysEventSubkeys : public CacheBase { +public: + uint32_t AppendSysEventSubkey(DataIndex eventSource, DataIndex appName); + const std::deque& SysEventNameId() const; + const std::deque& SysEventSubkeyId() const; + void Clear() override + { + CacheBase::Clear(); + sysEventNameIds_.clear(); + subkeyNameIds_.clear(); + } + +private: + std::deque sysEventNameIds_ = {}; + std::deque subkeyNameIds_ = {}; +}; +class HiSysEventMeasureData : public CacheBase { +public: + void AppendData(uint64_t serial, + uint64_t ts, + uint32_t nameId, + uint32_t keyId, + int32_t type, + double numericValue, + DataIndex stringValue); + const std::deque& Serial() const; + const std::deque& Ts() const; + const std::deque& NameFilterId() const; + const std::deque& AppKeyFilterId() const; + const std::deque& Type() const; + const std::deque& NumValue() const; + const std::deque& StringValue() const; + void Clear() override + { + CacheBase::Clear(); + serial_.clear(); + ts_.clear(); + nameFilterIds_.clear(); + appKeyFilterIds_.clear(); + types_.clear(); + numValues_.clear(); + stringValues_.clear(); + } + +private: + std::deque serial_ = {}; + std::deque ts_ = {}; + std::deque nameFilterIds_ = {}; + std::deque appKeyFilterIds_ = {}; + std::deque types_ = {}; + std::deque numValues_ = {}; + std::deque stringValues_ = {}; + uint32_t rowCount_ = 0; +}; + +class HiSysEventDeviceStateData : public CacheBase { +public: + void AppendNewData(int32_t brightness, + int32_t btState, + int32_t location, + int32_t wifi, + int32_t streamDefault, + int32_t voiceCall, + int32_t music, + int32_t streamRing, + int32_t media, + int32_t voiceAssistant, + int32_t system, + int32_t alarm, + int32_t notification, + int32_t btSco, + int32_t enforcedAudible, + int32_t streamDtmf, + int32_t streamTts, + int32_t accessibility, + int32_t recording, + int32_t streamAll); + const std::deque& Brightness() const; + const std::deque& BtState() const; + const std::deque& Location() const; + const std::deque& Wifi() const; + const std::deque& StreamDefault() const; + const std::deque& VoiceCall() const; + const std::deque& Music() const; + const std::deque& StreamRing() const; + const std::deque& Media() const; + const std::deque& VoiceAssistant() const; + const std::deque& System() const; + const std::deque& Alarm() const; + const std::deque& Notification() const; + const std::deque& BtSco() const; + const std::deque& EnforcedAudible() const; + const std::deque& StreamDtmf() const; + const std::deque& StreamTts() const; + const std::deque& Accessibility() const; + const std::deque& Recordings() const; + const std::deque& StreamAll() const; + void Clear() override + { + CacheBase::Clear(); + brightness_.clear(); + btStates_.clear(); + locations_.clear(); + wifis_.clear(); + streamDefaults_.clear(); + voiceCalls_.clear(); + musics_.clear(); + streamRings_.clear(); + medias_.clear(); + voiceAssistants_.clear(); + systems_.clear(); + alarms_.clear(); + notifications_.clear(); + btScos_.clear(); + enforcedAudibles_.clear(); + streamDtmfs_.clear(); + streamTts_.clear(); + accessibilitys_.clear(); + recordings_.clear(); + streamAlls_.clear(); + } + +private: + std::deque stringValues_ = {}; + std::deque brightness_ = {}; + std::deque btStates_ = {}; + std::deque locations_ = {}; + std::deque wifis_ = {}; + std::deque streamDefaults_ = {}; + std::deque voiceCalls_ = {}; + std::deque musics_ = {}; + std::deque streamRings_ = {}; + std::deque medias_ = {}; + std::deque voiceAssistants_ = {}; + std::deque systems_ = {}; + std::deque alarms_ = {}; + std::deque notifications_ = {}; + std::deque btScos_ = {}; + std::deque enforcedAudibles_ = {}; + std::deque streamDtmfs_ = {}; + std::deque streamTts_ = {}; + std::deque accessibilitys_ = {}; + std::deque recordings_ = {}; + std::deque streamAlls_ = {}; + uint32_t rowCounts_ = 0; +}; + +class HiSysEventAllEventData : public CacheBase { +public: + uint32_t AppendHiSysEventData(DataIndex domainId, + DataIndex eventNameId, + uint64_t timeStamp, + uint32_t type, + const std::string& timeZone, + uint32_t pid, + uint32_t tid, + uint32_t uid, + const std::string& level, + const std::string& tag, + const std::string& eventId, + uint64_t seq, + const std::string& info, + const std::string& content); + const std::deque& DomainIds() const; + const std::deque& EventNameIds() const; + const std::deque& Types() const; + const std::deque& TimeZones() const; + const std::deque& Pids() const; + const std::deque& Tids() const; + const std::deque& Uids() const; + const std::deque& Levels() const; + const std::deque& Tags() const; + const std::deque& EventIds() const; + const std::deque& Seqs() const; + const std::deque& Infos() const; + const std::deque& Contents() const; + void Clear() override + { + CacheBase::Clear(); + domainIds_.clear(); + eventNameIds_.clear(); + types_.clear(); + timeZones_.clear(); + pids_.clear(); + tids_.clear(); + uids_.clear(); + levels_.clear(); + tags_.clear(); + eventIds_.clear(); + seqs_.clear(); + infos_.clear(); + contents_.clear(); + } + +private: + std::deque domainIds_ = {}; + std::deque eventNameIds_ = {}; + std::deque types_ = {}; + std::deque timeZones_ = {}; + std::deque pids_ = {}; + std::deque tids_ = {}; + std::deque uids_ = {}; + std::deque levels_ = {}; + std::deque tags_ = {}; + std::deque eventIds_ = {}; + std::deque seqs_ = {}; + std::deque infos_ = {}; + std::deque contents_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // HISYSEVENT_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/activity_monitor_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/htrace/activity_monitor_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01dc146c693ace92003d7990a7b6877f9e93c1e8 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/activity_monitor_stdtype.cpp @@ -0,0 +1,839 @@ +/* + * 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 "activity_monitor_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t Hidump::AppendNewHidumpInfo(uint64_t timeStamp, uint32_t fps) +{ + timeStamps_.emplace_back(timeStamp); + fpss_.emplace_back(fps); + return Size() - 1; +} +const std::deque& Hidump::Fpss() const +{ + return fpss_; +} +void Hidump::Clear() +{ + CacheBase::Clear(); + fpss_.clear(); +} + +void DiskIOData::AppendNewData(uint64_t ts, + uint64_t dur, + uint64_t rd, + uint64_t wr, + uint64_t rdPerSec, + uint64_t wrPerSec, + double rdCountPerSec, + double wrCountPerSec, + uint64_t rdCount, + uint64_t wrCount) +{ + timeStamps_.emplace_back(ts); + durs_.emplace_back(dur); + rdDatas_.emplace_back(rd); + wrDatas_.emplace_back(wr); + rdPerSec_.emplace_back(rdPerSec); + wrPerSec_.emplace_back(wrPerSec); + rdCountPerSec_.emplace_back(rdCountPerSec); + wrCountPerSec_.emplace_back(wrCountPerSec); + rdCountDatas_.emplace_back(rdCount); + wrCountDatas_.emplace_back(wrCount); +} +const std::deque& DiskIOData::Durs() const +{ + return durs_; +} +const std::deque& DiskIOData::RdDatas() const +{ + return rdDatas_; +} +const std::deque& DiskIOData::WrDatas() const +{ + return wrDatas_; +} +const std::deque& DiskIOData::RdSpeedDatas() const +{ + return rdPerSec_; +} +const std::deque& DiskIOData::WrSpeedDatas() const +{ + return wrPerSec_; +} + +const std::deque& DiskIOData::RdCountPerSecDatas() const +{ + return rdCountPerSec_; +} +const std::deque& DiskIOData::WrCountPerSecDatas() const +{ + return wrCountPerSec_; +} +const std::deque& DiskIOData::RdCountDatas() const +{ + return rdCountDatas_; +} +const std::deque& DiskIOData::WrCountDatas() const +{ + return wrCountDatas_; +} +void DiskIOData::Clear() +{ + CacheBase::Clear(); + durs_.clear(); + rdDatas_.clear(); + wrDatas_.clear(); + wrPerSec_.clear(); + rdPerSec_.clear(); + wrCountPerSec_.clear(); + rdCountPerSec_.clear(); + rdCountDatas_.clear(); + wrCountDatas_.clear(); +} + +size_t LiveProcessDetailData::AppendNewData(uint64_t newTimeStamp, + uint64_t dur, + int32_t processID, + std::string processName, + int32_t parentProcessID, + int32_t uid, + std::string userName, + double cpuUsage, + int32_t pssInfo, + uint64_t cpuTime, + int32_t threads, + int64_t diskWrites, + int64_t diskReads) +{ + timeStamps_.emplace_back(newTimeStamp); + durs_.emplace_back(dur); + processID_.emplace_back(processID); + processName_.emplace_back(processName); + parentProcessID_.emplace_back(parentProcessID); + uid_.emplace_back(uid); + userName_.emplace_back(userName); + cpuUsage_.emplace_back(cpuUsage); + pssInfo_.emplace_back(pssInfo); + threads_.emplace_back(threads); + diskWrites_.emplace_back(diskWrites); + diskReads_.emplace_back(diskReads); + cpuTimes_.emplace_back(cpuTime); + return Size() - 1; +} +const std::deque& LiveProcessDetailData::Durs() const +{ + return durs_; +} +const std::deque& LiveProcessDetailData::ProcessID() const +{ + return processID_; +} +const std::deque& LiveProcessDetailData::ProcessName() const +{ + return processName_; +} +const std::deque& LiveProcessDetailData::ParentProcessID() const +{ + return parentProcessID_; +} +const std::deque& LiveProcessDetailData::Uid() const +{ + return uid_; +} +const std::deque& LiveProcessDetailData::UserName() const +{ + return userName_; +} +const std::deque& LiveProcessDetailData::CpuUsage() const +{ + return cpuUsage_; +} +const std::deque& LiveProcessDetailData::PssInfo() const +{ + return pssInfo_; +} +const std::deque& LiveProcessDetailData::Threads() const +{ + return threads_; +} +const std::deque& LiveProcessDetailData::DiskWrites() const +{ + return diskWrites_; +} +const std::deque& LiveProcessDetailData::DiskReads() const +{ + return diskReads_; +} + +const std::deque& LiveProcessDetailData::CpuTimes() const +{ + return cpuTimes_; +} +void LiveProcessDetailData::Clear() +{ + CacheBase::Clear(); + durs_.clear(); + processID_.clear(); + processName_.clear(); + parentProcessID_.clear(); + uid_.clear(); + userName_.clear(); + cpuUsage_.clear(); + pssInfo_.clear(); + threads_.clear(); + diskWrites_.clear(); + diskReads_.clear(); +} + +size_t CpuUsageDetailData::AppendNewData(uint64_t newTimeStamp, + uint64_t dur, + double totalLoad, + double userLoad, + double systemLoad, + int64_t threads) +{ + timeStamps_.emplace_back(newTimeStamp); + durs_.emplace_back(dur); + totalLoad_.emplace_back(totalLoad); + userLoad_.emplace_back(userLoad); + systemLoad_.emplace_back(systemLoad); + threads_.emplace_back(threads); + return Size() - 1; +} +const std::deque& CpuUsageDetailData::Durs() const +{ + return durs_; +} +const std::deque& CpuUsageDetailData::TotalLoad() const +{ + return totalLoad_; +} +const std::deque& CpuUsageDetailData::UserLoad() const +{ + return userLoad_; +} +const std::deque& CpuUsageDetailData::SystemLoad() const +{ + return systemLoad_; +} +const std::deque& CpuUsageDetailData::Threads() const +{ + return threads_; +} +void CpuUsageDetailData::Clear() +{ + CacheBase::Clear(); + durs_.clear(); + totalLoad_.clear(); + userLoad_.clear(); + systemLoad_.clear(); + threads_.clear(); +} + +size_t NetDetailData::AppendNewNetData(uint64_t newTimeStamp, + uint64_t tx, + uint64_t rx, + uint64_t dur, + double rxSpeed, + double txSpeed, + uint64_t packetIn, + double packetInSec, + uint64_t packetOut, + double packetOutSec, + const std::string& netType) +{ + timeStamps_.emplace_back(newTimeStamp); + txs_.emplace_back(tx); + rxs_.emplace_back(rx); + durs_.emplace_back(dur); + txSpeeds_.emplace_back(txSpeed); + rxSpeeds_.emplace_back(rxSpeed); + netTypes_.emplace_back(netType); + packetIn_.emplace_back(packetIn); + packetInSec_.emplace_back(packetInSec); + packetOut_.emplace_back(packetOut); + packetOutSec_.emplace_back(packetOutSec); + + return Size() - 1; +} +const std::deque& NetDetailData::Durs() const +{ + return durs_; +} +const std::deque& NetDetailData::RxSpeed() const +{ + return rxSpeeds_; +} +const std::deque& NetDetailData::TxSpeed() const +{ + return txSpeeds_; +} +const std::deque& NetDetailData::NetTypes() const +{ + return netTypes_; +} +const std::deque& NetDetailData::RxDatas() const +{ + return rxs_; +} +const std::deque& NetDetailData::TxDatas() const +{ + return txs_; +} +const std::deque& NetDetailData::PacketIn() const +{ + return packetIn_; +} +const std::deque& NetDetailData::PacketInSec() const +{ + return packetInSec_; +} +const std::deque& NetDetailData::PacketOut() const +{ + return packetOut_; +} +const std::deque& NetDetailData::PacketOutSec() const +{ + return packetOutSec_; +} +void NetDetailData::Clear() +{ + CacheBase::Clear(); + durs_.clear(); + rxSpeeds_.clear(); + txSpeeds_.clear(); + netTypes_.clear(); + packetIn_.clear(); + packetInSec_.clear(); + packetOut_.clear(); + packetOutSec_.clear(); +} + +void SmapsData::AppendNewData(uint64_t timeStamp, + uint64_t ipid, + std::string startAddr, + std::string endAddr, + uint64_t dirty, + uint64_t swapper, + uint64_t rss, + uint64_t pss, + uint64_t size, + double reside, + DataIndex protectionId, + DataIndex pathId, + uint64_t sharedClean, + uint64_t sharedDirty, + uint64_t privateClean, + uint64_t privateDirty, + uint64_t swap, + uint64_t swapPss, + uint32_t type) +{ + timeStamps_.emplace_back(timeStamp); + ipids_.emplace_back(ipid); + startAddrs_.emplace_back(startAddr); + endAddrs_.emplace_back(endAddr); + dirtys_.emplace_back(dirty); + swappers_.emplace_back(swapper); + rss_.emplace_back(rss); + pss_.emplace_back(pss); + sizes_.emplace_back(size); + resides_.emplace_back(reside); + protectionIds_.emplace_back(protectionId); + pathIds_.emplace_back(pathId); + sharedClean_.emplace_back(sharedClean); + sharedDirty_.emplace_back(sharedDirty); + privateClean_.emplace_back(privateClean); + privateDirty_.emplace_back(privateDirty); + swap_.emplace_back(swap); + swapPss_.emplace_back(swapPss); + type_.emplace_back(type); + ids_.emplace_back(rowCount_); + rowCount_++; +} +const std::deque& SmapsData::TimeStamps() const +{ + return timeStamps_; +} +const std::deque& SmapsData::Ipids() const +{ + return ipids_; +} +const std::deque& SmapsData::StartAddrs() const +{ + return startAddrs_; +} +const std::deque& SmapsData::EndAddrs() const +{ + return endAddrs_; +} +const std::deque& SmapsData::Dirtys() const +{ + return dirtys_; +} +const std::deque& SmapsData::Swappers() const +{ + return swappers_; +} +const std::deque& SmapsData::Rss() const +{ + return rss_; +} +const std::deque& SmapsData::Pss() const +{ + return pss_; +} +const std::deque& SmapsData::Sizes() const +{ + return sizes_; +} +const std::deque& SmapsData::Resides() const +{ + return resides_; +} +const std::deque& SmapsData::ProtectionIds() const +{ + return protectionIds_; +} +const std::deque& SmapsData::PathIds() const +{ + return pathIds_; +} +const std::deque& SmapsData::SharedClean() const +{ + return sharedClean_; +} +const std::deque& SmapsData::SharedDirty() const +{ + return sharedDirty_; +} +const std::deque& SmapsData::PrivateClean() const +{ + return privateClean_; +} +const std::deque& SmapsData::PrivateDirty() const +{ + return privateDirty_; +} +const std::deque& SmapsData::Swap() const +{ + return swap_; +} +const std::deque& SmapsData::SwapPss() const +{ + return swapPss_; +} +const std::deque& SmapsData::Type() const +{ + return type_; +} +void SmapsData::Clear() +{ + CacheBase::Clear(); + ipids_.clear(); + startAddrs_.clear(); + endAddrs_.clear(); + dirtys_.clear(); + swappers_.clear(); + rss_.clear(); + pss_.clear(); + sizes_.clear(); + resides_.clear(); + protectionIds_.clear(); + pathIds_.clear(); + sharedClean_.clear(); + sharedDirty_.clear(); + privateClean_.clear(); + privateDirty_.clear(); + swap_.clear(); + swapPss_.clear(); + type_.clear(); +} + +void AshMemData::AppendNewData(InternalPid ipid, + uint64_t ts, + uint32_t adj, + uint32_t fd, + DataIndex ashmemNameId, + uint64_t size, + uint64_t pss, + uint32_t ashmemId, + uint64_t time, + uint64_t refCount, + uint64_t purged, + uint32_t flag) +{ + ipids_.emplace_back(ipid); + timeStamps_.emplace_back(ts); + adjs_.emplace_back(adj); + fds_.emplace_back(fd); + ashmemNameIds_.emplace_back(ashmemNameId); + sizes_.emplace_back(size); + psss_.emplace_back(pss); + ashmemIds_.emplace_back(ashmemId); + times_.emplace_back(time); + refCounts_.emplace_back(refCount); + purgeds_.emplace_back(purged); + flags_.emplace_back(flag); + ids_.emplace_back(rowCount_); + rowCount_++; +} +void AshMemData::SetFlag(uint64_t rowId, uint32_t flag) +{ + flags_[rowId] = flag; +} +const std::deque& AshMemData::Ipids() const +{ + return ipids_; +} +const std::deque& AshMemData::Adjs() const +{ + return adjs_; +} +const std::deque& AshMemData::Fds() const +{ + return fds_; +} +const std::deque& AshMemData::AshmemNameIds() const +{ + return ashmemNameIds_; +} +const std::deque& AshMemData::Sizes() const +{ + return sizes_; +} +const std::deque& AshMemData::Psss() const +{ + return psss_; +} +const std::deque& AshMemData::AshmemIds() const +{ + return ashmemIds_; +} +const std::deque& AshMemData::Times() const +{ + return times_; +} +const std::deque& AshMemData::RefCounts() const +{ + return refCounts_; +} +const std::deque& AshMemData::Purgeds() const +{ + return purgeds_; +} +const std::deque& AshMemData::Flags() const +{ + return flags_; +} +void AshMemData::Clear() +{ + CacheBase::Clear(); + ipids_.clear(); + adjs_.clear(); + fds_.clear(); + ashmemNameIds_.clear(); + sizes_.clear(); + psss_.clear(); + ashmemIds_.clear(); + times_.clear(); + refCounts_.clear(); + purgeds_.clear(); + flags_.clear(); +} + +void DmaMemData::AppendNewData(InternalPid ipid, + uint64_t ts, + uint32_t fd, + uint64_t size, + uint32_t ino, + uint32_t expPid, + DataIndex expTaskCommId, + DataIndex bufNameId, + DataIndex expNameId, + uint32_t flag) +{ + ipids_.emplace_back(ipid); + timeStamps_.emplace_back(ts); + fds_.emplace_back(fd); + sizes_.emplace_back(size); + inos_.emplace_back(ino); + expPids_.emplace_back(expPid); + expTaskCommIds_.emplace_back(expTaskCommId); + bufNameIds_.emplace_back(bufNameId); + expNameIds_.emplace_back(expNameId); + flags_.emplace_back(flag); + ids_.emplace_back(rowCount_); + rowCount_++; +} +void DmaMemData::SetFlag(uint64_t rowId, uint32_t flag) +{ + flags_[rowId] = flag; +} +const std::deque& DmaMemData::Ipids() const +{ + return ipids_; +} +const std::deque& DmaMemData::Fds() const +{ + return fds_; +} +const std::deque& DmaMemData::Sizes() const +{ + return sizes_; +} +const std::deque& DmaMemData::Inos() const +{ + return inos_; +} +const std::deque& DmaMemData::ExpPids() const +{ + return expPids_; +} +const std::deque& DmaMemData::ExpTaskCommIds() const +{ + return expTaskCommIds_; +} +const std::deque& DmaMemData::BufNameIds() const +{ + return bufNameIds_; +} +const std::deque& DmaMemData::ExpNameIds() const +{ + return expNameIds_; +} +const std::deque& DmaMemData::Flags() const +{ + return flags_; +} +void DmaMemData::Clear() +{ + CacheBase::Clear(); + ipids_.clear(); + fds_.clear(); + sizes_.clear(); + inos_.clear(); + expPids_.clear(); + expTaskCommIds_.clear(); + bufNameIds_.clear(); + expNameIds_.clear(); + flags_.clear(); +} + +void GpuProcessMemData::AppendNewData(uint64_t ts, + DataIndex gpuNameId, + uint64_t allGpuSize, + std::string addr, + InternalPid ipid, + InternalPid itid, + uint64_t usedGpuSize) +{ + timeStamps_.emplace_back(ts); + gpuNameIds_.emplace_back(gpuNameId); + allGpuSizes_.emplace_back(allGpuSize); + addrs_.emplace_back(addr); + ipids_.emplace_back(ipid); + itids_.emplace_back(itid); + usedGpuSizes_.emplace_back(usedGpuSize); + ids_.emplace_back(rowCount_); + rowCount_++; +} +const std::deque& GpuProcessMemData::GpuNameIds() const +{ + return gpuNameIds_; +} +const std::deque& GpuProcessMemData::AllGpuSizes() const +{ + return allGpuSizes_; +} +const std::deque& GpuProcessMemData::Addrs() const +{ + return addrs_; +} +const std::deque& GpuProcessMemData::Ipids() const +{ + return ipids_; +} +const std::deque& GpuProcessMemData::Itids() const +{ + return itids_; +} +const std::deque& GpuProcessMemData::UsedGpuSizes() const +{ + return usedGpuSizes_; +} +void GpuProcessMemData::Clear() +{ + CacheBase::Clear(); + gpuNameIds_.clear(); + allGpuSizes_.clear(); + addrs_.clear(); + ipids_.clear(); + itids_.clear(); + usedGpuSizes_.clear(); +} +void GpuWindowMemData::AppendNewData(uint64_t ts, + DataIndex windowNameId, + uint64_t windowId, + DataIndex moduleNameId, + DataIndex categoryNameId, + uint64_t size, + uint32_t count, + uint64_t purgeableSize) +{ + timeStamps_.emplace_back(ts); + windowNameIds_.emplace_back(windowNameId); + windowIds_.emplace_back(windowId); + moduleNameIds_.emplace_back(moduleNameId); + categoryNameIds_.emplace_back(categoryNameId); + sizes_.emplace_back(size); + counts_.emplace_back(count); + purgeableSizes_.emplace_back(purgeableSize); + ipids_.emplace_back(INVALID_IPID); + ids_.emplace_back(rowCount_); + rowCount_++; +} +const std::deque& GpuWindowMemData::WindowNameIds() const +{ + return windowNameIds_; +} +const std::deque& GpuWindowMemData::WindowIds() const +{ + return windowIds_; +} +const std::deque& GpuWindowMemData::ModuleNameIds() const +{ + return moduleNameIds_; +} +const std::deque& GpuWindowMemData::CategoryNameIds() const +{ + return categoryNameIds_; +} +const std::deque& GpuWindowMemData::Sizes() const +{ + return sizes_; +} +const std::deque& GpuWindowMemData::Counts() const +{ + return counts_; +} +const std::deque& GpuWindowMemData::PurgeableSizes() const +{ + return purgeableSizes_; +} +const std::deque& GpuWindowMemData::Ipids() const +{ + return ipids_; +} +void GpuWindowMemData::Clear() +{ + CacheBase::Clear(); + windowNameIds_.clear(); + windowIds_.clear(); + moduleNameIds_.clear(); + categoryNameIds_.clear(); + sizes_.clear(); + counts_.clear(); + purgeableSizes_.clear(); + ipids_.clear(); +} +void GpuWindowMemData::RevicesIpid(const std::map& windowIdToIpidMap) +{ + for (auto i = 0; i < Size(); i++) { + if (windowIdToIpidMap.count(windowNameIds_[i])) { + ipids_[i] = windowIdToIpidMap.at(windowNameIds_[i]); + } + } +} + +void CpuDumpInfo::AppendNewData(uint64_t timestamp, uint64_t size) +{ + timeStamps_.emplace_back(timestamp); + totalSizes_.emplace_back(size); + ids_.emplace_back(Size()); +} +const std::deque& CpuDumpInfo::TotalSizes() const +{ + return totalSizes_; +} +void CpuDumpInfo::Clear() +{ + CacheBase::Clear(); + totalSizes_.clear(); +} + +void ProfileMemInfo::AppendNewData(uint64_t timestamp, DataIndex channelIndex, uint64_t size) +{ + timeStamps_.emplace_back(timestamp); + totalSizes_.emplace_back(size); + channelIndexs_.emplace_back(channelIndex); + ids_.emplace_back(Size()); +} +const std::deque& ProfileMemInfo::ChannelIndexs() const +{ + return channelIndexs_; +} +const std::deque& ProfileMemInfo::TotalSizes() const +{ + return totalSizes_; +} +void ProfileMemInfo::Clear() +{ + CacheBase::Clear(); + channelIndexs_.clear(); + totalSizes_.clear(); +} + +void RSImageDumpInfo::AppendNewData(uint64_t timestamp, + uint64_t memSize, + DataIndex typeIndex, + InternalPid ipid, + DataIndex name) +{ + timeStamps_.emplace_back(timestamp); + memSizes_.emplace_back(memSize); + typeIndexs_.emplace_back(typeIndex); + ipids_.emplace_back(ipid); + surfaceNameIndexs_.emplace_back(name); + ids_.emplace_back(Size()); +} +const std::deque& RSImageDumpInfo::MemSizes() const +{ + return memSizes_; +} +const std::deque& RSImageDumpInfo::TypeIndexs() const +{ + return typeIndexs_; +} +const std::deque& RSImageDumpInfo::Ipids() const +{ + return ipids_; +} +const std::deque& RSImageDumpInfo::SurfaceNameIndexs() const +{ + return surfaceNameIndexs_; +} +void RSImageDumpInfo::Clear() +{ + CacheBase::Clear(); + memSizes_.clear(); + typeIndexs_.clear(); + ipids_.clear(); + surfaceNameIndexs_.clear(); +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/activity_monitor_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/htrace/activity_monitor_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..571b2c21e6a5d0273abc15022e4f2b9a075dee2f --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/activity_monitor_stdtype.h @@ -0,0 +1,415 @@ +/* + * 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 ACTIVITY_MONITOR_STDTYPE_H +#define ACTIVITY_MONITOR_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class Hidump : public CacheBase { +public: + size_t AppendNewHidumpInfo(uint64_t timeStamp, uint32_t fps); + const std::deque& Fpss() const; + void Clear() override; + +private: + std::deque fpss_ = {}; +}; + +class DiskIOData : public CacheBase { +public: + DiskIOData() = default; + ~DiskIOData() = default; + void AppendNewData(uint64_t ts, + uint64_t dur, + uint64_t rd, + uint64_t wr, + uint64_t rdPerSec, + uint64_t wrPerSec, + double rdCountPerSec, + double wrCountPerSec, + uint64_t rdCount, + uint64_t wrCount); + const std::deque& Durs() const; + const std::deque& RdDatas() const; + const std::deque& WrDatas() const; + const std::deque& RdSpeedDatas() const; + const std::deque& WrSpeedDatas() const; + const std::deque& RdCountPerSecDatas() const; + const std::deque& WrCountPerSecDatas() const; + const std::deque& RdCountDatas() const; + const std::deque& WrCountDatas() const; + void Clear() override; + +private: + std::deque durs_ = {}; + std::deque rdDatas_ = {}; + std::deque wrDatas_ = {}; + std::deque wrPerSec_ = {}; + std::deque rdPerSec_ = {}; + std::deque wrCountPerSec_ = {}; + std::deque rdCountPerSec_ = {}; + std::deque rdCountDatas_ = {}; + std::deque wrCountDatas_ = {}; +}; + +class LiveProcessDetailData : public CacheBase { +public: + size_t AppendNewData(uint64_t newTimeStamp, + uint64_t dur, + int32_t processID, + std::string processName, + int32_t parentProcessID, + int32_t uid, + std::string userName, + double cpuUsage, + int32_t pssInfo, + uint64_t cpuTime, + int32_t threads, + int64_t diskWrites, + int64_t diskReads); + const std::deque& Durs() const; + const std::deque& ProcessID() const; + const std::deque& ProcessName() const; + const std::deque& ParentProcessID() const; + const std::deque& Uid() const; + const std::deque& UserName() const; + const std::deque& CpuUsage() const; + const std::deque& PssInfo() const; + const std::deque& Threads() const; + const std::deque& DiskWrites() const; + const std::deque& DiskReads() const; + const std::deque& CpuTimes() const; + void Clear() override; + +private: + std::deque durs_ = {}; + std::deque processID_ = {}; + std::deque processName_ = {}; + std::deque parentProcessID_ = {}; + std::deque uid_ = {}; + std::deque userName_ = {}; + std::deque cpuUsage_ = {}; + std::deque pssInfo_ = {}; + std::deque threads_ = {}; + std::deque diskWrites_ = {}; + std::deque diskReads_ = {}; + std::deque cpuTimes_ = {}; +}; + +class CpuUsageDetailData : public CacheBase { +public: + size_t AppendNewData(uint64_t newTimeStamp, + uint64_t dur, + double totalLoad, + double userLoad, + double systemLoad, + int64_t threads); + const std::deque& Durs() const; + const std::deque& TotalLoad() const; + const std::deque& UserLoad() const; + const std::deque& SystemLoad() const; + const std::deque& Threads() const; + void Clear() override; + +private: + std::deque durs_ = {}; + std::deque totalLoad_ = {}; + std::deque userLoad_ = {}; + std::deque systemLoad_ = {}; + std::deque threads_ = {}; +}; + +class NetDetailData : public CacheBase { +public: + size_t AppendNewNetData(uint64_t newTimeStamp, + uint64_t tx, + uint64_t rx, + uint64_t dur, + double rxSpeed, + double txSpeed, + uint64_t packetIn, + double packetInSec, + uint64_t packetOut, + double packetOutSec, + const std::string& netType); + const std::deque& Durs() const; + const std::deque& RxSpeed() const; + const std::deque& TxSpeed() const; + const std::deque& NetTypes() const; + const std::deque& RxDatas() const; + const std::deque& TxDatas() const; + const std::deque& PacketIn() const; + const std::deque& PacketInSec() const; + const std::deque& PacketOut() const; + const std::deque& PacketOutSec() const; + void Clear() override; + +private: + std::deque rxs_ = {}; + std::deque txs_ = {}; + std::deque durs_ = {}; + std::deque rxSpeeds_ = {}; + std::deque txSpeeds_ = {}; + std::deque packetIn_ = {}; + std::deque packetInSec_ = {}; + std::deque packetOut_ = {}; + std::deque packetOutSec_ = {}; + std::deque netTypes_ = {}; +}; + +class SmapsData : public CacheBase { +public: + void AppendNewData(uint64_t timeStamp, + uint64_t ipid, + std::string startAddr, + std::string endAddr, + uint64_t dirty, + uint64_t swapper, + uint64_t rss, + uint64_t pss, + uint64_t size, + double reside, + DataIndex protectionId, + DataIndex pathId, + uint64_t sharedClean, + uint64_t sharedDirty, + uint64_t privateClean, + uint64_t privateDirty, + uint64_t swap, + uint64_t swapPss, + uint32_t type); + const std::deque& Id() const; + const std::deque& TimeStamps() const; + const std::deque& Ipids() const; + const std::deque& StartAddrs() const; + const std::deque& EndAddrs() const; + const std::deque& Dirtys() const; + const std::deque& Swappers() const; + const std::deque& Rss() const; + const std::deque& Pss() const; + const std::deque& Sizes() const; + const std::deque& Resides() const; + const std::deque& ProtectionIds() const; + const std::deque& PathIds() const; + const std::deque& SharedClean() const; + const std::deque& SharedDirty() const; + const std::deque& PrivateClean() const; + const std::deque& PrivateDirty() const; + const std::deque& Swap() const; + const std::deque& SwapPss() const; + const std::deque& Type() const; + void Clear() override; + +private: + std::deque ipids_ = {}; + std::deque startAddrs_ = {}; + std::deque endAddrs_ = {}; + std::deque dirtys_ = {}; + std::deque swappers_ = {}; + std::deque rss_ = {}; + std::deque pss_ = {}; + std::deque sizes_ = {}; + std::deque resides_ = {}; + std::deque protectionIds_ = {}; + std::deque pathIds_ = {}; + std::deque sharedClean_ = {}; + std::deque sharedDirty_ = {}; + std::deque privateClean_ = {}; + std::deque privateDirty_ = {}; + std::deque swap_ = {}; + std::deque swapPss_ = {}; + std::deque type_ = {}; + uint32_t rowCount_ = 0; +}; + +class AshMemData : public CacheBase { +public: + void AppendNewData(InternalPid ipid, + uint64_t ts, + uint32_t adj, + uint32_t fd, + DataIndex ashmemNameId, + uint64_t size, + uint64_t pss, + uint32_t ashmemId, + uint64_t time, + uint64_t refCount, + uint64_t purged, + uint32_t flag); + const std::deque& Ipids() const; + const std::deque& Adjs() const; + const std::deque& Fds() const; + const std::deque& AshmemNameIds() const; + const std::deque& Sizes() const; + const std::deque& Psss() const; + const std::deque& AshmemIds() const; + const std::deque& Times() const; + const std::deque& RefCounts() const; + const std::deque& Purgeds() const; + const std::deque& Flags() const; + void SetFlag(uint64_t rowId, uint32_t flag); + void Clear() override; + +private: + std::deque ipids_ = {}; + std::deque adjs_ = {}; + std::deque fds_ = {}; + std::deque ashmemNameIds_ = {}; + std::deque sizes_ = {}; + std::deque psss_ = {}; + std::deque ashmemIds_ = {}; + std::deque times_ = {}; + std::deque refCounts_ = {}; + std::deque purgeds_ = {}; + std::deque flags_ = {}; + uint32_t rowCount_ = 0; +}; + +class DmaMemData : public CacheBase { +public: + void AppendNewData(InternalPid ipid, + uint64_t ts, + uint32_t fd, + uint64_t size, + uint32_t ino, + uint32_t expPid, + DataIndex expTaskCommId, + DataIndex bufNameId, + DataIndex expNameId, + uint32_t flag); + const std::deque& Ipids() const; + const std::deque& Fds() const; + const std::deque& Sizes() const; + const std::deque& Inos() const; + const std::deque& ExpPids() const; + const std::deque& ExpTaskCommIds() const; + const std::deque& BufNameIds() const; + const std::deque& ExpNameIds() const; + const std::deque& Flags() const; + void SetFlag(uint64_t rowId, uint32_t flag); + void Clear() override; + +private: + std::deque ipids_ = {}; + std::deque fds_ = {}; + std::deque sizes_ = {}; + std::deque inos_ = {}; + std::deque expPids_ = {}; + std::deque expTaskCommIds_ = {}; + std::deque bufNameIds_ = {}; + std::deque expNameIds_ = {}; + std::deque flags_ = {}; + uint32_t rowCount_ = 0; +}; + +class GpuProcessMemData : public CacheBase { +public: + void AppendNewData(uint64_t ts, + DataIndex gpuNameId, + uint64_t allGpuSize, + std::string addr, + InternalPid ipid, + InternalPid itid, + uint64_t usedGpuSize); + const std::deque& GpuNameIds() const; + const std::deque& AllGpuSizes() const; + const std::deque& Addrs() const; + const std::deque& Ipids() const; + const std::deque& Itids() const; + const std::deque& UsedGpuSizes() const; + void Clear() override; + +private: + std::deque gpuNameIds_ = {}; + std::deque allGpuSizes_ = {}; + std::deque addrs_ = {}; + std::deque ipids_ = {}; + std::deque itids_ = {}; + std::deque usedGpuSizes_ = {}; + uint32_t rowCount_ = 0; +}; +class GpuWindowMemData : public CacheBase { +public: + void AppendNewData(uint64_t ts, + DataIndex windowNameId, + uint64_t windowId, + DataIndex moduleNameId, + DataIndex categoryNameId, + uint64_t size, + uint32_t count, + uint64_t purgeableSize); + void RevicesIpid(const std::map& windowIdToIpidMap); + const std::deque& WindowNameIds() const; + const std::deque& WindowIds() const; + const std::deque& ModuleNameIds() const; + const std::deque& CategoryNameIds() const; + const std::deque& Sizes() const; + const std::deque& Counts() const; + const std::deque& PurgeableSizes() const; + const std::deque& Ipids() const; + void Clear() override; + +private: + std::deque windowNameIds_ = {}; + std::deque windowIds_ = {}; + std::deque moduleNameIds_ = {}; + std::deque categoryNameIds_ = {}; + std::deque sizes_ = {}; + std::deque counts_ = {}; + std::deque purgeableSizes_ = {}; + std::deque ipids_ = {}; + uint32_t rowCount_ = 0; +}; +class CpuDumpInfo : public CacheBase { +public: + void AppendNewData(uint64_t timestamp, uint64_t size); + const std::deque& TotalSizes() const; + void Clear() override; + +private: + std::deque totalSizes_ = {}; +}; + +class ProfileMemInfo : public CacheBase { +public: + void AppendNewData(uint64_t timestamp, DataIndex channelIndex, uint64_t size); + const std::deque& ChannelIndexs() const; + const std::deque& TotalSizes() const; + void Clear() override; + +private: + std::deque channelIndexs_ = {}; + std::deque totalSizes_ = {}; +}; +class RSImageDumpInfo : public CacheBase { +public: + void AppendNewData(uint64_t timestamp, uint64_t memSize, DataIndex typeIndex, InternalPid ipid, DataIndex name); + const std::deque& MemSizes() const; + const std::deque& TypeIndexs() const; + const std::deque& Ipids() const; + const std::deque& SurfaceNameIndexs() const; + void Clear() override; + +private: + std::deque memSizes_ = {}; + std::deque typeIndexs_ = {}; + std::deque ipids_ = {}; + std::deque surfaceNameIndexs_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // ACTIVITY_MONITOR_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/arkts_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/htrace/arkts_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f58d25552633ae13b3fb7735377417fa8c740313 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/arkts_stdtype.cpp @@ -0,0 +1,497 @@ +/* + * 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 "arkts_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t JsHeapFiles::AppendNewData(uint32_t id, + std::string filePath, + uint64_t startTime, + uint64_t endTime, + uint64_t selfSizeCount) +{ + fileIds_.emplace_back(id); + filePaths_.emplace_back(filePath); + startTimes_.emplace_back(startTime); + endTimes_.emplace_back(endTime); + selfSizeCount_.emplace_back(selfSizeCount); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapFiles::IDs() const +{ + return fileIds_; +} +const std::deque& JsHeapFiles::FilePaths() const +{ + return filePaths_; +} +const std::deque& JsHeapFiles::StartTimes() const +{ + return startTimes_; +} +const std::deque& JsHeapFiles::EndTimes() const +{ + return endTimes_; +} + +const std::deque& JsHeapFiles::SelfSizeCount() const +{ + return selfSizeCount_; +} + +size_t JsHeapEdges::AppendNewData(uint32_t fileId, + uint32_t edgeIndex, + uint32_t type, + uint32_t nameOrIndex, + uint32_t toNode, + uint32_t fromNodeId, + uint32_t toNodeId) +{ + fileIds_.emplace_back(fileId); + edgeIndexs_.emplace_back(edgeIndex); + types_.emplace_back(type); + nameOrIndexs_.emplace_back(nameOrIndex); + toNodes_.emplace_back(toNode); + fromNodeIds_.emplace_back(fromNodeId); + toNodeIds_.emplace_back(toNodeId); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapEdges::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapEdges::EdgeIndexs() const +{ + return edgeIndexs_; +} +const std::deque& JsHeapEdges::Types() const +{ + return types_; +} +const std::deque& JsHeapEdges::NameOrIndexs() const +{ + return nameOrIndexs_; +} +const std::deque& JsHeapEdges::ToNodes() const +{ + return toNodes_; +} +const std::deque& JsHeapEdges::FromNodeIds() const +{ + return fromNodeIds_; +} +const std::deque& JsHeapEdges::ToNodeIds() const +{ + return toNodeIds_; +} + +size_t + JsHeapInfo::AppendNewData(uint32_t fileId, std::string key, uint32_t type, int32_t intValue, std::string strValue) +{ + fileIds_.emplace_back(fileId); + keys_.emplace_back(key); + types_.emplace_back(type); + intValues_.emplace_back(intValue); + strValues_.emplace_back(strValue); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapInfo::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapInfo::Keys() const +{ + return keys_; +} +const std::deque& JsHeapInfo::Types() const +{ + return types_; +} +const std::deque& JsHeapInfo::IntValues() const +{ + return intValues_; +} +const std::deque& JsHeapInfo::StrValues() const +{ + return strValues_; +} + +size_t JsHeapLocation::AppendNewData(uint32_t fileId, + uint32_t objectIndex, + uint32_t scriptId, + uint32_t line, + uint32_t column) +{ + fileIds_.emplace_back(fileId); + objectIndexs_.emplace_back(objectIndex); + scriptIds_.emplace_back(scriptId); + lines_.emplace_back(line); + columns_.emplace_back(column); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapLocation::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapLocation::ObjectIndexs() const +{ + return objectIndexs_; +} +const std::deque& JsHeapLocation::ScriptIds() const +{ + return scriptIds_; +} +const std::deque& JsHeapLocation::Lines() const +{ + return lines_; +} +const std::deque& JsHeapLocation::Columns() const +{ + return columns_; +} + +size_t JsHeapNodes::AppendNewData(uint32_t fileId, + uint32_t nodeIndex, + uint32_t type, + uint32_t name, + uint32_t id, + uint32_t selfSize, + uint32_t edgeCount, + uint32_t traceNodeId, + uint32_t detachedNess) +{ + fileIds_.emplace_back(fileId); + nodeIndexs_.emplace_back(nodeIndex); + types_.emplace_back(type); + names_.emplace_back(name); + nodeIds_.emplace_back(id); + selfSizes_.emplace_back(selfSize); + edgeCounts_.emplace_back(edgeCount); + traceNodeIds_.emplace_back(traceNodeId); + detachedNess_.emplace_back(detachedNess); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapNodes::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapNodes::NodeIndexs() const +{ + return nodeIndexs_; +} +const std::deque& JsHeapNodes::Types() const +{ + return types_; +} +const std::deque& JsHeapNodes::Names() const +{ + return names_; +} +const std::deque& JsHeapNodes::NodeIds() const +{ + return nodeIds_; +} +const std::deque& JsHeapNodes::SelfSizes() const +{ + return selfSizes_; +} +const std::deque& JsHeapNodes::EdgeCounts() const +{ + return edgeCounts_; +} +const std::deque& JsHeapNodes::TraceNodeIds() const +{ + return traceNodeIds_; +} +const std::deque& JsHeapNodes::DetachedNess() const +{ + return detachedNess_; +} + +size_t JsHeapSample::AppendNewData(uint32_t fileId, uint64_t timeStampUs, uint32_t lastAssignedId) +{ + fileIds_.emplace_back(fileId); + timeStampUs_.emplace_back(timeStampUs); + lastAssignedIds_.emplace_back(lastAssignedId); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapSample::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapSample::TimeStampUs() const +{ + return timeStampUs_; +} +const std::deque& JsHeapSample::LastAssignedIds() const +{ + return lastAssignedIds_; +} + +size_t JsHeapString::AppendNewData(uint32_t fileId, uint32_t fileIndex, std::string string) +{ + fileIds_.emplace_back(fileId); + fileIndexs_.emplace_back(fileIndex); + strings_.emplace_back(string); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapString::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapString::FileIndexs() const +{ + return fileIndexs_; +} +const std::deque& JsHeapString::Strings() const +{ + return strings_; +} + +size_t JsHeapTraceFuncInfo::AppendNewData(uint32_t fileId, + uint32_t functionIndex, + uint32_t functionId, + uint32_t name, + uint32_t scriptName, + uint32_t scriptId, + uint32_t line, + uint32_t column) +{ + fileIds_.emplace_back(fileId); + functionIndexs_.emplace_back(functionIndex); + functionIds_.emplace_back(functionId); + names_.emplace_back(name); + scriptNames_.emplace_back(scriptName); + scriptIds_.emplace_back(scriptId); + lines_.emplace_back(line); + columns_.emplace_back(column); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapTraceFuncInfo::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapTraceFuncInfo::FunctionIndexs() const +{ + return functionIndexs_; +} +const std::deque& JsHeapTraceFuncInfo::FunctionIds() const +{ + return functionIds_; +} +const std::deque& JsHeapTraceFuncInfo::Names() const +{ + return names_; +} +const std::deque& JsHeapTraceFuncInfo::ScriptNames() const +{ + return scriptNames_; +} +const std::deque& JsHeapTraceFuncInfo::ScriptIds() const +{ + return scriptIds_; +} +const std::deque& JsHeapTraceFuncInfo::Lines() const +{ + return lines_; +} +const std::deque& JsHeapTraceFuncInfo::Columns() const +{ + return columns_; +} + +size_t JsHeapTraceNode::AppendNewData(uint32_t fileId, + uint32_t traceNodeId, + uint32_t functionInfoIndex, + uint32_t count, + uint32_t size, + int32_t parentId) +{ + fileIds_.emplace_back(fileId); + traceNodeIds_.emplace_back(traceNodeId); + functionInfoIndexs_.emplace_back(functionInfoIndex); + counts_.emplace_back(count); + sizes_.emplace_back(size); + parentIds_.emplace_back(parentId); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsHeapTraceNode::FileIds() const +{ + return fileIds_; +} +const std::deque& JsHeapTraceNode::TraceNodeIDs() const +{ + return traceNodeIds_; +} +const std::deque& JsHeapTraceNode::FunctionInfoIndexs() const +{ + return functionInfoIndexs_; +} +const std::deque& JsHeapTraceNode::Counts() const +{ + return counts_; +} +const std::deque& JsHeapTraceNode::NodeSizes() const +{ + return sizes_; +} +const std::deque& JsHeapTraceNode::ParentIds() const +{ + return parentIds_; +} + +size_t JsCpuProfilerNode::AppendNewData(uint32_t functionId, + uint32_t functionName, + std::string scriptId, + uint32_t url, + uint32_t lineNumber, + uint32_t columnNumber, + uint32_t hitCount, + std::string children, + uint32_t parent) +{ + functionIds_.emplace_back(functionId); + functionNames_.emplace_back(functionName); + scriptIds_.emplace_back(scriptId); + urls_.emplace_back(url); + lineNumbers_.emplace_back(lineNumber); + columnNumbers_.emplace_back(columnNumber); + hitCounts_.emplace_back(hitCount); + children_.emplace_back(children); + parents_.emplace_back(parent); + ids_.emplace_back(Size()); + return Size() - 1; +} + +const std::deque& JsCpuProfilerNode::FunctionIds() const +{ + return functionIds_; +} +const std::deque& JsCpuProfilerNode::FunctionNames() const +{ + return functionNames_; +} +const std::deque& JsCpuProfilerNode::ScriptIds() const +{ + return scriptIds_; +} +const std::deque& JsCpuProfilerNode::Urls() const +{ + return urls_; +} +const std::deque& JsCpuProfilerNode::LineNumbers() const +{ + return lineNumbers_; +} +const std::deque& JsCpuProfilerNode::ColumnNumbers() const +{ + return columnNumbers_; +} +const std::deque& JsCpuProfilerNode::HitCounts() const +{ + return hitCounts_; +} +const std::deque& JsCpuProfilerNode::Children() const +{ + return children_; +} +const std::deque& JsCpuProfilerNode::Parents() const +{ + return parents_; +} + +size_t JsCpuProfilerSample::AppendNewData(uint32_t functionId, uint64_t startTime, uint64_t endTime, uint64_t dur) +{ + functionIds_.emplace_back(functionId); + startTimes_.emplace_back(startTime); + endTimes_.emplace_back(endTime); + durs_.emplace_back(dur); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsCpuProfilerSample::FunctionIds() const +{ + return functionIds_; +} +const std::deque& JsCpuProfilerSample::StartTimes() const +{ + return startTimes_; +} +const std::deque& JsCpuProfilerSample::EndTimes() const +{ + return endTimes_; +} +const std::deque& JsCpuProfilerSample::Durs() const +{ + return durs_; +} + +size_t JsConfig::AppendNewData(uint32_t pid, + uint64_t type, + uint32_t interval, + uint32_t captureNumericValue, + uint32_t trackAllocation, + uint32_t cpuProfiler, + uint32_t cpuProfilerInterval) +{ + pids_.emplace_back(pid); + types_.emplace_back(type); + intervals_.emplace_back(interval); + captureNumericValues_.emplace_back(captureNumericValue); + trackAllocations_.emplace_back(trackAllocation); + cpuProfilers_.emplace_back(cpuProfiler); + cpuProfilerIntervals_.emplace_back(cpuProfilerInterval); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& JsConfig::Pids() const +{ + return pids_; +} +const std::deque& JsConfig::Types() const +{ + return types_; +} +const std::deque& JsConfig::Intervals() const +{ + return intervals_; +} +const std::deque& JsConfig::CaptureNumericValue() const +{ + return captureNumericValues_; +} +const std::deque& JsConfig::TrackAllocations() const +{ + return trackAllocations_; +} +const std::deque& JsConfig::CpuProfiler() const +{ + return cpuProfilers_; +} +const std::deque& JsConfig::CpuProfilerInterval() const +{ + return cpuProfilerIntervals_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/arkts_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/htrace/arkts_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..ad0ac3fd8efd0423e638b0fa75613a419471c725 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/arkts_stdtype.h @@ -0,0 +1,409 @@ +/* + * 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 ARKTS_STDTYPE_H +#define ARKTS_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class JsHeapFiles : public CacheBase { +public: + size_t + AppendNewData(uint32_t id, std::string filePath, uint64_t startTime, uint64_t endTime, uint64_t selfSizeCount); + const std::deque& IDs() const; + const std::deque& FilePaths() const; + const std::deque& StartTimes() const; + const std::deque& EndTimes() const; + const std::deque& SelfSizeCount() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + filePaths_.clear(); + startTimes_.clear(); + endTimes_.clear(); + selfSizeCount_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque filePaths_ = {}; + std::deque startTimes_ = {}; + std::deque endTimes_ = {}; + std::deque selfSizeCount_ = {}; +}; + +class JsHeapEdges : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, + uint32_t edgeIndex, + uint32_t type, + uint32_t nameOrIndex, + uint32_t toNode, + uint32_t fromNodeId, + uint32_t toNodeId); + const std::deque& FileIds() const; + const std::deque& EdgeIndexs() const; + const std::deque& Types() const; + const std::deque& NameOrIndexs() const; + const std::deque& ToNodes() const; + const std::deque& FromNodeIds() const; + const std::deque& ToNodeIds() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + edgeIndexs_.clear(); + types_.clear(); + nameOrIndexs_.clear(); + toNodes_.clear(); + fromNodeIds_.clear(); + toNodeIds_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque edgeIndexs_ = {}; + std::deque types_ = {}; + std::deque nameOrIndexs_ = {}; + std::deque toNodes_ = {}; + std::deque fromNodeIds_ = {}; + std::deque toNodeIds_ = {}; +}; + +class JsHeapInfo : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, std::string key, uint32_t type, int32_t intValue, std::string strValue); + const std::deque& FileIds() const; + const std::deque& Keys() const; + const std::deque& Types() const; + const std::deque& IntValues() const; + const std::deque& StrValues() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + keys_.clear(); + types_.clear(); + intValues_.clear(); + strValues_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque keys_ = {}; + std::deque types_ = {}; + std::deque intValues_ = {}; + std::deque strValues_ = {}; +}; + +class JsHeapLocation : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, uint32_t objectIndex, uint32_t scriptId, uint32_t line, uint32_t column); + const std::deque& FileIds() const; + const std::deque& ObjectIndexs() const; + const std::deque& ScriptIds() const; + const std::deque& Lines() const; + const std::deque& Columns() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + objectIndexs_.clear(); + scriptIds_.clear(); + lines_.clear(); + columns_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque objectIndexs_ = {}; + std::deque scriptIds_ = {}; + std::deque lines_ = {}; + std::deque columns_ = {}; +}; + +class JsHeapNodes : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, + uint32_t nodeIndex, + uint32_t type, + uint32_t name, + uint32_t id, + uint32_t selfSize, + uint32_t edgeCount, + uint32_t traceNodeId, + uint32_t detachedNess); + const std::deque& FileIds() const; + const std::deque& NodeIndexs() const; + const std::deque& Types() const; + const std::deque& Names() const; + const std::deque& NodeIds() const; + const std::deque& SelfSizes() const; + const std::deque& EdgeCounts() const; + const std::deque& TraceNodeIds() const; + const std::deque& DetachedNess() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + nodeIndexs_.clear(); + types_.clear(); + names_.clear(); + nodeIds_.clear(); + selfSizes_.clear(); + edgeCounts_.clear(); + traceNodeIds_.clear(); + detachedNess_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque nodeIndexs_ = {}; + std::deque types_ = {}; + std::deque names_ = {}; + std::deque nodeIds_ = {}; + std::deque selfSizes_ = {}; + std::deque edgeCounts_ = {}; + std::deque traceNodeIds_ = {}; + std::deque detachedNess_ = {}; +}; + +class JsHeapSample : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, uint64_t timeStampUs, uint32_t lastAssignedId); + const std::deque& FileIds() const; + const std::deque& TimeStampUs() const; + const std::deque& LastAssignedIds() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + timeStampUs_.clear(); + lastAssignedIds_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque timeStampUs_ = {}; + std::deque lastAssignedIds_ = {}; +}; + +class JsHeapString : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, uint32_t fileIndex, std::string string); + const std::deque& FileIds() const; + const std::deque& FileIndexs() const; + const std::deque& Strings() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + fileIndexs_.clear(); + strings_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque fileIndexs_ = {}; + std::deque strings_ = {}; +}; + +class JsHeapTraceFuncInfo : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, + uint32_t functionIndex, + uint32_t functionId, + uint32_t name, + uint32_t scriptName, + uint32_t scriptId, + uint32_t line, + uint32_t column); + const std::deque& FileIds() const; + const std::deque& FunctionIndexs() const; + const std::deque& FunctionIds() const; + const std::deque& Names() const; + const std::deque& ScriptNames() const; + const std::deque& ScriptIds() const; + const std::deque& Lines() const; + const std::deque& Columns() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + functionIndexs_.clear(); + functionIds_.clear(); + names_.clear(); + scriptNames_.clear(); + scriptIds_.clear(); + lines_.clear(); + columns_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque functionIndexs_ = {}; + std::deque functionIds_ = {}; + std::deque names_ = {}; + std::deque scriptNames_ = {}; + std::deque scriptIds_ = {}; + std::deque lines_ = {}; + std::deque columns_ = {}; +}; + +class JsHeapTraceNode : public CacheBase { +public: + size_t AppendNewData(uint32_t fileId, + uint32_t traceNodeId, + uint32_t functionInfoIndex, + uint32_t count, + uint32_t size, + int32_t parentId); + const std::deque& FileIds() const; + const std::deque& TraceNodeIDs() const; + const std::deque& FunctionInfoIndexs() const; + const std::deque& Counts() const; + const std::deque& NodeSizes() const; + const std::deque& ParentIds() const; + void Clear() override + { + CacheBase::Clear(); + fileIds_.clear(); + traceNodeIds_.clear(); + functionInfoIndexs_.clear(); + counts_.clear(); + sizes_.clear(); + parentIds_.clear(); + } + +private: + std::deque fileIds_ = {}; + std::deque traceNodeIds_ = {}; + std::deque functionInfoIndexs_ = {}; + std::deque counts_ = {}; + std::deque sizes_ = {}; + std::deque parentIds_ = {}; +}; + +class JsConfig : public CacheBase { +public: + size_t AppendNewData(uint32_t pid, + uint64_t type, + uint32_t interval, + uint32_t captureNumericValue, + uint32_t trackAllocation, + uint32_t cpuProfiler, + uint32_t cpuProfilerInterval); + const std::deque& Pids() const; + const std::deque& Types() const; + const std::deque& Intervals() const; + const std::deque& CaptureNumericValue() const; + const std::deque& TrackAllocations() const; + const std::deque& CpuProfiler() const; + const std::deque& CpuProfilerInterval() const; + void Clear() override + { + CacheBase::Clear(); + pids_.clear(); + types_.clear(); + intervals_.clear(); + captureNumericValues_.clear(); + trackAllocations_.clear(); + cpuProfilers_.clear(); + cpuProfilerIntervals_.clear(); + } + +private: + std::deque pids_ = {}; + std::deque types_ = {}; + std::deque intervals_ = {}; + std::deque captureNumericValues_ = {}; + std::deque trackAllocations_ = {}; + std::deque cpuProfilers_ = {}; + std::deque cpuProfilerIntervals_ = {}; +}; + +class JsCpuProfilerNode : public CacheBase { +public: + size_t AppendNewData(uint32_t functionId, + uint32_t functionName, + std::string scriptId, + uint32_t url, + uint32_t lineNumber, + uint32_t columnNumber, + uint32_t hitCount, + std::string children, + uint32_t parent); + const std::deque& FunctionIds() const; + const std::deque& FunctionNames() const; + const std::deque& ScriptIds() const; + const std::deque& Urls() const; + const std::deque& LineNumbers() const; + const std::deque& ColumnNumbers() const; + const std::deque& HitCounts() const; + const std::deque& Children() const; + const std::deque& Parents() const; + void Clear() override + { + CacheBase::Clear(); + functionIds_.clear(); + functionNames_.clear(); + scriptIds_.clear(); + urls_.clear(); + lineNumbers_.clear(); + columnNumbers_.clear(); + hitCounts_.clear(); + children_.clear(); + parents_.clear(); + } + +private: + std::deque functionIds_ = {}; + std::deque functionNames_ = {}; + std::deque scriptIds_ = {}; + std::deque urls_ = {}; + std::deque lineNumbers_ = {}; + std::deque columnNumbers_ = {}; + std::deque hitCounts_ = {}; + std::deque children_ = {}; + std::deque parents_ = {}; +}; + +class JsCpuProfilerSample : public CacheBase { +public: + size_t AppendNewData(uint32_t functionId, uint64_t startTime, uint64_t endTime, uint64_t dur); + const std::deque& FunctionIds() const; + const std::deque& StartTimes() const; + const std::deque& EndTimes() const; + const std::deque& Durs() const; + void Clear() override + { + CacheBase::Clear(); + functionIds_.clear(); + startTimes_.clear(); + endTimes_.clear(); + durs_.clear(); + } + +private: + std::deque functionIds_ = {}; + std::deque startTimes_ = {}; + std::deque endTimes_ = {}; + std::deque durs_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // ARKTS_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/ebpf_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/htrace/ebpf_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a181022840a2136761148a35e59924c06f00eb4 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/ebpf_stdtype.cpp @@ -0,0 +1,305 @@ +/* + * 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 "ebpf_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t FileSystemSample::AppendNewData(uint32_t callChainId, + uint16_t type, + uint32_t ipid, + uint32_t itid, + uint64_t startTs, + uint64_t endTs, + uint64_t dur, + DataIndex returnValue, + DataIndex errorCode, + size_t size, + int32_t fd, + DataIndex fileId, + DataIndex firstArgument, + DataIndex secondArgument, + DataIndex thirdArgument, + DataIndex fourthArgument) +{ + callChainIds_.emplace_back(callChainId); + types_.emplace_back(type); + ipids_.emplace_back(ipid); + itids_.emplace_back(itid); + startTs_.emplace_back(startTs); + endTs_.emplace_back(endTs); + durs_.emplace_back(dur); + returnValues_.emplace_back(returnValue); + errorCodes_.emplace_back(errorCode); + fds_.emplace_back(fd); + fileIds_.emplace_back(fileId); + Sizes_.emplace_back(size); + firstArguments_.emplace_back(firstArgument); + secondArguments_.emplace_back(secondArgument); + thirdArguments_.emplace_back(thirdArgument); + fourthArguments_.emplace_back(fourthArgument); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& FileSystemSample::CallChainIds() const +{ + return callChainIds_; +} +const std::deque& FileSystemSample::Types() const +{ + return types_; +} +const std::deque& FileSystemSample::Ipids() const +{ + return ipids_; +} +const std::deque& FileSystemSample::Itids() const +{ + return itids_; +} +const std::deque& FileSystemSample::StartTs() const +{ + return startTs_; +} +const std::deque& FileSystemSample::EndTs() const +{ + return endTs_; +} +const std::deque& FileSystemSample::Durs() const +{ + return durs_; +} +const std::deque& FileSystemSample::ReturnValues() const +{ + return returnValues_; +} +const std::deque& FileSystemSample::ErrorCodes() const +{ + return errorCodes_; +} +const std::deque& FileSystemSample::Fds() const +{ + return fds_; +} +const std::deque& FileSystemSample::FileIds() const +{ + return fileIds_; +} +const std::deque& FileSystemSample::Sizes() const +{ + return Sizes_; +} +const std::deque& FileSystemSample::FirstArguments() const +{ + return firstArguments_; +} +const std::deque& FileSystemSample::SecondArguments() const +{ + return secondArguments_; +} +const std::deque& FileSystemSample::ThirdArguments() const +{ + return thirdArguments_; +} +const std::deque& FileSystemSample::FourthArguments() const +{ + return fourthArguments_; +} + +size_t PagedMemorySampleData::AppendNewData(uint32_t callChainId, + uint16_t type, + uint32_t ipid, + uint64_t startTs, + uint64_t endTs, + uint64_t dur, + size_t size, + DataIndex addr, + uint32_t itid) +{ + callChainIds_.emplace_back(callChainId); + types_.emplace_back(type); + ipids_.emplace_back(ipid); + startTs_.emplace_back(startTs); + endTs_.emplace_back(endTs); + durs_.emplace_back(dur); + Sizes_.emplace_back(size); + addrs_.emplace_back(addr); + itids_.emplace_back(itid); + ids_.emplace_back(Size()); + return Size() - 1; +} +const std::deque& PagedMemorySampleData::CallChainIds() const +{ + return callChainIds_; +} +const std::deque& PagedMemorySampleData::Types() const +{ + return types_; +} +const std::deque& PagedMemorySampleData::Ipids() const +{ + return ipids_; +} +const std::deque& PagedMemorySampleData::Itids() const +{ + return itids_; +} +const std::deque& PagedMemorySampleData::StartTs() const +{ + return startTs_; +} +const std::deque& PagedMemorySampleData::EndTs() const +{ + return endTs_; +} +const std::deque& PagedMemorySampleData::Durs() const +{ + return durs_; +} +const std::deque& PagedMemorySampleData::Sizes() const +{ + return Sizes_; +} +const std::deque& PagedMemorySampleData::Addr() const +{ + return addrs_; +} + +void BioLatencySampleData::AppendNewData(uint32_t callChainId, + uint64_t type, + uint32_t ipid, + uint32_t itid, + uint64_t startTs, + uint64_t endTs, + uint64_t latencyDur, + uint32_t tier, + uint64_t size, + uint64_t blockNumber, + uint64_t filePathId, + uint64_t durPer4k) +{ + callChainIds_.emplace_back(callChainId); + types_.emplace_back(type); + ipids_.emplace_back(ipid); + itids_.emplace_back(itid); + startTs_.emplace_back(startTs); + endTs_.emplace_back(endTs); + latencyDurs_.emplace_back(latencyDur); + tiers_.emplace_back(tier); + sizes_.emplace_back(size); + blockNumbers_.emplace_back(blockNumber); + filePathIds_.emplace_back(filePathId); + durPer4ks_.emplace_back(durPer4k); + ids_.emplace_back(rowCount_); + rowCount_++; +} +const std::deque& BioLatencySampleData::CallChainIds() const +{ + return callChainIds_; +} +const std::deque& BioLatencySampleData::Types() const +{ + return types_; +} +const std::deque& BioLatencySampleData::Ipids() const +{ + return ipids_; +} +const std::deque& BioLatencySampleData::Itids() const +{ + return itids_; +} +const std::deque& BioLatencySampleData::StartTs() const +{ + return startTs_; +} +const std::deque& BioLatencySampleData::EndTs() const +{ + return endTs_; +} +const std::deque& BioLatencySampleData::LatencyDurs() const +{ + return latencyDurs_; +} +const std::deque& BioLatencySampleData::Tiers() const +{ + return tiers_; +} +const std::deque& BioLatencySampleData::Sizes() const +{ + return sizes_; +} +const std::deque& BioLatencySampleData::BlockNumbers() const +{ + return blockNumbers_; +} +const std::deque& BioLatencySampleData::FilePathIds() const +{ + return filePathIds_; +} +const std::deque& BioLatencySampleData::DurPer4k() const +{ + return durPer4ks_; +} + +size_t EbpfCallStackData::AppendNewData(uint32_t callChainId, + uint32_t depth, + DataIndex ip, + DataIndex symbolId, + DataIndex filePathId, + uint64_t vaddr) +{ + callChainIds_.emplace_back(callChainId); + depths_.emplace_back(depth); + ips_.emplace_back(ip); + symbolIds_.emplace_back(symbolId); + filePathIds_.emplace_back(filePathId); + vaddrs_.emplace_back(vaddr); + ids_.emplace_back(Size()); + return Size() - 1; +} +void EbpfCallStackData::UpdateEbpfSymbolInfo(size_t row, DataIndex symbolId) +{ + if (row >= Size()) { + TS_LOGE("The updated row does not exist!"); + return; + } + symbolIds_[row] = symbolId; +} +const std::deque& EbpfCallStackData::CallChainIds() const +{ + return callChainIds_; +} +const std::deque& EbpfCallStackData::Depths() const +{ + return depths_; +} +const std::deque& EbpfCallStackData::Ips() const +{ + return ips_; +} +const std::deque& EbpfCallStackData::SymbolIds() const +{ + return symbolIds_; +} +const std::deque& EbpfCallStackData::FilePathIds() const +{ + return filePathIds_; +} +const std::deque& EbpfCallStackData::Vaddrs() const +{ + return vaddrs_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/ebpf_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/htrace/ebpf_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..a02dcbc2448c96e6a8424b9918043c37a1074683 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/ebpf_stdtype.h @@ -0,0 +1,233 @@ +/* + * 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 EBPF_STDTYPE_H +#define EBPF_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class FileSystemSample : public CacheBase { +public: + size_t AppendNewData(uint32_t callChainId, + uint16_t type, + uint32_t ipid, + uint32_t itid, + uint64_t startTs, + uint64_t endTs, + uint64_t dur, + DataIndex returnValue, + DataIndex errorCode, + size_t size, + int32_t fd, + DataIndex fileId, + DataIndex firstArgument, + DataIndex secondArgument, + DataIndex thirdArgument, + DataIndex fourthArgument); + const std::deque& CallChainIds() const; + const std::deque& Types() const; + const std::deque& Ipids() const; + const std::deque& Itids() const; + const std::deque& StartTs() const; + const std::deque& EndTs() const; + const std::deque& Durs() const; + const std::deque& ReturnValues() const; + const std::deque& ErrorCodes() const; + const std::deque& Fds() const; + const std::deque& FileIds() const; + const std::deque& Sizes() const; + const std::deque& FirstArguments() const; + const std::deque& SecondArguments() const; + const std::deque& ThirdArguments() const; + const std::deque& FourthArguments() const; + void Clear() override + { + CacheBase::Clear(); + callChainIds_.clear(); + types_.clear(); + ipids_.clear(); + itids_.clear(); + startTs_.clear(); + endTs_.clear(); + durs_.clear(); + returnValues_.clear(); + errorCodes_.clear(); + fds_.clear(); + Sizes_.clear(); + firstArguments_.clear(); + secondArguments_.clear(); + thirdArguments_.clear(); + fourthArguments_.clear(); + } + +private: + std::deque callChainIds_ = {}; + std::deque types_ = {}; + std::deque ipids_ = {}; + std::deque itids_ = {}; + std::deque startTs_ = {}; + std::deque endTs_ = {}; + std::deque durs_ = {}; + std::deque returnValues_ = {}; + std::deque errorCodes_ = {}; + std::deque fds_ = {}; + std::deque fileIds_ = {}; + std::deque Sizes_ = {}; + std::deque firstArguments_ = {}; + std::deque secondArguments_ = {}; + std::deque thirdArguments_ = {}; + std::deque fourthArguments_ = {}; +}; + +class PagedMemorySampleData : public CacheBase { +public: + size_t AppendNewData(uint32_t callChainId, + uint16_t type, + uint32_t ipid, + uint64_t startTs, + uint64_t endTs, + uint64_t dur, + size_t size, + DataIndex addr, + uint32_t itid); + const std::deque& CallChainIds() const; + const std::deque& Types() const; + const std::deque& Ipids() const; + const std::deque& StartTs() const; + const std::deque& EndTs() const; + const std::deque& Durs() const; + const std::deque& Sizes() const; + const std::deque& Addr() const; + const std::deque& Itids() const; + void Clear() override + { + CacheBase::Clear(); + callChainIds_.clear(); + types_.clear(); + ipids_.clear(); + startTs_.clear(); + endTs_.clear(); + durs_.clear(); + Sizes_.clear(); + addrs_.clear(); + itids_.clear(); + } + +private: + std::deque callChainIds_ = {}; + std::deque types_ = {}; + std::deque ipids_ = {}; + std::deque startTs_ = {}; + std::deque endTs_ = {}; + std::deque durs_ = {}; + std::deque Sizes_ = {}; + std::deque addrs_ = {}; + std::deque itids_ = {}; +}; +class BioLatencySampleData : public CacheBase { +public: + void AppendNewData(uint32_t callChainId, + uint64_t type, + uint32_t ipid, + uint32_t itid, + uint64_t startTs, + uint64_t endTs, + uint64_t latencyDur, + uint32_t tier, + uint64_t size, + uint64_t blockNumber, + uint64_t filePathId, + uint64_t durPer4k); + const std::deque& CallChainIds() const; + const std::deque& Types() const; + const std::deque& Ipids() const; + const std::deque& Itids() const; + const std::deque& StartTs() const; + const std::deque& EndTs() const; + const std::deque& LatencyDurs() const; + const std::deque& Tiers() const; + const std::deque& Sizes() const; + const std::deque& BlockNumbers() const; + const std::deque& FilePathIds() const; + const std::deque& DurPer4k() const; + void Clear() override + { + CacheBase::Clear(); + callChainIds_.clear(); + types_.clear(); + ipids_.clear(); + itids_.clear(); + startTs_.clear(); + endTs_.clear(); + latencyDurs_.clear(); + tiers_.clear(); + sizes_.clear(); + blockNumbers_.clear(); + filePathIds_.clear(); + durPer4ks_.clear(); + } + +private: + std::deque callChainIds_ = {}; + std::deque types_ = {}; + std::deque ipids_ = {}; + std::deque itids_ = {}; + std::deque startTs_ = {}; + std::deque endTs_ = {}; + std::deque latencyDurs_ = {}; + std::deque tiers_ = {}; + std::deque sizes_ = {}; + std::deque blockNumbers_ = {}; + std::deque filePathIds_ = {}; + std::deque durPer4ks_ = {}; + uint32_t rowCount_ = 0; +}; +class EbpfCallStackData : public CacheBase { +public: + size_t AppendNewData(uint32_t callChainId, + uint32_t depth, + DataIndex ip, + DataIndex symbolId, + DataIndex filePathId, + uint64_t vaddr); + void UpdateEbpfSymbolInfo(size_t row, DataIndex symbolId); + const std::deque& CallChainIds() const; + const std::deque& Depths() const; + const std::deque& Ips() const; + const std::deque& SymbolIds() const; + const std::deque& FilePathIds() const; + const std::deque& Vaddrs() const; + void Clear() override + { + CacheBase::Clear(); + callChainIds_.clear(); + depths_.clear(); + symbolIds_.clear(); + filePathIds_.clear(); + vaddrs_.clear(); + } + +private: + std::deque callChainIds_ = {}; + std::deque depths_ = {}; + std::deque ips_ = {}; + std::deque symbolIds_ = {}; + std::deque filePathIds_ = {}; + std::deque vaddrs_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // EBPF_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/native_memory_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/htrace/native_memory_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..854585a44b74ef7c71c7d5e2c2ef51c747abdcde --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/native_memory_stdtype.cpp @@ -0,0 +1,332 @@ +/* + * 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 "native_memory_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +void NativeHookSampleBase::AppendNativeHookSampleBase(uint32_t callChainId, + uint32_t ipid, + uint32_t itid, + uint64_t timeStamp) +{ + ids_.emplace_back(id_++); + 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(id_++); + 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, + uint32_t ipid, + uint32_t itid, + std::string eventType, + DataIndex subType, + uint64_t timeStamp, + uint64_t endTimeStamp, + uint64_t duration, + uint64_t addr, + int64_t memSize) +{ + AppendNativeHookSampleBase(callChainId, ipid, itid, timeStamp); + eventTypes_.emplace_back(eventType); + subTypes_.emplace_back(subType); + endTimeStamps_.emplace_back(endTimeStamp); + durations_.emplace_back(duration); + addrs_.emplace_back(addr); + memSizes_.emplace_back(memSize); + if (eventType == ALLOC_EVET) { + countHeapSizes_ += memSize; + allMemSizes_.emplace_back(countHeapSizes_); + } else if (eventType == FREE_EVENT) { + countHeapSizes_ -= memSize; + allMemSizes_.emplace_back(countHeapSizes_); + } else if (eventType == MMAP_EVENT) { + countMmapSizes_ += memSize; + allMemSizes_.emplace_back(countMmapSizes_); + } else if (eventType == MUNMAP_EVENT) { + countMmapSizes_ -= memSize; + allMemSizes_.emplace_back(countMmapSizes_); + } + currentSizeDurs_.emplace_back(0); + 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; + durations_[row] = endTimeStamp - timeStamps_[row]; +} +void NativeHook::UpdateCurrentSizeDur(size_t row, uint64_t timeStamp) +{ + currentSizeDurs_[row] = timeStamp - timeStamps_[row]; +} +void NativeHook::UpdateMemMapSubType(uint64_t row, uint64_t tagId) +{ + if (row < subTypes_.size()) { + subTypes_[row] = tagId; + } else { + TS_LOGE("subTypes_ row is invalid!"); + } +} +const std::deque& NativeHook::EventTypes() const +{ + return eventTypes_; +} +const std::deque& NativeHook::SubTypes() const +{ + return subTypes_; +} +const std::deque& NativeHook::EndTimeStamps() const +{ + return endTimeStamps_; +} +const std::deque& NativeHook::Durations() const +{ + return durations_; +} +const std::deque& NativeHook::Addrs() const +{ + return addrs_; +} +const std::deque& NativeHook::MemSizes() const +{ + return memSizes_; +} +const std::deque& NativeHook::AllMemSizes() const +{ + return allMemSizes_; +} +const std::deque& NativeHook::CurrentSizeDurs() const +{ + return currentSizeDurs_; +} +size_t NativeHookFrame::AppendNewNativeHookFrame(uint32_t callChainId, + uint16_t depth, + uint64_t ip, + DataIndex symbolName, + DataIndex filePath, + uint64_t offset, + uint64_t symbolOffset, + const std::string& vaddr) +{ + callChainIds_.emplace_back(callChainId); + ips_.emplace_back(ip); + depths_.emplace_back(depth); + symbolNames_.emplace_back(symbolName); + filePaths_.emplace_back(filePath); + offsets_.emplace_back(offset); + symbolOffsets_.emplace_back(symbolOffset); + vaddrs_.emplace_back(vaddr); + return Size() - 1; +} +size_t NativeHookFrame::AppendNewNativeHookFrame(uint32_t callChainId, + uint16_t depth, + uint64_t ip, + DataIndex symbolName, + DataIndex filePath, + uint64_t offset, + uint64_t symbolOffset) +{ + callChainIds_.emplace_back(callChainId); + ips_.emplace_back(ip); + depths_.emplace_back(depth); + symbolNames_.emplace_back(symbolName); + filePaths_.emplace_back(filePath); + offsets_.emplace_back(offset); + symbolOffsets_.emplace_back(symbolOffset); + return Size() - 1; +} +void NativeHookFrame::UpdateSymbolIdToNameMap(uint64_t originSymbolId, uint64_t symbolId) +{ + symbolIdToSymbolName_.insert(std::make_pair(originSymbolId, symbolId)); +} +void NativeHookFrame::UpdateFrameInfo(size_t row, + DataIndex symbolIndex, + DataIndex filePathIndex, + uint64_t offset, + uint64_t symbolOffset) +{ + if (row >= Size()) { + TS_LOGE("The updated row does not exist!"); + return; + } + symbolNames_[row] = symbolIndex; + filePaths_[row] = filePathIndex; + offsets_[row] = offset; + symbolOffsets_[row] = symbolOffset; +} + +void NativeHookFrame::UpdateSymbolId() +{ + if (symbolIdToSymbolName_.empty()) { + return; + } + for (auto i = 0; i < Size(); ++i) { + auto symbolIt = symbolIdToSymbolName_.find(symbolNames_[i]); + if (symbolIt != symbolIdToSymbolName_.end()) { + symbolNames_[i] = symbolIt->second; + } + } +} +void NativeHookFrame::UpdateSymbolId(size_t index, DataIndex symbolId) +{ + if (index < Size()) { + symbolNames_[index] = symbolId; + } +} +void NativeHookFrame::UpdateFileId(std::map& filePathIdToFilePathName) +{ + if (filePathIdToFilePathName.empty()) { + return; + } + for (auto i = 0; i < Size(); ++i) { + auto symbolIt = filePathIdToFilePathName.find(filePaths_[i]); + if (symbolIt != filePathIdToFilePathName.end()) { + filePaths_[i] = symbolIt->second; + } + } +} +void NativeHookFrame::UpdateVaddrs(std::deque& vaddrs) +{ + vaddrs_.assign(vaddrs.begin(), vaddrs.end()); +} +const std::deque& NativeHookFrame::CallChainIds() const +{ + return callChainIds_; +} +const std::deque& NativeHookFrame::Depths() const +{ + return depths_; +} +const std::deque& NativeHookFrame::Ips() const +{ + return ips_; +} +const std::deque& NativeHookFrame::SymbolNames() const +{ + return symbolNames_; +} +const std::deque& NativeHookFrame::FilePaths() const +{ + return filePaths_; +} +const std::deque& NativeHookFrame::Offsets() const +{ + return offsets_; +} +const std::deque& NativeHookFrame::SymbolOffsets() const +{ + return symbolOffsets_; +} +const std::deque& NativeHookFrame::Vaddrs() const +{ + return vaddrs_; +} + +size_t NativeHookStatistic::AppendNewNativeHookStatistic(uint32_t ipid, + uint64_t timeStamp, + uint32_t callChainId, + uint32_t memoryType, + DataIndex subMemType, + uint64_t applyCount, + uint64_t releaseCount, + uint64_t applySize, + uint64_t releaseSize) +{ + AppendNativeHookSampleBase(callChainId, ipid, timeStamp); + memoryTypes_.emplace_back(memoryType); + applyCounts_.emplace_back(applyCount); + memSubTypes_.emplace_back(subMemType); + releaseCounts_.emplace_back(releaseCount); + applySizes_.emplace_back(applySize); + releaseSizes_.emplace_back(releaseSize); + return Size() - 1; +} + +const std::deque& NativeHookStatistic::MemoryTypes() const +{ + return memoryTypes_; +} +const std::deque& NativeHookStatistic::MemorySubTypes() const +{ + return memSubTypes_; +} +const std::deque& NativeHookStatistic::ApplyCounts() const +{ + return applyCounts_; +} +const std::deque& NativeHookStatistic::ReleaseCounts() const +{ + return releaseCounts_; +} +const std::deque& NativeHookStatistic::ApplySizes() const +{ + return applySizes_; +} +const std::deque& NativeHookStatistic::ReleaseSizes() const +{ + return releaseSizes_; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/htrace/native_memory_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/htrace/native_memory_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..5eb20de262a4fa790bb86cdce225677dd4625845 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/htrace/native_memory_stdtype.h @@ -0,0 +1,223 @@ +/* + * 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 NATIVE_MEMORY_STDTYPE_H +#define NATIVE_MEMORY_STDTYPE_H +#include "base_stdtype.h" +#include + +namespace SysTuning { +namespace TraceStdtype { +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(); + } + +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, + uint32_t itid, + std::string eventType, + DataIndex subType, + uint64_t timeStamp, + uint64_t endTimeStamp, + uint64_t duration, + uint64_t addr, + int64_t memSize); + void UpdateCallChainId(size_t row, uint32_t callChainId); + void UpdateEndTimeStampAndDuration(size_t row, uint64_t endTimeStamp); + void UpdateCurrentSizeDur(size_t row, uint64_t timeStamp); + void UpdateMemMapSubType(uint64_t row, uint64_t tagId); + const std::deque& EventTypes() const; + const std::deque& SubTypes() const; + const std::deque& EndTimeStamps() const; + const std::deque& Durations() const; + const std::deque& Addrs() const; + const std::deque& MemSizes() const; + const std::deque& AllMemSizes() const; + const std::deque& CurrentSizeDurs() const; + void Clear() override + { + NativeHookSampleBase::Clear(); + eventTypes_.clear(); + subTypes_.clear(); + endTimeStamps_.clear(); + durations_.clear(); + addrs_.clear(); + memSizes_.clear(); + allMemSizes_.clear(); + currentSizeDurs_.clear(); + } + std::unordered_map* GetAddrToAllocEventRow() + { + return &addrToAllocEventRow_; + } + std::unordered_map* GetAddrToMmapEventRow() + { + return &addrToMmapEventRow_; + } + uint64_t& GetLastMallocEventRaw() + { + return lastMallocEventRaw_; + } + uint64_t& GetLastMmapEventRaw() + { + return lastMmapEventRaw_; + } + +private: + std::deque eventTypes_ = {}; + std::deque subTypes_ = {}; + std::deque endTimeStamps_ = {}; + std::deque durations_ = {}; + std::deque addrs_ = {}; + std::deque memSizes_ = {}; + std::deque allMemSizes_ = {}; + std::deque currentSizeDurs_ = {}; + int64_t countHeapSizes_ = 0; + int64_t countMmapSizes_ = 0; + const std::string ALLOC_EVET = "AllocEvent"; + const std::string FREE_EVENT = "FreeEvent"; + const std::string MMAP_EVENT = "MmapEvent"; + const std::string MUNMAP_EVENT = "MunmapEvent"; + std::unordered_map addrToAllocEventRow_ = {}; + std::unordered_map addrToMmapEventRow_ = {}; + uint64_t lastMallocEventRaw_ = INVALID_UINT64; + uint64_t lastMmapEventRaw_ = INVALID_UINT64; +}; + +class NativeHookFrame { +public: + size_t AppendNewNativeHookFrame(uint32_t callChainId, + uint16_t depth, + uint64_t ip, + DataIndex symbolName, + DataIndex filePath, + uint64_t offset, + uint64_t symbolOffset); + size_t AppendNewNativeHookFrame(uint32_t callChainId, + uint16_t depth, + uint64_t ip, + DataIndex symbolName, + DataIndex filePath, + uint64_t offset, + uint64_t symbolOffset, + const std::string& vaddr); + void UpdateFrameInfo(size_t row, + DataIndex symbolIndex, + DataIndex filePathIndex, + uint64_t offset, + uint64_t symbolOffset); + void UpdateSymbolIdToNameMap(uint64_t originSymbolId, uint64_t symbolId); + void UpdateSymbolId(); + void UpdateSymbolId(size_t index, DataIndex symbolId); + void UpdateFileId(std::map& filePathIdToFilePathName); + void UpdateVaddrs(std::deque& vaddrs); + const std::deque& CallChainIds() const; + const std::deque& Depths() const; + const std::deque& Ips() const; + const std::deque& SymbolNames() const; + const std::deque& FilePaths() const; + const std::deque& Offsets() const; + const std::deque& SymbolOffsets() const; + const std::deque& Vaddrs() const; + size_t Size() const + { + return callChainIds_.size(); + } + void Clear() + { + callChainIds_.clear(); + depths_.clear(); + ips_.clear(); + symbolNames_.clear(); + filePaths_.clear(); + offsets_.clear(); + symbolOffsets_.clear(); + vaddrs_.clear(); + } + +private: + std::deque callChainIds_ = {}; + std::deque depths_ = {}; + std::deque ips_ = {}; + std::deque symbolNames_ = {}; + std::deque filePaths_ = {}; + std::deque offsets_ = {}; + std::deque symbolOffsets_ = {}; + std::deque vaddrs_ = {}; + std::map symbolIdToSymbolName_ = {}; +}; + +class NativeHookStatistic : public NativeHookSampleBase { +public: + size_t AppendNewNativeHookStatistic(uint32_t ipid, + uint64_t timeStamp, + uint32_t callChainId, + uint32_t memoryType, + DataIndex subMemType, + uint64_t applyCount, + uint64_t releaseCount, + uint64_t applySize, + uint64_t releaseSize); + const std::deque& MemoryTypes() const; + const std::deque& MemorySubTypes() const; + const std::deque& ApplyCounts() const; + const std::deque& ReleaseCounts() const; + const std::deque& ApplySizes() const; + const std::deque& ReleaseSizes() const; + void Clear() override + { + NativeHookSampleBase::Clear(); + memoryTypes_.clear(); + applyCounts_.clear(); + releaseCounts_.clear(); + applySizes_.clear(); + releaseSizes_.clear(); + } + +private: + std::deque memoryTypes_ = {}; + std::deque memSubTypes_ = {}; + std::deque applyCounts_ = {}; + std::deque releaseCounts_ = {}; + std::deque applySizes_ = {}; + std::deque releaseSizes_ = {}; +}; +} // namespace TraceStdtype +} // namespace SysTuning + +#endif // NATIVE_MEMORY_STDTYPE_H diff --git a/trace_streamer/src/trace_data/trace_stdtype/measure/measure_stdtype.cpp b/trace_streamer/src/trace_data/trace_stdtype/measure/measure_stdtype.cpp new file mode 100644 index 0000000000000000000000000000000000000000..332b6641ca1f0316332a4c207c9d70c3c1b8b7a8 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/measure/measure_stdtype.cpp @@ -0,0 +1,106 @@ +/* + * 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 "measure_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +size_t Filter::AppendNewFilterData(std::string type, std::string name, uint64_t sourceArgSetId) +{ + nameDeque_.emplace_back(name); + sourceArgSetId_.emplace_back(sourceArgSetId); + ids_.emplace_back(id_++); + typeDeque_.emplace_back(type); + return Size() - 1; +} + +size_t Measure::AppendMeasureData(uint32_t type, uint64_t timeStamp, int64_t value, uint32_t filterId) +{ + valuesDeque_.emplace_back(value); + filterIdDeque_.emplace_back(filterId); + typeDeque_.emplace_back(type); + timeStamps_.emplace_back(timeStamp); + durDeque_.emplace_back(INVALID_UINT64); + return Size() - 1; +} + +void Measure::SetDur(uint32_t row, uint64_t timeStamp) +{ + durDeque_[row] = timeStamp - timeStamps_[row]; +} + +void Measure::UpdatePrevSizeAndAdapterRows(size_t size) +{ + readySize_ = size; + // if filterIdToRow_.empty(), the readySize_ is all + if (filterIdToRow_.empty()) { + return; + } + // find minRowToBeUpdated + auto minRowToBeUpdated = filterIdToRow_.begin()->second; + for (const auto& pair : filterIdToRow_) { + if (minRowToBeUpdated > pair.second) { + minRowToBeUpdated = pair.second; + } + } + readySize_ = minRowToBeUpdated; + for (auto& pair : filterIdToRow_) { + pair.second -= readySize_; + } +} + +size_t SysMeasureFilter::AppendNewFilter(uint64_t filterId, DataIndex type, DataIndex nameId) +{ + ids_.emplace_back(filterId); + names_.emplace_back(nameId); + types_.emplace_back(type); + return ids_.size() - 1; +} +const std::deque& SysMeasureFilter::NamesData() const +{ + return names_; +} + +const std::deque& SysMeasureFilter::TypesData() const +{ + return types_; +} + +size_t ProcessMeasureFilter::AppendNewFilter(uint64_t id, DataIndex name, uint32_t internalPid) +{ + internalPids_.emplace_back(internalPid); + ids_.emplace_back(id); + names_.emplace_back(name); + return Size() - 1; +} + +size_t ClockEventData::AppendNewFilter(uint64_t id, DataIndex type, DataIndex name, uint64_t cpu) +{ + cpus_.emplace_back(cpu); + ids_.emplace_back(id); + types_.emplace_back(type); + names_.emplace_back(name); + return Size() - 1; +} +size_t ClkEventData::AppendNewFilter(uint64_t id, uint64_t rate, DataIndex name, uint64_t cpu) +{ + ids_.emplace_back(id); + rates_.emplace_back(rate); + names_.emplace_back(name); + cpus_.emplace_back(cpu); + return Size() - 1; +} +} // namespace TraceStdtype +} // namespace SysTuning diff --git a/trace_streamer/src/trace_data/trace_stdtype/measure/measure_stdtype.h b/trace_streamer/src/trace_data/trace_stdtype/measure/measure_stdtype.h new file mode 100644 index 0000000000000000000000000000000000000000..73a2ee542ad7a30a93cfa1029c3dc184d71a6eb4 --- /dev/null +++ b/trace_streamer/src/trace_data/trace_stdtype/measure/measure_stdtype.h @@ -0,0 +1,260 @@ +/* + * 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 MEASURE_STDTYPE_H +#define MEASURE_STDTYPE_H +#include "base_stdtype.h" + +namespace SysTuning { +namespace TraceStdtype { +class Filter : public CacheBase, public BatchCacheBase { +public: + size_t AppendNewFilterData(std::string type, std::string name, uint64_t sourceArgSetId); + const std::deque& NameData() const + { + return nameDeque_; + } + const std::deque& TypeData() const + { + return typeDeque_; + } + const std::deque& SourceArgSetIdData() const + { + return sourceArgSetId_; + } + void Clear() override + { + CacheBase::Clear(); + nameDeque_.clear(); + typeDeque_.clear(); + sourceArgSetId_.clear(); + } + void ClearExportedData() override + { + EraseElements(ids_, nameDeque_, typeDeque_, sourceArgSetId_); + } + +private: + std::deque nameDeque_ = {}; + std::deque typeDeque_ = {}; + std::deque sourceArgSetId_ = {}; +}; + +class Measure : public CacheBase, public BatchCacheBase { +public: + size_t AppendMeasureData(uint32_t type, uint64_t timeStamp, int64_t value, uint32_t filterId); + const std::deque& TypeData() const + { + return typeDeque_; + } + const std::deque& ValuesData() const + { + return valuesDeque_; + } + const std::deque& DursData() const + { + return durDeque_; + } + void SetDur(uint32_t row, uint64_t timeStamp); + const std::deque& FilterIdData() const + { + return filterIdDeque_; + } + void Clear() override + { + CacheBase::Clear(); + typeDeque_.clear(); + durDeque_.clear(); + valuesDeque_.clear(); + filterIdDeque_.clear(); + } + void UpdateReadySize(size_t size) override + { + UpdatePrevSizeAndAdapterRows(size); + } + void ClearExportedData() override + { + EraseElements(timeStamps_, typeDeque_, durDeque_, valuesDeque_, filterIdDeque_); + } + std::map* GetFilterIdToRow() + { + return &filterIdToRow_; + } + void ClearRowMap() + { + filterIdToRow_.clear(); + } + +private: + void UpdatePrevSizeAndAdapterRows(size_t size); + std::deque typeDeque_ = {}; + std::deque durDeque_ = {}; + std::deque valuesDeque_ = {}; + std::deque filterIdDeque_ = {}; + std::map filterIdToRow_ = {}; +}; + +class SysMeasureFilter : public CacheBase { +public: + size_t AppendNewFilter(uint64_t filterId, DataIndex type, DataIndex nameId); + const std::deque& NamesData() const; + const std::deque& TypesData() const; + void Clear() override + { + CacheBase::Clear(); + types_.clear(); + names_.clear(); + } + +private: + std::deque types_ = {}; + std::deque names_ = {}; +}; + +class CpuMeasureFilter : public CacheBase, public BatchCacheBase { +public: + inline size_t AppendNewFilter(uint64_t filterId, DataIndex name, uint32_t cpu) + { + ids_.emplace_back(filterId); + cpu_.emplace_back(cpu); + name_.emplace_back(name); + return Size() - 1; + } + + const std::deque& CpuData() const + { + return cpu_; + } + + const std::deque& NameData() const + { + return name_; + } + void Clear() override + { + CacheBase::Clear(); + cpu_.clear(); + name_.clear(); + } + void ClearExportedData() override + { + EraseElements(ids_, cpu_, name_); + } + +private: + std::deque cpu_ = {}; + std::deque name_ = {}; +}; + +class ProcessMeasureFilter : public CacheBase, public BatchCacheBase { +public: + size_t AppendNewFilter(uint64_t id, DataIndex name, uint32_t internalPid); + + const std::deque& UpidsData() const + { + return internalPids_; + } + + const std::deque& NamesData() const + { + return names_; + } + void Clear() override + { + CacheBase::Clear(); + internalPids_.clear(); + names_.clear(); + } + void ClearExportedData() override + { + EraseElements(internalTids_, ids_, internalPids_, names_); + } + +private: + std::deque internalPids_ = {}; + std::deque names_ = {}; +}; + +class ClockEventData : public CacheBase, public BatchCacheBase { +public: + size_t AppendNewFilter(uint64_t id, DataIndex type, DataIndex name, uint64_t cpu); + + const std::deque& CpusData() const + { + return cpus_; + } + + const std::deque& NamesData() const + { + return names_; + } + const std::deque& TypesData() const + { + return types_; + } + void Clear() override + { + CacheBase::Clear(); + cpus_.clear(); + names_.clear(); + types_.clear(); + } + void ClearExportedData() override + { + EraseElements(ids_, cpus_, names_, types_); + } + +private: + std::deque cpus_ = {}; // in clock_set_rate event, it save cpu + std::deque names_ = {}; + std::deque types_ = {}; +}; + +class ClkEventData : public CacheBase, public BatchCacheBase { +public: + size_t AppendNewFilter(uint64_t id, uint64_t rate, DataIndex name, uint64_t cpu); + + const std::deque& NamesData() const + { + return names_; + } + const std::deque& RatesData() const + { + return rates_; + } + const std::deque& CpusData() const + { + return cpus_; + } + void Clear() override + { + CacheBase::Clear(); + names_.clear(); + rates_.clear(); + cpus_.clear(); + } + void ClearExportedData() override + { + EraseElements(ids_, cpus_, names_, rates_); + } + +private: + std::deque names_; + std::deque rates_; + std::deque cpus_; +}; +} // namespace TraceStdtype +} // namespace SysTuning +#endif // MEASURE_STDTYPE_H diff --git a/trace_streamer/src/trace_streamer/trace_streamer_filters.cpp b/trace_streamer/src/trace_streamer/trace_streamer_filters.cpp index 6bdda748dbe1cfc7d0766bde2b8c285b66850da2..faaddbcaa0f84265d659751ab43c58170f3f5282 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_filters.cpp +++ b/trace_streamer/src/trace_streamer/trace_streamer_filters.cpp @@ -29,7 +29,6 @@ #include "process_filter.h" #include "slice_filter.h" #include "stat_filter.h" -#include "symbols_filter.h" #include "system_event_measure_filter.h" #include "task_pool_filter.h" @@ -43,17 +42,6 @@ void TraceStreamerFilters::FilterClear() sliceFilter_->Clear(); cpuFilter_->Clear(); irqFilter_->Clear(); - cpuMeasureFilter_->Clear(); - threadMeasureFilter_->Clear(); - threadFilter_->Clear(); - processMeasureFilter_->Clear(); - processFilterFilter_->Clear(); - clockEnableFilter_->Clear(); - clockDisableFilter_->Clear(); - clockRateFilter_->Clear(); - clkRateFilter_->Clear(); - clkEnableFilter_->Clear(); - clkDisableFilter_->Clear(); binderFilter_->Clear(); frameFilter_->Clear(); } diff --git a/trace_streamer/src/trace_streamer/trace_streamer_filters.h b/trace_streamer/src/trace_streamer/trace_streamer_filters.h index 7b4b1f1ca098982e3d6b3a0ac31965969b032786..50e275cb7b2e685116620eb9ae5f14b04246dcca 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_filters.h +++ b/trace_streamer/src/trace_streamer/trace_streamer_filters.h @@ -26,7 +26,6 @@ class CpuFilter; class MeasureFilter; class FilterFilter; class ClockFilterEx; -class SymbolsFilter; class StatFilter; class BinderFilter; class ArgsFilter; @@ -49,11 +48,7 @@ public: std::unique_ptr processFilter_; std::unique_ptr cpuFilter_; std::unique_ptr cpuMeasureFilter_; - std::unique_ptr threadMeasureFilter_; - std::unique_ptr threadFilter_; std::unique_ptr processMeasureFilter_; - std::unique_ptr processFilterFilter_; - std::unique_ptr symbolsFilter_; std::unique_ptr statFilter_; std::unique_ptr clockRateFilter_; std::unique_ptr clockEnableFilter_; diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp index 231f4c244ab7443460cfea3e4e1d54ab886ce1b3..39620f0c8d7cec626aba50edc2fd0460519d5204 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.cpp @@ -40,7 +40,6 @@ #include "slice_filter.h" #include "stat_filter.h" #include "string_help.h" -#include "symbols_filter.h" #include "system_event_measure_filter.h" namespace { @@ -140,17 +139,10 @@ void TraceStreamerSelector::InitFilter() streamFilters_->clockFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); streamFilters_->filterFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); - streamFilters_->threadMeasureFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_THREADMEASURE_FILTER); - streamFilters_->threadFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_THREAD_FILTER); streamFilters_->cpuMeasureFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_CPU_MEASURE_FILTER); streamFilters_->processMeasureFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_PROCESS_MEASURE_FILTER); - streamFilters_->processFilterFilter_ = - std::make_unique(traceDataCache_.get(), streamFilters_.get(), E_PROCESS_FILTER_FILTER); - streamFilters_->symbolsFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); streamFilters_->statFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); streamFilters_->binderFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); streamFilters_->argsFilter_ = std::make_unique(traceDataCache_.get(), streamFilters_.get()); @@ -403,7 +395,7 @@ const std::string TraceStreamerSelector::MetricsSqlQuery(const std::string& metr int32_t TraceStreamerSelector::UpdateTraceRangeTime(uint8_t* data, int32_t len) { std::string traceRangeStr; - memcpy(&traceRangeStr, data, len); + (void)memcpy_s(&traceRangeStr, len, data, len); std::vector vTraceRangeStr = SplitStringToVec(traceRangeStr, ";"); uint64_t minTs = std::stoull(vTraceRangeStr.at(0)); uint64_t maxTs = std::stoull(vTraceRangeStr.at(1)); @@ -458,7 +450,7 @@ bool TraceStreamerSelector::LoadQueryFile(const std::string& sqlOperator, std::v } sqlStrings.push_back(sqlString); } - fclose(fd); + (void)fclose(fd); fd = nullptr; return true; } @@ -468,6 +460,10 @@ bool TraceStreamerSelector::ReadSqlFileAndPrintResult(const std::string& sqlOper if (!LoadQueryFile(sqlOperator, sqlStrings)) { return false; } + if (sqlStrings.empty()) { + TS_LOGE("%s is empty!", sqlOperator.c_str()); + return false; + } for (auto& str : sqlStrings) { SearchDatabase(str, true); } diff --git a/trace_streamer/src/trace_streamer/trace_streamer_selector.h b/trace_streamer/src/trace_streamer/trace_streamer_selector.h index 4dbf993805ac680647ef76e72914abbd69e1164f..80ec91d0f50b55354c79fd4804ac5244a1c0e197 100644 --- a/trace_streamer/src/trace_streamer/trace_streamer_selector.h +++ b/trace_streamer/src/trace_streamer/trace_streamer_selector.h @@ -38,7 +38,7 @@ public: int32_t ExportPerfReadableText(const std::string& outputName, TraceDataDB::ResultCallBack resultCallBack = nullptr); int32_t ExportHookReadableText(const std::string& outputName, TraceDataDB::ResultCallBack resultCallBack = nullptr); int32_t ExportEbpfReadableText(const std::string& outputName, TraceDataDB::ResultCallBack resultCallBack = nullptr); - bool ReloadSymbolFiles(std::string& symbolsPath, std::vector& symbolsPaths); + bool ReloadSymbolFiles(std::string& directory, std::vector& symbolsPaths); std::vector SearchData(); int32_t OperateDatabase(const std::string& sql); int32_t SearchDatabase(const std::string& sql, TraceDataDB::ResultCallBack resultCallBack); @@ -72,7 +72,7 @@ public: { return htraceParser_.get(); } - auto GetFileType() + const auto GetFileType() { return fileType_; } diff --git a/trace_streamer/test/BUILD.gn b/trace_streamer/test/BUILD.gn index 80e6ce3f4173a8e6fcc4612dc417875b3b315f0f..a87b833730490123ad51ba15b0f28c73ac86690b 100644 --- a/trace_streamer/test/BUILD.gn +++ b/trace_streamer/test/BUILD.gn @@ -19,57 +19,56 @@ import("test_ts.gni") if (is_test) { ohos_unittest("trace_streamer_ut") { sources = [ - "unittest/animation_filter_test.cpp", - "unittest/app_start_filter_test.cpp", - "unittest/binder_filter_test.cpp", - "unittest/bio_parser_test.cpp", - "unittest/bytrace_parser_test.cpp", - "unittest/clock_filter_test.cpp", - "unittest/cpu_filter_test.cpp", - "unittest/ebpf_file_system_test.cpp", - "unittest/ebpf_parser_test.cpp", - "unittest/event_parser_test.cpp", - "unittest/export_test.cpp", # Don't comment, for common method - "unittest/filter_filter_test.cpp", - "unittest/frame_filter_test.cpp", - "unittest/ftrace_field_processor_test.cpp", - "unittest/hidump_parser_test.cpp", - "unittest/hilog_parser_test.cpp", - "unittest/hisys_event_parser_test.cpp", - "unittest/htrace_binder_event_test.cpp", - "unittest/htrace_cpu_data_parser_test.cpp", - "unittest/htrace_cpu_detail_parser_test.cpp", - "unittest/htrace_diskio_parser_test.cpp", - "unittest/htrace_event_parser_test.cpp", - "unittest/htrace_irq_event_test.cpp", - "unittest/htrace_mem_parser_test.cpp", - "unittest/htrace_network_parser_test.cpp", - "unittest/htrace_process_parser_test.cpp", - "unittest/htrace_sys_mem_parser_test.cpp", - "unittest/htrace_sys_vmem_parser_test.cpp", - "unittest/http_server_test.cpp", - "unittest/irq_filter_test.cpp", - "unittest/js_cpu_profiler_test.cpp", - "unittest/js_memory_test.cpp", - "unittest/measure_filter_test.cpp", - "unittest/native_hook_parser_test.cpp", - "unittest/paged_memory_parser_test.cpp", + "unittest/base/export_test.cpp", # Don't comment, for common method + "unittest/filter/animation_filter_test.cpp", + "unittest/filter/app_start_filter_test.cpp", + "unittest/filter/binder_filter_test.cpp", + "unittest/filter/clock_filter_test.cpp", + "unittest/filter/cpu_filter_test.cpp", + "unittest/filter/filter_filter_test.cpp", + "unittest/filter/frame_filter_test.cpp", + "unittest/filter/irq_filter_test.cpp", + "unittest/filter/measure_filter_test.cpp", + "unittest/filter/process_filter_test.cpp", + "unittest/filter/slice_filter_test.cpp", + "unittest/filter/task_pool_filter_test.cpp", + "unittest/htrace/arkts/js_cpu_profiler_test.cpp", + "unittest/htrace/arkts/js_memory_test.cpp", + "unittest/htrace/ebpf/bio_parser_test.cpp", + "unittest/htrace/ebpf/ebpf_file_system_test.cpp", + "unittest/htrace/ebpf/ebpf_parser_test.cpp", + "unittest/htrace/ebpf/paged_memory_parser_test.cpp", + "unittest/htrace/hidump_parser_test.cpp", + "unittest/htrace/hilog_parser_test.cpp", + "unittest/htrace/hisys_event_parser_test.cpp", + "unittest/htrace/htrace_binder_event_test.cpp", + "unittest/htrace/htrace_cpu_data_parser_test.cpp", + "unittest/htrace/htrace_cpu_detail_parser_test.cpp", + "unittest/htrace/htrace_diskio_parser_test.cpp", + "unittest/htrace/htrace_event_parser_test.cpp", + "unittest/htrace/htrace_irq_event_test.cpp", + "unittest/htrace/htrace_mem_parser_test.cpp", + "unittest/htrace/htrace_network_parser_test.cpp", + "unittest/htrace/htrace_process_parser_test.cpp", + "unittest/htrace/htrace_sys_mem_parser_test.cpp", + "unittest/htrace/htrace_sys_vmem_parser_test.cpp", + "unittest/htrace/native_memory/native_hook_parser_test.cpp", + "unittest/htrace/smaps_parser_test.cpp", + "unittest/interface/rpc_server_test.cpp", + "unittest/interface/split_file_data_test.cpp", + "unittest/interface/wasm_func_test.cpp", "unittest/parser_pbreader_test.cpp", - "unittest/process_filter_test.cpp", "unittest/proto_reader_test.cpp", - "unittest/query_file_test.cpp", - "unittest/query_metrics_test.cpp", - "unittest/rawtrace_cpu_detail_parse_test.cpp", - "unittest/rawtrace_parser_test.cpp", - "unittest/rpc_server_test.cpp", - "unittest/slice_filter_test.cpp", - "unittest/smaps_parser_test.cpp", - "unittest/span_join_test.cpp", - "unittest/split_file_data_test.cpp", - "unittest/sqllite_prepar_cache_data_test.cpp", - "unittest/table_test.cpp", - "unittest/task_pool_filter_test.cpp", - "unittest/wasm_func_test.cpp", + "unittest/query/query_file_test.cpp", + "unittest/query/query_metrics_test.cpp", + "unittest/query/span_join_test.cpp", + "unittest/query/sqllite_prepar_cache_data_test.cpp", + "unittest/rawtrace/ftrace_field_processor_test.cpp", + "unittest/rawtrace/rawtrace_cpu_detail_parse_test.cpp", + "unittest/rawtrace/rawtrace_parser_test.cpp", + "unittest/systrace/bytrace_parser_test.cpp", + "unittest/systrace/event_parser_test.cpp", + "unittest/table/table_test.cpp", ] deps = [ diff --git a/trace_streamer/test/test_fuzzer/bytrace_fuzzer/bytrace_fuzzer.cpp b/trace_streamer/test/test_fuzzer/bytrace_fuzzer/bytrace_fuzzer.cpp index f01d7f156aeee782e7f5e53afef2e3420bab6368..eaf6ad5fac31c7f25ca9baf0f0f2ba4a4e9afb71 100644 --- a/trace_streamer/test/test_fuzzer/bytrace_fuzzer/bytrace_fuzzer.cpp +++ b/trace_streamer/test/test_fuzzer/bytrace_fuzzer/bytrace_fuzzer.cpp @@ -32,7 +32,7 @@ bool BytraceParserFuzzTest(const uint8_t* data, size_t size) TraceStreamerSelector stream_ = {}; stream_.SetDataType(TRACE_FILETYPE_BY_TRACE); std::unique_ptr buf = std::make_unique(size); - if (memcpy_s(buf.get(), size, data, size)) { + if ((void)memcpy_s(buf.get(), size, data, size)) { return false; } stream_.SetCleanMode(true); diff --git a/trace_streamer/test/test_fuzzer/htrace_fuzzer/htrace_fuzzer.cpp b/trace_streamer/test/test_fuzzer/htrace_fuzzer/htrace_fuzzer.cpp index e7a55e57ff9dc0ee837773c172a770591d670028..741a21333a6293e5dcd9eaf9bf66ad24d86cab93 100644 --- a/trace_streamer/test/test_fuzzer/htrace_fuzzer/htrace_fuzzer.cpp +++ b/trace_streamer/test/test_fuzzer/htrace_fuzzer/htrace_fuzzer.cpp @@ -28,7 +28,7 @@ bool HtraceParserFuzzTest(const uint8_t* data, size_t size) TraceStreamerSelector stream_ = {}; stream_.SetDataType(TRACE_FILETYPE_H_TRACE); std::unique_ptr buf = std::make_unique(size); - if (memcpy_s(buf.get(), size, data, size)) { + if ((void)memcpy_s(buf.get(), size, data, size)) { return false; } stream_.SetCleanMode(true); diff --git a/trace_streamer/test/test_fuzzer/selector_fuzzer/selector_fuzzer.cpp b/trace_streamer/test/test_fuzzer/selector_fuzzer/selector_fuzzer.cpp index ce675b0fda5c0e5759b450742e7b62eb51408d75..ca322600af60b94c7eb4b62ed2700860b19c9a9f 100644 --- a/trace_streamer/test/test_fuzzer/selector_fuzzer/selector_fuzzer.cpp +++ b/trace_streamer/test/test_fuzzer/selector_fuzzer/selector_fuzzer.cpp @@ -27,7 +27,7 @@ bool TraceStreamerSelectorFuzzTest(const uint8_t* data, size_t size) { TraceStreamerSelector stream_ = {}; std::unique_ptr buf = std::make_unique(size); - if (memcpy_s(buf.get(), size, data, size)) { + if ((void)memcpy_s(buf.get(), size, data, size)) { return false; } stream_.SetCleanMode(true); diff --git a/trace_streamer/test/unittest/export_test.cpp b/trace_streamer/test/unittest/base/export_test.cpp similarity index 100% rename from trace_streamer/test/unittest/export_test.cpp rename to trace_streamer/test/unittest/base/export_test.cpp diff --git a/trace_streamer/test/unittest/export_test.h b/trace_streamer/test/unittest/base/export_test.h similarity index 100% rename from trace_streamer/test/unittest/export_test.h rename to trace_streamer/test/unittest/base/export_test.h diff --git a/trace_streamer/test/unittest/animation_filter_test.cpp b/trace_streamer/test/unittest/filter/animation_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/animation_filter_test.cpp rename to trace_streamer/test/unittest/filter/animation_filter_test.cpp diff --git a/trace_streamer/test/unittest/app_start_filter_test.cpp b/trace_streamer/test/unittest/filter/app_start_filter_test.cpp similarity index 99% rename from trace_streamer/test/unittest/app_start_filter_test.cpp rename to trace_streamer/test/unittest/filter/app_start_filter_test.cpp index 9cc535937a276ebab8519fb4feec22246ffed16a..b39d7053df3ec09f2cf406ef21e0dc142039a5bd 100644 --- a/trace_streamer/test/unittest/app_start_filter_test.cpp +++ b/trace_streamer/test/unittest/filter/app_start_filter_test.cpp @@ -204,7 +204,7 @@ HWTEST_F(AppStartFilterTest, SoInitalizationTest, TestSize.Level1) stream_.streamFilters_->sliceFilter_->EndSlice(ts2, pid1, threadGroupId1); stream_.streamFilters_->appStartupFilter_->FilterAllAPPStartupData(); - EXPECT_TRUE(stream_.traceDataCache_->GetConstStaticInitalizationData().Size() == 1); + EXPECT_TRUE(stream_.traceDataCache_->GetConstSoStaticInitalizationData().Size() == 1); } } // namespace TraceStreamer diff --git a/trace_streamer/test/unittest/binder_filter_test.cpp b/trace_streamer/test/unittest/filter/binder_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/binder_filter_test.cpp rename to trace_streamer/test/unittest/filter/binder_filter_test.cpp diff --git a/trace_streamer/test/unittest/clock_filter_test.cpp b/trace_streamer/test/unittest/filter/clock_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/clock_filter_test.cpp rename to trace_streamer/test/unittest/filter/clock_filter_test.cpp diff --git a/trace_streamer/test/unittest/cpu_filter_test.cpp b/trace_streamer/test/unittest/filter/cpu_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/cpu_filter_test.cpp rename to trace_streamer/test/unittest/filter/cpu_filter_test.cpp diff --git a/trace_streamer/test/unittest/filter_filter_test.cpp b/trace_streamer/test/unittest/filter/filter_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/filter_filter_test.cpp rename to trace_streamer/test/unittest/filter/filter_filter_test.cpp diff --git a/trace_streamer/test/unittest/frame_filter_test.cpp b/trace_streamer/test/unittest/filter/frame_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/frame_filter_test.cpp rename to trace_streamer/test/unittest/filter/frame_filter_test.cpp diff --git a/trace_streamer/test/unittest/irq_filter_test.cpp b/trace_streamer/test/unittest/filter/irq_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/irq_filter_test.cpp rename to trace_streamer/test/unittest/filter/irq_filter_test.cpp diff --git a/trace_streamer/test/unittest/measure_filter_test.cpp b/trace_streamer/test/unittest/filter/measure_filter_test.cpp similarity index 75% rename from trace_streamer/test/unittest/measure_filter_test.cpp rename to trace_streamer/test/unittest/filter/measure_filter_test.cpp index 1f1f9cd78cca30585fa2d3bbd3647ab3f957117c..3fa1faa75f7df7415691bd2e608944b498e40131 100644 --- a/trace_streamer/test/unittest/measure_filter_test.cpp +++ b/trace_streamer/test/unittest/filter/measure_filter_test.cpp @@ -48,61 +48,6 @@ public: SysTuning::TraceStreamer::TraceStreamerSelector stream_ = {}; }; -/** - * @tc.name: ThreadMeasureFilter - * @tc.desc: Test whether the GetOrCreateFilterId interface generated filterid and threadmeasure Info is correct - * @tc.type: FUNC - */ -HWTEST_F(MeasureFilterTest, ThreadMeasureFilter, TestSize.Level1) -{ - TS_LOGI("test23-1"); - auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); - uint32_t filterId = - stream_.streamFilters_->threadMeasureFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_0, nameIndex0); - EXPECT_TRUE(filterId == 0); - - auto nameIndex1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); - filterId = stream_.streamFilters_->threadMeasureFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_1, nameIndex1); - EXPECT_TRUE(filterId == 1); - - Filter* filterTable = stream_.traceDataCache_->GetFilterData(); - EXPECT_TRUE(filterTable->Size() == 2); - - ThreadMeasureFilter* threadMeasureTable = stream_.traceDataCache_->GetThreadMeasureFilterData(); - EXPECT_TRUE(threadMeasureTable->Size() == 2); - EXPECT_TRUE(threadMeasureTable->FilterIdData()[0] == 0); - EXPECT_TRUE(threadMeasureTable->FilterIdData()[1] == 1); - EXPECT_TRUE(threadMeasureTable->InternalTidData()[0] == INTERNAL_THREAD_ID_0); - EXPECT_TRUE(threadMeasureTable->InternalTidData()[1] == INTERNAL_THREAD_ID_1); -} - -/** - * @tc.name: ThreadFilter - * @tc.desc: Test whether the GetOrCreateFilterId interface generated filterid and thread Info is correct - * @tc.type: FUNC - */ -HWTEST_F(MeasureFilterTest, ThreadFilter, TestSize.Level1) -{ - TS_LOGI("test23-2"); - auto nameIndex0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); - uint32_t filterId = stream_.streamFilters_->threadFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_0, nameIndex0); - EXPECT_TRUE(filterId == 0); - - auto nameIndex1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); - filterId = stream_.streamFilters_->threadFilter_->GetOrCreateFilterId(INTERNAL_THREAD_ID_1, nameIndex1); - EXPECT_TRUE(filterId == 1); - - Filter* filterTable = stream_.traceDataCache_->GetFilterData(); - EXPECT_TRUE(filterTable->Size() == 2); - - ThreadMeasureFilter* threadTable = stream_.traceDataCache_->GetThreadFilterData(); - EXPECT_TRUE(threadTable->Size() == 2); - EXPECT_TRUE(threadTable->FilterIdData()[0] == 0); - EXPECT_TRUE(threadTable->FilterIdData()[1] == 1); - EXPECT_TRUE(threadTable->InternalTidData()[0] == INTERNAL_THREAD_ID_0); - EXPECT_TRUE(threadTable->InternalTidData()[1] == INTERNAL_THREAD_ID_1); -} - /** * @tc.name: CpuFilter * @tc.desc: Test GetOrCreateFilterId interface of class CpuFilter @@ -130,30 +75,6 @@ HWTEST_F(MeasureFilterTest, CpuFilter, TestSize.Level1) EXPECT_TRUE(cpuMeasureTable->CpuData()[1] == CPU_ID_1); } -/** - * @tc.name: ProcessFilter - * @tc.desc: Test GetOrCreateFilterId interface of class ProcessFilter - * @tc.type: FUNC - */ -HWTEST_F(MeasureFilterTest, ProcessFilter, TestSize.Level1) -{ - TS_LOGI("test23-4"); - auto nameIndex_0 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_0); - uint32_t filterId = - stream_.streamFilters_->processFilterFilter_->GetOrCreateFilterId(INTERNAL_PROCESS_ID_0, nameIndex_0); - EXPECT_TRUE(filterId == 0); - - auto nameIndex_1 = stream_.traceDataCache_->GetDataIndex(TASK_NAME_1); - filterId = stream_.streamFilters_->processFilterFilter_->GetOrCreateFilterId(INTERNAL_PROCESS_ID_1, nameIndex_1); - EXPECT_TRUE(filterId == 1); - - Filter* filterTable = stream_.traceDataCache_->GetFilterData(); - EXPECT_TRUE(filterTable->Size() == 2); - - ProcessMeasureFilter* processFilterTable = stream_.traceDataCache_->GetProcessFilterData(); - EXPECT_TRUE(processFilterTable->Size() == 2); -} - /** * @tc.name: ClockRateFilter * @tc.desc: Test GetOrCreateFilterId interface of class ClockRateFilter diff --git a/trace_streamer/test/unittest/process_filter_test.cpp b/trace_streamer/test/unittest/filter/process_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/process_filter_test.cpp rename to trace_streamer/test/unittest/filter/process_filter_test.cpp diff --git a/trace_streamer/test/unittest/slice_filter_test.cpp b/trace_streamer/test/unittest/filter/slice_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/slice_filter_test.cpp rename to trace_streamer/test/unittest/filter/slice_filter_test.cpp diff --git a/trace_streamer/test/unittest/task_pool_filter_test.cpp b/trace_streamer/test/unittest/filter/task_pool_filter_test.cpp similarity index 100% rename from trace_streamer/test/unittest/task_pool_filter_test.cpp rename to trace_streamer/test/unittest/filter/task_pool_filter_test.cpp diff --git a/trace_streamer/test/unittest/js_cpu_profiler_test.cpp b/trace_streamer/test/unittest/htrace/arkts/js_cpu_profiler_test.cpp similarity index 100% rename from trace_streamer/test/unittest/js_cpu_profiler_test.cpp rename to trace_streamer/test/unittest/htrace/arkts/js_cpu_profiler_test.cpp diff --git a/trace_streamer/test/unittest/js_memory_test.cpp b/trace_streamer/test/unittest/htrace/arkts/js_memory_test.cpp similarity index 100% rename from trace_streamer/test/unittest/js_memory_test.cpp rename to trace_streamer/test/unittest/htrace/arkts/js_memory_test.cpp diff --git a/trace_streamer/test/unittest/bio_parser_test.cpp b/trace_streamer/test/unittest/htrace/ebpf/bio_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/bio_parser_test.cpp rename to trace_streamer/test/unittest/htrace/ebpf/bio_parser_test.cpp diff --git a/trace_streamer/test/unittest/ebpf_file_system_test.cpp b/trace_streamer/test/unittest/htrace/ebpf/ebpf_file_system_test.cpp similarity index 100% rename from trace_streamer/test/unittest/ebpf_file_system_test.cpp rename to trace_streamer/test/unittest/htrace/ebpf/ebpf_file_system_test.cpp diff --git a/trace_streamer/test/unittest/ebpf_parser_test.cpp b/trace_streamer/test/unittest/htrace/ebpf/ebpf_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/ebpf_parser_test.cpp rename to trace_streamer/test/unittest/htrace/ebpf/ebpf_parser_test.cpp diff --git a/trace_streamer/test/unittest/paged_memory_parser_test.cpp b/trace_streamer/test/unittest/htrace/ebpf/paged_memory_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/paged_memory_parser_test.cpp rename to trace_streamer/test/unittest/htrace/ebpf/paged_memory_parser_test.cpp diff --git a/trace_streamer/test/unittest/hidump_parser_test.cpp b/trace_streamer/test/unittest/htrace/hidump_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/hidump_parser_test.cpp rename to trace_streamer/test/unittest/htrace/hidump_parser_test.cpp diff --git a/trace_streamer/test/unittest/hilog_parser_test.cpp b/trace_streamer/test/unittest/htrace/hilog_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/hilog_parser_test.cpp rename to trace_streamer/test/unittest/htrace/hilog_parser_test.cpp diff --git a/trace_streamer/test/unittest/hisys_event_parser_test.cpp b/trace_streamer/test/unittest/htrace/hisys_event_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/hisys_event_parser_test.cpp rename to trace_streamer/test/unittest/htrace/hisys_event_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_binder_event_test.cpp b/trace_streamer/test/unittest/htrace/htrace_binder_event_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_binder_event_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_binder_event_test.cpp diff --git a/trace_streamer/test/unittest/htrace_cpu_data_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_cpu_data_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_cpu_data_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_cpu_data_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_cpu_detail_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_cpu_detail_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_cpu_detail_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_cpu_detail_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_diskio_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_diskio_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_diskio_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_diskio_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_event_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_event_parser_test.cpp similarity index 99% rename from trace_streamer/test/unittest/htrace_event_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_event_parser_test.cpp index 467eb875a605237ee2a7f8bc09ebd388b4e31448..86169dec0ce7132a675351b872554b8430e459d8 100644 --- a/trace_streamer/test/unittest/htrace_event_parser_test.cpp +++ b/trace_streamer/test/unittest/htrace/htrace_event_parser_test.cpp @@ -21,7 +21,6 @@ #include "cpu_filter.h" #include "htrace_cpu_detail_parser.h" #include "parser/common_types.h" -#include "src/filter/symbols_filter.h" #include "trace_plugin_result.pb.h" #include "trace_plugin_result.pbreader.h" #include "trace_streamer_filters.h" @@ -437,8 +436,8 @@ HWTEST_F(HtraceEventParserTest, ParseCpuFrequencyEvent, TestSize.Level1) HWTEST_F(HtraceEventParserTest, ParseWorkqueueExecuteStartEvent, TestSize.Level1) { TS_LOGI("test14-10"); - stream_.streamFilters_->symbolsFilter_->RegisterFunc(1, 1); - auto funcNum = stream_.streamFilters_->symbolsFilter_->GetFunc(1); + stream_.traceDataCache_->GetSymbolsData()->UpdateSymbol(1, 1); + auto funcNum = stream_.traceDataCache_->GetSymbolsData()->GetFunc(1); WorkqueueExecuteStartFormat* workqueueExecuteStartEvent = new WorkqueueExecuteStartFormat(); workqueueExecuteStartEvent->set_work(0); workqueueExecuteStartEvent->set_function(1); diff --git a/trace_streamer/test/unittest/htrace_irq_event_test.cpp b/trace_streamer/test/unittest/htrace/htrace_irq_event_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_irq_event_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_irq_event_test.cpp diff --git a/trace_streamer/test/unittest/htrace_mem_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_mem_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_mem_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_mem_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_network_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_network_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_network_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_network_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_process_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_process_parser_test.cpp similarity index 98% rename from trace_streamer/test/unittest/htrace_process_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_process_parser_test.cpp index d81701eddb1e58c42167c3dff78dd263cc0f8d8f..c11b5b1ee264256246591983f20ef296eff3947e 100644 --- a/trace_streamer/test/unittest/htrace_process_parser_test.cpp +++ b/trace_streamer/test/unittest/htrace/htrace_process_parser_test.cpp @@ -72,17 +72,17 @@ HWTEST_F(HtraceProcessParserTest, ParseHtraceProcessWithProcessData, TestSize.Le { TS_LOGI("test18-2"); uint64_t ts = 100; - const uint32_t PID = 312; - const string NAME = "resource_schedu"; - const int32_t PPID = 22; - const int32_t UID = 23; + const uint32_t pid = 312; + const string name = "resource_schedu"; + const int32_t ppid = 22; + const int32_t uid = 23; auto processData = std::make_unique(); ProcessInfo* processInfo = processData->add_processesinfo(); - processInfo->set_pid(PID); - processInfo->set_name(NAME); - processInfo->set_ppid(PPID); - processInfo->set_uid(UID); + processInfo->set_pid(pid); + processInfo->set_name(name); + processInfo->set_ppid(ppid); + processInfo->set_uid(uid); std::string processStrMsg = ""; processData->SerializeToString(&processStrMsg); diff --git a/trace_streamer/test/unittest/htrace_sys_mem_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_sys_mem_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_sys_mem_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_sys_mem_parser_test.cpp diff --git a/trace_streamer/test/unittest/htrace_sys_vmem_parser_test.cpp b/trace_streamer/test/unittest/htrace/htrace_sys_vmem_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/htrace_sys_vmem_parser_test.cpp rename to trace_streamer/test/unittest/htrace/htrace_sys_vmem_parser_test.cpp diff --git a/trace_streamer/test/unittest/native_hook_parser_test.cpp b/trace_streamer/test/unittest/htrace/native_memory/native_hook_parser_test.cpp similarity index 99% rename from trace_streamer/test/unittest/native_hook_parser_test.cpp rename to trace_streamer/test/unittest/htrace/native_memory/native_hook_parser_test.cpp index b7657c0b7e63d3922def485e72648a650bd48d08..e0303cac6f78145e088e8afbba5f390a630411e6 100644 --- a/trace_streamer/test/unittest/native_hook_parser_test.cpp +++ b/trace_streamer/test/unittest/htrace/native_memory/native_hook_parser_test.cpp @@ -18,7 +18,7 @@ #include #include -#include "export_test.h" +#include "base/export_test.h" #include "file.h" #include "htrace_native_hook_parser.h" #include "native_hook_result.pb.h" diff --git a/trace_streamer/test/unittest/smaps_parser_test.cpp b/trace_streamer/test/unittest/htrace/smaps_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/smaps_parser_test.cpp rename to trace_streamer/test/unittest/htrace/smaps_parser_test.cpp diff --git a/trace_streamer/test/unittest/http_server_test.cpp b/trace_streamer/test/unittest/http_server_test.cpp deleted file mode 100644 index 720437978f8fbc1be97d166584bc7b1c21b10bfe..0000000000000000000000000000000000000000 --- a/trace_streamer/test/unittest/http_server_test.cpp +++ /dev/null @@ -1,346 +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. - */ - -#include -#include -#include -#include - -#include "http_server.h" -#include "http_socket.h" -#include "rpc/rpc_server.h" -#include "string_help.h" - -using namespace testing::ext; -namespace SysTuning { -namespace TraceStreamer { -#define UNUSED(expr) \ - do { \ - static_cast(expr); \ - } while (0) - -const uint32_t MAX_TESET_BUF_SIZE = 1024; -std::string g_parserData = "sugov:0-178 ( 178) [001] .... 28462.257501: cpu_frequency: state=816000 cpu_id=0 \n"; -std::string g_sqlQuery("select * from measure;"); -char g_clientRecvBuf[MAX_TESET_BUF_SIZE] = {0}; -class HttpServerTest : public ::testing::Test { -public: - void SetUp() - { - stream_.InitFilter(); - } - void TearDown() {} - -public: - TraceStreamerSelector stream_ = {}; -}; - -void ResultCallbackFunc(const std::string result, int32_t num) -{ - // unused - UNUSED(result); -} - -void* HttpServerThread(void* arg) -{ - HttpServer* httpServer = static_cast(arg); - httpServer->Run(); - TS_LOGI("Server thread end"); - pthread_exit(nullptr); -} - -int32_t HttpClient(const char* buf) -{ - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = htons(INADDR_ANY); - const uint16_t listenPort = 9001; - addr.sin_port = htons(listenPort); - struct timeval recvTimeout = {1, 100000}; - - int32_t sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd < 0) { - TS_LOGI("CreateSocket socket error"); - return -1; - } - - int32_t ret = connect(sockfd, (struct sockaddr*)(&addr), sizeof(struct sockaddr)); - if (ret < 0) { - TS_LOGE("Connect error"); - return -1; - } - - ret = send(sockfd, buf, strlen(buf), 0); - if (ret < 0) { - TS_LOGE("Send error"); - return -1; - } - - if (memset_s(g_clientRecvBuf, strlen(g_clientRecvBuf), 0, strlen(g_clientRecvBuf)) != 0) { - TS_LOGE("memset_s error:%s", strerror(errno)); - return -1; - } - int32_t index = 0; - ret = setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)(&recvTimeout), sizeof(recvTimeout)); - if (ret != 0) { - TS_LOGE("set recv time out error"); - return -1; - } - while (true) { - ret = recv(sockfd, g_clientRecvBuf + index, MAX_TESET_BUF_SIZE, 0); - if (ret < 0) { - TS_LOGE("Recv timeout"); - break; - } - index += ret; - } - return 0; -} - -/** - * @tc.name: HttpCorrectRequest - * @tc.desc: HTTP correct request - * @tc.type: FUNC - */ -HWTEST_F(HttpServerTest, HttpCorrectRequest, TestSize.Level1) -{ - TS_LOGI("test21-1"); - HttpServer httpServer; - RpcServer rpcServer; - pthread_t pthreadId = 0; - int32_t ret = 0; - - ret = rpcServer.ParseData((const uint8_t*)g_parserData.c_str(), g_parserData.length(), ResultCallbackFunc, 0); - ret = rpcServer.ParseDataOver(nullptr, 0, ResultCallbackFunc); - ret = rpcServer.SqlQuery((const uint8_t*)g_sqlQuery.c_str(), g_sqlQuery.length(), ResultCallbackFunc); - - httpServer.RegisterRpcFunction(&rpcServer); - ret = pthread_create(&pthreadId, nullptr, HttpServerThread, &httpServer); - if (ret != 0) { - TS_LOGE("Server pthread create fail"); - pthread_exit(nullptr); - } - - sleep(1); - std::string bufToSend = - "GET /sqlquery HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length:\ - 23\r\n\r\nselect * from measure\r\n"; - - ret = HttpClient(bufToSend.c_str()); - if (ret < 0) { - TS_LOGE("Client fail"); - } - httpServer.Exit(); - ret = pthread_join(pthreadId, nullptr); - if (ret != 0) { - TS_LOGE("Server pthread jion fail"); - } - char targetStr[MAX_TESET_BUF_SIZE] = { - "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Type: application/json\r\nTransfer-Encoding: " - "chunked\r\n\r\n6d\r\nok\r\n{\"columns\":[\"type\",\"ts\",\"dur\",\"value\",\"filter_id\"],\"values\":[[" - "\"measure\",28462257501000,null,816000,0]]}\r\n\r\n0\r\n\r\n"}; - - EXPECT_STREQ(targetStr, g_clientRecvBuf); -} -/** - * @tc.name: OthreAgreement - * @tc.desc: Use http1 1. Agreements other than agreements - * @tc.type: FUNC - */ -HWTEST_F(HttpServerTest, OthreAgreement, TestSize.Level1) -{ - TS_LOGI("test21-2"); - HttpServer httpServer; - RpcServer rpcServer; - pthread_t pthreadId = 0; - int32_t ret = 0; - - httpServer.RegisterRpcFunction(&rpcServer); - ret = pthread_create(&pthreadId, nullptr, HttpServerThread, &httpServer); - if (ret != 0) { - TS_LOGE("Server pthread create fail"); - pthread_exit(nullptr); - } - - sleep(1); - std::string bufToSend = - "GET /sqlquery HTTP/0.9\r\nHost: 127.0.0.1\r\nContent-Length:\ - 23\r\n\r\nselect * from measure\r\n"; - - ret = HttpClient(bufToSend.c_str()); - if (ret < 0) { - TS_LOGE("Client fail"); - } - httpServer.Exit(); - ret = pthread_join(pthreadId, nullptr); - if (ret != 0) { - TS_LOGE("Server pthread jion fail"); - } - char targetStr[MAX_TESET_BUF_SIZE] = {"HTTP/1.1 400 Bad Request\r\nConnection: Keep-Alive\r\n\r\n"}; - EXPECT_STREQ(targetStr, g_clientRecvBuf); -} - -/** - * @tc.name: OthreProtocols - * @tc.desc: Use protocols other than GET and POST - * @tc.type: FUNC - */ -HWTEST_F(HttpServerTest, OthreProtocols, TestSize.Level1) -{ - TS_LOGI("test21-3"); - HttpServer httpServer; - RpcServer rpcServer; - pthread_t pthreadId = 0; - int32_t ret = 0; - - httpServer.RegisterRpcFunction(&rpcServer); - ret = pthread_create(&pthreadId, nullptr, HttpServerThread, &httpServer); - if (ret != 0) { - TS_LOGE("Server pthread create fail"); - pthread_exit(nullptr); - } - - sleep(1); - std::string bufToSend = - "HEAD /sqlquery HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length:\ - 23\r\n\r\nselect * from measure\r\n"; - - ret = HttpClient(bufToSend.c_str()); - if (ret < 0) { - TS_LOGE("Client fail"); - } - httpServer.Exit(); - ret = pthread_join(pthreadId, nullptr); - if (ret != 0) { - TS_LOGE("Server pthread jion fail"); - } - char targetStr[MAX_TESET_BUF_SIZE] = {"HTTP/1.1 405 Method Not Allowed\r\nConnection: Keep-Alive\r\n\r\n"}; - EXPECT_STREQ(targetStr, g_clientRecvBuf); -} - -/** - * @tc.name: RequestLineFormatError - * @tc.desc: Request line format error - * @tc.type: FUNC - */ -HWTEST_F(HttpServerTest, RequestLineFormatError, TestSize.Level1) -{ - TS_LOGI("test21-4"); - HttpServer httpServer; - RpcServer rpcServer; - pthread_t pthreadId = 0; - int32_t ret = 0; - - httpServer.RegisterRpcFunction(&rpcServer); - ret = pthread_create(&pthreadId, nullptr, HttpServerThread, &httpServer); - if (ret != 0) { - TS_LOGE("Server pthread create fail"); - pthread_exit(nullptr); - } - - sleep(1); - std::string bufToSend = - "POST /sqlqueryHTTP/0.9\r\nHost: 127.0.0.1\r\nContent-Length:\ - 20\r\n\r\nselect * from meta\r\n"; - - ret = HttpClient(bufToSend.c_str()); - if (ret < 0) { - TS_LOGE("Client fail"); - } - httpServer.Exit(); - ret = pthread_join(pthreadId, nullptr); - if (ret != 0) { - TS_LOGE("Server pthread jion fail"); - } - char targetStr[MAX_TESET_BUF_SIZE] = {"HTTP/1.1 400 Bad Request\r\nConnection: Keep-Alive\r\n\r\n"}; - EXPECT_STREQ(targetStr, g_clientRecvBuf); -} - -/** - * @tc.name: RequestIsNotRPC - * @tc.desc: The URI of HTTP request is not the method of RPC - * @tc.type: FUNC - */ -HWTEST_F(HttpServerTest, RequestIsNotRPC, TestSize.Level1) -{ - TS_LOGI("test21-5"); - HttpServer httpServer; - RpcServer rpcServer; - pthread_t pthreadId = 0; - int32_t ret = 0; - - httpServer.RegisterRpcFunction(&rpcServer); - ret = pthread_create(&pthreadId, nullptr, HttpServerThread, &httpServer); - if (ret != 0) { - TS_LOGE("Server pthread create fail"); - pthread_exit(nullptr); - } - - sleep(1); - std::string bufToSend = - "POST /query HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length:20\r\n\r\n\ - select * from meta\r\n"; - - ret = HttpClient(bufToSend.c_str()); - if (ret < 0) { - TS_LOGE("Client fail"); - } - httpServer.Exit(); - ret = pthread_join(pthreadId, nullptr); - if (ret != 0) { - TS_LOGE("Server pthread jion fail"); - } - char targetStr[MAX_TESET_BUF_SIZE] = {"HTTP/1.1 404 Not Found\r\nConnection: Keep-Alive\r\n\r\n"}; - EXPECT_STREQ(targetStr, g_clientRecvBuf); -} -/** - * @tc.name: RequestTimeout - * @tc.desc: Incomplete request content data - * @tc.type: FUNC - */ -HWTEST_F(HttpServerTest, RequestTimeout, TestSize.Level1) -{ - TS_LOGI("test21-6"); - HttpServer httpServer; - RpcServer rpcServer; - pthread_t pthreadId = 0; - int32_t ret = 0; - - httpServer.RegisterRpcFunction(&rpcServer); - ret = pthread_create(&pthreadId, nullptr, HttpServerThread, &httpServer); - if (ret != 0) { - TS_LOGE("Server pthread create fail"); - pthread_exit(nullptr); - } - - sleep(1); - std::string buf = - "GET /sqlquery HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length:\ - 28\r\n\r\nselect * from measure\r\n"; - - ret = HttpClient(buf.c_str()); - if (ret < 0) { - TS_LOGE("Client fail"); - } - httpServer.Exit(); - ret = pthread_join(pthreadId, nullptr); - if (ret != 0) { - TS_LOGE("Server pthread jion fail"); - } - char targetStr[MAX_TESET_BUF_SIZE] = {"HTTP/1.1 408 Request Time-out\r\nConnection: Keep-Alive\r\n\r\n"}; - EXPECT_STREQ(targetStr, g_clientRecvBuf); -} -} // namespace TraceStreamer -} // namespace SysTuning \ No newline at end of file diff --git a/trace_streamer/test/unittest/rpc_server_test.cpp b/trace_streamer/test/unittest/interface/rpc_server_test.cpp similarity index 100% rename from trace_streamer/test/unittest/rpc_server_test.cpp rename to trace_streamer/test/unittest/interface/rpc_server_test.cpp diff --git a/trace_streamer/test/unittest/split_file_data_test.cpp b/trace_streamer/test/unittest/interface/split_file_data_test.cpp similarity index 100% rename from trace_streamer/test/unittest/split_file_data_test.cpp rename to trace_streamer/test/unittest/interface/split_file_data_test.cpp diff --git a/trace_streamer/test/unittest/wasm_func_test.cpp b/trace_streamer/test/unittest/interface/wasm_func_test.cpp similarity index 100% rename from trace_streamer/test/unittest/wasm_func_test.cpp rename to trace_streamer/test/unittest/interface/wasm_func_test.cpp diff --git a/trace_streamer/test/unittest/parser_pbreader_test.cpp b/trace_streamer/test/unittest/pbreader/parser_pbreader_test.cpp similarity index 100% rename from trace_streamer/test/unittest/parser_pbreader_test.cpp rename to trace_streamer/test/unittest/pbreader/parser_pbreader_test.cpp diff --git a/trace_streamer/test/unittest/proto_reader_test.cpp b/trace_streamer/test/unittest/pbreader/proto_reader_test.cpp similarity index 72% rename from trace_streamer/test/unittest/proto_reader_test.cpp rename to trace_streamer/test/unittest/pbreader/proto_reader_test.cpp index dd9d29d069764d43aaff415c524085186ca9121f..332c8ee6c814a291fa61f0e2e22c0205dbef973d 100644 --- a/trace_streamer/test/unittest/proto_reader_test.cpp +++ b/trace_streamer/test/unittest/pbreader/proto_reader_test.cpp @@ -47,38 +47,38 @@ HWTEST_F(ProtoReaderTest, ParserDataByPBReader, TestSize.Level1) { TS_LOGI("test33-1"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER = 100; - const uint64_t TVNSEC = 1000000; - const std::string NAME = "1000"; - const int32_t ALLOCEVENT = 10000; - testParser.set_count(COUNT); + const int32_t count = 100; + const int32_t number = 100; + const uint64_t tvnsec = 1000000; + const std::string name = "1000"; + const int32_t allocEvent = 10000; + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test = cores->add_test(); - test->set_number(NUMBER); - test->set_tv_nsec(TVNSEC); - test->set_name(NAME); + test->set_number(number); + test->set_tv_nsec(tvnsec); + test->set_name(name); test->set_is_test(true); test->set_state(::Test_State(0)); - test->set_alloc_event(ALLOCEVENT); + test->set_alloc_event(allocEvent); testParser.set_allocated_cores(cores); std::string str = ""; testParser.SerializeToString(&str); TestParser_Reader testParserReader(str); - EXPECT_EQ(COUNT, testParserReader.count()); + EXPECT_EQ(count, testParserReader.count()); auto core = testParserReader.cores(); CpuInfoTest_Reader cpuInfoTest(core.data_, core.size_); auto itor = cpuInfoTest.test(); Test_Reader cpuInfoReader1(itor->ToBytes()); - EXPECT_EQ(NUMBER, cpuInfoReader1.number()); - EXPECT_EQ(TVNSEC, cpuInfoReader1.tv_nsec()); - EXPECT_EQ(NAME, cpuInfoReader1.name().ToStdString()); + EXPECT_EQ(number, cpuInfoReader1.number()); + EXPECT_EQ(tvnsec, cpuInfoReader1.tv_nsec()); + EXPECT_EQ(name, cpuInfoReader1.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader1.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader1.state()); - EXPECT_EQ(ALLOCEVENT, cpuInfoReader1.alloc_event()); + EXPECT_EQ(allocEvent, cpuInfoReader1.alloc_event()); } /** @@ -90,76 +90,76 @@ HWTEST_F(ProtoReaderTest, ParserRepeatedDataByPBReader, TestSize.Level1) { TS_LOGI("test33-2"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER1 = 100; - const uint64_t TVNSEC1 = 1000000; - const std::string NAME1 = "1000"; - const int32_t ALLOCEVENT1 = 10000; - const int32_t NUMBER2 = 200; - const uint64_t TVNSEC2 = 2000000; - const std::string NAME2 = "2000"; - const int32_t ALLOCEVENT2 = 20000; - const int32_t NUMBER3 = 300; - const uint64_t TVNSEC3 = 3000000; - const std::string NAME3 = "3000"; - const int32_t ALLOCEVENT3 = 30000; + const int32_t count = 100; + const int32_t number1 = 100; + const uint64_t tvnsec1 = 1000000; + const std::string name1 = "1000"; + const int32_t allocEvent1 = 10000; + const int32_t nameber2 = 200; + const uint64_t tvnsec2 = 2000000; + const std::string name2 = "2000"; + const int32_t allocEvent2 = 20000; + const int32_t number3 = 300; + const uint64_t tvnsec3 = 3000000; + const std::string name3 = "3000"; + const int32_t allocEvent3 = 30000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test1 = cores->add_test(); - test1->set_number(NUMBER1); - test1->set_tv_nsec(TVNSEC1); - test1->set_name(NAME1); + test1->set_number(number1); + test1->set_tv_nsec(tvnsec1); + test1->set_name(name1); test1->set_is_test(true); test1->set_state(::Test_State(0)); - test1->set_alloc_event(ALLOCEVENT1); + test1->set_alloc_event(allocEvent1); auto test2 = cores->add_test(); - test2->set_number(NUMBER2); - test2->set_tv_nsec(TVNSEC2); - test2->set_name(NAME2); + test2->set_number(nameber2); + test2->set_tv_nsec(tvnsec2); + test2->set_name(name2); test2->set_is_test(false); test2->set_state(::Test_State(1)); - test2->set_alloc_event(ALLOCEVENT2); + test2->set_alloc_event(allocEvent2); auto test3 = cores->add_test(); - test3->set_number(NUMBER3); - test3->set_tv_nsec(TVNSEC3); - test3->set_name(NAME3); + test3->set_number(number3); + test3->set_tv_nsec(tvnsec3); + test3->set_name(name3); test3->set_is_test(true); test3->set_state(::Test_State(0)); - test3->set_alloc_event(ALLOCEVENT3); + test3->set_alloc_event(allocEvent3); testParser.set_allocated_cores(cores); testParser.SerializeToString(&str); TestParser_Reader testParserReader(str); - EXPECT_EQ(COUNT, testParserReader.count()); + EXPECT_EQ(count, testParserReader.count()); auto core = testParserReader.cores(); CpuInfoTest_Reader cpuInfoTest(core.data_, core.size_); auto itor = cpuInfoTest.test(); Test_Reader cpuInfoReader1(itor->ToBytes()); - EXPECT_EQ(NUMBER1, cpuInfoReader1.number()); - EXPECT_EQ(TVNSEC1, cpuInfoReader1.tv_nsec()); - EXPECT_EQ(NAME1, cpuInfoReader1.name().ToStdString()); + EXPECT_EQ(number1, cpuInfoReader1.number()); + EXPECT_EQ(tvnsec1, cpuInfoReader1.tv_nsec()); + EXPECT_EQ(name1, cpuInfoReader1.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader1.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader1.state()); - EXPECT_EQ(ALLOCEVENT1, cpuInfoReader1.alloc_event()); + EXPECT_EQ(allocEvent1, cpuInfoReader1.alloc_event()); itor++; Test_Reader cpuInfoReader2(itor->ToBytes()); - EXPECT_EQ(NUMBER2, cpuInfoReader2.number()); - EXPECT_EQ(TVNSEC2, cpuInfoReader2.tv_nsec()); - EXPECT_EQ(NAME2, cpuInfoReader2.name().ToStdString()); + EXPECT_EQ(nameber2, cpuInfoReader2.number()); + EXPECT_EQ(tvnsec2, cpuInfoReader2.tv_nsec()); + EXPECT_EQ(name2, cpuInfoReader2.name().ToStdString()); EXPECT_EQ(false, cpuInfoReader2.is_test()); EXPECT_EQ(::Test_State(1), cpuInfoReader2.state()); - EXPECT_EQ(ALLOCEVENT2, cpuInfoReader2.alloc_event()); + EXPECT_EQ(allocEvent2, cpuInfoReader2.alloc_event()); itor++; Test_Reader cpuInfoReader3(itor->ToBytes()); - EXPECT_EQ(NUMBER3, cpuInfoReader3.number()); - EXPECT_EQ(TVNSEC3, cpuInfoReader3.tv_nsec()); - EXPECT_EQ(NAME3, cpuInfoReader3.name().ToStdString()); + EXPECT_EQ(number3, cpuInfoReader3.number()); + EXPECT_EQ(tvnsec3, cpuInfoReader3.tv_nsec()); + EXPECT_EQ(name3, cpuInfoReader3.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader3.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader3.state()); - EXPECT_EQ(ALLOCEVENT3, cpuInfoReader3.alloc_event()); + EXPECT_EQ(allocEvent3, cpuInfoReader3.alloc_event()); } /** @@ -199,76 +199,76 @@ HWTEST_F(ProtoReaderTest, ParserOneofForMutiDataByPBReader, TestSize.Level1) { TS_LOGI("test33-4"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER1 = 100; - const uint64_t TVNSEC1 = 1000000; - const std::string NAME1 = "1000"; - const int32_t ALLOCEVENT1 = 10000; - const int32_t NUMBER2 = 200; - const uint64_t TVNSEC2 = 2000000; - const std::string NAME2 = "2000"; - const std::string FREEEVENT = "20000"; - const int32_t NUMBER3 = 300; - const uint64_t TVNSEC3 = 3000000; - const std::string NAME3 = "3000"; - const int32_t ALLOCEVENT3 = 30000; + const int32_t count = 100; + const int32_t number1 = 100; + const uint64_t tvnsec1 = 1000000; + const std::string name1 = "1000"; + const int32_t allocEvent1 = 10000; + const int32_t nameber2 = 200; + const uint64_t tvnsec2 = 2000000; + const std::string name2 = "2000"; + const std::string freeEvent = "20000"; + const int32_t number3 = 300; + const uint64_t tvnsec3 = 3000000; + const std::string name3 = "3000"; + const int32_t allocEvent3 = 30000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test1 = cores->add_test(); - test1->set_number(NUMBER1); - test1->set_tv_nsec(TVNSEC1); - test1->set_name(NAME1); + test1->set_number(number1); + test1->set_tv_nsec(tvnsec1); + test1->set_name(name1); test1->set_is_test(true); test1->set_state(::Test_State(0)); - test1->set_alloc_event(ALLOCEVENT1); + test1->set_alloc_event(allocEvent1); auto test2 = cores->add_test(); - test2->set_number(NUMBER2); - test2->set_tv_nsec(TVNSEC2); - test2->set_name(NAME2); + test2->set_number(nameber2); + test2->set_tv_nsec(tvnsec2); + test2->set_name(name2); test2->set_is_test(false); test2->set_state(::Test_State(1)); - test2->set_free_event(FREEEVENT); + test2->set_free_event(freeEvent); auto test3 = cores->add_test(); - test3->set_number(NUMBER3); - test3->set_tv_nsec(TVNSEC3); - test3->set_name(NAME3); + test3->set_number(number3); + test3->set_tv_nsec(tvnsec3); + test3->set_name(name3); test3->set_is_test(true); test3->set_state(::Test_State(0)); - test3->set_alloc_event(ALLOCEVENT3); + test3->set_alloc_event(allocEvent3); testParser.set_allocated_cores(cores); testParser.SerializeToString(&str); TestParser_Reader testParserReader(str); - EXPECT_EQ(COUNT, testParserReader.count()); + EXPECT_EQ(count, testParserReader.count()); auto core = testParserReader.cores(); CpuInfoTest_Reader cpuInfoTest(core.data_, core.size_); auto itor = cpuInfoTest.test(); Test_Reader cpuInfoReader1(itor->ToBytes()); - EXPECT_EQ(NUMBER1, cpuInfoReader1.number()); - EXPECT_EQ(TVNSEC1, cpuInfoReader1.tv_nsec()); - EXPECT_EQ(NAME1, cpuInfoReader1.name().ToStdString()); + EXPECT_EQ(number1, cpuInfoReader1.number()); + EXPECT_EQ(tvnsec1, cpuInfoReader1.tv_nsec()); + EXPECT_EQ(name1, cpuInfoReader1.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader1.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader1.state()); - EXPECT_EQ(ALLOCEVENT1, cpuInfoReader1.alloc_event()); + EXPECT_EQ(allocEvent1, cpuInfoReader1.alloc_event()); itor++; Test_Reader cpuInfoReader2(itor->ToBytes()); - EXPECT_EQ(NUMBER2, cpuInfoReader2.number()); - EXPECT_EQ(TVNSEC2, cpuInfoReader2.tv_nsec()); - EXPECT_EQ(NAME2, cpuInfoReader2.name().ToStdString()); + EXPECT_EQ(nameber2, cpuInfoReader2.number()); + EXPECT_EQ(tvnsec2, cpuInfoReader2.tv_nsec()); + EXPECT_EQ(name2, cpuInfoReader2.name().ToStdString()); EXPECT_EQ(false, cpuInfoReader2.is_test()); EXPECT_EQ(::Test_State(1), cpuInfoReader2.state()); - EXPECT_EQ(FREEEVENT, cpuInfoReader2.free_event().ToStdString()); + EXPECT_EQ(freeEvent, cpuInfoReader2.free_event().ToStdString()); itor++; Test_Reader cpuInfoReader3(itor->ToBytes()); - EXPECT_EQ(NUMBER3, cpuInfoReader3.number()); - EXPECT_EQ(TVNSEC3, cpuInfoReader3.tv_nsec()); - EXPECT_EQ(NAME3, cpuInfoReader3.name().ToStdString()); + EXPECT_EQ(number3, cpuInfoReader3.number()); + EXPECT_EQ(tvnsec3, cpuInfoReader3.tv_nsec()); + EXPECT_EQ(name3, cpuInfoReader3.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader3.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader3.state()); - EXPECT_EQ(ALLOCEVENT3, cpuInfoReader3.alloc_event()); + EXPECT_EQ(allocEvent3, cpuInfoReader3.alloc_event()); } /** @@ -280,38 +280,38 @@ HWTEST_F(ProtoReaderTest, ParserOneofDataForAllocEventByPBReader, TestSize.Level { TS_LOGI("test33-5"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER1 = 100; - const uint64_t TVNSEC1 = 1000000; - const std::string NAME1 = "1000"; - const int32_t ALLOCEVENT = 10000; + const int32_t count = 100; + const int32_t number1 = 100; + const uint64_t tvnsec1 = 1000000; + const std::string name1 = "1000"; + const int32_t allocEvent = 10000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test1 = cores->add_test(); - test1->set_number(NUMBER1); - test1->set_tv_nsec(TVNSEC1); - test1->set_name(NAME1); + test1->set_number(number1); + test1->set_tv_nsec(tvnsec1); + test1->set_name(name1); test1->set_is_test(true); test1->set_state(::Test_State(0)); - test1->set_alloc_event(ALLOCEVENT); + test1->set_alloc_event(allocEvent); testParser.set_allocated_cores(cores); testParser.SerializeToString(&str); TestParser_Reader testParserReader(str); - EXPECT_EQ(COUNT, testParserReader.count()); + EXPECT_EQ(count, testParserReader.count()); auto core = testParserReader.cores(); CpuInfoTest_Reader cpuInfoTest(core.data_, core.size_); auto itor = cpuInfoTest.test(); Test_Reader cpuInfoReader1(itor->ToBytes()); - EXPECT_EQ(NUMBER1, cpuInfoReader1.number()); - EXPECT_EQ(TVNSEC1, cpuInfoReader1.tv_nsec()); - EXPECT_EQ(NAME1, cpuInfoReader1.name().ToStdString()); + EXPECT_EQ(number1, cpuInfoReader1.number()); + EXPECT_EQ(tvnsec1, cpuInfoReader1.tv_nsec()); + EXPECT_EQ(name1, cpuInfoReader1.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader1.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader1.state()); - EXPECT_EQ(ALLOCEVENT, cpuInfoReader1.alloc_event()); + EXPECT_EQ(allocEvent, cpuInfoReader1.alloc_event()); } /** @@ -323,38 +323,38 @@ HWTEST_F(ProtoReaderTest, ParserOneofDataForFreeEventByPBReader, TestSize.Level1 { TS_LOGI("test33-6"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER1 = 100; - const uint64_t TVNSEC1 = 1000000; - const std::string NAME1 = "1000"; - const int32_t FREEEVENT = 10000; + const int32_t count = 100; + const int32_t number1 = 100; + const uint64_t tvnsec1 = 1000000; + const std::string name1 = "1000"; + const int32_t freeEvent = 10000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test1 = cores->add_test(); - test1->set_number(NUMBER1); - test1->set_tv_nsec(TVNSEC1); - test1->set_name(NAME1); + test1->set_number(number1); + test1->set_tv_nsec(tvnsec1); + test1->set_name(name1); test1->set_is_test(true); test1->set_state(::Test_State(0)); - test1->set_alloc_event(FREEEVENT); + test1->set_alloc_event(freeEvent); testParser.set_allocated_cores(cores); testParser.SerializeToString(&str); TestParser_Reader testParserReader(str); - EXPECT_EQ(COUNT, testParserReader.count()); + EXPECT_EQ(count, testParserReader.count()); auto core = testParserReader.cores(); CpuInfoTest_Reader cpuInfoTest(core.data_, core.size_); auto itor = cpuInfoTest.test(); Test_Reader cpuInfoReader1(itor->ToBytes()); - EXPECT_EQ(NUMBER1, cpuInfoReader1.number()); - EXPECT_EQ(TVNSEC1, cpuInfoReader1.tv_nsec()); - EXPECT_EQ(NAME1, cpuInfoReader1.name().ToStdString()); + EXPECT_EQ(number1, cpuInfoReader1.number()); + EXPECT_EQ(tvnsec1, cpuInfoReader1.tv_nsec()); + EXPECT_EQ(name1, cpuInfoReader1.name().ToStdString()); EXPECT_EQ(true, cpuInfoReader1.is_test()); EXPECT_EQ(::Test_State(0), cpuInfoReader1.state()); - EXPECT_EQ(FREEEVENT, cpuInfoReader1.alloc_event()); + EXPECT_EQ(freeEvent, cpuInfoReader1.alloc_event()); } /** @@ -389,20 +389,20 @@ HWTEST_F(ProtoReaderTest, ParserDataByVarInt, TestSize.Level1) { TS_LOGI("test33-8"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER = 100; - const uint64_t TVNSEC = 1000000; - const std::string NAME = "1000"; - const int32_t ALLOCEVENT = 10000; - testParser.set_count(COUNT); + const int32_t count = 100; + const int32_t number = 100; + const uint64_t tvnsec = 1000000; + const std::string name = "1000"; + const int32_t allocEvent = 10000; + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test = cores->add_test(); - test->set_number(NUMBER); - test->set_tv_nsec(TVNSEC); - test->set_name(NAME); + test->set_number(number); + test->set_tv_nsec(tvnsec); + test->set_name(name); test->set_is_test(true); test->set_state(::Test_State(0)); - test->set_alloc_event(ALLOCEVENT); + test->set_alloc_event(allocEvent); testParser.set_allocated_cores(cores); std::string str = ""; @@ -415,7 +415,7 @@ HWTEST_F(ProtoReaderTest, ParserDataByVarInt, TestSize.Level1) const uint8_t* nextData = VarIntDecode(reinterpret_cast(str.data() + 1), reinterpret_cast(str.data() + 11), &count); } - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); } /** @@ -427,20 +427,20 @@ HWTEST_F(ProtoReaderTest, ParserDataByPBReaderBase, TestSize.Level1) { TS_LOGI("test33-9"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER = 100; - const uint64_t TVNSEC = 1000000; - const std::string NAME = "1000"; - const int32_t ALLOCEVENT = 10000; - testParser.set_count(COUNT); + const int32_t count = 100; + const int32_t number = 100; + const uint64_t tvnsec = 1000000; + const std::string name = "1000"; + const int32_t allocEvent = 10000; + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test = cores->add_test(); - test->set_number(NUMBER); - test->set_tv_nsec(TVNSEC); - test->set_name(NAME); + test->set_number(number); + test->set_tv_nsec(tvnsec); + test->set_name(name); test->set_is_test(true); test->set_state(::Test_State(0)); - test->set_alloc_event(ALLOCEVENT); + test->set_alloc_event(allocEvent); testParser.set_allocated_cores(cores); std::string str = ""; @@ -448,7 +448,7 @@ HWTEST_F(ProtoReaderTest, ParserDataByPBReaderBase, TestSize.Level1) TypedProtoReader<2> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.FindDataArea(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto core = typedProtoTest.FindDataArea(TestParser_Reader::kCoresDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(core.data_), core.size_); auto typtest = typedProtoCpuInfoTest.FindDataArea(CpuInfoTest_Reader::kTestDataAreaNumber).ToBytes(); @@ -460,12 +460,12 @@ HWTEST_F(ProtoReaderTest, ParserDataByPBReaderBase, TestSize.Level1) auto state = typedProtoTestReader.FindDataArea(Test_Reader::kStateDataAreaNumber).ToInt32(); auto allocEvent = typedProtoTestReader.FindDataArea(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER, number); - EXPECT_EQ(TVNSEC, tvNsec); - EXPECT_EQ(NAME, name); + EXPECT_EQ(number, number); + EXPECT_EQ(tvnsec, tvNsec); + EXPECT_EQ(name, name); EXPECT_EQ(true, isTest); EXPECT_EQ(::Test_State(0), state); - EXPECT_EQ(ALLOCEVENT, allocEvent); + EXPECT_EQ(allocEvent, allocEvent); } /** @@ -477,99 +477,99 @@ HWTEST_F(ProtoReaderTest, ParserMutiDataByPBReaderBase, TestSize.Level1) { TS_LOGI("test33-10"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER1 = 100; - const uint64_t TVNSEC1 = 1000000; - const std::string NAME1 = "1000"; - const int32_t ALLOCEVENT1 = 10000; - const int32_t NUMBER2 = 200; - const uint64_t TVNSEC2 = 2000000; - const std::string NAME2 = "2000"; - const int32_t ALLOCEVENT2 = 20000; - const int32_t NUMBER3 = 300; - const uint64_t TVNSEC3 = 3000000; - const std::string NAME3 = "3000"; - const int32_t ALLOCEVENT3 = 30000; + const int32_t count = 100; + const int32_t number1 = 100; + const uint64_t tvnsec1 = 1000000; + const std::string name1 = "1000"; + const int32_t allocEvent1 = 10000; + const int32_t nameber2 = 200; + const uint64_t tvnsec2 = 2000000; + const std::string name2 = "2000"; + const int32_t allocEvent2 = 20000; + const int32_t number3 = 300; + const uint64_t tvnsec3 = 3000000; + const std::string name3 = "3000"; + const int32_t allocEvent3 = 30000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test1 = cores->add_test(); - test1->set_number(NUMBER1); - test1->set_tv_nsec(TVNSEC1); - test1->set_name(NAME1); + test1->set_number(number1); + test1->set_tv_nsec(tvnsec1); + test1->set_name(name1); test1->set_is_test(true); test1->set_state(::Test_State(0)); - test1->set_alloc_event(ALLOCEVENT1); + test1->set_alloc_event(allocEvent1); auto test2 = cores->add_test(); - test2->set_number(NUMBER2); - test2->set_tv_nsec(TVNSEC2); - test2->set_name(NAME2); + test2->set_number(nameber2); + test2->set_tv_nsec(tvnsec2); + test2->set_name(name2); test2->set_is_test(false); test2->set_state(::Test_State(1)); - test2->set_alloc_event(ALLOCEVENT2); + test2->set_alloc_event(allocEvent2); auto test3 = cores->add_test(); - test3->set_number(NUMBER3); - test3->set_tv_nsec(TVNSEC3); - test3->set_name(NAME3); + test3->set_number(number3); + test3->set_tv_nsec(tvnsec3); + test3->set_name(name3); test3->set_is_test(true); test3->set_state(::Test_State(0)); - test3->set_alloc_event(ALLOCEVENT3); + test3->set_alloc_event(allocEvent3); testParser.set_allocated_cores(cores); testParser.SerializeToString(&str); TypedProtoReader<2> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.FindDataArea(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto core = typedProtoTest.FindDataArea(TestParser_Reader::kCoresDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(core.data_), core.size_); auto repeate = typedProtoCpuInfoTest.GetRepeated(CpuInfoTest_Reader::kTestDataAreaNumber); TypedProtoReader<7> typedProtoTestReader1(repeate->ToBytes().data_, repeate->ToBytes().size_); auto number1 = typedProtoTestReader1.FindDataArea(Test_Reader::kNumberDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER1, number1); + EXPECT_EQ(number1, number1); auto tvNsec1 = typedProtoTestReader1.FindDataArea(Test_Reader::kTvNsecDataAreaNumber).ToUint64(); - EXPECT_EQ(TVNSEC1, tvNsec1); + EXPECT_EQ(tvnsec1, tvNsec1); auto name1 = typedProtoTestReader1.FindDataArea(Test_Reader::kNameDataAreaNumber).ToStdString(); - EXPECT_EQ(NAME1, name1); + EXPECT_EQ(name1, name1); auto isTest1 = typedProtoTestReader1.FindDataArea(Test_Reader::kIsTestDataAreaNumber).ToBool(); EXPECT_EQ(true, isTest1); auto state1 = typedProtoTestReader1.FindDataArea(Test_Reader::kStateDataAreaNumber).ToInt32(); EXPECT_EQ(::Test_State(0), state1); auto allocEvent1 = typedProtoTestReader1.FindDataArea(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(ALLOCEVENT1, allocEvent1); + EXPECT_EQ(allocEvent1, allocEvent1); repeate++; TypedProtoReader<7> typedProtoTestReader2(repeate->ToBytes().data_, repeate->ToBytes().size_); auto number2 = typedProtoTestReader2.FindDataArea(Test_Reader::kNumberDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER2, number2); + EXPECT_EQ(nameber2, number2); auto tvNsec2 = typedProtoTestReader2.FindDataArea(Test_Reader::kTvNsecDataAreaNumber).ToUint64(); - EXPECT_EQ(TVNSEC2, tvNsec2); + EXPECT_EQ(tvnsec2, tvNsec2); auto name2 = typedProtoTestReader2.FindDataArea(Test_Reader::kNameDataAreaNumber).ToStdString(); - EXPECT_EQ(NAME2, name2); + EXPECT_EQ(name2, name2); auto isTest2 = typedProtoTestReader2.FindDataArea(Test_Reader::kIsTestDataAreaNumber).ToBool(); EXPECT_EQ(false, isTest2); auto state2 = typedProtoTestReader2.FindDataArea(Test_Reader::kStateDataAreaNumber).ToInt32(); EXPECT_EQ(::Test_State(1), state2); auto allocEvent2 = typedProtoTestReader2.FindDataArea(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(ALLOCEVENT2, allocEvent2); + EXPECT_EQ(allocEvent2, allocEvent2); repeate++; TypedProtoReader<7> typedProtoTestReader3(repeate->ToBytes().data_, repeate->ToBytes().size_); auto number3 = typedProtoTestReader3.FindDataArea(Test_Reader::kNumberDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER3, number3); + EXPECT_EQ(number3, number3); auto tvNsec3 = typedProtoTestReader3.FindDataArea(Test_Reader::kTvNsecDataAreaNumber).ToUint64(); - EXPECT_EQ(TVNSEC3, tvNsec3); + EXPECT_EQ(tvnsec3, tvNsec3); auto name3 = typedProtoTestReader3.FindDataArea(Test_Reader::kNameDataAreaNumber).ToStdString(); - EXPECT_EQ(NAME3, name3); + EXPECT_EQ(name3, name3); auto isTest3 = typedProtoTestReader3.FindDataArea(Test_Reader::kIsTestDataAreaNumber).ToBool(); EXPECT_EQ(true, isTest3); auto state3 = typedProtoTestReader3.FindDataArea(Test_Reader::kStateDataAreaNumber).ToInt32(); EXPECT_EQ(::Test_State(0), state3); auto allocEvent3 = typedProtoTestReader3.FindDataArea(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(ALLOCEVENT3, allocEvent3); + EXPECT_EQ(allocEvent3, allocEvent3); } /** @@ -616,20 +616,20 @@ HWTEST_F(ProtoReaderTest, ParserDataByGet, TestSize.Level1) { TS_LOGI("test33-12"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER = 100; - const uint64_t TVNSEC = 1000000; - const std::string NAME = "1000"; - const int32_t ALLOCEVENT = 10000; - testParser.set_count(COUNT); + const int32_t count = 100; + const int32_t number = 100; + const uint64_t tvnsec = 1000000; + const std::string name = "1000"; + const int32_t allocEvent = 10000; + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test = cores->add_test(); - test->set_number(NUMBER); - test->set_tv_nsec(TVNSEC); - test->set_name(NAME); + test->set_number(number); + test->set_tv_nsec(tvnsec); + test->set_name(name); test->set_is_test(true); test->set_state(::Test_State(0)); - test->set_alloc_event(ALLOCEVENT); + test->set_alloc_event(allocEvent); testParser.set_allocated_cores(cores); std::string str = ""; @@ -637,7 +637,7 @@ HWTEST_F(ProtoReaderTest, ParserDataByGet, TestSize.Level1) TypedProtoReader<2> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto core = typedProtoTest.Get(TestParser_Reader::kCoresDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(core.data_), core.size_); auto typtest = typedProtoCpuInfoTest.Get(CpuInfoTest_Reader::kTestDataAreaNumber).ToBytes(); @@ -649,12 +649,12 @@ HWTEST_F(ProtoReaderTest, ParserDataByGet, TestSize.Level1) auto state = typedProtoTestReader.Get(Test_Reader::kStateDataAreaNumber).ToInt32(); auto allocEvent = typedProtoTestReader.Get(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER, number); - EXPECT_EQ(TVNSEC, tvNsec); - EXPECT_EQ(NAME, name); + EXPECT_EQ(number, number); + EXPECT_EQ(tvnsec, tvNsec); + EXPECT_EQ(name, name); EXPECT_EQ(true, isTest); EXPECT_EQ(::Test_State(0), state); - EXPECT_EQ(ALLOCEVENT, allocEvent); + EXPECT_EQ(allocEvent, allocEvent); } /** @@ -666,99 +666,99 @@ HWTEST_F(ProtoReaderTest, ParserMutiDataByGet, TestSize.Level1) { TS_LOGI("test33-13"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER1 = 100; - const uint64_t TVNSEC1 = 1000000; - const std::string NAME1 = "1000"; - const int32_t ALLOCEVENT1 = 10000; - const int32_t NUMBER2 = 200; - const uint64_t TVNSEC2 = 2000000; - const std::string NAME2 = "2000"; - const int32_t ALLOCEVENT2 = 20000; - const int32_t NUMBER3 = 300; - const uint64_t TVNSEC3 = 3000000; - const std::string NAME3 = "3000"; - const int32_t ALLOCEVENT3 = 30000; + const int32_t count = 100; + const int32_t number1 = 100; + const uint64_t tvnsec1 = 1000000; + const std::string name1 = "1000"; + const int32_t allocEvent1 = 10000; + const int32_t nameber2 = 200; + const uint64_t tvnsec2 = 2000000; + const std::string name2 = "2000"; + const int32_t allocEvent2 = 20000; + const int32_t number3 = 300; + const uint64_t tvnsec3 = 3000000; + const std::string name3 = "3000"; + const int32_t allocEvent3 = 30000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::CpuInfoTest* cores = new ::CpuInfoTest(); auto test1 = cores->add_test(); - test1->set_number(NUMBER1); - test1->set_tv_nsec(TVNSEC1); - test1->set_name(NAME1); + test1->set_number(number1); + test1->set_tv_nsec(tvnsec1); + test1->set_name(name1); test1->set_is_test(true); test1->set_state(::Test_State(0)); - test1->set_alloc_event(ALLOCEVENT1); + test1->set_alloc_event(allocEvent1); auto test2 = cores->add_test(); - test2->set_number(NUMBER2); - test2->set_tv_nsec(TVNSEC2); - test2->set_name(NAME2); + test2->set_number(nameber2); + test2->set_tv_nsec(tvnsec2); + test2->set_name(name2); test2->set_is_test(false); test2->set_state(::Test_State(1)); - test2->set_alloc_event(ALLOCEVENT2); + test2->set_alloc_event(allocEvent2); auto test3 = cores->add_test(); - test3->set_number(NUMBER3); - test3->set_tv_nsec(TVNSEC3); - test3->set_name(NAME3); + test3->set_number(number3); + test3->set_tv_nsec(tvnsec3); + test3->set_name(name3); test3->set_is_test(true); test3->set_state(::Test_State(0)); - test3->set_alloc_event(ALLOCEVENT3); + test3->set_alloc_event(allocEvent3); testParser.set_allocated_cores(cores); testParser.SerializeToString(&str); TypedProtoReader<2> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto core = typedProtoTest.Get(TestParser_Reader::kCoresDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(core.data_), core.size_); auto repeate = typedProtoCpuInfoTest.GetRepeated(CpuInfoTest_Reader::kTestDataAreaNumber); TypedProtoReader<7> typedProtoTestReader1(repeate->ToBytes().data_, repeate->ToBytes().size_); auto number1 = typedProtoTestReader1.Get(Test_Reader::kNumberDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER1, number1); + EXPECT_EQ(number1, number1); auto tvNsec1 = typedProtoTestReader1.Get(Test_Reader::kTvNsecDataAreaNumber).ToUint64(); - EXPECT_EQ(TVNSEC1, tvNsec1); + EXPECT_EQ(tvnsec1, tvNsec1); auto name1 = typedProtoTestReader1.Get(Test_Reader::kNameDataAreaNumber).ToStdString(); - EXPECT_EQ(NAME1, name1); + EXPECT_EQ(name1, name1); auto isTest1 = typedProtoTestReader1.Get(Test_Reader::kIsTestDataAreaNumber).ToBool(); EXPECT_EQ(true, isTest1); auto state1 = typedProtoTestReader1.Get(Test_Reader::kStateDataAreaNumber).ToInt32(); EXPECT_EQ(::Test_State(0), state1); auto allocEvent1 = typedProtoTestReader1.Get(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(ALLOCEVENT1, allocEvent1); + EXPECT_EQ(allocEvent1, allocEvent1); repeate++; TypedProtoReader<7> typedProtoTestReader2(repeate->ToBytes().data_, repeate->ToBytes().size_); auto number2 = typedProtoTestReader2.Get(Test_Reader::kNumberDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER2, number2); + EXPECT_EQ(nameber2, number2); auto tvNsec2 = typedProtoTestReader2.Get(Test_Reader::kTvNsecDataAreaNumber).ToUint64(); - EXPECT_EQ(TVNSEC2, tvNsec2); + EXPECT_EQ(tvnsec2, tvNsec2); auto name2 = typedProtoTestReader2.Get(Test_Reader::kNameDataAreaNumber).ToStdString(); - EXPECT_EQ(NAME2, name2); + EXPECT_EQ(name2, name2); auto isTest2 = typedProtoTestReader2.Get(Test_Reader::kIsTestDataAreaNumber).ToBool(); EXPECT_EQ(false, isTest2); auto state2 = typedProtoTestReader2.Get(Test_Reader::kStateDataAreaNumber).ToInt32(); EXPECT_EQ(::Test_State(1), state2); auto allocEvent2 = typedProtoTestReader2.Get(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(ALLOCEVENT2, allocEvent2); + EXPECT_EQ(allocEvent2, allocEvent2); repeate++; TypedProtoReader<7> typedProtoTestReader3(repeate->ToBytes().data_, repeate->ToBytes().size_); auto number3 = typedProtoTestReader3.Get(Test_Reader::kNumberDataAreaNumber).ToInt32(); - EXPECT_EQ(NUMBER3, number3); + EXPECT_EQ(number3, number3); auto tvNsec3 = typedProtoTestReader3.Get(Test_Reader::kTvNsecDataAreaNumber).ToUint64(); - EXPECT_EQ(TVNSEC3, tvNsec3); + EXPECT_EQ(tvnsec3, tvNsec3); auto name3 = typedProtoTestReader3.Get(Test_Reader::kNameDataAreaNumber).ToStdString(); - EXPECT_EQ(NAME3, name3); + EXPECT_EQ(name3, name3); auto isTest3 = typedProtoTestReader3.Get(Test_Reader::kIsTestDataAreaNumber).ToBool(); EXPECT_EQ(true, isTest3); auto state3 = typedProtoTestReader3.Get(Test_Reader::kStateDataAreaNumber).ToInt32(); EXPECT_EQ(::Test_State(0), state3); auto allocEvent3 = typedProtoTestReader3.Get(Test_Reader::kAllocEventDataAreaNumber).ToInt32(); - EXPECT_EQ(ALLOCEVENT3, allocEvent3); + EXPECT_EQ(allocEvent3, allocEvent3); } /** @@ -805,18 +805,18 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedInt32DataByPBReader, TestSize.Leve { TS_LOGI("test33-15"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER = 1000; - const int32_t NUMBER1 = 1001; - const int32_t NUMBER2 = 1002; - const int32_t NUMBER3 = 1003; + const int32_t count = 100; + const int32_t number = 1000; + const int32_t number1 = 1001; + const int32_t nameber2 = 1002; + const int32_t number3 = 1003; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::NumberTest* numberTest = new ::NumberTest(); - numberTest->add_numbertext(NUMBER); - numberTest->add_numbertext(NUMBER1); - numberTest->add_numbertext(NUMBER2); - numberTest->add_numbertext(NUMBER3); + numberTest->add_numbertext(number); + numberTest->add_numbertext(number1); + numberTest->add_numbertext(nameber2); + numberTest->add_numbertext(number3); testParser.set_allocated_numbertest(numberTest); testParser.SerializeToString(&str); @@ -824,22 +824,22 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedInt32DataByPBReader, TestSize.Leve TypedProtoReader<3> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto numberType = typedProtoTest.Get(TestParser_Reader::kNumberTestDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(numberType.data_), numberType.size_); auto packedRepeate = typedProtoCpuInfoTest.GetPackedRepeated( NumberTest_Reader::kNumberTextDataAreaNumber, &parserError); auto numberValue = *packedRepeate; - EXPECT_EQ(NUMBER, numberValue); + EXPECT_EQ(number, numberValue); packedRepeate++; auto numberValue1 = *packedRepeate; - EXPECT_EQ(NUMBER1, numberValue1); + EXPECT_EQ(number1, numberValue1); packedRepeate++; auto numberValue2 = *packedRepeate; - EXPECT_EQ(NUMBER2, numberValue2); + EXPECT_EQ(nameber2, numberValue2); packedRepeate++; auto numberValue3 = *packedRepeate; - EXPECT_EQ(NUMBER3, numberValue3); + EXPECT_EQ(number3, numberValue3); } /** @@ -851,18 +851,18 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedFixed64DataByPBReader, TestSize.Le { TS_LOGI("test33-16"); TestParser testParser; - const int32_t COUNT = 100; - const double NUMBER = 1000.01; - const double NUMBER1 = 1001.01; - const double NUMBER2 = 1002.01; - const double NUMBER3 = 1003.01; + const int32_t count = 100; + const double number = 1000.01; + const double number1 = 1001.01; + const double nameber2 = 1002.01; + const double number3 = 1003.01; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::Fixed64Test* fixed64Test = new ::Fixed64Test(); - fixed64Test->add_fixed64numbertext(NUMBER); - fixed64Test->add_fixed64numbertext(NUMBER1); - fixed64Test->add_fixed64numbertext(NUMBER2); - fixed64Test->add_fixed64numbertext(NUMBER3); + fixed64Test->add_fixed64numbertext(number); + fixed64Test->add_fixed64numbertext(number1); + fixed64Test->add_fixed64numbertext(nameber2); + fixed64Test->add_fixed64numbertext(number3); testParser.set_allocated_fixed64test(fixed64Test); testParser.SerializeToString(&str); @@ -870,22 +870,22 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedFixed64DataByPBReader, TestSize.Le TypedProtoReader<5> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto fix64Type = typedProtoTest.Get(TestParser_Reader::kFixed64TestDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(fix64Type.data_), fix64Type.size_); auto packedRepeate = typedProtoCpuInfoTest.GetPackedRepeated( Fixed64Test_Reader::kFixed64NumberTextDataAreaNumber, &parserError); auto numberValue = *packedRepeate; - EXPECT_EQ(NUMBER, numberValue); + EXPECT_EQ(number, numberValue); packedRepeate++; auto numberValue1 = *packedRepeate; - EXPECT_EQ(NUMBER1, numberValue1); + EXPECT_EQ(number1, numberValue1); packedRepeate++; auto numberValue2 = *packedRepeate; - EXPECT_EQ(NUMBER2, numberValue2); + EXPECT_EQ(nameber2, numberValue2); packedRepeate++; auto numberValue3 = *packedRepeate; - EXPECT_EQ(NUMBER3, numberValue3); + EXPECT_EQ(number3, numberValue3); } /** @@ -897,18 +897,18 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedFixed32DataByPBReader, TestSize.Le { TS_LOGI("test33-17"); TestParser testParser; - const int32_t COUNT = 100; - const float NUMBER = 1000.01; - const float NUMBER1 = 1001.01; - const float NUMBER2 = 1002.01; - const float NUMBER3 = 1003.01; + const int32_t count = 100; + const float number = 1000.01; + const float number1 = 1001.01; + const float nameber2 = 1002.01; + const float number3 = 1003.01; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::Fixed32Test* fixed32Test = new ::Fixed32Test(); - fixed32Test->add_fixed32numbertext(NUMBER); - fixed32Test->add_fixed32numbertext(NUMBER1); - fixed32Test->add_fixed32numbertext(NUMBER2); - fixed32Test->add_fixed32numbertext(NUMBER3); + fixed32Test->add_fixed32numbertext(number); + fixed32Test->add_fixed32numbertext(number1); + fixed32Test->add_fixed32numbertext(nameber2); + fixed32Test->add_fixed32numbertext(number3); testParser.set_allocated_fixed32test(fixed32Test); testParser.SerializeToString(&str); @@ -916,22 +916,22 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedFixed32DataByPBReader, TestSize.Le TypedProtoReader<5> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto fix32Type = typedProtoTest.Get(TestParser_Reader::kFixed32TestDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(fix32Type.data_), fix32Type.size_); auto packedRepeate = typedProtoCpuInfoTest.GetPackedRepeated( Fixed32Test_Reader::kFixed32NumberTextDataAreaNumber, &parserError); auto numberValue = *packedRepeate; - EXPECT_EQ(NUMBER, numberValue); + EXPECT_EQ(number, numberValue); packedRepeate++; auto numberValue1 = *packedRepeate; - EXPECT_EQ(NUMBER1, numberValue1); + EXPECT_EQ(number1, numberValue1); packedRepeate++; auto numberValue2 = *packedRepeate; - EXPECT_EQ(NUMBER2, numberValue2); + EXPECT_EQ(nameber2, numberValue2); packedRepeate++; auto numberValue3 = *packedRepeate; - EXPECT_EQ(NUMBER3, numberValue3); + EXPECT_EQ(number3, numberValue3); } /** @@ -943,12 +943,12 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedInt32OneDataByPBReader, TestSize.L { TS_LOGI("test33-18"); TestParser testParser; - const int32_t COUNT = 100; - const int32_t NUMBER = 1000; + const int32_t count = 100; + const int32_t number = 1000; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::NumberTest* numberTest = new ::NumberTest(); - numberTest->add_numbertext(NUMBER); + numberTest->add_numbertext(number); testParser.set_allocated_numbertest(numberTest); testParser.SerializeToString(&str); @@ -956,13 +956,13 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedInt32OneDataByPBReader, TestSize.L TypedProtoReader<3> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto numberType = typedProtoTest.Get(TestParser_Reader::kNumberTestDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(numberType.data_), numberType.size_); auto packedRepeate = typedProtoCpuInfoTest.GetPackedRepeated( NumberTest_Reader::kNumberTextDataAreaNumber, &parserError); auto numberValue = *packedRepeate; - EXPECT_EQ(NUMBER, numberValue); + EXPECT_EQ(number, numberValue); } /** @@ -974,25 +974,25 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedFixed64OneDataByPBReader, TestSize { TS_LOGI("test33-19"); TestParser testParser; - const int32_t COUNT = 100; - const double NUMBER = 1000.01; + const int32_t count = 100; + const double number = 1000.01; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::Fixed64Test* fixed64Test = new ::Fixed64Test(); - fixed64Test->add_fixed64numbertext(NUMBER); + fixed64Test->add_fixed64numbertext(number); testParser.set_allocated_fixed64test(fixed64Test); testParser.SerializeToString(&str); bool parserError = true; TypedProtoReader<5> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto fix64Type = typedProtoTest.Get(TestParser_Reader::kFixed64TestDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(fix64Type.data_), fix64Type.size_); auto packedRepeate = typedProtoCpuInfoTest.GetPackedRepeated( Fixed64Test_Reader::kFixed64NumberTextDataAreaNumber, &parserError); auto numberValue = *packedRepeate; - EXPECT_EQ(NUMBER, numberValue); + EXPECT_EQ(number, numberValue); } /** @@ -1004,25 +1004,25 @@ HWTEST_F(ProtoReaderTest, ParserPackedRepeatedFixed32OneDataByPBReader, TestSize { TS_LOGI("test33-20"); TestParser testParser; - const int32_t COUNT = 100; - const float NUMBER = 1000.01; + const int32_t count = 100; + const float number = 1000.01; std::string str = ""; - testParser.set_count(COUNT); + testParser.set_count(count); ::Fixed32Test* fixed32Test = new ::Fixed32Test(); - fixed32Test->add_fixed32numbertext(NUMBER); + fixed32Test->add_fixed32numbertext(number); testParser.set_allocated_fixed32test(fixed32Test); testParser.SerializeToString(&str); bool parserError = true; TypedProtoReader<5> typedProtoTest(reinterpret_cast(str.data()), str.size()); auto count = typedProtoTest.Get(TestParser_Reader::kCountDataAreaNumber).ToInt32(); - EXPECT_EQ(COUNT, count); + EXPECT_EQ(count, count); auto fix32Type = typedProtoTest.Get(TestParser_Reader::kFixed32TestDataAreaNumber).ToBytes(); TypedProtoReader<1> typedProtoCpuInfoTest(reinterpret_cast(fix32Type.data_), fix32Type.size_); auto packedRepeate = typedProtoCpuInfoTest.GetPackedRepeated( Fixed32Test_Reader::kFixed32NumberTextDataAreaNumber, &parserError); auto numberValue = *packedRepeate; - EXPECT_EQ(NUMBER, numberValue); + EXPECT_EQ(number, numberValue); } } // namespace TraceStreamer } // namespace SysTuning diff --git a/trace_streamer/test/unittest/query_file_test.cpp b/trace_streamer/test/unittest/query/query_file_test.cpp similarity index 100% rename from trace_streamer/test/unittest/query_file_test.cpp rename to trace_streamer/test/unittest/query/query_file_test.cpp diff --git a/trace_streamer/test/unittest/query_metrics_test.cpp b/trace_streamer/test/unittest/query/query_metrics_test.cpp similarity index 92% rename from trace_streamer/test/unittest/query_metrics_test.cpp rename to trace_streamer/test/unittest/query/query_metrics_test.cpp index 943e56331c69f316e3de4a1396c4286eb330d15f..3ff886656ce77e666e412d7be8e2d7131fc1cb22 100644 --- a/trace_streamer/test/unittest/query_metrics_test.cpp +++ b/trace_streamer/test/unittest/query/query_metrics_test.cpp @@ -27,9 +27,9 @@ using namespace testing::ext; using namespace SysTuning::TraceStreamer; -const std::string tracePath = "../../test/resource/trace_small_10.systrace"; -constexpr size_t readSize = 1024; -constexpr uint32_t lineLength = 256; +const std::string TRACE_PATH = "../../test/resource/trace_small_10.systrace"; +constexpr size_t READ_SIZE = 1024; +constexpr uint32_t LINE_LENGTH = 256; constexpr size_t G_FILE_PERMISSION = 664; namespace SysTuning { @@ -42,15 +42,15 @@ protected: void ParseTraceFile(TraceStreamerSelector& ts) { - int32_t fd(base::OpenFile(tracePath, O_RDONLY, G_FILE_PERMISSION)); + int32_t fd(base::OpenFile(TRACE_PATH, O_RDONLY, G_FILE_PERMISSION)); if (fd < 0) { TS_LOGD("Failed to open trace file (errno: %d, %s)", errno, strerror(errno)); return; } while (true) { - std::unique_ptr buf = std::make_unique(readSize); - auto rsize = base::Read(fd, buf.get(), readSize); + std::unique_ptr buf = std::make_unique(READ_SIZE); + auto rsize = base::Read(fd, buf.get(), READ_SIZE); if (rsize <= 0) { break; diff --git a/trace_streamer/test/unittest/span_join_test.cpp b/trace_streamer/test/unittest/query/span_join_test.cpp similarity index 100% rename from trace_streamer/test/unittest/span_join_test.cpp rename to trace_streamer/test/unittest/query/span_join_test.cpp diff --git a/trace_streamer/test/unittest/sqllite_prepar_cache_data_test.cpp b/trace_streamer/test/unittest/query/sqllite_prepar_cache_data_test.cpp similarity index 100% rename from trace_streamer/test/unittest/sqllite_prepar_cache_data_test.cpp rename to trace_streamer/test/unittest/query/sqllite_prepar_cache_data_test.cpp diff --git a/trace_streamer/test/unittest/ftrace_field_processor_test.cpp b/trace_streamer/test/unittest/rawtrace/ftrace_field_processor_test.cpp similarity index 100% rename from trace_streamer/test/unittest/ftrace_field_processor_test.cpp rename to trace_streamer/test/unittest/rawtrace/ftrace_field_processor_test.cpp diff --git a/trace_streamer/test/unittest/rawtrace_cpu_detail_parse_test.cpp b/trace_streamer/test/unittest/rawtrace/rawtrace_cpu_detail_parse_test.cpp similarity index 100% rename from trace_streamer/test/unittest/rawtrace_cpu_detail_parse_test.cpp rename to trace_streamer/test/unittest/rawtrace/rawtrace_cpu_detail_parse_test.cpp diff --git a/trace_streamer/test/unittest/rawtrace_parser_test.cpp b/trace_streamer/test/unittest/rawtrace/rawtrace_parser_test.cpp similarity index 97% rename from trace_streamer/test/unittest/rawtrace_parser_test.cpp rename to trace_streamer/test/unittest/rawtrace/rawtrace_parser_test.cpp index c020a1e4d271a10c2ff211bbdd717441b86a5d0f..fd7f9f8979863f11405945f67a7d42fc6f5809c7 100644 --- a/trace_streamer/test/unittest/rawtrace_parser_test.cpp +++ b/trace_streamer/test/unittest/rawtrace/rawtrace_parser_test.cpp @@ -135,9 +135,9 @@ HWTEST_F(RawTraceParserTest, HandleHeadPage, TestSize.Level1) break; } } - std::string noCommitField = R"(field: u64 timestamp; offset:0; size:8; signed:0; - field: int overwrite; offset:8; size:1; signed:1; - field: char data; offset:16; size:4080; signed:0;)"; + std::string noCommitField = R"(field: u64 timestamp; offset:0; size:8; signed:0; + field: int overwrite; offset:8; size:1; signed:1; + field: char data; offset:16; size:4080; signed:0;)"; EXPECT_FALSE(parser_->ftraceProcessor_->HandleHeaderPageFormat(noCommitField)); } /** diff --git a/trace_streamer/test/unittest/bytrace_parser_test.cpp b/trace_streamer/test/unittest/systrace/bytrace_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/bytrace_parser_test.cpp rename to trace_streamer/test/unittest/systrace/bytrace_parser_test.cpp diff --git a/trace_streamer/test/unittest/event_parser_test.cpp b/trace_streamer/test/unittest/systrace/event_parser_test.cpp similarity index 100% rename from trace_streamer/test/unittest/event_parser_test.cpp rename to trace_streamer/test/unittest/systrace/event_parser_test.cpp diff --git a/trace_streamer/test/unittest/table_test.cpp b/trace_streamer/test/unittest/table/table_test.cpp similarity index 99% rename from trace_streamer/test/unittest/table_test.cpp rename to trace_streamer/test/unittest/table/table_test.cpp index 9c708c3bdb5ec170b9e69b941a8edf6830db2973..fc38c45b965d59924bf427621f95007d948cd0c5 100644 --- a/trace_streamer/test/unittest/table_test.cpp +++ b/trace_streamer/test/unittest/table/table_test.cpp @@ -334,8 +334,8 @@ HWTEST_F(TableTest, DataTypeTableTest, TestSize.Level1) BaseDataType dataType1 = BASE_DATA_TYPE_STRING; DataIndex dataDescIndex1 = stream_.traceDataCache_->GetDataIndex("dataDescIndex1"); - stream_.traceDataCache_->GetDataTypeData()->AppendNewDataType(dataType, dataDescIndex); - stream_.traceDataCache_->GetDataTypeData()->AppendNewDataType(dataType1, dataDescIndex1); + stream_.traceDataCache_->GetDataTypeData()->UpdateNewDataType(dataType, dataDescIndex); + stream_.traceDataCache_->GetDataTypeData()->UpdateNewDataType(dataType1, dataDescIndex1); auto row = stream_.traceDataCache_->SearchDatabase(sqlSelect, false); EXPECT_EQ(row, 6); row = stream_.traceDataCache_->SearchDatabase(sqlSelect1, false);