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 @@

Alerting

+ +
+

Other

+ + +
diff --git a/dist/panel-triggers/triggers_panel_ctrl.js b/dist/panel-triggers/triggers_panel_ctrl.js index 77ba26603..8d8dc8780 100644 --- a/dist/panel-triggers/triggers_panel_ctrl.js +++ b/dist/panel-triggers/triggers_panel_ctrl.js @@ -603,6 +603,10 @@ System.register(['lodash', 'jquery', 'moment', '../datasource-zabbix/utils', 'ap var grafana_user = this.contextSrv.user.name; var ack_message = grafana_user + ' (Grafana): ' + message; return this.datasourceSrv.get(trigger.datasource).then(function (datasource) { + var userIsEditor = _this8.contextSrv.isEditor || _this8.contextSrv.isGrafanaAdmin; + if (datasource.disableReadOnlyUsersAck && !userIsEditor) { + return Promise.reject({ message: 'You have no permissions to acknowledge events.' }); + } if (eventid) { return datasource.zabbix.zabbixAPI.acknowledgeEvent(eventid, ack_message); } else { diff --git a/dist/panel-triggers/triggers_panel_ctrl.js.map b/dist/panel-triggers/triggers_panel_ctrl.js.map index 7090a2844..5fea90a50 100644 --- a/dist/panel-triggers/triggers_panel_ctrl.js.map +++ b/dist/panel-triggers/triggers_panel_ctrl.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/triggers_panel_ctrl.js"],"names":["filterTriggers","triggers","triggerFilter","utils","isRegex","_","filter","trigger","buildRegex","test","description","$","moment","PanelCtrl","triggerPanelOptionsTab","triggerPanelTriggersTab","migratePanelSchema","CURRENT_SCHEMA_VERSION","ZABBIX_DS_ID","DEFAULT_TARGET","group","host","application","tags","DEFAULT_SEVERITY","priority","severity","color","show","DEFAULT_TIME_FORMAT","PANEL_DEFAULTS","schemaVersion","datasources","targets","hostField","hostTechNameField","hostGroups","showTags","statusField","severityField","descriptionField","descriptionAtNewLine","hostsInMaintenance","showTriggers","sortTriggersBy","text","value","showEvents","limit","fontSize","pageSize","highlightBackground","highlightNewEvents","highlightNewerThan","customLastChangeFormat","lastChangeFormat","triggerSeverity","okEventColor","ackEventColor","triggerStatusMap","TriggerPanelCtrl","$scope","$injector","$timeout","datasourceSrv","templateSrv","contextSrv","dashboardSrv","scope","editorTabIndex","defaultTimeFormat","pageIndex","triggerList","currentTriggersPage","panel","defaultsDeep","cloneDeep","available_datasources","map","getZabbixDataSources","length","push","isEmpty","initDatasources","events","on","onInitEditMode","bind","onRefresh","promises","ds","get","then","datasource","Promise","all","getMetricSources","meta","id","addEditorTab","timing","queryStart","Date","getTime","queryEnd","otherPanelInFullscreenMode","error","loading","setTimeQueryStart","getTriggers","setTimeQueryEnd","render","zabbixTriggers","catch","err","cancelled","console","log","message","data","emit","triggerListUnfiltered","formatTrigger","filterTriggersPost","sortTriggers","slice","getCurrentTriggersPage","zabbix","groupFilter","replaceTemplateVars","hostFilter","appFilter","triggersOptions","getAcknowledges","setMaintenanceStatus","filterTriggersPre","addTriggerDataSource","flatten","results","eventids","lastEvent","eventid","each","event","find","acknowledges","formatAcknowledge","ack","timestamp","unix","clock","time","format","user","alias","name","surname","fullName","target","tagsFilter","replace","parseTags","every","tag","maintenance","maintenance_status","some","hosts","orderBy","zabbixTrigger","triggerObj","hostTechName","comments","lastchangeUnix","Number","lastchange","setTriggerLastChange","setTriggerSeverity","markAckEvents","age","fromNow","tagStr","split","trim","tagParts","join","tagFilter","targetTags","newTag","uniqWith","isEqual","newFilter","tagsToString","refresh","showComment","grafana_user","ack_message","zabbixAPI","acknowledgeEvent","reject","startPos","endPos","Math","min","groupNames","groups","iconClass","isNewTrigger","statusClass","mainColor","secondColor","lightTheme","highlightIntervalMs","parseInterval","durationSec","now","e","elem","attrs","ctrl","pageCount","$watchGroup","renderPanel","switchPage","renderData","getContentHeight","panelHeight","height","el","currentTarget","parseInt","$apply","appendPaginationControls","footerElem","empty","ceil","startPage","max","endPage","paginationList","i","activeClass","pageLinkElem","append","setFontSize","triggerCardElem","css","rootElem","renderingCompleted","unbindDestroy","$on","off","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmpBA,WAASA,cAAT,CAAwBC,QAAxB,EAAkCC,aAAlC,EAAiD;AAC/C,QAAIC,MAAMC,OAAN,CAAcF,aAAd,CAAJ,EAAkC;AAChC,aAAOG,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,eAAOJ,MAAMK,UAAN,CAAiBN,aAAjB,EAAgCO,IAAhC,CAAqCF,QAAQG,WAA7C,CAAP;AACD,OAFM,CAAP;AAGD,KAJD,MAIO;AACL,aAAOL,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,eAAOA,QAAQG,WAAR,KAAwBR,aAA/B;AACD,OAFM,CAAP;AAGD;AACF;;;AA7pBMG,O;;AACAM,O;;AACAC,Y;;AACKT,W;;AACJU,e,kBAAAA,S;;AACAC,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AASD,GAAT,CAAa,EAAC,UAAUrB,kBAAX,EAAb;AACAmB;AACAzB,mBAAK6B,kBAAL;AACD;;AAED,gBAAIC,gBAAgBrL,MAAMsL,GAAN,CAAU,UAAV,EAAsB,YAAW;AACnDjC,mBAAKkC,GAAL,CAAS,OAAT,EAAkB,2BAAlB;AACAF;AACD,aAHmB,CAApB;AAID;;;;QA1kBmC5O,S;;;;AA6kBtC+C,uBAAiBgM,WAAjB,GAA+B,+EAA/B","file":"triggers_panel_ctrl.js","sourcesContent":["import _ from 'lodash';\nimport $ from 'jquery';\nimport moment from 'moment';\nimport * as utils from '../datasource-zabbix/utils';\nimport {PanelCtrl} from 'app/plugins/sdk';\nimport {triggerPanelOptionsTab} from './options_tab';\nimport {triggerPanelTriggersTab} from './triggers_tab';\nimport {migratePanelSchema, CURRENT_SCHEMA_VERSION} from './migrations';\n\nconst ZABBIX_DS_ID = 'alexanderzobnin-zabbix-datasource';\n\nexport const DEFAULT_TARGET = {\n group: {filter: \"\"},\n host: {filter: \"\"},\n application: {filter: \"\"},\n trigger: {filter: \"\"},\n tags: {filter: \"\"},\n};\n\nexport const DEFAULT_SEVERITY = [\n { priority: 0, severity: 'Not classified', color: 'rgb(108, 108, 108)', show: true},\n { priority: 1, severity: 'Information', color: 'rgb(120, 158, 183)', show: true},\n { priority: 2, severity: 'Warning', color: 'rgb(175, 180, 36)', show: true},\n { priority: 3, severity: 'Average', color: 'rgb(255, 137, 30)', show: true},\n { priority: 4, severity: 'High', color: 'rgb(255, 101, 72)', show: true},\n { priority: 5, severity: 'Disaster', color: 'rgb(215, 0, 0)', show: true},\n];\n\nconst DEFAULT_TIME_FORMAT = \"DD MMM YYYY HH:mm:ss\";\n\nexport const PANEL_DEFAULTS = {\n schemaVersion: CURRENT_SCHEMA_VERSION,\n datasources: [],\n targets: {},\n // Fields\n hostField: true,\n hostTechNameField: false,\n hostGroups: false,\n showTags: true,\n statusField: true,\n severityField: true,\n descriptionField: true,\n descriptionAtNewLine: false,\n // Options\n hostsInMaintenance: true,\n showTriggers: 'all triggers',\n sortTriggersBy: { text: 'last change', value: 'lastchange' },\n showEvents: { text: 'Problems', value: '1' },\n limit: 100,\n // View options\n fontSize: '100%',\n pageSize: 10,\n highlightBackground: false,\n highlightNewEvents: false,\n highlightNewerThan: '1h',\n customLastChangeFormat: false,\n lastChangeFormat: \"\",\n // Triggers severity and colors\n triggerSeverity: DEFAULT_SEVERITY,\n okEventColor: 'rgb(56, 189, 113)',\n ackEventColor: 'rgb(56, 219, 156)'\n};\n\nconst triggerStatusMap = {\n '0': 'OK',\n '1': 'PROBLEM'\n};\n\nexport class TriggerPanelCtrl extends PanelCtrl {\n\n /** @ngInject */\n constructor($scope, $injector, $timeout, datasourceSrv, templateSrv, contextSrv, dashboardSrv) {\n super($scope, $injector);\n this.datasourceSrv = datasourceSrv;\n this.templateSrv = templateSrv;\n this.contextSrv = contextSrv;\n this.dashboardSrv = dashboardSrv;\n this.scope = $scope;\n this.$timeout = $timeout;\n\n this.editorTabIndex = 1;\n this.triggerStatusMap = triggerStatusMap;\n this.defaultTimeFormat = DEFAULT_TIME_FORMAT;\n this.pageIndex = 0;\n this.triggerList = [];\n this.currentTriggersPage = [];\n this.datasources = {};\n\n this.panel = migratePanelSchema(this.panel);\n _.defaultsDeep(this.panel, _.cloneDeep(PANEL_DEFAULTS));\n\n this.available_datasources = _.map(this.getZabbixDataSources(), 'name');\n if (this.panel.datasources.length === 0) {\n this.panel.datasources.push(this.available_datasources[0]);\n }\n if (_.isEmpty(this.panel.targets)) {\n this.panel.targets[this.panel.datasources[0]] = DEFAULT_TARGET;\n }\n\n this.initDatasources();\n this.events.on('init-edit-mode', this.onInitEditMode.bind(this));\n this.events.on('refresh', this.onRefresh.bind(this));\n }\n\n initDatasources() {\n let promises = _.map(this.panel.datasources, (ds) => {\n // Load datasource\n return this.datasourceSrv.get(ds)\n .then(datasource => {\n this.datasources[ds] = datasource;\n return datasource;\n });\n });\n return Promise.all(promises);\n }\n\n getZabbixDataSources() {\n return _.filter(this.datasourceSrv.getMetricSources(), datasource => {\n return datasource.meta.id === ZABBIX_DS_ID && datasource.value;\n });\n }\n\n onInitEditMode() {\n this.addEditorTab('Triggers', triggerPanelTriggersTab, 1);\n this.addEditorTab('Options', triggerPanelOptionsTab, 2);\n }\n\n setTimeQueryStart() {\n this.timing.queryStart = new Date().getTime();\n }\n\n setTimeQueryEnd() {\n this.timing.queryEnd = new Date().getTime();\n }\n\n onRefresh() {\n // ignore fetching data if another panel is in fullscreen\n if (this.otherPanelInFullscreenMode()) { return; }\n\n // clear loading/error state\n delete this.error;\n this.loading = true;\n this.setTimeQueryStart();\n this.pageIndex = 0;\n\n return this.getTriggers()\n .then(zabbixTriggers => {\n // Notify panel that request is finished\n this.loading = false;\n this.setTimeQueryEnd();\n\n this.render(zabbixTriggers);\n })\n .catch(err => {\n // if cancelled keep loading set to true\n if (err.cancelled) {\n console.log('Panel request cancelled', err);\n return;\n }\n\n this.loading = false;\n this.error = err.message || \"Request Error\";\n\n if (err.data) {\n if (err.data.message) {\n this.error = err.data.message;\n }\n if (err.data.error) {\n this.error = err.data.error;\n }\n }\n\n this.events.emit('data-error', err);\n console.log('Panel data error:', err);\n });\n }\n\n render(zabbixTriggers) {\n let triggers = _.cloneDeep(zabbixTriggers || this.triggerListUnfiltered);\n this.triggerListUnfiltered = _.cloneDeep(triggers);\n\n triggers = _.map(triggers, this.formatTrigger.bind(this));\n triggers = this.filterTriggersPost(triggers);\n triggers = this.sortTriggers(triggers);\n\n // Limit triggers number\n triggers = triggers.slice(0, this.panel.limit || PANEL_DEFAULTS.limit);\n\n this.triggerList = triggers;\n this.getCurrentTriggersPage();\n\n this.$timeout(() => {\n super.render(this.triggerList);\n });\n }\n\n getTriggers() {\n let promises = _.map(this.panel.datasources, (ds) => {\n return this.datasourceSrv.get(ds)\n .then(datasource => {\n var zabbix = datasource.zabbix;\n var showEvents = this.panel.showEvents.value;\n var triggerFilter = this.panel.targets[ds];\n\n // Replace template variables\n var groupFilter = datasource.replaceTemplateVars(triggerFilter.group.filter);\n var hostFilter = datasource.replaceTemplateVars(triggerFilter.host.filter);\n var appFilter = datasource.replaceTemplateVars(triggerFilter.application.filter);\n\n let triggersOptions = {\n showTriggers: showEvents\n };\n\n return zabbix.getTriggers(groupFilter, hostFilter, appFilter, triggersOptions);\n }).then((triggers) => {\n return this.getAcknowledges(triggers, ds);\n }).then((triggers) => {\n return this.setMaintenanceStatus(triggers);\n }).then((triggers) => {\n return this.filterTriggersPre(triggers, ds);\n }).then((triggers) => {\n return this.addTriggerDataSource(triggers, ds);\n });\n });\n\n return Promise.all(promises)\n .then(results => _.flatten(results));\n }\n\n getAcknowledges(triggerList, ds) {\n // Request acknowledges for trigger\n var eventids = _.map(triggerList, trigger => {\n return trigger.lastEvent.eventid;\n });\n\n return this.datasources[ds].zabbix.getAcknowledges(eventids)\n .then(events => {\n\n // Map events to triggers\n _.each(triggerList, trigger => {\n var event = _.find(events, event => {\n return event.eventid === trigger.lastEvent.eventid;\n });\n\n if (event) {\n trigger.acknowledges = _.map(event.acknowledges, this.formatAcknowledge.bind(this));\n }\n\n if (!trigger.lastEvent.eventid) {\n trigger.lastEvent = null;\n }\n });\n\n return triggerList;\n });\n }\n\n formatAcknowledge(ack) {\n let timestamp = moment.unix(ack.clock);\n if (this.panel.customLastChangeFormat) {\n ack.time = timestamp.format(this.panel.lastChangeFormat);\n } else {\n ack.time = timestamp.format(this.defaultTimeFormat);\n }\n ack.user = ack.alias || '';\n if (ack.name || ack.surname) {\n const fullName = `${ack.name || ''} ${ack.surname || ''}`;\n ack.user += ` (${fullName})`;\n }\n return ack;\n }\n\n filterTriggersPre(triggerList, ds) {\n // Filter triggers by description\n let triggerFilter = this.panel.targets[ds].trigger.filter;\n triggerFilter = this.datasources[ds].replaceTemplateVars(triggerFilter);\n if (triggerFilter) {\n triggerList = filterTriggers(triggerList, triggerFilter);\n }\n\n // Filter by tags\n const target = this.panel.targets[ds];\n if (target.tags.filter) {\n let tagsFilter = this.datasources[ds].replaceTemplateVars(target.tags.filter);\n // replaceTemplateVars() builds regex-like string, so we should trim it.\n tagsFilter = tagsFilter.replace('/^', '').replace('$/', '');\n const tags = this.parseTags(tagsFilter);\n triggerList = _.filter(triggerList, trigger => {\n return _.every(tags, (tag) => {\n return _.find(trigger.tags, {tag: tag.tag, value: tag.value});\n });\n });\n }\n\n return triggerList;\n }\n\n filterTriggersPost(triggers) {\n let triggerList = _.cloneDeep(triggers);\n\n // Filter acknowledged triggers\n if (this.panel.showTriggers === 'unacknowledged') {\n triggerList = _.filter(triggerList, trigger => {\n return !trigger.acknowledges;\n });\n } else if (this.panel.showTriggers === 'acknowledged') {\n triggerList = _.filter(triggerList, 'acknowledges');\n } else {\n triggerList = triggerList;\n }\n\n // Filter by maintenance status\n if (!this.panel.hostsInMaintenance) {\n triggerList = _.filter(triggerList, (trigger) => trigger.maintenance === false);\n }\n\n // Filter triggers by severity\n triggerList = _.filter(triggerList, trigger => {\n return this.panel.triggerSeverity[trigger.priority].show;\n });\n\n return triggerList;\n }\n\n setMaintenanceStatus(triggers) {\n _.each(triggers, (trigger) => {\n let maintenance_status = _.some(trigger.hosts, (host) => host.maintenance_status === '1');\n trigger.maintenance = maintenance_status;\n });\n return triggers;\n }\n\n addTriggerDataSource(triggers, ds) {\n _.each(triggers, (trigger) => {\n trigger.datasource = ds;\n });\n return triggers;\n }\n\n sortTriggers(triggerList) {\n if (this.panel.sortTriggersBy.value === 'priority') {\n triggerList = _.orderBy(triggerList, ['priority', 'lastchangeUnix', 'triggerid'], ['desc', 'desc', 'desc']);\n } else {\n triggerList = _.orderBy(triggerList, ['lastchangeUnix', 'priority', 'triggerid'], ['desc', 'desc', 'desc']);\n }\n return triggerList;\n }\n\n formatTrigger(zabbixTrigger) {\n let trigger = _.cloneDeep(zabbixTrigger);\n let triggerObj = trigger;\n\n // Set host that the trigger belongs\n if (trigger.hosts && trigger.hosts.length) {\n triggerObj.host = trigger.hosts[0].name;\n triggerObj.hostTechName = trigger.hosts[0].host;\n }\n\n // Set tags if present\n if (trigger.tags && trigger.tags.length === 0) {\n trigger.tags = null;\n }\n\n // Handle multi-line description\n if (trigger.comments) {\n trigger.comments = trigger.comments.replace('\\n', '
');\n }\n\n // Format last change and age\n trigger.lastchangeUnix = Number(trigger.lastchange);\n triggerObj = this.setTriggerLastChange(triggerObj);\n triggerObj = this.setTriggerSeverity(triggerObj);\n return triggerObj;\n }\n\n updateTriggerFormat(trigger) {\n trigger = this.setTriggerLastChange(trigger);\n trigger = this.setTriggerSeverity(trigger);\n return trigger;\n }\n\n setTriggerSeverity(trigger) {\n if (trigger.value === '1') {\n // Problem state\n trigger.color = this.panel.triggerSeverity[trigger.priority].color;\n } else {\n // OK state\n trigger.color = this.panel.okEventColor;\n }\n trigger.severity = this.panel.triggerSeverity[trigger.priority].severity;\n\n // Mark acknowledged triggers with different color\n if (this.panel.markAckEvents && trigger.acknowledges && trigger.acknowledges.length) {\n trigger.color = this.panel.ackEventColor;\n }\n\n return trigger;\n }\n\n setTriggerLastChange(trigger) {\n if (!trigger.lastchangeUnix) {\n trigger.lastchange = \"\";\n trigger.age = \"\";\n return trigger;\n }\n\n let timestamp = moment.unix(trigger.lastchangeUnix);\n if (this.panel.customLastChangeFormat) {\n // User defined format\n trigger.lastchange = timestamp.format(this.panel.lastChangeFormat);\n } else {\n trigger.lastchange = timestamp.format(this.defaultTimeFormat);\n }\n trigger.age = timestamp.fromNow(true);\n return trigger;\n }\n\n parseTags(tagStr) {\n if (!tagStr) {\n return [];\n }\n\n let tags = _.map(tagStr.split(','), (tag) => tag.trim());\n tags = _.map(tags, (tag) => {\n const tagParts = tag.split(':');\n return {tag: tagParts[0].trim(), value: tagParts[1].trim()};\n });\n return tags;\n }\n\n tagsToString(tags) {\n return _.map(tags, (tag) => `${tag.tag}:${tag.value}`).join(', ');\n }\n\n addTagFilter(tag, ds) {\n let tagFilter = this.panel.targets[ds].tags.filter;\n let targetTags = this.parseTags(tagFilter);\n let newTag = {tag: tag.tag, value: tag.value};\n targetTags.push(newTag);\n targetTags = _.uniqWith(targetTags, _.isEqual);\n let newFilter = this.tagsToString(targetTags);\n this.panel.targets[ds].tags.filter = newFilter;\n this.refresh();\n }\n\n switchComment(trigger) {\n trigger.showComment = !trigger.showComment;\n }\n\n acknowledgeTrigger(trigger, message) {\n let eventid = trigger.lastEvent ? trigger.lastEvent.eventid : null;\n let grafana_user = this.contextSrv.user.name;\n let ack_message = grafana_user + ' (Grafana): ' + message;\n return this.datasourceSrv.get(trigger.datasource)\n .then(datasource => {\n if (eventid) {\n return datasource.zabbix.zabbixAPI.acknowledgeEvent(eventid, ack_message);\n } else {\n return Promise.reject({message: 'Trigger has no events. Nothing to acknowledge.'});\n }\n })\n .then(this.onRefresh.bind(this))\n .catch((err) => {\n this.error = err.message || \"Acknowledge Error\";\n this.events.emit('data-error', err);\n console.log('Panel data error:', err);\n });\n }\n\n getCurrentTriggersPage() {\n let pageSize = this.panel.pageSize || PANEL_DEFAULTS.pageSize;\n let startPos = this.pageIndex * pageSize;\n let endPos = Math.min(startPos + pageSize, this.triggerList.length);\n this.currentTriggersPage = this.triggerList.slice(startPos, endPos);\n return this.currentTriggersPage;\n }\n\n formatHostName(trigger) {\n let host = \"\";\n if (this.panel.hostField && this.panel.hostTechNameField) {\n host = `${trigger.host} (${trigger.hostTechName})`;\n } else if (this.panel.hostField || this.panel.hostTechNameField) {\n host = this.panel.hostField ? trigger.host : trigger.hostTechName;\n }\n\n return host;\n }\n\n formatHostGroups(trigger) {\n let groupNames = \"\";\n if (this.panel.hostGroups) {\n let groups = _.map(trigger.groups, 'name').join(', ');\n groupNames += `[ ${groups} ]`;\n }\n\n return groupNames;\n }\n\n getAlertIconClass(trigger) {\n let iconClass = '';\n if (trigger.value === '1') {\n if (trigger.priority >= 3) {\n iconClass = 'icon-gf-critical';\n } else {\n iconClass = 'icon-gf-warning';\n }\n } else {\n iconClass = 'icon-gf-online';\n }\n\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\n iconClass += ' zabbix-trigger--blinked';\n }\n return iconClass;\n }\n\n getAlertIconClassBySeverity(triggerSeverity) {\n let iconClass = 'icon-gf-warning';\n if (triggerSeverity.priority >= 3) {\n iconClass = 'icon-gf-critical';\n }\n return iconClass;\n }\n\n getAlertStateClass(trigger) {\n let statusClass = '';\n\n if (trigger.value === '1') {\n statusClass = 'alert-state-critical';\n } else {\n statusClass = 'alert-state-ok';\n }\n\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\n statusClass += ' zabbix-trigger--blinked';\n }\n\n return statusClass;\n }\n\n getBackground(trigger) {\n const mainColor = trigger.color;\n const secondColor = this.contextSrv.user.lightTheme ? '#dde4ed' : '#262628';\n if (this.contextSrv.user.lightTheme) {\n return `linear-gradient(135deg, ${secondColor}, ${mainColor})`;\n }\n return `linear-gradient(135deg, ${mainColor}, ${secondColor})`;\n }\n\n isNewTrigger(trigger) {\n try {\n const highlightIntervalMs = utils.parseInterval(this.panel.highlightNewerThan || PANEL_DEFAULTS.highlightNewerThan);\n const durationSec = (Date.now() - trigger.lastchangeUnix * 1000);\n return durationSec < highlightIntervalMs;\n } catch (e) {\n return false;\n }\n }\n\n link(scope, elem, attrs, ctrl) {\n let panel = ctrl.panel;\n let pageCount = 0;\n let triggerList = ctrl.triggerList;\n\n scope.$watchGroup(['ctrl.currentTriggersPage', 'ctrl.triggerList'], renderPanel);\n elem.on('click', '.triggers-panel-page-link', switchPage);\n ctrl.events.on('render', (renderData) => {\n triggerList = renderData || triggerList;\n renderPanel();\n });\n\n function getContentHeight() {\n let panelHeight = ctrl.height;\n if (pageCount > 1) {\n panelHeight -= 36;\n }\n return panelHeight + 'px';\n }\n\n function switchPage(e) {\n let el = $(e.currentTarget);\n ctrl.pageIndex = (parseInt(el.text(), 10)-1);\n\n let pageSize = panel.pageSize || 10;\n let startPos = ctrl.pageIndex * pageSize;\n let endPos = Math.min(startPos + pageSize, triggerList.length);\n ctrl.currentTriggersPage = triggerList.slice(startPos, endPos);\n\n scope.$apply(() => {\n renderPanel();\n });\n }\n\n function appendPaginationControls(footerElem) {\n footerElem.empty();\n\n let pageSize = panel.pageSize || 5;\n pageCount = Math.ceil(triggerList.length / pageSize);\n if (pageCount === 1) {\n return;\n }\n\n let startPage = Math.max(ctrl.pageIndex - 3, 0);\n let endPage = Math.min(pageCount, startPage + 9);\n\n let paginationList = $('');\n\n for (let i = startPage; i < endPage; i++) {\n let activeClass = i === ctrl.pageIndex ? 'active' : '';\n let pageLinkElem = $('
  • ' + (i+1) + '
  • ');\n paginationList.append(pageLinkElem);\n }\n\n footerElem.append(paginationList);\n }\n\n function setFontSize() {\n const fontSize = parseInt(panel.fontSize.slice(0, panel.fontSize.length - 1));\n let triggerCardElem = elem.find('.alert-rule-item');\n if (fontSize && fontSize !== 100) {\n triggerCardElem.find('.alert-rule-item__icon').css({\n 'font-size': fontSize + '%',\n 'margin': fontSize / 100 * 6 + 'px'\n });\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': fontSize + '%'});\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': fontSize * 0.8 + '%'});\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': fontSize * 0.8 + '%'});\n triggerCardElem.find('.zbx-tag').css({'font-size': fontSize * 0.6 + '%'});\n triggerCardElem.find('.zbx-tag').css({'line-height': fontSize / 100 * 16 + 'px'});\n } else {\n // remove css\n triggerCardElem.find('.alert-rule-item__icon').css({'font-size': '', 'margin-right': ''});\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': ''});\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': ''});\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': ''});\n triggerCardElem.find('.zbx-tag').css({'font-size': ''});\n triggerCardElem.find('.zbx-tag').css({'line-height': ''});\n }\n }\n\n function renderPanel() {\n let rootElem = elem.find('.triggers-panel-scroll');\n let footerElem = elem.find('.triggers-panel-footer');\n appendPaginationControls(footerElem);\n rootElem.css({'max-height': getContentHeight()});\n rootElem.css({'height': getContentHeight()});\n setFontSize();\n ctrl.renderingCompleted();\n }\n\n let unbindDestroy = scope.$on('$destroy', function() {\n elem.off('click', '.triggers-panel-page-link');\n unbindDestroy();\n });\n }\n}\n\nTriggerPanelCtrl.templateUrl = 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/module.html';\n\nfunction filterTriggers(triggers, triggerFilter) {\n if (utils.isRegex(triggerFilter)) {\n return _.filter(triggers, function(trigger) {\n return utils.buildRegex(triggerFilter).test(trigger.description);\n });\n } else {\n return _.filter(triggers, function(trigger) {\n return trigger.description === triggerFilter;\n });\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/triggers_panel_ctrl.js"],"names":["filterTriggers","triggers","triggerFilter","utils","isRegex","_","filter","trigger","buildRegex","test","description","$","moment","PanelCtrl","triggerPanelOptionsTab","triggerPanelTriggersTab","migratePanelSchema","CURRENT_SCHEMA_VERSION","ZABBIX_DS_ID","DEFAULT_TARGET","group","host","application","tags","DEFAULT_SEVERITY","priority","severity","color","show","DEFAULT_TIME_FORMAT","PANEL_DEFAULTS","schemaVersion","datasources","targets","hostField","hostTechNameField","hostGroups","showTags","statusField","severityField","descriptionField","descriptionAtNewLine","hostsInMaintenance","showTriggers","sortTriggersBy","text","value","showEvents","limit","fontSize","pageSize","highlightBackground","highlightNewEvents","highlightNewerThan","customLastChangeFormat","lastChangeFormat","triggerSeverity","okEventColor","ackEventColor","triggerStatusMap","TriggerPanelCtrl","$scope","$injector","$timeout","datasourceSrv","templateSrv","contextSrv","dashboardSrv","scope","editorTabIndex","defaultTimeFormat","pageIndex","triggerList","currentTriggersPage","panel","defaultsDeep","cloneDeep","available_datasources","map","getZabbixDataSources","length","push","isEmpty","initDatasources","events","on","onInitEditMode","bind","onRefresh","promises","ds","get","then","datasource","Promise","all","getMetricSources","meta","id","addEditorTab","timing","queryStart","Date","getTime","queryEnd","otherPanelInFullscreenMode","error","loading","setTimeQueryStart","getTriggers","setTimeQueryEnd","render","zabbixTriggers","catch","err","cancelled","console","log","message","data","emit","triggerListUnfiltered","formatTrigger","filterTriggersPost","sortTriggers","slice","getCurrentTriggersPage","zabbix","groupFilter","replaceTemplateVars","hostFilter","appFilter","triggersOptions","getAcknowledges","setMaintenanceStatus","filterTriggersPre","addTriggerDataSource","flatten","results","eventids","lastEvent","eventid","each","event","find","acknowledges","formatAcknowledge","ack","timestamp","unix","clock","time","format","user","alias","name","surname","fullName","target","tagsFilter","replace","parseTags","every","tag","maintenance","maintenance_status","some","hosts","orderBy","zabbixTrigger","triggerObj","hostTechName","comments","lastchangeUnix","Number","lastchange","setTriggerLastChange","setTriggerSeverity","markAckEvents","age","fromNow","tagStr","split","trim","tagParts","join","tagFilter","targetTags","newTag","uniqWith","isEqual","newFilter","tagsToString","refresh","showComment","grafana_user","ack_message","userIsEditor","isEditor","isGrafanaAdmin","disableReadOnlyUsersAck","reject","zabbixAPI","acknowledgeEvent","startPos","endPos","Math","min","groupNames","groups","iconClass","isNewTrigger","statusClass","mainColor","secondColor","lightTheme","highlightIntervalMs","parseInterval","durationSec","now","e","elem","attrs","ctrl","pageCount","$watchGroup","renderPanel","switchPage","renderData","getContentHeight","panelHeight","height","el","currentTarget","parseInt","$apply","appendPaginationControls","footerElem","empty","ceil","startPage","max","endPage","paginationList","i","activeClass","pageLinkElem","append","setFontSize","triggerCardElem","css","rootElem","renderingCompleted","unbindDestroy","$on","off","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAupBA,WAASA,cAAT,CAAwBC,QAAxB,EAAkCC,aAAlC,EAAiD;AAC/C,QAAIC,MAAMC,OAAN,CAAcF,aAAd,CAAJ,EAAkC;AAChC,aAAOG,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,eAAOJ,MAAMK,UAAN,CAAiBN,aAAjB,EAAgCO,IAAhC,CAAqCF,QAAQG,WAA7C,CAAP;AACD,OAFM,CAAP;AAG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CAAoD,EAAC,aAAa,EAAd,EAApD;AACAD,gCAAgBzG,IAAhB,CAAqB,UAArB,EAAiC0G,GAAjC,CAAqC,EAAC,aAAa,EAAd,EAArC;AACAD,gCAAgBzG,IAAhB,CAAqB,UAArB,EAAiC0G,GAAjC,CAAqC,EAAC,eAAe,EAAhB,EAArC;AACD;AACF;;AAED,qBAASxB,WAAT,GAAuB;AACrB,kBAAIyB,WAAW9B,KAAK7E,IAAL,CAAU,wBAAV,CAAf;AACA,kBAAI6F,aAAahB,KAAK7E,IAAL,CAAU,wBAAV,CAAjB;AACA4F,uCAAyBC,UAAzB;AACAc,uBAASD,GAAT,CAAa,EAAC,cAAcrB,kBAAf,EAAb;AACAsB,uBAASD,GAAT,CAAa,EAAC,UAAUrB,kBAAX,EAAb;AACAmB;AACAzB,mBAAK6B,kBAAL;AACD;;AAED,gBAAIC,gBAAgBzL,MAAM0L,GAAN,CAAU,UAAV,EAAsB,YAAW;AACnDjC,mBAAKkC,GAAL,CAAS,OAAT,EAAkB,2BAAlB;AACAF;AACD,aAHmB,CAApB;AAID;;;;QA9kBmChP,S;;;;AAilBtC+C,uBAAiBoM,WAAjB,GAA+B,+EAA/B","file":"triggers_panel_ctrl.js","sourcesContent":["import _ from 'lodash';\nimport $ from 'jquery';\nimport moment from 'moment';\nimport * as utils from '../datasource-zabbix/utils';\nimport {PanelCtrl} from 'app/plugins/sdk';\nimport {triggerPanelOptionsTab} from './options_tab';\nimport {triggerPanelTriggersTab} from './triggers_tab';\nimport {migratePanelSchema, CURRENT_SCHEMA_VERSION} from './migrations';\n\nconst ZABBIX_DS_ID = 'alexanderzobnin-zabbix-datasource';\n\nexport const DEFAULT_TARGET = {\n group: {filter: \"\"},\n host: {filter: \"\"},\n application: {filter: \"\"},\n trigger: {filter: \"\"},\n tags: {filter: \"\"},\n};\n\nexport const DEFAULT_SEVERITY = [\n { priority: 0, severity: 'Not classified', color: 'rgb(108, 108, 108)', show: true},\n { priority: 1, severity: 'Information', color: 'rgb(120, 158, 183)', show: true},\n { priority: 2, severity: 'Warning', color: 'rgb(175, 180, 36)', show: true},\n { priority: 3, severity: 'Average', color: 'rgb(255, 137, 30)', show: true},\n { priority: 4, severity: 'High', color: 'rgb(255, 101, 72)', show: true},\n { priority: 5, severity: 'Disaster', color: 'rgb(215, 0, 0)', show: true},\n];\n\nconst DEFAULT_TIME_FORMAT = \"DD MMM YYYY HH:mm:ss\";\n\nexport const PANEL_DEFAULTS = {\n schemaVersion: CURRENT_SCHEMA_VERSION,\n datasources: [],\n targets: {},\n // Fields\n hostField: true,\n hostTechNameField: false,\n hostGroups: false,\n showTags: true,\n statusField: true,\n severityField: true,\n descriptionField: true,\n descriptionAtNewLine: false,\n // Options\n hostsInMaintenance: true,\n showTriggers: 'all triggers',\n sortTriggersBy: { text: 'last change', value: 'lastchange' },\n showEvents: { text: 'Problems', value: '1' },\n limit: 100,\n // View options\n fontSize: '100%',\n pageSize: 10,\n highlightBackground: false,\n highlightNewEvents: false,\n highlightNewerThan: '1h',\n customLastChangeFormat: false,\n lastChangeFormat: \"\",\n // Triggers severity and colors\n triggerSeverity: DEFAULT_SEVERITY,\n okEventColor: 'rgb(56, 189, 113)',\n ackEventColor: 'rgb(56, 219, 156)'\n};\n\nconst triggerStatusMap = {\n '0': 'OK',\n '1': 'PROBLEM'\n};\n\nexport class TriggerPanelCtrl extends PanelCtrl {\n\n /** @ngInject */\n constructor($scope, $injector, $timeout, datasourceSrv, templateSrv, contextSrv, dashboardSrv) {\n super($scope, $injector);\n this.datasourceSrv = datasourceSrv;\n this.templateSrv = templateSrv;\n this.contextSrv = contextSrv;\n this.dashboardSrv = dashboardSrv;\n this.scope = $scope;\n this.$timeout = $timeout;\n\n this.editorTabIndex = 1;\n this.triggerStatusMap = triggerStatusMap;\n this.defaultTimeFormat = DEFAULT_TIME_FORMAT;\n this.pageIndex = 0;\n this.triggerList = [];\n this.currentTriggersPage = [];\n this.datasources = {};\n\n this.panel = migratePanelSchema(this.panel);\n _.defaultsDeep(this.panel, _.cloneDeep(PANEL_DEFAULTS));\n\n this.available_datasources = _.map(this.getZabbixDataSources(), 'name');\n if (this.panel.datasources.length === 0) {\n this.panel.datasources.push(this.available_datasources[0]);\n }\n if (_.isEmpty(this.panel.targets)) {\n this.panel.targets[this.panel.datasources[0]] = DEFAULT_TARGET;\n }\n\n this.initDatasources();\n this.events.on('init-edit-mode', this.onInitEditMode.bind(this));\n this.events.on('refresh', this.onRefresh.bind(this));\n }\n\n initDatasources() {\n let promises = _.map(this.panel.datasources, (ds) => {\n // Load datasource\n return this.datasourceSrv.get(ds)\n .then(datasource => {\n this.datasources[ds] = datasource;\n return datasource;\n });\n });\n return Promise.all(promises);\n }\n\n getZabbixDataSources() {\n return _.filter(this.datasourceSrv.getMetricSources(), datasource => {\n return datasource.meta.id === ZABBIX_DS_ID && datasource.value;\n });\n }\n\n onInitEditMode() {\n this.addEditorTab('Triggers', triggerPanelTriggersTab, 1);\n this.addEditorTab('Options', triggerPanelOptionsTab, 2);\n }\n\n setTimeQueryStart() {\n this.timing.queryStart = new Date().getTime();\n }\n\n setTimeQueryEnd() {\n this.timing.queryEnd = new Date().getTime();\n }\n\n onRefresh() {\n // ignore fetching data if another panel is in fullscreen\n if (this.otherPanelInFullscreenMode()) { return; }\n\n // clear loading/error state\n delete this.error;\n this.loading = true;\n this.setTimeQueryStart();\n this.pageIndex = 0;\n\n return this.getTriggers()\n .then(zabbixTriggers => {\n // Notify panel that request is finished\n this.loading = false;\n this.setTimeQueryEnd();\n\n this.render(zabbixTriggers);\n })\n .catch(err => {\n // if cancelled keep loading set to true\n if (err.cancelled) {\n console.log('Panel request cancelled', err);\n return;\n }\n\n this.loading = false;\n this.error = err.message || \"Request Error\";\n\n if (err.data) {\n if (err.data.message) {\n this.error = err.data.message;\n }\n if (err.data.error) {\n this.error = err.data.error;\n }\n }\n\n this.events.emit('data-error', err);\n console.log('Panel data error:', err);\n });\n }\n\n render(zabbixTriggers) {\n let triggers = _.cloneDeep(zabbixTriggers || this.triggerListUnfiltered);\n this.triggerListUnfiltered = _.cloneDeep(triggers);\n\n triggers = _.map(triggers, this.formatTrigger.bind(this));\n triggers = this.filterTriggersPost(triggers);\n triggers = this.sortTriggers(triggers);\n\n // Limit triggers number\n triggers = triggers.slice(0, this.panel.limit || PANEL_DEFAULTS.limit);\n\n this.triggerList = triggers;\n this.getCurrentTriggersPage();\n\n this.$timeout(() => {\n super.render(this.triggerList);\n });\n }\n\n getTriggers() {\n let promises = _.map(this.panel.datasources, (ds) => {\n return this.datasourceSrv.get(ds)\n .then(datasource => {\n var zabbix = datasource.zabbix;\n var showEvents = this.panel.showEvents.value;\n var triggerFilter = this.panel.targets[ds];\n\n // Replace template variables\n var groupFilter = datasource.replaceTemplateVars(triggerFilter.group.filter);\n var hostFilter = datasource.replaceTemplateVars(triggerFilter.host.filter);\n var appFilter = datasource.replaceTemplateVars(triggerFilter.application.filter);\n\n let triggersOptions = {\n showTriggers: showEvents\n };\n\n return zabbix.getTriggers(groupFilter, hostFilter, appFilter, triggersOptions);\n }).then((triggers) => {\n return this.getAcknowledges(triggers, ds);\n }).then((triggers) => {\n return this.setMaintenanceStatus(triggers);\n }).then((triggers) => {\n return this.filterTriggersPre(triggers, ds);\n }).then((triggers) => {\n return this.addTriggerDataSource(triggers, ds);\n });\n });\n\n return Promise.all(promises)\n .then(results => _.flatten(results));\n }\n\n getAcknowledges(triggerList, ds) {\n // Request acknowledges for trigger\n var eventids = _.map(triggerList, trigger => {\n return trigger.lastEvent.eventid;\n });\n\n return this.datasources[ds].zabbix.getAcknowledges(eventids)\n .then(events => {\n\n // Map events to triggers\n _.each(triggerList, trigger => {\n var event = _.find(events, event => {\n return event.eventid === trigger.lastEvent.eventid;\n });\n\n if (event) {\n trigger.acknowledges = _.map(event.acknowledges, this.formatAcknowledge.bind(this));\n }\n\n if (!trigger.lastEvent.eventid) {\n trigger.lastEvent = null;\n }\n });\n\n return triggerList;\n });\n }\n\n formatAcknowledge(ack) {\n let timestamp = moment.unix(ack.clock);\n if (this.panel.customLastChangeFormat) {\n ack.time = timestamp.format(this.panel.lastChangeFormat);\n } else {\n ack.time = timestamp.format(this.defaultTimeFormat);\n }\n ack.user = ack.alias || '';\n if (ack.name || ack.surname) {\n const fullName = `${ack.name || ''} ${ack.surname || ''}`;\n ack.user += ` (${fullName})`;\n }\n return ack;\n }\n\n filterTriggersPre(triggerList, ds) {\n // Filter triggers by description\n let triggerFilter = this.panel.targets[ds].trigger.filter;\n triggerFilter = this.datasources[ds].replaceTemplateVars(triggerFilter);\n if (triggerFilter) {\n triggerList = filterTriggers(triggerList, triggerFilter);\n }\n\n // Filter by tags\n const target = this.panel.targets[ds];\n if (target.tags.filter) {\n let tagsFilter = this.datasources[ds].replaceTemplateVars(target.tags.filter);\n // replaceTemplateVars() builds regex-like string, so we should trim it.\n tagsFilter = tagsFilter.replace('/^', '').replace('$/', '');\n const tags = this.parseTags(tagsFilter);\n triggerList = _.filter(triggerList, trigger => {\n return _.every(tags, (tag) => {\n return _.find(trigger.tags, {tag: tag.tag, value: tag.value});\n });\n });\n }\n\n return triggerList;\n }\n\n filterTriggersPost(triggers) {\n let triggerList = _.cloneDeep(triggers);\n\n // Filter acknowledged triggers\n if (this.panel.showTriggers === 'unacknowledged') {\n triggerList = _.filter(triggerList, trigger => {\n return !trigger.acknowledges;\n });\n } else if (this.panel.showTriggers === 'acknowledged') {\n triggerList = _.filter(triggerList, 'acknowledges');\n } else {\n triggerList = triggerList;\n }\n\n // Filter by maintenance status\n if (!this.panel.hostsInMaintenance) {\n triggerList = _.filter(triggerList, (trigger) => trigger.maintenance === false);\n }\n\n // Filter triggers by severity\n triggerList = _.filter(triggerList, trigger => {\n return this.panel.triggerSeverity[trigger.priority].show;\n });\n\n return triggerList;\n }\n\n setMaintenanceStatus(triggers) {\n _.each(triggers, (trigger) => {\n let maintenance_status = _.some(trigger.hosts, (host) => host.maintenance_status === '1');\n trigger.maintenance = maintenance_status;\n });\n return triggers;\n }\n\n addTriggerDataSource(triggers, ds) {\n _.each(triggers, (trigger) => {\n trigger.datasource = ds;\n });\n return triggers;\n }\n\n sortTriggers(triggerList) {\n if (this.panel.sortTriggersBy.value === 'priority') {\n triggerList = _.orderBy(triggerList, ['priority', 'lastchangeUnix', 'triggerid'], ['desc', 'desc', 'desc']);\n } else {\n triggerList = _.orderBy(triggerList, ['lastchangeUnix', 'priority', 'triggerid'], ['desc', 'desc', 'desc']);\n }\n return triggerList;\n }\n\n formatTrigger(zabbixTrigger) {\n let trigger = _.cloneDeep(zabbixTrigger);\n let triggerObj = trigger;\n\n // Set host that the trigger belongs\n if (trigger.hosts && trigger.hosts.length) {\n triggerObj.host = trigger.hosts[0].name;\n triggerObj.hostTechName = trigger.hosts[0].host;\n }\n\n // Set tags if present\n if (trigger.tags && trigger.tags.length === 0) {\n trigger.tags = null;\n }\n\n // Handle multi-line description\n if (trigger.comments) {\n trigger.comments = trigger.comments.replace('\\n', '
    ');\n }\n\n // Format last change and age\n trigger.lastchangeUnix = Number(trigger.lastchange);\n triggerObj = this.setTriggerLastChange(triggerObj);\n triggerObj = this.setTriggerSeverity(triggerObj);\n return triggerObj;\n }\n\n updateTriggerFormat(trigger) {\n trigger = this.setTriggerLastChange(trigger);\n trigger = this.setTriggerSeverity(trigger);\n return trigger;\n }\n\n setTriggerSeverity(trigger) {\n if (trigger.value === '1') {\n // Problem state\n trigger.color = this.panel.triggerSeverity[trigger.priority].color;\n } else {\n // OK state\n trigger.color = this.panel.okEventColor;\n }\n trigger.severity = this.panel.triggerSeverity[trigger.priority].severity;\n\n // Mark acknowledged triggers with different color\n if (this.panel.markAckEvents && trigger.acknowledges && trigger.acknowledges.length) {\n trigger.color = this.panel.ackEventColor;\n }\n\n return trigger;\n }\n\n setTriggerLastChange(trigger) {\n if (!trigger.lastchangeUnix) {\n trigger.lastchange = \"\";\n trigger.age = \"\";\n return trigger;\n }\n\n let timestamp = moment.unix(trigger.lastchangeUnix);\n if (this.panel.customLastChangeFormat) {\n // User defined format\n trigger.lastchange = timestamp.format(this.panel.lastChangeFormat);\n } else {\n trigger.lastchange = timestamp.format(this.defaultTimeFormat);\n }\n trigger.age = timestamp.fromNow(true);\n return trigger;\n }\n\n parseTags(tagStr) {\n if (!tagStr) {\n return [];\n }\n\n let tags = _.map(tagStr.split(','), (tag) => tag.trim());\n tags = _.map(tags, (tag) => {\n const tagParts = tag.split(':');\n return {tag: tagParts[0].trim(), value: tagParts[1].trim()};\n });\n return tags;\n }\n\n tagsToString(tags) {\n return _.map(tags, (tag) => `${tag.tag}:${tag.value}`).join(', ');\n }\n\n addTagFilter(tag, ds) {\n let tagFilter = this.panel.targets[ds].tags.filter;\n let targetTags = this.parseTags(tagFilter);\n let newTag = {tag: tag.tag, value: tag.value};\n targetTags.push(newTag);\n targetTags = _.uniqWith(targetTags, _.isEqual);\n let newFilter = this.tagsToString(targetTags);\n this.panel.targets[ds].tags.filter = newFilter;\n this.refresh();\n }\n\n switchComment(trigger) {\n trigger.showComment = !trigger.showComment;\n }\n\n acknowledgeTrigger(trigger, message) {\n let eventid = trigger.lastEvent ? trigger.lastEvent.eventid : null;\n let grafana_user = this.contextSrv.user.name;\n let ack_message = grafana_user + ' (Grafana): ' + message;\n return this.datasourceSrv.get(trigger.datasource)\n .then(datasource => {\n const userIsEditor = this.contextSrv.isEditor || this.contextSrv.isGrafanaAdmin;\n if (datasource.disableReadOnlyUsersAck && !userIsEditor) {\n return Promise.reject({message: 'You have no permissions to acknowledge events.'});\n }\n if (eventid) {\n return datasource.zabbix.zabbixAPI.acknowledgeEvent(eventid, ack_message);\n } else {\n return Promise.reject({message: 'Trigger has no events. Nothing to acknowledge.'});\n }\n })\n .then(this.onRefresh.bind(this))\n .catch((err) => {\n this.error = err.message || \"Acknowledge Error\";\n this.events.emit('data-error', err);\n console.log('Panel data error:', err);\n });\n }\n\n getCurrentTriggersPage() {\n let pageSize = this.panel.pageSize || PANEL_DEFAULTS.pageSize;\n let startPos = this.pageIndex * pageSize;\n let endPos = Math.min(startPos + pageSize, this.triggerList.length);\n this.currentTriggersPage = this.triggerList.slice(startPos, endPos);\n return this.currentTriggersPage;\n }\n\n formatHostName(trigger) {\n let host = \"\";\n if (this.panel.hostField && this.panel.hostTechNameField) {\n host = `${trigger.host} (${trigger.hostTechName})`;\n } else if (this.panel.hostField || this.panel.hostTechNameField) {\n host = this.panel.hostField ? trigger.host : trigger.hostTechName;\n }\n\n return host;\n }\n\n formatHostGroups(trigger) {\n let groupNames = \"\";\n if (this.panel.hostGroups) {\n let groups = _.map(trigger.groups, 'name').join(', ');\n groupNames += `[ ${groups} ]`;\n }\n\n return groupNames;\n }\n\n getAlertIconClass(trigger) {\n let iconClass = '';\n if (trigger.value === '1') {\n if (trigger.priority >= 3) {\n iconClass = 'icon-gf-critical';\n } else {\n iconClass = 'icon-gf-warning';\n }\n } else {\n iconClass = 'icon-gf-online';\n }\n\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\n iconClass += ' zabbix-trigger--blinked';\n }\n return iconClass;\n }\n\n getAlertIconClassBySeverity(triggerSeverity) {\n let iconClass = 'icon-gf-warning';\n if (triggerSeverity.priority >= 3) {\n iconClass = 'icon-gf-critical';\n }\n return iconClass;\n }\n\n getAlertStateClass(trigger) {\n let statusClass = '';\n\n if (trigger.value === '1') {\n statusClass = 'alert-state-critical';\n } else {\n statusClass = 'alert-state-ok';\n }\n\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\n statusClass += ' zabbix-trigger--blinked';\n }\n\n return statusClass;\n }\n\n getBackground(trigger) {\n const mainColor = trigger.color;\n const secondColor = this.contextSrv.user.lightTheme ? '#dde4ed' : '#262628';\n if (this.contextSrv.user.lightTheme) {\n return `linear-gradient(135deg, ${secondColor}, ${mainColor})`;\n }\n return `linear-gradient(135deg, ${mainColor}, ${secondColor})`;\n }\n\n isNewTrigger(trigger) {\n try {\n const highlightIntervalMs = utils.parseInterval(this.panel.highlightNewerThan || PANEL_DEFAULTS.highlightNewerThan);\n const durationSec = (Date.now() - trigger.lastchangeUnix * 1000);\n return durationSec < highlightIntervalMs;\n } catch (e) {\n return false;\n }\n }\n\n link(scope, elem, attrs, ctrl) {\n let panel = ctrl.panel;\n let pageCount = 0;\n let triggerList = ctrl.triggerList;\n\n scope.$watchGroup(['ctrl.currentTriggersPage', 'ctrl.triggerList'], renderPanel);\n elem.on('click', '.triggers-panel-page-link', switchPage);\n ctrl.events.on('render', (renderData) => {\n triggerList = renderData || triggerList;\n renderPanel();\n });\n\n function getContentHeight() {\n let panelHeight = ctrl.height;\n if (pageCount > 1) {\n panelHeight -= 36;\n }\n return panelHeight + 'px';\n }\n\n function switchPage(e) {\n let el = $(e.currentTarget);\n ctrl.pageIndex = (parseInt(el.text(), 10)-1);\n\n let pageSize = panel.pageSize || 10;\n let startPos = ctrl.pageIndex * pageSize;\n let endPos = Math.min(startPos + pageSize, triggerList.length);\n ctrl.currentTriggersPage = triggerList.slice(startPos, endPos);\n\n scope.$apply(() => {\n renderPanel();\n });\n }\n\n function appendPaginationControls(footerElem) {\n footerElem.empty();\n\n let pageSize = panel.pageSize || 5;\n pageCount = Math.ceil(triggerList.length / pageSize);\n if (pageCount === 1) {\n return;\n }\n\n let startPage = Math.max(ctrl.pageIndex - 3, 0);\n let endPage = Math.min(pageCount, startPage + 9);\n\n let paginationList = $('');\n\n for (let i = startPage; i < endPage; i++) {\n let activeClass = i === ctrl.pageIndex ? 'active' : '';\n let pageLinkElem = $('
  • ' + (i+1) + '
  • ');\n paginationList.append(pageLinkElem);\n }\n\n footerElem.append(paginationList);\n }\n\n function setFontSize() {\n const fontSize = parseInt(panel.fontSize.slice(0, panel.fontSize.length - 1));\n let triggerCardElem = elem.find('.alert-rule-item');\n if (fontSize && fontSize !== 100) {\n triggerCardElem.find('.alert-rule-item__icon').css({\n 'font-size': fontSize + '%',\n 'margin': fontSize / 100 * 6 + 'px'\n });\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': fontSize + '%'});\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': fontSize * 0.8 + '%'});\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': fontSize * 0.8 + '%'});\n triggerCardElem.find('.zbx-tag').css({'font-size': fontSize * 0.6 + '%'});\n triggerCardElem.find('.zbx-tag').css({'line-height': fontSize / 100 * 16 + 'px'});\n } else {\n // remove css\n triggerCardElem.find('.alert-rule-item__icon').css({'font-size': '', 'margin-right': ''});\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': ''});\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': ''});\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': ''});\n triggerCardElem.find('.zbx-tag').css({'font-size': ''});\n triggerCardElem.find('.zbx-tag').css({'line-height': ''});\n }\n }\n\n function renderPanel() {\n let rootElem = elem.find('.triggers-panel-scroll');\n let footerElem = elem.find('.triggers-panel-footer');\n appendPaginationControls(footerElem);\n rootElem.css({'max-height': getContentHeight()});\n rootElem.css({'height': getContentHeight()});\n setFontSize();\n ctrl.renderingCompleted();\n }\n\n let unbindDestroy = scope.$on('$destroy', function() {\n elem.off('click', '.triggers-panel-page-link');\n unbindDestroy();\n });\n }\n}\n\nTriggerPanelCtrl.templateUrl = 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/module.html';\n\nfunction filterTriggers(triggers, triggerFilter) {\n if (utils.isRegex(triggerFilter)) {\n return _.filter(triggers, function(trigger) {\n return utils.buildRegex(triggerFilter).test(trigger.description);\n });\n } else {\n return _.filter(triggers, function(trigger) {\n return trigger.description === triggerFilter;\n });\n }\n}\n"]} \ No newline at end of file diff --git a/src/datasource-zabbix/datasource.js b/src/datasource-zabbix/datasource.js index 9c5dca518..b23cd0c52 100644 --- a/src/datasource-zabbix/datasource.js +++ b/src/datasource-zabbix/datasource.js @@ -28,7 +28,7 @@ class ZabbixAPIDatasource { this.basicAuth = instanceSettings.basicAuth; this.withCredentials = instanceSettings.withCredentials; - const jsonData = instanceSettings.jsonData; + const jsonData = instanceSettings.jsonData || {}; // Zabbix API credentials this.username = jsonData.username; @@ -48,6 +48,9 @@ class ZabbixAPIDatasource { this.addThresholds = jsonData.addThresholds; this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING; + // Other options + this.disableReadOnlyUsersAck = jsonData.disableReadOnlyUsersAck; + // Direct DB Connection options let dbConnectionOptions = jsonData.dbConnection || {}; this.enableDirectDBConnection = dbConnectionOptions.enable; diff --git a/src/datasource-zabbix/partials/config.html b/src/datasource-zabbix/partials/config.html index 7f626c24c..0df746203 100644 --- a/src/datasource-zabbix/partials/config.html +++ b/src/datasource-zabbix/partials/config.html @@ -126,3 +126,11 @@

    Alerting

    + +
    +

    Other

    + + +
    diff --git a/src/panel-triggers/triggers_panel_ctrl.js b/src/panel-triggers/triggers_panel_ctrl.js index 8c4d92a01..ae938f110 100644 --- a/src/panel-triggers/triggers_panel_ctrl.js +++ b/src/panel-triggers/triggers_panel_ctrl.js @@ -453,6 +453,10 @@ export class TriggerPanelCtrl extends PanelCtrl { let ack_message = grafana_user + ' (Grafana): ' + message; return this.datasourceSrv.get(trigger.datasource) .then(datasource => { + const userIsEditor = this.contextSrv.isEditor || this.contextSrv.isGrafanaAdmin; + if (datasource.disableReadOnlyUsersAck && !userIsEditor) { + return Promise.reject({message: 'You have no permissions to acknowledge events.'}); + } if (eventid) { return datasource.zabbix.zabbixAPI.acknowledgeEvent(eventid, ack_message); } else {