diff --git a/dist/datasource-zabbix/datasource.js b/dist/datasource-zabbix/datasource.js index 96fc27c09..186478378 100644 --- a/dist/datasource-zabbix/datasource.js +++ b/dist/datasource-zabbix/datasource.js @@ -220,7 +220,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', this.basicAuth = instanceSettings.basicAuth; this.withCredentials = instanceSettings.withCredentials; - var jsonData = instanceSettings.jsonData; + var jsonData = instanceSettings.jsonData || {}; // Zabbix API credentials this.username = jsonData.username; @@ -240,6 +240,9 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', this.addThresholds = jsonData.addThresholds; this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING; + // Other options + this.disableReadOnlyUsersAck = jsonData.disableReadOnlyUsersAck; + // Direct DB Connection options var dbConnectionOptions = jsonData.dbConnection || {}; this.enableDirectDBConnection = dbConnectionOptions.enable; diff --git a/dist/datasource-zabbix/datasource.js.map b/dist/datasource-zabbix/datasource.js.map index 7d7b5e71f..1edc066f6 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","migrate","queryNumericData","queryTextData","MODE_ITEMID","itemids","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","resultFormat","handleHistoryAsTable","handleText","resolve","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","getHostsFromTarget","results","hosts","apps","hostids","appids","minSeverity","triggers","acknowledged","count","getHostAlerts","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":";;;;;;;;;;;;;AAwoBA,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,EAA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yB2O,MAAMC,QAAN,EAAzB,EAA2CnQ,QAAQqB,UAAnD,CAAR;AACD,iBAFD,MAEO;AACL,yBAAO,QAAKD,WAAL,CAAiBG,OAAjB,CAAyB2O,KAAzB,EAAgClQ,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;sCAEWoF,S,EAAW;AAAA,6CACIA,SADJ;AAAA,gBAChBb,QADgB;AAAA,gBACNM,MADM;;AAErB,gBAAIkK,gBAAgBvK,KAAKC,IAAL,CAAUnD,SAASoD,KAAT,CAAe,SAAS,KAAKjC,UAA7B,IAA2C,IAArD,CAApB;AACA,gBAAIuM,iBAAiBxK,KAAKC,IAAL,CAAUhF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI2C,YAAY,KAAK7C,MAAL,KACb+B,YAAYwK,aAAb,IACClK,SAASN,QAAT,IAAqByK,cAFR,CAAhB;AAIA,mBAAO3J,SAAP;AACD;;;;;;qCAoHK1D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE8R,QAAf;AAAyB;AAC3C,UAAI,CAAC9R,EAAEwQ,KAAP,EAAc;AAACxQ,UAAEwQ,KAAF,GAAUxQ,EAAE+R,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 || target.mode === c.MODE_TEXT) {\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 }\n } else if (target.mode === c.MODE_ITEMID) {\n // Item ID mode\n if (!target.itemids) {\n return [];\n }\n return this.queryItemIdData(target, timeRange, useTrends, options);\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 // Triggers mode\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 if (target.resultFormat === 'table') {\n return responseHandler.handleHistoryAsTable(history, items, target);\n } else {\n return responseHandler.handleText(history, items, target);\n }\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 let options = {\n minSeverity: target.triggers.minSeverity,\n acknowledged: target.triggers.acknowledged,\n count: target.triggers.count,\n timeFrom: timeFrom,\n timeTo: timeTo\n };\n return this.zabbix.getHostAlerts(hostids, appids, options)\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 if (itemids.length === 0) {\n return [];\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 = /.*[<>=]{1,2}([\\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","disableReadOnlyUsersAck","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","migrate","queryNumericData","queryTextData","MODE_ITEMID","itemids","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","resultFormat","handleHistoryAsTable","handleText","resolve","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","getHostsFromTarget","results","hosts","apps","hostids","appids","minSeverity","triggers","acknowledged","count","getHostAlerts","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":";;;;;;;;;;;;;AA2oBA,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,QAAIC,aAAaX,cAAcf,oBAAd,CAAmC,KAAnC,CAAjB;AACA,QAAI2B,oBAAoBZ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2CpQ,QAAQqB,UAAnD,CAAR;AACD,iBAFD,MAEO;AACL,yBAAO,QAAKD,WAAL,CAAiBG,OAAjB,CAAyB4O,KAAzB,EAAgCnQ,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;sCAEWqF,S,EAAW;AAAA,6CACIA,SADJ;AAAA,gBAChBb,QADgB;AAAA,gBACNM,MADM;;AAErB,gBAAIkK,gBAAgBvK,KAAKC,IAAL,CAAUpD,SAASqD,KAAT,CAAe,SAAS,KAAKlC,UAA7B,IAA2C,IAArD,CAApB;AACA,gBAAIwM,iBAAiBxK,KAAKC,IAAL,CAAUjF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI4C,YAAY,KAAK9C,MAAL,KACbgC,YAAYwK,aAAb,IACClK,SAASN,QAAT,IAAqByK,cAFR,CAAhB;AAIA,mBAAO3J,SAAP;AACD;;;;;;qCAoHK3D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE+R,QAAf;AAAyB;AAC3C,UAAI,CAAC/R,EAAEyQ,KAAP,EAAc;AAACzQ,UAAEyQ,KAAF,GAAUzQ,EAAEgS,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 // Other options\n this.disableReadOnlyUsersAck = jsonData.disableReadOnlyUsersAck;\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 || target.mode === c.MODE_TEXT) {\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 }\n } else if (target.mode === c.MODE_ITEMID) {\n // Item ID mode\n if (!target.itemids) {\n return [];\n }\n return this.queryItemIdData(target, timeRange, useTrends, options);\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 // Triggers mode\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 if (target.resultFormat === 'table') {\n return responseHandler.handleHistoryAsTable(history, items, target);\n } else {\n return responseHandler.handleText(history, items, target);\n }\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 let options = {\n minSeverity: target.triggers.minSeverity,\n acknowledged: target.triggers.acknowledged,\n count: target.triggers.count,\n timeFrom: timeFrom,\n timeTo: timeTo\n };\n return this.zabbix.getHostAlerts(hostids, appids, options)\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 if (itemids.length === 0) {\n return [];\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 = /.*[<>=]{1,2}([\\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 7f626c24c..0df746203 100644 --- a/dist/datasource-zabbix/partials/config.html +++ b/dist/datasource-zabbix/partials/config.html @@ -126,3 +126,11 @@