Refactor: format some files

This commit is contained in:
Alexander Zobnin
2022-11-30 15:08:12 +01:00
parent 14987efae4
commit 26ed740945
11 changed files with 343 additions and 280 deletions

View File

@@ -39,7 +39,7 @@ export const TRIGGER_SEVERITY = [
{ val: 2, text: 'Warning' }, { val: 2, text: 'Warning' },
{ val: 3, text: 'Average' }, { val: 3, text: 'Average' },
{ val: 4, text: 'High' }, { val: 4, text: 'High' },
{val: 5, text: 'Disaster'} { val: 5, text: 'Disaster' },
]; ];
/** Minimum interval for SLA over time (1 hour) */ /** Minimum interval for SLA over time (1 hour) */

View File

@@ -5,7 +5,7 @@ import { DataFrame, FieldType, TIME_SERIES_VALUE_FIELD_NAME } from '@grafana/dat
function setAlias(alias: string, frame: DataFrame) { function setAlias(alias: string, frame: DataFrame) {
if (frame.fields?.length <= 2) { if (frame.fields?.length <= 2) {
const valueField = frame.fields.find(f => f.name === TIME_SERIES_VALUE_FIELD_NAME); const valueField = frame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);
if (valueField?.config?.custom?.scopedVars) { if (valueField?.config?.custom?.scopedVars) {
alias = getTemplateSrv().replace(alias, valueField?.config?.custom?.scopedVars); alias = getTemplateSrv().replace(alias, valueField?.config?.custom?.scopedVars);
} }
@@ -38,7 +38,7 @@ function replaceAlias(regexp: string, newAlias: string, frame: DataFrame) {
if (frame.fields?.length <= 2) { if (frame.fields?.length <= 2) {
let alias = frame.name.replace(pattern, newAlias); let alias = frame.name.replace(pattern, newAlias);
const valueField = frame.fields.find(f => f.name === TIME_SERIES_VALUE_FIELD_NAME); const valueField = frame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);
if (valueField?.state?.scopedVars) { if (valueField?.state?.scopedVars) {
alias = getTemplateSrv().replace(alias, valueField?.state?.scopedVars); alias = getTemplateSrv().replace(alias, valueField?.state?.scopedVars);
} }
@@ -63,7 +63,7 @@ function replaceAlias(regexp: string, newAlias: string, frame: DataFrame) {
function setAliasByRegex(alias: string, frame: DataFrame) { function setAliasByRegex(alias: string, frame: DataFrame) {
if (frame.fields?.length <= 2) { if (frame.fields?.length <= 2) {
const valueField = frame.fields.find(f => f.name === TIME_SERIES_VALUE_FIELD_NAME); const valueField = frame.fields.find((f) => f.name === TIME_SERIES_VALUE_FIELD_NAME);
try { try {
if (valueField) { if (valueField) {
valueField.config.displayNameFromDS = extractText(valueField.config?.displayNameFromDS, alias); valueField.config.displayNameFromDS = extractText(valueField.config?.displayNameFromDS, alias);
@@ -96,7 +96,7 @@ function extractText(str: string, pattern: string) {
function timeShift(interval, range) { function timeShift(interval, range) {
const shift = utils.parseTimeShiftInterval(interval) / 1000; const shift = utils.parseTimeShiftInterval(interval) / 1000;
return _.map(range, time => { return _.map(range, (time) => {
return time - shift; return time - shift;
}); });
} }
@@ -105,11 +105,11 @@ const metricFunctions = {
timeShift: timeShift, timeShift: timeShift,
setAlias: setAlias, setAlias: setAlias,
setAliasByRegex: setAliasByRegex, setAliasByRegex: setAliasByRegex,
replaceAlias: replaceAlias replaceAlias: replaceAlias,
}; };
export default { export default {
get metricFunctions() { get metricFunctions() {
return metricFunctions; return metricFunctions;
} },
}; };

View File

@@ -41,7 +41,6 @@ export function joinTriggersWithProblems(problems: ZBXProblem[], triggers: ZBXTr
problemDTOList.push(problemDTO); problemDTOList.push(problemDTO);
} }
} }
return problemDTOList; return problemDTOList;
@@ -51,7 +50,11 @@ interface JoinOptions {
valueFromEvent?: boolean; valueFromEvent?: boolean;
} }
export function joinTriggersWithEvents(events: ZBXEvent[], triggers: ZBXTrigger[], options?: JoinOptions): ProblemDTO[] { export function joinTriggersWithEvents(
events: ZBXEvent[],
triggers: ZBXTrigger[],
options?: JoinOptions
): ProblemDTO[] {
const { valueFromEvent } = options; const { valueFromEvent } = options;
const problemDTOList: ProblemDTO[] = []; const problemDTOList: ProblemDTO[] = [];
@@ -89,7 +92,6 @@ export function joinTriggersWithEvents(events: ZBXEvent[], triggers: ZBXTrigger[
problemDTOList.push(problemDTO); problemDTOList.push(problemDTO);
} }
} }
return problemDTOList; return problemDTOList;
@@ -118,7 +120,7 @@ export function addTriggerDataSource(triggers, target) {
} }
export function addTriggerHostProxy(triggers, proxies) { export function addTriggerHostProxy(triggers, proxies) {
triggers.forEach(trigger => { triggers.forEach((trigger) => {
if (trigger.hosts && trigger.hosts.length) { if (trigger.hosts && trigger.hosts.length) {
const host = trigger.hosts[0]; const host = trigger.hosts[0];
if (host.proxy_hostid !== '0') { if (host.proxy_hostid !== '0') {
@@ -147,11 +149,11 @@ export function filterTriggersPre(triggerList, replacedTarget) {
function filterTriggers(triggers, triggerFilter) { function filterTriggers(triggers, triggerFilter) {
if (utils.isRegex(triggerFilter)) { if (utils.isRegex(triggerFilter)) {
return _.filter(triggers, trigger => { return _.filter(triggers, (trigger) => {
return utils.buildRegex(triggerFilter).test(trigger.description); return utils.buildRegex(triggerFilter).test(trigger.description);
}); });
} else { } else {
return _.filter(triggers, trigger => { return _.filter(triggers, (trigger) => {
return trigger.description === triggerFilter; return trigger.description === triggerFilter;
}); });
} }

View File

@@ -26,7 +26,7 @@ function downsample(datapoints, time_to, ms_interval, func) {
const downsampledSeries = []; const downsampledSeries = [];
const timeWindow = { const timeWindow = {
from: time_to * 1000 - ms_interval, from: time_to * 1000 - ms_interval,
to: time_to * 1000 to: time_to * 1000,
}; };
let points_sum = 0; let points_sum = 0;
@@ -42,9 +42,9 @@ function downsample(datapoints, time_to, ms_interval, func) {
} else { } else {
value_avg = points_num ? points_sum / points_num : 0; value_avg = points_num ? points_sum / points_num : 0;
if (func === "max") { if (func === 'max') {
downsampledSeries.push([_.max(frame), timeWindow.to]); downsampledSeries.push([_.max(frame), timeWindow.to]);
} else if (func === "min") { } else if (func === 'min') {
downsampledSeries.push([_.min(frame), timeWindow.to]); downsampledSeries.push([_.min(frame), timeWindow.to]);
} else { } else {
downsampledSeries.push([value_avg, timeWindow.to]); downsampledSeries.push([value_avg, timeWindow.to]);
@@ -156,24 +156,26 @@ function groupBy(datapoints, interval, groupByCallback) {
const ms_interval = utils.parseInterval(interval); const ms_interval = utils.parseInterval(interval);
// Calculate frame timestamps // Calculate frame timestamps
const frames = _.groupBy(datapoints, point => { const frames = _.groupBy(datapoints, (point) => {
// Calculate time for group of points // Calculate time for group of points
return Math.floor(point[1] / ms_interval) * ms_interval; return Math.floor(point[1] / ms_interval) * ms_interval;
}); });
// frame: { '<unixtime>': [[<value>, <unixtime>], ...] } // frame: { '<unixtime>': [[<value>, <unixtime>], ...] }
// return [{ '<unixtime>': <value> }, { '<unixtime>': <value> }, ...] // return [{ '<unixtime>': <value> }, { '<unixtime>': <value> }, ...]
const grouped = _.mapValues(frames, frame => { const grouped = _.mapValues(frames, (frame) => {
const points = _.map(frame, point => { const points = _.map(frame, (point) => {
return point[0]; return point[0];
}); });
return groupByCallback(points); return groupByCallback(points);
}); });
// Convert points to Grafana format // Convert points to Grafana format
return sortByTime(_.map(grouped, (value, timestamp) => { return sortByTime(
_.map(grouped, (value, timestamp) => {
return [Number(value), Number(timestamp)]; return [Number(value), Number(timestamp)];
})); })
);
} }
export function groupBy_perf(datapoints, interval, groupByCallback) { export function groupBy_perf(datapoints, interval, groupByCallback) {
@@ -228,7 +230,10 @@ export function groupByRange(datapoints, groupByCallback) {
frame_values.push(point[POINT_VALUE]); frame_values.push(point[POINT_VALUE]);
} }
const frame_value = groupByCallback(frame_values); const frame_value = groupByCallback(frame_values);
return [[frame_value, frame_start], [frame_value, frame_end]]; return [
[frame_value, frame_start],
[frame_value, frame_end],
];
} }
/** /**
@@ -236,19 +241,20 @@ export function groupByRange(datapoints, groupByCallback) {
* @param {datapoints[]} timeseries array of time series * @param {datapoints[]} timeseries array of time series
*/ */
function sumSeries(timeseries) { function sumSeries(timeseries) {
// Calculate new points for interpolation // Calculate new points for interpolation
let new_timestamps = _.uniq(_.map(_.flatten(timeseries), point => { let new_timestamps = _.uniq(
_.map(_.flatten(timeseries), (point) => {
return point[1]; return point[1];
})); })
);
new_timestamps = _.sortBy(new_timestamps); new_timestamps = _.sortBy(new_timestamps);
const interpolated_timeseries = _.map(timeseries, series => { const interpolated_timeseries = _.map(timeseries, (series) => {
series = fillZeroes(series, new_timestamps); series = fillZeroes(series, new_timestamps);
const timestamps = _.map(series, point => { const timestamps = _.map(series, (point) => {
return point[1]; return point[1];
}); });
const new_points = _.map(_.difference(new_timestamps, timestamps), timestamp => { const new_points = _.map(_.difference(new_timestamps, timestamps), (timestamp) => {
return [null, timestamp]; return [null, timestamp];
}); });
const new_series = series.concat(new_points); const new_series = series.concat(new_points);
@@ -271,20 +277,14 @@ function sumSeries(timeseries) {
} }
function scale(datapoints, factor) { function scale(datapoints, factor) {
return _.map(datapoints, point => { return _.map(datapoints, (point) => {
return [ return [point[0] * factor, point[1]];
point[0] * factor,
point[1]
];
}); });
} }
function scale_perf(datapoints, factor) { function scale_perf(datapoints, factor) {
for (let i = 0; i < datapoints.length; i++) { for (let i = 0; i < datapoints.length; i++) {
datapoints[i] = [ datapoints[i] = [datapoints[i][POINT_VALUE] * factor, datapoints[i][POINT_TIMESTAMP]];
datapoints[i][POINT_VALUE] * factor,
datapoints[i][POINT_TIMESTAMP]
];
} }
return datapoints; return datapoints;
@@ -292,10 +292,7 @@ function scale_perf(datapoints, factor) {
function offset(datapoints, delta) { function offset(datapoints, delta) {
for (let i = 0; i < datapoints.length; i++) { for (let i = 0; i < datapoints.length; i++) {
datapoints[i] = [ datapoints[i] = [datapoints[i][POINT_VALUE] + delta, datapoints[i][POINT_TIMESTAMP]];
datapoints[i][POINT_VALUE] + delta,
datapoints[i][POINT_TIMESTAMP]
];
} }
return datapoints; return datapoints;
@@ -440,7 +437,7 @@ function expMovingAverage(datapoints: TimeSeriesPoints, n: number): TimeSeriesPo
function PERCENTILE(n, values) { function PERCENTILE(n, values) {
const sorted = _.sortBy(values); const sorted = _.sortBy(values);
return sorted[Math.floor(sorted.length * n / 100)]; return sorted[Math.floor((sorted.length * n) / 100)];
} }
function COUNT(values) { function COUNT(values) {
@@ -505,7 +502,7 @@ function getPointTimeFrame(timestamp, ms_interval) {
} }
function sortByTime(series) { function sortByTime(series) {
return _.sortBy(series, point => { return _.sortBy(series, (point) => {
return point[1]; return point[1];
}); });
} }
@@ -561,7 +558,7 @@ function linearInterpolation(timestamp, left, right) {
if (left[1] === right[1]) { if (left[1] === right[1]) {
return (left[0] + right[0]) / 2; return (left[0] + right[0]) / 2;
} else { } else {
return (left[0] + (right[0] - left[0]) / (right[1] - left[1]) * (timestamp - left[1])); return left[0] + ((right[0] - left[0]) / (right[1] - left[1])) * (timestamp - left[1]);
} }
} }

View File

@@ -8,27 +8,27 @@ export const HISTORY_TO_TABLE_MAP = {
'1': 'history_str', '1': 'history_str',
'2': 'history_log', '2': 'history_log',
'3': 'history_uint', '3': 'history_uint',
'4': 'history_text' '4': 'history_text',
}; };
export const TREND_TO_TABLE_MAP = { export const TREND_TO_TABLE_MAP = {
'0': 'trends', '0': 'trends',
'3': 'trends_uint' '3': 'trends_uint',
}; };
export const consolidateByFunc = { export const consolidateByFunc = {
'avg': 'AVG', avg: 'AVG',
'min': 'MIN', min: 'MIN',
'max': 'MAX', max: 'MAX',
'sum': 'SUM', sum: 'SUM',
'count': 'COUNT' count: 'COUNT',
}; };
export const consolidateByTrendColumns = { export const consolidateByTrendColumns = {
'avg': 'value_avg', avg: 'value_avg',
'min': 'value_min', min: 'value_min',
'max': 'value_max', max: 'value_max',
'sum': 'num*value_avg' // sum of sums inside the one-hour trend period sum: 'num*value_avg', // sum of sums inside the one-hour trend period
}; };
export interface IDBConnector { export interface IDBConnector {
@@ -58,7 +58,7 @@ export class DBConnector {
static loadDatasource(dsId, dsName) { static loadDatasource(dsId, dsName) {
if (!dsName && dsId !== undefined) { if (!dsName && dsId !== undefined) {
const ds = _.find(getDataSourceSrv().getList(), { 'id': dsId }); const ds = _.find(getDataSourceSrv().getList(), { id: dsId });
if (!ds) { if (!ds) {
return Promise.reject(`Data Source with ID ${dsId} not found`); return Promise.reject(`Data Source with ID ${dsId} not found`);
} }
@@ -72,8 +72,7 @@ export class DBConnector {
} }
loadDBDataSource() { loadDBDataSource() {
return DBConnector.loadDatasource(this.datasourceId, this.datasourceName) return DBConnector.loadDatasource(this.datasourceId, this.datasourceName).then((ds) => {
.then(ds => {
this.datasourceTypeId = ds.meta.id; this.datasourceTypeId = ds.meta.id;
this.datasourceTypeName = ds.meta.name; this.datasourceTypeName = ds.meta.name;
if (!this.datasourceName) { if (!this.datasourceName) {
@@ -93,5 +92,5 @@ export default {
HISTORY_TO_TABLE_MAP, HISTORY_TO_TABLE_MAP,
TREND_TO_TABLE_MAP, TREND_TO_TABLE_MAP,
consolidateByFunc, consolidateByFunc,
consolidateByTrendColumns consolidateByTrendColumns,
}; };

View File

@@ -1,14 +1,24 @@
import { ArrayVector, DataFrame, dataFrameToJSON, DataSourceApi, Field, FieldType, MutableDataFrame, TIME_SERIES_TIME_FIELD_NAME, toDataFrame } from '@grafana/data'; import {
ArrayVector,
DataFrame,
dataFrameToJSON,
DataSourceApi,
Field,
FieldType,
MutableDataFrame,
TIME_SERIES_TIME_FIELD_NAME,
toDataFrame,
} from '@grafana/data';
import _ from 'lodash'; import _ from 'lodash';
import { compactQuery } from '../../../utils'; import { compactQuery } from '../../../utils';
import { consolidateByTrendColumns, DBConnector, HISTORY_TO_TABLE_MAP } from '../dbConnector'; import { consolidateByTrendColumns, DBConnector, HISTORY_TO_TABLE_MAP } from '../dbConnector';
const consolidateByFunc = { const consolidateByFunc = {
'avg': 'MEAN', avg: 'MEAN',
'min': 'MIN', min: 'MIN',
'max': 'MAX', max: 'MAX',
'sum': 'SUM', sum: 'SUM',
'count': 'COUNT' count: 'COUNT',
}; };
export class InfluxDBConnector extends DBConnector { export class InfluxDBConnector extends DBConnector {
@@ -18,7 +28,7 @@ export class InfluxDBConnector extends DBConnector {
constructor(options) { constructor(options) {
super(options); super(options);
this.retentionPolicy = options.retentionPolicy; this.retentionPolicy = options.retentionPolicy;
super.loadDBDataSource().then(ds => { super.loadDBDataSource().then((ds) => {
this.influxDS = ds; this.influxDS = ds;
return ds; return ds;
}); });
@@ -28,12 +38,12 @@ export class InfluxDBConnector extends DBConnector {
* Try to invoke test query for one of Zabbix database tables. * Try to invoke test query for one of Zabbix database tables.
*/ */
testDataSource() { testDataSource() {
return this.influxDS.testDatasource().then(result => { return this.influxDS.testDatasource().then((result) => {
if (result.status && result.status === 'error') { if (result.status && result.status === 'error') {
return Promise.reject({ return Promise.reject({
data: { data: {
message: `InfluxDB connection error: ${result.message}` message: `InfluxDB connection error: ${result.message}`,
} },
}); });
} }
return result; return result;
@@ -59,7 +69,7 @@ export class InfluxDBConnector extends DBConnector {
return Promise.all(promises) return Promise.all(promises)
.then(_.flatten) .then(_.flatten)
.then(results => { .then((results) => {
return handleInfluxHistoryResponse(results); return handleInfluxHistoryResponse(results);
}); });
} }
@@ -88,7 +98,7 @@ export class InfluxDBConnector extends DBConnector {
} }
buildWhereClause(itemids) { buildWhereClause(itemids) {
const itemidsWhere = itemids.map(itemid => `"itemid" = '${itemid}'`).join(' OR '); const itemidsWhere = itemids.map((itemid) => `"itemid" = '${itemid}'`).join(' OR ');
return `(${itemidsWhere})`; return `(${itemidsWhere})`;
} }
@@ -127,7 +137,7 @@ function handleInfluxHistoryResponse(results) {
if (influxSeries.values) { if (influxSeries.values) {
for (i = 0; i < influxSeries.values.length; i++) { for (i = 0; i < influxSeries.values.length; i++) {
tsBuffer.push(influxSeries.values[i][0]); tsBuffer.push(influxSeries.values[i][0]);
valuesBuffer.push(influxSeries.values[i][1]) valuesBuffer.push(influxSeries.values[i][1]);
} }
} }
const timeFiled: Field<number> = { const timeFiled: Field<number> = {
@@ -144,12 +154,14 @@ function handleInfluxHistoryResponse(results) {
values: new ArrayVector(valuesBuffer), values: new ArrayVector(valuesBuffer),
}; };
frames.push(new MutableDataFrame({ frames.push(
new MutableDataFrame({
name: influxSeries?.tags?.itemid, name: influxSeries?.tags?.itemid,
fields: [timeFiled, valueFiled] fields: [timeFiled, valueFiled],
})); })
);
} }
} }
return frames.map(f => dataFrameToJSON(f)); return frames.map((f) => dataFrameToJSON(f));
} }

View File

@@ -40,7 +40,7 @@ function testQuery() {
const mysql = { const mysql = {
historyQuery, historyQuery,
trendsQuery, trendsQuery,
testQuery testQuery,
}; };
export default mysql; export default mysql;

View File

@@ -46,7 +46,7 @@ function testQuery() {
const postgres = { const postgres = {
historyQuery, historyQuery,
trendsQuery, trendsQuery,
testQuery testQuery,
}; };
export default postgres; export default postgres;

View File

@@ -3,11 +3,16 @@ import { getBackendSrv } from '@grafana/runtime';
import { compactQuery } from '../../../utils'; import { compactQuery } from '../../../utils';
import mysql from './mysql'; import mysql from './mysql';
import postgres from './postgres'; import postgres from './postgres';
import dbConnector, { DBConnector, DEFAULT_QUERY_LIMIT, HISTORY_TO_TABLE_MAP, TREND_TO_TABLE_MAP } from '../dbConnector'; import dbConnector, {
DBConnector,
DEFAULT_QUERY_LIMIT,
HISTORY_TO_TABLE_MAP,
TREND_TO_TABLE_MAP,
} from '../dbConnector';
const supportedDatabases = { const supportedDatabases = {
mysql: 'mysql', mysql: 'mysql',
postgres: 'postgres' postgres: 'postgres',
}; };
export class SQLConnector extends DBConnector { export class SQLConnector extends DBConnector {
@@ -20,8 +25,7 @@ export class SQLConnector extends DBConnector {
this.limit = options.limit || DEFAULT_QUERY_LIMIT; this.limit = options.limit || DEFAULT_QUERY_LIMIT;
this.sqlDialect = null; this.sqlDialect = null;
super.loadDBDataSource() super.loadDBDataSource().then(() => {
.then(() => {
this.loadSQLDialect(); this.loadSQLDialect();
}); });
} }
@@ -56,7 +60,7 @@ export class SQLConnector extends DBConnector {
return this.invokeSQLQuery(query); return this.invokeSQLQuery(query);
}); });
return Promise.all(promises).then(results => { return Promise.all(promises).then((results) => {
return _.flatten(results); return _.flatten(results);
}); });
} }
@@ -72,13 +76,21 @@ export class SQLConnector extends DBConnector {
const table = TREND_TO_TABLE_MAP[value_type]; const table = TREND_TO_TABLE_MAP[value_type];
let valueColumn = _.includes(['avg', 'min', 'max', 'sum'], consolidateBy) ? consolidateBy : 'avg'; let valueColumn = _.includes(['avg', 'min', 'max', 'sum'], consolidateBy) ? consolidateBy : 'avg';
valueColumn = dbConnector.consolidateByTrendColumns[valueColumn]; valueColumn = dbConnector.consolidateByTrendColumns[valueColumn];
let query = this.sqlDialect.trendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn); let query = this.sqlDialect.trendsQuery(
itemids,
table,
timeFrom,
timeTill,
intervalSec,
aggFunction,
valueColumn
);
query = compactQuery(query); query = compactQuery(query);
return this.invokeSQLQuery(query); return this.invokeSQLQuery(query);
}); });
return Promise.all(promises).then(results => { return Promise.all(promises).then((results) => {
return _.flatten(results); return _.flatten(results);
}); });
} }
@@ -89,17 +101,18 @@ export class SQLConnector extends DBConnector {
format: 'time_series', format: 'time_series',
datasourceId: this.datasourceId, datasourceId: this.datasourceId,
rawSql: query, rawSql: query,
maxDataPoints: this.limit maxDataPoints: this.limit,
}; };
return getBackendSrv().datasourceRequest({ return getBackendSrv()
.datasourceRequest({
url: '/api/ds/query', url: '/api/ds/query',
method: 'POST', method: 'POST',
data: { data: {
queries: [queryDef], queries: [queryDef],
} },
}) })
.then(response => { .then((response) => {
const results = response.data.results; const results = response.data.results;
if (results['A']) { if (results['A']) {
return results['A'].frames; return results['A'].frames;

View File

@@ -61,11 +61,13 @@ function callOnce(func, promiseKeeper, funcScope) {
const hash = getRequestHash(arguments); const hash = getRequestHash(arguments);
if (!promiseKeeper[hash]) { if (!promiseKeeper[hash]) {
promiseKeeper[hash] = Promise.resolve( promiseKeeper[hash] = Promise.resolve(
func.apply(funcScope, arguments) func
.then(result => { .apply(funcScope, arguments)
.then((result) => {
promiseKeeper[hash] = null; promiseKeeper[hash] = null;
return result; return result;
}).catch(err => { })
.catch((err) => {
promiseKeeper[hash] = null; promiseKeeper[hash] = null;
throw err; throw err;
}) })
@@ -87,12 +89,11 @@ function cacheRequest(func, funcName, funcScope, self) {
if (self.cacheEnabled && !self._isExpired(cacheObject[hash])) { if (self.cacheEnabled && !self._isExpired(cacheObject[hash])) {
return Promise.resolve(cacheObject[hash].value); return Promise.resolve(cacheObject[hash].value);
} else { } else {
return func.apply(funcScope, arguments) return func.apply(funcScope, arguments).then((result) => {
.then(result => {
if (result !== undefined) { if (result !== undefined) {
cacheObject[hash] = { cacheObject[hash] = {
value: result, value: result,
timestamp: Date.now() timestamp: Date.now(),
}; };
} }
return result; return result;
@@ -107,11 +108,14 @@ function getRequestHash(args) {
} }
function getHash(str: string): number { function getHash(str: string): number {
let hash = 0, i, chr, len; let hash = 0,
i,
chr,
len;
if (str.length !== 0) { if (str.length !== 0) {
for (i = 0, len = str.length; i < len; i++) { for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i); chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr; hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer hash |= 0; // Convert to 32bit integer
} }
} }

View File

@@ -18,19 +18,59 @@ interface AppsResponse extends Array<any> {
} }
const REQUESTS_TO_PROXYFY = [ const REQUESTS_TO_PROXYFY = [
'getHistory', 'getTrend', 'getGroups', 'getHosts', 'getApps', 'getItems', 'getMacros', 'getItemsByIDs', 'getHistory',
'getEvents', 'getAlerts', 'getHostAlerts', 'getAcknowledges', 'getITService', 'getSLA', 'getProxies', 'getTrend',
'getEventAlerts', 'getExtendedEventData', 'getProblems', 'getEventsHistory', 'getTriggersByIds', 'getScripts', 'getValueMappings' 'getGroups',
'getHosts',
'getApps',
'getItems',
'getMacros',
'getItemsByIDs',
'getEvents',
'getAlerts',
'getHostAlerts',
'getAcknowledges',
'getITService',
'getSLA',
'getProxies',
'getEventAlerts',
'getExtendedEventData',
'getProblems',
'getEventsHistory',
'getTriggersByIds',
'getScripts',
'getValueMappings',
]; ];
const REQUESTS_TO_CACHE = [ const REQUESTS_TO_CACHE = [
'getGroups', 'getHosts', 'getApps', 'getItems', 'getMacros', 'getItemsByIDs', 'getITService', 'getProxies', 'getValueMappings' 'getGroups',
'getHosts',
'getApps',
'getItems',
'getMacros',
'getItemsByIDs',
'getITService',
'getProxies',
'getValueMappings',
]; ];
const REQUESTS_TO_BIND = [ const REQUESTS_TO_BIND = [
'getHistory', 'getTrend', 'getMacros', 'getItemsByIDs', 'getEvents', 'getAlerts', 'getHostAlerts', 'getHistory',
'getAcknowledges', 'getITService', 'acknowledgeEvent', 'getProxies', 'getEventAlerts', 'getTrend',
'getExtendedEventData', 'getScripts', 'executeScript', 'getValueMappings' 'getMacros',
'getItemsByIDs',
'getEvents',
'getAlerts',
'getHostAlerts',
'getAcknowledges',
'getITService',
'acknowledgeEvent',
'getProxies',
'getEventAlerts',
'getExtendedEventData',
'getScripts',
'executeScript',
'getValueMappings',
]; ];
export class Zabbix implements ZabbixConnector { export class Zabbix implements ZabbixConnector {
@@ -74,7 +114,7 @@ export class Zabbix implements ZabbixConnector {
// Initialize caching proxy for requests // Initialize caching proxy for requests
const cacheOptions = { const cacheOptions = {
enabled: true, enabled: true,
ttl: cacheTTL ttl: cacheTTL,
}; };
this.cachingProxy = new CachingProxy(cacheOptions); this.cachingProxy = new CachingProxy(cacheOptions);
@@ -86,17 +126,23 @@ export class Zabbix implements ZabbixConnector {
if (enableDirectDBConnection) { if (enableDirectDBConnection) {
const connectorOptions: any = { dbConnectionRetentionPolicy }; const connectorOptions: any = { dbConnectionRetentionPolicy };
this.initDBConnector(dbConnectionDatasourceId, dbConnectionDatasourceName, connectorOptions) this.initDBConnector(dbConnectionDatasourceId, dbConnectionDatasourceName, connectorOptions).then(() => {
.then(() => { this.getHistoryDB = this.cachingProxy.proxifyWithCache(
this.getHistoryDB = this.cachingProxy.proxifyWithCache(this.dbConnector.getHistory, 'getHistory', this.dbConnector); this.dbConnector.getHistory,
this.getTrendsDB = this.cachingProxy.proxifyWithCache(this.dbConnector.getTrends, 'getTrends', this.dbConnector); 'getHistory',
this.dbConnector
);
this.getTrendsDB = this.cachingProxy.proxifyWithCache(
this.dbConnector.getTrends,
'getTrends',
this.dbConnector
);
}); });
} }
} }
initDBConnector(datasourceId, datasourceName, options) { initDBConnector(datasourceId, datasourceName, options) {
return DBConnector.loadDatasource(datasourceId, datasourceName) return DBConnector.loadDatasource(datasourceId, datasourceName).then((ds) => {
.then(ds => {
const connectorOptions: any = { datasourceId, datasourceName }; const connectorOptions: any = { datasourceId, datasourceName };
if (ds.type === 'influxdb') { if (ds.type === 'influxdb') {
connectorOptions.retentionPolicy = options.dbConnectionRetentionPolicy; connectorOptions.retentionPolicy = options.dbConnectionRetentionPolicy;
@@ -143,7 +189,7 @@ export class Zabbix implements ZabbixConnector {
let zabbixVersion; let zabbixVersion;
let dbConnectorStatus; let dbConnectorStatus;
return this.getVersion() return this.getVersion()
.then(version => { .then((version) => {
zabbixVersion = version; zabbixVersion = version;
return this.getAllGroups(); return this.getAllGroups();
}) })
@@ -154,14 +200,14 @@ export class Zabbix implements ZabbixConnector {
return Promise.resolve(); return Promise.resolve();
} }
}) })
.catch(error => { .catch((error) => {
return Promise.reject(error); return Promise.reject(error);
}) })
.then(testResult => { .then((testResult) => {
if (testResult) { if (testResult) {
dbConnectorStatus = { dbConnectorStatus = {
dsType: this.dbConnector.datasourceTypeName, dsType: this.dbConnector.datasourceTypeName,
dsName: this.dbConnector.datasourceName dsName: this.dbConnector.datasourceName,
}; };
} }
return { zabbixVersion, dbConnectorStatus }; return { zabbixVersion, dbConnectorStatus };
@@ -196,17 +242,14 @@ export class Zabbix implements ZabbixConnector {
getItemsFromTarget(target, options) { getItemsFromTarget(target, options) {
const parts = ['group', 'host', 'application', 'itemTag', 'item']; const parts = ['group', 'host', 'application', 'itemTag', 'item'];
const filters = _.map(parts, p => target[p].filter); const filters = _.map(parts, (p) => target[p].filter);
return this.getItems(...filters, options); return this.getItems(...filters, options);
} }
getHostsFromTarget(target) { getHostsFromTarget(target) {
const parts = ['group', 'host', 'application']; const parts = ['group', 'host', 'application'];
const filters = _.map(parts, p => target[p].filter); const filters = _.map(parts, (p) => target[p].filter);
return Promise.all([ return Promise.all([this.getHosts(...filters), this.getApps(...filters)]).then((results) => {
this.getHosts(...filters),
this.getApps(...filters),
]).then(results => {
const hosts = results[0]; const hosts = results[0];
let apps: AppsResponse = results[1]; let apps: AppsResponse = results[1];
if (apps.appFilterEmpty) { if (apps.appFilterEmpty) {
@@ -221,24 +264,21 @@ export class Zabbix implements ZabbixConnector {
} }
getGroups(groupFilter) { getGroups(groupFilter) {
return this.getAllGroups() return this.getAllGroups().then((groups) => findByFilter(groups, groupFilter));
.then(groups => findByFilter(groups, groupFilter));
} }
/** /**
* Get list of host belonging to given groups. * Get list of host belonging to given groups.
*/ */
getAllHosts(groupFilter) { getAllHosts(groupFilter) {
return this.getGroups(groupFilter) return this.getGroups(groupFilter).then((groups) => {
.then(groups => {
const groupids = _.map(groups, 'groupid'); const groupids = _.map(groups, 'groupid');
return this.zabbixAPI.getHosts(groupids); return this.zabbixAPI.getHosts(groupids);
}); });
} }
getHosts(groupFilter?, hostFilter?) { getHosts(groupFilter?, hostFilter?) {
return this.getAllHosts(groupFilter) return this.getAllHosts(groupFilter).then((hosts) => findByFilter(hosts, hostFilter));
.then(hosts => findByFilter(hosts, hostFilter));
} }
/** /**
@@ -250,8 +290,7 @@ export class Zabbix implements ZabbixConnector {
return []; return [];
} }
return this.getHosts(groupFilter, hostFilter) return this.getHosts(groupFilter, hostFilter).then((hosts) => {
.then(hosts => {
const hostids = _.map(hosts, 'hostid'); const hostids = _.map(hosts, 'hostid');
return this.zabbixAPI.getApps(hostids); return this.zabbixAPI.getApps(hostids);
}); });
@@ -261,12 +300,10 @@ export class Zabbix implements ZabbixConnector {
await this.getVersion(); await this.getVersion();
const skipAppFilter = !this.supportsApplications(); const skipAppFilter = !this.supportsApplications();
return this.getHosts(groupFilter, hostFilter) return this.getHosts(groupFilter, hostFilter).then((hosts) => {
.then(hosts => {
const hostids = _.map(hosts, 'hostid'); const hostids = _.map(hosts, 'hostid');
if (appFilter && !skipAppFilter) { if (appFilter && !skipAppFilter) {
return this.zabbixAPI.getApps(hostids) return this.zabbixAPI.getApps(hostids).then((apps) => filterByQuery(apps, appFilter));
.then(apps => filterByQuery(apps, appFilter));
} else { } else {
const appsResponse: AppsResponse = hostids; const appsResponse: AppsResponse = hostids;
appsResponse.hostids = hostids; appsResponse.hostids = hostids;
@@ -278,15 +315,17 @@ export class Zabbix implements ZabbixConnector {
async getItemTags(groupFilter?, hostFilter?, itemTagFilter?) { async getItemTags(groupFilter?, hostFilter?, itemTagFilter?) {
const items = await this.getAllItems(groupFilter, hostFilter, null, null, {}); const items = await this.getAllItems(groupFilter, hostFilter, null, null, {});
let tags: ZBXItemTag[] = _.flatten(items.map((item: ZBXItem) => { let tags: ZBXItemTag[] = _.flatten(
items.map((item: ZBXItem) => {
if (item.tags) { if (item.tags) {
return item.tags; return item.tags;
} else { } else {
return []; return [];
} }
})); })
tags = _.uniqBy(tags, t => t.tag + t.value || ''); );
const tagsStr = tags.map(t => ({ name: utils.itemTagToString(t) })); tags = _.uniqBy(tags, (t) => t.tag + t.value || '');
const tagsStr = tags.map((t) => ({ name: utils.itemTagToString(t) }));
return findByFilter(tagsStr, itemTagFilter); return findByFilter(tagsStr, itemTagFilter);
} }
@@ -309,7 +348,7 @@ export class Zabbix implements ZabbixConnector {
} }
if (!options.showDisabledItems) { if (!options.showDisabledItems) {
items = _.filter(items, { 'status': '0' }); items = _.filter(items, { status: '0' });
} }
return await this.expandUserMacro(items, false); return await this.expandUserMacro(items, false);
@@ -317,9 +356,8 @@ export class Zabbix implements ZabbixConnector {
expandUserMacro(items, isTriggerItem) { expandUserMacro(items, isTriggerItem) {
const hostids = getHostIds(items); const hostids = getHostIds(items);
return this.getMacros(hostids) return this.getMacros(hostids).then((macros) => {
.then(macros => { _.forEach(items, (item) => {
_.forEach(items, item => {
if (utils.containsMacro(isTriggerItem ? item.url : item.name)) { if (utils.containsMacro(isTriggerItem ? item.url : item.name)) {
if (isTriggerItem) { if (isTriggerItem) {
item.url = utils.replaceMacro(item, macros, isTriggerItem); item.url = utils.replaceMacro(item, macros, isTriggerItem);
@@ -333,22 +371,23 @@ export class Zabbix implements ZabbixConnector {
} }
getItems(groupFilter?, hostFilter?, appFilter?, itemTagFilter?, itemFilter?, options = {}) { getItems(groupFilter?, hostFilter?, appFilter?, itemTagFilter?, itemFilter?, options = {}) {
return this.getAllItems(groupFilter, hostFilter, appFilter, itemTagFilter, options) return this.getAllItems(groupFilter, hostFilter, appFilter, itemTagFilter, options).then((items) =>
.then(items => filterByQuery(items, itemFilter)); filterByQuery(items, itemFilter)
);
} }
getItemValues(groupFilter?, hostFilter?, appFilter?, itemFilter?, options: any = {}) { getItemValues(groupFilter?, hostFilter?, appFilter?, itemFilter?, options: any = {}) {
return this.getItems(groupFilter, hostFilter, appFilter, null, itemFilter, options).then(items => { return this.getItems(groupFilter, hostFilter, appFilter, null, itemFilter, options).then((items) => {
let timeRange = [moment().subtract(2, 'h').unix(), moment().unix()]; let timeRange = [moment().subtract(2, 'h').unix(), moment().unix()];
if (options.range) { if (options.range) {
timeRange = [options.range.from.unix(), options.range.to.unix()]; timeRange = [options.range.from.unix(), options.range.to.unix()];
} }
const [timeFrom, timeTo] = timeRange; const [timeFrom, timeTo] = timeRange;
return this.zabbixAPI.getHistory(items, timeFrom, timeTo).then(history => { return this.zabbixAPI.getHistory(items, timeFrom, timeTo).then((history) => {
if (history) { if (history) {
const values = _.uniq(history.map(v => v.value)); const values = _.uniq(history.map((v) => v.value));
return values.map(value => ({ name: value })); return values.map((value) => ({ name: value }));
} else { } else {
return []; return [];
} }
@@ -357,19 +396,18 @@ export class Zabbix implements ZabbixConnector {
} }
getITServices(itServiceFilter) { getITServices(itServiceFilter) {
return this.zabbixAPI.getITService() return this.zabbixAPI.getITService().then((itServices) => findByFilter(itServices, itServiceFilter));
.then(itServices => findByFilter(itServices, itServiceFilter));
} }
getProblems(groupFilter, hostFilter, appFilter, proxyFilter?, options?): Promise<ProblemDTO[]> { getProblems(groupFilter, hostFilter, appFilter, proxyFilter?, options?): Promise<ProblemDTO[]> {
const promises = [ const promises = [
this.getGroups(groupFilter), this.getGroups(groupFilter),
this.getHosts(groupFilter, hostFilter), this.getHosts(groupFilter, hostFilter),
this.getApps(groupFilter, hostFilter, appFilter) this.getApps(groupFilter, hostFilter, appFilter),
]; ];
return Promise.all(promises) return Promise.all(promises)
.then(results => { .then((results) => {
const [filteredGroups, filteredHosts, filteredApps] = results; const [filteredGroups, filteredHosts, filteredApps] = results;
const query: any = {}; const query: any = {};
@@ -385,16 +423,13 @@ export class Zabbix implements ZabbixConnector {
return query; return query;
}) })
.then(query => this.zabbixAPI.getProblems(query.groupids, query.hostids, query.applicationids, options)) .then((query) => this.zabbixAPI.getProblems(query.groupids, query.hostids, query.applicationids, options))
.then(problems => { .then((problems) => {
const triggerids = problems?.map(problem => problem.objectid); const triggerids = problems?.map((problem) => problem.objectid);
return Promise.all([ return Promise.all([Promise.resolve(problems), this.zabbixAPI.getTriggersByIds(triggerids)]);
Promise.resolve(problems),
this.zabbixAPI.getTriggersByIds(triggerids)
]);
}) })
.then(([problems, triggers]) => joinTriggersWithProblems(problems, triggers)) .then(([problems, triggers]) => joinTriggersWithProblems(problems, triggers))
.then(triggers => this.filterTriggersByProxy(triggers, proxyFilter)); .then((triggers) => this.filterTriggersByProxy(triggers, proxyFilter));
// .then(triggers => this.expandUserMacro.bind(this)(triggers, true)); // .then(triggers => this.expandUserMacro.bind(this)(triggers, true));
} }
@@ -404,11 +439,11 @@ export class Zabbix implements ZabbixConnector {
const promises = [ const promises = [
this.getGroups(groupFilter), this.getGroups(groupFilter),
this.getHosts(groupFilter, hostFilter), this.getHosts(groupFilter, hostFilter),
this.getApps(groupFilter, hostFilter, appFilter) this.getApps(groupFilter, hostFilter, appFilter),
]; ];
return Promise.all(promises) return Promise.all(promises)
.then(results => { .then((results) => {
const [filteredGroups, filteredHosts, filteredApps] = results; const [filteredGroups, filteredHosts, filteredApps] = results;
const query: any = {}; const query: any = {};
@@ -424,22 +459,21 @@ export class Zabbix implements ZabbixConnector {
return query; return query;
}) })
.then(query => this.zabbixAPI.getEventsHistory(query.groupids, query.hostids, query.applicationids, options)) .then((query) => this.zabbixAPI.getEventsHistory(query.groupids, query.hostids, query.applicationids, options))
.then(problems => { .then((problems) => {
const triggerids = problems?.map(problem => problem.objectid); const triggerids = problems?.map((problem) => problem.objectid);
return Promise.all([Promise.resolve(problems), this.zabbixAPI.getTriggersByIds(triggerids)]); return Promise.all([Promise.resolve(problems), this.zabbixAPI.getTriggersByIds(triggerids)]);
}) })
.then(([problems, triggers]) => joinTriggersWithEvents(problems, triggers, { valueFromEvent })) .then(([problems, triggers]) => joinTriggersWithEvents(problems, triggers, { valueFromEvent }))
.then(triggers => this.filterTriggersByProxy(triggers, proxyFilter)); .then((triggers) => this.filterTriggersByProxy(triggers, proxyFilter));
// .then(triggers => this.expandUserMacro.bind(this)(triggers, true)); // .then(triggers => this.expandUserMacro.bind(this)(triggers, true));
} }
filterTriggersByProxy(triggers, proxyFilter) { filterTriggersByProxy(triggers, proxyFilter) {
return this.getFilteredProxies(proxyFilter) return this.getFilteredProxies(proxyFilter).then((proxies) => {
.then(proxies => {
if (proxyFilter && proxyFilter !== '/.*/' && triggers) { if (proxyFilter && proxyFilter !== '/.*/' && triggers) {
const proxy_ids = proxies.map(proxy => proxy.proxyid); const proxy_ids = proxies.map((proxy) => proxy.proxyid);
triggers = triggers.filter(trigger => { triggers = triggers.filter((trigger) => {
for (let i = 0; i < trigger.hosts.length; i++) { for (let i = 0; i < trigger.hosts.length; i++) {
const host = trigger.hosts[i]; const host = trigger.hosts[i];
if (proxy_ids.includes(host.proxy_hostid)) { if (proxy_ids.includes(host.proxy_hostid)) {
@@ -454,9 +488,8 @@ export class Zabbix implements ZabbixConnector {
} }
getFilteredProxies(proxyFilter) { getFilteredProxies(proxyFilter) {
return this.zabbixAPI.getProxies() return this.zabbixAPI.getProxies().then((proxies) => {
.then(proxies => { proxies.forEach((proxy) => (proxy.name = proxy.host));
proxies.forEach(proxy => proxy.name = proxy.host);
return findByFilter(proxies, proxyFilter); return findByFilter(proxies, proxyFilter);
}); });
} }
@@ -464,23 +497,27 @@ export class Zabbix implements ZabbixConnector {
getHistoryTS(items, timeRange, request) { getHistoryTS(items, timeRange, request) {
const [timeFrom, timeTo] = timeRange; const [timeFrom, timeTo] = timeRange;
if (this.enableDirectDBConnection) { if (this.enableDirectDBConnection) {
return this.getHistoryDB(items, timeFrom, timeTo, request) return this.getHistoryDB(items, timeFrom, timeTo, request).then((history) =>
.then(history => responseHandler.dataResponseToTimeSeries(history, items, request)); responseHandler.dataResponseToTimeSeries(history, items, request)
);
} else { } else {
return this.zabbixAPI.getHistory(items, timeFrom, timeTo) return this.zabbixAPI
.then(history => responseHandler.handleHistory(history, items)); .getHistory(items, timeFrom, timeTo)
.then((history) => responseHandler.handleHistory(history, items));
} }
} }
getTrends(items, timeRange, request) { getTrends(items, timeRange, request) {
const [timeFrom, timeTo] = timeRange; const [timeFrom, timeTo] = timeRange;
if (this.enableDirectDBConnection) { if (this.enableDirectDBConnection) {
return this.getTrendsDB(items, timeFrom, timeTo, request) return this.getTrendsDB(items, timeFrom, timeTo, request).then((history) =>
.then(history => responseHandler.dataResponseToTimeSeries(history, items, request)); responseHandler.dataResponseToTimeSeries(history, items, request)
);
} else { } else {
const valueType = request.consolidateBy || request.valueType; const valueType = request.consolidateBy || request.valueType;
return this.zabbixAPI.getTrend(items, timeFrom, timeTo) return this.zabbixAPI
.then(history => responseHandler.handleTrends(history, items, valueType)) .getTrend(items, timeFrom, timeTo)
.then((history) => responseHandler.handleTrends(history, items, valueType))
.then(responseHandler.sortTimeseries); // Sort trend data, issue #202 .then(responseHandler.sortTimeseries); // Sort trend data, issue #202
} }
} }
@@ -488,8 +525,7 @@ export class Zabbix implements ZabbixConnector {
getHistoryText(items, timeRange, target) { getHistoryText(items, timeRange, target) {
const [timeFrom, timeTo] = timeRange; const [timeFrom, timeTo] = timeRange;
if (items.length) { if (items.length) {
return this.zabbixAPI.getHistory(items, timeFrom, timeTo) return this.zabbixAPI.getHistory(items, timeFrom, timeTo).then((history) => {
.then(history => {
if (target.resultFormat === 'table') { if (target.resultFormat === 'table') {
return responseHandler.handleHistoryAsTable(history, items, target); return responseHandler.handleHistoryAsTable(history, items, target);
} else { } else {
@@ -505,14 +541,14 @@ export class Zabbix implements ZabbixConnector {
const itServiceIds = _.map(itservices, 'serviceid'); const itServiceIds = _.map(itservices, 'serviceid');
if (this.supportSLA()) { if (this.supportSLA()) {
const slaResponse = await this.zabbixAPI.getSLA60(itServiceIds, timeRange, options); const slaResponse = await this.zabbixAPI.getSLA60(itServiceIds, timeRange, options);
return _.map(itServiceIds, serviceid => { return _.map(itServiceIds, (serviceid) => {
const itservice = _.find(itservices, { 'serviceid': serviceid }); const itservice = _.find(itservices, { serviceid: serviceid });
return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse); return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);
}); });
} }
const slaResponse = await this.zabbixAPI.getSLA(itServiceIds, timeRange, options); const slaResponse = await this.zabbixAPI.getSLA(itServiceIds, timeRange, options);
return _.map(itServiceIds, serviceid => { return _.map(itServiceIds, (serviceid) => {
const itservice = _.find(itservices, { 'serviceid': serviceid }); const itservice = _.find(itservices, { serviceid: serviceid });
return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse); return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);
}); });
} }
@@ -527,7 +563,7 @@ export class Zabbix implements ZabbixConnector {
* @return array with finded element or empty array * @return array with finded element or empty array
*/ */
function findByName(list, name) { function findByName(list, name) {
const finded = _.find(list, { 'name': name }); const finded = _.find(list, { name: name });
if (finded) { if (finded) {
return [finded]; return [finded];
} else { } else {
@@ -544,7 +580,7 @@ function findByName(list, name) {
* @return {[type]} array with finded element or empty array * @return {[type]} array with finded element or empty array
*/ */
function filterByName(list, name) { function filterByName(list, name) {
const finded = _.filter(list, { 'name': name }); const finded = _.filter(list, { name: name });
if (finded) { if (finded) {
return finded; return finded;
} else { } else {
@@ -576,7 +612,7 @@ function filterByQuery(list, filter) {
} }
function getHostIds(items) { function getHostIds(items) {
const hostIds = _.map(items, item => { const hostIds = _.map(items, (item) => {
return _.map(item.hosts, 'hostid'); return _.map(item.hosts, 'hostid');
}); });
return _.uniq(_.flatten(hostIds)); return _.uniq(_.flatten(hostIds));
@@ -587,7 +623,7 @@ function filterItemsByTag(items: any[], itemTagFilter: string) {
const filterPattern = utils.buildRegex(itemTagFilter); const filterPattern = utils.buildRegex(itemTagFilter);
return items.filter((item) => { return items.filter((item) => {
if (item.tags) { if (item.tags) {
const tags: string[] = item.tags.map(t => utils.itemTagToString(t)); const tags: string[] = item.tags.map((t) => utils.itemTagToString(t));
return tags.some((tag) => { return tags.some((tag) => {
return filterPattern.test(tag); return filterPattern.test(tag);
}); });
@@ -596,9 +632,9 @@ function filterItemsByTag(items: any[], itemTagFilter: string) {
} }
}); });
} else { } else {
return items.filter(item => { return items.filter((item) => {
if (item.tags) { if (item.tags) {
const tags: string[] = item.tags.map(t => utils.itemTagToString(t)); const tags: string[] = item.tags.map((t) => utils.itemTagToString(t));
return tags.includes(itemTagFilter); return tags.includes(itemTagFilter);
} else { } else {
return false; return false;