From e241a5f99006b462cefe1fa15292267e8a0d2129 Mon Sep 17 00:00:00 2001 From: Alexander Zobnin Date: Tue, 18 Apr 2017 12:09:25 +0300 Subject: [PATCH] Able to use both time and range for trends config, #364 --- dist/datasource-zabbix/datasource.js | 48 +++++++++++------- dist/datasource-zabbix/datasource.js.map | 2 +- dist/datasource-zabbix/partials/config.html | 55 +++++++++++++-------- dist/test/datasource-zabbix/datasource.js | 48 +++++++++++------- src/datasource-zabbix/datasource.js | 9 +++- src/datasource-zabbix/partials/config.html | 55 +++++++++++++-------- 6 files changed, 137 insertions(+), 80 deletions(-) diff --git a/dist/datasource-zabbix/datasource.js b/dist/datasource-zabbix/datasource.js index 73029fb9e..ae76ce417 100644 --- a/dist/datasource-zabbix/datasource.js +++ b/dist/datasource-zabbix/datasource.js @@ -215,6 +215,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', // Use trends instead history since specified time this.trends = instanceSettings.jsonData.trends; this.trendsFrom = instanceSettings.jsonData.trendsFrom || '7d'; + this.trendsRange = instanceSettings.jsonData.trendsRange || '4d'; // Set cache update interval var ttl = instanceSettings.jsonData.cacheTTL || '1h'; @@ -251,7 +252,10 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', var timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000); var useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000); - var useTrends = timeFrom <= useTrendsFrom && this.trends; + var useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000); + var useTrends = this.trends && (timeFrom <= useTrendsFrom || timeTo - timeFrom >= useTrendsRange); + + console.log(useTrends); // Get alerts for current panel if (this.alertingEnabled) { @@ -334,10 +338,12 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', var getHistoryPromise = void 0; if (useTrends) { - var valueType = _this2.getTrendValueType(target); - getHistoryPromise = _this2.zabbix.getTrend(items, timeFrom, timeTo).then(function (history) { - return responseHandler.handleTrends(history, items, valueType); - }); + (function () { + var valueType = _this2.getTrendValueType(target); + getHistoryPromise = _this2.zabbix.getTrend(items, timeFrom, timeTo).then(function (history) { + return responseHandler.handleTrends(history, items, valueType); + }); + })(); } else { // Use history getHistoryPromise = _this2.zabbix.getHistory(items, timeFrom, timeTo).then(function (history) { @@ -384,18 +390,20 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', // Apply aggregations if (aggregationFunctions.length) { - var dp = _.map(timeseries_data, 'datapoints'); - dp = sequence(aggregationFunctions)(dp); + (function () { + var dp = _.map(timeseries_data, 'datapoints'); + dp = sequence(aggregationFunctions)(dp); - var aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name'); - var lastAgg = _.findLast(target.functions, function (func) { - return _.includes(aggFuncNames, func.def.name); - }); + var aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name'); + var lastAgg = _.findLast(target.functions, function (func) { + return _.includes(aggFuncNames, func.def.name); + }); - timeseries_data = [{ - target: lastAgg.text, - datapoints: dp - }]; + timeseries_data = [{ + target: lastAgg.text, + datapoints: dp + }]; + })(); } // Apply alias functions @@ -415,10 +423,12 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', return func.def.name === 'timeShift'; }); if (timeShiftFunc) { - var shift = timeShiftFunc.params[0]; - _.forEach(timeseries_data, function (series) { - series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints); - }); + (function () { + var shift = timeShiftFunc.params[0]; + _.forEach(timeseries_data, function (series) { + series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints); + }); + })(); } } }, { diff --git a/dist/datasource-zabbix/datasource.js.map b/dist/datasource-zabbix/datasource.js.map index 68e341694..d108da05e 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","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","url","basicAuth","withCredentials","username","jsonData","password","trends","trendsFrom","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","zabbix","partial","timeFrom","Math","ceil","parse","range","from","timeTo","to","useTrendsFrom","useTrends","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","cloneDeep","replaceTargetVariables","timeFunctions","functions","time_from","time_to","mode","migrate","queryNumericData","queryTextData","itservice","slaProperty","getSLA","serviceid","handleSLAResponse","slaObject","Promise","all","flatten","data","itemtype","getItemsFromTarget","getHistoryPromise","valueType","getTrendValueType","getTrend","items","handleTrends","history","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","find","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","series","unShiftTimeSeries","convertHistory","point","textFilter","clock","round","ns","resolve","zabbixVersion","getVersion","version","login","status","title","message","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","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","hosts","formatted_acknowledges","formatAcknowledges","time","objectid","enabled_targets","getPanelItems","results","itemids","getAlerts","firedTriggers","p","param","toString","contains","indexBy"],"mappings":";;;;;;;;;;;;;AAyeA,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;AACD,KAHM,CAAP;AAID;;AAED,WAASa,gBAAT,CAA0BC,eAA1B,EAA2CC,OAA3C,EAAoD;AAClD,WAAOjB,EAAEC,GAAF,CAAMe,eAAN,EAAuB,sBAAc;AAC1C,UAAIE,WAAWC,UAAX,CAAsBC,MAAtB,GAA+BH,QAAQI,aAA3C,EAA0D;AACxDH,mBAAWC,UAAX,GAAwBL,cACrBQ,OADqB,CACbL,QAAQM,QADK,EACKT,cAAcU,OADnB,EAC4BN,WAAWC,UADvC,CAAxB;AAED;AACD,aAAOD,UAAP;AACD,KANM,CAAP;AAOD;;AAED,WAASO,YAAT,CAAsBC,SAAtB,EAAiC;AAC/B,WAAO;AACLC,YAAMD,UAAUjB,IADX;AAELmB,kBAAY;AAFP,KAAP;AAID;;AAED;;;;;;;;;;AAUA,WAASC,oBAAT,CAA8BC,KAA9B,EAAqC;AACnC,QAAI,OAAOA,KAAP,K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AAV,EAAkB,aAAlB,EAAiC,MAAjC,CAAZ;AACAtL,cAAEgH,OAAF,CAAUsE,KAAV,EAAiB,aAAK;AACpB,kBAAIjJ,OAAOgM,CAAP,KAAahM,OAAOgM,CAAP,EAAUhO,MAA3B,EAAmC;AACjCgC,uBAAOgM,CAAP,EAAUhO,MAAV,GAAmB,OAAK8B,mBAAL,CAAyBE,OAAOgM,CAAP,EAAUhO,MAAnC,EAA2CY,QAAQqB,UAAnD,CAAnB;AACD;AACF,aAJD;AAKAD,mBAAOoI,UAAP,GAAoB,KAAKtI,mBAAL,CAAyBE,OAAOoI,UAAhC,EAA4CxJ,QAAQqB,UAApD,CAApB;;AAEAtC,cAAEgH,OAAF,CAAU3E,OAAOkF,SAAjB,EAA4B,gBAAQ;AAClCjH,mBAAKM,MAAL,GAAcZ,EAAEC,GAAF,CAAMK,KAAKM,MAAX,EAAmB,iBAAS;AACxC,oBAAI,OAAO0N,KAAP,KAAiB,QAArB,EAA+B;AAC7B,yBAAO,CAAC,OAAKlM,WAAL,CAAiBI,OAAjB,CAAyB8L,MAAMC,QAAN,EAAzB,EAA2CtN,QAAQqB,UAAnD,CAAR;AACD,iBAFD,MAEO;AACL,yBAAO,OAAKF,WAAL,CAAiBI,OAAjB,CAAyB8L,KAAzB,EAAgCrN,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;;;;qCA8GKkC,mB;;sCAAqB3C,oB;;AAE7B;AACA,UAAI,CAAC7B,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAEwO,QAAf;AAAyB;AAC3C,UAAI,CAACxO,EAAEmN,KAAP,EAAc;AAACnN,UAAEmN,KAAF,GAAUnN,EAAEyO,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["import _ 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 './zabbixAlerting.service.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n /** @ngInject */\n constructor(instanceSettings, templateSrv, alertSrv, dashboardSrv, zabbixAlertingSrv, Zabbix) {\n this.templateSrv = templateSrv;\n this.alertSrv = alertSrv;\n this.dashboardSrv = dashboardSrv;\n this.zabbixAlertingSrv = zabbixAlertingSrv;\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 // Alerting options\n this.alertingEnabled = instanceSettings.jsonData.alerting;\n this.addThresholds = instanceSettings.jsonData.addThresholds;\n this.alertingMinSeverity = instanceSettings.jsonData.alertingMinSeverity || 2;\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 // Get alerts for current panel\n if (this.alertingEnabled) {\n this.alertQuery(options).then(alert => {\n this.zabbixAlertingSrv.setPanelAlertState(options.panelId, alert.state);\n\n this.zabbixAlertingSrv.removeZabbixThreshold(options.panelId);\n if (this.addThresholds) {\n _.forEach(alert.thresholds, threshold => {\n this.zabbixAlertingSrv.setPanelThreshold(options.panelId, threshold);\n });\n }\n });\n }\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 .catch(error => {\n console.log(error);\n return [];\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 [\n value,\n point.clock * 1000 + Math.round(point.ns / 1000000)\n ];\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 /**\n * Get triggers and its details for panel's targets\n * Returns alert state ('ok' if no fired triggers, or 'alerting' if at least 1 trigger is fired)\n * or empty object if no related triggers are finded.\n */\n alertQuery(options) {\n let enabled_targets = filterEnabledTargets(options.targets);\n let getPanelItems = _.map(enabled_targets, target => {\n return this.zabbix.getItemsFromTarget(target, {itemtype: 'num'});\n });\n\n return Promise.all(getPanelItems)\n .then(results => {\n let items = _.flatten(results);\n let itemids = _.map(items, 'itemid');\n\n return this.zabbix.getAlerts(itemids);\n })\n .then(triggers => {\n triggers = _.filter(triggers, trigger => {\n return trigger.priority >= this.alertingMinSeverity;\n });\n\n if (!triggers || triggers.length === 0) {\n return {};\n }\n\n let state = 'ok';\n\n let firedTriggers = _.filter(triggers, {value: '1'});\n if (firedTriggers.length) {\n state = 'alerting';\n }\n\n let thresholds = _.map(triggers, trigger => {\n return getTriggerThreshold(trigger.expression);\n });\n\n return {\n panelId: options.panelId,\n state: state,\n thresholds: thresholds\n };\n });\n }\n\n // Replace template variables\n replaceTargetVariables(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n _.forEach(parts, 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 = _.map(func.params, 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\nfunction filterEnabledTargets(targets) {\n return _.filter(targets, target => {\n return !(target.hide || !target.group || !target.host || !target.item);\n });\n}\n\nfunction getTriggerThreshold(expression) {\n let thresholdPattern = /.*[<>]([\\d\\.]+)/;\n let finded_thresholds = expression.match(thresholdPattern);\n if (finded_thresholds && finded_thresholds.length >= 2) {\n let threshold = finded_thresholds[1];\n threshold = Number(threshold);\n return threshold;\n } else {\n return null;\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","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","url","basicAuth","withCredentials","username","jsonData","password","trends","trendsFrom","trendsRange","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","zabbix","partial","timeFrom","Math","ceil","parse","range","from","timeTo","to","useTrendsFrom","useTrendsRange","useTrends","console","log","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","cloneDeep","replaceTargetVariables","timeFunctions","functions","time_from","time_to","mode","migrate","queryNumericData","queryTextData","itservice","slaProperty","getSLA","serviceid","handleSLAResponse","slaObject","Promise","all","flatten","data","itemtype","getItemsFromTarget","getHistoryPromise","valueType","getTrendValueType","getTrend","items","handleTrends","history","getHistory","handleHistory","applyDataProcessingFunctions","catch","error","trendFunctions","trendValueFunc","find","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","series","unShiftTimeSeries","convertHistory","point","textFilter","clock","round","ns","resolve","zabbixVersion","getVersion","version","login","status","title","message","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","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","hosts","formatted_acknowledges","formatAcknowledges","time","objectid","enabled_targets","getPanelItems","results","itemids","getAlerts","firedTriggers","p","param","toString","contains","indexBy"],"mappings":";;;;;;;;;;;;;AAgfA,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,eA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AAL,CAAyBE,OAAOsI,UAAhC,EAA4C1J,QAAQqB,UAApD,CAApB;;AAEAtC,cAAEoH,OAAF,CAAU/E,OAAOsF,SAAjB,EAA4B,gBAAQ;AAClCrH,mBAAKM,MAAL,GAAcZ,EAAEC,GAAF,CAAMK,KAAKM,MAAX,EAAmB,iBAAS;AACxC,oBAAI,OAAO4N,KAAP,KAAiB,QAArB,EAA+B;AAC7B,yBAAO,CAAC,OAAKpM,WAAL,CAAiBI,OAAjB,CAAyBgM,MAAMC,QAAN,EAAzB,EAA2CxN,QAAQqB,UAAnD,CAAR;AACD,iBAFD,MAEO;AACL,yBAAO,OAAKF,WAAL,CAAiBI,OAAjB,CAAyBgM,KAAzB,EAAgCvN,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;;;;qCA8GKkC,mB;;sCAAqB3C,oB;;AAE7B;AACA,UAAI,CAAC7B,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE0O,QAAf;AAAyB;AAC3C,UAAI,CAAC1O,EAAEqN,KAAP,EAAc;AAACrN,UAAEqN,KAAF,GAAUrN,EAAE2O,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["import _ 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 './zabbixAlerting.service.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n /** @ngInject */\n constructor(instanceSettings, templateSrv, alertSrv, dashboardSrv, zabbixAlertingSrv, Zabbix) {\n this.templateSrv = templateSrv;\n this.alertSrv = alertSrv;\n this.dashboardSrv = dashboardSrv;\n this.zabbixAlertingSrv = zabbixAlertingSrv;\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 this.trendsRange = instanceSettings.jsonData.trendsRange || '4d';\n\n // Set cache update interval\n var ttl = instanceSettings.jsonData.cacheTTL || '1h';\n this.cacheTTL = utils.parseInterval(ttl);\n\n // Alerting options\n this.alertingEnabled = instanceSettings.jsonData.alerting;\n this.addThresholds = instanceSettings.jsonData.addThresholds;\n this.alertingMinSeverity = instanceSettings.jsonData.alertingMinSeverity || 2;\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 useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);\n let useTrends = this.trends && (\n (timeFrom <= useTrendsFrom) ||\n (timeTo - timeFrom >= useTrendsRange)\n );\n\n console.log(useTrends);\n\n // Get alerts for current panel\n if (this.alertingEnabled) {\n this.alertQuery(options).then(alert => {\n this.zabbixAlertingSrv.setPanelAlertState(options.panelId, alert.state);\n\n this.zabbixAlertingSrv.removeZabbixThreshold(options.panelId);\n if (this.addThresholds) {\n _.forEach(alert.thresholds, threshold => {\n this.zabbixAlertingSrv.setPanelThreshold(options.panelId, threshold);\n });\n }\n });\n }\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 .catch(error => {\n console.log(error);\n return [];\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 [\n value,\n point.clock * 1000 + Math.round(point.ns / 1000000)\n ];\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 /**\n * Get triggers and its details for panel's targets\n * Returns alert state ('ok' if no fired triggers, or 'alerting' if at least 1 trigger is fired)\n * or empty object if no related triggers are finded.\n */\n alertQuery(options) {\n let enabled_targets = filterEnabledTargets(options.targets);\n let getPanelItems = _.map(enabled_targets, target => {\n return this.zabbix.getItemsFromTarget(target, {itemtype: 'num'});\n });\n\n return Promise.all(getPanelItems)\n .then(results => {\n let items = _.flatten(results);\n let itemids = _.map(items, 'itemid');\n\n return this.zabbix.getAlerts(itemids);\n })\n .then(triggers => {\n triggers = _.filter(triggers, trigger => {\n return trigger.priority >= this.alertingMinSeverity;\n });\n\n if (!triggers || triggers.length === 0) {\n return {};\n }\n\n let state = 'ok';\n\n let firedTriggers = _.filter(triggers, {value: '1'});\n if (firedTriggers.length) {\n state = 'alerting';\n }\n\n let thresholds = _.map(triggers, trigger => {\n return getTriggerThreshold(trigger.expression);\n });\n\n return {\n panelId: options.panelId,\n state: state,\n thresholds: thresholds\n };\n });\n }\n\n // Replace template variables\n replaceTargetVariables(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n _.forEach(parts, 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 = _.map(func.params, 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\nfunction filterEnabledTargets(targets) {\n return _.filter(targets, target => {\n return !(target.hide || !target.group || !target.host || !target.item);\n });\n}\n\nfunction getTriggerThreshold(expression) {\n let thresholdPattern = /.*[<>]([\\d\\.]+)/;\n let finded_thresholds = expression.match(thresholdPattern);\n if (finded_thresholds && finded_thresholds.length >= 2) {\n let threshold = finded_thresholds[1];\n threshold = Number(threshold);\n return threshold;\n } else {\n return null;\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/partials/config.html b/dist/datasource-zabbix/partials/config.html index 6290d2e17..49e18b833 100644 --- a/dist/datasource-zabbix/partials/config.html +++ b/dist/datasource-zabbix/partials/config.html @@ -27,51 +27,66 @@

Zabbix API details

+ +
-
- -
- -
- Use from + After + + Time after which trends will be used. + Best practice is to set this value to your history storage period (7d, 30d, etc). + + type="text" + ng-model='ctrl.current.jsonData.trendsFrom' + placeholder="7d"> + +
+
+ + Range + + Time range width after which trends will be used instead of history. + It's better to set this value in range of 4 to 7 days to prevent loading large amount of history data. + + +
- Cache update interval + Cache TTL + + Zabbix data source caches metric names in memory. Specify how often data will be updated. + - +

Alerting

- -
- Min severity + Min severity
+ type="text" + ng-model='ctrl.current.jsonData.trendsFrom' + placeholder="7d"> + +
+
+ + Range + + Time range width after which trends will be used instead of history. + It's better to set this value in range of 4 to 7 days to prevent loading large amount of history data. + + +
- Cache update interval + Cache TTL + + Zabbix data source caches metric names in memory. Specify how often data will be updated. + - +

Alerting

- -
- Min severity + Min severity