Merge remote-tracking branch 'upstream/master' into threshold_regex

# Conflicts:
#	dist/datasource-zabbix/datasource.js
#	dist/datasource-zabbix/datasource.js.map
#	dist/datasource-zabbix/specs/test-main.js
#	dist/test/datasource-zabbix/datasource.js
#	dist/test/datasource-zabbix/specs/test-main.js
This commit is contained in:
akotynski
2017-10-23 14:26:46 +02:00
48 changed files with 1835 additions and 649 deletions

View File

@@ -1,4 +1,4 @@
"use strict";
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
@@ -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;
@@ -24,3 +25,5 @@ var SHOW_OK_EVENTS = exports.SHOW_OK_EVENTS = 1;
// Data point
var DATAPOINT_VALUE = exports.DATAPOINT_VALUE = 0;
var DATAPOINT_TS = exports.DATAPOINT_TS = 1;
var TRIGGER_SEVERITY = exports.TRIGGER_SEVERITY = [{ 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' }];

View File

@@ -73,26 +73,28 @@ var ZabbixAPIDatasource = function () {
this.basicAuth = instanceSettings.basicAuth;
this.withCredentials = instanceSettings.withCredentials;
var jsonData = instanceSettings.jsonData;
// Zabbix API credentials
this.username = instanceSettings.jsonData.username;
this.password = instanceSettings.jsonData.password;
this.username = jsonData.username;
this.password = jsonData.password;
// Use trends instead history since specified time
this.trends = instanceSettings.jsonData.trends;
this.trendsFrom = instanceSettings.jsonData.trendsFrom || '7d';
this.trendsRange = instanceSettings.jsonData.trendsRange || '4d';
this.trends = jsonData.trends;
this.trendsFrom = jsonData.trendsFrom || '7d';
this.trendsRange = jsonData.trendsRange || '4d';
// Set cache update interval
var ttl = instanceSettings.jsonData.cacheTTL || '1h';
var ttl = jsonData.cacheTTL || '1h';
this.cacheTTL = utils.parseInterval(ttl);
// Alerting options
this.alertingEnabled = instanceSettings.jsonData.alerting;
this.addThresholds = instanceSettings.jsonData.addThresholds;
this.alertingMinSeverity = instanceSettings.jsonData.alertingMinSeverity || c.SEV_WARNING;
this.alertingEnabled = jsonData.alerting;
this.addThresholds = jsonData.addThresholds;
this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;
// Direct DB Connection options
var dbConnectionOptions = instanceSettings.jsonData.dbConnection || {};
var dbConnectionOptions = jsonData.dbConnection || {};
this.enableDirectDBConnection = dbConnectionOptions.enable;
this.sqlDatasourceId = dbConnectionOptions.datasourceId;
@@ -188,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 [];
}
});
@@ -434,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.countTriggers, timeFrom, timeTo).then(function (triggers) {
return _responseHandler2.default.handleTriggersResponse(triggers, timeRange);
});
} else {
return Promise.resolve([]);
}
});
}
/**
* Test connection to Zabbix API
@@ -443,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();
}
@@ -466,13 +497,13 @@ var ZabbixAPIDatasource = function () {
return {
status: "error",
title: error.message,
message: error.data
message: error.message
};
} else if (error.data && error.data.message) {
return {
status: "error",
title: "Connection failed",
message: error.data.message
message: "Connection failed: " + error.data.message
};
} else {
return {
@@ -499,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 === '*') {
@@ -548,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);
@@ -566,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);
@@ -583,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
@@ -624,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) {
@@ -671,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);
@@ -684,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);
}
});
});
@@ -694,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);
@@ -809,7 +840,7 @@ function filterEnabledTargets(targets) {
}
function getTriggerThreshold(expression) {
var thresholdPattern = /.*[<>=]{1,2}([\d\.]+)/;
var thresholdPattern = /.*[<>]([\d\.]+)/;
var finded_thresholds = expression.match(thresholdPattern);
if (finded_thresholds && finded_thresholds.length >= 2) {
var threshold = finded_thresholds[1];

View File

@@ -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 = c.TRIGGER_SEVERITY;
// 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,6 +113,8 @@ var ZabbixQueryController = exports.ZabbixQueryController = function (_QueryCtrl
'application': { 'filter': "" },
'item': { 'filter': "" },
'functions': [],
'minSeverity': 3,
'countTriggers': true,
'options': {
'showDisabledItems': false
}
@@ -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;
}

View File

@@ -8,8 +8,20 @@ var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _table_model = require('app/core/table_model');
var _table_model2 = _interopRequireDefault(_table_model);
var _constants = require('./constants');
var c = _interopRequireWildcard(_constants);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/**
* Convert Zabbix API history.get response to Grafana format
*
@@ -109,6 +121,49 @@ function handleSLAResponse(itservice, slaProperty, slaObject) {
}
}
function handleTriggersResponse(triggers, timeRange) {
if (_lodash2.default.isNumber(triggers)) {
return {
target: "triggers count",
datapoints: [[triggers, timeRange[1] * 1000]]
};
} else {
var stats = getTriggerStats(triggers);
var table = new _table_model2.default();
table.addColumn({ text: 'Host group' });
_lodash2.default.each(_lodash2.default.orderBy(c.TRIGGER_SEVERITY, ['val'], ['desc']), function (severity) {
table.addColumn({ text: severity.text });
});
_lodash2.default.each(stats, function (severity_stats, group) {
var row = _lodash2.default.map(_lodash2.default.orderBy(_lodash2.default.toPairs(severity_stats), function (s) {
return s[0];
}, ['desc']), function (s) {
return s[1];
});
row = _lodash2.default.concat.apply(_lodash2.default, [[group]].concat(_toConsumableArray(row)));
table.rows.push(row);
});
return table;
}
}
function getTriggerStats(triggers) {
var groups = _lodash2.default.uniq(_lodash2.default.flattenDeep(_lodash2.default.map(triggers, function (trigger) {
return _lodash2.default.map(trigger.groups, 'name');
})));
// let severity = _.map(c.TRIGGER_SEVERITY, 'text');
var stats = {};
_lodash2.default.each(groups, function (group) {
stats[group] = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }; // severity:count
});
_lodash2.default.each(triggers, function (trigger) {
_lodash2.default.each(trigger.groups, function (group) {
stats[group.name][trigger.priority]++;
});
});
return stats;
}
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 +199,8 @@ exports.default = {
convertHistory: convertHistory,
handleTrends: handleTrends,
handleText: handleText,
handleSLAResponse: handleSLAResponse
handleSLAResponse: handleSLAResponse,
handleTriggersResponse: handleTriggersResponse
};
// Fix for backward compatibility with lodash 2.4

View File

@@ -49,14 +49,15 @@ _prunk2.default.mock('app/plugins/sdk', {
QueryCtrl: null
});
_prunk2.default.mock('app/core/utils/datemath', datemathMock);
_prunk2.default.mock('app/core/table_model', {});
_prunk2.default.mock('angular', angularMocks);
_prunk2.default.mock('jquery', 'module not found');
// Required for loading angularjs
var dom = new _jsdom.JSDOM('<html><head><script></script></head><body></body></html>');
// Setup jsdom
global.window = dom.window;
global.document = global.window.document;
// Required for loading angularjs
global.document = (0, _jsdom.jsdom)('<html><head><script></script></head><body></body></html>');
global.window = global.document.parentWindow;
global.navigator = window.navigator = {};
global.Node = window.Node;
// Setup Chai

View File

@@ -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() {

View File

@@ -483,6 +483,39 @@ 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',
selectGroups: 'extend',
selectHosts: ['host', 'name']
};
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);
}
}]);

View File

@@ -83,8 +83,6 @@ var ZabbixAPICoreService = function () {
// Success
return response.data.result;
}).catch(function () {
return Promise.reject(new ZabbixAPIError({ data: "Connection Error" }));
});
}
@@ -125,16 +123,16 @@ var ZabbixAPIError = exports.ZabbixAPIError = function () {
function ZabbixAPIError(error) {
_classCallCheck(this, ZabbixAPIError);
this.code = error.code;
this.name = error.data;
this.message = error.data;
this.data = error.data;
this.code = error.code || null;
this.name = error.message || "";
this.data = error.data || "";
this.message = "Zabbix API Error: " + this.name + " " + this.data;
}
_createClass(ZabbixAPIError, [{
key: 'toString',
value: function toString() {
return this.name + ": " + this.message;
return this.name + " " + this.data;
}
}]);