diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..4242942 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,15 @@ +## How to contribute to Grafana-Zabbix + +#### **Did you find a bug?** + +* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/alexanderzobnin/grafana-zabbix/issues). + +* If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/alexanderzobnin/grafana-zabbix/issues/new). Be sure to include a **title and clear description**, as much relevant information as possible. + +#### **Did you write a patch that fixes a bug?** + +* Open a new GitHub pull request with the patch. + +* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. + +Thanks! :heart: :heart: :heart: diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..1e848bf --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,17 @@ +#### I'm submitting a ... +- [ ] Bug report +- [ ] Feature request +- [ ] Question / Support request + +#### For bug report please include this information: +- What Grafana version are you using? +- What Zabbix version are you using? +- What zabbix plugin version are you using? +- What OS are you running grafana on? +- What did you do? +- What was the expected result? +- What happened instead? + +**IMPORTANT** If it relates to metric data visualization would be great to get: +- An image or text representation of your metric query +- The raw query and response for the network request (check this in chrome dev tools network tab, here you can see metric requests and other request, please include the request body and request response) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index be343e6..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -# Contributing to Grafana-Zabbix \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js index 7c5c08d..025733b 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -98,6 +98,29 @@ module.exports = function(grunt) { 'dist/panel-triggers/css/panel_triggers.css' : 'src/panel-triggers/sass/panel_triggers.scss', } } + }, + + jshint: { + source: { + files: { + src: ['src/**/*.js'], + } + }, + options: { + jshintrc: true, + reporter: require('jshint-stylish'), + ignores: [ + 'node_modules/*', + 'dist/*', + ] + } + }, + + jscs: { + src: ['src/**/*.js'], + options: { + config: ".jscs.json", + }, } }); @@ -106,8 +129,10 @@ module.exports = function(grunt) { 'clean', 'copy:src_to_dist', 'copy:pluginDef', - 'babel', + 'jshint', + 'jscs', 'sass', + 'babel', 'mochaTest' ]); }; diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d7b33b6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015-2016 Alexander Zobnin + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index ee0bee2..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015-2016 Alexander Zobnin - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/docs/sources/index.md b/docs/sources/index.md index bd9ed6b..0ace143 100644 --- a/docs/sources/index.md +++ b/docs/sources/index.md @@ -22,7 +22,7 @@ a number of ways to get help: - [Gitter room](https://gitter.im/alexanderzobnin/grafana-zabbix) - [Twitter](https://twitter.com/AlexanderZobnin) -Or you can just send me [email](mailto:alexanderzobnin@gmail.com). +Or you can send me [email](mailto:alexanderzobnin@gmail.com). ## Support Project I develop this project in my free time, but if you really find it helpful and promising, you can @@ -34,5 +34,5 @@ Triggers panel was sponsored by [Core IT Project](http://coreit.fr/)). By utilizing this software, you agree to the terms of the included license. Grafana-Zabbix plugin is licensed under the Apache 2.0 agreement. See -[LICENSE](https://github.com/alexanderzobnin/grafana-zabbix/blob/master/LICENSE.md) for the full +[LICENSE](https://github.com/alexanderzobnin/grafana-zabbix/blob/master/LICENSE) for the full license terms. diff --git a/docs/sources/reference/functions.md b/docs/sources/reference/functions.md index 089edac..c620ca7 100644 --- a/docs/sources/reference/functions.md +++ b/docs/sources/reference/functions.md @@ -30,6 +30,13 @@ scale(100) scale(0.01) ``` +### delta +``` +delta() +``` +Convert absolute values to delta, for example, bits to bits/sec. + + Aggregate --------- @@ -71,6 +78,38 @@ max(interval) ``` **Deprecated**, use `aggregateBy(interval, max)` instead. + +Filter +--------- + +### top + +``` +top(N, value) +``` + +Returns top N series, sorted by _value_, which can be one of: _avg_, _min_, _max_, _median_. + +Examples: +``` +top(10, avg) +top(5, max) +``` + +### bottom + +``` +bottom(N, value) +``` + +Returns bottom N series, sorted by _value_, which can be one of: _avg_, _min_, _max_, _median_. + +Examples: +``` +bottom(5, avg) +``` + + ## Trends ### trendValue diff --git a/package.json b/package.json index 67de01a..5d305bb 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,10 @@ "babel-plugin-transform-es2015-modules-systemjs": "^6.5.0", "babel-plugin-transform-es2015-for-of": "^6.6.0", "babel-preset-es2015": "^6.5.0", - "lodash": "^2.4.1", + "grunt-contrib-jshint": "^1.0.0", + "grunt-jscs": "^2.8.0", + "jshint-stylish": "^2.1.0", + "lodash": "~4.0.0", "mocha": "^2.4.5", "sinon": "~1.16.1" }, diff --git a/src/datasource-zabbix/DataProcessor.js b/src/datasource-zabbix/DataProcessor.js index 0dad30d..cb6c4c2 100644 --- a/src/datasource-zabbix/DataProcessor.js +++ b/src/datasource-zabbix/DataProcessor.js @@ -116,6 +116,22 @@ export default class DataProcessor { return sortByTime(new_timeseries); } + static limit(order, n, orderByFunc, timeseries) { + let orderByCallback = DataProcessor.aggregationFunctions[orderByFunc]; + let sortByIteratee = (ts) => { + let values = _.map(ts.datapoints, (point) => { + return point[0]; + }); + return orderByCallback(values); + }; + let sortedTimeseries = _.sortBy(timeseries, sortByIteratee); + if (order === 'bottom') { + return sortedTimeseries.slice(0, n); + } else { + return sortedTimeseries.slice(-n); + } + } + static AVERAGE(values) { var sum = 0; _.each(values, function(value) { @@ -151,6 +167,16 @@ export default class DataProcessor { }); } + static delta(datapoints) { + let newSeries = []; + let deltaValue; + for (var i = 1; i < datapoints.length; i++) { + deltaValue = datapoints[i][0] - datapoints[i - 1][0]; + newSeries.push([deltaValue, datapoints[i][1]]); + } + return newSeries; + } + static groupByWrapper(interval, groupFunc, datapoints) { var groupByCallback = DataProcessor.aggregationFunctions[groupFunc]; return DataProcessor.groupBy(interval, groupByCallback, datapoints); @@ -181,12 +207,15 @@ export default class DataProcessor { return { groupBy: this.groupByWrapper, scale: this.scale, + delta: this.delta, aggregateBy: this.aggregateByWrapper, average: _.partial(this.aggregateWrapper, this.AVERAGE), min: _.partial(this.aggregateWrapper, this.MIN), max: _.partial(this.aggregateWrapper, this.MAX), median: _.partial(this.aggregateWrapper, this.MEDIAN), sumSeries: this.sumSeries, + top: _.partial(this.limit, 'top'), + bottom: _.partial(this.limit, 'bottom'), setAlias: this.setAlias, }; } diff --git a/src/datasource-zabbix/datasource.js b/src/datasource-zabbix/datasource.js index 932920d..f2176c2 100644 --- a/src/datasource-zabbix/datasource.js +++ b/src/datasource-zabbix/datasource.js @@ -92,7 +92,11 @@ export class ZabbixAPIDatasource { _.forEach(target.functions, func => { func.params = _.map(func.params, param => { - return this.templateSrv.replace(param, options.scopedVars); + if (typeof param === 'number') { + return +this.templateSrv.replace(param.toString(), options.scopedVars); + } else { + return this.templateSrv.replace(param, options.scopedVars); + } }); }); @@ -158,7 +162,7 @@ export class ZabbixAPIDatasource { // Find trendValue() function and get specified trend value var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name'); var trendValueFunc = _.find(target.functions, func => { - return _.contains(trendFunctions, func.def.name); + return _.includes(trendFunctions, func.def.name); }); var valueType = trendValueFunc ? trendValueFunc.params[0] : "avg"; @@ -181,6 +185,7 @@ export class ZabbixAPIDatasource { return getHistory.then(timeseries_data => { let transformFunctions = bindFunctionDefs(target.functions, 'Transform'); let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate'); + let filterFunctions = bindFunctionDefs(target.functions, 'Filter'); let aliasFunctions = bindFunctionDefs(target.functions, 'Alias'); // Apply transformation functions @@ -189,6 +194,11 @@ export class ZabbixAPIDatasource { return timeseries; }); + // Apply filter functions + if (filterFunctions.length) { + timeseries_data = sequence(filterFunctions)(timeseries_data); + } + // Apply aggregations if (aggregationFunctions.length) { let dp = _.map(timeseries_data, 'datapoints'); @@ -196,7 +206,7 @@ export class ZabbixAPIDatasource { let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name'); let lastAgg = _.findLast(target.functions, func => { - return _.contains(aggFuncNames, func.def.name); + return _.includes(aggFuncNames, func.def.name); }); timeseries_data = [ @@ -247,10 +257,9 @@ export class ZabbixAPIDatasource { * @return {object} Connection status and Zabbix API version */ testDatasource() { - var self = this; return this.zabbixAPI.getVersion() .then(version => { - return self.zabbixAPI.login() + return this.zabbixAPI.login() .then(auth => { if (auth) { return { @@ -307,7 +316,7 @@ export class ZabbixAPIDatasource { } parts.push(part); }); - let template = _.object(['group', 'host', 'app', 'item'], parts); + let template = _.zipObject(['group', 'host', 'app', 'item'], parts); // Get items if (parts.length === 4) { @@ -351,11 +360,10 @@ export class ZabbixAPIDatasource { .buildTriggerQuery(this.replaceTemplateVars(annotation.group, {}), this.replaceTemplateVars(annotation.host, {}), this.replaceTemplateVars(annotation.application, {})); - var self = this; + return buildQuery.then(query => { - return self.zabbixAPI - .getTriggers(query.groupids, query.hostids, query.applicationids, - showTriggers, timeFrom, timeTo) + return this.zabbixAPI + .getTriggers(query.groupids, query.hostids, query.applicationids, showTriggers) .then(triggers => { // Filter triggers by description @@ -375,10 +383,10 @@ export class ZabbixAPIDatasource { }); var objectids = _.map(triggers, 'triggerid'); - return self.zabbixAPI + return this.zabbixAPI .getEvents(objectids, timeFrom, timeTo, showOkEvents) .then(events => { - var indexedTriggers = _.indexBy(triggers, 'triggerid'); + var indexedTriggers = _.keyBy(triggers, 'triggerid'); // Hide acknowledged events if option enabled if (annotation.hideAcknowledged) { @@ -388,19 +396,20 @@ export class ZabbixAPIDatasource { } return _.map(events, event => { - var title =''; + let tags; if (annotation.showHostname) { - title += event.hosts[0].name + ': '; + tags = _.map(event.hosts, 'name'); } // Show event type (OK or Problem) - title += Number(event.value) ? 'Problem' : 'OK'; + let title = Number(event.value) ? 'Problem' : 'OK'; - var formatted_acknowledges = utils.formatAcknowledges(event.acknowledges); + let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges); return { annotation: annotation, time: event.clock * 1000, title: title, + tags: tags, text: indexedTriggers[event.objectid].description + formatted_acknowledges }; }); @@ -414,7 +423,7 @@ export class ZabbixAPIDatasource { function bindFunctionDefs(functionDefs, category) { var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name'); var aggFuncDefs = _.filter(functionDefs, function(func) { - return _.contains(aggregationFunctions, func.def.name); + return _.includes(aggregationFunctions, func.def.name); }); return _.map(aggFuncDefs, function(func) { @@ -423,13 +432,6 @@ function bindFunctionDefs(functionDefs, category) { }); } -function filterFunctionDefs(funcs, category) { - let filteredFuncs = _.map(metricFunctions.getCategories()[category]); - return _.filter(funcs, func => { - return _.contains(filteredFuncs, func.def.name); - }); -} - function formatMetric(metricObj) { return { text: metricObj.name, @@ -447,7 +449,7 @@ function formatMetric(metricObj) { * template variables, for example * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait */ -function zabbixTemplateFormat(value, variable) { +function zabbixTemplateFormat(value) { if (typeof value === 'string') { return utils.escapeRegex(value); } @@ -456,7 +458,8 @@ function zabbixTemplateFormat(value, variable) { return '(' + escapedValues.join('|') + ')'; } -/** If template variables are used in request, replace it using regex format +/** + * If template variables are used in request, replace it using regex format * and wrap with '/' for proper multi-value work. Example: * $variable selected as a, b, c * We use filter $variable @@ -494,3 +497,7 @@ function sequence(funcsArray) { return result; }; } + +// Fix for backward compatibility with lodash 2.4 +if (!_.includes) {_.includes = _.contains;} +if (!_.keyBy) {_.keyBy = _.indexBy;} diff --git a/src/datasource-zabbix/metricFunctions.js b/src/datasource-zabbix/metricFunctions.js index 5616bc2..5d467f4 100644 --- a/src/datasource-zabbix/metricFunctions.js +++ b/src/datasource-zabbix/metricFunctions.js @@ -5,6 +5,7 @@ var index = []; var categories = { Transform: [], Aggregate: [], + Filter: [], Trends: [], Alias: [] }; @@ -39,6 +40,13 @@ addFuncDef({ defaultParams: [100], }); +addFuncDef({ + name: 'delta', + category: 'Transform', + params: [], + defaultParams: [], +}); + addFuncDef({ name: 'sumSeries', category: 'Aggregate', @@ -92,6 +100,26 @@ addFuncDef({ defaultParams: ['1m', 'avg'], }); +addFuncDef({ + name: 'top', + category: 'Filter', + params: [ + { name: 'number', type: 'int' }, + { name: 'value', type: 'string', options: ['avg', 'min', 'max', 'median'] } + ], + defaultParams: [5, 'avg'], +}); + +addFuncDef({ + name: 'bottom', + category: 'Filter', + params: [ + { name: 'number', type: 'int' }, + { name: 'value', type: 'string', options: ['avg', 'min', 'max', 'median'] } + ], + defaultParams: [5, 'avg'], +}); + addFuncDef({ name: 'trendValue', category: 'Trends', diff --git a/src/datasource-zabbix/query.controller.js b/src/datasource-zabbix/query.controller.js index ca271cc..5536d48 100644 --- a/src/datasource-zabbix/query.controller.js +++ b/src/datasource-zabbix/query.controller.js @@ -1,4 +1,5 @@ import {QueryCtrl} from 'app/plugins/sdk'; +import angular from 'angular'; import _ from 'lodash'; import * as utils from './utils'; import * as metricFunctions from './metricFunctions'; diff --git a/src/datasource-zabbix/queryProcessor.service.js b/src/datasource-zabbix/queryProcessor.service.js index 557b2f1..d151ff0 100644 --- a/src/datasource-zabbix/queryProcessor.service.js +++ b/src/datasource-zabbix/queryProcessor.service.js @@ -230,13 +230,13 @@ angular.module('grafana.services').factory('QueryProcessor', function($q) { // Group history by itemid var grouped_history = _.groupBy(history, 'itemid'); - var hosts = _.indexBy(_.flatten(_.map(items, 'hosts')), 'hostid'); + var hosts = _.uniq(_.flatten(_.map(items, 'hosts')),'hostid'); //uniq is needed to deduplicate return _.map(grouped_history, function(hist, itemid) { var item = _.find(items, {'itemid': itemid}); var alias = item.name; - if (_.keys(hosts).length > 1 || addHostName) { - var host = hosts[item.hostid]; + if (_.keys(hosts).length > 1 && addHostName) { //only when actual multi hosts selected + var host = _.find(hosts, {'hostid': item.hostid}); alias = host.name + ": " + alias; } return { @@ -335,12 +335,6 @@ function getByFilter(list, filter) { } } -function getFromIndex(index, objids) { - return _.map(objids, function(id) { - return index[id]; - }); -} - function convertHistoryPoint(point) { // Value must be a number for properly work return [ diff --git a/src/datasource-zabbix/utils.js b/src/datasource-zabbix/utils.js index 5925da0..01e0932 100644 --- a/src/datasource-zabbix/utils.js +++ b/src/datasource-zabbix/utils.js @@ -1,7 +1,6 @@ import _ from 'lodash'; import moment from 'moment'; - /** * Expand Zabbix item name * @@ -35,7 +34,7 @@ export function isTemplateVariable(str, templateVariables) { var variables = _.map(templateVariables, variable => { return '$' + variable.name; }); - return _.contains(variables, str); + return _.includes(variables, str); } else { return false; } @@ -93,3 +92,8 @@ export function convertToZabbixAPIUrl(url) { return url.replace(trimSlashPattern, "$1"); } } + +// Fix for backward compatibility with lodash 2.4 +if (!_.includes) { + _.includes = _.contains; +} diff --git a/src/datasource-zabbix/zabbixAPI.service.js b/src/datasource-zabbix/zabbixAPI.service.js index 523f8a1..b8f9edb 100644 --- a/src/datasource-zabbix/zabbixAPI.service.js +++ b/src/datasource-zabbix/zabbixAPI.service.js @@ -41,12 +41,12 @@ function ZabbixAPIService($q, alertSrv, zabbixAPICoreService) { request(method, params) { var self = this; - return this.zabbixAPICore.request(this.url, method, params, this.requestOptions, this.auth) - .then(function(result) { + return this.zabbixAPICore + .request(this.url, method, params, this.requestOptions, this.auth) + .then((result) => { return result; - }, - // Handle API errors - function(error) { + }, (error) => { + // Handle API errors if (isNotAuthorized(error.data)) { return self.loginOnce().then( function() { @@ -56,15 +56,18 @@ function ZabbixAPIService($q, alertSrv, zabbixAPICoreService) { function(error) { self.alertAPIError(error.data); }); + } else { + this.alertSrv.set("Connection Error", error.data, 'error', 5000); } }); } - alertAPIError(message) { + alertAPIError(message, timeout = 5000) { this.alertSrv.set( "Zabbix API Error", message, - 'error' + 'error', + timeout ); } @@ -336,6 +339,7 @@ function ZabbixAPIService($q, alertSrv, zabbixAPICoreService) { applicationids: applicationids, expandDescription: true, expandData: true, + expandComment: true, monitored: true, skipDependent: true, //only_true: true, diff --git a/src/datasource-zabbix/zabbixAPICore.service.js b/src/datasource-zabbix/zabbixAPICore.service.js index a1623e6..2a7473c 100644 --- a/src/datasource-zabbix/zabbixAPICore.service.js +++ b/src/datasource-zabbix/zabbixAPICore.service.js @@ -51,19 +51,23 @@ class ZabbixAPICoreService { requestOptions.headers.Authorization = options.basicAuth; } - this.backendSrv.datasourceRequest(requestOptions).then(function (response) { - // General connection issues - if (!response.data) { - deferred.reject(response); - } + this.backendSrv.datasourceRequest(requestOptions) + .then((response) => { + // General connection issues + if (!response.data) { + deferred.reject(response); + } - // Handle Zabbix API errors - else if (response.data.error) { - deferred.reject(response.data.error); - } + // Handle Zabbix API errors + else if (response.data.error) { + deferred.reject(response.data.error); + } + + deferred.resolve(response.data.result); + }, (error) => { + deferred.reject(error.err); + }); - deferred.resolve(response.data.result); - }); return deferred.promise; } diff --git a/src/datasource-zabbix/zabbixCache.service.js b/src/datasource-zabbix/zabbixCache.service.js index e4c9868..e2a9a00 100644 --- a/src/datasource-zabbix/zabbixCache.service.js +++ b/src/datasource-zabbix/zabbixCache.service.js @@ -1,6 +1,5 @@ import angular from 'angular'; import _ from 'lodash'; -import * as utils from './utils'; // Use factory() instead service() for multiple datasources support. // Each datasource instance must initialize its own cache. @@ -117,7 +116,7 @@ angular.module('grafana.services').factory('ZabbixCachingProxy', function($q, $i var deferred = this.$q.defer(); var historyStorage = this.storage.history; var full_history; - var expired = _.filter(_.indexBy(items, 'itemid'), function(item, itemid) { + var expired = _.filter(_.keyBy(items, 'itemid'), function(item, itemid) { return !historyStorage[itemid]; }); if (expired.length) { @@ -236,3 +235,6 @@ String.prototype.getHash = function() { } return hash; }; + +// Fix for backward compatibility with lodash 2.4 +if (!_.keyBy) {_.keyBy = _.indexBy;} diff --git a/src/panel-triggers/module.js b/src/panel-triggers/module.js index 32ca76f..ce412f5 100644 --- a/src/panel-triggers/module.js +++ b/src/panel-triggers/module.js @@ -222,7 +222,7 @@ class TriggerPanelCtrl extends MetricsPanelCtrl { } // Limit triggers number - self.triggerList = _.first(triggerList, self.panel.limit); + self.triggerList = triggerList.slice(0, self.panel.limit); // Notify panel that request is finished self.setTimeQueryEnd(); diff --git a/src/plugin.json b/src/plugin.json index e44aaf2..d0232e7 100644 --- a/src/plugin.json +++ b/src/plugin.json @@ -31,8 +31,8 @@ {"name": "Metric Editor", "path": "img/screenshot-metric_editor.png"}, {"name": "Triggers", "path": "img/screenshot-triggers.png"} ], - "version": "3.0.0", - "updated": "2016-07-03" + "version": "3.1.1", + "updated": "2016-09-27" }, "includes": [