diff --git a/.gitignore b/.gitignore index dbb0ecd0f..b3e2d22d1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ .idea/ .vscode +grafana-zabbix.iml +package-lock.json *.bat diff --git a/dist/README.md b/dist/README.md index 625f81873..f2840b876 100644 --- a/dist/README.md +++ b/dist/README.md @@ -1,22 +1,22 @@ -# Zabbix plugin for Grafana - -[![GitHub version](https://badge.fury.io/gh/alexanderzobnin%2Fgrafana-zabbix.svg)](https://github.com/alexanderzobnin/grafana-zabbix/releases) -[![Change Log](https://img.shields.io/badge/change-log-blue.svg?style=flat)](https://github.com/alexanderzobnin/grafana-zabbix/blob/master/CHANGELOG.md) -[![Docs](https://img.shields.io/badge/docs-latest-red.svg?style=flat)](http://docs.grafana-zabbix.org) - -Visualize your Zabbix metrics with the leading open source software for time series analytics. - -### Live Demo - -See all features overview and dashboards examples at Grafana-Zabbix [Live demo](http://play.grafana-zabbix.org) site. - -### Features - -- Select multiple metrics [by using Regex](http://docs.grafana-zabbix.org/guides/gettingstarted/#multiple-items-on-one-graph) -- Create interactive and reusable dashboards with [template variables](http://docs.grafana-zabbix.org/guides/templating/) -- Show events on graphs with [Annotations](http://docs.grafana.org/reference/annotations/) -- Display active problems with Triggers panel -- Transform and shape your data with [metric processing functions](http://docs.grafana-zabbix.org/reference/functions/) (Avg, Median, Min, Max, Multiply, Summarize, Time shift, Alias) -- Find problems faster with [Alerting](http://docs.grafana-zabbix.org/reference/alerting/) feature -- Mix metrics from multiple data sources in the same dashboard or even graph -- Discover and share [dashboards](https://grafana.com/dashboards) in the official library +# Zabbix plugin for Grafana + +[![GitHub version](https://badge.fury.io/gh/alexanderzobnin%2Fgrafana-zabbix.svg)](https://github.com/alexanderzobnin/grafana-zabbix/releases) +[![Change Log](https://img.shields.io/badge/change-log-blue.svg?style=flat)](https://github.com/alexanderzobnin/grafana-zabbix/blob/master/CHANGELOG.md) +[![Docs](https://img.shields.io/badge/docs-latest-red.svg?style=flat)](http://docs.grafana-zabbix.org) + +Visualize your Zabbix metrics with the leading open source software for time series analytics. + +### Live Demo + +See all features overview and dashboards examples at Grafana-Zabbix [Live demo](http://play.grafana-zabbix.org) site. + +### Features + +- Select multiple metrics [by using Regex](http://docs.grafana-zabbix.org/guides/gettingstarted/#multiple-items-on-one-graph) +- Create interactive and reusable dashboards with [template variables](http://docs.grafana-zabbix.org/guides/templating/) +- Show events on graphs with [Annotations](http://docs.grafana.org/reference/annotations/) +- Display active problems with Triggers panel +- Transform and shape your data with [metric processing functions](http://docs.grafana-zabbix.org/reference/functions/) (Avg, Median, Min, Max, Multiply, Summarize, Time shift, Alias) +- Find problems faster with [Alerting](http://docs.grafana-zabbix.org/reference/alerting/) feature +- Mix metrics from multiple data sources in the same dashboard or even graph +- Discover and share [dashboards](https://grafana.com/dashboards) in the official library diff --git a/dist/components/config.html b/dist/components/config.html index 4c4b34c39..5d775294a 100644 --- a/dist/components/config.html +++ b/dist/components/config.html @@ -1 +1 @@ -

Zabbix Plugin Config

+

Zabbix Plugin Config

diff --git a/dist/components/config.js.map b/dist/components/config.js.map index 69b4032a0..4baa289f4 100644 --- a/dist/components/config.js.map +++ b/dist/components/config.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/components/config.js"],"names":["ZabbixAppConfigCtrl","templateUrl"],"mappings":";;;;;;;;;;;;;;;;qCAAaA,mB,GACX,+BAAc;AAAA;AAAG,O;;;;AAEnBA,0BAAoBC,WAApB,GAAkC,wBAAlC","file":"config.js","sourcesContent":["export class ZabbixAppConfigCtrl {\n constructor() { }\n}\nZabbixAppConfigCtrl.templateUrl = 'components/config.html';\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/components/config.js"],"names":["ZabbixAppConfigCtrl","templateUrl"],"mappings":";;;;;;;;;;;;;;;;qCAAaA,mB,GACX,+BAAc;AAAA;AAAG,O;;;;AAEnBA,0BAAoBC,WAApB,GAAkC,wBAAlC","file":"config.js","sourcesContent":["export class ZabbixAppConfigCtrl {\r\n constructor() { }\r\n}\r\nZabbixAppConfigCtrl.templateUrl = 'components/config.html';\r\n"]} \ No newline at end of file diff --git a/dist/css/grafana-zabbix.dark.css.map b/dist/css/grafana-zabbix.dark.css.map index bbee0ea64..3dd74bd52 100644 --- a/dist/css/grafana-zabbix.dark.css.map +++ b/dist/css/grafana-zabbix.dark.css.map @@ -9,6 +9,6 @@ "../../src/sass/_panel-triggers.scss", "../../src/sass/_query_editor.scss" ], - "mappings": "AIAA,AAAA,sBAAsB,CAAC;EACrB,QAAQ,EAAE,IAAK,GAChB;;AAED,AAAA,yBAAyB,CAAC;EACxB,QAAQ,EAAE,QAAS,GAoDpB;EArDD,AAGE,yBAHuB,CAGvB,oBAAoB,CAAC;IACnB,WAAW,EAAE,IAAK,GACnB;EALH,AAOE,yBAPuB,CAOvB,gBAAgB,CAAC;IACf,KAAK,EHHU,OAAO;IGItB,WAAW,EAAE,IAAK;IAClB,WAAW,EAAE,GAAI,GAClB;EAXH,AAaE,yBAbuB,CAavB,gBAAgB,CAAC;IACf,KAAK,EHRU,OAAO;IGStB,WAAW,EAAE,MAAO;IACpB,WAAW,EAAE,MAAO,GAKrB;IArBH,AAaE,yBAbuB,CAavB,yBAAgB,CAKH;MACT,WAAW,EAAE,IAAK,GACnB;EApBL,AAuBE,yBAvBuB,CAuBvB,iBAAiB,CAAC;IAChB,WAAW,EAAE,MAAO,GAUrB;IAlCH,AA0BI,yBA1BqB,CAuBvB,iBAAiB,CAGf,QAAQ,CAAC;MACP,KAAK,EHnBQ,OAAO;MGoBpB,WAAW,EAAE,GAAI;MACjB,SAAS,EAAE,IAAK;MAChB,YAAY,EAAE,GAAI;MAClB,OAAO,EAAE,OAAQ;MACjB,MAAM,EAAE,OAAQ,GACjB;EAjCL,AAoCE,yBApCuB,CAoCvB,mBAAmB,CAAC;IAClB,OAAO,EAAE,IAAK,GAMf;IA3CH,AAuCI,yBAvCqB,CAoCvB,mBAAmB,CAGjB,CAAC,EAvCL,AAuCO,yBAvCkB,CAoCvB,mBAAm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AClB;;AAbH,AAeE,YAfU,CAeV,KAAK,CAAC,EAAE,EAfV,YAAY,CAeA,EAAE,CAAC;EACX,aAAa,EAAE,IAAI,GACpB;;AAjBH,AAmBE,YAnBU,CAmBV,gBAAgB,CAAC;EACf,WAAW,EAAE,IAAI,GAWlB;EA/BH,AAsBI,YAtBQ,CAmBV,gBAAgB,CAGd,KAAK,CAAC;IACJ,MAAM,EAAE,SAAS;IACjB,aAAa,EAAE,GAAG;IAClB,KAAK,EAAE,GAAG,GACX;EA1BL,AA4BI,YA5BQ,CAmBV,gBAAgB,CASd,MAAM,CAAC;IACL,WAAW,EAAE,IAAI,GAClB;;AAIL,AACE,yBADuB,AACtB,cAAc,CAAC;EACd,WAAW,EAAE,GAAG;EAChB,cAAc,EAAE,GAAG;EACnB,aAAa,EAAE,GAAG,GACnB;;AALH,AAOE,yBAPuB,CAOvB,QAAQ,CAAC;EACP,SAAS,EAAE,IAAI,GAChB;;ACrLH,AAAA,UAAU,CAAC;EACT,KAAK,EJ6BY,OAAO,GI5BzB;;AAED,AAAA,aAAa,CAAC;EACZ,KAAK,EJwBY,OAAO,GIvBzB" } \ No newline at end of file diff --git a/dist/css/grafana-zabbix.light.css.map b/dist/css/grafana-zabbix.light.css.map index c8daf62be..9928a6a99 100644 --- a/dist/css/grafana-zabbix.light.css.map +++ b/dist/css/grafana-zabbix.light.css.map @@ -9,6 +9,6 @@ "../../src/sass/_panel-triggers.scss", "../../src/sass/_query_editor.scss" ], - "mappings": "AIAA,AAAA,sBAAsB,CAAC;EACrB,QAAQ,EAAE,IAAK,GAChB;;AAED,AAAA,yBAAyB,CAAC;EACxB,QAAQ,EAAE,QAAS,GAoDpB;EArDD,AAGE,yBAHuB,CAGvB,oBAAoB,CAAC;IACnB,WAAW,EAAE,IAAK,GACnB;EALH,AAOE,yBAPuB,CAOvB,gBAAgB,CAAC;IACf,KAAK,EHHU,OAAO;IGItB,WAAW,EAAE,IAAK;IAClB,WAAW,EAAE,GAAI,GAClB;EAX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ACrLH,AAAA,UAAU,CAAC;EACT,KAAK,EJ4BY,OAAO,GI3BzB;;AAED,AAAA,aAAa,CAAC;EACZ,KAAK,EJeY,OAAO,GIdzB" } \ No newline at end of file diff --git a/dist/dashboards/template_linux_server.json b/dist/dashboards/template_linux_server.json index 453f84392..8ab9d811a 100644 --- a/dist/dashboards/template_linux_server.json +++ b/dist/dashboards/template_linux_server.json @@ -1,447 +1,447 @@ -{ - "__inputs": [ - { - "name": "DS_NAME", - "type": "datasource", - "pluginId": "alexanderzobnin-zabbix-datasource" - } - ], - "title": "Zabbix Template Linux Server", - "revision": 1, - "annotations": { - "list": [] - }, - "editable": true, - "gnetId": null, - "graphTooltip": 0, - "hideControls": false, - "id": null, - "links": [], - "rows": [ - { - "collapse": false, - "height": "250px", - "panels": [ - { - "aliasColors": { - "CPU iowait time": "#B7DBAB", - "CPU system time": "#BF1B00", - "CPU user time": "#EAB839" - }, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": "${DS_NAME}", - "editable": true, - "error": false, - "fill": 3, - "grid": {}, - "id": 1, - "legend": { - "avg": false, - "current": false, - "max": false, - "min": false, - "show": true, - "total": false, - "values": false - }, - "lines": true, - "linewidth": 1, - "links": [], - "nullPointMode": "connected", - "percentage": false, - "pointradius": 2, - "points": false, - "renderer": "flot", - "seriesOverrides": [], - "spaceLength": 10, - "span": 6, - "stack": true, - "steppedLine": false, - "targets": [ - { - "application": { - "filter": "CPU" - }, - "countTriggers": true, - "functions": [], - "group": { - "filter": "$group" - }, - "host": { - "filter": "$host" - }, - "item": { - "filter": "/CPU/" - }, - "minSeverity": 3, - "mode": 0, - "options": { - "showDisabledItems": false - }, - "refId": "A" - } - ], - "thresholds": [], - "timeFrom": null, - "timeShift": null, - "title": "CPU", - "tooltip": { - "msResolution": false, - "shared": true, - "sort": 0, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "buckets": null, - "mode": "time", - "name": null, - "show": true, - "values": [] - }, - "yaxes": [ - { - "format": "percent", - "logBase": 1, - "max": 100, - "min": 0, - "show": true - }, - { - "format": "short", - "logBase": 1, - "max": null, - "min": null, - "show": true - } - ] - }, - { - "aliasColors": { - "Processor load (1 min average per core)": "#1F78C1" - }, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": "${DS_NAME}", - "editable": true, - "error": false, - "fill": 1, - "grid": {}, - "id": 2, - "legend": { - "avg": false, - "current": false, - "max": false, - "min": false, - "show": true, - "total": false, - "values": false - }, - "lines": true, - "linewidth": 2, - "links": [], - "nullPointMode": "connected", - "percentage": false, - "pointradius": 5, - "points": false, - "renderer": "flot", - "seriesOverrides": [], - "spaceLength": 10, - "span": 6, - "stack": false, - "steppedLine": false, - "targets": [ - { - "application": { - "filter": "CPU" - }, - "countTriggers": true, - "functions": [], - "group": { - "filter": "$group" - }, - "host": { - "filter": "$host" - }, - "item": { - "filter": "Processor load (15 min average per core)" - }, - "minSeverity": 3, - "mode": 0, - "options": { - "showDisabledItems": false - }, - "refId": "A" - } - ], - "thresholds": [], - "timeFrom": null, - "timeShift": null, - "title": "System load", - "tooltip": { - "msResolution": false, - "shared": true, - "sort": 0, - "value_type": "cumulative" - }, - "type": "graph", - "xaxis": { - "buckets": null, - "mode": "time", - "name": null, - "show": true, - "values": [] - }, - "yaxes": [ - { - "format": "short", - "logBase": 1, - "max": null, - "min": 0, - "show": true - }, - { - "format": "short", - "logBase": 1, - "max": null, - "min": null, - "show": true - } - ] - } - ], - "repeat": null, - "repeatIteration": null, - "repeatRowId": null, - "showTitle": true, - "title": "CPU", - "titleSize": "h6" - }, - { - "collapse": false, - "height": "250px", - "panels": [ - { - "aliasColors": {}, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": "${DS_NAME}", - "editable": true, - "error": false, - "fill": 3, - "grid": {}, - "id": 3, - "legend": { - "alignAsTable": false, - "avg": false, - "current": false, - "max": false, - "min": false, - "rightSide": false, - "show": true, - "total": false, - "values": false - }, - "lines": true, - "linewidth": 2, - "links": [], - "minSpan": 4, - "nullPointMode": "connected", - "percentage": false, - "pointradius": 5, - "points": false, - "renderer": "flot", - "repeat": "netif", - "seriesOverrides": [ - { - "alias": "/Incoming/", - "transform": "negative-Y" - } - ], - "spaceLength": 10, - "span": 12, - "stack": false, - "steppedLine": false, - "targets": [ - { - "application": { - "filter": "" - }, - "countTriggers": true, - "functions": [], - "group": { - "filter": "$group" - }, - "host": { - "filter": "$host" - }, - "item": { - "filter": "/$netif/" - }, - "minSeverity": 3, - "mode": 0, - "options": { - "showDisabledItems": false - }, - "refId": "A" - } - ], - "thresholds": [], - "timeFrom": null, - "timeShift": null, - "title": "Network traffic on $netif", - "tooltip": { - "msResolution": false, - "shared": true, - "sort": 0, - "value_type": "cumulative" - }, - "type": "graph", - "xaxis": { - "buckets": null, - "mode": "time", - "name": null, - "show": true, - "values": [] - }, - "yaxes": [ - { - "format": "bps", - "logBase": 1, - "max": null, - "min": null, - "show": true - }, - { - "format": "short", - "logBase": 1, - "max": null, - "min": null, - "show": true - } - ] - } - ], - "repeat": null, - "repeatIteration": null, - "repeatRowId": null, - "showTitle": true, - "title": "Network", - "titleSize": "h6" - } - ], - "schemaVersion": 14, - "style": "dark", - "tags": [ - "zabbix", - "example" - ], - "templating": { - "list": [ - { - "allFormat": "regex values", - "allValue": null, - "current": {}, - "datasource": "${DS_NAME}", - "hide": 0, - "includeAll": false, - "label": "Group", - "multi": false, - "multiFormat": "glob", - "name": "group", - "options": [], - "query": "*", - "refresh": 1, - "refresh_on_load": false, - "regex": "", - "sort": 0, - "tagValuesQuery": "", - "tags": [], - "tagsQuery": "", - "type": "query", - "useTags": false - }, - { - "allFormat": "glob", - "allValue": null, - "current": {}, - "datasource": "${DS_NAME}", - "hide": 0, - "includeAll": false, - "label": "Host", - "multi": false, - "multiFormat": "glob", - "name": "host", - "options": [], - "query": "$group.*", - "refresh": 1, - "refresh_on_load": false, - "regex": "", - "sort": 0, - "tagValuesQuery": "", - "tags": [], - "tagsQuery": "", - "type": "query", - "useTags": false - }, - { - "allFormat": "regex values", - "allValue": null, - "current": {}, - "datasource": "${DS_NAME}", - "hide": 0, - "hideLabel": false, - "includeAll": true, - "label": "Network interface", - "multi": true, - "multiFormat": "regex values", - "name": "netif", - "options": [], - "query": "*.$host.Network interfaces.*", - "refresh": 1, - "refresh_on_load": false, - "regex": "/(?:Incoming|Outgoing) network traffic on (.*)/", - "sort": 0, - "tagValuesQuery": "", - "tags": [], - "tagsQuery": "", - "type": "query", - "useTags": false - } - ] - }, - "time": { - "from": "now-3h", - "to": "now" - }, - "timepicker": { - "now": true, - "refresh_intervals": [ - "30s", - "1m", - "5m", - "15m", - "30m", - "1h", - "3h", - "2h", - "1d" - ], - "time_options": [ - "5m", - "15m", - "1h", - "6h", - "12h", - "24h", - "2d", - "7d", - "30d" - ] - }, - "timezone": "browser" -} +{ + "__inputs": [ + { + "name": "DS_NAME", + "type": "datasource", + "pluginId": "alexanderzobnin-zabbix-datasource" + } + ], + "title": "Zabbix Template Linux Server", + "revision": 1, + "annotations": { + "list": [] + }, + "editable": true, + "gnetId": null, + "graphTooltip": 0, + "hideControls": false, + "id": null, + "links": [], + "rows": [ + { + "collapse": false, + "height": "250px", + "panels": [ + { + "aliasColors": { + "CPU iowait time": "#B7DBAB", + "CPU system time": "#BF1B00", + "CPU user time": "#EAB839" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_NAME}", + "editable": true, + "error": false, + "fill": 3, + "grid": {}, + "id": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "connected", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "span": 6, + "stack": true, + "steppedLine": false, + "targets": [ + { + "application": { + "filter": "CPU" + }, + "countTriggers": true, + "functions": [], + "group": { + "filter": "$group" + }, + "host": { + "filter": "$host" + }, + "item": { + "filter": "/CPU/" + }, + "minSeverity": 3, + "mode": 0, + "options": { + "showDisabledItems": false + }, + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeShift": null, + "title": "CPU", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "logBase": 1, + "max": 100, + "min": 0, + "show": true + }, + { + "format": "short", + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ] + }, + { + "aliasColors": { + "Processor load (1 min average per core)": "#1F78C1" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_NAME}", + "editable": true, + "error": false, + "fill": 1, + "grid": {}, + "id": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "links": [], + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "span": 6, + "stack": false, + "steppedLine": false, + "targets": [ + { + "application": { + "filter": "CPU" + }, + "countTriggers": true, + "functions": [], + "group": { + "filter": "$group" + }, + "host": { + "filter": "$host" + }, + "item": { + "filter": "Processor load (15 min average per core)" + }, + "minSeverity": 3, + "mode": 0, + "options": { + "showDisabledItems": false + }, + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeShift": null, + "title": "System load", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ] + } + ], + "repeat": null, + "repeatIteration": null, + "repeatRowId": null, + "showTitle": true, + "title": "CPU", + "titleSize": "h6" + }, + { + "collapse": false, + "height": "250px", + "panels": [ + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "${DS_NAME}", + "editable": true, + "error": false, + "fill": 3, + "grid": {}, + "id": 3, + "legend": { + "alignAsTable": false, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "links": [], + "minSpan": 4, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": "netif", + "seriesOverrides": [ + { + "alias": "/Incoming/", + "transform": "negative-Y" + } + ], + "spaceLength": 10, + "span": 12, + "stack": false, + "steppedLine": false, + "targets": [ + { + "application": { + "filter": "" + }, + "countTriggers": true, + "functions": [], + "group": { + "filter": "$group" + }, + "host": { + "filter": "$host" + }, + "item": { + "filter": "/$netif/" + }, + "minSeverity": 3, + "mode": 0, + "options": { + "showDisabledItems": false + }, + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeShift": null, + "title": "Network traffic on $netif", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bps", + "logBase": 1, + "max": null, + "min": null, + "show": true + }, + { + "format": "short", + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ] + } + ], + "repeat": null, + "repeatIteration": null, + "repeatRowId": null, + "showTitle": true, + "title": "Network", + "titleSize": "h6" + } + ], + "schemaVersion": 14, + "style": "dark", + "tags": [ + "zabbix", + "example" + ], + "templating": { + "list": [ + { + "allFormat": "regex values", + "allValue": null, + "current": {}, + "datasource": "${DS_NAME}", + "hide": 0, + "includeAll": false, + "label": "Group", + "multi": false, + "multiFormat": "glob", + "name": "group", + "options": [], + "query": "*", + "refresh": 1, + "refresh_on_load": false, + "regex": "", + "sort": 0, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + }, + { + "allFormat": "glob", + "allValue": null, + "current": {}, + "datasource": "${DS_NAME}", + "hide": 0, + "includeAll": false, + "label": "Host", + "multi": false, + "multiFormat": "glob", + "name": "host", + "options": [], + "query": "$group.*", + "refresh": 1, + "refresh_on_load": false, + "regex": "", + "sort": 0, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + }, + { + "allFormat": "regex values", + "allValue": null, + "current": {}, + "datasource": "${DS_NAME}", + "hide": 0, + "hideLabel": false, + "includeAll": true, + "label": "Network interface", + "multi": true, + "multiFormat": "regex values", + "name": "netif", + "options": [], + "query": "*.$host.Network interfaces.*", + "refresh": 1, + "refresh_on_load": false, + "regex": "/(?:Incoming|Outgoing) network traffic on (.*)/", + "sort": 0, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + } + ] + }, + "time": { + "from": "now-3h", + "to": "now" + }, + "timepicker": { + "now": true, + "refresh_intervals": [ + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "3h", + "2h", + "1d" + ], + "time_options": [ + "5m", + "15m", + "1h", + "6h", + "12h", + "24h", + "2d", + "7d", + "30d" + ] + }, + "timezone": "browser" +} diff --git a/dist/dashboards/zabbix_server_dashboard.json b/dist/dashboards/zabbix_server_dashboard.json index 9f92024e6..4c741141b 100644 --- a/dist/dashboards/zabbix_server_dashboard.json +++ b/dist/dashboards/zabbix_server_dashboard.json @@ -1,646 +1,646 @@ -{ - "id": null, - "title": "Zabbix Server Dashboard", - "originalTitle": "Zabbix Server Dashboard", - "tags": [ - "zabbix", - "example" - ], - "style": "dark", - "timezone": "browser", - "editable": true, - "hideControls": false, - "sharedCrosshair": false, - "rows": [ - { - "collapse": false, - "editable": true, - "height": "100px", - "panels": [ - { - "cacheTimeout": null, - "colorBackground": false, - "colorValue": false, - "colors": [ - "rgba(245, 54, 54, 0.9)", - "rgba(237, 129, 40, 0.89)", - "rgba(50, 172, 45, 0.97)" - ], - "datasource": "$datasource", - "editable": true, - "error": false, - "format": "none", - "id": 3, - "interval": null, - "isNew": true, - "links": [], - "maxDataPoints": 100, - "nullPointMode": "connected", - "nullText": null, - "postfix": "", - "postfixFontSize": "50%", - "prefix": "", - "prefixFontSize": "50%", - "span": 4, - "sparkline": { - "fillColor": "rgba(31, 118, 189, 0.18)", - "full": false, - "lineColor": "rgb(31, 120, 193)", - "show": false - }, - "targets": [ - { - "application": { - "filter": "General" - }, - "functions": [], - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "item": { - "filter": "Host name" - }, - "mode": 2, - "refId": "A" - } - ], - "thresholds": "", - "title": "Host name", - "type": "singlestat", - "valueFontSize": "80%", - "valueMaps": [ - { - "op": "=", - "text": "N/A", - "value": "null" - } - ], - "valueName": "avg" - }, - { - "cacheTimeout": null, - "colorBackground": false, - "colorValue": false, - "colors": [ - "rgba(245, 54, 54, 0.9)", - "rgba(237, 129, 40, 0.89)", - "rgba(50, 172, 45, 0.97)" - ], - "datasource": "$datasource", - "decimals": 0, - "editable": true, - "error": false, - "format": "s", - "id": 4, - "interval": null, - "isNew": true, - "links": [], - "maxDataPoints": "", - "nullPointMode": "connected", - "nullText": null, - "postfix": "", - "postfixFontSize": "50%", - "prefix": "", - "prefixFontSize": "50%", - "span": 4, - "sparkline": { - "fillColor": "rgba(31, 118, 189, 0.18)", - "full": false, - "lineColor": "rgb(31, 120, 193)", - "show": false - }, - "targets": [ - { - "application": { - "filter": "General" - }, - "functions": [], - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "item": { - "filter": "System uptime" - }, - "mode": 0, - "refId": "A" - } - ], - "thresholds": "", - "title": "Uptime", - "type": "singlestat", - "valueFontSize": "80%", - "valueMaps": [ - { - "op": "=", - "text": "N/A", - "value": "null" - } - ], - "valueName": "current" - }, - { - "cacheTimeout": null, - "colorBackground": false, - "colorValue": false, - "colors": [ - "rgba(245, 54, 54, 0.9)", - "rgba(237, 129, 40, 0.89)", - "rgba(50, 172, 45, 0.97)" - ], - "datasource": "$datasource", - "editable": true, - "error": false, - "format": "none", - "id": 5, - "interval": null, - "isNew": true, - "links": [], - "maxDataPoints": "", - "nullPointMode": "connected", - "nullText": null, - "postfix": "", - "postfixFontSize": "50%", - "prefix": "", - "prefixFontSize": "50%", - "span": 4, - "sparkline": { - "fillColor": "rgba(31, 118, 189, 0.18)", - "full": false, - "lineColor": "rgb(31, 120, 193)", - "show": false - }, - "targets": [ - { - "application": { - "filter": "Zabbix server" - }, - "functions": [], - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "item": { - "filter": "/Required performance of Zabbix server/" - }, - "mode": 0, - "refId": "A" - } - ], - "thresholds": "", - "title": "Required performance, NVPS", - "type": "singlestat", - "valueFontSize": "80%", - "valueMaps": [ - { - "op": "=", - "text": "N/A", - "value": "null" - } - ], - "valueName": "current" - } - ], - "title": "General" - }, - { - "collapse": false, - "editable": true, - "height": "300px", - "panels": [ - { - "aliasColors": {}, - "bars": false, - "datasource": "$datasource", - "editable": true, - "error": false, - "fill": 1, - "grid": { - "threshold1": null, - "threshold1Color": "rgba(216, 200, 27, 0.27)", - "threshold2": null, - "threshold2Color": "rgba(234, 112, 112, 0.22)" - }, - "id": 1, - "isNew": true, - "legend": { - "alignAsTable": true, - "avg": false, - "current": false, - "max": false, - "min": false, - "rightSide": true, - "show": true, - "total": false, - "values": false - }, - "lines": true, - "linewidth": 2, - "links": [], - "nullPointMode": "connected", - "percentage": false, - "pointradius": 5, - "points": false, - "renderer": "flot", - "seriesOverrides": [ - { - "alias": "/user/", - "color": "#1F78C1" - }, - { - "alias": "/system/", - "color": "#BF1B00" - }, - { - "alias": "/iowait/", - "color": "#E5AC0E" - } - ], - "span": 7, - "stack": true, - "steppedLine": false, - "targets": [ - { - "application": { - "filter": "CPU" - }, - "functions": [], - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "item": { - "filter": "/CPU (?!idle)/" - }, - "mode": 0, - "refId": "A" - } - ], - "timeFrom": null, - "timeShift": null, - "title": "CPU", - "tooltip": { - "msResolution": false, - "shared": true, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "show": true - }, - "yaxes": [ - { - "format": "percent", - "label": null, - "logBase": 1, - "max": null, - "min": null, - "show": true - }, - { - "format": "short", - "label": null, - "logBase": 1, - "max": null, - "min": null, - "show": true - } - ] - }, - { - "columns": [ - { - "text": "Current", - "value": "current" - }, - { - "text": "Avg", - "value": "avg" - } - ], - "datasource": "$datasource", - "editable": true, - "error": false, - "fontSize": "100%", - "id": 2, - "isNew": true, - "links": [], - "pageSize": null, - "scroll": true, - "showHeader": true, - "sort": { - "col": 2, - "desc": true - }, - "span": 5, - "styles": [ - { - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "pattern": "Time", - "type": "date" - }, - { - "colorMode": "cell", - "colors": [ - "rgb(41, 170, 106)", - "rgba(239, 148, 21, 0.89)", - "rgba(239, 10, 10, 0.9)" - ], - "decimals": 1, - "pattern": "/.*/", - "thresholds": [ - "50", - "80" - ], - "type": "number", - "unit": "percent" - } - ], - "targets": [ - { - "application": { - "filter": "Zabbix server" - }, - "functions": [], - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "item": { - "filter": "/Zabbix busy/" - }, - "mode": 0, - "refId": "A" - } - ], - "title": "Zabbix processes", - "transform": "timeseries_aggregations", - "type": "table" - } - ], - "title": "Row" - }, - { - "title": "New row", - "height": "380", - "editable": true, - "collapse": false, - "panels": [ - { - "title": "Zabbix busy processes", - "error": false, - "span": 7.069277691711851, - "editable": true, - "type": "graph", - "isNew": true, - "id": 6, - "targets": [ - { - "refId": "A", - "mode": 0, - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "application": { - "filter": "Zabbix server" - }, - "item": { - "filter": "/Zabbix busy/" - }, - "functions": [] - } - ], - "datasource": "$datasource", - "renderer": "flot", - "yaxes": [ - { - "label": null, - "show": true, - "logBase": 1, - "min": null, - "max": null, - "format": "percent" - }, - { - "label": null, - "show": true, - "logBase": 1, - "min": null, - "max": null, - "format": "short" - } - ], - "xaxis": { - "show": true - }, - "grid": { - "threshold1": null, - "threshold2": null, - "threshold1Color": "rgba(216, 200, 27, 0.27)", - "threshold2Color": "rgba(234, 112, 112, 0.22)" - }, - "lines": true, - "fill": 0, - "linewidth": 2, - "points": false, - "pointradius": 5, - "bars": false, - "stack": false, - "percentage": false, - "legend": { - "show": true, - "values": false, - "min": false, - "max": false, - "current": false, - "total": false, - "avg": false, - "hideEmpty": true, - "hideZero": true, - "alignAsTable": true, - "rightSide": true - }, - "nullPointMode": "connected", - "steppedLine": false, - "tooltip": { - "value_type": "cumulative", - "shared": true, - "msResolution": false - }, - "timeFrom": null, - "timeShift": null, - "aliasColors": {}, - "seriesOverrides": [], - "links": [] - }, - { - "title": "Zabbix Queue", - "error": false, - "span": 4.930722308288148, - "editable": true, - "type": "graph", - "isNew": true, - "id": 7, - "targets": [ - { - "refId": "A", - "mode": 0, - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "application": { - "filter": "Zabbix server" - }, - "item": { - "filter": "Zabbix queue" - }, - "functions": [] - }, - { - "refId": "B", - "mode": 0, - "group": { - "filter": "Zabbix servers" - }, - "host": { - "filter": "Zabbix server" - }, - "application": { - "filter": "Zabbix server" - }, - "item": { - "filter": "/Values processed/" - }, - "functions": [] - } - ], - "datasource": "$datasource", - "renderer": "flot", - "yaxes": [ - { - "label": null, - "show": true, - "logBase": 1, - "min": null, - "max": null, - "format": "short" - }, - { - "label": null, - "show": true, - "logBase": 1, - "min": null, - "max": null, - "format": "short" - } - ], - "xaxis": { - "show": true - }, - "grid": { - "threshold1": null, - "threshold2": null, - "threshold1Color": "rgba(216, 200, 27, 0.27)", - "threshold2Color": "rgba(234, 112, 112, 0.22)" - }, - "lines": true, - "fill": 0, - "linewidth": 2, - "points": false, - "pointradius": 5, - "bars": false, - "stack": false, - "percentage": false, - "legend": { - "show": true, - "values": false, - "min": false, - "max": false, - "current": false, - "total": false, - "avg": false - }, - "nullPointMode": "connected", - "steppedLine": false, - "tooltip": { - "value_type": "cumulative", - "shared": true, - "msResolution": false - }, - "timeFrom": null, - "timeShift": null, - "aliasColors": {}, - "seriesOverrides": [], - "links": [] - } - ] - } - ], - "templating": { - "list": [ - { - "current": {}, - "hide": 0, - "label": "Zabbix Data Source", - "name": "datasource", - "options": [], - "query": "alexanderzobnin-zabbix-datasource", - "refresh": 1, - "regex": "", - "type": "datasource" - } - ] - }, - "time": { - "from": "now-6h", - "to": "now" - }, - "timepicker": { - "refresh_intervals": [ - "5s", - "10s", - "30s", - "1m", - "5m", - "15m", - "30m", - "1h", - "2h", - "1d" - ], - "time_options": [ - "5m", - "15m", - "1h", - "6h", - "12h", - "24h", - "2d", - "7d", - "30d" - ] - }, - "annotations": { - "list": [] - }, - "schemaVersion": 12, - "version": 7, - "links": [] -} +{ + "id": null, + "title": "Zabbix Server Dashboard", + "originalTitle": "Zabbix Server Dashboard", + "tags": [ + "zabbix", + "example" + ], + "style": "dark", + "timezone": "browser", + "editable": true, + "hideControls": false, + "sharedCrosshair": false, + "rows": [ + { + "collapse": false, + "editable": true, + "height": "100px", + "panels": [ + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": false, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "datasource": "$datasource", + "editable": true, + "error": false, + "format": "none", + "id": 3, + "interval": null, + "isNew": true, + "links": [], + "maxDataPoints": 100, + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "span": 4, + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "targets": [ + { + "application": { + "filter": "General" + }, + "functions": [], + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "item": { + "filter": "Host name" + }, + "mode": 2, + "refId": "A" + } + ], + "thresholds": "", + "title": "Host name", + "type": "singlestat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + }, + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": false, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "datasource": "$datasource", + "decimals": 0, + "editable": true, + "error": false, + "format": "s", + "id": 4, + "interval": null, + "isNew": true, + "links": [], + "maxDataPoints": "", + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "span": 4, + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "targets": [ + { + "application": { + "filter": "General" + }, + "functions": [], + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "item": { + "filter": "System uptime" + }, + "mode": 0, + "refId": "A" + } + ], + "thresholds": "", + "title": "Uptime", + "type": "singlestat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "current" + }, + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": false, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "datasource": "$datasource", + "editable": true, + "error": false, + "format": "none", + "id": 5, + "interval": null, + "isNew": true, + "links": [], + "maxDataPoints": "", + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "span": 4, + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "targets": [ + { + "application": { + "filter": "Zabbix server" + }, + "functions": [], + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "item": { + "filter": "/Required performance of Zabbix server/" + }, + "mode": 0, + "refId": "A" + } + ], + "thresholds": "", + "title": "Required performance, NVPS", + "type": "singlestat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "current" + } + ], + "title": "General" + }, + { + "collapse": false, + "editable": true, + "height": "300px", + "panels": [ + { + "aliasColors": {}, + "bars": false, + "datasource": "$datasource", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "threshold1": null, + "threshold1Color": "rgba(216, 200, 27, 0.27)", + "threshold2": null, + "threshold2Color": "rgba(234, 112, 112, 0.22)" + }, + "id": 1, + "isNew": true, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "links": [], + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "/user/", + "color": "#1F78C1" + }, + { + "alias": "/system/", + "color": "#BF1B00" + }, + { + "alias": "/iowait/", + "color": "#E5AC0E" + } + ], + "span": 7, + "stack": true, + "steppedLine": false, + "targets": [ + { + "application": { + "filter": "CPU" + }, + "functions": [], + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "item": { + "filter": "/CPU (?!idle)/" + }, + "mode": 0, + "refId": "A" + } + ], + "timeFrom": null, + "timeShift": null, + "title": "CPU", + "tooltip": { + "msResolution": false, + "shared": true, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "show": true + }, + "yaxes": [ + { + "format": "percent", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ] + }, + { + "columns": [ + { + "text": "Current", + "value": "current" + }, + { + "text": "Avg", + "value": "avg" + } + ], + "datasource": "$datasource", + "editable": true, + "error": false, + "fontSize": "100%", + "id": 2, + "isNew": true, + "links": [], + "pageSize": null, + "scroll": true, + "showHeader": true, + "sort": { + "col": 2, + "desc": true + }, + "span": 5, + "styles": [ + { + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "colorMode": "cell", + "colors": [ + "rgb(41, 170, 106)", + "rgba(239, 148, 21, 0.89)", + "rgba(239, 10, 10, 0.9)" + ], + "decimals": 1, + "pattern": "/.*/", + "thresholds": [ + "50", + "80" + ], + "type": "number", + "unit": "percent" + } + ], + "targets": [ + { + "application": { + "filter": "Zabbix server" + }, + "functions": [], + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "item": { + "filter": "/Zabbix busy/" + }, + "mode": 0, + "refId": "A" + } + ], + "title": "Zabbix processes", + "transform": "timeseries_aggregations", + "type": "table" + } + ], + "title": "Row" + }, + { + "title": "New row", + "height": "380", + "editable": true, + "collapse": false, + "panels": [ + { + "title": "Zabbix busy processes", + "error": false, + "span": 7.069277691711851, + "editable": true, + "type": "graph", + "isNew": true, + "id": 6, + "targets": [ + { + "refId": "A", + "mode": 0, + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "application": { + "filter": "Zabbix server" + }, + "item": { + "filter": "/Zabbix busy/" + }, + "functions": [] + } + ], + "datasource": "$datasource", + "renderer": "flot", + "yaxes": [ + { + "label": null, + "show": true, + "logBase": 1, + "min": null, + "max": null, + "format": "percent" + }, + { + "label": null, + "show": true, + "logBase": 1, + "min": null, + "max": null, + "format": "short" + } + ], + "xaxis": { + "show": true + }, + "grid": { + "threshold1": null, + "threshold2": null, + "threshold1Color": "rgba(216, 200, 27, 0.27)", + "threshold2Color": "rgba(234, 112, 112, 0.22)" + }, + "lines": true, + "fill": 0, + "linewidth": 2, + "points": false, + "pointradius": 5, + "bars": false, + "stack": false, + "percentage": false, + "legend": { + "show": true, + "values": false, + "min": false, + "max": false, + "current": false, + "total": false, + "avg": false, + "hideEmpty": true, + "hideZero": true, + "alignAsTable": true, + "rightSide": true + }, + "nullPointMode": "connected", + "steppedLine": false, + "tooltip": { + "value_type": "cumulative", + "shared": true, + "msResolution": false + }, + "timeFrom": null, + "timeShift": null, + "aliasColors": {}, + "seriesOverrides": [], + "links": [] + }, + { + "title": "Zabbix Queue", + "error": false, + "span": 4.930722308288148, + "editable": true, + "type": "graph", + "isNew": true, + "id": 7, + "targets": [ + { + "refId": "A", + "mode": 0, + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "application": { + "filter": "Zabbix server" + }, + "item": { + "filter": "Zabbix queue" + }, + "functions": [] + }, + { + "refId": "B", + "mode": 0, + "group": { + "filter": "Zabbix servers" + }, + "host": { + "filter": "Zabbix server" + }, + "application": { + "filter": "Zabbix server" + }, + "item": { + "filter": "/Values processed/" + }, + "functions": [] + } + ], + "datasource": "$datasource", + "renderer": "flot", + "yaxes": [ + { + "label": null, + "show": true, + "logBase": 1, + "min": null, + "max": null, + "format": "short" + }, + { + "label": null, + "show": true, + "logBase": 1, + "min": null, + "max": null, + "format": "short" + } + ], + "xaxis": { + "show": true + }, + "grid": { + "threshold1": null, + "threshold2": null, + "threshold1Color": "rgba(216, 200, 27, 0.27)", + "threshold2Color": "rgba(234, 112, 112, 0.22)" + }, + "lines": true, + "fill": 0, + "linewidth": 2, + "points": false, + "pointradius": 5, + "bars": false, + "stack": false, + "percentage": false, + "legend": { + "show": true, + "values": false, + "min": false, + "max": false, + "current": false, + "total": false, + "avg": false + }, + "nullPointMode": "connected", + "steppedLine": false, + "tooltip": { + "value_type": "cumulative", + "shared": true, + "msResolution": false + }, + "timeFrom": null, + "timeShift": null, + "aliasColors": {}, + "seriesOverrides": [], + "links": [] + } + ] + } + ], + "templating": { + "list": [ + { + "current": {}, + "hide": 0, + "label": "Zabbix Data Source", + "name": "datasource", + "options": [], + "query": "alexanderzobnin-zabbix-datasource", + "refresh": 1, + "regex": "", + "type": "datasource" + } + ] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": { + "refresh_intervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "time_options": [ + "5m", + "15m", + "1h", + "6h", + "12h", + "24h", + "2d", + "7d", + "30d" + ] + }, + "annotations": { + "list": [] + }, + "schemaVersion": 12, + "version": 7, + "links": [] +} diff --git a/dist/dashboards/zabbix_system_status.json b/dist/dashboards/zabbix_system_status.json index 1fa7c0387..0f14bc10c 100644 --- a/dist/dashboards/zabbix_system_status.json +++ b/dist/dashboards/zabbix_system_status.json @@ -1,370 +1,370 @@ -{ - "__inputs": [ - { - "name": "DS_NAME", - "type": "datasource", - "pluginId": "alexanderzobnin-zabbix-datasource" - } - ], - "title": "Zabbix System Status", - "revision": "1.0", - "annotations": { - "list": [] - }, - "editable": true, - "gnetId": null, - "graphTooltip": 0, - "hideControls": false, - "id": null, - "links": [], - "rows": [ - { - "collapse": false, - "height": 250, - "panels": [ - { - "columns": [], - "datasource": "${DS_NAME}", - "fontSize": "100%", - "id": 9, - "links": [], - "pageSize": null, - "scroll": true, - "showHeader": true, - "sort": { - "col": 0, - "desc": true - }, - "span": 12, - "styles": [ - { - "alias": "Time", - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "pattern": "Time", - "type": "date" - }, - { - "alias": "", - "colorMode": "cell", - "colors": [ - "rgba(45, 172, 121, 0.97)", - "rgba(45, 172, 121, 0.97)", - "#58140c" - ], - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "decimals": 0, - "pattern": "Disaster", - "thresholds": [ - "0", - "1" - ], - "type": "number", - "unit": "none" - }, - { - "alias": "", - "colorMode": "cell", - "colors": [ - "#99440a", - "rgba(45, 172, 121, 0.97)", - "#99440a" - ], - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "decimals": 0, - "pattern": "High", - "thresholds": [ - "0", - "1" - ], - "type": "number", - "unit": "short" - }, - { - "alias": "", - "colorMode": "cell", - "colors": [ - "rgba(50, 172, 45, 0.97)", - "rgba(45, 172, 121, 0.97)", - "#c15c17" - ], - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "decimals": 0, - "pattern": "Average", - "thresholds": [ - "0", - "1" - ], - "type": "number", - "unit": "short" - }, - { - "alias": "", - "colorMode": "cell", - "colors": [ - "rgba(50, 172, 45, 0.97)", - "rgba(45, 172, 121, 0.97)", - "#cca300" - ], - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "decimals": 0, - "pattern": "Warning", - "thresholds": [ - "0", - "1" - ], - "type": "number", - "unit": "short" - }, - { - "alias": "", - "colorMode": "cell", - "colors": [ - "rgba(50, 172, 45, 0.97)", - "rgba(45, 172, 121, 0.97)", - "#64b0c8" - ], - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "decimals": 0, - "pattern": "Information", - "thresholds": [ - "0", - "1" - ], - "type": "number", - "unit": "short" - }, - { - "alias": "", - "colorMode": "cell", - "colors": [ - "rgba(50, 172, 45, 0.97)", - "rgba(45, 172, 121, 0.97)", - "rgb(176, 176, 176)" - ], - "dateFormat": "YYYY-MM-DD HH:mm:ss", - "decimals": 0, - "pattern": "Not classified", - "thresholds": [ - "0", - "1" - ], - "type": "number", - "unit": "short" - }, - { - "alias": "", - "colorMode": null, - "colors": [ - "rgba(245, 54, 54, 0.9)", - "rgba(237, 129, 40, 0.89)", - "rgba(50, 172, 45, 0.97)" - ], - "decimals": 0, - "pattern": "/.*/", - "thresholds": [], - "type": "number", - "unit": "none" - } - ], - "targets": [ - { - "application": { - "filter": "" - }, - "functions": [], - "group": { - "filter": "/.*/" - }, - "host": { - "filter": "/.*/" - }, - "item": { - "filter": "" - }, - "mode": 4, - "triggers": { - "count": false, - "minSeverity": 0, - "acknowledged": 2 - }, - "refId": "A", - "target": "" - } - ], - "title": "System status", - "transform": "table", - "type": "table" - } - ], - "repeat": null, - "repeatIteration": null, - "repeatRowId": null, - "showTitle": false, - "title": "Dashboard Row", - "titleSize": "h6" - }, - { - "collapse": false, - "height": "150px", - "panels": [ - { - "cacheTimeout": null, - "colorBackground": true, - "colorValue": false, - "colors": [ - "rgba(50, 172, 45, 0.97)", - "rgba(16, 154, 113, 0.97)", - "#890f02" - ], - "datasource": "${DS_NAME}", - "format": "none", - "gauge": { - "maxValue": 100, - "minValue": 0, - "show": false, - "thresholdLabels": false, - "thresholdMarkers": true - }, - "id": 1, - "interval": null, - "links": [], - "mappingType": 1, - "mappingTypes": [ - { - "name": "value to text", - "value": 1 - }, - { - "name": "range to text", - "value": 2 - } - ], - "maxDataPoints": 100, - "minSpan": 2, - "nullPointMode": "connected", - "nullText": null, - "postfix": "", - "postfixFontSize": "50%", - "prefix": "", - "prefixFontSize": "50%", - "rangeMaps": [ - { - "from": "null", - "text": "N/A", - "to": "null" - } - ], - "repeat": "group", - "span": 2, - "sparkline": { - "fillColor": "rgba(31, 118, 189, 0.18)", - "full": false, - "lineColor": "rgb(31, 120, 193)", - "show": false - }, - "tableColumn": "", - "targets": [ - { - "application": { - "filter": "" - }, - "functions": [], - "group": { - "filter": "$group" - }, - "host": { - "filter": "/.*/" - }, - "item": { - "filter": "" - }, - "mode": 4, - "triggers": { - "count": true, - "minSeverity": 3, - "acknowledged": 2 - }, - "refId": "A", - "target": "" - } - ], - "thresholds": "0,1", - "title": "$group", - "type": "singlestat", - "valueFontSize": "120%", - "valueMaps": [ - { - "op": "=", - "text": "N/A", - "value": "null" - } - ], - "valueName": "avg" - } - ], - "repeat": null, - "repeatIteration": null, - "repeatRowId": null, - "showTitle": false, - "title": "Dashboard Row", - "titleSize": "h6" - } - ], - "schemaVersion": 14, - "style": "dark", - "tags": [], - "templating": { - "list": [ - { - "allValue": null, - "current": {}, - "datasource": "${DS_NAME}", - "hide": 0, - "includeAll": true, - "label": null, - "multi": true, - "name": "group", - "options": [], - "query": "*", - "refresh": 1, - "regex": "", - "sort": 0, - "tagValuesQuery": "", - "tags": [], - "tagsQuery": "", - "type": "query", - "useTags": false - } - ] - }, - "time": { - "from": "now-6h", - "to": "now" - }, - "timepicker": { - "refresh_intervals": [ - "5s", - "10s", - "30s", - "1m", - "5m", - "15m", - "30m", - "1h", - "2h", - "1d" - ], - "time_options": [ - "5m", - "15m", - "1h", - "6h", - "12h", - "24h", - "2d", - "7d", - "30d" - ] - }, - "timezone": "" -} +{ + "__inputs": [ + { + "name": "DS_NAME", + "type": "datasource", + "pluginId": "alexanderzobnin-zabbix-datasource" + } + ], + "title": "Zabbix System Status", + "revision": "1.0", + "annotations": { + "list": [] + }, + "editable": true, + "gnetId": null, + "graphTooltip": 0, + "hideControls": false, + "id": null, + "links": [], + "rows": [ + { + "collapse": false, + "height": 250, + "panels": [ + { + "columns": [], + "datasource": "${DS_NAME}", + "fontSize": "100%", + "id": 9, + "links": [], + "pageSize": null, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "span": 12, + "styles": [ + { + "alias": "Time", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "colorMode": "cell", + "colors": [ + "rgba(45, 172, 121, 0.97)", + "rgba(45, 172, 121, 0.97)", + "#58140c" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 0, + "pattern": "Disaster", + "thresholds": [ + "0", + "1" + ], + "type": "number", + "unit": "none" + }, + { + "alias": "", + "colorMode": "cell", + "colors": [ + "#99440a", + "rgba(45, 172, 121, 0.97)", + "#99440a" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 0, + "pattern": "High", + "thresholds": [ + "0", + "1" + ], + "type": "number", + "unit": "short" + }, + { + "alias": "", + "colorMode": "cell", + "colors": [ + "rgba(50, 172, 45, 0.97)", + "rgba(45, 172, 121, 0.97)", + "#c15c17" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 0, + "pattern": "Average", + "thresholds": [ + "0", + "1" + ], + "type": "number", + "unit": "short" + }, + { + "alias": "", + "colorMode": "cell", + "colors": [ + "rgba(50, 172, 45, 0.97)", + "rgba(45, 172, 121, 0.97)", + "#cca300" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 0, + "pattern": "Warning", + "thresholds": [ + "0", + "1" + ], + "type": "number", + "unit": "short" + }, + { + "alias": "", + "colorMode": "cell", + "colors": [ + "rgba(50, 172, 45, 0.97)", + "rgba(45, 172, 121, 0.97)", + "#64b0c8" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 0, + "pattern": "Information", + "thresholds": [ + "0", + "1" + ], + "type": "number", + "unit": "short" + }, + { + "alias": "", + "colorMode": "cell", + "colors": [ + "rgba(50, 172, 45, 0.97)", + "rgba(45, 172, 121, 0.97)", + "rgb(176, 176, 176)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 0, + "pattern": "Not classified", + "thresholds": [ + "0", + "1" + ], + "type": "number", + "unit": "short" + }, + { + "alias": "", + "colorMode": null, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 0, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "none" + } + ], + "targets": [ + { + "application": { + "filter": "" + }, + "functions": [], + "group": { + "filter": "/.*/" + }, + "host": { + "filter": "/.*/" + }, + "item": { + "filter": "" + }, + "mode": 4, + "triggers": { + "count": false, + "minSeverity": 0, + "acknowledged": 2 + }, + "refId": "A", + "target": "" + } + ], + "title": "System status", + "transform": "table", + "type": "table" + } + ], + "repeat": null, + "repeatIteration": null, + "repeatRowId": null, + "showTitle": false, + "title": "Dashboard Row", + "titleSize": "h6" + }, + { + "collapse": false, + "height": "150px", + "panels": [ + { + "cacheTimeout": null, + "colorBackground": true, + "colorValue": false, + "colors": [ + "rgba(50, 172, 45, 0.97)", + "rgba(16, 154, 113, 0.97)", + "#890f02" + ], + "datasource": "${DS_NAME}", + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "id": 1, + "interval": null, + "links": [], + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "minSpan": 2, + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "repeat": "group", + "span": 2, + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "targets": [ + { + "application": { + "filter": "" + }, + "functions": [], + "group": { + "filter": "$group" + }, + "host": { + "filter": "/.*/" + }, + "item": { + "filter": "" + }, + "mode": 4, + "triggers": { + "count": true, + "minSeverity": 3, + "acknowledged": 2 + }, + "refId": "A", + "target": "" + } + ], + "thresholds": "0,1", + "title": "$group", + "type": "singlestat", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + ], + "repeat": null, + "repeatIteration": null, + "repeatRowId": null, + "showTitle": false, + "title": "Dashboard Row", + "titleSize": "h6" + } + ], + "schemaVersion": 14, + "style": "dark", + "tags": [], + "templating": { + "list": [ + { + "allValue": null, + "current": {}, + "datasource": "${DS_NAME}", + "hide": 0, + "includeAll": true, + "label": null, + "multi": true, + "name": "group", + "options": [], + "query": "*", + "refresh": 1, + "regex": "", + "sort": 0, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + } + ] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": { + "refresh_intervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "time_options": [ + "5m", + "15m", + "1h", + "6h", + "12h", + "24h", + "2d", + "7d", + "30d" + ] + }, + "timezone": "" +} diff --git a/dist/datasource-zabbix/add-metric-function.directive.js.map b/dist/datasource-zabbix/add-metric-function.directive.js.map index 24912c031..3ec068f4d 100644 --- a/dist/datasource-zabbix/add-metric-function.directive.js.map +++ b/dist/datasource-zabbix/add-metric-function.directive.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/add-metric-function.directive.js"],"names":["getAllFunctionNames","categories","_","reduce","list","category","each","func","push","name","createFunctionDropDownMenu","map","text","submenu","value","click","angular","$","metricFunctions","module","directive","$compile","inputTemplate","buttonTemplate","link","$scope","elem","getCategories","allFunctions","functionMenu","$input","$button","appendTo","attr","typeahead","source","minLength","items","updater","funcDef","getFuncDef","toLowerCase","find","funcName","indexOf","$apply","addFunction","trigger","hide","show","focus","keyup","toggleClass","val","blur","setTimeout","removeClass","contents"],"mappings":";;;;;;;AAiFA,WAASA,mBAAT,CAA6BC,UAA7B,EAAyC;AACvC,WAAOC,EAAEC,MAAF,CAASF,UAAT,EAAqB,UAASG,IAAT,EAAeC,QAAf,EAAyB;AACnDH,QAAEI,IAAF,CAAOD,QAAP,EAAiB,UAASE,IAAT,EAAe;AAC9BH,aAAKI,IAAL,CAAUD,KAAKE,IAAf;AACD,OAFD;AAGA,aAAOL,IAAP;AACD,KALM,EAKJ,EALI,CAAP;AAMD;;AAED,WAASM,0BAAT,CAAoCT,UAApC,EAAgD;AAC9C,WAAOC,EAAES,GAAF,CAAMV,UAAN,EAAkB,UAASG,IAAT,EAAeC,QAAf,EAAyB;AAChD,aAAO;AACLO,cAAMP,QADD;AAELQ,iBAASX,EAAES,GAAF,CAAMP,IAAN,EAAY,UAASU,KAAT,EAAgB;AACnC,iBAAO;AACLF,kBAAME,MAAML,IADP;AAELM,mBAAO,uBAAuBD,MAAML,IAA7B,GAAoC;AAFtC,WAAP;AAID,SALQ;AAFJ,OAAP;AASD,KAVM,CAAP;AAWD;;;AAtGMO,a;;AACAd,O;;AACAe,O;;AACKC,qB;;;;AAEZ;AACAF,cACGG,MADH,CACU,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hB,KAAR,CAAc,YAAW;AACvBgB,sBAAQiB,IAAR;AACAlB,qBAAOmB,IAAP;AACAnB,qBAAOoB,KAAP;AACD,aAJD;;AAMApB,mBAAOqB,KAAP,CAAa,YAAW;AACtBzB,mBAAK0B,WAAL,CAAiB,MAAjB,EAAyBtB,OAAOuB,GAAP,OAAiB,EAA1C;AACD,aAFD;;AAIAvB,mBAAOwB,IAAP,CAAY,YAAW;AACrB;AACA;AACAC,yBAAW,YAAW;AACpBzB,uBAAOuB,GAAP,CAAW,EAAX;AACAvB,uBAAOkB,IAAP;AACAjB,wBAAQkB,IAAR;AACAvB,qBAAK8B,WAAL,CAAiB,MAAjB;AACD,eALD,EAKG,GALH;AAMD,aATD;;AAWAnC,qBAASK,KAAK+B,QAAL,EAAT,EAA0BhC,MAA1B;AACD;AA5DI,SAAP;AA8DD,OAzEH","file":"add-metric-function.directive.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport $ from 'jquery';\nimport * as metricFunctions from './metricFunctions';\n\n/** @ngInject */\nangular\n .module('grafana.directives')\n .directive('addMetricFunction', function($compile) {\n var inputTemplate = '';\n\n var buttonTemplate = '' +\n '';\n\n return {\n link: function($scope, elem) {\n var categories = metricFunctions.getCategories();\n var allFunctions = getAllFunctionNames(categories);\n\n $scope.functionMenu = createFunctionDropDownMenu(categories);\n\n var $input = $(inputTemplate);\n var $button = $(buttonTemplate);\n $input.appendTo(elem);\n $button.appendTo(elem);\n\n $input.attr('data-provide', 'typeahead');\n $input.typeahead({\n source: allFunctions,\n minLength: 1,\n items: 10,\n updater: function (value) {\n var funcDef = metricFunctions.getFuncDef(value);\n if (!funcDef) {\n // try find close match\n value = value.toLowerCase();\n funcDef = _.find(allFunctions, function(funcName) {\n return funcName.toLowerCase().indexOf(value) === 0;\n });\n\n if (!funcDef) { return; }\n }\n\n $scope.$apply(function() {\n $scope.addFunction(funcDef);\n });\n\n $input.trigger('blur');\n return '';\n }\n });\n\n $button.click(function() {\n $button.hide();\n $input.show();\n $input.focus();\n });\n\n $input.keyup(function() {\n elem.toggleClass('open', $input.val() === '');\n });\n\n $input.blur(function() {\n // clicking the function dropdown menu wont\n // work if you remove class at once\n setTimeout(function() {\n $input.val('');\n $input.hide();\n $button.show();\n elem.removeClass('open');\n }, 200);\n });\n\n $compile(elem.contents())($scope);\n }\n };\n });\n\nfunction getAllFunctionNames(categories) {\n return _.reduce(categories, function(list, category) {\n _.each(category, function(func) {\n list.push(func.name);\n });\n return list;\n }, []);\n}\n\nfunction createFunctionDropDownMenu(categories) {\n return _.map(categories, function(list, category) {\n return {\n text: category,\n submenu: _.map(list, function(value) {\n return {\n text: value.name,\n click: \"ctrl.addFunction('\" + value.name + \"')\",\n };\n })\n };\n });\n}\n\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/add-metric-function.directive.js"],"names":["getAllFunctionNames","categories","_","reduce","list","category","each","func","push","name","createFunctionDropDownMenu","map","text","submenu","value","click","angular","$","metricFunctions","module","directive","$compile","inputTemplate","buttonTemplate","link","$scope","elem","getCategories","allFunctions","functionMenu","$input","$button","appendTo","attr","typeahead","source","minLength","items","updater","funcDef","getFuncDef","toLowerCase","find","funcName","indexOf","$apply","addFunction","trigger","hide","show","focus","keyup","toggleClass","val","blur","setTimeout","removeClass","contents"],"mappings":";;;;;;;AAiFA,WAASA,mBAAT,CAA6BC,UAA7B,EAAyC;AACvC,WAAOC,EAAEC,MAAF,CAASF,UAAT,EAAqB,UAASG,IAAT,EAAeC,QAAf,EAAyB;AACnDH,QAAEI,IAAF,CAAOD,QAAP,EAAiB,UAASE,IAAT,EAAe;AAC9BH,aAAKI,IAAL,CAAUD,KAAKE,IAAf;AACD,OAFD;AAGA,aAAOL,IAAP;AACD,KALM,EAKJ,EALI,CAAP;AAMD;;AAED,WAASM,0BAAT,CAAoCT,UAApC,EAAgD;AAC9C,WAAOC,EAAES,GAAF,CAAMV,UAAN,EAAkB,UAASG,IAAT,EAAeC,QAAf,EAAyB;AAChD,aAA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WAAT,GAAuBG,OAAvB,CAA+B9B,KAA/B,MAA0C,CAAjD;AACD,mBAFS,CAAV;;AAIA,sBAAI,CAACyB,OAAL,EAAc;AAAE;AAAS;AAC1B;;AAEDd,uBAAOoB,MAAP,CAAc,YAAW;AACvBpB,yBAAOqB,WAAP,CAAmBP,OAAnB;AACD,iBAFD;;AAIAT,uBAAOiB,OAAP,CAAe,MAAf;AACA,uBAAO,EAAP;AACD;AAtBc,aAAjB;;AAyBAhB,oBAAQhB,KAAR,CAAc,YAAW;AACvBgB,sBAAQiB,IAAR;AACAlB,qBAAOmB,IAAP;AACAnB,qBAAOoB,KAAP;AACD,aAJD;;AAMApB,mBAAOqB,KAAP,CAAa,YAAW;AACtBzB,mBAAK0B,WAAL,CAAiB,MAAjB,EAAyBtB,OAAOuB,GAAP,OAAiB,EAA1C;AACD,aAFD;;AAIAvB,mBAAOwB,IAAP,CAAY,YAAW;AACrB;AACA;AACAC,yBAAW,YAAW;AACpBzB,uBAAOuB,GAAP,CAAW,EAAX;AACAvB,uBAAOkB,IAAP;AACAjB,wBAAQkB,IAAR;AACAvB,qBAAK8B,WAAL,CAAiB,MAAjB;AACD,eALD,EAKG,GALH;AAMD,aATD;;AAWAnC,qBAASK,KAAK+B,QAAL,EAAT,EAA0BhC,MAA1B;AACD;AA5DI,SAAP;AA8DD,OAzEH","file":"add-metric-function.directive.js","sourcesContent":["import angular from 'angular';\r\nimport _ from 'lodash';\r\nimport $ from 'jquery';\r\nimport * as metricFunctions from './metricFunctions';\r\n\r\n/** @ngInject */\r\nangular\r\n .module('grafana.directives')\r\n .directive('addMetricFunction', function($compile) {\r\n var inputTemplate = '';\r\n\r\n var buttonTemplate = '' +\r\n '';\r\n\r\n return {\r\n link: function($scope, elem) {\r\n var categories = metricFunctions.getCategories();\r\n var allFunctions = getAllFunctionNames(categories);\r\n\r\n $scope.functionMenu = createFunctionDropDownMenu(categories);\r\n\r\n var $input = $(inputTemplate);\r\n var $button = $(buttonTemplate);\r\n $input.appendTo(elem);\r\n $button.appendTo(elem);\r\n\r\n $input.attr('data-provide', 'typeahead');\r\n $input.typeahead({\r\n source: allFunctions,\r\n minLength: 1,\r\n items: 10,\r\n updater: function (value) {\r\n var funcDef = metricFunctions.getFuncDef(value);\r\n if (!funcDef) {\r\n // try find close match\r\n value = value.toLowerCase();\r\n funcDef = _.find(allFunctions, function(funcName) {\r\n return funcName.toLowerCase().indexOf(value) === 0;\r\n });\r\n\r\n if (!funcDef) { return; }\r\n }\r\n\r\n $scope.$apply(function() {\r\n $scope.addFunction(funcDef);\r\n });\r\n\r\n $input.trigger('blur');\r\n return '';\r\n }\r\n });\r\n\r\n $button.click(function() {\r\n $button.hide();\r\n $input.show();\r\n $input.focus();\r\n });\r\n\r\n $input.keyup(function() {\r\n elem.toggleClass('open', $input.val() === '');\r\n });\r\n\r\n $input.blur(function() {\r\n // clicking the function dropdown menu wont\r\n // work if you remove class at once\r\n setTimeout(function() {\r\n $input.val('');\r\n $input.hide();\r\n $button.show();\r\n elem.removeClass('open');\r\n }, 200);\r\n });\r\n\r\n $compile(elem.contents())($scope);\r\n }\r\n };\r\n });\r\n\r\nfunction getAllFunctionNames(categories) {\r\n return _.reduce(categories, function(list, category) {\r\n _.each(category, function(func) {\r\n list.push(func.name);\r\n });\r\n return list;\r\n }, []);\r\n}\r\n\r\nfunction createFunctionDropDownMenu(categories) {\r\n return _.map(categories, function(list, category) {\r\n return {\r\n text: category,\r\n submenu: _.map(list, function(value) {\r\n return {\r\n text: value.name,\r\n click: \"ctrl.addFunction('\" + value.name + \"')\",\r\n };\r\n })\r\n };\r\n });\r\n}\r\n\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/benchmarks/timeseries_bench.js b/dist/datasource-zabbix/benchmarks/timeseries_bench.js index 857af9b94..9d315d2c8 100644 --- a/dist/datasource-zabbix/benchmarks/timeseries_bench.js +++ b/dist/datasource-zabbix/benchmarks/timeseries_bench.js @@ -1,70 +1,70 @@ -import _ from 'lodash'; -import ts from '../timeseries'; - -let datapoints = [[10.7104, 1498409636085], [10.578, 1498409651011], [10.5985, 1498409666628], [10.6877, 1498409681525], [10.5495, 1498409696586], [10.5981, 1498409711009], [10.5076, 1498409726949], [11.4807, 1498409741853], [11.6165, 1498409756165], [11.8575, 1498409771018], [11.9936, 1498409786056], [10.7566, 1498409801942], [10.7484, 1498409816010], [10.6038, 1498409831018], [10.2932, 1498409846010], [10.4912, 1498409861946], [10.4151, 1498409876871], [10.2401, 1498409891710], [10.4921, 1498409906143], [10.4413, 1498409921477], [10.6318, 1498409936147], [10.5277, 1498409951915], [10.6333, 1498409966052], [10.6417, 1498409981944], [10.4505, 1498409996867], [10.5812, 1498410011770], [10.4934, 1498410026573], [10.5731, 1498410041317], [10.5, 1498410056213], [10.6505, 1498410071013], [9.4035, 1498410086387]]; - -let series_set = [ - [[1.0247, 1498409631773], [0.9988, 1498409646697], [0.9817, 1498409661239], [0.9569, 1498409676045], [1.0331, 1498409691922], [1.0755, 1498409706546], [1.1862, 1498409721525], [1.2984, 1498409736175], [1.2389, 1498409751817], [1.1452, 1498409766783], [1.102, 1498409781699], [0.9647, 1498409796664], [1.0063, 1498409811627], [1.0318, 1498409826887], [1.065, 1498409841645], [1.0907, 1498409856647], [1.0229, 1498409871521], [1.0654, 1498409886031], [1.0568, 1498409901544], [1.0818, 1498409916194], [1.1335, 1498409931672], [1.057, 1498409946673], [1.0243, 1498409961669], [1.0329, 1498409976637], [1.1428, 1498409991563], [1.2198, 1498410006441], [1.2192, 1498410021230], [1.2615, 1498410036027], [1.1765, 1498410051907], [1.2352, 1498410066109], [1.0557, 1498410081043]], - [[10.7104, 1498409636085], [10.578, 1498409651011], [10.5985, 1498409666628], [10.6877, 1498409681525], [10.5495, 1498409696586], [10.5981, 1498409711009], [10.5076, 1498409726949], [11.4807, 1498409741853], [11.6165, 1498409756165], [11.8575, 1498409771018], [11.9936, 1498409786056], [10.7566, 1498409801942], [10.7484, 1498409816010], [10.6038, 1498409831018], [10.2932, 1498409846010], [10.4912, 1498409861946], [10.4151, 1498409876871], [10.2401, 1498409891710], [10.4921, 1498409906143], [10.4413, 1498409921477], [10.6318, 1498409936147], [10.5277, 1498409951915], [10.6333, 1498409966052], [10.6417, 1498409981944], [10.4505, 1498409996867], [10.5812, 1498410011770], [10.4934, 1498410026573], [10.5731, 1498410041317], [10.5, 1498410056213], [10.6505, 1498410071013], [9.4035, 1498410086387]] -]; - -let growing_series = [[10755200, 1498332216642], [10761200, 1498332276802], [10767200, 1498332336367], [10773200, 1498332396584], [10779200, 1498332456880], [10785200, 1498332516479], [10791200, 1498332576610], [10797200, 1498332636353], [10803200, 1498332696513], [10809200, 1498332756884], [10815200, 1498332816890], [10821200, 1498332876305], [10827200, 1498332936384], [10833200, 1498332996659], [10839200, 1498333056965], [10845200, 1498333116748], [10851200, 1498333176687], [10857200, 1498333236646], [10863200, 1498333297034], [10869200, 1498333356358], [10875200, 1498333416445], [4800, 1498333536686], [17900, 1498333667962], [24000, 1498333729157], [29500, 1498333783662], [34800, 1498333836813], [40700, 1498333896403], [46800, 1498333956953], [52800, 1498334016976], [6000, 1498334136593], [12000, 1498334196567]]; - -module.exports = [ - { - name: 'groupBy', - tests: { - 'groupBy(AVERAGE)': () => { - ts.groupBy(datapoints, '5m', ts.AVERAGE); - }, - 'groupBy(MAX)': () => { - ts.groupBy(datapoints, '5m', ts.COUNT); - } - } - }, - { - name: 'sumSeries', - tests: { - 'sumSeries()': () => { - ts.sumSeries(series_set); - }, - 'groupBy(MAX)->sumSeries()': () => { - let prepeared_series = _.map(series_set, datapoints => ts.groupBy(datapoints, '5m', ts.MAX)); - ts.sumSeries(prepeared_series); - } - } - }, - { - name: 'delta vs rate', - tests: { - 'delta()': () => { - ts.delta(growing_series); - }, - 'rate()': () => { - ts.rate(growing_series); - } - } - }, - { - name: 'scale', - tests: { - 'scale()': () => { - ts.scale(datapoints, 42); - }, - 'scale_perf()': () => { - ts.scale_perf(datapoints, 42); - } - } - }, - { - name: 'groupBy vs groupBy_perf', - tests: { - 'groupBy()': () => { - ts.groupBy(datapoints, '5m', ts.AVERAGE); - }, - 'groupBy_perf()': () => { - ts.groupBy_perf(datapoints, '5m', ts.AVERAGE); - } - } - } -]; +import _ from 'lodash'; +import ts from '../timeseries'; + +let datapoints = [[10.7104, 1498409636085], [10.578, 1498409651011], [10.5985, 1498409666628], [10.6877, 1498409681525], [10.5495, 1498409696586], [10.5981, 1498409711009], [10.5076, 1498409726949], [11.4807, 1498409741853], [11.6165, 1498409756165], [11.8575, 1498409771018], [11.9936, 1498409786056], [10.7566, 1498409801942], [10.7484, 1498409816010], [10.6038, 1498409831018], [10.2932, 1498409846010], [10.4912, 1498409861946], [10.4151, 1498409876871], [10.2401, 1498409891710], [10.4921, 1498409906143], [10.4413, 1498409921477], [10.6318, 1498409936147], [10.5277, 1498409951915], [10.6333, 1498409966052], [10.6417, 1498409981944], [10.4505, 1498409996867], [10.5812, 1498410011770], [10.4934, 1498410026573], [10.5731, 1498410041317], [10.5, 1498410056213], [10.6505, 1498410071013], [9.4035, 1498410086387]]; + +let series_set = [ + [[1.0247, 1498409631773], [0.9988, 1498409646697], [0.9817, 1498409661239], [0.9569, 1498409676045], [1.0331, 1498409691922], [1.0755, 1498409706546], [1.1862, 1498409721525], [1.2984, 1498409736175], [1.2389, 1498409751817], [1.1452, 1498409766783], [1.102, 1498409781699], [0.9647, 1498409796664], [1.0063, 1498409811627], [1.0318, 1498409826887], [1.065, 1498409841645], [1.0907, 1498409856647], [1.0229, 1498409871521], [1.0654, 1498409886031], [1.0568, 1498409901544], [1.0818, 1498409916194], [1.1335, 1498409931672], [1.057, 1498409946673], [1.0243, 1498409961669], [1.0329, 1498409976637], [1.1428, 1498409991563], [1.2198, 1498410006441], [1.2192, 1498410021230], [1.2615, 1498410036027], [1.1765, 1498410051907], [1.2352, 1498410066109], [1.0557, 1498410081043]], + [[10.7104, 1498409636085], [10.578, 1498409651011], [10.5985, 1498409666628], [10.6877, 1498409681525], [10.5495, 1498409696586], [10.5981, 1498409711009], [10.5076, 1498409726949], [11.4807, 1498409741853], [11.6165, 1498409756165], [11.8575, 1498409771018], [11.9936, 1498409786056], [10.7566, 1498409801942], [10.7484, 1498409816010], [10.6038, 1498409831018], [10.2932, 1498409846010], [10.4912, 1498409861946], [10.4151, 1498409876871], [10.2401, 1498409891710], [10.4921, 1498409906143], [10.4413, 1498409921477], [10.6318, 1498409936147], [10.5277, 1498409951915], [10.6333, 1498409966052], [10.6417, 1498409981944], [10.4505, 1498409996867], [10.5812, 1498410011770], [10.4934, 1498410026573], [10.5731, 1498410041317], [10.5, 1498410056213], [10.6505, 1498410071013], [9.4035, 1498410086387]] +]; + +let growing_series = [[10755200, 1498332216642], [10761200, 1498332276802], [10767200, 1498332336367], [10773200, 1498332396584], [10779200, 1498332456880], [10785200, 1498332516479], [10791200, 1498332576610], [10797200, 1498332636353], [10803200, 1498332696513], [10809200, 1498332756884], [10815200, 1498332816890], [10821200, 1498332876305], [10827200, 1498332936384], [10833200, 1498332996659], [10839200, 1498333056965], [10845200, 1498333116748], [10851200, 1498333176687], [10857200, 1498333236646], [10863200, 1498333297034], [10869200, 1498333356358], [10875200, 1498333416445], [4800, 1498333536686], [17900, 1498333667962], [24000, 1498333729157], [29500, 1498333783662], [34800, 1498333836813], [40700, 1498333896403], [46800, 1498333956953], [52800, 1498334016976], [6000, 1498334136593], [12000, 1498334196567]]; + +module.exports = [ + { + name: 'groupBy', + tests: { + 'groupBy(AVERAGE)': () => { + ts.groupBy(datapoints, '5m', ts.AVERAGE); + }, + 'groupBy(MAX)': () => { + ts.groupBy(datapoints, '5m', ts.COUNT); + } + } + }, + { + name: 'sumSeries', + tests: { + 'sumSeries()': () => { + ts.sumSeries(series_set); + }, + 'groupBy(MAX)->sumSeries()': () => { + let prepeared_series = _.map(series_set, datapoints => ts.groupBy(datapoints, '5m', ts.MAX)); + ts.sumSeries(prepeared_series); + } + } + }, + { + name: 'delta vs rate', + tests: { + 'delta()': () => { + ts.delta(growing_series); + }, + 'rate()': () => { + ts.rate(growing_series); + } + } + }, + { + name: 'scale', + tests: { + 'scale()': () => { + ts.scale(datapoints, 42); + }, + 'scale_perf()': () => { + ts.scale_perf(datapoints, 42); + } + } + }, + { + name: 'groupBy vs groupBy_perf', + tests: { + 'groupBy()': () => { + ts.groupBy(datapoints, '5m', ts.AVERAGE); + }, + 'groupBy_perf()': () => { + ts.groupBy_perf(datapoints, '5m', ts.AVERAGE); + } + } + } +]; diff --git a/dist/datasource-zabbix/config.controller.js.map b/dist/datasource-zabbix/config.controller.js.map index 6f2361867..18da935a3 100644 --- a/dist/datasource-zabbix/config.controller.js.map +++ b/dist/datasource-zabbix/config.controller.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/config.controller.js"],"names":["_","SUPPORTED_SQL_DS","defaultConfig","dbConnection","enable","ZabbixDSConfigController","$scope","$injector","datasourceSrv","defaults","current","jsonData","sqlDataSources","getSupportedSQLDataSources","datasources","getAll","filter","includes","ds","type","templateUrl"],"mappings":";;;;;;;;;;;;;;;AAAOA,O;;;;;;;;;;;;;;;;;;;;;AAEDC,sB,GAAmB,CAAC,OAAD,EAAU,UAAV,C;AAEnBC,mB,GAAgB;AACpBC,sBAAc;AACZC,kBAAQ;AADI;AADM,O;;0CAMTC,wB;AACX;AACA,0CAAYC,MAAZ,EAAoBC,SAApB,EAA+BC,aAA/B,EAA8C;AAAA;;AAC5C,eAAKA,aAAL,GAAqBA,aAArB;;AAEAR,YAAES,QAAF,CAAW,KAAKC,OAAL,CAAaC,QAAxB,EAAkCT,aAAlC;AACA,eAAKU,cAAL,GAAsB,KAAKC,0BAAL,EAAtB;AACD;;;;uDAE4B;AAC3B,gBAAIC,cAAc,KAAKN,aAAL,CAAmBO,MAAnB,EAAlB;AACA,mBAAOf,EAAEgB,MAAF,CAASF,WAAT,EAAsB,cAAM;AACjC,qBAAOd,EAAEiB,QAAF,CAAWhB,gBAAX,EAA6BiB,GAAGC,IAAhC,CAAP;AACD,aAFM,CAAP;AAGD;;;;;;;;AAGHd,+BAAyBe,WAAzB,GAAuC,wCAAvC","file":"config.controller.js","sourcesContent":["import _ from 'lodash';\n\nconst SUPPORTED_SQL_DS = ['mysql', 'postgres'];\n\nconst defaultConfig = {\n dbConnection: {\n enable: false,\n }\n};\n\nexport class ZabbixDSConfigController {\n /** @ngInject */\n constructor($scope, $injector, datasourceSrv) {\n this.datasourceSrv = datasourceSrv;\n\n _.defaults(this.current.jsonData, defaultConfig);\n this.sqlDataSources = this.getSupportedSQLDataSources();\n }\n\n getSupportedSQLDataSources() {\n let datasources = this.datasourceSrv.getAll();\n return _.filter(datasources, ds => {\n return _.includes(SUPPORTED_SQL_DS, ds.type);\n });\n }\n}\n\nZabbixDSConfigController.templateUrl = 'datasource-zabbix/partials/config.html';\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/config.controller.js"],"names":["_","SUPPORTED_SQL_DS","defaultConfig","dbConnection","enable","ZabbixDSConfigController","$scope","$injector","datasourceSrv","defaults","current","jsonData","sqlDataSources","getSupportedSQLDataSources","datasources","getAll","filter","includes","ds","type","templateUrl"],"mappings":";;;;;;;;;;;;;;;AAAOA,O;;;;;;;;;;;;;;;;;;;;;AAEDC,sB,GAAmB,CAAC,OAAD,EAAU,UAAV,C;AAEnBC,mB,GAAgB;AACpBC,sBAAc;AACZC,kBAAQ;AADI;AADM,O;;0CAMTC,wB;AACX;AACA,0CAAYC,MAAZ,EAAoBC,SAApB,EAA+BC,aAA/B,EAA8C;AAAA;;AAC5C,eAAKA,aAAL,GAAqBA,aAArB;;AAEAR,YAAES,QAAF,CAAW,KAAKC,OAAL,CAAaC,QAAxB,EAAkCT,aAAlC;AACA,eAAKU,cAAL,GAAsB,KAAKC,0BAAL,EAAtB;AACD;;;;uDAE4B;AAC3B,gBAAIC,cAAc,KAAKN,aAAL,CAAmBO,MAAnB,EAAlB;AACA,mBAAOf,EAAEgB,MAAF,CAASF,WAAT,EAAsB,cAAM;AACjC,qBAAOd,EAAEiB,QAAF,CAAWhB,gBAAX,EAA6BiB,GAAGC,IAAhC,CAAP;AACD,aAFM,CAAP;AAGD;;;;;;;;AAGHd,+BAAyBe,WAAzB,GAAuC,wCAAvC","file":"config.controller.js","sourcesContent":["import _ from 'lodash';\r\n\r\nconst SUPPORTED_SQL_DS = ['mysql', 'postgres'];\r\n\r\nconst defaultConfig = {\r\n dbConnection: {\r\n enable: false,\r\n }\r\n};\r\n\r\nexport class ZabbixDSConfigController {\r\n /** @ngInject */\r\n constructor($scope, $injector, datasourceSrv) {\r\n this.datasourceSrv = datasourceSrv;\r\n\r\n _.defaults(this.current.jsonData, defaultConfig);\r\n this.sqlDataSources = this.getSupportedSQLDataSources();\r\n }\r\n\r\n getSupportedSQLDataSources() {\r\n let datasources = this.datasourceSrv.getAll();\r\n return _.filter(datasources, ds => {\r\n return _.includes(SUPPORTED_SQL_DS, ds.type);\r\n });\r\n }\r\n}\r\n\r\nZabbixDSConfigController.templateUrl = 'datasource-zabbix/partials/config.html';\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/constants.js.map b/dist/datasource-zabbix/constants.js.map index 523a895c9..1cc7f6e9d 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","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","TRIGGER_SEVERITY","val","text"],"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;;;;kCAEfC,gB,GAAmB,CAC9B,EAACC,KAAK,CAAN,EAASC,MAAM,gBAAf,EAD8B,EAE9B,EAACD,KAAK,CAAN,EAASC,MAAM,aAAf,EAF8B,EAG9B,EAACD,KAAK,CAAN,EAASC,MAAM,SAAf,EAH8B,EAI9B,EAACD,KAAK,CAAN,EAASC,MAAM,SAAf,EAJ8B,EAK9B,EAACD,KAAK,CAAN,EAASC,MAAM,MAAf,EAL8B,EAM9B,EAACD,KAAK,CAAN,EAASC,MAAM,UAAf,EAN8B,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\nexport const TRIGGER_SEVERITY = [\n {val: 0, text: 'Not classified'},\n {val: 1, text: 'Information'},\n {val: 2, text: 'Warning'},\n {val: 3, text: 'Average'},\n {val: 4, text: 'High'},\n {val: 5, text: 'Disaster'}\n];\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","TRIGGER_SEVERITY","val","text"],"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;;;;kCAEfC,gB,GAAmB,CAC9B,EAACC,KAAK,CAAN,EAASC,MAAM,gBAAf,EAD8B,EAE9B,EAACD,KAAK,CAAN,EAASC,MAAM,aAAf,EAF8B,EAG9B,EAACD,KAAK,CAAN,EAASC,MAAM,SAAf,EAH8B,EAI9B,EAACD,KAAK,CAAN,EAASC,MAAM,SAAf,EAJ8B,EAK9B,EAACD,KAAK,CAAN,EAASC,MAAM,MAAf,EAL8B,EAM9B,EAACD,KAAK,CAAN,EAASC,MAAM,UAAf,EAN8B,C","file":"constants.js","sourcesContent":["// Editor modes\r\nexport const MODE_METRICS = 0;\r\nexport const MODE_ITSERVICE = 1;\r\nexport const MODE_TEXT = 2;\r\nexport const MODE_ITEMID = 3;\r\nexport const MODE_TRIGGERS = 4;\r\n\r\n// Triggers severity\r\nexport const SEV_NOT_CLASSIFIED = 0;\r\nexport const SEV_INFORMATION = 1;\r\nexport const SEV_WARNING = 2;\r\nexport const SEV_AVERAGE = 3;\r\nexport const SEV_HIGH = 4;\r\nexport const SEV_DISASTER = 5;\r\n\r\nexport const SHOW_ALL_TRIGGERS = [0, 1];\r\nexport const SHOW_ALL_EVENTS = [0, 1];\r\nexport const SHOW_OK_EVENTS = 1;\r\n\r\n// Data point\r\nexport const DATAPOINT_VALUE = 0;\r\nexport const DATAPOINT_TS = 1;\r\n\r\nexport const TRIGGER_SEVERITY = [\r\n {val: 0, text: 'Not classified'},\r\n {val: 1, text: 'Information'},\r\n {val: 2, text: 'Warning'},\r\n {val: 3, text: 'Average'},\r\n {val: 4, text: 'High'},\r\n {val: 5, text: 'Disaster'}\r\n];\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/dataProcessor.js b/dist/datasource-zabbix/dataProcessor.js index b8304de06..47a2ce815 100644 --- a/dist/datasource-zabbix/dataProcessor.js +++ b/dist/datasource-zabbix/dataProcessor.js @@ -21,6 +21,24 @@ System.register(['lodash', './utils', './timeseries'], function (_export, _conte } } + function removeAboveValue(n, datapoints) { + return _.map(datapoints, function (point) { + return [point[0] > n ? null : point[0], point[1]]; + }); + } + + function removeBelowValue(n, datapoints) { + return _.map(datapoints, function (point) { + return [point[0] < n ? null : point[0], point[1]]; + }); + } + + function transformNull(n, datapoints) { + return _.map(datapoints, function (point) { + return [point[0] !== null ? point[0] : n, point[1]]; + }); + } + function sortSeries(direction, timeseries) { return _.orderBy(timeseries, [function (ts) { return ts.target.toLowerCase(); @@ -142,6 +160,7 @@ System.register(['lodash', './utils', './timeseries'], function (_export, _conte rate: rate, movingAverage: simpleMovingAverage, exponentialMovingAverage: expMovingAverage, + transformNull: transformNull, aggregateBy: aggregateByWrapper, // Predefined aggs percentil: percentil, @@ -152,6 +171,8 @@ System.register(['lodash', './utils', './timeseries'], function (_export, _conte sum: _.partial(aggregateWrapper, SUM), count: _.partial(aggregateWrapper, COUNT), sumSeries: sumSeries, + removeAboveValue: removeAboveValue, + removeBelowValue: removeBelowValue, top: _.partial(limit, 'top'), bottom: _.partial(limit, 'bottom'), sortSeries: sortSeries, diff --git a/dist/datasource-zabbix/dataProcessor.js.map b/dist/datasource-zabbix/dataProcessor.js.map index 4bed20313..69fcde956 100644 --- a/dist/datasource-zabbix/dataProcessor.js.map +++ b/dist/datasource-zabbix/dataProcessor.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/dataProcessor.js"],"names":["limit","order","n","orderByFunc","timeseries","orderByCallback","aggregationFunctions","sortByIteratee","ts","values","_","map","datapoints","point","sortedTimeseries","sortBy","slice","sortSeries","direction","orderBy","target","toLowerCase","setAlias","alias","replaceAlias","regexp","newAlias","pattern","utils","isRegex","buildRegex","replace","setAliasByRegex","extractText","str","extractPattern","RegExp","extractedValue","exec","groupByWrapper","interval","groupFunc","groupByCallback","groupBy","aggregateByWrapper","aggregateFunc","flattenedPoints","flatten","sortedPoints","sortByTime","aggregateWrapper","percentil","partial","PERCENTIL","timeShift","range","shift","parseTimeShiftInterval","time","unShiftTimeSeries","unshift","dp","downsampleSeries","downsample","groupBy_perf","groupBy_exported","sumSeries","delta","rate","scale","factor","scale_perf","simpleMovingAverage","expMovingAverage","a","SUM","COUNT","AVERAGE","MIN","MAX","MEDIAN","metricFunctions","movingAverage","exponentialMovingAverage","aggregateBy","average","min","max","median","sum","count","top","bottom","avg"],"mappings":";;;;;;;AAsBA,WAASA,KAAT,CAAeC,KAAf,EAAsBC,CAAtB,EAAyBC,WAAzB,EAAsCC,UAAtC,EAAkD;AAChD,QAAIC,kBAAkBC,qBAAqBH,WAArB,CAAtB;AACA,QAAII,iBAAiB,SAAjBA,cAAiB,CAACC,EAAD,EAAQ;AAC3B,UAAIC,SAASC,EAAEC,GAAF,CAAMH,GAAGI,UAAT,EAAqB,UAACC,KAAD,EAAW;AAC3C,eAAOA,MAAM,CAAN,CAAP;AACD,OAFY,C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GAHoB;AAIzBS,gBAAQR,MAJiB;AAKzBS,aAAKd,GALoB;AAMzBe,eAAOd;AANkB,O;;yBASZ;AACbd,0BAAkBA,gBADL;AAEbnB,iBAASsB,gBAFI;AAGbY,iBAASA,OAHI;AAIbC,aAAKA,GAJQ;AAKbC,aAAKA,GALQ;AAMbC,gBAAQA,MANK;AAObL,aAAKA,GAPQ;AAQbC,eAAOA,KARM;AASbjB,2BAAmBA,iBATN;;AAWb,YAAIrD,oBAAJ,GAA2B;AACzB,iBAAOA,oBAAP;AACD,SAbY;;AAeb,YAAI2E,eAAJ,GAAsB;AACpB,iBAAOA,eAAP;AACD;AAjBY,O","file":"dataProcessor.js","sourcesContent":["import _ from 'lodash';\nimport * as utils from './utils';\nimport ts from './timeseries';\n\nlet downsampleSeries = ts.downsample;\nlet groupBy = ts.groupBy_perf;\nlet groupBy_exported = (interval, groupFunc, datapoints) => groupBy(datapoints, interval, groupFunc);\nlet sumSeries = ts.sumSeries;\nlet delta = ts.delta;\nlet rate = ts.rate;\nlet scale = (factor, datapoints) => ts.scale_perf(datapoints, factor);\nlet simpleMovingAverage = (n, datapoints) => ts.simpleMovingAverage(datapoints, n);\nlet expMovingAverage = (a, datapoints) => ts.expMovingAverage(datapoints, a);\n\nlet SUM = ts.SUM;\nlet COUNT = ts.COUNT;\nlet AVERAGE = ts.AVERAGE;\nlet MIN = ts.MIN;\nlet MAX = ts.MAX;\nlet MEDIAN = ts.MEDIAN;\nlet PERCENTIL = ts.PERCENTIL;\n\nfunction limit(order, n, orderByFunc, timeseries) {\n let orderByCallback = aggregationFunctions[orderByFunc];\n let sortByIteratee = (ts) => {\n let values = _.map(ts.datapoints, (point) => {\n return point[0];\n });\n return orderByCallback(values);\n };\n let sortedTimeseries = _.sortBy(timeseries, sortByIteratee);\n if (order === 'bottom') {\n return sortedTimeseries.slice(0, n);\n } else {\n return sortedTimeseries.slice(-n);\n }\n}\n\nfunction sortSeries(direction, timeseries) {\n return _.orderBy(timeseries, [function (ts) {\n return ts.target.toLowerCase();\n }], direction);\n}\n\nfunction setAlias(alias, timeseries) {\n timeseries.target = alias;\n return timeseries;\n}\n\nfunction replaceAlias(regexp, newAlias, timeseries) {\n let pattern;\n if (utils.isRegex(regexp)) {\n pattern = utils.buildRegex(regexp);\n } else {\n pattern = regexp;\n }\n\n let alias = timeseries.target.replace(pattern, newAlias);\n timeseries.target = alias;\n return timeseries;\n}\n\nfunction setAliasByRegex(alias, timeseries) {\n timeseries.target = extractText(timeseries.target, alias);\n return timeseries;\n}\n\nfunction extractText(str, pattern) {\n var extractPattern = new RegExp(pattern);\n var extractedValue = extractPattern.exec(str);\n extractedValue = extractedValue[0];\n return extractedValue;\n}\n\nfunction groupByWrapper(interval, groupFunc, datapoints) {\n var groupByCallback = aggregationFunctions[groupFunc];\n return groupBy(datapoints, interval, groupByCallback);\n}\n\nfunction aggregateByWrapper(interval, aggregateFunc, datapoints) {\n // Flatten all points in frame and then just use groupBy()\n const flattenedPoints = _.flatten(datapoints, true);\n // groupBy_perf works with sorted series only\n const sortedPoints = ts.sortByTime(flattenedPoints);\n let groupByCallback = aggregationFunctions[aggregateFunc];\n return groupBy(sortedPoints, interval, groupByCallback);\n}\n\nfunction aggregateWrapper(groupByCallback, interval, datapoints) {\n var flattenedPoints = _.flatten(datapoints, true);\n return groupBy(flattenedPoints, interval, groupByCallback);\n}\n\nfunction percentil(interval, n, datapoints) {\n var flattenedPoints = _.flatten(datapoints, true);\n var groupByCallback = _.partial(PERCENTIL, n);\n return groupBy(flattenedPoints, interval, groupByCallback);\n}\n\nfunction timeShift(interval, range) {\n let shift = utils.parseTimeShiftInterval(interval) / 1000;\n return _.map(range, time => {\n return time - shift;\n });\n}\n\nfunction unShiftTimeSeries(interval, datapoints) {\n let unshift = utils.parseTimeShiftInterval(interval);\n return _.map(datapoints, dp => {\n return [\n dp[0],\n dp[1] + unshift\n ];\n });\n}\n\nlet metricFunctions = {\n groupBy: groupByWrapper,\n scale: scale,\n delta: delta,\n rate: rate,\n movingAverage: simpleMovingAverage,\n exponentialMovingAverage: expMovingAverage,\n aggregateBy: aggregateByWrapper,\n // Predefined aggs\n percentil: percentil,\n average: _.partial(aggregateWrapper, AVERAGE),\n min: _.partial(aggregateWrapper, MIN),\n max: _.partial(aggregateWrapper, MAX),\n median: _.partial(aggregateWrapper, MEDIAN),\n sum: _.partial(aggregateWrapper, SUM),\n count: _.partial(aggregateWrapper, COUNT),\n sumSeries: sumSeries,\n top: _.partial(limit, 'top'),\n bottom: _.partial(limit, 'bottom'),\n sortSeries: sortSeries,\n timeShift: timeShift,\n setAlias: setAlias,\n setAliasByRegex: setAliasByRegex,\n replaceAlias: replaceAlias\n};\n\nlet aggregationFunctions = {\n avg: AVERAGE,\n min: MIN,\n max: MAX,\n median: MEDIAN,\n sum: SUM,\n count: COUNT\n};\n\nexport default {\n downsampleSeries: downsampleSeries,\n groupBy: groupBy_exported,\n AVERAGE: AVERAGE,\n MIN: MIN,\n MAX: MAX,\n MEDIAN: MEDIAN,\n SUM: SUM,\n COUNT: COUNT,\n unShiftTimeSeries: unShiftTimeSeries,\n\n get aggregationFunctions() {\n return aggregationFunctions;\n },\n\n get metricFunctions() {\n return metricFunctions;\n }\n};\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/dataProcessor.js"],"names":["limit","order","n","orderByFunc","timeseries","orderByCallback","aggregationFunctions","sortByIteratee","ts","values","_","map","datapoints","point","sortedTimeseries","sortBy","slice","removeAboveValue","removeBelowValue","transformNull","sortSeries","direction","orderBy","target","toLowerCase","setAlias","alias","replaceAlias","regexp","newAlias","pattern","utils","isRegex","buildRegex","replace","setAliasByRegex","extractText","str","extractPattern","RegExp","extractedValue","exec","groupByWrapper","interval","groupFunc","groupByCallback","groupBy","aggregateByWrapper","aggregateFunc","flattenedPoints","flatten","sortedPoints","sortByTime","aggregateWrapper","percentil","partial","PERCENTIL","timeShift","range","shift","parseTimeShiftInterval","time","unShiftTimeSeries","unshift","dp","downsampleSeries","downsample","groupBy_perf","groupBy_exported","sumSeries","delta","rate","scale","factor","scale_perf","simpleMovingAverage","expMovingAverage","a","SUM","COUNT","AVERAGE","MIN","MAX","MEDIAN","metricFunctions","movingAverage","exponentialMovingAverage","aggregateBy","average","min","max","median","sum","count","top","bottom","avg"],"mappings":";;;;;;;AAsBA,WAASA,KAAT,CAAeC,KAAf,EAAsBC,CAAtB,EAAyBC,WAAzB,EAAsCC,UAAtC,EAAkD;AAChD,QAAIC,kBAAkBC,qBAAqBH,WAArB,CAAtB;AACA,QAAII,iBAAiB,SAAjBA,cAAiB,CAACC,EAAD,EAAQ;AAC3B,UAAIC,SAASC,EAAEC,GAAF,CAAMH,GAAGI,UAAT,EAAqB,UAACC,KAAD,EAAW;AAC3C,eAAOA,MAAM,CAAN,CAAP;AACD,OAFY,CAAb;AAGA,aAAOR,gBAAgBI,MAAhB,CAAP;AACD,KALD;AAMA,QAAIK,mBAAmBJ,EAAEK,MAAF,CAASX,UAAT,EAAqBG,cAArB,CAAvB;AACA,QAAIN,UAAU,QAAd,EAAwB;AACtB,aAAOa,iBAAiBE,KAAjB,CAAuB,CAAvB,EAA0Bd,CAA1B,CAAP;AACD,KAFD,MAEO;AACL,aAAOY,iBAAiBE,KAAjB,CAAuB,CAACd,CAAxB,CAAP;AACD;AACF;;AAED,WAASe,gBAAT,CAA0Bf,CAA1B,EAA6BU,UAA7B,EAAyC;AACvC,WAAOF,EAAEC,GAAF,CAAMC,UAAN,EAAkB,iBAAS;AAChC,aAAO,CACJC,MAAM,CAAN,IAAWX,CAAZ,GAAiB,IAAjB,GAAwBW,MAAM,CAAN,CADnB,EAELA,MAAM,CAAN,CAFK,CAAP;AAID,KALM,CAAP;AAMD;;AAED,WAASK,gBAAT,CAA0BhB,CAA1B,EAA6BU,UAA7B,EAAyC;AACvC,WAAOF,EAAEC,GAAF,CAAMC,UAAN,EAAkB,iBAAS;AAChC,aAAO,CACJC,MAAM,CAAN,IAAWX,CAAZ,GAAiB,IAAjB,GAAwBW,M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sBAAcA;AA1BM,O;AA6BlBrB,0B,GAAuB;AACzB0F,aAAKhB,OADoB;AAEzBS,aAAKR,GAFoB;AAGzBS,aAAKR,GAHoB;AAIzBS,gBAAQR,MAJiB;AAKzBS,aAAKd,GALoB;AAMzBe,eAAOd;AANkB,O;;yBASZ;AACbd,0BAAkBA,gBADL;AAEbnB,iBAASsB,gBAFI;AAGbY,iBAASA,OAHI;AAIbC,aAAKA,GAJQ;AAKbC,aAAKA,GALQ;AAMbC,gBAAQA,MANK;AAObL,aAAKA,GAPQ;AAQbC,eAAOA,KARM;AASbjB,2BAAmBA,iBATN;;AAWb,YAAIxD,oBAAJ,GAA2B;AACzB,iBAAOA,oBAAP;AACD,SAbY;;AAeb,YAAI8E,eAAJ,GAAsB;AACpB,iBAAOA,eAAP;AACD;AAjBY,O","file":"dataProcessor.js","sourcesContent":["import _ from 'lodash';\r\nimport * as utils from './utils';\r\nimport ts from './timeseries';\r\n\r\nlet downsampleSeries = ts.downsample;\r\nlet groupBy = ts.groupBy_perf;\r\nlet groupBy_exported = (interval, groupFunc, datapoints) => groupBy(datapoints, interval, groupFunc);\r\nlet sumSeries = ts.sumSeries;\r\nlet delta = ts.delta;\r\nlet rate = ts.rate;\r\nlet scale = (factor, datapoints) => ts.scale_perf(datapoints, factor);\r\nlet simpleMovingAverage = (n, datapoints) => ts.simpleMovingAverage(datapoints, n);\r\nlet expMovingAverage = (a, datapoints) => ts.expMovingAverage(datapoints, a);\r\n\r\nlet SUM = ts.SUM;\r\nlet COUNT = ts.COUNT;\r\nlet AVERAGE = ts.AVERAGE;\r\nlet MIN = ts.MIN;\r\nlet MAX = ts.MAX;\r\nlet MEDIAN = ts.MEDIAN;\r\nlet PERCENTIL = ts.PERCENTIL;\r\n\r\nfunction limit(order, n, orderByFunc, timeseries) {\r\n let orderByCallback = aggregationFunctions[orderByFunc];\r\n let sortByIteratee = (ts) => {\r\n let values = _.map(ts.datapoints, (point) => {\r\n return point[0];\r\n });\r\n return orderByCallback(values);\r\n };\r\n let sortedTimeseries = _.sortBy(timeseries, sortByIteratee);\r\n if (order === 'bottom') {\r\n return sortedTimeseries.slice(0, n);\r\n } else {\r\n return sortedTimeseries.slice(-n);\r\n }\r\n}\r\n\r\nfunction removeAboveValue(n, datapoints) {\r\n return _.map(datapoints, point => {\r\n return [\r\n (point[0] > n) ? null : point[0],\r\n point[1]\r\n ];\r\n });\r\n}\r\n\r\nfunction removeBelowValue(n, datapoints) {\r\n return _.map(datapoints, point => {\r\n return [\r\n (point[0] < n) ? null : point[0],\r\n point[1]\r\n ];\r\n });\r\n}\r\n\r\nfunction transformNull(n, datapoints) {\r\n return _.map(datapoints, point => {\r\n return [\r\n (point[0] !== null) ? point[0] : n,\r\n point[1]\r\n ];\r\n });\r\n}\r\n\r\nfunction sortSeries(direction, timeseries) {\r\n return _.orderBy(timeseries, [function (ts) {\r\n return ts.target.toLowerCase();\r\n }], direction);\r\n}\r\n\r\nfunction setAlias(alias, timeseries) {\r\n timeseries.target = alias;\r\n return timeseries;\r\n}\r\n\r\nfunction replaceAlias(regexp, newAlias, timeseries) {\r\n let pattern;\r\n if (utils.isRegex(regexp)) {\r\n pattern = utils.buildRegex(regexp);\r\n } else {\r\n pattern = regexp;\r\n }\r\n\r\n let alias = timeseries.target.replace(pattern, newAlias);\r\n timeseries.target = alias;\r\n return timeseries;\r\n}\r\n\r\nfunction setAliasByRegex(alias, timeseries) {\r\n timeseries.target = extractText(timeseries.target, alias);\r\n return timeseries;\r\n}\r\n\r\nfunction extractText(str, pattern) {\r\n var extractPattern = new RegExp(pattern);\r\n var extractedValue = extractPattern.exec(str);\r\n extractedValue = extractedValue[0];\r\n return extractedValue;\r\n}\r\n\r\nfunction groupByWrapper(interval, groupFunc, datapoints) {\r\n var groupByCallback = aggregationFunctions[groupFunc];\r\n return groupBy(datapoints, interval, groupByCallback);\r\n}\r\n\r\nfunction aggregateByWrapper(interval, aggregateFunc, datapoints) {\r\n // Flatten all points in frame and then just use groupBy()\r\n const flattenedPoints = _.flatten(datapoints, true);\r\n // groupBy_perf works with sorted series only\r\n const sortedPoints = ts.sortByTime(flattenedPoints);\r\n let groupByCallback = aggregationFunctions[aggregateFunc];\r\n return groupBy(sortedPoints, interval, groupByCallback);\r\n}\r\n\r\nfunction aggregateWrapper(groupByCallback, interval, datapoints) {\r\n var flattenedPoints = _.flatten(datapoints, true);\r\n return groupBy(flattenedPoints, interval, groupByCallback);\r\n}\r\n\r\nfunction percentil(interval, n, datapoints) {\r\n var flattenedPoints = _.flatten(datapoints, true);\r\n var groupByCallback = _.partial(PERCENTIL, n);\r\n return groupBy(flattenedPoints, interval, groupByCallback);\r\n}\r\n\r\nfunction timeShift(interval, range) {\r\n let shift = utils.parseTimeShiftInterval(interval) / 1000;\r\n return _.map(range, time => {\r\n return time - shift;\r\n });\r\n}\r\n\r\nfunction unShiftTimeSeries(interval, datapoints) {\r\n let unshift = utils.parseTimeShiftInterval(interval);\r\n return _.map(datapoints, dp => {\r\n return [\r\n dp[0],\r\n dp[1] + unshift\r\n ];\r\n });\r\n}\r\n\r\nlet metricFunctions = {\r\n groupBy: groupByWrapper,\r\n scale: scale,\r\n delta: delta,\r\n rate: rate,\r\n movingAverage: simpleMovingAverage,\r\n exponentialMovingAverage: expMovingAverage,\r\n transformNull: transformNull,\r\n aggregateBy: aggregateByWrapper,\r\n // Predefined aggs\r\n percentil: percentil,\r\n average: _.partial(aggregateWrapper, AVERAGE),\r\n min: _.partial(aggregateWrapper, MIN),\r\n max: _.partial(aggregateWrapper, MAX),\r\n median: _.partial(aggregateWrapper, MEDIAN),\r\n sum: _.partial(aggregateWrapper, SUM),\r\n count: _.partial(aggregateWrapper, COUNT),\r\n sumSeries: sumSeries,\r\n removeAboveValue: removeAboveValue,\r\n removeBelowValue: removeBelowValue,\r\n top: _.partial(limit, 'top'),\r\n bottom: _.partial(limit, 'bottom'),\r\n sortSeries: sortSeries,\r\n timeShift: timeShift,\r\n setAlias: setAlias,\r\n setAliasByRegex: setAliasByRegex,\r\n replaceAlias: replaceAlias\r\n};\r\n\r\nlet aggregationFunctions = {\r\n avg: AVERAGE,\r\n min: MIN,\r\n max: MAX,\r\n median: MEDIAN,\r\n sum: SUM,\r\n count: COUNT\r\n};\r\n\r\nexport default {\r\n downsampleSeries: downsampleSeries,\r\n groupBy: groupBy_exported,\r\n AVERAGE: AVERAGE,\r\n MIN: MIN,\r\n MAX: MAX,\r\n MEDIAN: MEDIAN,\r\n SUM: SUM,\r\n COUNT: COUNT,\r\n unShiftTimeSeries: unShiftTimeSeries,\r\n\r\n get aggregationFunctions() {\r\n return aggregationFunctions;\r\n },\r\n\r\n get metricFunctions() {\r\n return metricFunctions;\r\n }\r\n};\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/datasource.js b/dist/datasource-zabbix/datasource.js index 186478378..cc0c2369e 100644 --- a/dist/datasource-zabbix/datasource.js +++ b/dist/datasource-zabbix/datasource.js @@ -52,15 +52,15 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', }; } - /** - * Custom formatter for template variables. - * Default Grafana "regex" formatter returns - * value1|value2 - * This formatter returns - * (value1|value2) - * This format needed for using in complex regex with - * template variables, for example - * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait + /** + * Custom formatter for template variables. + * Default Grafana "regex" formatter returns + * value1|value2 + * This formatter returns + * (value1|value2) + * This format needed for using in complex regex with + * template variables, for example + * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait */ function zabbixTemplateFormat(value) { if (typeof value === 'string') { @@ -78,13 +78,13 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', return value.join(','); } - /** - * 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 - * $variable -> a|b|c -> /a|b|c/ - * /$variable/ -> /a|b|c/ -> /a|b|c/ + /** + * 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 + * $variable -> a|b|c -> /a|b|c/ + * /$variable/ -> /a|b|c/ -> /a|b|c/ */ function replaceTemplateVars(templateSrv, target, scopedVars) { var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat); @@ -265,10 +265,10 @@ System.register(['lodash', 'app/core/utils/datemath', './utils', './migrations', // Datasource methods // //////////////////////// - /** - * Query panel data. Calls for each panel in dashboard. - * @param {Object} options Contains time range, targets and other info. - * @return {Object} Grafana metrics object with timeseries data for each target. + /** + * Query panel data. Calls for each panel in dashboard. + * @param {Object} options Contains time range, targets and other info. + * @return {Object} Grafana metrics object with timeseries data for each target. */ diff --git a/dist/datasource-zabbix/datasource.js.map b/dist/datasource-zabbix/datasource.js.map index 1edc066f6..ff12a33f4 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","disableReadOnlyUsersAck","dbConnectionOptions","dbConnection","enableDirectDBConnection","enable","sqlDatasourceId","datasourceId","zabbixOptions","zabbix","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","t","timeFrom","Math","ceil","parse","range","from","timeTo","to","cloneDeep","replaceTargetVariables","timeFunctions","time_from","time_to","timeRange","useTrends","isUseTrends","mode","MODE_METRICS","MODE_TEXT","migrate","queryNumericData","queryTextData","MODE_ITEMID","itemids","queryItemIdData","MODE_ITSERVICE","queryITServiceData","MODE_TRIGGERS","queryTriggersData","Promise","all","flatten","data","getItemOptions","itemtype","getItemsFromTarget","queryNumericDataForItems","items","getHistoryPromise","getTrendsDB","dbConnector","handleGrafanaTSResponse","history","valueType","getTrendValueType","getTrend","handleTrends","series","sortBy","point","DATAPOINT_TS","getHistoryDB","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","unShiftTimeSeries","resultFormat","handleHistoryAsTable","handleText","resolve","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","getHostsFromTarget","results","hosts","apps","hostids","appids","minSeverity","triggers","acknowledged","count","getHostAlerts","handleTriggersResponse","zabbixVersion","getVersion","version","login","testSQLDataSource","status","title","message","query","parts","each","splitTemplateQuery","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","triggersOptions","showTriggers","SHOW_ALL_TRIGGERS","hideHostsInMaintenance","getTriggers","application","triggerName","trigger","buildRegex","test","description","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","formatted_acknowledges","formatAcknowledges","time","clock","objectid","enabled_targets","getPanelItems","getAlerts","firedTriggers","p","textFilter","param","toString","useTrendsFrom","useTrendsRange","contains","indexBy"],"mappings":";;;;;;;;;;;;;AA2oBA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC,gBAAgBC,aAAhB,GAAgCL,QAAhC,CAAN,EAAiD,MAAjD,CAA3B;AACA,QAAIM,cAAcJ,EAAEK,MAAF,CAASR,YAAT,EAAuB,UAASS,IAAT,EAAe;AACtD,aAAON,EAAEO,QAAF,CAAWR,oBAAX,EAAiCO,KAAKE,GAAL,CAASC,IAA1C,CAAP;AACD,KAFiB,CAAlB;;AAIA,WAAOT,EAAEC,GAAF,CAAMG,WAAN,EAAmB,UAASE,IAAT,EAAe;AACvC,UAAII,eAAeR,gBAAgBS,kBAAhB,CAAmCL,KAAKE,GAAxC,EAA6CF,KAAKM,MAAlD,CAAnB;AACA,aAAOF,aAAaG,YAAb,CAA0BC,cAAcZ,eAAxC,CAAP;AACD,KAHM,CAAP;AAID;;AAED,WAASa,gBAAT,CAA0BC,MAA1B,EAAkC;AAChC,QAAIC,gBAAgB,KAApB;AACA,QAAIC,UAAUlB,EAAEmB,IAAF,CAAOH,OAAOI,SAAd,EAAyB,gBAAQ;AAC7C,aAAOd,KAAKE,GAAL,CAASC,IAAT,KAAkB,eAAzB;AACD,KAFa,CAAd;AAGA,QAAIS,WAAWA,QAAQN,MAAnB,IAA6BM,QAAQN,MAAR,CAAeS,MAAhD,EAAwD;AACtDJ,sBAAgBC,QAAQN,MAAR,CAAe,CAAf,CAAhB;AACD;AACD,WAAOK,aAAP;AACD;;AAED,WAASK,gBAAT,CAA0BC,eAA1B,EAA2CC,OAA3C,EAAoD;AAClD,QAAIC,aAAaX,cAAcf,oBAAd,CAAmC,KAAnC,CAAjB;AACA,QAAI2B,oBAAoBZ,cAAcf,oBAAd,CAAmCyB,QAAQP,aAA3C,KAA6DQ,UAArF;AACA,WAAOzB,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L,CAAiBG,OAAjB,CAAyB4O,KAAzB,EAAgCnQ,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;sCAEWqF,S,EAAW;AAAA,6CACIA,SADJ;AAAA,gBAChBb,QADgB;AAAA,gBACNM,MADM;;AAErB,gBAAIkK,gBAAgBvK,KAAKC,IAAL,CAAUpD,SAASqD,KAAT,CAAe,SAAS,KAAKlC,UAA7B,IAA2C,IAArD,CAApB;AACA,gBAAIwM,iBAAiBxK,KAAKC,IAAL,CAAUjF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI4C,YAAY,KAAK9C,MAAL,KACbgC,YAAYwK,aAAb,IACClK,SAASN,QAAT,IAAqByK,cAFR,CAAhB;AAIA,mBAAO3J,SAAP;AACD;;;;;;qCAoHK3D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE+R,QAAf;AAAyB;AAC3C,UAAI,CAAC/R,EAAEyQ,KAAP,EAAc;AAACzQ,UAAEyQ,KAAF,GAAUzQ,EAAEgS,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["import _ from 'lodash';\nimport * as dateMath from 'app/core/utils/datemath';\nimport * as utils from './utils';\nimport * as migrations from './migrations';\nimport * as metricFunctions from './metricFunctions';\nimport * as c from './constants';\nimport dataProcessor from './dataProcessor';\nimport responseHandler from './responseHandler';\nimport './zabbix.js';\nimport './zabbixAlerting.service.js';\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\n\nclass ZabbixAPIDatasource {\n\n /** @ngInject */\n constructor(instanceSettings, templateSrv, alertSrv, dashboardSrv, zabbixAlertingSrv, Zabbix) {\n this.templateSrv = templateSrv;\n this.alertSrv = alertSrv;\n this.dashboardSrv = dashboardSrv;\n this.zabbixAlertingSrv = zabbixAlertingSrv;\n\n // Use custom format for template variables\n this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\n\n // General data source settings\n this.name = instanceSettings.name;\n this.url = instanceSettings.url;\n this.basicAuth = instanceSettings.basicAuth;\n this.withCredentials = instanceSettings.withCredentials;\n\n const jsonData = instanceSettings.jsonData || {};\n\n // Zabbix API credentials\n this.username = jsonData.username;\n this.password = jsonData.password;\n\n // Use trends instead history since specified time\n this.trends = jsonData.trends;\n this.trendsFrom = jsonData.trendsFrom || '7d';\n this.trendsRange = jsonData.trendsRange || '4d';\n\n // Set cache update interval\n var ttl = jsonData.cacheTTL || '1h';\n this.cacheTTL = utils.parseInterval(ttl);\n\n // Alerting options\n this.alertingEnabled = jsonData.alerting;\n this.addThresholds = jsonData.addThresholds;\n this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;\n\n // Other options\n this.disableReadOnlyUsersAck = jsonData.disableReadOnlyUsersAck;\n\n // Direct DB Connection options\n let dbConnectionOptions = jsonData.dbConnection || {};\n this.enableDirectDBConnection = dbConnectionOptions.enable;\n this.sqlDatasourceId = dbConnectionOptions.datasourceId;\n\n let zabbixOptions = {\n username: this.username,\n password: this.password,\n basicAuth: this.basicAuth,\n withCredentials: this.withCredentials,\n cacheTTL: this.cacheTTL,\n enableDirectDBConnection: this.enableDirectDBConnection,\n sqlDatasourceId: this.sqlDatasourceId\n };\n\n this.zabbix = new Zabbix(this.url, zabbixOptions);\n }\n\n ////////////////////////\n // Datasource methods //\n ////////////////////////\n\n /**\n * Query panel data. Calls for each panel in dashboard.\n * @param {Object} options Contains time range, targets and other info.\n * @return {Object} Grafana metrics object with timeseries data for each target.\n */\n query(options) {\n // Get alerts for current panel\n if (this.alertingEnabled) {\n this.alertQuery(options).then(alert => {\n this.zabbixAlertingSrv.setPanelAlertState(options.panelId, alert.state);\n\n this.zabbixAlertingSrv.removeZabbixThreshold(options.panelId);\n if (this.addThresholds) {\n _.forEach(alert.thresholds, threshold => {\n this.zabbixAlertingSrv.setPanelThreshold(options.panelId, threshold);\n });\n }\n });\n }\n\n // Create request for each target\n let promises = _.map(options.targets, t => {\n // Don't request undefined and hidden targets\n if (t.hide) {\n return [];\n }\n\n let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\n let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\n\n // Prevent changes of original object\n let target = _.cloneDeep(t);\n this.replaceTargetVariables(target, options);\n\n // Apply Time-related functions (timeShift(), etc)\n let timeFunctions = bindFunctionDefs(target.functions, 'Time');\n if (timeFunctions.length) {\n const [time_from, time_to] = sequence(timeFunctions)([timeFrom, timeTo]);\n timeFrom = time_from;\n timeTo = time_to;\n }\n let timeRange = [timeFrom, timeTo];\n\n let useTrends = this.isUseTrends(timeRange);\n\n // Metrics or Text query mode\n if (!target.mode || target.mode === c.MODE_METRICS || target.mode === c.MODE_TEXT) {\n // Migrate old targets\n target = migrations.migrate(target);\n\n // Don't request undefined and hidden targets\n if (target.hide || !target.group || !target.host || !target.item) {\n return [];\n }\n\n if (!target.mode || target.mode === c.MODE_METRICS) {\n return this.queryNumericData(target, timeRange, useTrends, options);\n } else if (target.mode === c.MODE_TEXT) {\n return this.queryTextData(target, timeRange);\n }\n } else if (target.mode === c.MODE_ITEMID) {\n // Item ID mode\n if (!target.itemids) {\n return [];\n }\n return this.queryItemIdData(target, timeRange, useTrends, options);\n } else if (target.mode === c.MODE_ITSERVICE) {\n // IT services mode\n return this.queryITServiceData(target, timeRange, options);\n } else if (target.mode === c.MODE_TRIGGERS) {\n // Triggers mode\n return this.queryTriggersData(target, timeRange);\n } else {\n return [];\n }\n });\n\n // Data for panel (all targets)\n return Promise.all(_.flatten(promises))\n .then(_.flatten)\n .then(data => {\n return { data: data };\n });\n }\n\n /**\n * Query target data for Metrics mode\n */\n queryNumericData(target, timeRange, useTrends, options) {\n let getItemOptions = {\n itemtype: 'num'\n };\n return this.zabbix.getItemsFromTarget(target, getItemOptions)\n .then(items => {\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n });\n }\n\n /**\n * Query history for numeric items\n */\n queryNumericDataForItems(items, target, timeRange, useTrends, options) {\n let [timeFrom, timeTo] = timeRange;\n let getHistoryPromise;\n options.consolidateBy = getConsolidateBy(target);\n\n if (useTrends) {\n if (this.enableDirectDBConnection) {\n getHistoryPromise = this.zabbix.getTrendsDB(items, timeFrom, timeTo, options)\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n } else {\n let valueType = this.getTrendValueType(target);\n getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\n .then(history => responseHandler.handleTrends(history, items, valueType))\n .then(timeseries => {\n // Sort trend data, issue #202\n _.forEach(timeseries, series => {\n series.datapoints = _.sortBy(series.datapoints, point => point[c.DATAPOINT_TS]);\n });\n return timeseries;\n });\n }\n } else {\n // Use history\n if (this.enableDirectDBConnection) {\n getHistoryPromise = this.zabbix.getHistoryDB(items, timeFrom, timeTo, options)\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\n } else {\n getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => responseHandler.handleHistory(history, items));\n }\n }\n\n return getHistoryPromise\n .then(timeseries => this.applyDataProcessingFunctions(timeseries, target))\n .then(timeseries => downsampleSeries(timeseries, options))\n .catch(error => {\n console.log(error);\n return [];\n });\n }\n\n getTrendValueType(target) {\n // Find trendValue() function and get specified trend value\n var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name');\n var trendValueFunc = _.find(target.functions, func => {\n return _.includes(trendFunctions, func.def.name);\n });\n return trendValueFunc ? trendValueFunc.params[0] : \"avg\";\n }\n\n applyDataProcessingFunctions(timeseries_data, target) {\n let transformFunctions = bindFunctionDefs(target.functions, 'Transform');\n let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate');\n let filterFunctions = bindFunctionDefs(target.functions, 'Filter');\n let aliasFunctions = bindFunctionDefs(target.functions, 'Alias');\n\n // Apply transformation functions\n timeseries_data = _.cloneDeep(_.map(timeseries_data, timeseries => {\n timeseries.datapoints = sequence(transformFunctions)(timeseries.datapoints);\n return timeseries;\n }));\n\n // Apply filter functions\n if (filterFunctions.length) {\n timeseries_data = sequence(filterFunctions)(timeseries_data);\n }\n\n // Apply aggregations\n if (aggregationFunctions.length) {\n let dp = _.map(timeseries_data, 'datapoints');\n dp = sequence(aggregationFunctions)(dp);\n\n let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name');\n let lastAgg = _.findLast(target.functions, func => {\n return _.includes(aggFuncNames, func.def.name);\n });\n\n timeseries_data = [{\n target: lastAgg.text,\n datapoints: dp\n }];\n }\n\n // Apply alias functions\n _.forEach(timeseries_data, sequence(aliasFunctions));\n\n // Apply Time-related functions (timeShift(), etc)\n // Find timeShift() function and get specified trend value\n this.applyTimeShiftFunction(timeseries_data, target);\n\n return timeseries_data;\n }\n\n applyTimeShiftFunction(timeseries_data, target) {\n // Find timeShift() function and get specified interval\n let timeShiftFunc = _.find(target.functions, (func) => {\n return func.def.name === 'timeShift';\n });\n if (timeShiftFunc) {\n let shift = timeShiftFunc.params[0];\n _.forEach(timeseries_data, (series) => {\n series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints);\n });\n }\n }\n\n /**\n * Query target data for Text mode\n */\n queryTextData(target, timeRange) {\n let [timeFrom, timeTo] = timeRange;\n let options = {\n itemtype: 'text'\n };\n return this.zabbix.getItemsFromTarget(target, options)\n .then(items => {\n if (items.length) {\n return this.zabbix.getHistory(items, timeFrom, timeTo)\n .then(history => {\n if (target.resultFormat === 'table') {\n return responseHandler.handleHistoryAsTable(history, items, target);\n } else {\n return responseHandler.handleText(history, items, target);\n }\n });\n } else {\n return Promise.resolve([]);\n }\n });\n }\n\n /**\n * Query target data for Item ID mode\n */\n queryItemIdData(target, timeRange, useTrends, options) {\n let itemids = target.itemids;\n itemids = this.templateSrv.replace(itemids, options.scopedVars, zabbixItemIdsTemplateFormat);\n itemids = _.map(itemids.split(','), itemid => itemid.trim());\n\n if (!itemids) {\n return [];\n }\n\n return this.zabbix.getItemsByIDs(itemids)\n .then(items => {\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\n });\n }\n\n /**\n * Query target data for IT Services mode\n */\n queryITServiceData(target, timeRange, options) {\n // Don't show undefined and hidden targets\n if (target.hide || (!target.itservice && !target.itServiceFilter) || !target.slaProperty) {\n return [];\n }\n\n let itServiceIds = [];\n let itServices = [];\n let itServiceFilter;\n let isOldVersion = target.itservice && !target.itServiceFilter;\n\n if (isOldVersion) {\n // Backward compatibility\n itServiceFilter = '/.*/';\n } else {\n itServiceFilter = this.replaceTemplateVars(target.itServiceFilter, options.scopedVars);\n }\n\n return this.zabbix.getITServices(itServiceFilter)\n .then(itservices => {\n itServices = itservices;\n if (isOldVersion) {\n itServices = _.filter(itServices, {'serviceid': target.itservice.serviceid});\n }\n\n itServiceIds = _.map(itServices, 'serviceid');\n return itServiceIds;\n })\n .then(serviceids => {\n return this.zabbix.getSLA(serviceids, timeRange);\n })\n .then(slaResponse => {\n return _.map(itServiceIds, serviceid => {\n let itservice = _.find(itServices, {'serviceid': serviceid});\n return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);\n });\n });\n }\n\n queryTriggersData(target, timeRange) {\n let [timeFrom, timeTo] = timeRange;\n return this.zabbix.getHostsFromTarget(target)\n .then((results) => {\n let [hosts, apps] = results;\n if (hosts.length) {\n let hostids = _.map(hosts, 'hostid');\n let appids = _.map(apps, 'applicationid');\n let options = {\n minSeverity: target.triggers.minSeverity,\n acknowledged: target.triggers.acknowledged,\n count: target.triggers.count,\n timeFrom: timeFrom,\n timeTo: timeTo\n };\n return this.zabbix.getHostAlerts(hostids, appids, options)\n .then((triggers) => {\n return responseHandler.handleTriggersResponse(triggers, timeRange);\n });\n } else {\n return Promise.resolve([]);\n }\n });\n }\n\n /**\n * Test connection to Zabbix API\n * @return {object} Connection status and Zabbix API version\n */\n testDatasource() {\n let zabbixVersion;\n return this.zabbix.getVersion()\n .then(version => {\n zabbixVersion = version;\n return this.zabbix.login();\n })\n .then(() => {\n if (this.enableDirectDBConnection) {\n return this.zabbix.dbConnector.testSQLDataSource();\n } else {\n return Promise.resolve();\n }\n })\n .then(() => {\n return {\n status: \"success\",\n title: \"Success\",\n message: \"Zabbix API version: \" + zabbixVersion\n };\n })\n .catch(error => {\n if (error instanceof ZabbixAPIError) {\n return {\n status: \"error\",\n title: error.message,\n message: error.message\n };\n } else if (error.data && error.data.message) {\n return {\n status: \"error\",\n title: \"Connection failed\",\n message: \"Connection failed: \" + error.data.message\n };\n } else {\n return {\n status: \"error\",\n title: \"Connection failed\",\n message: \"Could not connect to given url\"\n };\n }\n });\n }\n\n ////////////////\n // Templating //\n ////////////////\n\n /**\n * Find metrics from templated request.\n *\n * @param {string} query Query from Templating\n * @return {string} Metric name - group, host, app or item or list\n * of metrics in \"{metric1,metcic2,...,metricN}\" format.\n */\n metricFindQuery(query) {\n let result;\n let parts = [];\n\n // Split query. Query structure: group.host.app.item\n _.each(utils.splitTemplateQuery(query), part => {\n part = this.replaceTemplateVars(part, {});\n\n // Replace wildcard to regex\n if (part === '*') {\n part = '/.*/';\n }\n parts.push(part);\n });\n let template = _.zipObject(['group', 'host', 'app', 'item'], parts);\n\n // Get items\n if (parts.length === 4) {\n // Search for all items, even it's not belong to any application\n if (template.app === '/.*/') {\n template.app = '';\n }\n result = this.zabbix.getItems(template.group, template.host, template.app, template.item);\n } else if (parts.length === 3) {\n // Get applications\n result = this.zabbix.getApps(template.group, template.host, template.app);\n } else if (parts.length === 2) {\n // Get hosts\n result = this.zabbix.getHosts(template.group, template.host);\n } else if (parts.length === 1) {\n // Get groups\n result = this.zabbix.getGroups(template.group);\n } else {\n result = Promise.resolve([]);\n }\n\n return result.then(metrics => {\n return _.map(metrics, formatMetric);\n });\n }\n\n /////////////////\n // Annotations //\n /////////////////\n\n annotationQuery(options) {\n var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);\n var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);\n var annotation = options.annotation;\n var showOkEvents = annotation.showOkEvents ? c.SHOW_ALL_EVENTS : c.SHOW_OK_EVENTS;\n\n // Show all triggers\n let triggersOptions = {\n showTriggers: c.SHOW_ALL_TRIGGERS,\n hideHostsInMaintenance: false\n };\n\n var getTriggers = this.zabbix.getTriggers(this.replaceTemplateVars(annotation.group, {}),\n this.replaceTemplateVars(annotation.host, {}),\n this.replaceTemplateVars(annotation.application, {}),\n triggersOptions);\n\n return getTriggers.then(triggers => {\n\n // Filter triggers by description\n let triggerName = this.replaceTemplateVars(annotation.trigger, {});\n if (utils.isRegex(triggerName)) {\n triggers = _.filter(triggers, trigger => {\n return utils.buildRegex(triggerName).test(trigger.description);\n });\n } else if (triggerName) {\n triggers = _.filter(triggers, trigger => {\n return trigger.description === triggerName;\n });\n }\n\n // Remove events below the chose severity\n triggers = _.filter(triggers, trigger => {\n return Number(trigger.priority) >= Number(annotation.minseverity);\n });\n\n var objectids = _.map(triggers, 'triggerid');\n return this.zabbix\n .getEvents(objectids, timeFrom, timeTo, showOkEvents)\n .then(events => {\n var indexedTriggers = _.keyBy(triggers, 'triggerid');\n\n // Hide acknowledged events if option enabled\n if (annotation.hideAcknowledged) {\n events = _.filter(events, event => {\n return !event.acknowledges.length;\n });\n }\n\n return _.map(events, event => {\n let tags;\n if (annotation.showHostname) {\n tags = _.map(event.hosts, 'name');\n }\n\n // Show event type (OK or Problem)\n let title = Number(event.value) ? 'Problem' : 'OK';\n\n let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges);\n return {\n annotation: annotation,\n time: event.clock * 1000,\n title: title,\n tags: tags,\n text: indexedTriggers[event.objectid].description + formatted_acknowledges\n };\n });\n });\n });\n }\n\n /**\n * Get triggers and its details for panel's targets\n * Returns alert state ('ok' if no fired triggers, or 'alerting' if at least 1 trigger is fired)\n * or empty object if no related triggers are finded.\n */\n alertQuery(options) {\n let enabled_targets = filterEnabledTargets(options.targets);\n let getPanelItems = _.map(enabled_targets, t => {\n let target = _.cloneDeep(t);\n this.replaceTargetVariables(target, options);\n return this.zabbix.getItemsFromTarget(target, {itemtype: 'num'});\n });\n\n return Promise.all(getPanelItems)\n .then(results => {\n let items = _.flatten(results);\n let itemids = _.map(items, 'itemid');\n\n if (itemids.length === 0) {\n return [];\n }\n return this.zabbix.getAlerts(itemids);\n })\n .then(triggers => {\n triggers = _.filter(triggers, trigger => {\n return trigger.priority >= this.alertingMinSeverity;\n });\n\n if (!triggers || triggers.length === 0) {\n return {};\n }\n\n let state = 'ok';\n\n let firedTriggers = _.filter(triggers, {value: '1'});\n if (firedTriggers.length) {\n state = 'alerting';\n }\n\n let thresholds = _.map(triggers, trigger => {\n return getTriggerThreshold(trigger.expression);\n });\n\n return {\n panelId: options.panelId,\n state: state,\n thresholds: thresholds\n };\n });\n }\n\n // Replace template variables\n replaceTargetVariables(target, options) {\n let parts = ['group', 'host', 'application', 'item'];\n _.forEach(parts, p => {\n if (target[p] && target[p].filter) {\n target[p].filter = this.replaceTemplateVars(target[p].filter, options.scopedVars);\n }\n });\n target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);\n\n _.forEach(target.functions, func => {\n func.params = _.map(func.params, param => {\n if (typeof param === 'number') {\n return +this.templateSrv.replace(param.toString(), options.scopedVars);\n } else {\n return this.templateSrv.replace(param, options.scopedVars);\n }\n });\n });\n }\n\n isUseTrends(timeRange) {\n let [timeFrom, timeTo] = timeRange;\n let useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);\n let useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);\n let useTrends = this.trends && (\n (timeFrom <= useTrendsFrom) ||\n (timeTo - timeFrom >= useTrendsRange)\n );\n return useTrends;\n }\n}\n\nfunction bindFunctionDefs(functionDefs, category) {\n var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name');\n var aggFuncDefs = _.filter(functionDefs, function(func) {\n return _.includes(aggregationFunctions, func.def.name);\n });\n\n return _.map(aggFuncDefs, function(func) {\n var funcInstance = metricFunctions.createFuncInstance(func.def, func.params);\n return funcInstance.bindFunction(dataProcessor.metricFunctions);\n });\n}\n\nfunction getConsolidateBy(target) {\n let consolidateBy = 'avg';\n let funcDef = _.find(target.functions, func => {\n return func.def.name === 'consolidateBy';\n });\n if (funcDef && funcDef.params && funcDef.params.length) {\n consolidateBy = funcDef.params[0];\n }\n return consolidateBy;\n}\n\nfunction downsampleSeries(timeseries_data, options) {\n let defaultAgg = dataProcessor.aggregationFunctions['avg'];\n let consolidateByFunc = dataProcessor.aggregationFunctions[options.consolidateBy] || defaultAgg;\n return _.map(timeseries_data, timeseries => {\n if (timeseries.datapoints.length > options.maxDataPoints) {\n timeseries.datapoints = dataProcessor\n .groupBy(options.interval, consolidateByFunc, timeseries.datapoints);\n }\n return timeseries;\n });\n}\n\nfunction formatMetric(metricObj) {\n return {\n text: metricObj.name,\n expandable: false\n };\n}\n\n/**\n * Custom formatter for template variables.\n * Default Grafana \"regex\" formatter returns\n * value1|value2\n * This formatter returns\n * (value1|value2)\n * This format needed for using in complex regex with\n * template variables, for example\n * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait\n */\nfunction zabbixTemplateFormat(value) {\n if (typeof value === 'string') {\n return utils.escapeRegex(value);\n }\n\n var escapedValues = _.map(value, utils.escapeRegex);\n return '(' + escapedValues.join('|') + ')';\n}\n\nfunction zabbixItemIdsTemplateFormat(value) {\n if (typeof value === 'string') {\n return value;\n }\n return value.join(',');\n}\n\n/**\n * If template variables are used in request, replace it using regex format\n * and wrap with '/' for proper multi-value work. Example:\n * $variable selected as a, b, c\n * We use filter $variable\n * $variable -> a|b|c -> /a|b|c/\n * /$variable/ -> /a|b|c/ -> /a|b|c/\n */\nfunction replaceTemplateVars(templateSrv, target, scopedVars) {\n var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat);\n if (target !== replacedTarget && !utils.isRegex(replacedTarget)) {\n replacedTarget = '/^' + replacedTarget + '$/';\n }\n return replacedTarget;\n}\n\n// Apply function one by one:\n// sequence([a(), b(), c()]) = c(b(a()));\nfunction sequence(funcsArray) {\n return function(result) {\n for (var i = 0; i < funcsArray.length; i++) {\n result = funcsArray[i].call(this, result);\n }\n return result;\n };\n}\n\nfunction filterEnabledTargets(targets) {\n return _.filter(targets, target => {\n return !(target.hide || !target.group || !target.host || !target.item);\n });\n}\n\nfunction getTriggerThreshold(expression) {\n let thresholdPattern = /.*[<>=]{1,2}([\\d\\.]+)/;\n let finded_thresholds = expression.match(thresholdPattern);\n if (finded_thresholds && finded_thresholds.length >= 2) {\n let threshold = finded_thresholds[1];\n threshold = Number(threshold);\n return threshold;\n } else {\n return null;\n }\n}\n\nexport {ZabbixAPIDatasource, zabbixTemplateFormat};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.includes) {_.includes = _.contains;}\nif (!_.keyBy) {_.keyBy = _.indexBy;}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/datasource.js"],"names":["bindFunctionDefs","functionDefs","category","aggregationFunctions","_","map","metricFunctions","getCategories","aggFuncDefs","filter","func","includes","def","name","funcInstance","createFuncInstance","params","bindFunction","dataProcessor","getConsolidateBy","target","consolidateBy","funcDef","find","functions","length","downsampleSeries","timeseries_data","options","defaultAgg","consolidateByFunc","timeseries","datapoints","maxDataPoints","groupBy","interval","formatMetric","metricObj","text","expandable","zabbixTemplateFormat","value","utils","escapeRegex","escapedValues","join","zabbixItemIdsTemplateFormat","replaceTemplateVars","templateSrv","scopedVars","replacedTarget","replace","isRegex","sequence","funcsArray","result","i","call","filterEnabledTargets","targets","hide","group","host","item","getTriggerThreshold","expression","thresholdPattern","finded_thresholds","match","threshold","Number","dateMath","migrations","c","responseHandler","ZabbixAPIError","ZabbixAPIDatasource","instanceSettings","alertSrv","dashboardSrv","zabbixAlertingSrv","Zabbix","partial","url","basicAuth","withCredentials","jsonData","username","password","trends","trendsFrom","trendsRange","ttl","cacheTTL","parseInterval","alertingEnabled","alerting","addThresholds","alertingMinSeverity","SEV_WARNING","disableReadOnlyUsersAck","dbConnectionOptions","dbConnection","enableDirectDBConnection","enable","sqlDatasourceId","datasourceId","zabbixOptions","zabbix","alertQuery","then","setPanelAlertState","panelId","alert","state","removeZabbixThreshold","forEach","thresholds","setPanelThreshold","promises","t","timeFrom","Math","ceil","parse","range","from","timeTo","to","cloneDeep","replaceTargetVariables","timeFunctions","time_from","time_to","timeRange","useTrends","isUseTrends","mode","MODE_METRICS","MODE_TEXT","migrate","queryNumericData","queryTextData","MODE_ITEMID","itemids","queryItemIdData","MODE_ITSERVICE","queryITServiceData","MODE_TRIGGERS","queryTriggersData","Promise","all","flatten","data","getItemOptions","itemtype","getItemsFromTarget","queryNumericDataForItems","items","getHistoryPromise","getTrendsDB","dbConnector","handleGrafanaTSResponse","history","valueType","getTrendValueType","getTrend","handleTrends","series","sortBy","point","DATAPOINT_TS","getHistoryDB","getHistory","handleHistory","applyDataProcessingFunctions","catch","console","log","error","trendFunctions","trendValueFunc","transformFunctions","filterFunctions","aliasFunctions","dp","aggFuncNames","lastAgg","findLast","applyTimeShiftFunction","timeShiftFunc","shift","unShiftTimeSeries","resultFormat","handleHistoryAsTable","handleText","resolve","split","itemid","trim","getItemsByIDs","itservice","itServiceFilter","slaProperty","itServiceIds","itServices","isOldVersion","getITServices","itservices","serviceid","getSLA","serviceids","handleSLAResponse","slaResponse","getHostsFromTarget","results","hosts","apps","hostids","appids","minSeverity","triggers","acknowledged","count","getHostAlerts","handleTriggersResponse","zabbixVersion","getVersion","version","login","testSQLDataSource","status","title","message","query","parts","each","splitTemplateQuery","part","push","template","zipObject","app","getItems","getApps","getHosts","getGroups","metrics","rangeRaw","annotation","showOkEvents","SHOW_ALL_EVENTS","SHOW_OK_EVENTS","triggersOptions","showTriggers","SHOW_ALL_TRIGGERS","hideHostsInMaintenance","getTriggers","application","triggerName","trigger","buildRegex","test","description","priority","minseverity","objectids","getEvents","indexedTriggers","keyBy","hideAcknowledged","events","event","acknowledges","tags","showHostname","formatted_acknowledges","formatAcknowledges","time","clock","objectid","enabled_targets","getPanelItems","getAlerts","firedTriggers","p","textFilter","param","toString","useTrendsFrom","useTrendsRange","contains","indexBy"],"mappings":";;;;;;;;;;;;;AA2oBA,WAASA,gBAAT,CAA0BC,YAA1B,EAAwCC,QAAxC,EAAkD;AAChD,QAAIC,uBAAuBC,EAAEC,GAAF,CAAMC,gBAAgBC,aAAhB,GAAgCL,QAAhC,CAAN,EAAiD,MAAjD,CAA3B;AACA,QAAIM,cAAcJ,EAAEK,MAAF,CAASR,YAAT,EAAuB,UAASS,IAAT,EAAe;AACtD,aAAON,EAAEO,QAAF,CAAWR,oBAAX,EAAiCO,KAAKE,GAAL,CAASC,IAA1C,CAAP;AACD,KAFiB,CAAlB;;AAIA,WAAOT,EAAEC,GAAF,CAAMG,WAAN,EAAmB,UAASE,IAAT,EAAe;AACvC,UAAII,eAAeR,gBAAgBS,kBAAhB,CAAmCL,KAAKE,GAAxC,EAA6CF,KAAKM,MAAlD,CAAnB;AACA,aAAOF,aAAaG,YAAb,CAA0BC,cAAcZ,eAAxC,CAAP;AACD,KAHM,CAAP;AAID;;AAED,WAASa,gBAAT,CAA0BC,MAA1B,EAAkC;AAChC,QAAIC,gBAAgB,KAApB;AACA,QAAIC,UAAUlB,EAAEmB,IAAF,CAAOH,OAAOI,SAAd,EAAyB,gBAAQ;AAC7C,aAAOd,KAAKE,GAAL,CAASC,IAAT,KAAkB,eAAzB;AACD,KAFa,CAAd;AAGA,QAAIS,WAAWA,QAAQN,MAAnB,IAA6BM,QAAQN,MAAR,CAAeS,MAAhD,EAAwD;AACtDJ,sBAAgBC,QAAQN,MAAR,CAAe,CAAf,CAAhB;AACD;AACD,WAAOK,aAAP;AACD;;AAED,WAASK,gBAAT,CAA0BC,eAA1B,EAA2CC,OAA3C,EAAoD;AAClD,QAAIC,aAAaX,cAAcf,oBAAd,CAAmC,KAAnC,CAAjB;AACA,QAAI2B,oBAAoBZ,cAAcf,oBAAd,CAAmCyB,QAAQP,aAA3C,K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AEO;AACL,yBAAO,QAAKD,WAAL,CAAiBG,OAAjB,CAAyB4O,KAAzB,EAAgCnQ,QAAQqB,UAAxC,CAAP;AACD;AACF,eANa,CAAd;AAOD,aARD;AASD;;;sCAEWqF,S,EAAW;AAAA,6CACIA,SADJ;AAAA,gBAChBb,QADgB;AAAA,gBACNM,MADM;;AAErB,gBAAIkK,gBAAgBvK,KAAKC,IAAL,CAAUpD,SAASqD,KAAT,CAAe,SAAS,KAAKlC,UAA7B,IAA2C,IAArD,CAApB;AACA,gBAAIwM,iBAAiBxK,KAAKC,IAAL,CAAUjF,MAAMoD,aAAN,CAAoB,KAAKH,WAAzB,IAAwC,IAAlD,CAArB;AACA,gBAAI4C,YAAY,KAAK9C,MAAL,KACbgC,YAAYwK,aAAb,IACClK,SAASN,QAAT,IAAqByK,cAFR,CAAhB;AAIA,mBAAO3J,SAAP;AACD;;;;;;qCAoHK3D,mB;;sCAAqBpC,oB;;AAE7B;AACA,UAAI,CAACpC,EAAEO,QAAP,EAAiB;AAACP,UAAEO,QAAF,GAAaP,EAAE+R,QAAf;AAAyB;AAC3C,UAAI,CAAC/R,EAAEyQ,KAAP,EAAc;AAACzQ,UAAEyQ,KAAF,GAAUzQ,EAAEgS,OAAZ;AAAqB","file":"datasource.js","sourcesContent":["import _ from 'lodash';\r\nimport * as dateMath from 'app/core/utils/datemath';\r\nimport * as utils from './utils';\r\nimport * as migrations from './migrations';\r\nimport * as metricFunctions from './metricFunctions';\r\nimport * as c from './constants';\r\nimport dataProcessor from './dataProcessor';\r\nimport responseHandler from './responseHandler';\r\nimport './zabbix.js';\r\nimport './zabbixAlerting.service.js';\r\nimport {ZabbixAPIError} from './zabbixAPICore.service.js';\r\n\r\nclass ZabbixAPIDatasource {\r\n\r\n /** @ngInject */\r\n constructor(instanceSettings, templateSrv, alertSrv, dashboardSrv, zabbixAlertingSrv, Zabbix) {\r\n this.templateSrv = templateSrv;\r\n this.alertSrv = alertSrv;\r\n this.dashboardSrv = dashboardSrv;\r\n this.zabbixAlertingSrv = zabbixAlertingSrv;\r\n\r\n // Use custom format for template variables\r\n this.replaceTemplateVars = _.partial(replaceTemplateVars, this.templateSrv);\r\n\r\n // General data source settings\r\n this.name = instanceSettings.name;\r\n this.url = instanceSettings.url;\r\n this.basicAuth = instanceSettings.basicAuth;\r\n this.withCredentials = instanceSettings.withCredentials;\r\n\r\n const jsonData = instanceSettings.jsonData || {};\r\n\r\n // Zabbix API credentials\r\n this.username = jsonData.username;\r\n this.password = jsonData.password;\r\n\r\n // Use trends instead history since specified time\r\n this.trends = jsonData.trends;\r\n this.trendsFrom = jsonData.trendsFrom || '7d';\r\n this.trendsRange = jsonData.trendsRange || '4d';\r\n\r\n // Set cache update interval\r\n var ttl = jsonData.cacheTTL || '1h';\r\n this.cacheTTL = utils.parseInterval(ttl);\r\n\r\n // Alerting options\r\n this.alertingEnabled = jsonData.alerting;\r\n this.addThresholds = jsonData.addThresholds;\r\n this.alertingMinSeverity = jsonData.alertingMinSeverity || c.SEV_WARNING;\r\n\r\n // Other options\r\n this.disableReadOnlyUsersAck = jsonData.disableReadOnlyUsersAck;\r\n\r\n // Direct DB Connection options\r\n let dbConnectionOptions = jsonData.dbConnection || {};\r\n this.enableDirectDBConnection = dbConnectionOptions.enable;\r\n this.sqlDatasourceId = dbConnectionOptions.datasourceId;\r\n\r\n let zabbixOptions = {\r\n username: this.username,\r\n password: this.password,\r\n basicAuth: this.basicAuth,\r\n withCredentials: this.withCredentials,\r\n cacheTTL: this.cacheTTL,\r\n enableDirectDBConnection: this.enableDirectDBConnection,\r\n sqlDatasourceId: this.sqlDatasourceId\r\n };\r\n\r\n this.zabbix = new Zabbix(this.url, zabbixOptions);\r\n }\r\n\r\n ////////////////////////\r\n // Datasource methods //\r\n ////////////////////////\r\n\r\n /**\r\n * Query panel data. Calls for each panel in dashboard.\r\n * @param {Object} options Contains time range, targets and other info.\r\n * @return {Object} Grafana metrics object with timeseries data for each target.\r\n */\r\n query(options) {\r\n // Get alerts for current panel\r\n if (this.alertingEnabled) {\r\n this.alertQuery(options).then(alert => {\r\n this.zabbixAlertingSrv.setPanelAlertState(options.panelId, alert.state);\r\n\r\n this.zabbixAlertingSrv.removeZabbixThreshold(options.panelId);\r\n if (this.addThresholds) {\r\n _.forEach(alert.thresholds, threshold => {\r\n this.zabbixAlertingSrv.setPanelThreshold(options.panelId, threshold);\r\n });\r\n }\r\n });\r\n }\r\n\r\n // Create request for each target\r\n let promises = _.map(options.targets, t => {\r\n // Don't request undefined and hidden targets\r\n if (t.hide) {\r\n return [];\r\n }\r\n\r\n let timeFrom = Math.ceil(dateMath.parse(options.range.from) / 1000);\r\n let timeTo = Math.ceil(dateMath.parse(options.range.to) / 1000);\r\n\r\n // Prevent changes of original object\r\n let target = _.cloneDeep(t);\r\n this.replaceTargetVariables(target, options);\r\n\r\n // Apply Time-related functions (timeShift(), etc)\r\n let timeFunctions = bindFunctionDefs(target.functions, 'Time');\r\n if (timeFunctions.length) {\r\n const [time_from, time_to] = sequence(timeFunctions)([timeFrom, timeTo]);\r\n timeFrom = time_from;\r\n timeTo = time_to;\r\n }\r\n let timeRange = [timeFrom, timeTo];\r\n\r\n let useTrends = this.isUseTrends(timeRange);\r\n\r\n // Metrics or Text query mode\r\n if (!target.mode || target.mode === c.MODE_METRICS || target.mode === c.MODE_TEXT) {\r\n // Migrate old targets\r\n target = migrations.migrate(target);\r\n\r\n // Don't request undefined and hidden targets\r\n if (target.hide || !target.group || !target.host || !target.item) {\r\n return [];\r\n }\r\n\r\n if (!target.mode || target.mode === c.MODE_METRICS) {\r\n return this.queryNumericData(target, timeRange, useTrends, options);\r\n } else if (target.mode === c.MODE_TEXT) {\r\n return this.queryTextData(target, timeRange);\r\n }\r\n } else if (target.mode === c.MODE_ITEMID) {\r\n // Item ID mode\r\n if (!target.itemids) {\r\n return [];\r\n }\r\n return this.queryItemIdData(target, timeRange, useTrends, options);\r\n } else if (target.mode === c.MODE_ITSERVICE) {\r\n // IT services mode\r\n return this.queryITServiceData(target, timeRange, options);\r\n } else if (target.mode === c.MODE_TRIGGERS) {\r\n // Triggers mode\r\n return this.queryTriggersData(target, timeRange);\r\n } else {\r\n return [];\r\n }\r\n });\r\n\r\n // Data for panel (all targets)\r\n return Promise.all(_.flatten(promises))\r\n .then(_.flatten)\r\n .then(data => {\r\n return { data: data };\r\n });\r\n }\r\n\r\n /**\r\n * Query target data for Metrics mode\r\n */\r\n queryNumericData(target, timeRange, useTrends, options) {\r\n let getItemOptions = {\r\n itemtype: 'num'\r\n };\r\n return this.zabbix.getItemsFromTarget(target, getItemOptions)\r\n .then(items => {\r\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\r\n });\r\n }\r\n\r\n /**\r\n * Query history for numeric items\r\n */\r\n queryNumericDataForItems(items, target, timeRange, useTrends, options) {\r\n let [timeFrom, timeTo] = timeRange;\r\n let getHistoryPromise;\r\n options.consolidateBy = getConsolidateBy(target);\r\n\r\n if (useTrends) {\r\n if (this.enableDirectDBConnection) {\r\n getHistoryPromise = this.zabbix.getTrendsDB(items, timeFrom, timeTo, options)\r\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\r\n } else {\r\n let valueType = this.getTrendValueType(target);\r\n getHistoryPromise = this.zabbix.getTrend(items, timeFrom, timeTo)\r\n .then(history => responseHandler.handleTrends(history, items, valueType))\r\n .then(timeseries => {\r\n // Sort trend data, issue #202\r\n _.forEach(timeseries, series => {\r\n series.datapoints = _.sortBy(series.datapoints, point => point[c.DATAPOINT_TS]);\r\n });\r\n return timeseries;\r\n });\r\n }\r\n } else {\r\n // Use history\r\n if (this.enableDirectDBConnection) {\r\n getHistoryPromise = this.zabbix.getHistoryDB(items, timeFrom, timeTo, options)\r\n .then(history => this.zabbix.dbConnector.handleGrafanaTSResponse(history, items));\r\n } else {\r\n getHistoryPromise = this.zabbix.getHistory(items, timeFrom, timeTo)\r\n .then(history => responseHandler.handleHistory(history, items));\r\n }\r\n }\r\n\r\n return getHistoryPromise\r\n .then(timeseries => this.applyDataProcessingFunctions(timeseries, target))\r\n .then(timeseries => downsampleSeries(timeseries, options))\r\n .catch(error => {\r\n console.log(error);\r\n return [];\r\n });\r\n }\r\n\r\n getTrendValueType(target) {\r\n // Find trendValue() function and get specified trend value\r\n var trendFunctions = _.map(metricFunctions.getCategories()['Trends'], 'name');\r\n var trendValueFunc = _.find(target.functions, func => {\r\n return _.includes(trendFunctions, func.def.name);\r\n });\r\n return trendValueFunc ? trendValueFunc.params[0] : \"avg\";\r\n }\r\n\r\n applyDataProcessingFunctions(timeseries_data, target) {\r\n let transformFunctions = bindFunctionDefs(target.functions, 'Transform');\r\n let aggregationFunctions = bindFunctionDefs(target.functions, 'Aggregate');\r\n let filterFunctions = bindFunctionDefs(target.functions, 'Filter');\r\n let aliasFunctions = bindFunctionDefs(target.functions, 'Alias');\r\n\r\n // Apply transformation functions\r\n timeseries_data = _.cloneDeep(_.map(timeseries_data, timeseries => {\r\n timeseries.datapoints = sequence(transformFunctions)(timeseries.datapoints);\r\n return timeseries;\r\n }));\r\n\r\n // Apply filter functions\r\n if (filterFunctions.length) {\r\n timeseries_data = sequence(filterFunctions)(timeseries_data);\r\n }\r\n\r\n // Apply aggregations\r\n if (aggregationFunctions.length) {\r\n let dp = _.map(timeseries_data, 'datapoints');\r\n dp = sequence(aggregationFunctions)(dp);\r\n\r\n let aggFuncNames = _.map(metricFunctions.getCategories()['Aggregate'], 'name');\r\n let lastAgg = _.findLast(target.functions, func => {\r\n return _.includes(aggFuncNames, func.def.name);\r\n });\r\n\r\n timeseries_data = [{\r\n target: lastAgg.text,\r\n datapoints: dp\r\n }];\r\n }\r\n\r\n // Apply alias functions\r\n _.forEach(timeseries_data, sequence(aliasFunctions));\r\n\r\n // Apply Time-related functions (timeShift(), etc)\r\n // Find timeShift() function and get specified trend value\r\n this.applyTimeShiftFunction(timeseries_data, target);\r\n\r\n return timeseries_data;\r\n }\r\n\r\n applyTimeShiftFunction(timeseries_data, target) {\r\n // Find timeShift() function and get specified interval\r\n let timeShiftFunc = _.find(target.functions, (func) => {\r\n return func.def.name === 'timeShift';\r\n });\r\n if (timeShiftFunc) {\r\n let shift = timeShiftFunc.params[0];\r\n _.forEach(timeseries_data, (series) => {\r\n series.datapoints = dataProcessor.unShiftTimeSeries(shift, series.datapoints);\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Query target data for Text mode\r\n */\r\n queryTextData(target, timeRange) {\r\n let [timeFrom, timeTo] = timeRange;\r\n let options = {\r\n itemtype: 'text'\r\n };\r\n return this.zabbix.getItemsFromTarget(target, options)\r\n .then(items => {\r\n if (items.length) {\r\n return this.zabbix.getHistory(items, timeFrom, timeTo)\r\n .then(history => {\r\n if (target.resultFormat === 'table') {\r\n return responseHandler.handleHistoryAsTable(history, items, target);\r\n } else {\r\n return responseHandler.handleText(history, items, target);\r\n }\r\n });\r\n } else {\r\n return Promise.resolve([]);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Query target data for Item ID mode\r\n */\r\n queryItemIdData(target, timeRange, useTrends, options) {\r\n let itemids = target.itemids;\r\n itemids = this.templateSrv.replace(itemids, options.scopedVars, zabbixItemIdsTemplateFormat);\r\n itemids = _.map(itemids.split(','), itemid => itemid.trim());\r\n\r\n if (!itemids) {\r\n return [];\r\n }\r\n\r\n return this.zabbix.getItemsByIDs(itemids)\r\n .then(items => {\r\n return this.queryNumericDataForItems(items, target, timeRange, useTrends, options);\r\n });\r\n }\r\n\r\n /**\r\n * Query target data for IT Services mode\r\n */\r\n queryITServiceData(target, timeRange, options) {\r\n // Don't show undefined and hidden targets\r\n if (target.hide || (!target.itservice && !target.itServiceFilter) || !target.slaProperty) {\r\n return [];\r\n }\r\n\r\n let itServiceIds = [];\r\n let itServices = [];\r\n let itServiceFilter;\r\n let isOldVersion = target.itservice && !target.itServiceFilter;\r\n\r\n if (isOldVersion) {\r\n // Backward compatibility\r\n itServiceFilter = '/.*/';\r\n } else {\r\n itServiceFilter = this.replaceTemplateVars(target.itServiceFilter, options.scopedVars);\r\n }\r\n\r\n return this.zabbix.getITServices(itServiceFilter)\r\n .then(itservices => {\r\n itServices = itservices;\r\n if (isOldVersion) {\r\n itServices = _.filter(itServices, {'serviceid': target.itservice.serviceid});\r\n }\r\n\r\n itServiceIds = _.map(itServices, 'serviceid');\r\n return itServiceIds;\r\n })\r\n .then(serviceids => {\r\n return this.zabbix.getSLA(serviceids, timeRange);\r\n })\r\n .then(slaResponse => {\r\n return _.map(itServiceIds, serviceid => {\r\n let itservice = _.find(itServices, {'serviceid': serviceid});\r\n return responseHandler.handleSLAResponse(itservice, target.slaProperty, slaResponse);\r\n });\r\n });\r\n }\r\n\r\n queryTriggersData(target, timeRange) {\r\n let [timeFrom, timeTo] = timeRange;\r\n return this.zabbix.getHostsFromTarget(target)\r\n .then((results) => {\r\n let [hosts, apps] = results;\r\n if (hosts.length) {\r\n let hostids = _.map(hosts, 'hostid');\r\n let appids = _.map(apps, 'applicationid');\r\n let options = {\r\n minSeverity: target.triggers.minSeverity,\r\n acknowledged: target.triggers.acknowledged,\r\n count: target.triggers.count,\r\n timeFrom: timeFrom,\r\n timeTo: timeTo\r\n };\r\n return this.zabbix.getHostAlerts(hostids, appids, options)\r\n .then((triggers) => {\r\n return responseHandler.handleTriggersResponse(triggers, timeRange);\r\n });\r\n } else {\r\n return Promise.resolve([]);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Test connection to Zabbix API\r\n * @return {object} Connection status and Zabbix API version\r\n */\r\n testDatasource() {\r\n let zabbixVersion;\r\n return this.zabbix.getVersion()\r\n .then(version => {\r\n zabbixVersion = version;\r\n return this.zabbix.login();\r\n })\r\n .then(() => {\r\n if (this.enableDirectDBConnection) {\r\n return this.zabbix.dbConnector.testSQLDataSource();\r\n } else {\r\n return Promise.resolve();\r\n }\r\n })\r\n .then(() => {\r\n return {\r\n status: \"success\",\r\n title: \"Success\",\r\n message: \"Zabbix API version: \" + zabbixVersion\r\n };\r\n })\r\n .catch(error => {\r\n if (error instanceof ZabbixAPIError) {\r\n return {\r\n status: \"error\",\r\n title: error.message,\r\n message: error.message\r\n };\r\n } else if (error.data && error.data.message) {\r\n return {\r\n status: \"error\",\r\n title: \"Connection failed\",\r\n message: \"Connection failed: \" + error.data.message\r\n };\r\n } else {\r\n return {\r\n status: \"error\",\r\n title: \"Connection failed\",\r\n message: \"Could not connect to given url\"\r\n };\r\n }\r\n });\r\n }\r\n\r\n ////////////////\r\n // Templating //\r\n ////////////////\r\n\r\n /**\r\n * Find metrics from templated request.\r\n *\r\n * @param {string} query Query from Templating\r\n * @return {string} Metric name - group, host, app or item or list\r\n * of metrics in \"{metric1,metcic2,...,metricN}\" format.\r\n */\r\n metricFindQuery(query) {\r\n let result;\r\n let parts = [];\r\n\r\n // Split query. Query structure: group.host.app.item\r\n _.each(utils.splitTemplateQuery(query), part => {\r\n part = this.replaceTemplateVars(part, {});\r\n\r\n // Replace wildcard to regex\r\n if (part === '*') {\r\n part = '/.*/';\r\n }\r\n parts.push(part);\r\n });\r\n let template = _.zipObject(['group', 'host', 'app', 'item'], parts);\r\n\r\n // Get items\r\n if (parts.length === 4) {\r\n // Search for all items, even it's not belong to any application\r\n if (template.app === '/.*/') {\r\n template.app = '';\r\n }\r\n result = this.zabbix.getItems(template.group, template.host, template.app, template.item);\r\n } else if (parts.length === 3) {\r\n // Get applications\r\n result = this.zabbix.getApps(template.group, template.host, template.app);\r\n } else if (parts.length === 2) {\r\n // Get hosts\r\n result = this.zabbix.getHosts(template.group, template.host);\r\n } else if (parts.length === 1) {\r\n // Get groups\r\n result = this.zabbix.getGroups(template.group);\r\n } else {\r\n result = Promise.resolve([]);\r\n }\r\n\r\n return result.then(metrics => {\r\n return _.map(metrics, formatMetric);\r\n });\r\n }\r\n\r\n /////////////////\r\n // Annotations //\r\n /////////////////\r\n\r\n annotationQuery(options) {\r\n var timeFrom = Math.ceil(dateMath.parse(options.rangeRaw.from) / 1000);\r\n var timeTo = Math.ceil(dateMath.parse(options.rangeRaw.to) / 1000);\r\n var annotation = options.annotation;\r\n var showOkEvents = annotation.showOkEvents ? c.SHOW_ALL_EVENTS : c.SHOW_OK_EVENTS;\r\n\r\n // Show all triggers\r\n let triggersOptions = {\r\n showTriggers: c.SHOW_ALL_TRIGGERS,\r\n hideHostsInMaintenance: false\r\n };\r\n\r\n var getTriggers = this.zabbix.getTriggers(this.replaceTemplateVars(annotation.group, {}),\r\n this.replaceTemplateVars(annotation.host, {}),\r\n this.replaceTemplateVars(annotation.application, {}),\r\n triggersOptions);\r\n\r\n return getTriggers.then(triggers => {\r\n\r\n // Filter triggers by description\r\n let triggerName = this.replaceTemplateVars(annotation.trigger, {});\r\n if (utils.isRegex(triggerName)) {\r\n triggers = _.filter(triggers, trigger => {\r\n return utils.buildRegex(triggerName).test(trigger.description);\r\n });\r\n } else if (triggerName) {\r\n triggers = _.filter(triggers, trigger => {\r\n return trigger.description === triggerName;\r\n });\r\n }\r\n\r\n // Remove events below the chose severity\r\n triggers = _.filter(triggers, trigger => {\r\n return Number(trigger.priority) >= Number(annotation.minseverity);\r\n });\r\n\r\n var objectids = _.map(triggers, 'triggerid');\r\n return this.zabbix\r\n .getEvents(objectids, timeFrom, timeTo, showOkEvents)\r\n .then(events => {\r\n var indexedTriggers = _.keyBy(triggers, 'triggerid');\r\n\r\n // Hide acknowledged events if option enabled\r\n if (annotation.hideAcknowledged) {\r\n events = _.filter(events, event => {\r\n return !event.acknowledges.length;\r\n });\r\n }\r\n\r\n return _.map(events, event => {\r\n let tags;\r\n if (annotation.showHostname) {\r\n tags = _.map(event.hosts, 'name');\r\n }\r\n\r\n // Show event type (OK or Problem)\r\n let title = Number(event.value) ? 'Problem' : 'OK';\r\n\r\n let formatted_acknowledges = utils.formatAcknowledges(event.acknowledges);\r\n return {\r\n annotation: annotation,\r\n time: event.clock * 1000,\r\n title: title,\r\n tags: tags,\r\n text: indexedTriggers[event.objectid].description + formatted_acknowledges\r\n };\r\n });\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * Get triggers and its details for panel's targets\r\n * Returns alert state ('ok' if no fired triggers, or 'alerting' if at least 1 trigger is fired)\r\n * or empty object if no related triggers are finded.\r\n */\r\n alertQuery(options) {\r\n let enabled_targets = filterEnabledTargets(options.targets);\r\n let getPanelItems = _.map(enabled_targets, t => {\r\n let target = _.cloneDeep(t);\r\n this.replaceTargetVariables(target, options);\r\n return this.zabbix.getItemsFromTarget(target, {itemtype: 'num'});\r\n });\r\n\r\n return Promise.all(getPanelItems)\r\n .then(results => {\r\n let items = _.flatten(results);\r\n let itemids = _.map(items, 'itemid');\r\n\r\n if (itemids.length === 0) {\r\n return [];\r\n }\r\n return this.zabbix.getAlerts(itemids);\r\n })\r\n .then(triggers => {\r\n triggers = _.filter(triggers, trigger => {\r\n return trigger.priority >= this.alertingMinSeverity;\r\n });\r\n\r\n if (!triggers || triggers.length === 0) {\r\n return {};\r\n }\r\n\r\n let state = 'ok';\r\n\r\n let firedTriggers = _.filter(triggers, {value: '1'});\r\n if (firedTriggers.length) {\r\n state = 'alerting';\r\n }\r\n\r\n let thresholds = _.map(triggers, trigger => {\r\n return getTriggerThreshold(trigger.expression);\r\n });\r\n\r\n return {\r\n panelId: options.panelId,\r\n state: state,\r\n thresholds: thresholds\r\n };\r\n });\r\n }\r\n\r\n // Replace template variables\r\n replaceTargetVariables(target, options) {\r\n let parts = ['group', 'host', 'application', 'item'];\r\n _.forEach(parts, p => {\r\n if (target[p] && target[p].filter) {\r\n target[p].filter = this.replaceTemplateVars(target[p].filter, options.scopedVars);\r\n }\r\n });\r\n target.textFilter = this.replaceTemplateVars(target.textFilter, options.scopedVars);\r\n\r\n _.forEach(target.functions, func => {\r\n func.params = _.map(func.params, param => {\r\n if (typeof param === 'number') {\r\n return +this.templateSrv.replace(param.toString(), options.scopedVars);\r\n } else {\r\n return this.templateSrv.replace(param, options.scopedVars);\r\n }\r\n });\r\n });\r\n }\r\n\r\n isUseTrends(timeRange) {\r\n let [timeFrom, timeTo] = timeRange;\r\n let useTrendsFrom = Math.ceil(dateMath.parse('now-' + this.trendsFrom) / 1000);\r\n let useTrendsRange = Math.ceil(utils.parseInterval(this.trendsRange) / 1000);\r\n let useTrends = this.trends && (\r\n (timeFrom <= useTrendsFrom) ||\r\n (timeTo - timeFrom >= useTrendsRange)\r\n );\r\n return useTrends;\r\n }\r\n}\r\n\r\nfunction bindFunctionDefs(functionDefs, category) {\r\n var aggregationFunctions = _.map(metricFunctions.getCategories()[category], 'name');\r\n var aggFuncDefs = _.filter(functionDefs, function(func) {\r\n return _.includes(aggregationFunctions, func.def.name);\r\n });\r\n\r\n return _.map(aggFuncDefs, function(func) {\r\n var funcInstance = metricFunctions.createFuncInstance(func.def, func.params);\r\n return funcInstance.bindFunction(dataProcessor.metricFunctions);\r\n });\r\n}\r\n\r\nfunction getConsolidateBy(target) {\r\n let consolidateBy = 'avg';\r\n let funcDef = _.find(target.functions, func => {\r\n return func.def.name === 'consolidateBy';\r\n });\r\n if (funcDef && funcDef.params && funcDef.params.length) {\r\n consolidateBy = funcDef.params[0];\r\n }\r\n return consolidateBy;\r\n}\r\n\r\nfunction downsampleSeries(timeseries_data, options) {\r\n let defaultAgg = dataProcessor.aggregationFunctions['avg'];\r\n let consolidateByFunc = dataProcessor.aggregationFunctions[options.consolidateBy] || defaultAgg;\r\n return _.map(timeseries_data, timeseries => {\r\n if (timeseries.datapoints.length > options.maxDataPoints) {\r\n timeseries.datapoints = dataProcessor\r\n .groupBy(options.interval, consolidateByFunc, timeseries.datapoints);\r\n }\r\n return timeseries;\r\n });\r\n}\r\n\r\nfunction formatMetric(metricObj) {\r\n return {\r\n text: metricObj.name,\r\n expandable: false\r\n };\r\n}\r\n\r\n/**\r\n * Custom formatter for template variables.\r\n * Default Grafana \"regex\" formatter returns\r\n * value1|value2\r\n * This formatter returns\r\n * (value1|value2)\r\n * This format needed for using in complex regex with\r\n * template variables, for example\r\n * /CPU $cpu_item.*time/ where $cpu_item is system,user,iowait\r\n */\r\nfunction zabbixTemplateFormat(value) {\r\n if (typeof value === 'string') {\r\n return utils.escapeRegex(value);\r\n }\r\n\r\n var escapedValues = _.map(value, utils.escapeRegex);\r\n return '(' + escapedValues.join('|') + ')';\r\n}\r\n\r\nfunction zabbixItemIdsTemplateFormat(value) {\r\n if (typeof value === 'string') {\r\n return value;\r\n }\r\n return value.join(',');\r\n}\r\n\r\n/**\r\n * If template variables are used in request, replace it using regex format\r\n * and wrap with '/' for proper multi-value work. Example:\r\n * $variable selected as a, b, c\r\n * We use filter $variable\r\n * $variable -> a|b|c -> /a|b|c/\r\n * /$variable/ -> /a|b|c/ -> /a|b|c/\r\n */\r\nfunction replaceTemplateVars(templateSrv, target, scopedVars) {\r\n var replacedTarget = templateSrv.replace(target, scopedVars, zabbixTemplateFormat);\r\n if (target !== replacedTarget && !utils.isRegex(replacedTarget)) {\r\n replacedTarget = '/^' + replacedTarget + '$/';\r\n }\r\n return replacedTarget;\r\n}\r\n\r\n// Apply function one by one:\r\n// sequence([a(), b(), c()]) = c(b(a()));\r\nfunction sequence(funcsArray) {\r\n return function(result) {\r\n for (var i = 0; i < funcsArray.length; i++) {\r\n result = funcsArray[i].call(this, result);\r\n }\r\n return result;\r\n };\r\n}\r\n\r\nfunction filterEnabledTargets(targets) {\r\n return _.filter(targets, target => {\r\n return !(target.hide || !target.group || !target.host || !target.item);\r\n });\r\n}\r\n\r\nfunction getTriggerThreshold(expression) {\r\n let thresholdPattern = /.*[<>=]{1,2}([\\d\\.]+)/;\r\n let finded_thresholds = expression.match(thresholdPattern);\r\n if (finded_thresholds && finded_thresholds.length >= 2) {\r\n let threshold = finded_thresholds[1];\r\n threshold = Number(threshold);\r\n return threshold;\r\n } else {\r\n return null;\r\n }\r\n}\r\n\r\nexport {ZabbixAPIDatasource, zabbixTemplateFormat};\r\n\r\n// Fix for backward compatibility with lodash 2.4\r\nif (!_.includes) {_.includes = _.contains;}\r\nif (!_.keyBy) {_.keyBy = _.indexBy;}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/img/zabbix_app_logo.svg b/dist/datasource-zabbix/img/zabbix_app_logo.svg index 237247d8b..87950ba1b 100644 --- a/dist/datasource-zabbix/img/zabbix_app_logo.svg +++ b/dist/datasource-zabbix/img/zabbix_app_logo.svg @@ -1,107 +1,107 @@ - - - -image/svg+xml + + +image/svg+xml \ No newline at end of file diff --git a/dist/datasource-zabbix/metric-function-editor.directive.js.map b/dist/datasource-zabbix/metric-function-editor.directive.js.map index ca5b8ba76..c275d0a53 100644 --- a/dist/datasource-zabbix/metric-function-editor.directive.js.map +++ b/dist/datasource-zabbix/metric-function-editor.directive.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/metric-function-editor.directive.js"],"names":["angular","_","$","module","directive","$compile","templateSrv","funcSpanTemplate","paramTemplate","funcControlsTemplate","restrict","link","postLink","$scope","elem","$funcLink","$funcControls","ctrl","func","funcDef","def","scheduledRelink","paramCountAtLink","clickFuncParam","paramIndex","$link","$input","next","val","params","css","width","hide","show","focus","select","typeahead","data","lookup","scheduledRelinkIfNeeded","length","setTimeout","relink","inputBlur","prev","newValue","optional","html","highlightVariablesAsHtml","updateParam","$apply","targetChanged","inputKeyPress","e","which","call","inputKeyDown","style","value","addTypeahead","attr","options","type","map","toString","source","minLength","items","updater","query","$element","process","toggleFuncControls","targetDiv","closest","hasClass","removeClass","addClass","addElementsAndCompile","appendTo","each","param","index","paramValue","$paramLink","blur","partial","keyup","keypress","click","contents","ifJustAddedFocusFistParam","added","find","first","registerFuncControlsToggle","registerFuncControlsActions","$target","target","removeFunction","move","functions","$index","docSite","window","open","name","toLowerCase","children","remove"],"mappings":";;;;;;;;;AAAOA,a;;AACAC,O;;AACAC,O;;;;AAEP;AACAF,cACGG,MADH,CACU,oBADV,EAEGC,SAFH,CAEa,sBAFb,EAEqC,UAASC,QAAT,EAAmBC,WAAnB,EAAgC;;AAEjE,YAAIC,mBAAmB,oDAAvB;AACA,YAAIC,gBAAgB,4CACA,oDADpB;;AAGA,YAAIC,uBACD,2CACE,gDADF,GAE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,CAAoB,UAASpC,CAAT,EAAY;AAC9B,oBAAI4C,UAAU/F,EAAEmD,EAAE6C,MAAJ,CAAd;AACA,oBAAID,QAAQtB,QAAR,CAAiB,WAAjB,CAAJ,EAAmC;AACjCH;AACA3D,yBAAOqC,MAAP,CAAc,YAAW;AACvBjC,yBAAKkF,cAAL,CAAoBtF,OAAOK,IAA3B;AACD,mBAFD;AAGA;AACD;;AAED,oBAAI+E,QAAQtB,QAAR,CAAiB,eAAjB,CAAJ,EAAuC;AACrC9D,yBAAOqC,MAAP,CAAc,YAAW;AACvBjD,sBAAEmG,IAAF,CAAOvF,OAAOqF,MAAP,CAAcG,SAArB,EAAgCxF,OAAOyF,MAAvC,EAA+CzF,OAAOyF,MAAP,GAAgB,CAA/D;AACArF,yBAAKkC,aAAL;AACD,mBAHD;AAIA;AACD;;AAED,oBAAI8C,QAAQtB,QAAR,CAAiB,gBAAjB,CAAJ,EAAwC;AACtC9D,yBAAOqC,MAAP,CAAc,YAAW;AACvBjD,sBAAEmG,IAAF,CAAOvF,OAAOqF,MAAP,CAAcG,SAArB,EAAgCxF,OAAOyF,MAAvC,EAA+CzF,OAAOyF,MAAP,GAAgB,CAA/D;AACArF,yBAAKkC,aAAL;AACD,mBAHD;AAIA;AACD;;AAED,oBAAI8C,QAAQtB,QAAR,CAAiB,oBAAjB,CAAJ,EAA4C;AAC1C,sBAAI4B,UAAU,qDAAd;AACAC,yBAAOC,IAAP,CAAYF,UAAU,GAAV,GAAgBpF,QAAQuF,IAAR,CAAaC,WAAb,EAA5B,EAAuD,QAAvD;AACA;AACD;AACF,eA/BD;AAgCD;;AAED,qBAASjE,MAAT,GAAkB;AAChB5B,mBAAK8F,QAAL,GAAgBC,MAAhB;;AAEA/B;AACAa;AACAI;AACAC;AACD;;AAEDtD;AACD;AA3NI,SAAP;AA8ND,OA9OH","file":"metric-function-editor.directive.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\nimport $ from 'jquery';\n\n/** @ngInject */\nangular\n .module('grafana.directives')\n .directive('metricFunctionEditor', function($compile, templateSrv) {\n\n var funcSpanTemplate = '{{func.def.name}}(';\n var paramTemplate = '';\n\n var funcControlsTemplate =\n '
' +\n '' +\n '' +\n '' +\n '' +\n '
';\n\n return {\n restrict: 'A',\n link: function postLink($scope, elem) {\n var $funcLink = $(funcSpanTemplate);\n var $funcControls = $(funcControlsTemplate);\n var ctrl = $scope.ctrl;\n var func = $scope.func;\n var funcDef = func.def;\n var scheduledRelink = false;\n var paramCountAtLink = 0;\n\n function clickFuncParam(paramIndex) {\n /*jshint validthis:true */\n\n var $link = $(this);\n var $input = $link.next();\n\n $input.val(func.params[paramIndex]);\n $input.css('width', ($link.width() + 16) + 'px');\n\n $link.hide();\n $input.show();\n $input.focus();\n $input.select();\n\n var typeahead = $input.data('typeahead');\n if (typeahead) {\n $input.val('');\n typeahead.lookup();\n }\n }\n\n function scheduledRelinkIfNeeded() {\n if (paramCountAtLink === func.params.length) {\n return;\n }\n\n if (!scheduledRelink) {\n scheduledRelink = true;\n setTimeout(function() {\n relink();\n scheduledRelink = false;\n }, 200);\n }\n }\n\n function inputBlur(paramIndex) {\n /*jshint validthis:true */\n var $input = $(this);\n var $link = $input.prev();\n var newValue = $input.val();\n\n if (newValue !== '' || func.def.params[paramIndex].optional) {\n $link.html(templateSrv.highlightVariablesAsHtml(newValue));\n\n func.updateParam($input.val(), paramIndex);\n scheduledRelinkIfNeeded();\n\n $scope.$apply(function() {\n ctrl.targetChanged();\n });\n\n $input.hide();\n $link.show();\n }\n }\n\n function inputKeyPress(paramIndex, e) {\n /*jshint validthis:true */\n if(e.which === 13) {\n inputBlur.call(this, paramIndex);\n }\n }\n\n function inputKeyDown() {\n /*jshint validthis:true */\n this.style.width = (3 + this.value.length) * 8 + 'px';\n }\n\n function addTypeahead($input, paramIndex) {\n $input.attr('data-provide', 'typeahead');\n\n var options = funcDef.params[paramIndex].options;\n if (funcDef.params[paramIndex].type === 'int' ||\n funcDef.params[paramIndex].type === 'float') {\n options = _.map(options, function(val) { return val.toString(); });\n }\n\n $input.typeahead({\n source: options,\n minLength: 0,\n items: 20,\n updater: function (value) {\n setTimeout(function() {\n inputBlur.call($input[0], paramIndex);\n }, 0);\n return value;\n }\n });\n\n var typeahead = $input.data('typeahead');\n typeahead.lookup = function () {\n this.query = this.$element.val() || '';\n return this.process(this.source);\n };\n }\n\n function toggleFuncControls() {\n var targetDiv = elem.closest('.tight-form');\n\n if (elem.hasClass('show-function-controls')) {\n elem.removeClass('show-function-controls');\n targetDiv.removeClass('has-open-function');\n $funcControls.hide();\n return;\n }\n\n elem.addClass('show-function-controls');\n targetDiv.addClass('has-open-function');\n\n $funcControls.show();\n }\n\n function addElementsAndCompile() {\n $funcControls.appendTo(elem);\n $funcLink.appendTo(elem);\n\n _.each(funcDef.params, function(param, index) {\n if (param.optional && func.params.length <= index) {\n return;\n }\n\n if (index > 0) {\n $(', ').appendTo(elem);\n }\n\n var paramValue = templateSrv.highlightVariablesAsHtml(func.params[index]);\n var $paramLink = $('' + paramValue + '');\n var $input = $(paramTemplate);\n\n paramCountAtLink++;\n\n $paramLink.appendTo(elem);\n $input.appendTo(elem);\n\n $input.blur(_.partial(inputBlur, index));\n $input.keyup(inputKeyDown);\n $input.keypress(_.partial(inputKeyPress, index));\n $paramLink.click(_.partial(clickFuncParam, index));\n\n if (funcDef.params[index].options) {\n addTypeahead($input, index);\n }\n\n });\n\n $(')').appendTo(elem);\n\n $compile(elem.contents())($scope);\n }\n\n function ifJustAddedFocusFistParam() {\n if ($scope.func.added) {\n $scope.func.added = false;\n setTimeout(function() {\n elem.find('.graphite-func-param-link').first().click();\n }, 10);\n }\n }\n\n function registerFuncControlsToggle() {\n $funcLink.click(toggleFuncControls);\n }\n\n function registerFuncControlsActions() {\n $funcControls.click(function(e) {\n var $target = $(e.target);\n if ($target.hasClass('fa-remove')) {\n toggleFuncControls();\n $scope.$apply(function() {\n ctrl.removeFunction($scope.func);\n });\n return;\n }\n\n if ($target.hasClass('fa-arrow-left')) {\n $scope.$apply(function() {\n _.move($scope.target.functions, $scope.$index, $scope.$index - 1);\n ctrl.targetChanged();\n });\n return;\n }\n\n if ($target.hasClass('fa-arrow-right')) {\n $scope.$apply(function() {\n _.move($scope.target.functions, $scope.$index, $scope.$index + 1);\n ctrl.targetChanged();\n });\n return;\n }\n\n if ($target.hasClass('fa-question-circle')) {\n var docSite = \"http://docs.grafana-zabbix.org/reference/functions/\";\n window.open(docSite + '#' + funcDef.name.toLowerCase(),'_blank');\n return;\n }\n });\n }\n\n function relink() {\n elem.children().remove();\n\n addElementsAndCompile();\n ifJustAddedFocusFistParam();\n registerFuncControlsToggle();\n registerFuncControlsActions();\n }\n\n relink();\n }\n };\n\n });\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/metric-function-editor.directive.js"],"names":["angular","_","$","module","directive","$compile","templateSrv","funcSpanTemplate","paramTemplate","funcControlsTemplate","restrict","link","postLink","$scope","elem","$funcLink","$funcControls","ctrl","func","funcDef","def","scheduledRelink","paramCountAtLink","clickFuncParam","paramIndex","$link","$input","next","val","params","css","width","hide","show","focus","select","typeahead","data","lookup","scheduledRelinkIfNeeded","length","setTimeout","relink","inputBlur","prev","newValue","optional","html","highlightVariablesAsHtml","updateParam","$apply","targetChanged","inputKeyPress","e","which","call","inputKeyDown","style","value","addTypeahead","attr","options","type","map","toString","source","minLength","items","updater","query","$element","process","toggleFuncControls","targetDiv","closest","hasClass","removeClass","addClass","addElementsAndCompile","appendTo","each","param","index","paramValue","$paramLink","blur","partial","keyup","keypress","click","contents","ifJustAddedFocusFistParam","added","find","first","registerFuncControlsToggle","registerFuncControlsActions","$target","target","removeFunction","move","functions","$index","docSite","window","open","name","toLowerCase","children","remove"],"mappings":";;;;;;;;;AAAOA,a;;AACAC,O;;AACAC,O;;;;AAEP;AACAF,cACGG,MADH,CACU,oBADV,EAEGC,SAFH,CAEa,sBAFb,EAEqC,UAASC,QAAT,EAAmBC,WAAnB,EAAgC;;AAEjE,YA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":"metric-function-editor.directive.js","sourcesContent":["import angular from 'angular';\r\nimport _ from 'lodash';\r\nimport $ from 'jquery';\r\n\r\n/** @ngInject */\r\nangular\r\n .module('grafana.directives')\r\n .directive('metricFunctionEditor', function($compile, templateSrv) {\r\n\r\n var funcSpanTemplate = '{{func.def.name}}(';\r\n var paramTemplate = '';\r\n\r\n var funcControlsTemplate =\r\n '
' +\r\n '' +\r\n '' +\r\n '' +\r\n '' +\r\n '
';\r\n\r\n return {\r\n restrict: 'A',\r\n link: function postLink($scope, elem) {\r\n var $funcLink = $(funcSpanTemplate);\r\n var $funcControls = $(funcControlsTemplate);\r\n var ctrl = $scope.ctrl;\r\n var func = $scope.func;\r\n var funcDef = func.def;\r\n var scheduledRelink = false;\r\n var paramCountAtLink = 0;\r\n\r\n function clickFuncParam(paramIndex) {\r\n /*jshint validthis:true */\r\n\r\n var $link = $(this);\r\n var $input = $link.next();\r\n\r\n $input.val(func.params[paramIndex]);\r\n $input.css('width', ($link.width() + 16) + 'px');\r\n\r\n $link.hide();\r\n $input.show();\r\n $input.focus();\r\n $input.select();\r\n\r\n var typeahead = $input.data('typeahead');\r\n if (typeahead) {\r\n $input.val('');\r\n typeahead.lookup();\r\n }\r\n }\r\n\r\n function scheduledRelinkIfNeeded() {\r\n if (paramCountAtLink === func.params.length) {\r\n return;\r\n }\r\n\r\n if (!scheduledRelink) {\r\n scheduledRelink = true;\r\n setTimeout(function() {\r\n relink();\r\n scheduledRelink = false;\r\n }, 200);\r\n }\r\n }\r\n\r\n function inputBlur(paramIndex) {\r\n /*jshint validthis:true */\r\n var $input = $(this);\r\n var $link = $input.prev();\r\n var newValue = $input.val();\r\n\r\n if (newValue !== '' || func.def.params[paramIndex].optional) {\r\n $link.html(templateSrv.highlightVariablesAsHtml(newValue));\r\n\r\n func.updateParam($input.val(), paramIndex);\r\n scheduledRelinkIfNeeded();\r\n\r\n $scope.$apply(function() {\r\n ctrl.targetChanged();\r\n });\r\n\r\n $input.hide();\r\n $link.show();\r\n }\r\n }\r\n\r\n function inputKeyPress(paramIndex, e) {\r\n /*jshint validthis:true */\r\n if(e.which === 13) {\r\n inputBlur.call(this, paramIndex);\r\n }\r\n }\r\n\r\n function inputKeyDown() {\r\n /*jshint validthis:true */\r\n this.style.width = (3 + this.value.length) * 8 + 'px';\r\n }\r\n\r\n function addTypeahead($input, paramIndex) {\r\n $input.attr('data-provide', 'typeahead');\r\n\r\n var options = funcDef.params[paramIndex].options;\r\n if (funcDef.params[paramIndex].type === 'int' ||\r\n funcDef.params[paramIndex].type === 'float') {\r\n options = _.map(options, function(val) { return val.toString(); });\r\n }\r\n\r\n $input.typeahead({\r\n source: options,\r\n minLength: 0,\r\n items: 20,\r\n updater: function (value) {\r\n setTimeout(function() {\r\n inputBlur.call($input[0], paramIndex);\r\n }, 0);\r\n return value;\r\n }\r\n });\r\n\r\n var typeahead = $input.data('typeahead');\r\n typeahead.lookup = function () {\r\n this.query = this.$element.val() || '';\r\n return this.process(this.source);\r\n };\r\n }\r\n\r\n function toggleFuncControls() {\r\n var targetDiv = elem.closest('.tight-form');\r\n\r\n if (elem.hasClass('show-function-controls')) {\r\n elem.removeClass('show-function-controls');\r\n targetDiv.removeClass('has-open-function');\r\n $funcControls.hide();\r\n return;\r\n }\r\n\r\n elem.addClass('show-function-controls');\r\n targetDiv.addClass('has-open-function');\r\n\r\n $funcControls.show();\r\n }\r\n\r\n function addElementsAndCompile() {\r\n $funcControls.appendTo(elem);\r\n $funcLink.appendTo(elem);\r\n\r\n _.each(funcDef.params, function(param, index) {\r\n if (param.optional && func.params.length <= index) {\r\n return;\r\n }\r\n\r\n if (index > 0) {\r\n $(', ').appendTo(elem);\r\n }\r\n\r\n var paramValue = templateSrv.highlightVariablesAsHtml(func.params[index]);\r\n var $paramLink = $('' + paramValue + '');\r\n var $input = $(paramTemplate);\r\n\r\n paramCountAtLink++;\r\n\r\n $paramLink.appendTo(elem);\r\n $input.appendTo(elem);\r\n\r\n $input.blur(_.partial(inputBlur, index));\r\n $input.keyup(inputKeyDown);\r\n $input.keypress(_.partial(inputKeyPress, index));\r\n $paramLink.click(_.partial(clickFuncParam, index));\r\n\r\n if (funcDef.params[index].options) {\r\n addTypeahead($input, index);\r\n }\r\n\r\n });\r\n\r\n $(')').appendTo(elem);\r\n\r\n $compile(elem.contents())($scope);\r\n }\r\n\r\n function ifJustAddedFocusFistParam() {\r\n if ($scope.func.added) {\r\n $scope.func.added = false;\r\n setTimeout(function() {\r\n elem.find('.graphite-func-param-link').first().click();\r\n }, 10);\r\n }\r\n }\r\n\r\n function registerFuncControlsToggle() {\r\n $funcLink.click(toggleFuncControls);\r\n }\r\n\r\n function registerFuncControlsActions() {\r\n $funcControls.click(function(e) {\r\n var $target = $(e.target);\r\n if ($target.hasClass('fa-remove')) {\r\n toggleFuncControls();\r\n $scope.$apply(function() {\r\n ctrl.removeFunction($scope.func);\r\n });\r\n return;\r\n }\r\n\r\n if ($target.hasClass('fa-arrow-left')) {\r\n $scope.$apply(function() {\r\n _.move($scope.target.functions, $scope.$index, $scope.$index - 1);\r\n ctrl.targetChanged();\r\n });\r\n return;\r\n }\r\n\r\n if ($target.hasClass('fa-arrow-right')) {\r\n $scope.$apply(function() {\r\n _.move($scope.target.functions, $scope.$index, $scope.$index + 1);\r\n ctrl.targetChanged();\r\n });\r\n return;\r\n }\r\n\r\n if ($target.hasClass('fa-question-circle')) {\r\n var docSite = \"http://docs.grafana-zabbix.org/reference/functions/\";\r\n window.open(docSite + '#' + funcDef.name.toLowerCase(),'_blank');\r\n return;\r\n }\r\n });\r\n }\r\n\r\n function relink() {\r\n elem.children().remove();\r\n\r\n addElementsAndCompile();\r\n ifJustAddedFocusFistParam();\r\n registerFuncControlsToggle();\r\n registerFuncControlsActions();\r\n }\r\n\r\n relink();\r\n }\r\n };\r\n\r\n });\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/metricFunctions.js b/dist/datasource-zabbix/metricFunctions.js index d6bd53fef..6e68c6b4b 100644 --- a/dist/datasource-zabbix/metricFunctions.js +++ b/dist/datasource-zabbix/metricFunctions.js @@ -125,6 +125,13 @@ System.register(['lodash', 'jquery'], function (_export, _context) { defaultParams: [0.2] }); + addFuncDef({ + name: 'transformNull', + category: 'Transform', + params: [{ name: 'number', type: 'float' }], + defaultParams: [0] + }); + // Aggregate addFuncDef({ @@ -192,6 +199,20 @@ System.register(['lodash', 'jquery'], function (_export, _context) { // Filter + addFuncDef({ + name: 'removeAboveValue', + category: 'Filter', + params: [{ name: 'number', type: 'float' }], + defaultParams: [0] + }); + + addFuncDef({ + name: 'removeBelowValue', + category: 'Filter', + params: [{ name: 'number', type: 'float' }], + defaultParams: [0] + }); + addFuncDef({ name: 'top', category: 'Filter', diff --git a/dist/datasource-zabbix/metricFunctions.js.map b/dist/datasource-zabbix/metricFunctions.js.map index 0f1cf36f4..643779888 100644 --- a/dist/datasource-zabbix/metricFunctions.js.map +++ b/dist/datasource-zabbix/metricFunctions.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/metricFunctions.js"],"names":["addFuncDef","funcDef","params","defaultParams","category","categories","push","index","name","shortName","createFuncInstance","_","isString","message","FuncInstance","getFuncDef","getCategories","$","Transform","Aggregate","Filter","Trends","Time","Alias","Special","type","options","each","funcList","catName","sortBy","def","slice","updateText","metricFunctions","func","bindedFunc","param","i","length","Number","partial","metricExp","str","parameters","map","value","paramType","isNumeric","unshift","join","strValue","indexOf","optional","_hasMultipleParamsInString","split","partVal","idx","updateParam","trim","splice","text"],"mappings":";;;;;;;;;;;;;AAcA,WAASA,UAAT,CAAoBC,OAApB,EAA6B;AAC3BA,YAAQC,MAAR,GAAiBD,QAAQC,MAAR,IAAkB,EAAnC;AACAD,YAAQE,aAAR,GAAwBF,QAAQE,aAAR,IAAyB,EAAjD;;AAEA,QAAIF,QAAQG,QAAZ,EAAsB;AACpBC,iBAAWJ,QAAQG,QAAnB,EAA6BE,IAA7B,CAAkCL,OAAlC;AACD;AACDM,UAAMN,QAAQO,IAAd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ED,gBAAIN,aAAa,EAAb,IAAmB,KAAKpB,GAAL,CAAS7B,MAAT,CAAgBK,KAAhB,EAAuB8C,QAA9C,EAAwD;AACtD,mBAAKnD,MAAL,CAAY0D,MAAZ,CAAmBrD,KAAnB,EAA0B,CAA1B;AACD,aAFD,MAGK;AACH,mBAAKL,MAAL,CAAYK,KAAZ,IAAqB4C,QAArB;AACD;;AAED,iBAAKlB,UAAL;AACD;;;uCAEY;AACX,gBAAI,KAAK/B,MAAL,CAAYqC,MAAZ,KAAuB,CAA3B,EAA8B;AAC5B,mBAAKsB,IAAL,GAAY,KAAK9B,GAAL,CAASvB,IAAT,GAAgB,IAA5B;AACA;AACD;;AAED,gBAAIqD,OAAO,KAAK9B,GAAL,CAASvB,IAAT,GAAgB,GAA3B;AACAqD,oBAAQ,KAAK3D,MAAL,CAAYgD,IAAZ,CAAiB,IAAjB,CAAR;AACAW,oBAAQ,GAAR;AACA,iBAAKA,IAAL,GAAYA,IAAZ;AACD","file":"metricFunctions.js","sourcesContent":["import _ from 'lodash';\nimport $ from 'jquery';\n\nvar index = [];\nvar categories = {\n Transform: [],\n Aggregate: [],\n Filter: [],\n Trends: [],\n Time: [],\n Alias: [],\n Special: []\n};\n\nfunction addFuncDef(funcDef) {\n funcDef.params = funcDef.params || [];\n funcDef.defaultParams = funcDef.defaultParams || [];\n\n if (funcDef.category) {\n categories[funcDef.category].push(funcDef);\n }\n index[funcDef.name] = funcDef;\n index[funcDef.shortName || funcDef.name] = funcDef;\n}\n\n// Transform\n\naddFuncDef({\n name: 'groupBy',\n category: 'Transform',\n params: [\n { name: 'interval', type: 'string'},\n { name: 'function', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\n ],\n defaultParams: ['1m', 'avg'],\n});\n\naddFuncDef({\n name: 'scale',\n category: 'Transform',\n params: [\n { name: 'factor', type: 'float', options: [100, 0.01, 10, -1]}\n ],\n defaultParams: [100],\n});\n\naddFuncDef({\n name: 'delta',\n category: 'Transform',\n params: [],\n defaultParams: [],\n});\n\naddFuncDef({\n name: 'rate',\n category: 'Transform',\n params: [],\n defaultParams: [],\n});\n\naddFuncDef({\n name: 'movingAverage',\n category: 'Transform',\n params: [\n { name: 'factor', type: 'int', options: [6, 10, 60, 100, 600] }\n ],\n defaultParams: [10],\n});\n\naddFuncDef({\n name: 'exponentialMovingAverage',\n category: 'Transform',\n params: [\n { name: 'smoothing', type: 'float', options: [6, 10, 60, 100, 600] }\n ],\n defaultParams: [0.2],\n});\n\n// Aggregate\n\naddFuncDef({\n name: 'sumSeries',\n category: 'Aggregate',\n params: [],\n defaultParams: [],\n});\n\naddFuncDef({\n name: 'median',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string'}\n ],\n defaultParams: ['1m'],\n});\n\naddFuncDef({\n name: 'average',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' }\n ],\n defaultParams: ['1m'],\n});\n\naddFuncDef({\n name: 'percentil',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' },\n { name: 'percent', type: 'float', options: [25, 50, 75, 90, 95, 99, 99.9] }\n ],\n defaultParams: ['1m', 95],\n});\n\naddFuncDef({\n name: 'min',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' }\n ],\n defaultParams: ['1m'],\n});\n\naddFuncDef({\n name: 'max',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' }\n ],\n defaultParams: ['1m'],\n});\n\naddFuncDef({\n name: 'sum',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' }\n ],\n defaultParams: ['1m'],\n});\n\naddFuncDef({\n name: 'count',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' }\n ],\n defaultParams: ['1m'],\n});\n\naddFuncDef({\n name: 'aggregateBy',\n category: 'Aggregate',\n params: [\n { name: 'interval', type: 'string' },\n { name: 'function', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\n ],\n defaultParams: ['1m', 'avg'],\n});\n\n// Filter\n\naddFuncDef({\n name: 'top',\n category: 'Filter',\n params: [\n { name: 'number', type: 'int' },\n { name: 'value', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\n ],\n defaultParams: [5, 'avg'],\n});\n\naddFuncDef({\n name: 'bottom',\n category: 'Filter',\n params: [\n { name: 'number', type: 'int' },\n { name: 'value', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\n ],\n defaultParams: [5, 'avg'],\n});\n\naddFuncDef({\n name: 'sortSeries',\n category: 'Filter',\n params: [\n { name: 'direction', type: 'string', options: ['asc', 'desc'] }\n ],\n defaultParams: ['asc']\n});\n\n// Trends\n\naddFuncDef({\n name: 'trendValue',\n category: 'Trends',\n params: [\n { name: 'type', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count'] }\n ],\n defaultParams: ['avg'],\n});\n\n// Time\n\naddFuncDef({\n name: 'timeShift',\n category: 'Time',\n params: [\n { name: 'interval', type: 'string', options: ['24h', '7d', '1M', '+24h', '-24h']}\n ],\n defaultParams: ['24h'],\n});\n\n//Alias\n\naddFuncDef({\n name: 'setAlias',\n category: 'Alias',\n params: [\n { name: 'alias', type: 'string' }\n ],\n defaultParams: []\n});\n\naddFuncDef({\n name: 'setAliasByRegex',\n category: 'Alias',\n params: [\n { name: 'aliasByRegex', type: 'string' }\n ],\n defaultParams: []\n});\n\naddFuncDef({\n name: 'replaceAlias',\n category: 'Alias',\n params: [\n { name: 'regexp', type: 'string' },\n { name: 'newAlias', type: 'string' }\n ],\n defaultParams: ['/(.*)/', '$1']\n});\n\n// Special\naddFuncDef({\n name: 'consolidateBy',\n category: 'Special',\n params: [\n { name: 'type', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count'] }\n ],\n defaultParams: ['avg'],\n});\n\n_.each(categories, function(funcList, catName) {\n categories[catName] = _.sortBy(funcList, 'name');\n});\n\nclass FuncInstance {\n constructor(funcDef, params) {\n this.def = funcDef;\n\n if (params) {\n this.params = params;\n } else {\n // Create with default params\n this.params = [];\n this.params = funcDef.defaultParams.slice(0);\n }\n\n this.updateText();\n }\n\n bindFunction(metricFunctions) {\n var func = metricFunctions[this.def.name];\n if (func) {\n\n // Bind function arguments\n var bindedFunc = func;\n var param;\n for (var i = 0; i < this.params.length; i++) {\n param = this.params[i];\n\n // Convert numeric params\n if (this.def.params[i].type === 'int' ||\n this.def.params[i].type === 'float') {\n param = Number(param);\n }\n bindedFunc = _.partial(bindedFunc, param);\n }\n return bindedFunc;\n } else {\n throw { message: 'Method not found ' + this.def.name };\n }\n }\n\n render(metricExp) {\n var str = this.def.name + '(';\n var parameters = _.map(this.params, function(value, index) {\n\n var paramType = this.def.params[index].type;\n if (paramType === 'int' ||\n paramType === 'float' ||\n paramType === 'value_or_series' ||\n paramType === 'boolean') {\n return value;\n }\n else if (paramType === 'int_or_interval' && $.isNumeric(value)) {\n return value;\n }\n\n return \"'\" + value + \"'\";\n\n }, this);\n\n if (metricExp) {\n parameters.unshift(metricExp);\n }\n\n return str + parameters.join(', ') + ')';\n }\n\n _hasMultipleParamsInString(strValue, index) {\n if (strValue.indexOf(',') === -1) {\n return false;\n }\n\n return this.def.params[index + 1] && this.def.params[index + 1].optional;\n }\n\n updateParam(strValue, index) {\n // handle optional parameters\n // if string contains ',' and next param is optional, split and update both\n if (this._hasMultipleParamsInString(strValue, index)) {\n _.each(strValue.split(','), function(partVal, idx) {\n this.updateParam(partVal.trim(), idx);\n }, this);\n return;\n }\n\n if (strValue === '' && this.def.params[index].optional) {\n this.params.splice(index, 1);\n }\n else {\n this.params[index] = strValue;\n }\n\n this.updateText();\n }\n\n updateText() {\n if (this.params.length === 0) {\n this.text = this.def.name + '()';\n return;\n }\n\n var text = this.def.name + '(';\n text += this.params.join(', ');\n text += ')';\n this.text = text;\n }\n}\n\nexport function createFuncInstance(funcDef, params) {\n if (_.isString(funcDef)) {\n if (!index[funcDef]) {\n throw { message: 'Method not found ' + name };\n }\n funcDef = index[funcDef];\n }\n return new FuncInstance(funcDef, params);\n}\n\nexport function getFuncDef(name) {\n return index[name];\n}\n\nexport function getCategories() {\n return categories;\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/metricFunctions.js"],"names":["addFuncDef","funcDef","params","defaultParams","category","categories","push","index","name","shortName","createFuncInstance","_","isString","message","FuncInstance","getFuncDef","getCategories","$","Transform","Aggregate","Filter","Trends","Time","Alias","Special","type","options","each","funcList","catName","sortBy","def","slice","updateText","metricFunctions","func","bindedFunc","param","i","length","Number","partial","metricExp","str","parameters","map","value","paramType","isNumeric","unshift","join","strValue","indexOf","optional","_hasMultipleParamsInString","split","partVal","idx","updateParam","trim","splice","text"],"mappings":";;;;;;;;;;;;;AAcA,WAASA,UAAT,CAAoBC,OAApB,EAA6B;AAC3BA,YAAQC,MAAR,GAAiBD,QAAQC,MAAR,IAAkB,EAAnC;AACAD,YAAQE,aAAR,GAAwBF,QAAQE,aAAR,IAAyB,EAAjD;;AAEA,QAAIF,QAAQG,QAAZ,EAAsB;AACpBC,iBAAWJ,QAAQG,QAAnB,EAA6BE,IAA7B,CAAkCL,OAAlC;AACD;AACDM,UAAMN,QAAQO,IAAd,IAAsBP,OAAtB;AACAM,UAAMN,QAAQQ,SAAR,IAAqBR,QAAQO,IAAnC,IAA2CP,OAA3C;AACD;;AAED;;AA6WO,WAASS,kBAAT,CAA4BT,OAA5B,EAAqCC,MAArC,EAA6C;AAClD,QAAIS,EAAEC,QAAF,CAAWX,OAAX,CAAJ,EAAyB;AACvB,UAAI,CAACM,MAAMN,OAAN,CAAL,EAAqB;AACnB,cAAM,EAAEY,SAAS,sBAAsBL,IAAjC,EAAN;AACD;AACDP,gBAAUM,MAAMN,OAAN,CAAV;AACD;AACD,WAAO,IAAIa,YAAJ,CAAiBb,OAAjB,EAA0BC,MAA1B,CAAP;AACD;;gCAReQ,kB;;AAUT,WAASK,UAAT,CAAoBP,IAApB,EAA0B;AAC/B,WAAOD,MAAMC,IAAN,CAAP;AACD;;wBAFeO,U;;AAIT,WAASC,aAA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AAL,CAAS7B,MAAT,CAAgBK,KAAhB,EAAuB8C,QAA9C,EAAwD;AACtD,mBAAKnD,MAAL,CAAY0D,MAAZ,CAAmBrD,KAAnB,EAA0B,CAA1B;AACD,aAFD,MAGK;AACH,mBAAKL,MAAL,CAAYK,KAAZ,IAAqB4C,QAArB;AACD;;AAED,iBAAKlB,UAAL;AACD;;;uCAEY;AACX,gBAAI,KAAK/B,MAAL,CAAYqC,MAAZ,KAAuB,CAA3B,EAA8B;AAC5B,mBAAKsB,IAAL,GAAY,KAAK9B,GAAL,CAASvB,IAAT,GAAgB,IAA5B;AACA;AACD;;AAED,gBAAIqD,OAAO,KAAK9B,GAAL,CAASvB,IAAT,GAAgB,GAA3B;AACAqD,oBAAQ,KAAK3D,MAAL,CAAYgD,IAAZ,CAAiB,IAAjB,CAAR;AACAW,oBAAQ,GAAR;AACA,iBAAKA,IAAL,GAAYA,IAAZ;AACD","file":"metricFunctions.js","sourcesContent":["import _ from 'lodash';\r\nimport $ from 'jquery';\r\n\r\nvar index = [];\r\nvar categories = {\r\n Transform: [],\r\n Aggregate: [],\r\n Filter: [],\r\n Trends: [],\r\n Time: [],\r\n Alias: [],\r\n Special: []\r\n};\r\n\r\nfunction addFuncDef(funcDef) {\r\n funcDef.params = funcDef.params || [];\r\n funcDef.defaultParams = funcDef.defaultParams || [];\r\n\r\n if (funcDef.category) {\r\n categories[funcDef.category].push(funcDef);\r\n }\r\n index[funcDef.name] = funcDef;\r\n index[funcDef.shortName || funcDef.name] = funcDef;\r\n}\r\n\r\n// Transform\r\n\r\naddFuncDef({\r\n name: 'groupBy',\r\n category: 'Transform',\r\n params: [\r\n { name: 'interval', type: 'string'},\r\n { name: 'function', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\r\n ],\r\n defaultParams: ['1m', 'avg'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'scale',\r\n category: 'Transform',\r\n params: [\r\n { name: 'factor', type: 'float', options: [100, 0.01, 10, -1]}\r\n ],\r\n defaultParams: [100],\r\n});\r\n\r\naddFuncDef({\r\n name: 'delta',\r\n category: 'Transform',\r\n params: [],\r\n defaultParams: [],\r\n});\r\n\r\naddFuncDef({\r\n name: 'rate',\r\n category: 'Transform',\r\n params: [],\r\n defaultParams: [],\r\n});\r\n\r\naddFuncDef({\r\n name: 'movingAverage',\r\n category: 'Transform',\r\n params: [\r\n { name: 'factor', type: 'int', options: [6, 10, 60, 100, 600] }\r\n ],\r\n defaultParams: [10],\r\n});\r\n\r\naddFuncDef({\r\n name: 'exponentialMovingAverage',\r\n category: 'Transform',\r\n params: [\r\n { name: 'smoothing', type: 'float', options: [6, 10, 60, 100, 600] }\r\n ],\r\n defaultParams: [0.2],\r\n});\r\n\r\naddFuncDef({\r\n name: 'transformNull',\r\n category: 'Transform',\r\n params: [\r\n {name: 'number', type: 'float'}\r\n ],\r\n defaultParams: [0],\r\n});\r\n\r\n// Aggregate\r\n\r\naddFuncDef({\r\n name: 'sumSeries',\r\n category: 'Aggregate',\r\n params: [],\r\n defaultParams: [],\r\n});\r\n\r\naddFuncDef({\r\n name: 'median',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string'}\r\n ],\r\n defaultParams: ['1m'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'average',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' }\r\n ],\r\n defaultParams: ['1m'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'percentil',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' },\r\n { name: 'percent', type: 'float', options: [25, 50, 75, 90, 95, 99, 99.9] }\r\n ],\r\n defaultParams: ['1m', 95],\r\n});\r\n\r\naddFuncDef({\r\n name: 'min',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' }\r\n ],\r\n defaultParams: ['1m'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'max',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' }\r\n ],\r\n defaultParams: ['1m'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'sum',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' }\r\n ],\r\n defaultParams: ['1m'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'count',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' }\r\n ],\r\n defaultParams: ['1m'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'aggregateBy',\r\n category: 'Aggregate',\r\n params: [\r\n { name: 'interval', type: 'string' },\r\n { name: 'function', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\r\n ],\r\n defaultParams: ['1m', 'avg'],\r\n});\r\n\r\n// Filter\r\n\r\naddFuncDef({\r\n name: 'removeAboveValue',\r\n category: 'Filter',\r\n params: [\r\n {name: 'number', type: 'float'},\r\n ],\r\n defaultParams: [0],\r\n});\r\n\r\naddFuncDef({\r\n name: 'removeBelowValue',\r\n category: 'Filter',\r\n params: [\r\n {name: 'number', type: 'float'},\r\n ],\r\n defaultParams: [0],\r\n});\r\n\r\naddFuncDef({\r\n name: 'top',\r\n category: 'Filter',\r\n params: [\r\n { name: 'number', type: 'int' },\r\n { name: 'value', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\r\n ],\r\n defaultParams: [5, 'avg'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'bottom',\r\n category: 'Filter',\r\n params: [\r\n { name: 'number', type: 'int' },\r\n { name: 'value', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count', 'median'] }\r\n ],\r\n defaultParams: [5, 'avg'],\r\n});\r\n\r\naddFuncDef({\r\n name: 'sortSeries',\r\n category: 'Filter',\r\n params: [\r\n { name: 'direction', type: 'string', options: ['asc', 'desc'] }\r\n ],\r\n defaultParams: ['asc']\r\n});\r\n\r\n// Trends\r\n\r\naddFuncDef({\r\n name: 'trendValue',\r\n category: 'Trends',\r\n params: [\r\n { name: 'type', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count'] }\r\n ],\r\n defaultParams: ['avg'],\r\n});\r\n\r\n// Time\r\n\r\naddFuncDef({\r\n name: 'timeShift',\r\n category: 'Time',\r\n params: [\r\n { name: 'interval', type: 'string', options: ['24h', '7d', '1M', '+24h', '-24h']}\r\n ],\r\n defaultParams: ['24h'],\r\n});\r\n\r\n//Alias\r\n\r\naddFuncDef({\r\n name: 'setAlias',\r\n category: 'Alias',\r\n params: [\r\n { name: 'alias', type: 'string' }\r\n ],\r\n defaultParams: []\r\n});\r\n\r\naddFuncDef({\r\n name: 'setAliasByRegex',\r\n category: 'Alias',\r\n params: [\r\n { name: 'aliasByRegex', type: 'string' }\r\n ],\r\n defaultParams: []\r\n});\r\n\r\naddFuncDef({\r\n name: 'replaceAlias',\r\n category: 'Alias',\r\n params: [\r\n { name: 'regexp', type: 'string' },\r\n { name: 'newAlias', type: 'string' }\r\n ],\r\n defaultParams: ['/(.*)/', '$1']\r\n});\r\n\r\n// Special\r\naddFuncDef({\r\n name: 'consolidateBy',\r\n category: 'Special',\r\n params: [\r\n { name: 'type', type: 'string', options: ['avg', 'min', 'max', 'sum', 'count'] }\r\n ],\r\n defaultParams: ['avg'],\r\n});\r\n\r\n_.each(categories, function(funcList, catName) {\r\n categories[catName] = _.sortBy(funcList, 'name');\r\n});\r\n\r\nclass FuncInstance {\r\n constructor(funcDef, params) {\r\n this.def = funcDef;\r\n\r\n if (params) {\r\n this.params = params;\r\n } else {\r\n // Create with default params\r\n this.params = [];\r\n this.params = funcDef.defaultParams.slice(0);\r\n }\r\n\r\n this.updateText();\r\n }\r\n\r\n bindFunction(metricFunctions) {\r\n var func = metricFunctions[this.def.name];\r\n if (func) {\r\n\r\n // Bind function arguments\r\n var bindedFunc = func;\r\n var param;\r\n for (var i = 0; i < this.params.length; i++) {\r\n param = this.params[i];\r\n\r\n // Convert numeric params\r\n if (this.def.params[i].type === 'int' ||\r\n this.def.params[i].type === 'float') {\r\n param = Number(param);\r\n }\r\n bindedFunc = _.partial(bindedFunc, param);\r\n }\r\n return bindedFunc;\r\n } else {\r\n throw { message: 'Method not found ' + this.def.name };\r\n }\r\n }\r\n\r\n render(metricExp) {\r\n var str = this.def.name + '(';\r\n var parameters = _.map(this.params, function(value, index) {\r\n\r\n var paramType = this.def.params[index].type;\r\n if (paramType === 'int' ||\r\n paramType === 'float' ||\r\n paramType === 'value_or_series' ||\r\n paramType === 'boolean') {\r\n return value;\r\n }\r\n else if (paramType === 'int_or_interval' && $.isNumeric(value)) {\r\n return value;\r\n }\r\n\r\n return \"'\" + value + \"'\";\r\n\r\n }, this);\r\n\r\n if (metricExp) {\r\n parameters.unshift(metricExp);\r\n }\r\n\r\n return str + parameters.join(', ') + ')';\r\n }\r\n\r\n _hasMultipleParamsInString(strValue, index) {\r\n if (strValue.indexOf(',') === -1) {\r\n return false;\r\n }\r\n\r\n return this.def.params[index + 1] && this.def.params[index + 1].optional;\r\n }\r\n\r\n updateParam(strValue, index) {\r\n // handle optional parameters\r\n // if string contains ',' and next param is optional, split and update both\r\n if (this._hasMultipleParamsInString(strValue, index)) {\r\n _.each(strValue.split(','), function(partVal, idx) {\r\n this.updateParam(partVal.trim(), idx);\r\n }, this);\r\n return;\r\n }\r\n\r\n if (strValue === '' && this.def.params[index].optional) {\r\n this.params.splice(index, 1);\r\n }\r\n else {\r\n this.params[index] = strValue;\r\n }\r\n\r\n this.updateText();\r\n }\r\n\r\n updateText() {\r\n if (this.params.length === 0) {\r\n this.text = this.def.name + '()';\r\n return;\r\n }\r\n\r\n var text = this.def.name + '(';\r\n text += this.params.join(', ');\r\n text += ')';\r\n this.text = text;\r\n }\r\n}\r\n\r\nexport function createFuncInstance(funcDef, params) {\r\n if (_.isString(funcDef)) {\r\n if (!index[funcDef]) {\r\n throw { message: 'Method not found ' + name };\r\n }\r\n funcDef = index[funcDef];\r\n }\r\n return new FuncInstance(funcDef, params);\r\n}\r\n\r\nexport function getFuncDef(name) {\r\n return index[name];\r\n}\r\n\r\nexport function getCategories() {\r\n return categories;\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/migrations.js b/dist/datasource-zabbix/migrations.js index e1f0be96c..7d1c14906 100644 --- a/dist/datasource-zabbix/migrations.js +++ b/dist/datasource-zabbix/migrations.js @@ -3,9 +3,9 @@ System.register([], function (_export, _context) { "use strict"; - /** - * Query format migration. - * This module can detect query format version and make migration. + /** + * Query format migration. + * This module can detect query format version and make migration. */ function isGrafana2target(target) { diff --git a/dist/datasource-zabbix/migrations.js.map b/dist/datasource-zabbix/migrations.js.map index a10a69af9..06e01f4b4 100644 --- a/dist/datasource-zabbix/migrations.js.map +++ b/dist/datasource-zabbix/migrations.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/migrations.js"],"names":["isGrafana2target","target","mode","hostFilter","itemFilter","downsampleFunction","host","item","filter","undefined","migrateFrom2To3version","group","name","convertToRegex","application","migrate","resultFormat","str"],"mappings":";;;;;AAAA;;;;;AAKO,WAASA,gBAAT,CAA0BC,MAA1B,EAAkC;AACvC,QAAI,CAACA,OAAOC,IAAR,IAAgBD,OAAOC,IAAP,KAAgB,CAAhC,IAAqCD,OAAOC,IAAP,KAAgB,CAAzD,EAA4D;AAC1D,UAAI,CAACD,OAAOE,UAAP,IAAqBF,OAAOG,UAA5B,IAA0CH,OAAOI,kBAAjD,IACAJ,OAAOK,IAAP,IAAeL,OAAOK,IAAP,CAAYA,IAD5B,KAECL,OAAOM,IAAP,CAAYC,MAAZ,KAAuBC,SAAvB,IAAoCR,OAAOK,IAAP,CAAYE,MAAZ,KAAuBC,SAFhE,EAE4E;AAC1E,eAAO,IAAP;AACD,OAJD,MAIO;AACL,eAAO,KAAP;AACD;AACF,KARD,MAQO;AACL,aAAO,KAAP;AACD;AACF;;8BAZeT,gB;;AAcT,WAASU,sBAAT,CAAgCT,MAAhC,EAAwC;AAC7CA,WAAOU,KAAP,CAAaH,MAAb,GAAsBP,OAAOU,KAAP,CAAaC,IAAb,KAAsB,GAAtB,GAA4B,MAA5B,GAAqCX,OAAOU,KAAP,CAAaC,IAAxE;AACAX,WAAOK,IAAP,CAAYE,MAAZ,GAAqBP,OAAOK,IAAP,CAAYM,IAAZ,KAAqB,GAArB,GAA2BC,eAAeZ,OAAOE,UAAtB,CAA3B,GAA+DF,OAAOK,IAAP,CAAYM,IAAhG;AACAX,WAAOa,WAAP,CAAmBN,MAAnB,GAA4BP,OAAOa,WAAP,CAAmBF,IAAnB,KAA4B,GAA5B,GAAkC,EAAlC,GAAuCX,OAAOa,WAAP,CAAmBF,IAAtF;AACAX,WAAOM,IAAP,CAAYC,MAAZ,GAAqBP,OAAOM,IAAP,CAAYK,IAAZ,KAAqB,KAArB,GAA6BC,eAAeZ,OAAOG,UAAtB,CAA7B,GAAiEH,OAAOM,IAAP,CAAYK,IAAlG;AACA,WAAOX,MAAP;AACD;oCANeS,sB;;AAQT,WAASK,OAAT,CAAiBd,MAAjB,EAAyB;AAC9BA,WAAOe,YAAP,GAAsBf,OAAOe,YAAP,IAAuB,aAA7C;AACA,QAAIhB,iBAAiBC,MAAjB,CAAJ,EAA8B;AAC5B,aAAOS,uBAAuBT,MAAvB,CAAP;AACD,KAFD,MAEO;AACL,aAAOA,MAAP;AACD;AACF;;qBAPec,O;;AAShB,WAASF,cAAT,CAAwBI,GAAxB,EAA6B;AAC3B,QAAIA,GAAJ,EAAS;AACP,aAAO,MAAMA,GAAN,GAAY,GAAnB;AACD,KAFD,MAEO;AACL,aAAO,MAAP;AACD;AACF,G","file":"migrations.js","sourcesContent":["/**\n * Query format migration.\n * This module can detect query format version and make migration.\n */\n\nexport function isGrafana2target(target) {\n if (!target.mode || target.mode === 0 || target.mode === 2) {\n if ((target.hostFilter || target.itemFilter || target.downsampleFunction ||\n (target.host && target.host.host)) &&\n (target.item.filter === undefined && target.host.filter === undefined)) {\n return true;\n } else {\n return false;\n }\n } else {\n return false;\n }\n}\n\nexport function migrateFrom2To3version(target) {\n target.group.filter = target.group.name === \"*\" ? \"/.*/\" : target.group.name;\n target.host.filter = target.host.name === \"*\" ? convertToRegex(target.hostFilter) : target.host.name;\n target.application.filter = target.application.name === \"*\" ? \"\" : target.application.name;\n target.item.filter = target.item.name === \"All\" ? convertToRegex(target.itemFilter) : target.item.name;\n return target;\n}\n\nexport function migrate(target) {\n target.resultFormat = target.resultFormat || 'time_series';\n if (isGrafana2target(target)) {\n return migrateFrom2To3version(target);\n } else {\n return target;\n }\n}\n\nfunction convertToRegex(str) {\n if (str) {\n return '/' + str + '/';\n } else {\n return '/.*/';\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/migrations.js"],"names":["isGrafana2target","target","mode","hostFilter","itemFilter","downsampleFunction","host","item","filter","undefined","migrateFrom2To3version","group","name","convertToRegex","application","migrate","resultFormat","str"],"mappings":";;;;;AAAA;;;;;AAKO,WAASA,gBAAT,CAA0BC,MAA1B,EAAkC;AACvC,QAAI,CAACA,OAAOC,IAAR,IAAgBD,OAAOC,IAAP,KAAgB,CAAhC,IAAqCD,OAAOC,IAAP,KAAgB,CAAzD,EAA4D;AAC1D,UAAI,CAACD,OAAOE,UAAP,IAAqBF,OAAOG,UAA5B,IAA0CH,OAAOI,kBAAjD,IACAJ,OAAOK,IAAP,IAAeL,OAAOK,IAAP,CAAYA,IAD5B,KAECL,OAAOM,IAAP,CAAYC,MAAZ,KAAuBC,SAAvB,IAAoCR,OAAOK,IAAP,CAAYE,MAAZ,KAAuBC,SAFhE,EAE4E;AAC1E,eAAO,IAAP;AACD,OAJD,MAIO;AACL,eAAO,KAAP;AACD;AACF,KARD,MAQO;AACL,aAAO,KAAP;AACD;AACF;;8BAZeT,gB;;AAcT,WAASU,sBAAT,CAAgCT,MAAhC,EAAwC;AAC7CA,WAAOU,KAAP,CAAaH,MAAb,GAAsBP,OAAOU,KAAP,CAAaC,IAAb,KAAsB,GAAtB,GAA4B,MAA5B,GAAqCX,OAAOU,KAAP,CAAaC,IAAxE;AACAX,WAAOK,IAAP,CAAYE,MAAZ,GAAqBP,OAAOK,IAAP,CAAYM,IAAZ,KAAqB,GAArB,GAA2BC,eAAeZ,OAAOE,UAAtB,CAA3B,GAA+DF,OAAOK,IAAP,CAAYM,IAAhG;AACAX,WAAOa,WAAP,CAAmBN,MAAnB,GAA4BP,OAAOa,WAAP,CAAmBF,IAAnB,KAA4B,GAA5B,GAAkC,EAAlC,GAAuCX,OAAOa,WAAP,CAAmBF,IAAtF;AACAX,WAAOM,IAAP,CAAYC,MAAZ,GAAqBP,OAAOM,IAAP,CAAYK,IAAZ,KAAqB,KAArB,GAA6BC,eAAeZ,OAAOG,UAAtB,CAA7B,GAAiEH,OAAOM,IAAP,CAAYK,IAAlG;AACA,WAAOX,MAAP;AACD;oCANeS,sB;;AAQT,WAASK,OAAT,CAAiBd,MAAjB,EAAyB;AAC9BA,WAAOe,YAAP,GAAsBf,OAAOe,YAAP,IAAuB,aAA7C;AACA,QAAIhB,iBAAiBC,MAAjB,CAAJ,EAA8B;AAC5B,aAAOS,uBAAuBT,MAAvB,CAAP;AACD,KAFD,MAEO;AACL,aAAOA,MAAP;AACD;AACF;;qBAPec,O;;AAShB,WAASF,cAAT,CAAwBI,GAAxB,EAA6B;AAC3B,QAAIA,GAAJ,EAAS;AACP,aAAO,MAAMA,GAAN,GAAY,GAAnB;AACD,KAFD,MAEO;AACL,aAAO,MAAP;AACD;AACF,G","file":"migrations.js","sourcesContent":["/**\r\n * Query format migration.\r\n * This module can detect query format version and make migration.\r\n */\r\n\r\nexport function isGrafana2target(target) {\r\n if (!target.mode || target.mode === 0 || target.mode === 2) {\r\n if ((target.hostFilter || target.itemFilter || target.downsampleFunction ||\r\n (target.host && target.host.host)) &&\r\n (target.item.filter === undefined && target.host.filter === undefined)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n}\r\n\r\nexport function migrateFrom2To3version(target) {\r\n target.group.filter = target.group.name === \"*\" ? \"/.*/\" : target.group.name;\r\n target.host.filter = target.host.name === \"*\" ? convertToRegex(target.hostFilter) : target.host.name;\r\n target.application.filter = target.application.name === \"*\" ? \"\" : target.application.name;\r\n target.item.filter = target.item.name === \"All\" ? convertToRegex(target.itemFilter) : target.item.name;\r\n return target;\r\n}\r\n\r\nexport function migrate(target) {\r\n target.resultFormat = target.resultFormat || 'time_series';\r\n if (isGrafana2target(target)) {\r\n return migrateFrom2To3version(target);\r\n } else {\r\n return target;\r\n }\r\n}\r\n\r\nfunction convertToRegex(str) {\r\n if (str) {\r\n return '/' + str + '/';\r\n } else {\r\n return '/.*/';\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/module.js.map b/dist/datasource-zabbix/module.js.map index 20329e5a1..07fe5be90 100644 --- a/dist/datasource-zabbix/module.js.map +++ b/dist/datasource-zabbix/module.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/module.js"],"names":["loadPluginCss","ZabbixAPIDatasource","ZabbixQueryController","ZabbixDSConfigController","dark","light","ZabbixQueryOptionsController","templateUrl","ZabbixAnnotationsQueryController"],"mappings":";;;;;;;;;;;;;;;AAAQA,mB,kBAAAA,a;;AACAC,yB,eAAAA,mB;;AACAC,2B,oBAAAA,qB;;AACAC,8B,qBAAAA,wB;;;;AAERH,oBAAc;AACZI,cAAM,gEADM;AAEZC,eAAO;AAFK,OAAd;;kCAKMC,4B;;;;AACNA,mCAA6BC,WAA7B,GAA2C,+CAA3C;;sCAEMC,gC;;;;AACNA,uCAAiCD,WAAjC,GAA+C,oDAA/C;;4BAGEN,mB;;4BACAE,wB;;2BACAD,qB;;kCACAI,4B;;sCACAE,gC","file":"module.js","sourcesContent":["import {loadPluginCss} from 'app/plugins/sdk';\nimport {ZabbixAPIDatasource} from './datasource';\nimport {ZabbixQueryController} from './query.controller';\nimport {ZabbixDSConfigController} from './config.controller';\n\nloadPluginCss({\n dark: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.dark.css',\n light: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.light.css'\n});\n\nclass ZabbixQueryOptionsController {}\nZabbixQueryOptionsController.templateUrl = 'datasource-zabbix/partials/query.options.html';\n\nclass ZabbixAnnotationsQueryController {}\nZabbixAnnotationsQueryController.templateUrl = 'datasource-zabbix/partials/annotations.editor.html';\n\nexport {\n ZabbixAPIDatasource as Datasource,\n ZabbixDSConfigController as ConfigCtrl,\n ZabbixQueryController as QueryCtrl,\n ZabbixQueryOptionsController as QueryOptionsCtrl,\n ZabbixAnnotationsQueryController as AnnotationsQueryCtrl\n};\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/module.js"],"names":["loadPluginCss","ZabbixAPIDatasource","ZabbixQueryController","ZabbixDSConfigController","dark","light","ZabbixQueryOptionsController","templateUrl","ZabbixAnnotationsQueryController"],"mappings":";;;;;;;;;;;;;;;AAAQA,mB,kBAAAA,a;;AACAC,yB,eAAAA,mB;;AACAC,2B,oBAAAA,qB;;AACAC,8B,qBAAAA,wB;;;;AAERH,oBAAc;AACZI,cAAM,gEADM;AAEZC,eAAO;AAFK,OAAd;;kCAKMC,4B;;;;AACNA,mCAA6BC,WAA7B,GAA2C,+CAA3C;;sCAEMC,gC;;;;AACNA,uCAAiCD,WAAjC,GAA+C,oDAA/C;;4BAGEN,mB;;4BACAE,wB;;2BACAD,qB;;kCACAI,4B;;sCACAE,gC","file":"module.js","sourcesContent":["import {loadPluginCss} from 'app/plugins/sdk';\r\nimport {ZabbixAPIDatasource} from './datasource';\r\nimport {ZabbixQueryController} from './query.controller';\r\nimport {ZabbixDSConfigController} from './config.controller';\r\n\r\nloadPluginCss({\r\n dark: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.dark.css',\r\n light: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.light.css'\r\n});\r\n\r\nclass ZabbixQueryOptionsController {}\r\nZabbixQueryOptionsController.templateUrl = 'datasource-zabbix/partials/query.options.html';\r\n\r\nclass ZabbixAnnotationsQueryController {}\r\nZabbixAnnotationsQueryController.templateUrl = 'datasource-zabbix/partials/annotations.editor.html';\r\n\r\nexport {\r\n ZabbixAPIDatasource as Datasource,\r\n ZabbixDSConfigController as ConfigCtrl,\r\n ZabbixQueryController as QueryCtrl,\r\n ZabbixQueryOptionsController as QueryOptionsCtrl,\r\n ZabbixAnnotationsQueryController as AnnotationsQueryCtrl\r\n};\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/partials/annotations.editor.html b/dist/datasource-zabbix/partials/annotations.editor.html index 6e2e4954e..e8c6cdbb6 100644 --- a/dist/datasource-zabbix/partials/annotations.editor.html +++ b/dist/datasource-zabbix/partials/annotations.editor.html @@ -1,65 +1,65 @@ -
-
Filter Triggers
-
-
- Group - - -
- -
- Host - - -
-
-
-
- Application - - -
- -
- Trigger - - -
-
-
-
-
- Minimum severity -
- -
-
-
-
-
Options
-
- - - -
-
+
+
Filter Triggers
+
+
+ Group + + +
+ +
+ Host + + +
+
+
+
+ Application + + +
+ +
+ Trigger + + +
+
+
+
+
+ Minimum severity +
+ +
+
+
+
+
Options
+
+ + + +
+
diff --git a/dist/datasource-zabbix/partials/config.html b/dist/datasource-zabbix/partials/config.html index 0df746203..7c3ba293d 100644 --- a/dist/datasource-zabbix/partials/config.html +++ b/dist/datasource-zabbix/partials/config.html @@ -1,136 +1,136 @@ - - - -
-

Zabbix API details

- -
- - Username - - - -
- -
- - Password - - - -
- - - -
-
- - After - - Time after which trends will be used. - Best practice is to set this value to your history storage period (7d, 30d, etc). - - - - -
-
- - Range - - Time range width after which trends will be used instead of history. - It's better to set this value in range of 4 to 7 days to prevent loading large amount of history data. - - - - -
-
- -
- - Cache TTL - - Zabbix data source caches metric names in memory. Specify how often data will be updated. - - - - -
-
- -
-

Direct DB Connection

- - -
-
- - SQL Data Source - - Select SQL Data Source for Zabbix database. - In order to use this feature you should create and - configure it first. Zabbix plugin uses this data source for querying history data directly from database. - This way usually faster than pulling data from Zabbix API, especially on the wide time ranges, and reduces - amount of data transfered. - - -
- -
-
-
-
- -
-

Alerting

- - -
- - -
- Min severity -
- -
-
-
-
- -
-

Other

- - -
+ + + +
+

Zabbix API details

+ +
+ + Username + + + +
+ +
+ + Password + + + +
+ + + +
+
+ + After + + Time after which trends will be used. + Best practice is to set this value to your history storage period (7d, 30d, etc). + + + + +
+
+ + Range + + Time range width after which trends will be used instead of history. + It's better to set this value in range of 4 to 7 days to prevent loading large amount of history data. + + + + +
+
+ +
+ + Cache TTL + + Zabbix data source caches metric names in memory. Specify how often data will be updated. + + + + +
+
+ +
+

Direct DB Connection

+ + +
+
+ + SQL Data Source + + Select SQL Data Source for Zabbix database. + In order to use this feature you should create and + configure it first. Zabbix plugin uses this data source for querying history data directly from database. + This way usually faster than pulling data from Zabbix API, especially on the wide time ranges, and reduces + amount of data transfered. + + +
+ +
+
+
+
+ +
+

Alerting

+ + +
+ + +
+ Min severity +
+ +
+
+
+
+ +
+

Other

+ + +
diff --git a/dist/datasource-zabbix/partials/query.editor.html b/dist/datasource-zabbix/partials/query.editor.html index de976ae9c..c101ec743 100644 --- a/dist/datasource-zabbix/partials/query.editor.html +++ b/dist/datasource-zabbix/partials/query.editor.html @@ -1,235 +1,235 @@ - - -
-
- -
- -
-
-
- -
- -
-
-
-
-
-
- - -
-
- - - -
-
- -
- -
-
-
-
-
-
- -
- -
- - -
- -
- - -
- -
-
-
-
- -
- -
- - -
- - -
- - -
- -
- -
- -
-
-
- -
- -
-
- - - - - -
- - -
-
- - -
-
- - -
-
- - -
-
- - - -
-
-
-
-
- - -
-
- -
-
- -
-
-
-
- - -
- -
- - -
- - - -
-
-
-
-
+ + +
+
+ +
+ +
+
+
+ +
+ +
+
+
+
+
+
+ + +
+
+ + + +
+
+ +
+ +
+
+
+
+
+
+ +
+ +
+ + +
+ +
+ + +
+ +
+
+
+
+ +
+ +
+ + +
+ + +
+ + +
+ +
+ +
+ +
+
+
+ +
+ +
+
+ + + + + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + + +
+
+
+
+
+ + +
+
+ +
+
+ +
+
+
+
+ + +
+ +
+ + +
+ + + +
+
+
+
+
diff --git a/dist/datasource-zabbix/partials/query.options.html b/dist/datasource-zabbix/partials/query.options.html index 9224822aa..e2995de15 100644 --- a/dist/datasource-zabbix/partials/query.options.html +++ b/dist/datasource-zabbix/partials/query.options.html @@ -1,88 +1,88 @@ -
-
-
- Max data points - - -
-
-
- -
-
- -
-
- -
-
Max data points
-
    -
  • Grafana-Zabbix plugin uses maxDataPoints parameter to consolidate the real number of values down to this - number -
  • -
  • If there are more real values, then by default they will be consolidated using averages
  • -
  • This could hide real peaks and max values in your series
  • -
  • Point consolidation will effect series legend values (min,max,total,current)
  • -
  • If you override maxDataPoint and set a high value performance can be severely effected
  • -
-
- -
-
IT services
-
    -
  • Select "IT services" in targets menu to activate IT services mode.
  • -
-
- -
-
IT service property
-
    -
  • Zabbix returns the following availability information about IT service
  • -
  • Status - current status of the IT service
  • -
  • SLA - SLA for the given time interval
  • -
  • OK time - time the service was in OK state, in seconds
  • -
  • Problem time - time the service was in problem state, in seconds
  • -
  • Down time - time the service was in scheduled downtime, in seconds
  • -
-
- -
-
Text filter
-
    -
  • Use regex to extract a part of the returned value.
  • -
-
-
-
+
+
+
+ Max data points + + +
+
+
+ +
+
+ +
+
+ +
+
Max data points
+
    +
  • Grafana-Zabbix plugin uses maxDataPoints parameter to consolidate the real number of values down to this + number +
  • +
  • If there are more real values, then by default they will be consolidated using averages
  • +
  • This could hide real peaks and max values in your series
  • +
  • Point consolidation will effect series legend values (min,max,total,current)
  • +
  • If you override maxDataPoint and set a high value performance can be severely effected
  • +
+
+ +
+
IT services
+
    +
  • Select "IT services" in targets menu to activate IT services mode.
  • +
+
+ +
+
IT service property
+
    +
  • Zabbix returns the following availability information about IT service
  • +
  • Status - current status of the IT service
  • +
  • SLA - SLA for the given time interval
  • +
  • OK time - time the service was in OK state, in seconds
  • +
  • Problem time - time the service was in problem state, in seconds
  • +
  • Down time - time the service was in scheduled downtime, in seconds
  • +
+
+ +
+
Text filter
+
    +
  • Use regex to extract a part of the returned value.
  • +
+
+
+
diff --git a/dist/datasource-zabbix/plugin.json b/dist/datasource-zabbix/plugin.json index 3f3d88451..28a561a24 100644 --- a/dist/datasource-zabbix/plugin.json +++ b/dist/datasource-zabbix/plugin.json @@ -1,36 +1,36 @@ -{ - "type": "datasource", - "name": "Zabbix", - "id": "alexanderzobnin-zabbix-datasource", - - "includes": [ - { - "type": "dashboard", - "name": "Zabbix System Status", - "path": "../dashboards/zabbix_system_status.json" - }, - { - "type": "dashboard", - "name": "Zabbix Template Linux Server", - "path": "../dashboards/template_linux_server.json" - } - ], - - "metrics": true, - "annotations": true, - - "queryOptions": { - "maxDataPoints": true - }, - - "info": { - "author": { - "name": "Alexander Zobnin", - "url": "https://github.com/alexanderzobnin/grafana-zabbix" - }, - "logos": { - "small": "img/zabbix_app_logo.svg", - "large": "img/zabbix_app_logo.svg" - } - } -} +{ + "type": "datasource", + "name": "Zabbix", + "id": "alexanderzobnin-zabbix-datasource", + + "includes": [ + { + "type": "dashboard", + "name": "Zabbix System Status", + "path": "../dashboards/zabbix_system_status.json" + }, + { + "type": "dashboard", + "name": "Zabbix Template Linux Server", + "path": "../dashboards/template_linux_server.json" + } + ], + + "metrics": true, + "annotations": true, + + "queryOptions": { + "maxDataPoints": true + }, + + "info": { + "author": { + "name": "Alexander Zobnin", + "url": "https://github.com/alexanderzobnin/grafana-zabbix" + }, + "logos": { + "small": "img/zabbix_app_logo.svg", + "large": "img/zabbix_app_logo.svg" + } + } +} diff --git a/dist/datasource-zabbix/query.controller.js.map b/dist/datasource-zabbix/query.controller.js.map index 2b80eb0fa..4f06bbf93 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","MODE_TRIGGERS","editorMode","METRICS","TEXT","ITSERVICE","ITEMID","TRIGGERS","slaPropertyList","name","property","ackFilters","resultFormats","triggerSeverity","TRIGGER_SEVERITY","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","skipEmptyValues","forOwn","key","join","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAQA,e,kBAAAA,S;;AACDC,O;;AACKC,O;;AACAC,W;;AACAC,qB;;AACAC,gB;;;;;;;;;;;;;;;;;;;;;uCAKCC,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,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AAQsH,GAAR,EAAgB;AAC5C,kBAAItH,KAAJ,EAAW;AACT,oBAAIA,UAAU,IAAd,EAAoB;AAClB;AACAsF,0BAAQuB,IAAR,CAAaM,WAAWG,GAAX,CAAb;AACD,iBAHD,MAGO;AACL;AACAhC,0BAAQuB,IAAR,CAAaM,WAAWG,GAAX,IAAkB,KAAlB,GAA0BtH,KAAvC;AACD;AACF;AACF,aAVD;AAWA,mBAAO,cAAcsF,QAAQiC,IAAR,CAAa,IAAb,CAArB;AACD;;;2CASgBrH,I,EAAM;AACrB,iBAAKgC,MAAL,CAAYhC,IAAZ,GAAmBA,IAAnB;AACA,iBAAK+B,IAAL;AACA,iBAAKkE,aAAL;AACD;;;;QAnUwCnH,S;;;;AAsU3C;AACAM,4BAAsBkI,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\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.ackFilters = [\n {text: 'all triggers', value: 2},\n {text: 'unacknowledged', value: 0},\n {text: 'acknowledged', value: 1},\n ];\n\n this.resultFormats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];\n\n this.triggerSeverity = c.TRIGGER_SEVERITY;\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 'triggers': {\n 'count': true,\n 'minSeverity': 3,\n 'acknowledged': 2\n },\n 'options': {\n 'showDisabledItems': false,\n 'skipEmptyValues': false\n },\n 'table': {\n 'skipEmptyValues': 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 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 skipEmptyValues: \"Skip empty values\"\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","ackFilters","resultFormats","triggerSeverity","TRIGGER_SEVERITY","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","skipEmptyValues","forOwn","key","join","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAQA,e,kBAAAA,S;;AACDC,O;;AACKC,O;;AACAC,W;;AACAC,qB;;AACAC,gB;;;;;;;;;;;;;;;;;;;;;uCAKCC,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,MAAR,EAAqBC,MAAM,MAA3B,EAA0CC,MAAMhB,EAAEkB,SAAlD,EAFiB,EAGjB,EAACJ,OAAO,WAAR,EAAqBC,MAAM,aAA3B,EAA0CC,MAAMhB,EAAEmB,cAAlD,EAHiB,EAIjB,EAACL,OAAO,QAAR,EAAqBC,MAAM,SAA3B,EAA0CC,MAAMhB,EAAEoB,WAAlD,EAJiB,EAKjB,EAACN,OAAO,UAAR,EAAqBC,MAAM,UAA3B,EAA0CC,MAAMhB,EAAEqB,aAAlD,EALiB,CAAnB;;AAQA,gBAAKhB,MAAL,CAAYiB,UAAZ,GAAyB;AACvBC,qBAASvB,EAAEiB,YADY;AAEvBO,kBAAMxB,EAAEkB,SAFe;AAGvBO,uBAAWzB,EAAEmB,cAHU;AAIvBO,oBAAQ1B,EAA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B,eAFpB;AAGD,aAJe,CAAhB;;AAMA,gBAAIkG,SAAJ,EAAe;AACb,mBAAK/E,MAAL,CAAYU,SAAZ,GAAwB3D,EAAE+H,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,qBADJ;AAEf6B,+BAAiB;AAFF,aAAjB;AAIA,gBAAI9B,UAAU,EAAd;AACArG,cAAEoI,MAAF,CAAS,KAAKnF,MAAL,CAAYoD,OAArB,EAA8B,UAACtF,KAAD,EAAQsH,GAAR,EAAgB;AAC5C,kBAAItH,KAAJ,EAAW;AACT,oBAAIA,UAAU,IAAd,EAAoB;AAClB;AACAsF,0BAAQuB,IAAR,CAAaM,WAAWG,GAAX,CAAb;AACD,iBAHD,MAGO;AACL;AACAhC,0BAAQuB,IAAR,CAAaM,WAAWG,GAAX,IAAkB,KAAlB,GAA0BtH,KAAvC;AACD;AACF;AACF,aAVD;AAWA,mBAAO,cAAcsF,QAAQiC,IAAR,CAAa,IAAb,CAArB;AACD;;;2CASgBrH,I,EAAM;AACrB,iBAAKgC,MAAL,CAAYhC,IAAZ,GAAmBA,IAAnB;AACA,iBAAK+B,IAAL;AACA,iBAAKkE,aAAL;AACD;;;;QAnUwCnH,S;;;;AAsU3C;AACAM,4BAAsBkI,WAAtB,GAAoC,8CAApC","file":"query.controller.js","sourcesContent":["import {QueryCtrl} from 'app/plugins/sdk';\r\nimport _ from 'lodash';\r\nimport * as c from './constants';\r\nimport * as utils from './utils';\r\nimport * as metricFunctions from './metricFunctions';\r\nimport * as migrations from './migrations';\r\n\r\nimport './add-metric-function.directive';\r\nimport './metric-function-editor.directive';\r\n\r\nexport class ZabbixQueryController extends QueryCtrl {\r\n\r\n // ZabbixQueryCtrl constructor\r\n constructor($scope, $injector, $rootScope, $sce, templateSrv) {\r\n super($scope, $injector);\r\n this.zabbix = this.datasource.zabbix;\r\n\r\n // Use custom format for template variables\r\n this.replaceTemplateVars = this.datasource.replaceTemplateVars;\r\n this.templateSrv = templateSrv;\r\n\r\n this.editorModes = [\r\n {value: 'num', text: 'Metrics', mode: c.MODE_METRICS},\r\n {value: 'text', text: 'Text', mode: c.MODE_TEXT},\r\n {value: 'itservice', text: 'IT Services', mode: c.MODE_ITSERVICE},\r\n {value: 'itemid', text: 'Item ID', mode: c.MODE_ITEMID},\r\n {value: 'triggers', text: 'Triggers', mode: c.MODE_TRIGGERS}\r\n ];\r\n\r\n this.$scope.editorMode = {\r\n METRICS: c.MODE_METRICS,\r\n TEXT: c.MODE_TEXT,\r\n ITSERVICE: c.MODE_ITSERVICE,\r\n ITEMID: c.MODE_ITEMID,\r\n TRIGGERS: c.MODE_TRIGGERS\r\n };\r\n\r\n this.slaPropertyList = [\r\n {name: \"Status\", property: \"status\"},\r\n {name: \"SLA\", property: \"sla\"},\r\n {name: \"OK time\", property: \"okTime\"},\r\n {name: \"Problem time\", property: \"problemTime\"},\r\n {name: \"Down time\", property: \"downtimeTime\"}\r\n ];\r\n\r\n this.ackFilters = [\r\n {text: 'all triggers', value: 2},\r\n {text: 'unacknowledged', value: 0},\r\n {text: 'acknowledged', value: 1},\r\n ];\r\n\r\n this.resultFormats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];\r\n\r\n this.triggerSeverity = c.TRIGGER_SEVERITY;\r\n\r\n // Map functions for bs-typeahead\r\n this.getGroupNames = _.bind(this.getMetricNames, this, 'groupList');\r\n this.getHostNames = _.bind(this.getMetricNames, this, 'hostList', true);\r\n this.getApplicationNames = _.bind(this.getMetricNames, this, 'appList');\r\n this.getItemNames = _.bind(this.getMetricNames, this, 'itemList');\r\n this.getITServices = _.bind(this.getMetricNames, this, 'itServiceList');\r\n this.getVariables = _.bind(this.getTemplateVariables, this);\r\n\r\n // Update metric suggestion when template variable was changed\r\n $rootScope.$on('template-variable-value-updated', () => this.onVariableChange());\r\n\r\n // Update metrics when item selected from dropdown\r\n $scope.$on('typeahead-updated', () => {\r\n this.onTargetBlur();\r\n });\r\n\r\n this.init = function() {\r\n var target = this.target;\r\n\r\n // Migrate old targets\r\n target = migrations.migrate(target);\r\n\r\n var scopeDefaults = {\r\n metric: {},\r\n oldTarget: _.cloneDeep(this.target),\r\n queryOptionsText: this.renderQueryOptionsText()\r\n };\r\n _.defaults(this, scopeDefaults);\r\n\r\n // Load default values\r\n var targetDefaults = {\r\n 'mode': c.MODE_METRICS,\r\n 'group': { 'filter': \"\" },\r\n 'host': { 'filter': \"\" },\r\n 'application': { 'filter': \"\" },\r\n 'item': { 'filter': \"\" },\r\n 'functions': [],\r\n 'triggers': {\r\n 'count': true,\r\n 'minSeverity': 3,\r\n 'acknowledged': 2\r\n },\r\n 'options': {\r\n 'showDisabledItems': false,\r\n 'skipEmptyValues': false\r\n },\r\n 'table': {\r\n 'skipEmptyValues': false\r\n }\r\n };\r\n _.defaults(target, targetDefaults);\r\n\r\n // Create function instances from saved JSON\r\n target.functions = _.map(target.functions, function(func) {\r\n return metricFunctions.createFuncInstance(func.def, func.params);\r\n });\r\n\r\n if (target.mode === c.MODE_METRICS ||\r\n target.mode === c.MODE_TEXT ||\r\n target.mode === c.MODE_TRIGGERS) {\r\n this.initFilters();\r\n }\r\n else if (target.mode === c.MODE_ITSERVICE) {\r\n _.defaults(target, {slaProperty: {name: \"SLA\", property: \"sla\"}});\r\n this.suggestITServices();\r\n }\r\n };\r\n\r\n this.init();\r\n this.queryOptionsText = this.renderQueryOptionsText();\r\n }\r\n\r\n initFilters() {\r\n let itemtype = _.find(this.editorModes, {'mode': this.target.mode});\r\n itemtype = itemtype ? itemtype.value : null;\r\n return Promise.all([\r\n this.suggestGroups(),\r\n this.suggestHosts(),\r\n this.suggestApps(),\r\n this.suggestItems(itemtype)\r\n ]);\r\n }\r\n\r\n // Get list of metric names for bs-typeahead directive\r\n getMetricNames(metricList, addAllValue) {\r\n let metrics = _.uniq(_.map(this.metric[metricList], 'name'));\r\n\r\n // Add template variables\r\n _.forEach(this.templateSrv.variables, variable => {\r\n metrics.unshift('$' + variable.name);\r\n });\r\n\r\n if (addAllValue) {\r\n metrics.unshift('/.*/');\r\n }\r\n\r\n return metrics;\r\n }\r\n\r\n getTemplateVariables() {\r\n return _.map(this.templateSrv.variables, variable => {\r\n return '$' + variable.name;\r\n });\r\n }\r\n\r\n suggestGroups() {\r\n return this.zabbix.getAllGroups()\r\n .then(groups => {\r\n this.metric.groupList = groups;\r\n return groups;\r\n });\r\n }\r\n\r\n suggestHosts() {\r\n let groupFilter = this.replaceTemplateVars(this.target.group.filter);\r\n return this.zabbix.getAllHosts(groupFilter)\r\n .then(hosts => {\r\n this.metric.hostList = hosts;\r\n return hosts;\r\n });\r\n }\r\n\r\n suggestApps() {\r\n let groupFilter = this.replaceTemplateVars(this.target.group.filter);\r\n let hostFilter = this.replaceTemplateVars(this.target.host.filter);\r\n return this.zabbix.getAllApps(groupFilter, hostFilter)\r\n .then(apps => {\r\n this.metric.appList = apps;\r\n return apps;\r\n });\r\n }\r\n\r\n suggestItems(itemtype = 'num') {\r\n let groupFilter = this.replaceTemplateVars(this.target.group.filter);\r\n let hostFilter = this.replaceTemplateVars(this.target.host.filter);\r\n let appFilter = this.replaceTemplateVars(this.target.application.filter);\r\n let options = {\r\n itemtype: itemtype,\r\n showDisabledItems: this.target.options.showDisabledItems\r\n };\r\n\r\n return this.zabbix\r\n .getAllItems(groupFilter, hostFilter, appFilter, options)\r\n .then(items => {\r\n this.metric.itemList = items;\r\n return items;\r\n });\r\n }\r\n\r\n suggestITServices() {\r\n return this.zabbix.getITService()\r\n .then(itservices => {\r\n this.metric.itServiceList = itservices;\r\n return itservices;\r\n });\r\n }\r\n\r\n isRegex(str) {\r\n return utils.isRegex(str);\r\n }\r\n\r\n isVariable(str) {\r\n return utils.isTemplateVariable(str, this.templateSrv.variables);\r\n }\r\n\r\n onTargetBlur() {\r\n var newTarget = _.cloneDeep(this.target);\r\n if (!_.isEqual(this.oldTarget, this.target)) {\r\n this.oldTarget = newTarget;\r\n this.targetChanged();\r\n }\r\n }\r\n\r\n onVariableChange() {\r\n if (this.isContainsVariables()) {\r\n this.targetChanged();\r\n }\r\n }\r\n\r\n /**\r\n * Check query for template variables\r\n */\r\n isContainsVariables() {\r\n return _.some(['group', 'host', 'application'], field => {\r\n if (this.target[field] && this.target[field].filter) {\r\n return utils.isTemplateVariable(this.target[field].filter, this.templateSrv.variables);\r\n } else {\r\n return false;\r\n }\r\n });\r\n }\r\n\r\n parseTarget() {\r\n // Parse target\r\n }\r\n\r\n // Validate target and set validation info\r\n validateTarget() {\r\n // validate\r\n }\r\n\r\n targetChanged() {\r\n this.initFilters();\r\n this.parseTarget();\r\n this.panelCtrl.refresh();\r\n }\r\n\r\n addFunction(funcDef) {\r\n var newFunc = metricFunctions.createFuncInstance(funcDef);\r\n newFunc.added = true;\r\n this.target.functions.push(newFunc);\r\n\r\n this.moveAliasFuncLast();\r\n\r\n if (newFunc.params.length && newFunc.added ||\r\n newFunc.def.params.length === 0) {\r\n this.targetChanged();\r\n }\r\n }\r\n\r\n removeFunction(func) {\r\n this.target.functions = _.without(this.target.functions, func);\r\n this.targetChanged();\r\n }\r\n\r\n moveAliasFuncLast() {\r\n var aliasFunc = _.find(this.target.functions, function(func) {\r\n return func.def.name === 'alias' ||\r\n func.def.name === 'aliasByNode' ||\r\n func.def.name === 'aliasByMetric';\r\n });\r\n\r\n if (aliasFunc) {\r\n this.target.functions = _.without(this.target.functions, aliasFunc);\r\n this.target.functions.push(aliasFunc);\r\n }\r\n }\r\n\r\n toggleQueryOptions() {\r\n this.showQueryOptions = !this.showQueryOptions;\r\n }\r\n\r\n onQueryOptionChange() {\r\n this.queryOptionsText = this.renderQueryOptionsText();\r\n this.onTargetBlur();\r\n }\r\n\r\n renderQueryOptionsText() {\r\n var optionsMap = {\r\n showDisabledItems: \"Show disabled items\",\r\n skipEmptyValues: \"Skip empty values\"\r\n };\r\n var options = [];\r\n _.forOwn(this.target.options, (value, key) => {\r\n if (value) {\r\n if (value === true) {\r\n // Show only option name (if enabled) for boolean options\r\n options.push(optionsMap[key]);\r\n } else {\r\n // Show \"option = value\" for another options\r\n options.push(optionsMap[key] + \" = \" + value);\r\n }\r\n }\r\n });\r\n return \"Options: \" + options.join(', ');\r\n }\r\n\r\n /**\r\n * Switch query editor to specified mode.\r\n * Modes:\r\n * 0 - items\r\n * 1 - IT services\r\n * 2 - Text metrics\r\n */\r\n switchEditorMode(mode) {\r\n this.target.mode = mode;\r\n this.init();\r\n this.targetChanged();\r\n }\r\n}\r\n\r\n// Set templateUrl as static property\r\nZabbixQueryController.templateUrl = 'datasource-zabbix/partials/query.editor.html';\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/query_help.md b/dist/datasource-zabbix/query_help.md index bb6c526bc..5816e01ca 100644 --- a/dist/datasource-zabbix/query_help.md +++ b/dist/datasource-zabbix/query_help.md @@ -1,31 +1,31 @@ -#### Max data points -Override max data points, automatically set to graph width in pixels. Grafana-Zabbix plugin uses maxDataPoints parameter to consolidate the real number of values down to this number. If there are more real values, then by default they will be consolidated using averages. This could hide real peaks and max values in your series. Point consolidation will affect series legend values (min,max,total,current). - -#### Query Mode -##### Merics -Data from numeric items. - -##### Text -Data from items with `Character`, `Text` or `Log` type. - -##### IT Services -Time series representation of IT Services data -###### IT service property -Zabbix returns the following availability information about IT service: -- Status - current status of the IT service -- SLA - SLA for the given time interval -- OK time - time the service was in OK state, in seconds -- Problem time - time the service was in problem state, in seconds -- Down time - time the service was in scheduled downtime, in seconds - -##### Item ID -Data from items with specified ID's (comma separated). -This mode is suitable for rendering charts in grafana by passing itemids as url params. -1. Create multivalue template variable with type _Custom_, for example, `itemids`. -1. Create graph with desired parameters and use `$itemids` in _Item IDs_ filed. -1. Save dashboard. -1. Click to graph title and select _Share_ -> _Direct link rendered image_. -1. Use this URL for graph png image and set `var-itemids` param to desired IDs. Note, for multiple IDs you should pass multiple params, like `&var-itemids=28276&var-itemids=28277`. - -##### Triggers -Active triggers count for selected hosts or table data like Zabbix _System status_ panel on the main dashboard. +#### Max data points +Override max data points, automatically set to graph width in pixels. Grafana-Zabbix plugin uses maxDataPoints parameter to consolidate the real number of values down to this number. If there are more real values, then by default they will be consolidated using averages. This could hide real peaks and max values in your series. Point consolidation will affect series legend values (min,max,total,current). + +#### Query Mode +##### Merics +Data from numeric items. + +##### Text +Data from items with `Character`, `Text` or `Log` type. + +##### IT Services +Time series representation of IT Services data +###### IT service property +Zabbix returns the following availability information about IT service: +- Status - current status of the IT service +- SLA - SLA for the given time interval +- OK time - time the service was in OK state, in seconds +- Problem time - time the service was in problem state, in seconds +- Down time - time the service was in scheduled downtime, in seconds + +##### Item ID +Data from items with specified ID's (comma separated). +This mode is suitable for rendering charts in grafana by passing itemids as url params. +1. Create multivalue template variable with type _Custom_, for example, `itemids`. +1. Create graph with desired parameters and use `$itemids` in _Item IDs_ filed. +1. Save dashboard. +1. Click to graph title and select _Share_ -> _Direct link rendered image_. +1. Use this URL for graph png image and set `var-itemids` param to desired IDs. Note, for multiple IDs you should pass multiple params, like `&var-itemids=28276&var-itemids=28277`. + +##### Triggers +Active triggers count for selected hosts or table data like Zabbix _System status_ panel on the main dashboard. diff --git a/dist/datasource-zabbix/responseHandler.js b/dist/datasource-zabbix/responseHandler.js index fad1d09d7..36482ca1e 100644 --- a/dist/datasource-zabbix/responseHandler.js +++ b/dist/datasource-zabbix/responseHandler.js @@ -17,24 +17,24 @@ System.register(['lodash', 'app/core/table_model', './constants'], function (_ex } } - /** - * Convert Zabbix API history.get response to Grafana format - * - * @return {Array} Array of timeseries in Grafana format - * { - * target: "Metric name", - * datapoints: [[, ], ...] - * } + /** + * Convert Zabbix API history.get response to Grafana format + * + * @return {Array} Array of timeseries in Grafana format + * { + * target: "Metric name", + * datapoints: [[, ], ...] + * } */ function convertHistory(history, items, addHostName, convertPointCallback) { - /** - * Response should be in the format: - * data: [ - * { - * target: "Metric name", - * datapoints: [[, ], ...] - * }, ... - * ] + /** + * Response should be in the format: + * data: [ + * { + * target: "Metric name", + * datapoints: [[, ], ...] + * }, ... + * ] */ // Group history by itemid diff --git a/dist/datasource-zabbix/responseHandler.js.map b/dist/datasource-zabbix/responseHandler.js.map index aad8c3e89..de6805290 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","handleHistoryAsTable","table","TableModel","addColumn","text","each","itemHistory","lastPoint","last","lastValue","value","options","skipEmptyValues","textFilter","extractText","useCaptureGroups","first","rows","push","key_","point","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","stats","getTriggerStats","orderBy","c","TRIGGER_SEVERITY","severity","severity_stats","group","row","toPairs","s","concat","groups","uniq","flattenDeep","trigger","priority","Number","value_min","value_max","value_avg","value_sum","value_count"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;AASA,WAASA,cAAT,CAAwBC,OAAxB,EAAiCC,KAAjC,EAAwCC,WAAxC,EAAqDC,oBAArD,EAA2E;AACzE;;;;;;;;;;AAUA;AACA,QAAIC,kBAAkBC,EAAEC,OAAF,CAAUN,OA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,EAAsC0B,KAAtC,EAA6C;AAC3C,QAAIV,KAAJ;AACA,YAAQhB,SAAR;AACE,WAAK,KAAL;AACEgB,gBAAQU,MAAM8C,SAAd;AACA;AACF,WAAK,KAAL;AACExD,gBAAQU,MAAM+C,SAAd;AACA;AACF,WAAK,KAAL;AACEzD,gBAAQU,MAAMgD,SAAd;AACA;AACF,WAAK,KAAL;AACE1D,gBAAQU,MAAMiD,SAAd;AACA;AACF,WAAK,OAAL;AACE3D,gBAAQU,MAAMkD,WAAd;AACA;AACF;AACE5D,gBAAQU,MAAMgD,SAAd;AAjBJ;;AAoBA,WAAO,CACLH,OAAOvD,KAAP,CADK,EAELU,MAAMC,KAAN,GAAc,IAFT,CAAP;AAID,G;;AAlNMhD,O;;AACA6B,gB;;AACKiD,O;;;yBAkNG;AACb5D,uBAAeA,aADF;AAEbxB,wBAAgBA,cAFH;AAGb0B,sBAAcA,YAHD;AAIbI,oBAAYA,UAJC;AAKbG,8BAAsBA,oBALT;AAMb+B,2BAAmBA,iBANN;AAOba,gCAAwBA;AAPX,O;;AAUf;AACA,UAAI,CAACvE,EAAEG,MAAP,EAAe;AAACH,UAAEG,MAAF,GAAWH,EAAEwF,IAAb;AAAmB","file":"responseHandler.js","sourcesContent":["import _ from 'lodash';\nimport TableModel from 'app/core/table_model';\nimport * as c from './constants';\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: [[, ], ...]\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: [[, ], ...]\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 handleHistoryAsTable(history, items, target) {\n let table = new TableModel();\n table.addColumn({text: 'Host'});\n table.addColumn({text: 'Item'});\n table.addColumn({text: 'Key'});\n table.addColumn({text: 'Last value'});\n\n let grouped_history = _.groupBy(history, 'itemid');\n _.each(items, (item) => {\n let itemHistory = grouped_history[item.itemid] || [];\n let lastPoint = _.last(itemHistory);\n let lastValue = lastPoint ? lastPoint.value : null;\n\n if(target.options.skipEmptyValues && (!lastValue || lastValue === '')) {\n return;\n }\n\n // Regex-based extractor\n if (target.textFilter) {\n lastValue = extractText(lastValue, target.textFilter, target.useCaptureGroups);\n }\n\n let host = _.first(item.hosts);\n host = host ? host.name : \"\";\n\n table.rows.push([\n host, item.name, item.key_, lastValue\n ]);\n });\n\n return table;\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] * 1000]\n ]\n };\n } else {\n let stats = getTriggerStats(triggers);\n let table = new TableModel();\n table.addColumn({text: 'Host group'});\n _.each(_.orderBy(c.TRIGGER_SEVERITY, ['val'], ['desc']), (severity) => {\n table.addColumn({text: severity.text});\n });\n _.each(stats, (severity_stats, group) => {\n let row = _.map(_.orderBy(_.toPairs(severity_stats), (s) => s[0], ['desc']), (s) => s[1]);\n row = _.concat([group], ...row);\n table.rows.push(row);\n });\n return table;\n }\n}\n\nfunction getTriggerStats(triggers) {\n let groups = _.uniq(_.flattenDeep(_.map(triggers, (trigger) => _.map(trigger.groups, 'name'))));\n // let severity = _.map(c.TRIGGER_SEVERITY, 'text');\n let stats = {};\n _.each(groups, (group) => {\n stats[group] = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0}; // severity:count\n });\n _.each(triggers, (trigger) => {\n _.each(trigger.groups, (group) => {\n stats[group.name][trigger.priority]++;\n });\n });\n return stats;\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 handleHistoryAsTable: handleHistoryAsTable,\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 +{"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","handleHistoryAsTable","table","TableModel","addColumn","text","each","itemHistory","lastPoint","last","lastValue","value","options","skipEmptyValues","textFilter","extractText","useCaptureGroups","first","rows","push","key_","point","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","stats","getTriggerStats","orderBy","c","TRIGGER_SEVERITY","severity","severity_stats","group","row","toPairs","s","concat","groups","uniq","flattenDeep","trigger","priority","Number","value_min","value_max","value_avg","value_sum","value_count"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;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,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;AACA;AACF,WAAK,KAAL;AACExD,gBAAQU,MAAM+C,SAAd;AACA;AACF,WAAK,KAAL;AACEzD,gBAAQU,MAAMgD,SAAd;AACA;AACF,WAAK,KAAL;AACE1D,gBAAQU,MAAMiD,SAAd;AACA;AACF,WAAK,OAAL;AACE3D,gBAAQU,MAAMkD,WAAd;AACA;AACF;AACE5D,gBAAQU,MAAMgD,SAAd;AAjBJ;;AAoBA,WAAO,CACLH,OAAOvD,KAAP,CADK,EAELU,MAAMC,KAAN,GAAc,IAFT,CAAP;AAID,G;;AAlNMhD,O;;AACA6B,gB;;AACKiD,O;;;yBAkNG;AACb5D,uBAAeA,aADF;AAEbxB,wBAAgBA,cAFH;AAGb0B,sBAAcA,YAHD;AAIbI,oBAAYA,UAJC;AAKbG,8BAAsBA,oBALT;AAMb+B,2BAAmBA,iBANN;AAOba,gCAAwBA;AAPX,O;;AAUf;AACA,UAAI,CAACvE,EAAEG,MAAP,EAAe;AAACH,UAAEG,MAAF,GAAWH,EAAEwF,IAAb;AAAmB","file":"responseHandler.js","sourcesContent":["import _ from 'lodash';\r\nimport TableModel from 'app/core/table_model';\r\nimport * as c from './constants';\r\n\r\n/**\r\n * Convert Zabbix API history.get response to Grafana format\r\n *\r\n * @return {Array} Array of timeseries in Grafana format\r\n * {\r\n * target: \"Metric name\",\r\n * datapoints: [[, ], ...]\r\n * }\r\n */\r\nfunction convertHistory(history, items, addHostName, convertPointCallback) {\r\n /**\r\n * Response should be in the format:\r\n * data: [\r\n * {\r\n * target: \"Metric name\",\r\n * datapoints: [[, ], ...]\r\n * }, ...\r\n * ]\r\n */\r\n\r\n // Group history by itemid\r\n var grouped_history = _.groupBy(history, 'itemid');\r\n var hosts = _.uniqBy(_.flatten(_.map(items, 'hosts')), 'hostid'); //uniqBy is needed to deduplicate\r\n\r\n return _.map(grouped_history, function(hist, itemid) {\r\n var item = _.find(items, {'itemid': itemid});\r\n var alias = item.name;\r\n if (_.keys(hosts).length > 1 && addHostName) { //only when actual multi hosts selected\r\n var host = _.find(hosts, {'hostid': item.hostid});\r\n alias = host.name + \": \" + alias;\r\n }\r\n return {\r\n target: alias,\r\n datapoints: _.map(hist, convertPointCallback)\r\n };\r\n });\r\n}\r\n\r\nfunction handleHistory(history, items, addHostName = true) {\r\n return convertHistory(history, items, addHostName, convertHistoryPoint);\r\n}\r\n\r\nfunction handleTrends(history, items, valueType, addHostName = true) {\r\n var convertPointCallback = _.partial(convertTrendPoint, valueType);\r\n return convertHistory(history, items, addHostName, convertPointCallback);\r\n}\r\n\r\nfunction handleText(history, items, target, addHostName = true) {\r\n let convertTextCallback = _.partial(convertText, target);\r\n return convertHistory(history, items, addHostName, convertTextCallback);\r\n}\r\n\r\nfunction handleHistoryAsTable(history, items, target) {\r\n let table = new TableModel();\r\n table.addColumn({text: 'Host'});\r\n table.addColumn({text: 'Item'});\r\n table.addColumn({text: 'Key'});\r\n table.addColumn({text: 'Last value'});\r\n\r\n let grouped_history = _.groupBy(history, 'itemid');\r\n _.each(items, (item) => {\r\n let itemHistory = grouped_history[item.itemid] || [];\r\n let lastPoint = _.last(itemHistory);\r\n let lastValue = lastPoint ? lastPoint.value : null;\r\n\r\n if(target.options.skipEmptyValues && (!lastValue || lastValue === '')) {\r\n return;\r\n }\r\n\r\n // Regex-based extractor\r\n if (target.textFilter) {\r\n lastValue = extractText(lastValue, target.textFilter, target.useCaptureGroups);\r\n }\r\n\r\n let host = _.first(item.hosts);\r\n host = host ? host.name : \"\";\r\n\r\n table.rows.push([\r\n host, item.name, item.key_, lastValue\r\n ]);\r\n });\r\n\r\n return table;\r\n}\r\n\r\nfunction convertText(target, point) {\r\n let value = point.value;\r\n\r\n // Regex-based extractor\r\n if (target.textFilter) {\r\n value = extractText(point.value, target.textFilter, target.useCaptureGroups);\r\n }\r\n\r\n return [\r\n value,\r\n point.clock * 1000 + Math.round(point.ns / 1000000)\r\n ];\r\n}\r\n\r\nfunction extractText(str, pattern, useCaptureGroups) {\r\n let extractPattern = new RegExp(pattern);\r\n let extractedValue = extractPattern.exec(str);\r\n if (extractedValue) {\r\n if (useCaptureGroups) {\r\n extractedValue = extractedValue[1];\r\n } else {\r\n extractedValue = extractedValue[0];\r\n }\r\n }\r\n return extractedValue;\r\n}\r\n\r\nfunction handleSLAResponse(itservice, slaProperty, slaObject) {\r\n var targetSLA = slaObject[itservice.serviceid].sla[0];\r\n if (slaProperty.property === 'status') {\r\n var targetStatus = parseInt(slaObject[itservice.serviceid].status);\r\n return {\r\n target: itservice.name + ' ' + slaProperty.name,\r\n datapoints: [\r\n [targetStatus, targetSLA.to * 1000]\r\n ]\r\n };\r\n } else {\r\n return {\r\n target: itservice.name + ' ' + slaProperty.name,\r\n datapoints: [\r\n [targetSLA[slaProperty.property], targetSLA.from * 1000],\r\n [targetSLA[slaProperty.property], targetSLA.to * 1000]\r\n ]\r\n };\r\n }\r\n}\r\n\r\nfunction handleTriggersResponse(triggers, timeRange) {\r\n if (_.isNumber(triggers)) {\r\n return {\r\n target: \"triggers count\",\r\n datapoints: [\r\n [triggers, timeRange[1] * 1000]\r\n ]\r\n };\r\n } else {\r\n let stats = getTriggerStats(triggers);\r\n let table = new TableModel();\r\n table.addColumn({text: 'Host group'});\r\n _.each(_.orderBy(c.TRIGGER_SEVERITY, ['val'], ['desc']), (severity) => {\r\n table.addColumn({text: severity.text});\r\n });\r\n _.each(stats, (severity_stats, group) => {\r\n let row = _.map(_.orderBy(_.toPairs(severity_stats), (s) => s[0], ['desc']), (s) => s[1]);\r\n row = _.concat([group], ...row);\r\n table.rows.push(row);\r\n });\r\n return table;\r\n }\r\n}\r\n\r\nfunction getTriggerStats(triggers) {\r\n let groups = _.uniq(_.flattenDeep(_.map(triggers, (trigger) => _.map(trigger.groups, 'name'))));\r\n // let severity = _.map(c.TRIGGER_SEVERITY, 'text');\r\n let stats = {};\r\n _.each(groups, (group) => {\r\n stats[group] = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0}; // severity:count\r\n });\r\n _.each(triggers, (trigger) => {\r\n _.each(trigger.groups, (group) => {\r\n stats[group.name][trigger.priority]++;\r\n });\r\n });\r\n return stats;\r\n}\r\n\r\nfunction convertHistoryPoint(point) {\r\n // Value must be a number for properly work\r\n return [\r\n Number(point.value),\r\n point.clock * 1000 + Math.round(point.ns / 1000000)\r\n ];\r\n}\r\n\r\nfunction convertTrendPoint(valueType, point) {\r\n var value;\r\n switch (valueType) {\r\n case \"min\":\r\n value = point.value_min;\r\n break;\r\n case \"max\":\r\n value = point.value_max;\r\n break;\r\n case \"avg\":\r\n value = point.value_avg;\r\n break;\r\n case \"sum\":\r\n value = point.value_sum;\r\n break;\r\n case \"count\":\r\n value = point.value_count;\r\n break;\r\n default:\r\n value = point.value_avg;\r\n }\r\n\r\n return [\r\n Number(value),\r\n point.clock * 1000\r\n ];\r\n}\r\n\r\nexport default {\r\n handleHistory: handleHistory,\r\n convertHistory: convertHistory,\r\n handleTrends: handleTrends,\r\n handleText: handleText,\r\n handleHistoryAsTable: handleHistoryAsTable,\r\n handleSLAResponse: handleSLAResponse,\r\n handleTriggersResponse: handleTriggersResponse\r\n};\r\n\r\n// Fix for backward compatibility with lodash 2.4\r\nif (!_.uniqBy) {_.uniqBy = _.uniq;}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/specs/dataProcessor.spec.js b/dist/datasource-zabbix/specs/dataProcessor.spec.js index 999e3a7b4..9ab605fe4 100644 --- a/dist/datasource-zabbix/specs/dataProcessor.spec.js +++ b/dist/datasource-zabbix/specs/dataProcessor.spec.js @@ -1,51 +1,51 @@ -import _ from 'lodash'; -import dataProcessor from '../dataProcessor'; - -describe('dataProcessor', () => { - let ctx = {}; - - beforeEach(() => { - ctx.datapoints = [ - [[10, 1500000000000], [2, 1500000001000], [7, 1500000002000], [1, 1500000003000]], - [[9, 1500000000000], [3, 1500000001000], [4, 1500000002000], [8, 1500000003000]], - ]; - }); - - describe('When apply groupBy() functions', () => { - it('should return series average', () => { - let aggregateBy = dataProcessor.metricFunctions['groupBy']; - const avg2s = _.map(ctx.datapoints, (dp) => aggregateBy('2s', 'avg', dp)); - expect(avg2s).toEqual([ - [[6, 1500000000000], [4, 1500000002000]], - [[6, 1500000000000], [6, 1500000002000]], - ]); - - const avg10s = _.map(ctx.datapoints, (dp) => aggregateBy('10s', 'avg', dp)); - expect(avg10s).toEqual([ - [[5, 1500000000000]], - [[6, 1500000000000]], - ]); - - // not aligned - const dp = [[10, 1500000001000], [2, 1500000002000], [7, 1500000003000], [1, 1500000004000]]; - expect(aggregateBy('2s', 'avg', dp)).toEqual([ - [10, 1500000000000], [4.5, 1500000002000], [1, 1500000004000] - ]); - }); - }); - - describe('When apply aggregateBy() functions', () => { - it('should return series average', () => { - let aggregateBy = dataProcessor.metricFunctions['aggregateBy']; - const avg1s = aggregateBy('1s', 'avg', ctx.datapoints); - expect(avg1s).toEqual([ - [9.5, 1500000000000], [2.5, 1500000001000], [5.5, 1500000002000], [4.5, 1500000003000] - ]); - - const avg10s = aggregateBy('10s', 'avg', ctx.datapoints); - expect(avg10s).toEqual([ - [5.5, 1500000000000] - ]); - }); - }); -}); +import _ from 'lodash'; +import dataProcessor from '../dataProcessor'; + +describe('dataProcessor', () => { + let ctx = {}; + + beforeEach(() => { + ctx.datapoints = [ + [[10, 1500000000000], [2, 1500000001000], [7, 1500000002000], [1, 1500000003000]], + [[9, 1500000000000], [3, 1500000001000], [4, 1500000002000], [8, 1500000003000]], + ]; + }); + + describe('When apply groupBy() functions', () => { + it('should return series average', () => { + let aggregateBy = dataProcessor.metricFunctions['groupBy']; + const avg2s = _.map(ctx.datapoints, (dp) => aggregateBy('2s', 'avg', dp)); + expect(avg2s).toEqual([ + [[6, 1500000000000], [4, 1500000002000]], + [[6, 1500000000000], [6, 1500000002000]], + ]); + + const avg10s = _.map(ctx.datapoints, (dp) => aggregateBy('10s', 'avg', dp)); + expect(avg10s).toEqual([ + [[5, 1500000000000]], + [[6, 1500000000000]], + ]); + + // not aligned + const dp = [[10, 1500000001000], [2, 1500000002000], [7, 1500000003000], [1, 1500000004000]]; + expect(aggregateBy('2s', 'avg', dp)).toEqual([ + [10, 1500000000000], [4.5, 1500000002000], [1, 1500000004000] + ]); + }); + }); + + describe('When apply aggregateBy() functions', () => { + it('should return series average', () => { + let aggregateBy = dataProcessor.metricFunctions['aggregateBy']; + const avg1s = aggregateBy('1s', 'avg', ctx.datapoints); + expect(avg1s).toEqual([ + [9.5, 1500000000000], [2.5, 1500000001000], [5.5, 1500000002000], [4.5, 1500000003000] + ]); + + const avg10s = aggregateBy('10s', 'avg', ctx.datapoints); + expect(avg10s).toEqual([ + [5.5, 1500000000000] + ]); + }); + }); +}); diff --git a/dist/datasource-zabbix/specs/datasource.spec.js b/dist/datasource-zabbix/specs/datasource.spec.js index 697c982b4..07b3d6a3b 100644 --- a/dist/datasource-zabbix/specs/datasource.spec.js +++ b/dist/datasource-zabbix/specs/datasource.spec.js @@ -1,429 +1,429 @@ -import _ from 'lodash'; -import Q, { Promise } from "q"; -import {Datasource} from "../module"; -import {zabbixTemplateFormat} from "../datasource"; - -describe('ZabbixDatasource', () => { - let ctx = {}; - - beforeEach(() => { - ctx.instanceSettings = { - jsonData: { - alerting: true, - username: 'zabbix', - password: 'zabbix', - trends: true, - trendsFrom: '14d', - trendsRange: '7d', - dbConnection: { - enabled: false - } - } - }; - ctx.templateSrv = {}; - ctx.alertSrv = {}; - ctx.dashboardSrv = {}; - ctx.zabbixAlertingSrv = { - setPanelAlertState: jest.fn(), - removeZabbixThreshold: jest.fn(), - }; - ctx.zabbix = () => {}; - - ctx.ds = new Datasource(ctx.instanceSettings, ctx.templateSrv, ctx.alertSrv, ctx.dashboardSrv, ctx.zabbixAlertingSrv, ctx.zabbix); - }); - - describe('When querying data', () => { - beforeEach(() => { - ctx.ds.replaceTemplateVars = (str) => str; - ctx.ds.alertQuery = () => Q.when([]); - }); - - ctx.options = { - targets: [ - { - group: {filter: ""}, - host: {filter: ""}, - application: {filter: ""}, - item: {filter: ""} - } - ], - range: {from: 'now-7d', to: 'now'} - }; - - it('should return an empty array when no targets are set', (done) => { - let options = { - targets: [], - range: {from: 'now-6h', to: 'now'} - }; - ctx.ds.query(options).then(result => { - expect(result.data.length).toBe(0); - done(); - }); - }); - - it('should use trends if it enabled and time more than trendsFrom', (done) => { - let ranges = ['now-7d', 'now-168h', 'now-1M', 'now-1y']; - - _.forEach(ranges, range => { - ctx.options.range.from = range; - ctx.ds.queryNumericData = jest.fn(); - ctx.ds.query(ctx.options); - - // Check that useTrends options is true - let callArgs = ctx.ds.queryNumericData.mock.calls[0]; - expect(callArgs[2]).toBe(true); - ctx.ds.queryNumericData.mockClear(); - }); - - done(); - }); - - it('shouldnt use trends if it enabled and time less than trendsFrom', (done) => { - let ranges = ['now-6d', 'now-167h', 'now-1h', 'now-30m', 'now-30s']; - - _.forEach(ranges, range => { - ctx.options.range.from = range; - ctx.ds.queryNumericData = jest.fn(); - ctx.ds.query(ctx.options); - - // Check that useTrends options is false - let callArgs = ctx.ds.queryNumericData.mock.calls[0]; - expect(callArgs[2]).toBe(false); - ctx.ds.queryNumericData.mockClear(); - }); - done(); - }); - - }); - - describe('When querying text data', () => { - beforeEach(() => { - ctx.ds.replaceTemplateVars = (str) => str; - ctx.ds.alertQuery = () => Q.when([]); - ctx.ds.zabbix.getHistory = jest.fn().mockReturnValue(Promise.resolve([ - {clock: "1500010200", itemid:"10100", ns:"900111000", value:"Linux first"}, - {clock: "1500010300", itemid:"10100", ns:"900111000", value:"Linux 2nd"}, - {clock: "1500010400", itemid:"10100", ns:"900111000", value:"Linux last"} - ])); - - ctx.ds.zabbix.getItemsFromTarget = jest.fn().mockReturnValue(Promise.resolve([ - { - hosts: [{hostid: "10001", name: "Zabbix server"}], - itemid: "10100", - name: "System information", - key_: "system.uname", - } - ])); - - ctx.options = { - range: {from: 'now-1h', to: 'now'}, - targets: [ - { - group: {filter: ""}, - host: {filter: "Zabbix server"}, - application: {filter: ""}, - item: {filter: "System information"}, - textFilter: "", - useCaptureGroups: true, - mode: 2, - resultFormat: "table", - options: { - skipEmptyValues: false - } - } - ], - }; - }); - - it('should return data in table format', (done) => { - ctx.ds.query(ctx.options).then(result => { - expect(result.data.length).toBe(1); - - let tableData = result.data[0]; - expect(tableData.columns).toEqual([ - {text: 'Host'}, {text: 'Item'}, {text: 'Key'}, {text: 'Last value'} - ]); - expect(tableData.rows).toEqual([ - ['Zabbix server', 'System information', 'system.uname', 'Linux last'] - ]); - done(); - }); - }); - - it('should extract value if regex with capture group is used', (done) => { - ctx.options.targets[0].textFilter = "Linux (.*)"; - ctx.ds.query(ctx.options).then(result => { - let tableData = result.data[0]; - expect(tableData.rows[0][3]).toEqual('last'); - done(); - }); - }); - - it('should skip item when last value is empty', () => { - ctx.ds.zabbix.getItemsFromTarget = jest.fn().mockReturnValue(Promise.resolve([ - { - hosts: [{hostid: "10001", name: "Zabbix server"}], - itemid: "10100", name: "System information", key_: "system.uname" - }, - { - hosts: [{hostid: "10002", name: "Server02"}], - itemid: "90109", name: "System information", key_: "system.uname" - } - ])); - - ctx.options.targets[0].options.skipEmptyValues = true; - ctx.ds.zabbix.getHistory = jest.fn().mockReturnValue(Promise.resolve([ - {clock: "1500010200", itemid:"10100", ns:"900111000", value:"Linux first"}, - {clock: "1500010300", itemid:"10100", ns:"900111000", value:"Linux 2nd"}, - {clock: "1500010400", itemid:"10100", ns:"900111000", value:"Linux last"}, - {clock: "1500010200", itemid:"90109", ns:"900111000", value:"Non empty value"}, - {clock: "1500010500", itemid:"90109", ns:"900111000", value:""} - ])); - return ctx.ds.query(ctx.options).then(result => { - let tableData = result.data[0]; - expect(tableData.rows.length).toBe(1); - expect(tableData.rows[0][3]).toEqual('Linux last'); - }); - }); - }); - - describe('When replacing template variables', () => { - - function testReplacingVariable(target, varValue, expectedResult, done) { - ctx.ds.templateSrv.replace = () => { - return zabbixTemplateFormat(varValue); - }; - - let result = ctx.ds.replaceTemplateVars(target); - expect(result).toBe(expectedResult); - done(); - } - - /* - * Alphanumerics, spaces, dots, dashes and underscores - * are allowed in Zabbix host name. - * 'AaBbCc0123 .-_' - */ - it('should return properly escaped regex', (done) => { - let target = '$host'; - let template_var_value = 'AaBbCc0123 .-_'; - let expected_result = '/^AaBbCc0123 \\.-_$/'; - - testReplacingVariable(target, template_var_value, expected_result, done); - }); - - /* - * Single-value variable - * $host = backend01 - * $host => /^backend01|backend01$/ - */ - it('should return proper regex for single value', (done) => { - let target = '$host'; - let template_var_value = 'backend01'; - let expected_result = '/^backend01$/'; - - testReplacingVariable(target, template_var_value, expected_result, done); - }); - - /* - * Multi-value variable - * $host = [backend01, backend02] - * $host => /^(backend01|backend01)$/ - */ - it('should return proper regex for multi-value', (done) => { - let target = '$host'; - let template_var_value = ['backend01', 'backend02']; - let expected_result = '/^(backend01|backend02)$/'; - - testReplacingVariable(target, template_var_value, expected_result, done); - }); - }); - - describe('When invoking metricFindQuery()', () => { - beforeEach(() => { - ctx.ds.replaceTemplateVars = (str) => str; - ctx.ds.zabbix = { - getGroups: jest.fn().mockReturnValue(Q.when([])), - getHosts: jest.fn().mockReturnValue(Q.when([])), - getApps: jest.fn().mockReturnValue(Q.when([])), - getItems: jest.fn().mockReturnValue(Q.when([])) - }; - }); - - it('should return groups', (done) => { - const tests = [ - {query: '*', expect: '/.*/'}, - {query: '', expect: ''}, - {query: 'Backend', expect: 'Backend'}, - {query: 'Back*', expect: 'Back*'}, - ]; - - for (const test of tests) { - ctx.ds.metricFindQuery(test.query); - expect(ctx.ds.zabbix.getGroups).toBeCalledWith(test.expect); - ctx.ds.zabbix.getGroups.mockClear(); - } - done(); - }); - - it('should return hosts', (done) => { - const tests = [ - {query: '*.*', expect: ['/.*/', '/.*/']}, - {query: '.', expect: ['', '']}, - {query: 'Backend.*', expect: ['Backend', '/.*/']}, - {query: 'Back*.', expect: ['Back*', '']}, - ]; - - for (const test of tests) { - ctx.ds.metricFindQuery(test.query); - expect(ctx.ds.zabbix.getHosts).toBeCalledWith(test.expect[0], test.expect[1]); - ctx.ds.zabbix.getHosts.mockClear(); - } - done(); - }); - - it('should return applications', (done) => { - const tests = [ - {query: '*.*.*', expect: ['/.*/', '/.*/', '/.*/']}, - {query: '.*.', expect: ['', '/.*/', '']}, - {query: 'Backend.backend01.*', expect: ['Backend', 'backend01', '/.*/']}, - {query: 'Back*.*.', expect: ['Back*', '/.*/', '']} - ]; - - for (const test of tests) { - ctx.ds.metricFindQuery(test.query); - expect(ctx.ds.zabbix.getApps).toBeCalledWith(test.expect[0], test.expect[1], test.expect[2]); - ctx.ds.zabbix.getApps.mockClear(); - } - done(); - }); - - it('should return items', (done) => { - const tests = [ - {query: '*.*.*.*', expect: ['/.*/', '/.*/', '', '/.*/']}, - {query: '.*.*.*', expect: ['', '/.*/', '', '/.*/']}, - {query: 'Backend.backend01.*.*', expect: ['Backend', 'backend01', '', '/.*/']}, - {query: 'Back*.*.cpu.*', expect: ['Back*', '/.*/', 'cpu', '/.*/']} - ]; - - for (const test of tests) { - ctx.ds.metricFindQuery(test.query); - expect(ctx.ds.zabbix.getItems) - .toBeCalledWith(test.expect[0], test.expect[1], test.expect[2], test.expect[3]); - ctx.ds.zabbix.getItems.mockClear(); - } - done(); - }); - - it('should invoke method with proper arguments', (done) => { - let query = '*.*'; - - ctx.ds.metricFindQuery(query); - expect(ctx.ds.zabbix.getHosts).toBeCalledWith('/.*/', '/.*/'); - done(); - }); - }); - - describe('When querying alerts', () => { - let options = {}; - - beforeEach(() => { - ctx.ds.replaceTemplateVars = (str) => str; - - let targetItems = [{ - "itemid": "1", - "name": "test item", - "key_": "test.key", - "value_type": "3", - "hostid": "10631", - "status": "0", - "state": "0", - "hosts": [{"hostid": "10631", "name": "Test host"}], - "item": "Test item" - }]; - ctx.ds.zabbix.getItemsFromTarget = () => Promise.resolve(targetItems); - - options = { - "panelId": 10, - "targets": [{ - "application": {"filter": ""}, - "group": {"filter": "Test group"}, - "host": {"filter": "Test host"}, - "item": {"filter": "Test item"}, - }] - }; - }); - - it('should return threshold when comparative symbol is `less than`', () => { - - let itemTriggers = [{ - "triggerid": "15383", - "priority": "4", - "expression": "{15915}<100", - }]; - - ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); - - return ctx.ds.alertQuery(options) - .then(resp => { - expect(resp.thresholds).toHaveLength(1); - expect(resp.thresholds[0]).toBe(100); - return resp; - }); - }); - - it('should return threshold when comparative symbol is `less than or equal`', () => { - - let itemTriggers = [{ - "triggerid": "15383", - "priority": "4", - "expression": "{15915}<=100", - }]; - - ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); - - return ctx.ds.alertQuery(options) - .then(resp => { - expect(resp.thresholds.length).toBe(1); - expect(resp.thresholds[0]).toBe(100); - return resp; - }); - }); - - it('should return threshold when comparative symbol is `greater than or equal`', () => { - - let itemTriggers = [{ - "triggerid": "15383", - "priority": "4", - "expression": "{15915}>=30", - }]; - - ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); - - return ctx.ds.alertQuery(options) - .then(resp => { - expect(resp.thresholds.length).toBe(1); - expect(resp.thresholds[0]).toBe(30); - return resp; - }); - }); - - it('should return threshold when comparative symbol is `equal`', () => { - - let itemTriggers = [{ - "triggerid": "15383", - "priority": "4", - "expression": "{15915}=50", - }]; - - ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); - - return ctx.ds.alertQuery(options) - .then(resp => { - expect(resp.thresholds.length).toBe(1); - expect(resp.thresholds[0]).toBe(50); - return resp; - }); - }); - }); -}); +import _ from 'lodash'; +import Q, { Promise } from "q"; +import {Datasource} from "../module"; +import {zabbixTemplateFormat} from "../datasource"; + +describe('ZabbixDatasource', () => { + let ctx = {}; + + beforeEach(() => { + ctx.instanceSettings = { + jsonData: { + alerting: true, + username: 'zabbix', + password: 'zabbix', + trends: true, + trendsFrom: '14d', + trendsRange: '7d', + dbConnection: { + enabled: false + } + } + }; + ctx.templateSrv = {}; + ctx.alertSrv = {}; + ctx.dashboardSrv = {}; + ctx.zabbixAlertingSrv = { + setPanelAlertState: jest.fn(), + removeZabbixThreshold: jest.fn(), + }; + ctx.zabbix = () => {}; + + ctx.ds = new Datasource(ctx.instanceSettings, ctx.templateSrv, ctx.alertSrv, ctx.dashboardSrv, ctx.zabbixAlertingSrv, ctx.zabbix); + }); + + describe('When querying data', () => { + beforeEach(() => { + ctx.ds.replaceTemplateVars = (str) => str; + ctx.ds.alertQuery = () => Q.when([]); + }); + + ctx.options = { + targets: [ + { + group: {filter: ""}, + host: {filter: ""}, + application: {filter: ""}, + item: {filter: ""} + } + ], + range: {from: 'now-7d', to: 'now'} + }; + + it('should return an empty array when no targets are set', (done) => { + let options = { + targets: [], + range: {from: 'now-6h', to: 'now'} + }; + ctx.ds.query(options).then(result => { + expect(result.data.length).toBe(0); + done(); + }); + }); + + it('should use trends if it enabled and time more than trendsFrom', (done) => { + let ranges = ['now-7d', 'now-168h', 'now-1M', 'now-1y']; + + _.forEach(ranges, range => { + ctx.options.range.from = range; + ctx.ds.queryNumericData = jest.fn(); + ctx.ds.query(ctx.options); + + // Check that useTrends options is true + let callArgs = ctx.ds.queryNumericData.mock.calls[0]; + expect(callArgs[2]).toBe(true); + ctx.ds.queryNumericData.mockClear(); + }); + + done(); + }); + + it('shouldnt use trends if it enabled and time less than trendsFrom', (done) => { + let ranges = ['now-6d', 'now-167h', 'now-1h', 'now-30m', 'now-30s']; + + _.forEach(ranges, range => { + ctx.options.range.from = range; + ctx.ds.queryNumericData = jest.fn(); + ctx.ds.query(ctx.options); + + // Check that useTrends options is false + let callArgs = ctx.ds.queryNumericData.mock.calls[0]; + expect(callArgs[2]).toBe(false); + ctx.ds.queryNumericData.mockClear(); + }); + done(); + }); + + }); + + describe('When querying text data', () => { + beforeEach(() => { + ctx.ds.replaceTemplateVars = (str) => str; + ctx.ds.alertQuery = () => Q.when([]); + ctx.ds.zabbix.getHistory = jest.fn().mockReturnValue(Promise.resolve([ + {clock: "1500010200", itemid:"10100", ns:"900111000", value:"Linux first"}, + {clock: "1500010300", itemid:"10100", ns:"900111000", value:"Linux 2nd"}, + {clock: "1500010400", itemid:"10100", ns:"900111000", value:"Linux last"} + ])); + + ctx.ds.zabbix.getItemsFromTarget = jest.fn().mockReturnValue(Promise.resolve([ + { + hosts: [{hostid: "10001", name: "Zabbix server"}], + itemid: "10100", + name: "System information", + key_: "system.uname", + } + ])); + + ctx.options = { + range: {from: 'now-1h', to: 'now'}, + targets: [ + { + group: {filter: ""}, + host: {filter: "Zabbix server"}, + application: {filter: ""}, + item: {filter: "System information"}, + textFilter: "", + useCaptureGroups: true, + mode: 2, + resultFormat: "table", + options: { + skipEmptyValues: false + } + } + ], + }; + }); + + it('should return data in table format', (done) => { + ctx.ds.query(ctx.options).then(result => { + expect(result.data.length).toBe(1); + + let tableData = result.data[0]; + expect(tableData.columns).toEqual([ + {text: 'Host'}, {text: 'Item'}, {text: 'Key'}, {text: 'Last value'} + ]); + expect(tableData.rows).toEqual([ + ['Zabbix server', 'System information', 'system.uname', 'Linux last'] + ]); + done(); + }); + }); + + it('should extract value if regex with capture group is used', (done) => { + ctx.options.targets[0].textFilter = "Linux (.*)"; + ctx.ds.query(ctx.options).then(result => { + let tableData = result.data[0]; + expect(tableData.rows[0][3]).toEqual('last'); + done(); + }); + }); + + it('should skip item when last value is empty', () => { + ctx.ds.zabbix.getItemsFromTarget = jest.fn().mockReturnValue(Promise.resolve([ + { + hosts: [{hostid: "10001", name: "Zabbix server"}], + itemid: "10100", name: "System information", key_: "system.uname" + }, + { + hosts: [{hostid: "10002", name: "Server02"}], + itemid: "90109", name: "System information", key_: "system.uname" + } + ])); + + ctx.options.targets[0].options.skipEmptyValues = true; + ctx.ds.zabbix.getHistory = jest.fn().mockReturnValue(Promise.resolve([ + {clock: "1500010200", itemid:"10100", ns:"900111000", value:"Linux first"}, + {clock: "1500010300", itemid:"10100", ns:"900111000", value:"Linux 2nd"}, + {clock: "1500010400", itemid:"10100", ns:"900111000", value:"Linux last"}, + {clock: "1500010200", itemid:"90109", ns:"900111000", value:"Non empty value"}, + {clock: "1500010500", itemid:"90109", ns:"900111000", value:""} + ])); + return ctx.ds.query(ctx.options).then(result => { + let tableData = result.data[0]; + expect(tableData.rows.length).toBe(1); + expect(tableData.rows[0][3]).toEqual('Linux last'); + }); + }); + }); + + describe('When replacing template variables', () => { + + function testReplacingVariable(target, varValue, expectedResult, done) { + ctx.ds.templateSrv.replace = () => { + return zabbixTemplateFormat(varValue); + }; + + let result = ctx.ds.replaceTemplateVars(target); + expect(result).toBe(expectedResult); + done(); + } + + /* + * Alphanumerics, spaces, dots, dashes and underscores + * are allowed in Zabbix host name. + * 'AaBbCc0123 .-_' + */ + it('should return properly escaped regex', (done) => { + let target = '$host'; + let template_var_value = 'AaBbCc0123 .-_'; + let expected_result = '/^AaBbCc0123 \\.-_$/'; + + testReplacingVariable(target, template_var_value, expected_result, done); + }); + + /* + * Single-value variable + * $host = backend01 + * $host => /^backend01|backend01$/ + */ + it('should return proper regex for single value', (done) => { + let target = '$host'; + let template_var_value = 'backend01'; + let expected_result = '/^backend01$/'; + + testReplacingVariable(target, template_var_value, expected_result, done); + }); + + /* + * Multi-value variable + * $host = [backend01, backend02] + * $host => /^(backend01|backend01)$/ + */ + it('should return proper regex for multi-value', (done) => { + let target = '$host'; + let template_var_value = ['backend01', 'backend02']; + let expected_result = '/^(backend01|backend02)$/'; + + testReplacingVariable(target, template_var_value, expected_result, done); + }); + }); + + describe('When invoking metricFindQuery()', () => { + beforeEach(() => { + ctx.ds.replaceTemplateVars = (str) => str; + ctx.ds.zabbix = { + getGroups: jest.fn().mockReturnValue(Q.when([])), + getHosts: jest.fn().mockReturnValue(Q.when([])), + getApps: jest.fn().mockReturnValue(Q.when([])), + getItems: jest.fn().mockReturnValue(Q.when([])) + }; + }); + + it('should return groups', (done) => { + const tests = [ + {query: '*', expect: '/.*/'}, + {query: '', expect: ''}, + {query: 'Backend', expect: 'Backend'}, + {query: 'Back*', expect: 'Back*'}, + ]; + + for (const test of tests) { + ctx.ds.metricFindQuery(test.query); + expect(ctx.ds.zabbix.getGroups).toBeCalledWith(test.expect); + ctx.ds.zabbix.getGroups.mockClear(); + } + done(); + }); + + it('should return hosts', (done) => { + const tests = [ + {query: '*.*', expect: ['/.*/', '/.*/']}, + {query: '.', expect: ['', '']}, + {query: 'Backend.*', expect: ['Backend', '/.*/']}, + {query: 'Back*.', expect: ['Back*', '']}, + ]; + + for (const test of tests) { + ctx.ds.metricFindQuery(test.query); + expect(ctx.ds.zabbix.getHosts).toBeCalledWith(test.expect[0], test.expect[1]); + ctx.ds.zabbix.getHosts.mockClear(); + } + done(); + }); + + it('should return applications', (done) => { + const tests = [ + {query: '*.*.*', expect: ['/.*/', '/.*/', '/.*/']}, + {query: '.*.', expect: ['', '/.*/', '']}, + {query: 'Backend.backend01.*', expect: ['Backend', 'backend01', '/.*/']}, + {query: 'Back*.*.', expect: ['Back*', '/.*/', '']} + ]; + + for (const test of tests) { + ctx.ds.metricFindQuery(test.query); + expect(ctx.ds.zabbix.getApps).toBeCalledWith(test.expect[0], test.expect[1], test.expect[2]); + ctx.ds.zabbix.getApps.mockClear(); + } + done(); + }); + + it('should return items', (done) => { + const tests = [ + {query: '*.*.*.*', expect: ['/.*/', '/.*/', '', '/.*/']}, + {query: '.*.*.*', expect: ['', '/.*/', '', '/.*/']}, + {query: 'Backend.backend01.*.*', expect: ['Backend', 'backend01', '', '/.*/']}, + {query: 'Back*.*.cpu.*', expect: ['Back*', '/.*/', 'cpu', '/.*/']} + ]; + + for (const test of tests) { + ctx.ds.metricFindQuery(test.query); + expect(ctx.ds.zabbix.getItems) + .toBeCalledWith(test.expect[0], test.expect[1], test.expect[2], test.expect[3]); + ctx.ds.zabbix.getItems.mockClear(); + } + done(); + }); + + it('should invoke method with proper arguments', (done) => { + let query = '*.*'; + + ctx.ds.metricFindQuery(query); + expect(ctx.ds.zabbix.getHosts).toBeCalledWith('/.*/', '/.*/'); + done(); + }); + }); + + describe('When querying alerts', () => { + let options = {}; + + beforeEach(() => { + ctx.ds.replaceTemplateVars = (str) => str; + + let targetItems = [{ + "itemid": "1", + "name": "test item", + "key_": "test.key", + "value_type": "3", + "hostid": "10631", + "status": "0", + "state": "0", + "hosts": [{"hostid": "10631", "name": "Test host"}], + "item": "Test item" + }]; + ctx.ds.zabbix.getItemsFromTarget = () => Promise.resolve(targetItems); + + options = { + "panelId": 10, + "targets": [{ + "application": {"filter": ""}, + "group": {"filter": "Test group"}, + "host": {"filter": "Test host"}, + "item": {"filter": "Test item"}, + }] + }; + }); + + it('should return threshold when comparative symbol is `less than`', () => { + + let itemTriggers = [{ + "triggerid": "15383", + "priority": "4", + "expression": "{15915}<100", + }]; + + ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); + + return ctx.ds.alertQuery(options) + .then(resp => { + expect(resp.thresholds).toHaveLength(1); + expect(resp.thresholds[0]).toBe(100); + return resp; + }); + }); + + it('should return threshold when comparative symbol is `less than or equal`', () => { + + let itemTriggers = [{ + "triggerid": "15383", + "priority": "4", + "expression": "{15915}<=100", + }]; + + ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); + + return ctx.ds.alertQuery(options) + .then(resp => { + expect(resp.thresholds.length).toBe(1); + expect(resp.thresholds[0]).toBe(100); + return resp; + }); + }); + + it('should return threshold when comparative symbol is `greater than or equal`', () => { + + let itemTriggers = [{ + "triggerid": "15383", + "priority": "4", + "expression": "{15915}>=30", + }]; + + ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); + + return ctx.ds.alertQuery(options) + .then(resp => { + expect(resp.thresholds.length).toBe(1); + expect(resp.thresholds[0]).toBe(30); + return resp; + }); + }); + + it('should return threshold when comparative symbol is `equal`', () => { + + let itemTriggers = [{ + "triggerid": "15383", + "priority": "4", + "expression": "{15915}=50", + }]; + + ctx.ds.zabbix.getAlerts = () => Promise.resolve(itemTriggers); + + return ctx.ds.alertQuery(options) + .then(resp => { + expect(resp.thresholds.length).toBe(1); + expect(resp.thresholds[0]).toBe(50); + return resp; + }); + }); + }); +}); diff --git a/dist/datasource-zabbix/specs/timeseries.spec.js b/dist/datasource-zabbix/specs/timeseries.spec.js index f1311bdfb..fa11852fc 100644 --- a/dist/datasource-zabbix/specs/timeseries.spec.js +++ b/dist/datasource-zabbix/specs/timeseries.spec.js @@ -1,34 +1,34 @@ -// import _ from 'lodash'; -import ts from '../timeseries'; - -describe('timeseries processing functions', () => { - - describe('sumSeries()', () => { - it('should properly sum series', (done) => { - let series = [ - [[0, 1], [1, 2], [1, 3]], - [[2, 1], [3, 2], [4, 3]] - ]; - - let expected = [[2, 1], [4, 2], [5, 3]]; - - let result = ts.sumSeries(series); - expect(result).toEqual(expected); - done(); - }); - - it('should properly sum series with nulls', (done) => { - // issue #286 - let series = [ - [[1, 1], [1, 2], [1, 3]], - [[3, 2], [4, 3]] - ]; - - let expected = [[1, 1], [4, 2], [5, 3]]; - - let result = ts.sumSeries(series); - expect(result).toEqual(expected); - done(); - }); - }); -}); +// import _ from 'lodash'; +import ts from '../timeseries'; + +describe('timeseries processing functions', () => { + + describe('sumSeries()', () => { + it('should properly sum series', (done) => { + let series = [ + [[0, 1], [1, 2], [1, 3]], + [[2, 1], [3, 2], [4, 3]] + ]; + + let expected = [[2, 1], [4, 2], [5, 3]]; + + let result = ts.sumSeries(series); + expect(result).toEqual(expected); + done(); + }); + + it('should properly sum series with nulls', (done) => { + // issue #286 + let series = [ + [[1, 1], [1, 2], [1, 3]], + [[3, 2], [4, 3]] + ]; + + let expected = [[1, 1], [4, 2], [5, 3]]; + + let result = ts.sumSeries(series); + expect(result).toEqual(expected); + done(); + }); + }); +}); diff --git a/dist/datasource-zabbix/specs/utils.spec.js b/dist/datasource-zabbix/specs/utils.spec.js index d460baa27..6928eaaba 100644 --- a/dist/datasource-zabbix/specs/utils.spec.js +++ b/dist/datasource-zabbix/specs/utils.spec.js @@ -1,141 +1,141 @@ -import _ from 'lodash'; -import * as utils from '../utils'; - -describe('Utils', () => { - - describe('expandItemName()', () => { - - it('should properly expand unquoted params', (done) => { - let test_cases = [ - { - name: `CPU $2 time`, - key: `system.cpu.util[,user,avg1]`, - expected: "CPU user time" - }, - { - name: `CPU $2 time - $3`, - key: `system.cpu.util[,system,avg1]`, - expected: "CPU system time - avg1" - }, - { - name: `CPU - $1 - $2 - $3`, - key: `system.cpu.util[,system,avg1]`, - expected: "CPU - - system - avg1" - } - ]; - - _.each(test_cases, test_case => { - let expandedName = utils.expandItemName(test_case.name, test_case.key); - expect(expandedName).toBe(test_case.expected); - }); - done(); - }); - - it('should properly expand quoted params with commas', (done) => { - let test_cases = [ - { - name: `CPU $2 time`, - key: `system.cpu.util["type=user,value=avg",user]`, - expected: "CPU user time" - }, - { - name: `CPU $1 time`, - key: `system.cpu.util["type=user,value=avg","user"]`, - expected: "CPU type=user,value=avg time" - }, - { - name: `CPU $1 time $3`, - key: `system.cpu.util["type=user,value=avg",,"user"]`, - expected: "CPU type=user,value=avg time user" - }, - { - name: `CPU $1 $2 $3`, - key: `system.cpu.util["type=user,value=avg",time,"user"]`, - expected: "CPU type=user,value=avg time user" - } - ]; - - _.each(test_cases, test_case => { - let expandedName = utils.expandItemName(test_case.name, test_case.key); - expect(expandedName).toBe(test_case.expected); - }); - done(); - }); - - it('should properly expand array params', (done) => { - let test_cases = [ - { - name: `CPU $2 - $3 time`, - key: `system.cpu.util[,[user,system],avg1]`, - expected: "CPU user,system - avg1 time" - }, - { - name: `CPU $2 - $3 time`, - key: `system.cpu.util[,["user,system",iowait],avg1]`, - expected: `CPU "user,system",iowait - avg1 time` - }, - { - name: `CPU - $2 - $3 - $4`, - key: `system.cpu.util[,[],["user,system",iowait],avg1]`, - expected: `CPU - - "user,system",iowait - avg1` - } - ]; - - _.each(test_cases, test_case => { - let expandedName = utils.expandItemName(test_case.name, test_case.key); - expect(expandedName).toBe(test_case.expected); - }); - done(); - }); - }); - - describe('splitTemplateQuery()', () => { - - // Backward compatibility - it('should properly split query in old format', (done) => { - let test_cases = [ - { - query: `/alu/./tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9{2}/`, - expected: ['/alu/', '/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9{2}/'] - }, - { - query: `a.b.c.d`, - expected: ['a', 'b', 'c', 'd'] - } - ]; - - _.each(test_cases, test_case => { - let splitQuery = utils.splitTemplateQuery(test_case.query); - expect(splitQuery).toEqual(test_case.expected); - }); - done(); - }); - - it('should properly split query', (done) => { - let test_cases = [ - { - query: `{alu}{/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]*/}`, - expected: ['alu', '/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]*/'] - }, - { - query: `{alu}{/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]{2}/}`, - expected: ['alu', '/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]{2}/'] - }, - { - query: `{a}{b}{c}{d}`, - expected: ['a', 'b', 'c', 'd'] - }, - { - query: `{a}{b.c.d}`, - expected: ['a', 'b.c.d'] - } - ]; - - _.each(test_cases, test_case => { - let splitQuery = utils.splitTemplateQuery(test_case.query); - expect(splitQuery).toEqual(test_case.expected); - }); - done(); - }); - }); -}); +import _ from 'lodash'; +import * as utils from '../utils'; + +describe('Utils', () => { + + describe('expandItemName()', () => { + + it('should properly expand unquoted params', (done) => { + let test_cases = [ + { + name: `CPU $2 time`, + key: `system.cpu.util[,user,avg1]`, + expected: "CPU user time" + }, + { + name: `CPU $2 time - $3`, + key: `system.cpu.util[,system,avg1]`, + expected: "CPU system time - avg1" + }, + { + name: `CPU - $1 - $2 - $3`, + key: `system.cpu.util[,system,avg1]`, + expected: "CPU - - system - avg1" + } + ]; + + _.each(test_cases, test_case => { + let expandedName = utils.expandItemName(test_case.name, test_case.key); + expect(expandedName).toBe(test_case.expected); + }); + done(); + }); + + it('should properly expand quoted params with commas', (done) => { + let test_cases = [ + { + name: `CPU $2 time`, + key: `system.cpu.util["type=user,value=avg",user]`, + expected: "CPU user time" + }, + { + name: `CPU $1 time`, + key: `system.cpu.util["type=user,value=avg","user"]`, + expected: "CPU type=user,value=avg time" + }, + { + name: `CPU $1 time $3`, + key: `system.cpu.util["type=user,value=avg",,"user"]`, + expected: "CPU type=user,value=avg time user" + }, + { + name: `CPU $1 $2 $3`, + key: `system.cpu.util["type=user,value=avg",time,"user"]`, + expected: "CPU type=user,value=avg time user" + } + ]; + + _.each(test_cases, test_case => { + let expandedName = utils.expandItemName(test_case.name, test_case.key); + expect(expandedName).toBe(test_case.expected); + }); + done(); + }); + + it('should properly expand array params', (done) => { + let test_cases = [ + { + name: `CPU $2 - $3 time`, + key: `system.cpu.util[,[user,system],avg1]`, + expected: "CPU user,system - avg1 time" + }, + { + name: `CPU $2 - $3 time`, + key: `system.cpu.util[,["user,system",iowait],avg1]`, + expected: `CPU "user,system",iowait - avg1 time` + }, + { + name: `CPU - $2 - $3 - $4`, + key: `system.cpu.util[,[],["user,system",iowait],avg1]`, + expected: `CPU - - "user,system",iowait - avg1` + } + ]; + + _.each(test_cases, test_case => { + let expandedName = utils.expandItemName(test_case.name, test_case.key); + expect(expandedName).toBe(test_case.expected); + }); + done(); + }); + }); + + describe('splitTemplateQuery()', () => { + + // Backward compatibility + it('should properly split query in old format', (done) => { + let test_cases = [ + { + query: `/alu/./tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9{2}/`, + expected: ['/alu/', '/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9{2}/'] + }, + { + query: `a.b.c.d`, + expected: ['a', 'b', 'c', 'd'] + } + ]; + + _.each(test_cases, test_case => { + let splitQuery = utils.splitTemplateQuery(test_case.query); + expect(splitQuery).toEqual(test_case.expected); + }); + done(); + }); + + it('should properly split query', (done) => { + let test_cases = [ + { + query: `{alu}{/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]*/}`, + expected: ['alu', '/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]*/'] + }, + { + query: `{alu}{/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]{2}/}`, + expected: ['alu', '/tw-(nyc|que|brx|dwt|brk)-sta_(\w|\d)*-alu-[0-9]{2}/'] + }, + { + query: `{a}{b}{c}{d}`, + expected: ['a', 'b', 'c', 'd'] + }, + { + query: `{a}{b.c.d}`, + expected: ['a', 'b.c.d'] + } + ]; + + _.each(test_cases, test_case => { + let splitQuery = utils.splitTemplateQuery(test_case.query); + expect(splitQuery).toEqual(test_case.expected); + }); + done(); + }); + }); +}); diff --git a/dist/datasource-zabbix/timeseries.js b/dist/datasource-zabbix/timeseries.js index 0fc9d8222..8e87810b4 100644 --- a/dist/datasource-zabbix/timeseries.js +++ b/dist/datasource-zabbix/timeseries.js @@ -5,8 +5,8 @@ System.register(['lodash', './utils'], function (_export, _context) { var _, utils, POINT_VALUE, POINT_TIMESTAMP, exportedFunctions; - /** - * Downsample time series by using given function (avg, min, max). + /** + * Downsample time series by using given function (avg, min, max). */ function downsample(datapoints, time_to, ms_interval, func) { var downsampledSeries = []; @@ -54,9 +54,9 @@ System.register(['lodash', './utils'], function (_export, _context) { return downsampledSeries.reverse(); } - /** - * Group points by given time interval - * datapoints: [[, ], ...] + /** + * Group points by given time interval + * datapoints: [[, ], ...] */ function groupBy(datapoints, interval, groupByCallback) { var ms_interval = utils.parseInterval(interval); @@ -120,9 +120,9 @@ System.register(['lodash', './utils'], function (_export, _context) { return grouped_series; } - /** - * Summarize set of time series into one. - * @param {datapoints[]} timeseries array of time series + /** + * Summarize set of time series into one. + * @param {datapoints[]} timeseries array of time series */ function sumSeries(timeseries) { @@ -173,9 +173,9 @@ System.register(['lodash', './utils'], function (_export, _context) { return datapoints; } - /** - * Simple delta. Calculate value delta between points. - * @param {*} datapoints + /** + * Simple delta. Calculate value delta between points. + * @param {*} datapoints */ function delta(datapoints) { var newSeries = []; @@ -187,9 +187,9 @@ System.register(['lodash', './utils'], function (_export, _context) { return newSeries; } - /** - * Calculates rate per second. Resistant to counter reset. - * @param {*} datapoints + /** + * Calculates rate per second. Resistant to counter reset. + * @param {*} datapoints */ function rate(datapoints) { var newSeries = []; @@ -359,13 +359,13 @@ System.register(['lodash', './utils'], function (_export, _context) { // Utility functions // /////////////////////// - /** - * For given point calculate corresponding time frame. - * - * |__*_|_*__|___*| -> |*___|*___|*___| - * - * @param {*} timestamp - * @param {*} ms_interval + /** + * For given point calculate corresponding time frame. + * + * |__*_|_*__|___*| -> |*___|*___|*___| + * + * @param {*} timestamp + * @param {*} ms_interval */ function getPointTimeFrame(timestamp, ms_interval) { return Math.floor(timestamp / ms_interval) * ms_interval; @@ -377,13 +377,13 @@ System.register(['lodash', './utils'], function (_export, _context) { }); } - /** - * Fill empty front and end of series by zeroes. - * - * | *** | | *** | - * |___ ___| -> |*** ***| - * @param {*} series - * @param {*} timestamps + /** + * Fill empty front and end of series by zeroes. + * + * | *** | | *** | + * |___ ___| -> |*** ***| + * @param {*} series + * @param {*} timestamps */ function fillZeroes(series, timestamps) { var prepend = []; @@ -401,8 +401,8 @@ System.register(['lodash', './utils'], function (_export, _context) { return _.concat(_.concat(prepend, series), append); } - /** - * Interpolate series with gaps + /** + * Interpolate series with gaps */ function interpolateSeries(series) { var left, right; diff --git a/dist/datasource-zabbix/timeseries.js.map b/dist/datasource-zabbix/timeseries.js.map index 1333120e9..d1eda91e7 100644 --- a/dist/datasource-zabbix/timeseries.js.map +++ b/dist/datasource-zabbix/timeseries.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/timeseries.js"],"names":["downsample","datapoints","time_to","ms_interval","func","downsampledSeries","timeWindow","from","to","points_sum","points_num","value_avg","frame","i","length","push","_","max","min","reverse","groupBy","interval","groupByCallback","utils","parseInterval","frames","point","Math","floor","grouped","mapValues","points","map","sortByTime","value","timestamp","Number","groupBy_perf","grouped_series","frame_values","frame_value","frame_ts","getPointTimeFrame","POINT_TIMESTAMP","point_frame_ts","POINT_VALUE","sumSeries","timeseries","new_timestamps","uniq","flatten","sortBy","interpolated_timeseries","series","fillZeroes","timestamps","new_points","difference","new_series","concat","each","interpolateSeries","new_timeseries","sum","j","scale","factor","scale_perf","delta","newSeries","deltaValue","rate","point_prev","valueDelta","timeDelta","simpleMovingAverage","n","sma","w_sum","w_avg","w_count","expMovingAverage","ema","ema_prev","ema_cur","a","PERCENTIL","values","sorted","COUNT","SUM","AVERAGE","values_non_null","getNonNullValues","MIN","MAX","MEDIAN","prepend","append","new_point","left","right","findNearestLeft","findNearestRight","linearInterpolation","pointIndex","exportedFunctions"],"mappings":";;;;;;;AAiBA;;;AAGA,WAASA,UAAT,CAAoBC,UAApB,EAAgCC,OAAhC,EAAyCC,WAAzC,EAAsDC,IAAtD,EAA4D;AAC1D,QAAIC,oBAAoB,EAAxB;AACA,QAAIC,aAAa;AACfC,YAAML,UAAU,IAAV,GAAiBC,WADR;AAEfK,UAAIN,UAAU;AAFC,KAAjB;;AAKA,QAAIO,aAAa,CAAjB;AACA,QAAIC,aAAa,CAAjB;AACA,QAAIC,YAAY,CAAhB;AACA,QAAIC,QAAQ,EAAZ;;AAEA,SAAK,IAAIC,IAAIZ,WAAWa,MAAX,GAAoB,CAAjC,EAAoCD,KAAK,CAAzC,EAA4CA,KAAK,CAAjD,EAAoD;AAClD,UAAIP,WAAWC,IAAX,GAAkBN,WAAWY,CAAX,EAAc,CAAd,CAAlB,IAAsCZ,WAAWY,CAAX,EAAc,CAAd,KAAoBP,WAAWE,EAAzE,EAA6E;AAC3EC,sBAAcR,WAAWY,CAAX,EAAc,CAAd,CAAd;AACAH;AACAE,cAAMG,IAAN,CAAWd,WAAWY,CAAX,EAAc,CAAd,CAAX;AACD,OAJD,MAKK;AACHF,oBAAYD,aAAaD,aAAaC,UAA1B,GAAuC,CAAnD;;AAEA,YAAIN,SAAS,KAAb,EAAoB;AAClBC,4BAAkBU,IAAlB,CAAuB,CAACC,EAAEC,GAAF,CAAML,KAAN,CAAD,EAAeN,WAAWE,EAA1B,CAAvB;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,GAAkB,C;AA0clB+D,uB,GAAoB;AACxB1G,8BADwB;AAExBoB,wBAFwB;AAGxBiB,kCAHwB;AAIxBS,4BAJwB;AAKxBmB,oBALwB;AAMxBE,8BANwB;AAOxBC,oBAPwB;AAQxBG,kBARwB;AASxBI,gDATwB;AAUxBM,0CAVwB;AAWxBS,gBAXwB;AAYxBD,oBAZwB;AAaxBE,wBAbwB;AAcxBG,gBAdwB;AAexBC,gBAfwB;AAgBxBC,sBAhBwB;AAiBxBV,4BAjBwB;AAkBxBrD;AAlBwB,O;;yBAqBXyE,iB","file":"timeseries.js","sourcesContent":["/**\n * timeseries.js\n *\n * This module contains functions for working with time series.\n *\n * datapoints - array of points where point is [value, timestamp]. In almost all cases (if other wasn't\n * explicitly said) we assume datapoints are sorted by timestamp. Timestamp is the number of milliseconds\n * since 1 January 1970 00:00:00 UTC.\n *\n */\n\nimport _ from 'lodash';\nimport * as utils from './utils';\n\nconst POINT_VALUE = 0;\nconst POINT_TIMESTAMP = 1;\n\n/**\n * Downsample time series by using given function (avg, min, max).\n */\nfunction downsample(datapoints, time_to, ms_interval, func) {\n var downsampledSeries = [];\n var timeWindow = {\n from: time_to * 1000 - ms_interval,\n to: time_to * 1000\n };\n\n var points_sum = 0;\n var points_num = 0;\n var value_avg = 0;\n var frame = [];\n\n for (var i = datapoints.length - 1; i >= 0; i -= 1) {\n if (timeWindow.from < datapoints[i][1] && datapoints[i][1] <= timeWindow.to) {\n points_sum += datapoints[i][0];\n points_num++;\n frame.push(datapoints[i][0]);\n }\n else {\n value_avg = points_num ? points_sum / points_num : 0;\n\n if (func === \"max\") {\n downsampledSeries.push([_.max(frame), timeWindow.to]);\n }\n else if (func === \"min\") {\n downsampledSeries.push([_.min(frame), timeWindow.to]);\n }\n\n // avg by default\n else {\n downsampledSeries.push([value_avg, timeWindow.to]);\n }\n\n // Shift time window\n timeWindow.to = timeWindow.from;\n timeWindow.from -= ms_interval;\n\n points_sum = 0;\n points_num = 0;\n frame = [];\n\n // Process point again\n i++;\n }\n }\n return downsampledSeries.reverse();\n}\n\n/**\n * Group points by given time interval\n * datapoints: [[, ], ...]\n */\nfunction groupBy(datapoints, interval, groupByCallback) {\n var ms_interval = utils.parseInterval(interval);\n\n // Calculate frame timestamps\n var frames = _.groupBy(datapoints, function (point) {\n // Calculate time for group of points\n return Math.floor(point[1] / ms_interval) * ms_interval;\n });\n\n // frame: { '': [[, ], ...] }\n // return [{ '': }, { '': }, ...]\n var grouped = _.mapValues(frames, function (frame) {\n var points = _.map(frame, function (point) {\n return point[0];\n });\n return groupByCallback(points);\n });\n\n // Convert points to Grafana format\n return sortByTime(_.map(grouped, function (value, timestamp) {\n return [Number(value), Number(timestamp)];\n }));\n}\n\nfunction groupBy_perf(datapoints, interval, groupByCallback) {\n if (datapoints.length === 0) {\n return [];\n }\n\n let ms_interval = utils.parseInterval(interval);\n let grouped_series = [];\n let frame_values = [];\n let frame_value;\n let frame_ts = datapoints.length ? getPointTimeFrame(datapoints[0][POINT_TIMESTAMP], ms_interval) : 0;\n let point_frame_ts = frame_ts;\n let point;\n\n for (let i=0; i < datapoints.length; i++) {\n point = datapoints[i];\n point_frame_ts = getPointTimeFrame(point[POINT_TIMESTAMP], ms_interval);\n if (point_frame_ts === frame_ts) {\n frame_values.push(point[POINT_VALUE]);\n } else if (point_frame_ts > frame_ts) {\n frame_value = groupByCallback(frame_values);\n grouped_series.push([frame_value, frame_ts]);\n\n // Move frame window to next non-empty interval and fill empty by null\n frame_ts += ms_interval;\n while (frame_ts < point_frame_ts) {\n grouped_series.push([null, frame_ts]);\n frame_ts += ms_interval;\n }\n frame_values = [point[POINT_VALUE]];\n }\n }\n\n frame_value = groupByCallback(frame_values);\n grouped_series.push([frame_value, frame_ts]);\n\n return grouped_series;\n}\n\n/**\n * Summarize set of time series into one.\n * @param {datapoints[]} timeseries array of time series\n */\nfunction sumSeries(timeseries) {\n\n // Calculate new points for interpolation\n var new_timestamps = _.uniq(_.map(_.flatten(timeseries, true), function (point) {\n return point[1];\n }));\n new_timestamps = _.sortBy(new_timestamps);\n\n var interpolated_timeseries = _.map(timeseries, function (series) {\n series = fillZeroes(series, new_timestamps);\n var timestamps = _.map(series, function (point) {\n return point[1];\n });\n var new_points = _.map(_.difference(new_timestamps, timestamps), function (timestamp) {\n return [null, timestamp];\n });\n var new_series = series.concat(new_points);\n return sortByTime(new_series);\n });\n\n _.each(interpolated_timeseries, interpolateSeries);\n\n var new_timeseries = [];\n var sum;\n for (var i = new_timestamps.length - 1; i >= 0; i--) {\n sum = 0;\n for (var j = interpolated_timeseries.length - 1; j >= 0; j--) {\n sum += interpolated_timeseries[j][i][0];\n }\n new_timeseries.push([sum, new_timestamps[i]]);\n }\n\n return sortByTime(new_timeseries);\n}\n\nfunction scale(datapoints, factor) {\n return _.map(datapoints, point => {\n return [\n point[0] * factor,\n point[1]\n ];\n });\n}\n\nfunction scale_perf(datapoints, factor) {\n for (let i = 0; i < datapoints.length; i++) {\n datapoints[i] = [\n datapoints[i][POINT_VALUE] * factor,\n datapoints[i][POINT_TIMESTAMP]\n ];\n }\n\n return datapoints;\n}\n\n/**\n * Simple delta. Calculate value delta between points.\n * @param {*} datapoints\n */\nfunction delta(datapoints) {\n let newSeries = [];\n let deltaValue;\n for (var i = 1; i < datapoints.length; i++) {\n deltaValue = datapoints[i][0] - datapoints[i - 1][0];\n newSeries.push([deltaValue, datapoints[i][1]]);\n }\n return newSeries;\n}\n\n/**\n * Calculates rate per second. Resistant to counter reset.\n * @param {*} datapoints\n */\nfunction rate(datapoints) {\n let newSeries = [];\n let point, point_prev;\n let valueDelta = 0;\n let timeDelta = 0;\n for (let i = 1; i < datapoints.length; i++) {\n point = datapoints[i];\n point_prev = datapoints[i - 1];\n\n // Convert ms to seconds\n timeDelta = (point[POINT_TIMESTAMP] - point_prev[POINT_TIMESTAMP]) / 1000;\n\n // Handle counter reset - use previous value\n if (point[POINT_VALUE] >= point_prev[POINT_VALUE]) {\n valueDelta = (point[POINT_VALUE] - point_prev[POINT_VALUE]) / timeDelta;\n }\n\n newSeries.push([valueDelta, point[POINT_TIMESTAMP]]);\n }\n return newSeries;\n}\n\nfunction simpleMovingAverage(datapoints, n) {\n let sma = [];\n let w_sum;\n let w_avg = null;\n let w_count = 0;\n\n // Initial window\n for (let j = n; j > 0; j--) {\n if (datapoints[n - j][POINT_VALUE] !== null) {\n w_avg += datapoints[n - j][POINT_VALUE];\n w_count++;\n }\n }\n if (w_count > 0) {\n w_avg = w_avg / w_count;\n } else {\n w_avg = null;\n }\n sma.push([w_avg, datapoints[n - 1][POINT_TIMESTAMP]]);\n\n for (let i = n; i < datapoints.length; i++) {\n // Insert next value\n if (datapoints[i][POINT_VALUE] !== null) {\n w_sum = w_avg * w_count;\n w_avg = (w_sum + datapoints[i][POINT_VALUE]) / (w_count + 1);\n w_count++;\n }\n // Remove left side point\n if (datapoints[i - n][POINT_VALUE] !== null) {\n w_sum = w_avg * w_count;\n if (w_count > 1) {\n w_avg = (w_sum - datapoints[i - n][POINT_VALUE]) / (w_count - 1);\n w_count--;\n } else {\n w_avg = null;\n w_count = 0;\n }\n }\n sma.push([w_avg, datapoints[i][POINT_TIMESTAMP]]);\n }\n return sma;\n}\n\nfunction expMovingAverage(datapoints, n) {\n let ema = [datapoints[0]];\n let ema_prev = datapoints[0][POINT_VALUE];\n let ema_cur;\n let a;\n\n if (n > 1) {\n // Calculate a from window size\n a = 2 / (n + 1);\n\n // Initial window, use simple moving average\n let w_avg = null;\n let w_count = 0;\n for (let j = n; j > 0; j--) {\n if (datapoints[n - j][POINT_VALUE] !== null) {\n w_avg += datapoints[n - j][POINT_VALUE];\n w_count++;\n }\n }\n if (w_count > 0) {\n w_avg = w_avg / w_count;\n // Actually, we should set timestamp from datapoints[n-1] and start calculation of EMA from n.\n // But in order to start EMA from first point (not from Nth) we should expand time range and request N additional\n // points outside left side of range. We can't do that, so this trick is used for pretty view of first N points.\n // We calculate AVG for first N points, but then start from 2nd point, not from Nth. In general, it means we\n // assume that previous N values (0-N, 0-(N-1), ..., 0-1) have the same average value as a first N values.\n ema = [[w_avg, datapoints[0][POINT_TIMESTAMP]]];\n ema_prev = w_avg;\n n = 1;\n }\n } else {\n // Use predefined a and start from 1st point (use it as initial EMA value)\n a = n;\n n = 1;\n }\n\n for (let i = n; i < datapoints.length; i++) {\n if (datapoints[i][POINT_VALUE] !== null) {\n ema_cur = a * datapoints[i][POINT_VALUE] + (1 - a) * ema_prev;\n ema_prev = ema_cur;\n ema.push([ema_cur, datapoints[i][POINT_TIMESTAMP]]);\n } else {\n ema.push([null, datapoints[i][POINT_TIMESTAMP]]);\n }\n }\n return ema;\n}\n\nfunction PERCENTIL(n, values) {\n var sorted = _.sortBy(values);\n return sorted[Math.floor(sorted.length * n / 100)];\n}\n\nfunction COUNT(values) {\n return values.length;\n}\n\nfunction SUM(values) {\n var sum = null;\n for (let i = 0; i < values.length; i++) {\n if (values[i] !== null) {\n sum += values[i];\n }\n }\n return sum;\n}\n\nfunction AVERAGE(values) {\n let values_non_null = getNonNullValues(values);\n if (values_non_null.length === 0) {\n return null;\n }\n return SUM(values_non_null) / values_non_null.length;\n}\n\nfunction getNonNullValues(values) {\n let values_non_null = [];\n for (let i = 0; i < values.length; i++) {\n if (values[i] !== null) {\n values_non_null.push(values[i]);\n }\n }\n return values_non_null;\n}\n\nfunction MIN(values) {\n return _.min(values);\n}\n\nfunction MAX(values) {\n return _.max(values);\n}\n\nfunction MEDIAN(values) {\n var sorted = _.sortBy(values);\n return sorted[Math.floor(sorted.length / 2)];\n}\n\n///////////////////////\n// Utility functions //\n///////////////////////\n\n/**\n * For given point calculate corresponding time frame.\n *\n * |__*_|_*__|___*| -> |*___|*___|*___|\n *\n * @param {*} timestamp\n * @param {*} ms_interval\n */\nfunction getPointTimeFrame(timestamp, ms_interval) {\n return Math.floor(timestamp / ms_interval) * ms_interval;\n}\n\nfunction sortByTime(series) {\n return _.sortBy(series, function (point) {\n return point[1];\n });\n}\n\n/**\n * Fill empty front and end of series by zeroes.\n *\n * | *** | | *** |\n * |___ ___| -> |*** ***|\n * @param {*} series\n * @param {*} timestamps\n */\nfunction fillZeroes(series, timestamps) {\n let prepend = [];\n let append = [];\n let new_point;\n for (let i = 0; i < timestamps.length; i++) {\n if (timestamps[i] < series[0][POINT_TIMESTAMP]) {\n new_point = [0, timestamps[i]];\n prepend.push(new_point);\n } else if (timestamps[i] > series[series.length - 1][POINT_TIMESTAMP]) {\n new_point = [0, timestamps[i]];\n append.push(new_point);\n }\n }\n return _.concat(_.concat(prepend, series), append);\n}\n\n/**\n * Interpolate series with gaps\n */\nfunction interpolateSeries(series) {\n var left, right;\n\n // Interpolate series\n for (var i = series.length - 1; i >= 0; i--) {\n if (!series[i][0]) {\n left = findNearestLeft(series, i);\n right = findNearestRight(series, i);\n if (!left) {\n left = right;\n }\n if (!right) {\n right = left;\n }\n series[i][0] = linearInterpolation(series[i][1], left, right);\n }\n }\n return series;\n}\n\nfunction linearInterpolation(timestamp, left, right) {\n if (left[1] === right[1]) {\n return (left[0] + right[0]) / 2;\n } else {\n return (left[0] + (right[0] - left[0]) / (right[1] - left[1]) * (timestamp - left[1]));\n }\n}\n\nfunction findNearestRight(series, pointIndex) {\n for (var i = pointIndex; i < series.length; i++) {\n if (series[i][0] !== null) {\n return series[i];\n }\n }\n return null;\n}\n\nfunction findNearestLeft(series, pointIndex) {\n for (var i = pointIndex; i > 0; i--) {\n if (series[i][0] !== null) {\n return series[i];\n }\n }\n return null;\n}\n\n////////////\n// Export //\n////////////\n\nconst exportedFunctions = {\n downsample,\n groupBy,\n groupBy_perf,\n sumSeries,\n scale,\n scale_perf,\n delta,\n rate,\n simpleMovingAverage,\n expMovingAverage,\n SUM,\n COUNT,\n AVERAGE,\n MIN,\n MAX,\n MEDIAN,\n PERCENTIL,\n sortByTime\n};\n\nexport default exportedFunctions;\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/timeseries.js"],"names":["downsample","datapoints","time_to","ms_interval","func","downsampledSeries","timeWindow","from","to","points_sum","points_num","value_avg","frame","i","length","push","_","max","min","reverse","groupBy","interval","groupByCallback","utils","parseInterval","frames","point","Math","floor","grouped","mapValues","points","map","sortByTime","value","timestamp","Number","groupBy_perf","grouped_series","frame_values","frame_value","frame_ts","getPointTimeFrame","POINT_TIMESTAMP","point_frame_ts","POINT_VALUE","sumSeries","timeseries","new_timestamps","uniq","flatten","sortBy","interpolated_timeseries","series","fillZeroes","timestamps","new_points","difference","new_series","concat","each","interpolateSeries","new_timeseries","sum","j","scale","factor","scale_perf","delta","newSeries","deltaValue","rate","point_prev","valueDelta","timeDelta","simpleMovingAverage","n","sma","w_sum","w_avg","w_count","expMovingAverage","ema","ema_prev","ema_cur","a","PERCENTIL","values","sorted","COUNT","SUM","AVERAGE","values_non_null","getNonNullValues","MIN","MAX","MEDIAN","prepend","append","new_point","left","right","findNearestLeft","findNearestRight","linearInterpolation","pointIndex","exportedFunctions"],"mappings":";;;;;;;AAiBA;;;AAGA,WAASA,UAAT,CAAoBC,UAApB,EAAgCC,OAAhC,EAAyCC,WAAzC,EAAsDC,IAAtD,EAA4D;AAC1D,QAAIC,oBAAoB,EAAxB;AACA,QAAIC,aAAa;AACfC,YAAML,UAAU,IAAV,GAAiBC,WADR;AAEfK,UAAIN,UAAU;AAFC,KAAjB;;AAKA,QAAIO,aAAa,CAAjB;AACA,QAAIC,aAAa,CAAjB;AACA,QAAIC,YAAY,CAAhB;AACA,QAAIC,QAAQ,EAAZ;;AAEA,SAAK,IAAIC,IAAIZ,WAAWa,MAAX,GAAoB,CAAjC,EAAoCD,KAAK,CAAzC,EAA4CA,KAAK,CAAjD,EAAoD;AAClD,UAAIP,WAAWC,IAAX,GAAkBN,WAAWY,CAAX,EAAc,CAAd,CAAlB,IAAsCZ,WAAWY,CAAX,EAAc,CAAd,KAAoBP,WAAWE,EAAzE,EAA6E;AAC3EC,sBAAcR,WAAWY,CAAX,EAAc,CAAd,CAAd;AACAH;AACAE,cAAMG,IAAN,CAAWd,WAAWY,CAAX,EA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A,GAAhC,EAAqC;AACnC,UAAIwC,OAAOxC,CAAP,EAAU,CAAV,MAAiB,IAArB,EAA2B;AACzB,eAAOwC,OAAOxC,CAAP,CAAP;AACD;AACF;AACD,WAAO,IAAP;AACD;;AAED;AACA;AACA;;;;AA5cOG,O;;AACKO,W;;;AAENsB,iB,GAAc,C;AACdF,qB,GAAkB,C;AA0clB+D,uB,GAAoB;AACxB1G,8BADwB;AAExBoB,wBAFwB;AAGxBiB,kCAHwB;AAIxBS,4BAJwB;AAKxBmB,oBALwB;AAMxBE,8BANwB;AAOxBC,oBAPwB;AAQxBG,kBARwB;AASxBI,gDATwB;AAUxBM,0CAVwB;AAWxBS,gBAXwB;AAYxBD,oBAZwB;AAaxBE,wBAbwB;AAcxBG,gBAdwB;AAexBC,gBAfwB;AAgBxBC,sBAhBwB;AAiBxBV,4BAjBwB;AAkBxBrD;AAlBwB,O;;yBAqBXyE,iB","file":"timeseries.js","sourcesContent":["/**\r\n * timeseries.js\r\n *\r\n * This module contains functions for working with time series.\r\n *\r\n * datapoints - array of points where point is [value, timestamp]. In almost all cases (if other wasn't\r\n * explicitly said) we assume datapoints are sorted by timestamp. Timestamp is the number of milliseconds\r\n * since 1 January 1970 00:00:00 UTC.\r\n *\r\n */\r\n\r\nimport _ from 'lodash';\r\nimport * as utils from './utils';\r\n\r\nconst POINT_VALUE = 0;\r\nconst POINT_TIMESTAMP = 1;\r\n\r\n/**\r\n * Downsample time series by using given function (avg, min, max).\r\n */\r\nfunction downsample(datapoints, time_to, ms_interval, func) {\r\n var downsampledSeries = [];\r\n var timeWindow = {\r\n from: time_to * 1000 - ms_interval,\r\n to: time_to * 1000\r\n };\r\n\r\n var points_sum = 0;\r\n var points_num = 0;\r\n var value_avg = 0;\r\n var frame = [];\r\n\r\n for (var i = datapoints.length - 1; i >= 0; i -= 1) {\r\n if (timeWindow.from < datapoints[i][1] && datapoints[i][1] <= timeWindow.to) {\r\n points_sum += datapoints[i][0];\r\n points_num++;\r\n frame.push(datapoints[i][0]);\r\n }\r\n else {\r\n value_avg = points_num ? points_sum / points_num : 0;\r\n\r\n if (func === \"max\") {\r\n downsampledSeries.push([_.max(frame), timeWindow.to]);\r\n }\r\n else if (func === \"min\") {\r\n downsampledSeries.push([_.min(frame), timeWindow.to]);\r\n }\r\n\r\n // avg by default\r\n else {\r\n downsampledSeries.push([value_avg, timeWindow.to]);\r\n }\r\n\r\n // Shift time window\r\n timeWindow.to = timeWindow.from;\r\n timeWindow.from -= ms_interval;\r\n\r\n points_sum = 0;\r\n points_num = 0;\r\n frame = [];\r\n\r\n // Process point again\r\n i++;\r\n }\r\n }\r\n return downsampledSeries.reverse();\r\n}\r\n\r\n/**\r\n * Group points by given time interval\r\n * datapoints: [[, ], ...]\r\n */\r\nfunction groupBy(datapoints, interval, groupByCallback) {\r\n var ms_interval = utils.parseInterval(interval);\r\n\r\n // Calculate frame timestamps\r\n var frames = _.groupBy(datapoints, function (point) {\r\n // Calculate time for group of points\r\n return Math.floor(point[1] / ms_interval) * ms_interval;\r\n });\r\n\r\n // frame: { '': [[, ], ...] }\r\n // return [{ '': }, { '': }, ...]\r\n var grouped = _.mapValues(frames, function (frame) {\r\n var points = _.map(frame, function (point) {\r\n return point[0];\r\n });\r\n return groupByCallback(points);\r\n });\r\n\r\n // Convert points to Grafana format\r\n return sortByTime(_.map(grouped, function (value, timestamp) {\r\n return [Number(value), Number(timestamp)];\r\n }));\r\n}\r\n\r\nfunction groupBy_perf(datapoints, interval, groupByCallback) {\r\n if (datapoints.length === 0) {\r\n return [];\r\n }\r\n\r\n let ms_interval = utils.parseInterval(interval);\r\n let grouped_series = [];\r\n let frame_values = [];\r\n let frame_value;\r\n let frame_ts = datapoints.length ? getPointTimeFrame(datapoints[0][POINT_TIMESTAMP], ms_interval) : 0;\r\n let point_frame_ts = frame_ts;\r\n let point;\r\n\r\n for (let i=0; i < datapoints.length; i++) {\r\n point = datapoints[i];\r\n point_frame_ts = getPointTimeFrame(point[POINT_TIMESTAMP], ms_interval);\r\n if (point_frame_ts === frame_ts) {\r\n frame_values.push(point[POINT_VALUE]);\r\n } else if (point_frame_ts > frame_ts) {\r\n frame_value = groupByCallback(frame_values);\r\n grouped_series.push([frame_value, frame_ts]);\r\n\r\n // Move frame window to next non-empty interval and fill empty by null\r\n frame_ts += ms_interval;\r\n while (frame_ts < point_frame_ts) {\r\n grouped_series.push([null, frame_ts]);\r\n frame_ts += ms_interval;\r\n }\r\n frame_values = [point[POINT_VALUE]];\r\n }\r\n }\r\n\r\n frame_value = groupByCallback(frame_values);\r\n grouped_series.push([frame_value, frame_ts]);\r\n\r\n return grouped_series;\r\n}\r\n\r\n/**\r\n * Summarize set of time series into one.\r\n * @param {datapoints[]} timeseries array of time series\r\n */\r\nfunction sumSeries(timeseries) {\r\n\r\n // Calculate new points for interpolation\r\n var new_timestamps = _.uniq(_.map(_.flatten(timeseries, true), function (point) {\r\n return point[1];\r\n }));\r\n new_timestamps = _.sortBy(new_timestamps);\r\n\r\n var interpolated_timeseries = _.map(timeseries, function (series) {\r\n series = fillZeroes(series, new_timestamps);\r\n var timestamps = _.map(series, function (point) {\r\n return point[1];\r\n });\r\n var new_points = _.map(_.difference(new_timestamps, timestamps), function (timestamp) {\r\n return [null, timestamp];\r\n });\r\n var new_series = series.concat(new_points);\r\n return sortByTime(new_series);\r\n });\r\n\r\n _.each(interpolated_timeseries, interpolateSeries);\r\n\r\n var new_timeseries = [];\r\n var sum;\r\n for (var i = new_timestamps.length - 1; i >= 0; i--) {\r\n sum = 0;\r\n for (var j = interpolated_timeseries.length - 1; j >= 0; j--) {\r\n sum += interpolated_timeseries[j][i][0];\r\n }\r\n new_timeseries.push([sum, new_timestamps[i]]);\r\n }\r\n\r\n return sortByTime(new_timeseries);\r\n}\r\n\r\nfunction scale(datapoints, factor) {\r\n return _.map(datapoints, point => {\r\n return [\r\n point[0] * factor,\r\n point[1]\r\n ];\r\n });\r\n}\r\n\r\nfunction scale_perf(datapoints, factor) {\r\n for (let i = 0; i < datapoints.length; i++) {\r\n datapoints[i] = [\r\n datapoints[i][POINT_VALUE] * factor,\r\n datapoints[i][POINT_TIMESTAMP]\r\n ];\r\n }\r\n\r\n return datapoints;\r\n}\r\n\r\n/**\r\n * Simple delta. Calculate value delta between points.\r\n * @param {*} datapoints\r\n */\r\nfunction delta(datapoints) {\r\n let newSeries = [];\r\n let deltaValue;\r\n for (var i = 1; i < datapoints.length; i++) {\r\n deltaValue = datapoints[i][0] - datapoints[i - 1][0];\r\n newSeries.push([deltaValue, datapoints[i][1]]);\r\n }\r\n return newSeries;\r\n}\r\n\r\n/**\r\n * Calculates rate per second. Resistant to counter reset.\r\n * @param {*} datapoints\r\n */\r\nfunction rate(datapoints) {\r\n let newSeries = [];\r\n let point, point_prev;\r\n let valueDelta = 0;\r\n let timeDelta = 0;\r\n for (let i = 1; i < datapoints.length; i++) {\r\n point = datapoints[i];\r\n point_prev = datapoints[i - 1];\r\n\r\n // Convert ms to seconds\r\n timeDelta = (point[POINT_TIMESTAMP] - point_prev[POINT_TIMESTAMP]) / 1000;\r\n\r\n // Handle counter reset - use previous value\r\n if (point[POINT_VALUE] >= point_prev[POINT_VALUE]) {\r\n valueDelta = (point[POINT_VALUE] - point_prev[POINT_VALUE]) / timeDelta;\r\n }\r\n\r\n newSeries.push([valueDelta, point[POINT_TIMESTAMP]]);\r\n }\r\n return newSeries;\r\n}\r\n\r\nfunction simpleMovingAverage(datapoints, n) {\r\n let sma = [];\r\n let w_sum;\r\n let w_avg = null;\r\n let w_count = 0;\r\n\r\n // Initial window\r\n for (let j = n; j > 0; j--) {\r\n if (datapoints[n - j][POINT_VALUE] !== null) {\r\n w_avg += datapoints[n - j][POINT_VALUE];\r\n w_count++;\r\n }\r\n }\r\n if (w_count > 0) {\r\n w_avg = w_avg / w_count;\r\n } else {\r\n w_avg = null;\r\n }\r\n sma.push([w_avg, datapoints[n - 1][POINT_TIMESTAMP]]);\r\n\r\n for (let i = n; i < datapoints.length; i++) {\r\n // Insert next value\r\n if (datapoints[i][POINT_VALUE] !== null) {\r\n w_sum = w_avg * w_count;\r\n w_avg = (w_sum + datapoints[i][POINT_VALUE]) / (w_count + 1);\r\n w_count++;\r\n }\r\n // Remove left side point\r\n if (datapoints[i - n][POINT_VALUE] !== null) {\r\n w_sum = w_avg * w_count;\r\n if (w_count > 1) {\r\n w_avg = (w_sum - datapoints[i - n][POINT_VALUE]) / (w_count - 1);\r\n w_count--;\r\n } else {\r\n w_avg = null;\r\n w_count = 0;\r\n }\r\n }\r\n sma.push([w_avg, datapoints[i][POINT_TIMESTAMP]]);\r\n }\r\n return sma;\r\n}\r\n\r\nfunction expMovingAverage(datapoints, n) {\r\n let ema = [datapoints[0]];\r\n let ema_prev = datapoints[0][POINT_VALUE];\r\n let ema_cur;\r\n let a;\r\n\r\n if (n > 1) {\r\n // Calculate a from window size\r\n a = 2 / (n + 1);\r\n\r\n // Initial window, use simple moving average\r\n let w_avg = null;\r\n let w_count = 0;\r\n for (let j = n; j > 0; j--) {\r\n if (datapoints[n - j][POINT_VALUE] !== null) {\r\n w_avg += datapoints[n - j][POINT_VALUE];\r\n w_count++;\r\n }\r\n }\r\n if (w_count > 0) {\r\n w_avg = w_avg / w_count;\r\n // Actually, we should set timestamp from datapoints[n-1] and start calculation of EMA from n.\r\n // But in order to start EMA from first point (not from Nth) we should expand time range and request N additional\r\n // points outside left side of range. We can't do that, so this trick is used for pretty view of first N points.\r\n // We calculate AVG for first N points, but then start from 2nd point, not from Nth. In general, it means we\r\n // assume that previous N values (0-N, 0-(N-1), ..., 0-1) have the same average value as a first N values.\r\n ema = [[w_avg, datapoints[0][POINT_TIMESTAMP]]];\r\n ema_prev = w_avg;\r\n n = 1;\r\n }\r\n } else {\r\n // Use predefined a and start from 1st point (use it as initial EMA value)\r\n a = n;\r\n n = 1;\r\n }\r\n\r\n for (let i = n; i < datapoints.length; i++) {\r\n if (datapoints[i][POINT_VALUE] !== null) {\r\n ema_cur = a * datapoints[i][POINT_VALUE] + (1 - a) * ema_prev;\r\n ema_prev = ema_cur;\r\n ema.push([ema_cur, datapoints[i][POINT_TIMESTAMP]]);\r\n } else {\r\n ema.push([null, datapoints[i][POINT_TIMESTAMP]]);\r\n }\r\n }\r\n return ema;\r\n}\r\n\r\nfunction PERCENTIL(n, values) {\r\n var sorted = _.sortBy(values);\r\n return sorted[Math.floor(sorted.length * n / 100)];\r\n}\r\n\r\nfunction COUNT(values) {\r\n return values.length;\r\n}\r\n\r\nfunction SUM(values) {\r\n var sum = null;\r\n for (let i = 0; i < values.length; i++) {\r\n if (values[i] !== null) {\r\n sum += values[i];\r\n }\r\n }\r\n return sum;\r\n}\r\n\r\nfunction AVERAGE(values) {\r\n let values_non_null = getNonNullValues(values);\r\n if (values_non_null.length === 0) {\r\n return null;\r\n }\r\n return SUM(values_non_null) / values_non_null.length;\r\n}\r\n\r\nfunction getNonNullValues(values) {\r\n let values_non_null = [];\r\n for (let i = 0; i < values.length; i++) {\r\n if (values[i] !== null) {\r\n values_non_null.push(values[i]);\r\n }\r\n }\r\n return values_non_null;\r\n}\r\n\r\nfunction MIN(values) {\r\n return _.min(values);\r\n}\r\n\r\nfunction MAX(values) {\r\n return _.max(values);\r\n}\r\n\r\nfunction MEDIAN(values) {\r\n var sorted = _.sortBy(values);\r\n return sorted[Math.floor(sorted.length / 2)];\r\n}\r\n\r\n///////////////////////\r\n// Utility functions //\r\n///////////////////////\r\n\r\n/**\r\n * For given point calculate corresponding time frame.\r\n *\r\n * |__*_|_*__|___*| -> |*___|*___|*___|\r\n *\r\n * @param {*} timestamp\r\n * @param {*} ms_interval\r\n */\r\nfunction getPointTimeFrame(timestamp, ms_interval) {\r\n return Math.floor(timestamp / ms_interval) * ms_interval;\r\n}\r\n\r\nfunction sortByTime(series) {\r\n return _.sortBy(series, function (point) {\r\n return point[1];\r\n });\r\n}\r\n\r\n/**\r\n * Fill empty front and end of series by zeroes.\r\n *\r\n * | *** | | *** |\r\n * |___ ___| -> |*** ***|\r\n * @param {*} series\r\n * @param {*} timestamps\r\n */\r\nfunction fillZeroes(series, timestamps) {\r\n let prepend = [];\r\n let append = [];\r\n let new_point;\r\n for (let i = 0; i < timestamps.length; i++) {\r\n if (timestamps[i] < series[0][POINT_TIMESTAMP]) {\r\n new_point = [0, timestamps[i]];\r\n prepend.push(new_point);\r\n } else if (timestamps[i] > series[series.length - 1][POINT_TIMESTAMP]) {\r\n new_point = [0, timestamps[i]];\r\n append.push(new_point);\r\n }\r\n }\r\n return _.concat(_.concat(prepend, series), append);\r\n}\r\n\r\n/**\r\n * Interpolate series with gaps\r\n */\r\nfunction interpolateSeries(series) {\r\n var left, right;\r\n\r\n // Interpolate series\r\n for (var i = series.length - 1; i >= 0; i--) {\r\n if (!series[i][0]) {\r\n left = findNearestLeft(series, i);\r\n right = findNearestRight(series, i);\r\n if (!left) {\r\n left = right;\r\n }\r\n if (!right) {\r\n right = left;\r\n }\r\n series[i][0] = linearInterpolation(series[i][1], left, right);\r\n }\r\n }\r\n return series;\r\n}\r\n\r\nfunction linearInterpolation(timestamp, left, right) {\r\n if (left[1] === right[1]) {\r\n return (left[0] + right[0]) / 2;\r\n } else {\r\n return (left[0] + (right[0] - left[0]) / (right[1] - left[1]) * (timestamp - left[1]));\r\n }\r\n}\r\n\r\nfunction findNearestRight(series, pointIndex) {\r\n for (var i = pointIndex; i < series.length; i++) {\r\n if (series[i][0] !== null) {\r\n return series[i];\r\n }\r\n }\r\n return null;\r\n}\r\n\r\nfunction findNearestLeft(series, pointIndex) {\r\n for (var i = pointIndex; i > 0; i--) {\r\n if (series[i][0] !== null) {\r\n return series[i];\r\n }\r\n }\r\n return null;\r\n}\r\n\r\n////////////\r\n// Export //\r\n////////////\r\n\r\nconst exportedFunctions = {\r\n downsample,\r\n groupBy,\r\n groupBy_perf,\r\n sumSeries,\r\n scale,\r\n scale_perf,\r\n delta,\r\n rate,\r\n simpleMovingAverage,\r\n expMovingAverage,\r\n SUM,\r\n COUNT,\r\n AVERAGE,\r\n MIN,\r\n MAX,\r\n MEDIAN,\r\n PERCENTIL,\r\n sortByTime\r\n};\r\n\r\nexport default exportedFunctions;\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/utils.js b/dist/datasource-zabbix/utils.js index 9f370a11b..4fe4f8181 100644 --- a/dist/datasource-zabbix/utils.js +++ b/dist/datasource-zabbix/utils.js @@ -5,12 +5,12 @@ System.register(['lodash', 'moment'], function (_export, _context) { var _, moment, MACRO_PATTERN, regexPattern; - /** - * Expand Zabbix item name - * - * @param {string} name item name, ie "CPU $2 time" - * @param {string} key item key, ie system.cpu.util[,system,avg1] - * @return {string} expanded name, ie "CPU system time" + /** + * Expand Zabbix item name + * + * @param {string} name item name, ie "CPU $2 time" + * @param {string} key item key, ie system.cpu.util[,system,avg1] + * @return {string} expanded name, ie "CPU system time" */ function expandItemName(name, key) { @@ -105,10 +105,10 @@ System.register(['lodash', 'moment'], function (_export, _context) { return macro; } - /** - * Split template query to parts of zabbix entities - * group.host.app.item -> [group, host, app, item] - * {group}{host.com} -> [group, host.com] + /** + * Split template query to parts of zabbix entities + * group.host.app.item -> [group, host, app, item] + * {group}{host.com} -> [group, host.com] */ function splitTemplateQuery(query) { var splitPattern = /\{[^\{\}]*\}|\{\/.*\/\}/g; @@ -194,11 +194,11 @@ System.register(['lodash', 'moment'], function (_export, _context) { return duration; } - /** - * Format acknowledges. - * - * @param {array} acknowledges array of Zabbix acknowledge objects - * @return {string} HTML-formatted table + /** + * Format acknowledges. + * + * @param {array} acknowledges array of Zabbix acknowledge objects + * @return {string} HTML-formatted table */ _export('parseTimeShiftInterval', parseTimeShiftInterval); @@ -231,9 +231,9 @@ System.register(['lodash', 'moment'], function (_export, _context) { } } - /** - * Wrap function to prevent multiple calls - * when waiting for result. + /** + * Wrap function to prevent multiple calls + * when waiting for result. */ _export('convertToZabbixAPIUrl', convertToZabbixAPIUrl); diff --git a/dist/datasource-zabbix/utils.js.map b/dist/datasource-zabbix/utils.js.map index 94c6f0aa3..a111dc852 100644 --- a/dist/datasource-zabbix/utils.js.map +++ b/dist/datasource-zabbix/utils.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/utils.js"],"names":["expandItemName","name","key","key_params_str","substring","indexOf","lastIndexOf","key_params","splitKeyParams","i","length","replace","expandItems","items","_","forEach","item","key_","paramStr","params","quoted","in_array","split_symbol","param","symbol","push","containsMacro","itemName","MACRO_PATTERN","test","replaceMacro","macros","item_macros","match","host_macros","filter","m","hostid","macro_def","find","macro","value","macro_value","macro_regex","RegExp","escapeMacro","splitTemplateQuery","query","splitPattern","split","isContainsBraces","result","map","trim","part","bracesPattern","isRegex","str","regexPattern","isTemplateVariable","templateVariables","variablePattern","variables","variable","includes","buildRegex","matches","pattern","flags","undefined","escapeRegex","parseInterval","interval","intervalPattern","momentInterval","exec","moment","duration","Number","valueOf","parseTimeShiftInterval","formatAcknowledges","acknowledges","formatted_acknowledges","each","ack","timestamp","unix","clock","format","alias","surname","message","concat","convertToZabbixAPIUrl","url","zabbixAPIUrlPattern","trimSlashPattern","callOnce","func","promiseKeeper","Promise","resolve","apply","arguments","then","contains"],"mappings":";;;;;;;AAGA;;;;;;;AAOO,WAASA,cAAT,CAAwBC,IAAxB,EAA8BC,GAA9B,EAAmC;;AAExC;AACA;AACA,QAAIC,iBAAiBD,IAAIE,SAAJ,CAAcF,IAAIG,OAAJ,CAAY,GAAZ,IAAmB,CAAjC,EAAoCH,IAAII,WAAJ,CAAgB,GAAhB,CAApC,CAArB;AACA,QAAIC,aAAaC,eAAeL,cAAf,CAAjB;;AAEA;AACA,SAAK,IAAIM,IAAIF,WAAWG,MAAxB,EAAgCD,KAAK,CAArC,EAAwCA,GAAxC,EAA6C;AAC3CR,aAAOA,KAAKU,OAAL,CAAa,MAAMF,CAAnB,EAAsBF,WAAWE,IAAI,CAAf,CAAtB,CAAP;AACD;AACD,WAAOR,IAAP;AACD;;4BAZeD,c;;AAcT,WAASY,WAAT,CAAqBC,KAArB,EAA4B;AACjCC,MAAEC,OAAF,CAAUF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AAvB,CAA8BR,GAA9B,CAAzB;AACD,OAND;AAOAF,+BAAyBA,uBAAuBU,MAAvB,CAA8B,UAA9B,CAAzB;AACA,aAAOV,sBAAP;AACD,KAZD,MAYO;AACL,aAAO,EAAP;AACD;AACF;;gCAhBeF,kB;;AAkBT,WAASa,qBAAT,CAA+BC,GAA/B,EAAoC;AACzC,QAAIC,sBAAsB,oBAA1B;AACA,QAAIC,mBAAmB,aAAvB;AACA,QAAIF,IAAI9D,KAAJ,CAAU+D,mBAAV,CAAJ,EAAoC;AAClC,aAAOD,GAAP;AACD,KAFD,MAEO;AACL,aAAOA,IAAIpF,OAAJ,CAAYsF,gBAAZ,EAA8B,IAA9B,CAAP;AACD;AACF;;AAED;;;;;mCAVgBH,qB;;AAcT,WAASI,QAAT,CAAkBC,IAAlB,EAAwBC,aAAxB,EAAuC;AAC5C,WAAO,YAAW;AAChB,UAAI,CAACA,aAAL,EAAoB;AAClBA,wBAAgBC,QAAQC,OAAR,CACdH,KAAKI,KAAL,CAAW,IAAX,EAAiBC,SAAjB,EACCC,IADD,CACM,kBAAU;AACdL,0BAAgB,IAAhB;AACA,iBAAOjD,MAAP;AACD,SAJD,CADc,CAAhB;AAOD;AACD,aAAOiD,aAAP;AACD,KAXD;AAYD;;AAED;;sBAfgBF,Q;;;;AAtNTpF,O;;AACA8D,Y;;;AA8DDhD,mB,GAAgB,mB;;8BA8DT8B,Y,GAAe,qB;;;;AAyG5B,UAAI,CAAC5C,EAAEkD,QAAP,EAAiB;AACflD,UAAEkD,QAAF,GAAalD,EAAE4F,QAAf;AACD","file":"utils.js","sourcesContent":["import _ from 'lodash';\nimport moment from 'moment';\n\n/**\n * Expand Zabbix item name\n *\n * @param {string} name item name, ie \"CPU $2 time\"\n * @param {string} key item key, ie system.cpu.util[,system,avg1]\n * @return {string} expanded name, ie \"CPU system time\"\n */\nexport function expandItemName(name, key) {\n\n // extract params from key:\n // \"system.cpu.util[,system,avg1]\" --> [\"\", \"system\", \"avg1\"]\n let key_params_str = key.substring(key.indexOf('[') + 1, key.lastIndexOf(']'));\n let key_params = splitKeyParams(key_params_str);\n\n // replace item parameters\n for (let i = key_params.length; i >= 1; i--) {\n name = name.replace('$' + i, key_params[i - 1]);\n }\n return name;\n}\n\nexport function expandItems(items) {\n _.forEach(items, item => {\n item.item = item.name;\n item.name = expandItemName(item.item, item.key_);\n return item;\n });\n return items;\n}\n\nfunction splitKeyParams(paramStr) {\n let params = [];\n let quoted = false;\n let in_array = false;\n let split_symbol = ',';\n let param = '';\n\n _.forEach(paramStr, symbol => {\n if (symbol === '\"' && in_array) {\n param += symbol;\n } else if (symbol === '\"' && quoted) {\n quoted = false;\n } else if (symbol === '\"' && !quoted) {\n quoted = true;\n } else if (symbol === '[' && !quoted) {\n in_array = true;\n } else if (symbol === ']' && !quoted) {\n in_array = false;\n } else if (symbol === split_symbol && !quoted && !in_array) {\n params.push(param);\n param = '';\n } else {\n param += symbol;\n }\n });\n\n params.push(param);\n return params;\n}\n\nconst MACRO_PATTERN = /{\\$[A-Z0-9_\\.]+}/g;\n\nexport function containsMacro(itemName) {\n return MACRO_PATTERN.test(itemName);\n}\n\nexport function replaceMacro(item, macros) {\n let itemName = item.name;\n let item_macros = itemName.match(MACRO_PATTERN);\n _.forEach(item_macros, macro => {\n let host_macros = _.filter(macros, m => {\n if (m.hostid) {\n return m.hostid === item.hostid;\n } else {\n // Add global macros\n return true;\n }\n });\n\n let macro_def = _.find(host_macros, { macro: macro });\n if (macro_def && macro_def.value) {\n let macro_value = macro_def.value;\n let macro_regex = new RegExp(escapeMacro(macro));\n itemName = itemName.replace(macro_regex, macro_value);\n }\n });\n\n return itemName;\n}\n\nfunction escapeMacro(macro) {\n macro = macro.replace(/\\$/, '\\\\\\$');\n return macro;\n}\n\n/**\n * Split template query to parts of zabbix entities\n * group.host.app.item -> [group, host, app, item]\n * {group}{host.com} -> [group, host.com]\n */\nexport function splitTemplateQuery(query) {\n let splitPattern = /\\{[^\\{\\}]*\\}|\\{\\/.*\\/\\}/g;\n let split;\n\n if (isContainsBraces(query)) {\n let result = query.match(splitPattern);\n split = _.map(result, part => {\n return _.trim(part, '{}');\n });\n } else {\n split = query.split('.');\n }\n\n return split;\n}\n\nfunction isContainsBraces(query) {\n let bracesPattern = /^\\{.+\\}$/;\n return bracesPattern.test(query);\n}\n\n// Pattern for testing regex\nexport const regexPattern = /^\\/(.*)\\/([gmi]*)$/m;\n\nexport function isRegex(str) {\n return regexPattern.test(str);\n}\n\nexport function isTemplateVariable(str, templateVariables) {\n var variablePattern = /^\\$\\w+/;\n if (variablePattern.test(str)) {\n var variables = _.map(templateVariables, variable => {\n return '$' + variable.name;\n });\n return _.includes(variables, str);\n } else {\n return false;\n }\n}\n\nexport function buildRegex(str) {\n var matches = str.match(regexPattern);\n var pattern = matches[1];\n var flags = matches[2] !== \"\" ? matches[2] : undefined;\n return new RegExp(pattern, flags);\n}\n\n// Need for template variables replace\n// From Grafana's templateSrv.js\nexport function escapeRegex(value) {\n return value.replace(/[\\\\^$*+?.()|[\\]{}\\/]/g, '\\\\$&');\n}\n\nexport function parseInterval(interval) {\n var intervalPattern = /(^[\\d]+)(y|M|w|d|h|m|s)/g;\n var momentInterval = intervalPattern.exec(interval);\n return moment.duration(Number(momentInterval[1]), momentInterval[2]).valueOf();\n}\n\nexport function parseTimeShiftInterval(interval) {\n let intervalPattern = /^([\\+\\-]*)([\\d]+)(y|M|w|d|h|m|s)/g;\n let momentInterval = intervalPattern.exec(interval);\n let duration = 0;\n\n if (momentInterval[1] === '+') {\n duration = 0 - moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf();\n } else {\n duration = moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf();\n }\n\n return duration;\n}\n\n/**\n * Format acknowledges.\n *\n * @param {array} acknowledges array of Zabbix acknowledge objects\n * @return {string} HTML-formatted table\n */\nexport function formatAcknowledges(acknowledges) {\n if (acknowledges.length) {\n var formatted_acknowledges = '

Acknowledges:
'\n + '';\n _.each(_.map(acknowledges, function (ack) {\n var timestamp = moment.unix(ack.clock);\n return '';\n }), function (ack) {\n formatted_acknowledges = formatted_acknowledges.concat(ack);\n });\n formatted_acknowledges = formatted_acknowledges.concat('
TimeUserComments
' + timestamp.format(\"DD MMM YYYY HH:mm:ss\") + '' + ack.alias\n + ' (' + ack.name + ' ' + ack.surname + ')' + '' + ack.message + '
');\n return formatted_acknowledges;\n } else {\n return '';\n }\n}\n\nexport function convertToZabbixAPIUrl(url) {\n var zabbixAPIUrlPattern = /.*api_jsonrpc.php$/;\n var trimSlashPattern = /(.*?)[\\/]*$/;\n if (url.match(zabbixAPIUrlPattern)) {\n return url;\n } else {\n return url.replace(trimSlashPattern, \"$1\");\n }\n}\n\n/**\n * Wrap function to prevent multiple calls\n * when waiting for result.\n */\nexport function callOnce(func, promiseKeeper) {\n return function() {\n if (!promiseKeeper) {\n promiseKeeper = Promise.resolve(\n func.apply(this, arguments)\n .then(result => {\n promiseKeeper = null;\n return result;\n })\n );\n }\n return promiseKeeper;\n };\n}\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.includes) {\n _.includes = _.contains;\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/utils.js"],"names":["expandItemName","name","key","key_params_str","substring","indexOf","lastIndexOf","key_params","splitKeyParams","i","length","replace","expandItems","items","_","forEach","item","key_","paramStr","params","quoted","in_array","split_symbol","param","symbol","push","containsMacro","itemName","MACRO_PATTERN","test","replaceMacro","macros","item_macros","match","host_macros","filter","m","hostid","macro_def","find","macro","value","macro_value","macro_regex","RegExp","escapeMacro","splitTemplateQuery","query","splitPattern","split","isContainsBraces","result","map","trim","part","bracesPattern","isRegex","str","regexPattern","isTemplateVariable","templateVariables","variablePattern","variables","variable","includes","buildRegex","matches","pattern","flags","undefined","escapeRegex","parseInterval","interval","intervalPattern","momentInterval","exec","moment","duration","Number","valueOf","parseTimeShiftInterval","formatAcknowledges","acknowledges","formatted_acknowledges","each","ack","timestamp","unix","clock","format","alias","surname","message","concat","convertToZabbixAPIUrl","url","zabbixAPIUrlPattern","trimSlashPattern","callOnce","func","promiseKeeper","Promise","resolve","apply","arguments","then","contains"],"mappings":";;;;;;;AAGA;;;;;;;AAOO,WAASA,cAAT,CAAwBC,IAAxB,EAA8BC,GAA9B,EAAmC;;AAExC;AACA;AACA,QAAIC,iBAAiBD,IAAIE,SAAJ,CAAcF,IAAIG,OAAJ,CAAY,GAAZ,IAAmB,CAAjC,EAAoCH,IAAII,WAAJ,CAAgB,GAAhB,CAApC,CAArB;AACA,QAAIC,aAAaC,eAAeL,cAAf,CAAjB;;AAEA;AACA,SAAK,IAAIM,IAAIF,WAAWG,MAAxB,EAAgCD,KAAK,CAArC,EAAwCA,GAAxC,EAA6C;AAC3CR,aAAOA,KAAKU,OAAL,CAAa,MAAMF,CAAnB,EAAsBF,WAAWE,IAAI,CAAf,CAAtB,CAAP;AACD;AACD,WAAOR,IAAP;AACD;;4BAZeD,c;;AAcT,WAASY,WAAT,CAAqBC,KAArB,EAA4B;AACjCC,MAAEC,OAAF,CAAUF,KAAV,EAAiB,gBAAQ;AACvBG,WAAKA,IAAL,GAAYA,KAAKf,IAAjB;AACAe,WAAKf,IAAL,GAAYD,eAAegB,KAAKA,IAApB,EAA0BA,KAAKC,IAA/B,CAAZ;AACA,aAAOD,IAAP;AACD,KAJD;AAKA,WAAOH,KAAP;AACD;yBAPeD,W;;AAShB,WAASJ,cAAT,CAAwBU,QAAxB,EAAkC;AAChC,QAAIC,SAAS,EAAb;AACA,QAAIC,SAAS,KAAb;AACA,QAAIC,WAAW,KAAf;AACA,QAAIC,eAAe,GAAnB;AACA,QAAIC,QAAQ,EAAZ;;AAEAT,MAAEC,OAAF,CAAUG,QAAV,EAAoB,kBAAU;AAC5B,UAAIM,WAAW,GAAX,IAAkBH,QAAtB,EAAgC;AAC9BE,iBAASC,MAAT;AACD,OAFD,MAEO,IAAIA,WAAW,GAAX,IAAkBJ,MAAtB,EAA8B;AACnCA,iBAAS,KAAT;AACD,OA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BAAgBC,QAAQC,OAAR,CACdH,KAAKI,KAAL,CAAW,IAAX,EAAiBC,SAAjB,EACCC,IADD,CACM,kBAAU;AACdL,0BAAgB,IAAhB;AACA,iBAAOjD,MAAP;AACD,SAJD,CADc,CAAhB;AAOD;AACD,aAAOiD,aAAP;AACD,KAXD;AAYD;;AAED;;sBAfgBF,Q;;;;AAtNTpF,O;;AACA8D,Y;;;AA8DDhD,mB,GAAgB,mB;;8BA8DT8B,Y,GAAe,qB;;;;AAyG5B,UAAI,CAAC5C,EAAEkD,QAAP,EAAiB;AACflD,UAAEkD,QAAF,GAAalD,EAAE4F,QAAf;AACD","file":"utils.js","sourcesContent":["import _ from 'lodash';\r\nimport moment from 'moment';\r\n\r\n/**\r\n * Expand Zabbix item name\r\n *\r\n * @param {string} name item name, ie \"CPU $2 time\"\r\n * @param {string} key item key, ie system.cpu.util[,system,avg1]\r\n * @return {string} expanded name, ie \"CPU system time\"\r\n */\r\nexport function expandItemName(name, key) {\r\n\r\n // extract params from key:\r\n // \"system.cpu.util[,system,avg1]\" --> [\"\", \"system\", \"avg1\"]\r\n let key_params_str = key.substring(key.indexOf('[') + 1, key.lastIndexOf(']'));\r\n let key_params = splitKeyParams(key_params_str);\r\n\r\n // replace item parameters\r\n for (let i = key_params.length; i >= 1; i--) {\r\n name = name.replace('$' + i, key_params[i - 1]);\r\n }\r\n return name;\r\n}\r\n\r\nexport function expandItems(items) {\r\n _.forEach(items, item => {\r\n item.item = item.name;\r\n item.name = expandItemName(item.item, item.key_);\r\n return item;\r\n });\r\n return items;\r\n}\r\n\r\nfunction splitKeyParams(paramStr) {\r\n let params = [];\r\n let quoted = false;\r\n let in_array = false;\r\n let split_symbol = ',';\r\n let param = '';\r\n\r\n _.forEach(paramStr, symbol => {\r\n if (symbol === '\"' && in_array) {\r\n param += symbol;\r\n } else if (symbol === '\"' && quoted) {\r\n quoted = false;\r\n } else if (symbol === '\"' && !quoted) {\r\n quoted = true;\r\n } else if (symbol === '[' && !quoted) {\r\n in_array = true;\r\n } else if (symbol === ']' && !quoted) {\r\n in_array = false;\r\n } else if (symbol === split_symbol && !quoted && !in_array) {\r\n params.push(param);\r\n param = '';\r\n } else {\r\n param += symbol;\r\n }\r\n });\r\n\r\n params.push(param);\r\n return params;\r\n}\r\n\r\nconst MACRO_PATTERN = /{\\$[A-Z0-9_\\.]+}/g;\r\n\r\nexport function containsMacro(itemName) {\r\n return MACRO_PATTERN.test(itemName);\r\n}\r\n\r\nexport function replaceMacro(item, macros) {\r\n let itemName = item.name;\r\n let item_macros = itemName.match(MACRO_PATTERN);\r\n _.forEach(item_macros, macro => {\r\n let host_macros = _.filter(macros, m => {\r\n if (m.hostid) {\r\n return m.hostid === item.hostid;\r\n } else {\r\n // Add global macros\r\n return true;\r\n }\r\n });\r\n\r\n let macro_def = _.find(host_macros, { macro: macro });\r\n if (macro_def && macro_def.value) {\r\n let macro_value = macro_def.value;\r\n let macro_regex = new RegExp(escapeMacro(macro));\r\n itemName = itemName.replace(macro_regex, macro_value);\r\n }\r\n });\r\n\r\n return itemName;\r\n}\r\n\r\nfunction escapeMacro(macro) {\r\n macro = macro.replace(/\\$/, '\\\\\\$');\r\n return macro;\r\n}\r\n\r\n/**\r\n * Split template query to parts of zabbix entities\r\n * group.host.app.item -> [group, host, app, item]\r\n * {group}{host.com} -> [group, host.com]\r\n */\r\nexport function splitTemplateQuery(query) {\r\n let splitPattern = /\\{[^\\{\\}]*\\}|\\{\\/.*\\/\\}/g;\r\n let split;\r\n\r\n if (isContainsBraces(query)) {\r\n let result = query.match(splitPattern);\r\n split = _.map(result, part => {\r\n return _.trim(part, '{}');\r\n });\r\n } else {\r\n split = query.split('.');\r\n }\r\n\r\n return split;\r\n}\r\n\r\nfunction isContainsBraces(query) {\r\n let bracesPattern = /^\\{.+\\}$/;\r\n return bracesPattern.test(query);\r\n}\r\n\r\n// Pattern for testing regex\r\nexport const regexPattern = /^\\/(.*)\\/([gmi]*)$/m;\r\n\r\nexport function isRegex(str) {\r\n return regexPattern.test(str);\r\n}\r\n\r\nexport function isTemplateVariable(str, templateVariables) {\r\n var variablePattern = /^\\$\\w+/;\r\n if (variablePattern.test(str)) {\r\n var variables = _.map(templateVariables, variable => {\r\n return '$' + variable.name;\r\n });\r\n return _.includes(variables, str);\r\n } else {\r\n return false;\r\n }\r\n}\r\n\r\nexport function buildRegex(str) {\r\n var matches = str.match(regexPattern);\r\n var pattern = matches[1];\r\n var flags = matches[2] !== \"\" ? matches[2] : undefined;\r\n return new RegExp(pattern, flags);\r\n}\r\n\r\n// Need for template variables replace\r\n// From Grafana's templateSrv.js\r\nexport function escapeRegex(value) {\r\n return value.replace(/[\\\\^$*+?.()|[\\]{}\\/]/g, '\\\\$&');\r\n}\r\n\r\nexport function parseInterval(interval) {\r\n var intervalPattern = /(^[\\d]+)(y|M|w|d|h|m|s)/g;\r\n var momentInterval = intervalPattern.exec(interval);\r\n return moment.duration(Number(momentInterval[1]), momentInterval[2]).valueOf();\r\n}\r\n\r\nexport function parseTimeShiftInterval(interval) {\r\n let intervalPattern = /^([\\+\\-]*)([\\d]+)(y|M|w|d|h|m|s)/g;\r\n let momentInterval = intervalPattern.exec(interval);\r\n let duration = 0;\r\n\r\n if (momentInterval[1] === '+') {\r\n duration = 0 - moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf();\r\n } else {\r\n duration = moment.duration(Number(momentInterval[2]), momentInterval[3]).valueOf();\r\n }\r\n\r\n return duration;\r\n}\r\n\r\n/**\r\n * Format acknowledges.\r\n *\r\n * @param {array} acknowledges array of Zabbix acknowledge objects\r\n * @return {string} HTML-formatted table\r\n */\r\nexport function formatAcknowledges(acknowledges) {\r\n if (acknowledges.length) {\r\n var formatted_acknowledges = '

Acknowledges:
'\r\n + '';\r\n _.each(_.map(acknowledges, function (ack) {\r\n var timestamp = moment.unix(ack.clock);\r\n return '';\r\n }), function (ack) {\r\n formatted_acknowledges = formatted_acknowledges.concat(ack);\r\n });\r\n formatted_acknowledges = formatted_acknowledges.concat('
TimeUserComments
' + timestamp.format(\"DD MMM YYYY HH:mm:ss\") + '' + ack.alias\r\n + ' (' + ack.name + ' ' + ack.surname + ')' + '' + ack.message + '
');\r\n return formatted_acknowledges;\r\n } else {\r\n return '';\r\n }\r\n}\r\n\r\nexport function convertToZabbixAPIUrl(url) {\r\n var zabbixAPIUrlPattern = /.*api_jsonrpc.php$/;\r\n var trimSlashPattern = /(.*?)[\\/]*$/;\r\n if (url.match(zabbixAPIUrlPattern)) {\r\n return url;\r\n } else {\r\n return url.replace(trimSlashPattern, \"$1\");\r\n }\r\n}\r\n\r\n/**\r\n * Wrap function to prevent multiple calls\r\n * when waiting for result.\r\n */\r\nexport function callOnce(func, promiseKeeper) {\r\n return function() {\r\n if (!promiseKeeper) {\r\n promiseKeeper = Promise.resolve(\r\n func.apply(this, arguments)\r\n .then(result => {\r\n promiseKeeper = null;\r\n return result;\r\n })\r\n );\r\n }\r\n return promiseKeeper;\r\n };\r\n}\r\n\r\n// Fix for backward compatibility with lodash 2.4\r\nif (!_.includes) {\r\n _.includes = _.contains;\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbix.js b/dist/datasource-zabbix/zabbix.js index 2c4a17888..1b64b9f6d 100644 --- a/dist/datasource-zabbix/zabbix.js +++ b/dist/datasource-zabbix/zabbix.js @@ -251,11 +251,11 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za /////////////////////////////////////////////////////////////////////////////// - /** - * Find group, host, app or item by given name. - * @param list list of groups, apps or other - * @param name visible name - * @return array with finded element or empty array + /** + * Find group, host, app or item by given name. + * @param list list of groups, apps or other + * @param name visible name + * @return array with finded element or empty array */ function findByName(list, name) { var finded = _.find(list, { 'name': name }); @@ -266,13 +266,13 @@ System.register(['angular', 'lodash', './utils', './zabbixAPI.service.js', './za } } - /** - * Different hosts can contains applications and items with same name. - * For this reason use _.filter, which return all elements instead _.find, - * which return only first finded. - * @param {[type]} list list of elements - * @param {[type]} name app name - * @return {[type]} array with finded element or empty array + /** + * Different hosts can contains applications and items with same name. + * For this reason use _.filter, which return all elements instead _.find, + * which return only first finded. + * @param {[type]} list list of elements + * @param {[type]} name app name + * @return {[type]} array with finded element or empty array */ function filterByName(list, name) { var finded = _.filter(list, { 'name': name }); diff --git a/dist/datasource-zabbix/zabbix.js.map b/dist/datasource-zabbix/zabbix.js.map index f21cf83cd..9a23c9c2a 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","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,YAEt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,EAA6BlD,MAA7B,EAAqC;AACnC,QAAI8B,MAAM8B,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,WAAS4B,UAAT,CAAoBF,KAApB,EAA2B;AACzB,QAAImC,UAAUhE,EAAEC,GAAF,CAAM4B,KAAN,EAAa,gBAAQ;AACjC,aAAO7B,EAAEC,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 +{"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,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EAAEC,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';\r\nimport _ from 'lodash';\r\nimport * as utils from './utils';\r\nimport './zabbixAPI.service.js';\r\nimport './zabbixCachingProxy.service.js';\r\nimport './zabbixDBConnector';\r\n\r\n// Use factory() instead service() for multiple data sources support.\r\n// Each Zabbix data source instance should initialize its own API instance.\r\n\r\n/** @ngInject */\r\nfunction ZabbixFactory(zabbixAPIService, ZabbixCachingProxy, ZabbixDBConnector) {\r\n\r\n class Zabbix {\r\n constructor(url, options) {\r\n let {\r\n username, password, basicAuth, withCredentials, cacheTTL,\r\n enableDirectDBConnection, sqlDatasourceId\r\n } = options;\r\n\r\n // Initialize Zabbix API\r\n var ZabbixAPI = zabbixAPIService;\r\n this.zabbixAPI = new ZabbixAPI(url, username, password, basicAuth, withCredentials);\r\n\r\n if (enableDirectDBConnection) {\r\n this.dbConnector = new ZabbixDBConnector(sqlDatasourceId);\r\n }\r\n\r\n // Initialize caching proxy for requests\r\n let cacheOptions = {\r\n enabled: true,\r\n ttl: cacheTTL\r\n };\r\n this.cachingProxy = new ZabbixCachingProxy(this.zabbixAPI, this.dbConnector, cacheOptions);\r\n\r\n // Proxy methods\r\n this.getHistory = this.cachingProxy.getHistory.bind(this.cachingProxy);\r\n this.getMacros = this.cachingProxy.getMacros.bind(this.cachingProxy);\r\n this.getItemsByIDs = this.cachingProxy.getItemsByIDs.bind(this.cachingProxy);\r\n\r\n if (enableDirectDBConnection) {\r\n this.getHistoryDB = this.cachingProxy.getHistoryDB.bind(this.cachingProxy);\r\n this.getTrendsDB = this.cachingProxy.getTrendsDB.bind(this.cachingProxy);\r\n }\r\n\r\n this.getTrend = this.zabbixAPI.getTrend.bind(this.zabbixAPI);\r\n this.getEvents = this.zabbixAPI.getEvents.bind(this.zabbixAPI);\r\n this.getAlerts = this.zabbixAPI.getAlerts.bind(this.zabbixAPI);\r\n this.getHostAlerts = this.zabbixAPI.getHostAlerts.bind(this.zabbixAPI);\r\n this.getAcknowledges = this.zabbixAPI.getAcknowledges.bind(this.zabbixAPI);\r\n this.getITService = this.zabbixAPI.getITService.bind(this.zabbixAPI);\r\n this.getSLA = this.zabbixAPI.getSLA.bind(this.zabbixAPI);\r\n this.getVersion = this.zabbixAPI.getVersion.bind(this.zabbixAPI);\r\n this.login = this.zabbixAPI.login.bind(this.zabbixAPI);\r\n }\r\n\r\n getItemsFromTarget(target, options) {\r\n let parts = ['group', 'host', 'application', 'item'];\r\n let filters = _.map(parts, p => target[p].filter);\r\n return this.getItems(...filters, options);\r\n }\r\n\r\n getHostsFromTarget(target) {\r\n let parts = ['group', 'host', 'application'];\r\n let filters = _.map(parts, p => target[p].filter);\r\n return Promise.all([\r\n this.getHosts(...filters),\r\n this.getApps(...filters),\r\n ]).then((results) => {\r\n let [hosts, apps] = results;\r\n if (apps.appFilterEmpty) {\r\n apps = [];\r\n }\r\n return [hosts, apps];\r\n });\r\n }\r\n\r\n getAllGroups() {\r\n return this.cachingProxy.getGroups();\r\n }\r\n\r\n getGroups(groupFilter) {\r\n return this.getAllGroups()\r\n .then(groups => findByFilter(groups, groupFilter));\r\n }\r\n\r\n /**\r\n * Get list of host belonging to given groups.\r\n */\r\n getAllHosts(groupFilter) {\r\n return this.getGroups(groupFilter)\r\n .then(groups => {\r\n let groupids = _.map(groups, 'groupid');\r\n return this.cachingProxy.getHosts(groupids);\r\n });\r\n }\r\n\r\n getHosts(groupFilter, hostFilter) {\r\n return this.getAllHosts(groupFilter)\r\n .then(hosts => findByFilter(hosts, hostFilter));\r\n }\r\n\r\n /**\r\n * Get list of applications belonging to given groups and hosts.\r\n */\r\n getAllApps(groupFilter, hostFilter) {\r\n return this.getHosts(groupFilter, hostFilter)\r\n .then(hosts => {\r\n let hostids = _.map(hosts, 'hostid');\r\n return this.cachingProxy.getApps(hostids);\r\n });\r\n }\r\n\r\n getApps(groupFilter, hostFilter, appFilter) {\r\n return this.getHosts(groupFilter, hostFilter)\r\n .then(hosts => {\r\n let hostids = _.map(hosts, 'hostid');\r\n if (appFilter) {\r\n return this.cachingProxy.getApps(hostids)\r\n .then(apps => filterByQuery(apps, appFilter));\r\n } else {\r\n return {\r\n appFilterEmpty: true,\r\n hostids: hostids\r\n };\r\n }\r\n });\r\n }\r\n\r\n getAllItems(groupFilter, hostFilter, appFilter, options = {}) {\r\n return this.getApps(groupFilter, hostFilter, appFilter)\r\n .then(apps => {\r\n if (apps.appFilterEmpty) {\r\n return this.cachingProxy.getItems(apps.hostids, undefined, options.itemtype);\r\n } else {\r\n let appids = _.map(apps, 'applicationid');\r\n return this.cachingProxy.getItems(undefined, appids, options.itemtype);\r\n }\r\n })\r\n .then(items => {\r\n if (!options.showDisabledItems) {\r\n items = _.filter(items, {'status': '0'});\r\n }\r\n\r\n return items;\r\n })\r\n .then(this.expandUserMacro.bind(this));\r\n }\r\n\r\n expandUserMacro(items) {\r\n let hostids = getHostIds(items);\r\n return this.getMacros(hostids)\r\n .then(macros => {\r\n _.forEach(items, item => {\r\n if (utils.containsMacro(item.name)) {\r\n item.name = utils.replaceMacro(item, macros);\r\n }\r\n });\r\n return items;\r\n });\r\n }\r\n\r\n getItems(groupFilter, hostFilter, appFilter, itemFilter, options = {}) {\r\n return this.getAllItems(groupFilter, hostFilter, appFilter, options)\r\n .then(items => filterByQuery(items, itemFilter));\r\n }\r\n\r\n getITServices(itServiceFilter) {\r\n return this.cachingProxy.getITServices()\r\n .then(itServices => findByFilter(itServices, itServiceFilter));\r\n }\r\n\r\n /**\r\n * Build query - convert target filters to array of Zabbix items\r\n */\r\n getTriggers(groupFilter, hostFilter, appFilter, options) {\r\n let promises = [\r\n this.getGroups(groupFilter),\r\n this.getHosts(groupFilter, hostFilter),\r\n this.getApps(groupFilter, hostFilter, appFilter)\r\n ];\r\n\r\n return Promise.all(promises)\r\n .then(results => {\r\n let filteredGroups = results[0];\r\n let filteredHosts = results[1];\r\n let filteredApps = results[2];\r\n let query = {};\r\n\r\n if (appFilter) {\r\n query.applicationids = _.flatten(_.map(filteredApps, 'applicationid'));\r\n }\r\n if (hostFilter) {\r\n query.hostids = _.map(filteredHosts, 'hostid');\r\n }\r\n if (groupFilter) {\r\n query.groupids = _.map(filteredGroups, 'groupid');\r\n }\r\n\r\n return query;\r\n }).then(query => {\r\n return this.zabbixAPI.getTriggers(query.groupids, query.hostids, query.applicationids, options);\r\n });\r\n }\r\n }\r\n\r\n return Zabbix;\r\n}\r\n\r\nangular\r\n .module('grafana.services')\r\n .factory('Zabbix', ZabbixFactory);\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n/**\r\n * Find group, host, app or item by given name.\r\n * @param list list of groups, apps or other\r\n * @param name visible name\r\n * @return array with finded element or empty array\r\n */\r\nfunction findByName(list, name) {\r\n var finded = _.find(list, {'name': name});\r\n if (finded) {\r\n return [finded];\r\n } else {\r\n return [];\r\n }\r\n}\r\n\r\n/**\r\n * Different hosts can contains applications and items with same name.\r\n * For this reason use _.filter, which return all elements instead _.find,\r\n * which return only first finded.\r\n * @param {[type]} list list of elements\r\n * @param {[type]} name app name\r\n * @return {[type]} array with finded element or empty array\r\n */\r\nfunction filterByName(list, name) {\r\n var finded = _.filter(list, {'name': name});\r\n if (finded) {\r\n return finded;\r\n } else {\r\n return [];\r\n }\r\n}\r\n\r\nfunction filterByRegex(list, regex) {\r\n var filterPattern = utils.buildRegex(regex);\r\n return _.filter(list, function (zbx_obj) {\r\n return filterPattern.test(zbx_obj.name);\r\n });\r\n}\r\n\r\nfunction findByFilter(list, filter) {\r\n if (utils.isRegex(filter)) {\r\n return filterByRegex(list, filter);\r\n } else {\r\n return findByName(list, filter);\r\n }\r\n}\r\n\r\nfunction filterByQuery(list, filter) {\r\n if (utils.isRegex(filter)) {\r\n return filterByRegex(list, filter);\r\n } else {\r\n return filterByName(list, filter);\r\n }\r\n}\r\n\r\nfunction getHostIds(items) {\r\n let hostIds = _.map(items, item => {\r\n return _.map(item.hosts, 'hostid');\r\n });\r\n return _.uniq(_.flatten(hostIds));\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbixAPI.service.js.map b/dist/datasource-zabbix/zabbixAPI.service.js.map index 70fa475b8..43431a9a6 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","maintenance","expandDescription","expandData","expandComment","monitored","skipDependent","value","selectGroups","selectItems","selectLastEvent","selectTags","lastChangeSince","lastChangeTill","objectids","showEvents","select_acknowledges","preservekeys","events","event","acknowledges","minSeverity","acknowledged","count","min_severity","countOutput","triggers","filterTriggersByAcknowledge","trigger","lastEvent","angular","module","factory"],"mappings":";;;;;;;;;;;;;AAKA;AACA,WAASA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,KAFD,MAEO,IAAIA,iBAAiB,CAArB,EAAwB;AAC7B,aAAOzC,EAAEf,MAAF,CAAS4D,QAAT,EAAmB,UAACE,OAAD;AAAA,eAAaA,QAAQC,SAAR,CAAkBP,YAAlB,KAAmC,GAAhD;AAAA,OAAnB,CAAP;AACD,KAFM,MAEA;AACL,aAAOI,QAAP;AACD;AACF;;AAED,WAASpF,eAAT,CAAyBK,OAAzB,EAAkC;AAChC,WACEA,YAAY,uCAAZ,IACAA,YAAY,iBADZ,IAEAA,YAAY,iBAHd;AAKD;;;;AAnfMmF,a;;AACAjD,O;;AACKX,W;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmfZ4D,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,kBAFX,EAE+BhH,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, maintenance, 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', 'maintenance_status'],\n selectItems: ['name', 'key_', 'lastvalue'],\n selectLastEvent: 'extend',\n selectTags: 'extend'\n };\n\n if (showTriggers) {\n params.filter.value = showTriggers;\n }\n\n if (maintenance) {\n params.maintenance = true;\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, options) {\n let {minSeverity, acknowledged, count, timeFrom, timeTo} = options;\n let 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 selectGroups: 'extend',\n selectHosts: ['host', 'name']\n };\n\n if (count && acknowledged !== 0 && acknowledged !== 1) {\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 .then((triggers) => {\n if (!count || acknowledged === 0 || acknowledged === 1) {\n triggers = filterTriggersByAcknowledge(triggers, acknowledged);\n if (count) {\n triggers = triggers.length;\n }\n }\n return triggers;\n });\n }\n }\n\n return ZabbixAPI;\n}\n\nfunction filterTriggersByAcknowledge(triggers, acknowledged) {\n if (acknowledged === 0) {\n return _.filter(triggers, (trigger) => trigger.lastEvent.acknowledged === \"0\");\n } else if (acknowledged === 1) {\n return _.filter(triggers, (trigger) => trigger.lastEvent.acknowledged === \"1\");\n } else {\n return triggers;\n }\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","maintenance","expandDescription","expandData","expandComment","monitored","skipDependent","value","selectGroups","selectItems","selectLastEvent","selectTags","lastChangeSince","lastChangeTill","objectids","showEvents","select_acknowledges","preservekeys","events","event","acknowledges","minSeverity","acknowledged","count","min_severity","countOutput","triggers","filterTriggersByAcknowledge","trigger","lastEvent","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,e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AAmC,GAAhD;AAAA,OAAnB,CAAP;AACD,KAFM,MAEA;AACL,aAAOI,QAAP;AACD;AACF;;AAED,WAASpF,eAAT,CAAyBK,OAAzB,EAAkC;AAChC,WACEA,YAAY,uCAAZ,IACAA,YAAY,iBADZ,IAEAA,YAAY,iBAHd;AAKD;;;;AAnfMmF,a;;AACAjD,O;;AACKX,W;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmfZ4D,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,kBAFX,EAE+BhH,uBAF/B","file":"zabbixAPI.service.js","sourcesContent":["import angular from 'angular';\r\nimport _ from 'lodash';\r\nimport * as utils from './utils';\r\nimport './zabbixAPICore.service';\r\n\r\n/** @ngInject */\r\nfunction ZabbixAPIServiceFactory(alertSrv, zabbixAPICoreService) {\r\n\r\n /**\r\n * Zabbix API Wrapper.\r\n * Creates Zabbix API instance with given parameters (url, credentials and other).\r\n * Wraps API calls and provides high-level methods.\r\n */\r\n class ZabbixAPI {\r\n\r\n constructor(api_url, username, password, basicAuth, withCredentials) {\r\n this.url = api_url;\r\n this.username = username;\r\n this.password = password;\r\n this.auth = \"\";\r\n\r\n this.requestOptions = {\r\n basicAuth: basicAuth,\r\n withCredentials: withCredentials\r\n };\r\n\r\n this.loginPromise = null;\r\n this.loginErrorCount = 0;\r\n this.maxLoginAttempts = 3;\r\n\r\n this.alertSrv = alertSrv;\r\n this.zabbixAPICore = zabbixAPICoreService;\r\n\r\n this.getTrend = this.getTrend_ZBXNEXT1193;\r\n //getTrend = getTrend_30;\r\n }\r\n\r\n //////////////////////////\r\n // Core method wrappers //\r\n //////////////////////////\r\n\r\n request(method, params) {\r\n return this.zabbixAPICore.request(this.url, method, params, this.requestOptions, this.auth)\r\n .catch(error => {\r\n if (isNotAuthorized(error.data)) {\r\n // Handle auth errors\r\n this.loginErrorCount++;\r\n if (this.loginErrorCount > this.maxLoginAttempts) {\r\n this.loginErrorCount = 0;\r\n return null;\r\n } else {\r\n return this.loginOnce()\r\n .then(() => this.request(method, params));\r\n }\r\n } else {\r\n // Handle API errors\r\n let message = error.data ? error.data : error.statusText;\r\n this.alertAPIError(message);\r\n }\r\n });\r\n }\r\n\r\n alertAPIError(message, timeout = 5000) {\r\n this.alertSrv.set(\r\n \"Zabbix API Error\",\r\n message,\r\n 'error',\r\n timeout\r\n );\r\n }\r\n\r\n /**\r\n * When API unauthenticated or auth token expired each request produce login()\r\n * call. But auth token is common to all requests. This function wraps login() method\r\n * and call it once. If login() already called just wait for it (return its promise).\r\n * @return login promise\r\n */\r\n loginOnce() {\r\n if (!this.loginPromise) {\r\n this.loginPromise = Promise.resolve(\r\n this.login().then(auth => {\r\n this.auth = auth;\r\n this.loginPromise = null;\r\n return auth;\r\n })\r\n );\r\n }\r\n return this.loginPromise;\r\n }\r\n\r\n /**\r\n * Get authentication token.\r\n */\r\n login() {\r\n return this.zabbixAPICore.login(this.url, this.username, this.password, this.requestOptions);\r\n }\r\n\r\n /**\r\n * Get Zabbix API version\r\n */\r\n getVersion() {\r\n return this.zabbixAPICore.getVersion(this.url, this.requestOptions);\r\n }\r\n\r\n ////////////////////////////////\r\n // Zabbix API method wrappers //\r\n ////////////////////////////////\r\n\r\n acknowledgeEvent(eventid, message) {\r\n var params = {\r\n eventids: eventid,\r\n message: message\r\n };\r\n\r\n return this.request('event.acknowledge', params);\r\n }\r\n\r\n getGroups() {\r\n var params = {\r\n output: ['name'],\r\n sortfield: 'name',\r\n real_hosts: true\r\n };\r\n\r\n return this.request('hostgroup.get', params);\r\n }\r\n\r\n getHosts(groupids) {\r\n var params = {\r\n output: ['name', 'host'],\r\n sortfield: 'name'\r\n };\r\n if (groupids) {\r\n params.groupids = groupids;\r\n }\r\n\r\n return this.request('host.get', params);\r\n }\r\n\r\n getApps(hostids) {\r\n var params = {\r\n output: 'extend',\r\n hostids: hostids\r\n };\r\n\r\n return this.request('application.get', params);\r\n }\r\n\r\n /**\r\n * Get Zabbix items\r\n * @param {[type]} hostids host ids\r\n * @param {[type]} appids application ids\r\n * @param {String} itemtype 'num' or 'text'\r\n * @return {[type]} array of items\r\n */\r\n getItems(hostids, appids, itemtype) {\r\n var params = {\r\n output: [\r\n 'name', 'key_',\r\n 'value_type',\r\n 'hostid',\r\n 'status',\r\n 'state'\r\n ],\r\n sortfield: 'name',\r\n webitems: true,\r\n filter: {},\r\n selectHosts: ['hostid', 'name']\r\n };\r\n if (hostids) {\r\n params.hostids = hostids;\r\n }\r\n if (appids) {\r\n params.applicationids = appids;\r\n }\r\n if (itemtype === 'num') {\r\n // Return only numeric metrics\r\n params.filter.value_type = [0, 3];\r\n }\r\n if (itemtype === 'text') {\r\n // Return only text metrics\r\n params.filter.value_type = [1, 2, 4];\r\n }\r\n\r\n return this.request('item.get', params)\r\n .then(utils.expandItems);\r\n }\r\n\r\n getItemsByIDs(itemids) {\r\n var params = {\r\n itemids: itemids,\r\n output: [\r\n 'name', 'key_',\r\n 'value_type',\r\n 'hostid',\r\n 'status',\r\n 'state'\r\n ],\r\n webitems: true,\r\n selectHosts: ['hostid', 'name']\r\n };\r\n\r\n return this.request('item.get', params)\r\n .then(utils.expandItems);\r\n }\r\n\r\n getMacros(hostids) {\r\n var params = {\r\n output: 'extend',\r\n hostids: hostids\r\n };\r\n\r\n return this.request('usermacro.get', params);\r\n }\r\n\r\n getGlobalMacros() {\r\n var params = {\r\n output: 'extend',\r\n globalmacro: true\r\n };\r\n\r\n return this.request('usermacro.get', params);\r\n }\r\n\r\n getLastValue(itemid) {\r\n var params = {\r\n output: ['lastvalue'],\r\n itemids: itemid\r\n };\r\n return this.request('item.get', params)\r\n .then(items => items.length ? items[0].lastvalue : null);\r\n }\r\n\r\n /**\r\n * Perform history query from Zabbix API\r\n *\r\n * @param {Array} items Array of Zabbix item objects\r\n * @param {Number} timeFrom Time in seconds\r\n * @param {Number} timeTill Time in seconds\r\n * @return {Array} Array of Zabbix history objects\r\n */\r\n getHistory(items, timeFrom, timeTill) {\r\n\r\n // Group items by value type and perform request for each value type\r\n let grouped_items = _.groupBy(items, 'value_type');\r\n let promises = _.map(grouped_items, (items, value_type) => {\r\n let itemids = _.map(items, 'itemid');\r\n let params = {\r\n output: 'extend',\r\n history: value_type,\r\n itemids: itemids,\r\n sortfield: 'clock',\r\n sortorder: 'ASC',\r\n time_from: timeFrom\r\n };\r\n\r\n // Relative queries (e.g. last hour) don't include an end time\r\n if (timeTill) {\r\n params.time_till = timeTill;\r\n }\r\n\r\n return this.request('history.get', params);\r\n });\r\n\r\n return Promise.all(promises).then(_.flatten);\r\n }\r\n\r\n /**\r\n * Perform trends query from Zabbix API\r\n * Use trends api extension from ZBXNEXT-1193 patch.\r\n *\r\n * @param {Array} items Array of Zabbix item objects\r\n * @param {Number} time_from Time in seconds\r\n * @param {Number} time_till Time in seconds\r\n * @return {Array} Array of Zabbix trend objects\r\n */\r\n getTrend_ZBXNEXT1193(items, timeFrom, timeTill) {\r\n\r\n // Group items by value type and perform request for each value type\r\n let grouped_items = _.groupBy(items, 'value_type');\r\n let promises = _.map(grouped_items, (items, value_type) => {\r\n let itemids = _.map(items, 'itemid');\r\n let params = {\r\n output: 'extend',\r\n trend: value_type,\r\n itemids: itemids,\r\n sortfield: 'clock',\r\n sortorder: 'ASC',\r\n time_from: timeFrom\r\n };\r\n\r\n // Relative queries (e.g. last hour) don't include an end time\r\n if (timeTill) {\r\n params.time_till = timeTill;\r\n }\r\n\r\n return this.request('trend.get', params);\r\n });\r\n\r\n return Promise.all(promises).then(_.flatten);\r\n }\r\n\r\n getTrend_30(items, time_from, time_till, value_type) {\r\n var self = this;\r\n var itemids = _.map(items, 'itemid');\r\n\r\n var params = {\r\n output: [\"itemid\",\r\n \"clock\",\r\n value_type\r\n ],\r\n itemids: itemids,\r\n time_from: time_from\r\n };\r\n\r\n // Relative queries (e.g. last hour) don't include an end time\r\n if (time_till) {\r\n params.time_till = time_till;\r\n }\r\n\r\n return self.request('trend.get', params);\r\n }\r\n\r\n getITService(serviceids) {\r\n var params = {\r\n output: 'extend',\r\n serviceids: serviceids\r\n };\r\n return this.request('service.get', params);\r\n }\r\n\r\n getSLA(serviceids, timeRange) {\r\n let [timeFrom, timeTo] = timeRange;\r\n var params = {\r\n serviceids: serviceids,\r\n intervals: [{\r\n from: timeFrom,\r\n to: timeTo\r\n }]\r\n };\r\n return this.request('service.getsla', params);\r\n }\r\n\r\n getTriggers(groupids, hostids, applicationids, options) {\r\n let {showTriggers, maintenance, timeFrom, timeTo} = options;\r\n\r\n let params = {\r\n output: 'extend',\r\n groupids: groupids,\r\n hostids: hostids,\r\n applicationids: applicationids,\r\n expandDescription: true,\r\n expandData: true,\r\n expandComment: true,\r\n monitored: true,\r\n skipDependent: true,\r\n //only_true: true,\r\n filter: {\r\n value: 1\r\n },\r\n selectGroups: ['name'],\r\n selectHosts: ['name', 'host', 'maintenance_status'],\r\n selectItems: ['name', 'key_', 'lastvalue'],\r\n selectLastEvent: 'extend',\r\n selectTags: 'extend'\r\n };\r\n\r\n if (showTriggers) {\r\n params.filter.value = showTriggers;\r\n }\r\n\r\n if (maintenance) {\r\n params.maintenance = true;\r\n }\r\n\r\n if (timeFrom || timeTo) {\r\n params.lastChangeSince = timeFrom;\r\n params.lastChangeTill = timeTo;\r\n }\r\n\r\n return this.request('trigger.get', params);\r\n }\r\n\r\n getEvents(objectids, timeFrom, timeTo, showEvents) {\r\n var params = {\r\n output: 'extend',\r\n time_from: timeFrom,\r\n time_till: timeTo,\r\n objectids: objectids,\r\n select_acknowledges: 'extend',\r\n selectHosts: 'extend',\r\n value: showEvents\r\n };\r\n\r\n return this.request('event.get', params);\r\n }\r\n\r\n getAcknowledges(eventids) {\r\n var params = {\r\n output: 'extend',\r\n eventids: eventids,\r\n preservekeys: true,\r\n select_acknowledges: 'extend',\r\n sortfield: 'clock',\r\n sortorder: 'DESC'\r\n };\r\n\r\n return this.request('event.get', params)\r\n .then(events => {\r\n return _.filter(events, (event) => event.acknowledges.length);\r\n });\r\n }\r\n\r\n getAlerts(itemids, timeFrom, timeTo) {\r\n var params = {\r\n output: 'extend',\r\n itemids: itemids,\r\n expandDescription: true,\r\n expandData: true,\r\n expandComment: true,\r\n monitored: true,\r\n skipDependent: true,\r\n //only_true: true,\r\n // filter: {\r\n // value: 1\r\n // },\r\n selectLastEvent: 'extend'\r\n };\r\n\r\n if (timeFrom || timeTo) {\r\n params.lastChangeSince = timeFrom;\r\n params.lastChangeTill = timeTo;\r\n }\r\n\r\n return this.request('trigger.get', params);\r\n }\r\n\r\n getHostAlerts(hostids, applicationids, options) {\r\n let {minSeverity, acknowledged, count, timeFrom, timeTo} = options;\r\n let params = {\r\n output: 'extend',\r\n hostids: hostids,\r\n min_severity: minSeverity,\r\n filter: { value: 1 },\r\n expandDescription: true,\r\n expandData: true,\r\n expandComment: true,\r\n monitored: true,\r\n skipDependent: true,\r\n selectLastEvent: 'extend',\r\n selectGroups: 'extend',\r\n selectHosts: ['host', 'name']\r\n };\r\n\r\n if (count && acknowledged !== 0 && acknowledged !== 1) {\r\n params.countOutput = true;\r\n }\r\n\r\n if (applicationids && applicationids.length) {\r\n params.applicationids = applicationids;\r\n }\r\n\r\n if (timeFrom || timeTo) {\r\n params.lastChangeSince = timeFrom;\r\n params.lastChangeTill = timeTo;\r\n }\r\n\r\n return this.request('trigger.get', params)\r\n .then((triggers) => {\r\n if (!count || acknowledged === 0 || acknowledged === 1) {\r\n triggers = filterTriggersByAcknowledge(triggers, acknowledged);\r\n if (count) {\r\n triggers = triggers.length;\r\n }\r\n }\r\n return triggers;\r\n });\r\n }\r\n }\r\n\r\n return ZabbixAPI;\r\n}\r\n\r\nfunction filterTriggersByAcknowledge(triggers, acknowledged) {\r\n if (acknowledged === 0) {\r\n return _.filter(triggers, (trigger) => trigger.lastEvent.acknowledged === \"0\");\r\n } else if (acknowledged === 1) {\r\n return _.filter(triggers, (trigger) => trigger.lastEvent.acknowledged === \"1\");\r\n } else {\r\n return triggers;\r\n }\r\n}\r\n\r\nfunction isNotAuthorized(message) {\r\n return (\r\n message === \"Session terminated, re-login, please.\" ||\r\n message === \"Not authorised.\" ||\r\n message === \"Not authorized.\"\r\n );\r\n}\r\n\r\nangular\r\n .module('grafana.services')\r\n .factory('zabbixAPIService', ZabbixAPIServiceFactory);\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbixAPICore.service.js b/dist/datasource-zabbix/zabbixAPICore.service.js index fef6be4b3..01d7a7a95 100644 --- a/dist/datasource-zabbix/zabbixAPICore.service.js +++ b/dist/datasource-zabbix/zabbixAPICore.service.js @@ -43,9 +43,9 @@ System.register(['angular'], function (_export, _context) { this.backendSrv = backendSrv; } - /** - * Request data from Zabbix API - * @return {object} response.result + /** + * Request data from Zabbix API + * @return {object} response.result */ diff --git a/dist/datasource-zabbix/zabbixAPICore.service.js.map b/dist/datasource-zabbix/zabbixAPICore.service.js.map index 7316ea11c..aa1b4587c 100644 --- a/dist/datasource-zabbix/zabbixAPICore.service.js.map +++ b/dist/datasource-zabbix/zabbixAPICore.service.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/zabbixAPICore.service.js"],"names":["angular","ZabbixAPICoreService","backendSrv","api_url","method","params","options","auth","requestData","jsonrpc","id","Promise","reject","ZabbixAPIError","data","requestOptions","url","headers","basicAuth","withCredentials","Authorization","datasourceRequest","then","response","error","result","username","password","user","request","code","name","message","module","service"],"mappings":";;;;;;;;;;;;;;;AAIOA,a;;;;;;;;;;;;;;;;;;;;;AAEDC,0B;;AAEJ;AACA,sCAAYC,UAAZ,EAAwB;AAAA;;AACtB,eAAKA,UAAL,GAAkBA,UAAlB;AACD;;AAED;;;;;;;;kCAIQC,O,EAASC,M,EAAQC,M,EAAQC,O,EAASC,I,EAAM;AAC9C,gBAAIC,cAAc;AAChBC,uBAAS,KADO;AAEhBL,sBAAQA,MAFQ;AAGhBC,sBAAQA,MAHQ;AAIhBK,kBAAI;AAJY,aAAlB;;AAOA,gBAAIH,SAAS,EAAb,EAAiB;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,EAAoCE,MAApC,EAA4CC,OAA5C,EAAqD,IAArD,CAAP;AACD;;;qCAMUH,O,EAASG,O,EAAS;AAC3B,mBAAO,KAAKuB,OAAL,CAAa1B,OAAb,EAAsB,iBAAtB,EAAyC,EAAzC,EAA6CG,OAA7C,CAAP;AACD;;;;;;gCAIUO,c;AACX,gCAAYW,KAAZ,EAAmB;AAAA;;AACjB,eAAKM,IAAL,GAAYN,MAAMM,IAAN,IAAc,IAA1B;AACA,eAAKC,IAAL,GAAYP,MAAMQ,OAAN,IAAiB,EAA7B;AACA,eAAKlB,IAAL,GAAYU,MAAMV,IAAN,IAAc,EAA1B;AACA,eAAKkB,OAAL,GAAe,uBAAuB,KAAKD,IAA5B,GAAmC,GAAnC,GAAyC,KAAKjB,IAA7D;AACD;;;;qCAEU;AACT,mBAAO,KAAKiB,IAAL,GAAY,GAAZ,GAAkB,KAAKjB,IAA9B;AACD;;;;;;;;AAGHd,cACGiC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,sBAFX,EAEmCjC,oBAFnC","file":"zabbixAPICore.service.js","sourcesContent":["/**\n * General Zabbix API methods\n */\n\nimport angular from 'angular';\n\nclass ZabbixAPICoreService {\n\n /** @ngInject */\n constructor(backendSrv) {\n this.backendSrv = backendSrv;\n }\n\n /**\n * Request data from Zabbix API\n * @return {object} response.result\n */\n request(api_url, method, params, options, auth) {\n let requestData = {\n jsonrpc: '2.0',\n method: method,\n params: params,\n id: 1\n };\n\n if (auth === \"\") {\n // Reject immediately if not authenticated\n return Promise.reject(new ZabbixAPIError({data: \"Not authorised.\"}));\n } else if (auth) {\n // Set auth parameter only if it needed\n requestData.auth = auth;\n }\n\n let requestOptions = {\n method: 'POST',\n url: api_url,\n data: requestData,\n headers: {\n 'Content-Type': 'application/json'\n }\n };\n\n // Set request options for basic auth\n if (options.basicAuth || options.withCredentials) {\n requestOptions.withCredentials = true;\n }\n if (options.basicAuth) {\n requestOptions.headers.Authorization = options.basicAuth;\n }\n\n return this.datasourceRequest(requestOptions);\n }\n\n datasourceRequest(requestOptions) {\n return this.backendSrv.datasourceRequest(requestOptions)\n .then((response) => {\n if (!response.data) {\n return Promise.reject(new ZabbixAPIError({data: \"General Error, no data\"}));\n } else if (response.data.error) {\n\n // Handle Zabbix API errors\n return Promise.reject(new ZabbixAPIError(response.data.error));\n }\n\n // Success\n return response.data.result;\n });\n }\n\n /**\n * Get authentication token.\n * @return {string} auth token\n */\n login(api_url, username, password, options) {\n let params = {\n user: username,\n password: password\n };\n return this.request(api_url, 'user.login', params, options, null);\n }\n\n /**\n * Get Zabbix API version\n * Matches the version of Zabbix starting from Zabbix 2.0.4\n */\n getVersion(api_url, options) {\n return this.request(api_url, 'apiinfo.version', [], options);\n }\n}\n\n// Define zabbix API exception type\nexport class ZabbixAPIError {\n constructor(error) {\n this.code = error.code || null;\n this.name = error.message || \"\";\n this.data = error.data || \"\";\n this.message = \"Zabbix API Error: \" + this.name + \" \" + this.data;\n }\n\n toString() {\n return this.name + \" \" + this.data;\n }\n}\n\nangular\n .module('grafana.services')\n .service('zabbixAPICoreService', ZabbixAPICoreService);\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/zabbixAPICore.service.js"],"names":["angular","ZabbixAPICoreService","backendSrv","api_url","method","params","options","auth","requestData","jsonrpc","id","Promise","reject","ZabbixAPIError","data","requestOptions","url","headers","basicAuth","withCredentials","Authorization","datasourceRequest","then","response","error","result","username","password","user","request","code","name","message","module","service"],"mappings":";;;;;;;;;;;;;;;AAIOA,a;;;;;;;;;;;;;;;;;;;;;AAEDC,0B;;AAEJ;AACA,sCAAYC,UAAZ,EAAwB;AAAA;;AACtB,eAAKA,UAAL,GAAkBA,UAAlB;AACD;;AAED;;;;;;;;kCAIQC,O,EAASC,M,EAAQC,M,EAAQC,O,EAASC,I,EAAM;AAC9C,gBAAIC,cAAc;AAChBC,uBAAS,KADO;AAEhBL,sBAAQA,MAFQ;AAGhBC,sBAAQA,MAHQ;AAIhBK,kBAAI;AAJY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O,KAAKE,OAAL,CAAa1B,OAAb,EAAsB,YAAtB,EAAoCE,MAApC,EAA4CC,OAA5C,EAAqD,IAArD,CAAP;AACD;;;qCAMUH,O,EAASG,O,EAAS;AAC3B,mBAAO,KAAKuB,OAAL,CAAa1B,OAAb,EAAsB,iBAAtB,EAAyC,EAAzC,EAA6CG,OAA7C,CAAP;AACD;;;;;;gCAIUO,c;AACX,gCAAYW,KAAZ,EAAmB;AAAA;;AACjB,eAAKM,IAAL,GAAYN,MAAMM,IAAN,IAAc,IAA1B;AACA,eAAKC,IAAL,GAAYP,MAAMQ,OAAN,IAAiB,EAA7B;AACA,eAAKlB,IAAL,GAAYU,MAAMV,IAAN,IAAc,EAA1B;AACA,eAAKkB,OAAL,GAAe,uBAAuB,KAAKD,IAA5B,GAAmC,GAAnC,GAAyC,KAAKjB,IAA7D;AACD;;;;qCAEU;AACT,mBAAO,KAAKiB,IAAL,GAAY,GAAZ,GAAkB,KAAKjB,IAA9B;AACD;;;;;;;;AAGHd,cACGiC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,sBAFX,EAEmCjC,oBAFnC","file":"zabbixAPICore.service.js","sourcesContent":["/**\r\n * General Zabbix API methods\r\n */\r\n\r\nimport angular from 'angular';\r\n\r\nclass ZabbixAPICoreService {\r\n\r\n /** @ngInject */\r\n constructor(backendSrv) {\r\n this.backendSrv = backendSrv;\r\n }\r\n\r\n /**\r\n * Request data from Zabbix API\r\n * @return {object} response.result\r\n */\r\n request(api_url, method, params, options, auth) {\r\n let requestData = {\r\n jsonrpc: '2.0',\r\n method: method,\r\n params: params,\r\n id: 1\r\n };\r\n\r\n if (auth === \"\") {\r\n // Reject immediately if not authenticated\r\n return Promise.reject(new ZabbixAPIError({data: \"Not authorised.\"}));\r\n } else if (auth) {\r\n // Set auth parameter only if it needed\r\n requestData.auth = auth;\r\n }\r\n\r\n let requestOptions = {\r\n method: 'POST',\r\n url: api_url,\r\n data: requestData,\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n }\r\n };\r\n\r\n // Set request options for basic auth\r\n if (options.basicAuth || options.withCredentials) {\r\n requestOptions.withCredentials = true;\r\n }\r\n if (options.basicAuth) {\r\n requestOptions.headers.Authorization = options.basicAuth;\r\n }\r\n\r\n return this.datasourceRequest(requestOptions);\r\n }\r\n\r\n datasourceRequest(requestOptions) {\r\n return this.backendSrv.datasourceRequest(requestOptions)\r\n .then((response) => {\r\n if (!response.data) {\r\n return Promise.reject(new ZabbixAPIError({data: \"General Error, no data\"}));\r\n } else if (response.data.error) {\r\n\r\n // Handle Zabbix API errors\r\n return Promise.reject(new ZabbixAPIError(response.data.error));\r\n }\r\n\r\n // Success\r\n return response.data.result;\r\n });\r\n }\r\n\r\n /**\r\n * Get authentication token.\r\n * @return {string} auth token\r\n */\r\n login(api_url, username, password, options) {\r\n let params = {\r\n user: username,\r\n password: password\r\n };\r\n return this.request(api_url, 'user.login', params, options, null);\r\n }\r\n\r\n /**\r\n * Get Zabbix API version\r\n * Matches the version of Zabbix starting from Zabbix 2.0.4\r\n */\r\n getVersion(api_url, options) {\r\n return this.request(api_url, 'apiinfo.version', [], options);\r\n }\r\n}\r\n\r\n// Define zabbix API exception type\r\nexport class ZabbixAPIError {\r\n constructor(error) {\r\n this.code = error.code || null;\r\n this.name = error.message || \"\";\r\n this.data = error.data || \"\";\r\n this.message = \"Zabbix API Error: \" + this.name + \" \" + this.data;\r\n }\r\n\r\n toString() {\r\n return this.name + \" \" + this.data;\r\n }\r\n}\r\n\r\nangular\r\n .module('grafana.services')\r\n .service('zabbixAPICoreService', ZabbixAPICoreService);\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbixAlerting.service.js.map b/dist/datasource-zabbix/zabbixAlerting.service.js.map index c368ec406..a9633e094 100644 --- a/dist/datasource-zabbix/zabbixAlerting.service.js.map +++ b/dist/datasource-zabbix/zabbixAlerting.service.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/zabbixAlerting.service.js"],"names":["_","$","angular","ZabbixAlertingService","dashboardSrv","dash","meta","fullscreen","panelId","alertState","panelIndex","panelContainers","filter","elem","clientHeight","clientWidth","panelModels","getPanelModels","isFullScreen","findIndex","panel","id","alertClass","removeClass","addClass","flatten","map","rows","row","collapse","panels","find","threshold","getPanelModel","containsThreshold","thresholds","value","type","thresholdOptions","colorMode","fill","line","lineColor","op","source","push","module","service"],"mappings":";;;;;;;;;;;;;;;AAAOA,O;;AACAC,O;;AACAC,a;;;;;;;;;;;;;;;;;;;;;AAEDC,2B;;AAEJ;AACA,uCAAYC,YAAZ,EAA0B;AAAA;;AACxB,eAAKA,YAAL,GAAoBA,YAApB;AACD;;;;yCAEc;AACb,mBAAO,KAAKA,YAAL,CAAkBC,IAAlB,CAAuBC,IAAvB,CAA4BC,UAAnC;AACD;;;6CAEkBC,O,EAASC,U,EAAY;AACtC,gBAAIC,mBAAJ;;AAEA,gBAAIC,kBAAkBX,EAAEY,MAAF,CAASX,EAAE,kBAAF,CAAT,EAAgC,gBAAQ;AAC5D,qBAAOY,KAAKC,YAAL,IAAqBD,KAAKE,WAAjC;AACD,aAFqB,CAAtB;;AAIA,gBAAIC,cAAc,KAAKC,cAAL,EAAlB;;AAEA,gBAAI,KAAKC,YAAL,EAAJ,EAAyB;AACvBR,2BAAa,CAAb;AACD,aAFD,MAEO;AACLA,2BAAaV,EAAEmB,SAAF,CAAYH,WAAZ,EAAyB,iBAAS;AAC7C,uBAAOI,MAAMC,EAAN,KAAab,OAApB;AACD,eAFY,CAAb;AAGD;;AAED,gBAAIE,cAAc,CAAlB,EAAqB;AACnB,kBAAIY,aAAa,mEAAjB;AACArB,gBAAEU,gBAAgBD,UAAhB,CAAF,EAA+Ba,WAA/B,CAA2CD,UAA3C;;AAEA,kBAAIb,UAAJ,EAAgB;AACd,oBAAIA,eAAe,UAAnB,EAA+B;AAC7Ba,+BAAa,wCAAwCb,UAArD;AACAR,oBAAEU,gBAAgBD,UAAhB,CAAF,EAA+Bc,QAA/B,CAAwCF,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,QAAQ,KAAKa,aAAL,CAAmBzB,OAAnB,CAAZ;;AAEA,gBAAIY,SAASA,MAAMiB,IAAN,KAAe,OAA5B,EAAqC;AACnCjB,oBAAMe,UAAN,GAAmBnC,EAAEY,MAAF,CAASQ,MAAMe,UAAf,EAA2B,qBAAa;AACzD,uBAAOH,UAAUY,MAAV,KAAqB,QAA5B;AACD,eAFkB,CAAnB;AAGD;AACF;;;;;;AAIH1C,cACG4C,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,mBAFX,EAEgC5C,qBAFhC","file":"zabbixAlerting.service.js","sourcesContent":["import _ from 'lodash';\nimport $ from 'jquery';\nimport angular from 'angular';\n\nclass ZabbixAlertingService {\n\n /** @ngInject */\n constructor(dashboardSrv) {\n this.dashboardSrv = dashboardSrv;\n }\n\n isFullScreen() {\n return this.dashboardSrv.dash.meta.fullscreen;\n }\n\n setPanelAlertState(panelId, alertState) {\n let panelIndex;\n\n let panelContainers = _.filter($('.panel-container'), elem => {\n return elem.clientHeight && elem.clientWidth;\n });\n\n let panelModels = this.getPanelModels();\n\n if (this.isFullScreen()) {\n panelIndex = 0;\n } else {\n panelIndex = _.findIndex(panelModels, panel => {\n return panel.id === panelId;\n });\n }\n\n if (panelIndex >= 0) {\n let alertClass = \"panel-has-alert panel-alert-state--ok panel-alert-state--alerting\";\n $(panelContainers[panelIndex]).removeClass(alertClass);\n\n if (alertState) {\n if (alertState === 'alerting') {\n alertClass = \"panel-has-alert panel-alert-state--\" + alertState;\n $(panelContainers[panelIndex]).addClass(alertClass);\n }\n if (alertState === 'ok') {\n alertClass = \"panel-alert-state--\" + alertState;\n $(panelContainers[panelIndex]).addClass(alertClass);\n $(panelContainers[panelIndex]).removeClass(\"panel-has-alert\");\n }\n }\n }\n }\n\n getPanelModels() {\n return _.flatten(_.map(this.dashboardSrv.dash.rows, row => {\n if (row.collapse) {\n return [];\n } else {\n return row.panels;\n }\n }));\n }\n\n getPanelModel(panelId) {\n let panelModels = this.getPanelModels();\n\n return _.find(panelModels, panel => {\n return panel.id === panelId;\n });\n }\n\n setPanelThreshold(panelId, threshold) {\n let panel = this.getPanelModel(panelId);\n let containsThreshold = _.find(panel.thresholds, {value: threshold});\n\n if (panel && panel.type === \"graph\" && !containsThreshold) {\n let thresholdOptions = {\n colorMode : \"custom\",\n fill : false,\n line : true,\n lineColor: \"rgb(255, 0, 0)\",\n op: \"gt\",\n value: threshold,\n source: \"zabbix\"\n };\n\n panel.thresholds.push(thresholdOptions);\n }\n }\n\n removeZabbixThreshold(panelId) {\n let panel = this.getPanelModel(panelId);\n\n if (panel && panel.type === \"graph\") {\n panel.thresholds = _.filter(panel.thresholds, threshold => {\n return threshold.source !== \"zabbix\";\n });\n }\n }\n\n}\n\nangular\n .module('grafana.services')\n .service('zabbixAlertingSrv', ZabbixAlertingService);\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/zabbixAlerting.service.js"],"names":["_","$","angular","ZabbixAlertingService","dashboardSrv","dash","meta","fullscreen","panelId","alertState","panelIndex","panelContainers","filter","elem","clientHeight","clientWidth","panelModels","getPanelModels","isFullScreen","findIndex","panel","id","alertClass","removeClass","addClass","flatten","map","rows","row","collapse","panels","find","threshold","getPanelModel","containsThreshold","thresholds","value","type","thresholdOptions","colorMode","fill","line","lineColor","op","source","push","module","service"],"mappings":";;;;;;;;;;;;;;;AAAOA,O;;AACAC,O;;AACAC,a;;;;;;;;;;;;;;;;;;;;;AAEDC,2B;;AAEJ;AACA,uCAAYC,YAAZ,EAA0B;AAAA;;AACxB,eAAKA,YAAL,GAAoBA,YAApB;AACD;;;;yCAEc;AACb,mBAAO,KAAKA,YAAL,CAAkBC,IAAlB,CAAuBC,IAAvB,CAA4BC,UAAnC;AACD;;;6CAEkBC,O,EAASC,U,EAAY;AACtC,gBAAIC,mBAAJ;;AAEA,gBAAIC,kBAAkBX,EAAEY,MAAF,CAASX,EAAE,kBAAF,CAAT,EAAgC,gBAAQ;AAC5D,qBAAOY,KAAKC,YAAL,IAA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,aAFM,CAAP;AAGD;;;4CAEiBA,O,EAASwB,S,EAAW;AACpC,gBAAIZ,QAAQ,KAAKa,aAAL,CAAmBzB,OAAnB,CAAZ;AACA,gBAAI0B,oBAAoBlC,EAAE+B,IAAF,CAAOX,MAAMe,UAAb,EAAyB,EAACC,OAAOJ,SAAR,EAAzB,CAAxB;;AAEA,gBAAIZ,SAASA,MAAMiB,IAAN,KAAe,OAAxB,IAAmC,CAACH,iBAAxC,EAA2D;AACzD,kBAAII,mBAAmB;AACrBC,2BAAY,QADS;AAErBC,sBAAO,KAFc;AAGrBC,sBAAO,IAHc;AAIrBC,2BAAW,gBAJU;AAKrBC,oBAAI,IALiB;AAMrBP,uBAAOJ,SANc;AAOrBY,wBAAQ;AAPa,eAAvB;;AAUAxB,oBAAMe,UAAN,CAAiBU,IAAjB,CAAsBP,gBAAtB;AACD;AACF;;;gDAEqB9B,O,EAAS;AAC7B,gBAAIY,QAAQ,KAAKa,aAAL,CAAmBzB,OAAnB,CAAZ;;AAEA,gBAAIY,SAASA,MAAMiB,IAAN,KAAe,OAA5B,EAAqC;AACnCjB,oBAAMe,UAAN,GAAmBnC,EAAEY,MAAF,CAASQ,MAAMe,UAAf,EAA2B,qBAAa;AACzD,uBAAOH,UAAUY,MAAV,KAAqB,QAA5B;AACD,eAFkB,CAAnB;AAGD;AACF;;;;;;AAIH1C,cACG4C,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,mBAFX,EAEgC5C,qBAFhC","file":"zabbixAlerting.service.js","sourcesContent":["import _ from 'lodash';\r\nimport $ from 'jquery';\r\nimport angular from 'angular';\r\n\r\nclass ZabbixAlertingService {\r\n\r\n /** @ngInject */\r\n constructor(dashboardSrv) {\r\n this.dashboardSrv = dashboardSrv;\r\n }\r\n\r\n isFullScreen() {\r\n return this.dashboardSrv.dash.meta.fullscreen;\r\n }\r\n\r\n setPanelAlertState(panelId, alertState) {\r\n let panelIndex;\r\n\r\n let panelContainers = _.filter($('.panel-container'), elem => {\r\n return elem.clientHeight && elem.clientWidth;\r\n });\r\n\r\n let panelModels = this.getPanelModels();\r\n\r\n if (this.isFullScreen()) {\r\n panelIndex = 0;\r\n } else {\r\n panelIndex = _.findIndex(panelModels, panel => {\r\n return panel.id === panelId;\r\n });\r\n }\r\n\r\n if (panelIndex >= 0) {\r\n let alertClass = \"panel-has-alert panel-alert-state--ok panel-alert-state--alerting\";\r\n $(panelContainers[panelIndex]).removeClass(alertClass);\r\n\r\n if (alertState) {\r\n if (alertState === 'alerting') {\r\n alertClass = \"panel-has-alert panel-alert-state--\" + alertState;\r\n $(panelContainers[panelIndex]).addClass(alertClass);\r\n }\r\n if (alertState === 'ok') {\r\n alertClass = \"panel-alert-state--\" + alertState;\r\n $(panelContainers[panelIndex]).addClass(alertClass);\r\n $(panelContainers[panelIndex]).removeClass(\"panel-has-alert\");\r\n }\r\n }\r\n }\r\n }\r\n\r\n getPanelModels() {\r\n return _.flatten(_.map(this.dashboardSrv.dash.rows, row => {\r\n if (row.collapse) {\r\n return [];\r\n } else {\r\n return row.panels;\r\n }\r\n }));\r\n }\r\n\r\n getPanelModel(panelId) {\r\n let panelModels = this.getPanelModels();\r\n\r\n return _.find(panelModels, panel => {\r\n return panel.id === panelId;\r\n });\r\n }\r\n\r\n setPanelThreshold(panelId, threshold) {\r\n let panel = this.getPanelModel(panelId);\r\n let containsThreshold = _.find(panel.thresholds, {value: threshold});\r\n\r\n if (panel && panel.type === \"graph\" && !containsThreshold) {\r\n let thresholdOptions = {\r\n colorMode : \"custom\",\r\n fill : false,\r\n line : true,\r\n lineColor: \"rgb(255, 0, 0)\",\r\n op: \"gt\",\r\n value: threshold,\r\n source: \"zabbix\"\r\n };\r\n\r\n panel.thresholds.push(thresholdOptions);\r\n }\r\n }\r\n\r\n removeZabbixThreshold(panelId) {\r\n let panel = this.getPanelModel(panelId);\r\n\r\n if (panel && panel.type === \"graph\") {\r\n panel.thresholds = _.filter(panel.thresholds, threshold => {\r\n return threshold.source !== \"zabbix\";\r\n });\r\n }\r\n }\r\n\r\n}\r\n\r\nangular\r\n .module('grafana.services')\r\n .service('zabbixAlertingSrv', ZabbixAlertingService);\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbixCachingProxy.service.js b/dist/datasource-zabbix/zabbixCachingProxy.service.js index 5e657ecc5..c0502b175 100644 --- a/dist/datasource-zabbix/zabbixCachingProxy.service.js +++ b/dist/datasource-zabbix/zabbixCachingProxy.service.js @@ -195,9 +195,9 @@ System.register(['angular', 'lodash'], function (_export, _context) { return ZabbixCachingProxy; } - /** - * Wrap zabbix API request to prevent multiple calls - * with same params when waiting for result. + /** + * Wrap zabbix API request to prevent multiple calls + * with same params when waiting for result. */ function callAPIRequestOnce(func, promiseKeeper, argsHashFunc) { return function () { diff --git a/dist/datasource-zabbix/zabbixCachingProxy.service.js.map b/dist/datasource-zabbix/zabbixCachingProxy.service.js.map index 5edd3810c..be08a4fd0 100644 --- a/dist/datasource-zabbix/zabbixCachingProxy.service.js.map +++ b/dist/datasource-zabbix/zabbixCachingProxy.service.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/zabbixCachingProxy.service.js"],"names":["ZabbixCachingProxyFactory","ZabbixCachingProxy","zabbixAPI","zabbixDBConnector","cacheOptions","dbConnector","cacheEnabled","enabled","ttl","cache","groups","hosts","applications","items","history","trends","macros","globalMacros","itServices","historyPromises","getHistory","callAPIRequestOnce","_","bind","getHistoryRequestHash","getHistoryDB","getDBQueryHash","getTrendsDB","getTrends","groupPromises","getGroupsOnce","getGroups","getRequestHash","hostPromises","getHostsOnce","getHosts","appPromises","getAppsOnce","getApps","itemPromises","getItemsOnce","getItems","itemByIdPromises","getItemsByIdOnce","getItemsByIDs","itServicesPromises","getITServicesOnce","getITService","macroPromises","getMacrosOnce","getMacros","globalMacroPromises","getGlobalMacrosOnce","getGlobalMacros","cacheObject","object_age","Date","now","timestamp","request","params","hash","isExpired","Promise","resolve","value","then","result","proxyRequest","groupids","hostids","appids","itemtype","itemids","promises","all","flatten","time_from","time_till","historyStorage","full_history","expired","filter","keyBy","item","itemid","length","grouped_history","groupBy","forEach","map","func","promiseKeeper","argsHashFunc","arguments","apply","args","requestStamp","arg","undefined","isArray","sort","toString","join","getHash","stamp","consolidateBy","intervalMs","angular","module","factory","String","prototype","i","chr","len","charCodeAt","indexBy"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGA;AACA;;AAEA;AACA,WAASA,yBAAT,GAAqC;AAAA,QAE7BC,kBAF6B;AAGjC,kCAAYC,SAAZ,EAAuBC,iBAAvB,EAA0CC,YAA1C,EAAwD;AAAA;;AACtD,aAAKF,SAAL,GAAiBA,SAAjB;AACA,aAAKG,WAAL,GAAmBF,iBAAnB;AACA,aAAKG,YAAL,GAAoBF,aAAaG,OAAjC;AACA,aAAKC,GAAL,GAAoBJ,aAAaI,GAAb,IAAoB,MAAxC,CAJsD,CAIN;;AAEhD;AACA,aAAKC,KAAL,GAAa;AACXC,kBAAQ,EADG;AAEXC,iBAAO,EAFI;AAGXC,wBAAc,EAHH;AAIXC,iBAAO,EAJI;AAKXC,mBAAS,EALE;AAMXC,kBAAQ,EANG;AAOXC,kBAAQ,EAPG;AAQXC,wBAAc,EARH;AASXC,sBAAY;AATD,SAAb;;AAYA,aAAKC,eAAL,GAAuB,EAAvB;;AAEA;AACA,aAAKC,UAAL,GAAkBC,mBAAmBC,EAAEC,IAAF,CAAO,KAAKrB,SAAL,CAAekB,UAAtB,EAAkC,KAAKlB,SAAvC,CAAnB,EACmB,KAAKiB,eADxB,EACyCK,qBADzC,CAAlB;;AAGA,YAAI,KAAKnB,WAAT,EAAsB;AACpB,eAAKoB,YAAL,GAAoBJ,mBAAmBC,EAAEC,IAAF,CAAO,KAAKlB,WAAL,CAAiBe,UAAxB,EAAoC,KAAKf,WAAzC,CAAnB,EACmB,KAAKc,eADxB,EACyCO,cADzC,CAApB;AAEA,eAAKC,WAAL,GAAmBN,mBAAmBC,EAAEC,IAAF,CAAO,KAAKlB,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AAhB,CAAR;AACApD,mBAAS,CAACA,QAAQ,CAAT,IAAcA,IAAf,GAAuBqD,GAA/B;AACArD,oBAAQ,CAAR,CAH2C,CAGhC;AACZ;AACF;AACD,eAAOA,IAAP;AACD,OAVD;;AAYA;AACA,UAAI,CAACvC,EAAE6D,KAAP,EAAc;AAAC7D,UAAE6D,KAAF,GAAU7D,EAAE+F,OAAZ;AAAqB","file":"zabbixCachingProxy.service.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\n\n// Use factory() instead service() for multiple datasources support.\n// Each datasource instance must initialize its own cache.\n\n/** @ngInject */\nfunction ZabbixCachingProxyFactory() {\n\n class ZabbixCachingProxy {\n constructor(zabbixAPI, zabbixDBConnector, cacheOptions) {\n this.zabbixAPI = zabbixAPI;\n this.dbConnector = zabbixDBConnector;\n this.cacheEnabled = cacheOptions.enabled;\n this.ttl = cacheOptions.ttl || 600000; // 10 minutes by default\n\n // Internal objects for data storing\n this.cache = {\n groups: {},\n hosts: {},\n applications: {},\n items: {},\n history: {},\n trends: {},\n macros: {},\n globalMacros: {},\n itServices: {}\n };\n\n this.historyPromises = {};\n\n // Don't run duplicated history requests\n this.getHistory = callAPIRequestOnce(_.bind(this.zabbixAPI.getHistory, this.zabbixAPI),\n this.historyPromises, getHistoryRequestHash);\n\n if (this.dbConnector) {\n this.getHistoryDB = callAPIRequestOnce(_.bind(this.dbConnector.getHistory, this.dbConnector),\n this.historyPromises, getDBQueryHash);\n this.getTrendsDB = callAPIRequestOnce(_.bind(this.dbConnector.getTrends, this.dbConnector),\n this.historyPromises, getDBQueryHash);\n }\n\n // Don't run duplicated requests\n this.groupPromises = {};\n this.getGroupsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getGroups, this.zabbixAPI),\n this.groupPromises, getRequestHash);\n\n this.hostPromises = {};\n this.getHostsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getHosts, this.zabbixAPI),\n this.hostPromises, getRequestHash);\n\n this.appPromises = {};\n this.getAppsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getApps, this.zabbixAPI),\n this.appPromises, getRequestHash);\n\n this.itemPromises = {};\n this.getItemsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getItems, this.zabbixAPI),\n this.itemPromises, getRequestHash);\n\n this.itemByIdPromises = {};\n this.getItemsByIdOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getItemsByIDs, this.zabbixAPI),\n this.itemPromises, getRequestHash);\n\n this.itServicesPromises = {};\n this.getITServicesOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getITService, this.zabbixAPI),\n this.itServicesPromises, getRequestHash);\n\n this.macroPromises = {};\n this.getMacrosOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getMacros, this.zabbixAPI),\n this.macroPromises, getRequestHash);\n\n this.globalMacroPromises = {};\n this.getGlobalMacrosOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getGlobalMacros, this.zabbixAPI),\n this.globalMacroPromises, getRequestHash);\n }\n\n isExpired(cacheObject) {\n if (cacheObject) {\n let object_age = Date.now() - cacheObject.timestamp;\n return !(cacheObject.timestamp && object_age < this.ttl);\n } else {\n return true;\n }\n }\n\n /**\n * Check that result is present in cache and up to date\n * or send request to API.\n */\n proxyRequest(request, params, cacheObject) {\n let hash = getRequestHash(params);\n if (this.cacheEnabled && !this.isExpired(cacheObject[hash])) {\n return Promise.resolve(cacheObject[hash].value);\n } else {\n return request(...params)\n .then(result => {\n cacheObject[hash] = {\n value: result,\n timestamp: Date.now()\n };\n return result;\n });\n }\n }\n\n getGroups() {\n return this.proxyRequest(this.getGroupsOnce, [], this.cache.groups);\n }\n\n getHosts(groupids) {\n return this.proxyRequest(this.getHostsOnce, [groupids], this.cache.hosts);\n }\n\n getApps(hostids) {\n return this.proxyRequest(this.getAppsOnce, [hostids], this.cache.applications);\n }\n\n getItems(hostids, appids, itemtype) {\n let params = [hostids, appids, itemtype];\n return this.proxyRequest(this.getItemsOnce, params, this.cache.items);\n }\n\n getItemsByIDs(itemids) {\n let params = [itemids];\n return this.proxyRequest(this.getItemsByIdOnce, params, this.cache.items);\n }\n\n getITServices() {\n return this.proxyRequest(this.getITServicesOnce, [], this.cache.itServices);\n }\n\n getMacros(hostids) {\n // Merge global macros and host macros\n let promises = [\n this.proxyRequest(this.getMacrosOnce, [hostids], this.cache.macros),\n this.proxyRequest(this.getGlobalMacrosOnce, [], this.cache.globalMacros)\n ];\n\n return Promise.all(promises).then(_.flatten);\n }\n\n getHistoryFromCache(items, time_from, time_till) {\n var historyStorage = this.cache.history;\n var full_history;\n var expired = _.filter(_.keyBy(items, 'itemid'), (item, itemid) => {\n return !historyStorage[itemid];\n });\n if (expired.length) {\n return this.zabbixAPI.getHistory(expired, time_from, time_till).then(function(history) {\n var grouped_history = _.groupBy(history, 'itemid');\n _.forEach(expired, item => {\n var itemid = item.itemid;\n historyStorage[itemid] = item;\n historyStorage[itemid].time_from = time_from;\n historyStorage[itemid].time_till = time_till;\n historyStorage[itemid].history = grouped_history[itemid];\n });\n full_history = _.map(items, item => {\n return historyStorage[item.itemid].history;\n });\n return _.flatten(full_history, true);\n });\n } else {\n full_history = _.map(items, function(item) {\n return historyStorage[item.itemid].history;\n });\n return Promise.resolve(_.flatten(full_history, true));\n }\n }\n\n getHistoryFromAPI(items, time_from, time_till) {\n return this.zabbixAPI.getHistory(items, time_from, time_till);\n }\n }\n\n return ZabbixCachingProxy;\n}\n\nangular\n .module('grafana.services')\n .factory('ZabbixCachingProxy', ZabbixCachingProxyFactory);\n\n/**\n * Wrap zabbix API request to prevent multiple calls\n * with same params when waiting for result.\n */\nfunction callAPIRequestOnce(func, promiseKeeper, argsHashFunc) {\n return function() {\n var hash = argsHashFunc(arguments);\n if (!promiseKeeper[hash]) {\n promiseKeeper[hash] = Promise.resolve(\n func.apply(this, arguments)\n .then(result => {\n promiseKeeper[hash] = null;\n return result;\n })\n );\n }\n return promiseKeeper[hash];\n };\n}\n\nfunction getRequestHash(args) {\n var requestStamp = _.map(args, arg => {\n if (arg === undefined) {\n return 'undefined';\n } else {\n if (_.isArray(arg)) {\n return arg.sort().toString();\n } else {\n return arg.toString();\n }\n }\n }).join();\n return requestStamp.getHash();\n}\n\nfunction getHistoryRequestHash(args) {\n let itemids = _.map(args[0], 'itemid');\n let stamp = itemids.join() + args[1] + args[2];\n return stamp.getHash();\n}\n\nfunction getDBQueryHash(args) {\n let itemids = _.map(args[0], 'itemid');\n let consolidateBy = args[3].consolidateBy;\n let intervalMs = args[3].intervalMs;\n let stamp = itemids.join() + args[1] + args[2] + consolidateBy + intervalMs;\n return stamp.getHash();\n}\n\nString.prototype.getHash = function() {\n var hash = 0, i, chr, len;\n if (this.length !== 0) {\n for (i = 0, len = this.length; i < len; i++) {\n chr = this.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n }\n return hash;\n};\n\n// Fix for backward compatibility with lodash 2.4\nif (!_.keyBy) {_.keyBy = _.indexBy;}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/zabbixCachingProxy.service.js"],"names":["ZabbixCachingProxyFactory","ZabbixCachingProxy","zabbixAPI","zabbixDBConnector","cacheOptions","dbConnector","cacheEnabled","enabled","ttl","cache","groups","hosts","applications","items","history","trends","macros","globalMacros","itServices","historyPromises","getHistory","callAPIRequestOnce","_","bind","getHistoryRequestHash","getHistoryDB","getDBQueryHash","getTrendsDB","getTrends","groupPromises","getGroupsOnce","getGroups","getRequestHash","hostPromises","getHostsOnce","getHosts","appPromises","getAppsOnce","getApps","itemPromises","getItemsOnce","getItems","itemByIdPromises","getItemsByIdOnce","getItemsByIDs","itServicesPromises","getITServicesOnce","getITService","macroPromises","getMacrosOnce","getMacros","globalMacroPromises","getGlobalMacrosOnce","getGlobalMacros","cacheObject","object_age","Date","now","timestamp","request","params","hash","isExpired","Promise","resolve","value","then","result","proxyRequest","groupids","hostids","appids","itemtype","itemids","promises","all","flatten","time_from","time_till","historyStorage","full_history","expired","filter","keyBy","item","itemid","length","grouped_history","groupBy","forEach","map","func","promiseKeeper","argsHashFunc","arguments","apply","args","requestStamp","arg","undefined","isArray","sort","toString","join","getHash","stamp","consolidateBy","intervalMs","angular","module","factory","String","prototype","i","chr","len","charCodeAt","indexBy"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGA;AACA;;AAEA;AACA,WAASA,yBAAT,GAAqC;AAAA,QAE7BC,kBAF6B;AAGjC,kCAAYC,SAAZ,EAAuBC,iBAAvB,EAA0CC,YAA1C,EAAwD;AAAA;;AACtD,aAAKF,SAAL,GAAiBA,SAAjB;AACA,aAAKG,WAAL,GAAmBF,iBAAnB;AACA,aAAKG,YAAL,GAAoBF,aAAaG,OAAjC;AACA,aAAKC,GAAL,GAAoBJ,aAAaI,GAAb,IAAoB,MAAxC,CAJsD,CAIN;;AAEhD;AACA,aAAKC,KAAL,GAAa;AACXC,kBAAQ,EADG;AAEXC,iBAAO,EAFI;AAGXC,wBAAc,EAHH;AAIXC,iBAAO,EAJI;AAKXC,mBAAS,EALE;AAMXC,kBAAQ,EANG;AAOXC,kBAAQ,EAPG;AAQXC,wBAAc,EARH;AASXC,sBAAY;AATD,SAAb;;AAYA,aAAKC,eAAL,GAAuB,EAAvB;;AAEA;AACA,aAAKC,UAAL,GAAkBC,mBAAmBC,EAAEC,IAAF,CAAO,KAAKrB,SAAL,CAAekB,UAAtB,EAAkC,KAAKlB,SAAvC,CAAnB,EACmB,KAAKiB,eADxB,EACyCK,qBADzC,CAAlB;;AAGA,YAAI,KAAKnB,WAAT,EAAsB;AACpB,eAAKoB,YAAL,GAAoBJ,mBAAmBC,EAAEC,IAAF,CAAO,KAAKlB,WAAL,CAAiBe,UAAxB,EAAoC,KAAKf,WAAzC,CAAnB,EACmB,KAAKc,eADxB,EACyCO,cADzC,CAApB;AAEA,eAAKC,WAAL,GAAmBN,mBAAmBC,EAAEC,IAAF,CAAO,KAAKlB,WAAL,CAAiBuB,SAAxB,EAAmC,KAAKvB,WAAx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,IAAcA,IAAf,GAAuBqD,GAA/B;AACArD,oBAAQ,CAAR,CAH2C,CAGhC;AACZ;AACF;AACD,eAAOA,IAAP;AACD,OAVD;;AAYA;AACA,UAAI,CAACvC,EAAE6D,KAAP,EAAc;AAAC7D,UAAE6D,KAAF,GAAU7D,EAAE+F,OAAZ;AAAqB","file":"zabbixCachingProxy.service.js","sourcesContent":["import angular from 'angular';\r\nimport _ from 'lodash';\r\n\r\n// Use factory() instead service() for multiple datasources support.\r\n// Each datasource instance must initialize its own cache.\r\n\r\n/** @ngInject */\r\nfunction ZabbixCachingProxyFactory() {\r\n\r\n class ZabbixCachingProxy {\r\n constructor(zabbixAPI, zabbixDBConnector, cacheOptions) {\r\n this.zabbixAPI = zabbixAPI;\r\n this.dbConnector = zabbixDBConnector;\r\n this.cacheEnabled = cacheOptions.enabled;\r\n this.ttl = cacheOptions.ttl || 600000; // 10 minutes by default\r\n\r\n // Internal objects for data storing\r\n this.cache = {\r\n groups: {},\r\n hosts: {},\r\n applications: {},\r\n items: {},\r\n history: {},\r\n trends: {},\r\n macros: {},\r\n globalMacros: {},\r\n itServices: {}\r\n };\r\n\r\n this.historyPromises = {};\r\n\r\n // Don't run duplicated history requests\r\n this.getHistory = callAPIRequestOnce(_.bind(this.zabbixAPI.getHistory, this.zabbixAPI),\r\n this.historyPromises, getHistoryRequestHash);\r\n\r\n if (this.dbConnector) {\r\n this.getHistoryDB = callAPIRequestOnce(_.bind(this.dbConnector.getHistory, this.dbConnector),\r\n this.historyPromises, getDBQueryHash);\r\n this.getTrendsDB = callAPIRequestOnce(_.bind(this.dbConnector.getTrends, this.dbConnector),\r\n this.historyPromises, getDBQueryHash);\r\n }\r\n\r\n // Don't run duplicated requests\r\n this.groupPromises = {};\r\n this.getGroupsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getGroups, this.zabbixAPI),\r\n this.groupPromises, getRequestHash);\r\n\r\n this.hostPromises = {};\r\n this.getHostsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getHosts, this.zabbixAPI),\r\n this.hostPromises, getRequestHash);\r\n\r\n this.appPromises = {};\r\n this.getAppsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getApps, this.zabbixAPI),\r\n this.appPromises, getRequestHash);\r\n\r\n this.itemPromises = {};\r\n this.getItemsOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getItems, this.zabbixAPI),\r\n this.itemPromises, getRequestHash);\r\n\r\n this.itemByIdPromises = {};\r\n this.getItemsByIdOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getItemsByIDs, this.zabbixAPI),\r\n this.itemPromises, getRequestHash);\r\n\r\n this.itServicesPromises = {};\r\n this.getITServicesOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getITService, this.zabbixAPI),\r\n this.itServicesPromises, getRequestHash);\r\n\r\n this.macroPromises = {};\r\n this.getMacrosOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getMacros, this.zabbixAPI),\r\n this.macroPromises, getRequestHash);\r\n\r\n this.globalMacroPromises = {};\r\n this.getGlobalMacrosOnce = callAPIRequestOnce(_.bind(this.zabbixAPI.getGlobalMacros, this.zabbixAPI),\r\n this.globalMacroPromises, getRequestHash);\r\n }\r\n\r\n isExpired(cacheObject) {\r\n if (cacheObject) {\r\n let object_age = Date.now() - cacheObject.timestamp;\r\n return !(cacheObject.timestamp && object_age < this.ttl);\r\n } else {\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Check that result is present in cache and up to date\r\n * or send request to API.\r\n */\r\n proxyRequest(request, params, cacheObject) {\r\n let hash = getRequestHash(params);\r\n if (this.cacheEnabled && !this.isExpired(cacheObject[hash])) {\r\n return Promise.resolve(cacheObject[hash].value);\r\n } else {\r\n return request(...params)\r\n .then(result => {\r\n cacheObject[hash] = {\r\n value: result,\r\n timestamp: Date.now()\r\n };\r\n return result;\r\n });\r\n }\r\n }\r\n\r\n getGroups() {\r\n return this.proxyRequest(this.getGroupsOnce, [], this.cache.groups);\r\n }\r\n\r\n getHosts(groupids) {\r\n return this.proxyRequest(this.getHostsOnce, [groupids], this.cache.hosts);\r\n }\r\n\r\n getApps(hostids) {\r\n return this.proxyRequest(this.getAppsOnce, [hostids], this.cache.applications);\r\n }\r\n\r\n getItems(hostids, appids, itemtype) {\r\n let params = [hostids, appids, itemtype];\r\n return this.proxyRequest(this.getItemsOnce, params, this.cache.items);\r\n }\r\n\r\n getItemsByIDs(itemids) {\r\n let params = [itemids];\r\n return this.proxyRequest(this.getItemsByIdOnce, params, this.cache.items);\r\n }\r\n\r\n getITServices() {\r\n return this.proxyRequest(this.getITServicesOnce, [], this.cache.itServices);\r\n }\r\n\r\n getMacros(hostids) {\r\n // Merge global macros and host macros\r\n let promises = [\r\n this.proxyRequest(this.getMacrosOnce, [hostids], this.cache.macros),\r\n this.proxyRequest(this.getGlobalMacrosOnce, [], this.cache.globalMacros)\r\n ];\r\n\r\n return Promise.all(promises).then(_.flatten);\r\n }\r\n\r\n getHistoryFromCache(items, time_from, time_till) {\r\n var historyStorage = this.cache.history;\r\n var full_history;\r\n var expired = _.filter(_.keyBy(items, 'itemid'), (item, itemid) => {\r\n return !historyStorage[itemid];\r\n });\r\n if (expired.length) {\r\n return this.zabbixAPI.getHistory(expired, time_from, time_till).then(function(history) {\r\n var grouped_history = _.groupBy(history, 'itemid');\r\n _.forEach(expired, item => {\r\n var itemid = item.itemid;\r\n historyStorage[itemid] = item;\r\n historyStorage[itemid].time_from = time_from;\r\n historyStorage[itemid].time_till = time_till;\r\n historyStorage[itemid].history = grouped_history[itemid];\r\n });\r\n full_history = _.map(items, item => {\r\n return historyStorage[item.itemid].history;\r\n });\r\n return _.flatten(full_history, true);\r\n });\r\n } else {\r\n full_history = _.map(items, function(item) {\r\n return historyStorage[item.itemid].history;\r\n });\r\n return Promise.resolve(_.flatten(full_history, true));\r\n }\r\n }\r\n\r\n getHistoryFromAPI(items, time_from, time_till) {\r\n return this.zabbixAPI.getHistory(items, time_from, time_till);\r\n }\r\n }\r\n\r\n return ZabbixCachingProxy;\r\n}\r\n\r\nangular\r\n .module('grafana.services')\r\n .factory('ZabbixCachingProxy', ZabbixCachingProxyFactory);\r\n\r\n/**\r\n * Wrap zabbix API request to prevent multiple calls\r\n * with same params when waiting for result.\r\n */\r\nfunction callAPIRequestOnce(func, promiseKeeper, argsHashFunc) {\r\n return function() {\r\n var hash = argsHashFunc(arguments);\r\n if (!promiseKeeper[hash]) {\r\n promiseKeeper[hash] = Promise.resolve(\r\n func.apply(this, arguments)\r\n .then(result => {\r\n promiseKeeper[hash] = null;\r\n return result;\r\n })\r\n );\r\n }\r\n return promiseKeeper[hash];\r\n };\r\n}\r\n\r\nfunction getRequestHash(args) {\r\n var requestStamp = _.map(args, arg => {\r\n if (arg === undefined) {\r\n return 'undefined';\r\n } else {\r\n if (_.isArray(arg)) {\r\n return arg.sort().toString();\r\n } else {\r\n return arg.toString();\r\n }\r\n }\r\n }).join();\r\n return requestStamp.getHash();\r\n}\r\n\r\nfunction getHistoryRequestHash(args) {\r\n let itemids = _.map(args[0], 'itemid');\r\n let stamp = itemids.join() + args[1] + args[2];\r\n return stamp.getHash();\r\n}\r\n\r\nfunction getDBQueryHash(args) {\r\n let itemids = _.map(args[0], 'itemid');\r\n let consolidateBy = args[3].consolidateBy;\r\n let intervalMs = args[3].intervalMs;\r\n let stamp = itemids.join() + args[1] + args[2] + consolidateBy + intervalMs;\r\n return stamp.getHash();\r\n}\r\n\r\nString.prototype.getHash = function() {\r\n var hash = 0, i, chr, len;\r\n if (this.length !== 0) {\r\n for (i = 0, len = this.length; i < len; i++) {\r\n chr = this.charCodeAt(i);\r\n hash = ((hash << 5) - hash) + chr;\r\n hash |= 0; // Convert to 32bit integer\r\n }\r\n }\r\n return hash;\r\n};\r\n\r\n// Fix for backward compatibility with lodash 2.4\r\nif (!_.keyBy) {_.keyBy = _.indexBy;}\r\n"]} \ No newline at end of file diff --git a/dist/datasource-zabbix/zabbixDBConnector.js b/dist/datasource-zabbix/zabbixDBConnector.js index 535e596da..0d0b04faa 100644 --- a/dist/datasource-zabbix/zabbixDBConnector.js +++ b/dist/datasource-zabbix/zabbixDBConnector.js @@ -28,9 +28,9 @@ System.register(['angular', 'lodash'], function (_export, _context) { this.loadSQLDataSource(sqlDataSourceId); } - /** - * Try to load DS with given id to check it's exist. - * @param {*} datasourceId ID of SQL data source + /** + * Try to load DS with given id to check it's exist. + * @param {*} datasourceId ID of SQL data source */ diff --git a/dist/datasource-zabbix/zabbixDBConnector.js.map b/dist/datasource-zabbix/zabbixDBConnector.js.map index 24c998d63..973c9b47c 100644 --- a/dist/datasource-zabbix/zabbixDBConnector.js.map +++ b/dist/datasource-zabbix/zabbixDBConnector.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/datasource-zabbix/zabbixDBConnector.js"],"names":["ZabbixDBConnectorFactory","datasourceSrv","backendSrv","ZabbixDBConnector","sqlDataSourceId","options","limit","DEFAULT_QUERY_LIMIT","loadSQLDataSource","datasourceId","ds","_","find","getAll","loadDatasource","name","then","sqlDataSourceType","meta","id","Promise","reject","testQuery","TEST_MYSQL_QUERY","TEST_POSTGRES_QUERY","invokeSQLQuery","items","timeFrom","timeTill","intervalMs","consolidateBy","intervalSec","Math","ceil","aggFunction","consolidateByFunc","grouped_items","groupBy","promises","map","value_type","itemids","join","table","HISTORY_TO_TABLE_MAP","dialect","query","buildSQLHistoryQuery","compactSQLQuery","all","flatten","results","TREND_TO_TABLE_MAP","valueColumn","includes","consolidateByTrendColumns","buildSQLTrendsQuery","history","addHostName","convertGrafanaTSResponse","queryDef","refId","format","rawSql","maxDataPoints","datasourceRequest","url","method","data","queries","response","series","time_series","hosts","uniqBy","grafanaSeries","itemid","item","alias","keys","length","host","hostid","datapoints","cloneDeep","points","target","sortBy","replace","buildPostgresHistoryQuery","buildMysqlHistoryQuery","buildPostgresTrendsQuery","buildMysqlTrendsQuery","time_expression","itemid_format","angular","module","factory"],"mappings":";;;;;;;;;;;;;AA+BA;AACA,WAASA,wBAAT,CAAkC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BF,OAHjB,6BAIcd,QAJd,qBAIsCC,QAJtC,mDAAJ;AAQA,WAAOkB,KAAP;AACD;;;;AA7QMiD,a;;AACApF,O;;;;;;;;;;;;;;;;;;;;;AAEDJ,yB,GAAsB,K;AACtBqC,0B,GAAuB;AAC3B,aAAK,SADsB;AAE3B,aAAK,aAFsB;AAG3B,aAAK,aAHsB;AAI3B,aAAK,cAJsB;AAK3B,aAAK;AALsB,O;AAQvBQ,wB,GAAqB;AACzB,aAAK,QADoB;AAEzB,aAAK;AAFoB,O;AAKrBjB,uB,GAAoB;AACxB,eAAO,KADiB;AAExB,eAAO,KAFiB;AAGxB,eAAO,KAHiB;AAIxB,eAAO,KAJiB;AAKxB,iBAAS;AALe,O;AAQpBoB,+B,GAA4B;AAChC,eAAO,WADyB;AAEhC,eAAO,WAFyB;AAGhC,eAAO;AAHyB,O;AAsIlCwC,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,mBAFX,EAEgCjG,wBAFhC,EA8EMuB,gB;AAMAuE,mB,GAAgB,wB;AA4BhBtE,yB,qCACsBsE,a","file":"zabbixDBConnector.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\n\nconst DEFAULT_QUERY_LIMIT = 10000;\nconst HISTORY_TO_TABLE_MAP = {\n '0': 'history',\n '1': 'history_str',\n '2': 'history_log',\n '3': 'history_uint',\n '4': 'history_text'\n};\n\nconst TREND_TO_TABLE_MAP = {\n '0': 'trends',\n '3': 'trends_uint'\n};\n\nconst consolidateByFunc = {\n 'avg': 'AVG',\n 'min': 'MIN',\n 'max': 'MAX',\n 'sum': 'SUM',\n 'count': 'COUNT'\n};\n\nconst consolidateByTrendColumns = {\n 'avg': 'value_avg',\n 'min': 'value_min',\n 'max': 'value_max'\n};\n\n/** @ngInject */\nfunction ZabbixDBConnectorFactory(datasourceSrv, backendSrv) {\n\n class ZabbixDBConnector {\n\n constructor(sqlDataSourceId, options = {}) {\n let {limit} = options;\n\n this.sqlDataSourceId = sqlDataSourceId;\n this.limit = limit || DEFAULT_QUERY_LIMIT;\n\n this.loadSQLDataSource(sqlDataSourceId);\n }\n\n /**\n * Try to load DS with given id to check it's exist.\n * @param {*} datasourceId ID of SQL data source\n */\n loadSQLDataSource(datasourceId) {\n let ds = _.find(datasourceSrv.getAll(), {'id': datasourceId});\n if (ds) {\n return datasourceSrv.loadDatasource(ds.name)\n .then(ds => {\n this.sqlDataSourceType = ds.meta.id;\n return ds;\n });\n } else {\n return Promise.reject(`SQL Data Source with ID ${datasourceId} not found`);\n }\n }\n\n /**\n * Try to invoke test query for one of Zabbix database tables.\n */\n testSQLDataSource() {\n let testQuery = TEST_MYSQL_QUERY;\n if (this.sqlDataSourceType === 'postgres') {\n testQuery = TEST_POSTGRES_QUERY;\n }\n return this.invokeSQLQuery(testQuery);\n }\n\n getHistory(items, timeFrom, timeTill, options) {\n let {intervalMs, consolidateBy} = options;\n let intervalSec = Math.ceil(intervalMs / 1000);\n\n consolidateBy = consolidateBy || 'avg';\n let aggFunction = consolidateByFunc[consolidateBy];\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').join(', ');\n let table = HISTORY_TO_TABLE_MAP[value_type];\n\n let dialect = this.sqlDataSourceType;\n let query = buildSQLHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, dialect);\n\n query = compactSQLQuery(query);\n return this.invokeSQLQuery(query);\n });\n\n return Promise.all(promises).then(results => {\n return _.flatten(results);\n });\n }\n\n getTrends(items, timeFrom, timeTill, options) {\n let {intervalMs, consolidateBy} = options;\n let intervalSec = Math.ceil(intervalMs / 1000);\n\n consolidateBy = consolidateBy || 'avg';\n let aggFunction = consolidateByFunc[consolidateBy];\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').join(', ');\n let table = TREND_TO_TABLE_MAP[value_type];\n let valueColumn = _.includes(['avg', 'min', 'max'], consolidateBy) ? consolidateBy : 'avg';\n valueColumn = consolidateByTrendColumns[valueColumn];\n\n let dialect = this.sqlDataSourceType;\n let query = buildSQLTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn, dialect);\n\n query = compactSQLQuery(query);\n return this.invokeSQLQuery(query);\n });\n\n return Promise.all(promises).then(results => {\n return _.flatten(results);\n });\n }\n\n handleGrafanaTSResponse(history, items, addHostName = true) {\n return convertGrafanaTSResponse(history, items, addHostName);\n }\n\n invokeSQLQuery(query) {\n let queryDef = {\n refId: 'A',\n format: 'time_series',\n datasourceId: this.sqlDataSourceId,\n rawSql: query,\n maxDataPoints: this.limit\n };\n\n return backendSrv.datasourceRequest({\n url: '/api/tsdb/query',\n method: 'POST',\n data: {\n queries: [queryDef],\n }\n })\n .then(response => {\n let results = response.data.results;\n if (results['A']) {\n return results['A'].series;\n } else {\n return null;\n }\n });\n }\n }\n\n return ZabbixDBConnector;\n}\n\nangular\n .module('grafana.services')\n .factory('ZabbixDBConnector', ZabbixDBConnectorFactory);\n\n///////////////////////////////////////////////////////////////////////////////\n\nfunction convertGrafanaTSResponse(time_series, items, addHostName) {\n var hosts = _.uniqBy(_.flatten(_.map(items, 'hosts')), 'hostid'); //uniqBy is needed to deduplicate\n let grafanaSeries = _.map(time_series, series => {\n let itemid = series.name;\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 // zabbixCachingProxy deduplicates requests and returns one time series for equal queries.\n // Clone is needed to prevent changing of series object shared between all targets.\n let datapoints = _.cloneDeep(series.points);\n return {\n target: alias,\n datapoints: datapoints\n };\n });\n\n return _.sortBy(grafanaSeries, 'target');\n}\n\nfunction compactSQLQuery(query) {\n return query.replace(/\\s+/g, ' ');\n}\n\nfunction buildSQLHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, dialect = 'mysql') {\n if (dialect === 'postgres') {\n return buildPostgresHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction);\n } else {\n return buildMysqlHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction);\n }\n}\n\nfunction buildSQLTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn, dialect = 'mysql') {\n if (dialect === 'postgres') {\n return buildPostgresTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn);\n } else {\n return buildMysqlTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn);\n }\n}\n\n///////////\n// MySQL //\n///////////\n\nfunction buildMysqlHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction) {\n let time_expression = `clock DIV ${intervalSec} * ${intervalSec}`;\n let query = `\n SELECT itemid AS metric, ${time_expression} AS time_sec, ${aggFunction}(value) AS value\n FROM ${table}\n WHERE itemid IN (${itemids})\n AND clock > ${timeFrom} AND clock < ${timeTill}\n GROUP BY ${time_expression}, metric\n ORDER BY time_sec ASC\n `;\n return query;\n}\n\nfunction buildMysqlTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn) {\n let time_expression = `clock DIV ${intervalSec} * ${intervalSec}`;\n let query = `\n SELECT itemid AS metric, ${time_expression} AS time_sec, ${aggFunction}(${valueColumn}) AS value\n FROM ${table}\n WHERE itemid IN (${itemids})\n AND clock > ${timeFrom} AND clock < ${timeTill}\n GROUP BY ${time_expression}, metric\n ORDER BY time_sec ASC\n `;\n return query;\n}\n\nconst TEST_MYSQL_QUERY = `SELECT itemid AS metric, clock AS time_sec, value_avg AS value FROM trends_uint LIMIT 1`;\n\n////////////////\n// PostgreSQL //\n////////////////\n\nconst itemid_format = 'FM99999999999999999999';\n\nfunction buildPostgresHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction) {\n let time_expression = `clock / ${intervalSec} * ${intervalSec}`;\n let query = `\n SELECT to_char(itemid, '${itemid_format}') AS metric, ${time_expression} AS time, ${aggFunction}(value) AS value\n FROM ${table}\n WHERE itemid IN (${itemids})\n AND clock > ${timeFrom} AND clock < ${timeTill}\n GROUP BY 1, 2\n ORDER BY time ASC\n `;\n return query;\n}\n\nfunction buildPostgresTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn) {\n let time_expression = `clock / ${intervalSec} * ${intervalSec}`;\n let query = `\n SELECT to_char(itemid, '${itemid_format}') AS metric, ${time_expression} AS time, ${aggFunction}(${valueColumn}) AS value\n FROM ${table}\n WHERE itemid IN (${itemids})\n AND clock > ${timeFrom} AND clock < ${timeTill}\n GROUP BY 1, 2\n ORDER BY time ASC\n `;\n return query;\n}\n\nconst TEST_POSTGRES_QUERY = `\n SELECT to_char(itemid, '${itemid_format}') AS metric, clock AS time, value_avg AS value\n FROM trends_uint LIMIT 1\n`;\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/datasource-zabbix/zabbixDBConnector.js"],"names":["ZabbixDBConnectorFactory","datasourceSrv","backendSrv","ZabbixDBConnector","sqlDataSourceId","options","limit","DEFAULT_QUERY_LIMIT","loadSQLDataSource","datasourceId","ds","_","find","getAll","loadDatasource","name","then","sqlDataSourceType","meta","id","Promise","reject","testQuery","TEST_MYSQL_QUERY","TEST_POSTGRES_QUERY","invokeSQLQuery","items","timeFrom","timeTill","intervalMs","consolidateBy","intervalSec","Math","ceil","aggFunction","consolidateByFunc","grouped_items","groupBy","promises","map","value_type","itemids","join","table","HISTORY_TO_TABLE_MAP","dialect","query","buildSQLHistoryQuery","compactSQLQuery","all","flatten","results","TREND_TO_TABLE_MAP","valueColumn","includes","consolidateByTrendColumns","buildSQLTrendsQuery","history","addHostName","convertGrafanaTSResponse","queryDef","refId","format","rawSql","maxDataPoints","datasourceRequest","url","method","data","queries","response","series","time_series","hosts","uniqBy","grafanaSeries","itemid","item","alias","keys","length","host","hostid","datapoints","cloneDeep","points","target","sortBy","replace","buildPostgresHistoryQuery","buildMysqlHistoryQuery","buildPostgresTrendsQuery","buildMysqlTrendsQuery","time_expression","itemid_format","angular","module","factory"],"mappings":";;;;;;;;;;;;;AA+BA;AACA,WAASA,wBAAT,CAAkCC,aAAlC,EAAiDC,UAAjD,EAA6D;AAAA,QAErDC,iBAFqD;AAIzD,iCAAYC,eAAZ,EAA2C;AAAA,YAAdC,OAAc,uEAAJ,EAAI;;AAAA;;AAAA,YACpCC,KADoC,GAC3BD,OAD2B,CACpCC,KADoC;;;AAGzC,aAAKF,eAAL,GAAuBA,eAAvB;AACA,aAAKE,KAAL,GAAaA,SAASC,mBAAtB;;AAEA,aAAKC,iBAAL,CAAuBJ,eAAvB;AACD;;AAED;;;;;;AAbyD;AAAA;AAAA,0CAiBvCK,YAjBuC,EAiBzB;AAAA;;AAC9B,cAAIC,KAAKC,EAAEC,IAAF,CAAOX,cAAcY,MAAd,EAAP,EAA+B,EAAC,MAAMJ,YAAP,EAA/B,CAAT;AACA,cAAIC,EAAJ,EAAQ;AACN,mBAAOT,cAAca,cAAd,CAA6BJ,GAAGK,IAAhC,EACNC,IADM,CACD,cAAM;AACV,oBAAKC,iBAAL,GAAyBP,GAAGQ,IAAH,CAAQC,EAAjC;AACA,qBAAOT,EAAP;AACD,aAJM,CAAP;AAKD,WAND,MAMO;AACL,mBAAOU,QAAQC,MAAR,8BAA0CZ,YAA1C,gBAAP;AACD;AACF;AA5BwD;AAAA;AAAA,4CAiCrC;AAClB,cAAIa,YAAYC,gBAAhB;AACA,cAAI,KAAKN,iBAAL,KAA2B,UAA/B,EAA2C;AACzCK,wBAAYE,mBAAZ;AACD;AACD,iBAAO,KAAKC,cAAL,CAAoBH,SAApB,CAAP;AACD;AAvCwD;AAAA;AAAA,mCAyC9CI,KAzC8C,EAyCvCC,QAzCuC,EAyC7BC,QAzC6B,EAyCnBvB,OAzCmB,EAyCV;AAAA;;AAAA,cACxCwB,UADwC,GACXx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mFG,WAAnF,EAAgGmB,WAAhG,EAA6G;AAC3G,QAAIwC,+BAA6B9D,WAA7B,WAA8CA,WAAlD;AACA,QAAIe,4CACwBgD,aADxB,uBACsDD,eADtD,kBACkF3D,WADlF,SACiGmB,WADjG,6BAEKV,KAFL,+BAGiBF,OAHjB,6BAIcd,QAJd,qBAIsCC,QAJtC,mDAAJ;AAQA,WAAOkB,KAAP;AACD;;;;AA7QMiD,a;;AACApF,O;;;;;;;;;;;;;;;;;;;;;AAEDJ,yB,GAAsB,K;AACtBqC,0B,GAAuB;AAC3B,aAAK,SADsB;AAE3B,aAAK,aAFsB;AAG3B,aAAK,aAHsB;AAI3B,aAAK,cAJsB;AAK3B,aAAK;AALsB,O;AAQvBQ,wB,GAAqB;AACzB,aAAK,QADoB;AAEzB,aAAK;AAFoB,O;AAKrBjB,uB,GAAoB;AACxB,eAAO,KADiB;AAExB,eAAO,KAFiB;AAGxB,eAAO,KAHiB;AAIxB,eAAO,KAJiB;AAKxB,iBAAS;AALe,O;AAQpBoB,+B,GAA4B;AAChC,eAAO,WADyB;AAEhC,eAAO,WAFyB;AAGhC,eAAO;AAHyB,O;AAsIlCwC,cACGC,MADH,CACU,kBADV,EAEGC,OAFH,CAEW,mBAFX,EAEgCjG,wBAFhC,EA8EMuB,gB;AAMAuE,mB,GAAgB,wB;AA4BhBtE,yB,qCACsBsE,a","file":"zabbixDBConnector.js","sourcesContent":["import angular from 'angular';\r\nimport _ from 'lodash';\r\n\r\nconst DEFAULT_QUERY_LIMIT = 10000;\r\nconst HISTORY_TO_TABLE_MAP = {\r\n '0': 'history',\r\n '1': 'history_str',\r\n '2': 'history_log',\r\n '3': 'history_uint',\r\n '4': 'history_text'\r\n};\r\n\r\nconst TREND_TO_TABLE_MAP = {\r\n '0': 'trends',\r\n '3': 'trends_uint'\r\n};\r\n\r\nconst consolidateByFunc = {\r\n 'avg': 'AVG',\r\n 'min': 'MIN',\r\n 'max': 'MAX',\r\n 'sum': 'SUM',\r\n 'count': 'COUNT'\r\n};\r\n\r\nconst consolidateByTrendColumns = {\r\n 'avg': 'value_avg',\r\n 'min': 'value_min',\r\n 'max': 'value_max'\r\n};\r\n\r\n/** @ngInject */\r\nfunction ZabbixDBConnectorFactory(datasourceSrv, backendSrv) {\r\n\r\n class ZabbixDBConnector {\r\n\r\n constructor(sqlDataSourceId, options = {}) {\r\n let {limit} = options;\r\n\r\n this.sqlDataSourceId = sqlDataSourceId;\r\n this.limit = limit || DEFAULT_QUERY_LIMIT;\r\n\r\n this.loadSQLDataSource(sqlDataSourceId);\r\n }\r\n\r\n /**\r\n * Try to load DS with given id to check it's exist.\r\n * @param {*} datasourceId ID of SQL data source\r\n */\r\n loadSQLDataSource(datasourceId) {\r\n let ds = _.find(datasourceSrv.getAll(), {'id': datasourceId});\r\n if (ds) {\r\n return datasourceSrv.loadDatasource(ds.name)\r\n .then(ds => {\r\n this.sqlDataSourceType = ds.meta.id;\r\n return ds;\r\n });\r\n } else {\r\n return Promise.reject(`SQL Data Source with ID ${datasourceId} not found`);\r\n }\r\n }\r\n\r\n /**\r\n * Try to invoke test query for one of Zabbix database tables.\r\n */\r\n testSQLDataSource() {\r\n let testQuery = TEST_MYSQL_QUERY;\r\n if (this.sqlDataSourceType === 'postgres') {\r\n testQuery = TEST_POSTGRES_QUERY;\r\n }\r\n return this.invokeSQLQuery(testQuery);\r\n }\r\n\r\n getHistory(items, timeFrom, timeTill, options) {\r\n let {intervalMs, consolidateBy} = options;\r\n let intervalSec = Math.ceil(intervalMs / 1000);\r\n\r\n consolidateBy = consolidateBy || 'avg';\r\n let aggFunction = consolidateByFunc[consolidateBy];\r\n\r\n // Group items by value type and perform request for each value type\r\n let grouped_items = _.groupBy(items, 'value_type');\r\n let promises = _.map(grouped_items, (items, value_type) => {\r\n let itemids = _.map(items, 'itemid').join(', ');\r\n let table = HISTORY_TO_TABLE_MAP[value_type];\r\n\r\n let dialect = this.sqlDataSourceType;\r\n let query = buildSQLHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, dialect);\r\n\r\n query = compactSQLQuery(query);\r\n return this.invokeSQLQuery(query);\r\n });\r\n\r\n return Promise.all(promises).then(results => {\r\n return _.flatten(results);\r\n });\r\n }\r\n\r\n getTrends(items, timeFrom, timeTill, options) {\r\n let {intervalMs, consolidateBy} = options;\r\n let intervalSec = Math.ceil(intervalMs / 1000);\r\n\r\n consolidateBy = consolidateBy || 'avg';\r\n let aggFunction = consolidateByFunc[consolidateBy];\r\n\r\n // Group items by value type and perform request for each value type\r\n let grouped_items = _.groupBy(items, 'value_type');\r\n let promises = _.map(grouped_items, (items, value_type) => {\r\n let itemids = _.map(items, 'itemid').join(', ');\r\n let table = TREND_TO_TABLE_MAP[value_type];\r\n let valueColumn = _.includes(['avg', 'min', 'max'], consolidateBy) ? consolidateBy : 'avg';\r\n valueColumn = consolidateByTrendColumns[valueColumn];\r\n\r\n let dialect = this.sqlDataSourceType;\r\n let query = buildSQLTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn, dialect);\r\n\r\n query = compactSQLQuery(query);\r\n return this.invokeSQLQuery(query);\r\n });\r\n\r\n return Promise.all(promises).then(results => {\r\n return _.flatten(results);\r\n });\r\n }\r\n\r\n handleGrafanaTSResponse(history, items, addHostName = true) {\r\n return convertGrafanaTSResponse(history, items, addHostName);\r\n }\r\n\r\n invokeSQLQuery(query) {\r\n let queryDef = {\r\n refId: 'A',\r\n format: 'time_series',\r\n datasourceId: this.sqlDataSourceId,\r\n rawSql: query,\r\n maxDataPoints: this.limit\r\n };\r\n\r\n return backendSrv.datasourceRequest({\r\n url: '/api/tsdb/query',\r\n method: 'POST',\r\n data: {\r\n queries: [queryDef],\r\n }\r\n })\r\n .then(response => {\r\n let results = response.data.results;\r\n if (results['A']) {\r\n return results['A'].series;\r\n } else {\r\n return null;\r\n }\r\n });\r\n }\r\n }\r\n\r\n return ZabbixDBConnector;\r\n}\r\n\r\nangular\r\n .module('grafana.services')\r\n .factory('ZabbixDBConnector', ZabbixDBConnectorFactory);\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\nfunction convertGrafanaTSResponse(time_series, items, addHostName) {\r\n var hosts = _.uniqBy(_.flatten(_.map(items, 'hosts')), 'hostid'); //uniqBy is needed to deduplicate\r\n let grafanaSeries = _.map(time_series, series => {\r\n let itemid = series.name;\r\n var item = _.find(items, {'itemid': itemid});\r\n var alias = item.name;\r\n if (_.keys(hosts).length > 1 && addHostName) { //only when actual multi hosts selected\r\n var host = _.find(hosts, {'hostid': item.hostid});\r\n alias = host.name + \": \" + alias;\r\n }\r\n // zabbixCachingProxy deduplicates requests and returns one time series for equal queries.\r\n // Clone is needed to prevent changing of series object shared between all targets.\r\n let datapoints = _.cloneDeep(series.points);\r\n return {\r\n target: alias,\r\n datapoints: datapoints\r\n };\r\n });\r\n\r\n return _.sortBy(grafanaSeries, 'target');\r\n}\r\n\r\nfunction compactSQLQuery(query) {\r\n return query.replace(/\\s+/g, ' ');\r\n}\r\n\r\nfunction buildSQLHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, dialect = 'mysql') {\r\n if (dialect === 'postgres') {\r\n return buildPostgresHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction);\r\n } else {\r\n return buildMysqlHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction);\r\n }\r\n}\r\n\r\nfunction buildSQLTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn, dialect = 'mysql') {\r\n if (dialect === 'postgres') {\r\n return buildPostgresTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn);\r\n } else {\r\n return buildMysqlTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn);\r\n }\r\n}\r\n\r\n///////////\r\n// MySQL //\r\n///////////\r\n\r\nfunction buildMysqlHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction) {\r\n let time_expression = `clock DIV ${intervalSec} * ${intervalSec}`;\r\n let query = `\r\n SELECT itemid AS metric, ${time_expression} AS time_sec, ${aggFunction}(value) AS value\r\n FROM ${table}\r\n WHERE itemid IN (${itemids})\r\n AND clock > ${timeFrom} AND clock < ${timeTill}\r\n GROUP BY ${time_expression}, metric\r\n ORDER BY time_sec ASC\r\n `;\r\n return query;\r\n}\r\n\r\nfunction buildMysqlTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn) {\r\n let time_expression = `clock DIV ${intervalSec} * ${intervalSec}`;\r\n let query = `\r\n SELECT itemid AS metric, ${time_expression} AS time_sec, ${aggFunction}(${valueColumn}) AS value\r\n FROM ${table}\r\n WHERE itemid IN (${itemids})\r\n AND clock > ${timeFrom} AND clock < ${timeTill}\r\n GROUP BY ${time_expression}, metric\r\n ORDER BY time_sec ASC\r\n `;\r\n return query;\r\n}\r\n\r\nconst TEST_MYSQL_QUERY = `SELECT itemid AS metric, clock AS time_sec, value_avg AS value FROM trends_uint LIMIT 1`;\r\n\r\n////////////////\r\n// PostgreSQL //\r\n////////////////\r\n\r\nconst itemid_format = 'FM99999999999999999999';\r\n\r\nfunction buildPostgresHistoryQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction) {\r\n let time_expression = `clock / ${intervalSec} * ${intervalSec}`;\r\n let query = `\r\n SELECT to_char(itemid, '${itemid_format}') AS metric, ${time_expression} AS time, ${aggFunction}(value) AS value\r\n FROM ${table}\r\n WHERE itemid IN (${itemids})\r\n AND clock > ${timeFrom} AND clock < ${timeTill}\r\n GROUP BY 1, 2\r\n ORDER BY time ASC\r\n `;\r\n return query;\r\n}\r\n\r\nfunction buildPostgresTrendsQuery(itemids, table, timeFrom, timeTill, intervalSec, aggFunction, valueColumn) {\r\n let time_expression = `clock / ${intervalSec} * ${intervalSec}`;\r\n let query = `\r\n SELECT to_char(itemid, '${itemid_format}') AS metric, ${time_expression} AS time, ${aggFunction}(${valueColumn}) AS value\r\n FROM ${table}\r\n WHERE itemid IN (${itemids})\r\n AND clock > ${timeFrom} AND clock < ${timeTill}\r\n GROUP BY 1, 2\r\n ORDER BY time ASC\r\n `;\r\n return query;\r\n}\r\n\r\nconst TEST_POSTGRES_QUERY = `\r\n SELECT to_char(itemid, '${itemid_format}') AS metric, clock AS time, value_avg AS value\r\n FROM trends_uint LIMIT 1\r\n`;\r\n"]} \ No newline at end of file diff --git a/dist/img/zabbix_app_logo.svg b/dist/img/zabbix_app_logo.svg index 237247d8b..87950ba1b 100644 --- a/dist/img/zabbix_app_logo.svg +++ b/dist/img/zabbix_app_logo.svg @@ -1,107 +1,107 @@ - - - -image/svg+xml + + +image/svg+xml \ No newline at end of file diff --git a/dist/module.js.map b/dist/module.js.map index 372f38fd4..38f8f1170 100644 --- a/dist/module.js.map +++ b/dist/module.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/module.js"],"names":["ZabbixAppConfigCtrl","loadPluginCss","dark","light"],"mappings":";;;;;;;;AAAQA,yB,qBAAAA,mB;;AACAC,mB,kBAAAA,a;;;;AAERA,oBAAc;AACZC,cAAM,gEADM;AAEZC,eAAO;AAFK,OAAd;;4BAMEH,mB","file":"module.js","sourcesContent":["import {ZabbixAppConfigCtrl} from './components/config';\nimport {loadPluginCss} from 'app/plugins/sdk';\n\nloadPluginCss({\n dark: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.dark.css',\n light: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.light.css'\n});\n\nexport {\n ZabbixAppConfigCtrl as ConfigCtrl\n};\n"]} \ No newline at end of file +{"version":3,"sources":["../src/module.js"],"names":["ZabbixAppConfigCtrl","loadPluginCss","dark","light"],"mappings":";;;;;;;;AAAQA,yB,qBAAAA,mB;;AACAC,mB,kBAAAA,a;;;;AAERA,oBAAc;AACZC,cAAM,gEADM;AAEZC,eAAO;AAFK,OAAd;;4BAMEH,mB","file":"module.js","sourcesContent":["import {ZabbixAppConfigCtrl} from './components/config';\r\nimport {loadPluginCss} from 'app/plugins/sdk';\r\n\r\nloadPluginCss({\r\n dark: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.dark.css',\r\n light: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.light.css'\r\n});\r\n\r\nexport {\r\n ZabbixAppConfigCtrl as ConfigCtrl\r\n};\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/ack-tooltip.directive.js.map b/dist/panel-triggers/ack-tooltip.directive.js.map index 781c9fc02..c519b34e7 100644 --- a/dist/panel-triggers/ack-tooltip.directive.js.map +++ b/dist/panel-triggers/ack-tooltip.directive.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/ack-tooltip.directive.js"],"names":["angular","$","System","config","paths","tether","getConfig","baseURL","Drop","amdRequire","drop","module","directive","$sanitize","$compile","buttonTemplate","scope","ack","trigger","onAck","context","link","element","acknowledges","$button","appendTo","click","tooltip","length","time","user","message","addAckButtonTemplate","target","content","position","classes","openOn","hoverCloseDelay","tetherOptions","constraints","to","pin","attachment","open","on","closeDrop","onAddAckButtonClick","inputTemplate","$input","$addAckButton","replaceWith","onAckCancelButtonClick","onAckSendlButtonClick","value","bind","then","setTimeout","destroy","err","console","log","contents"],"mappings":";;;;;;;;AAAOA,a;;AACAC,O;;;;AAEPC,aAAOC,MAAP,CAAc;AACZC,eAAO;AACLC,kBAAQH,OAAOI,SAAP,GAAmBC,OAAnB,GAA6B;AADhC;AADK,OAAd;;AAMIC,U;;AACJN,aAAOO,UAAP,CAAkB,CAAC,2DAAD,CAAlB,EAAiF,UAACC,IAAD,EAAU;AACzFF,eAAOE,IAAP;AACD,OAFD;;AAIA;AACAV,cACGW,MADH,CACU,oBADV,EAEGC,SAFH,CAEa,YAFb,EAE2B,UAASC,SAAT,EAAoBC,QAApB,EAA8B;AACrD,YAAIC,iBAAiB,uEACC,eADD,GAEG,kDAFH,GAGG,oDAHH,GAIC,aAJtB;;AAMA,eAAO;AACLC,iBAAO;AACLC,iBAAK,GADA;AAELC,qBAAS,GAFJ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A6B9C,KAA7B;AACD;AApGI,SAAP;AAsGD,OA/GH","file":"ack-tooltip.directive.js","sourcesContent":["import angular from 'angular';\nimport $ from 'jquery';\n\nSystem.config({\n paths: {\n tether: System.getConfig().baseURL + \"plugins/alexanderzobnin-zabbix-app/vendor/npm/tether.min.js\"\n }\n});\n\nlet Drop;\nSystem.amdRequire([\"plugins/alexanderzobnin-zabbix-app/vendor/npm/drop.min.js\"], (drop) => {\n Drop = drop;\n});\n\n/** @ngInject */\nangular\n .module('grafana.directives')\n .directive('ackTooltip', function($sanitize, $compile) {\n let buttonTemplate = '';\n\n return {\n scope: {\n ack: \"=\",\n trigger: \"=\",\n onAck: \"=\",\n context: \"=\"\n },\n link: function(scope, element) {\n let acknowledges = scope.ack;\n let $button = $(buttonTemplate);\n $button.appendTo(element);\n\n $button.click(function() {\n let tooltip = '
';\n\n if (acknowledges && acknowledges.length) {\n tooltip += '' +\n '' +\n '' +\n '' +\n '';\n for (let ack of acknowledges) {\n tooltip += '' +\n '' +\n '';\n }\n tooltip += '
TimeUserComments
' + ack.time + '' + ack.user + '' + ack.message + '
';\n } else {\n tooltip += 'Add acknowledge';\n }\n\n let addAckButtonTemplate = '
' +\n '
';\n tooltip += addAckButtonTemplate;\n tooltip += '
';\n\n let drop = new Drop({\n target: element[0],\n content: tooltip,\n position: \"bottom left\",\n classes: 'drop-popover ack-tooltip',\n openOn: 'hover',\n hoverCloseDelay: 500,\n tetherOptions: {\n constraints: [{to: 'window', pin: true, attachment: \"both\"}]\n }\n });\n\n drop.open();\n drop.on('close', closeDrop);\n\n $('#add-acknowledge-btn').on('click', onAddAckButtonClick);\n\n function onAddAckButtonClick() {\n let inputTemplate = '
' +\n '' +\n '' +\n '
';\n\n let $input = $(inputTemplate);\n let $addAckButton = $('.ack-tooltip .ack-add-button');\n $addAckButton.replaceWith($input);\n $('.ack-tooltip #cancel-ack-button').on('click', onAckCancelButtonClick);\n $('.ack-tooltip #send-ack-button').on('click', onAckSendlButtonClick);\n }\n\n function onAckCancelButtonClick() {\n $('.ack-tooltip .ack-input-group').replaceWith(addAckButtonTemplate);\n $('#add-acknowledge-btn').on('click', onAddAckButtonClick);\n }\n\n function onAckSendlButtonClick() {\n let message = $('.ack-tooltip #ack-message')[0].value;\n let onAck = scope.onAck.bind(scope.context);\n onAck(scope.trigger, message).then(() => {\n closeDrop();\n });\n }\n\n function closeDrop() {\n setTimeout(function() {\n try {\n drop.destroy();\n } catch (err) {\n console.log('drop.destroy() error: ', err.message);\n }\n });\n }\n\n });\n\n $compile(element.contents())(scope);\n }\n };\n });\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/ack-tooltip.directive.js"],"names":["angular","$","System","config","paths","tether","getConfig","baseURL","Drop","amdRequire","drop","module","directive","$sanitize","$compile","buttonTemplate","scope","ack","trigger","onAck","context","link","element","acknowledges","$button","appendTo","click","tooltip","length","time","user","message","addAckButtonTemplate","target","content","position","classes","openOn","hoverCloseDelay","tetherOptions","constraints","to","pin","attachment","open","on","closeDrop","onAddAckButtonClick","inputTemplate","$input","$addAckButton","replaceWith","onAckCancelButtonClick","onAckSendlButtonClick","value","bind","then","setTimeout","destroy","err","console","log","contents"],"mappings":";;;;;;;;AAAOA,a;;AACAC,O;;;;AAEPC,aAAOC,MAAP,CAAc;AACZC,eAAO;AACLC,kBAAQH,OAAOI,SAAP,GAAmBC,OAAnB,GAA6B;AADhC;AADK,OAAd;;AAMIC,U;;AACJN,aAAOO,UAAP,CAAkB,CAAC,2DAAD,CAAlB,EAAiF,UAACC,IAAD,EAAU;AACzFF,eAAOE,IAAP;AACD,OAFD;;AAIA;AACAV,cACGW,MADH,CACU,oBADV,EAEGC,SAFH,CAEa,YAFb,EAE2B,UAASC,SAAT,EAAoBC,QAApB,EAA8B;AACrD,YAAIC,iBAAiB,uEACC,eADD,GAEG,kDAFH,GAGG,oDAHH,GAIC,aAJtB;;AAMA,eAAO;AACLC,iBAAO;AACLC,iBAAK,GADA;AAELC,qBAAS,GAFJ;AAG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,KAA7B;AACD;AApGI,SAAP;AAsGD,OA/GH","file":"ack-tooltip.directive.js","sourcesContent":["import angular from 'angular';\r\nimport $ from 'jquery';\r\n\r\nSystem.config({\r\n paths: {\r\n tether: System.getConfig().baseURL + \"plugins/alexanderzobnin-zabbix-app/vendor/npm/tether.min.js\"\r\n }\r\n});\r\n\r\nlet Drop;\r\nSystem.amdRequire([\"plugins/alexanderzobnin-zabbix-app/vendor/npm/drop.min.js\"], (drop) => {\r\n Drop = drop;\r\n});\r\n\r\n/** @ngInject */\r\nangular\r\n .module('grafana.directives')\r\n .directive('ackTooltip', function($sanitize, $compile) {\r\n let buttonTemplate = '';\r\n\r\n return {\r\n scope: {\r\n ack: \"=\",\r\n trigger: \"=\",\r\n onAck: \"=\",\r\n context: \"=\"\r\n },\r\n link: function(scope, element) {\r\n let acknowledges = scope.ack;\r\n let $button = $(buttonTemplate);\r\n $button.appendTo(element);\r\n\r\n $button.click(function() {\r\n let tooltip = '
';\r\n\r\n if (acknowledges && acknowledges.length) {\r\n tooltip += '' +\r\n '' +\r\n '' +\r\n '' +\r\n '';\r\n for (let ack of acknowledges) {\r\n tooltip += '' +\r\n '' +\r\n '';\r\n }\r\n tooltip += '
TimeUserComments
' + ack.time + '' + ack.user + '' + ack.message + '
';\r\n } else {\r\n tooltip += 'Add acknowledge';\r\n }\r\n\r\n let addAckButtonTemplate = '
' +\r\n '
';\r\n tooltip += addAckButtonTemplate;\r\n tooltip += '
';\r\n\r\n let drop = new Drop({\r\n target: element[0],\r\n content: tooltip,\r\n position: \"bottom left\",\r\n classes: 'drop-popover ack-tooltip',\r\n openOn: 'hover',\r\n hoverCloseDelay: 500,\r\n tetherOptions: {\r\n constraints: [{to: 'window', pin: true, attachment: \"both\"}]\r\n }\r\n });\r\n\r\n drop.open();\r\n drop.on('close', closeDrop);\r\n\r\n $('#add-acknowledge-btn').on('click', onAddAckButtonClick);\r\n\r\n function onAddAckButtonClick() {\r\n let inputTemplate = '
' +\r\n '' +\r\n '' +\r\n '
';\r\n\r\n let $input = $(inputTemplate);\r\n let $addAckButton = $('.ack-tooltip .ack-add-button');\r\n $addAckButton.replaceWith($input);\r\n $('.ack-tooltip #cancel-ack-button').on('click', onAckCancelButtonClick);\r\n $('.ack-tooltip #send-ack-button').on('click', onAckSendlButtonClick);\r\n }\r\n\r\n function onAckCancelButtonClick() {\r\n $('.ack-tooltip .ack-input-group').replaceWith(addAckButtonTemplate);\r\n $('#add-acknowledge-btn').on('click', onAddAckButtonClick);\r\n }\r\n\r\n function onAckSendlButtonClick() {\r\n let message = $('.ack-tooltip #ack-message')[0].value;\r\n let onAck = scope.onAck.bind(scope.context);\r\n onAck(scope.trigger, message).then(() => {\r\n closeDrop();\r\n });\r\n }\r\n\r\n function closeDrop() {\r\n setTimeout(function() {\r\n try {\r\n drop.destroy();\r\n } catch (err) {\r\n console.log('drop.destroy() error: ', err.message);\r\n }\r\n });\r\n }\r\n\r\n });\r\n\r\n $compile(element.contents())(scope);\r\n }\r\n };\r\n });\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/datasource-selector.directive.js.map b/dist/panel-triggers/datasource-selector.directive.js.map index 06599c0bc..cbf9d5c87 100644 --- a/dist/panel-triggers/datasource-selector.directive.js.map +++ b/dist/panel-triggers/datasource-selector.directive.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/datasource-selector.directive.js"],"names":["angular","_","template","module","directive","scope","datasources","options","onChange","controller","DatasourceSelectorCtrl","controllerAs","$scope","dsOptions","multi","current","value","text","join","map","ds","selected","includes","updatedOptions","newDataSources","$$postDigest"],"mappings":";;;;;;;;;;;;;;;AAAOA,a;;AACAC,O;;;;;;;;;;;;;;;;;;;;;AAEDC,c;;;AAKNF,cACCG,MADD,CACQ,oBADR,EAECC,SAFD,CAEW,oBAFX,EAEiC,YAAM;AACrC,eAAO;AACLC,iBAAO;AACLC,yBAAa,GADR;AAELC,qBAAS,GAFJ;AAGLC,sBAAU;AAHL,WADF;AAMLC,sBAAYC,sBANP;AAOLC,wBAAc,MAPT;AAQLT,oBAAUA;AARL,SAAP;AAUD,OAbD;;AAeMQ,4B;;AAEJ;AACA,wCAAYE,MAAZ,EAAoB;AAAA;;AAClB,eAAKP,KAAL,GAAaO,MAAb;AACA,cAAIN,cAAcM,OAAON,WAAzB;AACA,cAAIC,UAAUK,OAAOL,OAArB;AACA,eAAKM,SAAL,GAAiB;AACfC,mBAAO,IADQ;AAEfC,qBAAS,EAACC,OAAOV,WAAR,EAAqBW,MAAMX,YAAYY,IAAZ,CAAiB,KAAjB,CAA3B,EAFM;AAGfX,qBAASN,EAAEkB,GAAF,CAAMZ,OAAN,EAAe,UAACa,EAAD,EAAQ;AAC9B,qBAAO,EAACH,MAAMG,EAAP,EAAWJ,OAAOI,EAAlB,EAAsBC,UAAUpB,EAAEqB,QAAF,CAAWhB,WAAX,EAAwBc,EAAxB,CAAhC,EAAP;AACD,aAFQ;AAHM,WAAjB;AAOD;;;;mCAEQG,c,EAAgB;AAAA;;AACvB,gBAAIC,iBAAiBD,eAAeR,OAAf,CAAuBC,KAA5C;AACA,iBAAKX,KAAL,CAAWC,WAAX,GAAyBkB,cAAzB;;AAEA;AACA,iBAAKnB,KAAL,CAAWoB,YAAX,CAAwB,YAAM;AAC5B,oBAAKpB,KAAL,CAAWG,QAAX;AACD,aAFD;AAGD","file":"datasource-selector.directive.js","sourcesContent":["import angular from 'angular';\nimport _ from 'lodash';\n\nconst template = `\n\n\n`;\n\nangular\n.module('grafana.directives')\n.directive('datasourceSelector', () => {\n return {\n scope: {\n datasources: \"=\",\n options: \"=\",\n onChange: \"&\"\n },\n controller: DatasourceSelectorCtrl,\n controllerAs: 'ctrl',\n template: template\n };\n});\n\nclass DatasourceSelectorCtrl {\n\n /** @ngInject */\n constructor($scope) {\n this.scope = $scope;\n let datasources = $scope.datasources;\n let options = $scope.options;\n this.dsOptions = {\n multi: true,\n current: {value: datasources, text: datasources.join(\" + \")},\n options: _.map(options, (ds) => {\n return {text: ds, value: ds, selected: _.includes(datasources, ds)};\n })\n };\n }\n\n onChange(updatedOptions) {\n let newDataSources = updatedOptions.current.value;\n this.scope.datasources = newDataSources;\n\n // Run after model was changed\n this.scope.$$postDigest(() => {\n this.scope.onChange();\n });\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/datasource-selector.directive.js"],"names":["angular","_","template","module","directive","scope","datasources","options","onChange","controller","DatasourceSelectorCtrl","controllerAs","$scope","dsOptions","multi","current","value","text","join","map","ds","selected","includes","updatedOptions","newDataSources","$$postDigest"],"mappings":";;;;;;;;;;;;;;;AAAOA,a;;AACAC,O;;;;;;;;;;;;;;;;;;;;;AAEDC,c;;;AAKNF,cACCG,MADD,CACQ,oBADR,EAECC,SAFD,CAEW,oBAFX,EAEiC,YAAM;AACrC,eAAO;AACLC,iBAAO;AACLC,yBAAa,GADR;AAELC,qBAAS,GAFJ;AAGLC,sBAAU;AAHL,WADF;AAMLC,sBAAYC,sBANP;AAOLC,wBAAc,MAPT;AAQLT,oBAAUA;AARL,SAAP;AAUD,OAbD;;AAeMQ,4B;;AAEJ;AACA,wCAAYE,MAAZ,EAAoB;AAAA;;AAClB,eAAKP,KAAL,GAAaO,MAAb;AACA,cAAIN,cAAcM,OAAON,WAAzB;AACA,cAAIC,UAAUK,OAAOL,OAArB;AACA,eAAKM,SAAL,GAAiB;AACfC,mBAAO,IADQ;AAEfC,qBAAS,EAACC,OAAOV,WAAR,EAAqBW,MAAMX,YAAYY,IAAZ,CAAiB,KAAjB,CAA3B,EAFM;AAGfX,qBAASN,EAAEkB,GAAF,CAAMZ,OAAN,EAAe,UAACa,EAAD,EAAQ;AAC9B,qBAAO,EAACH,MAAMG,EAAP,EAAWJ,OAAOI,EAAlB,EAAsBC,UAAUpB,EAAEqB,QAAF,CAAWhB,WAAX,EAAwBc,EAAxB,CAAhC,EAAP;AACD,aAFQ;AAHM,WAAjB;AAOD;;;;mCAEQG,c,EAAgB;AAAA;;AACvB,gBAAIC,iBAAiBD,eAAeR,OAAf,CAAuBC,KAA5C;AACA,iBAAKX,KAAL,CAAWC,WAAX,GAAyBkB,cAAzB;;AAEA;AACA,iBAAKnB,KAAL,CAAWoB,YAAX,CAAwB,YAAM;AAC5B,oBAAKpB,KAAL,CAAWG,QAAX;AACD,aAFD;AAGD","file":"datasource-selector.directive.js","sourcesContent":["import angular from 'angular';\r\nimport _ from 'lodash';\r\n\r\nconst template = `\r\n\r\n\r\n`;\r\n\r\nangular\r\n.module('grafana.directives')\r\n.directive('datasourceSelector', () => {\r\n return {\r\n scope: {\r\n datasources: \"=\",\r\n options: \"=\",\r\n onChange: \"&\"\r\n },\r\n controller: DatasourceSelectorCtrl,\r\n controllerAs: 'ctrl',\r\n template: template\r\n };\r\n});\r\n\r\nclass DatasourceSelectorCtrl {\r\n\r\n /** @ngInject */\r\n constructor($scope) {\r\n this.scope = $scope;\r\n let datasources = $scope.datasources;\r\n let options = $scope.options;\r\n this.dsOptions = {\r\n multi: true,\r\n current: {value: datasources, text: datasources.join(\" + \")},\r\n options: _.map(options, (ds) => {\r\n return {text: ds, value: ds, selected: _.includes(datasources, ds)};\r\n })\r\n };\r\n }\r\n\r\n onChange(updatedOptions) {\r\n let newDataSources = updatedOptions.current.value;\r\n this.scope.datasources = newDataSources;\r\n\r\n // Run after model was changed\r\n this.scope.$$postDigest(() => {\r\n this.scope.onChange();\r\n });\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/migrations.js.map b/dist/panel-triggers/migrations.js.map index 6acd33aa2..fb7ddb622 100644 --- a/dist/panel-triggers/migrations.js.map +++ b/dist/panel-triggers/migrations.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/migrations.js"],"names":["migratePanelSchema","panel","isEmptyPanel","schemaVersion","getSchemaVersion","CURRENT_SCHEMA_VERSION","datasources","datasource","targets","triggers","lastChangeField","ageField","infoField","scroll","hideHostsInMaintenance","_","isEmpty","each","target","defaultsDeep","DEFAULT_TARGET"],"mappings":";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;wCAGKf,sB,GAAyB,C","file":"migrations.js","sourcesContent":["import _ from 'lodash';\nimport {DEFAULT_TARGET} from './triggers_panel_ctrl';\n\n// Actual schema version\nexport const CURRENT_SCHEMA_VERSION = 4;\n\nexport function migratePanelSchema(panel) {\n if (isEmptyPanel(panel)) {\n return panel;\n }\n\n const schemaVersion = getSchemaVersion(panel);\n panel.schemaVersion = CURRENT_SCHEMA_VERSION;\n\n if (schemaVersion < 2) {\n panel.datasources = [panel.datasource];\n panel.targets = {};\n panel.targets[panel.datasources[0]] = panel.triggers;\n\n // delete old props\n delete panel.triggers;\n delete panel.datasource;\n }\n\n if (schemaVersion < 3) {\n // delete old props\n delete panel.lastChangeField;\n delete panel.ageField;\n delete panel.infoField;\n delete panel.scroll;\n delete panel.hideHostsInMaintenance;\n }\n\n if (schemaVersion < 4) {\n if (panel.targets && !_.isEmpty(panel.targets)) {\n _.each(panel.targets, (target) => {\n _.defaultsDeep(target, DEFAULT_TARGET);\n });\n }\n }\n\n return panel;\n}\n\nfunction getSchemaVersion(panel) {\n return panel.schemaVersion || 1;\n}\n\nfunction isEmptyPanel(panel) {\n return !panel.datasource && !panel.datasources && !panel.triggers && !panel.targets;\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/migrations.js"],"names":["migratePanelSchema","panel","isEmptyPanel","schemaVersion","getSchemaVersion","CURRENT_SCHEMA_VERSION","datasources","datasource","targets","triggers","lastChangeField","ageField","infoField","scroll","hideHostsInMaintenance","_","isEmpty","each","target","defaultsDeep","DEFAULT_TARGET"],"mappings":";;;;;;;AAMO,WAASA,kBAAT,CAA4BC,KAA5B,EAAmC;AACxC,QAAIC,aAAaD,KAAb,CAAJ,EAAyB;AACvB,aAAOA,KAAP;AACD;;AAED,QAAME,gBAAgBC,iBAAiBH,KAAjB,CAAtB;AACAA,UAAME,aAAN,GAAsBE,sBAAtB;;AAEA,QAAIF,gBAAgB,CAApB,EAAuB;AACrBF,YAAMK,WAAN,GAAoB,CAACL,MAAMM,UAAP,CAApB;AACAN,YAAMO,OAAN,GAAgB,EAAhB;AACAP,YAAMO,OAAN,CAAcP,MAAMK,WAAN,CAAkB,CAAlB,CAAd,IAAsCL,MAAMQ,QAA5C;;AAEA;AACA,aAAOR,MAAMQ,QAAb;AACA,aAAOR,MAAMM,UAAb;AACD;;AAED,QAAIJ,gBAAgB,CAApB,EAAuB;AACrB;AACA,aAAOF,MAAMS,eAAb;AACA,aAAOT,MAAMU,QAAb;AACA,aAAOV,MAAMW,SAAb;AACA,aAAOX,MAAMY,MAAb;AACA,aAAOZ,MAAMa,sBAAb;AACD;;AAED,QAAIX,gBAAgB,CAApB,EAAuB;AACrB,UAAIF,MAAMO,OAAN,IAAiB,CAACO,EAAEC,OAAF,CAAUf,MAAMO,OAAhB,CAAtB,EAAgD;AAC9CO,UAAEE,IAAF,CAAOhB,MAAMO,OAAb,EAAsB,UAACU,MAAD,EAAY;AAChCH,YAAEI,YAAF,CAAeD,MAAf,EAAuBE,cAAvB;AACD,SAFD;AAGD;AACF;;AAED,WAAOnB,KAAP;AACD;;gCApCeD,kB;;AAsChB,WAASI,gBAAT,CAA0BH,KAA1B,EAAiC;AAC/B,WAAOA,MAAME,aAAN,IAAuB,CAA9B;AACD;;AAED,WAASD,YAAT,CAAsBD,KAAtB,EAA6B;AAC3B,WAAO,CAACA,MAAMM,UAAP,IAAqB,CAACN,MAAMK,WAA5B,IAA2C,CAACL,MAAMQ,QAAlD,IAA8D,CAACR,MAAMO,OAA5E;AACD;;;AAlDMO,O;;AACCK,oB,wBAAAA,c;;;wCAGKf,sB,GAAyB,C","file":"migrations.js","sourcesContent":["import _ from 'lodash';\r\nimport {DEFAULT_TARGET} from './triggers_panel_ctrl';\r\n\r\n// Actual schema version\r\nexport const CURRENT_SCHEMA_VERSION = 4;\r\n\r\nexport function migratePanelSchema(panel) {\r\n if (isEmptyPanel(panel)) {\r\n return panel;\r\n }\r\n\r\n const schemaVersion = getSchemaVersion(panel);\r\n panel.schemaVersion = CURRENT_SCHEMA_VERSION;\r\n\r\n if (schemaVersion < 2) {\r\n panel.datasources = [panel.datasource];\r\n panel.targets = {};\r\n panel.targets[panel.datasources[0]] = panel.triggers;\r\n\r\n // delete old props\r\n delete panel.triggers;\r\n delete panel.datasource;\r\n }\r\n\r\n if (schemaVersion < 3) {\r\n // delete old props\r\n delete panel.lastChangeField;\r\n delete panel.ageField;\r\n delete panel.infoField;\r\n delete panel.scroll;\r\n delete panel.hideHostsInMaintenance;\r\n }\r\n\r\n if (schemaVersion < 4) {\r\n if (panel.targets && !_.isEmpty(panel.targets)) {\r\n _.each(panel.targets, (target) => {\r\n _.defaultsDeep(target, DEFAULT_TARGET);\r\n });\r\n }\r\n }\r\n\r\n return panel;\r\n}\r\n\r\nfunction getSchemaVersion(panel) {\r\n return panel.schemaVersion || 1;\r\n}\r\n\r\nfunction isEmptyPanel(panel) {\r\n return !panel.datasource && !panel.datasources && !panel.triggers && !panel.targets;\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/module.js b/dist/panel-triggers/module.js index bed75f4c3..bed2c3936 100644 --- a/dist/panel-triggers/module.js +++ b/dist/panel-triggers/module.js @@ -11,17 +11,17 @@ System.register(['./triggers_panel_ctrl', 'app/plugins/sdk', './datasource-selec loadPluginCss = _appPluginsSdk.loadPluginCss; }, function (_datasourceSelectorDirective) {}, function (_ackTooltipDirective) {}], execute: function () { - /** - * Grafana-Zabbix - * Zabbix plugin for Grafana. - * http://github.com/alexanderzobnin/grafana-zabbix - * - * Trigger panel. - * This feature sponsored by CORE IT - * http://www.coreit.fr - * - * Copyright 2015 Alexander Zobnin alexanderzobnin@gmail.com - * Licensed under the Apache License, Version 2.0 + /** + * Grafana-Zabbix + * Zabbix plugin for Grafana. + * http://github.com/alexanderzobnin/grafana-zabbix + * + * Trigger panel. + * This feature sponsored by CORE IT + * http://www.coreit.fr + * + * Copyright 2015 Alexander Zobnin alexanderzobnin@gmail.com + * Licensed under the Apache License, Version 2.0 */ loadPluginCss({ diff --git a/dist/panel-triggers/module.js.map b/dist/panel-triggers/module.js.map index a82ed2186..1fd669da0 100644 --- a/dist/panel-triggers/module.js.map +++ b/dist/panel-triggers/module.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/module.js"],"names":["TriggerPanelCtrl","loadPluginCss","dark","light"],"mappings":";;;;;;;;AAaQA,sB,wBAAAA,gB;;AACAC,mB,kBAAAA,a;;;AAdR;;;;;;;;;;;;;AAkBAA,oBAAc;AACZC,cAAM,gEADM;AAEZC,eAAO;AAFK,OAAd;;2BAMEH,gB","file":"module.js","sourcesContent":["/**\n * Grafana-Zabbix\n * Zabbix plugin for Grafana.\n * http://github.com/alexanderzobnin/grafana-zabbix\n *\n * Trigger panel.\n * This feature sponsored by CORE IT\n * http://www.coreit.fr\n *\n * Copyright 2015 Alexander Zobnin alexanderzobnin@gmail.com\n * Licensed under the Apache License, Version 2.0\n */\n\nimport {TriggerPanelCtrl} from './triggers_panel_ctrl';\nimport {loadPluginCss} from 'app/plugins/sdk';\nimport './datasource-selector.directive';\nimport './ack-tooltip.directive';\n\nloadPluginCss({\n dark: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.dark.css',\n light: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.light.css'\n});\n\nexport {\n TriggerPanelCtrl as PanelCtrl\n};\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/module.js"],"names":["TriggerPanelCtrl","loadPluginCss","dark","light"],"mappings":";;;;;;;;AAaQA,sB,wBAAAA,gB;;AACAC,mB,kBAAAA,a;;;AAdR;;;;;;;;;;;;;AAkBAA,oBAAc;AACZC,cAAM,gEADM;AAEZC,eAAO;AAFK,OAAd;;2BAMEH,gB","file":"module.js","sourcesContent":["/**\r\n * Grafana-Zabbix\r\n * Zabbix plugin for Grafana.\r\n * http://github.com/alexanderzobnin/grafana-zabbix\r\n *\r\n * Trigger panel.\r\n * This feature sponsored by CORE IT\r\n * http://www.coreit.fr\r\n *\r\n * Copyright 2015 Alexander Zobnin alexanderzobnin@gmail.com\r\n * Licensed under the Apache License, Version 2.0\r\n */\r\n\r\nimport {TriggerPanelCtrl} from './triggers_panel_ctrl';\r\nimport {loadPluginCss} from 'app/plugins/sdk';\r\nimport './datasource-selector.directive';\r\nimport './ack-tooltip.directive';\r\n\r\nloadPluginCss({\r\n dark: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.dark.css',\r\n light: 'plugins/alexanderzobnin-zabbix-app/css/grafana-zabbix.light.css'\r\n});\r\n\r\nexport {\r\n TriggerPanelCtrl as PanelCtrl\r\n};\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/options_tab.js.map b/dist/panel-triggers/options_tab.js.map index f7387089a..a53e1fcb7 100644 --- a/dist/panel-triggers/options_tab.js.map +++ b/dist/panel-triggers/options_tab.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/options_tab.js"],"names":["triggerPanelOptionsTab","restrict","scope","templateUrl","controller","TriggerPanelOptionsCtrl","$scope","editor","panelCtrl","ctrl","panel","fontSizes","ackFilters","sortByFields","text","value","showEventsFields"],"mappings":";;;;;;;;;;;;;AAuCO,WAASA,sBAAT,GAAkC;AACvC,WAAO;AACLC,gBAAU,GADL;AAELC,aAAO,IAFF;AAGLC,mBAAa,oFAHR;AAILC,kBAAYC;AAJP,KAAP;AAMD;;oCAPeL,sB;;;;;AA1BVK,6B;;AAEJ;AACA,uCAAYC,MAAZ,EAAoB;AAAA;;AAClBA,eAAOC,MAAP,GAAgB,IAAhB;AACA,aAAKC,SAAL,GAAiBF,OAAOG,IAAxB;AACA,aAAKC,KAAL,GAAa,KAAKF,SAAL,CAAeE,KAA5B;;AAEA,aAAKC,SAAL,GAAiB,CAAC,KAAD,EAAQ,KAAR,EAAe,MAAf,EAAuB,MAAvB,EAA+B,MAA/B,EAAuC,MAAvC,EAA+C,MAA/C,EAAuD,MAAvD,EAA+D,MAA/D,EAAuE,MAAvE,EAA+E,MAA/E,EAAuF,MAAvF,CAAjB;AACA,aAAKC,UAAL,GAAkB,CAChB,cADgB,EAEhB,gBAFgB,EAGhB,cAHgB,CAAlB;AAKA,aAAKC,YAAL,GAAoB,CAClB,EAAEC,MAAM,aAAR,EAAwBC,OAAO,YAA/B,EADkB,EAElB,EAAED,MAAM,UAAR,EAAwBC,OAAO,UAA/B,EAFkB,CAApB;AAIA,aAAKC,gBAAL,GAAwB,CACtB,EAAEF,MAAM,KAAR,EAAmBC,OAAO,CAAC,CAAD,EAAG,CAAH,CAA1B,EADsB,EAEtB,EAAED,MAAM,IAAR,EAAmBC,OAAO,CAAC,CAAD,CAA1B,EAFsB,EAGtB,EAAED,MAAM,UAAR,EAAoBC,OAAO,CAA3B,EAHsB,CAAxB;AAKD,O","file":"options_tab.js","sourcesContent":["/**\n * Grafana-Zabbix\n * Zabbix plugin for Grafana.\n * http://github.com/alexanderzobnin/grafana-zabbix\n *\n * Trigger panel.\n * This feature sponsored by CORE IT\n * http://www.coreit.fr\n *\n * Copyright 2015 Alexander Zobnin alexanderzobnin@gmail.com\n * Licensed under the Apache License, Version 2.0\n */\n\nclass TriggerPanelOptionsCtrl {\n\n /** @ngInject */\n constructor($scope) {\n $scope.editor = this;\n this.panelCtrl = $scope.ctrl;\n this.panel = this.panelCtrl.panel;\n\n this.fontSizes = ['80%', '90%', '100%', '110%', '120%', '130%', '150%', '160%', '180%', '200%', '220%', '250%'];\n this.ackFilters = [\n 'all triggers',\n 'unacknowledged',\n 'acknowledged'\n ];\n this.sortByFields = [\n { text: 'last change', value: 'lastchange' },\n { text: 'severity', value: 'priority' }\n ];\n this.showEventsFields = [\n { text: 'All', value: [0,1] },\n { text: 'OK', value: [0] },\n { text: 'Problems', value: 1 }\n ];\n }\n}\n\nexport function triggerPanelOptionsTab() {\n return {\n restrict: 'E',\n scope: true,\n templateUrl: 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/options_tab.html',\n controller: TriggerPanelOptionsCtrl,\n };\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/options_tab.js"],"names":["triggerPanelOptionsTab","restrict","scope","templateUrl","controller","TriggerPanelOptionsCtrl","$scope","editor","panelCtrl","ctrl","panel","fontSizes","ackFilters","sortByFields","text","value","showEventsFields"],"mappings":";;;;;;;;;;;;;AAuCO,WAASA,sBAAT,GAAkC;AACvC,WAAO;AACLC,gBAAU,GADL;AAELC,aAAO,IAFF;AAGLC,mBAAa,oFAHR;AAILC,kBAAYC;AAJP,KAAP;AAMD;;oCAPeL,sB;;;;;AA1BVK,6B;;AAEJ;AACA,uCAAYC,MAAZ,EAAoB;AAAA;;AAClBA,eAAOC,MAAP,GAAgB,IAAhB;AACA,aAAKC,SAAL,GAAiBF,OAAOG,IAAxB;AACA,aAAKC,KAAL,GAAa,KAAKF,SAAL,CAAeE,KAA5B;;AAEA,aAAKC,SAAL,GAAiB,CAAC,KAAD,EAAQ,KAAR,EAAe,MAAf,EAAuB,MAAvB,EAA+B,MAA/B,EAAuC,MAAvC,EAA+C,MAA/C,EAAuD,MAAvD,EAA+D,MAA/D,EAAuE,MAAvE,EAA+E,MAA/E,EAAuF,MAAvF,CAAjB;AACA,aAAKC,UAAL,GAAkB,CAChB,cADgB,EAEhB,gBAFgB,EAGhB,cAHgB,CAAlB;AAKA,aAAKC,YAAL,GAAoB,CAClB,EAAEC,MAAM,aAAR,EAAwBC,OAAO,YAA/B,EADkB,EAElB,EAAED,MAAM,UAAR,EAAwBC,OAAO,UAA/B,EAFkB,CAApB;AAIA,aAAKC,gBAAL,GAAwB,CACtB,EAAEF,MAAM,KAAR,EAAmBC,OAAO,CAAC,CAAD,EAAG,CAAH,CAA1B,EADsB,EAEtB,EAAED,MAAM,IAAR,EAAmBC,OAAO,CAAC,CAAD,CAA1B,EAFsB,EAGtB,EAAED,MAAM,UAAR,EAAoBC,OAAO,CAA3B,EAHsB,CAAxB;AAKD,O","file":"options_tab.js","sourcesContent":["/**\r\n * Grafana-Zabbix\r\n * Zabbix plugin for Grafana.\r\n * http://github.com/alexanderzobnin/grafana-zabbix\r\n *\r\n * Trigger panel.\r\n * This feature sponsored by CORE IT\r\n * http://www.coreit.fr\r\n *\r\n * Copyright 2015 Alexander Zobnin alexanderzobnin@gmail.com\r\n * Licensed under the Apache License, Version 2.0\r\n */\r\n\r\nclass TriggerPanelOptionsCtrl {\r\n\r\n /** @ngInject */\r\n constructor($scope) {\r\n $scope.editor = this;\r\n this.panelCtrl = $scope.ctrl;\r\n this.panel = this.panelCtrl.panel;\r\n\r\n this.fontSizes = ['80%', '90%', '100%', '110%', '120%', '130%', '150%', '160%', '180%', '200%', '220%', '250%'];\r\n this.ackFilters = [\r\n 'all triggers',\r\n 'unacknowledged',\r\n 'acknowledged'\r\n ];\r\n this.sortByFields = [\r\n { text: 'last change', value: 'lastchange' },\r\n { text: 'severity', value: 'priority' }\r\n ];\r\n this.showEventsFields = [\r\n { text: 'All', value: [0,1] },\r\n { text: 'OK', value: [0] },\r\n { text: 'Problems', value: 1 }\r\n ];\r\n }\r\n}\r\n\r\nexport function triggerPanelOptionsTab() {\r\n return {\r\n restrict: 'E',\r\n scope: true,\r\n templateUrl: 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/options_tab.html',\r\n controller: TriggerPanelOptionsCtrl,\r\n };\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/partials/module.html b/dist/panel-triggers/partials/module.html index ae779255b..8723c50bc 100644 --- a/dist/panel-triggers/partials/module.html +++ b/dist/panel-triggers/partials/module.html @@ -1,97 +1,97 @@ -
-
-
-
    - -
  1. - - -
    - -
    - -
    -
    - -

    - {{trigger.description}} - - - {{ ctrl.formatHostName(trigger) }} - - - {{ ctrl.formatHostGroups(trigger) }} - - - - - {{tag.tag}}: {{tag.value}} - - -

    - -
    - - {{ctrl.triggerStatusMap[trigger.value]}} - - - {{trigger.severity}} - - - {{trigger.age && "for " + trigger.age}} - - - -
    - - -
    - - -
    - -
    -
    - - -
    - - - {{trigger.datasource}} - -
    - -
    - {{trigger.lastchange || "last change unknown"}} - -
    - - - - - - - - - - -
    -
    -
  2. -
-
-
-
- - +
+
+
+
    + +
  1. + + +
    + +
    + +
    +
    + +

    + {{trigger.description}} + + + {{ ctrl.formatHostName(trigger) }} + + + {{ ctrl.formatHostGroups(trigger) }} + + + + + {{tag.tag}}: {{tag.value}} + + +

    + +
    + + {{ctrl.triggerStatusMap[trigger.value]}} + + + {{trigger.severity}} + + + {{trigger.age && "for " + trigger.age}} + + + +
    + + +
    + + +
    + +
    +
    + + +
    + + + {{trigger.datasource}} + +
    + +
    + {{trigger.lastchange || "last change unknown"}} + +
    + + + + + + + + + + +
    +
    +
  2. +
+
+
+
+ + diff --git a/dist/panel-triggers/partials/options_tab.html b/dist/panel-triggers/partials/options_tab.html index 72b695aac..6c4c2d874 100644 --- a/dist/panel-triggers/partials/options_tab.html +++ b/dist/panel-triggers/partials/options_tab.html @@ -1,223 +1,223 @@ -
-
-
Show fields
- - - - - - - - - - - - - - - - -
- -
-
Options
- - -
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- - -
-
- -
-
View options
-
- -
- -
-
-
- - -
- - - - -
- - -
- - - -
- -
-
Triggers severity and colors
-
-
- - - - - - -
- - -
- -
-
- - - - - - -
- - -
-
-
- - - - - - -
-
-
-
+
+
+
Show fields
+ + + + + + + + + + + + + + + + +
+ +
+
Options
+ + +
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ + +
+
+ +
+
View options
+
+ +
+ +
+
+
+ + +
+ + + + +
+ + +
+ + + +
+ +
+
Triggers severity and colors
+
+
+ + + + + + +
+ + +
+ +
+
+ + + + + + +
+ + +
+
+
+ + + + + + +
+
+
+
diff --git a/dist/panel-triggers/partials/triggers_tab.html b/dist/panel-triggers/partials/triggers_tab.html index 8af4f0924..3f011ff73 100644 --- a/dist/panel-triggers/partials/triggers_tab.html +++ b/dist/panel-triggers/partials/triggers_tab.html @@ -1,90 +1,90 @@ -
-
-
-
- -
-
- - -
-
-
-
- -
-
-
{{ ds }}
-
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
- - -
-
-
-
+
+
+
+
+ +
+
+ + +
+
+
+
+ +
+
+
{{ ds }}
+
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+
+
diff --git a/dist/panel-triggers/plugin.json b/dist/panel-triggers/plugin.json index d4c3ef80d..57e68c2ac 100644 --- a/dist/panel-triggers/plugin.json +++ b/dist/panel-triggers/plugin.json @@ -1,12 +1,12 @@ -{ - "type": "panel", - "name": "Zabbix Triggers", - "id": "alexanderzobnin-zabbix-triggers-panel", - - "info": { - "author": { - "name": "Alexander Zobnin", - "url": "https://github.com/alexanderzobnin/grafana-zabbix" - } - } -} +{ + "type": "panel", + "name": "Zabbix Triggers", + "id": "alexanderzobnin-zabbix-triggers-panel", + + "info": { + "author": { + "name": "Alexander Zobnin", + "url": "https://github.com/alexanderzobnin/grafana-zabbix" + } + } +} diff --git a/dist/panel-triggers/specs/migrations.spec.js b/dist/panel-triggers/specs/migrations.spec.js index b5c05411f..274743974 100644 --- a/dist/panel-triggers/specs/migrations.spec.js +++ b/dist/panel-triggers/specs/migrations.spec.js @@ -1,77 +1,77 @@ -import _ from 'lodash'; -import {TriggerPanelCtrl} from '../triggers_panel_ctrl'; -import {DEFAULT_TARGET, DEFAULT_SEVERITY, PANEL_DEFAULTS} from '../triggers_panel_ctrl'; -import {CURRENT_SCHEMA_VERSION} from '../migrations'; - -describe('Triggers Panel schema migration', () => { - let ctx = {}; - let datasourceSrvMock = { - getMetricSources: () => { - return [{ meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix_default' }]; - }, - get: () => Promise.resolve({}) - }; - - let timeoutMock = () => {}; - - beforeEach(() => { - ctx = { - scope: { - panel: { - datasource: 'zabbix', - triggers: DEFAULT_TARGET, - hostField: true, - statusField: false, - severityField: false, - lastChangeField: true, - ageField: true, - infoField: true, - limit: 10, - showTriggers: 'all triggers', - hideHostsInMaintenance: false, - sortTriggersBy: { text: 'last change', value: 'lastchange' }, - showEvents: { text: 'Problems', value: '1' }, - triggerSeverity: DEFAULT_SEVERITY, - okEventColor: 'rgba(0, 245, 153, 0.45)', - ackEventColor: 'rgba(0, 0, 0, 0)', - scroll: true, - pageSize: 10, - fontSize: '100%', - } - } - }; - }); - - it('should update old panel schema', () => { - let updatedPanelCtrl = new TriggerPanelCtrl(ctx.scope, {}, timeoutMock, datasourceSrvMock, {}, {}, {}); - - let expected = _.defaultsDeep({ - schemaVersion: CURRENT_SCHEMA_VERSION, - datasources: ['zabbix'], - targets: { - 'zabbix': DEFAULT_TARGET - }, - statusField: false, - severityField: false, - limit: 10, - okEventColor: 'rgba(0, 245, 153, 0.45)', - ackEventColor: 'rgba(0, 0, 0, 0)' - }, PANEL_DEFAULTS); - - expect(updatedPanelCtrl.panel).toEqual(expected); - }); - - it('should create new panel with default schema', () => { - ctx.scope.panel = {}; - let updatedPanelCtrl = new TriggerPanelCtrl(ctx.scope, {}, {}, datasourceSrvMock, {}, {}, {}); - - let expected = _.defaultsDeep({ - schemaVersion: CURRENT_SCHEMA_VERSION, - datasources: ['zabbix_default'], - targets: { - 'zabbix_default': DEFAULT_TARGET - } - }, PANEL_DEFAULTS); - expect(updatedPanelCtrl.panel).toEqual(expected); - }); -}); +import _ from 'lodash'; +import {TriggerPanelCtrl} from '../triggers_panel_ctrl'; +import {DEFAULT_TARGET, DEFAULT_SEVERITY, PANEL_DEFAULTS} from '../triggers_panel_ctrl'; +import {CURRENT_SCHEMA_VERSION} from '../migrations'; + +describe('Triggers Panel schema migration', () => { + let ctx = {}; + let datasourceSrvMock = { + getMetricSources: () => { + return [{ meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix_default' }]; + }, + get: () => Promise.resolve({}) + }; + + let timeoutMock = () => {}; + + beforeEach(() => { + ctx = { + scope: { + panel: { + datasource: 'zabbix', + triggers: DEFAULT_TARGET, + hostField: true, + statusField: false, + severityField: false, + lastChangeField: true, + ageField: true, + infoField: true, + limit: 10, + showTriggers: 'all triggers', + hideHostsInMaintenance: false, + sortTriggersBy: { text: 'last change', value: 'lastchange' }, + showEvents: { text: 'Problems', value: '1' }, + triggerSeverity: DEFAULT_SEVERITY, + okEventColor: 'rgba(0, 245, 153, 0.45)', + ackEventColor: 'rgba(0, 0, 0, 0)', + scroll: true, + pageSize: 10, + fontSize: '100%', + } + } + }; + }); + + it('should update old panel schema', () => { + let updatedPanelCtrl = new TriggerPanelCtrl(ctx.scope, {}, timeoutMock, datasourceSrvMock, {}, {}, {}); + + let expected = _.defaultsDeep({ + schemaVersion: CURRENT_SCHEMA_VERSION, + datasources: ['zabbix'], + targets: { + 'zabbix': DEFAULT_TARGET + }, + statusField: false, + severityField: false, + limit: 10, + okEventColor: 'rgba(0, 245, 153, 0.45)', + ackEventColor: 'rgba(0, 0, 0, 0)' + }, PANEL_DEFAULTS); + + expect(updatedPanelCtrl.panel).toEqual(expected); + }); + + it('should create new panel with default schema', () => { + ctx.scope.panel = {}; + let updatedPanelCtrl = new TriggerPanelCtrl(ctx.scope, {}, {}, datasourceSrvMock, {}, {}, {}); + + let expected = _.defaultsDeep({ + schemaVersion: CURRENT_SCHEMA_VERSION, + datasources: ['zabbix_default'], + targets: { + 'zabbix_default': DEFAULT_TARGET + } + }, PANEL_DEFAULTS); + expect(updatedPanelCtrl.panel).toEqual(expected); + }); +}); diff --git a/dist/panel-triggers/specs/panel_ctrl.spec.js b/dist/panel-triggers/specs/panel_ctrl.spec.js index 72cae5ce0..313671dd6 100644 --- a/dist/panel-triggers/specs/panel_ctrl.spec.js +++ b/dist/panel-triggers/specs/panel_ctrl.spec.js @@ -1,283 +1,283 @@ -import _ from 'lodash'; -import {TriggerPanelCtrl} from '../triggers_panel_ctrl'; -import {PANEL_DEFAULTS, DEFAULT_TARGET} from '../triggers_panel_ctrl'; -// import { create } from 'domain'; - -describe('TriggerPanelCtrl', () => { - let ctx = {}; - let datasourceSrvMock, zabbixDSMock; - let timeoutMock = () => {}; - let createPanelCtrl; - - beforeEach(() => { - ctx = {scope: {panel: PANEL_DEFAULTS}}; - zabbixDSMock = { - replaceTemplateVars: () => {}, - zabbix: { - getTriggers: jest.fn().mockReturnValue([generateTrigger("1"), generateTrigger("1")]), - getAcknowledges: jest.fn().mockReturnValue(Promise.resolve([])) - } - }; - - datasourceSrvMock = { - getMetricSources: () => { - return [ - { meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix_default' }, - { meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix' }, - { meta: {id: 'graphite'}, value: {}, name: 'graphite' }, - ]; - }, - get: () => Promise.resolve(zabbixDSMock) - }; - createPanelCtrl = () => new TriggerPanelCtrl(ctx.scope, {}, timeoutMock, datasourceSrvMock, {}, {}, {}); - - const getTriggersResp = [ - [ - createTrigger({ - triggerid: "1", lastchange: "1510000010", priority: 5, lastEvent: {eventid: "11"}, hosts: [{maintenance_status: '1'}] - }), - createTrigger({ - triggerid: "2", lastchange: "1510000040", priority: 3, lastEvent: {eventid: "12"} - }), - ], - [ - createTrigger({triggerid: "3", lastchange: "1510000020", priority: 4, lastEvent: {eventid: "13"}}), - createTrigger({triggerid: "4", lastchange: "1510000030", priority: 2, lastEvent: {eventid: "14"}}), - ] - ]; - - // Simulate 2 data sources - zabbixDSMock.zabbix.getTriggers = jest.fn() - .mockReturnValueOnce(getTriggersResp[0]) - .mockReturnValueOnce(getTriggersResp[1]); - zabbixDSMock.zabbix.getAcknowledges = jest.fn() - .mockReturnValue(Promise.resolve([defaultEvent])); - - ctx.panelCtrl = createPanelCtrl(); - }); - - describe('When adding new panel', () => { - it('should suggest all zabbix data sources', () => { - ctx.scope.panel = {}; - let panelCtrl = createPanelCtrl(); - expect(panelCtrl.available_datasources).toEqual([ - 'zabbix_default', 'zabbix' - ]); - }); - - it('should load first zabbix data source as default', () => { - ctx.scope.panel = {}; - let panelCtrl = createPanelCtrl(); - expect(panelCtrl.panel.datasources).toEqual([ - 'zabbix_default' - ]); - }); - }); - - describe('When refreshing panel', () => { - beforeEach(() => { - ctx.scope.panel.datasources = ['zabbix_default', 'zabbix']; - ctx.scope.panel.targets = { - 'zabbix_default': DEFAULT_TARGET, - 'zabbix': DEFAULT_TARGET - }; - ctx.panelCtrl = createPanelCtrl(); - }); - - it('should format triggers', (done) => { - ctx.panelCtrl.onRefresh().then(() => { - let formattedTrigger = _.find(ctx.panelCtrl.triggerList, {triggerid: "1"}); - expect(formattedTrigger.host).toBe('backend01'); - expect(formattedTrigger.hostTechName).toBe('backend01_tech'); - expect(formattedTrigger.datasource).toBe('zabbix_default'); - expect(formattedTrigger.severity).toBe('Disaster'); - expect(formattedTrigger.maintenance).toBe(true); - expect(formattedTrigger.age).toBeTruthy(); - expect(formattedTrigger.lastchange).toBeTruthy(); - done(); - }); - }); - - it('should sort triggers by time by default', (done) => { - ctx.panelCtrl.onRefresh().then(() => { - let trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid'); - expect(trigger_ids).toEqual([ - '2', '4', '3', '1' - ]); - done(); - }); - }); - - it('should sort triggers by severity', (done) => { - ctx.panelCtrl.panel.sortTriggersBy = { text: 'severity', value: 'priority' }; - ctx.panelCtrl.onRefresh().then(() => { - let trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid'); - expect(trigger_ids).toEqual([ - '1', '3', '2', '4' - ]); - done(); - }); - }); - - it('should add acknowledges to trigger', (done) => { - ctx.panelCtrl.onRefresh().then(() => { - let trigger = getTriggerById(1, ctx); - expect(trigger.acknowledges).toHaveLength(1); - expect(trigger.acknowledges[0].message).toBe("event ack"); - - expect(getTriggerById(2, ctx).acknowledges).toBe(undefined); - expect(getTriggerById(3, ctx).acknowledges).toBe(undefined); - expect(getTriggerById(4, ctx).acknowledges).toBe(undefined); - done(); - }); - }); - }); - - describe('When formatting triggers', () => { - beforeEach(() => { - ctx.panelCtrl = createPanelCtrl(); - }); - - it('should handle new lines in trigger description', () => { - ctx.panelCtrl.setTriggerSeverity = jest.fn((trigger) => trigger); - let trigger = {comments: "this is\ndescription"}; - const formattedTrigger = ctx.panelCtrl.formatTrigger(trigger); - expect(formattedTrigger.comments).toBe("this is
description"); - }); - - it('should format host name to display (default)', (done) => { - ctx.panelCtrl.onRefresh().then(() => { - let trigger = getTriggerById(1, ctx); - let hostname = ctx.panelCtrl.formatHostName(trigger); - expect(hostname).toBe('backend01'); - done(); - }); - }); - - it('should format host name to display (tech name)', (done) => { - ctx.panelCtrl.panel.hostField = false; - ctx.panelCtrl.panel.hostTechNameField = true; - ctx.panelCtrl.onRefresh().then(() => { - let trigger = getTriggerById(1, ctx); - let hostname = ctx.panelCtrl.formatHostName(trigger); - expect(hostname).toBe('backend01_tech'); - done(); - }); - }); - - it('should format host name to display (both tech and visible)', (done) => { - ctx.panelCtrl.panel.hostField = true; - ctx.panelCtrl.panel.hostTechNameField = true; - ctx.panelCtrl.onRefresh().then(() => { - let trigger = getTriggerById(1, ctx); - let hostname = ctx.panelCtrl.formatHostName(trigger); - expect(hostname).toBe('backend01 (backend01_tech)'); - done(); - }); - }); - - it('should hide hostname if both visible and tech name checkboxes unset', (done) => { - ctx.panelCtrl.panel.hostField = false; - ctx.panelCtrl.panel.hostTechNameField = false; - ctx.panelCtrl.onRefresh().then(() => { - let trigger = getTriggerById(1, ctx); - let hostname = ctx.panelCtrl.formatHostName(trigger); - expect(hostname).toBe(""); - done(); - }); - }); - }); - - describe('When formatting acknowledges', () => { - beforeEach(() => { - ctx.panelCtrl = createPanelCtrl(); - }); - - it('should build proper user name', () => { - const ack = { - alias: 'alias', name: 'name', surname: 'surname' - }; - - const formatted = ctx.panelCtrl.formatAcknowledge(ack); - expect(formatted.user).toBe('alias (name surname)'); - }); - - it('should return empty name if it is not defined', () => { - const formatted = ctx.panelCtrl.formatAcknowledge({}); - expect(formatted.user).toBe(''); - }); - }); -}); - -const defaultTrigger = { - "triggerid": "13565", - "value": "1", - "groups": [{"groupid": "1", "name": "Backend"}] , - "hosts": [{"host": "backend01_tech", "hostid": "10001","maintenance_status": "0", "name": "backend01"}] , - "lastEvent": { - "eventid": "11", - "clock": "1507229064", - "ns": "556202037", - "acknowledged": "1", - "value": "1", - "object": "0", - "source": "0", - "objectid": "13565", - }, - "tags": [] , - "lastchange": "1440259530", - "priority": "2", - "description": "Lack of free swap space on server", - "comments": "It probably means that the systems requires\nmore physical memory.", - "url": "https://host.local/path", - "templateid": "0", "expression": "{13174}<50", "manual_close": "0", "correlation_mode": "0", - "correlation_tag": "", "recovery_mode": "0", "recovery_expression": "", "state": "0", "status": "0", - "flags": "0", "type": "0", "items": [] , "error": "" -}; - -const defaultEvent = { - "eventid": "11", - "acknowledges": [ - { - "acknowledgeid": "185", - "action": "0", - "alias": "api", - "clock": "1512382246", - "eventid": "11", - "message": "event ack", - "name": "api", - "surname": "user", - "userid": "3" - } - ], - "clock": "1507229064", - "ns": "556202037", - "acknowledged": "1", - "value": "1", - "object": "0", - "source": "0", - "objectid": "1", -}; - -function generateTrigger(id, timestamp, severity) { - let trigger = _.cloneDeep(defaultTrigger); - trigger.triggerid = id.toString(); - if (severity) { - trigger.priority = severity.toString(); - } - if (timestamp) { - trigger.lastchange = timestamp; - } - return trigger; -} - -function createTrigger(props) { - let trigger = _.cloneDeep(defaultTrigger); - trigger = _.merge(trigger, props); - trigger.lastEvent.objectid = trigger.triggerid; - return trigger; -} - -function getTriggerById(id, ctx) { - return _.find(ctx.panelCtrl.triggerList, {triggerid: id.toString()}); -} +import _ from 'lodash'; +import {TriggerPanelCtrl} from '../triggers_panel_ctrl'; +import {PANEL_DEFAULTS, DEFAULT_TARGET} from '../triggers_panel_ctrl'; +// import { create } from 'domain'; + +describe('TriggerPanelCtrl', () => { + let ctx = {}; + let datasourceSrvMock, zabbixDSMock; + let timeoutMock = () => {}; + let createPanelCtrl; + + beforeEach(() => { + ctx = {scope: {panel: PANEL_DEFAULTS}}; + zabbixDSMock = { + replaceTemplateVars: () => {}, + zabbix: { + getTriggers: jest.fn().mockReturnValue([generateTrigger("1"), generateTrigger("1")]), + getAcknowledges: jest.fn().mockReturnValue(Promise.resolve([])) + } + }; + + datasourceSrvMock = { + getMetricSources: () => { + return [ + { meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix_default' }, + { meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix' }, + { meta: {id: 'graphite'}, value: {}, name: 'graphite' }, + ]; + }, + get: () => Promise.resolve(zabbixDSMock) + }; + createPanelCtrl = () => new TriggerPanelCtrl(ctx.scope, {}, timeoutMock, datasourceSrvMock, {}, {}, {}); + + const getTriggersResp = [ + [ + createTrigger({ + triggerid: "1", lastchange: "1510000010", priority: 5, lastEvent: {eventid: "11"}, hosts: [{maintenance_status: '1'}] + }), + createTrigger({ + triggerid: "2", lastchange: "1510000040", priority: 3, lastEvent: {eventid: "12"} + }), + ], + [ + createTrigger({triggerid: "3", lastchange: "1510000020", priority: 4, lastEvent: {eventid: "13"}}), + createTrigger({triggerid: "4", lastchange: "1510000030", priority: 2, lastEvent: {eventid: "14"}}), + ] + ]; + + // Simulate 2 data sources + zabbixDSMock.zabbix.getTriggers = jest.fn() + .mockReturnValueOnce(getTriggersResp[0]) + .mockReturnValueOnce(getTriggersResp[1]); + zabbixDSMock.zabbix.getAcknowledges = jest.fn() + .mockReturnValue(Promise.resolve([defaultEvent])); + + ctx.panelCtrl = createPanelCtrl(); + }); + + describe('When adding new panel', () => { + it('should suggest all zabbix data sources', () => { + ctx.scope.panel = {}; + let panelCtrl = createPanelCtrl(); + expect(panelCtrl.available_datasources).toEqual([ + 'zabbix_default', 'zabbix' + ]); + }); + + it('should load first zabbix data source as default', () => { + ctx.scope.panel = {}; + let panelCtrl = createPanelCtrl(); + expect(panelCtrl.panel.datasources).toEqual([ + 'zabbix_default' + ]); + }); + }); + + describe('When refreshing panel', () => { + beforeEach(() => { + ctx.scope.panel.datasources = ['zabbix_default', 'zabbix']; + ctx.scope.panel.targets = { + 'zabbix_default': DEFAULT_TARGET, + 'zabbix': DEFAULT_TARGET + }; + ctx.panelCtrl = createPanelCtrl(); + }); + + it('should format triggers', (done) => { + ctx.panelCtrl.onRefresh().then(() => { + let formattedTrigger = _.find(ctx.panelCtrl.triggerList, {triggerid: "1"}); + expect(formattedTrigger.host).toBe('backend01'); + expect(formattedTrigger.hostTechName).toBe('backend01_tech'); + expect(formattedTrigger.datasource).toBe('zabbix_default'); + expect(formattedTrigger.severity).toBe('Disaster'); + expect(formattedTrigger.maintenance).toBe(true); + expect(formattedTrigger.age).toBeTruthy(); + expect(formattedTrigger.lastchange).toBeTruthy(); + done(); + }); + }); + + it('should sort triggers by time by default', (done) => { + ctx.panelCtrl.onRefresh().then(() => { + let trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid'); + expect(trigger_ids).toEqual([ + '2', '4', '3', '1' + ]); + done(); + }); + }); + + it('should sort triggers by severity', (done) => { + ctx.panelCtrl.panel.sortTriggersBy = { text: 'severity', value: 'priority' }; + ctx.panelCtrl.onRefresh().then(() => { + let trigger_ids = _.map(ctx.panelCtrl.triggerList, 'triggerid'); + expect(trigger_ids).toEqual([ + '1', '3', '2', '4' + ]); + done(); + }); + }); + + it('should add acknowledges to trigger', (done) => { + ctx.panelCtrl.onRefresh().then(() => { + let trigger = getTriggerById(1, ctx); + expect(trigger.acknowledges).toHaveLength(1); + expect(trigger.acknowledges[0].message).toBe("event ack"); + + expect(getTriggerById(2, ctx).acknowledges).toBe(undefined); + expect(getTriggerById(3, ctx).acknowledges).toBe(undefined); + expect(getTriggerById(4, ctx).acknowledges).toBe(undefined); + done(); + }); + }); + }); + + describe('When formatting triggers', () => { + beforeEach(() => { + ctx.panelCtrl = createPanelCtrl(); + }); + + it('should handle new lines in trigger description', () => { + ctx.panelCtrl.setTriggerSeverity = jest.fn((trigger) => trigger); + let trigger = {comments: "this is\ndescription"}; + const formattedTrigger = ctx.panelCtrl.formatTrigger(trigger); + expect(formattedTrigger.comments).toBe("this is
description"); + }); + + it('should format host name to display (default)', (done) => { + ctx.panelCtrl.onRefresh().then(() => { + let trigger = getTriggerById(1, ctx); + let hostname = ctx.panelCtrl.formatHostName(trigger); + expect(hostname).toBe('backend01'); + done(); + }); + }); + + it('should format host name to display (tech name)', (done) => { + ctx.panelCtrl.panel.hostField = false; + ctx.panelCtrl.panel.hostTechNameField = true; + ctx.panelCtrl.onRefresh().then(() => { + let trigger = getTriggerById(1, ctx); + let hostname = ctx.panelCtrl.formatHostName(trigger); + expect(hostname).toBe('backend01_tech'); + done(); + }); + }); + + it('should format host name to display (both tech and visible)', (done) => { + ctx.panelCtrl.panel.hostField = true; + ctx.panelCtrl.panel.hostTechNameField = true; + ctx.panelCtrl.onRefresh().then(() => { + let trigger = getTriggerById(1, ctx); + let hostname = ctx.panelCtrl.formatHostName(trigger); + expect(hostname).toBe('backend01 (backend01_tech)'); + done(); + }); + }); + + it('should hide hostname if both visible and tech name checkboxes unset', (done) => { + ctx.panelCtrl.panel.hostField = false; + ctx.panelCtrl.panel.hostTechNameField = false; + ctx.panelCtrl.onRefresh().then(() => { + let trigger = getTriggerById(1, ctx); + let hostname = ctx.panelCtrl.formatHostName(trigger); + expect(hostname).toBe(""); + done(); + }); + }); + }); + + describe('When formatting acknowledges', () => { + beforeEach(() => { + ctx.panelCtrl = createPanelCtrl(); + }); + + it('should build proper user name', () => { + const ack = { + alias: 'alias', name: 'name', surname: 'surname' + }; + + const formatted = ctx.panelCtrl.formatAcknowledge(ack); + expect(formatted.user).toBe('alias (name surname)'); + }); + + it('should return empty name if it is not defined', () => { + const formatted = ctx.panelCtrl.formatAcknowledge({}); + expect(formatted.user).toBe(''); + }); + }); +}); + +const defaultTrigger = { + "triggerid": "13565", + "value": "1", + "groups": [{"groupid": "1", "name": "Backend"}] , + "hosts": [{"host": "backend01_tech", "hostid": "10001","maintenance_status": "0", "name": "backend01"}] , + "lastEvent": { + "eventid": "11", + "clock": "1507229064", + "ns": "556202037", + "acknowledged": "1", + "value": "1", + "object": "0", + "source": "0", + "objectid": "13565", + }, + "tags": [] , + "lastchange": "1440259530", + "priority": "2", + "description": "Lack of free swap space on server", + "comments": "It probably means that the systems requires\nmore physical memory.", + "url": "https://host.local/path", + "templateid": "0", "expression": "{13174}<50", "manual_close": "0", "correlation_mode": "0", + "correlation_tag": "", "recovery_mode": "0", "recovery_expression": "", "state": "0", "status": "0", + "flags": "0", "type": "0", "items": [] , "error": "" +}; + +const defaultEvent = { + "eventid": "11", + "acknowledges": [ + { + "acknowledgeid": "185", + "action": "0", + "alias": "api", + "clock": "1512382246", + "eventid": "11", + "message": "event ack", + "name": "api", + "surname": "user", + "userid": "3" + } + ], + "clock": "1507229064", + "ns": "556202037", + "acknowledged": "1", + "value": "1", + "object": "0", + "source": "0", + "objectid": "1", +}; + +function generateTrigger(id, timestamp, severity) { + let trigger = _.cloneDeep(defaultTrigger); + trigger.triggerid = id.toString(); + if (severity) { + trigger.priority = severity.toString(); + } + if (timestamp) { + trigger.lastchange = timestamp; + } + return trigger; +} + +function createTrigger(props) { + let trigger = _.cloneDeep(defaultTrigger); + trigger = _.merge(trigger, props); + trigger.lastEvent.objectid = trigger.triggerid; + return trigger; +} + +function getTriggerById(id, ctx) { + return _.find(ctx.panelCtrl.triggerList, {triggerid: id.toString()}); +} diff --git a/dist/panel-triggers/triggers_panel_ctrl.js.map b/dist/panel-triggers/triggers_panel_ctrl.js.map index 5fea90a50..31e9ce95c 100644 --- a/dist/panel-triggers/triggers_panel_ctrl.js.map +++ b/dist/panel-triggers/triggers_panel_ctrl.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/triggers_panel_ctrl.js"],"names":["filterTriggers","triggers","triggerFilter","utils","isRegex","_","filter","trigger","buildRegex","test","description","$","moment","PanelCtrl","triggerPanelOptionsTab","triggerPanelTriggersTab","migratePanelSchema","CURRENT_SCHEMA_VERSION","ZABBIX_DS_ID","DEFAULT_TARGET","group","host","application","tags","DEFAULT_SEVERITY","priority","severity","color","show","DEFAULT_TIME_FORMAT","PANEL_DEFAULTS","schemaVersion","datasources","targets","hostField","hostTechNameField","hostGroups","showTags","statusField","severityField","descriptionField","descriptionAtNewLine","hostsInMaintenance","showTriggers","sortTriggersBy","text","value","showEvents","limit","fontSize","pageSize","highlightBackground","highlightNewEvents","highlightNewerThan","customLastChangeFormat","lastChangeFormat","triggerSeverity","okEventColor","ackEventColor","triggerStatusMap","TriggerPanelCtrl","$scope","$injector","$timeout","datasourceSrv","templateSrv","contextSrv","dashboardSrv","scope","editorTabIndex","defaultTimeFormat","pageIndex","triggerList","currentTriggersPage","panel","defaultsDeep","cloneDeep","available_datasources","map","getZabbixDataSources","length","push","isEmpty","initDatasources","events","on","onInitEditMode","bind","onRefresh","promises","ds","get","then","datasource","Promise","all","getMetricSources","meta","id","addEditorTab","timing","queryStart","Date","getTime","queryEnd","otherPanelInFullscreenMode","error","loading","setTimeQueryStart","getTriggers","setTimeQueryEnd","render","zabbixTriggers","catch","err","cancelled","console","log","message","data","emit","triggerListUnfiltered","formatTrigger","filterTriggersPost","sortTriggers","slice","getCurrentTriggersPage","zabbix","groupFilter","replaceTemplateVars","hostFilter","appFilter","triggersOptions","getAcknowledges","setMaintenanceStatus","filterTriggersPre","addTriggerDataSource","flatten","results","eventids","lastEvent","eventid","each","event","find","acknowledges","formatAcknowledge","ack","timestamp","unix","clock","time","format","user","alias","name","surname","fullName","target","tagsFilter","replace","parseTags","every","tag","maintenance","maintenance_status","some","hosts","orderBy","zabbixTrigger","triggerObj","hostTechName","comments","lastchangeUnix","Number","lastchange","setTriggerLastChange","setTriggerSeverity","markAckEvents","age","fromNow","tagStr","split","trim","tagParts","join","tagFilter","targetTags","newTag","uniqWith","isEqual","newFilter","tagsToString","refresh","showComment","grafana_user","ack_message","userIsEditor","isEditor","isGrafanaAdmin","disableReadOnlyUsersAck","reject","zabbixAPI","acknowledgeEvent","startPos","endPos","Math","min","groupNames","groups","iconClass","isNewTrigger","statusClass","mainColor","secondColor","lightTheme","highlightIntervalMs","parseInterval","durationSec","now","e","elem","attrs","ctrl","pageCount","$watchGroup","renderPanel","switchPage","renderData","getContentHeight","panelHeight","height","el","currentTarget","parseInt","$apply","appendPaginationControls","footerElem","empty","ceil","startPage","max","endPage","paginationList","i","activeClass","pageLinkElem","append","setFontSize","triggerCardElem","css","rootElem","renderingCompleted","unbindDestroy","$on","off","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAupBA,WAASA,cAAT,CAAwBC,QAAxB,EAAkCC,aAAlC,EAAiD;AAC/C,QAAIC,MAAMC,OAAN,CAAcF,aAAd,CAAJ,EAAkC;AAChC,aAAOG,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,eAAOJ,MAAMK,UAAN,CAAiBN,aAAjB,EAAgCO,IAAhC,CAAqCF,QAAQG,WAA7C,CAAP;AACD,OAFM,CAAP;AAGD,KAJD,MAIO;AACL,aAAOL,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,eAAOA,QAAQG,WAAR,KAAwBR,aAA/B;AACD,OAFM,CAAP;AAGD;AACF;;;AAjqBMG,O;;AACAM,O;;AACAC,Y;;AACKT,W;;AACJU,e,kBAAAA,S;;AACAC,4B,gBAAAA,sB;;AACAC,6B,iBAAAA,uB;;AACAC,wB,eAAAA,kB;AAAoBC,4B,eAAAA,sB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtBC,kB,GAAe,mC;;gCAERC,c,GAAiB;AAC5BC,eAAO,EAACd,QAAQ,EAAT,EADqB;AAE5Be,cAAM,EAACf,QAAQ,EAAT,EAFsB;AAG5BgB,qBAAa,EAAChB,QAAQ,EAAT,EAHe;AAI5BC,iBAAS,EAACD,QAAQ,EAAT,EAJmB;AAK5BiB,cAAM,EAACjB,QAAQ,EAAT;AALsB,O;;;;kCAQjBkB,gB,GAAmB,CAC9B,EAAEC,UAAU,CA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CAApB;AAID;;;;QA9kBmChP,S;;;;AAilBtC+C,uBAAiBoM,WAAjB,GAA+B,+EAA/B","file":"triggers_panel_ctrl.js","sourcesContent":["import _ from 'lodash';\nimport $ from 'jquery';\nimport moment from 'moment';\nimport * as utils from '../datasource-zabbix/utils';\nimport {PanelCtrl} from 'app/plugins/sdk';\nimport {triggerPanelOptionsTab} from './options_tab';\nimport {triggerPanelTriggersTab} from './triggers_tab';\nimport {migratePanelSchema, CURRENT_SCHEMA_VERSION} from './migrations';\n\nconst ZABBIX_DS_ID = 'alexanderzobnin-zabbix-datasource';\n\nexport const DEFAULT_TARGET = {\n group: {filter: \"\"},\n host: {filter: \"\"},\n application: {filter: \"\"},\n trigger: {filter: \"\"},\n tags: {filter: \"\"},\n};\n\nexport const DEFAULT_SEVERITY = [\n { priority: 0, severity: 'Not classified', color: 'rgb(108, 108, 108)', show: true},\n { priority: 1, severity: 'Information', color: 'rgb(120, 158, 183)', show: true},\n { priority: 2, severity: 'Warning', color: 'rgb(175, 180, 36)', show: true},\n { priority: 3, severity: 'Average', color: 'rgb(255, 137, 30)', show: true},\n { priority: 4, severity: 'High', color: 'rgb(255, 101, 72)', show: true},\n { priority: 5, severity: 'Disaster', color: 'rgb(215, 0, 0)', show: true},\n];\n\nconst DEFAULT_TIME_FORMAT = \"DD MMM YYYY HH:mm:ss\";\n\nexport const PANEL_DEFAULTS = {\n schemaVersion: CURRENT_SCHEMA_VERSION,\n datasources: [],\n targets: {},\n // Fields\n hostField: true,\n hostTechNameField: false,\n hostGroups: false,\n showTags: true,\n statusField: true,\n severityField: true,\n descriptionField: true,\n descriptionAtNewLine: false,\n // Options\n hostsInMaintenance: true,\n showTriggers: 'all triggers',\n sortTriggersBy: { text: 'last change', value: 'lastchange' },\n showEvents: { text: 'Problems', value: '1' },\n limit: 100,\n // View options\n fontSize: '100%',\n pageSize: 10,\n highlightBackground: false,\n highlightNewEvents: false,\n highlightNewerThan: '1h',\n customLastChangeFormat: false,\n lastChangeFormat: \"\",\n // Triggers severity and colors\n triggerSeverity: DEFAULT_SEVERITY,\n okEventColor: 'rgb(56, 189, 113)',\n ackEventColor: 'rgb(56, 219, 156)'\n};\n\nconst triggerStatusMap = {\n '0': 'OK',\n '1': 'PROBLEM'\n};\n\nexport class TriggerPanelCtrl extends PanelCtrl {\n\n /** @ngInject */\n constructor($scope, $injector, $timeout, datasourceSrv, templateSrv, contextSrv, dashboardSrv) {\n super($scope, $injector);\n this.datasourceSrv = datasourceSrv;\n this.templateSrv = templateSrv;\n this.contextSrv = contextSrv;\n this.dashboardSrv = dashboardSrv;\n this.scope = $scope;\n this.$timeout = $timeout;\n\n this.editorTabIndex = 1;\n this.triggerStatusMap = triggerStatusMap;\n this.defaultTimeFormat = DEFAULT_TIME_FORMAT;\n this.pageIndex = 0;\n this.triggerList = [];\n this.currentTriggersPage = [];\n this.datasources = {};\n\n this.panel = migratePanelSchema(this.panel);\n _.defaultsDeep(this.panel, _.cloneDeep(PANEL_DEFAULTS));\n\n this.available_datasources = _.map(this.getZabbixDataSources(), 'name');\n if (this.panel.datasources.length === 0) {\n this.panel.datasources.push(this.available_datasources[0]);\n }\n if (_.isEmpty(this.panel.targets)) {\n this.panel.targets[this.panel.datasources[0]] = DEFAULT_TARGET;\n }\n\n this.initDatasources();\n this.events.on('init-edit-mode', this.onInitEditMode.bind(this));\n this.events.on('refresh', this.onRefresh.bind(this));\n }\n\n initDatasources() {\n let promises = _.map(this.panel.datasources, (ds) => {\n // Load datasource\n return this.datasourceSrv.get(ds)\n .then(datasource => {\n this.datasources[ds] = datasource;\n return datasource;\n });\n });\n return Promise.all(promises);\n }\n\n getZabbixDataSources() {\n return _.filter(this.datasourceSrv.getMetricSources(), datasource => {\n return datasource.meta.id === ZABBIX_DS_ID && datasource.value;\n });\n }\n\n onInitEditMode() {\n this.addEditorTab('Triggers', triggerPanelTriggersTab, 1);\n this.addEditorTab('Options', triggerPanelOptionsTab, 2);\n }\n\n setTimeQueryStart() {\n this.timing.queryStart = new Date().getTime();\n }\n\n setTimeQueryEnd() {\n this.timing.queryEnd = new Date().getTime();\n }\n\n onRefresh() {\n // ignore fetching data if another panel is in fullscreen\n if (this.otherPanelInFullscreenMode()) { return; }\n\n // clear loading/error state\n delete this.error;\n this.loading = true;\n this.setTimeQueryStart();\n this.pageIndex = 0;\n\n return this.getTriggers()\n .then(zabbixTriggers => {\n // Notify panel that request is finished\n this.loading = false;\n this.setTimeQueryEnd();\n\n this.render(zabbixTriggers);\n })\n .catch(err => {\n // if cancelled keep loading set to true\n if (err.cancelled) {\n console.log('Panel request cancelled', err);\n return;\n }\n\n this.loading = false;\n this.error = err.message || \"Request Error\";\n\n if (err.data) {\n if (err.data.message) {\n this.error = err.data.message;\n }\n if (err.data.error) {\n this.error = err.data.error;\n }\n }\n\n this.events.emit('data-error', err);\n console.log('Panel data error:', err);\n });\n }\n\n render(zabbixTriggers) {\n let triggers = _.cloneDeep(zabbixTriggers || this.triggerListUnfiltered);\n this.triggerListUnfiltered = _.cloneDeep(triggers);\n\n triggers = _.map(triggers, this.formatTrigger.bind(this));\n triggers = this.filterTriggersPost(triggers);\n triggers = this.sortTriggers(triggers);\n\n // Limit triggers number\n triggers = triggers.slice(0, this.panel.limit || PANEL_DEFAULTS.limit);\n\n this.triggerList = triggers;\n this.getCurrentTriggersPage();\n\n this.$timeout(() => {\n super.render(this.triggerList);\n });\n }\n\n getTriggers() {\n let promises = _.map(this.panel.datasources, (ds) => {\n return this.datasourceSrv.get(ds)\n .then(datasource => {\n var zabbix = datasource.zabbix;\n var showEvents = this.panel.showEvents.value;\n var triggerFilter = this.panel.targets[ds];\n\n // Replace template variables\n var groupFilter = datasource.replaceTemplateVars(triggerFilter.group.filter);\n var hostFilter = datasource.replaceTemplateVars(triggerFilter.host.filter);\n var appFilter = datasource.replaceTemplateVars(triggerFilter.application.filter);\n\n let triggersOptions = {\n showTriggers: showEvents\n };\n\n return zabbix.getTriggers(groupFilter, hostFilter, appFilter, triggersOptions);\n }).then((triggers) => {\n return this.getAcknowledges(triggers, ds);\n }).then((triggers) => {\n return this.setMaintenanceStatus(triggers);\n }).then((triggers) => {\n return this.filterTriggersPre(triggers, ds);\n }).then((triggers) => {\n return this.addTriggerDataSource(triggers, ds);\n });\n });\n\n return Promise.all(promises)\n .then(results => _.flatten(results));\n }\n\n getAcknowledges(triggerList, ds) {\n // Request acknowledges for trigger\n var eventids = _.map(triggerList, trigger => {\n return trigger.lastEvent.eventid;\n });\n\n return this.datasources[ds].zabbix.getAcknowledges(eventids)\n .then(events => {\n\n // Map events to triggers\n _.each(triggerList, trigger => {\n var event = _.find(events, event => {\n return event.eventid === trigger.lastEvent.eventid;\n });\n\n if (event) {\n trigger.acknowledges = _.map(event.acknowledges, this.formatAcknowledge.bind(this));\n }\n\n if (!trigger.lastEvent.eventid) {\n trigger.lastEvent = null;\n }\n });\n\n return triggerList;\n });\n }\n\n formatAcknowledge(ack) {\n let timestamp = moment.unix(ack.clock);\n if (this.panel.customLastChangeFormat) {\n ack.time = timestamp.format(this.panel.lastChangeFormat);\n } else {\n ack.time = timestamp.format(this.defaultTimeFormat);\n }\n ack.user = ack.alias || '';\n if (ack.name || ack.surname) {\n const fullName = `${ack.name || ''} ${ack.surname || ''}`;\n ack.user += ` (${fullName})`;\n }\n return ack;\n }\n\n filterTriggersPre(triggerList, ds) {\n // Filter triggers by description\n let triggerFilter = this.panel.targets[ds].trigger.filter;\n triggerFilter = this.datasources[ds].replaceTemplateVars(triggerFilter);\n if (triggerFilter) {\n triggerList = filterTriggers(triggerList, triggerFilter);\n }\n\n // Filter by tags\n const target = this.panel.targets[ds];\n if (target.tags.filter) {\n let tagsFilter = this.datasources[ds].replaceTemplateVars(target.tags.filter);\n // replaceTemplateVars() builds regex-like string, so we should trim it.\n tagsFilter = tagsFilter.replace('/^', '').replace('$/', '');\n const tags = this.parseTags(tagsFilter);\n triggerList = _.filter(triggerList, trigger => {\n return _.every(tags, (tag) => {\n return _.find(trigger.tags, {tag: tag.tag, value: tag.value});\n });\n });\n }\n\n return triggerList;\n }\n\n filterTriggersPost(triggers) {\n let triggerList = _.cloneDeep(triggers);\n\n // Filter acknowledged triggers\n if (this.panel.showTriggers === 'unacknowledged') {\n triggerList = _.filter(triggerList, trigger => {\n return !trigger.acknowledges;\n });\n } else if (this.panel.showTriggers === 'acknowledged') {\n triggerList = _.filter(triggerList, 'acknowledges');\n } else {\n triggerList = triggerList;\n }\n\n // Filter by maintenance status\n if (!this.panel.hostsInMaintenance) {\n triggerList = _.filter(triggerList, (trigger) => trigger.maintenance === false);\n }\n\n // Filter triggers by severity\n triggerList = _.filter(triggerList, trigger => {\n return this.panel.triggerSeverity[trigger.priority].show;\n });\n\n return triggerList;\n }\n\n setMaintenanceStatus(triggers) {\n _.each(triggers, (trigger) => {\n let maintenance_status = _.some(trigger.hosts, (host) => host.maintenance_status === '1');\n trigger.maintenance = maintenance_status;\n });\n return triggers;\n }\n\n addTriggerDataSource(triggers, ds) {\n _.each(triggers, (trigger) => {\n trigger.datasource = ds;\n });\n return triggers;\n }\n\n sortTriggers(triggerList) {\n if (this.panel.sortTriggersBy.value === 'priority') {\n triggerList = _.orderBy(triggerList, ['priority', 'lastchangeUnix', 'triggerid'], ['desc', 'desc', 'desc']);\n } else {\n triggerList = _.orderBy(triggerList, ['lastchangeUnix', 'priority', 'triggerid'], ['desc', 'desc', 'desc']);\n }\n return triggerList;\n }\n\n formatTrigger(zabbixTrigger) {\n let trigger = _.cloneDeep(zabbixTrigger);\n let triggerObj = trigger;\n\n // Set host that the trigger belongs\n if (trigger.hosts && trigger.hosts.length) {\n triggerObj.host = trigger.hosts[0].name;\n triggerObj.hostTechName = trigger.hosts[0].host;\n }\n\n // Set tags if present\n if (trigger.tags && trigger.tags.length === 0) {\n trigger.tags = null;\n }\n\n // Handle multi-line description\n if (trigger.comments) {\n trigger.comments = trigger.comments.replace('\\n', '
');\n }\n\n // Format last change and age\n trigger.lastchangeUnix = Number(trigger.lastchange);\n triggerObj = this.setTriggerLastChange(triggerObj);\n triggerObj = this.setTriggerSeverity(triggerObj);\n return triggerObj;\n }\n\n updateTriggerFormat(trigger) {\n trigger = this.setTriggerLastChange(trigger);\n trigger = this.setTriggerSeverity(trigger);\n return trigger;\n }\n\n setTriggerSeverity(trigger) {\n if (trigger.value === '1') {\n // Problem state\n trigger.color = this.panel.triggerSeverity[trigger.priority].color;\n } else {\n // OK state\n trigger.color = this.panel.okEventColor;\n }\n trigger.severity = this.panel.triggerSeverity[trigger.priority].severity;\n\n // Mark acknowledged triggers with different color\n if (this.panel.markAckEvents && trigger.acknowledges && trigger.acknowledges.length) {\n trigger.color = this.panel.ackEventColor;\n }\n\n return trigger;\n }\n\n setTriggerLastChange(trigger) {\n if (!trigger.lastchangeUnix) {\n trigger.lastchange = \"\";\n trigger.age = \"\";\n return trigger;\n }\n\n let timestamp = moment.unix(trigger.lastchangeUnix);\n if (this.panel.customLastChangeFormat) {\n // User defined format\n trigger.lastchange = timestamp.format(this.panel.lastChangeFormat);\n } else {\n trigger.lastchange = timestamp.format(this.defaultTimeFormat);\n }\n trigger.age = timestamp.fromNow(true);\n return trigger;\n }\n\n parseTags(tagStr) {\n if (!tagStr) {\n return [];\n }\n\n let tags = _.map(tagStr.split(','), (tag) => tag.trim());\n tags = _.map(tags, (tag) => {\n const tagParts = tag.split(':');\n return {tag: tagParts[0].trim(), value: tagParts[1].trim()};\n });\n return tags;\n }\n\n tagsToString(tags) {\n return _.map(tags, (tag) => `${tag.tag}:${tag.value}`).join(', ');\n }\n\n addTagFilter(tag, ds) {\n let tagFilter = this.panel.targets[ds].tags.filter;\n let targetTags = this.parseTags(tagFilter);\n let newTag = {tag: tag.tag, value: tag.value};\n targetTags.push(newTag);\n targetTags = _.uniqWith(targetTags, _.isEqual);\n let newFilter = this.tagsToString(targetTags);\n this.panel.targets[ds].tags.filter = newFilter;\n this.refresh();\n }\n\n switchComment(trigger) {\n trigger.showComment = !trigger.showComment;\n }\n\n acknowledgeTrigger(trigger, message) {\n let eventid = trigger.lastEvent ? trigger.lastEvent.eventid : null;\n let grafana_user = this.contextSrv.user.name;\n let ack_message = grafana_user + ' (Grafana): ' + message;\n return this.datasourceSrv.get(trigger.datasource)\n .then(datasource => {\n const userIsEditor = this.contextSrv.isEditor || this.contextSrv.isGrafanaAdmin;\n if (datasource.disableReadOnlyUsersAck && !userIsEditor) {\n return Promise.reject({message: 'You have no permissions to acknowledge events.'});\n }\n if (eventid) {\n return datasource.zabbix.zabbixAPI.acknowledgeEvent(eventid, ack_message);\n } else {\n return Promise.reject({message: 'Trigger has no events. Nothing to acknowledge.'});\n }\n })\n .then(this.onRefresh.bind(this))\n .catch((err) => {\n this.error = err.message || \"Acknowledge Error\";\n this.events.emit('data-error', err);\n console.log('Panel data error:', err);\n });\n }\n\n getCurrentTriggersPage() {\n let pageSize = this.panel.pageSize || PANEL_DEFAULTS.pageSize;\n let startPos = this.pageIndex * pageSize;\n let endPos = Math.min(startPos + pageSize, this.triggerList.length);\n this.currentTriggersPage = this.triggerList.slice(startPos, endPos);\n return this.currentTriggersPage;\n }\n\n formatHostName(trigger) {\n let host = \"\";\n if (this.panel.hostField && this.panel.hostTechNameField) {\n host = `${trigger.host} (${trigger.hostTechName})`;\n } else if (this.panel.hostField || this.panel.hostTechNameField) {\n host = this.panel.hostField ? trigger.host : trigger.hostTechName;\n }\n\n return host;\n }\n\n formatHostGroups(trigger) {\n let groupNames = \"\";\n if (this.panel.hostGroups) {\n let groups = _.map(trigger.groups, 'name').join(', ');\n groupNames += `[ ${groups} ]`;\n }\n\n return groupNames;\n }\n\n getAlertIconClass(trigger) {\n let iconClass = '';\n if (trigger.value === '1') {\n if (trigger.priority >= 3) {\n iconClass = 'icon-gf-critical';\n } else {\n iconClass = 'icon-gf-warning';\n }\n } else {\n iconClass = 'icon-gf-online';\n }\n\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\n iconClass += ' zabbix-trigger--blinked';\n }\n return iconClass;\n }\n\n getAlertIconClassBySeverity(triggerSeverity) {\n let iconClass = 'icon-gf-warning';\n if (triggerSeverity.priority >= 3) {\n iconClass = 'icon-gf-critical';\n }\n return iconClass;\n }\n\n getAlertStateClass(trigger) {\n let statusClass = '';\n\n if (trigger.value === '1') {\n statusClass = 'alert-state-critical';\n } else {\n statusClass = 'alert-state-ok';\n }\n\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\n statusClass += ' zabbix-trigger--blinked';\n }\n\n return statusClass;\n }\n\n getBackground(trigger) {\n const mainColor = trigger.color;\n const secondColor = this.contextSrv.user.lightTheme ? '#dde4ed' : '#262628';\n if (this.contextSrv.user.lightTheme) {\n return `linear-gradient(135deg, ${secondColor}, ${mainColor})`;\n }\n return `linear-gradient(135deg, ${mainColor}, ${secondColor})`;\n }\n\n isNewTrigger(trigger) {\n try {\n const highlightIntervalMs = utils.parseInterval(this.panel.highlightNewerThan || PANEL_DEFAULTS.highlightNewerThan);\n const durationSec = (Date.now() - trigger.lastchangeUnix * 1000);\n return durationSec < highlightIntervalMs;\n } catch (e) {\n return false;\n }\n }\n\n link(scope, elem, attrs, ctrl) {\n let panel = ctrl.panel;\n let pageCount = 0;\n let triggerList = ctrl.triggerList;\n\n scope.$watchGroup(['ctrl.currentTriggersPage', 'ctrl.triggerList'], renderPanel);\n elem.on('click', '.triggers-panel-page-link', switchPage);\n ctrl.events.on('render', (renderData) => {\n triggerList = renderData || triggerList;\n renderPanel();\n });\n\n function getContentHeight() {\n let panelHeight = ctrl.height;\n if (pageCount > 1) {\n panelHeight -= 36;\n }\n return panelHeight + 'px';\n }\n\n function switchPage(e) {\n let el = $(e.currentTarget);\n ctrl.pageIndex = (parseInt(el.text(), 10)-1);\n\n let pageSize = panel.pageSize || 10;\n let startPos = ctrl.pageIndex * pageSize;\n let endPos = Math.min(startPos + pageSize, triggerList.length);\n ctrl.currentTriggersPage = triggerList.slice(startPos, endPos);\n\n scope.$apply(() => {\n renderPanel();\n });\n }\n\n function appendPaginationControls(footerElem) {\n footerElem.empty();\n\n let pageSize = panel.pageSize || 5;\n pageCount = Math.ceil(triggerList.length / pageSize);\n if (pageCount === 1) {\n return;\n }\n\n let startPage = Math.max(ctrl.pageIndex - 3, 0);\n let endPage = Math.min(pageCount, startPage + 9);\n\n let paginationList = $('
    ');\n\n for (let i = startPage; i < endPage; i++) {\n let activeClass = i === ctrl.pageIndex ? 'active' : '';\n let pageLinkElem = $('
  • ' + (i+1) + '
  • ');\n paginationList.append(pageLinkElem);\n }\n\n footerElem.append(paginationList);\n }\n\n function setFontSize() {\n const fontSize = parseInt(panel.fontSize.slice(0, panel.fontSize.length - 1));\n let triggerCardElem = elem.find('.alert-rule-item');\n if (fontSize && fontSize !== 100) {\n triggerCardElem.find('.alert-rule-item__icon').css({\n 'font-size': fontSize + '%',\n 'margin': fontSize / 100 * 6 + 'px'\n });\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': fontSize + '%'});\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': fontSize * 0.8 + '%'});\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': fontSize * 0.8 + '%'});\n triggerCardElem.find('.zbx-tag').css({'font-size': fontSize * 0.6 + '%'});\n triggerCardElem.find('.zbx-tag').css({'line-height': fontSize / 100 * 16 + 'px'});\n } else {\n // remove css\n triggerCardElem.find('.alert-rule-item__icon').css({'font-size': '', 'margin-right': ''});\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': ''});\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': ''});\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': ''});\n triggerCardElem.find('.zbx-tag').css({'font-size': ''});\n triggerCardElem.find('.zbx-tag').css({'line-height': ''});\n }\n }\n\n function renderPanel() {\n let rootElem = elem.find('.triggers-panel-scroll');\n let footerElem = elem.find('.triggers-panel-footer');\n appendPaginationControls(footerElem);\n rootElem.css({'max-height': getContentHeight()});\n rootElem.css({'height': getContentHeight()});\n setFontSize();\n ctrl.renderingCompleted();\n }\n\n let unbindDestroy = scope.$on('$destroy', function() {\n elem.off('click', '.triggers-panel-page-link');\n unbindDestroy();\n });\n }\n}\n\nTriggerPanelCtrl.templateUrl = 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/module.html';\n\nfunction filterTriggers(triggers, triggerFilter) {\n if (utils.isRegex(triggerFilter)) {\n return _.filter(triggers, function(trigger) {\n return utils.buildRegex(triggerFilter).test(trigger.description);\n });\n } else {\n return _.filter(triggers, function(trigger) {\n return trigger.description === triggerFilter;\n });\n }\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/triggers_panel_ctrl.js"],"names":["filterTriggers","triggers","triggerFilter","utils","isRegex","_","filter","trigger","buildRegex","test","description","$","moment","PanelCtrl","triggerPanelOptionsTab","triggerPanelTriggersTab","migratePanelSchema","CURRENT_SCHEMA_VERSION","ZABBIX_DS_ID","DEFAULT_TARGET","group","host","application","tags","DEFAULT_SEVERITY","priority","severity","color","show","DEFAULT_TIME_FORMAT","PANEL_DEFAULTS","schemaVersion","datasources","targets","hostField","hostTechNameField","hostGroups","showTags","statusField","severityField","descriptionField","descriptionAtNewLine","hostsInMaintenance","showTriggers","sortTriggersBy","text","value","showEvents","limit","fontSize","pageSize","highlightBackground","highlightNewEvents","highlightNewerThan","customLastChangeFormat","lastChangeFormat","triggerSeverity","okEventColor","ackEventColor","triggerStatusMap","TriggerPanelCtrl","$scope","$injector","$timeout","datasourceSrv","templateSrv","contextSrv","dashboardSrv","scope","editorTabIndex","defaultTimeFormat","pageIndex","triggerList","currentTriggersPage","panel","defaultsDeep","cloneDeep","available_datasources","map","getZabbixDataSources","length","push","isEmpty","initDatasources","events","on","onInitEditMode","bind","onRefresh","promises","ds","get","then","datasource","Promise","all","getMetricSources","meta","id","addEditorTab","timing","queryStart","Date","getTime","queryEnd","otherPanelInFullscreenMode","error","loading","setTimeQueryStart","getTriggers","setTimeQueryEnd","render","zabbixTriggers","catch","err","cancelled","console","log","message","data","emit","triggerListUnfiltered","formatTrigger","filterTriggersPost","sortTriggers","slice","getCurrentTriggersPage","zabbix","groupFilter","replaceTemplateVars","hostFilter","appFilter","triggersOptions","getAcknowledges","setMaintenanceStatus","filterTriggersPre","addTriggerDataSource","flatten","results","eventids","lastEvent","eventid","each","event","find","acknowledges","formatAcknowledge","ack","timestamp","unix","clock","time","format","user","alias","name","surname","fullName","target","tagsFilter","replace","parseTags","every","tag","maintenance","maintenance_status","some","hosts","orderBy","zabbixTrigger","triggerObj","hostTechName","comments","lastchangeUnix","Number","lastchange","setTriggerLastChange","setTriggerSeverity","markAckEvents","age","fromNow","tagStr","split","trim","tagParts","join","tagFilter","targetTags","newTag","uniqWith","isEqual","newFilter","tagsToString","refresh","showComment","grafana_user","ack_message","userIsEditor","isEditor","isGrafanaAdmin","disableReadOnlyUsersAck","reject","zabbixAPI","acknowledgeEvent","startPos","endPos","Math","min","groupNames","groups","iconClass","isNewTrigger","statusClass","mainColor","secondColor","lightTheme","highlightIntervalMs","parseInterval","durationSec","now","e","elem","attrs","ctrl","pageCount","$watchGroup","renderPanel","switchPage","renderData","getContentHeight","panelHeight","height","el","currentTarget","parseInt","$apply","appendPaginationControls","footerElem","empty","ceil","startPage","max","endPage","paginationList","i","activeClass","pageLinkElem","append","setFontSize","triggerCardElem","css","rootElem","renderingCompleted","unbindDestroy","$on","off","templateUrl"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAupBA,WAASA,cAAT,CAAwBC,QAAxB,EAAkCC,aAAlC,EAAiD;AAC/C,QAAIC,MAAMC,OAAN,CAAcF,aAAd,CAAJ,EAAkC;AAChC,aAAOG,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,eAAOJ,MAAMK,UAAN,CAAiBN,aAAjB,EAAgCO,IAAhC,CAAqCF,QAAQG,WAA7C,CAAP;AACD,OAFM,CAAP;AAGD,KAJD,MAIO;AACL,aAAOL,EAAEC,MAAF,CAASL,QAAT,EAAmB,UAASM,OAAT,EAAkB;AAC1C,e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AAqC,EAAC,aAAa,EAAd,EAArC;AACAD,gCAAgBzG,IAAhB,CAAqB,UAArB,EAAiC0G,GAAjC,CAAqC,EAAC,eAAe,EAAhB,EAArC;AACD;AACF;;AAED,qBAASxB,WAAT,GAAuB;AACrB,kBAAIyB,WAAW9B,KAAK7E,IAAL,CAAU,wBAAV,CAAf;AACA,kBAAI6F,aAAahB,KAAK7E,IAAL,CAAU,wBAAV,CAAjB;AACA4F,uCAAyBC,UAAzB;AACAc,uBAASD,GAAT,CAAa,EAAC,cAAcrB,kBAAf,EAAb;AACAsB,uBAASD,GAAT,CAAa,EAAC,UAAUrB,kBAAX,EAAb;AACAmB;AACAzB,mBAAK6B,kBAAL;AACD;;AAED,gBAAIC,gBAAgBzL,MAAM0L,GAAN,CAAU,UAAV,EAAsB,YAAW;AACnDjC,mBAAKkC,GAAL,CAAS,OAAT,EAAkB,2BAAlB;AACAF;AACD,aAHmB,CAApB;AAID;;;;QA9kBmChP,S;;;;AAilBtC+C,uBAAiBoM,WAAjB,GAA+B,+EAA/B","file":"triggers_panel_ctrl.js","sourcesContent":["import _ from 'lodash';\r\nimport $ from 'jquery';\r\nimport moment from 'moment';\r\nimport * as utils from '../datasource-zabbix/utils';\r\nimport {PanelCtrl} from 'app/plugins/sdk';\r\nimport {triggerPanelOptionsTab} from './options_tab';\r\nimport {triggerPanelTriggersTab} from './triggers_tab';\r\nimport {migratePanelSchema, CURRENT_SCHEMA_VERSION} from './migrations';\r\n\r\nconst ZABBIX_DS_ID = 'alexanderzobnin-zabbix-datasource';\r\n\r\nexport const DEFAULT_TARGET = {\r\n group: {filter: \"\"},\r\n host: {filter: \"\"},\r\n application: {filter: \"\"},\r\n trigger: {filter: \"\"},\r\n tags: {filter: \"\"},\r\n};\r\n\r\nexport const DEFAULT_SEVERITY = [\r\n { priority: 0, severity: 'Not classified', color: 'rgb(108, 108, 108)', show: true},\r\n { priority: 1, severity: 'Information', color: 'rgb(120, 158, 183)', show: true},\r\n { priority: 2, severity: 'Warning', color: 'rgb(175, 180, 36)', show: true},\r\n { priority: 3, severity: 'Average', color: 'rgb(255, 137, 30)', show: true},\r\n { priority: 4, severity: 'High', color: 'rgb(255, 101, 72)', show: true},\r\n { priority: 5, severity: 'Disaster', color: 'rgb(215, 0, 0)', show: true},\r\n];\r\n\r\nconst DEFAULT_TIME_FORMAT = \"DD MMM YYYY HH:mm:ss\";\r\n\r\nexport const PANEL_DEFAULTS = {\r\n schemaVersion: CURRENT_SCHEMA_VERSION,\r\n datasources: [],\r\n targets: {},\r\n // Fields\r\n hostField: true,\r\n hostTechNameField: false,\r\n hostGroups: false,\r\n showTags: true,\r\n statusField: true,\r\n severityField: true,\r\n descriptionField: true,\r\n descriptionAtNewLine: false,\r\n // Options\r\n hostsInMaintenance: true,\r\n showTriggers: 'all triggers',\r\n sortTriggersBy: { text: 'last change', value: 'lastchange' },\r\n showEvents: { text: 'Problems', value: '1' },\r\n limit: 100,\r\n // View options\r\n fontSize: '100%',\r\n pageSize: 10,\r\n highlightBackground: false,\r\n highlightNewEvents: false,\r\n highlightNewerThan: '1h',\r\n customLastChangeFormat: false,\r\n lastChangeFormat: \"\",\r\n // Triggers severity and colors\r\n triggerSeverity: DEFAULT_SEVERITY,\r\n okEventColor: 'rgb(56, 189, 113)',\r\n ackEventColor: 'rgb(56, 219, 156)'\r\n};\r\n\r\nconst triggerStatusMap = {\r\n '0': 'OK',\r\n '1': 'PROBLEM'\r\n};\r\n\r\nexport class TriggerPanelCtrl extends PanelCtrl {\r\n\r\n /** @ngInject */\r\n constructor($scope, $injector, $timeout, datasourceSrv, templateSrv, contextSrv, dashboardSrv) {\r\n super($scope, $injector);\r\n this.datasourceSrv = datasourceSrv;\r\n this.templateSrv = templateSrv;\r\n this.contextSrv = contextSrv;\r\n this.dashboardSrv = dashboardSrv;\r\n this.scope = $scope;\r\n this.$timeout = $timeout;\r\n\r\n this.editorTabIndex = 1;\r\n this.triggerStatusMap = triggerStatusMap;\r\n this.defaultTimeFormat = DEFAULT_TIME_FORMAT;\r\n this.pageIndex = 0;\r\n this.triggerList = [];\r\n this.currentTriggersPage = [];\r\n this.datasources = {};\r\n\r\n this.panel = migratePanelSchema(this.panel);\r\n _.defaultsDeep(this.panel, _.cloneDeep(PANEL_DEFAULTS));\r\n\r\n this.available_datasources = _.map(this.getZabbixDataSources(), 'name');\r\n if (this.panel.datasources.length === 0) {\r\n this.panel.datasources.push(this.available_datasources[0]);\r\n }\r\n if (_.isEmpty(this.panel.targets)) {\r\n this.panel.targets[this.panel.datasources[0]] = DEFAULT_TARGET;\r\n }\r\n\r\n this.initDatasources();\r\n this.events.on('init-edit-mode', this.onInitEditMode.bind(this));\r\n this.events.on('refresh', this.onRefresh.bind(this));\r\n }\r\n\r\n initDatasources() {\r\n let promises = _.map(this.panel.datasources, (ds) => {\r\n // Load datasource\r\n return this.datasourceSrv.get(ds)\r\n .then(datasource => {\r\n this.datasources[ds] = datasource;\r\n return datasource;\r\n });\r\n });\r\n return Promise.all(promises);\r\n }\r\n\r\n getZabbixDataSources() {\r\n return _.filter(this.datasourceSrv.getMetricSources(), datasource => {\r\n return datasource.meta.id === ZABBIX_DS_ID && datasource.value;\r\n });\r\n }\r\n\r\n onInitEditMode() {\r\n this.addEditorTab('Triggers', triggerPanelTriggersTab, 1);\r\n this.addEditorTab('Options', triggerPanelOptionsTab, 2);\r\n }\r\n\r\n setTimeQueryStart() {\r\n this.timing.queryStart = new Date().getTime();\r\n }\r\n\r\n setTimeQueryEnd() {\r\n this.timing.queryEnd = new Date().getTime();\r\n }\r\n\r\n onRefresh() {\r\n // ignore fetching data if another panel is in fullscreen\r\n if (this.otherPanelInFullscreenMode()) { return; }\r\n\r\n // clear loading/error state\r\n delete this.error;\r\n this.loading = true;\r\n this.setTimeQueryStart();\r\n this.pageIndex = 0;\r\n\r\n return this.getTriggers()\r\n .then(zabbixTriggers => {\r\n // Notify panel that request is finished\r\n this.loading = false;\r\n this.setTimeQueryEnd();\r\n\r\n this.render(zabbixTriggers);\r\n })\r\n .catch(err => {\r\n // if cancelled keep loading set to true\r\n if (err.cancelled) {\r\n console.log('Panel request cancelled', err);\r\n return;\r\n }\r\n\r\n this.loading = false;\r\n this.error = err.message || \"Request Error\";\r\n\r\n if (err.data) {\r\n if (err.data.message) {\r\n this.error = err.data.message;\r\n }\r\n if (err.data.error) {\r\n this.error = err.data.error;\r\n }\r\n }\r\n\r\n this.events.emit('data-error', err);\r\n console.log('Panel data error:', err);\r\n });\r\n }\r\n\r\n render(zabbixTriggers) {\r\n let triggers = _.cloneDeep(zabbixTriggers || this.triggerListUnfiltered);\r\n this.triggerListUnfiltered = _.cloneDeep(triggers);\r\n\r\n triggers = _.map(triggers, this.formatTrigger.bind(this));\r\n triggers = this.filterTriggersPost(triggers);\r\n triggers = this.sortTriggers(triggers);\r\n\r\n // Limit triggers number\r\n triggers = triggers.slice(0, this.panel.limit || PANEL_DEFAULTS.limit);\r\n\r\n this.triggerList = triggers;\r\n this.getCurrentTriggersPage();\r\n\r\n this.$timeout(() => {\r\n super.render(this.triggerList);\r\n });\r\n }\r\n\r\n getTriggers() {\r\n let promises = _.map(this.panel.datasources, (ds) => {\r\n return this.datasourceSrv.get(ds)\r\n .then(datasource => {\r\n var zabbix = datasource.zabbix;\r\n var showEvents = this.panel.showEvents.value;\r\n var triggerFilter = this.panel.targets[ds];\r\n\r\n // Replace template variables\r\n var groupFilter = datasource.replaceTemplateVars(triggerFilter.group.filter);\r\n var hostFilter = datasource.replaceTemplateVars(triggerFilter.host.filter);\r\n var appFilter = datasource.replaceTemplateVars(triggerFilter.application.filter);\r\n\r\n let triggersOptions = {\r\n showTriggers: showEvents\r\n };\r\n\r\n return zabbix.getTriggers(groupFilter, hostFilter, appFilter, triggersOptions);\r\n }).then((triggers) => {\r\n return this.getAcknowledges(triggers, ds);\r\n }).then((triggers) => {\r\n return this.setMaintenanceStatus(triggers);\r\n }).then((triggers) => {\r\n return this.filterTriggersPre(triggers, ds);\r\n }).then((triggers) => {\r\n return this.addTriggerDataSource(triggers, ds);\r\n });\r\n });\r\n\r\n return Promise.all(promises)\r\n .then(results => _.flatten(results));\r\n }\r\n\r\n getAcknowledges(triggerList, ds) {\r\n // Request acknowledges for trigger\r\n var eventids = _.map(triggerList, trigger => {\r\n return trigger.lastEvent.eventid;\r\n });\r\n\r\n return this.datasources[ds].zabbix.getAcknowledges(eventids)\r\n .then(events => {\r\n\r\n // Map events to triggers\r\n _.each(triggerList, trigger => {\r\n var event = _.find(events, event => {\r\n return event.eventid === trigger.lastEvent.eventid;\r\n });\r\n\r\n if (event) {\r\n trigger.acknowledges = _.map(event.acknowledges, this.formatAcknowledge.bind(this));\r\n }\r\n\r\n if (!trigger.lastEvent.eventid) {\r\n trigger.lastEvent = null;\r\n }\r\n });\r\n\r\n return triggerList;\r\n });\r\n }\r\n\r\n formatAcknowledge(ack) {\r\n let timestamp = moment.unix(ack.clock);\r\n if (this.panel.customLastChangeFormat) {\r\n ack.time = timestamp.format(this.panel.lastChangeFormat);\r\n } else {\r\n ack.time = timestamp.format(this.defaultTimeFormat);\r\n }\r\n ack.user = ack.alias || '';\r\n if (ack.name || ack.surname) {\r\n const fullName = `${ack.name || ''} ${ack.surname || ''}`;\r\n ack.user += ` (${fullName})`;\r\n }\r\n return ack;\r\n }\r\n\r\n filterTriggersPre(triggerList, ds) {\r\n // Filter triggers by description\r\n let triggerFilter = this.panel.targets[ds].trigger.filter;\r\n triggerFilter = this.datasources[ds].replaceTemplateVars(triggerFilter);\r\n if (triggerFilter) {\r\n triggerList = filterTriggers(triggerList, triggerFilter);\r\n }\r\n\r\n // Filter by tags\r\n const target = this.panel.targets[ds];\r\n if (target.tags.filter) {\r\n let tagsFilter = this.datasources[ds].replaceTemplateVars(target.tags.filter);\r\n // replaceTemplateVars() builds regex-like string, so we should trim it.\r\n tagsFilter = tagsFilter.replace('/^', '').replace('$/', '');\r\n const tags = this.parseTags(tagsFilter);\r\n triggerList = _.filter(triggerList, trigger => {\r\n return _.every(tags, (tag) => {\r\n return _.find(trigger.tags, {tag: tag.tag, value: tag.value});\r\n });\r\n });\r\n }\r\n\r\n return triggerList;\r\n }\r\n\r\n filterTriggersPost(triggers) {\r\n let triggerList = _.cloneDeep(triggers);\r\n\r\n // Filter acknowledged triggers\r\n if (this.panel.showTriggers === 'unacknowledged') {\r\n triggerList = _.filter(triggerList, trigger => {\r\n return !trigger.acknowledges;\r\n });\r\n } else if (this.panel.showTriggers === 'acknowledged') {\r\n triggerList = _.filter(triggerList, 'acknowledges');\r\n } else {\r\n triggerList = triggerList;\r\n }\r\n\r\n // Filter by maintenance status\r\n if (!this.panel.hostsInMaintenance) {\r\n triggerList = _.filter(triggerList, (trigger) => trigger.maintenance === false);\r\n }\r\n\r\n // Filter triggers by severity\r\n triggerList = _.filter(triggerList, trigger => {\r\n return this.panel.triggerSeverity[trigger.priority].show;\r\n });\r\n\r\n return triggerList;\r\n }\r\n\r\n setMaintenanceStatus(triggers) {\r\n _.each(triggers, (trigger) => {\r\n let maintenance_status = _.some(trigger.hosts, (host) => host.maintenance_status === '1');\r\n trigger.maintenance = maintenance_status;\r\n });\r\n return triggers;\r\n }\r\n\r\n addTriggerDataSource(triggers, ds) {\r\n _.each(triggers, (trigger) => {\r\n trigger.datasource = ds;\r\n });\r\n return triggers;\r\n }\r\n\r\n sortTriggers(triggerList) {\r\n if (this.panel.sortTriggersBy.value === 'priority') {\r\n triggerList = _.orderBy(triggerList, ['priority', 'lastchangeUnix', 'triggerid'], ['desc', 'desc', 'desc']);\r\n } else {\r\n triggerList = _.orderBy(triggerList, ['lastchangeUnix', 'priority', 'triggerid'], ['desc', 'desc', 'desc']);\r\n }\r\n return triggerList;\r\n }\r\n\r\n formatTrigger(zabbixTrigger) {\r\n let trigger = _.cloneDeep(zabbixTrigger);\r\n let triggerObj = trigger;\r\n\r\n // Set host that the trigger belongs\r\n if (trigger.hosts && trigger.hosts.length) {\r\n triggerObj.host = trigger.hosts[0].name;\r\n triggerObj.hostTechName = trigger.hosts[0].host;\r\n }\r\n\r\n // Set tags if present\r\n if (trigger.tags && trigger.tags.length === 0) {\r\n trigger.tags = null;\r\n }\r\n\r\n // Handle multi-line description\r\n if (trigger.comments) {\r\n trigger.comments = trigger.comments.replace('\\n', '
    ');\r\n }\r\n\r\n // Format last change and age\r\n trigger.lastchangeUnix = Number(trigger.lastchange);\r\n triggerObj = this.setTriggerLastChange(triggerObj);\r\n triggerObj = this.setTriggerSeverity(triggerObj);\r\n return triggerObj;\r\n }\r\n\r\n updateTriggerFormat(trigger) {\r\n trigger = this.setTriggerLastChange(trigger);\r\n trigger = this.setTriggerSeverity(trigger);\r\n return trigger;\r\n }\r\n\r\n setTriggerSeverity(trigger) {\r\n if (trigger.value === '1') {\r\n // Problem state\r\n trigger.color = this.panel.triggerSeverity[trigger.priority].color;\r\n } else {\r\n // OK state\r\n trigger.color = this.panel.okEventColor;\r\n }\r\n trigger.severity = this.panel.triggerSeverity[trigger.priority].severity;\r\n\r\n // Mark acknowledged triggers with different color\r\n if (this.panel.markAckEvents && trigger.acknowledges && trigger.acknowledges.length) {\r\n trigger.color = this.panel.ackEventColor;\r\n }\r\n\r\n return trigger;\r\n }\r\n\r\n setTriggerLastChange(trigger) {\r\n if (!trigger.lastchangeUnix) {\r\n trigger.lastchange = \"\";\r\n trigger.age = \"\";\r\n return trigger;\r\n }\r\n\r\n let timestamp = moment.unix(trigger.lastchangeUnix);\r\n if (this.panel.customLastChangeFormat) {\r\n // User defined format\r\n trigger.lastchange = timestamp.format(this.panel.lastChangeFormat);\r\n } else {\r\n trigger.lastchange = timestamp.format(this.defaultTimeFormat);\r\n }\r\n trigger.age = timestamp.fromNow(true);\r\n return trigger;\r\n }\r\n\r\n parseTags(tagStr) {\r\n if (!tagStr) {\r\n return [];\r\n }\r\n\r\n let tags = _.map(tagStr.split(','), (tag) => tag.trim());\r\n tags = _.map(tags, (tag) => {\r\n const tagParts = tag.split(':');\r\n return {tag: tagParts[0].trim(), value: tagParts[1].trim()};\r\n });\r\n return tags;\r\n }\r\n\r\n tagsToString(tags) {\r\n return _.map(tags, (tag) => `${tag.tag}:${tag.value}`).join(', ');\r\n }\r\n\r\n addTagFilter(tag, ds) {\r\n let tagFilter = this.panel.targets[ds].tags.filter;\r\n let targetTags = this.parseTags(tagFilter);\r\n let newTag = {tag: tag.tag, value: tag.value};\r\n targetTags.push(newTag);\r\n targetTags = _.uniqWith(targetTags, _.isEqual);\r\n let newFilter = this.tagsToString(targetTags);\r\n this.panel.targets[ds].tags.filter = newFilter;\r\n this.refresh();\r\n }\r\n\r\n switchComment(trigger) {\r\n trigger.showComment = !trigger.showComment;\r\n }\r\n\r\n acknowledgeTrigger(trigger, message) {\r\n let eventid = trigger.lastEvent ? trigger.lastEvent.eventid : null;\r\n let grafana_user = this.contextSrv.user.name;\r\n let ack_message = grafana_user + ' (Grafana): ' + message;\r\n return this.datasourceSrv.get(trigger.datasource)\r\n .then(datasource => {\r\n const userIsEditor = this.contextSrv.isEditor || this.contextSrv.isGrafanaAdmin;\r\n if (datasource.disableReadOnlyUsersAck && !userIsEditor) {\r\n return Promise.reject({message: 'You have no permissions to acknowledge events.'});\r\n }\r\n if (eventid) {\r\n return datasource.zabbix.zabbixAPI.acknowledgeEvent(eventid, ack_message);\r\n } else {\r\n return Promise.reject({message: 'Trigger has no events. Nothing to acknowledge.'});\r\n }\r\n })\r\n .then(this.onRefresh.bind(this))\r\n .catch((err) => {\r\n this.error = err.message || \"Acknowledge Error\";\r\n this.events.emit('data-error', err);\r\n console.log('Panel data error:', err);\r\n });\r\n }\r\n\r\n getCurrentTriggersPage() {\r\n let pageSize = this.panel.pageSize || PANEL_DEFAULTS.pageSize;\r\n let startPos = this.pageIndex * pageSize;\r\n let endPos = Math.min(startPos + pageSize, this.triggerList.length);\r\n this.currentTriggersPage = this.triggerList.slice(startPos, endPos);\r\n return this.currentTriggersPage;\r\n }\r\n\r\n formatHostName(trigger) {\r\n let host = \"\";\r\n if (this.panel.hostField && this.panel.hostTechNameField) {\r\n host = `${trigger.host} (${trigger.hostTechName})`;\r\n } else if (this.panel.hostField || this.panel.hostTechNameField) {\r\n host = this.panel.hostField ? trigger.host : trigger.hostTechName;\r\n }\r\n\r\n return host;\r\n }\r\n\r\n formatHostGroups(trigger) {\r\n let groupNames = \"\";\r\n if (this.panel.hostGroups) {\r\n let groups = _.map(trigger.groups, 'name').join(', ');\r\n groupNames += `[ ${groups} ]`;\r\n }\r\n\r\n return groupNames;\r\n }\r\n\r\n getAlertIconClass(trigger) {\r\n let iconClass = '';\r\n if (trigger.value === '1') {\r\n if (trigger.priority >= 3) {\r\n iconClass = 'icon-gf-critical';\r\n } else {\r\n iconClass = 'icon-gf-warning';\r\n }\r\n } else {\r\n iconClass = 'icon-gf-online';\r\n }\r\n\r\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\r\n iconClass += ' zabbix-trigger--blinked';\r\n }\r\n return iconClass;\r\n }\r\n\r\n getAlertIconClassBySeverity(triggerSeverity) {\r\n let iconClass = 'icon-gf-warning';\r\n if (triggerSeverity.priority >= 3) {\r\n iconClass = 'icon-gf-critical';\r\n }\r\n return iconClass;\r\n }\r\n\r\n getAlertStateClass(trigger) {\r\n let statusClass = '';\r\n\r\n if (trigger.value === '1') {\r\n statusClass = 'alert-state-critical';\r\n } else {\r\n statusClass = 'alert-state-ok';\r\n }\r\n\r\n if (this.panel.highlightNewEvents && this.isNewTrigger(trigger)) {\r\n statusClass += ' zabbix-trigger--blinked';\r\n }\r\n\r\n return statusClass;\r\n }\r\n\r\n getBackground(trigger) {\r\n const mainColor = trigger.color;\r\n const secondColor = this.contextSrv.user.lightTheme ? '#dde4ed' : '#262628';\r\n if (this.contextSrv.user.lightTheme) {\r\n return `linear-gradient(135deg, ${secondColor}, ${mainColor})`;\r\n }\r\n return `linear-gradient(135deg, ${mainColor}, ${secondColor})`;\r\n }\r\n\r\n isNewTrigger(trigger) {\r\n try {\r\n const highlightIntervalMs = utils.parseInterval(this.panel.highlightNewerThan || PANEL_DEFAULTS.highlightNewerThan);\r\n const durationSec = (Date.now() - trigger.lastchangeUnix * 1000);\r\n return durationSec < highlightIntervalMs;\r\n } catch (e) {\r\n return false;\r\n }\r\n }\r\n\r\n link(scope, elem, attrs, ctrl) {\r\n let panel = ctrl.panel;\r\n let pageCount = 0;\r\n let triggerList = ctrl.triggerList;\r\n\r\n scope.$watchGroup(['ctrl.currentTriggersPage', 'ctrl.triggerList'], renderPanel);\r\n elem.on('click', '.triggers-panel-page-link', switchPage);\r\n ctrl.events.on('render', (renderData) => {\r\n triggerList = renderData || triggerList;\r\n renderPanel();\r\n });\r\n\r\n function getContentHeight() {\r\n let panelHeight = ctrl.height;\r\n if (pageCount > 1) {\r\n panelHeight -= 36;\r\n }\r\n return panelHeight + 'px';\r\n }\r\n\r\n function switchPage(e) {\r\n let el = $(e.currentTarget);\r\n ctrl.pageIndex = (parseInt(el.text(), 10)-1);\r\n\r\n let pageSize = panel.pageSize || 10;\r\n let startPos = ctrl.pageIndex * pageSize;\r\n let endPos = Math.min(startPos + pageSize, triggerList.length);\r\n ctrl.currentTriggersPage = triggerList.slice(startPos, endPos);\r\n\r\n scope.$apply(() => {\r\n renderPanel();\r\n });\r\n }\r\n\r\n function appendPaginationControls(footerElem) {\r\n footerElem.empty();\r\n\r\n let pageSize = panel.pageSize || 5;\r\n pageCount = Math.ceil(triggerList.length / pageSize);\r\n if (pageCount === 1) {\r\n return;\r\n }\r\n\r\n let startPage = Math.max(ctrl.pageIndex - 3, 0);\r\n let endPage = Math.min(pageCount, startPage + 9);\r\n\r\n let paginationList = $('
      ');\r\n\r\n for (let i = startPage; i < endPage; i++) {\r\n let activeClass = i === ctrl.pageIndex ? 'active' : '';\r\n let pageLinkElem = $('
    • ' + (i+1) + '
    • ');\r\n paginationList.append(pageLinkElem);\r\n }\r\n\r\n footerElem.append(paginationList);\r\n }\r\n\r\n function setFontSize() {\r\n const fontSize = parseInt(panel.fontSize.slice(0, panel.fontSize.length - 1));\r\n let triggerCardElem = elem.find('.alert-rule-item');\r\n if (fontSize && fontSize !== 100) {\r\n triggerCardElem.find('.alert-rule-item__icon').css({\r\n 'font-size': fontSize + '%',\r\n 'margin': fontSize / 100 * 6 + 'px'\r\n });\r\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': fontSize + '%'});\r\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': fontSize * 0.8 + '%'});\r\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': fontSize * 0.8 + '%'});\r\n triggerCardElem.find('.zbx-tag').css({'font-size': fontSize * 0.6 + '%'});\r\n triggerCardElem.find('.zbx-tag').css({'line-height': fontSize / 100 * 16 + 'px'});\r\n } else {\r\n // remove css\r\n triggerCardElem.find('.alert-rule-item__icon').css({'font-size': '', 'margin-right': ''});\r\n triggerCardElem.find('.alert-rule-item__name').css({'font-size': ''});\r\n triggerCardElem.find('.alert-rule-item__text').css({'font-size': ''});\r\n triggerCardElem.find('.zbx-trigger-lastchange').css({'font-size': ''});\r\n triggerCardElem.find('.zbx-tag').css({'font-size': ''});\r\n triggerCardElem.find('.zbx-tag').css({'line-height': ''});\r\n }\r\n }\r\n\r\n function renderPanel() {\r\n let rootElem = elem.find('.triggers-panel-scroll');\r\n let footerElem = elem.find('.triggers-panel-footer');\r\n appendPaginationControls(footerElem);\r\n rootElem.css({'max-height': getContentHeight()});\r\n rootElem.css({'height': getContentHeight()});\r\n setFontSize();\r\n ctrl.renderingCompleted();\r\n }\r\n\r\n let unbindDestroy = scope.$on('$destroy', function() {\r\n elem.off('click', '.triggers-panel-page-link');\r\n unbindDestroy();\r\n });\r\n }\r\n}\r\n\r\nTriggerPanelCtrl.templateUrl = 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/module.html';\r\n\r\nfunction filterTriggers(triggers, triggerFilter) {\r\n if (utils.isRegex(triggerFilter)) {\r\n return _.filter(triggers, function(trigger) {\r\n return utils.buildRegex(triggerFilter).test(trigger.description);\r\n });\r\n } else {\r\n return _.filter(triggers, function(trigger) {\r\n return trigger.description === triggerFilter;\r\n });\r\n }\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/panel-triggers/triggers_tab.js.map b/dist/panel-triggers/triggers_tab.js.map index 5392f929e..2e91e3400 100644 --- a/dist/panel-triggers/triggers_tab.js.map +++ b/dist/panel-triggers/triggers_tab.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/panel-triggers/triggers_tab.js"],"names":["triggerPanelTriggersTab","restrict","scope","templateUrl","controller","TriggersTabCtrl","_","utils","DEFAULT_TARGET","$scope","$rootScope","uiSegmentSrv","templateSrv","editor","panelCtrl","ctrl","panel","datasources","scopeDefaults","getGroupNames","getHostNames","getApplicationNames","oldTarget","cloneDeep","targets","defaultsDeep","initDatasources","refresh","then","each","datasource","bindSuggestionFunctions","ds","name","bind","suggestGroups","suggestHosts","suggestApps","query","callback","zabbix","getAllGroups","map","groups","groupFilter","replaceTemplateVars","group","filter","getAllHosts","hosts","hostFilter","host","getAllApps","apps","parseTarget","newTarget","isEqual","str","isRegex","isTemplateVariable","variables"],"mappings":";;;;;;;;;;;;;AAoGO,WAASA,uBAAT,GAAmC;AACxC,WAAO;AACLC,gBAAU,GADL;AAELC,aAAO,IAFF;AAGLC,mBAAa,qFAHR;AAILC,kBAAYC;AAJP,KAAP;AAMD;;qCAPeL,uB;;;;AApGTM,O;;AACKC,W;;AACJC,oB,wBAAAA,c;;;;;;;;;;;;;;;;;;;;;AAEFH,qB;;AAEJ;AACA,iCAAYI,MAAZ,EAAoBC,UAApB,EAAgCC,YAAhC,EAA8CC,WAA9C,EAA2D;AAAA;;AACzDH,iBAAOI,MAAP,GAAgB,IAAhB;AACA,eAAKC,SAAL,GAAiBL,OAAOM,IAAxB;AACA,eAAKC,KAAL,GAAa,KAAKF,SAAL,CAAeE,KAA5B;AACA,eAAKJ,WAAL,GAAmBA,WAAnB;AACA,eAAKK,WAAL,GAAmB,KAAKH,SAAL,CAAeG,WAAlC;;AAEA;AACA,cAAIC,gBAAgB;AAClBC,2BAAe,EADG;A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OAAF,CAAU,OAAKlC,SAAf,EAA0BiC,SAA1B,CAAL,EAA2C;AACzC,uBAAKjC,SAAL,GAAiBiC,SAAjB;AACD;AACD,qBAAKzC,SAAL,CAAea,OAAf;AACD,aAPD;AAQD;;;kCAEO8B,G,EAAK;AACX,mBAAOlD,MAAMmD,OAAN,CAAcD,GAAd,CAAP;AACD;;;qCAEUA,G,EAAK;AACd,mBAAOlD,MAAMoD,kBAAN,CAAyBF,GAAzB,EAA8B,KAAK7C,WAAL,CAAiBgD,SAA/C,CAAP;AACD","file":"triggers_tab.js","sourcesContent":["import _ from 'lodash';\nimport * as utils from '../datasource-zabbix/utils';\nimport {DEFAULT_TARGET} from './triggers_panel_ctrl';\n\nclass TriggersTabCtrl {\n\n /** @ngInject */\n constructor($scope, $rootScope, uiSegmentSrv, templateSrv) {\n $scope.editor = this;\n this.panelCtrl = $scope.ctrl;\n this.panel = this.panelCtrl.panel;\n this.templateSrv = templateSrv;\n this.datasources = this.panelCtrl.datasources;\n\n // Load scope defaults\n var scopeDefaults = {\n getGroupNames: {},\n getHostNames: {},\n getApplicationNames: {},\n oldTarget: _.cloneDeep(this.panel.targets)\n };\n _.defaultsDeep(this, scopeDefaults);\n\n this.initDatasources();\n this.panelCtrl.refresh();\n }\n\n initDatasources() {\n return this.panelCtrl.initDatasources()\n .then((datasources) => {\n _.each(datasources, (datasource) => {\n this.bindSuggestionFunctions(datasource);\n });\n });\n }\n\n bindSuggestionFunctions(datasource) {\n // Map functions for bs-typeahead\n let ds = datasource.name;\n this.getGroupNames[ds] = _.bind(this.suggestGroups, this, datasource);\n this.getHostNames[ds] = _.bind(this.suggestHosts, this, datasource);\n this.getApplicationNames[ds] = _.bind(this.suggestApps, this, datasource);\n }\n\n suggestGroups(datasource, query, callback) {\n return datasource.zabbix.getAllGroups()\n .then(groups => {\n return _.map(groups, 'name');\n })\n .then(callback);\n }\n\n suggestHosts(datasource, query, callback) {\n let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);\n return datasource.zabbix.getAllHosts(groupFilter)\n .then(hosts => {\n return _.map(hosts, 'name');\n })\n .then(callback);\n }\n\n suggestApps(datasource, query, callback) {\n let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);\n let hostFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].host.filter);\n return datasource.zabbix.getAllApps(groupFilter, hostFilter)\n .then(apps => {\n return _.map(apps, 'name');\n })\n .then(callback);\n }\n\n datasourcesChanged() {\n _.each(this.panel.datasources, (ds) => {\n if (!this.panel.targets[ds]) {\n this.panel.targets[ds] = _.cloneDeep(DEFAULT_TARGET);\n }\n });\n this.parseTarget();\n }\n\n parseTarget() {\n this.initDatasources()\n .then(() => {\n var newTarget = _.cloneDeep(this.panel.targets);\n if (!_.isEqual(this.oldTarget, newTarget)) {\n this.oldTarget = newTarget;\n }\n this.panelCtrl.refresh();\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\nexport function triggerPanelTriggersTab() {\n return {\n restrict: 'E',\n scope: true,\n templateUrl: 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/triggers_tab.html',\n controller: TriggersTabCtrl,\n };\n}\n"]} \ No newline at end of file +{"version":3,"sources":["../../src/panel-triggers/triggers_tab.js"],"names":["triggerPanelTriggersTab","restrict","scope","templateUrl","controller","TriggersTabCtrl","_","utils","DEFAULT_TARGET","$scope","$rootScope","uiSegmentSrv","templateSrv","editor","panelCtrl","ctrl","panel","datasources","scopeDefaults","getGroupNames","getHostNames","getApplicationNames","oldTarget","cloneDeep","targets","defaultsDeep","initDatasources","refresh","then","each","datasource","bindSuggestionFunctions","ds","name","bind","suggestGroups","suggestHosts","suggestApps","query","callback","zabbix","getAllGroups","map","groups","groupFilter","replaceTemplateVars","group","filter","getAllHosts","hosts","hostFilter","host","getAllApps","apps","parseTarget","newTarget","isEqual","str","isRegex","isTemplateV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AAQ;AACZ,qBAAOtB,EAAEoC,GAAF,CAAMW,IAAN,EAAY,MAAZ,CAAP;AACD,aAHM,EAINzB,IAJM,CAIDW,QAJC,CAAP;AAKD;;;+CAEoB;AAAA;;AACnBjC,cAAEuB,IAAF,CAAO,KAAKb,KAAL,CAAWC,WAAlB,EAA+B,UAACe,EAAD,EAAQ;AACrC,kBAAI,CAAC,OAAKhB,KAAL,CAAWQ,OAAX,CAAmBQ,EAAnB,CAAL,EAA6B;AAC3B,uBAAKhB,KAAL,CAAWQ,OAAX,CAAmBQ,EAAnB,IAAyB1B,EAAEiB,SAAF,CAAYf,cAAZ,CAAzB;AACD;AACF,aAJD;AAKA,iBAAK8C,WAAL;AACD;;;wCAEa;AAAA;;AACZ,iBAAK5B,eAAL,GACCE,IADD,CACM,YAAM;AACV,kBAAI2B,YAAYjD,EAAEiB,SAAF,CAAY,OAAKP,KAAL,CAAWQ,OAAvB,CAAhB;AACA,kBAAI,CAAClB,EAAEkD,OAAF,CAAU,OAAKlC,SAAf,EAA0BiC,SAA1B,CAAL,EAA2C;AACzC,uBAAKjC,SAAL,GAAiBiC,SAAjB;AACD;AACD,qBAAKzC,SAAL,CAAea,OAAf;AACD,aAPD;AAQD;;;kCAEO8B,G,EAAK;AACX,mBAAOlD,MAAMmD,OAAN,CAAcD,GAAd,CAAP;AACD;;;qCAEUA,G,EAAK;AACd,mBAAOlD,MAAMoD,kBAAN,CAAyBF,GAAzB,EAA8B,KAAK7C,WAAL,CAAiBgD,SAA/C,CAAP;AACD","file":"triggers_tab.js","sourcesContent":["import _ from 'lodash';\r\nimport * as utils from '../datasource-zabbix/utils';\r\nimport {DEFAULT_TARGET} from './triggers_panel_ctrl';\r\n\r\nclass TriggersTabCtrl {\r\n\r\n /** @ngInject */\r\n constructor($scope, $rootScope, uiSegmentSrv, templateSrv) {\r\n $scope.editor = this;\r\n this.panelCtrl = $scope.ctrl;\r\n this.panel = this.panelCtrl.panel;\r\n this.templateSrv = templateSrv;\r\n this.datasources = this.panelCtrl.datasources;\r\n\r\n // Load scope defaults\r\n var scopeDefaults = {\r\n getGroupNames: {},\r\n getHostNames: {},\r\n getApplicationNames: {},\r\n oldTarget: _.cloneDeep(this.panel.targets)\r\n };\r\n _.defaultsDeep(this, scopeDefaults);\r\n\r\n this.initDatasources();\r\n this.panelCtrl.refresh();\r\n }\r\n\r\n initDatasources() {\r\n return this.panelCtrl.initDatasources()\r\n .then((datasources) => {\r\n _.each(datasources, (datasource) => {\r\n this.bindSuggestionFunctions(datasource);\r\n });\r\n });\r\n }\r\n\r\n bindSuggestionFunctions(datasource) {\r\n // Map functions for bs-typeahead\r\n let ds = datasource.name;\r\n this.getGroupNames[ds] = _.bind(this.suggestGroups, this, datasource);\r\n this.getHostNames[ds] = _.bind(this.suggestHosts, this, datasource);\r\n this.getApplicationNames[ds] = _.bind(this.suggestApps, this, datasource);\r\n }\r\n\r\n suggestGroups(datasource, query, callback) {\r\n return datasource.zabbix.getAllGroups()\r\n .then(groups => {\r\n return _.map(groups, 'name');\r\n })\r\n .then(callback);\r\n }\r\n\r\n suggestHosts(datasource, query, callback) {\r\n let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);\r\n return datasource.zabbix.getAllHosts(groupFilter)\r\n .then(hosts => {\r\n return _.map(hosts, 'name');\r\n })\r\n .then(callback);\r\n }\r\n\r\n suggestApps(datasource, query, callback) {\r\n let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);\r\n let hostFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].host.filter);\r\n return datasource.zabbix.getAllApps(groupFilter, hostFilter)\r\n .then(apps => {\r\n return _.map(apps, 'name');\r\n })\r\n .then(callback);\r\n }\r\n\r\n datasourcesChanged() {\r\n _.each(this.panel.datasources, (ds) => {\r\n if (!this.panel.targets[ds]) {\r\n this.panel.targets[ds] = _.cloneDeep(DEFAULT_TARGET);\r\n }\r\n });\r\n this.parseTarget();\r\n }\r\n\r\n parseTarget() {\r\n this.initDatasources()\r\n .then(() => {\r\n var newTarget = _.cloneDeep(this.panel.targets);\r\n if (!_.isEqual(this.oldTarget, newTarget)) {\r\n this.oldTarget = newTarget;\r\n }\r\n this.panelCtrl.refresh();\r\n });\r\n }\r\n\r\n isRegex(str) {\r\n return utils.isRegex(str);\r\n }\r\n\r\n isVariable(str) {\r\n return utils.isTemplateVariable(str, this.templateSrv.variables);\r\n }\r\n}\r\n\r\nexport function triggerPanelTriggersTab() {\r\n return {\r\n restrict: 'E',\r\n scope: true,\r\n templateUrl: 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/triggers_tab.html',\r\n controller: TriggersTabCtrl,\r\n };\r\n}\r\n"]} \ No newline at end of file diff --git a/dist/plugin.json b/dist/plugin.json index 378eb4e47..bb1442a4f 100644 --- a/dist/plugin.json +++ b/dist/plugin.json @@ -1,55 +1,55 @@ -{ - "type": "app", - "name": "Zabbix", - "id": "alexanderzobnin-zabbix-app", - - "info": { - "description": "Zabbix plugin for Grafana", - "author": { - "name": "Alexander Zobnin", - "url": "https://github.com/alexanderzobnin" - }, - "keywords": ["zabbix"], - "logos": { - "small": "img/zabbix_app_logo.svg", - "large": "img/zabbix_app_logo.svg" - }, - "links": [ - {"name": "GitHub", "url": "https://github.com/alexanderzobnin/grafana-zabbix"}, - {"name": "Docs", "url": "http://docs.grafana-zabbix.org"}, - {"name": "License", "url": "https://github.com/alexanderzobnin/grafana-zabbix/blob/master/LICENSE"} - ], - "screenshots": [ - {"name": "Showcase", "path": "img/screenshot-showcase.png"}, - {"name": "Dashboard", "path": "img/screenshot-dashboard01.png"}, - {"name": "Annotations", "path": "img/screenshot-annotations.png"}, - {"name": "Metric Editor", "path": "img/screenshot-metric_editor.png"}, - {"name": "Triggers", "path": "img/screenshot-triggers.png"} - ], - "version": "3.9.0", - "updated": "2018-03-23" - }, - - "includes": [ - { - "type": "datasource", - "name": "Zabbix Datasource" - }, - { - "type": "panel", - "name": "Triggers Panel" - }, - { - "type": "dashboard", - "name": "Zabbix Server Dashboard", - "path": "dashboards/zabbix_server_dashboard.json", - "addToNav": true, - "defaultNav": true - } - ], - - "dependencies": { - "grafanaVersion": "5.x", - "plugins": [] - } -} +{ + "type": "app", + "name": "Zabbix", + "id": "alexanderzobnin-zabbix-app", + + "info": { + "description": "Zabbix plugin for Grafana", + "author": { + "name": "Alexander Zobnin", + "url": "https://github.com/alexanderzobnin" + }, + "keywords": ["zabbix"], + "logos": { + "small": "img/zabbix_app_logo.svg", + "large": "img/zabbix_app_logo.svg" + }, + "links": [ + {"name": "GitHub", "url": "https://github.com/alexanderzobnin/grafana-zabbix"}, + {"name": "Docs", "url": "http://docs.grafana-zabbix.org"}, + {"name": "License", "url": "https://github.com/alexanderzobnin/grafana-zabbix/blob/master/LICENSE"} + ], + "screenshots": [ + {"name": "Showcase", "path": "img/screenshot-showcase.png"}, + {"name": "Dashboard", "path": "img/screenshot-dashboard01.png"}, + {"name": "Annotations", "path": "img/screenshot-annotations.png"}, + {"name": "Metric Editor", "path": "img/screenshot-metric_editor.png"}, + {"name": "Triggers", "path": "img/screenshot-triggers.png"} + ], + "version": "3.9.0", + "updated": "2018-03-23" + }, + + "includes": [ + { + "type": "datasource", + "name": "Zabbix Datasource" + }, + { + "type": "panel", + "name": "Triggers Panel" + }, + { + "type": "dashboard", + "name": "Zabbix Server Dashboard", + "path": "dashboards/zabbix_server_dashboard.json", + "addToNav": true, + "defaultNav": true + } + ], + + "dependencies": { + "grafanaVersion": "5.x", + "plugins": [] + } +} diff --git a/dist/vendor/npm/tether.min.js b/dist/vendor/npm/tether.min.js index d16b9b14e..2e55d2782 100644 --- a/dist/vendor/npm/tether.min.js +++ b/dist/vendor/npm/tether.min.js @@ -1 +1 @@ -!function(t,e){"function"==typeof define&&define.amd?define(e):"object"==typeof exports?module.exports=e(require,exports,module):t.Tether=e()}(this,function(t,e,o){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t){var e=t.getBoundingClientRect(),o={};for(var i in e)o[i]=e[i];if(t.ownerDocument!==document){var r=t.ownerDocument.defaultView.frameElement;if(r){var s=n(r);o.top+=s.top,o.bottom+=s.top,o.left+=s.left,o.right+=s.left}}return o}function r(t){var e=getComputedStyle(t)||{},o=e.position,i=[];if("fixed"===o)return[t];for(var n=t;(n=n.parentNode)&&n&&1===n.nodeType;){var r=void 0;try{r=getComputedStyle(n)}catch(s){}if("undefined"==typeof r||null===r)return i.push(n),i;var a=r,f=a.overflow,l=a.overflowX,h=a.overflowY;/(auto|scroll)/.test(f+h+l)&&("absolute"!==o||["relative","absolute","fixed"].indexOf(r.position)>=0)&&i.push(n)}return i.push(t.ownerDocument.body),t.ownerDocument!==document&&i.push(t.ownerDocument.defaultView),i}function s(){A&&document.body.removeChild(A),A=null}function a(t){var e=void 0;t===document?(e=document,t=document.documentElement):e=t.ownerDocument;var o=e.documentElement,i=n(t),r=P();return i.top-=r.top,i.left-=r.left,"undefined"==typeof i.width&&(i.width=document.body.scrollWidth-i.left-i.right),"undefined"==typeof i.height&&(i.height=document.body.scrollHeight-i.top-i.bottom),i.top=i.top-o.clientTop,i.left=i.left-o.clientLeft,i.right=e.body.clientWidth-i.width-i.left,i.bottom=e.body.clientHeight-i.height-i.top,i}function f(t){return t.offsetParent||document.documentElement}function l(){if(M)return M;var t=document.createElement("div");t.style.width="100%",t.style.height="200px";var e=document.createElement("div");h(e.style,{position:"absolute",top:0,left:0,pointerEvents:"none",visibility:"hidden",width:"200px",height:"150px",overflow:"hidden"}),e.appendChild(t),document.body.appendChild(e);var o=t.offsetWidth;e.style.overflow="scroll";var i=t.offsetWidth;o===i&&(i=e.clientWidth),document.body.removeChild(e);var n=o-i;return M={width:n,height:n}}function h(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],e=[];return Array.prototype.push.apply(e,arguments),e.slice(1).forEach(function(e){if(e)for(var o in e)({}).hasOwnProperty.call(e,o)&&(t[o]=e[o])}),t}function d(t,e){if("undefined"!=typeof t.classList)e.split(" ").forEach(function(e){e.trim()&&t.classList.remove(e)});else{var o=new RegExp("(^| )"+e.split(" ").join("|")+"( |$)","gi"),i=c(t).replace(o," ");g(t,i)}}function p(t,e){if("undefined"!=typeof t.classList)e.split(" ").forEach(function(e){e.trim()&&t.classList.add(e)});else{d(t,e);var o=c(t)+(" "+e);g(t,o)}}function u(t,e){if("undefined"!=typeof t.classList)return t.classList.contains(e);var o=c(t);return new RegExp("(^| )"+e+"( |$)","gi").test(o)}function c(t){return t.className instanceof t.ownerDocument.defaultView.SVGAnimatedString?t.className.baseVal:t.className}function g(t,e){t.setAttribute("class",e)}function m(t,e,o){o.forEach(function(o){e.indexOf(o)===-1&&u(t,o)&&d(t,o)}),e.forEach(function(e){u(t,e)||p(t,e)})}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function v(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function y(t,e){var o=arguments.length<=2||void 0===arguments[2]?1:arguments[2];return t+o>=e&&e>=t-o}function b(){return"undefined"!=typeof performance&&"undefined"!=typeof performance.now?performance.now():+new Date}function w(){for(var t={top:0,left:0},e=arguments.length,o=Array(e),i=0;i1?o-1:0),n=1;n16?(e=Math.min(e-16,250),void(o=setTimeout(n,250))):void("undefined"!=typeof t&&b()-t<10||(null!=o&&(clearTimeout(o),o=null),t=b(),X(),e=b()-t))};"undefined"!=typeof window&&"undefined"!=typeof window.addEventListener&&["resize","scroll","touchmove"].forEach(function(t){window.addEventListener(t,i)})}();var F={center:"center",left:"right",right:"left"},H={middle:"middle",top:"bottom",bottom:"top"},N={top:0,left:0,middle:"50%",center:"50%",bottom:"100%",right:"100%"},U=function(t,e){var o=t.left,i=t.top;return"auto"===o&&(o=F[e.left]),"auto"===i&&(i=H[e.top]),{left:o,top:i}},V=function(t){var e=t.left,o=t.top;return"undefined"!=typeof N[t.left]&&(e=N[t.left]),"undefined"!=typeof N[t.top]&&(o=N[t.top]),{left:e,top:o}},R=function(t){var e=t.split(" "),o=z(e,2),i=o[0],n=o[1];return{top:i,left:n}},q=R,I=function(t){function e(t){var o=this;i(this,e),j(Object.getPrototypeOf(e.prototype),"constructor",this).call(this),this.position=this.position.bind(this),D.push(this),this.history=[],this.setOptions(t,!1),x.modules.forEach(function(t){"undefined"!=typeof t.initialize&&t.initialize.call(o)}),this.position()}return v(e,t),E(e,[{key:"getClass",value:function(){var t=arguments.length<=0||void 0===arguments[0]?"":arguments[0],e=this.options.classes;return"undefined"!=typeof e&&e[t]?this.options.classes[t]:this.options.classPrefix?this.options.classPrefix+"-"+t:t}},{key:"setOptions",value:function(t){var e=this,o=arguments.length<=1||void 0===arguments[1]||arguments[1],i={offset:"0 0",targetOffset:"0 0",targetAttachment:"auto auto",classPrefix:"tether"};this.options=h(i,t);var n=this.options,s=n.element,a=n.target,f=n.targetModifier;if(this.element=s,this.target=a,this.targetModifier=f,"viewport"===this.target?(this.target=document.body,this.targetModifier="visible"):"scroll-handle"===this.target&&(this.target=document.body,this.targetModifier="scroll-handle"),["element","target"].forEach(function(t){if("undefined"==typeof e[t])throw new Error("Tether Error: Both element and target must be defined");"undefined"!=typeof e[t].jquery?e[t]=e[t][0]:"string"==typeof e[t]&&(e[t]=document.querySelector(e[t]))}),p(this.element,this.getClass("element")),this.options.addTargetClasses!==!1&&p(this.target,this.getClass("target")),!this.options.attachment)throw new Error("Tether Error: You must provide an attachment");this.targetAttachment=q(this.options.targetAttachment),this.attachment=q(this.options.attachment),this.offset=R(this.options.offset),this.targetOffset=R(this.options.targetOffset),"undefined"!=typeof this.scrollParents&&this.disable(),"scroll-handle"===this.targetModifier?this.scrollParents=[this.target]:this.scrollParents=r(this.target),this.options.enabled!==!1&&this.enable(o)}},{key:"getTargetBounds",value:function(){if("undefined"==typeof this.targetModifier)return a(this.target);if("visible"===this.targetModifier){if(this.target===document.body)return{top:pageYOffset,left:pageXOffset,height:innerHeight,width:innerWidth};var t=a(this.target),e={height:t.height,width:t.width,top:t.top,left:t.left};return e.height=Math.min(e.height,t.height-(pageYOffset-t.top)),e.height=Math.min(e.height,t.height-(t.top+t.height-(pageYOffset+innerHeight))),e.height=Math.min(innerHeight,e.height),e.height-=2,e.width=Math.min(e.width,t.width-(pageXOffset-t.left)),e.width=Math.min(e.width,t.width-(t.left+t.width-(pageXOffset+innerWidth))),e.width=Math.min(innerWidth,e.width),e.width-=2,e.topo.clientWidth||[i.overflow,i.overflowX].indexOf("scroll")>=0||this.target!==document.body,r=0;n&&(r=15);var s=t.height-parseFloat(i.borderTopWidth)-parseFloat(i.borderBottomWidth)-r,e={width:15,height:.975*s*(s/o.scrollHeight),left:t.left+t.width-parseFloat(i.borderLeftWidth)-15},f=0;s<408&&this.target===document.body&&(f=-11e-5*Math.pow(s,2)-.00727*s+22.58),this.target!==document.body&&(e.height=Math.max(e.height,24));var l=this.target.scrollTop/(o.scrollHeight-s);return e.top=l*(s-e.height-f)+t.top+parseFloat(i.borderTopWidth),this.target===document.body&&(e.height=Math.max(e.height,24)),e}}},{key:"clearCache",value:function(){this._cache={}}},{key:"cache",value:function(t,e){return"undefined"==typeof this._cache&&(this._cache={}),"undefined"==typeof this._cache[t]&&(this._cache[t]=e.call(this)),this._cache[t]}},{key:"enable",value:function(){var t=this,e=arguments.length<=0||void 0===arguments[0]||arguments[0];this.options.addTargetClasses!==!1&&p(this.target,this.getClass("enabled")),p(this.element,this.getClass("enabled")),this.enabled=!0,this.scrollParents.forEach(function(e){e!==t.target.ownerDocument&&e.addEventListener("scroll",t.position)}),e&&this.position()}},{key:"disable",value:function(){var t=this;d(this.target,this.getClass("enabled")),d(this.element,this.getClass("enabled")),this.enabled=!1,"undefined"!=typeof this.scrollParents&&this.scrollParents.forEach(function(e){e.removeEventListener("scroll",t.position)})}},{key:"destroy",value:function(){var t=this;this.disable(),D.forEach(function(e,o){e===t&&D.splice(o,1)}),0===D.length&&s()}},{key:"updateAttachClasses",value:function(t,e){var o=this;t=t||this.attachment,e=e||this.targetAttachment;var i=["left","top","bottom","right","middle","center"];"undefined"!=typeof this._addAttachClasses&&this._addAttachClasses.length&&this._addAttachClasses.splice(0,this._addAttachClasses.length),"undefined"==typeof this._addAttachClasses&&(this._addAttachClasses=[]);var n=this._addAttachClasses;t.top&&n.push(this.getClass("element-attached")+"-"+t.top),t.left&&n.push(this.getClass("element-attached")+"-"+t.left),e.top&&n.push(this.getClass("target-attached")+"-"+e.top),e.left&&n.push(this.getClass("target-attached")+"-"+e.left);var r=[];i.forEach(function(t){r.push(o.getClass("element-attached")+"-"+t),r.push(o.getClass("target-attached")+"-"+t)}),k(function(){"undefined"!=typeof o._addAttachClasses&&(m(o.element,o._addAttachClasses,r),o.options.addTargetClasses!==!1&&m(o.target,o._addAttachClasses,r),delete o._addAttachClasses)})}},{key:"position",value:function(){var t=this,e=arguments.length<=0||void 0===arguments[0]||arguments[0];if(this.enabled){this.clearCache();var o=U(this.targetAttachment,this.attachment);this.updateAttachClasses(this.attachment,o);var i=this.cache("element-bounds",function(){return a(t.element)}),n=i.width,r=i.height;if(0===n&&0===r&&"undefined"!=typeof this.lastSize){var s=this.lastSize;n=s.width,r=s.height}else this.lastSize={width:n,height:r};var h=this.cache("target-bounds",function(){return t.getTargetBounds()}),d=h,p=C(V(this.attachment),{width:n,height:r}),u=C(V(o),d),c=C(this.offset,{width:n,height:r}),g=C(this.targetOffset,d);p=w(p,c),u=w(u,g);for(var m=h.left+u.left-p.left,v=h.top+u.top-p.top,y=0;yA.documentElement.clientHeight&&(S=this.cache("scrollbar-size",l),E.viewport.bottom-=S.height),T.innerWidth>A.documentElement.clientWidth&&(S=this.cache("scrollbar-size",l),E.viewport.right-=S.width),["","static"].indexOf(A.body.style.position)!==-1&&["","static"].indexOf(A.body.parentElement.style.position)!==-1||(E.page.bottom=A.body.scrollHeight-v-r,E.page.right=A.body.scrollWidth-m-n),"undefined"!=typeof this.options.optimizations&&this.options.optimizations.moveElement!==!1&&"undefined"==typeof this.targetModifier&&!function(){var e=t.cache("target-offsetparent",function(){return f(t.target)}),o=t.cache("target-offsetparent-bounds",function(){return a(e)}),i=getComputedStyle(e),n=o,r={};if(["Top","Left","Bottom","Right"].forEach(function(t){r[t.toLowerCase()]=parseFloat(i["border"+t+"Width"])}),o.right=A.body.scrollWidth-o.left-n.width+r.right,o.bottom=A.body.scrollHeight-o.top-n.height+r.bottom,E.page.top>=o.top+r.top&&E.page.bottom>=o.bottom&&E.page.left>=o.left+r.left&&E.page.right>=o.right){var s=e.scrollTop,l=e.scrollLeft;E.offset={top:E.page.top-o.top+s-r.top,left:E.page.left-o.left+l-r.left}}}(),this.move(E),this.history.unshift(E),this.history.length>3&&this.history.pop(),e&&_(),!0}}},{key:"move",value:function(t){var e=this;if("undefined"!=typeof this.element.parentNode){var o={};for(var i in t){o[i]={};for(var n in t[i]){for(var r=!1,s=0;s=0){var c=a.split(" "),m=z(c,2);d=m[0],h=m[1]}else h=d=a;var b=O(e,r);"target"!==d&&"both"!==d||(ob[3]&&"bottom"===v.top&&(o-=p,v.top="top")),"together"===d&&("top"===v.top&&("bottom"===y.top&&ob[3]&&o-(s-p)>=b[1]&&(o-=s-p,v.top="bottom",y.top="bottom")),"bottom"===v.top&&("top"===y.top&&o+s>b[3]?(o-=p,v.top="top",o-=s,y.top="bottom"):"bottom"===y.top&&ob[3]&&"top"===y.top?(o-=s,y.top="bottom"):ob[2]&&"right"===v.left&&(i-=u,v.left="left")),"together"===h&&(ib[2]&&"right"===v.left?"left"===y.left?(i-=u,v.left="left",i-=f,y.left="right"):"right"===y.left&&(i-=u,v.left="left",i+=f,y.left="left"):"center"===v.left&&(i+f>b[2]&&"left"===y.left?(i-=f,y.left="right"):ib[3]&&"top"===y.top&&(o-=s,y.top="bottom")),"element"!==h&&"both"!==h||(ib[2]&&("left"===y.left?(i-=f,y.left="right"):"center"===y.left&&(i-=f/2,y.left="right"))),"string"==typeof l?l=l.split(",").map(function(t){return t.trim()}):l===!0&&(l=["top","left","right","bottom"]),l=l||[];var w=[],C=[];o=0?(o=b[1],w.push("top")):C.push("top")),o+s>b[3]&&(l.indexOf("bottom")>=0?(o=b[3]-s,w.push("bottom")):C.push("bottom")),i=0?(i=b[0],w.push("left")):C.push("left")),i+f>b[2]&&(l.indexOf("right")>=0?(i=b[2]-f,w.push("right")):C.push("right")),w.length&&!function(){var t=void 0;t="undefined"!=typeof e.options.pinnedClass?e.options.pinnedClass:e.getClass("pinned"),g.push(t),w.forEach(function(e){g.push(t+"-"+e)})}(),C.length&&!function(){var t=void 0;t="undefined"!=typeof e.options.outOfBoundsClass?e.options.outOfBoundsClass:e.getClass("out-of-bounds"),g.push(t),C.forEach(function(e){g.push(t+"-"+e)})}(),(w.indexOf("left")>=0||w.indexOf("right")>=0)&&(y.left=v.left=!1),(w.indexOf("top")>=0||w.indexOf("bottom")>=0)&&(y.top=v.top=!1),v.top===n.top&&v.left===n.left&&y.top===e.attachment.top&&y.left===e.attachment.left||(e.updateAttachClasses(y,v),e.trigger("update",{attachment:y,targetAttachment:v}))}),k(function(){e.options.addTargetClasses!==!1&&m(e.target,g,c),m(e.element,g,c)}),{top:o,left:i}}});var Y=x.Utils,a=Y.getBounds,m=Y.updateClasses,k=Y.defer;x.modules.push({position:function(t){var e=this,o=t.top,i=t.left,n=this.cache("element-bounds",function(){return a(e.element)}),r=n.height,s=n.width,f=this.getTargetBounds(),l=o+r,h=i+s,d=[];o<=f.bottom&&l>=f.top&&["left","right"].forEach(function(t){var e=f[t];e!==i&&e!==h||d.push(t)}),i<=f.right&&h>=f.left&&["top","bottom"].forEach(function(t){var e=f[t];e!==o&&e!==l||d.push(t)});var p=[],u=[],c=["left","top","right","bottom"];return p.push(this.getClass("abutted")),c.forEach(function(t){p.push(e.getClass("abutted")+"-"+t)}),d.length&&u.push(this.getClass("abutted")),d.forEach(function(t){u.push(e.getClass("abutted")+"-"+t)}),k(function(){e.options.addTargetClasses!==!1&&m(e.target,u,p),m(e.element,u,p)}),!0}});var z=function(){function t(t,e){var o=[],i=!0,n=!1,r=void 0;try{for(var s,a=t[Symbol.iterator]();!(i=(s=a.next()).done)&&(o.push(s.value),!e||o.length!==e);i=!0);}catch(f){n=!0,r=f}finally{try{!i&&a["return"]&&a["return"]()}finally{if(n)throw r}}return o}return function(e,o){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,o);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();return x.modules.push({position:function(t){var e=t.top,o=t.left;if(this.options.shift){var i=this.options.shift;"function"==typeof this.options.shift&&(i=this.options.shift.call(this,{top:e,left:o}));var n=void 0,r=void 0;if("string"==typeof i){i=i.split(" "),i[1]=i[1]||i[0];var s=i,a=z(s,2);n=a[0],r=a[1],n=parseFloat(n,10),r=parseFloat(r,10)}else n=i.top,r=i.left;return e+=n,o+=r,{top:e,left:o}}}}),$}); \ No newline at end of file +!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.Tether=e()}(this,function(){"use strict";function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t){var o=t.getBoundingClientRect(),i={};for(var n in o)i[n]=o[n];if(t.ownerDocument!==document){var r=t.ownerDocument.defaultView.frameElement;if(r){var s=e(r);i.top+=s.top,i.bottom+=s.top,i.left+=s.left,i.right+=s.left}}return i}function o(t){var e=getComputedStyle(t)||{},o=e.position,i=[];if("fixed"===o)return[t];for(var n=t;(n=n.parentNode)&&n&&1===n.nodeType;){var r=void 0;try{r=getComputedStyle(n)}catch(s){}if("undefined"==typeof r||null===r)return i.push(n),i;var a=r,f=a.overflow,l=a.overflowX,h=a.overflowY;/(auto|scroll|overlay)/.test(f+h+l)&&("absolute"!==o||["relative","absolute","fixed"].indexOf(r.position)>=0)&&i.push(n)}return i.push(t.ownerDocument.body),t.ownerDocument!==document&&i.push(t.ownerDocument.defaultView),i}function i(){O&&document.body.removeChild(O),O=null}function n(t){var o=void 0;t===document?(o=document,t=document.documentElement):o=t.ownerDocument;var i=o.documentElement,n=e(t),r=A();return n.top-=r.top,n.left-=r.left,"undefined"==typeof n.width&&(n.width=document.body.scrollWidth-n.left-n.right),"undefined"==typeof n.height&&(n.height=document.body.scrollHeight-n.top-n.bottom),n.top=n.top-i.clientTop,n.left=n.left-i.clientLeft,n.right=o.body.clientWidth-n.width-n.left,n.bottom=o.body.clientHeight-n.height-n.top,n}function r(t){return t.offsetParent||document.documentElement}function s(){if(T)return T;var t=document.createElement("div");t.style.width="100%",t.style.height="200px";var e=document.createElement("div");a(e.style,{position:"absolute",top:0,left:0,pointerEvents:"none",visibility:"hidden",width:"200px",height:"150px",overflow:"hidden"}),e.appendChild(t),document.body.appendChild(e);var o=t.offsetWidth;e.style.overflow="scroll";var i=t.offsetWidth;o===i&&(i=e.clientWidth),document.body.removeChild(e);var n=o-i;return T={width:n,height:n}}function a(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],e=[];return Array.prototype.push.apply(e,arguments),e.slice(1).forEach(function(e){if(e)for(var o in e)({}).hasOwnProperty.call(e,o)&&(t[o]=e[o])}),t}function f(t,e){if("undefined"!=typeof t.classList)e.split(" ").forEach(function(e){e.trim()&&t.classList.remove(e)});else{var o=new RegExp("(^| )"+e.split(" ").join("|")+"( |$)","gi"),i=d(t).replace(o," ");p(t,i)}}function l(t,e){if("undefined"!=typeof t.classList)e.split(" ").forEach(function(e){e.trim()&&t.classList.add(e)});else{f(t,e);var o=d(t)+(" "+e);p(t,o)}}function h(t,e){if("undefined"!=typeof t.classList)return t.classList.contains(e);var o=d(t);return new RegExp("(^| )"+e+"( |$)","gi").test(o)}function d(t){return t.className instanceof t.ownerDocument.defaultView.SVGAnimatedString?t.className.baseVal:t.className}function p(t,e){t.setAttribute("class",e)}function u(t,e,o){o.forEach(function(o){e.indexOf(o)===-1&&h(t,o)&&f(t,o)}),e.forEach(function(e){h(t,e)||l(t,e)})}function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function c(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function g(t,e){var o=arguments.length<=2||void 0===arguments[2]?1:arguments[2];return t+o>=e&&e>=t-o}function m(){return"object"==typeof performance&&"function"==typeof performance.now?performance.now():+new Date}function v(){for(var t={top:0,left:0},e=arguments.length,o=Array(e),i=0;i1?o-1:0),n=1;n16?(e=Math.min(e-16,250),void(o=setTimeout(n,250))):void("undefined"!=typeof t&&m()-t<10||(null!=o&&(clearTimeout(o),o=null),t=m(),Y(),e=m()-t))};"undefined"!=typeof window&&"undefined"!=typeof window.addEventListener&&["resize","scroll","touchmove"].forEach(function(t){window.addEventListener(t,i)})}();var L={center:"center",left:"right",right:"left"},D={middle:"middle",top:"bottom",bottom:"top"},X={top:0,left:0,middle:"50%",center:"50%",bottom:"100%",right:"100%"},F=function(t,e){var o=t.left,i=t.top;return"auto"===o&&(o=L[e.left]),"auto"===i&&(i=D[e.top]),{left:o,top:i}},H=function(t){var e=t.left,o=t.top;return"undefined"!=typeof X[t.left]&&(e=X[t.left]),"undefined"!=typeof X[t.top]&&(o=X[t.top]),{left:e,top:o}},N=function(t){var e=t.split(" "),o=k(e,2),i=o[0],n=o[1];return{top:i,left:n}},U=N,V=function(e){function h(e){var o=this;t(this,h),_(Object.getPrototypeOf(h.prototype),"constructor",this).call(this),this.position=this.position.bind(this),z.push(this),this.history=[],this.setOptions(e,!1),C.modules.forEach(function(t){"undefined"!=typeof t.initialize&&t.initialize.call(o)}),this.position()}return c(h,e),w(h,[{key:"getClass",value:function(){var t=arguments.length<=0||void 0===arguments[0]?"":arguments[0],e=this.options.classes;return"undefined"!=typeof e&&e[t]?this.options.classes[t]:this.options.classPrefix?this.options.classPrefix+"-"+t:t}},{key:"setOptions",value:function(t){var e=this,i=arguments.length<=1||void 0===arguments[1]||arguments[1],n={offset:"0 0",targetOffset:"0 0",targetAttachment:"auto auto",classPrefix:"tether"};this.options=a(n,t);var r=this.options,s=r.element,f=r.target,h=r.targetModifier;if(this.element=s,this.target=f,this.targetModifier=h,"viewport"===this.target?(this.target=document.body,this.targetModifier="visible"):"scroll-handle"===this.target&&(this.target=document.body,this.targetModifier="scroll-handle"),["element","target"].forEach(function(t){if("undefined"==typeof e[t])throw new Error("Tether Error: Both element and target must be defined");"undefined"!=typeof e[t].jquery?e[t]=e[t][0]:"string"==typeof e[t]&&(e[t]=document.querySelector(e[t]))}),l(this.element,this.getClass("element")),this.options.addTargetClasses!==!1&&l(this.target,this.getClass("target")),!this.options.attachment)throw new Error("Tether Error: You must provide an attachment");this.targetAttachment=U(this.options.targetAttachment),this.attachment=U(this.options.attachment),this.offset=N(this.options.offset),this.targetOffset=N(this.options.targetOffset),"undefined"!=typeof this.scrollParents&&this.disable(),"scroll-handle"===this.targetModifier?this.scrollParents=[this.target]:this.scrollParents=o(this.target),this.options.enabled!==!1&&this.enable(i)}},{key:"getTargetBounds",value:function(){if("undefined"==typeof this.targetModifier)return n(this.target);if("visible"===this.targetModifier){if(this.target===document.body)return{top:pageYOffset,left:pageXOffset,height:innerHeight,width:innerWidth};var t=n(this.target),e={height:t.height,width:t.width,top:t.top,left:t.left};return e.height=Math.min(e.height,t.height-(pageYOffset-t.top)),e.height=Math.min(e.height,t.height-(t.top+t.height-(pageYOffset+innerHeight))),e.height=Math.min(innerHeight,e.height),e.height-=2,e.width=Math.min(e.width,t.width-(pageXOffset-t.left)),e.width=Math.min(e.width,t.width-(t.left+t.width-(pageXOffset+innerWidth))),e.width=Math.min(innerWidth,e.width),e.width-=2,e.topo.clientWidth||[i.overflow,i.overflowX].indexOf("scroll")>=0||this.target!==document.body,s=0;r&&(s=15);var a=t.height-parseFloat(i.borderTopWidth)-parseFloat(i.borderBottomWidth)-s,e={width:15,height:.975*a*(a/o.scrollHeight),left:t.left+t.width-parseFloat(i.borderLeftWidth)-15},f=0;a<408&&this.target===document.body&&(f=-11e-5*Math.pow(a,2)-.00727*a+22.58),this.target!==document.body&&(e.height=Math.max(e.height,24));var l=this.target.scrollTop/(o.scrollHeight-a);return e.top=l*(a-e.height-f)+t.top+parseFloat(i.borderTopWidth),this.target===document.body&&(e.height=Math.max(e.height,24)),e}}},{key:"clearCache",value:function(){this._cache={}}},{key:"cache",value:function(t,e){return"undefined"==typeof this._cache&&(this._cache={}),"undefined"==typeof this._cache[t]&&(this._cache[t]=e.call(this)),this._cache[t]}},{key:"enable",value:function(){var t=this,e=arguments.length<=0||void 0===arguments[0]||arguments[0];this.options.addTargetClasses!==!1&&l(this.target,this.getClass("enabled")),l(this.element,this.getClass("enabled")),this.enabled=!0,this.scrollParents.forEach(function(e){e!==t.target.ownerDocument&&e.addEventListener("scroll",t.position)}),e&&this.position()}},{key:"disable",value:function(){var t=this;f(this.target,this.getClass("enabled")),f(this.element,this.getClass("enabled")),this.enabled=!1,"undefined"!=typeof this.scrollParents&&this.scrollParents.forEach(function(e){e.removeEventListener("scroll",t.position)})}},{key:"destroy",value:function(){var t=this;this.disable(),z.forEach(function(e,o){e===t&&z.splice(o,1)}),0===z.length&&i()}},{key:"updateAttachClasses",value:function(t,e){var o=this;t=t||this.attachment,e=e||this.targetAttachment;var i=["left","top","bottom","right","middle","center"];"undefined"!=typeof this._addAttachClasses&&this._addAttachClasses.length&&this._addAttachClasses.splice(0,this._addAttachClasses.length),"undefined"==typeof this._addAttachClasses&&(this._addAttachClasses=[]);var n=this._addAttachClasses;t.top&&n.push(this.getClass("element-attached")+"-"+t.top),t.left&&n.push(this.getClass("element-attached")+"-"+t.left),e.top&&n.push(this.getClass("target-attached")+"-"+e.top),e.left&&n.push(this.getClass("target-attached")+"-"+e.left);var r=[];i.forEach(function(t){r.push(o.getClass("element-attached")+"-"+t),r.push(o.getClass("target-attached")+"-"+t)}),P(function(){"undefined"!=typeof o._addAttachClasses&&(u(o.element,o._addAttachClasses,r),o.options.addTargetClasses!==!1&&u(o.target,o._addAttachClasses,r),delete o._addAttachClasses)})}},{key:"position",value:function(){var t=this,e=arguments.length<=0||void 0===arguments[0]||arguments[0];if(this.enabled){this.clearCache();var o=F(this.targetAttachment,this.attachment);this.updateAttachClasses(this.attachment,o);var i=this.cache("element-bounds",function(){return n(t.element)}),a=i.width,f=i.height;if(0===a&&0===f&&"undefined"!=typeof this.lastSize){var l=this.lastSize;a=l.width,f=l.height}else this.lastSize={width:a,height:f};var h=this.cache("target-bounds",function(){return t.getTargetBounds()}),d=h,p=y(H(this.attachment),{width:a,height:f}),u=y(H(o),d),c=y(this.offset,{width:a,height:f}),g=y(this.targetOffset,d);p=v(p,c),u=v(u,g);for(var m=h.left+u.left-p.left,b=h.top+u.top-p.top,w=0;wA.documentElement.clientHeight&&(S=this.cache("scrollbar-size",s),x.viewport.bottom-=S.height),T.innerWidth>A.documentElement.clientWidth&&(S=this.cache("scrollbar-size",s),x.viewport.right-=S.width),["","static"].indexOf(A.body.style.position)!==-1&&["","static"].indexOf(A.body.parentElement.style.position)!==-1||(x.page.bottom=A.body.scrollHeight-b-f,x.page.right=A.body.scrollWidth-m-a),"undefined"!=typeof this.options.optimizations&&this.options.optimizations.moveElement!==!1&&"undefined"==typeof this.targetModifier&&!function(){var e=t.cache("target-offsetparent",function(){return r(t.target)}),o=t.cache("target-offsetparent-bounds",function(){return n(e)}),i=getComputedStyle(e),s=o,a={};if(["Top","Left","Bottom","Right"].forEach(function(t){a[t.toLowerCase()]=parseFloat(i["border"+t+"Width"])}),o.right=A.body.scrollWidth-o.left-s.width+a.right,o.bottom=A.body.scrollHeight-o.top-s.height+a.bottom,x.page.top>=o.top+a.top&&x.page.bottom>=o.bottom&&x.page.left>=o.left+a.left&&x.page.right>=o.right){var f=e.scrollTop,l=e.scrollLeft;x.offset={top:x.page.top-o.top+f-a.top,left:x.page.left-o.left+l-a.left}}}(),this.move(x),this.history.unshift(x),this.history.length>3&&this.history.pop(),e&&M(),!0}}},{key:"move",value:function(t){var e=this;if("undefined"!=typeof this.element.parentNode){var o={};for(var i in t){o[i]={};for(var n in t[i]){for(var s=!1,f=0;f=0){var u=s.split(" "),g=k(u,2);d=g[0],h=g[1]}else h=d=s;var w=b(e,n);"target"!==d&&"both"!==d||(ow[3]&&"bottom"===v.top&&(o-=p,v.top="top")),"together"===d&&("top"===v.top&&("bottom"===y.top&&ow[3]&&o-(f-p)>=w[1]&&(o-=f-p,v.top="bottom",y.top="bottom")),"bottom"===v.top&&("top"===y.top&&o+f>w[3]?(o-=p,v.top="top",o-=f,y.top="bottom"):"bottom"===y.top&&ow[3]&&"top"===y.top?(o-=f,y.top="bottom"):ow[2]&&"right"===v.left&&(i-=c,v.left="left")),"together"===h&&(iw[2]&&"right"===v.left?"left"===y.left?(i-=c,v.left="left",i-=l,y.left="right"):"right"===y.left&&(i-=c,v.left="left",i+=l,y.left="left"):"center"===v.left&&(i+l>w[2]&&"left"===y.left?(i-=l,y.left="right"):iw[3]&&"top"===y.top&&(o-=f,y.top="bottom")),"element"!==h&&"both"!==h||(iw[2]&&("left"===y.left?(i-=l,y.left="right"):"center"===y.left&&(i-=l/2,y.left="right"))),"string"==typeof a?a=a.split(",").map(function(t){return t.trim()}):a===!0&&(a=["top","left","right","bottom"]),a=a||[];var C=[],O=[];o=0?(o=w[1],C.push("top")):O.push("top")),o+f>w[3]&&(a.indexOf("bottom")>=0?(o=w[3]-f,C.push("bottom")):O.push("bottom")),i=0?(i=w[0],C.push("left")):O.push("left")),i+l>w[2]&&(a.indexOf("right")>=0?(i=w[2]-l,C.push("right")):O.push("right")),C.length&&!function(){var t=void 0;t="undefined"!=typeof e.options.pinnedClass?e.options.pinnedClass:e.getClass("pinned"),m.push(t),C.forEach(function(e){m.push(t+"-"+e)})}(),O.length&&!function(){var t=void 0;t="undefined"!=typeof e.options.outOfBoundsClass?e.options.outOfBoundsClass:e.getClass("out-of-bounds"),m.push(t),O.forEach(function(e){m.push(t+"-"+e)})}(),(C.indexOf("left")>=0||C.indexOf("right")>=0)&&(y.left=v.left=!1),(C.indexOf("top")>=0||C.indexOf("bottom")>=0)&&(y.top=v.top=!1),v.top===r.top&&v.left===r.left&&y.top===e.attachment.top&&y.left===e.attachment.left||(e.updateAttachClasses(y,v),e.trigger("update",{attachment:y,targetAttachment:v}))}),P(function(){e.options.addTargetClasses!==!1&&u(e.target,m,g),u(e.element,m,g)}),{top:o,left:i}}});var B=C.Utils,n=B.getBounds,u=B.updateClasses,P=B.defer;C.modules.push({position:function(t){var e=this,o=t.top,i=t.left,r=this.cache("element-bounds",function(){return n(e.element)}),s=r.height,a=r.width,f=this.getTargetBounds(),l=o+s,h=i+a,d=[];o<=f.bottom&&l>=f.top&&["left","right"].forEach(function(t){var e=f[t];e!==i&&e!==h||d.push(t)}),i<=f.right&&h>=f.left&&["top","bottom"].forEach(function(t){var e=f[t];e!==o&&e!==l||d.push(t)});var p=[],c=[],g=["left","top","right","bottom"];return p.push(this.getClass("abutted")),g.forEach(function(t){p.push(e.getClass("abutted")+"-"+t)}),d.length&&c.push(this.getClass("abutted")),d.forEach(function(t){c.push(e.getClass("abutted")+"-"+t)}),P(function(){e.options.addTargetClasses!==!1&&u(e.target,c,p),u(e.element,c,p)}),!0}});var k=function(){function t(t,e){var o=[],i=!0,n=!1,r=void 0;try{for(var s,a=t[Symbol.iterator]();!(i=(s=a.next()).done)&&(o.push(s.value),!e||o.length!==e);i=!0);}catch(f){n=!0,r=f}finally{try{!i&&a["return"]&&a["return"]()}finally{if(n)throw r}}return o}return function(e,o){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return t(e,o);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();return C.modules.push({position:function(t){var e=t.top,o=t.left;if(this.options.shift){var i=this.options.shift;"function"==typeof this.options.shift&&(i=this.options.shift.call(this,{top:e,left:o}));var n=void 0,r=void 0;if("string"==typeof i){i=i.split(" "),i[1]=i[1]||i[0];var s=i,a=k(s,2);n=a[0],r=a[1],n=parseFloat(n,10),r=parseFloat(r,10)}else n=i.top,r=i.left;return e+=n,o+=r,{top:e,left:o}}}}),R}); \ No newline at end of file diff --git a/package.json b/package.json index 718ce9a70..d5806c96d 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "url": "https://github.com/alexanderzobnin/grafana-zabbix/issues" }, "devDependencies": { - "babel": "~6.5.1", + "babel": "^6.23.0", "babel-jest": "^21.2.0", "babel-plugin-transform-es2015-for-of": "^6.6.0", "babel-plugin-transform-es2015-modules-systemjs": "^6.5.0", @@ -46,12 +46,16 @@ "jsdom": "~11.3.0", "jshint-stylish": "^2.1.0", "load-grunt-tasks": "~3.2.0", - "moment": "~2.21.0", + "moment": "^2.22.1", "q": "~1.4.1", "tether-drop": "^1.4.2" }, "dependencies": { + "loadash": "^1.0.0", "lodash": "~4.0.0", + "node-gyp": "^3.6.2", + "node-sass": "^3.13.1", + "python2": "0.0.1", "systemjs": "^0.20.19" }, "homepage": "http://grafana-zabbix.org" diff --git a/src/datasource-zabbix/dataProcessor.js b/src/datasource-zabbix/dataProcessor.js index f45470ab8..837bb6f6a 100644 --- a/src/datasource-zabbix/dataProcessor.js +++ b/src/datasource-zabbix/dataProcessor.js @@ -36,6 +36,33 @@ function limit(order, n, orderByFunc, timeseries) { } } +function removeAboveValue(n, datapoints) { + return _.map(datapoints, point => { + return [ + (point[0] > n) ? null : point[0], + point[1] + ]; + }); +} + +function removeBelowValue(n, datapoints) { + return _.map(datapoints, point => { + return [ + (point[0] < n) ? null : point[0], + point[1] + ]; + }); +} + +function transformNull(n, datapoints) { + return _.map(datapoints, point => { + return [ + (point[0] !== null) ? point[0] : n, + point[1] + ]; + }); +} + function sortSeries(direction, timeseries) { return _.orderBy(timeseries, [function (ts) { return ts.target.toLowerCase(); @@ -121,6 +148,7 @@ let metricFunctions = { rate: rate, movingAverage: simpleMovingAverage, exponentialMovingAverage: expMovingAverage, + transformNull: transformNull, aggregateBy: aggregateByWrapper, // Predefined aggs percentil: percentil, @@ -131,6 +159,8 @@ let metricFunctions = { sum: _.partial(aggregateWrapper, SUM), count: _.partial(aggregateWrapper, COUNT), sumSeries: sumSeries, + removeAboveValue: removeAboveValue, + removeBelowValue: removeBelowValue, top: _.partial(limit, 'top'), bottom: _.partial(limit, 'bottom'), sortSeries: sortSeries, diff --git a/src/datasource-zabbix/metricFunctions.js b/src/datasource-zabbix/metricFunctions.js index 261b28460..0ca0fe2d5 100644 --- a/src/datasource-zabbix/metricFunctions.js +++ b/src/datasource-zabbix/metricFunctions.js @@ -76,6 +76,15 @@ addFuncDef({ defaultParams: [0.2], }); +addFuncDef({ + name: 'transformNull', + category: 'Transform', + params: [ + {name: 'number', type: 'float'} + ], + defaultParams: [0], +}); + // Aggregate addFuncDef({ @@ -161,6 +170,24 @@ addFuncDef({ // Filter +addFuncDef({ + name: 'removeAboveValue', + category: 'Filter', + params: [ + {name: 'number', type: 'float'}, + ], + defaultParams: [0], +}); + +addFuncDef({ + name: 'removeBelowValue', + category: 'Filter', + params: [ + {name: 'number', type: 'float'}, + ], + defaultParams: [0], +}); + addFuncDef({ name: 'top', category: 'Filter',