changed var to const 2 (#13068)

* changed var to const

* fixed typo created in last commit

* added or empty object to options in prometheus/datasource
pull/13071/head
Patrick O'Carroll 7 years ago committed by Torkel Ödegaard
parent 5e0d0c5816
commit a702603e7b
  1. 14
      public/app/core/components/grafana_app.ts
  2. 15
      public/app/core/services/backend_srv.ts
  3. 18
      public/app/core/time_series2.ts
  4. 10
      public/app/features/annotations/annotation_tooltip.ts
  5. 10
      public/app/features/annotations/annotations_srv.ts
  6. 2
      public/app/features/annotations/editor_ctrl.ts
  7. 4
      public/app/features/annotations/event_manager.ts
  8. 20
      public/app/features/panellinks/link_srv.ts
  9. 6
      public/app/features/plugins/datasource_srv.ts
  10. 76
      public/app/plugins/datasource/cloudwatch/datasource.ts
  11. 10
      public/app/plugins/datasource/elasticsearch/bucket_agg.ts
  12. 2
      public/app/plugins/datasource/elasticsearch/config_ctrl.ts
  13. 90
      public/app/plugins/datasource/elasticsearch/datasource.ts
  14. 60
      public/app/plugins/datasource/elasticsearch/elastic_response.ts
  15. 8
      public/app/plugins/datasource/elasticsearch/index_pattern.ts
  16. 24
      public/app/plugins/datasource/elasticsearch/metric_agg.ts
  17. 28
      public/app/plugins/datasource/elasticsearch/query_builder.ts
  18. 16
      public/app/plugins/datasource/elasticsearch/query_ctrl.ts
  19. 16
      public/app/plugins/datasource/elasticsearch/query_def.ts
  20. 2
      public/app/plugins/datasource/grafana/datasource.ts
  21. 34
      public/app/plugins/datasource/graphite/datasource.ts
  22. 48
      public/app/plugins/datasource/influxdb/datasource.ts
  23. 30
      public/app/plugins/datasource/influxdb/influx_query.ts
  24. 34
      public/app/plugins/datasource/influxdb/influx_series.ts
  25. 2
      public/app/plugins/datasource/influxdb/query_builder.ts
  26. 30
      public/app/plugins/datasource/influxdb/query_ctrl.ts
  27. 22
      public/app/plugins/datasource/influxdb/query_part.ts
  28. 8
      public/app/plugins/datasource/influxdb/response_parser.ts
  29. 4
      public/app/plugins/datasource/mssql/datasource.ts
  30. 2
      public/app/plugins/datasource/mssql/response_parser.ts
  31. 6
      public/app/plugins/datasource/mysql/datasource.ts
  32. 2
      public/app/plugins/datasource/mysql/response_parser.ts
  33. 84
      public/app/plugins/datasource/opentsdb/datasource.ts
  34. 4
      public/app/plugins/datasource/opentsdb/query_ctrl.ts
  35. 6
      public/app/plugins/datasource/postgres/datasource.ts
  36. 2
      public/app/plugins/datasource/postgres/response_parser.ts
  37. 24
      public/app/plugins/datasource/prometheus/completer.ts
  38. 60
      public/app/plugins/datasource/prometheus/datasource.ts
  39. 32
      public/app/plugins/datasource/prometheus/metric_find_query.ts
  40. 12
      public/app/plugins/datasource/prometheus/query_ctrl.ts
  41. 28
      public/app/plugins/datasource/prometheus/result_transformer.ts
  42. 4
      public/app/plugins/datasource/testdata/datasource.ts
  43. 8
      public/app/plugins/panel/alertlist/module.ts
  44. 8
      public/app/plugins/panel/dashlist/module.ts
  45. 2
      public/app/plugins/panel/gettingstarted/module.ts
  46. 26
      public/app/plugins/panel/graph/align_yaxes.ts
  47. 4
      public/app/plugins/panel/graph/axes_editor.ts
  48. 20
      public/app/plugins/panel/graph/data_processor.ts
  49. 46
      public/app/plugins/panel/graph/graph.ts
  50. 6
      public/app/plugins/panel/graph/jquery.flot.events.ts
  51. 44
      public/app/plugins/panel/graph/legend.ts
  52. 8
      public/app/plugins/panel/graph/module.ts
  53. 6
      public/app/plugins/panel/graph/series_overrides_ctrl.ts
  54. 2
      public/app/plugins/panel/graph/template.ts
  55. 22
      public/app/plugins/panel/graph/threshold_manager.ts
  56. 4
      public/app/plugins/panel/graph/thresholds_form.ts
  57. 4
      public/app/plugins/panel/heatmap/color_legend.ts
  58. 2
      public/app/plugins/panel/pluginlist/module.ts
  59. 90
      public/app/plugins/panel/singlestat/module.ts
  60. 12
      public/app/plugins/panel/table/column_options.ts
  61. 10
      public/app/plugins/panel/table/editor.ts
  62. 30
      public/app/plugins/panel/table/module.ts
  63. 16
      public/app/plugins/panel/table/renderer.ts
  64. 54
      public/app/plugins/panel/table/transformers.ts

@ -49,7 +49,7 @@ export class GrafanaCtrl {
}; };
$rootScope.onAppEvent = function(name, callback, localScope) { $rootScope.onAppEvent = function(name, callback, localScope) {
var unbind = $rootScope.$on(name, callback); const unbind = $rootScope.$on(name, callback);
var callerScope = this; var callerScope = this;
if (callerScope.$id === 1 && !localScope) { if (callerScope.$id === 1 && !localScope) {
console.log('warning rootScope onAppEvent called without localscope'); console.log('warning rootScope onAppEvent called without localscope');
@ -76,7 +76,7 @@ export function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScop
controller: GrafanaCtrl, controller: GrafanaCtrl,
link: (scope, elem) => { link: (scope, elem) => {
var sidemenuOpen; var sidemenuOpen;
var body = $('body'); const body = $('body');
// see https://github.com/zenorocha/clipboard.js/issues/155 // see https://github.com/zenorocha/clipboard.js/issues/155
$.fn.modal.Constructor.prototype.enforceFocus = function() {}; $.fn.modal.Constructor.prototype.enforceFocus = function() {};
@ -153,7 +153,7 @@ export function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScop
// handle in active view state class // handle in active view state class
var lastActivity = new Date().getTime(); var lastActivity = new Date().getTime();
var activeUser = true; var activeUser = true;
var inActiveTimeLimit = 60 * 1000; const inActiveTimeLimit = 60 * 1000;
var sidemenuHidden = false; var sidemenuHidden = false;
function checkForInActiveUser() { function checkForInActiveUser() {
@ -215,16 +215,16 @@ export function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScop
// handle document clicks that should hide things // handle document clicks that should hide things
body.click(function(evt) { body.click(function(evt) {
var target = $(evt.target); const target = $(evt.target);
if (target.parents().length === 0) { if (target.parents().length === 0) {
return; return;
} }
// for stuff that animates, slides out etc, clicking it needs to // for stuff that animates, slides out etc, clicking it needs to
// hide it right away // hide it right away
var clickAutoHide = target.closest('[data-click-hide]'); const clickAutoHide = target.closest('[data-click-hide]');
if (clickAutoHide.length) { if (clickAutoHide.length) {
var clickAutoHideParent = clickAutoHide.parent(); const clickAutoHideParent = clickAutoHide.parent();
clickAutoHide.detach(); clickAutoHide.detach();
setTimeout(function() { setTimeout(function() {
clickAutoHideParent.append(clickAutoHide); clickAutoHideParent.append(clickAutoHide);
@ -245,7 +245,7 @@ export function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScop
} }
// hide popovers // hide popovers
var popover = elem.find('.popover'); const popover = elem.find('.popover');
if (popover.length > 0 && target.parents('.graph-legend').length === 0) { if (popover.length > 0 && target.parents('.graph-legend').length === 0) {
popover.hide(); popover.hide();
} }

@ -74,8 +74,8 @@ export class BackendSrv {
request(options) { request(options) {
options.retry = options.retry || 0; options.retry = options.retry || 0;
var requestIsLocal = !options.url.match(/^http/); const requestIsLocal = !options.url.match(/^http/);
var firstAttempt = options.retry === 0; const firstAttempt = options.retry === 0;
if (requestIsLocal) { if (requestIsLocal) {
if (this.contextSrv.user && this.contextSrv.user.orgId) { if (this.contextSrv.user && this.contextSrv.user.orgId) {
@ -123,30 +123,31 @@ export class BackendSrv {
} }
resolveCancelerIfExists(requestId) { resolveCancelerIfExists(requestId) {
var cancelers = this.inFlightRequests[requestId]; const cancelers = this.inFlightRequests[requestId];
if (!_.isUndefined(cancelers) && cancelers.length) { if (!_.isUndefined(cancelers) && cancelers.length) {
cancelers[0].resolve(); cancelers[0].resolve();
} }
} }
datasourceRequest(options) { datasourceRequest(options) {
let canceler = null;
options.retry = options.retry || 0; options.retry = options.retry || 0;
// A requestID is provided by the datasource as a unique identifier for a // A requestID is provided by the datasource as a unique identifier for a
// particular query. If the requestID exists, the promise it is keyed to // particular query. If the requestID exists, the promise it is keyed to
// is canceled, canceling the previous datasource request if it is still // is canceled, canceling the previous datasource request if it is still
// in-flight. // in-flight.
var requestId = options.requestId; const requestId = options.requestId;
if (requestId) { if (requestId) {
this.resolveCancelerIfExists(requestId); this.resolveCancelerIfExists(requestId);
// create new canceler // create new canceler
var canceler = this.$q.defer(); canceler = this.$q.defer();
options.timeout = canceler.promise; options.timeout = canceler.promise;
this.addCanceler(requestId, canceler); this.addCanceler(requestId, canceler);
} }
var requestIsLocal = !options.url.match(/^http/); const requestIsLocal = !options.url.match(/^http/);
var firstAttempt = options.retry === 0; const firstAttempt = options.retry === 0;
if (requestIsLocal) { if (requestIsLocal) {
if (this.contextSrv.user && this.contextSrv.user.orgId) { if (this.contextSrv.user && this.contextSrv.user.orgId) {

@ -8,7 +8,7 @@ function matchSeriesOverride(aliasOrRegex, seriesAlias) {
} }
if (aliasOrRegex[0] === '/') { if (aliasOrRegex[0] === '/') {
var regex = kbn.stringToJsRegex(aliasOrRegex); const regex = kbn.stringToJsRegex(aliasOrRegex);
return seriesAlias.match(regex) != null; return seriesAlias.match(regex) != null;
} }
@ -43,9 +43,9 @@ export function updateLegendValues(data: TimeSeries[], panel, height) {
// legend and tooltip gets one more decimal precision // legend and tooltip gets one more decimal precision
// than graph legend ticks // than graph legend ticks
const { datamin, datamax } = getDataMinMax(data); const { datamin, datamax } = getDataMinMax(data);
let { tickDecimals, scaledDecimals } = getFlotTickDecimals(datamin, datamax, axis, height); const { tickDecimals, scaledDecimals } = getFlotTickDecimals(datamin, datamax, axis, height);
tickDecimals = (tickDecimals || -1) + 1; const tickDecimalsPlusOne = (tickDecimals || -1) + 1;
series.updateLegendValues(formater, tickDecimals, scaledDecimals + 2); series.updateLegendValues(formater, tickDecimalsPlusOne, scaledDecimals + 2);
} }
} }
} }
@ -125,7 +125,7 @@ export default class TimeSeries {
delete this.bars.show; delete this.bars.show;
for (var i = 0; i < overrides.length; i++) { for (var i = 0; i < overrides.length; i++) {
var override = overrides[i]; const override = overrides[i];
if (!matchSeriesOverride(override.alias, this.alias)) { if (!matchSeriesOverride(override.alias, this.alias)) {
continue; continue;
} }
@ -193,7 +193,7 @@ export default class TimeSeries {
} }
getFlotPairs(fillStyle) { getFlotPairs(fillStyle) {
var result = []; const result = [];
this.stats.total = 0; this.stats.total = 0;
this.stats.max = -Number.MAX_VALUE; this.stats.max = -Number.MAX_VALUE;
@ -209,8 +209,8 @@ export default class TimeSeries {
this.allIsNull = true; this.allIsNull = true;
this.allIsZero = true; this.allIsZero = true;
var ignoreNulls = fillStyle === 'connected'; const ignoreNulls = fillStyle === 'connected';
var nullAsZero = fillStyle === 'null as zero'; const nullAsZero = fillStyle === 'null as zero';
var currentTime; var currentTime;
var currentValue; var currentValue;
var nonNulls = 0; var nonNulls = 0;
@ -330,7 +330,7 @@ export default class TimeSeries {
isMsResolutionNeeded() { isMsResolutionNeeded() {
for (var i = 0; i < this.datapoints.length; i++) { for (var i = 0; i < this.datapoints.length; i++) {
if (this.datapoints[i][1] !== null) { if (this.datapoints[i][1] !== null) {
var timestamp = this.datapoints[i][1].toString(); const timestamp = this.datapoints[i][1].toString();
if (timestamp.length === 13 && timestamp % 1000 !== 0) { if (timestamp.length === 13 && timestamp % 1000 !== 0) {
return true; return true;
} }

@ -21,16 +21,16 @@ export function annotationTooltipDirective($sanitize, dashboardSrv, contextSrv,
onEdit: '&', onEdit: '&',
}, },
link: function(scope, element) { link: function(scope, element) {
var event = scope.event; const event = scope.event;
var title = event.title; var title = event.title;
var text = event.text; var text = event.text;
var dashboard = dashboardSrv.getCurrent(); const dashboard = dashboardSrv.getCurrent();
var tooltip = '<div class="graph-annotation">'; var tooltip = '<div class="graph-annotation">';
var titleStateClass = ''; var titleStateClass = '';
if (event.alertId) { if (event.alertId) {
var stateModel = alertDef.getStateDisplayModel(event.newState); const stateModel = alertDef.getStateDisplayModel(event.newState);
titleStateClass = stateModel.stateClass; titleStateClass = stateModel.stateClass;
title = `<i class="icon-gf ${stateModel.iconClass}"></i> ${stateModel.text}`; title = `<i class="icon-gf ${stateModel.iconClass}"></i> ${stateModel.text}`;
text = alertDef.getAlertAnnotationInfo(event); text = alertDef.getAlertAnnotationInfo(event);
@ -70,7 +70,7 @@ export function annotationTooltipDirective($sanitize, dashboardSrv, contextSrv,
tooltip += '<div>' + sanitizeString(text.replace(/\n/g, '<br>')) + '</div>'; tooltip += '<div>' + sanitizeString(text.replace(/\n/g, '<br>')) + '</div>';
} }
var tags = event.tags; const tags = event.tags;
if (tags && tags.length) { if (tags && tags.length) {
scope.tags = tags; scope.tags = tags;
@ -81,7 +81,7 @@ export function annotationTooltipDirective($sanitize, dashboardSrv, contextSrv,
tooltip += '</div>'; tooltip += '</div>';
tooltip += '</div>'; tooltip += '</div>';
var $tooltip = $(tooltip); const $tooltip = $(tooltip);
$tooltip.appendTo(element); $tooltip.appendTo(element);
$compile(element.contents())(scope); $compile(element.contents())(scope);

@ -40,7 +40,7 @@ export class AnnotationsSrv {
annotations = makeRegions(annotations, options); annotations = makeRegions(annotations, options);
// look for alert state for this panel // look for alert state for this panel
var alertState = _.find(results[1], { panelId: options.panel.id }); const alertState = _.find(results[1], { panelId: options.panel.id });
return { return {
annotations: annotations, annotations: annotations,
@ -82,14 +82,14 @@ export class AnnotationsSrv {
} }
getGlobalAnnotations(options) { getGlobalAnnotations(options) {
var dashboard = options.dashboard; const dashboard = options.dashboard;
if (this.globalAnnotationsPromise) { if (this.globalAnnotationsPromise) {
return this.globalAnnotationsPromise; return this.globalAnnotationsPromise;
} }
var range = this.timeSrv.timeRange(); const range = this.timeSrv.timeRange();
var promises = []; const promises = [];
for (const annotation of dashboard.annotations.list) { for (const annotation of dashboard.annotations.list) {
if (!annotation.enable) { if (!annotation.enable) {
@ -155,7 +155,7 @@ export class AnnotationsSrv {
delete annotation.snapshotData; delete annotation.snapshotData;
} }
for (var item of results) { for (const item of results) {
item.source = annotation; item.source = annotation;
} }
return results; return results;

@ -81,7 +81,7 @@ export class AnnotationsEditorCtrl {
} }
removeAnnotation(annotation) { removeAnnotation(annotation) {
var index = _.indexOf(this.annotations, annotation); const index = _.indexOf(this.annotations, annotation);
this.annotations.splice(index, 1); this.annotations.splice(index, 1);
} }

@ -55,7 +55,7 @@ export class EventManager {
return; return;
} }
var types = { const types = {
$__alerting: { $__alerting: {
color: ALERTING_COLOR, color: ALERTING_COLOR,
position: 'BOTTOM', position: 'BOTTOM',
@ -103,7 +103,7 @@ export class EventManager {
} else { } else {
// annotations from query // annotations from query
for (var i = 0; i < annotations.length; i++) { for (var i = 0; i < annotations.length; i++) {
var item = annotations[i]; const item = annotations[i];
// add properties used by jquery flot events // add properties used by jquery flot events
item.min = item.time; item.min = item.time;

@ -7,11 +7,11 @@ export class LinkSrv {
constructor(private templateSrv, private timeSrv) {} constructor(private templateSrv, private timeSrv) {}
getLinkUrl(link) { getLinkUrl(link) {
var url = this.templateSrv.replace(link.url || ''); const url = this.templateSrv.replace(link.url || '');
var params = {}; const params = {};
if (link.keepTime) { if (link.keepTime) {
var range = this.timeSrv.timeRangeForUrl(); const range = this.timeSrv.timeRangeForUrl();
params['from'] = range.from; params['from'] = range.from;
params['to'] = range.to; params['to'] = range.to;
} }
@ -24,7 +24,7 @@ export class LinkSrv {
} }
addParamsToUrl(url, params) { addParamsToUrl(url, params) {
var paramsArray = []; const paramsArray = [];
_.each(params, function(value, key) { _.each(params, function(value, key) {
if (value === null) { if (value === null) {
@ -50,7 +50,7 @@ export class LinkSrv {
appendToQueryString(url, stringToAppend) { appendToQueryString(url, stringToAppend) {
if (!_.isUndefined(stringToAppend) && stringToAppend !== null && stringToAppend !== '') { if (!_.isUndefined(stringToAppend) && stringToAppend !== null && stringToAppend !== '') {
var pos = url.indexOf('?'); const pos = url.indexOf('?');
if (pos !== -1) { if (pos !== -1) {
if (url.length - pos > 1) { if (url.length - pos > 1) {
url += '&'; url += '&';
@ -65,14 +65,14 @@ export class LinkSrv {
} }
getAnchorInfo(link) { getAnchorInfo(link) {
var info: any = {}; const info: any = {};
info.href = this.getLinkUrl(link); info.href = this.getLinkUrl(link);
info.title = this.templateSrv.replace(link.title || ''); info.title = this.templateSrv.replace(link.title || '');
return info; return info;
} }
getPanelLinkAnchorInfo(link, scopedVars) { getPanelLinkAnchorInfo(link, scopedVars) {
var info: any = {}; const info: any = {};
if (link.type === 'absolute') { if (link.type === 'absolute') {
info.target = link.targetBlank ? '_blank' : '_self'; info.target = link.targetBlank ? '_blank' : '_self';
info.href = this.templateSrv.replace(link.url || '', scopedVars); info.href = this.templateSrv.replace(link.url || '', scopedVars);
@ -87,14 +87,14 @@ export class LinkSrv {
info.target = link.targetBlank ? '_blank' : ''; info.target = link.targetBlank ? '_blank' : '';
} else { } else {
info.title = this.templateSrv.replace(link.title || '', scopedVars); info.title = this.templateSrv.replace(link.title || '', scopedVars);
var slug = kbn.slugifyForUrl(link.dashboard || ''); const slug = kbn.slugifyForUrl(link.dashboard || '');
info.href = 'dashboard/db/' + slug + '?'; info.href = 'dashboard/db/' + slug + '?';
} }
var params = {}; const params = {};
if (link.keepTime) { if (link.keepTime) {
var range = this.timeSrv.timeRangeForUrl(); const range = this.timeSrv.timeRangeForUrl();
params['from'] = range.from; params['from'] = range.from;
params['to'] = range.to; params['to'] = range.to;
} }

@ -95,7 +95,7 @@ export class DatasourceSrv {
} }
getMetricSources(options) { getMetricSources(options) {
var metricSources = []; const metricSources = [];
_.each(config.datasources, function(value, key) { _.each(config.datasources, function(value, key) {
if (value.meta && value.meta.metrics) { if (value.meta && value.meta.metrics) {
@ -137,7 +137,7 @@ export class DatasourceSrv {
addDataSourceVariables(list) { addDataSourceVariables(list) {
// look for data source variables // look for data source variables
for (var i = 0; i < this.templateSrv.variables.length; i++) { for (var i = 0; i < this.templateSrv.variables.length; i++) {
var variable = this.templateSrv.variables[i]; const variable = this.templateSrv.variables[i];
if (variable.type !== 'datasource') { if (variable.type !== 'datasource') {
continue; continue;
} }
@ -147,7 +147,7 @@ export class DatasourceSrv {
first = config.defaultDatasource; first = config.defaultDatasource;
} }
var ds = config.datasources[first]; const ds = config.datasources[first];
if (ds) { if (ds) {
const key = `$${variable.name}`; const key = `$${variable.name}`;

@ -28,7 +28,7 @@ export default class CloudWatchDatasource {
options = angular.copy(options); options = angular.copy(options);
options.targets = this.expandTemplateVariable(options.targets, options.scopedVars, this.templateSrv); options.targets = this.expandTemplateVariable(options.targets, options.scopedVars, this.templateSrv);
var queries = _.filter(options.targets, item => { const queries = _.filter(options.targets, item => {
return ( return (
(item.id !== '' || item.hide !== true) && (item.id !== '' || item.hide !== true) &&
((!!item.region && !!item.namespace && !!item.metricName && !_.isEmpty(item.statistics)) || ((!!item.region && !!item.namespace && !!item.metricName && !_.isEmpty(item.statistics)) ||
@ -66,12 +66,12 @@ export default class CloudWatchDatasource {
// No valid targets, return the empty result to save a round trip. // No valid targets, return the empty result to save a round trip.
if (_.isEmpty(queries)) { if (_.isEmpty(queries)) {
var d = this.$q.defer(); const d = this.$q.defer();
d.resolve({ data: [] }); d.resolve({ data: [] });
return d.promise; return d.promise;
} }
var request = { const request = {
from: options.range.from.valueOf().toString(), from: options.range.from.valueOf().toString(),
to: options.range.to.valueOf().toString(), to: options.range.to.valueOf().toString(),
queries: queries, queries: queries,
@ -81,15 +81,15 @@ export default class CloudWatchDatasource {
} }
getPeriod(target, options, now?) { getPeriod(target, options, now?) {
var start = this.convertToCloudWatchTime(options.range.from, false); const start = this.convertToCloudWatchTime(options.range.from, false);
var end = this.convertToCloudWatchTime(options.range.to, true); const end = this.convertToCloudWatchTime(options.range.to, true);
now = Math.round((now || Date.now()) / 1000); now = Math.round((now || Date.now()) / 1000);
var period; var period;
var range = end - start; const range = end - start;
var hourSec = 60 * 60; const hourSec = 60 * 60;
var daySec = hourSec * 24; const daySec = hourSec * 24;
var periodUnit = 60; var periodUnit = 60;
if (!target.period) { if (!target.period) {
if (now - start <= daySec * 15) { if (now - start <= daySec * 15) {
@ -128,7 +128,7 @@ export default class CloudWatchDatasource {
performTimeSeriesQuery(request) { performTimeSeriesQuery(request) {
return this.awsRequest('/api/tsdb/query', request).then(res => { return this.awsRequest('/api/tsdb/query', request).then(res => {
var data = []; const data = [];
if (res.results) { if (res.results) {
_.forEach(res.results, queryRes => { _.forEach(res.results, queryRes => {
@ -152,7 +152,7 @@ export default class CloudWatchDatasource {
} }
doMetricQueryRequest(subtype, parameters) { doMetricQueryRequest(subtype, parameters) {
var range = this.timeSrv.timeRange(); const range = this.timeSrv.timeRange();
return this.awsRequest('/api/tsdb/query', { return this.awsRequest('/api/tsdb/query', {
from: range.from.valueOf().toString(), from: range.from.valueOf().toString(),
to: range.to.valueOf().toString(), to: range.to.valueOf().toString(),
@ -227,38 +227,38 @@ export default class CloudWatchDatasource {
var metricName; var metricName;
var filterJson; var filterJson;
var regionQuery = query.match(/^regions\(\)/); const regionQuery = query.match(/^regions\(\)/);
if (regionQuery) { if (regionQuery) {
return this.getRegions(); return this.getRegions();
} }
var namespaceQuery = query.match(/^namespaces\(\)/); const namespaceQuery = query.match(/^namespaces\(\)/);
if (namespaceQuery) { if (namespaceQuery) {
return this.getNamespaces(); return this.getNamespaces();
} }
var metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/); const metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
if (metricNameQuery) { if (metricNameQuery) {
namespace = metricNameQuery[1]; namespace = metricNameQuery[1];
region = metricNameQuery[3]; region = metricNameQuery[3];
return this.getMetrics(namespace, region); return this.getMetrics(namespace, region);
} }
var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/); const dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
if (dimensionKeysQuery) { if (dimensionKeysQuery) {
namespace = dimensionKeysQuery[1]; namespace = dimensionKeysQuery[1];
region = dimensionKeysQuery[3]; region = dimensionKeysQuery[3];
return this.getDimensionKeys(namespace, region); return this.getDimensionKeys(namespace, region);
} }
var dimensionValuesQuery = query.match( const dimensionValuesQuery = query.match(
/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?(.+))?\)/ /^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?(.+))?\)/
); );
if (dimensionValuesQuery) { if (dimensionValuesQuery) {
region = dimensionValuesQuery[1]; region = dimensionValuesQuery[1];
namespace = dimensionValuesQuery[2]; namespace = dimensionValuesQuery[2];
metricName = dimensionValuesQuery[3]; metricName = dimensionValuesQuery[3];
var dimensionKey = dimensionValuesQuery[4]; const dimensionKey = dimensionValuesQuery[4];
filterJson = {}; filterJson = {};
if (dimensionValuesQuery[6]) { if (dimensionValuesQuery[6]) {
filterJson = JSON.parse(this.templateSrv.replace(dimensionValuesQuery[6])); filterJson = JSON.parse(this.templateSrv.replace(dimensionValuesQuery[6]));
@ -267,17 +267,17 @@ export default class CloudWatchDatasource {
return this.getDimensionValues(region, namespace, metricName, dimensionKey, filterJson); return this.getDimensionValues(region, namespace, metricName, dimensionKey, filterJson);
} }
var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/); const ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
if (ebsVolumeIdsQuery) { if (ebsVolumeIdsQuery) {
region = ebsVolumeIdsQuery[1]; region = ebsVolumeIdsQuery[1];
var instanceId = ebsVolumeIdsQuery[2]; const instanceId = ebsVolumeIdsQuery[2];
return this.getEbsVolumeIds(region, instanceId); return this.getEbsVolumeIds(region, instanceId);
} }
var ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/); const ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
if (ec2InstanceAttributeQuery) { if (ec2InstanceAttributeQuery) {
region = ec2InstanceAttributeQuery[1]; region = ec2InstanceAttributeQuery[1];
var targetAttributeName = ec2InstanceAttributeQuery[2]; const targetAttributeName = ec2InstanceAttributeQuery[2];
filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3])); filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3]));
return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson); return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson);
} }
@ -286,14 +286,14 @@ export default class CloudWatchDatasource {
} }
annotationQuery(options) { annotationQuery(options) {
var annotation = options.annotation; const annotation = options.annotation;
var statistics = _.map(annotation.statistics, s => { const statistics = _.map(annotation.statistics, s => {
return this.templateSrv.replace(s); return this.templateSrv.replace(s);
}); });
var defaultPeriod = annotation.prefixMatching ? '' : '300'; const defaultPeriod = annotation.prefixMatching ? '' : '300';
var period = annotation.period || defaultPeriod; var period = annotation.period || defaultPeriod;
period = parseInt(period, 10); period = parseInt(period, 10);
var parameters = { const parameters = {
prefixMatching: annotation.prefixMatching, prefixMatching: annotation.prefixMatching,
region: this.templateSrv.replace(this.getActualRegion(annotation.region)), region: this.templateSrv.replace(this.getActualRegion(annotation.region)),
namespace: this.templateSrv.replace(annotation.namespace), namespace: this.templateSrv.replace(annotation.namespace),
@ -346,10 +346,10 @@ export default class CloudWatchDatasource {
testDatasource() { testDatasource() {
/* use billing metrics for test */ /* use billing metrics for test */
var region = this.defaultRegion; const region = this.defaultRegion;
var namespace = 'AWS/Billing'; const namespace = 'AWS/Billing';
var metricName = 'EstimatedCharges'; const metricName = 'EstimatedCharges';
var dimensions = {}; const dimensions = {};
return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then( return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(
() => { () => {
@ -362,7 +362,7 @@ export default class CloudWatchDatasource {
} }
awsRequest(url, data) { awsRequest(url, data) {
var options = { const options = {
method: 'POST', method: 'POST',
url: url, url: url,
data: data, data: data,
@ -386,15 +386,15 @@ export default class CloudWatchDatasource {
getExpandedVariables(target, dimensionKey, variable, templateSrv) { getExpandedVariables(target, dimensionKey, variable, templateSrv) {
/* if the all checkbox is marked we should add all values to the targets */ /* if the all checkbox is marked we should add all values to the targets */
var allSelected = _.find(variable.options, { selected: true, text: 'All' }); const allSelected = _.find(variable.options, { selected: true, text: 'All' });
var selectedVariables = _.filter(variable.options, v => { const selectedVariables = _.filter(variable.options, v => {
if (allSelected) { if (allSelected) {
return v.text !== 'All'; return v.text !== 'All';
} else { } else {
return v.selected; return v.selected;
} }
}); });
var currentVariables = !_.isArray(variable.current.value) const currentVariables = !_.isArray(variable.current.value)
? [variable.current] ? [variable.current]
: variable.current.value.map(v => { : variable.current.value.map(v => {
return { return {
@ -407,8 +407,8 @@ export default class CloudWatchDatasource {
return s.value === currentVariables[0].value; return s.value === currentVariables[0].value;
}) || currentVariables[0].value === '$__all'; }) || currentVariables[0].value === '$__all';
return (useSelectedVariables ? selectedVariables : currentVariables).map(v => { return (useSelectedVariables ? selectedVariables : currentVariables).map(v => {
var t = angular.copy(target); const t = angular.copy(target);
var scopedVar = {}; const scopedVar = {};
scopedVar[variable.name] = v; scopedVar[variable.name] = v;
t.refId = target.refId + '_' + v.value; t.refId = target.refId + '_' + v.value;
t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar); t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
@ -425,17 +425,17 @@ export default class CloudWatchDatasource {
// Datasource and template srv logic uber-complected. This should be cleaned up. // Datasource and template srv logic uber-complected. This should be cleaned up.
return _.chain(targets) return _.chain(targets)
.map(target => { .map(target => {
var dimensionKey = _.findKey(target.dimensions, v => { const dimensionKey = _.findKey(target.dimensions, v => {
return templateSrv.variableExists(v) && !_.has(scopedVars, templateSrv.getVariableName(v)); return templateSrv.variableExists(v) && !_.has(scopedVars, templateSrv.getVariableName(v));
}); });
if (dimensionKey) { if (dimensionKey) {
var multiVariable = _.find(templateSrv.variables, variable => { const multiVariable = _.find(templateSrv.variables, variable => {
return ( return (
templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name) && variable.multi templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name) && variable.multi
); );
}); });
var variable = _.find(templateSrv.variables, variable => { const variable = _.find(templateSrv.variables, variable => {
return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name); return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name);
}); });
return this.getExpandedVariables(target, dimensionKey, multiVariable || variable, templateSrv); return this.getExpandedVariables(target, dimensionKey, multiVariable || variable, templateSrv);
@ -455,7 +455,7 @@ export default class CloudWatchDatasource {
} }
convertDimensionFormat(dimensions, scopedVars) { convertDimensionFormat(dimensions, scopedVars) {
var convertedDimensions = {}; const convertedDimensions = {};
_.each(dimensions, (value, key) => { _.each(dimensions, (value, key) => {
convertedDimensions[this.templateSrv.replace(key, scopedVars)] = this.templateSrv.replace(value, scopedVars); convertedDimensions[this.templateSrv.replace(key, scopedVars)] = this.templateSrv.replace(value, scopedVars);
}); });

@ -19,7 +19,7 @@ export function elasticBucketAgg() {
export class ElasticBucketAggCtrl { export class ElasticBucketAggCtrl {
/** @nginject */ /** @nginject */
constructor($scope, uiSegmentSrv, $q, $rootScope) { constructor($scope, uiSegmentSrv, $q, $rootScope) {
var bucketAggs = $scope.target.bucketAggs; const bucketAggs = $scope.target.bucketAggs;
$scope.orderByOptions = []; $scope.orderByOptions = [];
@ -85,7 +85,7 @@ export class ElasticBucketAggCtrl {
$scope.bucketAggCount = bucketAggs.length; $scope.bucketAggCount = bucketAggs.length;
var settingsLinkText = ''; var settingsLinkText = '';
var settings = $scope.agg.settings || {}; const settings = $scope.agg.settings || {};
switch ($scope.agg.type) { switch ($scope.agg.type) {
case 'terms': { case 'terms': {
@ -198,14 +198,14 @@ export class ElasticBucketAggCtrl {
$scope.addBucketAgg = function() { $scope.addBucketAgg = function() {
// if last is date histogram add it before // if last is date histogram add it before
var lastBucket = bucketAggs[bucketAggs.length - 1]; const lastBucket = bucketAggs[bucketAggs.length - 1];
var addIndex = bucketAggs.length - 1; var addIndex = bucketAggs.length - 1;
if (lastBucket && lastBucket.type === 'date_histogram') { if (lastBucket && lastBucket.type === 'date_histogram') {
addIndex -= 1; addIndex -= 1;
} }
var id = _.reduce( const id = _.reduce(
$scope.target.bucketAggs.concat($scope.target.metrics), $scope.target.bucketAggs.concat($scope.target.metrics),
function(max, val) { function(max, val) {
return parseInt(val.id) > max ? parseInt(val.id) : max; return parseInt(val.id) > max ? parseInt(val.id) : max;
@ -226,6 +226,6 @@ export class ElasticBucketAggCtrl {
} }
} }
var module = angular.module('grafana.directives'); const module = angular.module('grafana.directives');
module.directive('elasticBucketAgg', elasticBucketAgg); module.directive('elasticBucketAgg', elasticBucketAgg);
module.controller('ElasticBucketAggCtrl', ElasticBucketAggCtrl); module.controller('ElasticBucketAggCtrl', ElasticBucketAggCtrl);

@ -23,7 +23,7 @@ export class ElasticConfigCtrl {
esVersions = [{ name: '2.x', value: 2 }, { name: '5.x', value: 5 }, { name: '5.6+', value: 56 }]; esVersions = [{ name: '2.x', value: 2 }, { name: '5.x', value: 5 }, { name: '5.6+', value: 56 }];
indexPatternTypeChanged() { indexPatternTypeChanged() {
var def = _.find(this.indexPatternTypes, { const def = _.find(this.indexPatternTypes, {
value: this.current.jsonData.interval, value: this.current.jsonData.interval,
}); });
this.current.database = def.example || 'es-index-name'; this.current.database = def.example || 'es-index-name';

@ -37,7 +37,7 @@ export class ElasticDatasource {
} }
private request(method, url, data?) { private request(method, url, data?) {
var options: any = { const options: any = {
url: this.url + '/' + url, url: this.url + '/' + url,
method: method, method: method,
data: data, data: data,
@ -56,8 +56,8 @@ export class ElasticDatasource {
} }
private get(url) { private get(url) {
var range = this.timeSrv.timeRange(); const range = this.timeSrv.timeRange();
var index_list = this.indexPattern.getIndexList(range.from.valueOf(), range.to.valueOf()); const index_list = this.indexPattern.getIndexList(range.from.valueOf(), range.to.valueOf());
if (_.isArray(index_list) && index_list.length) { if (_.isArray(index_list) && index_list.length) {
return this.request('GET', index_list[0] + url).then(function(results) { return this.request('GET', index_list[0] + url).then(function(results) {
results.data.$$config = results.config; results.data.$$config = results.config;
@ -90,21 +90,21 @@ export class ElasticDatasource {
} }
annotationQuery(options) { annotationQuery(options) {
var annotation = options.annotation; const annotation = options.annotation;
var timeField = annotation.timeField || '@timestamp'; const timeField = annotation.timeField || '@timestamp';
var queryString = annotation.query || '*'; const queryString = annotation.query || '*';
var tagsField = annotation.tagsField || 'tags'; const tagsField = annotation.tagsField || 'tags';
var textField = annotation.textField || null; const textField = annotation.textField || null;
var range = {}; const range = {};
range[timeField] = { range[timeField] = {
from: options.range.from.valueOf(), from: options.range.from.valueOf(),
to: options.range.to.valueOf(), to: options.range.to.valueOf(),
format: 'epoch_millis', format: 'epoch_millis',
}; };
var queryInterpolated = this.templateSrv.replace(queryString, {}, 'lucene'); const queryInterpolated = this.templateSrv.replace(queryString, {}, 'lucene');
var query = { const query = {
bool: { bool: {
filter: [ filter: [
{ range: range }, { range: range },
@ -117,7 +117,7 @@ export class ElasticDatasource {
}, },
}; };
var data = { const data = {
query: query, query: query,
size: 10000, size: 10000,
}; };
@ -127,7 +127,7 @@ export class ElasticDatasource {
data['fields'] = [timeField, '_source']; data['fields'] = [timeField, '_source'];
} }
var header: any = { const header: any = {
search_type: 'query_then_fetch', search_type: 'query_then_fetch',
ignore_unavailable: true, ignore_unavailable: true,
}; };
@ -139,18 +139,18 @@ export class ElasticDatasource {
header.index = this.indexPattern.getIndexList(options.range.from, options.range.to); header.index = this.indexPattern.getIndexList(options.range.from, options.range.to);
} }
var payload = angular.toJson(header) + '\n' + angular.toJson(data) + '\n'; const payload = angular.toJson(header) + '\n' + angular.toJson(data) + '\n';
return this.post('_msearch', payload).then(res => { return this.post('_msearch', payload).then(res => {
var list = []; const list = [];
var hits = res.responses[0].hits.hits; const hits = res.responses[0].hits.hits;
var getFieldFromSource = function(source, fieldName) { const getFieldFromSource = function(source, fieldName) {
if (!fieldName) { if (!fieldName) {
return; return;
} }
var fieldNames = fieldName.split('.'); const fieldNames = fieldName.split('.');
var fieldValue = source; var fieldValue = source;
for (var i = 0; i < fieldNames.length; i++) { for (var i = 0; i < fieldNames.length; i++) {
@ -165,16 +165,16 @@ export class ElasticDatasource {
}; };
for (var i = 0; i < hits.length; i++) { for (var i = 0; i < hits.length; i++) {
var source = hits[i]._source; const source = hits[i]._source;
var time = getFieldFromSource(source, timeField); var time = getFieldFromSource(source, timeField);
if (typeof hits[i].fields !== 'undefined') { if (typeof hits[i].fields !== 'undefined') {
var fields = hits[i].fields; const fields = hits[i].fields;
if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) { if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
time = fields[timeField]; time = fields[timeField];
} }
} }
var event = { const event = {
annotation: annotation, annotation: annotation,
time: moment.utc(time).valueOf(), time: moment.utc(time).valueOf(),
text: getFieldFromSource(source, textField), text: getFieldFromSource(source, textField),
@ -204,7 +204,7 @@ export class ElasticDatasource {
// validate that the index exist and has date field // validate that the index exist and has date field
return this.getFields({ type: 'date' }).then( return this.getFields({ type: 'date' }).then(
function(dateFields) { function(dateFields) {
var timeField = _.find(dateFields, { text: this.timeField }); const timeField = _.find(dateFields, { text: this.timeField });
if (!timeField) { if (!timeField) {
return { return {
status: 'error', status: 'error',
@ -229,7 +229,7 @@ export class ElasticDatasource {
} }
getQueryHeader(searchType, timeFrom, timeTo) { getQueryHeader(searchType, timeFrom, timeTo) {
var query_header: any = { const query_header: any = {
search_type: searchType, search_type: searchType,
ignore_unavailable: true, ignore_unavailable: true,
index: this.indexPattern.getIndexList(timeFrom, timeTo), index: this.indexPattern.getIndexList(timeFrom, timeTo),
@ -243,10 +243,10 @@ export class ElasticDatasource {
query(options) { query(options) {
var payload = ''; var payload = '';
var target; var target;
var sentTargets = []; const sentTargets = [];
// add global adhoc filters to timeFilter // add global adhoc filters to timeFilter
var adhocFilters = this.templateSrv.getAdhocFilters(this.name); const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
for (var i = 0; i < options.targets.length; i++) { for (var i = 0; i < options.targets.length; i++) {
target = options.targets[i]; target = options.targets[i];
@ -254,12 +254,12 @@ export class ElasticDatasource {
continue; continue;
} }
var queryString = this.templateSrv.replace(target.query || '*', options.scopedVars, 'lucene'); const queryString = this.templateSrv.replace(target.query || '*', options.scopedVars, 'lucene');
var queryObj = this.queryBuilder.build(target, adhocFilters, queryString); const queryObj = this.queryBuilder.build(target, adhocFilters, queryString);
var esQuery = angular.toJson(queryObj); const esQuery = angular.toJson(queryObj);
var searchType = queryObj.size === 0 && this.esVersion < 5 ? 'count' : 'query_then_fetch'; const searchType = queryObj.size === 0 && this.esVersion < 5 ? 'count' : 'query_then_fetch';
var header = this.getQueryHeader(searchType, options.range.from, options.range.to); const header = this.getQueryHeader(searchType, options.range.from, options.range.to);
payload += header + '\n'; payload += header + '\n';
payload += esQuery + '\n'; payload += esQuery + '\n';
@ -281,7 +281,7 @@ export class ElasticDatasource {
getFields(query) { getFields(query) {
return this.get('/_mapping').then(function(result) { return this.get('/_mapping').then(function(result) {
var typeMap = { const typeMap = {
float: 'number', float: 'number',
double: 'number', double: 'number',
integer: 'number', integer: 'number',
@ -307,12 +307,12 @@ export class ElasticDatasource {
} }
// Store subfield names: [system, process, cpu, total] -> system.process.cpu.total // Store subfield names: [system, process, cpu, total] -> system.process.cpu.total
var fieldNameParts = []; const fieldNameParts = [];
var fields = {}; const fields = {};
function getFieldsRecursively(obj) { function getFieldsRecursively(obj) {
for (var key in obj) { for (const key in obj) {
var subObj = obj[key]; const subObj = obj[key];
// Check mapping field for nested fields // Check mapping field for nested fields
if (_.isObject(subObj.properties)) { if (_.isObject(subObj.properties)) {
@ -326,7 +326,7 @@ export class ElasticDatasource {
} }
if (_.isString(subObj.type)) { if (_.isString(subObj.type)) {
var fieldName = fieldNameParts.concat(key).join('.'); const fieldName = fieldNameParts.concat(key).join('.');
// Hide meta-fields and check field type // Hide meta-fields and check field type
if (shouldAddField(subObj, key, query)) { if (shouldAddField(subObj, key, query)) {
@ -340,12 +340,12 @@ export class ElasticDatasource {
fieldNameParts.pop(); fieldNameParts.pop();
} }
for (var indexName in result) { for (const indexName in result) {
var index = result[indexName]; const index = result[indexName];
if (index && index.mappings) { if (index && index.mappings) {
var mappings = index.mappings; const mappings = index.mappings;
for (var typeName in mappings) { for (const typeName in mappings) {
var properties = mappings[typeName].properties; const properties = mappings[typeName].properties;
getFieldsRecursively(properties); getFieldsRecursively(properties);
} }
} }
@ -359,9 +359,9 @@ export class ElasticDatasource {
} }
getTerms(queryDef) { getTerms(queryDef) {
var range = this.timeSrv.timeRange(); const range = this.timeSrv.timeRange();
var searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count'; const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count';
var header = this.getQueryHeader(searchType, range.from, range.to); const header = this.getQueryHeader(searchType, range.from, range.to);
var esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef)); var esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf()); esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf());
@ -373,7 +373,7 @@ export class ElasticDatasource {
return []; return [];
} }
var buckets = res.responses[0].aggregations['1'].buckets; const buckets = res.responses[0].aggregations['1'].buckets;
return _.map(buckets, function(bucket) { return _.map(buckets, function(bucket) {
return { return {
text: bucket.key_as_string || bucket.key, text: bucket.key_as_string || bucket.key,

@ -33,10 +33,10 @@ export class ElasticResponse {
break; break;
} }
var firstBucket = esAgg.buckets[0]; const firstBucket = esAgg.buckets[0];
var percentiles = firstBucket[metric.id].values; const percentiles = firstBucket[metric.id].values;
for (var percentileName in percentiles) { for (const percentileName in percentiles) {
newSeries = { newSeries = {
datapoints: [], datapoints: [],
metric: 'p' + percentileName, metric: 'p' + percentileName,
@ -46,7 +46,7 @@ export class ElasticResponse {
for (i = 0; i < esAgg.buckets.length; i++) { for (i = 0; i < esAgg.buckets.length; i++) {
bucket = esAgg.buckets[i]; bucket = esAgg.buckets[i];
var values = bucket[metric.id].values; const values = bucket[metric.id].values;
newSeries.datapoints.push([values[percentileName], bucket.key]); newSeries.datapoints.push([values[percentileName], bucket.key]);
} }
seriesList.push(newSeries); seriesList.push(newSeries);
@ -55,7 +55,7 @@ export class ElasticResponse {
break; break;
} }
case 'extended_stats': { case 'extended_stats': {
for (var statName in metric.meta) { for (const statName in metric.meta) {
if (!metric.meta[statName]) { if (!metric.meta[statName]) {
continue; continue;
} }
@ -69,7 +69,7 @@ export class ElasticResponse {
for (i = 0; i < esAgg.buckets.length; i++) { for (i = 0; i < esAgg.buckets.length; i++) {
bucket = esAgg.buckets[i]; bucket = esAgg.buckets[i];
var stats = bucket[metric.id]; const stats = bucket[metric.id];
// add stats that are in nested obj to top level obj // add stats that are in nested obj to top level obj
stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper; stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
@ -141,12 +141,12 @@ export class ElasticResponse {
break; break;
} }
case 'extended_stats': { case 'extended_stats': {
for (var statName in metric.meta) { for (const statName in metric.meta) {
if (!metric.meta[statName]) { if (!metric.meta[statName]) {
continue; continue;
} }
var stats = bucket[metric.id]; const stats = bucket[metric.id];
// add stats that are in nested obj to top level obj // add stats that are in nested obj to top level obj
stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper; stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower; stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;
@ -178,7 +178,7 @@ export class ElasticResponse {
// need to recurise down the nested buckets to build series // need to recurise down the nested buckets to build series
processBuckets(aggs, target, seriesList, table, props, depth) { processBuckets(aggs, target, seriesList, table, props, depth) {
var bucket, aggDef, esAgg, aggId; var bucket, aggDef, esAgg, aggId;
var maxDepth = target.bucketAggs.length - 1; const maxDepth = target.bucketAggs.length - 1;
for (aggId in aggs) { for (aggId in aggs) {
aggDef = _.find(target.bucketAggs, { id: aggId }); aggDef = _.find(target.bucketAggs, { id: aggId });
@ -195,7 +195,7 @@ export class ElasticResponse {
this.processAggregationDocs(esAgg, aggDef, target, table, props); this.processAggregationDocs(esAgg, aggDef, target, table, props);
} }
} else { } else {
for (var nameIndex in esAgg.buckets) { for (const nameIndex in esAgg.buckets) {
bucket = esAgg.buckets[nameIndex]; bucket = esAgg.buckets[nameIndex];
props = _.clone(props); props = _.clone(props);
if (bucket.key !== void 0) { if (bucket.key !== void 0) {
@ -225,10 +225,10 @@ export class ElasticResponse {
var metricName = this.getMetricName(series.metric); var metricName = this.getMetricName(series.metric);
if (target.alias) { if (target.alias) {
var regex = /\{\{([\s\S]+?)\}\}/g; const regex = /\{\{([\s\S]+?)\}\}/g;
return target.alias.replace(regex, function(match, g1, g2) { return target.alias.replace(regex, function(match, g1, g2) {
var group = g1 || g2; const group = g1 || g2;
if (group.indexOf('term ') === 0) { if (group.indexOf('term ') === 0) {
return series.props[group.substring(5)]; return series.props[group.substring(5)];
@ -248,7 +248,7 @@ export class ElasticResponse {
} }
if (series.field && queryDef.isPipelineAgg(series.metric)) { if (series.field && queryDef.isPipelineAgg(series.metric)) {
var appliedAgg = _.find(target.metrics, { id: series.field }); const appliedAgg = _.find(target.metrics, { id: series.field });
if (appliedAgg) { if (appliedAgg) {
metricName += ' ' + queryDef.describeMetric(appliedAgg); metricName += ' ' + queryDef.describeMetric(appliedAgg);
} else { } else {
@ -258,13 +258,13 @@ export class ElasticResponse {
metricName += ' ' + series.field; metricName += ' ' + series.field;
} }
var propKeys = _.keys(series.props); const propKeys = _.keys(series.props);
if (propKeys.length === 0) { if (propKeys.length === 0) {
return metricName; return metricName;
} }
var name = ''; var name = '';
for (var propName in series.props) { for (const propName in series.props) {
name += series.props[propName] + ' '; name += series.props[propName] + ' ';
} }
@ -276,16 +276,16 @@ export class ElasticResponse {
} }
nameSeries(seriesList, target) { nameSeries(seriesList, target) {
var metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length; const metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length;
for (var i = 0; i < seriesList.length; i++) { for (var i = 0; i < seriesList.length; i++) {
var series = seriesList[i]; const series = seriesList[i];
series.target = this.getSeriesName(series, target, metricTypeCount); series.target = this.getSeriesName(series, target, metricTypeCount);
} }
} }
processHits(hits, seriesList) { processHits(hits, seriesList) {
var series = { const series = {
target: 'docs', target: 'docs',
type: 'docs', type: 'docs',
datapoints: [], datapoints: [],
@ -318,13 +318,13 @@ export class ElasticResponse {
} }
trimDatapoints(aggregations, target) { trimDatapoints(aggregations, target) {
var histogram = _.find(target.bucketAggs, { type: 'date_histogram' }); const histogram = _.find(target.bucketAggs, { type: 'date_histogram' });
var shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges; const shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges;
if (shouldDropFirstAndLast) { if (shouldDropFirstAndLast) {
var trim = histogram.settings.trimEdges; const trim = histogram.settings.trimEdges;
for (var prop in aggregations) { for (const prop in aggregations) {
var points = aggregations[prop]; const points = aggregations[prop];
if (points.datapoints.length > trim * 2) { if (points.datapoints.length > trim * 2) {
points.datapoints = points.datapoints.slice(trim, points.datapoints.length - trim); points.datapoints = points.datapoints.slice(trim, points.datapoints.length - trim);
} }
@ -333,7 +333,7 @@ export class ElasticResponse {
} }
getErrorFromElasticResponse(response, err) { getErrorFromElasticResponse(response, err) {
var result: any = {}; const result: any = {};
result.data = JSON.stringify(err, null, 4); result.data = JSON.stringify(err, null, 4);
if (err.root_cause && err.root_cause.length > 0 && err.root_cause[0].reason) { if (err.root_cause && err.root_cause.length > 0 && err.root_cause[0].reason) {
result.message = err.root_cause[0].reason; result.message = err.root_cause[0].reason;
@ -349,10 +349,10 @@ export class ElasticResponse {
} }
getTimeSeries() { getTimeSeries() {
var seriesList = []; const seriesList = [];
for (var i = 0; i < this.response.responses.length; i++) { for (var i = 0; i < this.response.responses.length; i++) {
var response = this.response.responses[i]; const response = this.response.responses[i];
if (response.error) { if (response.error) {
throw this.getErrorFromElasticResponse(this.response, response.error); throw this.getErrorFromElasticResponse(this.response, response.error);
} }
@ -362,10 +362,10 @@ export class ElasticResponse {
} }
if (response.aggregations) { if (response.aggregations) {
var aggregations = response.aggregations; const aggregations = response.aggregations;
var target = this.targets[i]; const target = this.targets[i];
var tmpSeriesList = []; const tmpSeriesList = [];
var table = new TableModel(); const table = new TableModel();
this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0); this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);
this.trimDatapoints(tmpSeriesList, target); this.trimDatapoints(tmpSeriesList, target);

@ -24,15 +24,15 @@ export class IndexPattern {
return this.pattern; return this.pattern;
} }
var intervalInfo = intervalMap[this.interval]; const intervalInfo = intervalMap[this.interval];
var start = moment(from) const start = moment(from)
.utc() .utc()
.startOf(intervalInfo.startOf); .startOf(intervalInfo.startOf);
var endEpoch = moment(to) const endEpoch = moment(to)
.utc() .utc()
.startOf(intervalInfo.startOf) .startOf(intervalInfo.startOf)
.valueOf(); .valueOf();
var indexList = []; const indexList = [];
while (start.valueOf() <= endEpoch) { while (start.valueOf() <= endEpoch) {
indexList.push(start.format(this.pattern)); indexList.push(start.format(this.pattern));

@ -19,7 +19,7 @@ export function elasticMetricAgg() {
export class ElasticMetricAggCtrl { export class ElasticMetricAggCtrl {
constructor($scope, uiSegmentSrv, $q, $rootScope) { constructor($scope, uiSegmentSrv, $q, $rootScope) {
var metricAggs = $scope.target.metrics; const metricAggs = $scope.target.metrics;
$scope.metricAggTypes = queryDef.getMetricAggTypes($scope.esVersion); $scope.metricAggTypes = queryDef.getMetricAggTypes($scope.esVersion);
$scope.extendedStats = queryDef.extendedStats; $scope.extendedStats = queryDef.extendedStats;
$scope.pipelineAggOptions = []; $scope.pipelineAggOptions = [];
@ -55,7 +55,7 @@ export class ElasticMetricAggCtrl {
$scope.agg.pipelineAgg = $scope.agg.pipelineAgg || 'select metric'; $scope.agg.pipelineAgg = $scope.agg.pipelineAgg || 'select metric';
$scope.agg.field = $scope.agg.pipelineAgg; $scope.agg.field = $scope.agg.pipelineAgg;
var pipelineOptions = queryDef.getPipelineOptions($scope.agg); const pipelineOptions = queryDef.getPipelineOptions($scope.agg);
if (pipelineOptions.length > 0) { if (pipelineOptions.length > 0) {
_.each(pipelineOptions, function(opt) { _.each(pipelineOptions, function(opt) {
$scope.agg.settings[opt.text] = $scope.agg.settings[opt.text] || opt.default; $scope.agg.settings[opt.text] = $scope.agg.settings[opt.text] || opt.default;
@ -67,7 +67,7 @@ export class ElasticMetricAggCtrl {
} }
switch ($scope.agg.type) { switch ($scope.agg.type) {
case 'cardinality': { case 'cardinality': {
var precision_threshold = $scope.agg.settings.precision_threshold || ''; const precision_threshold = $scope.agg.settings.precision_threshold || '';
$scope.settingsLinkText = 'Precision threshold: ' + precision_threshold; $scope.settingsLinkText = 'Precision threshold: ' + precision_threshold;
break; break;
} }
@ -82,11 +82,11 @@ export class ElasticMetricAggCtrl {
$scope.agg.meta.std_deviation_bounds_upper = true; $scope.agg.meta.std_deviation_bounds_upper = true;
} }
var stats = _.reduce( const stats = _.reduce(
$scope.agg.meta, $scope.agg.meta,
function(memo, val, key) { function(memo, val, key) {
if (val) { if (val) {
var def = _.find($scope.extendedStats, { value: key }); const def = _.find($scope.extendedStats, { value: key });
memo.push(def.text); memo.push(def.text);
} }
return memo; return memo;
@ -115,7 +115,7 @@ export class ElasticMetricAggCtrl {
if ($scope.aggDef.supportsInlineScript) { if ($scope.aggDef.supportsInlineScript) {
// I know this stores the inline script twice // I know this stores the inline script twice
// but having it like this simplifes the query_builder // but having it like this simplifes the query_builder
var inlineScript = $scope.agg.inlineScript; const inlineScript = $scope.agg.inlineScript;
if (inlineScript) { if (inlineScript) {
$scope.agg.settings.script = { inline: inlineScript }; $scope.agg.settings.script = { inline: inlineScript };
} else { } else {
@ -138,13 +138,13 @@ export class ElasticMetricAggCtrl {
}; };
$scope.updateMovingAvgModelSettings = function() { $scope.updateMovingAvgModelSettings = function() {
var modelSettingsKeys = []; const modelSettingsKeys = [];
var modelSettings = queryDef.getMovingAvgSettings($scope.agg.settings.model, false); const modelSettings = queryDef.getMovingAvgSettings($scope.agg.settings.model, false);
for (var i = 0; i < modelSettings.length; i++) { for (var i = 0; i < modelSettings.length; i++) {
modelSettingsKeys.push(modelSettings[i].value); modelSettingsKeys.push(modelSettings[i].value);
} }
for (var key in $scope.agg.settings.settings) { for (const key in $scope.agg.settings.settings) {
if ($scope.agg.settings.settings[key] === null || modelSettingsKeys.indexOf(key) === -1) { if ($scope.agg.settings.settings[key] === null || modelSettingsKeys.indexOf(key) === -1) {
delete $scope.agg.settings.settings[key]; delete $scope.agg.settings.settings[key];
} }
@ -172,9 +172,9 @@ export class ElasticMetricAggCtrl {
}; };
$scope.addMetricAgg = function() { $scope.addMetricAgg = function() {
var addIndex = metricAggs.length; const addIndex = metricAggs.length;
var id = _.reduce( const id = _.reduce(
$scope.target.bucketAggs.concat($scope.target.metrics), $scope.target.bucketAggs.concat($scope.target.metrics),
function(max, val) { function(max, val) {
return parseInt(val.id) > max ? parseInt(val.id) : max; return parseInt(val.id) > max ? parseInt(val.id) : max;
@ -203,6 +203,6 @@ export class ElasticMetricAggCtrl {
} }
} }
var module = angular.module('grafana.directives'); const module = angular.module('grafana.directives');
module.directive('elasticMetricAgg', elasticMetricAgg); module.directive('elasticMetricAgg', elasticMetricAgg);
module.controller('ElasticMetricAggCtrl', ElasticMetricAggCtrl); module.controller('ElasticMetricAggCtrl', ElasticMetricAggCtrl);

@ -10,7 +10,7 @@ export class ElasticQueryBuilder {
} }
getRangeFilter() { getRangeFilter() {
var filter = {}; const filter = {};
filter[this.timeField] = { filter[this.timeField] = {
gte: '$timeFrom', gte: '$timeFrom',
lte: '$timeTo', lte: '$timeTo',
@ -60,8 +60,8 @@ export class ElasticQueryBuilder {
} }
getDateHistogramAgg(aggDef) { getDateHistogramAgg(aggDef) {
var esAgg: any = {}; const esAgg: any = {};
var settings = aggDef.settings || {}; const settings = aggDef.settings || {};
esAgg.interval = settings.interval; esAgg.interval = settings.interval;
esAgg.field = this.timeField; esAgg.field = this.timeField;
esAgg.min_doc_count = settings.min_doc_count || 0; esAgg.min_doc_count = settings.min_doc_count || 0;
@ -80,8 +80,8 @@ export class ElasticQueryBuilder {
} }
getHistogramAgg(aggDef) { getHistogramAgg(aggDef) {
var esAgg: any = {}; const esAgg: any = {};
var settings = aggDef.settings || {}; const settings = aggDef.settings || {};
esAgg.interval = settings.interval; esAgg.interval = settings.interval;
esAgg.field = aggDef.field; esAgg.field = aggDef.field;
esAgg.min_doc_count = settings.min_doc_count || 0; esAgg.min_doc_count = settings.min_doc_count || 0;
@ -93,9 +93,9 @@ export class ElasticQueryBuilder {
} }
getFiltersAgg(aggDef) { getFiltersAgg(aggDef) {
var filterObj = {}; const filterObj = {};
for (var i = 0; i < aggDef.settings.filters.length; i++) { for (var i = 0; i < aggDef.settings.filters.length; i++) {
var query = aggDef.settings.filters[i].query; const query = aggDef.settings.filters[i].query;
var label = aggDef.settings.filters[i].label; var label = aggDef.settings.filters[i].label;
label = label === '' || label === undefined ? query : label; label = label === '' || label === undefined ? query : label;
filterObj[label] = { filterObj[label] = {
@ -182,7 +182,7 @@ export class ElasticQueryBuilder {
target.timeField = this.timeField; target.timeField = this.timeField;
var i, nestedAggs, metric; var i, nestedAggs, metric;
var query = { const query = {
size: 0, size: 0,
query: { query: {
bool: { bool: {
@ -208,15 +208,15 @@ export class ElasticQueryBuilder {
throw { message: 'Invalid query' }; throw { message: 'Invalid query' };
} }
var size = (metric.settings && metric.settings.size) || 500; const size = (metric.settings && metric.settings.size) || 500;
return this.documentQuery(query, size); return this.documentQuery(query, size);
} }
nestedAggs = query; nestedAggs = query;
for (i = 0; i < target.bucketAggs.length; i++) { for (i = 0; i < target.bucketAggs.length; i++) {
var aggDef = target.bucketAggs[i]; const aggDef = target.bucketAggs[i];
var esAgg = {}; const esAgg = {};
switch (aggDef.type) { switch (aggDef.type) {
case 'date_histogram': { case 'date_histogram': {
@ -257,7 +257,7 @@ export class ElasticQueryBuilder {
continue; continue;
} }
var aggField = {}; const aggField = {};
var metricAgg = null; var metricAgg = null;
if (queryDef.isPipelineAgg(metric.type)) { if (queryDef.isPipelineAgg(metric.type)) {
@ -270,7 +270,7 @@ export class ElasticQueryBuilder {
metricAgg = { field: metric.field }; metricAgg = { field: metric.field };
} }
for (var prop in metric.settings) { for (const prop in metric.settings) {
if (metric.settings.hasOwnProperty(prop) && metric.settings[prop] !== null) { if (metric.settings.hasOwnProperty(prop) && metric.settings[prop] !== null) {
metricAgg[prop] = metric.settings[prop]; metricAgg[prop] = metric.settings[prop];
} }
@ -284,7 +284,7 @@ export class ElasticQueryBuilder {
} }
getTermsQuery(queryDef) { getTermsQuery(queryDef) {
var query: any = { const query: any = {
size: 0, size: 0,
query: { query: {
bool: { bool: {

@ -21,7 +21,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
} }
getFields(type) { getFields(type) {
var jsonStr = angular.toJson({ find: 'fields', type: type }); const jsonStr = angular.toJson({ find: 'fields', type: type });
return this.datasource return this.datasource
.metricFindQuery(jsonStr) .metricFindQuery(jsonStr)
.then(this.uiSegmentSrv.transformToSegments(false)) .then(this.uiSegmentSrv.transformToSegments(false))
@ -29,7 +29,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
} }
queryUpdated() { queryUpdated() {
var newJson = angular.toJson(this.datasource.queryBuilder.build(this.target), true); const newJson = angular.toJson(this.datasource.queryBuilder.build(this.target), true);
if (this.rawQueryOld && newJson !== this.rawQueryOld) { if (this.rawQueryOld && newJson !== this.rawQueryOld) {
this.refresh(); this.refresh();
} }
@ -39,10 +39,10 @@ export class ElasticQueryCtrl extends QueryCtrl {
} }
getCollapsedText() { getCollapsedText() {
var metricAggs = this.target.metrics; const metricAggs = this.target.metrics;
var bucketAggs = this.target.bucketAggs; const bucketAggs = this.target.bucketAggs;
var metricAggTypes = queryDef.getMetricAggTypes(this.esVersion); const metricAggTypes = queryDef.getMetricAggTypes(this.esVersion);
var bucketAggTypes = queryDef.bucketAggTypes; const bucketAggTypes = queryDef.bucketAggTypes;
var text = ''; var text = '';
if (this.target.query) { if (this.target.query) {
@ -52,7 +52,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
text += 'Metrics: '; text += 'Metrics: ';
_.each(metricAggs, (metric, index) => { _.each(metricAggs, (metric, index) => {
var aggDef = _.find(metricAggTypes, { value: metric.type }); const aggDef = _.find(metricAggTypes, { value: metric.type });
text += aggDef.text + '('; text += aggDef.text + '(';
if (aggDef.requiresField) { if (aggDef.requiresField) {
text += metric.field; text += metric.field;
@ -65,7 +65,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
text += ' Group by: '; text += ' Group by: ';
} }
var aggDef = _.find(bucketAggTypes, { value: bucketAgg.type }); const aggDef = _.find(bucketAggTypes, { value: bucketAgg.type });
text += aggDef.text + '('; text += aggDef.text + '(';
if (aggDef.requiresField) { if (aggDef.requiresField) {
text += bucketAgg.field; text += bucketAgg.field;

@ -164,7 +164,7 @@ export function getPipelineOptions(metric) {
export function isPipelineAgg(metricType) { export function isPipelineAgg(metricType) {
if (metricType) { if (metricType) {
var po = pipelineOptions[metricType]; const po = pipelineOptions[metricType];
return po !== null && po !== undefined; return po !== null && po !== undefined;
} }
@ -172,7 +172,7 @@ export function isPipelineAgg(metricType) {
} }
export function getPipelineAggOptions(targets) { export function getPipelineAggOptions(targets) {
var result = []; const result = [];
_.each(targets.metrics, function(metric) { _.each(targets.metrics, function(metric) {
if (!isPipelineAgg(metric.type)) { if (!isPipelineAgg(metric.type)) {
result.push({ text: describeMetric(metric), value: metric.id }); result.push({ text: describeMetric(metric), value: metric.id });
@ -183,7 +183,7 @@ export function getPipelineAggOptions(targets) {
} }
export function getMovingAvgSettings(model, filtered) { export function getMovingAvgSettings(model, filtered) {
var filteredResult = []; const filteredResult = [];
if (filtered) { if (filtered) {
_.each(movingAvgModelSettings[model], function(setting) { _.each(movingAvgModelSettings[model], function(setting) {
if (!setting.isCheckbox) { if (!setting.isCheckbox) {
@ -196,7 +196,7 @@ export function getMovingAvgSettings(model, filtered) {
} }
export function getOrderByOptions(target) { export function getOrderByOptions(target) {
var metricRefs = []; const metricRefs = [];
_.each(target.metrics, function(metric) { _.each(target.metrics, function(metric) {
if (metric.type !== 'count') { if (metric.type !== 'count') {
metricRefs.push({ text: describeMetric(metric), value: metric.id }); metricRefs.push({ text: describeMetric(metric), value: metric.id });
@ -207,21 +207,21 @@ export function getOrderByOptions(target) {
} }
export function describeOrder(order) { export function describeOrder(order) {
var def = _.find(orderOptions, { value: order }); const def = _.find(orderOptions, { value: order });
return def.text; return def.text;
} }
export function describeMetric(metric) { export function describeMetric(metric) {
var def = _.find(metricAggTypes, { value: metric.type }); const def = _.find(metricAggTypes, { value: metric.type });
return def.text + ' ' + metric.field; return def.text + ' ' + metric.field;
} }
export function describeOrderBy(orderBy, target) { export function describeOrderBy(orderBy, target) {
var def = _.find(orderByOptions, { value: orderBy }); const def = _.find(orderByOptions, { value: orderBy });
if (def) { if (def) {
return def.text; return def.text;
} }
var metric = _.find(target.metrics, { id: orderBy }); const metric = _.find(target.metrics, { id: orderBy });
if (metric) { if (metric) {
return describeMetric(metric); return describeMetric(metric);
} else { } else {

@ -13,7 +13,7 @@ class GrafanaDatasource {
maxDataPoints: options.maxDataPoints, maxDataPoints: options.maxDataPoints,
}) })
.then(res => { .then(res => {
var data = []; const data = [];
if (res.results) { if (res.results) {
_.forEach(res.results, queryRes => { _.forEach(res.results, queryRes => {

@ -30,7 +30,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
}; };
this.query = function(options) { this.query = function(options) {
var graphOptions = { const graphOptions = {
from: this.translateTime(options.rangeRaw.from, false), from: this.translateTime(options.rangeRaw.from, false),
until: this.translateTime(options.rangeRaw.to, true), until: this.translateTime(options.rangeRaw.to, true),
targets: options.targets, targets: options.targets,
@ -39,12 +39,12 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
maxDataPoints: options.maxDataPoints, maxDataPoints: options.maxDataPoints,
}; };
var params = this.buildGraphiteParams(graphOptions, options.scopedVars); const params = this.buildGraphiteParams(graphOptions, options.scopedVars);
if (params.length === 0) { if (params.length === 0) {
return $q.when({ data: [] }); return $q.when({ data: [] });
} }
var httpOptions: any = { const httpOptions: any = {
method: 'POST', method: 'POST',
url: '/render', url: '/render',
data: params.join('&'), data: params.join('&'),
@ -63,7 +63,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
}; };
this.addTracingHeaders = function(httpOptions, options) { this.addTracingHeaders = function(httpOptions, options) {
var proxyMode = !this.url.match(/^http/); const proxyMode = !this.url.match(/^http/);
if (proxyMode) { if (proxyMode) {
httpOptions.headers['X-Dashboard-Id'] = options.dashboardId; httpOptions.headers['X-Dashboard-Id'] = options.dashboardId;
httpOptions.headers['X-Panel-Id'] = options.panelId; httpOptions.headers['X-Panel-Id'] = options.panelId;
@ -75,7 +75,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
return []; return [];
} }
for (var i = 0; i < result.data.length; i++) { for (var i = 0; i < result.data.length; i++) {
var series = result.data[i]; const series = result.data[i];
for (var y = 0; y < series.datapoints.length; y++) { for (var y = 0; y < series.datapoints.length; y++) {
series.datapoints[y][1] *= 1000; series.datapoints[y][1] *= 1000;
} }
@ -98,8 +98,8 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
this.annotationQuery = function(options) { this.annotationQuery = function(options) {
// Graphite metric as annotation // Graphite metric as annotation
if (options.annotation.target) { if (options.annotation.target) {
var target = templateSrv.replace(options.annotation.target, {}, 'glob'); const target = templateSrv.replace(options.annotation.target, {}, 'glob');
var graphiteQuery = { const graphiteQuery = {
rangeRaw: options.rangeRaw, rangeRaw: options.rangeRaw,
targets: [{ target: target }], targets: [{ target: target }],
format: 'json', format: 'json',
@ -107,13 +107,13 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
}; };
return this.query(graphiteQuery).then(function(result) { return this.query(graphiteQuery).then(function(result) {
var list = []; const list = [];
for (var i = 0; i < result.data.length; i++) { for (var i = 0; i < result.data.length; i++) {
var target = result.data[i]; const target = result.data[i];
for (var y = 0; y < target.datapoints.length; y++) { for (var y = 0; y < target.datapoints.length; y++) {
var datapoint = target.datapoints[y]; const datapoint = target.datapoints[y];
if (!datapoint[0]) { if (!datapoint[0]) {
continue; continue;
} }
@ -130,11 +130,11 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
}); });
} else { } else {
// Graphite event as annotation // Graphite event as annotation
var tags = templateSrv.replace(options.annotation.tags); const tags = templateSrv.replace(options.annotation.tags);
return this.events({ range: options.rangeRaw, tags: tags }).then(results => { return this.events({ range: options.rangeRaw, tags: tags }).then(results => {
var list = []; const list = [];
for (var i = 0; i < results.data.length; i++) { for (var i = 0; i < results.data.length; i++) {
var e = results.data[i]; const e = results.data[i];
var tags = e.tags; var tags = e.tags;
if (_.isString(e.tags)) { if (_.isString(e.tags)) {
@ -490,12 +490,12 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv
this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
this.buildGraphiteParams = function(options, scopedVars) { this.buildGraphiteParams = function(options, scopedVars) {
var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout']; const graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
var clean_options = [], const clean_options = [],
targets = {}; targets = {};
var target, targetValue, i; var target, targetValue, i;
var regex = /\#([A-Z])/g; const regex = /\#([A-Z])/g;
var intervalFormatFixRegex = /'(\d+)m'/gi; const intervalFormatFixRegex = /'(\d+)m'/gi;
var hasTargets = false; var hasTargets = false;
options['format'] = 'json'; options['format'] = 'json';

@ -41,9 +41,9 @@ export default class InfluxDatasource {
query(options) { query(options) {
var timeFilter = this.getTimeFilter(options); var timeFilter = this.getTimeFilter(options);
var scopedVars = options.scopedVars; const scopedVars = options.scopedVars;
var targets = _.cloneDeep(options.targets); const targets = _.cloneDeep(options.targets);
var queryTargets = []; const queryTargets = [];
var queryModel; var queryModel;
var i, y; var i, y;
@ -71,7 +71,7 @@ export default class InfluxDatasource {
} }
// add global adhoc filters to timeFilter // add global adhoc filters to timeFilter
var adhocFilters = this.templateSrv.getAdhocFilters(this.name); const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
if (adhocFilters.length > 0) { if (adhocFilters.length > 0) {
timeFilter += ' AND ' + queryModel.renderAdhocFilters(adhocFilters); timeFilter += ' AND ' + queryModel.renderAdhocFilters(adhocFilters);
} }
@ -87,20 +87,20 @@ export default class InfluxDatasource {
return []; return [];
} }
var seriesList = []; const seriesList = [];
for (i = 0; i < data.results.length; i++) { for (i = 0; i < data.results.length; i++) {
var result = data.results[i]; const result = data.results[i];
if (!result || !result.series) { if (!result || !result.series) {
continue; continue;
} }
var target = queryTargets[i]; const target = queryTargets[i];
var alias = target.alias; var alias = target.alias;
if (alias) { if (alias) {
alias = this.templateSrv.replace(target.alias, options.scopedVars); alias = this.templateSrv.replace(target.alias, options.scopedVars);
} }
var influxSeries = new InfluxSeries({ const influxSeries = new InfluxSeries({
series: data.results[i].series, series: data.results[i].series,
alias: alias, alias: alias,
}); });
@ -111,7 +111,7 @@ export default class InfluxDatasource {
break; break;
} }
default: { default: {
var timeSeries = influxSeries.getTimeSeries(); const timeSeries = influxSeries.getTimeSeries();
for (y = 0; y < timeSeries.length; y++) { for (y = 0; y < timeSeries.length; y++) {
seriesList.push(timeSeries[y]); seriesList.push(timeSeries[y]);
} }
@ -131,7 +131,7 @@ export default class InfluxDatasource {
}); });
} }
var timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw }); const timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
var query = options.annotation.query.replace('$timeFilter', timeFilter); var query = options.annotation.query.replace('$timeFilter', timeFilter);
query = this.templateSrv.replace(query, null, 'regex'); query = this.templateSrv.replace(query, null, 'regex');
@ -165,20 +165,20 @@ export default class InfluxDatasource {
} }
metricFindQuery(query: string, options?: any) { metricFindQuery(query: string, options?: any) {
var interpolated = this.templateSrv.replace(query, null, 'regex'); const interpolated = this.templateSrv.replace(query, null, 'regex');
return this._seriesQuery(interpolated, options).then(_.curry(this.responseParser.parse)(query)); return this._seriesQuery(interpolated, options).then(_.curry(this.responseParser.parse)(query));
} }
getTagKeys(options) { getTagKeys(options) {
var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database); const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
var query = queryBuilder.buildExploreQuery('TAG_KEYS'); const query = queryBuilder.buildExploreQuery('TAG_KEYS');
return this.metricFindQuery(query, options); return this.metricFindQuery(query, options);
} }
getTagValues(options) { getTagValues(options) {
var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database); const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
var query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key); const query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
return this.metricFindQuery(query, options); return this.metricFindQuery(query, options);
} }
@ -188,7 +188,7 @@ export default class InfluxDatasource {
} }
if (options && options.range) { if (options && options.range) {
var timeFilter = this.getTimeFilter({ rangeRaw: options.range }); const timeFilter = this.getTimeFilter({ rangeRaw: options.range });
query = query.replace('$timeFilter', timeFilter); query = query.replace('$timeFilter', timeFilter);
} }
@ -214,8 +214,8 @@ export default class InfluxDatasource {
} }
testDatasource() { testDatasource() {
var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database); const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
var query = queryBuilder.buildExploreQuery('RETENTION POLICIES'); const query = queryBuilder.buildExploreQuery('RETENTION POLICIES');
return this._seriesQuery(query) return this._seriesQuery(query)
.then(res => { .then(res => {
@ -295,9 +295,9 @@ export default class InfluxDatasource {
} }
getTimeFilter(options) { getTimeFilter(options) {
var from = this.getInfluxTime(options.rangeRaw.from, false); const from = this.getInfluxTime(options.rangeRaw.from, false);
var until = this.getInfluxTime(options.rangeRaw.to, true); const until = this.getInfluxTime(options.rangeRaw.to, true);
var fromIsAbsolute = from[from.length - 1] === 'ms'; const fromIsAbsolute = from[from.length - 1] === 'ms';
if (until === 'now()' && !fromIsAbsolute) { if (until === 'now()' && !fromIsAbsolute) {
return 'time >= ' + from; return 'time >= ' + from;
@ -312,10 +312,10 @@ export default class InfluxDatasource {
return 'now()'; return 'now()';
} }
var parts = /^now-(\d+)([d|h|m|s])$/.exec(date); const parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
if (parts) { if (parts) {
var amount = parseInt(parts[1]); const amount = parseInt(parts[1]);
var unit = parts[2]; const unit = parts[2];
return 'now() - ' + amount + unit; return 'now() - ' + amount + unit;
} }
date = dateMath.parse(date, roundUp); date = dateMath.parse(date, roundUp);

@ -50,11 +50,11 @@ export default class InfluxQuery {
} }
addGroupBy(value) { addGroupBy(value) {
var stringParts = value.match(/^(\w+)\((.*)\)$/); const stringParts = value.match(/^(\w+)\((.*)\)$/);
var typePart = stringParts[1]; const typePart = stringParts[1];
var arg = stringParts[2]; const arg = stringParts[2];
var partModel = queryPart.create({ type: typePart, params: [arg] }); const partModel = queryPart.create({ type: typePart, params: [arg] });
var partCount = this.target.groupBy.length; const partCount = this.target.groupBy.length;
if (partCount === 0) { if (partCount === 0) {
this.target.groupBy.push(partModel.part); this.target.groupBy.push(partModel.part);
@ -74,7 +74,7 @@ export default class InfluxQuery {
} }
removeGroupByPart(part, index) { removeGroupByPart(part, index) {
var categories = queryPart.getCategories(); const categories = queryPart.getCategories();
if (part.def.type === 'time') { if (part.def.type === 'time') {
// remove fill // remove fill
@ -82,7 +82,7 @@ export default class InfluxQuery {
// remove aggregations // remove aggregations
this.target.select = _.map(this.target.select, (s: any) => { this.target.select = _.map(this.target.select, (s: any) => {
return _.filter(s, (part: any) => { return _.filter(s, (part: any) => {
var partModel = queryPart.create(part); const partModel = queryPart.create(part);
if (partModel.def.category === categories.Aggregations) { if (partModel.def.category === categories.Aggregations) {
return false; return false;
} }
@ -107,11 +107,11 @@ export default class InfluxQuery {
// if we remove the field remove the whole statement // if we remove the field remove the whole statement
if (part.def.type === 'field') { if (part.def.type === 'field') {
if (this.selectModels.length > 1) { if (this.selectModels.length > 1) {
var modelsIndex = _.indexOf(this.selectModels, selectParts); const modelsIndex = _.indexOf(this.selectModels, selectParts);
this.selectModels.splice(modelsIndex, 1); this.selectModels.splice(modelsIndex, 1);
} }
} else { } else {
var partIndex = _.indexOf(selectParts, part); const partIndex = _.indexOf(selectParts, part);
selectParts.splice(partIndex, 1); selectParts.splice(partIndex, 1);
} }
@ -119,7 +119,7 @@ export default class InfluxQuery {
} }
addSelectPart(selectParts, type) { addSelectPart(selectParts, type) {
var partModel = queryPart.create({ type: type }); const partModel = queryPart.create({ type: type });
partModel.def.addStrategy(selectParts, partModel, this); partModel.def.addStrategy(selectParts, partModel, this);
this.updatePersistedParts(); this.updatePersistedParts();
} }
@ -184,12 +184,12 @@ export default class InfluxQuery {
return kbn.regexEscape(value); return kbn.regexEscape(value);
} }
var escapedValues = _.map(value, kbn.regexEscape); const escapedValues = _.map(value, kbn.regexEscape);
return '(' + escapedValues.join('|') + ')'; return '(' + escapedValues.join('|') + ')';
} }
render(interpolate?) { render(interpolate?) {
var target = this.target; const target = this.target;
if (target.rawQuery) { if (target.rawQuery) {
if (interpolate) { if (interpolate) {
@ -216,7 +216,7 @@ export default class InfluxQuery {
} }
query += ' FROM ' + this.getMeasurementAndPolicy(interpolate) + ' WHERE '; query += ' FROM ' + this.getMeasurementAndPolicy(interpolate) + ' WHERE ';
var conditions = _.map(target.tags, (tag, index) => { const conditions = _.map(target.tags, (tag, index) => {
return this.renderTagCondition(tag, index, interpolate); return this.renderTagCondition(tag, index, interpolate);
}); });
@ -228,7 +228,7 @@ export default class InfluxQuery {
var groupBySection = ''; var groupBySection = '';
for (i = 0; i < this.groupByParts.length; i++) { for (i = 0; i < this.groupByParts.length; i++) {
var part = this.groupByParts[i]; const part = this.groupByParts[i];
if (i > 0) { if (i > 0) {
// for some reason fill has no separator // for some reason fill has no separator
groupBySection += part.def.type === 'fill' ? ' ' : ', '; groupBySection += part.def.type === 'fill' ? ' ' : ', ';
@ -260,7 +260,7 @@ export default class InfluxQuery {
} }
renderAdhocFilters(filters) { renderAdhocFilters(filters) {
var conditions = _.map(filters, (tag, index) => { const conditions = _.map(filters, (tag, index) => {
return this.renderTagCondition(tag, index, false); return this.renderTagCondition(tag, index, false);
}); });
return conditions.join(' '); return conditions.join(' ');

@ -13,7 +13,7 @@ export default class InfluxSeries {
} }
getTimeSeries() { getTimeSeries() {
var output = []; const output = [];
var i, j; var i, j;
if (this.series.length === 0) { if (this.series.length === 0) {
@ -21,14 +21,14 @@ export default class InfluxSeries {
} }
_.each(this.series, series => { _.each(this.series, series => {
var columns = series.columns.length; const columns = series.columns.length;
var tags = _.map(series.tags, function(value, key) { const tags = _.map(series.tags, function(value, key) {
return key + ': ' + value; return key + ': ' + value;
}); });
for (j = 1; j < columns; j++) { for (j = 1; j < columns; j++) {
var seriesName = series.name; var seriesName = series.name;
var columnName = series.columns[j]; const columnName = series.columns[j];
if (columnName !== 'value') { if (columnName !== 'value') {
seriesName = seriesName + '.' + columnName; seriesName = seriesName + '.' + columnName;
} }
@ -39,7 +39,7 @@ export default class InfluxSeries {
seriesName = seriesName + ' {' + tags.join(', ') + '}'; seriesName = seriesName + ' {' + tags.join(', ') + '}';
} }
var datapoints = []; const datapoints = [];
if (series.values) { if (series.values) {
for (i = 0; i < series.values.length; i++) { for (i = 0; i < series.values.length; i++) {
datapoints[i] = [series.values[i][j], series.values[i][0]]; datapoints[i] = [series.values[i][j], series.values[i][0]];
@ -54,12 +54,12 @@ export default class InfluxSeries {
} }
_getSeriesName(series, index) { _getSeriesName(series, index) {
var regex = /\$(\w+)|\[\[([\s\S]+?)\]\]/g; const regex = /\$(\w+)|\[\[([\s\S]+?)\]\]/g;
var segments = series.name.split('.'); const segments = series.name.split('.');
return this.alias.replace(regex, function(match, g1, g2) { return this.alias.replace(regex, function(match, g1, g2) {
var group = g1 || g2; const group = g1 || g2;
var segIndex = parseInt(group, 10); const segIndex = parseInt(group, 10);
if (group === 'm' || group === 'measurement') { if (group === 'm' || group === 'measurement') {
return series.name; return series.name;
@ -74,7 +74,7 @@ export default class InfluxSeries {
return match; return match;
} }
var tag = group.replace('tag_', ''); const tag = group.replace('tag_', '');
if (!series.tags) { if (!series.tags) {
return match; return match;
} }
@ -83,12 +83,12 @@ export default class InfluxSeries {
} }
getAnnotations() { getAnnotations() {
var list = []; const list = [];
_.each(this.series, series => { _.each(this.series, series => {
var titleCol = null; var titleCol = null;
var timeCol = null; var timeCol = null;
var tagsCol = []; const tagsCol = [];
var textCol = null; var textCol = null;
_.each(series.columns, (column, index) => { _.each(series.columns, (column, index) => {
@ -117,7 +117,7 @@ export default class InfluxSeries {
}); });
_.each(series.values, value => { _.each(series.values, value => {
var data = { const data = {
annotation: this.annotation, annotation: this.annotation,
time: +new Date(value[timeCol]), time: +new Date(value[timeCol]),
title: value[titleCol], title: value[titleCol],
@ -142,7 +142,7 @@ export default class InfluxSeries {
} }
getTable() { getTable() {
var table = new TableModel(); const table = new TableModel();
var i, j; var i, j;
if (this.series.length === 0) { if (this.series.length === 0) {
@ -168,10 +168,10 @@ export default class InfluxSeries {
if (series.values) { if (series.values) {
for (i = 0; i < series.values.length; i++) { for (i = 0; i < series.values.length; i++) {
var values = series.values[i]; const values = series.values[i];
var reordered = [values[0]]; const reordered = [values[0]];
if (series.tags) { if (series.tags) {
for (var key in series.tags) { for (const key in series.tags) {
if (series.tags.hasOwnProperty(key)) { if (series.tags.hasOwnProperty(key)) {
reordered.push(series.tags[key]); reordered.push(series.tags[key]);
} }

@ -82,7 +82,7 @@ export class InfluxQueryBuilder {
} }
if (this.target.tags && this.target.tags.length > 0) { if (this.target.tags && this.target.tags.length > 0) {
var whereConditions = _.reduce( const whereConditions = _.reduce(
this.target.tags, this.target.tags,
function(memo, tag) { function(memo, tag) {
// do not add a condition for the key we want to explore for // do not add a condition for the key we want to explore for

@ -67,11 +67,11 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
buildSelectMenu() { buildSelectMenu() {
var categories = queryPart.getCategories(); const categories = queryPart.getCategories();
this.selectMenu = _.reduce( this.selectMenu = _.reduce(
categories, categories,
function(memo, cat, key) { function(memo, cat, key) {
var menu = { const menu = {
text: key, text: key,
submenu: cat.map(item => { submenu: cat.map(item => {
return { text: item.type, value: item.type }; return { text: item.type, value: item.type };
@ -85,12 +85,12 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
getGroupByOptions() { getGroupByOptions() {
var query = this.queryBuilder.buildExploreQuery('TAG_KEYS'); const query = this.queryBuilder.buildExploreQuery('TAG_KEYS');
return this.datasource return this.datasource
.metricFindQuery(query) .metricFindQuery(query)
.then(tags => { .then(tags => {
var options = []; const options = [];
if (!this.queryModel.hasFill()) { if (!this.queryModel.hasFill()) {
options.push(this.uiSegmentSrv.newSegment({ value: 'fill(null)' })); options.push(this.uiSegmentSrv.newSegment({ value: 'fill(null)' }));
} }
@ -133,7 +133,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
} }
var plusButton = this.uiSegmentSrv.newPlusButton(); const plusButton = this.uiSegmentSrv.newPlusButton();
this.groupBySegment.value = plusButton.value; this.groupBySegment.value = plusButton.value;
this.groupBySegment.html = plusButton.html; this.groupBySegment.html = plusButton.html;
this.panelCtrl.refresh(); this.panelCtrl.refresh();
@ -147,7 +147,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
handleSelectPartEvent(selectParts, part, evt) { handleSelectPartEvent(selectParts, part, evt) {
switch (evt.name) { switch (evt.name) {
case 'get-param-options': { case 'get-param-options': {
var fieldsQuery = this.queryBuilder.buildExploreQuery('FIELDS'); const fieldsQuery = this.queryBuilder.buildExploreQuery('FIELDS');
return this.datasource return this.datasource
.metricFindQuery(fieldsQuery) .metricFindQuery(fieldsQuery)
.then(this.transformToSegments(true)) .then(this.transformToSegments(true))
@ -171,7 +171,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
handleGroupByPartEvent(part, index, evt) { handleGroupByPartEvent(part, index, evt) {
switch (evt.name) { switch (evt.name) {
case 'get-param-options': { case 'get-param-options': {
var tagsQuery = this.queryBuilder.buildExploreQuery('TAG_KEYS'); const tagsQuery = this.queryBuilder.buildExploreQuery('TAG_KEYS');
return this.datasource return this.datasource
.metricFindQuery(tagsQuery) .metricFindQuery(tagsQuery)
.then(this.transformToSegments(true)) .then(this.transformToSegments(true))
@ -193,8 +193,8 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
fixTagSegments() { fixTagSegments() {
var count = this.tagSegments.length; const count = this.tagSegments.length;
var lastSegment = this.tagSegments[Math.max(count - 1, 0)]; const lastSegment = this.tagSegments[Math.max(count - 1, 0)];
if (!lastSegment || lastSegment.type !== 'plus-button') { if (!lastSegment || lastSegment.type !== 'plus-button') {
this.tagSegments.push(this.uiSegmentSrv.newPlusButton()); this.tagSegments.push(this.uiSegmentSrv.newPlusButton());
@ -207,7 +207,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
getPolicySegments() { getPolicySegments() {
var policiesQuery = this.queryBuilder.buildExploreQuery('RETENTION POLICIES'); const policiesQuery = this.queryBuilder.buildExploreQuery('RETENTION POLICIES');
return this.datasource return this.datasource
.metricFindQuery(policiesQuery) .metricFindQuery(policiesQuery)
.then(this.transformToSegments(false)) .then(this.transformToSegments(false))
@ -229,7 +229,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
getMeasurements(measurementFilter) { getMeasurements(measurementFilter) {
var query = this.queryBuilder.buildExploreQuery('MEASUREMENTS', undefined, measurementFilter); const query = this.queryBuilder.buildExploreQuery('MEASUREMENTS', undefined, measurementFilter);
return this.datasource return this.datasource
.metricFindQuery(query) .metricFindQuery(query)
.then(this.transformToSegments(true)) .then(this.transformToSegments(true))
@ -243,7 +243,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
transformToSegments(addTemplateVars) { transformToSegments(addTemplateVars) {
return results => { return results => {
var segments = _.map(results, segment => { const segments = _.map(results, segment => {
return this.uiSegmentSrv.newSegment({ return this.uiSegmentSrv.newSegment({
value: segment.text, value: segment.text,
expandable: segment.expandable, expandable: segment.expandable,
@ -271,7 +271,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]); return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]);
} }
if (segment.type === 'operator') { if (segment.type === 'operator') {
var nextValue = this.tagSegments[index + 1].value; const nextValue = this.tagSegments[index + 1].value;
if (/^\/.*\/$/.test(nextValue)) { if (/^\/.*\/$/.test(nextValue)) {
return this.$q.when(this.uiSegmentSrv.newOperators(['=~', '!~'])); return this.$q.when(this.uiSegmentSrv.newOperators(['=~', '!~']));
} else { } else {
@ -301,7 +301,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
getFieldSegments() { getFieldSegments() {
var fieldsQuery = this.queryBuilder.buildExploreQuery('FIELDS'); const fieldsQuery = this.queryBuilder.buildExploreQuery('FIELDS');
return this.datasource return this.datasource
.metricFindQuery(fieldsQuery) .metricFindQuery(fieldsQuery)
.then(this.transformToSegments(false)) .then(this.transformToSegments(false))
@ -342,7 +342,7 @@ export class InfluxQueryCtrl extends QueryCtrl {
} }
rebuildTargetTagConditions() { rebuildTargetTagConditions() {
var tags = []; const tags = [];
var tagIndex = 0; var tagIndex = 0;
var tagOperator = ''; var tagOperator = '';

@ -1,8 +1,8 @@
import _ from 'lodash'; import _ from 'lodash';
import { QueryPartDef, QueryPart, functionRenderer, suffixRenderer } from 'app/core/components/query_part/query_part'; import { QueryPartDef, QueryPart, functionRenderer, suffixRenderer } from 'app/core/components/query_part/query_part';
var index = []; const index = [];
var categories = { const categories = {
Aggregations: [], Aggregations: [],
Selectors: [], Selectors: [],
Transformations: [], Transformations: [],
@ -13,7 +13,7 @@ var categories = {
}; };
function createPart(part): any { function createPart(part): any {
var def = index[part.type]; const def = index[part.type];
if (!def) { if (!def) {
throw { message: 'Could not find query part ' + part.type }; throw { message: 'Could not find query part ' + part.type };
} }
@ -26,7 +26,7 @@ function register(options: any) {
options.category.push(index[options.type]); options.category.push(index[options.type]);
} }
var groupByTimeFunctions = []; const groupByTimeFunctions = [];
function aliasRenderer(part, innerExpr) { function aliasRenderer(part, innerExpr) {
return innerExpr + ' AS ' + '"' + part.params[0] + '"'; return innerExpr + ' AS ' + '"' + part.params[0] + '"';
@ -42,7 +42,7 @@ function fieldRenderer(part, innerExpr) {
function replaceAggregationAddStrategy(selectParts, partModel) { function replaceAggregationAddStrategy(selectParts, partModel) {
// look for existing aggregation // look for existing aggregation
for (var i = 0; i < selectParts.length; i++) { for (var i = 0; i < selectParts.length; i++) {
var part = selectParts[i]; const part = selectParts[i];
if (part.def.category === categories.Aggregations) { if (part.def.category === categories.Aggregations) {
if (part.def.type === partModel.def.type) { if (part.def.type === partModel.def.type) {
return; return;
@ -53,9 +53,9 @@ function replaceAggregationAddStrategy(selectParts, partModel) {
} }
// remove next aggregation if distinct was replaced // remove next aggregation if distinct was replaced
if (part.def.type === 'distinct') { if (part.def.type === 'distinct') {
var morePartsAvailable = selectParts.length >= i + 2; const morePartsAvailable = selectParts.length >= i + 2;
if (partModel.def.type !== 'count' && morePartsAvailable) { if (partModel.def.type !== 'count' && morePartsAvailable) {
var nextPart = selectParts[i + 1]; const nextPart = selectParts[i + 1];
if (nextPart.def.category === categories.Aggregations) { if (nextPart.def.category === categories.Aggregations) {
selectParts.splice(i + 1, 1); selectParts.splice(i + 1, 1);
} }
@ -82,7 +82,7 @@ function addTransformationStrategy(selectParts, partModel) {
var i; var i;
// look for index to add transformation // look for index to add transformation
for (i = 0; i < selectParts.length; i++) { for (i = 0; i < selectParts.length; i++) {
var part = selectParts[i]; const part = selectParts[i];
if (part.def.category === categories.Math || part.def.category === categories.Aliasing) { if (part.def.category === categories.Math || part.def.category === categories.Aliasing) {
break; break;
} }
@ -92,7 +92,7 @@ function addTransformationStrategy(selectParts, partModel) {
} }
function addMathStrategy(selectParts, partModel) { function addMathStrategy(selectParts, partModel) {
var partCount = selectParts.length; const partCount = selectParts.length;
if (partCount > 0) { if (partCount > 0) {
// if last is math, replace it // if last is math, replace it
if (selectParts[partCount - 1].def.type === 'math') { if (selectParts[partCount - 1].def.type === 'math') {
@ -113,7 +113,7 @@ function addMathStrategy(selectParts, partModel) {
} }
function addAliasStrategy(selectParts, partModel) { function addAliasStrategy(selectParts, partModel) {
var partCount = selectParts.length; const partCount = selectParts.length;
if (partCount > 0) { if (partCount > 0) {
// if last is alias, replace it // if last is alias, replace it
if (selectParts[partCount - 1].def.type === 'alias') { if (selectParts[partCount - 1].def.type === 'alias') {
@ -126,7 +126,7 @@ function addAliasStrategy(selectParts, partModel) {
function addFieldStrategy(selectParts, partModel, query) { function addFieldStrategy(selectParts, partModel, query) {
// copy all parts // copy all parts
var parts = _.map(selectParts, function(part: any) { const parts = _.map(selectParts, function(part: any) {
return createPart({ type: part.def.type, params: _.clone(part.params) }); return createPart({ type: part.def.type, params: _.clone(part.params) });
}); });

@ -6,16 +6,16 @@ export default class ResponseParser {
return []; return [];
} }
var influxResults = results.results[0]; const influxResults = results.results[0];
if (!influxResults.series) { if (!influxResults.series) {
return []; return [];
} }
var normalizedQuery = query.toLowerCase(); const normalizedQuery = query.toLowerCase();
var isValueFirst = const isValueFirst =
normalizedQuery.indexOf('show field keys') >= 0 || normalizedQuery.indexOf('show retention policies') >= 0; normalizedQuery.indexOf('show field keys') >= 0 || normalizedQuery.indexOf('show retention policies') >= 0;
var res = {}; const res = {};
_.each(influxResults.series, serie => { _.each(influxResults.series, serie => {
_.each(serie.values, value => { _.each(serie.values, value => {
if (_.isArray(value)) { if (_.isArray(value)) {

@ -26,7 +26,7 @@ export class MssqlDatasource {
return value; return value;
} }
var quotedValues = _.map(value, function(val) { const quotedValues = _.map(value, function(val) {
if (typeof value === 'number') { if (typeof value === 'number') {
return value; return value;
} }
@ -37,7 +37,7 @@ export class MssqlDatasource {
} }
query(options) { query(options) {
var queries = _.filter(options.targets, item => { const queries = _.filter(options.targets, item => {
return item.hide !== true; return item.hide !== true;
}).map(item => { }).map(item => {
return { return {

@ -4,7 +4,7 @@ export default class ResponseParser {
constructor(private $q) {} constructor(private $q) {}
processQueryResult(res) { processQueryResult(res) {
var data = []; const data = [];
if (!res.data.results) { if (!res.data.results) {
return { data: data }; return { data: data };

@ -26,7 +26,7 @@ export class MysqlDatasource {
return value; return value;
} }
var quotedValues = _.map(value, function(val) { const quotedValues = _.map(value, function(val) {
if (typeof value === 'number') { if (typeof value === 'number') {
return value; return value;
} }
@ -37,7 +37,7 @@ export class MysqlDatasource {
} }
query(options) { query(options) {
var queries = _.filter(options.targets, item => { const queries = _.filter(options.targets, item => {
return item.hide !== true; return item.hide !== true;
}).map(item => { }).map(item => {
return { return {
@ -107,7 +107,7 @@ export class MysqlDatasource {
format: 'table', format: 'table',
}; };
var data = { const data = {
queries: [interpolatedQuery], queries: [interpolatedQuery],
}; };

@ -4,7 +4,7 @@ export default class ResponseParser {
constructor(private $q) {} constructor(private $q) {}
processQueryResult(res) { processQueryResult(res) {
var data = []; const data = [];
if (!res.data.results) { if (!res.data.results) {
return { data: data }; return { data: data };

@ -35,9 +35,9 @@ export default class OpenTsDatasource {
// Called once per panel (graph) // Called once per panel (graph)
query(options) { query(options) {
var start = this.convertToTSDBTime(options.rangeRaw.from, false); const start = this.convertToTSDBTime(options.rangeRaw.from, false);
var end = this.convertToTSDBTime(options.rangeRaw.to, true); const end = this.convertToTSDBTime(options.rangeRaw.to, true);
var qs = []; const qs = [];
_.each( _.each(
options.targets, options.targets,
@ -49,16 +49,16 @@ export default class OpenTsDatasource {
}.bind(this) }.bind(this)
); );
var queries = _.compact(qs); const queries = _.compact(qs);
// No valid targets, return the empty result to save a round trip. // No valid targets, return the empty result to save a round trip.
if (_.isEmpty(queries)) { if (_.isEmpty(queries)) {
var d = this.$q.defer(); const d = this.$q.defer();
d.resolve({ data: [] }); d.resolve({ data: [] });
return d.promise; return d.promise;
} }
var groupByTags = {}; const groupByTags = {};
_.each(queries, function(query) { _.each(queries, function(query) {
if (query.filters && query.filters.length > 0) { if (query.filters && query.filters.length > 0) {
_.each(query.filters, function(val) { _.each(query.filters, function(val) {
@ -77,8 +77,8 @@ export default class OpenTsDatasource {
return this.performTimeSeriesQuery(queries, start, end).then( return this.performTimeSeriesQuery(queries, start, end).then(
function(response) { function(response) {
var metricToTargetMapping = this.mapMetricsToTargets(response.data, options, this.tsdbVersion); const metricToTargetMapping = this.mapMetricsToTargets(response.data, options, this.tsdbVersion);
var result = _.map( const result = _.map(
response.data, response.data,
function(metricData, index) { function(metricData, index) {
index = metricToTargetMapping[index]; index = metricToTargetMapping[index];
@ -102,14 +102,14 @@ export default class OpenTsDatasource {
} }
annotationQuery(options) { annotationQuery(options) {
var start = this.convertToTSDBTime(options.rangeRaw.from, false); const start = this.convertToTSDBTime(options.rangeRaw.from, false);
var end = this.convertToTSDBTime(options.rangeRaw.to, true); const end = this.convertToTSDBTime(options.rangeRaw.to, true);
var qs = []; const qs = [];
var eventList = []; const eventList = [];
qs.push({ aggregator: 'sum', metric: options.annotation.target }); qs.push({ aggregator: 'sum', metric: options.annotation.target });
var queries = _.compact(qs); const queries = _.compact(qs);
return this.performTimeSeriesQuery(queries, start, end).then( return this.performTimeSeriesQuery(queries, start, end).then(
function(results) { function(results) {
@ -120,7 +120,7 @@ export default class OpenTsDatasource {
} }
if (annotationObject) { if (annotationObject) {
_.each(annotationObject, function(annotation) { _.each(annotationObject, function(annotation) {
var event = { const event = {
text: annotation.description, text: annotation.description,
time: Math.floor(annotation.startTime) * 1000, time: Math.floor(annotation.startTime) * 1000,
annotation: options.annotation, annotation: options.annotation,
@ -145,7 +145,7 @@ export default class OpenTsDatasource {
} }
if (target.tags && Object.keys(target.tags).length > 0) { if (target.tags && Object.keys(target.tags).length > 0) {
for (var tagKey in target.tags) { for (const tagKey in target.tags) {
if (this.templateSrv.variableExists(target.tags[tagKey])) { if (this.templateSrv.variableExists(target.tags[tagKey])) {
return true; return true;
} }
@ -160,7 +160,7 @@ export default class OpenTsDatasource {
if (this.tsdbResolution === 2) { if (this.tsdbResolution === 2) {
msResolution = true; msResolution = true;
} }
var reqBody: any = { const reqBody: any = {
start: start, start: start,
queries: queries, queries: queries,
msResolution: msResolution, msResolution: msResolution,
@ -175,7 +175,7 @@ export default class OpenTsDatasource {
reqBody.end = end; reqBody.end = end;
} }
var options = { const options = {
method: 'POST', method: 'POST',
url: this.url + '/api/query', url: this.url + '/api/query',
data: reqBody, data: reqBody,
@ -190,7 +190,7 @@ export default class OpenTsDatasource {
} }
_saveTagKeys(metricData) { _saveTagKeys(metricData) {
var tagKeys = Object.keys(metricData.tags); const tagKeys = Object.keys(metricData.tags);
_.each(metricData.aggregateTags, function(tag) { _.each(metricData.aggregateTags, function(tag) {
tagKeys.push(tag); tagKeys.push(tag);
}); });
@ -209,21 +209,21 @@ export default class OpenTsDatasource {
return this.$q.when([]); return this.$q.when([]);
} }
var keysArray = keys.split(',').map(function(key) { const keysArray = keys.split(',').map(function(key) {
return key.trim(); return key.trim();
}); });
var key = keysArray[0]; const key = keysArray[0];
var keysQuery = key + '=*'; var keysQuery = key + '=*';
if (keysArray.length > 1) { if (keysArray.length > 1) {
keysQuery += ',' + keysArray.splice(1).join(','); keysQuery += ',' + keysArray.splice(1).join(',');
} }
var m = metric + '{' + keysQuery + '}'; const m = metric + '{' + keysQuery + '}';
return this._get('/api/search/lookup', { m: m, limit: 3000 }).then(function(result) { return this._get('/api/search/lookup', { m: m, limit: 3000 }).then(function(result) {
result = result.data.results; result = result.data.results;
var tagvs = []; const tagvs = [];
_.each(result, function(r) { _.each(result, function(r) {
if (tagvs.indexOf(r.tags[key]) === -1) { if (tagvs.indexOf(r.tags[key]) === -1) {
tagvs.push(r.tags[key]); tagvs.push(r.tags[key]);
@ -240,7 +240,7 @@ export default class OpenTsDatasource {
return this._get('/api/search/lookup', { m: metric, limit: 1000 }).then(function(result) { return this._get('/api/search/lookup', { m: metric, limit: 1000 }).then(function(result) {
result = result.data.results; result = result.data.results;
var tagks = []; const tagks = [];
_.each(result, function(r) { _.each(result, function(r) {
_.each(r.tags, function(tagv, tagk) { _.each(r.tags, function(tagv, tagk) {
if (tagks.indexOf(tagk) === -1) { if (tagks.indexOf(tagk) === -1) {
@ -253,7 +253,7 @@ export default class OpenTsDatasource {
} }
_get(relativeUrl, params?) { _get(relativeUrl, params?) {
var options = { const options = {
method: 'GET', method: 'GET',
url: this.url + relativeUrl, url: this.url + relativeUrl,
params: params, params: params,
@ -285,39 +285,39 @@ export default class OpenTsDatasource {
return this.$q.reject(err); return this.$q.reject(err);
} }
var responseTransform = function(result) { const responseTransform = function(result) {
return _.map(result, function(value) { return _.map(result, function(value) {
return { text: value }; return { text: value };
}); });
}; };
var metrics_regex = /metrics\((.*)\)/; const metrics_regex = /metrics\((.*)\)/;
var tag_names_regex = /tag_names\((.*)\)/; const tag_names_regex = /tag_names\((.*)\)/;
var tag_values_regex = /tag_values\((.*?),\s?(.*)\)/; const tag_values_regex = /tag_values\((.*?),\s?(.*)\)/;
var tag_names_suggest_regex = /suggest_tagk\((.*)\)/; const tag_names_suggest_regex = /suggest_tagk\((.*)\)/;
var tag_values_suggest_regex = /suggest_tagv\((.*)\)/; const tag_values_suggest_regex = /suggest_tagv\((.*)\)/;
var metrics_query = interpolated.match(metrics_regex); const metrics_query = interpolated.match(metrics_regex);
if (metrics_query) { if (metrics_query) {
return this._performSuggestQuery(metrics_query[1], 'metrics').then(responseTransform); return this._performSuggestQuery(metrics_query[1], 'metrics').then(responseTransform);
} }
var tag_names_query = interpolated.match(tag_names_regex); const tag_names_query = interpolated.match(tag_names_regex);
if (tag_names_query) { if (tag_names_query) {
return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform); return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform);
} }
var tag_values_query = interpolated.match(tag_values_regex); const tag_values_query = interpolated.match(tag_values_regex);
if (tag_values_query) { if (tag_values_query) {
return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2]).then(responseTransform); return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2]).then(responseTransform);
} }
var tag_names_suggest_query = interpolated.match(tag_names_suggest_regex); const tag_names_suggest_query = interpolated.match(tag_names_suggest_regex);
if (tag_names_suggest_query) { if (tag_names_suggest_query) {
return this._performSuggestQuery(tag_names_suggest_query[1], 'tagk').then(responseTransform); return this._performSuggestQuery(tag_names_suggest_query[1], 'tagk').then(responseTransform);
} }
var tag_values_suggest_query = interpolated.match(tag_values_suggest_regex); const tag_values_suggest_query = interpolated.match(tag_values_suggest_regex);
if (tag_values_suggest_query) { if (tag_values_suggest_query) {
return this._performSuggestQuery(tag_values_suggest_query[1], 'tagv').then(responseTransform); return this._performSuggestQuery(tag_values_suggest_query[1], 'tagv').then(responseTransform);
} }
@ -360,8 +360,8 @@ export default class OpenTsDatasource {
} }
transformMetricData(md, groupByTags, target, options, tsdbResolution) { transformMetricData(md, groupByTags, target, options, tsdbResolution) {
var metricLabel = this.createMetricLabel(md, target, groupByTags, options); const metricLabel = this.createMetricLabel(md, target, groupByTags, options);
var dps = []; const dps = [];
// TSDB returns datapoints has a hash of ts => value. // TSDB returns datapoints has a hash of ts => value.
// Can't use _.pairs(invert()) because it stringifies keys/values // Can't use _.pairs(invert()) because it stringifies keys/values
@ -378,7 +378,7 @@ export default class OpenTsDatasource {
createMetricLabel(md, target, groupByTags, options) { createMetricLabel(md, target, groupByTags, options) {
if (target.alias) { if (target.alias) {
var scopedVars = _.clone(options.scopedVars || {}); const scopedVars = _.clone(options.scopedVars || {});
_.each(md.tags, function(value, key) { _.each(md.tags, function(value, key) {
scopedVars['tag_' + key] = { value: value }; scopedVars['tag_' + key] = { value: value };
}); });
@ -386,7 +386,7 @@ export default class OpenTsDatasource {
} }
var label = md.metric; var label = md.metric;
var tagData = []; const tagData = [];
if (!_.isEmpty(md.tags)) { if (!_.isEmpty(md.tags)) {
_.each(_.toPairs(md.tags), function(tag) { _.each(_.toPairs(md.tags), function(tag) {
@ -408,7 +408,7 @@ export default class OpenTsDatasource {
return null; return null;
} }
var query: any = { const query: any = {
metric: this.templateSrv.replace(target.metric, options.scopedVars, 'pipe'), metric: this.templateSrv.replace(target.metric, options.scopedVars, 'pipe'),
aggregator: 'avg', aggregator: 'avg',
}; };
@ -454,7 +454,7 @@ export default class OpenTsDatasource {
if (target.filters && target.filters.length > 0) { if (target.filters && target.filters.length > 0) {
query.filters = angular.copy(target.filters); query.filters = angular.copy(target.filters);
if (query.filters) { if (query.filters) {
for (var filter_key in query.filters) { for (const filter_key in query.filters) {
query.filters[filter_key].filter = this.templateSrv.replace( query.filters[filter_key].filter = this.templateSrv.replace(
query.filters[filter_key].filter, query.filters[filter_key].filter,
options.scopedVars, options.scopedVars,
@ -465,7 +465,7 @@ export default class OpenTsDatasource {
} else { } else {
query.tags = angular.copy(target.tags); query.tags = angular.copy(target.tags);
if (query.tags) { if (query.tags) {
for (var tag_key in query.tags) { for (const tag_key in query.tags) {
query.tags[tag_key] = this.templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe'); query.tags[tag_key] = this.templateSrv.replace(query.tags[tag_key], options.scopedVars, 'pipe');
} }
} }

@ -161,7 +161,7 @@ export class OpenTsQueryCtrl extends QueryCtrl {
this.errors = this.validateTarget(); this.errors = this.validateTarget();
if (!this.errors.filters) { if (!this.errors.filters) {
var currentFilter = { const currentFilter = {
type: this.target.currentFilterType, type: this.target.currentFilterType,
tagk: this.target.currentFilterKey, tagk: this.target.currentFilterKey,
filter: this.target.currentFilterValue, filter: this.target.currentFilterValue,
@ -198,7 +198,7 @@ export class OpenTsQueryCtrl extends QueryCtrl {
} }
validateTarget() { validateTarget() {
var errs: any = {}; const errs: any = {};
if (this.target.shouldDownsample) { if (this.target.shouldDownsample) {
try { try {

@ -26,14 +26,14 @@ export class PostgresDatasource {
return value; return value;
} }
var quotedValues = _.map(value, function(val) { const quotedValues = _.map(value, function(val) {
return "'" + val.replace(/'/g, `''`) + "'"; return "'" + val.replace(/'/g, `''`) + "'";
}); });
return quotedValues.join(','); return quotedValues.join(',');
} }
query(options) { query(options) {
var queries = _.filter(options.targets, item => { const queries = _.filter(options.targets, item => {
return item.hide !== true; return item.hide !== true;
}).map(item => { }).map(item => {
return { return {
@ -103,7 +103,7 @@ export class PostgresDatasource {
format: 'table', format: 'table',
}; };
var data = { const data = {
queries: [interpolatedQuery], queries: [interpolatedQuery],
}; };

@ -4,7 +4,7 @@ export default class ResponseParser {
constructor(private $q) {} constructor(private $q) {}
processQueryResult(res) { processQueryResult(res) {
var data = []; const data = [];
if (!res.data.results) { if (!res.data.results) {
return { data: data }; return { data: data };

@ -50,7 +50,7 @@ export class PromCompleter {
} }
if (token.type === 'paren.lparen' && token.value === '[') { if (token.type === 'paren.lparen' && token.value === '[') {
var vectors = []; const vectors = [];
for (const unit of ['s', 'm', 'h']) { for (const unit of ['s', 'm', 'h']) {
for (const value of [1, 5, 10, 30]) { for (const value of [1, 5, 10, 30]) {
vectors.push({ vectors.push({
@ -77,7 +77,7 @@ export class PromCompleter {
return; return;
} }
var query = prefix; const query = prefix;
return this.datasource.performSuggestQuery(query, true).then(metricNames => { return this.datasource.performSuggestQuery(query, true).then(metricNames => {
wrappedCallback( wrappedCallback(
@ -109,7 +109,7 @@ export class PromCompleter {
} }
return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => { return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => {
var labelNames = this.transformToCompletions( const labelNames = this.transformToCompletions(
_.uniq( _.uniq(
_.flatten( _.flatten(
result.map(r => { result.map(r => {
@ -130,7 +130,7 @@ export class PromCompleter {
return Promise.resolve([]); return Promise.resolve([]);
} }
var labelNameToken = this.findToken( const labelNameToken = this.findToken(
session, session,
pos.row, pos.row,
pos.column, pos.column,
@ -141,14 +141,14 @@ export class PromCompleter {
if (!labelNameToken) { if (!labelNameToken) {
return Promise.resolve([]); return Promise.resolve([]);
} }
var labelName = labelNameToken.value; const labelName = labelNameToken.value;
if (this.labelValueCache[metricName] && this.labelValueCache[metricName][labelName]) { if (this.labelValueCache[metricName] && this.labelValueCache[metricName][labelName]) {
return Promise.resolve(this.labelValueCache[metricName][labelName]); return Promise.resolve(this.labelValueCache[metricName][labelName]);
} }
return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => { return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => {
var labelValues = this.transformToCompletions( const labelValues = this.transformToCompletions(
_.uniq( _.uniq(
result.map(r => { result.map(r => {
return r.metric[labelName]; return r.metric[labelName];
@ -187,7 +187,7 @@ export class PromCompleter {
return Promise.resolve([]); return Promise.resolve([]);
} }
return this.getLabelNameAndValueForExpression(expr, 'expression').then(result => { return this.getLabelNameAndValueForExpression(expr, 'expression').then(result => {
var labelNames = this.transformToCompletions( const labelNames = this.transformToCompletions(
_.uniq( _.uniq(
_.flatten( _.flatten(
result.map(r => { result.map(r => {
@ -229,7 +229,7 @@ export class PromCompleter {
return Promise.resolve([]); return Promise.resolve([]);
} }
return this.getLabelNameAndValueForExpression(expr, 'expression').then(result => { return this.getLabelNameAndValueForExpression(expr, 'expression').then(result => {
var labelNames = this.transformToCompletions( const labelNames = this.transformToCompletions(
_.uniq( _.uniq(
_.flatten( _.flatten(
result.map(r => { result.map(r => {
@ -245,7 +245,7 @@ export class PromCompleter {
} else { } else {
const metricName = this.findMetricName(session, binaryOperatorToken.row, binaryOperatorToken.column); const metricName = this.findMetricName(session, binaryOperatorToken.row, binaryOperatorToken.column);
return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => { return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => {
var labelNames = this.transformToCompletions( const labelNames = this.transformToCompletions(
_.uniq( _.uniq(
_.flatten( _.flatten(
result.map(r => { result.map(r => {
@ -297,7 +297,7 @@ export class PromCompleter {
var metricName = ''; var metricName = '';
var tokens; var tokens;
var nameLabelNameToken = this.findToken( const nameLabelNameToken = this.findToken(
session, session,
row, row,
column, column,
@ -307,12 +307,12 @@ export class PromCompleter {
); );
if (nameLabelNameToken) { if (nameLabelNameToken) {
tokens = session.getTokens(nameLabelNameToken.row); tokens = session.getTokens(nameLabelNameToken.row);
var nameLabelValueToken = tokens[nameLabelNameToken.index + 2]; const nameLabelValueToken = tokens[nameLabelNameToken.index + 2];
if (nameLabelValueToken && nameLabelValueToken.type === 'string.quoted.label-matcher') { if (nameLabelValueToken && nameLabelValueToken.type === 'string.quoted.label-matcher') {
metricName = nameLabelValueToken.value.slice(1, -1); // cut begin/end quotation metricName = nameLabelValueToken.value.slice(1, -1); // cut begin/end quotation
} }
} else { } else {
var metricNameToken = this.findToken(session, row, column, 'identifier', null, null); const metricNameToken = this.findToken(session, row, column, 'identifier', null, null);
if (metricNameToken) { if (metricNameToken) {
tokens = session.getTokens(metricNameToken.row); tokens = session.getTokens(metricNameToken.row);
metricName = metricNameToken.value; metricName = metricNameToken.value;

@ -248,11 +248,11 @@ export class PrometheusDatasource {
} }
_request(url, data?, options?: any) { _request(url, data?, options?: any) {
var options: any = { options = _.defaults(options || {}, {
url: this.url + url, url: this.url + url,
method: this.httpMethod, method: this.httpMethod,
...options, });
};
if (options.method === 'GET') { if (options.method === 'GET') {
if (!_.isEmpty(data)) { if (!_.isEmpty(data)) {
options.url = options.url =
@ -300,7 +300,7 @@ export class PrometheusDatasource {
return prometheusSpecialRegexEscape(value); return prometheusSpecialRegexEscape(value);
} }
var escapedValues = _.map(value, prometheusSpecialRegexEscape); const escapedValues = _.map(value, prometheusSpecialRegexEscape);
return escapedValues.join('|'); return escapedValues.join('|');
} }
@ -309,11 +309,11 @@ export class PrometheusDatasource {
} }
query(options) { query(options) {
var start = this.getPrometheusTime(options.range.from, false); const start = this.getPrometheusTime(options.range.from, false);
var end = this.getPrometheusTime(options.range.to, true); const end = this.getPrometheusTime(options.range.to, true);
var queries = []; const queries = [];
var activeTargets = []; const activeTargets = [];
options = _.clone(options); options = _.clone(options);
@ -331,7 +331,7 @@ export class PrometheusDatasource {
return this.$q.when({ data: [] }); return this.$q.when({ data: [] });
} }
var allQueryPromise = _.map(queries, query => { const allQueryPromise = _.map(queries, query => {
if (!query.instant) { if (!query.instant) {
return this.performTimeSeriesQuery(query, query.start, query.end); return this.performTimeSeriesQuery(query, query.start, query.end);
} else { } else {
@ -382,16 +382,16 @@ export class PrometheusDatasource {
hinting: target.hinting, hinting: target.hinting,
instant: target.instant, instant: target.instant,
}; };
var range = Math.ceil(end - start); const range = Math.ceil(end - start);
var interval = kbn.interval_to_seconds(options.interval); var interval = kbn.interval_to_seconds(options.interval);
// Minimum interval ("Min step"), if specified for the query. or same as interval otherwise // Minimum interval ("Min step"), if specified for the query. or same as interval otherwise
var minInterval = kbn.interval_to_seconds( const minInterval = kbn.interval_to_seconds(
this.templateSrv.replace(target.interval, options.scopedVars) || options.interval this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
); );
var intervalFactor = target.intervalFactor || 1; const intervalFactor = target.intervalFactor || 1;
// Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
var adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor); const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
var scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() }; var scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() };
// If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
if (interval !== adjustedInterval) { if (interval !== adjustedInterval) {
@ -430,8 +430,8 @@ export class PrometheusDatasource {
throw { message: 'Invalid time range' }; throw { message: 'Invalid time range' };
} }
var url = '/api/v1/query_range'; const url = '/api/v1/query_range';
var data = { const data = {
query: query.expr, query: query.expr,
start: start, start: start,
end: end, end: end,
@ -444,8 +444,8 @@ export class PrometheusDatasource {
} }
performInstantQuery(query, time) { performInstantQuery(query, time) {
var url = '/api/v1/query'; const url = '/api/v1/query';
var data = { const data = {
query: query.expr, query: query.expr,
time: time, time: time,
}; };
@ -456,7 +456,7 @@ export class PrometheusDatasource {
} }
performSuggestQuery(query, cache = false) { performSuggestQuery(query, cache = false) {
var url = '/api/v1/label/__name__/values'; const url = '/api/v1/label/__name__/values';
if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) { if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
return this.$q.when( return this.$q.when(
@ -488,7 +488,7 @@ export class PrometheusDatasource {
...this.getRangeScopedVars(), ...this.getRangeScopedVars(),
}; };
const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr); const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
var metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv); const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
return metricFindQuery.process(); return metricFindQuery.process();
} }
@ -505,19 +505,19 @@ export class PrometheusDatasource {
} }
annotationQuery(options) { annotationQuery(options) {
var annotation = options.annotation; const annotation = options.annotation;
var expr = annotation.expr || ''; const expr = annotation.expr || '';
var tagKeys = annotation.tagKeys || ''; var tagKeys = annotation.tagKeys || '';
var titleFormat = annotation.titleFormat || ''; const titleFormat = annotation.titleFormat || '';
var textFormat = annotation.textFormat || ''; const textFormat = annotation.textFormat || '';
if (!expr) { if (!expr) {
return this.$q.when([]); return this.$q.when([]);
} }
var step = annotation.step || '60s'; const step = annotation.step || '60s';
var start = this.getPrometheusTime(options.range.from, false); const start = this.getPrometheusTime(options.range.from, false);
var end = this.getPrometheusTime(options.range.to, true); const end = this.getPrometheusTime(options.range.to, true);
// Unsetting min interval // Unsetting min interval
const queryOptions = { const queryOptions = {
...options, ...options,
@ -525,13 +525,13 @@ export class PrometheusDatasource {
}; };
const query = this.createQuery({ expr, interval: step }, queryOptions, start, end); const query = this.createQuery({ expr, interval: step }, queryOptions, start, end);
var self = this; const self = this;
return this.performTimeSeriesQuery(query, query.start, query.end).then(function(results) { return this.performTimeSeriesQuery(query, query.start, query.end).then(function(results) {
var eventList = []; const eventList = [];
tagKeys = tagKeys.split(','); tagKeys = tagKeys.split(',');
_.each(results.data.data.result, function(series) { _.each(results.data.data.result, function(series) {
var tags = _.chain(series.metric) const tags = _.chain(series.metric)
.filter(function(v, k) { .filter(function(v, k) {
return _.includes(tagKeys, k); return _.includes(tagKeys, k);
}) })
@ -539,7 +539,7 @@ export class PrometheusDatasource {
for (const value of series.values) { for (const value of series.values) {
if (value[1] === '1') { if (value[1] === '1') {
var event = { const event = {
annotation: annotation, annotation: annotation,
time: Math.floor(parseFloat(value[0])) * 1000, time: Math.floor(parseFloat(value[0])) * 1000,
title: self.resultTransformer.renderTemplate(titleFormat, series.metric), title: self.resultTransformer.renderTemplate(titleFormat, series.metric),

@ -12,11 +12,11 @@ export default class PrometheusMetricFindQuery {
} }
process() { process() {
var label_values_regex = /^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]+)\)\s*$/; const label_values_regex = /^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]+)\)\s*$/;
var metric_names_regex = /^metrics\((.+)\)\s*$/; const metric_names_regex = /^metrics\((.+)\)\s*$/;
var query_result_regex = /^query_result\((.+)\)\s*$/; const query_result_regex = /^query_result\((.+)\)\s*$/;
var label_values_query = this.query.match(label_values_regex); const label_values_query = this.query.match(label_values_regex);
if (label_values_query) { if (label_values_query) {
if (label_values_query[1]) { if (label_values_query[1]) {
return this.labelValuesQuery(label_values_query[2], label_values_query[1]); return this.labelValuesQuery(label_values_query[2], label_values_query[1]);
@ -25,12 +25,12 @@ export default class PrometheusMetricFindQuery {
} }
} }
var metric_names_query = this.query.match(metric_names_regex); const metric_names_query = this.query.match(metric_names_regex);
if (metric_names_query) { if (metric_names_query) {
return this.metricNameQuery(metric_names_query[1]); return this.metricNameQuery(metric_names_query[1]);
} }
var query_result_query = this.query.match(query_result_regex); const query_result_query = this.query.match(query_result_regex);
if (query_result_query) { if (query_result_query) {
return this.queryResultQuery(query_result_query[1]); return this.queryResultQuery(query_result_query[1]);
} }
@ -52,12 +52,12 @@ export default class PrometheusMetricFindQuery {
}); });
}); });
} else { } else {
var start = this.datasource.getPrometheusTime(this.range.from, false); const start = this.datasource.getPrometheusTime(this.range.from, false);
var end = this.datasource.getPrometheusTime(this.range.to, true); const end = this.datasource.getPrometheusTime(this.range.to, true);
url = '/api/v1/series?match[]=' + encodeURIComponent(metric) + '&start=' + start + '&end=' + end; url = '/api/v1/series?match[]=' + encodeURIComponent(metric) + '&start=' + start + '&end=' + end;
return this.datasource.metadataRequest(url).then(function(result) { return this.datasource.metadataRequest(url).then(function(result) {
var _labels = _.map(result.data.data, function(metric) { const _labels = _.map(result.data.data, function(metric) {
return metric[label] || ''; return metric[label] || '';
}).filter(function(label) { }).filter(function(label) {
return label !== ''; return label !== '';
@ -74,12 +74,12 @@ export default class PrometheusMetricFindQuery {
} }
metricNameQuery(metricFilterPattern) { metricNameQuery(metricFilterPattern) {
var url = '/api/v1/label/__name__/values'; const url = '/api/v1/label/__name__/values';
return this.datasource.metadataRequest(url).then(function(result) { return this.datasource.metadataRequest(url).then(function(result) {
return _.chain(result.data.data) return _.chain(result.data.data)
.filter(function(metricName) { .filter(function(metricName) {
var r = new RegExp(metricFilterPattern); const r = new RegExp(metricFilterPattern);
return r.test(metricName); return r.test(metricName);
}) })
.map(function(matchedMetricName) { .map(function(matchedMetricName) {
@ -93,7 +93,7 @@ export default class PrometheusMetricFindQuery {
} }
queryResultQuery(query) { queryResultQuery(query) {
var end = this.datasource.getPrometheusTime(this.range.to, true); const end = this.datasource.getPrometheusTime(this.range.to, true);
return this.datasource.performInstantQuery({ expr: query }, end).then(function(result) { return this.datasource.performInstantQuery({ expr: query }, end).then(function(result) {
return _.map(result.data.data.result, function(metricData) { return _.map(result.data.data.result, function(metricData) {
var text = metricData.metric.__name__ || ''; var text = metricData.metric.__name__ || '';
@ -115,11 +115,11 @@ export default class PrometheusMetricFindQuery {
} }
metricNameAndLabelsQuery(query) { metricNameAndLabelsQuery(query) {
var start = this.datasource.getPrometheusTime(this.range.from, false); const start = this.datasource.getPrometheusTime(this.range.from, false);
var end = this.datasource.getPrometheusTime(this.range.to, true); const end = this.datasource.getPrometheusTime(this.range.to, true);
var url = '/api/v1/series?match[]=' + encodeURIComponent(query) + '&start=' + start + '&end=' + end; const url = '/api/v1/series?match[]=' + encodeURIComponent(query) + '&start=' + start + '&end=' + end;
var self = this; const self = this;
return this.datasource.metadataRequest(url).then(function(result) { return this.datasource.metadataRequest(url).then(function(result) {
return _.map(result.data.data, metric => { return _.map(result.data.data, metric => {
return { return {

@ -21,7 +21,7 @@ class PrometheusQueryCtrl extends QueryCtrl {
constructor($scope, $injector, private templateSrv) { constructor($scope, $injector, private templateSrv) {
super($scope, $injector); super($scope, $injector);
var target = this.target; const target = this.target;
target.expr = target.expr || ''; target.expr = target.expr || '';
target.intervalFactor = target.intervalFactor || 1; target.intervalFactor = target.intervalFactor || 1;
target.format = target.format || this.getDefaultFormat(); target.format = target.format || this.getDefaultFormat();
@ -65,14 +65,14 @@ class PrometheusQueryCtrl extends QueryCtrl {
} }
updateLink() { updateLink() {
var range = this.panelCtrl.range; const range = this.panelCtrl.range;
if (!range) { if (!range) {
return; return;
} }
var rangeDiff = Math.ceil((range.to.valueOf() - range.from.valueOf()) / 1000); const rangeDiff = Math.ceil((range.to.valueOf() - range.from.valueOf()) / 1000);
var endTime = range.to.utc().format('YYYY-MM-DD HH:mm'); const endTime = range.to.utc().format('YYYY-MM-DD HH:mm');
var expr = { const expr = {
'g0.expr': this.templateSrv.replace( 'g0.expr': this.templateSrv.replace(
this.target.expr, this.target.expr,
this.panelCtrl.panel.scopedVars, this.panelCtrl.panel.scopedVars,
@ -84,7 +84,7 @@ class PrometheusQueryCtrl extends QueryCtrl {
'g0.stacked': this.panelCtrl.panel.stack ? 1 : 0, 'g0.stacked': this.panelCtrl.panel.stack ? 1 : 0,
'g0.tab': 0, 'g0.tab': 0,
}; };
var args = _.map(expr, (v, k) => { const args = _.map(expr, (v, k) => {
return k + '=' + encodeURIComponent(v); return k + '=' + encodeURIComponent(v);
}).join('&'); }).join('&');
this.linkToPrometheus = this.datasource.directUrl + '/graph?' + args; this.linkToPrometheus = this.datasource.directUrl + '/graph?' + args;

@ -32,8 +32,8 @@ export class ResultTransformer {
} }
transformMetricData(metricData, options, start, end) { transformMetricData(metricData, options, start, end) {
let dps = [], const dps = [];
metricLabel = null; let metricLabel = null;
metricLabel = this.createMetricLabel(metricData.metric, options); metricLabel = this.createMetricLabel(metricData.metric, options);
@ -72,9 +72,9 @@ export class ResultTransformer {
} }
transformMetricDataToTable(md, resultCount: number, refId: string) { transformMetricDataToTable(md, resultCount: number, refId: string) {
var table = new TableModel(); const table = new TableModel();
var i, j; var i, j;
var metricLabels = {}; const metricLabels = {};
if (md.length === 0) { if (md.length === 0) {
return table; return table;
@ -82,7 +82,7 @@ export class ResultTransformer {
// Collect all labels across all metrics // Collect all labels across all metrics
_.each(md, function(series) { _.each(md, function(series) {
for (var label in series.metric) { for (const label in series.metric) {
if (!metricLabels.hasOwnProperty(label)) { if (!metricLabels.hasOwnProperty(label)) {
metricLabels[label] = 1; metricLabels[label] = 1;
} }
@ -90,7 +90,7 @@ export class ResultTransformer {
}); });
// Sort metric labels, create columns for them and record their index // Sort metric labels, create columns for them and record their index
var sortedLabels = _.keys(metricLabels).sort(); const sortedLabels = _.keys(metricLabels).sort();
table.columns.push({ text: 'Time', type: 'time' }); table.columns.push({ text: 'Time', type: 'time' });
_.each(sortedLabels, function(label, labelIndex) { _.each(sortedLabels, function(label, labelIndex) {
metricLabels[label] = labelIndex + 1; metricLabels[label] = labelIndex + 1;
@ -106,11 +106,11 @@ export class ResultTransformer {
} }
if (series.values) { if (series.values) {
for (i = 0; i < series.values.length; i++) { for (i = 0; i < series.values.length; i++) {
var values = series.values[i]; const values = series.values[i];
var reordered: any = [values[0] * 1000]; const reordered: any = [values[0] * 1000];
if (series.metric) { if (series.metric) {
for (j = 0; j < sortedLabels.length; j++) { for (j = 0; j < sortedLabels.length; j++) {
var label = sortedLabels[j]; const label = sortedLabels[j];
if (series.metric.hasOwnProperty(label)) { if (series.metric.hasOwnProperty(label)) {
reordered.push(series.metric[label]); reordered.push(series.metric[label]);
} else { } else {
@ -128,8 +128,8 @@ export class ResultTransformer {
} }
transformInstantMetricData(md, options) { transformInstantMetricData(md, options) {
var dps = [], const dps = [];
metricLabel = null; let metricLabel = null;
metricLabel = this.createMetricLabel(md.metric, options); metricLabel = this.createMetricLabel(md.metric, options);
dps.push([parseFloat(md.value[1]), md.value[0] * 1000]); dps.push([parseFloat(md.value[1]), md.value[0] * 1000]);
return { target: metricLabel, datapoints: dps, labels: md.metric }; return { target: metricLabel, datapoints: dps, labels: md.metric };
@ -149,7 +149,7 @@ export class ResultTransformer {
} }
renderTemplate(aliasPattern, aliasData) { renderTemplate(aliasPattern, aliasData) {
var aliasRegex = /\{\{\s*(.+?)\s*\}\}/g; const aliasRegex = /\{\{\s*(.+?)\s*\}\}/g;
return aliasPattern.replace(aliasRegex, function(match, g1) { return aliasPattern.replace(aliasRegex, function(match, g1) {
if (aliasData[g1]) { if (aliasData[g1]) {
return aliasData[g1]; return aliasData[g1];
@ -159,9 +159,9 @@ export class ResultTransformer {
} }
getOriginalMetricName(labelData) { getOriginalMetricName(labelData) {
var metricName = labelData.__name__ || ''; const metricName = labelData.__name__ || '';
delete labelData.__name__; delete labelData.__name__;
var labelPart = _.map(_.toPairs(labelData), function(label) { const labelPart = _.map(_.toPairs(labelData), function(label) {
return label[0] + '="' + label[1] + '"'; return label[0] + '="' + label[1] + '"';
}).join(','); }).join(',');
return metricName + '{' + labelPart + '}'; return metricName + '{' + labelPart + '}';

@ -9,7 +9,7 @@ class TestDataDatasource {
} }
query(options) { query(options) {
var queries = _.filter(options.targets, item => { const queries = _.filter(options.targets, item => {
return item.hide !== true; return item.hide !== true;
}).map(item => { }).map(item => {
return { return {
@ -35,7 +35,7 @@ class TestDataDatasource {
queries: queries, queries: queries,
}) })
.then(res => { .then(res => {
var data = []; const data = [];
if (res.results) { if (res.results) {
_.forEach(res.results, queryRes => { _.forEach(res.results, queryRes => {

@ -54,7 +54,7 @@ class AlertListPanel extends PanelCtrl {
}); });
} }
var result = _.sortBy(alerts, a => { const result = _.sortBy(alerts, a => {
return a.name.toLowerCase(); return a.name.toLowerCase();
}); });
if (this.panel.sortOrder === 2) { if (this.panel.sortOrder === 2) {
@ -65,7 +65,7 @@ class AlertListPanel extends PanelCtrl {
} }
updateStateFilter() { updateStateFilter() {
var result = []; const result = [];
for (const key in this.stateFilter) { for (const key in this.stateFilter) {
if (this.stateFilter[key]) { if (this.stateFilter[key]) {
@ -99,7 +99,7 @@ class AlertListPanel extends PanelCtrl {
} }
getStateChanges() { getStateChanges() {
var params: any = { const params: any = {
limit: this.panel.limit, limit: this.panel.limit,
type: 'alert', type: 'alert',
newState: this.panel.stateFilter, newState: this.panel.stateFilter,
@ -127,7 +127,7 @@ class AlertListPanel extends PanelCtrl {
} }
getCurrentAlertState() { getCurrentAlertState() {
var params: any = { const params: any = {
state: this.panel.stateFilter, state: this.panel.stateFilter,
}; };

@ -66,7 +66,7 @@ class DashListCtrl extends PanelCtrl {
} }
onRefresh() { onRefresh() {
var promises = []; const promises = [];
promises.push(this.getRecentDashboards()); promises.push(this.getRecentDashboards());
promises.push(this.getStarred()); promises.push(this.getStarred());
@ -81,7 +81,7 @@ class DashListCtrl extends PanelCtrl {
return Promise.resolve(); return Promise.resolve();
} }
var params = { const params = {
limit: this.panel.limit, limit: this.panel.limit,
query: this.panel.query, query: this.panel.query,
tag: this.panel.tags, tag: this.panel.tags,
@ -100,7 +100,7 @@ class DashListCtrl extends PanelCtrl {
return Promise.resolve(); return Promise.resolve();
} }
var params = { limit: this.panel.limit, starred: 'true' }; const params = { limit: this.panel.limit, starred: 'true' };
return this.backendSrv.search(params).then(result => { return this.backendSrv.search(params).then(result => {
this.groups[0].list = result; this.groups[0].list = result;
}); });
@ -123,7 +123,7 @@ class DashListCtrl extends PanelCtrl {
return Promise.resolve(); return Promise.resolve();
} }
var dashIds = _.take(impressionSrv.getDashboardOpened(), this.panel.limit); const dashIds = _.take(impressionSrv.getDashboardOpened(), this.panel.limit);
return this.backendSrv.search({ dashboardIds: dashIds, limit: this.panel.limit }).then(result => { return this.backendSrv.search({ dashboardIds: dashIds, limit: this.panel.limit }).then(result => {
this.groups[1].list = dashIds this.groups[1].list = dashIds
.map(orderId => { .map(orderId => {

@ -88,7 +88,7 @@ class GettingStartedPanelCtrl extends PanelCtrl {
} }
this.stepIndex += 1; this.stepIndex += 1;
var currentStep = this.steps[this.stepIndex]; const currentStep = this.steps[this.stepIndex];
return currentStep.check().then(passed => { return currentStep.check().then(passed => {
if (passed) { if (passed) {
currentStep.cssClass = 'completed'; currentStep.cssClass = 'completed';

@ -10,15 +10,15 @@ export function alignYLevel(yAxes, level) {
return; return;
} }
var [yLeft, yRight] = yAxes; const [yLeft, yRight] = yAxes;
moveLevelToZero(yLeft, yRight, level); moveLevelToZero(yLeft, yRight, level);
expandStuckValues(yLeft, yRight); expandStuckValues(yLeft, yRight);
// one of graphs on zero // one of graphs on zero
var zero = yLeft.min === 0 || yRight.min === 0 || yLeft.max === 0 || yRight.max === 0; const zero = yLeft.min === 0 || yRight.min === 0 || yLeft.max === 0 || yRight.max === 0;
var oneSide = checkOneSide(yLeft, yRight); const oneSide = checkOneSide(yLeft, yRight);
if (zero && oneSide) { if (zero && oneSide) {
yLeft.min = yLeft.max > 0 ? 0 : yLeft.min; yLeft.min = yLeft.max > 0 ? 0 : yLeft.min;
@ -35,7 +35,7 @@ export function alignYLevel(yAxes, level) {
yRight.min = -yRight.max; yRight.min = -yRight.max;
} }
} else { } else {
var rate = getRate(yLeft, yRight); const rate = getRate(yLeft, yRight);
if (oneSide) { if (oneSide) {
// all graphs above the Y level // all graphs above the Y level
@ -67,7 +67,7 @@ export function alignYLevel(yAxes, level) {
function expandStuckValues(yLeft, yRight) { function expandStuckValues(yLeft, yRight) {
// wide Y min and max using increased wideFactor // wide Y min and max using increased wideFactor
var wideFactor = 0.25; const wideFactor = 0.25;
if (yLeft.max === yLeft.min) { if (yLeft.max === yLeft.min) {
yLeft.min -= wideFactor; yLeft.min -= wideFactor;
yLeft.max += wideFactor; yLeft.max += wideFactor;
@ -126,14 +126,14 @@ function getRate(yLeft, yRight) {
rateRight = yRight.max ? yLeft.max / yRight.max : 0; rateRight = yRight.max ? yLeft.max / yRight.max : 0;
} else { } else {
if (checkOneSide(yLeft, yRight)) { if (checkOneSide(yLeft, yRight)) {
var absLeftMin = Math.abs(yLeft.min); const absLeftMin = Math.abs(yLeft.min);
var absLeftMax = Math.abs(yLeft.max); const absLeftMax = Math.abs(yLeft.max);
var absRightMin = Math.abs(yRight.min); const absRightMin = Math.abs(yRight.min);
var absRightMax = Math.abs(yRight.max); const absRightMax = Math.abs(yRight.max);
var upLeft = _.max([absLeftMin, absLeftMax]); const upLeft = _.max([absLeftMin, absLeftMax]);
var downLeft = _.min([absLeftMin, absLeftMax]); const downLeft = _.min([absLeftMin, absLeftMax]);
var upRight = _.max([absRightMin, absRightMax]); const upRight = _.max([absRightMin, absRightMax]);
var downRight = _.min([absRightMin, absRightMax]); const downRight = _.min([absRightMin, absRightMax]);
rateLeft = downLeft ? upLeft / downLeft : upLeft; rateLeft = downLeft ? upLeft / downLeft : upLeft;
rateRight = downRight ? upRight / downRight : upRight; rateRight = downRight ? upRight / downRight : upRight;

@ -67,8 +67,8 @@ export class AxesEditorCtrl {
} }
getDataFieldNames(onlyNumbers) { getDataFieldNames(onlyNumbers) {
var props = this.panelCtrl.processor.getDataFieldNames(this.panelCtrl.dataList, onlyNumbers); const props = this.panelCtrl.processor.getDataFieldNames(this.panelCtrl.dataList, onlyNumbers);
var items = props.map(prop => { const items = props.map(prop => {
return { text: prop, value: prop }; return { text: prop, value: prop };
}); });

@ -102,13 +102,13 @@ export class DataProcessor {
} }
timeSeriesHandler(seriesData, index, options) { timeSeriesHandler(seriesData, index, options) {
var datapoints = seriesData.datapoints || []; const datapoints = seriesData.datapoints || [];
var alias = seriesData.target; const alias = seriesData.target;
var colorIndex = index % colors.length; const colorIndex = index % colors.length;
var color = this.panel.aliasColors[alias] || colors[colorIndex]; const color = this.panel.aliasColors[alias] || colors[colorIndex];
var series = new TimeSeries({ const series = new TimeSeries({
datapoints: datapoints, datapoints: datapoints,
alias: alias, alias: alias,
color: color, color: color,
@ -116,8 +116,8 @@ export class DataProcessor {
}); });
if (datapoints && datapoints.length > 0) { if (datapoints && datapoints.length > 0) {
var last = datapoints[datapoints.length - 1][1]; const last = datapoints[datapoints.length - 1][1];
var from = options.range.from; const from = options.range.from;
if (last - from < -10000) { if (last - from < -10000) {
series.isOutsideRange = true; series.isOutsideRange = true;
} }
@ -144,8 +144,8 @@ export class DataProcessor {
return; return;
} }
var validOptions = this.getXAxisValueOptions({}); const validOptions = this.getXAxisValueOptions({});
var found = _.find(validOptions, { value: this.panel.xaxis.values[0] }); const found = _.find(validOptions, { value: this.panel.xaxis.values[0] });
if (!found) { if (!found) {
this.panel.xaxis.values = ['total']; this.panel.xaxis.values = ['total'];
} }
@ -160,7 +160,7 @@ export class DataProcessor {
} }
const fields = []; const fields = [];
var firstItem = dataList[0]; const firstItem = dataList[0];
const fieldParts = []; const fieldParts = [];
function getPropertiesRecursive(obj) { function getPropertiesRecursive(obj) {

@ -198,8 +198,8 @@ class GraphElement {
} }
processOffsetHook(plot, gridMargin) { processOffsetHook(plot, gridMargin) {
var left = this.panel.yaxes[0]; const left = this.panel.yaxes[0];
var right = this.panel.yaxes[1]; const right = this.panel.yaxes[1];
if (left.show && left.label) { if (left.show && left.label) {
gridMargin.left = 20; gridMargin.left = 20;
} }
@ -208,17 +208,17 @@ class GraphElement {
} }
// apply y-axis min/max options // apply y-axis min/max options
var yaxis = plot.getYAxes(); const yaxis = plot.getYAxes();
for (var i = 0; i < yaxis.length; i++) { for (var i = 0; i < yaxis.length; i++) {
var axis = yaxis[i]; const axis = yaxis[i];
var panelOptions = this.panel.yaxes[i]; const panelOptions = this.panel.yaxes[i];
axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max; axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min; axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
} }
} }
processRangeHook(plot) { processRangeHook(plot) {
var yAxes = plot.getYAxes(); const yAxes = plot.getYAxes();
const align = this.panel.yaxis.align || false; const align = this.panel.yaxis.align || false;
if (yAxes.length > 1 && align === true) { if (yAxes.length > 1 && align === true) {
@ -424,12 +424,12 @@ class GraphElement {
} }
sortSeries(series, panel) { sortSeries(series, panel) {
var sortBy = panel.legend.sort; const sortBy = panel.legend.sort;
var sortOrder = panel.legend.sortDesc; const sortOrder = panel.legend.sortDesc;
var haveSortBy = sortBy !== null && sortBy !== undefined; const haveSortBy = sortBy !== null && sortBy !== undefined;
var haveSortOrder = sortOrder !== null && sortOrder !== undefined; const haveSortOrder = sortOrder !== null && sortOrder !== undefined;
var shouldSortBy = panel.stack && haveSortBy && haveSortOrder; const shouldSortBy = panel.stack && haveSortBy && haveSortOrder;
var sortDesc = panel.legend.sortDesc === true ? -1 : 1; const sortDesc = panel.legend.sortDesc === true ? -1 : 1;
if (shouldSortBy) { if (shouldSortBy) {
return _.sortBy(series, s => s.stats[sortBy] * sortDesc); return _.sortBy(series, s => s.stats[sortBy] * sortDesc);
@ -447,9 +447,9 @@ class GraphElement {
} }
addTimeAxis(options) { addTimeAxis(options) {
var ticks = this.panelWidth / 100; const ticks = this.panelWidth / 100;
var min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf(); const min = _.isUndefined(this.ctrl.range.from) ? null : this.ctrl.range.from.valueOf();
var max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf(); const max = _.isUndefined(this.ctrl.range.to) ? null : this.ctrl.range.to.valueOf();
options.xaxis = { options.xaxis = {
timezone: this.dashboard.getTimezone(), timezone: this.dashboard.getTimezone(),
@ -464,7 +464,7 @@ class GraphElement {
} }
addXSeriesAxis(options) { addXSeriesAxis(options) {
var ticks = _.map(this.data, function(series, index) { const ticks = _.map(this.data, function(series, index) {
return [index + 1, series.alias]; return [index + 1, series.alias];
}); });
@ -535,7 +535,7 @@ class GraphElement {
addXTableAxis(options) { addXTableAxis(options) {
var ticks = _.map(this.data, function(series, seriesIndex) { var ticks = _.map(this.data, function(series, seriesIndex) {
return _.map(series.datapoints, function(point, pointIndex) { return _.map(series.datapoints, function(point, pointIndex) {
var tickIndex = seriesIndex * series.datapoints.length + pointIndex; const tickIndex = seriesIndex * series.datapoints.length + pointIndex;
return [tickIndex + 1, point[1]]; return [tickIndex + 1, point[1]];
}); });
}); });
@ -553,7 +553,7 @@ class GraphElement {
} }
configureYAxisOptions(data, options) { configureYAxisOptions(data, options) {
var defaults = { const defaults = {
position: 'left', position: 'left',
show: this.panel.yaxes[0].show, show: this.panel.yaxes[0].show,
index: 1, index: 1,
@ -566,7 +566,7 @@ class GraphElement {
options.yaxes.push(defaults); options.yaxes.push(defaults);
if (_.find(data, { yaxis: 2 })) { if (_.find(data, { yaxis: 2 })) {
var secondY = _.clone(defaults); const secondY = _.clone(defaults);
secondY.index = 2; secondY.index = 2;
secondY.show = this.panel.yaxes[1].show; secondY.show = this.panel.yaxes[1].show;
secondY.logBase = this.panel.yaxes[1].logBase || 1; secondY.logBase = this.panel.yaxes[1].logBase || 1;
@ -711,10 +711,10 @@ class GraphElement {
time_format(ticks, min, max) { time_format(ticks, min, max) {
if (min && max && ticks) { if (min && max && ticks) {
var range = max - min; const range = max - min;
var secPerTick = range / ticks / 1000; const secPerTick = range / ticks / 1000;
var oneDay = 86400000; const oneDay = 86400000;
var oneYear = 31536000000; const oneYear = 31536000000;
if (secPerTick <= 45) { if (secPerTick <= 45) {
return '%H:%M:%S'; return '%H:%M:%S';

@ -290,9 +290,9 @@ export class EventMarkers {
* update the position of the event-markers (e.g. after scrolling or zooming) * update the position of the event-markers (e.g. after scrolling or zooming)
*/ */
updateEvents() { updateEvents() {
let o = this._plot.getPlotOffset(), const o = this._plot.getPlotOffset();
left, let left;
top; let top;
const xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; const xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1];
$.each(this._events, (index, event) => { $.each(this._events, (index, event) => {

@ -3,14 +3,14 @@ import _ from 'lodash';
import $ from 'jquery'; import $ from 'jquery';
import baron from 'baron'; import baron from 'baron';
var module = angular.module('grafana.directives'); const module = angular.module('grafana.directives');
module.directive('graphLegend', function(popoverSrv, $timeout) { module.directive('graphLegend', function(popoverSrv, $timeout) {
return { return {
link: function(scope, elem) { link: function(scope, elem) {
var firstRender = true; var firstRender = true;
var ctrl = scope.ctrl; const ctrl = scope.ctrl;
var panel = ctrl.panel; const panel = ctrl.panel;
var data; var data;
var seriesList; var seriesList;
var i; var i;
@ -40,9 +40,9 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
return; return;
} }
var el = $(e.currentTarget).find('.fa-minus'); const el = $(e.currentTarget).find('.fa-minus');
var index = getSeriesIndexForElement(el); const index = getSeriesIndexForElement(el);
var series = seriesList[index]; const series = seriesList[index];
$timeout(function() { $timeout(function() {
popoverSrv.show({ popoverSrv.show({
@ -67,17 +67,17 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
} }
function toggleSeries(e) { function toggleSeries(e) {
var el = $(e.currentTarget); const el = $(e.currentTarget);
var index = getSeriesIndexForElement(el); const index = getSeriesIndexForElement(el);
var seriesInfo = seriesList[index]; const seriesInfo = seriesList[index];
const scrollPosition = legendScrollbar.scroller.scrollTop; const scrollPosition = legendScrollbar.scroller.scrollTop;
ctrl.toggleSeries(seriesInfo, e); ctrl.toggleSeries(seriesInfo, e);
legendScrollbar.scroller.scrollTop = scrollPosition; legendScrollbar.scroller.scrollTop = scrollPosition;
} }
function sortLegend(e) { function sortLegend(e) {
var el = $(e.currentTarget); const el = $(e.currentTarget);
var stat = el.data('stat'); const stat = el.data('stat');
if (stat !== panel.legend.sort) { if (stat !== panel.legend.sort) {
panel.legend.sortDesc = null; panel.legend.sortDesc = null;
@ -103,7 +103,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
var html = '<th class="pointer" data-stat="' + statName + '">' + statName; var html = '<th class="pointer" data-stat="' + statName + '">' + statName;
if (panel.legend.sort === statName) { if (panel.legend.sort === statName) {
var cssClass = panel.legend.sortDesc ? 'fa fa-caret-down' : 'fa fa-caret-up'; const cssClass = panel.legend.sortDesc ? 'fa fa-caret-down' : 'fa fa-caret-up';
html += ' <span class="' + cssClass + '"></span>'; html += ' <span class="' + cssClass + '"></span>';
} }
@ -131,8 +131,8 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
// Set min-width if side style and there is a value, otherwise remove the CSS property // Set min-width if side style and there is a value, otherwise remove the CSS property
// Set width so it works with IE11 // Set width so it works with IE11
var width: any = panel.legend.rightSide && panel.legend.sideWidth ? panel.legend.sideWidth + 'px' : ''; const width: any = panel.legend.rightSide && panel.legend.sideWidth ? panel.legend.sideWidth + 'px' : '';
var ieWidth: any = panel.legend.rightSide && panel.legend.sideWidth ? panel.legend.sideWidth - 1 + 'px' : ''; const ieWidth: any = panel.legend.rightSide && panel.legend.sideWidth ? panel.legend.sideWidth - 1 + 'px' : '';
legendElem.css('min-width', width); legendElem.css('min-width', width);
legendElem.css('width', ieWidth); legendElem.css('width', ieWidth);
@ -178,7 +178,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
function renderSeriesLegendElements() { function renderSeriesLegendElements() {
const seriesElements = []; const seriesElements = [];
for (i = 0; i < seriesList.length; i++) { for (i = 0; i < seriesList.length; i++) {
var series = seriesList[i]; const series = seriesList[i];
if (series.hideFromLegend(panel.legend)) { if (series.hideFromLegend(panel.legend)) {
continue; continue;
@ -201,11 +201,11 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
'<a class="graph-legend-alias pointer" title="' + series.aliasEscaped + '">' + series.aliasEscaped + '</a>'; '<a class="graph-legend-alias pointer" title="' + series.aliasEscaped + '">' + series.aliasEscaped + '</a>';
if (panel.legend.values) { if (panel.legend.values) {
var avg = series.formatValue(series.stats.avg); const avg = series.formatValue(series.stats.avg);
var current = series.formatValue(series.stats.current); const current = series.formatValue(series.stats.current);
var min = series.formatValue(series.stats.min); const min = series.formatValue(series.stats.min);
var max = series.formatValue(series.stats.max); const max = series.formatValue(series.stats.max);
var total = series.formatValue(series.stats.total); const total = series.formatValue(series.stats.total);
if (panel.legend.min) { if (panel.legend.min) {
html += '<div class="graph-legend-value min">' + min + '</div>'; html += '<div class="graph-legend-value min">' + min + '</div>';
@ -233,10 +233,10 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
function renderLegendElement(tableHeaderElem) { function renderLegendElement(tableHeaderElem) {
const legendWidth = elem.width(); const legendWidth = elem.width();
var seriesElements = renderSeriesLegendElements(); const seriesElements = renderSeriesLegendElements();
if (panel.legend.alignAsTable) { if (panel.legend.alignAsTable) {
var tbodyElem = $('<tbody></tbody>'); const tbodyElem = $('<tbody></tbody>');
tbodyElem.append(tableHeaderElem); tbodyElem.append(tableHeaderElem);
tbodyElem.append(seriesElements); tbodyElem.append(seriesElements);
elem.append(tbodyElem); elem.append(tbodyElem);

@ -255,14 +255,14 @@ class GraphCtrl extends MetricsPanelCtrl {
} }
toggleSeriesExclusiveMode(serie) { toggleSeriesExclusiveMode(serie) {
var hidden = this.hiddenSeries; const hidden = this.hiddenSeries;
if (hidden[serie.alias]) { if (hidden[serie.alias]) {
delete hidden[serie.alias]; delete hidden[serie.alias];
} }
// check if every other series is hidden // check if every other series is hidden
var alreadyExclusive = _.every(this.seriesList, value => { const alreadyExclusive = _.every(this.seriesList, value => {
if (value.alias === serie.alias) { if (value.alias === serie.alias) {
return true; return true;
} }
@ -312,13 +312,13 @@ class GraphCtrl extends MetricsPanelCtrl {
} }
legendValuesOptionChanged() { legendValuesOptionChanged() {
var legend = this.panel.legend; const legend = this.panel.legend;
legend.values = legend.min || legend.max || legend.avg || legend.current || legend.total; legend.values = legend.min || legend.max || legend.avg || legend.current || legend.total;
this.render(); this.render();
} }
exportCsv() { exportCsv() {
var scope = this.$scope.$new(true); const scope = this.$scope.$new(true);
scope.seriesList = this.seriesList; scope.seriesList = this.seriesList;
this.publishAppEvent('show-modal', { this.publishAppEvent('show-modal', {
templateHtml: '<export-data-modal data="seriesList"></export-data-modal>', templateHtml: '<export-data-modal data="seriesList"></export-data-modal>',

@ -8,7 +8,7 @@ export function SeriesOverridesCtrl($scope, $element, popoverSrv) {
$scope.override = $scope.override || {}; $scope.override = $scope.override || {};
$scope.addOverrideOption = function(name, propertyName, values) { $scope.addOverrideOption = function(name, propertyName, values) {
var option = { const option = {
text: name, text: name,
propertyName: propertyName, propertyName: propertyName,
index: $scope.overrideMenu.lenght, index: $scope.overrideMenu.lenght,
@ -48,7 +48,7 @@ export function SeriesOverridesCtrl($scope, $element, popoverSrv) {
}; };
$scope.openColorSelector = function(color) { $scope.openColorSelector = function(color) {
var fakeSeries = { color: color }; const fakeSeries = { color: color };
popoverSrv.show({ popoverSrv.show({
element: $element.find('.dropdown')[0], element: $element.find('.dropdown')[0],
position: 'top center', position: 'top center',
@ -80,7 +80,7 @@ export function SeriesOverridesCtrl($scope, $element, popoverSrv) {
$scope.updateCurrentOverrides = function() { $scope.updateCurrentOverrides = function() {
$scope.currentOverrides = []; $scope.currentOverrides = [];
_.each($scope.overrideMenu, function(option) { _.each($scope.overrideMenu, function(option) {
var value = $scope.override[option.propertyName]; const value = $scope.override[option.propertyName];
if (_.isUndefined(value)) { if (_.isUndefined(value)) {
return; return;
} }

@ -1,4 +1,4 @@
var template = ` const template = `
<div class="graph-panel" ng-class="{'graph-panel--legend-right': ctrl.panel.legend.rightSide}"> <div class="graph-panel" ng-class="{'graph-panel--legend-right': ctrl.panel.legend.rightSide}">
<div class="graph-panel__chart" grafana-graph ng-dblclick="ctrl.zoomOut()"> <div class="graph-panel__chart" grafana-graph ng-dblclick="ctrl.zoomOut()">
</div> </div>

@ -30,20 +30,20 @@ export class ThresholdManager {
} }
initDragging(evt) { initDragging(evt) {
var handleElem = $(evt.currentTarget).parents('.alert-handle-wrapper'); const handleElem = $(evt.currentTarget).parents('.alert-handle-wrapper');
var handleIndex = $(evt.currentTarget).data('handleIndex'); const handleIndex = $(evt.currentTarget).data('handleIndex');
var lastY = null; var lastY = null;
var posTop; var posTop;
var plot = this.plot; const plot = this.plot;
var panelCtrl = this.panelCtrl; const panelCtrl = this.panelCtrl;
var model = this.thresholds[handleIndex]; const model = this.thresholds[handleIndex];
function dragging(evt) { function dragging(evt) {
if (lastY === null) { if (lastY === null) {
lastY = evt.clientY; lastY = evt.clientY;
} else { } else {
var diff = evt.clientY - lastY; const diff = evt.clientY - lastY;
posTop = posTop + diff; posTop = posTop + diff;
lastY = evt.clientY; lastY = evt.clientY;
handleElem.css({ top: posTop + diff }); handleElem.css({ top: posTop + diff });
@ -84,8 +84,8 @@ export class ThresholdManager {
} }
renderHandle(handleIndex, defaultHandleTopPos) { renderHandle(handleIndex, defaultHandleTopPos) {
var model = this.thresholds[handleIndex]; const model = this.thresholds[handleIndex];
var value = model.value; const value = model.value;
var valueStr = value; var valueStr = value;
var handleTopPos = 0; var handleTopPos = 0;
@ -94,11 +94,11 @@ export class ThresholdManager {
valueStr = ''; valueStr = '';
handleTopPos = defaultHandleTopPos; handleTopPos = defaultHandleTopPos;
} else { } else {
var valueCanvasPos = this.plot.p2c({ x: 0, y: value }); const valueCanvasPos = this.plot.p2c({ x: 0, y: value });
handleTopPos = Math.round(Math.min(Math.max(valueCanvasPos.top, 0), this.height) - 6); handleTopPos = Math.round(Math.min(Math.max(valueCanvasPos.top, 0), this.height) - 6);
} }
var handleElem = $(this.getHandleHtml(handleIndex, model, valueStr)); const handleElem = $(this.getHandleHtml(handleIndex, model, valueStr));
this.placeholder.append(handleElem); this.placeholder.append(handleElem);
handleElem.toggleClass('alert-handle-wrapper--no-value', valueStr === ''); handleElem.toggleClass('alert-handle-wrapper--no-value', valueStr === '');
@ -119,7 +119,7 @@ export class ThresholdManager {
} }
if (this.shouldDrawHandles()) { if (this.shouldDrawHandles()) {
var thresholdMargin = this.panelCtrl.panel.thresholds.length > 1 ? '220px' : '110px'; const thresholdMargin = this.panelCtrl.panel.thresholds.length > 1 ? '220px' : '110px';
elem.css('margin-right', thresholdMargin); elem.css('margin-right', thresholdMargin);
} else if (this.needsCleanup) { } else if (this.needsCleanup) {
elem.css('margin-right', '0'); elem.css('margin-right', '0');

@ -13,7 +13,7 @@ export class ThresholdFormCtrl {
this.disabled = true; this.disabled = true;
} }
var unbindDestroy = $scope.$on('$destroy', () => { const unbindDestroy = $scope.$on('$destroy', () => {
this.panelCtrl.editingThresholds = false; this.panelCtrl.editingThresholds = false;
this.panelCtrl.render(); this.panelCtrl.render();
unbindDestroy(); unbindDestroy();
@ -58,7 +58,7 @@ export class ThresholdFormCtrl {
} }
} }
var template = ` const template = `
<div class="gf-form-group"> <div class="gf-form-group">
<h5>Thresholds</h5> <h5>Thresholds</h5>
<p class="muted" ng-show="ctrl.disabled"> <p class="muted" ng-show="ctrl.disabled">

@ -200,7 +200,7 @@ function drawSimpleColorLegend(elem, colorScale) {
const valuesRange = d3.range(0, legendWidth, rangeStep); const valuesRange = d3.range(0, legendWidth, rangeStep);
const legend = d3.select(legendElem.get(0)); const legend = d3.select(legendElem.get(0));
var legendRects = legend.selectAll('.heatmap-color-legend-rect').data(valuesRange); const legendRects = legend.selectAll('.heatmap-color-legend-rect').data(valuesRange);
legendRects legendRects
.enter() .enter()
@ -239,7 +239,7 @@ function drawSimpleOpacityLegend(elem, options) {
const rangeStep = 10; const rangeStep = 10;
const valuesRange = d3.range(0, legendWidth, rangeStep); const valuesRange = d3.range(0, legendWidth, rangeStep);
var legendRects = legend.selectAll('.heatmap-opacity-legend-rect').data(valuesRange); const legendRects = legend.selectAll('.heatmap-opacity-legend-rect').data(valuesRange);
legendRects legendRects
.enter() .enter()

@ -44,7 +44,7 @@ class PluginListCtrl extends PanelCtrl {
$event.stopPropagation(); $event.stopPropagation();
$event.preventDefault(); $event.preventDefault();
var modalScope = this.$scope.$new(true); const modalScope = this.$scope.$new(true);
modalScope.plugin = plugin; modalScope.plugin = plugin;
this.publishAppEvent('show-modal', { this.publishAppEvent('show-modal', {

@ -122,7 +122,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
seriesHandler(seriesData) { seriesHandler(seriesData) {
var series = new TimeSeries({ const series = new TimeSeries({
datapoints: seriesData.datapoints || [], datapoints: seriesData.datapoints || [],
alias: seriesData.target, alias: seriesData.target,
}); });
@ -214,7 +214,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
invertColorOrder() { invertColorOrder() {
var tmp = this.panel.colors[0]; const tmp = this.panel.colors[0];
this.panel.colors[0] = this.panel.colors[2]; this.panel.colors[0] = this.panel.colors[2];
this.panel.colors[2] = tmp; this.panel.colors[2] = tmp;
this.render(); this.render();
@ -242,12 +242,12 @@ class SingleStatCtrl extends MetricsPanelCtrl {
return { decimals: this.panel.decimals, scaledDecimals: null }; return { decimals: this.panel.decimals, scaledDecimals: null };
} }
var delta = value / 2; const delta = value / 2;
var dec = -Math.floor(Math.log(delta) / Math.LN10); var dec = -Math.floor(Math.log(delta) / Math.LN10);
var magn = Math.pow(10, -dec), const magn = Math.pow(10, -dec);
norm = delta / magn, // norm is between 1.0 and 10.0 const norm = delta / magn; // norm is between 1.0 and 10.0
size; let size;
if (norm < 1.5) { if (norm < 1.5) {
size = 1; size = 1;
@ -271,7 +271,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
dec = 0; dec = 0;
} }
var result: any = {}; const result: any = {};
result.decimals = Math.max(0, dec); result.decimals = Math.max(0, dec);
result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2; result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2;
@ -282,7 +282,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
data.flotpairs = []; data.flotpairs = [];
if (this.series.length > 1) { if (this.series.length > 1) {
var error: any = new Error(); const error: any = new Error();
error.message = 'Multiple Series Error'; error.message = 'Multiple Series Error';
error.data = error.data =
'Metric query returns ' + 'Metric query returns ' +
@ -341,7 +341,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
// value/number to text mapping // value/number to text mapping
var value = parseFloat(map.value); const value = parseFloat(map.value);
if (value === data.valueRounded) { if (value === data.valueRounded) {
data.valueFormatted = map.text; data.valueFormatted = map.text;
return; return;
@ -360,8 +360,8 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
// value/number to range mapping // value/number to range mapping
var from = parseFloat(map.from); const from = parseFloat(map.from);
var to = parseFloat(map.to); const to = parseFloat(map.to);
if (to >= data.valueRounded && from <= data.valueRounded) { if (to >= data.valueRounded && from <= data.valueRounded) {
data.valueFormatted = map.text; data.valueFormatted = map.text;
return; return;
@ -375,7 +375,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
removeValueMap(map) { removeValueMap(map) {
var index = _.indexOf(this.panel.valueMaps, map); const index = _.indexOf(this.panel.valueMaps, map);
this.panel.valueMaps.splice(index, 1); this.panel.valueMaps.splice(index, 1);
this.render(); this.render();
} }
@ -385,7 +385,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
removeRangeMap(rangeMap) { removeRangeMap(rangeMap) {
var index = _.indexOf(this.panel.rangeMaps, rangeMap); const index = _.indexOf(this.panel.rangeMaps, rangeMap);
this.panel.rangeMaps.splice(index, 1); this.panel.rangeMaps.splice(index, 1);
this.render(); this.render();
} }
@ -395,17 +395,17 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
link(scope, elem, attrs, ctrl) { link(scope, elem, attrs, ctrl) {
var $location = this.$location; const $location = this.$location;
var linkSrv = this.linkSrv; const linkSrv = this.linkSrv;
var $timeout = this.$timeout; const $timeout = this.$timeout;
var panel = ctrl.panel; const panel = ctrl.panel;
var templateSrv = this.templateSrv; const templateSrv = this.templateSrv;
var data, linkInfo; var data, linkInfo;
var $panelContainer = elem.find('.panel-container'); const $panelContainer = elem.find('.panel-container');
elem = elem.find('.singlestat-panel'); elem = elem.find('.singlestat-panel');
function applyColoringThresholds(value, valueString) { function applyColoringThresholds(value, valueString) {
var color = getColorForValue(data, value); const color = getColorForValue(data, value);
if (color) { if (color) {
return '<span style="color:' + color + '">' + valueString + '</span>'; return '<span style="color:' + color + '">' + valueString + '</span>';
} }
@ -457,10 +457,10 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
function addGauge() { function addGauge() {
var width = elem.width(); const width = elem.width();
var height = elem.height(); const height = elem.height();
// Allow to use a bit more space for wide gauges // Allow to use a bit more space for wide gauges
var dimension = Math.min(width, height * 1.3); const dimension = Math.min(width, height * 1.3);
ctrl.invalidGaugeRange = false; ctrl.invalidGaugeRange = false;
if (panel.gauge.minValue > panel.gauge.maxValue) { if (panel.gauge.minValue > panel.gauge.maxValue) {
@ -468,8 +468,8 @@ class SingleStatCtrl extends MetricsPanelCtrl {
return; return;
} }
var plotCanvas = $('<div></div>'); const plotCanvas = $('<div></div>');
var plotCss = { const plotCss = {
top: '10px', top: '10px',
margin: 'auto', margin: 'auto',
position: 'relative', position: 'relative',
@ -479,7 +479,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
plotCanvas.css(plotCss); plotCanvas.css(plotCss);
var thresholds = []; const thresholds = [];
for (var i = 0; i < data.thresholds.length; i++) { for (var i = 0; i < data.thresholds.length; i++) {
thresholds.push({ thresholds.push({
value: data.thresholds[i], value: data.thresholds[i],
@ -491,17 +491,17 @@ class SingleStatCtrl extends MetricsPanelCtrl {
color: data.colorMap[data.colorMap.length - 1], color: data.colorMap[data.colorMap.length - 1],
}); });
var bgColor = config.bootData.user.lightTheme ? 'rgb(230,230,230)' : 'rgb(38,38,38)'; const bgColor = config.bootData.user.lightTheme ? 'rgb(230,230,230)' : 'rgb(38,38,38)';
var fontScale = parseInt(panel.valueFontSize) / 100; const fontScale = parseInt(panel.valueFontSize) / 100;
var fontSize = Math.min(dimension / 5, 100) * fontScale; const fontSize = Math.min(dimension / 5, 100) * fontScale;
// Reduce gauge width if threshold labels enabled // Reduce gauge width if threshold labels enabled
var gaugeWidthReduceRatio = panel.gauge.thresholdLabels ? 1.5 : 1; const gaugeWidthReduceRatio = panel.gauge.thresholdLabels ? 1.5 : 1;
var gaugeWidth = Math.min(dimension / 6, 60) / gaugeWidthReduceRatio; const gaugeWidth = Math.min(dimension / 6, 60) / gaugeWidthReduceRatio;
var thresholdMarkersWidth = gaugeWidth / 5; const thresholdMarkersWidth = gaugeWidth / 5;
var thresholdLabelFontSize = fontSize / 2.5; const thresholdLabelFontSize = fontSize / 2.5;
var options = { const options = {
series: { series: {
gauges: { gauges: {
gauge: { gauge: {
@ -543,7 +543,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
elem.append(plotCanvas); elem.append(plotCanvas);
var plotSeries = { const plotSeries = {
data: [[0, data.valueRounded]], data: [[0, data.valueRounded]],
}; };
@ -551,7 +551,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
} }
function addSparkline() { function addSparkline() {
var width = elem.width() + 20; const width = elem.width() + 20;
if (width < 30) { if (width < 30) {
// element has not gotten it's width yet // element has not gotten it's width yet
// delay sparkline render // delay sparkline render
@ -559,16 +559,16 @@ class SingleStatCtrl extends MetricsPanelCtrl {
return; return;
} }
var height = ctrl.height; const height = ctrl.height;
var plotCanvas = $('<div></div>'); const plotCanvas = $('<div></div>');
var plotCss: any = {}; const plotCss: any = {};
plotCss.position = 'absolute'; plotCss.position = 'absolute';
if (panel.sparkline.full) { if (panel.sparkline.full) {
plotCss.bottom = '5px'; plotCss.bottom = '5px';
plotCss.left = '-5px'; plotCss.left = '-5px';
plotCss.width = width - 10 + 'px'; plotCss.width = width - 10 + 'px';
var dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5; const dynamicHeightMargin = height <= 100 ? 5 : Math.round(height / 100) * 15 + 5;
plotCss.height = height - dynamicHeightMargin + 'px'; plotCss.height = height - dynamicHeightMargin + 'px';
} else { } else {
plotCss.bottom = '0px'; plotCss.bottom = '0px';
@ -579,7 +579,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
plotCanvas.css(plotCss); plotCanvas.css(plotCss);
var options = { const options = {
legend: { show: false }, legend: { show: false },
series: { series: {
lines: { lines: {
@ -602,7 +602,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
elem.append(plotCanvas); elem.append(plotCanvas);
var plotSeries = { const plotSeries = {
data: data.flotpairs, data: data.flotpairs,
color: panel.sparkline.lineColor, color: panel.sparkline.lineColor,
}; };
@ -622,10 +622,10 @@ class SingleStatCtrl extends MetricsPanelCtrl {
}); });
data.colorMap = panel.colors; data.colorMap = panel.colors;
var body = panel.gauge.show ? '' : getBigValueHtml(); const body = panel.gauge.show ? '' : getBigValueHtml();
if (panel.colorBackground) { if (panel.colorBackground) {
var color = getColorForValue(data, data.value); const color = getColorForValue(data, data.value);
if (color) { if (color) {
$panelContainer.css('background-color', color); $panelContainer.css('background-color', color);
if (scope.fullscreen) { if (scope.fullscreen) {
@ -660,7 +660,7 @@ class SingleStatCtrl extends MetricsPanelCtrl {
function hookupDrilldownLinkTooltip() { function hookupDrilldownLinkTooltip() {
// drilldown link tooltip // drilldown link tooltip
var drilldownTooltip = $('<div id="tooltip" class="">hello</div>"'); const drilldownTooltip = $('<div id="tooltip" class="">hello</div>"');
elem.mouseleave(function() { elem.mouseleave(function() {
if (panel.links.length === 0) { if (panel.links.length === 0) {

@ -66,7 +66,7 @@ export class ColumnOptionsCtrl {
} }
addColumnStyle() { addColumnStyle() {
var newStyleRule = { const newStyleRule = {
unit: 'short', unit: 'short',
type: 'number', type: 'number',
alias: '', alias: '',
@ -79,13 +79,13 @@ export class ColumnOptionsCtrl {
mappingType: 1, mappingType: 1,
}; };
var styles = this.panel.styles; const styles = this.panel.styles;
var stylesCount = styles.length; const stylesCount = styles.length;
var indexToInsert = stylesCount; var indexToInsert = stylesCount;
// check if last is a catch all rule, then add it before that one // check if last is a catch all rule, then add it before that one
if (stylesCount > 0) { if (stylesCount > 0) {
var last = styles[stylesCount - 1]; const last = styles[stylesCount - 1];
if (last.pattern === '/.*/') { if (last.pattern === '/.*/') {
indexToInsert = stylesCount - 1; indexToInsert = stylesCount - 1;
} }
@ -100,8 +100,8 @@ export class ColumnOptionsCtrl {
} }
invertColorOrder(index) { invertColorOrder(index) {
var ref = this.panel.styles[index].colors; const ref = this.panel.styles[index].colors;
var copy = ref[0]; const copy = ref[0];
ref[0] = ref[2]; ref[0] = ref[2];
ref[2] = copy; ref[2] = copy;
this.panelCtrl.render(); this.panelCtrl.render();

@ -45,21 +45,21 @@ export class TablePanelEditorCtrl {
if (!this.panelCtrl.dataRaw) { if (!this.panelCtrl.dataRaw) {
return this.$q.when([]); return this.$q.when([]);
} }
var columns = this.transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw); const columns = this.transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw);
var segments = _.map(columns, (c: any) => this.uiSegmentSrv.newSegment({ value: c.text })); const segments = _.map(columns, (c: any) => this.uiSegmentSrv.newSegment({ value: c.text }));
return this.$q.when(segments); return this.$q.when(segments);
} }
addColumn() { addColumn() {
var columns = transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw); const columns = transformers[this.panel.transform].getColumns(this.panelCtrl.dataRaw);
var column = _.find(columns, { text: this.addColumnSegment.value }); const column = _.find(columns, { text: this.addColumnSegment.value });
if (column) { if (column) {
this.panel.columns.push(column); this.panel.columns.push(column);
this.render(); this.render();
} }
var plusButton = this.uiSegmentSrv.newPlusButton(); const plusButton = this.uiSegmentSrv.newPlusButton();
this.addColumnSegment.html = plusButton.html; this.addColumnSegment.html = plusButton.html;
this.addColumnSegment.value = plusButton.value; this.addColumnSegment.value = plusButton.value;
} }

@ -160,7 +160,7 @@ class TablePanelCtrl extends MetricsPanelCtrl {
} }
exportCsv() { exportCsv() {
var scope = this.$scope.$new(true); const scope = this.$scope.$new(true);
scope.tableData = this.renderer.render_values(); scope.tableData = this.renderer.render_values();
scope.panel = 'table'; scope.panel = 'table';
this.publishAppEvent('show-modal', { this.publishAppEvent('show-modal', {
@ -172,7 +172,7 @@ class TablePanelCtrl extends MetricsPanelCtrl {
link(scope, elem, attrs, ctrl: TablePanelCtrl) { link(scope, elem, attrs, ctrl: TablePanelCtrl) {
var data; var data;
var panel = ctrl.panel; const panel = ctrl.panel;
var pageCount = 0; var pageCount = 0;
function getTableHeight() { function getTableHeight() {
@ -192,7 +192,7 @@ class TablePanelCtrl extends MetricsPanelCtrl {
} }
function switchPage(e) { function switchPage(e) {
var el = $(e.currentTarget); const el = $(e.currentTarget);
ctrl.pageIndex = parseInt(el.text(), 10) - 1; ctrl.pageIndex = parseInt(el.text(), 10) - 1;
renderPanel(); renderPanel();
} }
@ -200,20 +200,20 @@ class TablePanelCtrl extends MetricsPanelCtrl {
function appendPaginationControls(footerElem) { function appendPaginationControls(footerElem) {
footerElem.empty(); footerElem.empty();
var pageSize = panel.pageSize || 100; const pageSize = panel.pageSize || 100;
pageCount = Math.ceil(data.rows.length / pageSize); pageCount = Math.ceil(data.rows.length / pageSize);
if (pageCount === 1) { if (pageCount === 1) {
return; return;
} }
var startPage = Math.max(ctrl.pageIndex - 3, 0); const startPage = Math.max(ctrl.pageIndex - 3, 0);
var endPage = Math.min(pageCount, startPage + 9); const endPage = Math.min(pageCount, startPage + 9);
var paginationList = $('<ul></ul>'); const paginationList = $('<ul></ul>');
for (var i = startPage; i < endPage; i++) { for (var i = startPage; i < endPage; i++) {
var activeClass = i === ctrl.pageIndex ? 'active' : ''; const activeClass = i === ctrl.pageIndex ? 'active' : '';
var pageLinkElem = $( const pageLinkElem = $(
'<li><a class="table-panel-page-link pointer ' + activeClass + '">' + (i + 1) + '</a></li>' '<li><a class="table-panel-page-link pointer ' + activeClass + '">' + (i + 1) + '</a></li>'
); );
paginationList.append(pageLinkElem); paginationList.append(pageLinkElem);
@ -223,10 +223,10 @@ class TablePanelCtrl extends MetricsPanelCtrl {
} }
function renderPanel() { function renderPanel() {
var panelElem = elem.parents('.panel-content'); const panelElem = elem.parents('.panel-content');
var rootElem = elem.find('.table-panel-scroll'); const rootElem = elem.find('.table-panel-scroll');
var tbodyElem = elem.find('tbody'); const tbodyElem = elem.find('tbody');
var footerElem = elem.find('.table-panel-footer'); const footerElem = elem.find('.table-panel-footer');
elem.css({ 'font-size': panel.fontSize }); elem.css({ 'font-size': panel.fontSize });
panelElem.addClass('table-panel-content'); panelElem.addClass('table-panel-content');
@ -244,7 +244,7 @@ class TablePanelCtrl extends MetricsPanelCtrl {
function addFilterClicked(e) { function addFilterClicked(e) {
const filterData = $(e.currentTarget).data(); const filterData = $(e.currentTarget).data();
var options = { const options = {
datasource: panel.datasource, datasource: panel.datasource,
key: data.columns[filterData.column].text, key: data.columns[filterData.column].text,
value: data.rows[filterData.row][filterData.column], value: data.rows[filterData.row][filterData.column],
@ -257,7 +257,7 @@ class TablePanelCtrl extends MetricsPanelCtrl {
elem.on('click', '.table-panel-page-link', switchPage); elem.on('click', '.table-panel-page-link', switchPage);
elem.on('click', '.table-panel-filter-link', addFilterClicked); elem.on('click', '.table-panel-filter-link', addFilterClicked);
var unbindDestroy = scope.$on('$destroy', function() { const unbindDestroy = scope.$on('$destroy', function() {
elem.off('click', '.table-panel-page-link'); elem.off('click', '.table-panel-page-link');
elem.off('click', '.table-panel-filter-link'); elem.off('click', '.table-panel-filter-link');
unbindDestroy(); unbindDestroy();

@ -27,7 +27,7 @@ export class TableRenderer {
for (let i = 0; i < this.panel.styles.length; i++) { for (let i = 0; i < this.panel.styles.length; i++) {
const style = this.panel.styles[i]; const style = this.panel.styles[i];
var regex = kbn.stringToJsRegex(style.pattern); const regex = kbn.stringToJsRegex(style.pattern);
if (column.text.match(regex)) { if (column.text.match(regex)) {
column.style = style; column.style = style;
@ -184,7 +184,7 @@ export class TableRenderer {
return; return;
} }
var numericValue = Number(value); const numericValue = Number(value);
if (numericValue === NaN) { if (numericValue === NaN) {
return; return;
} }
@ -210,9 +210,9 @@ export class TableRenderer {
renderCell(columnIndex, rowIndex, value, addWidthHack = false) { renderCell(columnIndex, rowIndex, value, addWidthHack = false) {
value = this.formatColumnValue(columnIndex, value); value = this.formatColumnValue(columnIndex, value);
var column = this.table.columns[columnIndex]; const column = this.table.columns[columnIndex];
var style = ''; var style = '';
var cellClasses = []; const cellClasses = [];
var cellClass = ''; var cellClass = '';
if (this.colorState.cell) { if (this.colorState.cell) {
@ -248,12 +248,12 @@ export class TableRenderer {
if (column.style && column.style.link) { if (column.style && column.style.link) {
// Render cell as link // Render cell as link
var scopedVars = this.renderRowVariables(rowIndex); const scopedVars = this.renderRowVariables(rowIndex);
scopedVars['__cell'] = { value: value }; scopedVars['__cell'] = { value: value };
var cellLink = this.templateSrv.replace(column.style.linkUrl, scopedVars, encodeURIComponent); const cellLink = this.templateSrv.replace(column.style.linkUrl, scopedVars, encodeURIComponent);
var cellLinkTooltip = this.templateSrv.replace(column.style.linkTooltip, scopedVars); const cellLinkTooltip = this.templateSrv.replace(column.style.linkTooltip, scopedVars);
var cellTarget = column.style.linkTargetBlank ? '_blank' : ''; const cellTarget = column.style.linkTargetBlank ? '_blank' : '';
cellClasses.push('table-panel-cell-link'); cellClasses.push('table-panel-cell-link');

@ -3,7 +3,7 @@ import flatten from '../../../core/utils/flatten';
import TimeSeries from '../../../core/time_series2'; import TimeSeries from '../../../core/time_series2';
import TableModel from '../../../core/table_model'; import TableModel from '../../../core/table_model';
var transformers = {}; const transformers = {};
transformers['timeseries_to_rows'] = { transformers['timeseries_to_rows'] = {
description: 'Time series to rows', description: 'Time series to rows',
@ -14,9 +14,9 @@ transformers['timeseries_to_rows'] = {
model.columns = [{ text: 'Time', type: 'date' }, { text: 'Metric' }, { text: 'Value' }]; model.columns = [{ text: 'Time', type: 'date' }, { text: 'Metric' }, { text: 'Value' }];
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
var series = data[i]; const series = data[i];
for (var y = 0; y < series.datapoints.length; y++) { for (var y = 0; y < series.datapoints.length; y++) {
var dp = series.datapoints[y]; const dp = series.datapoints[y];
model.rows.push([dp[1], series.target, dp[0]]); model.rows.push([dp[1], series.target, dp[0]]);
} }
} }
@ -32,15 +32,15 @@ transformers['timeseries_to_columns'] = {
model.columns.push({ text: 'Time', type: 'date' }); model.columns.push({ text: 'Time', type: 'date' });
// group by time // group by time
var points = {}; const points = {};
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
var series = data[i]; const series = data[i];
model.columns.push({ text: series.target }); model.columns.push({ text: series.target });
for (var y = 0; y < series.datapoints.length; y++) { for (var y = 0; y < series.datapoints.length; y++) {
var dp = series.datapoints[y]; const dp = series.datapoints[y];
var timeKey = dp[1].toString(); const timeKey = dp[1].toString();
if (!points[timeKey]) { if (!points[timeKey]) {
points[timeKey] = { time: dp[1] }; points[timeKey] = { time: dp[1] };
@ -51,12 +51,12 @@ transformers['timeseries_to_columns'] = {
} }
} }
for (var time in points) { for (const time in points) {
var point = points[time]; const point = points[time];
var values = [point.time]; const values = [point.time];
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
var value = point[i]; const value = point[i];
values.push(value); values.push(value);
} }
@ -86,13 +86,13 @@ transformers['timeseries_aggregations'] = {
} }
for (i = 0; i < data.length; i++) { for (i = 0; i < data.length; i++) {
var series = new TimeSeries({ const series = new TimeSeries({
datapoints: data[i].datapoints, datapoints: data[i].datapoints,
alias: data[i].target, alias: data[i].target,
}); });
series.getFlotPairs('connected'); series.getFlotPairs('connected');
var cells = [series.alias]; const cells = [series.alias];
for (y = 0; y < panel.columns.length; y++) { for (y = 0; y < panel.columns.length; y++) {
cells.push(series.stats[panel.columns[y].value]); cells.push(series.stats[panel.columns[y].value]);
@ -119,7 +119,7 @@ transformers['annotations'] = {
} }
for (var i = 0; i < data.annotations.length; i++) { for (var i = 0; i < data.annotations.length; i++) {
var evt = data.annotations[i]; const evt = data.annotations[i];
model.rows.push([evt.time, evt.title, evt.text, evt.tags]); model.rows.push([evt.time, evt.title, evt.text, evt.tags]);
} }
}, },
@ -269,19 +269,19 @@ transformers['json'] = {
return []; return [];
} }
var names: any = {}; const names: any = {};
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
var series = data[i]; const series = data[i];
if (series.type !== 'docs') { if (series.type !== 'docs') {
continue; continue;
} }
// only look at 100 docs // only look at 100 docs
var maxDocs = Math.min(series.datapoints.length, 100); const maxDocs = Math.min(series.datapoints.length, 100);
for (var y = 0; y < maxDocs; y++) { for (var y = 0; y < maxDocs; y++) {
var doc = series.datapoints[y]; const doc = series.datapoints[y];
var flattened = flatten(doc, null); const flattened = flatten(doc, null);
for (var propName in flattened) { for (const propName in flattened) {
names[propName] = true; names[propName] = true;
} }
} }
@ -295,7 +295,7 @@ transformers['json'] = {
var i, y, z; var i, y, z;
for (const column of panel.columns) { for (const column of panel.columns) {
var tableCol: any = { text: column.text }; const tableCol: any = { text: column.text };
// if filterable data then set columns to filterable // if filterable data then set columns to filterable
if (data.length > 0 && data[0].filterable) { if (data.length > 0 && data[0].filterable) {
@ -310,14 +310,14 @@ transformers['json'] = {
} }
for (i = 0; i < data.length; i++) { for (i = 0; i < data.length; i++) {
var series = data[i]; const series = data[i];
for (y = 0; y < series.datapoints.length; y++) { for (y = 0; y < series.datapoints.length; y++) {
var dp = series.datapoints[y]; const dp = series.datapoints[y];
var values = []; const values = [];
if (_.isObject(dp) && panel.columns.length > 0) { if (_.isObject(dp) && panel.columns.length > 0) {
var flattened = flatten(dp, null); const flattened = flatten(dp, null);
for (z = 0; z < panel.columns.length; z++) { for (z = 0; z < panel.columns.length; z++) {
values.push(flattened[panel.columns[z].value]); values.push(flattened[panel.columns[z].value]);
} }
@ -332,13 +332,13 @@ transformers['json'] = {
}; };
function transformDataToTable(data, panel) { function transformDataToTable(data, panel) {
var model = new TableModel(); const model = new TableModel();
if (!data || data.length === 0) { if (!data || data.length === 0) {
return model; return model;
} }
var transformer = transformers[panel.transform]; const transformer = transformers[panel.transform];
if (!transformer) { if (!transformer) {
throw { message: 'Transformer ' + panel.transform + ' not found' }; throw { message: 'Transformer ' + panel.transform + ' not found' };
} }

Loading…
Cancel
Save