diff --git a/dist/datasource-zabbix/constants.js b/dist/datasource-zabbix/constants.js
index f0f59169d..cb95d15e1 100644
--- a/dist/datasource-zabbix/constants.js
+++ b/dist/datasource-zabbix/constants.js
@@ -3,7 +3,7 @@
 System.register([], function (_export, _context) {
   "use strict";
 
-  var MODE_METRICS, MODE_ITSERVICE, MODE_TEXT, MODE_ITEMID, SEV_NOT_CLASSIFIED, SEV_INFORMATION, SEV_WARNING, SEV_AVERAGE, SEV_HIGH, SEV_DISASTER, SHOW_ALL_TRIGGERS, SHOW_ALL_EVENTS, SHOW_OK_EVENTS, DATAPOINT_VALUE, DATAPOINT_TS;
+  var MODE_METRICS, MODE_ITSERVICE, MODE_TEXT, MODE_ITEMID, MODE_TRIGGERS, SEV_NOT_CLASSIFIED, SEV_INFORMATION, SEV_WARNING, SEV_AVERAGE, SEV_HIGH, SEV_DISASTER, SHOW_ALL_TRIGGERS, SHOW_ALL_EVENTS, SHOW_OK_EVENTS, DATAPOINT_VALUE, DATAPOINT_TS;
   return {
     setters: [],
     execute: function () {
@@ -23,6 +23,10 @@ System.register([], function (_export, _context) {
 
       _export("MODE_ITEMID", MODE_ITEMID);
 
+      _export("MODE_TRIGGERS", MODE_TRIGGERS = 4);
+
+      _export("MODE_TRIGGERS", MODE_TRIGGERS);
+
       _export("SEV_NOT_CLASSIFIED", SEV_NOT_CLASSIFIED = 0);
 
       _export("SEV_NOT_CLASSIFIED", SEV_NOT_CLASSIFIED);
diff --git a/dist/datasource-zabbix/constants.js.map b/dist/datasource-zabbix/constants.js.map
index 427ad9db7..fb4d6c6c3 100644
--- a/dist/datasource-zabbix/constants.js.map
+++ b/dist/datasource-zabbix/constants.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/datasource-zabbix/constants.js"],"names":["MODE_METRICS","MODE_ITSERVICE","MODE_TEXT","MODE_ITEMID","SEV_NOT_CLASSIFIED","SEV_INFORMATION","SEV_WARNING","SEV_AVERAGE","SEV_HIGH","SEV_DISASTER","SHOW_ALL_TRIGGERS","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","DATAPOINT_VALUE","DATAPOINT_TS"],"mappings":";;;;;;;;;8BACaA,Y,GAAe,C;;;;gCACfC,c,GAAiB,C;;;;2BACjBC,S,GAAY,C;;;;6BACZC,W,GAAc,C;;;;oCAGdC,kB,GAAqB,C;;;;iCACrBC,e,GAAkB,C;;;;6BAClBC,W,GAAc,C;;;;6BACdC,W,GAAc,C;;;;0BACdC,Q,GAAW,C;;;;8BACXC,Y,GAAe,C;;;;mCAEfC,iB,GAAoB,CAAC,CAAD,EAAI,CAAJ,C;;;;iCACpBC,e,GAAkB,CAAC,CAAD,EAAI,CAAJ,C;;;;gCAClBC,c,GAAiB,C;;;;iCAGjBC,e,GAAkB,C;;;;8BAClBC,Y,GAAe,C","file":"constants.js","sourcesContent":["// Editor modes\nexport const MODE_METRICS = 0;\nexport const MODE_ITSERVICE = 1;\nexport const MODE_TEXT = 2;\nexport const MODE_ITEMID = 3;\n\n// Triggers severity\nexport const SEV_NOT_CLASSIFIED = 0;\nexport const SEV_INFORMATION = 1;\nexport const SEV_WARNING = 2;\nexport const SEV_AVERAGE = 3;\nexport const SEV_HIGH = 4;\nexport const SEV_DISASTER = 5;\n\nexport const SHOW_ALL_TRIGGERS = [0, 1];\nexport const SHOW_ALL_EVENTS = [0, 1];\nexport const SHOW_OK_EVENTS = 1;\n\n// Data point\nexport const DATAPOINT_VALUE = 0;\nexport const DATAPOINT_TS = 1;\n"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/datasource-zabbix/constants.js"],"names":["MODE_METRICS","MODE_ITSERVICE","MODE_TEXT","MODE_ITEMID","MODE_TRIGGERS","SEV_NOT_CLASSIFIED","SEV_INFORMATION","SEV_WARNING","SEV_AVERAGE","SEV_HIGH","SEV_DISASTER","SHOW_ALL_TRIGGERS","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","DATAPOINT_VALUE","DATAPOINT_TS"],"mappings":";;;;;;;;;8BACaA,Y,GAAe,C;;;;gCACfC,c,GAAiB,C;;;;2BACjBC,S,GAAY,C;;;;6BACZC,W,GAAc,C;;;;+BACdC,a,GAAgB,C;;;;oCAGhBC,kB,GAAqB,C;;;;iCACrBC,e,GAAkB,C;;;;6BAClBC,W,GAAc,C;;;;6BACdC,W,GAAc,C;;;;0BACdC,Q,GAAW,C;;;;8BACXC,Y,GAAe,C;;;;mCAEfC,iB,GAAoB,CAAC,CAAD,EAAI,CAAJ,C;;;;iCACpBC,e,GAAkB,CAAC,CAAD,EAAI,CAAJ,C;;;;gCAClBC,c,GAAiB,C;;;;iCAGjBC,e,GAAkB,C;;;;8BAClBC,Y,GAAe,C","file":"constants.js","sourcesContent":["// Editor modes\nexport const MODE_METRICS = 0;\nexport const MODE_ITSERVICE = 1;\nexport const MODE_TEXT = 2;\nexport const MODE_ITEMID = 3;\nexport const MODE_TRIGGERS = 4;\n\n// Triggers severity\nexport const SEV_NOT_CLASSIFIED = 0;\nexport const SEV_INFORMATION = 1;\nexport const SEV_WARNING = 2;\nexport const SEV_AVERAGE = 3;\nexport const SEV_HIGH = 4;\nexport const SEV_DISASTER = 5;\n\nexport const SHOW_ALL_TRIGGERS = [0, 1];\nexport const SHOW_ALL_EVENTS = [0, 1];\nexport const SHOW_OK_EVENTS = 1;\n\n// Data point\nexport const DATAPOINT_VALUE = 0;\nexport const DATAPOINT_TS = 1;\n"]}
\ No newline at end of file
diff --git a/dist/datasource-zabbix/datasource.js b/dist/datasource-zabbix/datasource.js
index 7abf5364d..32fe129e3 100644
--- a/dist/datasource-zabbix/datasource.js
+++ b/dist/datasource-zabbix/datasource.js
@@ -337,6 +337,10 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
               } else if (target.mode === c.MODE_ITSERVICE) {
                 // IT services mode
                 return _this.queryITServiceData(target, timeRange, options);
+              } else if (target.mode === c.MODE_TRIGGERS) {
+                return _this.queryTriggersData(target, timeRange);
+              } else {
+                return [];
               }
             });
 
@@ -558,18 +562,43 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
               });
             });
           }
