Skip to content

Commit

Permalink
chore: optimize metrics statistics
Browse files Browse the repository at this point in the history
  • Loading branch information
hyj1991 committed Sep 4, 2020
1 parent 1abbc2c commit 7cfb537
Showing 1 changed file with 48 additions and 5 deletions.
53 changes: 48 additions & 5 deletions app/service/metric.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,30 @@ class MetricService extends Service {
return list;
}

getAverageMetric(metrics, key) {
const { ctx: { app } } = this;

let value = 0;
for (const metric of metrics) {
if (!metric) {
continue;
}

const metricValue = metric[key];

// disks
if (typeof metricValue === 'object') {
return metricValue;
}

// common metric value
if (app.isNumber(metricValue)) {
value += metric[key] || 0;
}
}
return value / metrics.length;
}

handleTrends(trends, keys, duration) {
if (!trends.length || !keys.length) {
return [];
Expand All @@ -45,6 +69,7 @@ class MetricService extends Service {
const time = moment(trend.log_time).format(formatter);
trendMap[time] = trend;
}

const validInterval = 60 * 1000;
for (let time = start; time < end; time += 60 * 1000) {
const timeKey = moment(time).format(formatter);
Expand All @@ -58,22 +83,40 @@ class MetricService extends Service {
}
}

for (let time = start; time < end; time += interval) {
const timeKey = moment(time).format(formatter);
if (!trendMap[timeKey]) {
continue;
}
const duration = [];
for (let index = 0; index < interval / validInterval; index++) {
const timeKeyTmp = moment(time + index * validInterval).format(formatter);
const trendTmp = trendMap[timeKeyTmp];
if (!trendTmp) {
duration.push(null);
} else {
duration.push(trendTmp);
}
}
trendMap[timeKey] = duration;
}

const results = [];
for (let time = start; time < end; time += interval) {
const data = { time };
const timeKey = moment(time).format(formatter);
const trend = trendMap[timeKey];
if (trend) {
const metrics = trendMap[timeKey];
if (metrics && metrics.some(metric => metric)) {
keys.forEach(keyObj => {
if (typeof keyObj === 'string') {
data[keyObj] = trend[keyObj];
data[keyObj] = this.getAverageMetric(metrics, keyObj);
} else {
const { key, label, handle } = keyObj;
const showLabel = label || key;
if (typeof handle === 'function') {
data[showLabel] = handle(trend[key]);
data[showLabel] = handle(this.getAverageMetric(metrics, key));
} else {
data[showLabel] = trend[key];
data[showLabel] = this.getAverageMetric(metrics, key);
}
}
});
Expand Down

0 comments on commit 7cfb537

Please sign in to comment.