From 94c24e9be4c56fc60447b6d3ae7f168b8991abdf Mon Sep 17 00:00:00 2001 From: Alexander Zobnin Date: Sat, 11 Feb 2017 16:26:23 +0300 Subject: [PATCH] Fix templatig issue, when no values returned, closes #354 --- dist/datasource-zabbix/datasource.js | 2 +- dist/datasource-zabbix/datasource.js.map | 2 +- dist/datasource-zabbix/zabbix.js | 8 ++++---- dist/datasource-zabbix/zabbix.js.map | 2 +- dist/test/datasource-zabbix/datasource.js | 2 +- dist/test/datasource-zabbix/zabbix.js | 8 ++++---- src/datasource-zabbix/datasource.js | 2 +- src/datasource-zabbix/zabbix.js | 8 ++++---- 8 files changed, 17 insertions(+), 17 deletions(-) diff --git a/dist/datasource-zabbix/datasource.js b/dist/datasource-zabbix/datasource.js index 8c9c6452c..4bd133e7e 100644 --- a/dist/datasource-zabbix/datasource.js +++ b/dist/datasource-zabbix/datasource.js @@ -484,7 +484,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', } return result.then(function (metrics) { - return metrics.map(formatMetric); + return _.map(metrics, formatMetric); }); } }, { diff --git a/dist/datasource-zabbix/datasource.js.map b/dist/datasource-zabbix/datasource.js.map index fca55f1e5..e5410b1b1 100644 --- a/dist/datasource-zabbix/datasource.js.map +++ b/dist/datasource-zabbix/datasource.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/datasource.js"],"names":["bindFunctionDefs","functionDefs","category","aggregationFunctions","_","map","metricFunctions","getCategories","aggFuncDefs","filter","func","includes","def","name","funcInstance","createFuncInstance","params","bindFunction","dataProcessor","downsampleSeries","timeseries_data","options","timeseries","datapoints","length","maxDataPoints","groupBy","interval","AVERAGE","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","replaceTemplateVars","templateSrv","target","scopedVars","replacedTarget","replace","isRegex","extractText","str","pattern","useCaptureGroups","extractPattern","RegExp","extractedValue","exec","sequence","funcsArray","result","i","call","dateMath","migrations","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","Zabbix","url","basicAuth","withCredentials","username","jsonData","password","trends","trendsFrom","ttl","cacheTTL","parseInterval","zabbix","partial","timeFrom","Math","ceil","parse","range","from","timeTo","to","useTrendsFrom","useTrends","promises","targets","cloneDeep","replaceTargetVariables","timeFunctions","functions","time_from","time_to","mode","migrate","hide","group","host","item","queryNumericData","queryTextData","itservice","slaProperty","getSLA","serviceid","then","handleSLAResponse","slaObject","Promise","all","flatten","data","itemtype","getItemsFromTarget","getHistoryPromise","valueType","getTrendValueType","getTrend","items","handleTrends","history","getHistory","handleHistory","applyDataProcessingFunctions","trendFunctions","trendValueFunc","find","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","forEach","applyTimeShiftFunction","timeShiftFunc","shift","series","unShiftTimeSeries","convertHistory","point","textFilter","clock","resolve","zabbixVersion","getVersion","version","login","status","title","message","catch","error","query","parts","each","split","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","showTriggers","getTriggers","application","trigger","triggers","buildRegex","test","description","Number","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","hosts","formatted_acknowledges","formatAcknowledges","time","objectid","p","param","toString","contains","indexBy"],"mappings":";;;;;;;;;;;;;AA+ZA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC,gBAAgBC,aAAhB,GAAgCL,QAAhC,CAAN,EAAiD,MAAjD,CAA3B;AACA,QAAIM,cAAcJ,EAAEK,MAAF,CAASR,YAAT,EAAuB,UAASS,IAAT,EAAe;AACtD,aAAON,EAAEO,QAAF,CAAWR,oBAAX,EAAiCO,KAAKE,GAAL,CAASC,IAA1C,CAAP;AACD,KAFiB,CAAlB;;AAIA,WAAOT,EAAEC,GAAF,CAAMG,WAAN,EAAmB,UAASE,IAAT,EAAe;AACv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AAOD,aARD;AASD;;;;;;qCA4FKqB,mB;;sCAAqB9B,oB;;AAE7B;AACA,UAAI,CAAC7B,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAEyM,QAAf;AAAyB;AAC3C,UAAI,CAACzM,EAAE0L,KAAP,EAAc;AAAC1L,UAAE0L,KAAF,GAAU1L,EAAE0M,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["//import angular from 'angular';\nimport _ from 'lodash';\nimport * as dateMath from 'app/core/utils/datemath';\nimport * as utils from './utils';\nimport * as migrations from './migrations';\nimport * as metricFunctions from './metricFunctions';\nimport dataProcessor from './dataProcessor';\nimport responseHandler from './responseHandler';\nimport './zabbix.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n /** @ngInject */\n constructor(instanceSettings, templateSrv, alertSrv, Zabbix) {\n this.templateSrv = templateSrv;\n this.alertSrv = alertSrv;\n\n // General data source settings\n this.name = instanceSettings.name;\n this.url = instanceSettings.url;\n this.basicAuth = instanceSettings.basicAuth;\n this.withCredentials = instanceSettings.withCredentials;\n\n // Zabbix API credentials\n this.username = instanceSettings.jsonData.username;\n this.password = instanceSettings.jsonData.password;\n\n // Use trends instead history since specified time\n this.trends = instanceSettings.jsonData.trends;\n this.trendsFrom = instanceSettings.jsonData.trendsFrom || '7d';\n\n // Set cache update interval\n var ttl = instanceSettings.jsonData.cacheTTL || '1h';\n this.cacheTTL = utils.parseInterval(ttl);\n\n this.zabbix = new Zabbix(this.url, this.username, this.password, this.basicAuth, this.withCredentials, this.cacheTTL);\n\n // Use custom format for template variables\n this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\n }\n\n ////////////////////////\n // Datasource methods //\n ////////////////////////\n\n /**\n * Query panel data. Calls for each panel in dashboard.\n * @param {Object} options Contains time range, targets and other info.\n * @return {Object} Grafana metrics object with timeseries data for each target.\n */\n query(options) {\n let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n let useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);\n let useTrends = (timeFrom <= useTrendsFrom) && this.trends;\n\n // Create request for each target\n let promises = _.map(options.targets, target => {\n // Prevent changes of original object\n target = _.cloneDeep(target);\n this.replaceTargetVariables(target, options);\n\n // Apply Time-related functions (timeShift(), etc)\n let timeFunctions = bindFunctionDefs(target.functions, 'Time');\n if (timeFunctions.length) {\n const [time_from, time_to] = sequence(timeFunctions)([timeFrom, timeTo]);\n timeFrom = time_from;\n timeTo = time_to;\n }\n\n // Metrics or Text query mode\n if (target.mode !== 1) {\n // Migrate old targets\n target = migrations.migrate(target);\n\n // Don't request undefined and hidden targets\n if (target.hide || !target.group || !target.host || !target.item) {\n return [];\n }\n\n if (!target.mode || target.mode === 0) {\n return this.queryNumericData(target, timeFrom, timeTo, useTrends);\n } else if (target.mode === 2) {\n return this.queryTextData(target, timeFrom, timeTo);\n }\n }\n\n // IT services mode\n else if (target.mode === 1) {\n // Don't show undefined and hidden targets\n if (target.hide || !target.itservice || !target.slaProperty) {\n return [];\n }\n\n return this.zabbix.getSLA(target.itservice.serviceid, timeFrom, timeTo)\n .then(slaObject => {\n return responseHandler.handleSLAResponse(target.itservice, target.slaProperty, slaObject);\n });\n }\n });\n\n // Data for panel (all targets)\n return Promise.all(_.flatten(promises))\n .then(_.flatten)\n .then(timeseries_data => {\n return downsampleSeries(timeseries_data, options);\n })\n .then(data => {\n return { data: data };\n });\n }\n\n queryNumericData(target, timeFrom, timeTo, useTrends) {\n let options = {\n itemtype: 'num'\n };\n return this.zabbix.getItemsFromTarget(target, options)\n .then(items => {\n let getHistoryPromise;\n\n if (useTrends) {\n let valueType = this.getTrendValueType(target);\n getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n .then(history => {\n return responseHandler.handleTrends(history, items, valueType);\n });\n } else {\n // Use history\n getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => {\n return responseHandler.handleHistory(history, items);\n });\n }\n\n return getHistoryPromise.then(timeseries_data => {\n return this.applyDataProcessingFunctions(timeseries_data, target);\n });\n });\n }\n\n getTrendValueType(target) {\n // Find trendValue() function and get specified trend value\n var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name');\n var trendValueFunc = _.find(target.functions, func => {\n return _.includes(trendFunctions, func.def.name);\n });\n return trendValueFunc ? trendValueFunc.params[0] : \"avg\";\n }\n\n applyDataProcessingFunctions(timeseries_data, target) {\n let transformFunctions = bindFunctionDefs(target.functions, 'Transform');\n let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate');\n let filterFunctions = bindFunctionDefs(target.functions, 'Filter');\n let aliasFunctions = bindFunctionDefs(target.functions, 'Alias');\n\n // Apply transformation functions\n timeseries_data = _.map(timeseries_data, timeseries => {\n timeseries.datapoints = sequence(transformFunctions)(timeseries.datapoints);\n return timeseries;\n });\n\n // Apply filter functions\n if (filterFunctions.length) {\n timeseries_data = sequence(filterFunctions)(timeseries_data);\n }\n\n // Apply aggregations\n if (aggregationFunctions.length) {\n let dp = _.map(timeseries_data, 'datapoints');\n dp = sequence(aggregationFunctions)(dp);\n\n let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name');\n let lastAgg = _.findLast(target.functions, func => {\n return _.includes(aggFuncNames, func.def.name);\n });\n\n timeseries_data = [{\n target: lastAgg.text,\n datapoints: dp\n }];\n }\n\n // Apply alias functions\n _.forEach(timeseries_data, sequence(aliasFunctions));\n\n // Apply Time-related functions (timeShift(), etc)\n // Find timeShift() function and get specified trend value\n this.applyTimeShiftFunction(timeseries_data, target);\n\n return timeseries_data;\n }\n\n applyTimeShiftFunction(timeseries_data, target) {\n // Find timeShift() function and get specified interval\n let timeShiftFunc = _.find(target.functions, (func) => {\n return func.def.name === 'timeShift';\n });\n if (timeShiftFunc) {\n let shift = timeShiftFunc.params[0];\n _.forEach(timeseries_data, (series) => {\n series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints);\n });\n }\n }\n\n queryTextData(target, timeFrom, timeTo) {\n let options = {\n itemtype: 'text'\n };\n return this.zabbix.getItemsFromTarget(target, options)\n .then(items => {\n if (items.length) {\n return this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => {\n return responseHandler.convertHistory(history, items, false, (point) => {\n let value = point.value;\n\n // Regex-based extractor\n if (target.textFilter) {\n value = extractText(point.value, target.textFilter, target.useCaptureGroups);\n }\n\n return [value, point.clock * 1000];\n });\n });\n } else {\n return Promise.resolve([]);\n }\n });\n }\n\n /**\n * Test connection to Zabbix API\n * @return {object} Connection status and Zabbix API version\n */\n testDatasource() {\n let zabbixVersion;\n return this.zabbix.getVersion()\n .then(version => {\n zabbixVersion = version;\n return this.zabbix.login();\n })\n .then(() => {\n return {\n status: \"success\",\n title: \"Success\",\n message: \"Zabbix API version: \" + zabbixVersion\n };\n })\n .catch(error => {\n if (error instanceof ZabbixAPIError) {\n return {\n status: \"error\",\n title: error.message,\n message: error.data\n };\n } else {\n return {\n status: \"error\",\n title: \"Connection failed\",\n message: \"Could not connect to given url\"\n };\n }\n });\n }\n\n ////////////////\n // Templating //\n ////////////////\n\n /**\n * Find metrics from templated request.\n *\n * @param {string} query Query from Templating\n * @return {string} Metric name - group, host, app or item or list\n * of metrics in \"{metric1,metcic2,...,metricN}\" format.\n */\n metricFindQuery(query) {\n let result;\n let parts = [];\n\n // Split query. Query structure: group.host.app.item\n _.each(query.split('.'), part => {\n part = this.replaceTemplateVars(part, {});\n\n // Replace wildcard to regex\n if (part === '*') {\n part = '/.*/';\n }\n parts.push(part);\n });\n let template = _.zipObject(['group', 'host', 'app', 'item'], parts);\n\n // Get items\n if (parts.length === 4) {\n // Search for all items, even it's not belong to any application\n if (template.app === '/.*/') {\n template.app = '';\n }\n result = this.zabbix.getItems(template.group, template.host, template.app, template.item);\n } else if (parts.length === 3) {\n // Get applications\n result = this.zabbix.getApps(template.group, template.host, template.app);\n } else if (parts.length === 2) {\n // Get hosts\n result = this.zabbix.getHosts(template.group, template.host);\n } else if (parts.length === 1) {\n // Get groups\n result = this.zabbix.getGroups(template.group);\n } else {\n result = Promise.resolve([]);\n }\n\n return result.then(metrics => {\n return metrics.map(formatMetric);\n });\n }\n\n /////////////////\n // Annotations //\n /////////////////\n\n annotationQuery(options) {\n var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);\n var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);\n var annotation = options.annotation;\n var showOkEvents = annotation.showOkEvents ? [0, 1] : 1;\n\n // Show all triggers\n var showTriggers = [0, 1];\n\n var getTriggers = this.zabbix\n .getTriggers(this.replaceTemplateVars(annotation.group, {}),\n this.replaceTemplateVars(annotation.host, {}),\n this.replaceTemplateVars(annotation.application, {}),\n showTriggers);\n\n return getTriggers.then(triggers => {\n\n // Filter triggers by description\n if (utils.isRegex(annotation.trigger)) {\n triggers = _.filter(triggers, trigger => {\n return utils.buildRegex(annotation.trigger).test(trigger.description);\n });\n } else if (annotation.trigger) {\n triggers = _.filter(triggers, trigger => {\n return trigger.description === annotation.trigger;\n });\n }\n\n // Remove events below the chose severity\n triggers = _.filter(triggers, trigger => {\n return Number(trigger.priority) >= Number(annotation.minseverity);\n });\n\n var objectids = _.map(triggers, 'triggerid');\n return this.zabbix\n .getEvents(objectids, timeFrom, timeTo, showOkEvents)\n .then(events => {\n var indexedTriggers = _.keyBy(triggers, 'triggerid');\n\n // Hide acknowledged events if option enabled\n if (annotation.hideAcknowledged) {\n events = _.filter(events, event => {\n return !event.acknowledges.length;\n });\n }\n\n return _.map(events, event => {\n let tags;\n if (annotation.showHostname) {\n tags = _.map(event.hosts, 'name');\n }\n\n // Show event type (OK or Problem)\n let title = Number(event.value) ? 'Problem' : 'OK';\n\n let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges);\n return {\n annotation: annotation,\n time: event.clock * 1000,\n title: title,\n tags: tags,\n text: indexedTriggers[event.objectid].description + formatted_acknowledges\n };\n });\n });\n });\n }\n\n // Replace template variables\n replaceTargetVariables(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n parts.forEach(p => {\n if (target[p] && target[p].filter) {\n target[p].filter = this.replaceTemplateVars(target[p].filter, options.scopedVars);\n }\n });\n target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);\n\n _.forEach(target.functions, func => {\n func.params = func.params.map(param => {\n if (typeof param === 'number') {\n return +this.templateSrv.replace(param.toString(), options.scopedVars);\n } else {\n return this.templateSrv.replace(param, options.scopedVars);\n }\n });\n });\n }\n\n}\n\nfunction bindFunctionDefs(functionDefs, category) {\n var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name');\n var aggFuncDefs = _.filter(functionDefs, function(func) {\n return _.includes(aggregationFunctions, func.def.name);\n });\n\n return _.map(aggFuncDefs, function(func) {\n var funcInstance = metricFunctions.createFuncInstance(func.def, func.params);\n return funcInstance.bindFunction(dataProcessor.metricFunctions);\n });\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n return _.map(timeseries_data, timeseries => {\n if (timeseries.datapoints.length > options.maxDataPoints) {\n timeseries.datapoints = dataProcessor\n .groupBy(options.interval, dataProcessor.AVERAGE, timeseries.datapoints);\n }\n return timeseries;\n });\n}\n\nfunction formatMetric(metricObj) {\n return {\n text: metricObj.name,\n expandable: false\n };\n}\n\n/**\n * Custom formatter for template variables.\n * Default Grafana \"regex\" formatter returns\n * value1|value2\n * This formatter returns\n * (value1|value2)\n * This format needed for using in complex regex with\n * template variables, for example\n * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait\n */\nfunction zabbixTemplateFormat(value) {\n if (typeof value === 'string') {\n return utils.escapeRegex(value);\n }\n\n var escapedValues = _.map(value, utils.escapeRegex);\n return '(' + escapedValues.join('|') + ')';\n}\n\n/**\n * If template variables are used in request, replace it using regex format\n * and wrap with '/' for proper multi-value work. Example:\n * $variable selected as a, b, c\n * We use filter $variable\n * $variable -> a|b|c -> /a|b|c/\n * /$variable/ -> /a|b|c/ -> /a|b|c/\n */\nfunction replaceTemplateVars(templateSrv, target, scopedVars) {\n var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat);\n if (target !== replacedTarget && !utils.isRegex(replacedTarget)) {\n replacedTarget = '/^' + replacedTarget + '$/';\n }\n return replacedTarget;\n}\n\nfunction extractText(str, pattern, useCaptureGroups) {\n let extractPattern = new RegExp(pattern);\n let extractedValue = extractPattern.exec(str);\n if (extractedValue) {\n if (useCaptureGroups) {\n extractedValue = extractedValue[1];\n } else {\n extractedValue = extractedValue[0];\n }\n }\n return extractedValue;\n}\n\n// Apply function one by one:\n// sequence([a(), b(), c()]) = c(b(a()));\nfunction sequence(funcsArray) {\n return function(result) {\n for (var i = 0; i < funcsArray.length; i++) {\n result = funcsArray[i].call(this, result);\n }\n return result;\n };\n}\n\nexport {ZabbixAPIDatasource, zabbixTemplateFormat};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.includes) {_.includes = _.contains;}\nif (!_.keyBy) {_.keyBy = _.indexBy;}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/datasource.js"],"names":["bindFunctionDefs","functionDefs","category","aggregationFunctions","_","map","metricFunctions","getCategories","aggFuncDefs","filter","func","includes","def","name","funcInstance","createFuncInstance","params","bindFunction","dataProcessor","downsampleSeries","timeseries_data","options","timeseries","datapoints","length","maxDataPoints","groupBy","interval","AVERAGE","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","replaceTemplateVars","templateSrv","target","scopedVars","replacedTarget","replace","isRegex","extractText","str","pattern","useCaptureGroups","extractPattern","RegExp","extractedValue","exec","sequence","funcsArray","result","i","call","dateMath","migrations","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","Zabbix","url","basicAuth","withCredentials","username","jsonData","password","trends","trendsFrom","ttl","cacheTTL","parseInterval","zabbix","partial","timeFrom","Math","ceil","parse","range","from","timeTo","to","useTrendsFrom","useTrends","promises","targets","cloneDeep","replaceTargetVariables","timeFunctions","functions","time_from","time_to","mode","migrate","hide","group","host","item","queryNumericData","queryTextData","itservice","slaProperty","getSLA","serviceid","then","handleSLAResponse","slaObject","Promise","all","flatten","data","itemtype","getItemsFromTarget","getHistoryPromise","valueType","getTrendValueType","getTrend","items","handleTrends","history","getHistory","handleHistory","applyDataProcessingFunctions","trendFunctions","trendValueFunc","find","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","forEach","applyTimeShiftFunction","timeShiftFunc","shift","series","unShiftTimeSeries","convertHistory","point","textFilter","clock","resolve","zabbixVersion","getVersion","version","login","status","title","message","catch","error","query","parts","each","split","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","showTriggers","getTriggers","application","trigger","triggers","buildRegex","test","description","Number","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","hosts","formatted_acknowledges","formatAcknowledges","time","objectid","p","param","toString","contains","indexBy"],"mappings":";;;;;;;;;;;;;AA+ZA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC,gBAAgBC,aAAhB,GAAgCL,QAAhC,CAAN,EAAiD,MAAjD,CAA3B;AACA,QAAIM,cAAcJ,EAAEK,MAAF,CAASR,YAAT,EAAuB,UAASS,IAAT,EAAe;AACtD,aAAON,EAAEO,QAAF,CAAWR,oBAAX,EAAiCO,KAAKE,GAAL,CAASC,IAA1C,CAAP;AACD,KAFiB,CAAlB;;AAIA,WAAOT,EAAEC,GAAF,CAAMG,WAAN,EAAmB,UAASE,IAAT,EAAe;AACvC,UAAII,eAAeR,gBAAgBS,kBAAhB,CAAmCL,KAAKE,GAAxC,EAA6CF,KAAKM,MAAlD,CAAnB;AACA,aAAOF,aAAaG,YAAb,CAA0BC,cAAcZ,eAAxC,CAAP;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EyM,QAAf;AAAyB;AAC3C,UAAI,CAACzM,EAAE0L,KAAP,EAAc;AAAC1L,UAAE0L,KAAF,GAAU1L,EAAE0M,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["//import angular from 'angular';\nimport _ from 'lodash';\nimport * as dateMath from 'app/core/utils/datemath';\nimport * as utils from './utils';\nimport * as migrations from './migrations';\nimport * as metricFunctions from './metricFunctions';\nimport dataProcessor from './dataProcessor';\nimport responseHandler from './responseHandler';\nimport './zabbix.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n /** @ngInject */\n constructor(instanceSettings, templateSrv, alertSrv, Zabbix) {\n this.templateSrv = templateSrv;\n this.alertSrv = alertSrv;\n\n // General data source settings\n this.name = instanceSettings.name;\n this.url = instanceSettings.url;\n this.basicAuth = instanceSettings.basicAuth;\n this.withCredentials = instanceSettings.withCredentials;\n\n // Zabbix API credentials\n this.username = instanceSettings.jsonData.username;\n this.password = instanceSettings.jsonData.password;\n\n // Use trends instead history since specified time\n this.trends = instanceSettings.jsonData.trends;\n this.trendsFrom = instanceSettings.jsonData.trendsFrom || '7d';\n\n // Set cache update interval\n var ttl = instanceSettings.jsonData.cacheTTL || '1h';\n this.cacheTTL = utils.parseInterval(ttl);\n\n this.zabbix = new Zabbix(this.url, this.username, this.password, this.basicAuth, this.withCredentials, this.cacheTTL);\n\n // Use custom format for template variables\n this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\n }\n\n ////////////////////////\n // Datasource methods //\n ////////////////////////\n\n /**\n * Query panel data. Calls for each panel in dashboard.\n * @param {Object} options Contains time range, targets and other info.\n * @return {Object} Grafana metrics object with timeseries data for each target.\n */\n query(options) {\n let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n let useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);\n let useTrends = (timeFrom <= useTrendsFrom) && this.trends;\n\n // Create request for each target\n let promises = _.map(options.targets, target => {\n // Prevent changes of original object\n target = _.cloneDeep(target);\n this.replaceTargetVariables(target, options);\n\n // Apply Time-related functions (timeShift(), etc)\n let timeFunctions = bindFunctionDefs(target.functions, 'Time');\n if (timeFunctions.length) {\n const [time_from, time_to] = sequence(timeFunctions)([timeFrom, timeTo]);\n timeFrom = time_from;\n timeTo = time_to;\n }\n\n // Metrics or Text query mode\n if (target.mode !== 1) {\n // Migrate old targets\n target = migrations.migrate(target);\n\n // Don't request undefined and hidden targets\n if (target.hide || !target.group || !target.host || !target.item) {\n return [];\n }\n\n if (!target.mode || target.mode === 0) {\n return this.queryNumericData(target, timeFrom, timeTo, useTrends);\n } else if (target.mode === 2) {\n return this.queryTextData(target, timeFrom, timeTo);\n }\n }\n\n // IT services mode\n else if (target.mode === 1) {\n // Don't show undefined and hidden targets\n if (target.hide || !target.itservice || !target.slaProperty) {\n return [];\n }\n\n return this.zabbix.getSLA(target.itservice.serviceid, timeFrom, timeTo)\n .then(slaObject => {\n return responseHandler.handleSLAResponse(target.itservice, target.slaProperty, slaObject);\n });\n }\n });\n\n // Data for panel (all targets)\n return Promise.all(_.flatten(promises))\n .then(_.flatten)\n .then(timeseries_data => {\n return downsampleSeries(timeseries_data, options);\n })\n .then(data => {\n return { data: data };\n });\n }\n\n queryNumericData(target, timeFrom, timeTo, useTrends) {\n let options = {\n itemtype: 'num'\n };\n return this.zabbix.getItemsFromTarget(target, options)\n .then(items => {\n let getHistoryPromise;\n\n if (useTrends) {\n let valueType = this.getTrendValueType(target);\n getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n .then(history => {\n return responseHandler.handleTrends(history, items, valueType);\n });\n } else {\n // Use history\n getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => {\n return responseHandler.handleHistory(history, items);\n });\n }\n\n return getHistoryPromise.then(timeseries_data => {\n return this.applyDataProcessingFunctions(timeseries_data, target);\n });\n });\n }\n\n getTrendValueType(target) {\n // Find trendValue() function and get specified trend value\n var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name');\n var trendValueFunc = _.find(target.functions, func => {\n return _.includes(trendFunctions, func.def.name);\n });\n return trendValueFunc ? trendValueFunc.params[0] : \"avg\";\n }\n\n applyDataProcessingFunctions(timeseries_data, target) {\n let transformFunctions = bindFunctionDefs(target.functions, 'Transform');\n let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate');\n let filterFunctions = bindFunctionDefs(target.functions, 'Filter');\n let aliasFunctions = bindFunctionDefs(target.functions, 'Alias');\n\n // Apply transformation functions\n timeseries_data = _.map(timeseries_data, timeseries => {\n timeseries.datapoints = sequence(transformFunctions)(timeseries.datapoints);\n return timeseries;\n });\n\n // Apply filter functions\n if (filterFunctions.length) {\n timeseries_data = sequence(filterFunctions)(timeseries_data);\n }\n\n // Apply aggregations\n if (aggregationFunctions.length) {\n let dp = _.map(timeseries_data, 'datapoints');\n dp = sequence(aggregationFunctions)(dp);\n\n let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name');\n let lastAgg = _.findLast(target.functions, func => {\n return _.includes(aggFuncNames, func.def.name);\n });\n\n timeseries_data = [{\n target: lastAgg.text,\n datapoints: dp\n }];\n }\n\n // Apply alias functions\n _.forEach(timeseries_data, sequence(aliasFunctions));\n\n // Apply Time-related functions (timeShift(), etc)\n // Find timeShift() function and get specified trend value\n this.applyTimeShiftFunction(timeseries_data, target);\n\n return timeseries_data;\n }\n\n applyTimeShiftFunction(timeseries_data, target) {\n // Find timeShift() function and get specified interval\n let timeShiftFunc = _.find(target.functions, (func) => {\n return func.def.name === 'timeShift';\n });\n if (timeShiftFunc) {\n let shift = timeShiftFunc.params[0];\n _.forEach(timeseries_data, (series) => {\n series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints);\n });\n }\n }\n\n queryTextData(target, timeFrom, timeTo) {\n let options = {\n itemtype: 'text'\n };\n return this.zabbix.getItemsFromTarget(target, options)\n .then(items => {\n if (items.length) {\n return this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => {\n return responseHandler.convertHistory(history, items, false, (point) => {\n let value = point.value;\n\n // Regex-based extractor\n if (target.textFilter) {\n value = extractText(point.value, target.textFilter, target.useCaptureGroups);\n }\n\n return [value, point.clock * 1000];\n });\n });\n } else {\n return Promise.resolve([]);\n }\n });\n }\n\n /**\n * Test connection to Zabbix API\n * @return {object} Connection status and Zabbix API version\n */\n testDatasource() {\n let zabbixVersion;\n return this.zabbix.getVersion()\n .then(version => {\n zabbixVersion = version;\n return this.zabbix.login();\n })\n .then(() => {\n return {\n status: \"success\",\n title: \"Success\",\n message: \"Zabbix API version: \" + zabbixVersion\n };\n })\n .catch(error => {\n if (error instanceof ZabbixAPIError) {\n return {\n status: \"error\",\n title: error.message,\n message: error.data\n };\n } else {\n return {\n status: \"error\",\n title: \"Connection failed\",\n message: \"Could not connect to given url\"\n };\n }\n });\n }\n\n ////////////////\n // Templating //\n ////////////////\n\n /**\n * Find metrics from templated request.\n *\n * @param {string} query Query from Templating\n * @return {string} Metric name - group, host, app or item or list\n * of metrics in \"{metric1,metcic2,...,metricN}\" format.\n */\n metricFindQuery(query) {\n let result;\n let parts = [];\n\n // Split query. Query structure: group.host.app.item\n _.each(query.split('.'), part => {\n part = this.replaceTemplateVars(part, {});\n\n // Replace wildcard to regex\n if (part === '*') {\n part = '/.*/';\n }\n parts.push(part);\n });\n let template = _.zipObject(['group', 'host', 'app', 'item'], parts);\n\n // Get items\n if (parts.length === 4) {\n // Search for all items, even it's not belong to any application\n if (template.app === '/.*/') {\n template.app = '';\n }\n result = this.zabbix.getItems(template.group, template.host, template.app, template.item);\n } else if (parts.length === 3) {\n // Get applications\n result = this.zabbix.getApps(template.group, template.host, template.app);\n } else if (parts.length === 2) {\n // Get hosts\n result = this.zabbix.getHosts(template.group, template.host);\n } else if (parts.length === 1) {\n // Get groups\n result = this.zabbix.getGroups(template.group);\n } else {\n result = Promise.resolve([]);\n }\n\n return result.then(metrics => {\n return _.map(metrics, formatMetric);\n });\n }\n\n /////////////////\n // Annotations //\n /////////////////\n\n annotationQuery(options) {\n var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);\n var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);\n var annotation = options.annotation;\n var showOkEvents = annotation.showOkEvents ? [0, 1] : 1;\n\n // Show all triggers\n var showTriggers = [0, 1];\n\n var getTriggers = this.zabbix\n .getTriggers(this.replaceTemplateVars(annotation.group, {}),\n this.replaceTemplateVars(annotation.host, {}),\n this.replaceTemplateVars(annotation.application, {}),\n showTriggers);\n\n return getTriggers.then(triggers => {\n\n // Filter triggers by description\n if (utils.isRegex(annotation.trigger)) {\n triggers = _.filter(triggers, trigger => {\n return utils.buildRegex(annotation.trigger).test(trigger.description);\n });\n } else if (annotation.trigger) {\n triggers = _.filter(triggers, trigger => {\n return trigger.description === annotation.trigger;\n });\n }\n\n // Remove events below the chose severity\n triggers = _.filter(triggers, trigger => {\n return Number(trigger.priority) >= Number(annotation.minseverity);\n });\n\n var objectids = _.map(triggers, 'triggerid');\n return this.zabbix\n .getEvents(objectids, timeFrom, timeTo, showOkEvents)\n .then(events => {\n var indexedTriggers = _.keyBy(triggers, 'triggerid');\n\n // Hide acknowledged events if option enabled\n if (annotation.hideAcknowledged) {\n events = _.filter(events, event => {\n return !event.acknowledges.length;\n });\n }\n\n return _.map(events, event => {\n let tags;\n if (annotation.showHostname) {\n tags = _.map(event.hosts, 'name');\n }\n\n // Show event type (OK or Problem)\n let title = Number(event.value) ? 'Problem' : 'OK';\n\n let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges);\n return {\n annotation: annotation,\n time: event.clock * 1000,\n title: title,\n tags: tags,\n text: indexedTriggers[event.objectid].description + formatted_acknowledges\n };\n });\n });\n });\n }\n\n // Replace template variables\n replaceTargetVariables(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n parts.forEach(p => {\n if (target[p] && target[p].filter) {\n target[p].filter = this.replaceTemplateVars(target[p].filter, options.scopedVars);\n }\n });\n target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);\n\n _.forEach(target.functions, func => {\n func.params = func.params.map(param => {\n if (typeof param === 'number') {\n return +this.templateSrv.replace(param.toString(), options.scopedVars);\n } else {\n return this.templateSrv.replace(param, options.scopedVars);\n }\n });\n });\n }\n\n}\n\nfunction bindFunctionDefs(functionDefs, category) {\n var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name');\n var aggFuncDefs = _.filter(functionDefs, function(func) {\n return _.includes(aggregationFunctions, func.def.name);\n });\n\n return _.map(aggFuncDefs, function(func) {\n var funcInstance = metricFunctions.createFuncInstance(func.def, func.params);\n return funcInstance.bindFunction(dataProcessor.metricFunctions);\n });\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n return _.map(timeseries_data, timeseries => {\n if (timeseries.datapoints.length > options.maxDataPoints) {\n timeseries.datapoints = dataProcessor\n .groupBy(options.interval, dataProcessor.AVERAGE, timeseries.datapoints);\n }\n return timeseries;\n });\n}\n\nfunction formatMetric(metricObj) {\n return {\n text: metricObj.name,\n expandable: false\n };\n}\n\n/**\n * Custom formatter for template variables.\n * Default Grafana \"regex\" formatter returns\n * value1|value2\n * This formatter returns\n * (value1|value2)\n * This format needed for using in complex regex with\n * template variables, for example\n * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait\n */\nfunction zabbixTemplateFormat(value) {\n if (typeof value === 'string') {\n return utils.escapeRegex(value);\n }\n\n var escapedValues = _.map(value, utils.escapeRegex);\n return '(' + escapedValues.join('|') + ')';\n}\n\n/**\n * If template variables are used in request, replace it using regex format\n * and wrap with '/' for proper multi-value work. Example:\n * $variable selected as a, b, c\n * We use filter $variable\n * $variable -> a|b|c -> /a|b|c/\n * /$variable/ -> /a|b|c/ -> /a|b|c/\n */\nfunction replaceTemplateVars(templateSrv, target, scopedVars) {\n var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat);\n if (target !== replacedTarget && !utils.isRegex(replacedTarget)) {\n replacedTarget = '/^' + replacedTarget + '$/';\n }\n return replacedTarget;\n}\n\nfunction extractText(str, pattern, useCaptureGroups) {\n let extractPattern = new RegExp(pattern);\n let extractedValue = extractPattern.exec(str);\n if (extractedValue) {\n if (useCaptureGroups) {\n extractedValue = extractedValue[1];\n } else {\n extractedValue = extractedValue[0];\n }\n }\n return extractedValue;\n}\n\n// Apply function one by one:\n// sequence([a(), b(), c()]) = c(b(a()));\nfunction sequence(funcsArray) {\n return function(result) {\n for (var i = 0; i < funcsArray.length; i++) {\n result = funcsArray[i].call(this, result);\n }\n return result;\n };\n}\n\nexport {ZabbixAPIDatasource, zabbixTemplateFormat};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.includes) {_.includes = _.contains;}\nif (!_.keyBy) {_.keyBy = _.indexBy;}\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbix.js b/dist/datasource-zabbix/zabbix.js index 2f20188a2..c1e5272d5 100644 --- a/dist/datasource-zabbix/zabbix.js +++ b/dist/datasource-zabbix/zabbix.js @@ -194,14 +194,14 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za * Find group, host, app or item by given name. * @param list list of groups, apps or other * @param name visible name - * @return array with finded element or undefined + * @return array with finded element or empty array */ function findByName(list, name) { var finded = _.find(list, { 'name': name }); if (finded) { return [finded]; } else { - return undefined; + return []; } } @@ -211,14 +211,14 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za * which return only first finded. * @param {[type]} list list of elements * @param {[type]} name app name - * @return {[type]} array with finded element or undefined + * @return {[type]} array with finded element or empty array */ function filterByName(list, name) { var finded = _.filter(list, { 'name': name }); if (finded) { return finded; } else { - return undefined; + return []; } } diff --git a/dist/datasource-zabbix/zabbix.js.map b/dist/datasource-zabbix/zabbix.js.map index 456ee8f70..35beb3ead 100644 --- a/dist/datasource-zabbix/zabbix.js.map +++ b/dist/datasource-zabbix/zabbix.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/zabbix.js"],"names":["ZabbixFactory","zabbixAPIService","ZabbixCachingProxy","Zabbix","url","username","password","basicAuth","withCredentials","cacheTTL","ZabbixAPI","zabbixAPI","cacheOptions","enabled","ttl","cachingProxy","getHistory","bind","getTrend","getEvents","getAcknowledges","getITService","getSLA","getVersion","login","target","options","parts","filters","_","map","p","filter","getItems","getGroups","groupFilter","getAllGroups","then","findByFilter","groups","groupids","getHosts","hostFilter","getAllHosts","hosts","hostids","getApps","appFilter","filterByQuery","apps","appFilterEmpty","undefined","itemtype","appids","showDisabledItems","items","itemFilter","getAllItems","showTriggers","hideHostsInMaintenance","promises","Promise","all","filteredGroups","results","filteredHosts","filteredApps","query","applicationids","flatten","getTriggers","findByName","list","name","finded","find","filterByName","filterByRegex","regex","filterPattern","utils","buildRegex","zbx_obj","test","isRegex","angular","module","factory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA;AACA;;AAEA;AACA,WAASA,aAAT,CAAuBC,gBAAvB,EAAyCC,kBAAzC,EAA6D;AAAA,QAErDC,MAFqD;AAGzD,sBAAYC,GAAZ,EAAiBC,QAAjB,EAA2BC,QAA3B,EAAqCC,SAArC,EAAgDC,eAAhD,EAAiEC,QAAjE,EAA2E;AAAA;;AAEzE;AACA,YAAIC,YAAYT,gBAAhB;AACA,aAAKU,SAAL,GAAiB,IAAID,SAAJ,CAAcN,GAAd,EAAmBC,QAAnB,EAA6BC,QAA7B,EAAuCC,SAAvC,EAAkDC,eAAlD,CAAjB;;AAEA;AACA,YAAII,eAAe;AACjBC,mBAAS,IADQ;AAEjBC,eAAKL;AAFY,SAAnB;AAIA,aAAKM,YAAL,GAAoB,IAAIb,kBAAJ,CAAuB,KAAKS,SAA5B,EAAuCC,YAAvC,CAApB;;AAEA;AACA,aAAKI,UAAL,GAAkB,KAAKD,YAAL,CAAkBC,UAAlB,CAA6BC,IAA7B,CAAkC,KAAKF,YAAvC,CAAlB;;AAEA,aAAKG,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F,aAFrB","file":"zabbix.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport * as utils from './utils';\nimport './zabbixAPI.service.js';\nimport './zabbixCachingProxy.service.js';\n\n// Use factory() instead service() for multiple data sources support.\n// Each Zabbix data source instance should initialize its own API instance.\n\n/** @ngInject */\nfunction ZabbixFactory(zabbixAPIService, ZabbixCachingProxy) {\n\n class Zabbix {\n constructor(url, username, password, basicAuth, withCredentials, cacheTTL) {\n\n // Initialize Zabbix API\n var ZabbixAPI = zabbixAPIService;\n this.zabbixAPI = new ZabbixAPI(url, username, password, basicAuth, withCredentials);\n\n // Initialize caching proxy for requests\n let cacheOptions = {\n enabled: true,\n ttl: cacheTTL\n };\n this.cachingProxy = new ZabbixCachingProxy(this.zabbixAPI, cacheOptions);\n\n // Proxy methods\n this.getHistory = this.cachingProxy.getHistory.bind(this.cachingProxy);\n\n this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);\n this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);\n this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);\n this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);\n this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);\n this.getVersion = this.zabbixAPI.getVersion.bind(this.zabbixAPI);\n this.login = this.zabbixAPI.login.bind(this.zabbixAPI);\n }\n\n getItemsFromTarget(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n let filters = _.map(parts, p => target[p].filter);\n return this.getItems(...filters, options);\n }\n\n getAllGroups() {\n return this.cachingProxy.getGroups();\n }\n\n getGroups(groupFilter) {\n return this.getAllGroups()\n .then(groups => findByFilter(groups, groupFilter));\n }\n\n /**\n * Get list of host belonging to given groups.\n */\n getAllHosts(groupFilter) {\n return this.getGroups(groupFilter)\n .then(groups => {\n let groupids = _.map(groups, 'groupid');\n return this.cachingProxy.getHosts(groupids);\n });\n }\n\n getHosts(groupFilter, hostFilter) {\n return this.getAllHosts(groupFilter)\n .then(hosts => findByFilter(hosts, hostFilter));\n }\n\n /**\n * Get list of applications belonging to given groups and hosts.\n */\n getAllApps(groupFilter, hostFilter) {\n return this.getHosts(groupFilter, hostFilter)\n .then(hosts => {\n let hostids = _.map(hosts, 'hostid');\n return this.cachingProxy.getApps(hostids);\n });\n }\n\n getApps(groupFilter, hostFilter, appFilter) {\n return this.getHosts(groupFilter, hostFilter)\n .then(hosts => {\n let hostids = _.map(hosts, 'hostid');\n if (appFilter) {\n return this.cachingProxy.getApps(hostids)\n .then(apps => filterByQuery(apps, appFilter));\n } else {\n return {\n appFilterEmpty: true,\n hostids: hostids\n };\n }\n });\n }\n\n getAllItems(groupFilter, hostFilter, appFilter, options = {}) {\n return this.getApps(groupFilter, hostFilter, appFilter)\n .then(apps => {\n if (apps.appFilterEmpty) {\n return this.cachingProxy.getItems(apps.hostids, undefined, options.itemtype);\n } else {\n let appids = _.map(apps, 'applicationid');\n return this.cachingProxy.getItems(undefined, appids, options.itemtype);\n }\n })\n .then(items => {\n if (!options.showDisabledItems) {\n items = _.filter(items, {'status': '0'});\n }\n return items;\n });\n }\n\n getItems(groupFilter, hostFilter, appFilter, itemFilter, options = {}) {\n return this.getAllItems(groupFilter, hostFilter, appFilter, options)\n .then(items => filterByQuery(items, itemFilter));\n }\n\n /**\n * Build query - convert target filters to array of Zabbix items\n */\n getTriggers(groupFilter, hostFilter, appFilter, showTriggers, hideHostsInMaintenance) {\n let promises = [\n this.getGroups(groupFilter),\n this.getHosts(groupFilter, hostFilter),\n this.getApps(groupFilter, hostFilter, appFilter)\n ];\n\n return Promise.all(promises)\n .then(results => {\n let filteredGroups = results[0];\n let filteredHosts = results[1];\n let filteredApps = results[2];\n let query = {};\n\n if (appFilter) {\n query.applicationids = _.flatten(_.map(filteredApps, 'applicationid'));\n }\n if (hostFilter) {\n query.hostids = _.map(filteredHosts, 'hostid');\n }\n if (groupFilter) {\n query.groupids = _.map(filteredGroups, 'groupid');\n }\n\n return query;\n }).then(query => {\n return this.zabbixAPI\n .getTriggers(query.groupids, query.hostids, query.applicationids, showTriggers, hideHostsInMaintenance);\n });\n }\n }\n\n return Zabbix;\n}\n\nangular\n .module('grafana.services')\n .factory('Zabbix', ZabbixFactory);\n\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Find group, host, app or item by given name.\n * @param list list of groups, apps or other\n * @param name visible name\n * @return array with finded element or undefined\n */\nfunction findByName(list, name) {\n var finded = _.find(list, {'name': name});\n if (finded) {\n return [finded];\n } else {\n return undefined;\n }\n}\n\n/**\n * Different hosts can contains applications and items with same name.\n * For this reason use _.filter, which return all elements instead _.find,\n * which return only first finded.\n * @param {[type]} list list of elements\n * @param {[type]} name app name\n * @return {[type]} array with finded element or undefined\n */\nfunction filterByName(list, name) {\n var finded = _.filter(list, {'name': name});\n if (finded) {\n return finded;\n } else {\n return undefined;\n }\n}\n\nfunction filterByRegex(list, regex) {\n var filterPattern = utils.buildRegex(regex);\n return _.filter(list, function (zbx_obj) {\n return filterPattern.test(zbx_obj.name);\n });\n}\n\nfunction findByFilter(list, filter) {\n if (utils.isRegex(filter)) {\n return filterByRegex(list, filter);\n } else {\n return findByName(list, filter);\n }\n}\n\nfunction filterByQuery(list, filter) {\n if (utils.isRegex(filter)) {\n return filterByRegex(list, filter);\n } else {\n return filterByName(list, filter);\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/zabbix.js"],"names":["ZabbixFactory","zabbixAPIService","ZabbixCachingProxy","Zabbix","url","username","password","basicAuth","withCredentials","cacheTTL","ZabbixAPI","zabbixAPI","cacheOptions","enabled","ttl","cachingProxy","getHistory","bind","getTrend","getEvents","getAcknowledges","getITService","getSLA","getVersion","login","target","options","parts","filters","_","map","p","filter","getItems","getGroups","groupFilter","getAllGroups","then","findByFilter","groups","groupids","getHosts","hostFilter","getAllHosts","hosts","hostids","getApps","appFilter","filterByQuery","apps","appFilterEmpty","undefined","itemtype","appids","showDisabledItems","items","itemFilter","getAllItems","showTriggers","hideHostsInMaintenance","promises","Promise","all","filteredGroups","results","filteredHosts","filteredApps","query","applicationids","flatten","getTriggers","findByName","list","name","finded","find","filterByName","filterByRegex","regex","filterPattern","utils","buildRegex","zbx_obj","test","isRegex","angular","module","factory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA;AACA;;AAEA;AACA,WAASA,aAAT,CAAuBC,gBAAvB,EAAyCC,kBAAzC,EAA6D;AAAA,QAErDC,MAFqD;AAGzD,sBAAYC,GAAZ,EAAiBC,QAAjB,EAA2BC,QAA3B,EAAqCC,SAArC,EAAgDC,eAAhD,EAAiEC,QAAjE,EAA2E;AAAA;;AAEzE;AACA,YAAIC,YAAYT,gBAAhB;AACA,aAAKU,SAAL,GAAiB,IAAID,SAAJ,CAAcN,GAAd,EAAmBC,QAAnB,EAA6BC,QAA7B,EAAuCC,SAAvC,EAAkDC,eAAlD,CAAjB;;AAEA;AACA,YAAII,eAAe;AACjBC,mBAAS,IADQ;AAEjBC,eAAKL;AAFY,SAAnB;AAIA,aAAKM,YAAL,GAAoB,IAAIb,kBAAJ,CAAuB,KAAKS,SAA5B,EAAuCC,YAAvC,CAApB;;AAEA;AACA,aAAKI,UAAL,GAAkB,KAAKD,YAAL,CAAkBC,UAAlB,CAA6BC,IAA7B,CAAkC,KAAKF,YAAvC,CAAlB;;AAEA,aAAKG,QAAL,GAAgB,KAAKP,SAAL,CAAeO,QAAf,CAAwBD,IAAxB,CAA6B,KAAKN,SAAlC,CAAhB;AACA,aAAKQ,SAAL,GAAiB,KAAKR,SAAL,CAAeQ,SAAf,CAAyBF,IAAzB,CAA8B,KAAKN,SAAnC,CAAjB;AACA,aAAKS,eAAL,GAAuB,KAAKT,SAAL,CAAeS,eAAf,CAA+BH,IAA/B,CAAoC,KAAKN,SAAzC,CAAvB;AACA,aAAKU,YAAL,GAAoB,KAAKV,SAAL,CAAeU,YAAf,CAA4BJ,IAA5B,CAAiC,KAAKN,SAAtC,CAApB;AACA,aAAKW,MA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,EAA6BM,KAA7B,EAAoC;AAClC,QAAIC,gBAAgBC,MAAMC,UAAN,CAAiBH,KAAjB,CAApB;AACA,WAAOjD,EAAEG,MAAF,CAASwC,IAAT,EAAe,UAAUU,OAAV,EAAmB;AACvC,aAAOH,cAAcI,IAAd,CAAmBD,QAAQT,IAA3B,CAAP;AACD,KAFM,CAAP;AAGD;;AAED,WAASnC,YAAT,CAAsBkC,IAAtB,EAA4BxC,MAA5B,EAAoC;AAClC,QAAIgD,MAAMI,OAAN,CAAcpD,MAAd,CAAJ,EAA2B;AACzB,aAAO6C,cAAcL,IAAd,EAAoBxC,MAApB,CAAP;AACD,KAFD,MAEO;AACL,aAAOuC,WAAWC,IAAX,EAAiBxC,MAAjB,CAAP;AACD;AACF;;AAED,WAASgB,aAAT,CAAuBwB,IAAvB,EAA6BxC,MAA7B,EAAqC;AACnC,QAAIgD,MAAMI,OAAN,CAAcpD,MAAd,CAAJ,EAA2B;AACzB,aAAO6C,cAAcL,IAAd,EAAoBxC,MAApB,CAAP;AACD,KAFD,MAEO;AACL,aAAO4C,aAAaJ,IAAb,EAAmBxC,MAAnB,CAAP;AACD;AACF;;;AAxNMqD,a;;AACAxD,O;;AACKmD,W;;;;;;;;;;;;;;;;;;;;;AA2JZK,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,QAFX,EAEqBvF,aAFrB","file":"zabbix.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport * as utils from './utils';\nimport './zabbixAPI.service.js';\nimport './zabbixCachingProxy.service.js';\n\n// Use factory() instead service() for multiple data sources support.\n// Each Zabbix data source instance should initialize its own API instance.\n\n/** @ngInject */\nfunction ZabbixFactory(zabbixAPIService, ZabbixCachingProxy) {\n\n class Zabbix {\n constructor(url, username, password, basicAuth, withCredentials, cacheTTL) {\n\n // Initialize Zabbix API\n var ZabbixAPI = zabbixAPIService;\n this.zabbixAPI = new ZabbixAPI(url, username, password, basicAuth, withCredentials);\n\n // Initialize caching proxy for requests\n let cacheOptions = {\n enabled: true,\n ttl: cacheTTL\n };\n this.cachingProxy = new ZabbixCachingProxy(this.zabbixAPI, cacheOptions);\n\n // Proxy methods\n this.getHistory = this.cachingProxy.getHistory.bind(this.cachingProxy);\n\n this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);\n this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);\n this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);\n this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);\n this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);\n this.getVersion = this.zabbixAPI.getVersion.bind(this.zabbixAPI);\n this.login = this.zabbixAPI.login.bind(this.zabbixAPI);\n }\n\n getItemsFromTarget(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n let filters = _.map(parts, p => target[p].filter);\n return this.getItems(...filters, options);\n }\n\n getAllGroups() {\n return this.cachingProxy.getGroups();\n }\n\n getGroups(groupFilter) {\n return this.getAllGroups()\n .then(groups => findByFilter(groups, groupFilter));\n }\n\n /**\n * Get list of host belonging to given groups.\n */\n getAllHosts(groupFilter) {\n return this.getGroups(groupFilter)\n .then(groups => {\n let groupids = _.map(groups, 'groupid');\n return this.cachingProxy.getHosts(groupids);\n });\n }\n\n getHosts(groupFilter, hostFilter) {\n return this.getAllHosts(groupFilter)\n .then(hosts => findByFilter(hosts, hostFilter));\n }\n\n /**\n * Get list of applications belonging to given groups and hosts.\n */\n getAllApps(groupFilter, hostFilter) {\n return this.getHosts(groupFilter, hostFilter)\n .then(hosts => {\n let hostids = _.map(hosts, 'hostid');\n return this.cachingProxy.getApps(hostids);\n });\n }\n\n getApps(groupFilter, hostFilter, appFilter) {\n return this.getHosts(groupFilter, hostFilter)\n .then(hosts => {\n let hostids = _.map(hosts, 'hostid');\n if (appFilter) {\n return this.cachingProxy.getApps(hostids)\n .then(apps => filterByQuery(apps, appFilter));\n } else {\n return {\n appFilterEmpty: true,\n hostids: hostids\n };\n }\n });\n }\n\n getAllItems(groupFilter, hostFilter, appFilter, options = {}) {\n return this.getApps(groupFilter, hostFilter, appFilter)\n .then(apps => {\n if (apps.appFilterEmpty) {\n return this.cachingProxy.getItems(apps.hostids, undefined, options.itemtype);\n } else {\n let appids = _.map(apps, 'applicationid');\n return this.cachingProxy.getItems(undefined, appids, options.itemtype);\n }\n })\n .then(items => {\n if (!options.showDisabledItems) {\n items = _.filter(items, {'status': '0'});\n }\n return items;\n });\n }\n\n getItems(groupFilter, hostFilter, appFilter, itemFilter, options = {}) {\n return this.getAllItems(groupFilter, hostFilter, appFilter, options)\n .then(items => filterByQuery(items, itemFilter));\n }\n\n /**\n * Build query - convert target filters to array of Zabbix items\n */\n getTriggers(groupFilter, hostFilter, appFilter, showTriggers, hideHostsInMaintenance) {\n let promises = [\n this.getGroups(groupFilter),\n this.getHosts(groupFilter, hostFilter),\n this.getApps(groupFilter, hostFilter, appFilter)\n ];\n\n return Promise.all(promises)\n .then(results => {\n let filteredGroups = results[0];\n let filteredHosts = results[1];\n let filteredApps = results[2];\n let query = {};\n\n if (appFilter) {\n query.applicationids = _.flatten(_.map(filteredApps, 'applicationid'));\n }\n if (hostFilter) {\n query.hostids = _.map(filteredHosts, 'hostid');\n }\n if (groupFilter) {\n query.groupids = _.map(filteredGroups, 'groupid');\n }\n\n return query;\n }).then(query => {\n return this.zabbixAPI\n .getTriggers(query.groupids, query.hostids, query.applicationids, showTriggers, hideHostsInMaintenance);\n });\n }\n }\n\n return Zabbix;\n}\n\nangular\n .module('grafana.services')\n .factory('Zabbix', ZabbixFactory);\n\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Find group, host, app or item by given name.\n * @param list list of groups, apps or other\n * @param name visible name\n * @return array with finded element or empty array\n */\nfunction findByName(list, name) {\n var finded = _.find(list, {'name': name});\n if (finded) {\n return [finded];\n } else {\n return [];\n }\n}\n\n/**\n * Different hosts can contains applications and items with same name.\n * For this reason use _.filter, which return all elements instead _.find,\n * which return only first finded.\n * @param {[type]} list list of elements\n * @param {[type]} name app name\n * @return {[type]} array with finded element or empty array\n */\nfunction filterByName(list, name) {\n var finded = _.filter(list, {'name': name});\n if (finded) {\n return finded;\n } else {\n return [];\n }\n}\n\nfunction filterByRegex(list, regex) {\n var filterPattern = utils.buildRegex(regex);\n return _.filter(list, function (zbx_obj) {\n return filterPattern.test(zbx_obj.name);\n });\n}\n\nfunction findByFilter(list, filter) {\n if (utils.isRegex(filter)) {\n return filterByRegex(list, filter);\n } else {\n return findByName(list, filter);\n }\n}\n\nfunction filterByQuery(list, filter) {\n if (utils.isRegex(filter)) {\n return filterByRegex(list, filter);\n } else {\n return filterByName(list, filter);\n }\n}\n"]} \ No newline at end of file diff --git a/dist/test/datasource-zabbix/datasource.js b/dist/test/datasource-zabbix/datasource.js index 2ecc64a39..96f99d944 100644 --- a/dist/test/datasource-zabbix/datasource.js +++ b/dist/test/datasource-zabbix/datasource.js @@ -378,7 +378,7 @@ var ZabbixAPIDatasource = function () { } return result.then(function (metrics) { - return metrics.map(formatMetric); + return _lodash2.default.map(metrics, formatMetric); }); } diff --git a/dist/test/datasource-zabbix/zabbix.js b/dist/test/datasource-zabbix/zabbix.js index a34593f74..7f219c001 100644 --- a/dist/test/datasource-zabbix/zabbix.js +++ b/dist/test/datasource-zabbix/zabbix.js @@ -214,14 +214,14 @@ _angular2.default.module('grafana.services').factory('Zabbix', ZabbixFactory); * Find group, host, app or item by given name. * @param list list of groups, apps or other * @param name visible name - * @return array with finded element or undefined + * @return array with finded element or empty array */ function findByName(list, name) { var finded = _lodash2.default.find(list, { 'name': name }); if (finded) { return [finded]; } else { - return undefined; + return []; } } @@ -231,14 +231,14 @@ function findByName(list, name) { * which return only first finded. * @param {[type]} list list of elements * @param {[type]} name app name - * @return {[type]} array with finded element or undefined + * @return {[type]} array with finded element or empty array */ function filterByName(list, name) { var finded = _lodash2.default.filter(list, { 'name': name }); if (finded) { return finded; } else { - return undefined; + return []; } } diff --git a/src/datasource-zabbix/datasource.js b/src/datasource-zabbix/datasource.js index 55e3bf8b9..36d35ee6d 100644 --- a/src/datasource-zabbix/datasource.js +++ b/src/datasource-zabbix/datasource.js @@ -314,7 +314,7 @@ class ZabbixAPIDatasource { } return result.then(metrics => { - return metrics.map(formatMetric); + return _.map(metrics, formatMetric); }); } diff --git a/src/datasource-zabbix/zabbix.js b/src/datasource-zabbix/zabbix.js index 23e91f2f8..5d034f302 100644 --- a/src/datasource-zabbix/zabbix.js +++ b/src/datasource-zabbix/zabbix.js @@ -165,14 +165,14 @@ angular * Find group, host, app or item by given name. * @param list list of groups, apps or other * @param name visible name - * @return array with finded element or undefined + * @return array with finded element or empty array */ function findByName(list, name) { var finded = _.find(list, {'name': name}); if (finded) { return [finded]; } else { - return undefined; + return []; } } @@ -182,14 +182,14 @@ function findByName(list, name) { * which return only first finded. * @param {[type]} list list of elements * @param {[type]} name app name - * @return {[type]} array with finded element or undefined + * @return {[type]} array with finded element or empty array */ function filterByName(list, name) { var finded = _.filter(list, {'name': name}); if (finded) { return finded; } else { - return undefined; + return []; } }