2019-11-14 03:59:41 -06:00
|
|
|
import React from 'react';
|
2019-12-05 03:04:03 -06:00
|
|
|
import angular from 'angular';
|
2017-12-27 06:25:40 -06:00
|
|
|
import _ from 'lodash';
|
2019-11-14 03:59:41 -06:00
|
|
|
import { notifyApp } from 'app/core/actions';
|
|
|
|
import { createErrorNotification } from 'app/core/copy/appNotification';
|
|
|
|
import { AppNotificationTimeout } from 'app/types';
|
|
|
|
import { store } from 'app/store/store';
|
2019-10-31 04:48:05 -05:00
|
|
|
import {
|
2020-06-04 06:44:48 -05:00
|
|
|
DataFrame,
|
2020-03-24 10:03:53 -05:00
|
|
|
DataQueryRequest,
|
2020-06-04 06:44:48 -05:00
|
|
|
DataQueryResponse,
|
2020-03-24 10:03:53 -05:00
|
|
|
DataSourceApi,
|
|
|
|
DataSourceInstanceSettings,
|
2019-10-31 04:48:05 -05:00
|
|
|
dateMath,
|
2020-06-04 06:44:48 -05:00
|
|
|
LoadingState,
|
|
|
|
LogRowModel,
|
2019-10-31 04:48:05 -05:00
|
|
|
ScopedVars,
|
|
|
|
TimeRange,
|
2020-03-24 10:03:53 -05:00
|
|
|
toDataFrame,
|
2020-09-03 01:54:06 -05:00
|
|
|
rangeUtil,
|
2020-09-07 08:41:36 -05:00
|
|
|
DataQueryErrorType,
|
2019-10-31 04:48:05 -05:00
|
|
|
} from '@grafana/data';
|
2020-05-04 13:05:04 -05:00
|
|
|
import { getBackendSrv, toDataQueryResponse } from '@grafana/runtime';
|
2020-10-01 12:51:23 -05:00
|
|
|
import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';
|
|
|
|
import { getTimeSrv, TimeSrv } from 'app/features/dashboard/services/TimeSrv';
|
2019-11-14 03:59:41 -06:00
|
|
|
import { ThrottlingErrorMessage } from './components/ThrottlingErrorMessage';
|
|
|
|
import memoizedDebounce from './memoizedDebounce';
|
2020-04-25 15:48:20 -05:00
|
|
|
import {
|
|
|
|
CloudWatchJsonData,
|
|
|
|
CloudWatchLogsQuery,
|
|
|
|
CloudWatchLogsQueryStatus,
|
2020-06-04 06:44:48 -05:00
|
|
|
CloudWatchMetricsQuery,
|
|
|
|
CloudWatchQuery,
|
2020-04-25 15:48:20 -05:00
|
|
|
DescribeLogGroupsRequest,
|
2020-06-04 06:44:48 -05:00
|
|
|
GetLogEventsRequest,
|
2020-04-25 15:48:20 -05:00
|
|
|
GetLogGroupFieldsRequest,
|
|
|
|
GetLogGroupFieldsResponse,
|
|
|
|
LogAction,
|
2020-05-11 05:53:42 -05:00
|
|
|
MetricQuery,
|
2020-06-04 06:44:48 -05:00
|
|
|
MetricRequest,
|
|
|
|
TSDBResponse,
|
2020-09-09 04:00:43 -05:00
|
|
|
isCloudWatchLogsQuery,
|
2020-04-25 15:48:20 -05:00
|
|
|
} from './types';
|
2020-09-07 08:41:36 -05:00
|
|
|
import { from, Observable, of, merge, zip } from 'rxjs';
|
|
|
|
import { catchError, finalize, map, mergeMap, tap, concatMap, scan, share, repeat, takeWhile } from 'rxjs/operators';
|
2020-04-25 15:48:20 -05:00
|
|
|
import { CloudWatchLanguageProvider } from './language_provider';
|
|
|
|
|
2020-06-04 06:44:48 -05:00
|
|
|
import { VariableWithMultiSupport } from 'app/features/variables/types';
|
2020-04-25 15:48:20 -05:00
|
|
|
import { RowContextOptions } from '@grafana/ui/src/components/Logs/LogRowContextProvider';
|
2020-05-08 11:03:15 -05:00
|
|
|
import { AwsUrl, encodeUrl } from './aws_url';
|
2020-09-07 08:41:36 -05:00
|
|
|
import { increasingInterval } from './utils/rxjs/increasingInterval';
|
2019-11-14 03:59:41 -06:00
|
|
|
|
2020-05-13 08:34:23 -05:00
|
|
|
const TSDB_QUERY_ENDPOINT = '/api/tsdb/query';
|
|
|
|
|
|
|
|
// Constants also defined in tsdb/cloudwatch/cloudwatch.go
|
|
|
|
const LOG_IDENTIFIER_INTERNAL = '__log__grafana_internal__';
|
|
|
|
const LOGSTREAM_IDENTIFIER_INTERNAL = '__logstream__grafana_internal__';
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
const displayAlert = (datasourceName: string, region: string) =>
|
|
|
|
store.dispatch(
|
|
|
|
notifyApp(
|
|
|
|
createErrorNotification(
|
|
|
|
`CloudWatch request limit reached in ${region} for data source ${datasourceName}`,
|
|
|
|
'',
|
|
|
|
React.createElement(ThrottlingErrorMessage, { region }, null)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
const displayCustomError = (title: string, message: string) =>
|
|
|
|
store.dispatch(notifyApp(createErrorNotification(title, message)));
|
|
|
|
|
2020-09-07 08:41:36 -05:00
|
|
|
export const MAX_ATTEMPTS = 5;
|
2020-04-25 15:48:20 -05:00
|
|
|
|
|
|
|
export class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery, CloudWatchJsonData> {
|
2017-12-27 06:25:40 -06:00
|
|
|
type: any;
|
|
|
|
proxyUrl: any;
|
|
|
|
defaultRegion: any;
|
|
|
|
standardStatistics: any;
|
2019-11-14 03:59:41 -06:00
|
|
|
datasourceName: string;
|
|
|
|
debouncedAlert: (datasourceName: string, region: string) => void;
|
|
|
|
debouncedCustomAlert: (title: string, message: string) => void;
|
2020-07-09 09:14:55 -05:00
|
|
|
logQueries: Record<string, { id: string; region: string; statsQuery: boolean }>;
|
2020-04-25 15:48:20 -05:00
|
|
|
languageProvider: CloudWatchLanguageProvider;
|
2019-05-08 02:37:50 -05:00
|
|
|
|
|
|
|
constructor(
|
2019-11-14 03:59:41 -06:00
|
|
|
instanceSettings: DataSourceInstanceSettings<CloudWatchJsonData>,
|
2020-10-01 12:51:23 -05:00
|
|
|
private readonly templateSrv: TemplateSrv = getTemplateSrv(),
|
|
|
|
private readonly timeSrv: TimeSrv = getTimeSrv()
|
2019-05-08 02:37:50 -05:00
|
|
|
) {
|
2019-05-10 04:37:43 -05:00
|
|
|
super(instanceSettings);
|
2017-12-27 06:25:40 -06:00
|
|
|
this.type = 'cloudwatch';
|
|
|
|
this.proxyUrl = instanceSettings.url;
|
|
|
|
this.defaultRegion = instanceSettings.jsonData.defaultRegion;
|
2019-11-14 03:59:41 -06:00
|
|
|
this.datasourceName = instanceSettings.name;
|
2017-12-27 06:25:40 -06:00
|
|
|
this.standardStatistics = ['Average', 'Maximum', 'Minimum', 'Sum', 'SampleCount'];
|
2019-11-14 03:59:41 -06:00
|
|
|
this.debouncedAlert = memoizedDebounce(displayAlert, AppNotificationTimeout.Error);
|
|
|
|
this.debouncedCustomAlert = memoizedDebounce(displayCustomError, AppNotificationTimeout.Error);
|
2020-05-11 12:52:15 -05:00
|
|
|
this.logQueries = {};
|
2020-04-25 15:48:20 -05:00
|
|
|
|
|
|
|
this.languageProvider = new CloudWatchLanguageProvider(this);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
query(options: DataQueryRequest<CloudWatchQuery>): Observable<DataQueryResponse> {
|
2017-12-27 06:25:40 -06:00
|
|
|
options = angular.copy(options);
|
|
|
|
|
2020-05-11 05:53:42 -05:00
|
|
|
let queries = options.targets.filter(item => item.id !== '' || item.hide !== true);
|
2020-07-09 07:11:13 -05:00
|
|
|
const { logQueries, metricsQueries } = this.getTargetsByQueryMode(queries);
|
2020-05-11 05:53:42 -05:00
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
const dataQueryResponses: Array<Observable<DataQueryResponse>> = [];
|
|
|
|
if (logQueries.length > 0) {
|
|
|
|
dataQueryResponses.push(this.handleLogQueries(logQueries, options));
|
|
|
|
}
|
2020-05-11 05:53:42 -05:00
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
if (metricsQueries.length > 0) {
|
|
|
|
dataQueryResponses.push(this.handleMetricQueries(metricsQueries, options));
|
|
|
|
}
|
2020-05-11 05:53:42 -05:00
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
// No valid targets, return the empty result to save a round trip.
|
|
|
|
if (_.isEmpty(dataQueryResponses)) {
|
|
|
|
return of({
|
|
|
|
data: [],
|
|
|
|
state: LoadingState.Done,
|
|
|
|
});
|
|
|
|
}
|
2020-05-11 05:53:42 -05:00
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
return merge(...dataQueryResponses);
|
|
|
|
}
|
2020-04-25 15:48:20 -05:00
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
handleLogQueries = (
|
|
|
|
logQueries: CloudWatchLogsQuery[],
|
|
|
|
options: DataQueryRequest<CloudWatchQuery>
|
|
|
|
): Observable<DataQueryResponse> => {
|
|
|
|
const validLogQueries = logQueries.filter(item => item.logGroupNames?.length);
|
|
|
|
if (logQueries.length > validLogQueries.length) {
|
|
|
|
return of({ data: [], error: { message: 'Log group is required' } });
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
2018-10-11 14:58:17 -05:00
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
// No valid targets, return the empty result to save a round trip.
|
|
|
|
if (_.isEmpty(validLogQueries)) {
|
|
|
|
return of({ data: [], state: LoadingState.Done });
|
|
|
|
}
|
|
|
|
|
|
|
|
const queryParams = validLogQueries.map((target: CloudWatchLogsQuery) => ({
|
|
|
|
queryString: target.expression,
|
|
|
|
refId: target.refId,
|
|
|
|
logGroupNames: target.logGroupNames,
|
|
|
|
region: this.replace(this.getActualRegion(target.region), options.scopedVars, true, 'region'),
|
|
|
|
}));
|
|
|
|
|
|
|
|
return this.makeLogActionRequest('StartQuery', queryParams, options.scopedVars).pipe(
|
|
|
|
mergeMap(dataFrames =>
|
|
|
|
this.logsQuery(
|
|
|
|
dataFrames.map(dataFrame => ({
|
|
|
|
queryId: dataFrame.fields[0].values.get(0),
|
|
|
|
region: dataFrame.meta?.custom?.['Region'] ?? 'default',
|
|
|
|
refId: dataFrame.refId!,
|
|
|
|
statsGroups: (logQueries.find(target => target.refId === dataFrame.refId)! as CloudWatchLogsQuery)
|
|
|
|
.statsGroups,
|
|
|
|
}))
|
|
|
|
)
|
|
|
|
),
|
|
|
|
map(response => this.addDataLinksToLogsResponse(response, options))
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
handleMetricQueries = (
|
|
|
|
metricQueries: CloudWatchMetricsQuery[],
|
|
|
|
options: DataQueryRequest<CloudWatchQuery>
|
|
|
|
): Observable<DataQueryResponse> => {
|
|
|
|
const validMetricsQueries = metricQueries
|
2020-04-25 15:48:20 -05:00
|
|
|
.filter(
|
|
|
|
item =>
|
2020-07-09 07:11:13 -05:00
|
|
|
(!!item.region && !!item.namespace && !!item.metricName && !_.isEmpty(item.statistics)) ||
|
|
|
|
item.expression?.length > 0
|
2020-04-25 15:48:20 -05:00
|
|
|
)
|
2020-05-11 05:53:42 -05:00
|
|
|
.map(
|
|
|
|
(item: CloudWatchMetricsQuery): MetricQuery => {
|
|
|
|
item.region = this.replace(this.getActualRegion(item.region), options.scopedVars, true, 'region');
|
|
|
|
item.namespace = this.replace(item.namespace, options.scopedVars, true, 'namespace');
|
|
|
|
item.metricName = this.replace(item.metricName, options.scopedVars, true, 'metric name');
|
|
|
|
item.dimensions = this.convertDimensionFormat(item.dimensions, options.scopedVars);
|
|
|
|
item.statistics = item.statistics.map(stat => this.replace(stat, options.scopedVars, true, 'statistics'));
|
|
|
|
item.period = String(this.getPeriod(item, options)); // use string format for period in graph query, and alerting
|
|
|
|
item.id = this.templateSrv.replace(item.id, options.scopedVars);
|
|
|
|
item.expression = this.templateSrv.replace(item.expression, options.scopedVars);
|
|
|
|
|
|
|
|
// valid ExtendedStatistics is like p90.00, check the pattern
|
|
|
|
const hasInvalidStatistics = item.statistics.some(s => {
|
|
|
|
if (s.indexOf('p') === 0) {
|
|
|
|
const matches = /^p\d{2}(?:\.\d{1,2})?$/.exec(s);
|
|
|
|
return !matches || matches[0] !== s;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
});
|
|
|
|
|
|
|
|
if (hasInvalidStatistics) {
|
|
|
|
throw { message: 'Invalid extended statistics' };
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
|
|
|
|
2020-05-11 05:53:42 -05:00
|
|
|
return {
|
|
|
|
intervalMs: options.intervalMs,
|
|
|
|
maxDataPoints: options.maxDataPoints,
|
|
|
|
datasourceId: this.id,
|
|
|
|
type: 'timeSeriesQuery',
|
|
|
|
...item,
|
|
|
|
};
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
2020-05-11 05:53:42 -05:00
|
|
|
);
|
2017-12-27 06:25:40 -06:00
|
|
|
|
|
|
|
// No valid targets, return the empty result to save a round trip.
|
2020-07-09 07:11:13 -05:00
|
|
|
if (_.isEmpty(validMetricsQueries)) {
|
|
|
|
return of({ data: [] });
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const request = {
|
2020-03-20 07:00:49 -05:00
|
|
|
from: options?.range?.from.valueOf().toString(),
|
|
|
|
to: options?.range?.to.valueOf().toString(),
|
2020-07-09 07:11:13 -05:00
|
|
|
queries: validMetricsQueries,
|
2017-12-27 06:25:40 -06:00
|
|
|
};
|
|
|
|
|
2020-07-09 07:11:13 -05:00
|
|
|
return from(this.performTimeSeriesQuery(request, options.range));
|
|
|
|
};
|
2017-12-27 06:25:40 -06:00
|
|
|
|
2020-05-11 12:52:15 -05:00
|
|
|
logsQuery(
|
2020-05-21 09:18:09 -05:00
|
|
|
queryParams: Array<{ queryId: string; refId: string; limit?: number; region: string; statsGroups?: string[] }>
|
2020-05-11 12:52:15 -05:00
|
|
|
): Observable<DataQueryResponse> {
|
|
|
|
this.logQueries = {};
|
|
|
|
queryParams.forEach(param => {
|
2020-07-09 09:14:55 -05:00
|
|
|
this.logQueries[param.refId] = {
|
|
|
|
id: param.queryId,
|
|
|
|
region: param.region,
|
Chore: Fix all Typescript strict null errors (#26204)
* Chore: Fix typescript strict null errors
* Added new limit
* Fixed ts issue
* fixed tests
* trying to fix type inference
* Fixing more ts errors
* Revert tsconfig option
* Fix
* Fixed code
* More fixes
* fix tests
* Updated snapshot
* Chore: More ts strict null fixes
* More fixes in some really messed up azure config components
* More fixes, current count: 441
* 419
* More fixes
* Fixed invalid initial state in explore
* Fixing tests
* Fixed tests
* Explore fix
* More fixes
* Progress
* Sub 300
* Now at 218
* Progress
* Update
* Progress
* Updated tests
* at 159
* fixed tests
* Progress
* YAy blow 100! at 94
* 10,9,8,7,6,5,4,3,2,1... lift off
* Fixed tests
* Fixed more type errors
Co-authored-by: Ryan McKinley <ryantxu@gmail.com>
2020-07-10 05:46:59 -05:00
|
|
|
statsQuery: (param.statsGroups?.length ?? 0) > 0 ?? false,
|
2020-07-09 09:14:55 -05:00
|
|
|
};
|
2020-05-11 12:52:15 -05:00
|
|
|
});
|
2020-09-07 08:41:36 -05:00
|
|
|
|
|
|
|
const dataFrames = increasingInterval({ startPeriod: 100, endPeriod: 1000, step: 300 }).pipe(
|
|
|
|
concatMap(_ => this.makeLogActionRequest('GetQueryResults', queryParams)),
|
|
|
|
repeat(),
|
|
|
|
share()
|
|
|
|
);
|
|
|
|
|
|
|
|
const consecutiveFailedAttempts = dataFrames.pipe(
|
|
|
|
scan(
|
|
|
|
({ failures, prevRecordsMatched }, frames) => {
|
|
|
|
failures++;
|
|
|
|
for (const frame of frames) {
|
|
|
|
const recordsMatched = frame.meta?.stats?.find(stat => stat.displayName === 'Records matched')?.value!;
|
|
|
|
if (recordsMatched > (prevRecordsMatched[frame.refId!] ?? 0)) {
|
|
|
|
failures = 0;
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
2020-09-07 08:41:36 -05:00
|
|
|
prevRecordsMatched[frame.refId!] = recordsMatched;
|
|
|
|
}
|
|
|
|
|
|
|
|
return { failures, prevRecordsMatched };
|
|
|
|
},
|
|
|
|
{ failures: 0, prevRecordsMatched: {} as Record<string, number> }
|
|
|
|
),
|
|
|
|
map(({ failures }) => failures),
|
|
|
|
share()
|
|
|
|
);
|
|
|
|
|
|
|
|
const queryResponse: Observable<DataQueryResponse> = zip(dataFrames, consecutiveFailedAttempts).pipe(
|
|
|
|
tap(([dataFrames]) => {
|
|
|
|
for (const frame of dataFrames) {
|
|
|
|
if (
|
|
|
|
[
|
|
|
|
CloudWatchLogsQueryStatus.Complete,
|
|
|
|
CloudWatchLogsQueryStatus.Cancelled,
|
|
|
|
CloudWatchLogsQueryStatus.Failed,
|
|
|
|
].includes(frame.meta?.custom?.['Status']) &&
|
|
|
|
this.logQueries.hasOwnProperty(frame.refId!)
|
|
|
|
) {
|
|
|
|
delete this.logQueries[frame.refId!];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
map(([dataFrames, failedAttempts]) => {
|
|
|
|
if (failedAttempts >= MAX_ATTEMPTS) {
|
|
|
|
for (const frame of dataFrames) {
|
|
|
|
_.set(frame, 'meta.custom.Status', CloudWatchLogsQueryStatus.Cancelled);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2020-05-21 09:18:09 -05:00
|
|
|
data: dataFrames,
|
|
|
|
key: 'test-key',
|
2020-09-07 08:41:36 -05:00
|
|
|
state: dataFrames.every(dataFrame =>
|
|
|
|
[
|
|
|
|
CloudWatchLogsQueryStatus.Complete,
|
|
|
|
CloudWatchLogsQueryStatus.Cancelled,
|
|
|
|
CloudWatchLogsQueryStatus.Failed,
|
|
|
|
].includes(dataFrame.meta?.custom?.['Status'])
|
2020-05-21 09:18:09 -05:00
|
|
|
)
|
|
|
|
? LoadingState.Done
|
|
|
|
: LoadingState.Loading,
|
2020-09-07 08:41:36 -05:00
|
|
|
error:
|
|
|
|
failedAttempts >= MAX_ATTEMPTS
|
|
|
|
? {
|
|
|
|
message: `error: query timed out after ${MAX_ATTEMPTS} attempts`,
|
|
|
|
type: DataQueryErrorType.Timeout,
|
|
|
|
}
|
|
|
|
: undefined,
|
|
|
|
};
|
|
|
|
}),
|
|
|
|
takeWhile(({ state }) => state !== LoadingState.Error && state !== LoadingState.Done, true)
|
2020-04-25 15:48:20 -05:00
|
|
|
);
|
2020-09-07 08:41:36 -05:00
|
|
|
|
|
|
|
return withTeardown(queryResponse, () => this.stopQueries());
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
|
|
|
|
2020-05-08 11:03:15 -05:00
|
|
|
private addDataLinksToLogsResponse(response: DataQueryResponse, options: DataQueryRequest<CloudWatchQuery>) {
|
|
|
|
for (const dataFrame of response.data as DataFrame[]) {
|
|
|
|
const range = this.timeSrv.timeRange();
|
|
|
|
const start = range.from.toISOString();
|
|
|
|
const end = range.to.toISOString();
|
|
|
|
|
|
|
|
const curTarget = options.targets.find(target => target.refId === dataFrame.refId) as CloudWatchLogsQuery;
|
2020-08-12 10:26:51 -05:00
|
|
|
const interpolatedGroups =
|
|
|
|
curTarget.logGroupNames?.map((logGroup: string) =>
|
|
|
|
this.replace(logGroup, options.scopedVars, true, 'log groups')
|
|
|
|
) ?? [];
|
2020-05-08 11:03:15 -05:00
|
|
|
const urlProps: AwsUrl = {
|
|
|
|
end,
|
|
|
|
start,
|
|
|
|
timeType: 'ABSOLUTE',
|
|
|
|
tz: 'UTC',
|
2020-08-12 10:26:51 -05:00
|
|
|
editorString: curTarget.expression ? this.replace(curTarget.expression, options.scopedVars, true) : '',
|
2020-05-08 11:03:15 -05:00
|
|
|
isLiveTail: false,
|
2020-08-12 10:26:51 -05:00
|
|
|
source: interpolatedGroups,
|
2020-05-08 11:03:15 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
const encodedUrl = encodeUrl(
|
|
|
|
urlProps,
|
|
|
|
this.getActualRegion(this.replace(curTarget.region, options.scopedVars, true, 'region'))
|
|
|
|
);
|
|
|
|
|
|
|
|
for (const field of dataFrame.fields) {
|
|
|
|
field.config.links = [
|
|
|
|
{
|
|
|
|
url: encodedUrl,
|
|
|
|
title: 'View in CloudWatch console',
|
|
|
|
targetBlank: true,
|
|
|
|
},
|
|
|
|
];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
stopQueries() {
|
2020-05-11 12:52:15 -05:00
|
|
|
if (Object.keys(this.logQueries).length > 0) {
|
2020-04-25 15:48:20 -05:00
|
|
|
this.makeLogActionRequest(
|
|
|
|
'StopQuery',
|
2020-05-11 12:52:15 -05:00
|
|
|
Object.values(this.logQueries).map(logQuery => ({ queryId: logQuery.id, region: logQuery.region })),
|
2020-05-08 11:03:15 -05:00
|
|
|
undefined,
|
2020-04-25 15:48:20 -05:00
|
|
|
false
|
2020-05-11 12:52:15 -05:00
|
|
|
).pipe(
|
|
|
|
finalize(() => {
|
|
|
|
this.logQueries = {};
|
|
|
|
})
|
|
|
|
);
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async describeLogGroups(params: DescribeLogGroupsRequest): Promise<string[]> {
|
|
|
|
const dataFrames = await this.makeLogActionRequest('DescribeLogGroups', [params]).toPromise();
|
|
|
|
|
2020-05-06 06:52:21 -05:00
|
|
|
const logGroupNames = dataFrames[0]?.fields[0]?.values.toArray() ?? [];
|
|
|
|
return logGroupNames;
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
async getLogGroupFields(params: GetLogGroupFieldsRequest): Promise<GetLogGroupFieldsResponse> {
|
|
|
|
const dataFrames = await this.makeLogActionRequest('GetLogGroupFields', [params]).toPromise();
|
|
|
|
|
|
|
|
const fieldNames = dataFrames[0].fields[0].values.toArray();
|
|
|
|
const fieldPercentages = dataFrames[0].fields[1].values.toArray();
|
|
|
|
const getLogGroupFieldsResponse = {
|
|
|
|
logGroupFields: fieldNames.map((val, i) => ({ name: val, percent: fieldPercentages[i] })) ?? [],
|
|
|
|
};
|
|
|
|
|
|
|
|
return getLogGroupFieldsResponse;
|
|
|
|
}
|
|
|
|
|
|
|
|
getLogRowContext = async (
|
|
|
|
row: LogRowModel,
|
|
|
|
{ limit = 10, direction = 'BACKWARD' }: RowContextOptions = {}
|
|
|
|
): Promise<{ data: DataFrame[] }> => {
|
|
|
|
let logStreamField = null;
|
|
|
|
let logField = null;
|
|
|
|
|
|
|
|
for (const field of row.dataFrame.fields) {
|
2020-05-13 08:34:23 -05:00
|
|
|
if (field.name === LOGSTREAM_IDENTIFIER_INTERNAL) {
|
2020-04-25 15:48:20 -05:00
|
|
|
logStreamField = field;
|
|
|
|
if (logField !== null) {
|
|
|
|
break;
|
|
|
|
}
|
2020-05-13 08:34:23 -05:00
|
|
|
} else if (field.name === LOG_IDENTIFIER_INTERNAL) {
|
2020-04-25 15:48:20 -05:00
|
|
|
logField = field;
|
|
|
|
if (logStreamField !== null) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const requestParams: GetLogEventsRequest = {
|
|
|
|
limit,
|
|
|
|
startFromHead: direction !== 'BACKWARD',
|
|
|
|
logGroupName: parseLogGroupName(logField!.values.get(row.rowIndex)),
|
|
|
|
logStreamName: logStreamField!.values.get(row.rowIndex),
|
|
|
|
};
|
|
|
|
|
|
|
|
if (direction === 'BACKWARD') {
|
|
|
|
requestParams.endTime = row.timeEpochMs;
|
|
|
|
} else {
|
|
|
|
requestParams.startTime = row.timeEpochMs;
|
|
|
|
}
|
|
|
|
|
|
|
|
const dataFrames = await this.makeLogActionRequest('GetLogEvents', [requestParams]).toPromise();
|
|
|
|
|
|
|
|
return {
|
|
|
|
data: dataFrames,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
get variables() {
|
2020-03-24 10:03:53 -05:00
|
|
|
return this.templateSrv.getVariables().map(v => `$${v.name}`);
|
2019-11-14 03:59:41 -06:00
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
getPeriod(target: CloudWatchMetricsQuery, options: any) {
|
2020-05-06 13:15:31 -05:00
|
|
|
let period = this.templateSrv.replace(target.period, options.scopedVars) as any;
|
2020-01-17 06:22:43 -06:00
|
|
|
if (period && period.toLowerCase() !== 'auto') {
|
2019-11-19 05:36:50 -06:00
|
|
|
if (/^\d+$/.test(period)) {
|
|
|
|
period = parseInt(period, 10);
|
2017-12-27 06:25:40 -06:00
|
|
|
} else {
|
2020-09-03 01:54:06 -05:00
|
|
|
period = rangeUtil.intervalToSeconds(period);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
2020-01-17 06:22:43 -06:00
|
|
|
|
|
|
|
if (period < 1) {
|
|
|
|
period = 1;
|
|
|
|
}
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2020-01-17 08:30:54 -06:00
|
|
|
return period || '';
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2019-10-29 11:02:55 -05:00
|
|
|
buildCloudwatchConsoleUrl(
|
2020-04-25 15:48:20 -05:00
|
|
|
{ region, namespace, metricName, dimensions, statistics, expression }: CloudWatchMetricsQuery,
|
2019-10-29 11:02:55 -05:00
|
|
|
start: string,
|
|
|
|
end: string,
|
2019-11-14 03:59:41 -06:00
|
|
|
title: string,
|
2020-01-17 06:22:43 -06:00
|
|
|
gmdMeta: Array<{ Expression: string; Period: string }>
|
2019-10-29 11:02:55 -05:00
|
|
|
) {
|
2019-11-14 03:59:41 -06:00
|
|
|
region = this.getActualRegion(region);
|
|
|
|
let conf = {
|
2019-10-29 11:02:55 -05:00
|
|
|
view: 'timeSeries',
|
|
|
|
stacked: false,
|
|
|
|
title,
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
region,
|
2019-11-14 03:59:41 -06:00
|
|
|
} as any;
|
|
|
|
|
|
|
|
const isSearchExpression =
|
|
|
|
gmdMeta && gmdMeta.length && gmdMeta.every(({ Expression: expression }) => /SEARCH().*/.test(expression));
|
|
|
|
const isMathExpression = !isSearchExpression && expression;
|
|
|
|
|
|
|
|
if (isMathExpression) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isSearchExpression) {
|
|
|
|
const metrics: any =
|
|
|
|
gmdMeta && gmdMeta.length ? gmdMeta.map(({ Expression: expression }) => ({ expression })) : [{ expression }];
|
|
|
|
conf = { ...conf, metrics };
|
|
|
|
} else {
|
|
|
|
conf = {
|
|
|
|
...conf,
|
|
|
|
metrics: [
|
|
|
|
...statistics.map(stat => [
|
|
|
|
namespace,
|
|
|
|
metricName,
|
|
|
|
...Object.entries(dimensions).reduce((acc, [key, value]) => [...acc, key, value[0]], []),
|
|
|
|
{
|
|
|
|
stat,
|
2020-01-17 06:22:43 -06:00
|
|
|
period: gmdMeta.length ? gmdMeta[0].Period : 60,
|
2019-11-14 03:59:41 -06:00
|
|
|
},
|
|
|
|
]),
|
|
|
|
],
|
|
|
|
};
|
|
|
|
}
|
2019-10-29 11:02:55 -05:00
|
|
|
|
|
|
|
return `https://${region}.console.aws.amazon.com/cloudwatch/deeplink.js?region=${region}#metricsV2:graph=${encodeURIComponent(
|
|
|
|
JSON.stringify(conf)
|
|
|
|
)}`;
|
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
performTimeSeriesQuery(request: MetricRequest, { from, to }: TimeRange): Promise<any> {
|
|
|
|
return this.awsRequest(TSDB_QUERY_ENDPOINT, request)
|
|
|
|
.then((res: TSDBResponse) => {
|
2019-11-14 03:59:41 -06:00
|
|
|
if (!res.results) {
|
|
|
|
return { data: [] };
|
2019-10-29 11:02:55 -05:00
|
|
|
}
|
2019-11-14 03:59:41 -06:00
|
|
|
return Object.values(request.queries).reduce(
|
|
|
|
({ data, error }: any, queryRequest: any) => {
|
|
|
|
const queryResult = res.results[queryRequest.refId];
|
|
|
|
if (!queryResult) {
|
|
|
|
return { data, error };
|
|
|
|
}
|
2019-10-29 11:02:55 -05:00
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
const link = this.buildCloudwatchConsoleUrl(
|
|
|
|
queryRequest,
|
|
|
|
from.toISOString(),
|
|
|
|
to.toISOString(),
|
|
|
|
queryRequest.refId,
|
|
|
|
queryResult.meta.gmdMeta
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
error: error || queryResult.error ? { message: queryResult.error } : null,
|
|
|
|
data: [
|
|
|
|
...data,
|
|
|
|
...queryResult.series.map(({ name, points }: any) => {
|
|
|
|
const dataFrame = toDataFrame({
|
|
|
|
target: name,
|
|
|
|
datapoints: points,
|
|
|
|
refId: queryRequest.refId,
|
|
|
|
meta: queryResult.meta,
|
|
|
|
});
|
|
|
|
if (link) {
|
|
|
|
for (const field of dataFrame.fields) {
|
|
|
|
field.config.links = [
|
|
|
|
{
|
|
|
|
url: link,
|
|
|
|
title: 'View in CloudWatch console',
|
|
|
|
targetBlank: true,
|
|
|
|
},
|
|
|
|
];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return dataFrame;
|
|
|
|
}),
|
|
|
|
],
|
|
|
|
};
|
|
|
|
},
|
|
|
|
{ data: [], error: null }
|
2019-10-29 11:02:55 -05:00
|
|
|
);
|
2019-11-14 03:59:41 -06:00
|
|
|
})
|
|
|
|
.catch((err: any = { data: { error: '' } }) => {
|
|
|
|
if (/^Throttling:.*/.test(err.data.message)) {
|
|
|
|
const failedRedIds = Object.keys(err.data.results);
|
|
|
|
const regionsAffected = Object.values(request.queries).reduce(
|
2020-04-25 15:48:20 -05:00
|
|
|
(res: string[], { refId, region }) =>
|
|
|
|
(refId && !failedRedIds.includes(refId)) || res.includes(region) ? res : [...res, region],
|
2019-11-14 03:59:41 -06:00
|
|
|
[]
|
|
|
|
) as string[];
|
|
|
|
|
|
|
|
regionsAffected.forEach(region => this.debouncedAlert(this.datasourceName, this.getActualRegion(region)));
|
|
|
|
}
|
2019-10-29 11:02:55 -05:00
|
|
|
|
2019-11-20 06:34:44 -06:00
|
|
|
if (err.data && err.data.message === 'Metric request error' && err.data.error) {
|
|
|
|
err.data.message = err.data.error;
|
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
throw err;
|
|
|
|
});
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
transformSuggestDataFromTable(suggestData: TSDBResponse) {
|
|
|
|
return suggestData.results['metricFindQuery'].tables[0].rows.map(([text, value]) => ({
|
|
|
|
text,
|
|
|
|
value,
|
|
|
|
label: value,
|
|
|
|
}));
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
doMetricQueryRequest(subtype: string, parameters: any) {
|
2018-08-29 07:27:29 -05:00
|
|
|
const range = this.timeSrv.timeRange();
|
2020-04-25 15:48:20 -05:00
|
|
|
return this.awsRequest(TSDB_QUERY_ENDPOINT, {
|
2017-12-27 06:25:40 -06:00
|
|
|
from: range.from.valueOf().toString(),
|
|
|
|
to: range.to.valueOf().toString(),
|
|
|
|
queries: [
|
2020-04-25 15:48:20 -05:00
|
|
|
{
|
|
|
|
refId: 'metricFindQuery',
|
|
|
|
intervalMs: 1, // dummy
|
|
|
|
maxDataPoints: 1, // dummy
|
|
|
|
datasourceId: this.id,
|
|
|
|
type: 'metricFindQuery',
|
|
|
|
subtype: subtype,
|
|
|
|
...parameters,
|
|
|
|
},
|
2017-12-27 06:25:40 -06:00
|
|
|
],
|
2020-04-25 15:48:20 -05:00
|
|
|
}).then((r: TSDBResponse) => {
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.transformSuggestDataFromTable(r);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
makeLogActionRequest(
|
|
|
|
subtype: LogAction,
|
|
|
|
queryParams: any[],
|
2020-05-06 10:54:24 -05:00
|
|
|
scopedVars?: ScopedVars,
|
2020-04-25 15:48:20 -05:00
|
|
|
makeReplacements = true
|
|
|
|
): Observable<DataFrame[]> {
|
|
|
|
const range = this.timeSrv.timeRange();
|
|
|
|
|
|
|
|
const requestParams = {
|
|
|
|
from: range.from.valueOf().toString(),
|
|
|
|
to: range.to.valueOf().toString(),
|
|
|
|
queries: queryParams.map((param: any) => ({
|
|
|
|
refId: 'A',
|
|
|
|
intervalMs: 1, // dummy
|
|
|
|
maxDataPoints: 1, // dummy
|
|
|
|
datasourceId: this.id,
|
|
|
|
type: 'logAction',
|
|
|
|
subtype: subtype,
|
|
|
|
...param,
|
|
|
|
})),
|
|
|
|
};
|
|
|
|
|
|
|
|
if (makeReplacements) {
|
2020-05-06 10:54:24 -05:00
|
|
|
requestParams.queries.forEach(query => {
|
2020-05-13 08:38:42 -05:00
|
|
|
if (query.hasOwnProperty('queryString')) {
|
|
|
|
query.queryString = this.replace(query.queryString, scopedVars, true);
|
|
|
|
}
|
2020-05-06 10:54:24 -05:00
|
|
|
query.region = this.replace(query.region, scopedVars, true, 'region');
|
|
|
|
query.region = this.getActualRegion(query.region);
|
2020-06-18 09:54:29 -05:00
|
|
|
|
|
|
|
// interpolate log groups
|
|
|
|
if (query.logGroupNames) {
|
|
|
|
query.logGroupNames = query.logGroupNames.map((logGroup: string) =>
|
|
|
|
this.replace(logGroup, scopedVars, true, 'log groups')
|
|
|
|
);
|
|
|
|
}
|
2020-05-06 10:54:24 -05:00
|
|
|
});
|
2020-04-25 15:48:20 -05:00
|
|
|
}
|
|
|
|
|
2020-05-06 06:52:21 -05:00
|
|
|
const resultsToDataFrames = (val: any): DataFrame[] => toDataQueryResponse(val).data || [];
|
2020-05-04 13:05:04 -05:00
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
return from(this.awsRequest(TSDB_QUERY_ENDPOINT, requestParams)).pipe(
|
2020-05-06 06:52:21 -05:00
|
|
|
map(response => resultsToDataFrames({ data: response })),
|
2020-04-25 15:48:20 -05:00
|
|
|
catchError(err => {
|
|
|
|
if (err.data?.error) {
|
|
|
|
throw err.data.error;
|
|
|
|
}
|
|
|
|
|
|
|
|
throw err;
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
getRegions(): Promise<Array<{ label: string; value: string; text: string }>> {
|
2019-11-21 03:46:15 -06:00
|
|
|
return this.doMetricQueryRequest('regions', null).then((regions: any) => [
|
|
|
|
{ label: 'default', value: 'default', text: 'default' },
|
|
|
|
...regions,
|
|
|
|
]);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
getNamespaces() {
|
|
|
|
return this.doMetricQueryRequest('namespaces', null);
|
|
|
|
}
|
|
|
|
|
2019-11-27 10:06:11 -06:00
|
|
|
async getMetrics(namespace: string, region?: string) {
|
|
|
|
if (!namespace) {
|
2019-11-14 03:59:41 -06:00
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.doMetricQueryRequest('metrics', {
|
|
|
|
region: this.templateSrv.replace(this.getActualRegion(region)),
|
|
|
|
namespace: this.templateSrv.replace(namespace),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
async getDimensionKeys(namespace: string, region: string) {
|
|
|
|
if (!namespace) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.doMetricQueryRequest('dimension_keys', {
|
|
|
|
region: this.templateSrv.replace(this.getActualRegion(region)),
|
|
|
|
namespace: this.templateSrv.replace(namespace),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
async getDimensionValues(
|
2019-07-11 10:05:45 -05:00
|
|
|
region: string,
|
|
|
|
namespace: string,
|
|
|
|
metricName: string,
|
|
|
|
dimensionKey: string,
|
|
|
|
filterDimensions: {}
|
|
|
|
) {
|
2019-11-14 03:59:41 -06:00
|
|
|
if (!namespace || !metricName) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
const values = await this.doMetricQueryRequest('dimension_values', {
|
2017-12-27 06:25:40 -06:00
|
|
|
region: this.templateSrv.replace(this.getActualRegion(region)),
|
|
|
|
namespace: this.templateSrv.replace(namespace),
|
2019-11-14 03:59:41 -06:00
|
|
|
metricName: this.templateSrv.replace(metricName.trim()),
|
2017-12-27 06:25:40 -06:00
|
|
|
dimensionKey: this.templateSrv.replace(dimensionKey),
|
|
|
|
dimensions: this.convertDimensionFormat(filterDimensions, {}),
|
|
|
|
});
|
2019-11-14 03:59:41 -06:00
|
|
|
|
2019-11-27 04:48:58 -06:00
|
|
|
return values;
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2019-07-11 10:05:45 -05:00
|
|
|
getEbsVolumeIds(region: string, instanceId: string) {
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.doMetricQueryRequest('ebs_volume_ids', {
|
|
|
|
region: this.templateSrv.replace(this.getActualRegion(region)),
|
|
|
|
instanceId: this.templateSrv.replace(instanceId),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-07-11 10:05:45 -05:00
|
|
|
getEc2InstanceAttribute(region: string, attributeName: string, filters: any) {
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.doMetricQueryRequest('ec2_instance_attribute', {
|
|
|
|
region: this.templateSrv.replace(this.getActualRegion(region)),
|
|
|
|
attributeName: this.templateSrv.replace(attributeName),
|
|
|
|
filters: filters,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-07-11 10:05:45 -05:00
|
|
|
getResourceARNs(region: string, resourceType: string, tags: any) {
|
2019-01-09 15:06:27 -06:00
|
|
|
return this.doMetricQueryRequest('resource_arns', {
|
|
|
|
region: this.templateSrv.replace(this.getActualRegion(region)),
|
|
|
|
resourceType: this.templateSrv.replace(resourceType),
|
|
|
|
tags: tags,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
async metricFindQuery(query: string) {
|
2018-08-30 02:03:11 -05:00
|
|
|
let region;
|
|
|
|
let namespace;
|
|
|
|
let metricName;
|
|
|
|
let filterJson;
|
2017-12-27 06:25:40 -06:00
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const regionQuery = query.match(/^regions\(\)/);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (regionQuery) {
|
|
|
|
return this.getRegions();
|
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const namespaceQuery = query.match(/^namespaces\(\)/);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (namespaceQuery) {
|
|
|
|
return this.getNamespaces();
|
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (metricNameQuery) {
|
|
|
|
namespace = metricNameQuery[1];
|
|
|
|
region = metricNameQuery[3];
|
|
|
|
return this.getMetrics(namespace, region);
|
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (dimensionKeysQuery) {
|
|
|
|
namespace = dimensionKeysQuery[1];
|
|
|
|
region = dimensionKeysQuery[3];
|
|
|
|
return this.getDimensionKeys(namespace, region);
|
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const dimensionValuesQuery = query.match(
|
Cloudwatch dimension_values add dimension filter.
issue #10029
e.g.
- dimension_values($region, $namespace, cpu_usage_system, cpu)
- dimension_values($region, $namespace, disk_used_percent, device, {"InstanceId": "$instance_id"})
- dimension_values($region, $namespace, disk_used_percent, path, {"InstanceId": "$instance_id", "device": "$device"})
2018-02-12 04:13:55 -06:00
|
|
|
/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?(.+))?\)/
|
|
|
|
);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (dimensionValuesQuery) {
|
|
|
|
region = dimensionValuesQuery[1];
|
|
|
|
namespace = dimensionValuesQuery[2];
|
|
|
|
metricName = dimensionValuesQuery[3];
|
2018-08-29 07:27:29 -05:00
|
|
|
const dimensionKey = dimensionValuesQuery[4];
|
Cloudwatch dimension_values add dimension filter.
issue #10029
e.g.
- dimension_values($region, $namespace, cpu_usage_system, cpu)
- dimension_values($region, $namespace, disk_used_percent, device, {"InstanceId": "$instance_id"})
- dimension_values($region, $namespace, disk_used_percent, path, {"InstanceId": "$instance_id", "device": "$device"})
2018-02-12 04:13:55 -06:00
|
|
|
filterJson = {};
|
|
|
|
if (dimensionValuesQuery[6]) {
|
|
|
|
filterJson = JSON.parse(this.templateSrv.replace(dimensionValuesQuery[6]));
|
|
|
|
}
|
2017-12-27 06:25:40 -06:00
|
|
|
|
Cloudwatch dimension_values add dimension filter.
issue #10029
e.g.
- dimension_values($region, $namespace, cpu_usage_system, cpu)
- dimension_values($region, $namespace, disk_used_percent, device, {"InstanceId": "$instance_id"})
- dimension_values($region, $namespace, disk_used_percent, path, {"InstanceId": "$instance_id", "device": "$device"})
2018-02-12 04:13:55 -06:00
|
|
|
return this.getDimensionValues(region, namespace, metricName, dimensionKey, filterJson);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (ebsVolumeIdsQuery) {
|
|
|
|
region = ebsVolumeIdsQuery[1];
|
2018-08-29 07:27:29 -05:00
|
|
|
const instanceId = ebsVolumeIdsQuery[2];
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.getEbsVolumeIds(region, instanceId);
|
|
|
|
}
|
|
|
|
|
2018-08-29 07:27:29 -05:00
|
|
|
const ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
|
2017-12-27 06:25:40 -06:00
|
|
|
if (ec2InstanceAttributeQuery) {
|
|
|
|
region = ec2InstanceAttributeQuery[1];
|
2018-08-29 07:27:29 -05:00
|
|
|
const targetAttributeName = ec2InstanceAttributeQuery[2];
|
Cloudwatch dimension_values add dimension filter.
issue #10029
e.g.
- dimension_values($region, $namespace, cpu_usage_system, cpu)
- dimension_values($region, $namespace, disk_used_percent, device, {"InstanceId": "$instance_id"})
- dimension_values($region, $namespace, disk_used_percent, path, {"InstanceId": "$instance_id", "device": "$device"})
2018-02-12 04:13:55 -06:00
|
|
|
filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3]));
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson);
|
|
|
|
}
|
|
|
|
|
2019-01-09 15:06:27 -06:00
|
|
|
const resourceARNsQuery = query.match(/^resource_arns\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
|
|
|
|
if (resourceARNsQuery) {
|
|
|
|
region = resourceARNsQuery[1];
|
|
|
|
const resourceType = resourceARNsQuery[2];
|
|
|
|
const tagsJSON = JSON.parse(this.templateSrv.replace(resourceARNsQuery[3]));
|
|
|
|
return this.getResourceARNs(region, resourceType, tagsJSON);
|
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
const statsQuery = query.match(/^statistics\(\)/);
|
|
|
|
if (statsQuery) {
|
|
|
|
return this.standardStatistics.map((s: string) => ({ value: s, label: s, text: s }));
|
|
|
|
}
|
|
|
|
|
2019-12-05 03:04:03 -06:00
|
|
|
return Promise.resolve([]);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2019-07-11 10:05:45 -05:00
|
|
|
annotationQuery(options: any) {
|
2018-08-29 07:27:29 -05:00
|
|
|
const annotation = options.annotation;
|
2020-04-25 15:48:20 -05:00
|
|
|
const statistics = annotation.statistics.map((s: any) => this.templateSrv.replace(s));
|
2018-08-29 07:27:29 -05:00
|
|
|
const defaultPeriod = annotation.prefixMatching ? '' : '300';
|
2018-08-30 02:03:11 -05:00
|
|
|
let period = annotation.period || defaultPeriod;
|
2017-12-27 06:25:40 -06:00
|
|
|
period = parseInt(period, 10);
|
2018-08-29 07:27:29 -05:00
|
|
|
const parameters = {
|
2017-12-27 06:25:40 -06:00
|
|
|
prefixMatching: annotation.prefixMatching,
|
|
|
|
region: this.templateSrv.replace(this.getActualRegion(annotation.region)),
|
|
|
|
namespace: this.templateSrv.replace(annotation.namespace),
|
|
|
|
metricName: this.templateSrv.replace(annotation.metricName),
|
|
|
|
dimensions: this.convertDimensionFormat(annotation.dimensions, {}),
|
|
|
|
statistics: statistics,
|
|
|
|
period: period,
|
|
|
|
actionPrefix: annotation.actionPrefix || '',
|
|
|
|
alarmNamePrefix: annotation.alarmNamePrefix || '',
|
|
|
|
};
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
return this.awsRequest(TSDB_QUERY_ENDPOINT, {
|
2017-12-27 06:25:40 -06:00
|
|
|
from: options.range.from.valueOf().toString(),
|
|
|
|
to: options.range.to.valueOf().toString(),
|
|
|
|
queries: [
|
2020-04-25 15:48:20 -05:00
|
|
|
{
|
|
|
|
refId: 'annotationQuery',
|
|
|
|
datasourceId: this.id,
|
|
|
|
type: 'annotationQuery',
|
|
|
|
...parameters,
|
|
|
|
},
|
2017-12-27 06:25:40 -06:00
|
|
|
],
|
2020-04-25 15:48:20 -05:00
|
|
|
}).then((r: TSDBResponse) => {
|
|
|
|
return r.results['annotationQuery'].tables[0].rows.map(v => ({
|
|
|
|
annotation: annotation,
|
|
|
|
time: Date.parse(v[0]),
|
|
|
|
title: v[1],
|
|
|
|
tags: [v[2]],
|
|
|
|
text: v[3],
|
|
|
|
}));
|
2017-12-27 06:25:40 -06:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-07-11 10:05:45 -05:00
|
|
|
targetContainsTemplate(target: any) {
|
2017-12-27 06:25:40 -06:00
|
|
|
return (
|
|
|
|
this.templateSrv.variableExists(target.region) ||
|
|
|
|
this.templateSrv.variableExists(target.namespace) ||
|
|
|
|
this.templateSrv.variableExists(target.metricName) ||
|
2020-08-12 10:26:51 -05:00
|
|
|
this.templateSrv.variableExists(target.expression!) ||
|
|
|
|
target.logGroupNames?.some((logGroup: string) => this.templateSrv.variableExists(logGroup)) ||
|
|
|
|
_.find(target.dimensions, (v, k) => this.templateSrv.variableExists(k) || this.templateSrv.variableExists(v))
|
2017-12-27 06:25:40 -06:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
testDatasource() {
|
2019-11-14 03:59:41 -06:00
|
|
|
// use billing metrics for test
|
2018-08-29 07:27:29 -05:00
|
|
|
const region = this.defaultRegion;
|
|
|
|
const namespace = 'AWS/Billing';
|
|
|
|
const metricName = 'EstimatedCharges';
|
|
|
|
const dimensions = {};
|
2017-12-27 06:25:40 -06:00
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(() => ({
|
|
|
|
status: 'success',
|
|
|
|
message: 'Data source is working',
|
|
|
|
}));
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
async awsRequest(url: string, data: MetricRequest) {
|
2018-08-29 07:27:29 -05:00
|
|
|
const options = {
|
2017-12-27 06:25:40 -06:00
|
|
|
method: 'POST',
|
2019-07-11 10:05:45 -05:00
|
|
|
url,
|
|
|
|
data,
|
2017-12-27 06:25:40 -06:00
|
|
|
};
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
const result = await getBackendSrv().datasourceRequest(options);
|
|
|
|
|
|
|
|
return result.data;
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
getDefaultRegion() {
|
|
|
|
return this.defaultRegion;
|
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
getActualRegion(region?: string) {
|
|
|
|
if (region === 'default' || region === undefined || region === '') {
|
2017-12-27 06:25:40 -06:00
|
|
|
return this.getDefaultRegion();
|
|
|
|
}
|
|
|
|
return region;
|
|
|
|
}
|
|
|
|
|
2020-04-25 15:48:20 -05:00
|
|
|
showContextToggle() {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
convertToCloudWatchTime(date: any, roundUp: any) {
|
|
|
|
if (_.isString(date)) {
|
|
|
|
date = dateMath.parse(date, roundUp);
|
|
|
|
}
|
|
|
|
return Math.round(date.valueOf() / 1000);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
convertDimensionFormat(dimensions: { [key: string]: string | string[] }, scopedVars: ScopedVars) {
|
|
|
|
return Object.entries(dimensions).reduce((result, [key, value]) => {
|
|
|
|
key = this.replace(key, scopedVars, true, 'dimension keys');
|
2019-04-12 07:00:41 -05:00
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
if (Array.isArray(value)) {
|
|
|
|
return { ...result, [key]: value };
|
|
|
|
}
|
2017-12-27 06:25:40 -06:00
|
|
|
|
2020-03-24 10:03:53 -05:00
|
|
|
const valueVar = this.templateSrv
|
|
|
|
.getVariables()
|
|
|
|
.find(({ name }) => name === this.templateSrv.getVariableName(value));
|
2019-11-14 03:59:41 -06:00
|
|
|
if (valueVar) {
|
2020-03-24 10:03:53 -05:00
|
|
|
if (((valueVar as unknown) as VariableWithMultiSupport).multi) {
|
2019-11-14 03:59:41 -06:00
|
|
|
const values = this.templateSrv.replace(value, scopedVars, 'pipe').split('|');
|
|
|
|
return { ...result, [key]: values };
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
2019-11-14 03:59:41 -06:00
|
|
|
return { ...result, [key]: [this.templateSrv.replace(value, scopedVars)] };
|
|
|
|
}
|
|
|
|
|
|
|
|
return { ...result, [key]: [value] };
|
|
|
|
}, {});
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2020-05-06 10:54:24 -05:00
|
|
|
replace(
|
2020-09-09 04:00:43 -05:00
|
|
|
target?: string,
|
|
|
|
scopedVars?: ScopedVars,
|
2020-05-06 10:54:24 -05:00
|
|
|
displayErrorIfIsMultiTemplateVariable?: boolean,
|
|
|
|
fieldName?: string
|
|
|
|
) {
|
2020-09-09 04:00:43 -05:00
|
|
|
if (displayErrorIfIsMultiTemplateVariable && !!target) {
|
2020-03-24 10:03:53 -05:00
|
|
|
const variable = this.templateSrv
|
|
|
|
.getVariables()
|
|
|
|
.find(({ name }) => name === this.templateSrv.getVariableName(target));
|
|
|
|
if (variable && ((variable as unknown) as VariableWithMultiSupport).multi) {
|
2019-11-14 03:59:41 -06:00
|
|
|
this.debouncedCustomAlert(
|
|
|
|
'CloudWatch templating error',
|
|
|
|
`Multi template variables are not supported for ${fieldName || target}`
|
|
|
|
);
|
|
|
|
}
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
|
|
|
|
2019-11-14 03:59:41 -06:00
|
|
|
return this.templateSrv.replace(target, scopedVars);
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
2020-05-19 05:43:43 -05:00
|
|
|
|
|
|
|
getQueryDisplayText(query: CloudWatchQuery) {
|
|
|
|
if (query.queryMode === 'Logs') {
|
2020-07-09 07:11:13 -05:00
|
|
|
return query.expression ?? '';
|
2020-05-19 05:43:43 -05:00
|
|
|
} else {
|
|
|
|
return JSON.stringify(query);
|
|
|
|
}
|
|
|
|
}
|
2020-07-09 07:11:13 -05:00
|
|
|
|
|
|
|
getTargetsByQueryMode = (targets: CloudWatchQuery[]) => {
|
|
|
|
const logQueries: CloudWatchLogsQuery[] = [];
|
|
|
|
const metricsQueries: CloudWatchMetricsQuery[] = [];
|
|
|
|
|
|
|
|
targets.forEach(query => {
|
|
|
|
const mode = query.queryMode ?? 'Metrics';
|
|
|
|
if (mode === 'Logs') {
|
|
|
|
logQueries.push(query as CloudWatchLogsQuery);
|
|
|
|
} else {
|
|
|
|
metricsQueries.push(query as CloudWatchMetricsQuery);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
logQueries,
|
|
|
|
metricsQueries,
|
|
|
|
};
|
|
|
|
};
|
2020-09-09 04:00:43 -05:00
|
|
|
|
|
|
|
interpolateVariablesInQueries(queries: CloudWatchQuery[], scopedVars: ScopedVars): CloudWatchQuery[] {
|
|
|
|
if (!queries.length) {
|
|
|
|
return queries;
|
|
|
|
}
|
|
|
|
|
|
|
|
return queries.map(query => ({
|
|
|
|
...query,
|
|
|
|
region: this.getActualRegion(this.replace(query.region, scopedVars)),
|
|
|
|
expression: this.replace(query.expression, scopedVars),
|
|
|
|
|
|
|
|
...(!isCloudWatchLogsQuery(query) && this.interpolateMetricsQueryVariables(query, scopedVars)),
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
interpolateMetricsQueryVariables(
|
|
|
|
query: CloudWatchMetricsQuery,
|
|
|
|
scopedVars: ScopedVars
|
|
|
|
): Pick<CloudWatchMetricsQuery, 'alias' | 'metricName' | 'namespace' | 'period' | 'dimensions'> {
|
|
|
|
return {
|
|
|
|
alias: this.replace(query.alias, scopedVars),
|
|
|
|
metricName: this.replace(query.metricName, scopedVars),
|
|
|
|
namespace: this.replace(query.namespace, scopedVars),
|
|
|
|
period: this.replace(query.period, scopedVars),
|
|
|
|
dimensions: Object.entries(query.dimensions).reduce((prev, [key, value]) => {
|
|
|
|
if (Array.isArray(value)) {
|
|
|
|
return { ...prev, [key]: value };
|
|
|
|
}
|
|
|
|
|
|
|
|
return { ...prev, [this.replace(key, scopedVars)]: this.replace(value, scopedVars) };
|
|
|
|
}, {}),
|
|
|
|
};
|
|
|
|
}
|
2017-12-27 06:25:40 -06:00
|
|
|
}
|
2020-04-25 15:48:20 -05:00
|
|
|
|
|
|
|
function withTeardown<T = any>(observable: Observable<T>, onUnsubscribe: () => void): Observable<T> {
|
|
|
|
return new Observable<T>(subscriber => {
|
|
|
|
const innerSub = observable.subscribe({
|
|
|
|
next: val => subscriber.next(val),
|
|
|
|
error: err => subscriber.next(err),
|
|
|
|
complete: () => subscriber.complete(),
|
|
|
|
});
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
innerSub.unsubscribe();
|
|
|
|
onUnsubscribe();
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function parseLogGroupName(logIdentifier: string): string {
|
|
|
|
const colonIndex = logIdentifier.lastIndexOf(':');
|
|
|
|
return logIdentifier.substr(colonIndex + 1);
|
|
|
|
}
|