+        }, {
+          key: 'queryTriggersData',
+          value: function queryTriggersData(target, timeRange) {
+            var _this7 = this;
+
+            var _timeRange3 = _slicedToArray(timeRange, 2),
+                timeFrom = _timeRange3[0],
+                timeTo = _timeRange3[1];
+
+            return this.zabbix.getHostsFromTarget(target).then(function (results) {
+              var _results = _slicedToArray(results, 2),
+                  hosts = _results[0],
+                  apps = _results[1];
+
+              if (hosts.length) {
+                var hostids = _.map(hosts, 'hostid');
+                var appids = _.map(apps, 'applicationid');
+                return _this7.zabbix.getHostAlerts(hostids, appids, target.minSeverity, target.options.countTriggers, timeFrom, timeTo).then(function (triggers) {
+                  return responseHandler.handleTriggersResponse(triggers, timeRange);
+                });
+              } else {
+                return Promise.resolve([]);
+              }
+            });
+          }
         }, {
           key: 'testDatasource',
           value: function testDatasource() {
-            var _this7 = this;
+            var _this8 = this;
 
             var zabbixVersion = void 0;
             return this.zabbix.getVersion().then(function (version) {
               zabbixVersion = version;
-              return _this7.zabbix.login();
+              return _this8.zabbix.login();
             }).then(function () {
-              if (_this7.enableDirectDBConnection) {
-                return _this7.zabbix.dbConnector.testSQLDataSource();
+              if (_this8.enableDirectDBConnection) {
+                return _this8.zabbix.dbConnector.testSQLDataSource();
               } else {
                 return Promise.resolve();
               }
@@ -604,14 +633,14 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
         }, {
           key: 'metricFindQuery',
           value: function metricFindQuery(query) {
-            var _this8 = this;
+            var _this9 = this;
 
             var result = void 0;
             var parts = [];
 
             // Split query. Query structure: group.host.app.item
             _.each(utils.splitTemplateQuery(query), function (part) {
-              part = _this8.replaceTemplateVars(part, {});
+              part = _this9.replaceTemplateVars(part, {});
 
               // Replace wildcard to regex
               if (part === '*') {
@@ -648,7 +677,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
         }, {
           key: 'annotationQuery',
           value: function annotationQuery(options) {
-            var _this9 = this;
+            var _this10 = this;
 
             var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);
             var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);
@@ -666,7 +695,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
             return getTriggers.then(function (triggers) {
 
               // Filter triggers by description
-              var triggerName = _this9.replaceTemplateVars(annotation.trigger, {});
+              var triggerName = _this10.replaceTemplateVars(annotation.trigger, {});
               if (utils.isRegex(triggerName)) {
                 triggers = _.filter(triggers, function (trigger) {
                   return utils.buildRegex(triggerName).test(trigger.description);
@@ -683,7 +712,7 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
               });
 
               var objectids = _.map(triggers, 'triggerid');
-              return _this9.zabbix.getEvents(objectids, timeFrom, timeTo, showOkEvents).then(function (events) {
+              return _this10.zabbix.getEvents(objectids, timeFrom, timeTo, showOkEvents).then(function (events) {
                 var indexedTriggers = _.keyBy(triggers, 'triggerid');
 
                 // Hide acknowledged events if option enabled
@@ -717,23 +746,23 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
         }, {
           key: 'alertQuery',
           value: function alertQuery(options) {
-            var _this10 = this;
+            var _this11 = this;
 
             var enabled_targets = filterEnabledTargets(options.targets);
             var getPanelItems = _.map(enabled_targets, function (t) {
               var target = _.cloneDeep(t);
-              _this10.replaceTargetVariables(target, options);
-              return _this10.zabbix.getItemsFromTarget(target, { itemtype: 'num' });
+              _this11.replaceTargetVariables(target, options);
+              return _this11.zabbix.getItemsFromTarget(target, { itemtype: 'num' });
             });
 
             return Promise.all(getPanelItems).then(function (results) {
               var items = _.flatten(results);
               var itemids = _.map(items, 'itemid');
 
-              return _this10.zabbix.getAlerts(itemids);
+              return _this11.zabbix.getAlerts(itemids);
             }).then(function (triggers) {
               triggers = _.filter(triggers, function (trigger) {
-                return trigger.priority >= _this10.alertingMinSeverity;
+                return trigger.priority >= _this11.alertingMinSeverity;
               });
 
               if (!triggers || triggers.length === 0) {
@@ -761,12 +790,12 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
         }, {
           key: 'replaceTargetVariables',
           value: function replaceTargetVariables(target, options) {
-            var _this11 = this;
+            var _this12 = this;
 
             var parts = ['group', 'host', 'application', 'item'];
             _.forEach(parts, function (p) {
               if (target[p] && target[p].filter) {
-                target[p].filter = _this11.replaceTemplateVars(target[p].filter, options.scopedVars);
+                target[p].filter = _this12.replaceTemplateVars(target[p].filter, options.scopedVars);
               }
             });
             target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);
@@ -774,9 +803,9 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
             _.forEach(target.functions, function (func) {
               func.params = _.map(func.params, function (param) {
                 if (typeof param === 'number') {
-                  return +_this11.templateSrv.replace(param.toString(), options.scopedVars);
+                  return +_this12.templateSrv.replace(param.toString(), options.scopedVars);
                 } else {
-                  return _this11.templateSrv.replace(param, options.scopedVars);
+                  return _this12.templateSrv.replace(param, options.scopedVars);
                 }
               });
             });
@@ -784,9 +813,9 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations',
         }, {
           key: 'isUseTrends',
           value: function isUseTrends(timeRange) {
-            var _timeRange3 = _slicedToArray(timeRange, 2),
-                timeFrom = _timeRange3[0],
-                timeTo = _timeRange3[1];
+            var _timeRange4 = _slicedToArray(timeRange, 2),
+                timeFrom = _timeRange4[0],
+                timeTo = _timeRange4[1];
 
             var useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);
             var useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);
diff --git a/dist/datasource-zabbix/datasource.js.map b/dist/datasource-zabbix/datasource.js.map
index 26165b03f..961508f60 100644
--- a/dist/datasource-zabbix/datasource.js.map
+++ b/dist/datasource-zabbix/datasource.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/datasource-zabbix/datasource.js"],"names":["bindFunctionDefs","functionDefs","category","aggregationFunctions","_","map","metricFunctions","getCategories","aggFuncDefs","filter","func","includes","def","name","funcInstance","createFuncInstance","params","bindFunction","dataProcessor","getConsolidateBy","target","consolidateBy","funcDef","find","functions","length","downsampleSeries","timeseries_data","options","defaultAgg","consolidateByFunc","timeseries","datapoints","maxDataPoints","groupBy","interval","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","zabbixItemIdsTemplateFormat","replaceTemplateVars","templateSrv","scopedVars","replacedTarget","replace","isRegex","sequence","funcsArray","result","i","call","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","c","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","partial","url","basicAuth","withCredentials","jsonData","username","password","trends","trendsFrom","trendsRange","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","SEV_WARNING","dbConnectionOptions","dbConnection","enableDirectDBConnection","enable","sqlDatasourceId","datasourceId","zabbixOptions","zabbix","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","t","timeFrom","Math","ceil","parse","range","from","timeTo","to","cloneDeep","replaceTargetVariables","timeFunctions","time_from","time_to","timeRange","useTrends","isUseTrends","mode","MODE_METRICS","MODE_TEXT","MODE_ITEMID","migrate","queryNumericData","queryTextData","queryItemIdData","MODE_ITSERVICE","queryITServiceData","Promise","all","flatten","data","getItemOptions","itemtype","getItemsFromTarget","queryNumericDataForItems","items","getHistoryPromise","getTrendsDB","dbConnector","handleGrafanaTSResponse","history","valueType","getTrendValueType","getTrend","handleTrends","series","sortBy","point","DATAPOINT_TS","getHistoryDB","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","unShiftTimeSeries","handleText","resolve","itemids","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","zabbixVersion","getVersion","version","login","testSQLDataSource","status","title","message","query","parts","each","splitTemplateQuery","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","triggersOptions","showTriggers","SHOW_ALL_TRIGGERS","hideHostsInMaintenance","getTriggers","application","triggerName","trigger","triggers","buildRegex","test","description","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","hosts","formatted_acknowledges","formatAcknowledges","time","clock","objectid","enabled_targets","getPanelItems","results","getAlerts","firedTriggers","p","textFilter","param","toString","useTrendsFrom","useTrendsRange","contains","indexBy"],"mappings":";;;;;;;;;;;;;AAgmBA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC,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,UAAU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,KAAKM,MAAX,EAAmB,iBAAS;AACxC,oBAAI,OAAOiQ,KAAP,KAAiB,QAArB,EAA+B;AAC7B,yBAAO,CAAC,QAAKjO,WAAL,CAAiBG,OAAjB,CAAyB8N,MAAMC,QAAN,EAAzB,EAA2CtP,QAAQqB,UAAnD,CAAR;AACD,iBAFD,MAEO;AACL,yBAAO,QAAKD,WAAL,CAAiBG,OAAjB,CAAyB8N,KAAzB,EAAgCrP,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;sCAEWoF,S,EAAW;AAAA,6CACIA,SADJ;AAAA,gBAChBb,QADgB;AAAA,gBACNM,MADM;;AAErB,gBAAIqJ,gBAAgB1J,KAAKC,IAAL,CAAUnD,SAASoD,KAAT,CAAe,SAAS,KAAKjC,UAA7B,IAA2C,IAArD,CAApB;AACA,gBAAI0L,iBAAiB3J,KAAKC,IAAL,CAAUhF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI2C,YAAY,KAAK7C,MAAL,KACb+B,YAAY2J,aAAb,IACCrJ,SAASN,QAAT,IAAqB4J,cAFR,CAAhB;AAIA,mBAAO9I,SAAP;AACD;;;;;;qCAoHK1D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAEiR,QAAf;AAAyB;AAC3C,UAAI,CAACjR,EAAEyP,KAAP,EAAc;AAACzP,UAAEyP,KAAF,GAAUzP,EAAEkR,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["import _ from 'lodash';\nimport * as dateMath from 'app/core/utils/datemath';\nimport * as utils from './utils';\nimport * as migrations from './migrations';\nimport * as metricFunctions from './metricFunctions';\nimport * as c from './constants';\nimport dataProcessor from './dataProcessor';\nimport responseHandler from './responseHandler';\nimport './zabbix.js';\nimport './zabbixAlerting.service.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n  /** @ngInject */\n  constructor(instanceSettings, templateSrv, alertSrv, dashboardSrv, zabbixAlertingSrv, Zabbix) {\n    this.templateSrv = templateSrv;\n    this.alertSrv = alertSrv;\n    this.dashboardSrv = dashboardSrv;\n    this.zabbixAlertingSrv = zabbixAlertingSrv;\n\n    // Use custom format for template variables\n    this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\n\n    // General data source settings\n    this.name             = instanceSettings.name;\n    this.url              = instanceSettings.url;\n    this.basicAuth        = instanceSettings.basicAuth;\n    this.withCredentials  = instanceSettings.withCredentials;\n\n    const jsonData = instanceSettings.jsonData;\n\n    // Zabbix API credentials\n    this.username         = jsonData.username;\n    this.password         = jsonData.password;\n\n    // Use trends instead history since specified time\n    this.trends           = jsonData.trends;\n    this.trendsFrom       = jsonData.trendsFrom || '7d';\n    this.trendsRange      = jsonData.trendsRange || '4d';\n\n    // Set cache update interval\n    var ttl = jsonData.cacheTTL || '1h';\n    this.cacheTTL = utils.parseInterval(ttl);\n\n    // Alerting options\n    this.alertingEnabled =     jsonData.alerting;\n    this.addThresholds =       jsonData.addThresholds;\n    this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;\n\n    // Direct DB Connection options\n    let dbConnectionOptions = jsonData.dbConnection || {};\n    this.enableDirectDBConnection = dbConnectionOptions.enable;\n    this.sqlDatasourceId = dbConnectionOptions.datasourceId;\n\n    let zabbixOptions = {\n      username: this.username,\n      password: this.password,\n      basicAuth: this.basicAuth,\n      withCredentials: this.withCredentials,\n      cacheTTL: this.cacheTTL,\n      enableDirectDBConnection: this.enableDirectDBConnection,\n      sqlDatasourceId: this.sqlDatasourceId\n    };\n\n    this.zabbix = new Zabbix(this.url, zabbixOptions);\n  }\n\n  ////////////////////////\n  // Datasource methods //\n  ////////////////////////\n\n  /**\n   * Query panel data. Calls for each panel in dashboard.\n   * @param  {Object} options   Contains time range, targets and other info.\n   * @return {Object} Grafana metrics object with timeseries data for each target.\n   */\n  query(options) {\n    // Get alerts for current panel\n    if (this.alertingEnabled) {\n      this.alertQuery(options).then(alert => {\n        this.zabbixAlertingSrv.setPanelAlertState(options.panelId, alert.state);\n\n        this.zabbixAlertingSrv.removeZabbixThreshold(options.panelId);\n        if (this.addThresholds) {\n          _.forEach(alert.thresholds, threshold => {\n            this.zabbixAlertingSrv.setPanelThreshold(options.panelId, threshold);\n          });\n        }\n      });\n    }\n\n    // Create request for each target\n    let promises = _.map(options.targets, t => {\n      // Don't request undefined and hidden targets\n      if (t.hide) {\n        return [];\n      }\n\n      let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n      let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n      // Prevent changes of original object\n      let target = _.cloneDeep(t);\n      this.replaceTargetVariables(target, options);\n\n      // Apply Time-related functions (timeShift(), etc)\n      let timeFunctions = bindFunctionDefs(target.functions, 'Time');\n      if (timeFunctions.length) {\n        const [time_from, time_to] = sequence(timeFunctions)([timeFrom, timeTo]);\n        timeFrom = time_from;\n        timeTo = time_to;\n      }\n      let timeRange = [timeFrom, timeTo];\n\n      let useTrends = this.isUseTrends(timeRange);\n\n      // Metrics or Text query mode\n      if (!target.mode || target.mode === c.MODE_METRICS ||\n          target.mode === c.MODE_TEXT || target.mode === c.MODE_ITEMID) {\n        // Migrate old targets\n        target = migrations.migrate(target);\n\n        // Don't request undefined and hidden targets\n        if (target.hide || !target.group || !target.host || !target.item) {\n          return [];\n        }\n\n        if (!target.mode || target.mode === c.MODE_METRICS) {\n          return this.queryNumericData(target, timeRange, useTrends, options);\n        } else if (target.mode === c.MODE_TEXT) {\n          return this.queryTextData(target, timeRange);\n        } else if (target.mode === c.MODE_ITEMID) {\n          return this.queryItemIdData(target, timeRange, useTrends, options);\n        }\n      } else if (target.mode === c.MODE_ITSERVICE) {\n        // IT services mode\n        return this.queryITServiceData(target, timeRange, options);\n      }\n    });\n\n    // Data for panel (all targets)\n    return Promise.all(_.flatten(promises))\n      .then(_.flatten)\n      .then(data => {\n        return { data: data };\n      });\n  }\n\n  /**\n   * Query target data for Metrics mode\n   */\n  queryNumericData(target, timeRange, useTrends, options) {\n    let getItemOptions = {\n      itemtype: 'num'\n    };\n    return this.zabbix.getItemsFromTarget(target, getItemOptions)\n    .then(items => {\n      return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n    });\n  }\n\n  /**\n   * Query history for numeric items\n   */\n  queryNumericDataForItems(items, target, timeRange, useTrends, options) {\n    let [timeFrom, timeTo] = timeRange;\n    let getHistoryPromise;\n    options.consolidateBy = getConsolidateBy(target);\n\n    if (useTrends) {\n      if (this.enableDirectDBConnection) {\n        getHistoryPromise = this.zabbix.getTrendsDB(items, timeFrom, timeTo, options)\n        .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n      } else {\n        let valueType = this.getTrendValueType(target);\n        getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n        .then(history => responseHandler.handleTrends(history, items, valueType))\n        .then(timeseries => {\n          // Sort trend data, issue #202\n          _.forEach(timeseries, series => {\n            series.datapoints = _.sortBy(series.datapoints, point => point[c.DATAPOINT_TS]);\n          });\n          return timeseries;\n        });\n      }\n    } else {\n      // Use history\n      if (this.enableDirectDBConnection) {\n        getHistoryPromise = this.zabbix.getHistoryDB(items, timeFrom, timeTo, options)\n        .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n      } else {\n        getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n        .then(history => responseHandler.handleHistory(history, items));\n      }\n    }\n\n    return getHistoryPromise\n    .then(timeseries => this.applyDataProcessingFunctions(timeseries, target))\n    .then(timeseries => downsampleSeries(timeseries, options))\n    .catch(error => {\n      console.log(error);\n      return [];\n    });\n  }\n\n  getTrendValueType(target) {\n    // Find trendValue() function and get specified trend value\n    var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name');\n    var trendValueFunc = _.find(target.functions, func => {\n      return _.includes(trendFunctions, func.def.name);\n    });\n    return trendValueFunc ? trendValueFunc.params[0] : \"avg\";\n  }\n\n  applyDataProcessingFunctions(timeseries_data, target) {\n    let transformFunctions   = bindFunctionDefs(target.functions, 'Transform');\n    let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate');\n    let filterFunctions      = bindFunctionDefs(target.functions, 'Filter');\n    let aliasFunctions       = bindFunctionDefs(target.functions, 'Alias');\n\n    // Apply transformation functions\n    timeseries_data = _.cloneDeep(_.map(timeseries_data, timeseries => {\n      timeseries.datapoints = sequence(transformFunctions)(timeseries.datapoints);\n      return timeseries;\n    }));\n\n    // Apply filter functions\n    if (filterFunctions.length) {\n      timeseries_data = sequence(filterFunctions)(timeseries_data);\n    }\n\n    // Apply aggregations\n    if (aggregationFunctions.length) {\n      let dp = _.map(timeseries_data, 'datapoints');\n      dp = sequence(aggregationFunctions)(dp);\n\n      let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name');\n      let lastAgg = _.findLast(target.functions, func => {\n        return _.includes(aggFuncNames, func.def.name);\n      });\n\n      timeseries_data = [{\n        target: lastAgg.text,\n        datapoints: dp\n      }];\n    }\n\n    // Apply alias functions\n    _.forEach(timeseries_data, sequence(aliasFunctions));\n\n    // Apply Time-related functions (timeShift(), etc)\n    // Find timeShift() function and get specified trend value\n    this.applyTimeShiftFunction(timeseries_data, target);\n\n    return timeseries_data;\n  }\n\n  applyTimeShiftFunction(timeseries_data, target) {\n    // Find timeShift() function and get specified interval\n    let timeShiftFunc = _.find(target.functions, (func) => {\n      return func.def.name === 'timeShift';\n    });\n    if (timeShiftFunc) {\n      let shift = timeShiftFunc.params[0];\n      _.forEach(timeseries_data, (series) => {\n        series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints);\n      });\n    }\n  }\n\n  /**\n   * Query target data for Text mode\n   */\n  queryTextData(target, timeRange) {\n    let [timeFrom, timeTo] = timeRange;\n    let options = {\n      itemtype: 'text'\n    };\n    return this.zabbix.getItemsFromTarget(target, options)\n      .then(items => {\n        if (items.length) {\n          return this.zabbix.getHistory(items, timeFrom, timeTo)\n          .then(history => {\n            return responseHandler.handleText(history, items, target);\n          });\n        } else {\n          return Promise.resolve([]);\n        }\n      });\n  }\n\n  /**\n   * Query target data for Item ID mode\n   */\n  queryItemIdData(target, timeRange, useTrends, options) {\n    let itemids = target.itemids;\n    itemids = this.templateSrv.replace(itemids, options.scopedVars, zabbixItemIdsTemplateFormat);\n    itemids = _.map(itemids.split(','), itemid => itemid.trim());\n\n    if (!itemids) {\n      return [];\n    }\n\n    return this.zabbix.getItemsByIDs(itemids)\n    .then(items => {\n      return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n    });\n  }\n\n  /**\n   * Query target data for IT Services mode\n   */\n  queryITServiceData(target, timeRange, options) {\n    // Don't show undefined and hidden targets\n    if (target.hide || (!target.itservice && !target.itServiceFilter) || !target.slaProperty) {\n      return [];\n    }\n\n    let itServiceIds = [];\n    let itServices = [];\n    let itServiceFilter;\n    let isOldVersion = target.itservice && !target.itServiceFilter;\n\n    if (isOldVersion) {\n      // Backward compatibility\n      itServiceFilter = '/.*/';\n    } else {\n      itServiceFilter = this.replaceTemplateVars(target.itServiceFilter, options.scopedVars);\n    }\n\n    return this.zabbix.getITServices(itServiceFilter)\n    .then(itservices => {\n      itServices = itservices;\n      if (isOldVersion) {\n        itServices = _.filter(itServices, {'serviceid': target.itservice.serviceid});\n      }\n\n      itServiceIds = _.map(itServices, 'serviceid');\n      return itServiceIds;\n    })\n    .then(serviceids => {\n      return this.zabbix.getSLA(serviceids, timeRange);\n    })\n    .then(slaResponse => {\n      return _.map(itServiceIds, serviceid => {\n        let itservice = _.find(itServices, {'serviceid': serviceid});\n        return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);\n      });\n    });\n  }\n\n  /**\n   * Test connection to Zabbix API\n   * @return {object} Connection status and Zabbix API version\n   */\n  testDatasource() {\n    let zabbixVersion;\n    return this.zabbix.getVersion()\n    .then(version => {\n      zabbixVersion = version;\n      return this.zabbix.login();\n    })\n    .then(() => {\n      if (this.enableDirectDBConnection) {\n        return this.zabbix.dbConnector.testSQLDataSource();\n      } else {\n        return Promise.resolve();\n      }\n    })\n    .then(() => {\n      return {\n        status: \"success\",\n        title: \"Success\",\n        message: \"Zabbix API version: \" + zabbixVersion\n      };\n    })\n    .catch(error => {\n      if (error instanceof ZabbixAPIError) {\n        return {\n          status: \"error\",\n          title: error.message,\n          message: error.message\n        };\n      } else if (error.data && error.data.message) {\n        return {\n          status: \"error\",\n          title: \"Connection failed\",\n          message: \"Connection failed: \" + error.data.message\n        };\n      } else {\n        return {\n          status: \"error\",\n          title: \"Connection failed\",\n          message: \"Could not connect to given url\"\n        };\n      }\n    });\n  }\n\n  ////////////////\n  // Templating //\n  ////////////////\n\n  /**\n   * Find metrics from templated request.\n   *\n   * @param  {string} query Query from Templating\n   * @return {string}       Metric name - group, host, app or item or list\n   *                        of metrics in \"{metric1,metcic2,...,metricN}\" format.\n   */\n  metricFindQuery(query) {\n    let result;\n    let parts = [];\n\n    // Split query. Query structure: group.host.app.item\n    _.each(utils.splitTemplateQuery(query), part => {\n      part = this.replaceTemplateVars(part, {});\n\n      // Replace wildcard to regex\n      if (part === '*') {\n        part = '/.*/';\n      }\n      parts.push(part);\n    });\n    let template = _.zipObject(['group', 'host', 'app', 'item'], parts);\n\n    // Get items\n    if (parts.length === 4) {\n      // Search for all items, even it's not belong to any application\n      if (template.app === '/.*/') {\n        template.app = '';\n      }\n      result = this.zabbix.getItems(template.group, template.host, template.app, template.item);\n    } else if (parts.length === 3) {\n      // Get applications\n      result = this.zabbix.getApps(template.group, template.host, template.app);\n    } else if (parts.length === 2) {\n      // Get hosts\n      result = this.zabbix.getHosts(template.group, template.host);\n    } else if (parts.length === 1) {\n      // Get groups\n      result = this.zabbix.getGroups(template.group);\n    } else {\n      result = Promise.resolve([]);\n    }\n\n    return result.then(metrics => {\n      return _.map(metrics, formatMetric);\n    });\n  }\n\n  /////////////////\n  // Annotations //\n  /////////////////\n\n  annotationQuery(options) {\n    var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);\n    var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);\n    var annotation = options.annotation;\n    var showOkEvents = annotation.showOkEvents ? c.SHOW_ALL_EVENTS : c.SHOW_OK_EVENTS;\n\n    // Show all triggers\n    let triggersOptions = {\n      showTriggers: c.SHOW_ALL_TRIGGERS,\n      hideHostsInMaintenance: false\n    };\n\n    var getTriggers = this.zabbix.getTriggers(this.replaceTemplateVars(annotation.group, {}),\n                                              this.replaceTemplateVars(annotation.host, {}),\n                                              this.replaceTemplateVars(annotation.application, {}),\n                                              triggersOptions);\n\n    return getTriggers.then(triggers => {\n\n      // Filter triggers by description\n      let triggerName = this.replaceTemplateVars(annotation.trigger, {});\n      if (utils.isRegex(triggerName)) {\n        triggers = _.filter(triggers, trigger => {\n          return utils.buildRegex(triggerName).test(trigger.description);\n        });\n      } else if (triggerName) {\n        triggers = _.filter(triggers, trigger => {\n          return trigger.description === triggerName;\n        });\n      }\n\n      // Remove events below the chose severity\n      triggers = _.filter(triggers, trigger => {\n        return Number(trigger.priority) >= Number(annotation.minseverity);\n      });\n\n      var objectids = _.map(triggers, 'triggerid');\n      return this.zabbix\n        .getEvents(objectids, timeFrom, timeTo, showOkEvents)\n        .then(events => {\n          var indexedTriggers = _.keyBy(triggers, 'triggerid');\n\n          // Hide acknowledged events if option enabled\n          if (annotation.hideAcknowledged) {\n            events = _.filter(events, event => {\n              return !event.acknowledges.length;\n            });\n          }\n\n          return _.map(events, event => {\n            let tags;\n            if (annotation.showHostname) {\n              tags = _.map(event.hosts, 'name');\n            }\n\n            // Show event type (OK or Problem)\n            let title = Number(event.value) ? 'Problem' : 'OK';\n\n            let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges);\n            return {\n              annotation: annotation,\n              time: event.clock * 1000,\n              title: title,\n              tags: tags,\n              text: indexedTriggers[event.objectid].description + formatted_acknowledges\n            };\n          });\n        });\n    });\n  }\n\n  /**\n   * Get triggers and its details for panel's targets\n   * Returns alert state ('ok' if no fired triggers, or 'alerting' if at least 1 trigger is fired)\n   * or empty object if no related triggers are finded.\n   */\n  alertQuery(options) {\n    let enabled_targets = filterEnabledTargets(options.targets);\n    let getPanelItems = _.map(enabled_targets, t => {\n      let target = _.cloneDeep(t);\n      this.replaceTargetVariables(target, options);\n      return this.zabbix.getItemsFromTarget(target, {itemtype: 'num'});\n    });\n\n    return Promise.all(getPanelItems)\n    .then(results => {\n      let items = _.flatten(results);\n      let itemids = _.map(items, 'itemid');\n\n      return this.zabbix.getAlerts(itemids);\n    })\n    .then(triggers => {\n      triggers = _.filter(triggers, trigger => {\n        return trigger.priority >= this.alertingMinSeverity;\n      });\n\n      if (!triggers || triggers.length === 0) {\n        return {};\n      }\n\n      let state = 'ok';\n\n      let firedTriggers = _.filter(triggers, {value: '1'});\n      if (firedTriggers.length) {\n        state = 'alerting';\n      }\n\n      let thresholds = _.map(triggers, trigger => {\n        return getTriggerThreshold(trigger.expression);\n      });\n\n      return {\n        panelId: options.panelId,\n        state: state,\n        thresholds: thresholds\n      };\n    });\n  }\n\n  // Replace template variables\n  replaceTargetVariables(target, options) {\n    let parts = ['group', 'host', 'application', 'item'];\n    _.forEach(parts, p => {\n      if (target[p] && target[p].filter) {\n        target[p].filter = this.replaceTemplateVars(target[p].filter, options.scopedVars);\n      }\n    });\n    target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);\n\n    _.forEach(target.functions, func => {\n      func.params = _.map(func.params, param => {\n        if (typeof param === 'number') {\n          return +this.templateSrv.replace(param.toString(), options.scopedVars);\n        } else {\n          return this.templateSrv.replace(param, options.scopedVars);\n        }\n      });\n    });\n  }\n\n  isUseTrends(timeRange) {\n    let [timeFrom, timeTo] = timeRange;\n    let useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);\n    let useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);\n    let useTrends = this.trends && (\n      (timeFrom <= useTrendsFrom) ||\n      (timeTo - timeFrom >= useTrendsRange)\n    );\n    return useTrends;\n  }\n}\n\nfunction bindFunctionDefs(functionDefs, category) {\n  var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name');\n  var aggFuncDefs = _.filter(functionDefs, function(func) {\n    return _.includes(aggregationFunctions, func.def.name);\n  });\n\n  return _.map(aggFuncDefs, function(func) {\n    var funcInstance = metricFunctions.createFuncInstance(func.def, func.params);\n    return funcInstance.bindFunction(dataProcessor.metricFunctions);\n  });\n}\n\nfunction getConsolidateBy(target) {\n  let consolidateBy = 'avg';\n  let funcDef = _.find(target.functions, func => {\n    return func.def.name === 'consolidateBy';\n  });\n  if (funcDef && funcDef.params && funcDef.params.length) {\n    consolidateBy = funcDef.params[0];\n  }\n  return consolidateBy;\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n  let defaultAgg = dataProcessor.aggregationFunctions['avg'];\n  let consolidateByFunc = dataProcessor.aggregationFunctions[options.consolidateBy] || defaultAgg;\n  return _.map(timeseries_data, timeseries => {\n    if (timeseries.datapoints.length > options.maxDataPoints) {\n      timeseries.datapoints = dataProcessor\n        .groupBy(options.interval, consolidateByFunc, timeseries.datapoints);\n    }\n    return timeseries;\n  });\n}\n\nfunction formatMetric(metricObj) {\n  return {\n    text: metricObj.name,\n    expandable: false\n  };\n}\n\n/**\n * Custom formatter for template variables.\n * Default Grafana \"regex\" formatter returns\n * value1|value2\n * This formatter returns\n * (value1|value2)\n * This format needed for using in complex regex with\n * template variables, for example\n * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait\n */\nfunction zabbixTemplateFormat(value) {\n  if (typeof value === 'string') {\n    return utils.escapeRegex(value);\n  }\n\n  var escapedValues = _.map(value, utils.escapeRegex);\n  return '(' + escapedValues.join('|') + ')';\n}\n\nfunction zabbixItemIdsTemplateFormat(value) {\n  if (typeof value === 'string') {\n    return value;\n  }\n  return value.join(',');\n}\n\n/**\n * If template variables are used in request, replace it using regex format\n * and wrap with '/' for proper multi-value work. Example:\n * $variable selected as a, b, c\n * We use filter $variable\n * $variable    -> a|b|c    -> /a|b|c/\n * /$variable/  -> /a|b|c/  -> /a|b|c/\n */\nfunction replaceTemplateVars(templateSrv, target, scopedVars) {\n  var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat);\n  if (target !== replacedTarget && !utils.isRegex(replacedTarget)) {\n    replacedTarget = '/^' + replacedTarget + '$/';\n  }\n  return replacedTarget;\n}\n\n// Apply function one by one:\n// sequence([a(), b(), c()]) = c(b(a()));\nfunction sequence(funcsArray) {\n  return function(result) {\n    for (var i = 0; i < funcsArray.length; i++) {\n      result = funcsArray[i].call(this, result);\n    }\n    return result;\n  };\n}\n\nfunction filterEnabledTargets(targets) {\n  return _.filter(targets, target => {\n    return !(target.hide || !target.group || !target.host || !target.item);\n  });\n}\n\nfunction getTriggerThreshold(expression) {\n  let thresholdPattern = /.*[<>]([\\d\\.]+)/;\n  let finded_thresholds = expression.match(thresholdPattern);\n  if (finded_thresholds && finded_thresholds.length >= 2) {\n    let threshold = finded_thresholds[1];\n    threshold = Number(threshold);\n    return threshold;\n  } else {\n    return null;\n  }\n}\n\nexport {ZabbixAPIDatasource, zabbixTemplateFormat};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.includes) {_.includes = _.contains;}\nif (!_.keyBy) {_.keyBy = _.indexBy;}\n"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/datasource-zabbix/datasource.js"],"names":["bindFunctionDefs","functionDefs","category","aggregationFunctions","_","map","metricFunctions","getCategories","aggFuncDefs","filter","func","includes","def","name","funcInstance","createFuncInstance","params","bindFunction","dataProcessor","getConsolidateBy","target","consolidateBy","funcDef","find","functions","length","downsampleSeries","timeseries_data","options","defaultAgg","consolidateByFunc","timeseries","datapoints","maxDataPoints","groupBy","interval","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","zabbixItemIdsTemplateFormat","replaceTemplateVars","templateSrv","scopedVars","replacedTarget","replace","isRegex","sequence","funcsArray","result","i","call","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","c","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","partial","url","basicAuth","withCredentials","jsonData","username","password","trends","trendsFrom","trendsRange","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","SEV_WARNING","dbConnectionOptions","dbConnection","enableDirectDBConnection","enable","sqlDatasourceId","datasourceId","zabbixOptions","zabbix","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","t","timeFrom","Math","ceil","parse","range","from","timeTo","to","cloneDeep","replaceTargetVariables","timeFunctions","time_from","time_to","timeRange","useTrends","isUseTrends","mode","MODE_METRICS","MODE_TEXT","MODE_ITEMID","migrate","queryNumericData","queryTextData","queryItemIdData","MODE_ITSERVICE","queryITServiceData","MODE_TRIGGERS","queryTriggersData","Promise","all","flatten","data","getItemOptions","itemtype","getItemsFromTarget","queryNumericDataForItems","items","getHistoryPromise","getTrendsDB","dbConnector","handleGrafanaTSResponse","history","valueType","getTrendValueType","getTrend","handleTrends","series","sortBy","point","DATAPOINT_TS","getHistoryDB","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","unShiftTimeSeries","handleText","resolve","itemids","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","getHostsFromTarget","results","hosts","apps","hostids","appids","getHostAlerts","minSeverity","countTriggers","triggers","handleTriggersResponse","zabbixVersion","getVersion","version","login","testSQLDataSource","status","title","message","query","parts","each","splitTemplateQuery","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","triggersOptions","showTriggers","SHOW_ALL_TRIGGERS","hideHostsInMaintenance","getTriggers","application","triggerName","trigger","buildRegex","test","description","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","formatted_acknowledges","formatAcknowledges","time","clock","objectid","enabled_targets","getPanelItems","getAlerts","firedTriggers","p","textFilter","param","toString","useTrendsFrom","useTrendsRange","contains","indexBy"],"mappings":";;;;;;;;;;;;;AAsnBA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC,gBAAgBC,aAAhB,GAAgCL,QAAhC,CAAN,EAAiD,MAAjD,CAA3B;AACA,QAAIM,cAAcJ,EAAEK,MAAF,CAASR,YAAT,EAAuB,UAASS,IAAT,EAAe;AACtD,aAAON,EAAEO,QAAF,CAAWR,oBAAX,EAAiCO,KAAKE,GAAL,CAASC,IAA1C,CAAP;AACD,KAFiB,CAAlB;;AAIA,WAAOT,EAAEC,GAAF,CAAMG,WAAN,EAAmB,UAASE,IAAT,EAAe;AACvC,UAAII,eAAeR,gBAAgBS,kBAAhB,CAAmCL,KAAKE,GAAxC,EAA6CF,KAAKM,MAAlD,CAAnB;AACA,aAAOF,aAAaG,YAAb,CAA0BC,cAAcZ,eAAxC,CAAP;AACD,KAHM,CAAP;AAID;;AAED,WAASa,gBAAT,CAA0BC,MAA1B,EAAkC;AAChC,QAAIC,gBAAgB,KAApB;AACA,QAAIC,UAAUlB,EAAEmB,IAAF,CAAOH,OAAOI,SAAd,EAAyB,gBAAQ;AAC7C,aAAOd,KAAKE,GAAL,CAASC,IAAT,KAAkB,eAAzB;AACD,KAFa,CAAd;AAGA,QAAIS,WAAWA,QAAQN,MAAnB,IAA6B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SADJ;AAAA,gBAChBb,QADgB;AAAA,gBACNM,MADM;;AAErB,gBAAI+J,gBAAgBpK,KAAKC,IAAL,CAAUnD,SAASoD,KAAT,CAAe,SAAS,KAAKjC,UAA7B,IAA2C,IAArD,CAApB;AACA,gBAAIoM,iBAAiBrK,KAAKC,IAAL,CAAUhF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI2C,YAAY,KAAK7C,MAAL,KACb+B,YAAYqK,aAAb,IACC/J,SAASN,QAAT,IAAqBsK,cAFR,CAAhB;AAIA,mBAAOxJ,SAAP;AACD;;;;;;qCAoHK1D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE2R,QAAf;AAAyB;AAC3C,UAAI,CAAC3R,EAAEqQ,KAAP,EAAc;AAACrQ,UAAEqQ,KAAF,GAAUrQ,EAAE4R,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["import _ from 'lodash';\nimport * as dateMath from 'app/core/utils/datemath';\nimport * as utils from './utils';\nimport * as migrations from './migrations';\nimport * as metricFunctions from './metricFunctions';\nimport * as c from './constants';\nimport dataProcessor from './dataProcessor';\nimport responseHandler from './responseHandler';\nimport './zabbix.js';\nimport './zabbixAlerting.service.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n  /** @ngInject */\n  constructor(instanceSettings, templateSrv, alertSrv, dashboardSrv, zabbixAlertingSrv, Zabbix) {\n    this.templateSrv = templateSrv;\n    this.alertSrv = alertSrv;\n    this.dashboardSrv = dashboardSrv;\n    this.zabbixAlertingSrv = zabbixAlertingSrv;\n\n    // Use custom format for template variables\n    this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\n\n    // General data source settings\n    this.name             = instanceSettings.name;\n    this.url              = instanceSettings.url;\n    this.basicAuth        = instanceSettings.basicAuth;\n    this.withCredentials  = instanceSettings.withCredentials;\n\n    const jsonData = instanceSettings.jsonData;\n\n    // Zabbix API credentials\n    this.username         = jsonData.username;\n    this.password         = jsonData.password;\n\n    // Use trends instead history since specified time\n    this.trends           = jsonData.trends;\n    this.trendsFrom       = jsonData.trendsFrom || '7d';\n    this.trendsRange      = jsonData.trendsRange || '4d';\n\n    // Set cache update interval\n    var ttl = jsonData.cacheTTL || '1h';\n    this.cacheTTL = utils.parseInterval(ttl);\n\n    // Alerting options\n    this.alertingEnabled =     jsonData.alerting;\n    this.addThresholds =       jsonData.addThresholds;\n    this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;\n\n    // Direct DB Connection options\n    let dbConnectionOptions = jsonData.dbConnection || {};\n    this.enableDirectDBConnection = dbConnectionOptions.enable;\n    this.sqlDatasourceId = dbConnectionOptions.datasourceId;\n\n    let zabbixOptions = {\n      username: this.username,\n      password: this.password,\n      basicAuth: this.basicAuth,\n      withCredentials: this.withCredentials,\n      cacheTTL: this.cacheTTL,\n      enableDirectDBConnection: this.enableDirectDBConnection,\n      sqlDatasourceId: this.sqlDatasourceId\n    };\n\n    this.zabbix = new Zabbix(this.url, zabbixOptions);\n  }\n\n  ////////////////////////\n  // Datasource methods //\n  ////////////////////////\n\n  /**\n   * Query panel data. Calls for each panel in dashboard.\n   * @param  {Object} options   Contains time range, targets and other info.\n   * @return {Object} Grafana metrics object with timeseries data for each target.\n   */\n  query(options) {\n    // Get alerts for current panel\n    if (this.alertingEnabled) {\n      this.alertQuery(options).then(alert => {\n        this.zabbixAlertingSrv.setPanelAlertState(options.panelId, alert.state);\n\n        this.zabbixAlertingSrv.removeZabbixThreshold(options.panelId);\n        if (this.addThresholds) {\n          _.forEach(alert.thresholds, threshold => {\n            this.zabbixAlertingSrv.setPanelThreshold(options.panelId, threshold);\n          });\n        }\n      });\n    }\n\n    // Create request for each target\n    let promises = _.map(options.targets, t => {\n      // Don't request undefined and hidden targets\n      if (t.hide) {\n        return [];\n      }\n\n      let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n      let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n      // Prevent changes of original object\n      let target = _.cloneDeep(t);\n      this.replaceTargetVariables(target, options);\n\n      // Apply Time-related functions (timeShift(), etc)\n      let timeFunctions = bindFunctionDefs(target.functions, 'Time');\n      if (timeFunctions.length) {\n        const [time_from, time_to] = sequence(timeFunctions)([timeFrom, timeTo]);\n        timeFrom = time_from;\n        timeTo = time_to;\n      }\n      let timeRange = [timeFrom, timeTo];\n\n      let useTrends = this.isUseTrends(timeRange);\n\n      // Metrics or Text query mode\n      if (!target.mode || target.mode === c.MODE_METRICS ||\n          target.mode === c.MODE_TEXT || target.mode === c.MODE_ITEMID) {\n        // Migrate old targets\n        target = migrations.migrate(target);\n\n        // Don't request undefined and hidden targets\n        if (target.hide || !target.group || !target.host || !target.item) {\n          return [];\n        }\n\n        if (!target.mode || target.mode === c.MODE_METRICS) {\n          return this.queryNumericData(target, timeRange, useTrends, options);\n        } else if (target.mode === c.MODE_TEXT) {\n          return this.queryTextData(target, timeRange);\n        } else if (target.mode === c.MODE_ITEMID) {\n          return this.queryItemIdData(target, timeRange, useTrends, options);\n        }\n      } else if (target.mode === c.MODE_ITSERVICE) {\n        // IT services mode\n        return this.queryITServiceData(target, timeRange, options);\n      } else if (target.mode === c.MODE_TRIGGERS) {\n        return this.queryTriggersData(target, timeRange);\n      } else {\n        return [];\n      }\n    });\n\n    // Data for panel (all targets)\n    return Promise.all(_.flatten(promises))\n      .then(_.flatten)\n      .then(data => {\n        return { data: data };\n      });\n  }\n\n  /**\n   * Query target data for Metrics mode\n   */\n  queryNumericData(target, timeRange, useTrends, options) {\n    let getItemOptions = {\n      itemtype: 'num'\n    };\n    return this.zabbix.getItemsFromTarget(target, getItemOptions)\n    .then(items => {\n      return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n    });\n  }\n\n  /**\n   * Query history for numeric items\n   */\n  queryNumericDataForItems(items, target, timeRange, useTrends, options) {\n    let [timeFrom, timeTo] = timeRange;\n    let getHistoryPromise;\n    options.consolidateBy = getConsolidateBy(target);\n\n    if (useTrends) {\n      if (this.enableDirectDBConnection) {\n        getHistoryPromise = this.zabbix.getTrendsDB(items, timeFrom, timeTo, options)\n        .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n      } else {\n        let valueType = this.getTrendValueType(target);\n        getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n        .then(history => responseHandler.handleTrends(history, items, valueType))\n        .then(timeseries => {\n          // Sort trend data, issue #202\n          _.forEach(timeseries, series => {\n            series.datapoints = _.sortBy(series.datapoints, point => point[c.DATAPOINT_TS]);\n          });\n          return timeseries;\n        });\n      }\n    } else {\n      // Use history\n      if (this.enableDirectDBConnection) {\n        getHistoryPromise = this.zabbix.getHistoryDB(items, timeFrom, timeTo, options)\n        .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n      } else {\n        getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n        .then(history => responseHandler.handleHistory(history, items));\n      }\n    }\n\n    return getHistoryPromise\n    .then(timeseries => this.applyDataProcessingFunctions(timeseries, target))\n    .then(timeseries => downsampleSeries(timeseries, options))\n    .catch(error => {\n      console.log(error);\n      return [];\n    });\n  }\n\n  getTrendValueType(target) {\n    // Find trendValue() function and get specified trend value\n    var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name');\n    var trendValueFunc = _.find(target.functions, func => {\n      return _.includes(trendFunctions, func.def.name);\n    });\n    return trendValueFunc ? trendValueFunc.params[0] : \"avg\";\n  }\n\n  applyDataProcessingFunctions(timeseries_data, target) {\n    let transformFunctions   = bindFunctionDefs(target.functions, 'Transform');\n    let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate');\n    let filterFunctions      = bindFunctionDefs(target.functions, 'Filter');\n    let aliasFunctions       = bindFunctionDefs(target.functions, 'Alias');\n\n    // Apply transformation functions\n    timeseries_data = _.cloneDeep(_.map(timeseries_data, timeseries => {\n      timeseries.datapoints = sequence(transformFunctions)(timeseries.datapoints);\n      return timeseries;\n    }));\n\n    // Apply filter functions\n    if (filterFunctions.length) {\n      timeseries_data = sequence(filterFunctions)(timeseries_data);\n    }\n\n    // Apply aggregations\n    if (aggregationFunctions.length) {\n      let dp = _.map(timeseries_data, 'datapoints');\n      dp = sequence(aggregationFunctions)(dp);\n\n      let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name');\n      let lastAgg = _.findLast(target.functions, func => {\n        return _.includes(aggFuncNames, func.def.name);\n      });\n\n      timeseries_data = [{\n        target: lastAgg.text,\n        datapoints: dp\n      }];\n    }\n\n    // Apply alias functions\n    _.forEach(timeseries_data, sequence(aliasFunctions));\n\n    // Apply Time-related functions (timeShift(), etc)\n    // Find timeShift() function and get specified trend value\n    this.applyTimeShiftFunction(timeseries_data, target);\n\n    return timeseries_data;\n  }\n\n  applyTimeShiftFunction(timeseries_data, target) {\n    // Find timeShift() function and get specified interval\n    let timeShiftFunc = _.find(target.functions, (func) => {\n      return func.def.name === 'timeShift';\n    });\n    if (timeShiftFunc) {\n      let shift = timeShiftFunc.params[0];\n      _.forEach(timeseries_data, (series) => {\n        series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints);\n      });\n    }\n  }\n\n  /**\n   * Query target data for Text mode\n   */\n  queryTextData(target, timeRange) {\n    let [timeFrom, timeTo] = timeRange;\n    let options = {\n      itemtype: 'text'\n    };\n    return this.zabbix.getItemsFromTarget(target, options)\n      .then(items => {\n        if (items.length) {\n          return this.zabbix.getHistory(items, timeFrom, timeTo)\n          .then(history => {\n            return responseHandler.handleText(history, items, target);\n          });\n        } else {\n          return Promise.resolve([]);\n        }\n      });\n  }\n\n  /**\n   * Query target data for Item ID mode\n   */\n  queryItemIdData(target, timeRange, useTrends, options) {\n    let itemids = target.itemids;\n    itemids = this.templateSrv.replace(itemids, options.scopedVars, zabbixItemIdsTemplateFormat);\n    itemids = _.map(itemids.split(','), itemid => itemid.trim());\n\n    if (!itemids) {\n      return [];\n    }\n\n    return this.zabbix.getItemsByIDs(itemids)\n    .then(items => {\n      return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n    });\n  }\n\n  /**\n   * Query target data for IT Services mode\n   */\n  queryITServiceData(target, timeRange, options) {\n    // Don't show undefined and hidden targets\n    if (target.hide || (!target.itservice && !target.itServiceFilter) || !target.slaProperty) {\n      return [];\n    }\n\n    let itServiceIds = [];\n    let itServices = [];\n    let itServiceFilter;\n    let isOldVersion = target.itservice && !target.itServiceFilter;\n\n    if (isOldVersion) {\n      // Backward compatibility\n      itServiceFilter = '/.*/';\n    } else {\n      itServiceFilter = this.replaceTemplateVars(target.itServiceFilter, options.scopedVars);\n    }\n\n    return this.zabbix.getITServices(itServiceFilter)\n    .then(itservices => {\n      itServices = itservices;\n      if (isOldVersion) {\n        itServices = _.filter(itServices, {'serviceid': target.itservice.serviceid});\n      }\n\n      itServiceIds = _.map(itServices, 'serviceid');\n      return itServiceIds;\n    })\n    .then(serviceids => {\n      return this.zabbix.getSLA(serviceids, timeRange);\n    })\n    .then(slaResponse => {\n      return _.map(itServiceIds, serviceid => {\n        let itservice = _.find(itServices, {'serviceid': serviceid});\n        return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);\n      });\n    });\n  }\n\n  queryTriggersData(target, timeRange) {\n    let [timeFrom, timeTo] = timeRange;\n    return this.zabbix.getHostsFromTarget(target)\n    .then((results) => {\n      let [hosts, apps] = results;\n      if (hosts.length) {\n        let hostids = _.map(hosts, 'hostid');\n        let appids = _.map(apps, 'applicationid');\n        return this.zabbix.getHostAlerts(hostids, appids, target.minSeverity, target.options.countTriggers, timeFrom, timeTo)\n        .then((triggers) => {\n          return responseHandler.handleTriggersResponse(triggers, timeRange);\n        });\n      } else {\n        return Promise.resolve([]);\n      }\n    });\n  }\n\n  /**\n   * Test connection to Zabbix API\n   * @return {object} Connection status and Zabbix API version\n   */\n  testDatasource() {\n    let zabbixVersion;\n    return this.zabbix.getVersion()\n    .then(version => {\n      zabbixVersion = version;\n      return this.zabbix.login();\n    })\n    .then(() => {\n      if (this.enableDirectDBConnection) {\n        return this.zabbix.dbConnector.testSQLDataSource();\n      } else {\n        return Promise.resolve();\n      }\n    })\n    .then(() => {\n      return {\n        status: \"success\",\n        title: \"Success\",\n        message: \"Zabbix API version: \" + zabbixVersion\n      };\n    })\n    .catch(error => {\n      if (error instanceof ZabbixAPIError) {\n        return {\n          status: \"error\",\n          title: error.message,\n          message: error.message\n        };\n      } else if (error.data && error.data.message) {\n        return {\n          status: \"error\",\n          title: \"Connection failed\",\n          message: \"Connection failed: \" + error.data.message\n        };\n      } else {\n        return {\n          status: \"error\",\n          title: \"Connection failed\",\n          message: \"Could not connect to given url\"\n        };\n      }\n    });\n  }\n\n  ////////////////\n  // Templating //\n  ////////////////\n\n  /**\n   * Find metrics from templated request.\n   *\n   * @param  {string} query Query from Templating\n   * @return {string}       Metric name - group, host, app or item or list\n   *                        of metrics in \"{metric1,metcic2,...,metricN}\" format.\n   */\n  metricFindQuery(query) {\n    let result;\n    let parts = [];\n\n    // Split query. Query structure: group.host.app.item\n    _.each(utils.splitTemplateQuery(query), part => {\n      part = this.replaceTemplateVars(part, {});\n\n      // Replace wildcard to regex\n      if (part === '*') {\n        part = '/.*/';\n      }\n      parts.push(part);\n    });\n    let template = _.zipObject(['group', 'host', 'app', 'item'], parts);\n\n    // Get items\n    if (parts.length === 4) {\n      // Search for all items, even it's not belong to any application\n      if (template.app === '/.*/') {\n        template.app = '';\n      }\n      result = this.zabbix.getItems(template.group, template.host, template.app, template.item);\n    } else if (parts.length === 3) {\n      // Get applications\n      result = this.zabbix.getApps(template.group, template.host, template.app);\n    } else if (parts.length === 2) {\n      // Get hosts\n      result = this.zabbix.getHosts(template.group, template.host);\n    } else if (parts.length === 1) {\n      // Get groups\n      result = this.zabbix.getGroups(template.group);\n    } else {\n      result = Promise.resolve([]);\n    }\n\n    return result.then(metrics => {\n      return _.map(metrics, formatMetric);\n    });\n  }\n\n  /////////////////\n  // Annotations //\n  /////////////////\n\n  annotationQuery(options) {\n    var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);\n    var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);\n    var annotation = options.annotation;\n    var showOkEvents = annotation.showOkEvents ? c.SHOW_ALL_EVENTS : c.SHOW_OK_EVENTS;\n\n    // Show all triggers\n    let triggersOptions = {\n      showTriggers: c.SHOW_ALL_TRIGGERS,\n      hideHostsInMaintenance: false\n    };\n\n    var getTriggers = this.zabbix.getTriggers(this.replaceTemplateVars(annotation.group, {}),\n                                              this.replaceTemplateVars(annotation.host, {}),\n                                              this.replaceTemplateVars(annotation.application, {}),\n                                              triggersOptions);\n\n    return getTriggers.then(triggers => {\n\n      // Filter triggers by description\n      let triggerName = this.replaceTemplateVars(annotation.trigger, {});\n      if (utils.isRegex(triggerName)) {\n        triggers = _.filter(triggers, trigger => {\n          return utils.buildRegex(triggerName).test(trigger.description);\n        });\n      } else if (triggerName) {\n        triggers = _.filter(triggers, trigger => {\n          return trigger.description === triggerName;\n        });\n      }\n\n      // Remove events below the chose severity\n      triggers = _.filter(triggers, trigger => {\n        return Number(trigger.priority) >= Number(annotation.minseverity);\n      });\n\n      var objectids = _.map(triggers, 'triggerid');\n      return this.zabbix\n        .getEvents(objectids, timeFrom, timeTo, showOkEvents)\n        .then(events => {\n          var indexedTriggers = _.keyBy(triggers, 'triggerid');\n\n          // Hide acknowledged events if option enabled\n          if (annotation.hideAcknowledged) {\n            events = _.filter(events, event => {\n              return !event.acknowledges.length;\n            });\n          }\n\n          return _.map(events, event => {\n            let tags;\n            if (annotation.showHostname) {\n              tags = _.map(event.hosts, 'name');\n            }\n\n            // Show event type (OK or Problem)\n            let title = Number(event.value) ? 'Problem' : 'OK';\n\n            let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges);\n            return {\n              annotation: annotation,\n              time: event.clock * 1000,\n              title: title,\n              tags: tags,\n              text: indexedTriggers[event.objectid].description + formatted_acknowledges\n            };\n          });\n        });\n    });\n  }\n\n  /**\n   * Get triggers and its details for panel's targets\n   * Returns alert state ('ok' if no fired triggers, or 'alerting' if at least 1 trigger is fired)\n   * or empty object if no related triggers are finded.\n   */\n  alertQuery(options) {\n    let enabled_targets = filterEnabledTargets(options.targets);\n    let getPanelItems = _.map(enabled_targets, t => {\n      let target = _.cloneDeep(t);\n      this.replaceTargetVariables(target, options);\n      return this.zabbix.getItemsFromTarget(target, {itemtype: 'num'});\n    });\n\n    return Promise.all(getPanelItems)\n    .then(results => {\n      let items = _.flatten(results);\n      let itemids = _.map(items, 'itemid');\n\n      return this.zabbix.getAlerts(itemids);\n    })\n    .then(triggers => {\n      triggers = _.filter(triggers, trigger => {\n        return trigger.priority >= this.alertingMinSeverity;\n      });\n\n      if (!triggers || triggers.length === 0) {\n        return {};\n      }\n\n      let state = 'ok';\n\n      let firedTriggers = _.filter(triggers, {value: '1'});\n      if (firedTriggers.length) {\n        state = 'alerting';\n      }\n\n      let thresholds = _.map(triggers, trigger => {\n        return getTriggerThreshold(trigger.expression);\n      });\n\n      return {\n        panelId: options.panelId,\n        state: state,\n        thresholds: thresholds\n      };\n    });\n  }\n\n  // Replace template variables\n  replaceTargetVariables(target, options) {\n    let parts = ['group', 'host', 'application', 'item'];\n    _.forEach(parts, p => {\n      if (target[p] && target[p].filter) {\n        target[p].filter = this.replaceTemplateVars(target[p].filter, options.scopedVars);\n      }\n    });\n    target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);\n\n    _.forEach(target.functions, func => {\n      func.params = _.map(func.params, param => {\n        if (typeof param === 'number') {\n          return +this.templateSrv.replace(param.toString(), options.scopedVars);\n        } else {\n          return this.templateSrv.replace(param, options.scopedVars);\n        }\n      });\n    });\n  }\n\n  isUseTrends(timeRange) {\n    let [timeFrom, timeTo] = timeRange;\n    let useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);\n    let useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);\n    let useTrends = this.trends && (\n      (timeFrom <= useTrendsFrom) ||\n      (timeTo - timeFrom >= useTrendsRange)\n    );\n    return useTrends;\n  }\n}\n\nfunction bindFunctionDefs(functionDefs, category) {\n  var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name');\n  var aggFuncDefs = _.filter(functionDefs, function(func) {\n    return _.includes(aggregationFunctions, func.def.name);\n  });\n\n  return _.map(aggFuncDefs, function(func) {\n    var funcInstance = metricFunctions.createFuncInstance(func.def, func.params);\n    return funcInstance.bindFunction(dataProcessor.metricFunctions);\n  });\n}\n\nfunction getConsolidateBy(target) {\n  let consolidateBy = 'avg';\n  let funcDef = _.find(target.functions, func => {\n    return func.def.name === 'consolidateBy';\n  });\n  if (funcDef && funcDef.params && funcDef.params.length) {\n    consolidateBy = funcDef.params[0];\n  }\n  return consolidateBy;\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n  let defaultAgg = dataProcessor.aggregationFunctions['avg'];\n  let consolidateByFunc = dataProcessor.aggregationFunctions[options.consolidateBy] || defaultAgg;\n  return _.map(timeseries_data, timeseries => {\n    if (timeseries.datapoints.length > options.maxDataPoints) {\n      timeseries.datapoints = dataProcessor\n        .groupBy(options.interval, consolidateByFunc, timeseries.datapoints);\n    }\n    return timeseries;\n  });\n}\n\nfunction formatMetric(metricObj) {\n  return {\n    text: metricObj.name,\n    expandable: false\n  };\n}\n\n/**\n * Custom formatter for template variables.\n * Default Grafana \"regex\" formatter returns\n * value1|value2\n * This formatter returns\n * (value1|value2)\n * This format needed for using in complex regex with\n * template variables, for example\n * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait\n */\nfunction zabbixTemplateFormat(value) {\n  if (typeof value === 'string') {\n    return utils.escapeRegex(value);\n  }\n\n  var escapedValues = _.map(value, utils.escapeRegex);\n  return '(' + escapedValues.join('|') + ')';\n}\n\nfunction zabbixItemIdsTemplateFormat(value) {\n  if (typeof value === 'string') {\n    return value;\n  }\n  return value.join(',');\n}\n\n/**\n * If template variables are used in request, replace it using regex format\n * and wrap with '/' for proper multi-value work. Example:\n * $variable selected as a, b, c\n * We use filter $variable\n * $variable    -> a|b|c    -> /a|b|c/\n * /$variable/  -> /a|b|c/  -> /a|b|c/\n */\nfunction replaceTemplateVars(templateSrv, target, scopedVars) {\n  var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat);\n  if (target !== replacedTarget && !utils.isRegex(replacedTarget)) {\n    replacedTarget = '/^' + replacedTarget + '$/';\n  }\n  return replacedTarget;\n}\n\n// Apply function one by one:\n// sequence([a(), b(), c()]) = c(b(a()));\nfunction sequence(funcsArray) {\n  return function(result) {\n    for (var i = 0; i < funcsArray.length; i++) {\n      result = funcsArray[i].call(this, result);\n    }\n    return result;\n  };\n}\n\nfunction filterEnabledTargets(targets) {\n  return _.filter(targets, target => {\n    return !(target.hide || !target.group || !target.host || !target.item);\n  });\n}\n\nfunction getTriggerThreshold(expression) {\n  let thresholdPattern = /.*[<>]([\\d\\.]+)/;\n  let finded_thresholds = expression.match(thresholdPattern);\n  if (finded_thresholds && finded_thresholds.length >= 2) {\n    let threshold = finded_thresholds[1];\n    threshold = Number(threshold);\n    return threshold;\n  } else {\n    return null;\n  }\n}\n\nexport {ZabbixAPIDatasource, zabbixTemplateFormat};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.includes) {_.includes = _.contains;}\nif (!_.keyBy) {_.keyBy = _.indexBy;}\n"]}
\ No newline at end of file
diff --git a/dist/datasource-zabbix/partials/query.editor.html b/dist/datasource-zabbix/partials/query.editor.html
index f5831025e..3c69c3df4 100644
--- a/dist/datasource-zabbix/partials/query.editor.html
+++ b/dist/datasource-zabbix/partials/query.editor.html
@@ -48,7 +48,7 @@
     </div>
   </div>
 
-  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT">
+  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT || ctrl.target.mode == editorMode.TRIGGERS">
     <!-- Select Group -->
     <div class="gf-form max-width-20">
       <label class="gf-form-label query-keyword width-7">Group</label>
@@ -66,7 +66,7 @@
     </div>
     <!-- Select Host -->
     <div class="gf-form">
-      <label class="gf-form-label query-keyword width-7">Host</label>
+      <label class="gf-form-label query-keyword width-8">Host</label>
       <input type="text"
         ng-model="ctrl.target.host.filter"
         bs-typeahead="ctrl.getHostNames"
@@ -85,7 +85,7 @@
     </div>
   </div>
 
-  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT">
+  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT || ctrl.target.mode == editorMode.TRIGGERS">
     <!-- Select Application -->
     <div class="gf-form max-width-20">
       <label class="gf-form-label query-keyword width-7">Application</label>
@@ -103,8 +103,8 @@
     </div>
 
     <!-- Select Item -->
-    <div class="gf-form">
-      <label class="gf-form-label query-keyword width-7">Item</label>
+    <div class="gf-form" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT">
+      <label class="gf-form-label query-keyword width-8">Item</label>
       <input type="text"
         ng-model="ctrl.target.item.filter"
         bs-typeahead="ctrl.getItemNames"
@@ -117,6 +117,18 @@
           'zbx-regex': ctrl.isRegex(ctrl.target.item.filter)
         }">
     </div>
+
+    <div class="gf-form max-width-20" ng-show="ctrl.target.mode == editorMode.TRIGGERS">
+      <label class="gf-form-label query-keyword width-8">Min Severity</label>
+      <div class="gf-form-select-wrapper width-20">
+        <select class="gf-form-input"
+              ng-change="ctrl.onTargetBlur()"
+              ng-model="ctrl.target.minSeverity"
+              ng-options="s.val as s.text for s in ctrl.triggerSeverity">
+        </select>
+      </div>
+    </div>
+
     <div class="gf-form gf-form--grow">
       <label class="gf-form-label gf-form-label--grow">
         <a ng-click="ctrl.toggleQueryOptions()">
@@ -130,13 +142,20 @@
 
   <!-- Query options -->
   <div class="gf-form-group" ng-if="ctrl.showQueryOptions">
-    <div class="gf-form offset-width-7">
+    <div class="gf-form offset-width-7" ng-hide="ctrl.target.mode == editorMode.TRIGGERS">
       <gf-form-switch class="gf-form"
         label="Show disabled items"
         checked="ctrl.target.options.showDisabledItems"
         on-change="ctrl.onQueryOptionChange()">
       </gf-form-switch>
     </div>
+    <div class="gf-form offset-width-7" ng-show="ctrl.target.mode == editorMode.TRIGGERS">
+      <gf-form-switch class="gf-form"
+        label="Count triggers"
+        checked="ctrl.target.options.countTriggers"
+        on-change="ctrl.onQueryOptionChange()">
+      </gf-form-switch>
+    </div>
   </div>
 
   <!-- Item IDs editor mode -->
diff --git a/dist/datasource-zabbix/query.controller.js b/dist/datasource-zabbix/query.controller.js
index 87ad8f99e..c74c578dd 100644
--- a/dist/datasource-zabbix/query.controller.js
+++ b/dist/datasource-zabbix/query.controller.js
@@ -83,17 +83,20 @@ System.register(['app/plugins/sdk', 'lodash', './constants', './utils', './metri
           _this.replaceTemplateVars = _this.datasource.replaceTemplateVars;
           _this.templateSrv = templateSrv;
 
-          _this.editorModes = [{ value: 'num', text: 'Metrics', mode: c.MODE_METRICS }, { value: 'text', text: 'Text', mode: c.MODE_TEXT }, { value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE }, { value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID }];
+          _this.editorModes = [{ value: 'num', text: 'Metrics', mode: c.MODE_METRICS }, { value: 'text', text: 'Text', mode: c.MODE_TEXT }, { value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE }, { value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID }, { value: 'triggers', text: 'Triggers', mode: c.MODE_TRIGGERS }];
 
           _this.$scope.editorMode = {
             METRICS: c.MODE_METRICS,
             TEXT: c.MODE_TEXT,
             ITSERVICE: c.MODE_ITSERVICE,
-            ITEMID: c.MODE_ITEMID
+            ITEMID: c.MODE_ITEMID,
+            TRIGGERS: c.MODE_TRIGGERS
           };
 
           _this.slaPropertyList = [{ name: "Status", property: "status" }, { name: "SLA", property: "sla" }, { name: "OK time", property: "okTime" }, { name: "Problem time", property: "problemTime" }, { name: "Down time", property: "downtimeTime" }];
 
+          _this.triggerSeverity = [{ val: 0, text: 'Not classified' }, { val: 1, text: 'Information' }, { val: 2, text: 'Warning' }, { val: 3, text: 'Average' }, { val: 4, text: 'High' }, { val: 5, text: 'Disaster' }];
+
           // Map functions for bs-typeahead
           _this.getGroupNames = _.bind(_this.getMetricNames, _this, 'groupList');
           _this.getHostNames = _.bind(_this.getMetricNames, _this, 'hostList', true);
@@ -133,8 +136,10 @@ System.register(['app/plugins/sdk', 'lodash', './constants', './utils', './metri
               'application': { 'filter': "" },
               'item': { 'filter': "" },
               'functions': [],
+              'minSeverity': 3,
               'options': {
-                'showDisabledItems': false
+                'showDisabledItems': false,
+                'countTriggers': true
               }
             };
             _.defaults(target, targetDefaults);
@@ -144,8 +149,7 @@ System.register(['app/plugins/sdk', 'lodash', './constants', './utils', './metri
               return metricFunctions.createFuncInstance(func.def, func.params);
             });
 
-            if (target.mode === c.MODE_METRICS || target.mode === c.MODE_TEXT) {
-
+            if (target.mode === c.MODE_METRICS || target.mode === c.MODE_TEXT || target.mode === c.MODE_TRIGGERS) {
               this.initFilters();
             } else if (target.mode === c.MODE_ITSERVICE) {
               _.defaults(target, { slaProperty: { name: "SLA", property: "sla" } });
@@ -154,6 +158,7 @@ System.register(['app/plugins/sdk', 'lodash', './constants', './utils', './metri
           };
 
           _this.init();
+          _this.queryOptionsText = _this.renderQueryOptionsText();
           return _this;
         }
 
@@ -355,7 +360,8 @@ System.register(['app/plugins/sdk', 'lodash', './constants', './utils', './metri
           key: 'renderQueryOptionsText',
           value: function renderQueryOptionsText() {
             var optionsMap = {
-              showDisabledItems: "Show disabled items"
+              showDisabledItems: "Show disabled items",
+              countTriggers: "Count Triggers"
             };
             var options = [];
             _.forOwn(this.target.options, function (value, key) {
diff --git a/dist/datasource-zabbix/query.controller.js.map b/dist/datasource-zabbix/query.controller.js.map
index 0f7483570..d7fa59820 100644
--- a/dist/datasource-zabbix/query.controller.js.map
+++ b/dist/datasource-zabbix/query.controller.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/datasource-zabbix/query.controller.js"],"names":["QueryCtrl","_","c","utils","metricFunctions","migrations","ZabbixQueryController","$scope","$injector","$rootScope","$sce","templateSrv","zabbix","datasource","replaceTemplateVars","editorModes","value","text","mode","MODE_METRICS","MODE_TEXT","MODE_ITSERVICE","MODE_ITEMID","editorMode","METRICS","TEXT","ITSERVICE","ITEMID","slaPropertyList","name","property","getGroupNames","bind","getMetricNames","getHostNames","getApplicationNames","getItemNames","getITServices","getVariables","getTemplateVariables","$on","onVariableChange","onTargetBlur","init","target","migrate","scopeDefaults","metric","oldTarget","cloneDeep","queryOptionsText","renderQueryOptionsText","defaults","targetDefaults","functions","map","func","createFuncInstance","def","params","initFilters","slaProperty","suggestITServices","itemtype","find","Promise","all","suggestGroups","suggestHosts","suggestApps","suggestItems","metricList","addAllValue","metrics","uniq","forEach","variables","unshift","variable","getAllGroups","then","groupList","groups","groupFilter","group","filter","getAllHosts","hostList","hosts","hostFilter","host","getAllApps","appList","apps","appFilter","application","options","showDisabledItems","getAllItems","itemList","items","getITService","itServiceList","itservices","str","isRegex","isTemplateVariable","newTarget","isEqual","targetChanged","isContainsVariables","some","field","parseTarget","panelCtrl","refresh","funcDef","newFunc","added","push","moveAliasFuncLast","length","without","aliasFunc","showQueryOptions","optionsMap","forOwn","key","join","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAQA,e,kBAAAA,S;;AACDC,O;;AACKC,O;;AACAC,W;;AACAC,qB;;AACAC,gB;;;;;;;;;;;;;;;;;;;;;uCAOCC,qB;;;AAEX;AACA,uCAAYC,MAAZ,EAAoBC,SAApB,EAA+BC,UAA/B,EAA2CC,IAA3C,EAAiDC,WAAjD,EAA8D;AAAA;;AAAA,oJACtDJ,MAD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AS7B,IAAT,KAAkB,aADb,IAEL2B,KAAKE,GAAL,CAAS7B,IAAT,KAAkB,eAFpB;AAGD,aAJe,CAAhB;;AAMA,gBAAI8F,SAAJ,EAAe;AACb,mBAAK/E,MAAL,CAAYU,SAAZ,GAAwBrD,EAAEyH,OAAF,CAAU,KAAK9E,MAAL,CAAYU,SAAtB,EAAiCqE,SAAjC,CAAxB;AACA,mBAAK/E,MAAL,CAAYU,SAAZ,CAAsBiE,IAAtB,CAA2BI,SAA3B;AACD;AACF;;;+CAEoB;AACnB,iBAAKC,gBAAL,GAAwB,CAAC,KAAKA,gBAA9B;AACD;;;gDAEqB;AACpB,iBAAK1E,gBAAL,GAAwB,KAAKC,sBAAL,EAAxB;AACA,iBAAKT,YAAL;AACD;;;mDAEwB;AACvB,gBAAImF,aAAa;AACf5B,iCAAmB;AADJ,aAAjB;AAGA,gBAAID,UAAU,EAAd;AACA/F,cAAE6H,MAAF,CAAS,KAAKlF,MAAL,CAAYoD,OAArB,EAA8B,UAAChF,KAAD,EAAQ+G,GAAR,EAAgB;AAC5C,kBAAI/G,KAAJ,EAAW;AACT,oBAAIA,UAAU,IAAd,EAAoB;AAClB;AACAgF,0BAAQuB,IAAR,CAAaM,WAAWE,GAAX,CAAb;AACD,iBAHD,MAGO;AACL;AACA/B,0BAAQuB,IAAR,CAAaM,WAAWE,GAAX,IAAkB,KAAlB,GAA0B/G,KAAvC;AACD;AACF;AACF,aAVD;AAWA,mBAAO,cAAcgF,QAAQgC,IAAR,CAAa,IAAb,CAArB;AACD;;;2CASgB9G,I,EAAM;AACrB,iBAAK0B,MAAL,CAAY1B,IAAZ,GAAmBA,IAAnB;AACA,iBAAKyB,IAAL;AACA,iBAAKkE,aAAL;AACD;;;;QA5SwC7G,S;;;;AA+S3C;AACAM,4BAAsB2H,WAAtB,GAAoC,8CAApC","file":"query.controller.js","sourcesContent":["import {QueryCtrl} from 'app/plugins/sdk';\nimport _ from 'lodash';\nimport * as c from './constants';\nimport * as utils from './utils';\nimport * as metricFunctions from './metricFunctions';\nimport * as migrations from './migrations';\n\nimport './add-metric-function.directive';\nimport './metric-function-editor.directive';\n\nimport './css/query-editor.css!';\n\nexport class ZabbixQueryController extends QueryCtrl {\n\n  // ZabbixQueryCtrl constructor\n  constructor($scope, $injector, $rootScope, $sce, templateSrv) {\n    super($scope, $injector);\n    this.zabbix = this.datasource.zabbix;\n\n    // Use custom format for template variables\n    this.replaceTemplateVars = this.datasource.replaceTemplateVars;\n    this.templateSrv = templateSrv;\n\n    this.editorModes = [\n      {value: 'num',       text: 'Metrics',     mode: c.MODE_METRICS},\n      {value: 'text',      text: 'Text',        mode: c.MODE_TEXT},\n      {value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE},\n      {value: 'itemid',    text: 'Item ID',     mode: c.MODE_ITEMID}\n    ];\n\n    this.$scope.editorMode = {\n      METRICS: c.MODE_METRICS,\n      TEXT: c.MODE_TEXT,\n      ITSERVICE: c.MODE_ITSERVICE,\n      ITEMID: c.MODE_ITEMID\n    };\n\n    this.slaPropertyList = [\n      {name: \"Status\", property: \"status\"},\n      {name: \"SLA\", property: \"sla\"},\n      {name: \"OK time\", property: \"okTime\"},\n      {name: \"Problem time\", property: \"problemTime\"},\n      {name: \"Down time\", property: \"downtimeTime\"}\n    ];\n\n    // Map functions for bs-typeahead\n    this.getGroupNames = _.bind(this.getMetricNames, this, 'groupList');\n    this.getHostNames = _.bind(this.getMetricNames, this, 'hostList', true);\n    this.getApplicationNames = _.bind(this.getMetricNames, this, 'appList');\n    this.getItemNames = _.bind(this.getMetricNames, this, 'itemList');\n    this.getITServices = _.bind(this.getMetricNames, this, 'itServiceList');\n    this.getVariables = _.bind(this.getTemplateVariables, this);\n\n    // Update metric suggestion when template variable was changed\n    $rootScope.$on('template-variable-value-updated', () => this.onVariableChange());\n\n    // Update metrics when item selected from dropdown\n    $scope.$on('typeahead-updated', () => {\n      this.onTargetBlur();\n    });\n\n    this.init = function() {\n      var target = this.target;\n\n      // Migrate old targets\n      target = migrations.migrate(target);\n\n      var scopeDefaults = {\n        metric: {},\n        oldTarget: _.cloneDeep(this.target),\n        queryOptionsText: this.renderQueryOptionsText()\n      };\n      _.defaults(this, scopeDefaults);\n\n      // Load default values\n      var targetDefaults = {\n        'mode': c.MODE_METRICS,\n        'group': { 'filter': \"\" },\n        'host': { 'filter': \"\" },\n        'application': { 'filter': \"\" },\n        'item': { 'filter': \"\" },\n        'functions': [],\n        'options': {\n          'showDisabledItems': false\n        }\n      };\n      _.defaults(target, targetDefaults);\n\n      // Create function instances from saved JSON\n      target.functions = _.map(target.functions, function(func) {\n        return metricFunctions.createFuncInstance(func.def, func.params);\n      });\n\n      if (target.mode === c.MODE_METRICS ||\n          target.mode === c.MODE_TEXT) {\n\n        this.initFilters();\n      }\n      else if (target.mode === c.MODE_ITSERVICE) {\n        _.defaults(target, {slaProperty: {name: \"SLA\", property: \"sla\"}});\n        this.suggestITServices();\n      }\n    };\n\n    this.init();\n  }\n\n  initFilters() {\n    let itemtype = _.find(this.editorModes, {'mode': this.target.mode});\n    itemtype = itemtype ? itemtype.value : null;\n    return Promise.all([\n      this.suggestGroups(),\n      this.suggestHosts(),\n      this.suggestApps(),\n      this.suggestItems(itemtype)\n    ]);\n  }\n\n  // Get list of metric names for bs-typeahead directive\n  getMetricNames(metricList, addAllValue) {\n    let metrics = _.uniq(_.map(this.metric[metricList], 'name'));\n\n    // Add template variables\n    _.forEach(this.templateSrv.variables, variable => {\n      metrics.unshift('$' + variable.name);\n    });\n\n    if (addAllValue) {\n      metrics.unshift('/.*/');\n    }\n\n    return metrics;\n  }\n\n  getTemplateVariables() {\n    return _.map(this.templateSrv.variables, variable => {\n      return '$' + variable.name;\n    });\n  }\n\n  suggestGroups() {\n    return this.zabbix.getAllGroups()\n    .then(groups => {\n      this.metric.groupList = groups;\n      return groups;\n    });\n  }\n\n  suggestHosts() {\n    let groupFilter = this.replaceTemplateVars(this.target.group.filter);\n    return this.zabbix.getAllHosts(groupFilter)\n    .then(hosts => {\n      this.metric.hostList = hosts;\n      return hosts;\n    });\n  }\n\n  suggestApps() {\n    let groupFilter = this.replaceTemplateVars(this.target.group.filter);\n    let hostFilter = this.replaceTemplateVars(this.target.host.filter);\n    return this.zabbix.getAllApps(groupFilter, hostFilter)\n    .then(apps => {\n      this.metric.appList = apps;\n      return apps;\n    });\n  }\n\n  suggestItems(itemtype = 'num') {\n    let groupFilter = this.replaceTemplateVars(this.target.group.filter);\n    let hostFilter = this.replaceTemplateVars(this.target.host.filter);\n    let appFilter = this.replaceTemplateVars(this.target.application.filter);\n    let options = {\n      itemtype: itemtype,\n      showDisabledItems: this.target.options.showDisabledItems\n    };\n\n    return this.zabbix\n    .getAllItems(groupFilter, hostFilter, appFilter, options)\n    .then(items => {\n      this.metric.itemList = items;\n      return items;\n    });\n  }\n\n  suggestITServices() {\n    return this.zabbix.getITService()\n    .then(itservices => {\n      this.metric.itServiceList = itservices;\n      return itservices;\n    });\n  }\n\n  isRegex(str) {\n    return utils.isRegex(str);\n  }\n\n  isVariable(str) {\n    return utils.isTemplateVariable(str, this.templateSrv.variables);\n  }\n\n  onTargetBlur() {\n    var newTarget = _.cloneDeep(this.target);\n    if (!_.isEqual(this.oldTarget, this.target)) {\n      this.oldTarget = newTarget;\n      this.targetChanged();\n    }\n  }\n\n  onVariableChange() {\n    if (this.isContainsVariables()) {\n      this.targetChanged();\n    }\n  }\n\n  /**\n   * Check query for template variables\n   */\n  isContainsVariables() {\n    return _.some(['group', 'host', 'application'], field => {\n      if (this.target[field] && this.target[field].filter) {\n        return utils.isTemplateVariable(this.target[field].filter, this.templateSrv.variables);\n      } else {\n        return false;\n      }\n    });\n  }\n\n  parseTarget() {\n    // Parse target\n  }\n\n  // Validate target and set validation info\n  validateTarget() {\n    // validate\n  }\n\n  targetChanged() {\n    this.initFilters();\n    this.parseTarget();\n    this.panelCtrl.refresh();\n  }\n\n  addFunction(funcDef) {\n    var newFunc = metricFunctions.createFuncInstance(funcDef);\n    newFunc.added = true;\n    this.target.functions.push(newFunc);\n\n    this.moveAliasFuncLast();\n\n    if (newFunc.params.length && newFunc.added ||\n        newFunc.def.params.length === 0) {\n      this.targetChanged();\n    }\n  }\n\n  removeFunction(func) {\n    this.target.functions = _.without(this.target.functions, func);\n    this.targetChanged();\n  }\n\n  moveAliasFuncLast() {\n    var aliasFunc = _.find(this.target.functions, function(func) {\n      return func.def.name === 'alias' ||\n        func.def.name === 'aliasByNode' ||\n        func.def.name === 'aliasByMetric';\n    });\n\n    if (aliasFunc) {\n      this.target.functions = _.without(this.target.functions, aliasFunc);\n      this.target.functions.push(aliasFunc);\n    }\n  }\n\n  toggleQueryOptions() {\n    this.showQueryOptions = !this.showQueryOptions;\n  }\n\n  onQueryOptionChange() {\n    this.queryOptionsText = this.renderQueryOptionsText();\n    this.onTargetBlur();\n  }\n\n  renderQueryOptionsText() {\n    var optionsMap = {\n      showDisabledItems: \"Show disabled items\"\n    };\n    var options = [];\n    _.forOwn(this.target.options, (value, key) => {\n      if (value) {\n        if (value === true) {\n          // Show only option name (if enabled) for boolean options\n          options.push(optionsMap[key]);\n        } else {\n          // Show \"option = value\" for another options\n          options.push(optionsMap[key] + \" = \" + value);\n        }\n      }\n    });\n    return \"Options: \" + options.join(', ');\n  }\n\n  /**\n   * Switch query editor to specified mode.\n   * Modes:\n   *  0 - items\n   *  1 - IT services\n   *  2 - Text metrics\n   */\n  switchEditorMode(mode) {\n    this.target.mode = mode;\n    this.init();\n    this.targetChanged();\n  }\n}\n\n// Set templateUrl as static property\nZabbixQueryController.templateUrl = 'datasource-zabbix/partials/query.editor.html';\n"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/datasource-zabbix/query.controller.js"],"names":["QueryCtrl","_","c","utils","metricFunctions","migrations","ZabbixQueryController","$scope","$injector","$rootScope","$sce","templateSrv","zabbix","datasource","replaceTemplateVars","editorModes","value","text","mode","MODE_METRICS","MODE_TEXT","MODE_ITSERVICE","MODE_ITEMID","MODE_TRIGGERS","editorMode","METRICS","TEXT","ITSERVICE","ITEMID","TRIGGERS","slaPropertyList","name","property","triggerSeverity","val","getGroupNames","bind","getMetricNames","getHostNames","getApplicationNames","getItemNames","getITServices","getVariables","getTemplateVariables","$on","onVariableChange","onTargetBlur","init","target","migrate","scopeDefaults","metric","oldTarget","cloneDeep","queryOptionsText","renderQueryOptionsText","defaults","targetDefaults","functions","map","func","createFuncInstance","def","params","initFilters","slaProperty","suggestITServices","itemtype","find","Promise","all","suggestGroups","suggestHosts","suggestApps","suggestItems","metricList","addAllValue","metrics","uniq","forEach","variables","unshift","variable","getAllGroups","then","groupList","groups","groupFilter","group","filter","getAllHosts","hostList","hosts","hostFilter","host","getAllApps","appList","apps","appFilter","application","options","showDisabledItems","getAllItems","itemList","items","getITService","itServiceList","itservices","str","isRegex","isTemplateVariable","newTarget","isEqual","targetChanged","isContainsVariables","some","field","parseTarget","panelCtrl","refresh","funcDef","newFunc","added","push","moveAliasFuncLast","length","without","aliasFunc","showQueryOptions","optionsMap","countTriggers","forOwn","key","join","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAQA,e,kBAAAA,S;;AACDC,O;;AACKC,O;;AACAC,W;;AACAC,qB;;AACAC,gB;;;;;;;;;;;;;;;;;;;;;uCAOCC,qB;;;AAEX;AACA,uCAAYC,MAAZ,EAAoBC,SAApB,EAA+BC,UAA/B,EAA2CC,IAA3C,EAAiDC,WAAjD,EAA8D;AAAA;;AAAA,oJACtDJ,MADsD,EAC9CC,SAD8C;;AAE5D,gBAAKI,MAAL,GAAc,MAAKC,UAAL,CAAgBD,MAA9B;;AAEA;AACA,gBAAKE,mBAAL,GAA2B,MAAKD,UAAL,CAAgBC,mBAA3C;AACA,gBAAKH,WAAL,GAAmBA,WAAnB;;AAEA,gBAAKI,WAAL,GAAmB,CACjB,EAACC,OAAO,KAAR,EAAqBC,MAAM,SAA3B,EAA0CC,MAAMhB,EAAEiB,YAAlD,EADiB,EAEjB,EAACH,OAAO,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R,CAAa,IAAb,CAArB;AACD;;;2CASgBnH,I,EAAM;AACrB,iBAAK8B,MAAL,CAAY9B,IAAZ,GAAmBA,IAAnB;AACA,iBAAK6B,IAAL;AACA,iBAAKkE,aAAL;AACD;;;;QAxTwCjH,S;;;;AA2T3C;AACAM,4BAAsBgI,WAAtB,GAAoC,8CAApC","file":"query.controller.js","sourcesContent":["import {QueryCtrl} from 'app/plugins/sdk';\nimport _ from 'lodash';\nimport * as c from './constants';\nimport * as utils from './utils';\nimport * as metricFunctions from './metricFunctions';\nimport * as migrations from './migrations';\n\nimport './add-metric-function.directive';\nimport './metric-function-editor.directive';\n\nimport './css/query-editor.css!';\n\nexport class ZabbixQueryController extends QueryCtrl {\n\n  // ZabbixQueryCtrl constructor\n  constructor($scope, $injector, $rootScope, $sce, templateSrv) {\n    super($scope, $injector);\n    this.zabbix = this.datasource.zabbix;\n\n    // Use custom format for template variables\n    this.replaceTemplateVars = this.datasource.replaceTemplateVars;\n    this.templateSrv = templateSrv;\n\n    this.editorModes = [\n      {value: 'num',       text: 'Metrics',     mode: c.MODE_METRICS},\n      {value: 'text',      text: 'Text',        mode: c.MODE_TEXT},\n      {value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE},\n      {value: 'itemid',    text: 'Item ID',     mode: c.MODE_ITEMID},\n      {value: 'triggers',  text: 'Triggers',    mode: c.MODE_TRIGGERS}\n    ];\n\n    this.$scope.editorMode = {\n      METRICS: c.MODE_METRICS,\n      TEXT: c.MODE_TEXT,\n      ITSERVICE: c.MODE_ITSERVICE,\n      ITEMID: c.MODE_ITEMID,\n      TRIGGERS: c.MODE_TRIGGERS\n    };\n\n    this.slaPropertyList = [\n      {name: \"Status\", property: \"status\"},\n      {name: \"SLA\", property: \"sla\"},\n      {name: \"OK time\", property: \"okTime\"},\n      {name: \"Problem time\", property: \"problemTime\"},\n      {name: \"Down time\", property: \"downtimeTime\"}\n    ];\n\n    this.triggerSeverity = [\n      {val: 0, text: 'Not classified'}, {val: 1, text:'Information'},\n      {val: 2, text: 'Warning'}, {val: 3, text: 'Average'},\n      {val: 4, text: 'High'}, {val: 5, text: 'Disaster'}\n    ];\n\n    // Map functions for bs-typeahead\n    this.getGroupNames = _.bind(this.getMetricNames, this, 'groupList');\n    this.getHostNames = _.bind(this.getMetricNames, this, 'hostList', true);\n    this.getApplicationNames = _.bind(this.getMetricNames, this, 'appList');\n    this.getItemNames = _.bind(this.getMetricNames, this, 'itemList');\n    this.getITServices = _.bind(this.getMetricNames, this, 'itServiceList');\n    this.getVariables = _.bind(this.getTemplateVariables, this);\n\n    // Update metric suggestion when template variable was changed\n    $rootScope.$on('template-variable-value-updated', () => this.onVariableChange());\n\n    // Update metrics when item selected from dropdown\n    $scope.$on('typeahead-updated', () => {\n      this.onTargetBlur();\n    });\n\n    this.init = function() {\n      var target = this.target;\n\n      // Migrate old targets\n      target = migrations.migrate(target);\n\n      var scopeDefaults = {\n        metric: {},\n        oldTarget: _.cloneDeep(this.target),\n        queryOptionsText: this.renderQueryOptionsText()\n      };\n      _.defaults(this, scopeDefaults);\n\n      // Load default values\n      var targetDefaults = {\n        'mode': c.MODE_METRICS,\n        'group': { 'filter': \"\" },\n        'host': { 'filter': \"\" },\n        'application': { 'filter': \"\" },\n        'item': { 'filter': \"\" },\n        'functions': [],\n        'minSeverity': 3,\n        'options': {\n          'showDisabledItems': false,\n          'countTriggers': true\n        }\n      };\n      _.defaults(target, targetDefaults);\n\n      // Create function instances from saved JSON\n      target.functions = _.map(target.functions, function(func) {\n        return metricFunctions.createFuncInstance(func.def, func.params);\n      });\n\n      if (target.mode === c.MODE_METRICS ||\n          target.mode === c.MODE_TEXT ||\n          target.mode === c.MODE_TRIGGERS) {\n        this.initFilters();\n      }\n      else if (target.mode === c.MODE_ITSERVICE) {\n        _.defaults(target, {slaProperty: {name: \"SLA\", property: \"sla\"}});\n        this.suggestITServices();\n      }\n    };\n\n    this.init();\n    this.queryOptionsText = this.renderQueryOptionsText();\n  }\n\n  initFilters() {\n    let itemtype = _.find(this.editorModes, {'mode': this.target.mode});\n    itemtype = itemtype ? itemtype.value : null;\n    return Promise.all([\n      this.suggestGroups(),\n      this.suggestHosts(),\n      this.suggestApps(),\n      this.suggestItems(itemtype)\n    ]);\n  }\n\n  // Get list of metric names for bs-typeahead directive\n  getMetricNames(metricList, addAllValue) {\n    let metrics = _.uniq(_.map(this.metric[metricList], 'name'));\n\n    // Add template variables\n    _.forEach(this.templateSrv.variables, variable => {\n      metrics.unshift('$' + variable.name);\n    });\n\n    if (addAllValue) {\n      metrics.unshift('/.*/');\n    }\n\n    return metrics;\n  }\n\n  getTemplateVariables() {\n    return _.map(this.templateSrv.variables, variable => {\n      return '$' + variable.name;\n    });\n  }\n\n  suggestGroups() {\n    return this.zabbix.getAllGroups()\n    .then(groups => {\n      this.metric.groupList = groups;\n      return groups;\n    });\n  }\n\n  suggestHosts() {\n    let groupFilter = this.replaceTemplateVars(this.target.group.filter);\n    return this.zabbix.getAllHosts(groupFilter)\n    .then(hosts => {\n      this.metric.hostList = hosts;\n      return hosts;\n    });\n  }\n\n  suggestApps() {\n    let groupFilter = this.replaceTemplateVars(this.target.group.filter);\n    let hostFilter = this.replaceTemplateVars(this.target.host.filter);\n    return this.zabbix.getAllApps(groupFilter, hostFilter)\n    .then(apps => {\n      this.metric.appList = apps;\n      return apps;\n    });\n  }\n\n  suggestItems(itemtype = 'num') {\n    let groupFilter = this.replaceTemplateVars(this.target.group.filter);\n    let hostFilter = this.replaceTemplateVars(this.target.host.filter);\n    let appFilter = this.replaceTemplateVars(this.target.application.filter);\n    let options = {\n      itemtype: itemtype,\n      showDisabledItems: this.target.options.showDisabledItems\n    };\n\n    return this.zabbix\n    .getAllItems(groupFilter, hostFilter, appFilter, options)\n    .then(items => {\n      this.metric.itemList = items;\n      return items;\n    });\n  }\n\n  suggestITServices() {\n    return this.zabbix.getITService()\n    .then(itservices => {\n      this.metric.itServiceList = itservices;\n      return itservices;\n    });\n  }\n\n  isRegex(str) {\n    return utils.isRegex(str);\n  }\n\n  isVariable(str) {\n    return utils.isTemplateVariable(str, this.templateSrv.variables);\n  }\n\n  onTargetBlur() {\n    var newTarget = _.cloneDeep(this.target);\n    if (!_.isEqual(this.oldTarget, this.target)) {\n      this.oldTarget = newTarget;\n      this.targetChanged();\n    }\n  }\n\n  onVariableChange() {\n    if (this.isContainsVariables()) {\n      this.targetChanged();\n    }\n  }\n\n  /**\n   * Check query for template variables\n   */\n  isContainsVariables() {\n    return _.some(['group', 'host', 'application'], field => {\n      if (this.target[field] && this.target[field].filter) {\n        return utils.isTemplateVariable(this.target[field].filter, this.templateSrv.variables);\n      } else {\n        return false;\n      }\n    });\n  }\n\n  parseTarget() {\n    // Parse target\n  }\n\n  // Validate target and set validation info\n  validateTarget() {\n    // validate\n  }\n\n  targetChanged() {\n    this.initFilters();\n    this.parseTarget();\n    this.panelCtrl.refresh();\n  }\n\n  addFunction(funcDef) {\n    var newFunc = metricFunctions.createFuncInstance(funcDef);\n    newFunc.added = true;\n    this.target.functions.push(newFunc);\n\n    this.moveAliasFuncLast();\n\n    if (newFunc.params.length && newFunc.added ||\n        newFunc.def.params.length === 0) {\n      this.targetChanged();\n    }\n  }\n\n  removeFunction(func) {\n    this.target.functions = _.without(this.target.functions, func);\n    this.targetChanged();\n  }\n\n  moveAliasFuncLast() {\n    var aliasFunc = _.find(this.target.functions, function(func) {\n      return func.def.name === 'alias' ||\n        func.def.name === 'aliasByNode' ||\n        func.def.name === 'aliasByMetric';\n    });\n\n    if (aliasFunc) {\n      this.target.functions = _.without(this.target.functions, aliasFunc);\n      this.target.functions.push(aliasFunc);\n    }\n  }\n\n  toggleQueryOptions() {\n    this.showQueryOptions = !this.showQueryOptions;\n  }\n\n  onQueryOptionChange() {\n    this.queryOptionsText = this.renderQueryOptionsText();\n    this.onTargetBlur();\n  }\n\n  renderQueryOptionsText() {\n    var optionsMap = {\n      showDisabledItems: \"Show disabled items\",\n      countTriggers: \"Count Triggers\"\n    };\n    var options = [];\n    _.forOwn(this.target.options, (value, key) => {\n      if (value) {\n        if (value === true) {\n          // Show only option name (if enabled) for boolean options\n          options.push(optionsMap[key]);\n        } else {\n          // Show \"option = value\" for another options\n          options.push(optionsMap[key] + \" = \" + value);\n        }\n      }\n    });\n    return \"Options: \" + options.join(', ');\n  }\n\n  /**\n   * Switch query editor to specified mode.\n   * Modes:\n   *  0 - items\n   *  1 - IT services\n   *  2 - Text metrics\n   */\n  switchEditorMode(mode) {\n    this.target.mode = mode;\n    this.init();\n    this.targetChanged();\n  }\n}\n\n// Set templateUrl as static property\nZabbixQueryController.templateUrl = 'datasource-zabbix/partials/query.editor.html';\n"]}
\ No newline at end of file
diff --git a/dist/datasource-zabbix/responseHandler.js b/dist/datasource-zabbix/responseHandler.js
index 18fa5ff09..d467c05a4 100644
--- a/dist/datasource-zabbix/responseHandler.js
+++ b/dist/datasource-zabbix/responseHandler.js
@@ -98,10 +98,21 @@ System.register(['lodash'], function (_export, _context) {
     }
   }
 
-  function convertHistoryPoint(point) {
+  function handleTriggersResponse(triggers, timeRange) {
+    if (_.isNumber(triggers)) {
+      return {
+        target: "triggers count",
+        datapoints: [[triggers, timeRange[1]]]
+      };
+    } else {
+      return triggers;
+    }
+  }function convertHistoryPoint(point) {
     // Value must be a number for properly work
     return [Number(point.value), point.clock * 1000 + Math.round(point.ns / 1000000)];
-  }function convertTrendPoint(valueType, point) {
+  }
+
+  function convertTrendPoint(valueType, point) {
     var value;
     switch (valueType) {
       case "min":
@@ -124,9 +135,7 @@ System.register(['lodash'], function (_export, _context) {
     }
 
     return [Number(value), point.clock * 1000];
-  }
-
-  return {
+  }return {
     setters: [function (_lodash) {
       _ = _lodash.default;
     }],
@@ -136,7 +145,8 @@ System.register(['lodash'], function (_export, _context) {
         convertHistory: convertHistory,
         handleTrends: handleTrends,
         handleText: handleText,
-        handleSLAResponse: handleSLAResponse
+        handleSLAResponse: handleSLAResponse,
+        handleTriggersResponse: handleTriggersResponse
       });
 
       // Fix for backward compatibility with lodash 2.4
diff --git a/dist/datasource-zabbix/responseHandler.js.map b/dist/datasource-zabbix/responseHandler.js.map
index 400aca756..5b34446e2 100644
--- a/dist/datasource-zabbix/responseHandler.js.map
+++ b/dist/datasource-zabbix/responseHandler.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/datasource-zabbix/responseHandler.js"],"names":["convertHistory","history","items","addHostName","convertPointCallback","grouped_history","_","groupBy","hosts","uniqBy","flatten","map","hist","itemid","item","find","alias","name","keys","length","host","hostid","target","datapoints","handleHistory","convertHistoryPoint","handleTrends","valueType","partial","convertTrendPoint","handleText","convertTextCallback","convertText","point","value","textFilter","extractText","useCaptureGroups","clock","Math","round","ns","str","pattern","extractPattern","RegExp","extractedValue","exec","handleSLAResponse","itservice","slaProperty","slaObject","targetSLA","serviceid","sla","property","targetStatus","parseInt","status","to","from","Number","value_min","value_max","value_avg","value_sum","value_count","uniq"],"mappings":";;;;;;;AAEA;;;;;;;;;AASA,WAASA,cAAT,CAAwBC,OAAxB,EAAiCC,KAAjC,EAAwCC,WAAxC,EAAqDC,oBAArD,EAA2E;AACzE;;;;;;;;;;AAUA;AACA,QAAIC,kBAAkBC,EAAEC,OAAF,CAAUN,OAAV,EAAmB,QAAnB,CAAtB;AACA,QAAIO,QAAQF,EAAEG,MAAF,CAASH,EAAEI,OAAF,CAAUJ,EAAEK,GAAF,CAAMT,KAAN,EAAa,OAAb,CAAV,CAAT,EAA2C,QAA3C,CAAZ,CAbyE,CAaN;;AAEnE,WAAOI,EAAEK,GAAF,CAAMN,eAAN,EAAuB,UAASO,IAAT,EAAeC,MAAf,EAAuB;AACnD,UAAIC,OAAOR,EAAES,IAAF,CAAOb,KAAP,EAAc,EAAC,UAAUW,MAAX,EAAd,CAAX;AACA,UAAIG,QAAQF,KAAKG,IAAjB;AACA,UAAIX,EAAEY,IAAF,CAAOV,KAAP,EAAcW,MAAd,GAAuB,CAAvB,IAA4BhB,WAAhC,EAA6C;AAAI;AAC/C,YAAIiB,OAAOd,EAAES,I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AClC;AACA,WAAO,CACL4B,OAAO5B,MAAMC,KAAb,CADK,EAELD,MAAMK,KAAN,GAAc,IAAd,GAAqBC,KAAKC,KAAL,CAAWP,MAAMQ,EAAN,GAAW,OAAtB,CAFhB,CAAP;AAID,GAED,SAASZ,iBAAT,CAA2BF,SAA3B,EAAsCM,KAAtC,EAA6C;AAC3C,QAAIC,KAAJ;AACA,YAAQP,SAAR;AACE,WAAK,KAAL;AACEO,gBAAQD,MAAM6B,SAAd;AACA;AACF,WAAK,KAAL;AACE5B,gBAAQD,MAAM8B,SAAd;AACA;AACF,WAAK,KAAL;AACE7B,gBAAQD,MAAM+B,SAAd;AACA;AACF,WAAK,KAAL;AACE9B,gBAAQD,MAAMgC,SAAd;AACA;AACF,WAAK,OAAL;AACE/B,gBAAQD,MAAMiC,WAAd;AACA;AACF;AACEhC,gBAAQD,MAAM+B,SAAd;AAjBJ;;AAoBA,WAAO,CACLH,OAAO3B,KAAP,CADK,EAELD,MAAMK,KAAN,GAAc,IAFT,CAAP;AAID;;;;AAxIMhC,O;;;yBA0IQ;AACbkB,uBAAeA,aADF;AAEbxB,wBAAgBA,cAFH;AAGb0B,sBAAcA,YAHD;AAIbI,oBAAYA,UAJC;AAKbkB,2BAAmBA;AALN,O;;AAQf;AACA,UAAI,CAAC1C,EAAEG,MAAP,EAAe;AAACH,UAAEG,MAAF,GAAWH,EAAE6D,IAAb;AAAmB","file":"responseHandler.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * Convert Zabbix API history.get response to Grafana format\n *\n * @return {Array}            Array of timeseries in Grafana format\n *                            {\n *                               target: \"Metric name\",\n *                               datapoints: [[<value>, <unixtime>], ...]\n *                            }\n */\nfunction convertHistory(history, items, addHostName, convertPointCallback) {\n  /**\n   * Response should be in the format:\n   * data: [\n   *          {\n   *             target: \"Metric name\",\n   *             datapoints: [[<value>, <unixtime>], ...]\n   *          }, ...\n   *       ]\n   */\n\n  // Group history by itemid\n  var grouped_history = _.groupBy(history, 'itemid');\n  var hosts = _.uniqBy(_.flatten(_.map(items, 'hosts')), 'hostid');  //uniqBy is needed to deduplicate\n\n  return _.map(grouped_history, function(hist, itemid) {\n    var item = _.find(items, {'itemid': itemid});\n    var alias = item.name;\n    if (_.keys(hosts).length > 1 && addHostName) {   //only when actual multi hosts selected\n      var host = _.find(hosts, {'hostid': item.hostid});\n      alias = host.name + \": \" + alias;\n    }\n    return {\n      target: alias,\n      datapoints: _.map(hist, convertPointCallback)\n    };\n  });\n}\n\nfunction handleHistory(history, items, addHostName = true) {\n  return convertHistory(history, items, addHostName, convertHistoryPoint);\n}\n\nfunction handleTrends(history, items, valueType, addHostName = true) {\n  var convertPointCallback = _.partial(convertTrendPoint, valueType);\n  return convertHistory(history, items, addHostName, convertPointCallback);\n}\n\nfunction handleText(history, items, target, addHostName = true) {\n  let convertTextCallback = _.partial(convertText, target);\n  return convertHistory(history, items, addHostName, convertTextCallback);\n}\n\nfunction convertText(target, point) {\n  let value = point.value;\n\n  // Regex-based extractor\n  if (target.textFilter) {\n    value = extractText(point.value, target.textFilter, target.useCaptureGroups);\n  }\n\n  return [\n    value,\n    point.clock * 1000 + Math.round(point.ns / 1000000)\n  ];\n}\n\nfunction extractText(str, pattern, useCaptureGroups) {\n  let extractPattern = new RegExp(pattern);\n  let extractedValue = extractPattern.exec(str);\n  if (extractedValue) {\n    if (useCaptureGroups) {\n      extractedValue = extractedValue[1];\n    } else {\n      extractedValue = extractedValue[0];\n    }\n  }\n  return extractedValue;\n}\n\nfunction handleSLAResponse(itservice, slaProperty, slaObject) {\n  var targetSLA = slaObject[itservice.serviceid].sla[0];\n  if (slaProperty.property === 'status') {\n    var targetStatus = parseInt(slaObject[itservice.serviceid].status);\n    return {\n      target: itservice.name + ' ' + slaProperty.name,\n      datapoints: [\n        [targetStatus, targetSLA.to * 1000]\n      ]\n    };\n  } else {\n    return {\n      target: itservice.name + ' ' + slaProperty.name,\n      datapoints: [\n        [targetSLA[slaProperty.property], targetSLA.from * 1000],\n        [targetSLA[slaProperty.property], targetSLA.to * 1000]\n      ]\n    };\n  }\n}\n\nfunction convertHistoryPoint(point) {\n  // Value must be a number for properly work\n  return [\n    Number(point.value),\n    point.clock * 1000 + Math.round(point.ns / 1000000)\n  ];\n}\n\nfunction convertTrendPoint(valueType, point) {\n  var value;\n  switch (valueType) {\n    case \"min\":\n      value = point.value_min;\n      break;\n    case \"max\":\n      value = point.value_max;\n      break;\n    case \"avg\":\n      value = point.value_avg;\n      break;\n    case \"sum\":\n      value = point.value_sum;\n      break;\n    case \"count\":\n      value = point.value_count;\n      break;\n    default:\n      value = point.value_avg;\n  }\n\n  return [\n    Number(value),\n    point.clock * 1000\n  ];\n}\n\nexport default {\n  handleHistory: handleHistory,\n  convertHistory: convertHistory,\n  handleTrends: handleTrends,\n  handleText: handleText,\n  handleSLAResponse: handleSLAResponse\n};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.uniqBy) {_.uniqBy = _.uniq;}\n"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/datasource-zabbix/responseHandler.js"],"names":["convertHistory","history","items","addHostName","convertPointCallback","grouped_history","_","groupBy","hosts","uniqBy","flatten","map","hist","itemid","item","find","alias","name","keys","length","host","hostid","target","datapoints","handleHistory","convertHistoryPoint","handleTrends","valueType","partial","convertTrendPoint","handleText","convertTextCallback","convertText","point","value","textFilter","extractText","useCaptureGroups","clock","Math","round","ns","str","pattern","extractPattern","RegExp","extractedValue","exec","handleSLAResponse","itservice","slaProperty","slaObject","targetSLA","serviceid","sla","property","targetStatus","parseInt","status","to","from","handleTriggersResponse","triggers","timeRange","isNumber","Number","value_min","value_max","value_avg","value_sum","value_count","uniq"],"mappings":";;;;;;;AAEA;;;;;;;;;AASA,WAASA,cAAT,CAAwBC,OAAxB,EAAiCC,KAAjC,EAAwCC,WAAxC,EAAqDC,oBAArD,EAA2E;AACzE;;;;;;;;;;AAUA;AACA,QAAIC,kBAAkBC,EAAEC,OAAF,CAAUN,OAAV,EAAmB,QAAnB,CAAtB;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qC,WAAd;AACA;AACF;AACEpC,gBAAQD,MAAMmC,SAAd;AAjBJ;;AAoBA,WAAO,CACLH,OAAO/B,KAAP,CADK,EAELD,MAAMK,KAAN,GAAc,IAFT,CAAP;AAID,G;;AArJMhC,O;;;yBAuJQ;AACbkB,uBAAeA,aADF;AAEbxB,wBAAgBA,cAFH;AAGb0B,sBAAcA,YAHD;AAIbI,oBAAYA,UAJC;AAKbkB,2BAAmBA,iBALN;AAMba,gCAAwBA;AANX,O;;AASf;AACA,UAAI,CAACvD,EAAEG,MAAP,EAAe;AAACH,UAAEG,MAAF,GAAWH,EAAEiE,IAAb;AAAmB","file":"responseHandler.js","sourcesContent":["import _ from 'lodash';\n\n/**\n * Convert Zabbix API history.get response to Grafana format\n *\n * @return {Array}            Array of timeseries in Grafana format\n *                            {\n *                               target: \"Metric name\",\n *                               datapoints: [[<value>, <unixtime>], ...]\n *                            }\n */\nfunction convertHistory(history, items, addHostName, convertPointCallback) {\n  /**\n   * Response should be in the format:\n   * data: [\n   *          {\n   *             target: \"Metric name\",\n   *             datapoints: [[<value>, <unixtime>], ...]\n   *          }, ...\n   *       ]\n   */\n\n  // Group history by itemid\n  var grouped_history = _.groupBy(history, 'itemid');\n  var hosts = _.uniqBy(_.flatten(_.map(items, 'hosts')), 'hostid');  //uniqBy is needed to deduplicate\n\n  return _.map(grouped_history, function(hist, itemid) {\n    var item = _.find(items, {'itemid': itemid});\n    var alias = item.name;\n    if (_.keys(hosts).length > 1 && addHostName) {   //only when actual multi hosts selected\n      var host = _.find(hosts, {'hostid': item.hostid});\n      alias = host.name + \": \" + alias;\n    }\n    return {\n      target: alias,\n      datapoints: _.map(hist, convertPointCallback)\n    };\n  });\n}\n\nfunction handleHistory(history, items, addHostName = true) {\n  return convertHistory(history, items, addHostName, convertHistoryPoint);\n}\n\nfunction handleTrends(history, items, valueType, addHostName = true) {\n  var convertPointCallback = _.partial(convertTrendPoint, valueType);\n  return convertHistory(history, items, addHostName, convertPointCallback);\n}\n\nfunction handleText(history, items, target, addHostName = true) {\n  let convertTextCallback = _.partial(convertText, target);\n  return convertHistory(history, items, addHostName, convertTextCallback);\n}\n\nfunction convertText(target, point) {\n  let value = point.value;\n\n  // Regex-based extractor\n  if (target.textFilter) {\n    value = extractText(point.value, target.textFilter, target.useCaptureGroups);\n  }\n\n  return [\n    value,\n    point.clock * 1000 + Math.round(point.ns / 1000000)\n  ];\n}\n\nfunction extractText(str, pattern, useCaptureGroups) {\n  let extractPattern = new RegExp(pattern);\n  let extractedValue = extractPattern.exec(str);\n  if (extractedValue) {\n    if (useCaptureGroups) {\n      extractedValue = extractedValue[1];\n    } else {\n      extractedValue = extractedValue[0];\n    }\n  }\n  return extractedValue;\n}\n\nfunction handleSLAResponse(itservice, slaProperty, slaObject) {\n  var targetSLA = slaObject[itservice.serviceid].sla[0];\n  if (slaProperty.property === 'status') {\n    var targetStatus = parseInt(slaObject[itservice.serviceid].status);\n    return {\n      target: itservice.name + ' ' + slaProperty.name,\n      datapoints: [\n        [targetStatus, targetSLA.to * 1000]\n      ]\n    };\n  } else {\n    return {\n      target: itservice.name + ' ' + slaProperty.name,\n      datapoints: [\n        [targetSLA[slaProperty.property], targetSLA.from * 1000],\n        [targetSLA[slaProperty.property], targetSLA.to * 1000]\n      ]\n    };\n  }\n}\n\nfunction handleTriggersResponse(triggers, timeRange) {\n  if (_.isNumber(triggers)) {\n    return {\n      target: \"triggers count\",\n      datapoints: [\n        [triggers, timeRange[1]]\n      ]\n    };\n  } else {\n    return triggers;\n  }\n}\n\nfunction convertHistoryPoint(point) {\n  // Value must be a number for properly work\n  return [\n    Number(point.value),\n    point.clock * 1000 + Math.round(point.ns / 1000000)\n  ];\n}\n\nfunction convertTrendPoint(valueType, point) {\n  var value;\n  switch (valueType) {\n    case \"min\":\n      value = point.value_min;\n      break;\n    case \"max\":\n      value = point.value_max;\n      break;\n    case \"avg\":\n      value = point.value_avg;\n      break;\n    case \"sum\":\n      value = point.value_sum;\n      break;\n    case \"count\":\n      value = point.value_count;\n      break;\n    default:\n      value = point.value_avg;\n  }\n\n  return [\n    Number(value),\n    point.clock * 1000\n  ];\n}\n\nexport default {\n  handleHistory: handleHistory,\n  convertHistory: convertHistory,\n  handleTrends: handleTrends,\n  handleText: handleText,\n  handleSLAResponse: handleSLAResponse,\n  handleTriggersResponse: handleTriggersResponse\n};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.uniqBy) {_.uniqBy = _.uniq;}\n"]}
\ No newline at end of file
diff --git a/dist/datasource-zabbix/zabbix.js b/dist/datasource-zabbix/zabbix.js
index fb1cb12d8..2c4a17888 100644
--- a/dist/datasource-zabbix/zabbix.js
+++ b/dist/datasource-zabbix/zabbix.js
@@ -3,7 +3,7 @@
 System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './zabbixCachingProxy.service.js', './zabbixDBConnector'], function (_export, _context) {
   "use strict";
 
-  var angular, _, utils, _createClass;
+  var angular, _, utils, _slicedToArray, _createClass;
 
   function _toConsumableArray(arr) {
     if (Array.isArray(arr)) {
@@ -69,6 +69,7 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za
         this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);
         this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);
         this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI);
+        this.getHostAlerts = this.zabbixAPI.getHostAlerts.bind(this.zabbixAPI);
         this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);
         this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);
         this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);
@@ -85,6 +86,24 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za
           });
           return this.getItems.apply(this, _toConsumableArray(filters).concat([options]));
         }
+      }, {
+        key: 'getHostsFromTarget',
+        value: function getHostsFromTarget(target) {
+          var parts = ['group', 'host', 'application'];
+          var filters = _.map(parts, function (p) {
+            return target[p].filter;
+          });
+          return Promise.all([this.getHosts.apply(this, _toConsumableArray(filters)), this.getApps.apply(this, _toConsumableArray(filters))]).then(function (results) {
+            var _results = _slicedToArray(results, 2),
+                hosts = _results[0],
+                apps = _results[1];
+
+            if (apps.appFilterEmpty) {
+              apps = [];
+            }
+            return [hosts, apps];
+          });
+        }
       }, {
         key: 'getAllGroups',
         value: function getAllGroups() {
@@ -302,6 +321,44 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za
       utils = _utils;
     }, function (_zabbixAPIServiceJs) {}, function (_zabbixCachingProxyServiceJs) {}, function (_zabbixDBConnector) {}],
     execute: function () {
+      _slicedToArray = function () {
+        function sliceIterator(arr, i) {
+          var _arr = [];
+          var _n = true;
+          var _d = false;
+          var _e = undefined;
+
+          try {
+            for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
+              _arr.push(_s.value);
+
+              if (i && _arr.length === i) break;
+            }
+          } catch (err) {
+            _d = true;
+            _e = err;
+          } finally {
+            try {
+              if (!_n && _i["return"]) _i["return"]();
+            } finally {
+              if (_d) throw _e;
+            }
+          }
+
+          return _arr;
+        }
+
+        return function (arr, i) {
+          if (Array.isArray(arr)) {
+            return arr;
+          } else if (Symbol.iterator in Object(arr)) {
+            return sliceIterator(arr, i);
+          } else {
+            throw new TypeError("Invalid attempt to destructure non-iterable instance");
+          }
+        };
+      }();
+
       _createClass = function () {
         function defineProperties(target, props) {
           for (var i = 0; i < props.length; i++) {
diff --git a/dist/datasource-zabbix/zabbix.js.map b/dist/datasource-zabbix/zabbix.js.map
index 54358d98c..f21cf83cd 100644
--- a/dist/datasource-zabbix/zabbix.js.map
+++ b/dist/datasource-zabbix/zabbix.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/datasource-zabbix/zabbix.js"],"names":["ZabbixFactory","zabbixAPIService","ZabbixCachingProxy","ZabbixDBConnector","Zabbix","url","options","username","password","basicAuth","withCredentials","cacheTTL","enableDirectDBConnection","sqlDatasourceId","ZabbixAPI","zabbixAPI","dbConnector","cacheOptions","enabled","ttl","cachingProxy","getHistory","bind","getMacros","getItemsByIDs","getHistoryDB","getTrendsDB","getTrend","getEvents","getAlerts","getAcknowledges","getITService","getSLA","getVersion","login","target","parts","filters","_","map","p","filter","getItems","getGroups","groupFilter","getAllGroups","then","findByFilter","groups","groupids","getHosts","hostFilter","getAllHosts","hosts","hostids","getApps","appFilter","filterByQuery","apps","appFilterEmpty","undefined","itemtype","appids","showDisabledItems","items","expandUserMacro","getHostIds","forEach","utils","containsMacro","item","name","replaceMacro","macros","itemFilter","getAllItems","itServiceFilter","getITServices","itServices","promises","Promise","all","filteredGroups","results","filteredHosts","filteredApps","query","applicationids","flatten","getTriggers","findByName","list","finded","find","filterByName","filterByRegex","regex","filterPattern","buildRegex","zbx_obj","test","isRegex","hostIds","uniq","angular","module","factory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOA;AACA;;AAEA;AACA,WAASA,aAAT,CAAuBC,gBAAvB,EAAyCC,kBAAzC,EAA6DC,iBAA7D,EAAgF;AAAA,QAExEC,MAFwE;AAG5E,sBAAYC,GAAZ,EAAiBC,OAAjB,EAA0B;AAAA;;AAAA,YAEtBC,QAFsB,GAIpBD,OAJoB,CAEtBC,QAFsB;AAAA,YAEZC,QAFY,GAIpBF,OAJoB,CAEZE,QAFY;AAAA,YAEFC,SAFE,GAIpBH,OAJoB,CAEFG,SAFE;AAAA,YAESC,eAFT,GAIpBJ,OAJoB,CAESI,eAFT;AAAA,YAE0BC,QAF1B,GAIpBL,OAJoB,CAE0BK,QAF1B;AAAA,YAGtBC,wBAHsB,GAIpBN,OAJoB,CAGtBM,wBAHsB;AAAA,YAGIC,eAHJ,GAIpBP,OAJoB,CAGIO,eAHJ;;;AAMxB;AACA,YAAIC,YAAYb,gBAAhB;AACA,aAAKc,SAAL,GAAiB,IAAID,SAAJ,CAAcT,GAAd,EAAmBE,QAAnB,EAA6BC,QAA7B,EAAuCC,SAAv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B,CAAP;AACD;AACF;;AAED,WAASgB,aAAT,CAAuBkC,IAAvB,EAA6BlD,MAA7B,EAAqC;AACnC,QAAI2B,MAAMiC,OAAN,CAAc5D,MAAd,CAAJ,EAA2B;AACzB,aAAOsD,cAAcJ,IAAd,EAAoBlD,MAApB,CAAP;AACD,KAFD,MAEO;AACL,aAAOqD,aAAaH,IAAb,EAAmBlD,MAAnB,CAAP;AACD;AACF;;AAED,WAASyB,UAAT,CAAoBF,KAApB,EAA2B;AACzB,QAAIsC,UAAUhE,EAAEC,GAAF,CAAMyB,KAAN,EAAa,gBAAQ;AACjC,aAAO1B,EAAEC,GAAF,CAAM+B,KAAKjB,KAAX,EAAkB,QAAlB,CAAP;AACD,KAFa,CAAd;AAGA,WAAOf,EAAEiE,IAAF,CAAOjE,EAAEkD,OAAF,CAAUc,OAAV,CAAP,CAAP;AACD;;;AAnQME,a;;AACAlE,O;;AACK8B,W;;;;;;;;;;;;;;;;;;;;;AA+LZoC,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,QAFX,EAEqB1G,aAFrB","file":"zabbix.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport * as utils from './utils';\nimport './zabbixAPI.service.js';\nimport './zabbixCachingProxy.service.js';\nimport './zabbixDBConnector';\n\n// Use factory() instead service() for multiple data sources support.\n// Each Zabbix data source instance should initialize its own API instance.\n\n/** @ngInject */\nfunction ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector) {\n\n  class Zabbix {\n    constructor(url, options) {\n      let {\n        username, password, basicAuth, withCredentials, cacheTTL,\n        enableDirectDBConnection, sqlDatasourceId\n      } = options;\n\n      // Initialize Zabbix API\n      var ZabbixAPI = zabbixAPIService;\n      this.zabbixAPI = new ZabbixAPI(url, username, password, basicAuth, withCredentials);\n\n      if (enableDirectDBConnection) {\n        this.dbConnector = new ZabbixDBConnector(sqlDatasourceId);\n      }\n\n      // Initialize caching proxy for requests\n      let cacheOptions = {\n        enabled: true,\n        ttl: cacheTTL\n      };\n      this.cachingProxy = new ZabbixCachingProxy(this.zabbixAPI, this.dbConnector, cacheOptions);\n\n      // Proxy methods\n      this.getHistory = this.cachingProxy.getHistory.bind(this.cachingProxy);\n      this.getMacros = this.cachingProxy.getMacros.bind(this.cachingProxy);\n      this.getItemsByIDs = this.cachingProxy.getItemsByIDs.bind(this.cachingProxy);\n\n      if (enableDirectDBConnection) {\n        this.getHistoryDB = this.cachingProxy.getHistoryDB.bind(this.cachingProxy);\n        this.getTrendsDB = this.cachingProxy.getTrendsDB.bind(this.cachingProxy);\n      }\n\n      this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);\n      this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);\n      this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI);\n      this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);\n      this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);\n      this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);\n      this.getVersion = this.zabbixAPI.getVersion.bind(this.zabbixAPI);\n      this.login = this.zabbixAPI.login.bind(this.zabbixAPI);\n    }\n\n    getItemsFromTarget(target, options) {\n      let parts = ['group', 'host', 'application', 'item'];\n      let filters = _.map(parts, p => target[p].filter);\n      return this.getItems(...filters, options);\n    }\n\n    getAllGroups() {\n      return this.cachingProxy.getGroups();\n    }\n\n    getGroups(groupFilter) {\n      return this.getAllGroups()\n      .then(groups => findByFilter(groups, groupFilter));\n    }\n\n    /**\n     * Get list of host belonging to given groups.\n     */\n    getAllHosts(groupFilter) {\n      return this.getGroups(groupFilter)\n      .then(groups => {\n        let groupids = _.map(groups, 'groupid');\n        return this.cachingProxy.getHosts(groupids);\n      });\n    }\n\n    getHosts(groupFilter, hostFilter) {\n      return this.getAllHosts(groupFilter)\n      .then(hosts => findByFilter(hosts, hostFilter));\n    }\n\n    /**\n     * Get list of applications belonging to given groups and hosts.\n     */\n    getAllApps(groupFilter, hostFilter) {\n      return this.getHosts(groupFilter, hostFilter)\n      .then(hosts => {\n        let hostids = _.map(hosts, 'hostid');\n        return this.cachingProxy.getApps(hostids);\n      });\n    }\n\n    getApps(groupFilter, hostFilter, appFilter) {\n      return this.getHosts(groupFilter, hostFilter)\n      .then(hosts => {\n        let hostids = _.map(hosts, 'hostid');\n        if (appFilter) {\n          return this.cachingProxy.getApps(hostids)\n          .then(apps => filterByQuery(apps, appFilter));\n        } else {\n          return {\n            appFilterEmpty: true,\n            hostids: hostids\n          };\n        }\n      });\n    }\n\n    getAllItems(groupFilter, hostFilter, appFilter, options = {}) {\n      return this.getApps(groupFilter, hostFilter, appFilter)\n      .then(apps => {\n        if (apps.appFilterEmpty) {\n          return this.cachingProxy.getItems(apps.hostids, undefined, options.itemtype);\n        } else {\n          let appids = _.map(apps, 'applicationid');\n          return this.cachingProxy.getItems(undefined, appids, options.itemtype);\n        }\n      })\n      .then(items => {\n        if (!options.showDisabledItems) {\n          items = _.filter(items, {'status': '0'});\n        }\n\n        return items;\n      })\n      .then(this.expandUserMacro.bind(this));\n    }\n\n    expandUserMacro(items) {\n      let hostids = getHostIds(items);\n      return this.getMacros(hostids)\n      .then(macros => {\n        _.forEach(items, item => {\n          if (utils.containsMacro(item.name)) {\n            item.name = utils.replaceMacro(item, macros);\n          }\n        });\n        return items;\n      });\n    }\n\n    getItems(groupFilter, hostFilter, appFilter, itemFilter, options = {}) {\n      return this.getAllItems(groupFilter, hostFilter, appFilter, options)\n      .then(items => filterByQuery(items, itemFilter));\n    }\n\n    getITServices(itServiceFilter) {\n      return this.cachingProxy.getITServices()\n      .then(itServices => findByFilter(itServices, itServiceFilter));\n    }\n\n    /**\n     * Build query - convert target filters to array of Zabbix items\n     */\n    getTriggers(groupFilter, hostFilter, appFilter, options) {\n      let promises = [\n        this.getGroups(groupFilter),\n        this.getHosts(groupFilter, hostFilter),\n        this.getApps(groupFilter, hostFilter, appFilter)\n      ];\n\n      return Promise.all(promises)\n      .then(results => {\n        let filteredGroups = results[0];\n        let filteredHosts = results[1];\n        let filteredApps = results[2];\n        let query = {};\n\n        if (appFilter) {\n          query.applicationids = _.flatten(_.map(filteredApps, 'applicationid'));\n        }\n        if (hostFilter) {\n          query.hostids = _.map(filteredHosts, 'hostid');\n        }\n        if (groupFilter) {\n          query.groupids = _.map(filteredGroups, 'groupid');\n        }\n\n        return query;\n      }).then(query => {\n        return this.zabbixAPI.getTriggers(query.groupids, query.hostids, query.applicationids, options);\n      });\n    }\n  }\n\n  return Zabbix;\n}\n\nangular\n  .module('grafana.services')\n  .factory('Zabbix', ZabbixFactory);\n\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Find group, host, app or item by given name.\n * @param  list list of groups, apps or other\n * @param  name visible name\n * @return      array with finded element or empty array\n */\nfunction findByName(list, name) {\n  var finded = _.find(list, {'name': name});\n  if (finded) {\n    return [finded];\n  } else {\n    return [];\n  }\n}\n\n/**\n * Different hosts can contains applications and items with same name.\n * For this reason use _.filter, which return all elements instead _.find,\n * which return only first finded.\n * @param  {[type]} list list of elements\n * @param  {[type]} name app name\n * @return {[type]}      array with finded element or empty array\n */\nfunction filterByName(list, name) {\n  var finded = _.filter(list, {'name': name});\n  if (finded) {\n    return finded;\n  } else {\n    return [];\n  }\n}\n\nfunction filterByRegex(list, regex) {\n  var filterPattern = utils.buildRegex(regex);\n  return _.filter(list, function (zbx_obj) {\n    return filterPattern.test(zbx_obj.name);\n  });\n}\n\nfunction findByFilter(list, filter) {\n  if (utils.isRegex(filter)) {\n    return filterByRegex(list, filter);\n  } else {\n    return findByName(list, filter);\n  }\n}\n\nfunction filterByQuery(list, filter) {\n  if (utils.isRegex(filter)) {\n    return filterByRegex(list, filter);\n  } else {\n    return filterByName(list, filter);\n  }\n}\n\nfunction getHostIds(items) {\n  let hostIds = _.map(items, item => {\n    return _.map(item.hosts, 'hostid');\n  });\n  return _.uniq(_.flatten(hostIds));\n}\n"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/datasource-zabbix/zabbix.js"],"names":["ZabbixFactory","zabbixAPIService","ZabbixCachingProxy","ZabbixDBConnector","Zabbix","url","options","username","password","basicAuth","withCredentials","cacheTTL","enableDirectDBConnection","sqlDatasourceId","ZabbixAPI","zabbixAPI","dbConnector","cacheOptions","enabled","ttl","cachingProxy","getHistory","bind","getMacros","getItemsByIDs","getHistoryDB","getTrendsDB","getTrend","getEvents","getAlerts","getHostAlerts","getAcknowledges","getITService","getSLA","getVersion","login","target","parts","filters","_","map","p","filter","getItems","Promise","all","getHosts","getApps","then","results","hosts","apps","appFilterEmpty","getGroups","groupFilter","getAllGroups","findByFilter","groups","groupids","hostFilter","getAllHosts","hostids","appFilter","filterByQuery","undefined","itemtype","appids","showDisabledItems","items","expandUserMacro","getHostIds","forEach","utils","containsMacro","item","name","replaceMacro","macros","itemFilter","getAllItems","itServiceFilter","getITServices","itServices","promises","filteredGroups","filteredHosts","filteredApps","query","applicationids","flatten","getTriggers","findByName","list","finded","find","filterByName","filterByRegex","regex","filterPattern","buildRegex","zbx_obj","test","isRegex","hostIds","uniq","angular","module","factory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOA;AACA;;AAEA;AACA,WAASA,aAAT,CAAuBC,gBAAvB,EAAyCC,kBAAzC,EAA6DC,iBAA7D,EAAgF;AAAA,QAExEC,MAFwE;AAG5E,sBAAYC,GAAZ,EAAiBC,OAAjB,EAA0B;AAAA;;AAAA,YAEtBC,QAFsB,GAIpBD,OAJoB,CAEtBC,QAFsB;AAAA,YAEZC,QAFY,GAIpBF,OAJoB,CAEZE,QAFY;AAAA,YAEFC,SAFE,GAIpBH,OAJoB,CAEFG,SAFE;AAAA,YAESC,eAFT,GAIpBJ,OAJoB,CAESI,eAFT;AAAA,YAE0BC,QAF1B,GAIpBL,OAJoB,CAE0BK,QAF1B;AAAA,YAGtBC,wBAHsB,GAIpBN,OAJoB,CAGtBM,wBAHsB;AAAA,YAGIC,eAHJ,GAIpBP,OAJoB,CAG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EC,GAAF,CAAMkC,KAAKxB,KAAX,EAAkB,QAAlB,CAAP;AACD,KAFa,CAAd;AAGA,WAAOX,EAAEiE,IAAF,CAAOjE,EAAEkD,OAAF,CAAUc,OAAV,CAAP,CAAP;AACD;;;AAnRME,a;;AACAlE,O;;AACKiC,W;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+MZiC,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,QAFX,EAEqB3G,aAFrB","file":"zabbix.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport * as utils from './utils';\nimport './zabbixAPI.service.js';\nimport './zabbixCachingProxy.service.js';\nimport './zabbixDBConnector';\n\n// Use factory() instead service() for multiple data sources support.\n// Each Zabbix data source instance should initialize its own API instance.\n\n/** @ngInject */\nfunction ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector) {\n\n  class Zabbix {\n    constructor(url, options) {\n      let {\n        username, password, basicAuth, withCredentials, cacheTTL,\n        enableDirectDBConnection, sqlDatasourceId\n      } = options;\n\n      // Initialize Zabbix API\n      var ZabbixAPI = zabbixAPIService;\n      this.zabbixAPI = new ZabbixAPI(url, username, password, basicAuth, withCredentials);\n\n      if (enableDirectDBConnection) {\n        this.dbConnector = new ZabbixDBConnector(sqlDatasourceId);\n      }\n\n      // Initialize caching proxy for requests\n      let cacheOptions = {\n        enabled: true,\n        ttl: cacheTTL\n      };\n      this.cachingProxy = new ZabbixCachingProxy(this.zabbixAPI, this.dbConnector, cacheOptions);\n\n      // Proxy methods\n      this.getHistory = this.cachingProxy.getHistory.bind(this.cachingProxy);\n      this.getMacros = this.cachingProxy.getMacros.bind(this.cachingProxy);\n      this.getItemsByIDs = this.cachingProxy.getItemsByIDs.bind(this.cachingProxy);\n\n      if (enableDirectDBConnection) {\n        this.getHistoryDB = this.cachingProxy.getHistoryDB.bind(this.cachingProxy);\n        this.getTrendsDB = this.cachingProxy.getTrendsDB.bind(this.cachingProxy);\n      }\n\n      this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);\n      this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);\n      this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI);\n      this.getHostAlerts = this.zabbixAPI.getHostAlerts.bind(this.zabbixAPI);\n      this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);\n      this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);\n      this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);\n      this.getVersion = this.zabbixAPI.getVersion.bind(this.zabbixAPI);\n      this.login = this.zabbixAPI.login.bind(this.zabbixAPI);\n    }\n\n    getItemsFromTarget(target, options) {\n      let parts = ['group', 'host', 'application', 'item'];\n      let filters = _.map(parts, p => target[p].filter);\n      return this.getItems(...filters, options);\n    }\n\n    getHostsFromTarget(target) {\n      let parts = ['group', 'host', 'application'];\n      let filters = _.map(parts, p => target[p].filter);\n      return Promise.all([\n        this.getHosts(...filters),\n        this.getApps(...filters),\n      ]).then((results) => {\n        let [hosts, apps] = results;\n        if (apps.appFilterEmpty) {\n          apps = [];\n        }\n        return [hosts, apps];\n      });\n    }\n\n    getAllGroups() {\n      return this.cachingProxy.getGroups();\n    }\n\n    getGroups(groupFilter) {\n      return this.getAllGroups()\n      .then(groups => findByFilter(groups, groupFilter));\n    }\n\n    /**\n     * Get list of host belonging to given groups.\n     */\n    getAllHosts(groupFilter) {\n      return this.getGroups(groupFilter)\n      .then(groups => {\n        let groupids = _.map(groups, 'groupid');\n        return this.cachingProxy.getHosts(groupids);\n      });\n    }\n\n    getHosts(groupFilter, hostFilter) {\n      return this.getAllHosts(groupFilter)\n      .then(hosts => findByFilter(hosts, hostFilter));\n    }\n\n    /**\n     * Get list of applications belonging to given groups and hosts.\n     */\n    getAllApps(groupFilter, hostFilter) {\n      return this.getHosts(groupFilter, hostFilter)\n      .then(hosts => {\n        let hostids = _.map(hosts, 'hostid');\n        return this.cachingProxy.getApps(hostids);\n      });\n    }\n\n    getApps(groupFilter, hostFilter, appFilter) {\n      return this.getHosts(groupFilter, hostFilter)\n      .then(hosts => {\n        let hostids = _.map(hosts, 'hostid');\n        if (appFilter) {\n          return this.cachingProxy.getApps(hostids)\n          .then(apps => filterByQuery(apps, appFilter));\n        } else {\n          return {\n            appFilterEmpty: true,\n            hostids: hostids\n          };\n        }\n      });\n    }\n\n    getAllItems(groupFilter, hostFilter, appFilter, options = {}) {\n      return this.getApps(groupFilter, hostFilter, appFilter)\n      .then(apps => {\n        if (apps.appFilterEmpty) {\n          return this.cachingProxy.getItems(apps.hostids, undefined, options.itemtype);\n        } else {\n          let appids = _.map(apps, 'applicationid');\n          return this.cachingProxy.getItems(undefined, appids, options.itemtype);\n        }\n      })\n      .then(items => {\n        if (!options.showDisabledItems) {\n          items = _.filter(items, {'status': '0'});\n        }\n\n        return items;\n      })\n      .then(this.expandUserMacro.bind(this));\n    }\n\n    expandUserMacro(items) {\n      let hostids = getHostIds(items);\n      return this.getMacros(hostids)\n      .then(macros => {\n        _.forEach(items, item => {\n          if (utils.containsMacro(item.name)) {\n            item.name = utils.replaceMacro(item, macros);\n          }\n        });\n        return items;\n      });\n    }\n\n    getItems(groupFilter, hostFilter, appFilter, itemFilter, options = {}) {\n      return this.getAllItems(groupFilter, hostFilter, appFilter, options)\n      .then(items => filterByQuery(items, itemFilter));\n    }\n\n    getITServices(itServiceFilter) {\n      return this.cachingProxy.getITServices()\n      .then(itServices => findByFilter(itServices, itServiceFilter));\n    }\n\n    /**\n     * Build query - convert target filters to array of Zabbix items\n     */\n    getTriggers(groupFilter, hostFilter, appFilter, options) {\n      let promises = [\n        this.getGroups(groupFilter),\n        this.getHosts(groupFilter, hostFilter),\n        this.getApps(groupFilter, hostFilter, appFilter)\n      ];\n\n      return Promise.all(promises)\n      .then(results => {\n        let filteredGroups = results[0];\n        let filteredHosts = results[1];\n        let filteredApps = results[2];\n        let query = {};\n\n        if (appFilter) {\n          query.applicationids = _.flatten(_.map(filteredApps, 'applicationid'));\n        }\n        if (hostFilter) {\n          query.hostids = _.map(filteredHosts, 'hostid');\n        }\n        if (groupFilter) {\n          query.groupids = _.map(filteredGroups, 'groupid');\n        }\n\n        return query;\n      }).then(query => {\n        return this.zabbixAPI.getTriggers(query.groupids, query.hostids, query.applicationids, options);\n      });\n    }\n  }\n\n  return Zabbix;\n}\n\nangular\n  .module('grafana.services')\n  .factory('Zabbix', ZabbixFactory);\n\n///////////////////////////////////////////////////////////////////////////////\n\n/**\n * Find group, host, app or item by given name.\n * @param  list list of groups, apps or other\n * @param  name visible name\n * @return      array with finded element or empty array\n */\nfunction findByName(list, name) {\n  var finded = _.find(list, {'name': name});\n  if (finded) {\n    return [finded];\n  } else {\n    return [];\n  }\n}\n\n/**\n * Different hosts can contains applications and items with same name.\n * For this reason use _.filter, which return all elements instead _.find,\n * which return only first finded.\n * @param  {[type]} list list of elements\n * @param  {[type]} name app name\n * @return {[type]}      array with finded element or empty array\n */\nfunction filterByName(list, name) {\n  var finded = _.filter(list, {'name': name});\n  if (finded) {\n    return finded;\n  } else {\n    return [];\n  }\n}\n\nfunction filterByRegex(list, regex) {\n  var filterPattern = utils.buildRegex(regex);\n  return _.filter(list, function (zbx_obj) {\n    return filterPattern.test(zbx_obj.name);\n  });\n}\n\nfunction findByFilter(list, filter) {\n  if (utils.isRegex(filter)) {\n    return filterByRegex(list, filter);\n  } else {\n    return findByName(list, filter);\n  }\n}\n\nfunction filterByQuery(list, filter) {\n  if (utils.isRegex(filter)) {\n    return filterByRegex(list, filter);\n  } else {\n    return filterByName(list, filter);\n  }\n}\n\nfunction getHostIds(items) {\n  let hostIds = _.map(items, item => {\n    return _.map(item.hosts, 'hostid');\n  });\n  return _.uniq(_.flatten(hostIds));\n}\n"]}
\ No newline at end of file
diff --git a/dist/datasource-zabbix/zabbixAPI.service.js b/dist/datasource-zabbix/zabbixAPI.service.js
index 74739d8df..3cf9166be 100644
--- a/dist/datasource-zabbix/zabbixAPI.service.js
+++ b/dist/datasource-zabbix/zabbixAPI.service.js
@@ -411,6 +411,37 @@ System.register(['angular', 'lodash', './utils', './zabbixAPICore.service'], fun
             params.lastChangeTill = timeTo;
           }
 
+          return this.request('trigger.get', params);
+        }
+      }, {
+        key: 'getHostAlerts',
+        value: function getHostAlerts(hostids, applicationids, minSeverity, count, timeFrom, timeTo) {
+          var params = {
+            output: 'extend',
+            hostids: hostids,
+            min_severity: minSeverity,
+            filter: { value: 1 },
+            expandDescription: true,
+            expandData: true,
+            expandComment: true,
+            monitored: true,
+            skipDependent: true,
+            selectLastEvent: 'extend'
+          };
+
+          if (count) {
+            params.countOutput = true;
+          }
+
+          if (applicationids && applicationids.length) {
+            params.applicationids = applicationids;
+          }
+
+          if (timeFrom || timeTo) {
+            params.lastChangeSince = timeFrom;
+            params.lastChangeTill = timeTo;
+          }
+
           return this.request('trigger.get', params);
         }
       }]);
diff --git a/dist/datasource-zabbix/zabbixAPI.service.js.map b/dist/datasource-zabbix/zabbixAPI.service.js.map
index dc77eb469..a08f47d47 100644
--- a/dist/datasource-zabbix/zabbixAPI.service.js.map
+++ b/dist/datasource-zabbix/zabbixAPI.service.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../src/datasource-zabbix/zabbixAPI.service.js"],"names":["ZabbixAPIServiceFactory","alertSrv","zabbixAPICoreService","ZabbixAPI","api_url","username","password","basicAuth","withCredentials","url","auth","requestOptions","loginPromise","loginErrorCount","maxLoginAttempts","zabbixAPICore","getTrend","getTrend_ZBXNEXT1193","method","params","request","catch","isNotAuthorized","error","data","loginOnce","then","message","statusText","alertAPIError","timeout","set","Promise","resolve","login","getVersion","eventid","eventids","output","sortfield","real_hosts","groupids","hostids","appids","itemtype","webitems","filter","selectHosts","applicationids","value_type","utils","expandItems","itemids","globalmacro","itemid","items","length","lastvalue","timeFrom","timeTill","grouped_items","_","groupBy","promises","map","history","sortorder","time_from","time_till","all","flatten","trend","self","serviceids","timeRange","timeTo","intervals","from","to","options","showTriggers","hideHostsInMaintenance","expandDescription","expandData","expandComment","monitored","skipDependent","value","selectGroups","selectItems","selectLastEvent","maintenance","lastChangeSince","lastChangeTill","objectids","showEvents","select_acknowledges","preservekeys","events","event","acknowledges","angular","module","factory"],"mappings":";;;;;;;;;;;;;AAKA;AACA,WAASA,uBAAT,CAAiCC,QAAjC,EAA2CC,oBAA3C,EAAiE;AAAA,QAOzDC,SAPyD;AAS7D,yBAAYC,OAAZ,EAAqBC,QAArB,EAA+BC,QAA/B,EAAyCC,SAAzC,EAAoDC,eAApD,EAAqE;AAAA;;AACnE,aAAKC,GAAL,GAAwBL,OAAxB;AACA,aAAKC,QAAL,GAAwBA,QAAxB;AACA,aAAKC,QAAL,GAAwBA,QAAxB;AACA,aAAKI,IAAL,GAAwB,EAAxB;;AAEA,aAAKC,cAAL,GAAsB;AACpBJ,qBAAWA,SADS;AAEpBC,2BAAiBA;AAFG,SAAtB;;AAKA,aAAKI,YAAL,GAAoB,IAApB;AACA,aAAKC,eAAL,GAAuB,CAAvB;AACA,aAAKC,gBAAL,GAAwB,CAAxB;;AAEA,aAAKb,QAAL,GAAgBA,QAAhB;AACA,aAAKc,aAAL,GAAqBb,oBAArB;;AAEA,aAAKc,QAAL,GAAgB,KAAKC,oBAArB;AACA;AACD;;AAED;AACA;AACA;;AAjC6D;AAAA;AAAA,gCAmCrDC,MAnCqD,EAmC7CC,MAnC6C,EAmCrC;AAAA;;AACtB,iBAAO,KAAKJ,aAAL,CAAmBK,OAAnB,CAA2B,KAAKX,GAAhC,EAAqCS,MAArC,EAA6CC,MAA7C,EAAqD,KAAKR,cAA1D,EAA0E,KAAKD,IAA/E,EACNW,KADM,CACA,iBAAS;AACd,gBAAIC,gBAAgBC,MAAMC,IAAtB,CAAJ,EAAiC;AAC/B;AACA,oBAAKX,eAAL;AACA,kBAAI,MAAKA,eAAL,GAAuB,MAAKC,gBAAhC,EAAkD;AAChD,sBAAKD,eAAL,GAAuB,CAAvB;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AAKD;;;;AA9bM0E,a;;AACAxC,O;;AACKX,W;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8bZmD,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,kBAFX,EAE+BvG,uBAF/B","file":"zabbixAPI.service.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport * as utils from './utils';\nimport './zabbixAPICore.service';\n\n/** @ngInject */\nfunction ZabbixAPIServiceFactory(alertSrv, zabbixAPICoreService) {\n\n  /**\n   * Zabbix API Wrapper.\n   * Creates Zabbix API instance with given parameters (url, credentials and other).\n   * Wraps API calls and provides high-level methods.\n   */\n  class ZabbixAPI {\n\n    constructor(api_url, username, password, basicAuth, withCredentials) {\n      this.url              = api_url;\n      this.username         = username;\n      this.password         = password;\n      this.auth             = \"\";\n\n      this.requestOptions = {\n        basicAuth: basicAuth,\n        withCredentials: withCredentials\n      };\n\n      this.loginPromise = null;\n      this.loginErrorCount = 0;\n      this.maxLoginAttempts = 3;\n\n      this.alertSrv = alertSrv;\n      this.zabbixAPICore = zabbixAPICoreService;\n\n      this.getTrend = this.getTrend_ZBXNEXT1193;\n      //getTrend = getTrend_30;\n    }\n\n    //////////////////////////\n    // Core method wrappers //\n    //////////////////////////\n\n    request(method, params) {\n      return this.zabbixAPICore.request(this.url, method, params, this.requestOptions, this.auth)\n      .catch(error => {\n        if (isNotAuthorized(error.data)) {\n          // Handle auth errors\n          this.loginErrorCount++;\n          if (this.loginErrorCount > this.maxLoginAttempts) {\n            this.loginErrorCount = 0;\n            return null;\n          } else {\n            return this.loginOnce()\n            .then(() => this.request(method, params));\n          }\n        } else {\n          // Handle API errors\n          let message = error.data ? error.data : error.statusText;\n          this.alertAPIError(message);\n        }\n      });\n    }\n\n    alertAPIError(message, timeout = 5000) {\n      this.alertSrv.set(\n        \"Zabbix API Error\",\n        message,\n        'error',\n        timeout\n      );\n    }\n\n    /**\n     * When API unauthenticated or auth token expired each request produce login()\n     * call. But auth token is common to all requests. This function wraps login() method\n     * and call it once. If login() already called just wait for it (return its promise).\n     * @return login promise\n     */\n    loginOnce() {\n      if (!this.loginPromise) {\n        this.loginPromise = Promise.resolve(\n          this.login().then(auth => {\n            this.auth = auth;\n            this.loginPromise = null;\n            return auth;\n          })\n        );\n      }\n      return this.loginPromise;\n    }\n\n    /**\n     * Get authentication token.\n     */\n    login() {\n      return this.zabbixAPICore.login(this.url, this.username, this.password, this.requestOptions);\n    }\n\n    /**\n     * Get Zabbix API version\n     */\n    getVersion() {\n      return this.zabbixAPICore.getVersion(this.url, this.requestOptions);\n    }\n\n    ////////////////////////////////\n    // Zabbix API method wrappers //\n    ////////////////////////////////\n\n    acknowledgeEvent(eventid, message) {\n      var params = {\n        eventids: eventid,\n        message: message\n      };\n\n      return this.request('event.acknowledge', params);\n    }\n\n    getGroups() {\n      var params = {\n        output: ['name'],\n        sortfield: 'name',\n        real_hosts: true\n      };\n\n      return this.request('hostgroup.get', params);\n    }\n\n    getHosts(groupids) {\n      var params = {\n        output: ['name', 'host'],\n        sortfield: 'name'\n      };\n      if (groupids) {\n        params.groupids = groupids;\n      }\n\n      return this.request('host.get', params);\n    }\n\n    getApps(hostids) {\n      var params = {\n        output: 'extend',\n        hostids: hostids\n      };\n\n      return this.request('application.get', params);\n    }\n\n    /**\n     * Get Zabbix items\n     * @param  {[type]} hostids  host ids\n     * @param  {[type]} appids   application ids\n     * @param  {String} itemtype 'num' or 'text'\n     * @return {[type]}          array of items\n     */\n    getItems(hostids, appids, itemtype) {\n      var params = {\n        output: [\n          'name', 'key_',\n          'value_type',\n          'hostid',\n          'status',\n          'state'\n        ],\n        sortfield: 'name',\n        webitems: true,\n        filter: {},\n        selectHosts: ['hostid', 'name']\n      };\n      if (hostids) {\n        params.hostids = hostids;\n      }\n      if (appids) {\n        params.applicationids = appids;\n      }\n      if (itemtype === 'num') {\n        // Return only numeric metrics\n        params.filter.value_type = [0, 3];\n      }\n      if (itemtype === 'text') {\n        // Return only text metrics\n        params.filter.value_type = [1, 2, 4];\n      }\n\n      return this.request('item.get', params)\n      .then(utils.expandItems);\n    }\n\n    getItemsByIDs(itemids) {\n      var params = {\n        itemids: itemids,\n        output: [\n          'name', 'key_',\n          'value_type',\n          'hostid',\n          'status',\n          'state'\n        ],\n        webitems: true,\n        selectHosts: ['hostid', 'name']\n      };\n\n      return this.request('item.get', params)\n      .then(utils.expandItems);\n    }\n\n    getMacros(hostids) {\n      var params = {\n        output: 'extend',\n        hostids: hostids\n      };\n\n      return this.request('usermacro.get', params);\n    }\n\n    getGlobalMacros() {\n      var params = {\n        output: 'extend',\n        globalmacro: true\n      };\n\n      return this.request('usermacro.get', params);\n    }\n\n    getLastValue(itemid) {\n      var params = {\n        output: ['lastvalue'],\n        itemids: itemid\n      };\n      return this.request('item.get', params)\n      .then(items => items.length ? items[0].lastvalue : null);\n    }\n\n    /**\n     * Perform history query from Zabbix API\n     *\n     * @param  {Array}  items       Array of Zabbix item objects\n     * @param  {Number} timeFrom   Time in seconds\n     * @param  {Number} timeTill   Time in seconds\n     * @return {Array}  Array of Zabbix history objects\n     */\n    getHistory(items, timeFrom, timeTill) {\n\n      // Group items by value type and perform request for each value type\n      let grouped_items = _.groupBy(items, 'value_type');\n      let promises = _.map(grouped_items, (items, value_type) => {\n        let itemids = _.map(items, 'itemid');\n        let params = {\n          output: 'extend',\n          history: value_type,\n          itemids: itemids,\n          sortfield: 'clock',\n          sortorder: 'ASC',\n          time_from: timeFrom\n        };\n\n        // Relative queries (e.g. last hour) don't include an end time\n        if (timeTill) {\n          params.time_till = timeTill;\n        }\n\n        return this.request('history.get', params);\n      });\n\n      return Promise.all(promises).then(_.flatten);\n    }\n\n    /**\n     * Perform trends query from Zabbix API\n     * Use trends api extension from ZBXNEXT-1193 patch.\n     *\n     * @param  {Array}  items       Array of Zabbix item objects\n     * @param  {Number} time_from   Time in seconds\n     * @param  {Number} time_till   Time in seconds\n     * @return {Array}  Array of Zabbix trend objects\n     */\n    getTrend_ZBXNEXT1193(items, timeFrom, timeTill) {\n\n      // Group items by value type and perform request for each value type\n      let grouped_items = _.groupBy(items, 'value_type');\n      let promises = _.map(grouped_items, (items, value_type) => {\n        let itemids = _.map(items, 'itemid');\n        let params = {\n          output: 'extend',\n          trend: value_type,\n          itemids: itemids,\n          sortfield: 'clock',\n          sortorder: 'ASC',\n          time_from: timeFrom\n        };\n\n        // Relative queries (e.g. last hour) don't include an end time\n        if (timeTill) {\n          params.time_till = timeTill;\n        }\n\n        return this.request('trend.get', params);\n      });\n\n      return Promise.all(promises).then(_.flatten);\n    }\n\n    getTrend_30(items, time_from, time_till, value_type) {\n      var self = this;\n      var itemids = _.map(items, 'itemid');\n\n      var params = {\n        output: [\"itemid\",\n          \"clock\",\n          value_type\n        ],\n        itemids: itemids,\n        time_from: time_from\n      };\n\n      // Relative queries (e.g. last hour) don't include an end time\n      if (time_till) {\n        params.time_till = time_till;\n      }\n\n      return self.request('trend.get', params);\n    }\n\n    getITService(serviceids) {\n      var params = {\n        output: 'extend',\n        serviceids: serviceids\n      };\n      return this.request('service.get', params);\n    }\n\n    getSLA(serviceids, timeRange) {\n      let [timeFrom, timeTo] = timeRange;\n      var params = {\n        serviceids: serviceids,\n        intervals: [{\n          from: timeFrom,\n          to: timeTo\n        }]\n      };\n      return this.request('service.getsla', params);\n    }\n\n    getTriggers(groupids, hostids, applicationids, options) {\n      let {showTriggers, hideHostsInMaintenance, timeFrom, timeTo} = options;\n\n      let params = {\n        output: 'extend',\n        groupids: groupids,\n        hostids: hostids,\n        applicationids: applicationids,\n        expandDescription: true,\n        expandData: true,\n        expandComment: true,\n        monitored: true,\n        skipDependent: true,\n        //only_true: true,\n        filter: {\n          value: 1\n        },\n        selectGroups: ['name'],\n        selectHosts: ['name', 'host'],\n        selectItems: ['name', 'key_', 'lastvalue'],\n        selectLastEvent: 'extend'\n      };\n\n      if (showTriggers) {\n        params.filter.value = showTriggers;\n      }\n\n      if (hideHostsInMaintenance) {\n        params.maintenance = false;\n      }\n\n      if (timeFrom || timeTo) {\n        params.lastChangeSince = timeFrom;\n        params.lastChangeTill = timeTo;\n      }\n\n      return this.request('trigger.get', params);\n    }\n\n    getEvents(objectids, timeFrom, timeTo, showEvents) {\n      var params = {\n        output: 'extend',\n        time_from: timeFrom,\n        time_till: timeTo,\n        objectids: objectids,\n        select_acknowledges: 'extend',\n        selectHosts: 'extend',\n        value: showEvents\n      };\n\n      return this.request('event.get', params);\n    }\n\n    getAcknowledges(eventids) {\n      var params = {\n        output: 'extend',\n        eventids: eventids,\n        preservekeys: true,\n        select_acknowledges: 'extend',\n        sortfield: 'clock',\n        sortorder: 'DESC'\n      };\n\n      return this.request('event.get', params)\n      .then(events => {\n        return _.filter(events, (event) => event.acknowledges.length);\n      });\n    }\n\n    getAlerts(itemids, timeFrom, timeTo) {\n      var params = {\n        output: 'extend',\n        itemids: itemids,\n        expandDescription: true,\n        expandData: true,\n        expandComment: true,\n        monitored: true,\n        skipDependent: true,\n        //only_true: true,\n        // filter: {\n        //   value: 1\n        // },\n        selectLastEvent: 'extend'\n      };\n\n      if (timeFrom || timeTo) {\n        params.lastChangeSince = timeFrom;\n        params.lastChangeTill = timeTo;\n      }\n\n      return this.request('trigger.get', params);\n    }\n  }\n\n  return ZabbixAPI;\n}\n\nfunction isNotAuthorized(message) {\n  return (\n    message === \"Session terminated, re-login, please.\" ||\n    message === \"Not authorised.\" ||\n    message === \"Not authorized.\"\n  );\n}\n\nangular\n  .module('grafana.services')\n  .factory('zabbixAPIService', ZabbixAPIServiceFactory);\n"]}
\ No newline at end of file
+{"version":3,"sources":["../../src/datasource-zabbix/zabbixAPI.service.js"],"names":["ZabbixAPIServiceFactory","alertSrv","zabbixAPICoreService","ZabbixAPI","api_url","username","password","basicAuth","withCredentials","url","auth","requestOptions","loginPromise","loginErrorCount","maxLoginAttempts","zabbixAPICore","getTrend","getTrend_ZBXNEXT1193","method","params","request","catch","isNotAuthorized","error","data","loginOnce","then","message","statusText","alertAPIError","timeout","set","Promise","resolve","login","getVersion","eventid","eventids","output","sortfield","real_hosts","groupids","hostids","appids","itemtype","webitems","filter","selectHosts","applicationids","value_type","utils","expandItems","itemids","globalmacro","itemid","items","length","lastvalue","timeFrom","timeTill","grouped_items","_","groupBy","promises","map","history","sortorder","time_from","time_till","all","flatten","trend","self","serviceids","timeRange","timeTo","intervals","from","to","options","showTriggers","hideHostsInMaintenance","expandDescription","expandData","expandComment","monitored","skipDependent","value","selectGroups","selectItems","selectLastEvent","maintenance","lastChangeSince","lastChangeTill","objectids","showEvents","select_acknowledges","preservekeys","events","event","acknowledges","minSeverity","count","min_severity","countOutput","angular","module","factory"],"mappings":";;;;;;;;;;;;;AAKA;AACA,WAASA,uBAAT,CAAiCC,QAAjC,EAA2CC,oBAA3C,EAAiE;AAAA,QAOzDC,SAPyD;AAS7D,yBAAYC,OAAZ,EAAqBC,QAArB,EAA+BC,QAA/B,EAAyCC,SAAzC,EAAoDC,eAApD,EAAqE;AAAA;;AACnE,aAAKC,GAAL,GAAwBL,OAAxB;AACA,aAAKC,QAAL,GAAwBA,QAAxB;AACA,aAAKC,QAAL,GAAwBA,QAAxB;AACA,aAAKI,IAAL,GAAwB,EAAxB;;AAEA,aAAKC,cAAL,GAAsB;AACpBJ,qBAAWA,SADS;AAEpBC,2BAAiBA;AAFG,SAAtB;;AAKA,aAAKI,YAAL,GAAoB,IAApB;AACA,aAAKC,eAAL,GAAuB,CAAvB;AACA,aAAKC,gBAAL,GAAwB,CAAxB;;AAEA,aAAKb,QAAL,GAAgBA,QAAhB;AACA,aAAKc,aAAL,GAAqBb,oBAArB;;AAEA,aAAKc,QAAL,GAAgB,KAAKC,oBAArB;AACA;AACD;;AAED;AACA;AACA;;AAjC6D;AAAA;AAAA,gCAmCrDC,MAnCqD,EAmC7CC,MAnC6C,EAmCrC;AAAA;;AACtB,iBAAO,KAAKJ,aAAL,CAAmBK,OAAnB,CAA2B,KAAKX,GAAhC,EAAqCS,MAArC,EAA6CC,MAA7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MAAxB;AACD;;AAED,iBAAO,KAAKvD,OAAL,CAAa,aAAb,EAA4BD,MAA5B,CAAP;AACD;AA5a4D;AAAA;AAAA,sCA8a/CuB,OA9a+C,EA8atCM,cA9asC,EA8atBqD,WA9asB,EA8aTC,KA9aS,EA8aF5C,QA9aE,EA8aQiB,MA9aR,EA8agB;AAC3E,cAAIxD,SAAS;AACXmB,oBAAQ,QADG;AAEXI,qBAASA,OAFE;AAGX6D,0BAAcF,WAHH;AAIXvD,oBAAQ,EAAEyC,OAAO,CAAT,EAJG;AAKXL,+BAAmB,IALR;AAMXC,wBAAY,IAND;AAOXC,2BAAe,IAPJ;AAQXC,uBAAW,IARA;AASXC,2BAAe,IATJ;AAUXI,6BAAiB;AAVN,WAAb;;AAaA,cAAIY,KAAJ,EAAW;AACTnF,mBAAOqF,WAAP,GAAqB,IAArB;AACD;;AAED,cAAIxD,kBAAkBA,eAAeQ,MAArC,EAA6C;AAC3CrC,mBAAO6B,cAAP,GAAwBA,cAAxB;AACD;;AAED,cAAIU,YAAYiB,MAAhB,EAAwB;AACtBxD,mBAAOyE,eAAP,GAAyBlC,QAAzB;AACAvC,mBAAO0E,cAAP,GAAwBlB,MAAxB;AACD;;AAED,iBAAO,KAAKvD,OAAL,CAAa,aAAb,EAA4BD,MAA5B,CAAP;AACD;AA1c4D;;AAAA;AAAA;;AA6c/D,WAAOhB,SAAP;AACD;;AAED,WAASmB,eAAT,CAAyBK,OAAzB,EAAkC;AAChC,WACEA,YAAY,uCAAZ,IACAA,YAAY,iBADZ,IAEAA,YAAY,iBAHd;AAKD;;;;AA5dM8E,a;;AACA5C,O;;AACKX,W;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4dZuD,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,kBAFX,EAE+B3G,uBAF/B","file":"zabbixAPI.service.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport * as utils from './utils';\nimport './zabbixAPICore.service';\n\n/** @ngInject */\nfunction ZabbixAPIServiceFactory(alertSrv, zabbixAPICoreService) {\n\n  /**\n   * Zabbix API Wrapper.\n   * Creates Zabbix API instance with given parameters (url, credentials and other).\n   * Wraps API calls and provides high-level methods.\n   */\n  class ZabbixAPI {\n\n    constructor(api_url, username, password, basicAuth, withCredentials) {\n      this.url              = api_url;\n      this.username         = username;\n      this.password         = password;\n      this.auth             = \"\";\n\n      this.requestOptions = {\n        basicAuth: basicAuth,\n        withCredentials: withCredentials\n      };\n\n      this.loginPromise = null;\n      this.loginErrorCount = 0;\n      this.maxLoginAttempts = 3;\n\n      this.alertSrv = alertSrv;\n      this.zabbixAPICore = zabbixAPICoreService;\n\n      this.getTrend = this.getTrend_ZBXNEXT1193;\n      //getTrend = getTrend_30;\n    }\n\n    //////////////////////////\n    // Core method wrappers //\n    //////////////////////////\n\n    request(method, params) {\n      return this.zabbixAPICore.request(this.url, method, params, this.requestOptions, this.auth)\n      .catch(error => {\n        if (isNotAuthorized(error.data)) {\n          // Handle auth errors\n          this.loginErrorCount++;\n          if (this.loginErrorCount > this.maxLoginAttempts) {\n            this.loginErrorCount = 0;\n            return null;\n          } else {\n            return this.loginOnce()\n            .then(() => this.request(method, params));\n          }\n        } else {\n          // Handle API errors\n          let message = error.data ? error.data : error.statusText;\n          this.alertAPIError(message);\n        }\n      });\n    }\n\n    alertAPIError(message, timeout = 5000) {\n      this.alertSrv.set(\n        \"Zabbix API Error\",\n        message,\n        'error',\n        timeout\n      );\n    }\n\n    /**\n     * When API unauthenticated or auth token expired each request produce login()\n     * call. But auth token is common to all requests. This function wraps login() method\n     * and call it once. If login() already called just wait for it (return its promise).\n     * @return login promise\n     */\n    loginOnce() {\n      if (!this.loginPromise) {\n        this.loginPromise = Promise.resolve(\n          this.login().then(auth => {\n            this.auth = auth;\n            this.loginPromise = null;\n            return auth;\n          })\n        );\n      }\n      return this.loginPromise;\n    }\n\n    /**\n     * Get authentication token.\n     */\n    login() {\n      return this.zabbixAPICore.login(this.url, this.username, this.password, this.requestOptions);\n    }\n\n    /**\n     * Get Zabbix API version\n     */\n    getVersion() {\n      return this.zabbixAPICore.getVersion(this.url, this.requestOptions);\n    }\n\n    ////////////////////////////////\n    // Zabbix API method wrappers //\n    ////////////////////////////////\n\n    acknowledgeEvent(eventid, message) {\n      var params = {\n        eventids: eventid,\n        message: message\n      };\n\n      return this.request('event.acknowledge', params);\n    }\n\n    getGroups() {\n      var params = {\n        output: ['name'],\n        sortfield: 'name',\n        real_hosts: true\n      };\n\n      return this.request('hostgroup.get', params);\n    }\n\n    getHosts(groupids) {\n      var params = {\n        output: ['name', 'host'],\n        sortfield: 'name'\n      };\n      if (groupids) {\n        params.groupids = groupids;\n      }\n\n      return this.request('host.get', params);\n    }\n\n    getApps(hostids) {\n      var params = {\n        output: 'extend',\n        hostids: hostids\n      };\n\n      return this.request('application.get', params);\n    }\n\n    /**\n     * Get Zabbix items\n     * @param  {[type]} hostids  host ids\n     * @param  {[type]} appids   application ids\n     * @param  {String} itemtype 'num' or 'text'\n     * @return {[type]}          array of items\n     */\n    getItems(hostids, appids, itemtype) {\n      var params = {\n        output: [\n          'name', 'key_',\n          'value_type',\n          'hostid',\n          'status',\n          'state'\n        ],\n        sortfield: 'name',\n        webitems: true,\n        filter: {},\n        selectHosts: ['hostid', 'name']\n      };\n      if (hostids) {\n        params.hostids = hostids;\n      }\n      if (appids) {\n        params.applicationids = appids;\n      }\n      if (itemtype === 'num') {\n        // Return only numeric metrics\n        params.filter.value_type = [0, 3];\n      }\n      if (itemtype === 'text') {\n        // Return only text metrics\n        params.filter.value_type = [1, 2, 4];\n      }\n\n      return this.request('item.get', params)\n      .then(utils.expandItems);\n    }\n\n    getItemsByIDs(itemids) {\n      var params = {\n        itemids: itemids,\n        output: [\n          'name', 'key_',\n          'value_type',\n          'hostid',\n          'status',\n          'state'\n        ],\n        webitems: true,\n        selectHosts: ['hostid', 'name']\n      };\n\n      return this.request('item.get', params)\n      .then(utils.expandItems);\n    }\n\n    getMacros(hostids) {\n      var params = {\n        output: 'extend',\n        hostids: hostids\n      };\n\n      return this.request('usermacro.get', params);\n    }\n\n    getGlobalMacros() {\n      var params = {\n        output: 'extend',\n        globalmacro: true\n      };\n\n      return this.request('usermacro.get', params);\n    }\n\n    getLastValue(itemid) {\n      var params = {\n        output: ['lastvalue'],\n        itemids: itemid\n      };\n      return this.request('item.get', params)\n      .then(items => items.length ? items[0].lastvalue : null);\n    }\n\n    /**\n     * Perform history query from Zabbix API\n     *\n     * @param  {Array}  items       Array of Zabbix item objects\n     * @param  {Number} timeFrom   Time in seconds\n     * @param  {Number} timeTill   Time in seconds\n     * @return {Array}  Array of Zabbix history objects\n     */\n    getHistory(items, timeFrom, timeTill) {\n\n      // Group items by value type and perform request for each value type\n      let grouped_items = _.groupBy(items, 'value_type');\n      let promises = _.map(grouped_items, (items, value_type) => {\n        let itemids = _.map(items, 'itemid');\n        let params = {\n          output: 'extend',\n          history: value_type,\n          itemids: itemids,\n          sortfield: 'clock',\n          sortorder: 'ASC',\n          time_from: timeFrom\n        };\n\n        // Relative queries (e.g. last hour) don't include an end time\n        if (timeTill) {\n          params.time_till = timeTill;\n        }\n\n        return this.request('history.get', params);\n      });\n\n      return Promise.all(promises).then(_.flatten);\n    }\n\n    /**\n     * Perform trends query from Zabbix API\n     * Use trends api extension from ZBXNEXT-1193 patch.\n     *\n     * @param  {Array}  items       Array of Zabbix item objects\n     * @param  {Number} time_from   Time in seconds\n     * @param  {Number} time_till   Time in seconds\n     * @return {Array}  Array of Zabbix trend objects\n     */\n    getTrend_ZBXNEXT1193(items, timeFrom, timeTill) {\n\n      // Group items by value type and perform request for each value type\n      let grouped_items = _.groupBy(items, 'value_type');\n      let promises = _.map(grouped_items, (items, value_type) => {\n        let itemids = _.map(items, 'itemid');\n        let params = {\n          output: 'extend',\n          trend: value_type,\n          itemids: itemids,\n          sortfield: 'clock',\n          sortorder: 'ASC',\n          time_from: timeFrom\n        };\n\n        // Relative queries (e.g. last hour) don't include an end time\n        if (timeTill) {\n          params.time_till = timeTill;\n        }\n\n        return this.request('trend.get', params);\n      });\n\n      return Promise.all(promises).then(_.flatten);\n    }\n\n    getTrend_30(items, time_from, time_till, value_type) {\n      var self = this;\n      var itemids = _.map(items, 'itemid');\n\n      var params = {\n        output: [\"itemid\",\n          \"clock\",\n          value_type\n        ],\n        itemids: itemids,\n        time_from: time_from\n      };\n\n      // Relative queries (e.g. last hour) don't include an end time\n      if (time_till) {\n        params.time_till = time_till;\n      }\n\n      return self.request('trend.get', params);\n    }\n\n    getITService(serviceids) {\n      var params = {\n        output: 'extend',\n        serviceids: serviceids\n      };\n      return this.request('service.get', params);\n    }\n\n    getSLA(serviceids, timeRange) {\n      let [timeFrom, timeTo] = timeRange;\n      var params = {\n        serviceids: serviceids,\n        intervals: [{\n          from: timeFrom,\n          to: timeTo\n        }]\n      };\n      return this.request('service.getsla', params);\n    }\n\n    getTriggers(groupids, hostids, applicationids, options) {\n      let {showTriggers, hideHostsInMaintenance, timeFrom, timeTo} = options;\n\n      let params = {\n        output: 'extend',\n        groupids: groupids,\n        hostids: hostids,\n        applicationids: applicationids,\n        expandDescription: true,\n        expandData: true,\n        expandComment: true,\n        monitored: true,\n        skipDependent: true,\n        //only_true: true,\n        filter: {\n          value: 1\n        },\n        selectGroups: ['name'],\n        selectHosts: ['name', 'host'],\n        selectItems: ['name', 'key_', 'lastvalue'],\n        selectLastEvent: 'extend'\n      };\n\n      if (showTriggers) {\n        params.filter.value = showTriggers;\n      }\n\n      if (hideHostsInMaintenance) {\n        params.maintenance = false;\n      }\n\n      if (timeFrom || timeTo) {\n        params.lastChangeSince = timeFrom;\n        params.lastChangeTill = timeTo;\n      }\n\n      return this.request('trigger.get', params);\n    }\n\n    getEvents(objectids, timeFrom, timeTo, showEvents) {\n      var params = {\n        output: 'extend',\n        time_from: timeFrom,\n        time_till: timeTo,\n        objectids: objectids,\n        select_acknowledges: 'extend',\n        selectHosts: 'extend',\n        value: showEvents\n      };\n\n      return this.request('event.get', params);\n    }\n\n    getAcknowledges(eventids) {\n      var params = {\n        output: 'extend',\n        eventids: eventids,\n        preservekeys: true,\n        select_acknowledges: 'extend',\n        sortfield: 'clock',\n        sortorder: 'DESC'\n      };\n\n      return this.request('event.get', params)\n      .then(events => {\n        return _.filter(events, (event) => event.acknowledges.length);\n      });\n    }\n\n    getAlerts(itemids, timeFrom, timeTo) {\n      var params = {\n        output: 'extend',\n        itemids: itemids,\n        expandDescription: true,\n        expandData: true,\n        expandComment: true,\n        monitored: true,\n        skipDependent: true,\n        //only_true: true,\n        // filter: {\n        //   value: 1\n        // },\n        selectLastEvent: 'extend'\n      };\n\n      if (timeFrom || timeTo) {\n        params.lastChangeSince = timeFrom;\n        params.lastChangeTill = timeTo;\n      }\n\n      return this.request('trigger.get', params);\n    }\n\n    getHostAlerts(hostids, applicationids, minSeverity, count, timeFrom, timeTo) {\n      var params = {\n        output: 'extend',\n        hostids: hostids,\n        min_severity: minSeverity,\n        filter: { value: 1 },\n        expandDescription: true,\n        expandData: true,\n        expandComment: true,\n        monitored: true,\n        skipDependent: true,\n        selectLastEvent: 'extend'\n      };\n\n      if (count) {\n        params.countOutput = true;\n      }\n\n      if (applicationids && applicationids.length) {\n        params.applicationids = applicationids;\n      }\n\n      if (timeFrom || timeTo) {\n        params.lastChangeSince = timeFrom;\n        params.lastChangeTill = timeTo;\n      }\n\n      return this.request('trigger.get', params);\n    }\n  }\n\n  return ZabbixAPI;\n}\n\nfunction isNotAuthorized(message) {\n  return (\n    message === \"Session terminated, re-login, please.\" ||\n    message === \"Not authorised.\" ||\n    message === \"Not authorized.\"\n  );\n}\n\nangular\n  .module('grafana.services')\n  .factory('zabbixAPIService', ZabbixAPIServiceFactory);\n"]}
\ No newline at end of file
diff --git a/dist/test/datasource-zabbix/constants.js b/dist/test/datasource-zabbix/constants.js
index 1670215ba..9f2b4d089 100644
--- a/dist/test/datasource-zabbix/constants.js
+++ b/dist/test/datasource-zabbix/constants.js
@@ -8,6 +8,7 @@ var MODE_METRICS = exports.MODE_METRICS = 0;
 var MODE_ITSERVICE = exports.MODE_ITSERVICE = 1;
 var MODE_TEXT = exports.MODE_TEXT = 2;
 var MODE_ITEMID = exports.MODE_ITEMID = 3;
+var MODE_TRIGGERS = exports.MODE_TRIGGERS = 4;
 
 // Triggers severity
 var SEV_NOT_CLASSIFIED = exports.SEV_NOT_CLASSIFIED = 0;
diff --git a/dist/test/datasource-zabbix/datasource.js b/dist/test/datasource-zabbix/datasource.js
index fd6f6be84..d249b4dc7 100644
--- a/dist/test/datasource-zabbix/datasource.js
+++ b/dist/test/datasource-zabbix/datasource.js
@@ -190,6 +190,10 @@ var ZabbixAPIDatasource = function () {
         } else if (target.mode === c.MODE_ITSERVICE) {
           // IT services mode
           return _this.queryITServiceData(target, timeRange, options);
+        } else if (target.mode === c.MODE_TRIGGERS) {
+          return _this.queryTriggersData(target, timeRange);
+        } else {
+          return [];
         }
       });
 
@@ -436,6 +440,31 @@ var ZabbixAPIDatasource = function () {
         });
       });
     }
+  }, {
+    key: 'queryTriggersData',
+    value: function queryTriggersData(target, timeRange) {
+      var _this7 = this;
+
+      var _timeRange3 = _slicedToArray(timeRange, 2),
+          timeFrom = _timeRange3[0],
+          timeTo = _timeRange3[1];
+
+      return this.zabbix.getHostsFromTarget(target).then(function (results) {
+        var _results = _slicedToArray(results, 2),
+            hosts = _results[0],
+            apps = _results[1];
+
+        if (hosts.length) {
+          var hostids = _lodash2.default.map(hosts, 'hostid');
+          var appids = _lodash2.default.map(apps, 'applicationid');
+          return _this7.zabbix.getHostAlerts(hostids, appids, target.minSeverity, target.options.countTriggers, timeFrom, timeTo).then(function (triggers) {
+            return _responseHandler2.default.handleTriggersResponse(triggers, timeRange);
+          });
+        } else {
+          return Promise.resolve([]);
+        }
+      });
+    }
 
     /**
      * Test connection to Zabbix API
@@ -445,15 +474,15 @@ var ZabbixAPIDatasource = function () {
   }, {
     key: 'testDatasource',
     value: function testDatasource() {
-      var _this7 = this;
+      var _this8 = this;
 
       var zabbixVersion = void 0;
       return this.zabbix.getVersion().then(function (version) {
         zabbixVersion = version;
-        return _this7.zabbix.login();
+        return _this8.zabbix.login();
       }).then(function () {
-        if (_this7.enableDirectDBConnection) {
-          return _this7.zabbix.dbConnector.testSQLDataSource();
+        if (_this8.enableDirectDBConnection) {
+          return _this8.zabbix.dbConnector.testSQLDataSource();
         } else {
           return Promise.resolve();
         }
@@ -501,14 +530,14 @@ var ZabbixAPIDatasource = function () {
   }, {
     key: 'metricFindQuery',
     value: function metricFindQuery(query) {
-      var _this8 = this;
+      var _this9 = this;
 
       var result = void 0;
       var parts = [];
 
       // Split query. Query structure: group.host.app.item
       _lodash2.default.each(utils.splitTemplateQuery(query), function (part) {
-        part = _this8.replaceTemplateVars(part, {});
+        part = _this9.replaceTemplateVars(part, {});
 
         // Replace wildcard to regex
         if (part === '*') {
@@ -550,7 +579,7 @@ var ZabbixAPIDatasource = function () {
   }, {
     key: 'annotationQuery',
     value: function annotationQuery(options) {
-      var _this9 = this;
+      var _this10 = this;
 
       var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);
       var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);
@@ -568,7 +597,7 @@ var ZabbixAPIDatasource = function () {
       return getTriggers.then(function (triggers) {
 
         // Filter triggers by description
-        var triggerName = _this9.replaceTemplateVars(annotation.trigger, {});
+        var triggerName = _this10.replaceTemplateVars(annotation.trigger, {});
         if (utils.isRegex(triggerName)) {
           triggers = _lodash2.default.filter(triggers, function (trigger) {
             return utils.buildRegex(triggerName).test(trigger.description);
@@ -585,7 +614,7 @@ var ZabbixAPIDatasource = function () {
         });
 
         var objectids = _lodash2.default.map(triggers, 'triggerid');
-        return _this9.zabbix.getEvents(objectids, timeFrom, timeTo, showOkEvents).then(function (events) {
+        return _this10.zabbix.getEvents(objectids, timeFrom, timeTo, showOkEvents).then(function (events) {
           var indexedTriggers = _lodash2.default.keyBy(triggers, 'triggerid');
 
           // Hide acknowledged events if option enabled
@@ -626,23 +655,23 @@ var ZabbixAPIDatasource = function () {
   }, {
     key: 'alertQuery',
     value: function alertQuery(options) {
-      var _this10 = this;
+      var _this11 = this;
 
       var enabled_targets = filterEnabledTargets(options.targets);
       var getPanelItems = _lodash2.default.map(enabled_targets, function (t) {
         var target = _lodash2.default.cloneDeep(t);
-        _this10.replaceTargetVariables(target, options);
-        return _this10.zabbix.getItemsFromTarget(target, { itemtype: 'num' });
+        _this11.replaceTargetVariables(target, options);
+        return _this11.zabbix.getItemsFromTarget(target, { itemtype: 'num' });
       });
 
       return Promise.all(getPanelItems).then(function (results) {
         var items = _lodash2.default.flatten(results);
         var itemids = _lodash2.default.map(items, 'itemid');
 
-        return _this10.zabbix.getAlerts(itemids);
+        return _this11.zabbix.getAlerts(itemids);
       }).then(function (triggers) {
         triggers = _lodash2.default.filter(triggers, function (trigger) {
-          return trigger.priority >= _this10.alertingMinSeverity;
+          return trigger.priority >= _this11.alertingMinSeverity;
         });
 
         if (!triggers || triggers.length === 0) {
@@ -673,12 +702,12 @@ var ZabbixAPIDatasource = function () {
   }, {
     key: 'replaceTargetVariables',
     value: function replaceTargetVariables(target, options) {
-      var _this11 = this;
+      var _this12 = this;
 
       var parts = ['group', 'host', 'application', 'item'];
       _lodash2.default.forEach(parts, function (p) {
         if (target[p] && target[p].filter) {
-          target[p].filter = _this11.replaceTemplateVars(target[p].filter, options.scopedVars);
+          target[p].filter = _this12.replaceTemplateVars(target[p].filter, options.scopedVars);
         }
       });
       target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);
@@ -686,9 +715,9 @@ var ZabbixAPIDatasource = function () {
       _lodash2.default.forEach(target.functions, function (func) {
         func.params = _lodash2.default.map(func.params, function (param) {
           if (typeof param === 'number') {
-            return +_this11.templateSrv.replace(param.toString(), options.scopedVars);
+            return +_this12.templateSrv.replace(param.toString(), options.scopedVars);
           } else {
-            return _this11.templateSrv.replace(param, options.scopedVars);
+            return _this12.templateSrv.replace(param, options.scopedVars);
           }
         });
       });
@@ -696,9 +725,9 @@ var ZabbixAPIDatasource = function () {
   }, {
     key: 'isUseTrends',
     value: function isUseTrends(timeRange) {
-      var _timeRange3 = _slicedToArray(timeRange, 2),
-          timeFrom = _timeRange3[0],
-          timeTo = _timeRange3[1];
+      var _timeRange4 = _slicedToArray(timeRange, 2),
+          timeFrom = _timeRange4[0],
+          timeTo = _timeRange4[1];
 
       var useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);
       var useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);
diff --git a/dist/test/datasource-zabbix/query.controller.js b/dist/test/datasource-zabbix/query.controller.js
index a0e9914b8..e9214c1ed 100644
--- a/dist/test/datasource-zabbix/query.controller.js
+++ b/dist/test/datasource-zabbix/query.controller.js
@@ -60,17 +60,20 @@ var ZabbixQueryController = exports.ZabbixQueryController = function (_QueryCtrl
     _this.replaceTemplateVars = _this.datasource.replaceTemplateVars;
     _this.templateSrv = templateSrv;
 
-    _this.editorModes = [{ value: 'num', text: 'Metrics', mode: c.MODE_METRICS }, { value: 'text', text: 'Text', mode: c.MODE_TEXT }, { value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE }, { value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID }];
+    _this.editorModes = [{ value: 'num', text: 'Metrics', mode: c.MODE_METRICS }, { value: 'text', text: 'Text', mode: c.MODE_TEXT }, { value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE }, { value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID }, { value: 'triggers', text: 'Triggers', mode: c.MODE_TRIGGERS }];
 
     _this.$scope.editorMode = {
       METRICS: c.MODE_METRICS,
       TEXT: c.MODE_TEXT,
       ITSERVICE: c.MODE_ITSERVICE,
-      ITEMID: c.MODE_ITEMID
+      ITEMID: c.MODE_ITEMID,
+      TRIGGERS: c.MODE_TRIGGERS
     };
 
     _this.slaPropertyList = [{ name: "Status", property: "status" }, { name: "SLA", property: "sla" }, { name: "OK time", property: "okTime" }, { name: "Problem time", property: "problemTime" }, { name: "Down time", property: "downtimeTime" }];
 
+    _this.triggerSeverity = [{ val: 0, text: 'Not classified' }, { val: 1, text: 'Information' }, { val: 2, text: 'Warning' }, { val: 3, text: 'Average' }, { val: 4, text: 'High' }, { val: 5, text: 'Disaster' }];
+
     // Map functions for bs-typeahead
     _this.getGroupNames = _lodash2.default.bind(_this.getMetricNames, _this, 'groupList');
     _this.getHostNames = _lodash2.default.bind(_this.getMetricNames, _this, 'hostList', true);
@@ -110,8 +113,10 @@ var ZabbixQueryController = exports.ZabbixQueryController = function (_QueryCtrl
         'application': { 'filter': "" },
         'item': { 'filter': "" },
         'functions': [],
+        'minSeverity': 3,
         'options': {
-          'showDisabledItems': false
+          'showDisabledItems': false,
+          'countTriggers': true
         }
       };
       _lodash2.default.defaults(target, targetDefaults);
@@ -121,8 +126,7 @@ var ZabbixQueryController = exports.ZabbixQueryController = function (_QueryCtrl
         return metricFunctions.createFuncInstance(func.def, func.params);
       });
 
-      if (target.mode === c.MODE_METRICS || target.mode === c.MODE_TEXT) {
-
+      if (target.mode === c.MODE_METRICS || target.mode === c.MODE_TEXT || target.mode === c.MODE_TRIGGERS) {
         this.initFilters();
       } else if (target.mode === c.MODE_ITSERVICE) {
         _lodash2.default.defaults(target, { slaProperty: { name: "SLA", property: "sla" } });
@@ -131,6 +135,7 @@ var ZabbixQueryController = exports.ZabbixQueryController = function (_QueryCtrl
     };
 
     _this.init();
+    _this.queryOptionsText = _this.renderQueryOptionsText();
     return _this;
   }
 
@@ -340,7 +345,8 @@ var ZabbixQueryController = exports.ZabbixQueryController = function (_QueryCtrl
     key: 'renderQueryOptionsText',
     value: function renderQueryOptionsText() {
       var optionsMap = {
-        showDisabledItems: "Show disabled items"
+        showDisabledItems: "Show disabled items",
+        countTriggers: "Count Triggers"
       };
       var options = [];
       _lodash2.default.forOwn(this.target.options, function (value, key) {
diff --git a/dist/test/datasource-zabbix/responseHandler.js b/dist/test/datasource-zabbix/responseHandler.js
index 3f0b2b198..88ed899ab 100644
--- a/dist/test/datasource-zabbix/responseHandler.js
+++ b/dist/test/datasource-zabbix/responseHandler.js
@@ -109,6 +109,17 @@ function handleSLAResponse(itservice, slaProperty, slaObject) {
   }
 }
 
+function handleTriggersResponse(triggers, timeRange) {
+  if (_lodash2.default.isNumber(triggers)) {
+    return {
+      target: "triggers count",
+      datapoints: [[triggers, timeRange[1]]]
+    };
+  } else {
+    return triggers;
+  }
+}
+
 function convertHistoryPoint(point) {
   // Value must be a number for properly work
   return [Number(point.value), point.clock * 1000 + Math.round(point.ns / 1000000)];
@@ -144,7 +155,8 @@ exports.default = {
   convertHistory: convertHistory,
   handleTrends: handleTrends,
   handleText: handleText,
-  handleSLAResponse: handleSLAResponse
+  handleSLAResponse: handleSLAResponse,
+  handleTriggersResponse: handleTriggersResponse
 };
 
 // Fix for backward compatibility with lodash 2.4
diff --git a/dist/test/datasource-zabbix/zabbix.js b/dist/test/datasource-zabbix/zabbix.js
index 6335b9280..e90c74506 100644
--- a/dist/test/datasource-zabbix/zabbix.js
+++ b/dist/test/datasource-zabbix/zabbix.js
@@ -1,5 +1,7 @@
 'use strict';
 
+var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
+
 var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
 var _angular = require('angular');
@@ -74,6 +76,7 @@ function ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector)
       this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);
       this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);
       this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI);
+      this.getHostAlerts = this.zabbixAPI.getHostAlerts.bind(this.zabbixAPI);
       this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);
       this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);
       this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);
@@ -90,6 +93,24 @@ function ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector)
         });
         return this.getItems.apply(this, _toConsumableArray(filters).concat([options]));
       }
+    }, {
+      key: 'getHostsFromTarget',
+      value: function getHostsFromTarget(target) {
+        var parts = ['group', 'host', 'application'];
+        var filters = _lodash2.default.map(parts, function (p) {
+          return target[p].filter;
+        });
+        return Promise.all([this.getHosts.apply(this, _toConsumableArray(filters)), this.getApps.apply(this, _toConsumableArray(filters))]).then(function (results) {
+          var _results = _slicedToArray(results, 2),
+              hosts = _results[0],
+              apps = _results[1];
+
+          if (apps.appFilterEmpty) {
+            apps = [];
+          }
+          return [hosts, apps];
+        });
+      }
     }, {
       key: 'getAllGroups',
       value: function getAllGroups() {
diff --git a/dist/test/datasource-zabbix/zabbixAPI.service.js b/dist/test/datasource-zabbix/zabbixAPI.service.js
index 05865786e..288e38372 100644
--- a/dist/test/datasource-zabbix/zabbixAPI.service.js
+++ b/dist/test/datasource-zabbix/zabbixAPI.service.js
@@ -483,6 +483,37 @@ function ZabbixAPIServiceFactory(alertSrv, zabbixAPICoreService) {
           params.lastChangeTill = timeTo;
         }
 
+        return this.request('trigger.get', params);
+      }
+    }, {
+      key: 'getHostAlerts',
+      value: function getHostAlerts(hostids, applicationids, minSeverity, count, timeFrom, timeTo) {
+        var params = {
+          output: 'extend',
+          hostids: hostids,
+          min_severity: minSeverity,
+          filter: { value: 1 },
+          expandDescription: true,
+          expandData: true,
+          expandComment: true,
+          monitored: true,
+          skipDependent: true,
+          selectLastEvent: 'extend'
+        };
+
+        if (count) {
+          params.countOutput = true;
+        }
+
+        if (applicationids && applicationids.length) {
+          params.applicationids = applicationids;
+        }
+
+        if (timeFrom || timeTo) {
+          params.lastChangeSince = timeFrom;
+          params.lastChangeTill = timeTo;
+        }
+
         return this.request('trigger.get', params);
       }
     }]);
diff --git a/src/datasource-zabbix/constants.js b/src/datasource-zabbix/constants.js
index 4d76ab6fd..a1fcf8d20 100644
--- a/src/datasource-zabbix/constants.js
+++ b/src/datasource-zabbix/constants.js
@@ -3,6 +3,7 @@ export const MODE_METRICS = 0;
 export const MODE_ITSERVICE = 1;
 export const MODE_TEXT = 2;
 export const MODE_ITEMID = 3;
+export const MODE_TRIGGERS = 4;
 
 // Triggers severity
 export const SEV_NOT_CLASSIFIED = 0;
diff --git a/src/datasource-zabbix/datasource.js b/src/datasource-zabbix/datasource.js
index a156d9b3e..f46d5d2a3 100644
--- a/src/datasource-zabbix/datasource.js
+++ b/src/datasource-zabbix/datasource.js
@@ -136,6 +136,10 @@ class ZabbixAPIDatasource {
       } else if (target.mode === c.MODE_ITSERVICE) {
         // IT services mode
         return this.queryITServiceData(target, timeRange, options);
+      } else if (target.mode === c.MODE_TRIGGERS) {
+        return this.queryTriggersData(target, timeRange);
+      } else {
+        return [];
       }
     });
 
@@ -350,6 +354,24 @@ class ZabbixAPIDatasource {
     });
   }
 
+  queryTriggersData(target, timeRange) {
+    let [timeFrom, timeTo] = timeRange;
+    return this.zabbix.getHostsFromTarget(target)
+    .then((results) => {
+      let [hosts, apps] = results;
+      if (hosts.length) {
+        let hostids = _.map(hosts, 'hostid');
+        let appids = _.map(apps, 'applicationid');
+        return this.zabbix.getHostAlerts(hostids, appids, target.minSeverity, target.options.countTriggers, timeFrom, timeTo)
+        .then((triggers) => {
+          return responseHandler.handleTriggersResponse(triggers, timeRange);
+        });
+      } else {
+        return Promise.resolve([]);
+      }
+    });
+  }
+
   /**
    * Test connection to Zabbix API
    * @return {object} Connection status and Zabbix API version
diff --git a/src/datasource-zabbix/partials/query.editor.html b/src/datasource-zabbix/partials/query.editor.html
index f5831025e..3c69c3df4 100644
--- a/src/datasource-zabbix/partials/query.editor.html
+++ b/src/datasource-zabbix/partials/query.editor.html
@@ -48,7 +48,7 @@
     </div>
   </div>
 
-  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT">
+  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT || ctrl.target.mode == editorMode.TRIGGERS">
     <!-- Select Group -->
     <div class="gf-form max-width-20">
       <label class="gf-form-label query-keyword width-7">Group</label>
@@ -66,7 +66,7 @@
     </div>
     <!-- Select Host -->
     <div class="gf-form">
-      <label class="gf-form-label query-keyword width-7">Host</label>
+      <label class="gf-form-label query-keyword width-8">Host</label>
       <input type="text"
         ng-model="ctrl.target.host.filter"
         bs-typeahead="ctrl.getHostNames"
@@ -85,7 +85,7 @@
     </div>
   </div>
 
-  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT">
+  <div class="gf-form-inline" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT || ctrl.target.mode == editorMode.TRIGGERS">
     <!-- Select Application -->
     <div class="gf-form max-width-20">
       <label class="gf-form-label query-keyword width-7">Application</label>
@@ -103,8 +103,8 @@
     </div>
 
     <!-- Select Item -->
-    <div class="gf-form">
-      <label class="gf-form-label query-keyword width-7">Item</label>
+    <div class="gf-form" ng-show="ctrl.target.mode == editorMode.METRICS || ctrl.target.mode == editorMode.TEXT">
+      <label class="gf-form-label query-keyword width-8">Item</label>
       <input type="text"
         ng-model="ctrl.target.item.filter"
         bs-typeahead="ctrl.getItemNames"
@@ -117,6 +117,18 @@
           'zbx-regex': ctrl.isRegex(ctrl.target.item.filter)
         }">
     </div>
+
+    <div class="gf-form max-width-20" ng-show="ctrl.target.mode == editorMode.TRIGGERS">
+      <label class="gf-form-label query-keyword width-8">Min Severity</label>
+      <div class="gf-form-select-wrapper width-20">
+        <select class="gf-form-input"
+              ng-change="ctrl.onTargetBlur()"
+              ng-model="ctrl.target.minSeverity"
+              ng-options="s.val as s.text for s in ctrl.triggerSeverity">
+        </select>
+      </div>
+    </div>
+
     <div class="gf-form gf-form--grow">
       <label class="gf-form-label gf-form-label--grow">
         <a ng-click="ctrl.toggleQueryOptions()">
@@ -130,13 +142,20 @@
 
   <!-- Query options -->
   <div class="gf-form-group" ng-if="ctrl.showQueryOptions">
-    <div class="gf-form offset-width-7">
+    <div class="gf-form offset-width-7" ng-hide="ctrl.target.mode == editorMode.TRIGGERS">
       <gf-form-switch class="gf-form"
         label="Show disabled items"
         checked="ctrl.target.options.showDisabledItems"
         on-change="ctrl.onQueryOptionChange()">
       </gf-form-switch>
     </div>
+    <div class="gf-form offset-width-7" ng-show="ctrl.target.mode == editorMode.TRIGGERS">
+      <gf-form-switch class="gf-form"
+        label="Count triggers"
+        checked="ctrl.target.options.countTriggers"
+        on-change="ctrl.onQueryOptionChange()">
+      </gf-form-switch>
+    </div>
   </div>
 
   <!-- Item IDs editor mode -->
diff --git a/src/datasource-zabbix/query.controller.js b/src/datasource-zabbix/query.controller.js
index 1330f4f1b..90e9a9a14 100644
--- a/src/datasource-zabbix/query.controller.js
+++ b/src/datasource-zabbix/query.controller.js
@@ -25,14 +25,16 @@ export class ZabbixQueryController extends QueryCtrl {
       {value: 'num',       text: 'Metrics',     mode: c.MODE_METRICS},
       {value: 'text',      text: 'Text',        mode: c.MODE_TEXT},
       {value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE},
-      {value: 'itemid',    text: 'Item ID',     mode: c.MODE_ITEMID}
+      {value: 'itemid',    text: 'Item ID',     mode: c.MODE_ITEMID},
+      {value: 'triggers',  text: 'Triggers',    mode: c.MODE_TRIGGERS}
     ];
 
     this.$scope.editorMode = {
       METRICS: c.MODE_METRICS,
       TEXT: c.MODE_TEXT,
       ITSERVICE: c.MODE_ITSERVICE,
-      ITEMID: c.MODE_ITEMID
+      ITEMID: c.MODE_ITEMID,
+      TRIGGERS: c.MODE_TRIGGERS
     };
 
     this.slaPropertyList = [
@@ -43,6 +45,12 @@ export class ZabbixQueryController extends QueryCtrl {
       {name: "Down time", property: "downtimeTime"}
     ];
 
+    this.triggerSeverity = [
+      {val: 0, text: 'Not classified'}, {val: 1, text:'Information'},
+      {val: 2, text: 'Warning'}, {val: 3, text: 'Average'},
+      {val: 4, text: 'High'}, {val: 5, text: 'Disaster'}
+    ];
+
     // Map functions for bs-typeahead
     this.getGroupNames = _.bind(this.getMetricNames, this, 'groupList');
     this.getHostNames = _.bind(this.getMetricNames, this, 'hostList', true);
@@ -80,8 +88,10 @@ export class ZabbixQueryController extends QueryCtrl {
         'application': { 'filter': "" },
         'item': { 'filter': "" },
         'functions': [],
+        'minSeverity': 3,
         'options': {
-          'showDisabledItems': false
+          'showDisabledItems': false,
+          'countTriggers': true
         }
       };
       _.defaults(target, targetDefaults);
@@ -92,8 +102,8 @@ export class ZabbixQueryController extends QueryCtrl {
       });
 
       if (target.mode === c.MODE_METRICS ||
-          target.mode === c.MODE_TEXT) {
-
+          target.mode === c.MODE_TEXT ||
+          target.mode === c.MODE_TRIGGERS) {
         this.initFilters();
       }
       else if (target.mode === c.MODE_ITSERVICE) {
@@ -103,6 +113,7 @@ export class ZabbixQueryController extends QueryCtrl {
     };
 
     this.init();
+    this.queryOptionsText = this.renderQueryOptionsText();
   }
 
   initFilters() {
@@ -282,7 +293,8 @@ export class ZabbixQueryController extends QueryCtrl {
 
   renderQueryOptionsText() {
     var optionsMap = {
-      showDisabledItems: "Show disabled items"
+      showDisabledItems: "Show disabled items",
+      countTriggers: "Count Triggers"
     };
     var options = [];
     _.forOwn(this.target.options, (value, key) => {
diff --git a/src/datasource-zabbix/responseHandler.js b/src/datasource-zabbix/responseHandler.js
index 6a61118dd..25f83f0a6 100644
--- a/src/datasource-zabbix/responseHandler.js
+++ b/src/datasource-zabbix/responseHandler.js
@@ -100,6 +100,19 @@ function handleSLAResponse(itservice, slaProperty, slaObject) {
   }
 }
 
+function handleTriggersResponse(triggers, timeRange) {
+  if (_.isNumber(triggers)) {
+    return {
+      target: "triggers count",
+      datapoints: [
+        [triggers, timeRange[1]]
+      ]
+    };
+  } else {
+    return triggers;
+  }
+}
+
 function convertHistoryPoint(point) {
   // Value must be a number for properly work
   return [
@@ -141,7 +154,8 @@ export default {
   convertHistory: convertHistory,
   handleTrends: handleTrends,
   handleText: handleText,
-  handleSLAResponse: handleSLAResponse
+  handleSLAResponse: handleSLAResponse,
+  handleTriggersResponse: handleTriggersResponse
 };
 
 // Fix for backward compatibility with lodash 2.4
diff --git a/src/datasource-zabbix/zabbix.js b/src/datasource-zabbix/zabbix.js
index f5dd71420..694a5d85b 100644
--- a/src/datasource-zabbix/zabbix.js
+++ b/src/datasource-zabbix/zabbix.js
@@ -46,6 +46,7 @@ function ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector)
       this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);
       this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);
       this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI);
+      this.getHostAlerts = this.zabbixAPI.getHostAlerts.bind(this.zabbixAPI);
       this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);
       this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);
       this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);
@@ -59,6 +60,21 @@ function ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector)
       return this.getItems(...filters, options);
     }
 
+    getHostsFromTarget(target) {
+      let parts = ['group', 'host', 'application'];
+      let filters = _.map(parts, p => target[p].filter);
+      return Promise.all([
+        this.getHosts(...filters),
+        this.getApps(...filters),
+      ]).then((results) => {
+        let [hosts, apps] = results;
+        if (apps.appFilterEmpty) {
+          apps = [];
+        }
+        return [hosts, apps];
+      });
+    }
+
     getAllGroups() {
       return this.cachingProxy.getGroups();
     }
diff --git a/src/datasource-zabbix/zabbixAPI.service.js b/src/datasource-zabbix/zabbixAPI.service.js
index bd1b40e0a..74b145f6c 100644
--- a/src/datasource-zabbix/zabbixAPI.service.js
+++ b/src/datasource-zabbix/zabbixAPI.service.js
@@ -433,6 +433,36 @@ function ZabbixAPIServiceFactory(alertSrv, zabbixAPICoreService) {
 
       return this.request('trigger.get', params);
     }
+
+    getHostAlerts(hostids, applicationids, minSeverity, count, timeFrom, timeTo) {
+      var params = {
+        output: 'extend',
+        hostids: hostids,
+        min_severity: minSeverity,
+        filter: { value: 1 },
+        expandDescription: true,
+        expandData: true,
+        expandComment: true,
+        monitored: true,
+        skipDependent: true,
+        selectLastEvent: 'extend'
+      };
+
+      if (count) {
+        params.countOutput = true;
+      }
+
+      if (applicationids && applicationids.length) {
+        params.applicationids = applicationids;
+      }
+
+      if (timeFrom || timeTo) {
+        params.lastChangeSince = timeFrom;
+        params.lastChangeTill = timeTo;
+      }
+
+      return this.request('trigger.get', params);
+    }
   }
 
   return ZabbixAPI;