From 6c64f21b1a2562f394292d95178d2312b2a8b3c8 Mon Sep 17 00:00:00 2001 From: Alexander Zobnin Date: Sun, 22 Oct 2017 14:30:54 +0300 Subject: [PATCH] Triggers query mode, allow to get active triggers count, #141 --- dist/datasource-zabbix/constants.js | 6 +- dist/datasource-zabbix/constants.js.map | 2 +- dist/datasource-zabbix/datasource.js | 71 +++++++++++++------ dist/datasource-zabbix/datasource.js.map | 2 +- .../partials/query.editor.html | 31 ++++++-- dist/datasource-zabbix/query.controller.js | 18 +++-- .../datasource-zabbix/query.controller.js.map | 2 +- dist/datasource-zabbix/responseHandler.js | 22 ++++-- dist/datasource-zabbix/responseHandler.js.map | 2 +- dist/datasource-zabbix/zabbix.js | 59 ++++++++++++++- dist/datasource-zabbix/zabbix.js.map | 2 +- dist/datasource-zabbix/zabbixAPI.service.js | 31 ++++++++ .../zabbixAPI.service.js.map | 2 +- dist/test/datasource-zabbix/constants.js | 1 + dist/test/datasource-zabbix/datasource.js | 71 +++++++++++++------ .../datasource-zabbix/query.controller.js | 18 +++-- .../test/datasource-zabbix/responseHandler.js | 14 +++- dist/test/datasource-zabbix/zabbix.js | 21 ++++++ .../datasource-zabbix/zabbixAPI.service.js | 31 ++++++++ src/datasource-zabbix/constants.js | 1 + src/datasource-zabbix/datasource.js | 22 ++++++ .../partials/query.editor.html | 31 ++++++-- src/datasource-zabbix/query.controller.js | 24 +++++-- src/datasource-zabbix/responseHandler.js | 16 ++++- src/datasource-zabbix/zabbix.js | 16 +++++ src/datasource-zabbix/zabbixAPI.service.js | 30 ++++++++ 26 files changed, 458 insertions(+), 88 deletions(-) diff --git a/dist/datasource-zabbix/constants.js b/dist/datasource-zabbix/constants.js index f0f59169d..cb95d15e1 100644 --- a/dist/datasource-zabbix/constants.js +++ b/dist/datasource-zabbix/constants.js @@ -3,7 +3,7 @@ System.register([], function (_export, _context) { "use strict"; - var MODE_METRICS, MODE_ITSERVICE, MODE_TEXT, MODE_ITEMID, SEV_NOT_CLASSIFIED, SEV_INFORMATION, SEV_WARNING, SEV_AVERAGE, SEV_HIGH, SEV_DISASTER, SHOW_ALL_TRIGGERS, SHOW_ALL_EVENTS, SHOW_OK_EVENTS, DATAPOINT_VALUE, DATAPOINT_TS; + var MODE_METRICS, MODE_ITSERVICE, MODE_TEXT, MODE_ITEMID, MODE_TRIGGERS, SEV_NOT_CLASSIFIED, SEV_INFORMATION, SEV_WARNING, SEV_AVERAGE, SEV_HIGH, SEV_DISASTER, SHOW_ALL_TRIGGERS, SHOW_ALL_EVENTS, SHOW_OK_EVENTS, DATAPOINT_VALUE, DATAPOINT_TS; return { setters: [], execute: function () { @@ -23,6 +23,10 @@ System.register([], function (_export, _context) { _export("MODE_ITEMID", MODE_ITEMID); + _export("MODE_TRIGGERS", MODE_TRIGGERS = 4); + + _export("MODE_TRIGGERS", MODE_TRIGGERS); + _export("SEV_NOT_CLASSIFIED", SEV_NOT_CLASSIFIED = 0); _export("SEV_NOT_CLASSIFIED", SEV_NOT_CLASSIFIED); diff --git a/dist/datasource-zabbix/constants.js.map b/dist/datasource-zabbix/constants.js.map index 427ad9db7..fb4d6c6c3 100644 --- a/dist/datasource-zabbix/constants.js.map +++ b/dist/datasource-zabbix/constants.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/constants.js"],"names":["MODE_METRICS","MODE_ITSERVICE","MODE_TEXT","MODE_ITEMID","SEV_NOT_CLASSIFIED","SEV_INFORMATION","SEV_WARNING","SEV_AVERAGE","SEV_HIGH","SEV_DISASTER","SHOW_ALL_TRIGGERS","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","DATAPOINT_VALUE","DATAPOINT_TS"],"mappings":";;;;;;;;;8BACaA,Y,GAAe,C;;;;gCACfC,c,GAAiB,C;;;;2BACjBC,S,GAAY,C;;;;6BACZC,W,GAAc,C;;;;oCAGdC,kB,GAAqB,C;;;;iCACrBC,e,GAAkB,C;;;;6BAClBC,W,GAAc,C;;;;6BACdC,W,GAAc,C;;;;0BACdC,Q,GAAW,C;;;;8BACXC,Y,GAAe,C;;;;mCAEfC,iB,GAAoB,CAAC,CAAD,EAAI,CAAJ,C;;;;iCACpBC,e,GAAkB,CAAC,CAAD,EAAI,CAAJ,C;;;;gCAClBC,c,GAAiB,C;;;;iCAGjBC,e,GAAkB,C;;;;8BAClBC,Y,GAAe,C","file":"constants.js","sourcesContent":["// Editor modes\nexport const MODE_METRICS = 0;\nexport const MODE_ITSERVICE = 1;\nexport const MODE_TEXT = 2;\nexport const MODE_ITEMID = 3;\n\n// Triggers severity\nexport const SEV_NOT_CLASSIFIED = 0;\nexport const SEV_INFORMATION = 1;\nexport const SEV_WARNING = 2;\nexport const SEV_AVERAGE = 3;\nexport const SEV_HIGH = 4;\nexport const SEV_DISASTER = 5;\n\nexport const SHOW_ALL_TRIGGERS = [0, 1];\nexport const SHOW_ALL_EVENTS = [0, 1];\nexport const SHOW_OK_EVENTS = 1;\n\n// Data point\nexport const DATAPOINT_VALUE = 0;\nexport const DATAPOINT_TS = 1;\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/constants.js"],"names":["MODE_METRICS","MODE_ITSERVICE","MODE_TEXT","MODE_ITEMID","MODE_TRIGGERS","SEV_NOT_CLASSIFIED","SEV_INFORMATION","SEV_WARNING","SEV_AVERAGE","SEV_HIGH","SEV_DISASTER","SHOW_ALL_TRIGGERS","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","DATAPOINT_VALUE","DATAPOINT_TS"],"mappings":";;;;;;;;;8BACaA,Y,GAAe,C;;;;gCACfC,c,GAAiB,C;;;;2BACjBC,S,GAAY,C;;;;6BACZC,W,GAAc,C;;;;+BACdC,a,GAAgB,C;;;;oCAGhBC,kB,GAAqB,C;;;;iCACrBC,e,GAAkB,C;;;;6BAClBC,W,GAAc,C;;;;6BACdC,W,GAAc,C;;;;0BACdC,Q,GAAW,C;;;;8BACXC,Y,GAAe,C;;;;mCAEfC,iB,GAAoB,CAAC,CAAD,EAAI,CAAJ,C;;;;iCACpBC,e,GAAkB,CAAC,CAAD,EAAI,CAAJ,C;;;;gCAClBC,c,GAAiB,C;;;;iCAGjBC,e,GAAkB,C;;;;8BAClBC,Y,GAAe,C","file":"constants.js","sourcesContent":["// Editor modes\nexport const MODE_METRICS = 0;\nexport const MODE_ITSERVICE = 1;\nexport const MODE_TEXT = 2;\nexport const MODE_ITEMID = 3;\nexport const MODE_TRIGGERS = 4;\n\n// Triggers severity\nexport const SEV_NOT_CLASSIFIED = 0;\nexport const SEV_INFORMATION = 1;\nexport const SEV_WARNING = 2;\nexport const SEV_AVERAGE = 3;\nexport const SEV_HIGH = 4;\nexport const SEV_DISASTER = 5;\n\nexport const SHOW_ALL_TRIGGERS = [0, 1];\nexport const SHOW_ALL_EVENTS = [0, 1];\nexport const SHOW_OK_EVENTS = 1;\n\n// Data point\nexport const DATAPOINT_VALUE = 0;\nexport const DATAPOINT_TS = 1;\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/datasource.js b/dist/datasource-zabbix/datasource.js index 7abf5364d..32fe129e3 100644 --- a/dist/datasource-zabbix/datasource.js +++ b/dist/datasource-zabbix/datasource.js @@ -337,6 +337,10 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', } else if (target.mode === c.MODE_ITSERVICE) { // IT services mode return _this.queryITServiceData(target, timeRange, options); + } else if (target.mode === c.MODE_TRIGGERS) { + return _this.queryTriggersData(target, timeRange); + } else { + return []; } }); @@ -558,18 +562,43 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }); }); } + }, { + key: 'queryTriggersData', + value: function queryTriggersData(target, timeRange) { + var _this7 = this; + + var _timeRange3 = _slicedToArray(timeRange, 2), + timeFrom = _timeRange3[0], + timeTo = _timeRange3[1]; + + return this.zabbix.getHostsFromTarget(target).then(function (results) { + var _results = _slicedToArray(results, 2), + hosts = _results[0], + apps = _results[1]; + + if (hosts.length) { + var hostids = _.map(hosts, 'hostid'); + var appids = _.map(apps, 'applicationid'); + return _this7.zabbix.getHostAlerts(hostids, appids, target.minSeverity, target.options.countTriggers, timeFrom, timeTo).then(function (triggers) { + return responseHandler.handleTriggersResponse(triggers, timeRange); + }); + } else { + return Promise.resolve([]); + } + }); + } }, { key: 'testDatasource', value: function testDatasource() { - var _this7 = this; + var _this8 = this; var zabbixVersion = void 0; return this.zabbix.getVersion().then(function (version) { zabbixVersion = version; - return _this7.zabbix.login(); + return _this8.zabbix.login(); }).then(function () { - if (_this7.enableDirectDBConnection) { - return _this7.zabbix.dbConnector.testSQLDataSource(); + if (_this8.enableDirectDBConnection) { + return _this8.zabbix.dbConnector.testSQLDataSource(); } else { return Promise.resolve(); } @@ -604,14 +633,14 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }, { key: 'metricFindQuery', value: function metricFindQuery(query) { - var _this8 = this; + var _this9 = this; var result = void 0; var parts = []; // Split query. Query structure: group.host.app.item _.each(utils.splitTemplateQuery(query), function (part) { - part = _this8.replaceTemplateVars(part, {}); + part = _this9.replaceTemplateVars(part, {}); // Replace wildcard to regex if (part === '*') { @@ -648,7 +677,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }, { key: 'annotationQuery', value: function annotationQuery(options) { - var _this9 = this; + var _this10 = this; var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000); var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000); @@ -666,7 +695,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', return getTriggers.then(function (triggers) { // Filter triggers by description - var triggerName = _this9.replaceTemplateVars(annotation.trigger, {}); + var triggerName = _this10.replaceTemplateVars(annotation.trigger, {}); if (utils.isRegex(triggerName)) { triggers = _.filter(triggers, function (trigger) { return utils.buildRegex(triggerName).test(trigger.description); @@ -683,7 +712,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }); var objectids = _.map(triggers, 'triggerid'); - return _this9.zabbix.getEvents(objectids, timeFrom, timeTo, showOkEvents).then(function (events) { + return _this10.zabbix.getEvents(objectids, timeFrom, timeTo, showOkEvents).then(function (events) { var indexedTriggers = _.keyBy(triggers, 'triggerid'); // Hide acknowledged events if option enabled @@ -717,23 +746,23 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }, { key: 'alertQuery', value: function alertQuery(options) { - var _this10 = this; + var _this11 = this; var enabled_targets = filterEnabledTargets(options.targets); var getPanelItems = _.map(enabled_targets, function (t) { var target = _.cloneDeep(t); - _this10.replaceTargetVariables(target, options); - return _this10.zabbix.getItemsFromTarget(target, { itemtype: 'num' }); + _this11.replaceTargetVariables(target, options); + return _this11.zabbix.getItemsFromTarget(target, { itemtype: 'num' }); }); return Promise.all(getPanelItems).then(function (results) { var items = _.flatten(results); var itemids = _.map(items, 'itemid'); - return _this10.zabbix.getAlerts(itemids); + return _this11.zabbix.getAlerts(itemids); }).then(function (triggers) { triggers = _.filter(triggers, function (trigger) { - return trigger.priority >= _this10.alertingMinSeverity; + return trigger.priority >= _this11.alertingMinSeverity; }); if (!triggers || triggers.length === 0) { @@ -761,12 +790,12 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }, { key: 'replaceTargetVariables', value: function replaceTargetVariables(target, options) { - var _this11 = this; + var _this12 = this; var parts = ['group', 'host', 'application', 'item']; _.forEach(parts, function (p) { if (target[p] && target[p].filter) { - target[p].filter = _this11.replaceTemplateVars(target[p].filter, options.scopedVars); + target[p].filter = _this12.replaceTemplateVars(target[p].filter, options.scopedVars); } }); target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars); @@ -774,9 +803,9 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', _.forEach(target.functions, function (func) { func.params = _.map(func.params, function (param) { if (typeof param === 'number') { - return +_this11.templateSrv.replace(param.toString(), options.scopedVars); + return +_this12.templateSrv.replace(param.toString(), options.scopedVars); } else { - return _this11.templateSrv.replace(param, options.scopedVars); + return _this12.templateSrv.replace(param, options.scopedVars); } }); }); @@ -784,9 +813,9 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }, { key: 'isUseTrends', value: function isUseTrends(timeRange) { - var _timeRange3 = _slicedToArray(timeRange, 2), - timeFrom = _timeRange3[0], - timeTo = _timeRange3[1]; + var _timeRange4 = _slicedToArray(timeRange, 2), + timeFrom = _timeRange4[0], + timeTo = _timeRange4[1]; var useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000); var useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000); diff --git a/dist/datasource-zabbix/datasource.js.map b/dist/datasource-zabbix/datasource.js.map index 26165b03f..961508f60 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","getConsolidateBy","target","consolidateBy","funcDef","find","functions","length","downsampleSeries","timeseries_data","options","defaultAgg","consolidateByFunc","timeseries","datapoints","maxDataPoints","groupBy","interval","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","zabbixItemIdsTemplateFormat","replaceTemplateVars","templateSrv","scopedVars","replacedTarget","replace","isRegex","sequence","funcsArray","result","i","call","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","c","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","partial","url","basicAuth","withCredentials","jsonData","username","password","trends","trendsFrom","trendsRange","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","SEV_WARNING","dbConnectionOptions","dbConnection","enableDirectDBConnection","enable","sqlDatasourceId","datasourceId","zabbixOptions","zabbix","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","t","timeFrom","Math","ceil","parse","range","from","timeTo","to","cloneDeep","replaceTargetVariables","timeFunctions","time_from","time_to","timeRange","useTrends","isUseTrends","mode","MODE_METRICS","MODE_TEXT","MODE_ITEMID","migrate","queryNumericData","queryTextData","queryItemIdData","MODE_ITSERVICE","queryITServiceData","Promise","all","flatten","data","getItemOptions","itemtype","getItemsFromTarget","queryNumericDataForItems","items","getHistoryPromise","getTrendsDB","dbConnector","handleGrafanaTSResponse","history","valueType","getTrendValueType","getTrend","handleTrends","series","sortBy","point","DATAPOINT_TS","getHistoryDB","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","unShiftTimeSeries","handleText","resolve","itemids","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","zabbixVersion","getVersion","version","login","testSQLDataSource","status","title","message","query","parts","each","splitTemplateQuery","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","triggersOptions","showTriggers","SHOW_ALL_TRIGGERS","hideHostsInMaintenance","getTriggers","application","triggerName","trigger","triggers","buildRegex","test","description","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","hosts","formatted_acknowledges","formatAcknowledges","time","clock","objectid","enabled_targets","getPanelItems","results","getAlerts","firedTriggers","p","textFilter","param","toString","useTrendsFrom","useTrendsRange","contains","indexBy"],"mappings":";;;;;;;;;;;;;AAgmBA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC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b,IACCrJ,SAASN,QAAT,IAAqB4J,cAFR,CAAhB;AAIA,mBAAO9I,SAAP;AACD;;;;;;qCAoHK1D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAEiR,QAAf;AAAyB;AAC3C,UAAI,CAACjR,EAAEyP,KAAP,EAAc;AAACzP,UAAEyP,KAAF,GAAUzP,EAAEkR,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 * as c from './constants';\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 // Use custom format for template variables\n this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\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 const jsonData = instanceSettings.jsonData;\n\n // Zabbix API credentials\n this.username = jsonData.username;\n this.password = jsonData.password;\n\n // Use trends instead history since specified time\n this.trends = jsonData.trends;\n this.trendsFrom = jsonData.trendsFrom || '7d';\n this.trendsRange = jsonData.trendsRange || '4d';\n\n // Set cache update interval\n var ttl = jsonData.cacheTTL || '1h';\n this.cacheTTL = utils.parseInterval(ttl);\n\n // Alerting options\n this.alertingEnabled = jsonData.alerting;\n this.addThresholds = jsonData.addThresholds;\n this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;\n\n // Direct DB Connection options\n let dbConnectionOptions = jsonData.dbConnection || {};\n this.enableDirectDBConnection = dbConnectionOptions.enable;\n this.sqlDatasourceId = dbConnectionOptions.datasourceId;\n\n let zabbixOptions = {\n username: this.username,\n password: this.password,\n basicAuth: this.basicAuth,\n withCredentials: this.withCredentials,\n cacheTTL: this.cacheTTL,\n enableDirectDBConnection: this.enableDirectDBConnection,\n sqlDatasourceId: this.sqlDatasourceId\n };\n\n this.zabbix = new Zabbix(this.url, zabbixOptions);\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 // 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, t => {\n // Don't request undefined and hidden targets\n if (t.hide) {\n return [];\n }\n\n let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n // Prevent changes of original object\n let target = _.cloneDeep(t);\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 let timeRange = [timeFrom, timeTo];\n\n let useTrends = this.isUseTrends(timeRange);\n\n // Metrics or Text query mode\n if (!target.mode || target.mode === c.MODE_METRICS ||\n target.mode === c.MODE_TEXT || target.mode === c.MODE_ITEMID) {\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 === c.MODE_METRICS) {\n return this.queryNumericData(target, timeRange, useTrends, options);\n } else if (target.mode === c.MODE_TEXT) {\n return this.queryTextData(target, timeRange);\n } else if (target.mode === c.MODE_ITEMID) {\n return this.queryItemIdData(target, timeRange, useTrends, options);\n }\n } else if (target.mode === c.MODE_ITSERVICE) {\n // IT services mode\n return this.queryITServiceData(target, timeRange, options);\n }\n });\n\n // Data for panel (all targets)\n return Promise.all(_.flatten(promises))\n .then(_.flatten)\n .then(data => {\n return { data: data };\n });\n }\n\n /**\n * Query target data for Metrics mode\n */\n queryNumericData(target, timeRange, useTrends, options) {\n let getItemOptions = {\n itemtype: 'num'\n };\n return this.zabbix.getItemsFromTarget(target, getItemOptions)\n .then(items => {\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n });\n }\n\n /**\n * Query history for numeric items\n */\n queryNumericDataForItems(items, target, timeRange, useTrends, options) {\n let [timeFrom, timeTo] = timeRange;\n let getHistoryPromise;\n options.consolidateBy = getConsolidateBy(target);\n\n if (useTrends) {\n if (this.enableDirectDBConnection) {\n getHistoryPromise = this.zabbix.getTrendsDB(items, timeFrom, timeTo, options)\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n } else {\n let valueType = this.getTrendValueType(target);\n getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n .then(history => responseHandler.handleTrends(history, items, valueType))\n .then(timeseries => {\n // Sort trend data, issue #202\n _.forEach(timeseries, series => {\n series.datapoints = _.sortBy(series.datapoints, point => point[c.DATAPOINT_TS]);\n });\n return timeseries;\n });\n }\n } else {\n // Use history\n if (this.enableDirectDBConnection) {\n getHistoryPromise = this.zabbix.getHistoryDB(items, timeFrom, timeTo, options)\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n } else {\n getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => responseHandler.handleHistory(history, items));\n }\n }\n\n return getHistoryPromise\n .then(timeseries => this.applyDataProcessingFunctions(timeseries, target))\n .then(timeseries => downsampleSeries(timeseries, options))\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 = _.cloneDeep(_.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 /**\n * Query target data for Text mode\n */\n queryTextData(target, timeRange) {\n let [timeFrom, timeTo] = timeRange;\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.handleText(history, items, target);\n });\n } else {\n return Promise.resolve([]);\n }\n });\n }\n\n /**\n * Query target data for Item ID mode\n */\n queryItemIdData(target, timeRange, useTrends, options) {\n let itemids = target.itemids;\n itemids = this.templateSrv.replace(itemids, options.scopedVars, zabbixItemIdsTemplateFormat);\n itemids = _.map(itemids.split(','), itemid => itemid.trim());\n\n if (!itemids) {\n return [];\n }\n\n return this.zabbix.getItemsByIDs(itemids)\n .then(items => {\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n });\n }\n\n /**\n * Query target data for IT Services mode\n */\n queryITServiceData(target, timeRange, options) {\n // Don't show undefined and hidden targets\n if (target.hide || (!target.itservice && !target.itServiceFilter) || !target.slaProperty) {\n return [];\n }\n\n let itServiceIds = [];\n let itServices = [];\n let itServiceFilter;\n let isOldVersion = target.itservice && !target.itServiceFilter;\n\n if (isOldVersion) {\n // Backward compatibility\n itServiceFilter = '/.*/';\n } else {\n itServiceFilter = this.replaceTemplateVars(target.itServiceFilter, options.scopedVars);\n }\n\n return this.zabbix.getITServices(itServiceFilter)\n .then(itservices => {\n itServices = itservices;\n if (isOldVersion) {\n itServices = _.filter(itServices, {'serviceid': target.itservice.serviceid});\n }\n\n itServiceIds = _.map(itServices, 'serviceid');\n return itServiceIds;\n })\n .then(serviceids => {\n return this.zabbix.getSLA(serviceids, timeRange);\n })\n .then(slaResponse => {\n return _.map(itServiceIds, serviceid => {\n let itservice = _.find(itServices, {'serviceid': serviceid});\n return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);\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 if (this.enableDirectDBConnection) {\n return this.zabbix.dbConnector.testSQLDataSource();\n } else {\n return Promise.resolve();\n }\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.message\n };\n } else if (error.data && error.data.message) {\n return {\n status: \"error\",\n title: \"Connection failed\",\n message: \"Connection failed: \" + error.data.message\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(utils.splitTemplateQuery(query), 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 ? c.SHOW_ALL_EVENTS : c.SHOW_OK_EVENTS;\n\n // Show all triggers\n let triggersOptions = {\n showTriggers: c.SHOW_ALL_TRIGGERS,\n hideHostsInMaintenance: false\n };\n\n var getTriggers = this.zabbix.getTriggers(this.replaceTemplateVars(annotation.group, {}),\n this.replaceTemplateVars(annotation.host, {}),\n this.replaceTemplateVars(annotation.application, {}),\n triggersOptions);\n\n return getTriggers.then(triggers => {\n\n // Filter triggers by description\n let triggerName = this.replaceTemplateVars(annotation.trigger, {});\n if (utils.isRegex(triggerName)) {\n triggers = _.filter(triggers, trigger => {\n return utils.buildRegex(triggerName).test(trigger.description);\n });\n } else if (triggerName) {\n triggers = _.filter(triggers, trigger => {\n return trigger.description === triggerName;\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, t => {\n let target = _.cloneDeep(t);\n this.replaceTargetVariables(target, options);\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 isUseTrends(timeRange) {\n let [timeFrom, timeTo] = timeRange;\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 return useTrends;\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 getConsolidateBy(target) {\n let consolidateBy = 'avg';\n let funcDef = _.find(target.functions, func => {\n return func.def.name === 'consolidateBy';\n });\n if (funcDef && funcDef.params && funcDef.params.length) {\n consolidateBy = funcDef.params[0];\n }\n return consolidateBy;\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n let defaultAgg = dataProcessor.aggregationFunctions['avg'];\n let consolidateByFunc = dataProcessor.aggregationFunctions[options.consolidateBy] || defaultAgg;\n return _.map(timeseries_data, timeseries => {\n if (timeseries.datapoints.length > options.maxDataPoints) {\n timeseries.datapoints = dataProcessor\n .groupBy(options.interval, consolidateByFunc, 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\nfunction zabbixItemIdsTemplateFormat(value) {\n if (typeof value === 'string') {\n return value;\n }\n return value.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\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","getConsolidateBy","target","consolidateBy","funcDef","find","functions","length","downsampleSeries","timeseries_data","options","defaultAgg","consolidateByFunc","timeseries","datapoints","maxDataPoints","groupBy","interval","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","zabbixItemIdsTemplateFormat","replaceTemplateVars","templateSrv","scopedVars","replacedTarget","replace","isRegex","sequence","funcsArray","result","i","call","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","c","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","partial","url","basicAuth","withCredentials","jsonData","username","password","trends","trendsFrom","trendsRange","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","SEV_WARNING","dbConnectionOptions","dbConnection","enableDirectDBConnection","enable","sqlDatasourceId","datasourceId","zabbixOptions","zabbix","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","t","timeFrom","Math","ceil","parse","range","from","timeTo","to","cloneDeep","replaceTargetVariables","timeFunctions","time_from","time_to","timeRange","useTrends","isUseTrends","mode","MODE_METRICS","MODE_TEXT","MODE_ITEMID","migrate","queryNumericData","queryTextData","queryItemIdData","MODE_ITSERVICE","queryITServiceData","MODE_TRIGGERS","queryTriggersData","Promise","all","flatten","data","getItemOptions","itemtype","getItemsFromTarget","queryNumericDataForItems","items","getHistoryPromise","getTrendsDB","dbConnector","handleGrafanaTSResponse","history","valueType","getTrendValueType","getTrend","handleTrends","series","sortBy","point","DATAPOINT_TS","getHistoryDB","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","unShiftTimeSeries","handleText","resolve","itemids","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","getHostsFromTarget","results","hosts","apps","hostids","appids","getHostAlerts","minSeverity","countTriggers","triggers","handleTriggersResponse","zabbixVersion","getVersion","version","login","testSQLDataSource","status","title","message","query","parts","each","splitTemplateQuery","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","triggersOptions","showTriggers","SHOW_ALL_TRIGGERS","hideHostsInMaintenance","getTriggers","application","triggerName","trigger","buildRegex","test","description","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","formatted_acknowledges","formatAcknowledges","time","clock","objectid","enabled_targets","getPanelItems","getAlerts","firedTriggers","p","textFilter","param","toString","useTrendsFrom","useTrendsRange","contains","indexBy"],"mappings":";;;;;;;;;;;;;AAsnBA,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,MAA1B,EAAkC;AAChC,QAAIC,gBAAgB,KAApB;AACA,QAAIC,UAAUlB,EAAEmB,IAAF,CAAOH,OAAOI,SAAd,EAAyB,gBAAQ;AAC7C,aAAOd,KAAKE,GAAL,CAASC,IAAT,KAAkB,eAAzB;AACD,KAFa,CAAd;AAGA,QAAIS,WAAWA,QAAQN,MAAnB,IAA6BM,QAAQN,MAAR,CAAeS,MAAhD,EAAwD;AACtDJ,sBAAgBC,QAAQN,MAAR,CAAe,CAAf,CAAhB;AACD;AACD,WAAOK,aAAP;AACD;;AAED,WAASK,gBAAT,CAA0BC,eAA1B,EAA2CC,OAA3C,EAAoD;AAClD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,KAAKC,IAAL,CAAUhF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI2C,YAAY,KAAK7C,MAAL,KACb+B,YAAYqK,aAAb,IACC/J,SAASN,QAAT,IAAqBsK,cAFR,CAAhB;AAIA,mBAAOxJ,SAAP;AACD;;;;;;qCAoHK1D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE2R,QAAf;AAAyB;AAC3C,UAAI,CAAC3R,EAAEqQ,KAAP,EAAc;AAACrQ,UAAEqQ,KAAF,GAAUrQ,EAAE4R,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 * as c from './constants';\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 // Use custom format for template variables\n this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\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 const jsonData = instanceSettings.jsonData;\n\n // Zabbix API credentials\n this.username = jsonData.username;\n this.password = jsonData.password;\n\n // Use trends instead history since specified time\n this.trends = jsonData.trends;\n this.trendsFrom = jsonData.trendsFrom || '7d';\n this.trendsRange = jsonData.trendsRange || '4d';\n\n // Set cache update interval\n var ttl = jsonData.cacheTTL || '1h';\n this.cacheTTL = utils.parseInterval(ttl);\n\n // Alerting options\n this.alertingEnabled = jsonData.alerting;\n this.addThresholds = jsonData.addThresholds;\n this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;\n\n // Direct DB Connection options\n let dbConnectionOptions = jsonData.dbConnection || {};\n this.enableDirectDBConnection = dbConnectionOptions.enable;\n this.sqlDatasourceId = dbConnectionOptions.datasourceId;\n\n let zabbixOptions = {\n username: this.username,\n password: this.password,\n basicAuth: this.basicAuth,\n withCredentials: this.withCredentials,\n cacheTTL: this.cacheTTL,\n enableDirectDBConnection: this.enableDirectDBConnection,\n sqlDatasourceId: this.sqlDatasourceId\n };\n\n this.zabbix = new Zabbix(this.url, zabbixOptions);\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 // 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, t => {\n // Don't request undefined and hidden targets\n if (t.hide) {\n return [];\n }\n\n let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n // Prevent changes of original object\n let target = _.cloneDeep(t);\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 let timeRange = [timeFrom, timeTo];\n\n let useTrends = this.isUseTrends(timeRange);\n\n // Metrics or Text query mode\n if (!target.mode || target.mode === c.MODE_METRICS ||\n target.mode === c.MODE_TEXT || target.mode === c.MODE_ITEMID) {\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 === c.MODE_METRICS) {\n return this.queryNumericData(target, timeRange, useTrends, options);\n } else if (target.mode === c.MODE_TEXT) {\n return this.queryTextData(target, timeRange);\n } else if (target.mode === c.MODE_ITEMID) {\n return this.queryItemIdData(target, timeRange, useTrends, options);\n }\n } else if (target.mode === c.MODE_ITSERVICE) {\n // IT services mode\n return this.queryITServiceData(target, timeRange, options);\n } else if (target.mode === c.MODE_TRIGGERS) {\n return this.queryTriggersData(target, timeRange);\n } else {\n return [];\n }\n });\n\n // Data for panel (all targets)\n return Promise.all(_.flatten(promises))\n .then(_.flatten)\n .then(data => {\n return { data: data };\n });\n }\n\n /**\n * Query target data for Metrics mode\n */\n queryNumericData(target, timeRange, useTrends, options) {\n let getItemOptions = {\n itemtype: 'num'\n };\n return this.zabbix.getItemsFromTarget(target, getItemOptions)\n .then(items => {\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n });\n }\n\n /**\n * Query history for numeric items\n */\n queryNumericDataForItems(items, target, timeRange, useTrends, options) {\n let [timeFrom, timeTo] = timeRange;\n let getHistoryPromise;\n options.consolidateBy = getConsolidateBy(target);\n\n if (useTrends) {\n if (this.enableDirectDBConnection) {\n getHistoryPromise = this.zabbix.getTrendsDB(items, timeFrom, timeTo, options)\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n } else {\n let valueType = this.getTrendValueType(target);\n getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n .then(history => responseHandler.handleTrends(history, items, valueType))\n .then(timeseries => {\n // Sort trend data, issue #202\n _.forEach(timeseries, series => {\n series.datapoints = _.sortBy(series.datapoints, point => point[c.DATAPOINT_TS]);\n });\n return timeseries;\n });\n }\n } else {\n // Use history\n if (this.enableDirectDBConnection) {\n getHistoryPromise = this.zabbix.getHistoryDB(items, timeFrom, timeTo, options)\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n } else {\n getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => responseHandler.handleHistory(history, items));\n }\n }\n\n return getHistoryPromise\n .then(timeseries => this.applyDataProcessingFunctions(timeseries, target))\n .then(timeseries => downsampleSeries(timeseries, options))\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 = _.cloneDeep(_.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 /**\n * Query target data for Text mode\n */\n queryTextData(target, timeRange) {\n let [timeFrom, timeTo] = timeRange;\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.handleText(history, items, target);\n });\n } else {\n return Promise.resolve([]);\n }\n });\n }\n\n /**\n * Query target data for Item ID mode\n */\n queryItemIdData(target, timeRange, useTrends, options) {\n let itemids = target.itemids;\n itemids = this.templateSrv.replace(itemids, options.scopedVars, zabbixItemIdsTemplateFormat);\n itemids = _.map(itemids.split(','), itemid => itemid.trim());\n\n if (!itemids) {\n return [];\n }\n\n return this.zabbix.getItemsByIDs(itemids)\n .then(items => {\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n });\n }\n\n /**\n * Query target data for IT Services mode\n */\n queryITServiceData(target, timeRange, options) {\n // Don't show undefined and hidden targets\n if (target.hide || (!target.itservice && !target.itServiceFilter) || !target.slaProperty) {\n return [];\n }\n\n let itServiceIds = [];\n let itServices = [];\n let itServiceFilter;\n let isOldVersion = target.itservice && !target.itServiceFilter;\n\n if (isOldVersion) {\n // Backward compatibility\n itServiceFilter = '/.*/';\n } else {\n itServiceFilter = this.replaceTemplateVars(target.itServiceFilter, options.scopedVars);\n }\n\n return this.zabbix.getITServices(itServiceFilter)\n .then(itservices => {\n itServices = itservices;\n if (isOldVersion) {\n itServices = _.filter(itServices, {'serviceid': target.itservice.serviceid});\n }\n\n itServiceIds = _.map(itServices, 'serviceid');\n return itServiceIds;\n })\n .then(serviceids => {\n return this.zabbix.getSLA(serviceids, timeRange);\n })\n .then(slaResponse => {\n return _.map(itServiceIds, serviceid => {\n let itservice = _.find(itServices, {'serviceid': serviceid});\n return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);\n });\n });\n }\n\n queryTriggersData(target, timeRange) {\n let [timeFrom, timeTo] = timeRange;\n return this.zabbix.getHostsFromTarget(target)\n .then((results) => {\n let [hosts, apps] = results;\n if (hosts.length) {\n let hostids = _.map(hosts, 'hostid');\n let appids = _.map(apps, 'applicationid');\n return this.zabbix.getHostAlerts(hostids, appids, target.minSeverity, target.options.countTriggers, timeFrom, timeTo)\n .then((triggers) => {\n return responseHandler.handleTriggersResponse(triggers, timeRange);\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 if (this.enableDirectDBConnection) {\n return this.zabbix.dbConnector.testSQLDataSource();\n } else {\n return Promise.resolve();\n }\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.message\n };\n } else if (error.data && error.data.message) {\n return {\n status: \"error\",\n title: \"Connection failed\",\n message: \"Connection failed: \" + error.data.message\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(utils.splitTemplateQuery(query), 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 ? c.SHOW_ALL_EVENTS : c.SHOW_OK_EVENTS;\n\n // Show all triggers\n let triggersOptions = {\n showTriggers: c.SHOW_ALL_TRIGGERS,\n hideHostsInMaintenance: false\n };\n\n var getTriggers = this.zabbix.getTriggers(this.replaceTemplateVars(annotation.group, {}),\n this.replaceTemplateVars(annotation.host, {}),\n this.replaceTemplateVars(annotation.application, {}),\n triggersOptions);\n\n return getTriggers.then(triggers => {\n\n // Filter triggers by description\n let triggerName = this.replaceTemplateVars(annotation.trigger, {});\n if (utils.isRegex(triggerName)) {\n triggers = _.filter(triggers, trigger => {\n return utils.buildRegex(triggerName).test(trigger.description);\n });\n } else if (triggerName) {\n triggers = _.filter(triggers, trigger => {\n return trigger.description === triggerName;\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, t => {\n let target = _.cloneDeep(t);\n this.replaceTargetVariables(target, options);\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 isUseTrends(timeRange) {\n let [timeFrom, timeTo] = timeRange;\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 return useTrends;\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 getConsolidateBy(target) {\n let consolidateBy = 'avg';\n let funcDef = _.find(target.functions, func => {\n return func.def.name === 'consolidateBy';\n });\n if (funcDef && funcDef.params && funcDef.params.length) {\n consolidateBy = funcDef.params[0];\n }\n return consolidateBy;\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n let defaultAgg = dataProcessor.aggregationFunctions['avg'];\n let consolidateByFunc = dataProcessor.aggregationFunctions[options.consolidateBy] || defaultAgg;\n return _.map(timeseries_data, timeseries => {\n if (timeseries.datapoints.length > options.maxDataPoints) {\n timeseries.datapoints = dataProcessor\n .groupBy(options.interval, consolidateByFunc, 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\nfunction zabbixItemIdsTemplateFormat(value) {\n if (typeof value === 'string') {\n return value;\n }\n return value.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\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/query.editor.html b/dist/datasource-zabbix/partials/query.editor.html index f5831025e..3c69c3df4 100644 --- a/dist/datasource-zabbix/partials/query.editor.html +++ b/dist/datasource-zabbix/partials/query.editor.html @@ -48,7 +48,7 @@ -
+
@@ -66,7 +66,7 @@
- +
-
+
@@ -103,8 +103,8 @@
-
- +
+
+ +
+ +
+ +
+
+
-
+
@@ -66,7 +66,7 @@
- +
-
+
@@ -103,8 +103,8 @@
-
- +
+
+ +
+ +
+ +
+
+
@@ -130,13 +142,20 @@
-
+
+
+ + +
diff --git a/src/datasource-zabbix/query.controller.js b/src/datasource-zabbix/query.controller.js index 1330f4f1b..90e9a9a14 100644 --- a/src/datasource-zabbix/query.controller.js +++ b/src/datasource-zabbix/query.controller.js @@ -25,14 +25,16 @@ export class ZabbixQueryController extends QueryCtrl { {value: 'num', text: 'Metrics', mode: c.MODE_METRICS}, {value: 'text', text: 'Text', mode: c.MODE_TEXT}, {value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE}, - {value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID} + {value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID}, + {value: 'triggers', text: 'Triggers', mode: c.MODE_TRIGGERS} ]; this.$scope.editorMode = { METRICS: c.MODE_METRICS, TEXT: c.MODE_TEXT, ITSERVICE: c.MODE_ITSERVICE, - ITEMID: c.MODE_ITEMID + ITEMID: c.MODE_ITEMID, + TRIGGERS: c.MODE_TRIGGERS }; this.slaPropertyList = [ @@ -43,6 +45,12 @@ export class ZabbixQueryController extends QueryCtrl { {name: "Down time", property: "downtimeTime"} ]; + this.triggerSeverity = [ + {val: 0, text: 'Not classified'}, {val: 1, text:'Information'}, + {val: 2, text: 'Warning'}, {val: 3, text: 'Average'}, + {val: 4, text: 'High'}, {val: 5, text: 'Disaster'} + ]; + // Map functions for bs-typeahead this.getGroupNames = _.bind(this.getMetricNames, this, 'groupList'); this.getHostNames = _.bind(this.getMetricNames, this, 'hostList', true); @@ -80,8 +88,10 @@ export class ZabbixQueryController extends QueryCtrl { 'application': { 'filter': "" }, 'item': { 'filter': "" }, 'functions': [], + 'minSeverity': 3, 'options': { - 'showDisabledItems': false + 'showDisabledItems': false, + 'countTriggers': true } }; _.defaults(target, targetDefaults); @@ -92,8 +102,8 @@ export class ZabbixQueryController extends QueryCtrl { }); if (target.mode === c.MODE_METRICS || - target.mode === c.MODE_TEXT) { - + target.mode === c.MODE_TEXT || + target.mode === c.MODE_TRIGGERS) { this.initFilters(); } else if (target.mode === c.MODE_ITSERVICE) { @@ -103,6 +113,7 @@ export class ZabbixQueryController extends QueryCtrl { }; this.init(); + this.queryOptionsText = this.renderQueryOptionsText(); } initFilters() { @@ -282,7 +293,8 @@ export class ZabbixQueryController extends QueryCtrl { renderQueryOptionsText() { var optionsMap = { - showDisabledItems: "Show disabled items" + showDisabledItems: "Show disabled items", + countTriggers: "Count Triggers" }; var options = []; _.forOwn(this.target.options, (value, key) => { diff --git a/src/datasource-zabbix/responseHandler.js b/src/datasource-zabbix/responseHandler.js index 6a61118dd..25f83f0a6 100644 --- a/src/datasource-zabbix/responseHandler.js +++ b/src/datasource-zabbix/responseHandler.js @@ -100,6 +100,19 @@ function handleSLAResponse(itservice, slaProperty, slaObject) { } } +function handleTriggersResponse(triggers, timeRange) { + if (_.isNumber(triggers)) { + return { + target: "triggers count", + datapoints: [ + [triggers, timeRange[1]] + ] + }; + } else { + return triggers; + } +} + function convertHistoryPoint(point) { // Value must be a number for properly work return [ @@ -141,7 +154,8 @@ export default { convertHistory: convertHistory, handleTrends: handleTrends, handleText: handleText, - handleSLAResponse: handleSLAResponse + handleSLAResponse: handleSLAResponse, + handleTriggersResponse: handleTriggersResponse }; // Fix for backward compatibility with lodash 2.4 diff --git a/src/datasource-zabbix/zabbix.js b/src/datasource-zabbix/zabbix.js index f5dd71420..694a5d85b 100644 --- a/src/datasource-zabbix/zabbix.js +++ b/src/datasource-zabbix/zabbix.js @@ -46,6 +46,7 @@ function ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector) this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI); this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI); this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI); + this.getHostAlerts = this.zabbixAPI.getHostAlerts.bind(this.zabbixAPI); this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI); this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI); this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI); @@ -59,6 +60,21 @@ function ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector) return this.getItems(...filters, options); } + getHostsFromTarget(target) { + let parts = ['group', 'host', 'application']; + let filters = _.map(parts, p => target[p].filter); + return Promise.all([ + this.getHosts(...filters), + this.getApps(...filters), + ]).then((results) => { + let [hosts, apps] = results; + if (apps.appFilterEmpty) { + apps = []; + } + return [hosts, apps]; + }); + } + getAllGroups() { return this.cachingProxy.getGroups(); } diff --git a/src/datasource-zabbix/zabbixAPI.service.js b/src/datasource-zabbix/zabbixAPI.service.js index bd1b40e0a..74b145f6c 100644 --- a/src/datasource-zabbix/zabbixAPI.service.js +++ b/src/datasource-zabbix/zabbixAPI.service.js @@ -433,6 +433,36 @@ function ZabbixAPIServiceFactory(alertSrv, zabbixAPICoreService) { return this.request('trigger.get', params); } + + getHostAlerts(hostids, applicationids, minSeverity, count, timeFrom, timeTo) { + var params = { + output: 'extend', + hostids: hostids, + min_severity: minSeverity, + filter: { value: 1 }, + expandDescription: true, + expandData: true, + expandComment: true, + monitored: true, + skipDependent: true, + selectLastEvent: 'extend' + }; + + if (count) { + params.countOutput = true; + } + + if (applicationids && applicationids.length) { + params.applicationids = applicationids; + } + + if (timeFrom || timeTo) { + params.lastChangeSince = timeFrom; + params.lastChangeTill = timeTo; + } + + return this.request('trigger.get', params); + } } return ZabbixAPI;