Commit e1cec106 by Tobias Skarhed Committed by Torkel Ödegaard

noImplicitAny: 1670 errors (#18035)

* Sub 2000 errors

* Down to 1670 errors

* Minor fixes
parent 6aa58182
...@@ -4,7 +4,7 @@ import { variableRegex } from 'app/features/templating/variable'; ...@@ -4,7 +4,7 @@ import { variableRegex } from 'app/features/templating/variable';
import { ScopedVars } from '@grafana/ui'; import { ScopedVars } from '@grafana/ui';
import { TimeRange } from '@grafana/data'; import { TimeRange } from '@grafana/data';
function luceneEscape(value) { function luceneEscape(value: string) {
return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1'); return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1');
} }
...@@ -12,8 +12,8 @@ export class TemplateSrv { ...@@ -12,8 +12,8 @@ export class TemplateSrv {
variables: any[]; variables: any[];
private regex = variableRegex; private regex = variableRegex;
private index = {}; private index: any = {};
private grafanaVariables = {}; private grafanaVariables: any = {};
private builtIns: any = {}; private builtIns: any = {};
private timeRange: TimeRange = null; private timeRange: TimeRange = null;
...@@ -23,7 +23,7 @@ export class TemplateSrv { ...@@ -23,7 +23,7 @@ export class TemplateSrv {
this.variables = []; this.variables = [];
} }
init(variables, timeRange?: TimeRange) { init(variables: any, timeRange?: TimeRange) {
this.variables = variables; this.variables = variables;
this.timeRange = timeRange; this.timeRange = timeRange;
this.updateIndex(); this.updateIndex();
...@@ -34,7 +34,7 @@ export class TemplateSrv { ...@@ -34,7 +34,7 @@ export class TemplateSrv {
} }
updateIndex() { updateIndex() {
const existsOrEmpty = value => value || value === ''; const existsOrEmpty = (value: any) => value || value === '';
this.index = this.variables.reduce((acc, currentValue) => { this.index = this.variables.reduce((acc, currentValue) => {
if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) { if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) {
...@@ -64,12 +64,12 @@ export class TemplateSrv { ...@@ -64,12 +64,12 @@ export class TemplateSrv {
this.updateIndex(); this.updateIndex();
} }
variableInitialized(variable) { variableInitialized(variable: any) {
this.index[variable.name] = variable; this.index[variable.name] = variable;
} }
getAdhocFilters(datasourceName) { getAdhocFilters(datasourceName: string) {
let filters = []; let filters: any = [];
if (this.variables) { if (this.variables) {
for (let i = 0; i < this.variables.length; i++) { for (let i = 0; i < this.variables.length; i++) {
...@@ -92,7 +92,7 @@ export class TemplateSrv { ...@@ -92,7 +92,7 @@ export class TemplateSrv {
return filters; return filters;
} }
luceneFormat(value) { luceneFormat(value: any) {
if (typeof value === 'string') { if (typeof value === 'string') {
return luceneEscape(value); return luceneEscape(value);
} }
...@@ -108,7 +108,7 @@ export class TemplateSrv { ...@@ -108,7 +108,7 @@ export class TemplateSrv {
// encode string according to RFC 3986; in contrast to encodeURIComponent() // encode string according to RFC 3986; in contrast to encodeURIComponent()
// also the sub-delims "!", "'", "(", ")" and "*" are encoded; // also the sub-delims "!", "'", "(", ")" and "*" are encoded;
// unicode handling uses UTF-8 as in ECMA-262. // unicode handling uses UTF-8 as in ECMA-262.
encodeURIComponentStrict(str) { encodeURIComponentStrict(str: string) {
return encodeURIComponent(str).replace(/[!'()*]/g, c => { return encodeURIComponent(str).replace(/[!'()*]/g, c => {
return ( return (
'%' + '%' +
...@@ -120,7 +120,7 @@ export class TemplateSrv { ...@@ -120,7 +120,7 @@ export class TemplateSrv {
}); });
} }
formatValue(value, format, variable) { formatValue(value: any, format: any, variable: any) {
// for some scopedVars there is no variable // for some scopedVars there is no variable
variable = variable || {}; variable = variable || {};
...@@ -180,11 +180,11 @@ export class TemplateSrv { ...@@ -180,11 +180,11 @@ export class TemplateSrv {
} }
} }
setGrafanaVariable(name, value) { setGrafanaVariable(name: string, value: any) {
this.grafanaVariables[name] = value; this.grafanaVariables[name] = value;
} }
getVariableName(expression) { getVariableName(expression: string) {
this.regex.lastIndex = 0; this.regex.lastIndex = 0;
const match = this.regex.exec(expression); const match = this.regex.exec(expression);
if (!match) { if (!match) {
...@@ -194,12 +194,12 @@ export class TemplateSrv { ...@@ -194,12 +194,12 @@ export class TemplateSrv {
return variableName; return variableName;
} }
variableExists(expression) { variableExists(expression: string) {
const name = this.getVariableName(expression); const name = this.getVariableName(expression);
return name && this.index[name] !== void 0; return name && this.index[name] !== void 0;
} }
highlightVariablesAsHtml(str) { highlightVariablesAsHtml(str: string) {
if (!str || !_.isString(str)) { if (!str || !_.isString(str)) {
return str; return str;
} }
...@@ -214,7 +214,7 @@ export class TemplateSrv { ...@@ -214,7 +214,7 @@ export class TemplateSrv {
}); });
} }
getAllValue(variable) { getAllValue(variable: any) {
if (variable.allValue) { if (variable.allValue) {
return variable.allValue; return variable.allValue;
} }
...@@ -225,7 +225,7 @@ export class TemplateSrv { ...@@ -225,7 +225,7 @@ export class TemplateSrv {
return values; return values;
} }
replace(target: string, scopedVars?: ScopedVars, format?: string | Function) { replace(target: string, scopedVars?: ScopedVars, format?: string | Function): any {
if (!target) { if (!target) {
return target; return target;
} }
...@@ -266,11 +266,11 @@ export class TemplateSrv { ...@@ -266,11 +266,11 @@ export class TemplateSrv {
}); });
} }
isAllValue(value) { isAllValue(value: any) {
return value === '$__all' || (Array.isArray(value) && value[0] === '$__all'); return value === '$__all' || (Array.isArray(value) && value[0] === '$__all');
} }
replaceWithText(target, scopedVars) { replaceWithText(target: string, scopedVars: ScopedVars) {
if (!target) { if (!target) {
return target; return target;
} }
...@@ -278,7 +278,7 @@ export class TemplateSrv { ...@@ -278,7 +278,7 @@ export class TemplateSrv {
let variable; let variable;
this.regex.lastIndex = 0; this.regex.lastIndex = 0;
return target.replace(this.regex, (match, var1, var2, fmt2, var3) => { return target.replace(this.regex, (match: any, var1: any, var2: any, fmt2: any, var3: any) => {
if (scopedVars) { if (scopedVars) {
const option = scopedVars[var1 || var2 || var3]; const option = scopedVars[var1 || var2 || var3];
if (option) { if (option) {
...@@ -297,7 +297,7 @@ export class TemplateSrv { ...@@ -297,7 +297,7 @@ export class TemplateSrv {
}); });
} }
fillVariableValuesForUrl(params, scopedVars?) { fillVariableValuesForUrl(params: any, scopedVars?: ScopedVars) {
_.each(this.variables, variable => { _.each(this.variables, variable => {
if (scopedVars && scopedVars[variable.name] !== void 0) { if (scopedVars && scopedVars[variable.name] !== void 0) {
if (scopedVars[variable.name].skipUrlSync) { if (scopedVars[variable.name].skipUrlSync) {
...@@ -313,7 +313,7 @@ export class TemplateSrv { ...@@ -313,7 +313,7 @@ export class TemplateSrv {
}); });
} }
distributeVariable(value, variable) { distributeVariable(value: any, variable: any) {
value = _.map(value, (val: any, index: number) => { value = _.map(value, (val: any, index: number) => {
if (index !== 0) { if (index !== 0) {
return variable + '=' + val; return variable + '=' + val;
......
...@@ -16,12 +16,12 @@ export const variableRegexExec = (variableString: string) => { ...@@ -16,12 +16,12 @@ export const variableRegexExec = (variableString: string) => {
}; };
export interface Variable { export interface Variable {
setValue(option); setValue(option: any): any;
updateOptions(); updateOptions(): any;
dependsOn(variable); dependsOn(variable: any): any;
setValueFromUrl(urlValue); setValueFromUrl(urlValue: any): any;
getValueForUrl(); getValueForUrl(): any;
getSaveModel(); getSaveModel(): any;
} }
export let variableTypes = {}; export let variableTypes = {};
......
// Libaries // Libaries
import angular from 'angular'; import angular, { IQService, ILocationService, auto, IPromise } from 'angular';
import _ from 'lodash'; import _ from 'lodash';
// Utils & Services // Utils & Services
...@@ -19,9 +19,9 @@ export class VariableSrv { ...@@ -19,9 +19,9 @@ export class VariableSrv {
/** @ngInject */ /** @ngInject */
constructor( constructor(
private $q, private $q: IQService,
private $location, private $location: ILocationService,
private $injector, private $injector: auto.IInjectorService,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
) {} ) {}
...@@ -71,7 +71,7 @@ export class VariableSrv { ...@@ -71,7 +71,7 @@ export class VariableSrv {
}); });
} }
processVariable(variable, queryParams) { processVariable(variable: any, queryParams: any) {
const dependencies = []; const dependencies = [];
for (const otherVariable of this.variables) { for (const otherVariable of this.variables) {
...@@ -100,7 +100,8 @@ export class VariableSrv { ...@@ -100,7 +100,8 @@ export class VariableSrv {
}); });
} }
createVariableFromModel(model) { createVariableFromModel(model: any) {
// @ts-ignore
const ctor = variableTypes[model.type].ctor; const ctor = variableTypes[model.type].ctor;
if (!ctor) { if (!ctor) {
throw { throw {
...@@ -112,24 +113,24 @@ export class VariableSrv { ...@@ -112,24 +113,24 @@ export class VariableSrv {
return variable; return variable;
} }
addVariable(variable) { addVariable(variable: any) {
this.variables.push(variable); this.variables.push(variable);
this.templateSrv.updateIndex(); this.templateSrv.updateIndex();
this.dashboard.updateSubmenuVisibility(); this.dashboard.updateSubmenuVisibility();
} }
removeVariable(variable) { removeVariable(variable: any) {
const index = _.indexOf(this.variables, variable); const index = _.indexOf(this.variables, variable);
this.variables.splice(index, 1); this.variables.splice(index, 1);
this.templateSrv.updateIndex(); this.templateSrv.updateIndex();
this.dashboard.updateSubmenuVisibility(); this.dashboard.updateSubmenuVisibility();
} }
updateOptions(variable) { updateOptions(variable: any) {
return variable.updateOptions(); return variable.updateOptions();
} }
variableUpdated(variable, emitChangeEvents?) { variableUpdated(variable: any, emitChangeEvents?: any) {
// if there is a variable lock ignore cascading update because we are in a boot up scenario // if there is a variable lock ignore cascading update because we are in a boot up scenario
if (variable.initLock) { if (variable.initLock) {
return this.$q.when(); return this.$q.when();
...@@ -152,7 +153,7 @@ export class VariableSrv { ...@@ -152,7 +153,7 @@ export class VariableSrv {
}); });
} }
selectOptionsForCurrentValue(variable) { selectOptionsForCurrentValue(variable: any) {
let i, y, value, option; let i, y, value, option;
const selected: any = []; const selected: any = [];
...@@ -176,7 +177,7 @@ export class VariableSrv { ...@@ -176,7 +177,7 @@ export class VariableSrv {
return selected; return selected;
} }
validateVariableSelectionState(variable) { validateVariableSelectionState(variable: any) {
if (!variable.current) { if (!variable.current) {
variable.current = {}; variable.current = {};
} }
...@@ -221,7 +222,7 @@ export class VariableSrv { ...@@ -221,7 +222,7 @@ export class VariableSrv {
* @param variable Instance of Variable * @param variable Instance of Variable
* @param urlValue Value of the query parameter * @param urlValue Value of the query parameter
*/ */
setOptionFromUrl(variable: any, urlValue: string | string[]): Promise<any> { setOptionFromUrl(variable: any, urlValue: string | string[]): IPromise<any> {
let promise = this.$q.when(); let promise = this.$q.when();
if (variable.refresh) { if (variable.refresh) {
...@@ -268,7 +269,7 @@ export class VariableSrv { ...@@ -268,7 +269,7 @@ export class VariableSrv {
}); });
} }
setOptionAsCurrent(variable, option) { setOptionAsCurrent(variable: any, option: any) {
variable.current = _.cloneDeep(option); variable.current = _.cloneDeep(option);
if (_.isArray(variable.current.text) && variable.current.text.length > 0) { if (_.isArray(variable.current.text) && variable.current.text.length > 0) {
...@@ -298,7 +299,7 @@ export class VariableSrv { ...@@ -298,7 +299,7 @@ export class VariableSrv {
this.$location.search(params); this.$location.search(params);
} }
setAdhocFilter(options) { setAdhocFilter(options: any) {
let variable: any = _.find(this.variables, { let variable: any = _.find(this.variables, {
type: 'adhoc', type: 'adhoc',
datasource: options.datasource, datasource: options.datasource,
......
...@@ -78,7 +78,7 @@ export class UsersActionBar extends PureComponent<Props> { ...@@ -78,7 +78,7 @@ export class UsersActionBar extends PureComponent<Props> {
} }
} }
function mapStateToProps(state) { function mapStateToProps(state: any) {
return { return {
searchQuery: getUsersSearchQuery(state.users), searchQuery: getUsersSearchQuery(state.users),
pendingInvitesCount: getInviteesCount(state.users), pendingInvitesCount: getInviteesCount(state.users),
......
...@@ -34,7 +34,7 @@ export interface State { ...@@ -34,7 +34,7 @@ export interface State {
export class UsersListPage extends PureComponent<Props, State> { export class UsersListPage extends PureComponent<Props, State> {
externalUserMngInfoHtml: string; externalUserMngInfoHtml: string;
constructor(props) { constructor(props: Props) {
super(props); super(props);
if (this.props.externalUserMngInfo) { if (this.props.externalUserMngInfo) {
...@@ -59,13 +59,13 @@ export class UsersListPage extends PureComponent<Props, State> { ...@@ -59,13 +59,13 @@ export class UsersListPage extends PureComponent<Props, State> {
return await this.props.loadInvitees(); return await this.props.loadInvitees();
} }
onRoleChange = (role, user) => { onRoleChange = (role: string, user: OrgUser) => {
const updatedUser = { ...user, role: role }; const updatedUser = { ...user, role: role };
this.props.updateUser(updatedUser); this.props.updateUser(updatedUser);
}; };
onRemoveUser = user => { onRemoveUser = (user: OrgUser) => {
appEvents.emit('confirm-modal', { appEvents.emit('confirm-modal', {
title: 'Delete', title: 'Delete',
text: 'Are you sure you want to delete user ' + user.login + '?', text: 'Are you sure you want to delete user ' + user.login + '?',
...@@ -119,7 +119,7 @@ export class UsersListPage extends PureComponent<Props, State> { ...@@ -119,7 +119,7 @@ export class UsersListPage extends PureComponent<Props, State> {
} }
} }
function mapStateToProps(state) { function mapStateToProps(state: any) {
return { return {
navModel: getNavModel(state.navIndex, 'users'), navModel: getNavModel(state.navIndex, 'users'),
users: getUsers(state.users), users: getUsers(state.users),
......
export const getUsers = state => { import { UsersState } from 'app/types';
export const getUsers = (state: UsersState) => {
const regex = new RegExp(state.searchQuery, 'i'); const regex = new RegExp(state.searchQuery, 'i');
return state.users.filter(user => { return state.users.filter(user => {
...@@ -6,7 +8,7 @@ export const getUsers = state => { ...@@ -6,7 +8,7 @@ export const getUsers = state => {
}); });
}; };
export const getInvitees = state => { export const getInvitees = (state: UsersState) => {
const regex = new RegExp(state.searchQuery, 'i'); const regex = new RegExp(state.searchQuery, 'i');
return state.invitees.filter(invitee => { return state.invitees.filter(invitee => {
...@@ -14,5 +16,5 @@ export const getInvitees = state => { ...@@ -14,5 +16,5 @@ export const getInvitees = state => {
}); });
}; };
export const getInviteesCount = state => state.invitees.length; export const getInviteesCount = (state: UsersState) => state.invitees.length;
export const getUsersSearchQuery = state => state.searchQuery; export const getUsersSearchQuery = (state: UsersState) => state.searchQuery;
import _ from 'lodash'; import _ from 'lodash';
import DatasourceSrv from 'app/features/plugins/datasource_srv';
import CloudWatchDatasource from './datasource';
export class CloudWatchConfigCtrl { export class CloudWatchConfigCtrl {
static templateUrl = 'partials/config.html'; static templateUrl = 'partials/config.html';
current: any; current: any;
...@@ -8,7 +10,7 @@ export class CloudWatchConfigCtrl { ...@@ -8,7 +10,7 @@ export class CloudWatchConfigCtrl {
secretKeyExist = false; secretKeyExist = false;
/** @ngInject */ /** @ngInject */
constructor($scope, datasourceSrv) { constructor($scope: any, datasourceSrv: DatasourceSrv) {
this.current.jsonData.timeField = this.current.jsonData.timeField || '@timestamp'; this.current.jsonData.timeField = this.current.jsonData.timeField || '@timestamp';
this.current.jsonData.authType = this.current.jsonData.authType || 'credentials'; this.current.jsonData.authType = this.current.jsonData.authType || 'credentials';
...@@ -32,7 +34,7 @@ export class CloudWatchConfigCtrl { ...@@ -32,7 +34,7 @@ export class CloudWatchConfigCtrl {
{ name: 'ARN', value: 'arn' }, { name: 'ARN', value: 'arn' },
]; ];
indexPatternTypes = [ indexPatternTypes: any = [
{ name: 'No pattern', value: undefined }, { name: 'No pattern', value: undefined },
{ name: 'Hourly', value: 'Hourly', example: '[logstash-]YYYY.MM.DD.HH' }, { name: 'Hourly', value: 'Hourly', example: '[logstash-]YYYY.MM.DD.HH' },
{ name: 'Daily', value: 'Daily', example: '[logstash-]YYYY.MM.DD' }, { name: 'Daily', value: 'Daily', example: '[logstash-]YYYY.MM.DD' },
...@@ -71,14 +73,14 @@ export class CloudWatchConfigCtrl { ...@@ -71,14 +73,14 @@ export class CloudWatchConfigCtrl {
getRegions() { getRegions() {
this.datasourceSrv this.datasourceSrv
.loadDatasource(this.current.name) .loadDatasource(this.current.name)
.then(ds => { .then((ds: CloudWatchDatasource) => {
return ds.getRegions(); return ds.getRegions();
}) })
.then( .then(
regions => { (regions: any) => {
this.regions = _.map(regions, 'value'); this.regions = _.map(regions, 'value');
}, },
err => { (err: any) => {
console.error('failed to get latest regions'); console.error('failed to get latest regions');
} }
); );
......
import angular from 'angular'; import angular, { IQService } from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import { dateMath } from '@grafana/data'; import { dateMath } from '@grafana/data';
import kbn from 'app/core/utils/kbn'; import kbn from 'app/core/utils/kbn';
import { CloudWatchQuery } from './types'; import { CloudWatchQuery } from './types';
import { DataSourceApi, DataQueryRequest, DataSourceInstanceSettings } from '@grafana/ui'; import { DataSourceApi, DataQueryRequest, DataSourceInstanceSettings, ScopedVars } from '@grafana/ui';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
...@@ -18,7 +18,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -18,7 +18,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
/** @ngInject */ /** @ngInject */
constructor( constructor(
private instanceSettings: DataSourceInstanceSettings, private instanceSettings: DataSourceInstanceSettings,
private $q, private $q: IQService,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private timeSrv: TimeSrv private timeSrv: TimeSrv
...@@ -96,7 +96,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -96,7 +96,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
return this.performTimeSeriesQuery(request); return this.performTimeSeriesQuery(request);
} }
getPeriod(target, options, now?) { getPeriod(target: any, options: any, now?: number) {
const start = this.convertToCloudWatchTime(options.range.from, false); const start = this.convertToCloudWatchTime(options.range.from, false);
const 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);
...@@ -142,8 +142,8 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -142,8 +142,8 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
return period; return period;
} }
performTimeSeriesQuery(request) { performTimeSeriesQuery(request: any) {
return this.awsRequest('/api/tsdb/query', request).then(res => { return this.awsRequest('/api/tsdb/query', request).then((res: any) => {
const data = []; const data = [];
if (res.results) { if (res.results) {
...@@ -165,7 +165,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -165,7 +165,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
transformSuggestDataFromTable(suggestData) { transformSuggestDataFromTable(suggestData: any) {
return _.map(suggestData.results['metricFindQuery'].tables[0].rows, v => { return _.map(suggestData.results['metricFindQuery'].tables[0].rows, v => {
return { return {
text: v[0], text: v[0],
...@@ -174,7 +174,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -174,7 +174,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
doMetricQueryRequest(subtype, parameters) { doMetricQueryRequest(subtype: any, parameters: any) {
const 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(),
...@@ -192,7 +192,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -192,7 +192,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
parameters parameters
), ),
], ],
}).then(r => { }).then((r: any) => {
return this.transformSuggestDataFromTable(r); return this.transformSuggestDataFromTable(r);
}); });
} }
...@@ -205,21 +205,27 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -205,21 +205,27 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
return this.doMetricQueryRequest('namespaces', null); return this.doMetricQueryRequest('namespaces', null);
} }
getMetrics(namespace, region) { getMetrics(namespace: string, region: string) {
return this.doMetricQueryRequest('metrics', { return this.doMetricQueryRequest('metrics', {
region: this.templateSrv.replace(this.getActualRegion(region)), region: this.templateSrv.replace(this.getActualRegion(region)),
namespace: this.templateSrv.replace(namespace), namespace: this.templateSrv.replace(namespace),
}); });
} }
getDimensionKeys(namespace, region) { getDimensionKeys(namespace: string, region: string) {
return this.doMetricQueryRequest('dimension_keys', { return this.doMetricQueryRequest('dimension_keys', {
region: this.templateSrv.replace(this.getActualRegion(region)), region: this.templateSrv.replace(this.getActualRegion(region)),
namespace: this.templateSrv.replace(namespace), namespace: this.templateSrv.replace(namespace),
}); });
} }
getDimensionValues(region, namespace, metricName, dimensionKey, filterDimensions) { getDimensionValues(
region: string,
namespace: string,
metricName: string,
dimensionKey: string,
filterDimensions: {}
) {
return this.doMetricQueryRequest('dimension_values', { return this.doMetricQueryRequest('dimension_values', {
region: this.templateSrv.replace(this.getActualRegion(region)), region: this.templateSrv.replace(this.getActualRegion(region)),
namespace: this.templateSrv.replace(namespace), namespace: this.templateSrv.replace(namespace),
...@@ -229,14 +235,14 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -229,14 +235,14 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
getEbsVolumeIds(region, instanceId) { getEbsVolumeIds(region: string, instanceId: string) {
return this.doMetricQueryRequest('ebs_volume_ids', { return this.doMetricQueryRequest('ebs_volume_ids', {
region: this.templateSrv.replace(this.getActualRegion(region)), region: this.templateSrv.replace(this.getActualRegion(region)),
instanceId: this.templateSrv.replace(instanceId), instanceId: this.templateSrv.replace(instanceId),
}); });
} }
getEc2InstanceAttribute(region, attributeName, filters) { getEc2InstanceAttribute(region: string, attributeName: string, filters: any) {
return this.doMetricQueryRequest('ec2_instance_attribute', { return this.doMetricQueryRequest('ec2_instance_attribute', {
region: this.templateSrv.replace(this.getActualRegion(region)), region: this.templateSrv.replace(this.getActualRegion(region)),
attributeName: this.templateSrv.replace(attributeName), attributeName: this.templateSrv.replace(attributeName),
...@@ -244,7 +250,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -244,7 +250,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
getResourceARNs(region, resourceType, tags) { getResourceARNs(region: string, resourceType: string, tags: any) {
return this.doMetricQueryRequest('resource_arns', { return this.doMetricQueryRequest('resource_arns', {
region: this.templateSrv.replace(this.getActualRegion(region)), region: this.templateSrv.replace(this.getActualRegion(region)),
resourceType: this.templateSrv.replace(resourceType), resourceType: this.templateSrv.replace(resourceType),
...@@ -252,7 +258,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -252,7 +258,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
metricFindQuery(query) { metricFindQuery(query: string) {
let region; let region;
let namespace; let namespace;
let metricName; let metricName;
...@@ -324,7 +330,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -324,7 +330,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
return this.$q.when([]); return this.$q.when([]);
} }
annotationQuery(options) { annotationQuery(options: any) {
const annotation = options.annotation; const annotation = options.annotation;
const statistics = _.map(annotation.statistics, s => { const statistics = _.map(annotation.statistics, s => {
return this.templateSrv.replace(s); return this.templateSrv.replace(s);
...@@ -359,7 +365,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -359,7 +365,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
parameters parameters
), ),
], ],
}).then(r => { }).then((r: any) => {
return _.map(r.results['annotationQuery'].tables[0].rows, v => { return _.map(r.results['annotationQuery'].tables[0].rows, v => {
return { return {
annotation: annotation, annotation: annotation,
...@@ -372,7 +378,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -372,7 +378,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
targetContainsTemplate(target) { targetContainsTemplate(target: any) {
return ( return (
this.templateSrv.variableExists(target.region) || this.templateSrv.variableExists(target.region) ||
this.templateSrv.variableExists(target.namespace) || this.templateSrv.variableExists(target.namespace) ||
...@@ -395,14 +401,14 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -395,14 +401,14 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
awsRequest(url, data) { awsRequest(url: string, data: any) {
const options = { const options = {
method: 'POST', method: 'POST',
url: url, url,
data: data, data,
}; };
return this.backendSrv.datasourceRequest(options).then(result => { return this.backendSrv.datasourceRequest(options).then((result: any) => {
return result.data; return result.data;
}); });
} }
...@@ -411,14 +417,14 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -411,14 +417,14 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
return this.defaultRegion; return this.defaultRegion;
} }
getActualRegion(region) { getActualRegion(region: string) {
if (region === 'default' || _.isEmpty(region)) { if (region === 'default' || _.isEmpty(region)) {
return this.getDefaultRegion(); return this.getDefaultRegion();
} }
return region; return region;
} }
getExpandedVariables(target, dimensionKey, variable, templateSrv) { getExpandedVariables(target: any, dimensionKey: any, variable: any, templateSrv: 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 */
const allSelected: any = _.find(variable.options, { selected: true, text: 'All' }); const allSelected: any = _.find(variable.options, { selected: true, text: 'All' });
const selectedVariables = _.filter(variable.options, v => { const selectedVariables = _.filter(variable.options, v => {
...@@ -430,7 +436,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -430,7 +436,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
const 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: any) => {
return { return {
text: v, text: v,
value: v, value: v,
...@@ -440,9 +446,9 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -440,9 +446,9 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
selectedVariables.some((s: any) => { selectedVariables.some((s: any) => {
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: any) => {
const t = angular.copy(target); const t = angular.copy(target);
const scopedVar = {}; const scopedVar: any = {};
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);
...@@ -455,7 +461,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -455,7 +461,7 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
}); });
} }
expandTemplateVariable(targets, scopedVars, templateSrv) { expandTemplateVariable(targets: any, scopedVars: ScopedVars, templateSrv: TemplateSrv) {
// 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 => {
...@@ -480,15 +486,15 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> ...@@ -480,15 +486,15 @@ export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery>
.value(); .value();
} }
convertToCloudWatchTime(date, roundUp) { convertToCloudWatchTime(date: any, roundUp: any) {
if (_.isString(date)) { if (_.isString(date)) {
date = dateMath.parse(date, roundUp); date = dateMath.parse(date, roundUp);
} }
return Math.round(date.valueOf() / 1000); return Math.round(date.valueOf() / 1000);
} }
convertDimensionFormat(dimensions, scopedVars) { convertDimensionFormat(dimensions: any, scopedVars: ScopedVars) {
const convertedDimensions = {}; const convertedDimensions: any = {};
_.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);
}); });
......
import './query_parameter_ctrl'; import './query_parameter_ctrl';
import { QueryCtrl } from 'app/plugins/sdk'; import { QueryCtrl } from 'app/plugins/sdk';
import { auto } from 'angular';
export class CloudWatchQueryCtrl extends QueryCtrl { export class CloudWatchQueryCtrl extends QueryCtrl {
static templateUrl = 'partials/query.editor.html'; static templateUrl = 'partials/query.editor.html';
...@@ -7,7 +8,7 @@ export class CloudWatchQueryCtrl extends QueryCtrl { ...@@ -7,7 +8,7 @@ export class CloudWatchQueryCtrl extends QueryCtrl {
aliasSyntax: string; aliasSyntax: string;
/** @ngInject */ /** @ngInject */
constructor($scope, $injector) { constructor($scope: any, $injector: auto.IInjectorService) {
super($scope, $injector); super($scope, $injector);
this.aliasSyntax = '{{metric}} {{stat}} {{namespace}} {{region}} {{<dimension name>}}'; this.aliasSyntax = '{{metric}} {{stat}} {{namespace}} {{region}} {{<dimension name>}}';
} }
......
import angular from 'angular'; import angular, { IQService } from 'angular';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import _ from 'lodash'; import _ from 'lodash';
import { TemplateSrv } from 'app/features/templating/template_srv';
import DatasourceSrv from 'app/features/plugins/datasource_srv';
export class CloudWatchQueryParameterCtrl { export class CloudWatchQueryParameterCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope, templateSrv, uiSegmentSrv, datasourceSrv, $q) { constructor($scope: any, templateSrv: TemplateSrv, uiSegmentSrv: any, datasourceSrv: DatasourceSrv, $q: IQService) {
$scope.init = () => { $scope.init = () => {
const target = $scope.target; const target = $scope.target;
target.namespace = target.namespace || ''; target.namespace = target.namespace || '';
...@@ -69,7 +71,7 @@ export class CloudWatchQueryParameterCtrl { ...@@ -69,7 +71,7 @@ export class CloudWatchQueryParameterCtrl {
); );
}; };
$scope.statSegmentChanged = (segment, index) => { $scope.statSegmentChanged = (segment: any, index: number) => {
if (segment.value === $scope.removeStatSegment.value) { if (segment.value === $scope.removeStatSegment.value) {
$scope.statSegments.splice(index, 1); $scope.statSegments.splice(index, 1);
} else { } else {
...@@ -91,7 +93,7 @@ export class CloudWatchQueryParameterCtrl { ...@@ -91,7 +93,7 @@ export class CloudWatchQueryParameterCtrl {
$scope.onChange(); $scope.onChange();
}; };
$scope.ensurePlusButton = segments => { $scope.ensurePlusButton = (segments: any) => {
const count = segments.length; const count = segments.length;
const lastSegment = segments[Math.max(count - 1, 0)]; const lastSegment = segments[Math.max(count - 1, 0)];
...@@ -100,7 +102,7 @@ export class CloudWatchQueryParameterCtrl { ...@@ -100,7 +102,7 @@ export class CloudWatchQueryParameterCtrl {
} }
}; };
$scope.getDimSegments = (segment, $index) => { $scope.getDimSegments = (segment: any, $index: number) => {
if (segment.type === 'operator') { if (segment.type === 'operator') {
return $q.when([]); return $q.when([]);
} }
...@@ -130,7 +132,7 @@ export class CloudWatchQueryParameterCtrl { ...@@ -130,7 +132,7 @@ export class CloudWatchQueryParameterCtrl {
}); });
}; };
$scope.dimSegmentChanged = (segment, index) => { $scope.dimSegmentChanged = (segment: any, index: number) => {
$scope.dimSegments[index] = segment; $scope.dimSegments[index] = segment;
if (segment.value === $scope.removeDimSegment.value) { if (segment.value === $scope.removeDimSegment.value) {
...@@ -148,7 +150,7 @@ export class CloudWatchQueryParameterCtrl { ...@@ -148,7 +150,7 @@ export class CloudWatchQueryParameterCtrl {
}; };
$scope.syncDimSegmentsWithModel = () => { $scope.syncDimSegmentsWithModel = () => {
const dims = {}; const dims: any = {};
const length = $scope.dimSegments.length; const length = $scope.dimSegments.length;
for (let i = 0; i < length - 2; i += 3) { for (let i = 0; i < length - 2; i += 3) {
...@@ -165,7 +167,7 @@ export class CloudWatchQueryParameterCtrl { ...@@ -165,7 +167,7 @@ export class CloudWatchQueryParameterCtrl {
$scope.getRegions = () => { $scope.getRegions = () => {
return $scope.datasource return $scope.datasource
.metricFindQuery('regions()') .metricFindQuery('regions()')
.then(results => { .then((results: any) => {
results.unshift({ text: 'default' }); results.unshift({ text: 'default' });
return results; return results;
}) })
...@@ -197,8 +199,8 @@ export class CloudWatchQueryParameterCtrl { ...@@ -197,8 +199,8 @@ export class CloudWatchQueryParameterCtrl {
$scope.onChange(); $scope.onChange();
}; };
$scope.transformToSegments = addTemplateVars => { $scope.transformToSegments = (addTemplateVars: any) => {
return results => { return (results: any) => {
const segments = _.map(results, segment => { const segments = _.map(results, segment => {
return uiSegmentSrv.newSegment({ return uiSegmentSrv.newSegment({
value: segment.text, value: segment.text,
......
...@@ -32,7 +32,7 @@ describe('CloudWatchDatasource', () => { ...@@ -32,7 +32,7 @@ describe('CloudWatchDatasource', () => {
} as any; } as any;
beforeEach(() => { beforeEach(() => {
ctx.ds = new CloudWatchDatasource(instanceSettings, {}, backendSrv, templateSrv, timeSrv); ctx.ds = new CloudWatchDatasource(instanceSettings, {} as any, backendSrv, templateSrv, timeSrv);
}); });
describe('When performing CloudWatch query', () => { describe('When performing CloudWatch query', () => {
...@@ -56,7 +56,7 @@ describe('CloudWatchDatasource', () => { ...@@ -56,7 +56,7 @@ describe('CloudWatchDatasource', () => {
], ],
}; };
const response = { const response: any = {
timings: [null], timings: [null],
results: { results: {
A: { A: {
...@@ -156,7 +156,7 @@ describe('CloudWatchDatasource', () => { ...@@ -156,7 +156,7 @@ describe('CloudWatchDatasource', () => {
}); });
it('should return series list', done => { it('should return series list', done => {
ctx.ds.query(query).then(result => { ctx.ds.query(query).then((result: any) => {
expect(result.data[0].target).toBe(response.results.A.series[0].name); expect(result.data[0].target).toBe(response.results.A.series[0].name);
expect(result.data[0].datapoints[0][0]).toBe(response.results.A.series[0].points[0][0]); expect(result.data[0].datapoints[0][0]).toBe(response.results.A.series[0].points[0][0]);
done(); done();
...@@ -204,7 +204,7 @@ describe('CloudWatchDatasource', () => { ...@@ -204,7 +204,7 @@ describe('CloudWatchDatasource', () => {
], ],
}; };
ctx.ds.query(query).then(result => { ctx.ds.query(query).then((result: any) => {
expect(requestParams.queries[0].region).toBe(instanceSettings.jsonData.defaultRegion); expect(requestParams.queries[0].region).toBe(instanceSettings.jsonData.defaultRegion);
done(); done();
}); });
...@@ -231,7 +231,7 @@ describe('CloudWatchDatasource', () => { ...@@ -231,7 +231,7 @@ describe('CloudWatchDatasource', () => {
], ],
}; };
const response = { const response: any = {
timings: [null], timings: [null],
results: { results: {
A: { A: {
...@@ -259,7 +259,7 @@ describe('CloudWatchDatasource', () => { ...@@ -259,7 +259,7 @@ describe('CloudWatchDatasource', () => {
}); });
it('should return series list', done => { it('should return series list', done => {
ctx.ds.query(query).then(result => { ctx.ds.query(query).then((result: any) => {
expect(result.data[0].target).toBe(response.results.A.series[0].name); expect(result.data[0].target).toBe(response.results.A.series[0].name);
expect(result.data[0].datapoints[0][0]).toBe(response.results.A.series[0].points[0][0]); expect(result.data[0].datapoints[0][0]).toBe(response.results.A.series[0].points[0][0]);
done(); done();
...@@ -411,7 +411,7 @@ describe('CloudWatchDatasource', () => { ...@@ -411,7 +411,7 @@ describe('CloudWatchDatasource', () => {
}); });
it('should generate the correct query for multilple template variables with expression', done => { it('should generate the correct query for multilple template variables with expression', done => {
const query = { const query: any = {
range: { from: 'now-1h', to: 'now' }, range: { from: 'now-1h', to: 'now' },
rangeRaw: { from: 1483228800, to: 1483232400 }, rangeRaw: { from: 1483228800, to: 1483232400 },
targets: [ targets: [
...@@ -466,17 +466,17 @@ describe('CloudWatchDatasource', () => { ...@@ -466,17 +466,17 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
function describeMetricFindQuery(query, func) { function describeMetricFindQuery(query: any, func: any) {
describe('metricFindQuery ' + query, () => { describe('metricFindQuery ' + query, () => {
const scenario: any = {}; const scenario: any = {};
scenario.setup = setupCallback => { scenario.setup = (setupCallback: any) => {
beforeEach(() => { beforeEach(() => {
setupCallback(); setupCallback();
ctx.backendSrv.datasourceRequest = jest.fn(args => { ctx.backendSrv.datasourceRequest = jest.fn(args => {
scenario.request = args.data; scenario.request = args.data;
return Promise.resolve({ data: scenario.requestResponse }); return Promise.resolve({ data: scenario.requestResponse });
}); });
ctx.ds.metricFindQuery(query).then(args => { ctx.ds.metricFindQuery(query).then((args: any) => {
scenario.result = args; scenario.result = args;
}); });
}); });
...@@ -486,7 +486,7 @@ describe('CloudWatchDatasource', () => { ...@@ -486,7 +486,7 @@ describe('CloudWatchDatasource', () => {
}); });
} }
describeMetricFindQuery('regions()', scenario => { describeMetricFindQuery('regions()', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
...@@ -504,7 +504,7 @@ describe('CloudWatchDatasource', () => { ...@@ -504,7 +504,7 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
describeMetricFindQuery('namespaces()', scenario => { describeMetricFindQuery('namespaces()', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
...@@ -522,7 +522,7 @@ describe('CloudWatchDatasource', () => { ...@@ -522,7 +522,7 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
describeMetricFindQuery('metrics(AWS/EC2)', scenario => { describeMetricFindQuery('metrics(AWS/EC2)', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
...@@ -540,7 +540,7 @@ describe('CloudWatchDatasource', () => { ...@@ -540,7 +540,7 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
describeMetricFindQuery('dimension_keys(AWS/EC2)', scenario => { describeMetricFindQuery('dimension_keys(AWS/EC2)', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
...@@ -558,7 +558,7 @@ describe('CloudWatchDatasource', () => { ...@@ -558,7 +558,7 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
describeMetricFindQuery('dimension_values(us-east-1,AWS/EC2,CPUUtilization,InstanceId)', scenario => { describeMetricFindQuery('dimension_values(us-east-1,AWS/EC2,CPUUtilization,InstanceId)', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
...@@ -576,7 +576,7 @@ describe('CloudWatchDatasource', () => { ...@@ -576,7 +576,7 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
describeMetricFindQuery('dimension_values(default,AWS/EC2,CPUUtilization,InstanceId)', scenario => { describeMetricFindQuery('dimension_values(default,AWS/EC2,CPUUtilization,InstanceId)', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
...@@ -594,7 +594,7 @@ describe('CloudWatchDatasource', () => { ...@@ -594,7 +594,7 @@ describe('CloudWatchDatasource', () => {
}); });
}); });
describeMetricFindQuery('resource_arns(default,ec2:instance,{"environment":["production"]})', scenario => { describeMetricFindQuery('resource_arns(default,ec2:instance,{"environment":["production"]})', (scenario: any) => {
scenario.setup(() => { scenario.setup(() => {
scenario.requestResponse = { scenario.requestResponse = {
results: { results: {
......
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import _ from 'lodash'; import _ from 'lodash';
import * as queryDef from './query_def'; import * as queryDef from './query_def';
import { IQService } from 'angular';
export class ElasticBucketAggCtrl { export class ElasticBucketAggCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope, uiSegmentSrv, $q, $rootScope) { constructor($scope: any, uiSegmentSrv: any, $q: IQService, $rootScope: any) {
const bucketAggs = $scope.target.bucketAggs; const bucketAggs = $scope.target.bucketAggs;
$scope.orderByOptions = []; $scope.orderByOptions = [];
...@@ -158,7 +159,7 @@ export class ElasticBucketAggCtrl { ...@@ -158,7 +159,7 @@ export class ElasticBucketAggCtrl {
$scope.agg.settings.filters.push({ query: '*' }); $scope.agg.settings.filters.push({ query: '*' });
}; };
$scope.removeFiltersQuery = filter => { $scope.removeFiltersQuery = (filter: any) => {
$scope.agg.settings.filters = _.without($scope.agg.settings.filters, filter); $scope.agg.settings.filters = _.without($scope.agg.settings.filters, filter);
}; };
......
...@@ -8,7 +8,7 @@ export class ElasticConfigCtrl { ...@@ -8,7 +8,7 @@ export class ElasticConfigCtrl {
current: DataSourceInstanceSettings<ElasticsearchOptions>; current: DataSourceInstanceSettings<ElasticsearchOptions>;
/** @ngInject */ /** @ngInject */
constructor($scope) { constructor($scope: any) {
this.current.jsonData.timeField = this.current.jsonData.timeField || '@timestamp'; this.current.jsonData.timeField = this.current.jsonData.timeField || '@timestamp';
this.current.jsonData.esVersion = this.current.jsonData.esVersion || 5; this.current.jsonData.esVersion = this.current.jsonData.esVersion || 5;
const defaultMaxConcurrentShardRequests = this.current.jsonData.esVersion >= 70 ? 5 : 256; const defaultMaxConcurrentShardRequests = this.current.jsonData.esVersion >= 70 ? 5 : 256;
...@@ -18,7 +18,7 @@ export class ElasticConfigCtrl { ...@@ -18,7 +18,7 @@ export class ElasticConfigCtrl {
this.current.jsonData.logLevelField = this.current.jsonData.logLevelField || ''; this.current.jsonData.logLevelField = this.current.jsonData.logLevelField || '';
} }
indexPatternTypes = [ indexPatternTypes: any = [
{ name: 'No pattern', value: undefined }, { name: 'No pattern', value: undefined },
{ name: 'Hourly', value: 'Hourly', example: '[logstash-]YYYY.MM.DD.HH' }, { name: 'Hourly', value: 'Hourly', example: '[logstash-]YYYY.MM.DD.HH' },
{ name: 'Daily', value: 'Daily', example: '[logstash-]YYYY.MM.DD' }, { name: 'Daily', value: 'Daily', example: '[logstash-]YYYY.MM.DD' },
......
...@@ -63,7 +63,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -63,7 +63,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
} }
} }
private request(method, url, data?) { private request(method: string, url: string, data?: undefined) {
const options: any = { const options: any = {
url: this.url + '/' + url, url: this.url + '/' + url,
method: method, method: method,
...@@ -82,29 +82,29 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -82,29 +82,29 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
return this.backendSrv.datasourceRequest(options); return this.backendSrv.datasourceRequest(options);
} }
private get(url) { private get(url: string) {
const range = this.timeSrv.timeRange(); const range = this.timeSrv.timeRange();
const indexList = this.indexPattern.getIndexList(range.from.valueOf(), range.to.valueOf()); const indexList = this.indexPattern.getIndexList(range.from.valueOf(), range.to.valueOf());
if (_.isArray(indexList) && indexList.length) { if (_.isArray(indexList) && indexList.length) {
return this.request('GET', indexList[0] + url).then(results => { return this.request('GET', indexList[0] + url).then((results: any) => {
results.data.$$config = results.config; results.data.$$config = results.config;
return results.data; return results.data;
}); });
} else { } else {
return this.request('GET', this.indexPattern.getIndexForToday() + url).then(results => { return this.request('GET', this.indexPattern.getIndexForToday() + url).then((results: any) => {
results.data.$$config = results.config; results.data.$$config = results.config;
return results.data; return results.data;
}); });
} }
} }
private post(url, data) { private post(url: string, data: any) {
return this.request('POST', url, data) return this.request('POST', url, data)
.then(results => { .then((results: any) => {
results.data.$$config = results.config; results.data.$$config = results.config;
return results.data; return results.data;
}) })
.catch(err => { .catch((err: any) => {
if (err.data && err.data.error) { if (err.data && err.data.error) {
throw { throw {
message: 'Elasticsearch error: ' + err.data.error.reason, message: 'Elasticsearch error: ' + err.data.error.reason,
...@@ -116,14 +116,14 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -116,14 +116,14 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
}); });
} }
annotationQuery(options) { annotationQuery(options: any) {
const annotation = options.annotation; const annotation = options.annotation;
const timeField = annotation.timeField || '@timestamp'; const timeField = annotation.timeField || '@timestamp';
const queryString = annotation.query || '*'; const queryString = annotation.query || '*';
const tagsField = annotation.tagsField || 'tags'; const tagsField = annotation.tagsField || 'tags';
const textField = annotation.textField || null; const textField = annotation.textField || null;
const range = {}; const range: any = {};
range[timeField] = { range[timeField] = {
from: options.range.from.valueOf(), from: options.range.from.valueOf(),
to: options.range.to.valueOf(), to: options.range.to.valueOf(),
...@@ -144,8 +144,8 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -144,8 +144,8 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
}, },
}; };
const data = { const data: any = {
query: query, query,
size: 10000, size: 10000,
}; };
...@@ -168,11 +168,11 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -168,11 +168,11 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
const 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: any) => {
const list = []; const list = [];
const hits = res.responses[0].hits.hits; const hits = res.responses[0].hits.hits;
const getFieldFromSource = (source, fieldName) => { const getFieldFromSource = (source: any, fieldName: any) => {
if (!fieldName) { if (!fieldName) {
return; return;
} }
...@@ -229,7 +229,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -229,7 +229,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
testDatasource() { testDatasource() {
// 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(
dateFields => { (dateFields: any) => {
const timeField: any = _.find(dateFields, { text: this.timeField }); const timeField: any = _.find(dateFields, { text: this.timeField });
if (!timeField) { if (!timeField) {
return { return {
...@@ -239,7 +239,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -239,7 +239,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
} }
return { status: 'success', message: 'Index OK. Time field name OK.' }; return { status: 'success', message: 'Index OK. Time field name OK.' };
}, },
err => { (err: any) => {
console.log(err); console.log(err);
if (err.data && err.data.error) { if (err.data && err.data.error) {
let message = angular.toJson(err.data.error); let message = angular.toJson(err.data.error);
...@@ -254,7 +254,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -254,7 +254,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
); );
} }
getQueryHeader(searchType, timeFrom, timeTo) { getQueryHeader(searchType: any, timeFrom: any, timeTo: any) {
const queryHeader: any = { const queryHeader: any = {
search_type: searchType, search_type: searchType,
ignore_unavailable: true, ignore_unavailable: true,
...@@ -319,7 +319,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -319,7 +319,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
const url = this.getMultiSearchUrl(); const url = this.getMultiSearchUrl();
return this.post(url, payload).then(res => { return this.post(url, payload).then((res: any) => {
const er = new ElasticResponse(sentTargets, res); const er = new ElasticResponse(sentTargets, res);
if (sentTargets.some(target => target.isLogsQuery)) { if (sentTargets.some(target => target.isLogsQuery)) {
return er.getLogs(this.logMessageField, this.logLevelField); return er.getLogs(this.logMessageField, this.logLevelField);
...@@ -329,10 +329,10 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -329,10 +329,10 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
}); });
} }
getFields(query) { getFields(query: any) {
const configuredEsVersion = this.esVersion; const configuredEsVersion = this.esVersion;
return this.get('/_mapping').then(result => { return this.get('/_mapping').then((result: any) => {
const typeMap = { const typeMap: any = {
float: 'number', float: 'number',
double: 'number', double: 'number',
integer: 'number', integer: 'number',
...@@ -344,7 +344,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -344,7 +344,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
nested: 'nested', nested: 'nested',
}; };
function shouldAddField(obj, key, query) { function shouldAddField(obj: any, key: any, query: any) {
if (key[0] === '_') { if (key[0] === '_') {
return false; return false;
} }
...@@ -358,10 +358,10 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -358,10 +358,10 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
} }
// Store subfield names: [system, process, cpu, total] -> system.process.cpu.total // Store subfield names: [system, process, cpu, total] -> system.process.cpu.total
const fieldNameParts = []; const fieldNameParts: any = [];
const fields = {}; const fields: any = {};
function getFieldsRecursively(obj) { function getFieldsRecursively(obj: any) {
for (const key in obj) { for (const key in obj) {
const subObj = obj[key]; const subObj = obj[key];
...@@ -415,7 +415,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -415,7 +415,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
}); });
} }
getTerms(queryDef) { getTerms(queryDef: any) {
const range = this.timeSrv.timeRange(); const range = this.timeSrv.timeRange();
const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count'; const searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count';
const header = this.getQueryHeader(searchType, range.from, range.to); const header = this.getQueryHeader(searchType, range.from, range.to);
...@@ -427,7 +427,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -427,7 +427,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
const url = this.getMultiSearchUrl(); const url = this.getMultiSearchUrl();
return this.post(url, esQuery).then(res => { return this.post(url, esQuery).then((res: any) => {
if (!res.responses[0].aggregations) { if (!res.responses[0].aggregations) {
return []; return [];
} }
...@@ -450,7 +450,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -450,7 +450,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
return '_msearch'; return '_msearch';
} }
metricFindQuery(query) { metricFindQuery(query: any) {
query = angular.fromJson(query); query = angular.fromJson(query);
if (!query) { if (!query) {
return this.$q.when([]); return this.$q.when([]);
...@@ -472,11 +472,11 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -472,11 +472,11 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
return this.getFields({}); return this.getFields({});
} }
getTagValues(options) { getTagValues(options: any) {
return this.getTerms({ field: options.key, query: '*' }); return this.getTerms({ field: options.key, query: '*' });
} }
targetContainsTemplate(target) { targetContainsTemplate(target: any) {
if (this.templateSrv.variableExists(target.query) || this.templateSrv.variableExists(target.alias)) { if (this.templateSrv.variableExists(target.query) || this.templateSrv.variableExists(target.alias)) {
return true; return true;
} }
...@@ -500,7 +500,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -500,7 +500,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
return false; return false;
} }
private isPrimitive(obj) { private isPrimitive(obj: any) {
if (obj === null || obj === undefined) { if (obj === null || obj === undefined) {
return true; return true;
} }
...@@ -511,7 +511,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic ...@@ -511,7 +511,7 @@ export class ElasticDatasource extends DataSourceApi<ElasticsearchQuery, Elastic
return false; return false;
} }
private objectContainsTemplate(obj) { private objectContainsTemplate(obj: any) {
if (!obj) { if (!obj) {
return false; return false;
} }
......
...@@ -4,14 +4,15 @@ import * as queryDef from './query_def'; ...@@ -4,14 +4,15 @@ import * as queryDef from './query_def';
import TableModel from 'app/core/table_model'; import TableModel from 'app/core/table_model';
import { DataFrame, toDataFrame, FieldType } from '@grafana/data'; import { DataFrame, toDataFrame, FieldType } from '@grafana/data';
import { DataQueryResponse } from '@grafana/ui'; import { DataQueryResponse } from '@grafana/ui';
import { ElasticsearchAggregation } from './types';
export class ElasticResponse { export class ElasticResponse {
constructor(private targets, private response) { constructor(private targets: any, private response: any) {
this.targets = targets; this.targets = targets;
this.response = response; this.response = response;
} }
processMetrics(esAgg, target, seriesList, props) { processMetrics(esAgg: any, target: any, seriesList: any, props: any) {
let metric, y, i, newSeries, bucket, value; let metric, y, i, newSeries, bucket, value;
for (y = 0; y < target.metrics.length; y++) { for (y = 0; y < target.metrics.length; y++) {
...@@ -113,7 +114,7 @@ export class ElasticResponse { ...@@ -113,7 +114,7 @@ export class ElasticResponse {
} }
} }
processAggregationDocs(esAgg, aggDef, target, table, props) { processAggregationDocs(esAgg: any, aggDef: ElasticsearchAggregation, target: any, table: any, props: any) {
// add columns // add columns
if (table.columns.length === 0) { if (table.columns.length === 0) {
for (const propKey of _.keys(props)) { for (const propKey of _.keys(props)) {
...@@ -123,7 +124,7 @@ export class ElasticResponse { ...@@ -123,7 +124,7 @@ export class ElasticResponse {
} }
// helper func to add values to value array // helper func to add values to value array
const addMetricValue = (values, metricName, value) => { const addMetricValue = (values: any[], metricName: string, value: any) => {
table.addColumn({ text: metricName }); table.addColumn({ text: metricName });
values.push(value); values.push(value);
}; };
...@@ -188,8 +189,8 @@ export class ElasticResponse { ...@@ -188,8 +189,8 @@ export class ElasticResponse {
// This is quite complex // This is quite complex
// need to recurse down the nested buckets to build series // need to recurse down the nested buckets to build series
processBuckets(aggs, target, seriesList, table, props, depth) { processBuckets(aggs: any, target: any, seriesList: any, table: any, props: any, depth: any) {
let bucket, aggDef, esAgg, aggId; let bucket, aggDef: any, esAgg, aggId;
const maxDepth = target.bucketAggs.length - 1; const maxDepth = target.bucketAggs.length - 1;
for (aggId in aggs) { for (aggId in aggs) {
...@@ -224,7 +225,7 @@ export class ElasticResponse { ...@@ -224,7 +225,7 @@ export class ElasticResponse {
} }
} }
private getMetricName(metric) { private getMetricName(metric: any) {
let metricDef: any = _.find(queryDef.metricAggTypes, { value: metric }); let metricDef: any = _.find(queryDef.metricAggTypes, { value: metric });
if (!metricDef) { if (!metricDef) {
metricDef = _.find(queryDef.extendedStats, { value: metric }); metricDef = _.find(queryDef.extendedStats, { value: metric });
...@@ -233,13 +234,13 @@ export class ElasticResponse { ...@@ -233,13 +234,13 @@ export class ElasticResponse {
return metricDef ? metricDef.text : metric; return metricDef ? metricDef.text : metric;
} }
private getSeriesName(series, target, metricTypeCount) { private getSeriesName(series: any, target: any, metricTypeCount: any) {
let metricName = this.getMetricName(series.metric); let metricName = this.getMetricName(series.metric);
if (target.alias) { if (target.alias) {
const regex = /\{\{([\s\S]+?)\}\}/g; const regex = /\{\{([\s\S]+?)\}\}/g;
return target.alias.replace(regex, (match, g1, g2) => { return target.alias.replace(regex, (match: any, g1: any, g2: any) => {
const group = g1 || g2; const group = g1 || g2;
if (group.indexOf('term ') === 0) { if (group.indexOf('term ') === 0) {
...@@ -303,7 +304,7 @@ export class ElasticResponse { ...@@ -303,7 +304,7 @@ export class ElasticResponse {
return name.trim() + ' ' + metricName; return name.trim() + ' ' + metricName;
} }
nameSeries(seriesList, target) { nameSeries(seriesList: any, target: any) {
const metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length; const metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length;
for (let i = 0; i < seriesList.length; i++) { for (let i = 0; i < seriesList.length; i++) {
...@@ -312,17 +313,17 @@ export class ElasticResponse { ...@@ -312,17 +313,17 @@ export class ElasticResponse {
} }
} }
processHits(hits, seriesList) { processHits(hits: { total: { value: any }; hits: any[] }, seriesList: any[]) {
const hitsTotal = typeof hits.total === 'number' ? hits.total : hits.total.value; // <- Works with Elasticsearch 7.0+ const hitsTotal = typeof hits.total === 'number' ? hits.total : hits.total.value; // <- Works with Elasticsearch 7.0+
const series = { const series: any = {
target: 'docs', target: 'docs',
type: 'docs', type: 'docs',
datapoints: [], datapoints: [],
total: hitsTotal, total: hitsTotal,
filterable: true, filterable: true,
}; };
let propName, hit, doc, i; let propName, hit, doc: any, i;
for (i = 0; i < hits.hits.length; i++) { for (i = 0; i < hits.hits.length; i++) {
hit = hits.hits[i]; hit = hits.hits[i];
...@@ -347,7 +348,7 @@ export class ElasticResponse { ...@@ -347,7 +348,7 @@ export class ElasticResponse {
seriesList.push(series); seriesList.push(series);
} }
trimDatapoints(aggregations, target) { trimDatapoints(aggregations: any, target: any) {
const histogram: any = _.find(target.bucketAggs, { type: 'date_histogram' }); const histogram: any = _.find(target.bucketAggs, { type: 'date_histogram' });
const shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges; const shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges;
...@@ -362,7 +363,7 @@ export class ElasticResponse { ...@@ -362,7 +363,7 @@ export class ElasticResponse {
} }
} }
getErrorFromElasticResponse(response, err) { getErrorFromElasticResponse(response: any, err: any) {
const 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) {
...@@ -394,7 +395,7 @@ export class ElasticResponse { ...@@ -394,7 +395,7 @@ export class ElasticResponse {
if (response.aggregations) { if (response.aggregations) {
const aggregations = response.aggregations; const aggregations = response.aggregations;
const target = this.targets[i]; const target = this.targets[i];
const tmpSeriesList = []; const tmpSeriesList: any[] = [];
const table = new TableModel(); const table = new TableModel();
this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0); this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);
...@@ -426,7 +427,7 @@ export class ElasticResponse { ...@@ -426,7 +427,7 @@ export class ElasticResponse {
const hits = response.hits; const hits = response.hits;
let propNames: string[] = []; let propNames: string[] = [];
let propName, hit, doc, i; let propName, hit, doc: any, i;
for (i = 0; i < hits.hits.length; i++) { for (i = 0; i < hits.hits.length; i++) {
hit = hits.hits[i]; hit = hits.hits[i];
...@@ -534,7 +535,7 @@ export class ElasticResponse { ...@@ -534,7 +535,7 @@ export class ElasticResponse {
if (response.aggregations) { if (response.aggregations) {
const aggregations = response.aggregations; const aggregations = response.aggregations;
const target = this.targets[n]; const target = this.targets[n];
const tmpSeriesList = []; const tmpSeriesList: any[] = [];
const table = new TableModel(); const table = new TableModel();
this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0); this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);
......
import { toUtc, dateTime } from '@grafana/data'; import { toUtc, dateTime } from '@grafana/data';
const intervalMap = { const intervalMap: any = {
Hourly: { startOf: 'hour', amount: 'hours' }, Hourly: { startOf: 'hour', amount: 'hours' },
Daily: { startOf: 'day', amount: 'days' }, Daily: { startOf: 'day', amount: 'days' },
Weekly: { startOf: 'isoWeek', amount: 'weeks' }, Weekly: { startOf: 'isoWeek', amount: 'weeks' },
...@@ -9,7 +9,7 @@ const intervalMap = { ...@@ -9,7 +9,7 @@ const intervalMap = {
}; };
export class IndexPattern { export class IndexPattern {
constructor(private pattern, private interval: string | null) {} constructor(private pattern: any, private interval: string | null) {}
getIndexForToday() { getIndexForToday() {
if (this.interval) { if (this.interval) {
...@@ -19,7 +19,7 @@ export class IndexPattern { ...@@ -19,7 +19,7 @@ export class IndexPattern {
} }
} }
getIndexList(from, to) { getIndexList(from: any, to: any) {
if (!this.interval) { if (!this.interval) {
return this.pattern; return this.pattern;
} }
......
...@@ -2,10 +2,11 @@ import coreModule from 'app/core/core_module'; ...@@ -2,10 +2,11 @@ import coreModule from 'app/core/core_module';
import _ from 'lodash'; import _ from 'lodash';
import * as queryDef from './query_def'; import * as queryDef from './query_def';
import { ElasticsearchAggregation } from './types'; import { ElasticsearchAggregation } from './types';
import { IQService } from 'angular';
export class ElasticMetricAggCtrl { export class ElasticMetricAggCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope, uiSegmentSrv, $q, $rootScope) { constructor($scope: any, uiSegmentSrv: any, $q: IQService, $rootScope: any) {
const metricAggs: ElasticsearchAggregation[] = $scope.target.metrics; const metricAggs: ElasticsearchAggregation[] = $scope.target.metrics;
$scope.metricAggTypes = queryDef.getMetricAggTypes($scope.esVersion); $scope.metricAggTypes = queryDef.getMetricAggTypes($scope.esVersion);
$scope.extendedStats = queryDef.extendedStats; $scope.extendedStats = queryDef.extendedStats;
......
...@@ -14,7 +14,7 @@ export function elasticPipelineVariables() { ...@@ -14,7 +14,7 @@ export function elasticPipelineVariables() {
}; };
} }
const newVariable = index => { const newVariable = (index: any) => {
return { return {
name: 'var' + index, name: 'var' + index,
pipelineAgg: 'select metric', pipelineAgg: 'select metric',
...@@ -23,7 +23,7 @@ const newVariable = index => { ...@@ -23,7 +23,7 @@ const newVariable = index => {
export class ElasticPipelineVariablesCtrl { export class ElasticPipelineVariablesCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope) { constructor($scope: any) {
$scope.variables = $scope.variables || [newVariable(1)]; $scope.variables = $scope.variables || [newVariable(1)];
$scope.onChangeInternal = () => { $scope.onChangeInternal = () => {
...@@ -35,7 +35,7 @@ export class ElasticPipelineVariablesCtrl { ...@@ -35,7 +35,7 @@ export class ElasticPipelineVariablesCtrl {
$scope.onChange(); $scope.onChange();
}; };
$scope.remove = index => { $scope.remove = (index: number) => {
$scope.variables.splice(index, 1); $scope.variables.splice(index, 1);
$scope.onChange(); $scope.onChange();
}; };
......
import * as queryDef from './query_def'; import * as queryDef from './query_def';
import { ElasticsearchAggregation } from './types';
export class ElasticQueryBuilder { export class ElasticQueryBuilder {
timeField: string; timeField: string;
esVersion: number; esVersion: number;
constructor(options) { constructor(options: any) {
this.timeField = options.timeField; this.timeField = options.timeField;
this.esVersion = options.esVersion; this.esVersion = options.esVersion;
} }
getRangeFilter() { getRangeFilter() {
const filter = {}; const filter: any = {};
filter[this.timeField] = { filter[this.timeField] = {
gte: '$timeFrom', gte: '$timeFrom',
lte: '$timeTo', lte: '$timeTo',
...@@ -20,7 +21,7 @@ export class ElasticQueryBuilder { ...@@ -20,7 +21,7 @@ export class ElasticQueryBuilder {
return filter; return filter;
} }
buildTermsAgg(aggDef, queryNode, target) { buildTermsAgg(aggDef: ElasticsearchAggregation, queryNode: { terms?: any; aggs?: any }, target: { metrics: any[] }) {
let metricRef, metric, y; let metricRef, metric, y;
queryNode.terms = { field: aggDef.field }; queryNode.terms = { field: aggDef.field };
...@@ -63,7 +64,7 @@ export class ElasticQueryBuilder { ...@@ -63,7 +64,7 @@ export class ElasticQueryBuilder {
return queryNode; return queryNode;
} }
getDateHistogramAgg(aggDef) { getDateHistogramAgg(aggDef: ElasticsearchAggregation) {
const esAgg: any = {}; const esAgg: any = {};
const settings = aggDef.settings || {}; const settings = aggDef.settings || {};
esAgg.interval = settings.interval; esAgg.interval = settings.interval;
...@@ -87,7 +88,7 @@ export class ElasticQueryBuilder { ...@@ -87,7 +88,7 @@ export class ElasticQueryBuilder {
return esAgg; return esAgg;
} }
getHistogramAgg(aggDef) { getHistogramAgg(aggDef: ElasticsearchAggregation) {
const esAgg: any = {}; const esAgg: any = {};
const settings = aggDef.settings || {}; const settings = aggDef.settings || {};
esAgg.interval = settings.interval; esAgg.interval = settings.interval;
...@@ -100,8 +101,8 @@ export class ElasticQueryBuilder { ...@@ -100,8 +101,8 @@ export class ElasticQueryBuilder {
return esAgg; return esAgg;
} }
getFiltersAgg(aggDef) { getFiltersAgg(aggDef: ElasticsearchAggregation) {
const filterObj = {}; const filterObj: any = {};
for (let i = 0; i < aggDef.settings.filters.length; i++) { for (let i = 0; i < aggDef.settings.filters.length; i++) {
const query = aggDef.settings.filters[i].query; const query = aggDef.settings.filters[i].query;
let label = aggDef.settings.filters[i].label; let label = aggDef.settings.filters[i].label;
...@@ -117,7 +118,7 @@ export class ElasticQueryBuilder { ...@@ -117,7 +118,7 @@ export class ElasticQueryBuilder {
return filterObj; return filterObj;
} }
documentQuery(query, size) { documentQuery(query: any, size: number) {
query.size = size; query.size = size;
query.sort = {}; query.sort = {};
query.sort[this.timeField] = { order: 'desc', unmapped_type: 'boolean' }; query.sort[this.timeField] = { order: 'desc', unmapped_type: 'boolean' };
...@@ -136,12 +137,12 @@ export class ElasticQueryBuilder { ...@@ -136,12 +137,12 @@ export class ElasticQueryBuilder {
return query; return query;
} }
addAdhocFilters(query, adhocFilters) { addAdhocFilters(query: any, adhocFilters: any) {
if (!adhocFilters) { if (!adhocFilters) {
return; return;
} }
let i, filter, condition, queryCondition; let i, filter, condition: any, queryCondition: any;
for (i = 0; i < adhocFilters.length; i++) { for (i = 0; i < adhocFilters.length; i++) {
filter = adhocFilters[i]; filter = adhocFilters[i];
...@@ -183,7 +184,7 @@ export class ElasticQueryBuilder { ...@@ -183,7 +184,7 @@ export class ElasticQueryBuilder {
} }
} }
build(target, adhocFilters?, queryString?) { build(target: any, adhocFilters?: any, queryString?: string) {
// make sure query has defaults; // make sure query has defaults;
target.metrics = target.metrics || [queryDef.defaultMetricAgg()]; target.metrics = target.metrics || [queryDef.defaultMetricAgg()];
target.bucketAggs = target.bucketAggs || [queryDef.defaultBucketAgg()]; target.bucketAggs = target.bucketAggs || [queryDef.defaultBucketAgg()];
...@@ -224,7 +225,7 @@ export class ElasticQueryBuilder { ...@@ -224,7 +225,7 @@ export class ElasticQueryBuilder {
for (i = 0; i < target.bucketAggs.length; i++) { for (i = 0; i < target.bucketAggs.length; i++) {
const aggDef = target.bucketAggs[i]; const aggDef = target.bucketAggs[i];
const esAgg = {}; const esAgg: any = {};
switch (aggDef.type) { switch (aggDef.type) {
case 'date_histogram': { case 'date_histogram': {
...@@ -265,8 +266,8 @@ export class ElasticQueryBuilder { ...@@ -265,8 +266,8 @@ export class ElasticQueryBuilder {
continue; continue;
} }
const aggField = {}; const aggField: any = {};
let metricAgg = null; let metricAgg: any = null;
if (queryDef.isPipelineAgg(metric.type)) { if (queryDef.isPipelineAgg(metric.type)) {
if (queryDef.isPipelineAggWithMultipleBucketPaths(metric.type)) { if (queryDef.isPipelineAggWithMultipleBucketPaths(metric.type)) {
...@@ -323,7 +324,7 @@ export class ElasticQueryBuilder { ...@@ -323,7 +324,7 @@ export class ElasticQueryBuilder {
return query; return query;
} }
getTermsQuery(queryDef) { getTermsQuery(queryDef: any) {
const query: any = { const query: any = {
size: 0, size: 0,
query: { query: {
...@@ -368,7 +369,7 @@ export class ElasticQueryBuilder { ...@@ -368,7 +369,7 @@ export class ElasticQueryBuilder {
return query; return query;
} }
getLogsQuery(target, querystring) { getLogsQuery(target: any, querystring: string) {
let query: any = { let query: any = {
size: 0, size: 0,
query: { query: {
......
...@@ -2,7 +2,7 @@ import './bucket_agg'; ...@@ -2,7 +2,7 @@ import './bucket_agg';
import './metric_agg'; import './metric_agg';
import './pipeline_variables'; import './pipeline_variables';
import angular from 'angular'; import angular, { auto } from 'angular';
import _ from 'lodash'; import _ from 'lodash';
import * as queryDef from './query_def'; import * as queryDef from './query_def';
import { QueryCtrl } from 'app/plugins/sdk'; import { QueryCtrl } from 'app/plugins/sdk';
...@@ -15,7 +15,7 @@ export class ElasticQueryCtrl extends QueryCtrl { ...@@ -15,7 +15,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
rawQueryOld: string; rawQueryOld: string;
/** @ngInject */ /** @ngInject */
constructor($scope, $injector, private $rootScope, private uiSegmentSrv) { constructor($scope: any, $injector: auto.IInjectorService, private $rootScope: any, private uiSegmentSrv: any) {
super($scope, $injector); super($scope, $injector);
this.esVersion = this.datasource.esVersion; this.esVersion = this.datasource.esVersion;
...@@ -35,7 +35,7 @@ export class ElasticQueryCtrl extends QueryCtrl { ...@@ -35,7 +35,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
this.queryUpdated(); this.queryUpdated();
} }
getFields(type) { getFields(type: any) {
const 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)
...@@ -98,7 +98,7 @@ export class ElasticQueryCtrl extends QueryCtrl { ...@@ -98,7 +98,7 @@ export class ElasticQueryCtrl extends QueryCtrl {
return text; return text;
} }
handleQueryError(err) { handleQueryError(err: any): any[] {
this.error = err.message || 'Failed to issue metric query'; this.error = err.message || 'Failed to issue metric query';
return []; return [];
} }
......
...@@ -128,7 +128,7 @@ export const movingAvgModelOptions = [ ...@@ -128,7 +128,7 @@ export const movingAvgModelOptions = [
{ text: 'Holt Winters', value: 'holt_winters' }, { text: 'Holt Winters', value: 'holt_winters' },
]; ];
export const pipelineOptions = { export const pipelineOptions: any = {
moving_avg: [ moving_avg: [
{ text: 'window', default: 5 }, { text: 'window', default: 5 },
{ text: 'model', default: 'simple' }, { text: 'model', default: 'simple' },
...@@ -139,7 +139,7 @@ export const pipelineOptions = { ...@@ -139,7 +139,7 @@ export const pipelineOptions = {
bucket_script: [], bucket_script: [],
}; };
export const movingAvgModelSettings = { export const movingAvgModelSettings: any = {
simple: [], simple: [],
linear: [], linear: [],
ewma: [{ text: 'Alpha', value: 'alpha', default: undefined }], ewma: [{ text: 'Alpha', value: 'alpha', default: undefined }],
...@@ -153,7 +153,7 @@ export const movingAvgModelSettings = { ...@@ -153,7 +153,7 @@ export const movingAvgModelSettings = {
], ],
}; };
export function getMetricAggTypes(esVersion) { export function getMetricAggTypes(esVersion: any) {
return _.filter(metricAggTypes, f => { return _.filter(metricAggTypes, f => {
if (f.minVersion) { if (f.minVersion) {
return f.minVersion <= esVersion; return f.minVersion <= esVersion;
...@@ -163,7 +163,7 @@ export function getMetricAggTypes(esVersion) { ...@@ -163,7 +163,7 @@ export function getMetricAggTypes(esVersion) {
}); });
} }
export function getPipelineOptions(metric) { export function getPipelineOptions(metric: any) {
if (!isPipelineAgg(metric.type)) { if (!isPipelineAgg(metric.type)) {
return []; return [];
} }
...@@ -171,7 +171,7 @@ export function getPipelineOptions(metric) { ...@@ -171,7 +171,7 @@ export function getPipelineOptions(metric) {
return pipelineOptions[metric.type]; return pipelineOptions[metric.type];
} }
export function isPipelineAgg(metricType) { export function isPipelineAgg(metricType: any) {
if (metricType) { if (metricType) {
const po = pipelineOptions[metricType]; const po = pipelineOptions[metricType];
return po !== null && po !== undefined; return po !== null && po !== undefined;
...@@ -180,7 +180,7 @@ export function isPipelineAgg(metricType) { ...@@ -180,7 +180,7 @@ export function isPipelineAgg(metricType) {
return false; return false;
} }
export function isPipelineAggWithMultipleBucketPaths(metricType) { export function isPipelineAggWithMultipleBucketPaths(metricType: any) {
if (metricType) { if (metricType) {
return metricAggTypes.find(t => t.value === metricType && t.supportsMultipleBucketPaths) !== undefined; return metricAggTypes.find(t => t.value === metricType && t.supportsMultipleBucketPaths) !== undefined;
} }
...@@ -188,8 +188,8 @@ export function isPipelineAggWithMultipleBucketPaths(metricType) { ...@@ -188,8 +188,8 @@ export function isPipelineAggWithMultipleBucketPaths(metricType) {
return false; return false;
} }
export function getPipelineAggOptions(targets) { export function getPipelineAggOptions(targets: any) {
const result = []; const result: any[] = [];
_.each(targets.metrics, metric => { _.each(targets.metrics, 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 });
...@@ -199,8 +199,8 @@ export function getPipelineAggOptions(targets) { ...@@ -199,8 +199,8 @@ export function getPipelineAggOptions(targets) {
return result; return result;
} }
export function getMovingAvgSettings(model, filtered) { export function getMovingAvgSettings(model: any, filtered: boolean) {
const filteredResult = []; const filteredResult: any[] = [];
if (filtered) { if (filtered) {
_.each(movingAvgModelSettings[model], setting => { _.each(movingAvgModelSettings[model], setting => {
if (!setting.isCheckbox) { if (!setting.isCheckbox) {
...@@ -212,8 +212,8 @@ export function getMovingAvgSettings(model, filtered) { ...@@ -212,8 +212,8 @@ export function getMovingAvgSettings(model, filtered) {
return movingAvgModelSettings[model]; return movingAvgModelSettings[model];
} }
export function getOrderByOptions(target) { export function getOrderByOptions(target: any) {
const metricRefs = []; const metricRefs: any[] = [];
_.each(target.metrics, metric => { _.each(target.metrics, 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 });
...@@ -223,12 +223,12 @@ export function getOrderByOptions(target) { ...@@ -223,12 +223,12 @@ export function getOrderByOptions(target) {
return orderByOptions.concat(metricRefs); return orderByOptions.concat(metricRefs);
} }
export function describeOrder(order) { export function describeOrder(order: string) {
const def: any = _.find(orderOptions, { value: order }); const def: any = _.find(orderOptions, { value: order });
return def.text; return def.text;
} }
export function describeMetric(metric) { export function describeMetric(metric: { type: string; field: string }) {
const def: any = _.find(metricAggTypes, { value: metric.type }); const def: any = _.find(metricAggTypes, { value: metric.type });
if (!def.requiresField && !isPipelineAgg(metric.type)) { if (!def.requiresField && !isPipelineAgg(metric.type)) {
return def.text; return def.text;
...@@ -236,7 +236,7 @@ export function describeMetric(metric) { ...@@ -236,7 +236,7 @@ export function describeMetric(metric) {
return def.text + ' ' + metric.field; return def.text + ' ' + metric.field;
} }
export function describeOrderBy(orderBy, target) { export function describeOrderBy(orderBy: any, target: any) {
const def: any = _.find(orderByOptions, { value: orderBy }); const def: any = _.find(orderByOptions, { value: orderBy });
if (def) { if (def) {
return def.text; return def.text;
......
...@@ -69,7 +69,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -69,7 +69,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
it('should translate index pattern to current day', () => { it('should translate index pattern to current day', () => {
let requestOptions; let requestOptions: any;
ctx.backendSrv.datasourceRequest = jest.fn(options => { ctx.backendSrv.datasourceRequest = jest.fn(options => {
requestOptions = options; requestOptions = options;
return Promise.resolve({ data: {} }); return Promise.resolve({ data: {} });
...@@ -83,7 +83,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -83,7 +83,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
describe('When issuing metric query with interval pattern', () => { describe('When issuing metric query with interval pattern', () => {
let requestOptions, parts, header, query, result; let requestOptions: any, parts: any, header: any, query: any, result: any;
beforeEach(async () => { beforeEach(async () => {
createDatasource({ createDatasource({
...@@ -154,7 +154,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -154,7 +154,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
describe('When issuing logs query with interval pattern', () => { describe('When issuing logs query with interval pattern', () => {
let query, queryBuilderSpy; let query, queryBuilderSpy: any;
beforeEach(async () => { beforeEach(async () => {
createDatasource({ createDatasource({
...@@ -249,7 +249,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -249,7 +249,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
describe('When issuing document query', () => { describe('When issuing document query', () => {
let requestOptions, parts, header; let requestOptions: any, parts: any, header: any;
beforeEach(() => { beforeEach(() => {
createDatasource({ createDatasource({
...@@ -539,7 +539,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -539,7 +539,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
describe('When issuing aggregation query on es5.x', () => { describe('When issuing aggregation query on es5.x', () => {
let requestOptions, parts, header; let requestOptions: any, parts: any, header: any;
beforeEach(() => { beforeEach(() => {
createDatasource({ createDatasource({
...@@ -582,7 +582,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -582,7 +582,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
describe('When issuing metricFind query on es5.x', () => { describe('When issuing metricFind query on es5.x', () => {
let requestOptions, parts, header, body, results; let requestOptions: any, parts, header: any, body: any, results: any;
beforeEach(() => { beforeEach(() => {
createDatasource({ createDatasource({
...@@ -615,7 +615,7 @@ describe('ElasticDatasource', function(this: any) { ...@@ -615,7 +615,7 @@ describe('ElasticDatasource', function(this: any) {
}); });
}); });
ctx.ds.metricFindQuery('{"find": "terms", "field": "test"}').then(res => { ctx.ds.metricFindQuery('{"find": "terms", "field": "test"}').then((res: any) => {
results = res; results = res;
}); });
......
...@@ -2,8 +2,8 @@ import { ElasticResponse } from '../elastic_response'; ...@@ -2,8 +2,8 @@ import { ElasticResponse } from '../elastic_response';
describe('ElasticResponse', () => { describe('ElasticResponse', () => {
let targets; let targets;
let response; let response: any;
let result; let result: any;
describe('simple query and count', () => { describe('simple query and count', () => {
beforeEach(() => { beforeEach(() => {
...@@ -48,7 +48,7 @@ describe('ElasticResponse', () => { ...@@ -48,7 +48,7 @@ describe('ElasticResponse', () => {
}); });
describe('simple query count & avg aggregation', () => { describe('simple query count & avg aggregation', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -97,7 +97,7 @@ describe('ElasticResponse', () => { ...@@ -97,7 +97,7 @@ describe('ElasticResponse', () => {
}); });
describe('single group by query one metric', () => { describe('single group by query one metric', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -149,7 +149,7 @@ describe('ElasticResponse', () => { ...@@ -149,7 +149,7 @@ describe('ElasticResponse', () => {
}); });
describe('single group by query two metrics', () => { describe('single group by query two metrics', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -209,7 +209,7 @@ describe('ElasticResponse', () => { ...@@ -209,7 +209,7 @@ describe('ElasticResponse', () => {
}); });
describe('with percentiles ', () => { describe('with percentiles ', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -257,7 +257,7 @@ describe('ElasticResponse', () => { ...@@ -257,7 +257,7 @@ describe('ElasticResponse', () => {
}); });
describe('with extended_stats', () => { describe('with extended_stats', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -333,7 +333,7 @@ describe('ElasticResponse', () => { ...@@ -333,7 +333,7 @@ describe('ElasticResponse', () => {
}); });
describe('single group by with alias pattern', () => { describe('single group by with alias pattern', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -394,7 +394,7 @@ describe('ElasticResponse', () => { ...@@ -394,7 +394,7 @@ describe('ElasticResponse', () => {
}); });
describe('histogram response', () => { describe('histogram response', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -426,7 +426,7 @@ describe('ElasticResponse', () => { ...@@ -426,7 +426,7 @@ describe('ElasticResponse', () => {
}); });
describe('with two filters agg', () => { describe('with two filters agg', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -583,7 +583,7 @@ describe('ElasticResponse', () => { ...@@ -583,7 +583,7 @@ describe('ElasticResponse', () => {
}); });
describe('No group by time with percentiles ', () => { describe('No group by time with percentiles ', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -720,7 +720,7 @@ describe('ElasticResponse', () => { ...@@ -720,7 +720,7 @@ describe('ElasticResponse', () => {
}); });
describe('with bucket_script ', () => { describe('with bucket_script ', () => {
let result; let result: any;
beforeEach(() => { beforeEach(() => {
targets = [ targets = [
...@@ -861,7 +861,7 @@ describe('ElasticResponse', () => { ...@@ -861,7 +861,7 @@ describe('ElasticResponse', () => {
expect(result.data[0].fields).toContainEqual({ name: '@timestamp', type: 'time' }); expect(result.data[0].fields).toContainEqual({ name: '@timestamp', type: 'time' });
expect(result.data[0].fields).toContainEqual({ name: 'host', type: 'string' }); expect(result.data[0].fields).toContainEqual({ name: 'host', type: 'string' });
expect(result.data[0].fields).toContainEqual({ name: 'message', type: 'string' }); expect(result.data[0].fields).toContainEqual({ name: 'message', type: 'string' });
result.data[0].rows.forEach((row, i) => { result.data[0].rows.forEach((row: any, i: number) => {
expect(row).toContain(response.responses[0].hits.hits[i]._id); expect(row).toContain(response.responses[0].hits.hits[i]._id);
expect(row).toContain(response.responses[0].hits.hits[i]._type); expect(row).toContain(response.responses[0].hits.hits[i]._type);
expect(row).toContain(response.responses[0].hits.hits[i]._index); expect(row).toContain(response.responses[0].hits.hits[i]._index);
...@@ -869,7 +869,7 @@ describe('ElasticResponse', () => { ...@@ -869,7 +869,7 @@ describe('ElasticResponse', () => {
}); });
expect(result.data[1]).toHaveProperty('name', 'Count'); expect(result.data[1]).toHaveProperty('name', 'Count');
response.responses[0].aggregations['2'].buckets.forEach(bucket => { response.responses[0].aggregations['2'].buckets.forEach((bucket: any) => {
expect(result.data[1].rows).toContainEqual([bucket.doc_count, bucket.key]); expect(result.data[1].rows).toContainEqual([bucket.doc_count, bucket.key]);
}); });
}); });
......
import { ElasticQueryBuilder } from '../query_builder'; import { ElasticQueryBuilder } from '../query_builder';
describe('ElasticQueryBuilder', () => { describe('ElasticQueryBuilder', () => {
let builder; let builder: any;
beforeEach(() => { beforeEach(() => {
builder = new ElasticQueryBuilder({ timeField: '@timestamp' }); builder = new ElasticQueryBuilder({ timeField: '@timestamp' });
...@@ -103,6 +103,7 @@ describe('ElasticQueryBuilder', () => { ...@@ -103,6 +103,7 @@ describe('ElasticQueryBuilder', () => {
], ],
}, },
100, 100,
// @ts-ignore
1000 1000
); );
......
import { auto } from 'angular';
export class QueryCtrl { export class QueryCtrl {
target: any; target: any;
datasource: any; datasource: any;
...@@ -6,7 +8,7 @@ export class QueryCtrl { ...@@ -6,7 +8,7 @@ export class QueryCtrl {
hasRawMode: boolean; hasRawMode: boolean;
error: string; error: string;
constructor(public $scope, _$injector) { constructor(public $scope: any, _$injector: auto.IInjectorService) {
this.panelCtrl = this.panelCtrl || { panel: {} }; this.panelCtrl = this.panelCtrl || { panel: {} };
this.target = this.target || { target: '' }; this.target = this.target || { target: '' };
this.panel = this.panelCtrl.panel; this.panel = this.panelCtrl.panel;
......
import { TemplateSrv } from 'app/features/templating/template_srv';
export class AzureMonitorAnnotationsQueryCtrl { export class AzureMonitorAnnotationsQueryCtrl {
static templateUrl = 'partials/annotations.editor.html'; static templateUrl = 'partials/annotations.editor.html';
datasource: any; datasource: any;
...@@ -9,7 +11,7 @@ export class AzureMonitorAnnotationsQueryCtrl { ...@@ -9,7 +11,7 @@ export class AzureMonitorAnnotationsQueryCtrl {
'<your table>\n| where $__timeFilter() \n| project TimeGenerated, Text=YourTitleColumn, Tags="tag1,tag2"'; '<your table>\n| where $__timeFilter() \n| project TimeGenerated, Text=YourTitleColumn, Tags="tag1,tag2"';
/** @ngInject */ /** @ngInject */
constructor(private templateSrv) { constructor(private templateSrv: TemplateSrv) {
this.annotation.queryType = this.annotation.queryType || 'Azure Log Analytics'; this.annotation.queryType = this.annotation.queryType || 'Azure Log Analytics';
this.annotation.rawQuery = this.annotation.rawQuery || this.defaultQuery; this.annotation.rawQuery = this.annotation.rawQuery || this.defaultQuery;
this.initDropdowns(); this.initDropdowns();
...@@ -25,7 +27,7 @@ export class AzureMonitorAnnotationsQueryCtrl { ...@@ -25,7 +27,7 @@ export class AzureMonitorAnnotationsQueryCtrl {
return; return;
} }
return this.datasource.azureMonitorDatasource.getSubscriptions().then(subs => { return this.datasource.azureMonitorDatasource.getSubscriptions().then((subs: any[]) => {
this.subscriptions = subs; this.subscriptions = subs;
if (!this.annotation.subscription && this.annotation.queryType === 'Azure Log Analytics') { if (!this.annotation.subscription && this.annotation.queryType === 'Azure Log Analytics') {
...@@ -45,7 +47,7 @@ export class AzureMonitorAnnotationsQueryCtrl { ...@@ -45,7 +47,7 @@ export class AzureMonitorAnnotationsQueryCtrl {
return this.datasource return this.datasource
.getAzureLogAnalyticsWorkspaces(this.annotation.subscription) .getAzureLogAnalyticsWorkspaces(this.annotation.subscription)
.then(list => { .then((list: any[]) => {
this.workspaces = list; this.workspaces = list;
if (list.length > 0 && !this.annotation.workspace) { if (list.length > 0 && !this.annotation.workspace) {
this.annotation.workspace = list[0].value; this.annotation.workspace = list[0].value;
...@@ -72,6 +74,6 @@ export class AzureMonitorAnnotationsQueryCtrl { ...@@ -72,6 +74,6 @@ export class AzureMonitorAnnotationsQueryCtrl {
}; };
get templateVariables() { get templateVariables() {
return this.templateSrv.variables.map(t => '$' + t.name); return this.templateSrv.variables.map((t: any) => '$' + t.name);
} }
} }
import AzureMonitorDatasource from '../datasource'; import AzureMonitorDatasource from '../datasource';
// @ts-ignore
import Q from 'q'; import Q from 'q';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { toUtc } from '@grafana/data'; import { toUtc } from '@grafana/data';
...@@ -46,7 +47,7 @@ describe('AppInsightsDatasource', () => { ...@@ -46,7 +47,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return success status', () => { it('should return success status', () => {
return ctx.ds.testDatasource().then(results => { return ctx.ds.testDatasource().then((results: any) => {
expect(results.status).toEqual('success'); expect(results.status).toEqual('success');
}); });
}); });
...@@ -71,7 +72,7 @@ describe('AppInsightsDatasource', () => { ...@@ -71,7 +72,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return error status and a detailed error message', () => { it('should return error status and a detailed error message', () => {
return ctx.ds.testDatasource().then(results => { return ctx.ds.testDatasource().then((results: any) => {
expect(results.status).toEqual('error'); expect(results.status).toEqual('error');
expect(results.message).toEqual( expect(results.message).toEqual(
'1. Application Insights: Not Found: Invalid Application Id for Application Insights service. ' '1. Application Insights: Not Found: Invalid Application Id for Application Insights service. '
...@@ -99,7 +100,7 @@ describe('AppInsightsDatasource', () => { ...@@ -99,7 +100,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return error status and a detailed error message', () => { it('should return error status and a detailed error message', () => {
return ctx.ds.testDatasource().then(results => { return ctx.ds.testDatasource().then((results: any) => {
expect(results.status).toEqual('error'); expect(results.status).toEqual('error');
expect(results.message).toEqual('1. Application Insights: Error: SomeOtherError. An error message. '); expect(results.message).toEqual('1. Application Insights: Error: SomeOtherError. An error message. ');
}); });
...@@ -149,7 +150,7 @@ describe('AppInsightsDatasource', () => { ...@@ -149,7 +150,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a single datapoint', () => { it('should return a single datapoint', () => {
return ctx.ds.query(options).then(results => { return ctx.ds.query(options).then((results: any) => {
expect(results.data.length).toBe(1); expect(results.data.length).toBe(1);
expect(results.data[0].datapoints.length).toBe(1); expect(results.data[0].datapoints.length).toBe(1);
expect(results.data[0].target).toEqual('exceptions/server'); expect(results.data[0].target).toEqual('exceptions/server');
...@@ -196,7 +197,7 @@ describe('AppInsightsDatasource', () => { ...@@ -196,7 +197,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of datapoints', () => { it('should return a list of datapoints', () => {
return ctx.ds.query(options).then(results => { return ctx.ds.query(options).then((results: any) => {
expect(results.data.length).toBe(1); expect(results.data.length).toBe(1);
expect(results.data[0].datapoints.length).toBe(2); expect(results.data[0].datapoints.length).toBe(2);
expect(results.data[0].target).toEqual('exceptions/server'); expect(results.data[0].target).toEqual('exceptions/server');
...@@ -267,7 +268,7 @@ describe('AppInsightsDatasource', () => { ...@@ -267,7 +268,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of datapoints', () => { it('should return a list of datapoints', () => {
return ctx.ds.query(options).then(results => { return ctx.ds.query(options).then((results: any) => {
expect(results.data.length).toBe(3); expect(results.data.length).toBe(3);
expect(results.data[0].datapoints.length).toBe(2); expect(results.data[0].datapoints.length).toBe(2);
expect(results.data[0].target).toEqual('exceptions/server{client/city="Miami"}'); expect(results.data[0].target).toEqual('exceptions/server{client/city="Miami"}');
...@@ -292,7 +293,7 @@ describe('AppInsightsDatasource', () => { ...@@ -292,7 +293,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of datapoints', () => { it('should return a list of datapoints', () => {
return ctx.ds.query(options).then(results => { return ctx.ds.query(options).then((results: any) => {
expect(results.data.length).toBe(3); expect(results.data.length).toBe(3);
expect(results.data[0].datapoints.length).toBe(2); expect(results.data[0].datapoints.length).toBe(2);
expect(results.data[0].target).toEqual('exceptions/server + client/city + Miami'); expect(results.data[0].target).toEqual('exceptions/server + client/city + Miami');
...@@ -323,7 +324,7 @@ describe('AppInsightsDatasource', () => { ...@@ -323,7 +324,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of metric names', () => { it('should return a list of metric names', () => {
return ctx.ds.metricFindQuery('appInsightsMetricNames()').then(results => { return ctx.ds.metricFindQuery('appInsightsMetricNames()').then((results: any) => {
expect(results.length).toBe(2); expect(results.length).toBe(2);
expect(results[0].text).toBe('exceptions/server'); expect(results[0].text).toBe('exceptions/server');
expect(results[0].value).toBe('exceptions/server'); expect(results[0].value).toBe('exceptions/server');
...@@ -361,7 +362,7 @@ describe('AppInsightsDatasource', () => { ...@@ -361,7 +362,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of group bys', () => { it('should return a list of group bys', () => {
return ctx.ds.metricFindQuery('appInsightsGroupBys(requests/count)').then(results => { return ctx.ds.metricFindQuery('appInsightsGroupBys(requests/count)').then((results: any) => {
expect(results[0].text).toContain('client/os'); expect(results[0].text).toContain('client/os');
expect(results[0].value).toContain('client/os'); expect(results[0].value).toContain('client/os');
expect(results[1].text).toContain('client/city'); expect(results[1].text).toContain('client/city');
...@@ -389,7 +390,7 @@ describe('AppInsightsDatasource', () => { ...@@ -389,7 +390,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of metric names', () => { it('should return a list of metric names', () => {
return ctx.ds.getAppInsightsMetricNames().then(results => { return ctx.ds.getAppInsightsMetricNames().then((results: any) => {
expect(results.length).toBe(2); expect(results.length).toBe(2);
expect(results[0].text).toBe('exceptions/server'); expect(results[0].text).toBe('exceptions/server');
expect(results[0].value).toBe('exceptions/server'); expect(results[0].value).toBe('exceptions/server');
...@@ -427,7 +428,7 @@ describe('AppInsightsDatasource', () => { ...@@ -427,7 +428,7 @@ describe('AppInsightsDatasource', () => {
}); });
it('should return a list of group bys', () => { it('should return a list of group bys', () => {
return ctx.ds.getAppInsightsMetricMetadata('requests/count').then(results => { return ctx.ds.getAppInsightsMetricMetadata('requests/count').then((results: any) => {
expect(results.primaryAggType).toEqual('avg'); expect(results.primaryAggType).toEqual('avg');
expect(results.supportedAggTypes).toContain('avg'); expect(results.supportedAggTypes).toContain('avg');
expect(results.supportedAggTypes).toContain('sum'); expect(results.supportedAggTypes).toContain('sum');
......
...@@ -6,6 +6,7 @@ import { DataSourceInstanceSettings } from '@grafana/ui'; ...@@ -6,6 +6,7 @@ import { DataSourceInstanceSettings } from '@grafana/ui';
import { AzureDataSourceJsonData } from '../types'; import { AzureDataSourceJsonData } from '../types';
import { BackendSrv } from 'app/core/services/backend_srv'; import { BackendSrv } from 'app/core/services/backend_srv';
import { TemplateSrv } from 'app/features/templating/template_srv'; import { TemplateSrv } from 'app/features/templating/template_srv';
import { IQService } from 'angular';
export interface LogAnalyticsColumn { export interface LogAnalyticsColumn {
text: string; text: string;
...@@ -24,7 +25,7 @@ export default class AppInsightsDatasource { ...@@ -24,7 +25,7 @@ export default class AppInsightsDatasource {
instanceSettings: DataSourceInstanceSettings<AzureDataSourceJsonData>, instanceSettings: DataSourceInstanceSettings<AzureDataSourceJsonData>,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private templateSrv: TemplateSrv, private templateSrv: TemplateSrv,
private $q private $q: IQService
) { ) {
this.id = instanceSettings.id; this.id = instanceSettings.id;
this.applicationId = instanceSettings.jsonData.appInsightsAppId; this.applicationId = instanceSettings.jsonData.appInsightsAppId;
...@@ -36,7 +37,7 @@ export default class AppInsightsDatasource { ...@@ -36,7 +37,7 @@ export default class AppInsightsDatasource {
return !!this.applicationId && this.applicationId.length > 0; return !!this.applicationId && this.applicationId.length > 0;
} }
query(options) { query(options: any) {
const queries = _.filter(options.targets, item => { const queries = _.filter(options.targets, item => {
return item.hide !== true; return item.hide !== true;
}).map(target => { }).map(target => {
...@@ -106,6 +107,7 @@ export default class AppInsightsDatasource { ...@@ -106,6 +107,7 @@ export default class AppInsightsDatasource {
}); });
if (!queries || queries.length === 0) { if (!queries || queries.length === 0) {
// @ts-ignore
return; return;
} }
...@@ -130,16 +132,16 @@ export default class AppInsightsDatasource { ...@@ -130,16 +132,16 @@ export default class AppInsightsDatasource {
}); });
} }
doQueries(queries) { doQueries(queries: any) {
return _.map(queries, query => { return _.map(queries, query => {
return this.doRequest(query.url) return this.doRequest(query.url)
.then(result => { .then((result: any) => {
return { return {
result: result, result: result,
query: query, query: query,
}; };
}) })
.catch(err => { .catch((err: any) => {
throw { throw {
error: err, error: err,
query: query, query: query,
...@@ -148,7 +150,7 @@ export default class AppInsightsDatasource { ...@@ -148,7 +150,7 @@ export default class AppInsightsDatasource {
}); });
} }
annotationQuery(options) {} annotationQuery(options: any) {}
metricFindQuery(query: string) { metricFindQuery(query: string) {
const appInsightsMetricNameQuery = query.match(/^AppInsightsMetricNames\(\)/i); const appInsightsMetricNameQuery = query.match(/^AppInsightsMetricNames\(\)/i);
...@@ -168,7 +170,7 @@ export default class AppInsightsDatasource { ...@@ -168,7 +170,7 @@ export default class AppInsightsDatasource {
testDatasource() { testDatasource() {
const url = `${this.baseUrl}/metrics/metadata`; const url = `${this.baseUrl}/metrics/metadata`;
return this.doRequest(url) return this.doRequest(url)
.then(response => { .then((response: any) => {
if (response.status === 200) { if (response.status === 200) {
return { return {
status: 'success', status: 'success',
...@@ -182,7 +184,7 @@ export default class AppInsightsDatasource { ...@@ -182,7 +184,7 @@ export default class AppInsightsDatasource {
message: 'Returned http status code ' + response.status, message: 'Returned http status code ' + response.status,
}; };
}) })
.catch(error => { .catch((error: any) => {
let message = 'Application Insights: '; let message = 'Application Insights: ';
message += error.statusText ? error.statusText + ': ' : ''; message += error.statusText ? error.statusText + ': ' : '';
...@@ -201,13 +203,13 @@ export default class AppInsightsDatasource { ...@@ -201,13 +203,13 @@ export default class AppInsightsDatasource {
}); });
} }
doRequest(url, maxRetries = 1) { doRequest(url: any, maxRetries = 1) {
return this.backendSrv return this.backendSrv
.datasourceRequest({ .datasourceRequest({
url: this.url + url, url: this.url + url,
method: 'GET', method: 'GET',
}) })
.catch(error => { .catch((error: any) => {
if (maxRetries > 0) { if (maxRetries > 0) {
return this.doRequest(url, maxRetries - 1); return this.doRequest(url, maxRetries - 1);
} }
...@@ -223,20 +225,20 @@ export default class AppInsightsDatasource { ...@@ -223,20 +225,20 @@ export default class AppInsightsDatasource {
getMetricMetadata(metricName: string) { getMetricMetadata(metricName: string) {
const url = `${this.baseUrl}/metrics/metadata`; const url = `${this.baseUrl}/metrics/metadata`;
return this.doRequest(url).then(result => { return this.doRequest(url).then((result: any) => {
return new ResponseParser(result).parseMetadata(metricName); return new ResponseParser(result).parseMetadata(metricName);
}); });
} }
getGroupBys(metricName: string) { getGroupBys(metricName: string) {
return this.getMetricMetadata(metricName).then(result => { return this.getMetricMetadata(metricName).then((result: any) => {
return new ResponseParser(result).parseGroupBys(); return new ResponseParser(result).parseGroupBys();
}); });
} }
getQuerySchema() { getQuerySchema() {
const url = `${this.baseUrl}/query/schema`; const url = `${this.baseUrl}/query/schema`;
return this.doRequest(url).then(result => { return this.doRequest(url).then((result: any) => {
const schema = new ResponseParser(result).parseQuerySchema(); const schema = new ResponseParser(result).parseQuerySchema();
// console.log(schema); // console.log(schema);
return schema; return schema;
......
...@@ -162,7 +162,7 @@ export default class FakeSchemaData { ...@@ -162,7 +162,7 @@ export default class FakeSchemaData {
}; };
} }
static getlogAnalyticsFakeMetadata() { static getlogAnalyticsFakeMetadata(): any {
return { return {
tables: [ tables: [
{ {
......
export default class SupportedNamespaces { export default class SupportedNamespaces {
supportedMetricNamespaces = { supportedMetricNamespaces: any = {
azuremonitor: [ azuremonitor: [
'Microsoft.AnalysisServices/servers', 'Microsoft.AnalysisServices/servers',
'Microsoft.ApiManagement/service', 'Microsoft.ApiManagement/service',
......
...@@ -43,7 +43,7 @@ const defaultSchema: any = () => ({ ...@@ -43,7 +43,7 @@ const defaultSchema: any = () => ({
}, },
}); });
const cleanText = s => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim(); const cleanText = (s: string) => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim();
const wrapText = (text: string) => ({ text }); const wrapText = (text: string) => ({ text });
export default class KustoQueryField extends QueryField { export default class KustoQueryField extends QueryField {
...@@ -353,11 +353,13 @@ export default class KustoQueryField extends QueryField { ...@@ -353,11 +353,13 @@ export default class KustoQueryField extends QueryField {
} }
getTableSuggestions(db = 'Default'): SuggestionGroup[] { getTableSuggestions(db = 'Default'): SuggestionGroup[] {
// @ts-ignore
if (this.schema.Databases[db]) { if (this.schema.Databases[db]) {
return [ return [
{ {
prefixMatch: true, prefixMatch: true,
label: 'Tables', label: 'Tables',
// @ts-ignore
items: _.map(this.schema.Databases[db].Tables, (t: any) => ({ text: t.Name })), items: _.map(this.schema.Databases[db].Tables, (t: any) => ({ text: t.Name })),
}, },
]; ];
......
...@@ -10,6 +10,7 @@ describe('Graphite query model', () => { ...@@ -10,6 +10,7 @@ describe('Graphite query model', () => {
waitForFuncDefsLoaded: jest.fn().mockReturnValue(Promise.resolve(null)), waitForFuncDefsLoaded: jest.fn().mockReturnValue(Promise.resolve(null)),
createFuncInstance: gfunc.createFuncInstance, createFuncInstance: gfunc.createFuncInstance,
}, },
// @ts-ignore
templateSrv: new TemplateSrvStub(), templateSrv: new TemplateSrvStub(),
targets: [], targets: [],
}; };
......
...@@ -111,7 +111,7 @@ describe('Request URL', () => { ...@@ -111,7 +111,7 @@ describe('Request URL', () => {
}; };
const datasourceWithLabels = { const datasourceWithLabels = {
metadataRequest: url => { metadataRequest: (url: string) => {
if (url.slice(0, 15) === '/api/prom/label') { if (url.slice(0, 15) === '/api/prom/label') {
return { data: { data: ['other'] } }; return { data: { data: ['other'] } };
} else { } else {
...@@ -154,7 +154,7 @@ describe('Query imports', () => { ...@@ -154,7 +154,7 @@ describe('Query imports', () => {
it('returns empty query from selector query if label is not available', async () => { it('returns empty query from selector query if label is not available', async () => {
const datasourceWithLabels = { const datasourceWithLabels = {
metadataRequest: url => metadataRequest: (url: string) =>
url.slice(0, 15) === '/api/prom/label' url.slice(0, 15) === '/api/prom/label'
? { data: { data: ['other'] } } ? { data: { data: ['other'] } }
: { data: { data: [] as DataQueryResponseData[] } }, : { data: { data: [] as DataQueryResponseData[] } },
...@@ -166,7 +166,7 @@ describe('Query imports', () => { ...@@ -166,7 +166,7 @@ describe('Query imports', () => {
it('returns selector query from selector query with common labels', async () => { it('returns selector query from selector query with common labels', async () => {
const datasourceWithLabels = { const datasourceWithLabels = {
metadataRequest: url => metadataRequest: (url: string) =>
url.slice(0, 15) === '/api/prom/label' url.slice(0, 15) === '/api/prom/label'
? { data: { data: ['foo'] } } ? { data: { data: ['foo'] } }
: { data: { data: [] as DataQueryResponseData[] } }, : { data: { data: [] as DataQueryResponseData[] } },
...@@ -178,7 +178,7 @@ describe('Query imports', () => { ...@@ -178,7 +178,7 @@ describe('Query imports', () => {
it('returns selector query from selector query with all labels if logging label list is empty', async () => { it('returns selector query from selector query with all labels if logging label list is empty', async () => {
const datasourceWithLabels = { const datasourceWithLabels = {
metadataRequest: url => metadataRequest: (url: string) =>
url.slice(0, 15) === '/api/prom/label' url.slice(0, 15) === '/api/prom/label'
? { data: { data: [] as DataQueryResponseData[] } } ? { data: { data: [] as DataQueryResponseData[] } }
: { data: { data: [] as DataQueryResponseData[] } }, : { data: { data: [] as DataQueryResponseData[] } },
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
echo -e "Collecting code stats (typescript errors & more)" echo -e "Collecting code stats (typescript errors & more)"
ERROR_COUNT_LIMIT=2350 ERROR_COUNT_LIMIT=1670
DIRECTIVES_LIMIT=172 DIRECTIVES_LIMIT=172
CONTROLLERS_LIMIT=139 CONTROLLERS_LIMIT=139
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment