datasource.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import angular, { IQService } from 'angular';
  2. import _ from 'lodash';
  3. import { dateMath } from '@grafana/data';
  4. import kbn from 'app/core/utils/kbn';
  5. import { CloudWatchQuery } from './types';
  6. import { DataSourceApi, DataQueryRequest, DataSourceInstanceSettings, ScopedVars } from '@grafana/ui';
  7. import { BackendSrv } from 'app/core/services/backend_srv';
  8. import { TemplateSrv } from 'app/features/templating/template_srv';
  9. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  10. // import * as moment from 'moment';
  11. export default class CloudWatchDatasource extends DataSourceApi<CloudWatchQuery> {
  12. type: any;
  13. proxyUrl: any;
  14. defaultRegion: any;
  15. standardStatistics: any;
  16. /** @ngInject */
  17. constructor(
  18. private instanceSettings: DataSourceInstanceSettings,
  19. private $q: IQService,
  20. private backendSrv: BackendSrv,
  21. private templateSrv: TemplateSrv,
  22. private timeSrv: TimeSrv
  23. ) {
  24. super(instanceSettings);
  25. this.type = 'cloudwatch';
  26. this.proxyUrl = instanceSettings.url;
  27. this.defaultRegion = instanceSettings.jsonData.defaultRegion;
  28. this.instanceSettings = instanceSettings;
  29. this.standardStatistics = ['Average', 'Maximum', 'Minimum', 'Sum', 'SampleCount'];
  30. }
  31. query(options: DataQueryRequest<CloudWatchQuery>) {
  32. options = angular.copy(options);
  33. options.targets = this.expandTemplateVariable(options.targets, options.scopedVars, this.templateSrv);
  34. const queries = _.filter(options.targets, item => {
  35. return (
  36. (item.id !== '' || item.hide !== true) &&
  37. ((!!item.region && !!item.namespace && !!item.metricName && !_.isEmpty(item.statistics)) ||
  38. item.expression.length > 0)
  39. );
  40. }).map(item => {
  41. item.region = this.templateSrv.replace(this.getActualRegion(item.region), options.scopedVars);
  42. item.namespace = this.templateSrv.replace(item.namespace, options.scopedVars);
  43. item.metricName = this.templateSrv.replace(item.metricName, options.scopedVars);
  44. item.dimensions = this.convertDimensionFormat(item.dimensions, options.scopedVars);
  45. item.statistics = item.statistics.map(s => {
  46. return this.templateSrv.replace(s, options.scopedVars);
  47. });
  48. item.period = String(this.getPeriod(item, options)); // use string format for period in graph query, and alerting
  49. item.id = this.templateSrv.replace(item.id, options.scopedVars);
  50. item.expression = this.templateSrv.replace(item.expression, options.scopedVars);
  51. item.returnData = typeof item.hide === 'undefined' ? true : !item.hide;
  52. // valid ExtendedStatistics is like p90.00, check the pattern
  53. const hasInvalidStatistics = item.statistics.some(s => {
  54. if (s.indexOf('p') === 0) {
  55. const matches = /^p\d{2}(?:\.\d{1,2})?$/.exec(s);
  56. return !matches || matches[0] !== s;
  57. }
  58. return false;
  59. });
  60. if (hasInvalidStatistics) {
  61. throw { message: 'Invalid extended statistics' };
  62. }
  63. return _.extend(
  64. {
  65. refId: item.refId,
  66. intervalMs: options.intervalMs,
  67. maxDataPoints: options.maxDataPoints,
  68. datasourceId: this.instanceSettings.id,
  69. type: 'timeSeriesQuery',
  70. },
  71. item
  72. );
  73. });
  74. // No valid targets, return the empty result to save a round trip.
  75. if (_.isEmpty(queries)) {
  76. const d = this.$q.defer();
  77. d.resolve({ data: [] });
  78. return d.promise;
  79. }
  80. const request = {
  81. from: options.range.from.valueOf().toString(),
  82. to: options.range.to.valueOf().toString(),
  83. queries: queries,
  84. };
  85. return this.performTimeSeriesQuery(request);
  86. }
  87. getPeriod(target: any, options: any, now?: number) {
  88. const start = this.convertToCloudWatchTime(options.range.from, false);
  89. const end = this.convertToCloudWatchTime(options.range.to, true);
  90. now = Math.round((now || Date.now()) / 1000);
  91. let period;
  92. const range = end - start;
  93. const hourSec = 60 * 60;
  94. const daySec = hourSec * 24;
  95. let periodUnit = 60;
  96. if (!target.period) {
  97. if (now - start <= daySec * 15) {
  98. // until 15 days ago
  99. if (target.namespace === 'AWS/EC2') {
  100. periodUnit = period = 300;
  101. } else {
  102. periodUnit = period = 60;
  103. }
  104. } else if (now - start <= daySec * 63) {
  105. // until 63 days ago
  106. periodUnit = period = 60 * 5;
  107. } else if (now - start <= daySec * 455) {
  108. // until 455 days ago
  109. periodUnit = period = 60 * 60;
  110. } else {
  111. // over 455 days, should return error, but try to long period
  112. periodUnit = period = 60 * 60;
  113. }
  114. } else {
  115. if (/^\d+$/.test(target.period)) {
  116. period = parseInt(target.period, 10);
  117. } else {
  118. period = kbn.interval_to_seconds(this.templateSrv.replace(target.period, options.scopedVars));
  119. }
  120. }
  121. if (period < 1) {
  122. period = 1;
  123. }
  124. if (!target.highResolution && range / period >= 1440) {
  125. period = Math.ceil(range / 1440 / periodUnit) * periodUnit;
  126. }
  127. return period;
  128. }
  129. performTimeSeriesQuery(request: any) {
  130. return this.awsRequest('/api/tsdb/query', request).then((res: any) => {
  131. const data = [];
  132. if (res.results) {
  133. for (const query of request.queries) {
  134. const queryRes = res.results[query.refId];
  135. if (queryRes) {
  136. for (const series of queryRes.series) {
  137. const s = { target: series.name, datapoints: series.points } as any;
  138. if (queryRes.meta.unit) {
  139. s.unit = queryRes.meta.unit;
  140. }
  141. data.push(s);
  142. }
  143. }
  144. }
  145. }
  146. return { data: data };
  147. });
  148. }
  149. transformSuggestDataFromTable(suggestData: any) {
  150. return _.map(suggestData.results['metricFindQuery'].tables[0].rows, v => {
  151. return {
  152. text: v[0],
  153. value: v[1],
  154. };
  155. });
  156. }
  157. doMetricQueryRequest(subtype: any, parameters: any) {
  158. const range = this.timeSrv.timeRange();
  159. return this.awsRequest('/api/tsdb/query', {
  160. from: range.from.valueOf().toString(),
  161. to: range.to.valueOf().toString(),
  162. queries: [
  163. _.extend(
  164. {
  165. refId: 'metricFindQuery',
  166. intervalMs: 1, // dummy
  167. maxDataPoints: 1, // dummy
  168. datasourceId: this.instanceSettings.id,
  169. type: 'metricFindQuery',
  170. subtype: subtype,
  171. },
  172. parameters
  173. ),
  174. ],
  175. }).then((r: any) => {
  176. return this.transformSuggestDataFromTable(r);
  177. });
  178. }
  179. getRegions() {
  180. return this.doMetricQueryRequest('regions', null);
  181. }
  182. getNamespaces() {
  183. return this.doMetricQueryRequest('namespaces', null);
  184. }
  185. getMetrics(namespace: string, region: string) {
  186. return this.doMetricQueryRequest('metrics', {
  187. region: this.templateSrv.replace(this.getActualRegion(region)),
  188. namespace: this.templateSrv.replace(namespace),
  189. });
  190. }
  191. getDimensionKeys(namespace: string, region: string) {
  192. return this.doMetricQueryRequest('dimension_keys', {
  193. region: this.templateSrv.replace(this.getActualRegion(region)),
  194. namespace: this.templateSrv.replace(namespace),
  195. });
  196. }
  197. getDimensionValues(
  198. region: string,
  199. namespace: string,
  200. metricName: string,
  201. dimensionKey: string,
  202. filterDimensions: {}
  203. ) {
  204. return this.doMetricQueryRequest('dimension_values', {
  205. region: this.templateSrv.replace(this.getActualRegion(region)),
  206. namespace: this.templateSrv.replace(namespace),
  207. metricName: this.templateSrv.replace(metricName),
  208. dimensionKey: this.templateSrv.replace(dimensionKey),
  209. dimensions: this.convertDimensionFormat(filterDimensions, {}),
  210. });
  211. }
  212. getEbsVolumeIds(region: string, instanceId: string) {
  213. return this.doMetricQueryRequest('ebs_volume_ids', {
  214. region: this.templateSrv.replace(this.getActualRegion(region)),
  215. instanceId: this.templateSrv.replace(instanceId),
  216. });
  217. }
  218. getEc2InstanceAttribute(region: string, attributeName: string, filters: any) {
  219. return this.doMetricQueryRequest('ec2_instance_attribute', {
  220. region: this.templateSrv.replace(this.getActualRegion(region)),
  221. attributeName: this.templateSrv.replace(attributeName),
  222. filters: filters,
  223. });
  224. }
  225. getResourceARNs(region: string, resourceType: string, tags: any) {
  226. return this.doMetricQueryRequest('resource_arns', {
  227. region: this.templateSrv.replace(this.getActualRegion(region)),
  228. resourceType: this.templateSrv.replace(resourceType),
  229. tags: tags,
  230. });
  231. }
  232. metricFindQuery(query: string) {
  233. let region;
  234. let namespace;
  235. let metricName;
  236. let filterJson;
  237. const regionQuery = query.match(/^regions\(\)/);
  238. if (regionQuery) {
  239. return this.getRegions();
  240. }
  241. const namespaceQuery = query.match(/^namespaces\(\)/);
  242. if (namespaceQuery) {
  243. return this.getNamespaces();
  244. }
  245. const metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
  246. if (metricNameQuery) {
  247. namespace = metricNameQuery[1];
  248. region = metricNameQuery[3];
  249. return this.getMetrics(namespace, region);
  250. }
  251. const dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
  252. if (dimensionKeysQuery) {
  253. namespace = dimensionKeysQuery[1];
  254. region = dimensionKeysQuery[3];
  255. return this.getDimensionKeys(namespace, region);
  256. }
  257. const dimensionValuesQuery = query.match(
  258. /^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?(.+))?\)/
  259. );
  260. if (dimensionValuesQuery) {
  261. region = dimensionValuesQuery[1];
  262. namespace = dimensionValuesQuery[2];
  263. metricName = dimensionValuesQuery[3];
  264. const dimensionKey = dimensionValuesQuery[4];
  265. filterJson = {};
  266. if (dimensionValuesQuery[6]) {
  267. filterJson = JSON.parse(this.templateSrv.replace(dimensionValuesQuery[6]));
  268. }
  269. return this.getDimensionValues(region, namespace, metricName, dimensionKey, filterJson);
  270. }
  271. const ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  272. if (ebsVolumeIdsQuery) {
  273. region = ebsVolumeIdsQuery[1];
  274. const instanceId = ebsVolumeIdsQuery[2];
  275. return this.getEbsVolumeIds(region, instanceId);
  276. }
  277. const ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
  278. if (ec2InstanceAttributeQuery) {
  279. region = ec2InstanceAttributeQuery[1];
  280. const targetAttributeName = ec2InstanceAttributeQuery[2];
  281. filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3]));
  282. return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson);
  283. }
  284. const resourceARNsQuery = query.match(/^resource_arns\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
  285. if (resourceARNsQuery) {
  286. region = resourceARNsQuery[1];
  287. const resourceType = resourceARNsQuery[2];
  288. const tagsJSON = JSON.parse(this.templateSrv.replace(resourceARNsQuery[3]));
  289. return this.getResourceARNs(region, resourceType, tagsJSON);
  290. }
  291. return this.$q.when([]);
  292. }
  293. annotationQuery(options: any) {
  294. const annotation = options.annotation;
  295. const statistics = _.map(annotation.statistics, s => {
  296. return this.templateSrv.replace(s);
  297. });
  298. const defaultPeriod = annotation.prefixMatching ? '' : '300';
  299. let period = annotation.period || defaultPeriod;
  300. period = parseInt(period, 10);
  301. const parameters = {
  302. prefixMatching: annotation.prefixMatching,
  303. region: this.templateSrv.replace(this.getActualRegion(annotation.region)),
  304. namespace: this.templateSrv.replace(annotation.namespace),
  305. metricName: this.templateSrv.replace(annotation.metricName),
  306. dimensions: this.convertDimensionFormat(annotation.dimensions, {}),
  307. statistics: statistics,
  308. period: period,
  309. actionPrefix: annotation.actionPrefix || '',
  310. alarmNamePrefix: annotation.alarmNamePrefix || '',
  311. };
  312. return this.awsRequest('/api/tsdb/query', {
  313. from: options.range.from.valueOf().toString(),
  314. to: options.range.to.valueOf().toString(),
  315. queries: [
  316. _.extend(
  317. {
  318. refId: 'annotationQuery',
  319. intervalMs: 1, // dummy
  320. maxDataPoints: 1, // dummy
  321. datasourceId: this.instanceSettings.id,
  322. type: 'annotationQuery',
  323. },
  324. parameters
  325. ),
  326. ],
  327. }).then((r: any) => {
  328. return _.map(r.results['annotationQuery'].tables[0].rows, v => {
  329. return {
  330. annotation: annotation,
  331. time: Date.parse(v[0]),
  332. title: v[1],
  333. tags: [v[2]],
  334. text: v[3],
  335. };
  336. });
  337. });
  338. }
  339. targetContainsTemplate(target: any) {
  340. return (
  341. this.templateSrv.variableExists(target.region) ||
  342. this.templateSrv.variableExists(target.namespace) ||
  343. this.templateSrv.variableExists(target.metricName) ||
  344. _.find(target.dimensions, (v, k) => {
  345. return this.templateSrv.variableExists(k) || this.templateSrv.variableExists(v);
  346. })
  347. );
  348. }
  349. testDatasource() {
  350. /* use billing metrics for test */
  351. const region = this.defaultRegion;
  352. const namespace = 'AWS/Billing';
  353. const metricName = 'EstimatedCharges';
  354. const dimensions = {};
  355. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(() => {
  356. return { status: 'success', message: 'Data source is working' };
  357. });
  358. }
  359. awsRequest(url: string, data: any) {
  360. const options = {
  361. method: 'POST',
  362. url,
  363. data,
  364. };
  365. return this.backendSrv.datasourceRequest(options).then((result: any) => {
  366. return result.data;
  367. });
  368. }
  369. getDefaultRegion() {
  370. return this.defaultRegion;
  371. }
  372. getActualRegion(region: string) {
  373. if (region === 'default' || _.isEmpty(region)) {
  374. return this.getDefaultRegion();
  375. }
  376. return region;
  377. }
  378. getExpandedVariables(target: any, dimensionKey: any, variable: any, templateSrv: TemplateSrv) {
  379. /* if the all checkbox is marked we should add all values to the targets */
  380. const allSelected: any = _.find(variable.options, { selected: true, text: 'All' });
  381. const selectedVariables = _.filter(variable.options, v => {
  382. if (allSelected) {
  383. return v.text !== 'All';
  384. } else {
  385. return v.selected;
  386. }
  387. });
  388. const currentVariables = !_.isArray(variable.current.value)
  389. ? [variable.current]
  390. : variable.current.value.map((v: any) => {
  391. return {
  392. text: v,
  393. value: v,
  394. };
  395. });
  396. const useSelectedVariables =
  397. selectedVariables.some((s: any) => {
  398. return s.value === currentVariables[0].value;
  399. }) || currentVariables[0].value === '$__all';
  400. return (useSelectedVariables ? selectedVariables : currentVariables).map((v: any) => {
  401. const t = angular.copy(target);
  402. const scopedVar: any = {};
  403. scopedVar[variable.name] = v;
  404. t.refId = target.refId + '_' + v.value;
  405. t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
  406. if (variable.multi && target.id) {
  407. t.id = target.id + window.btoa(v.value).replace(/=/g, '0'); // generate unique id
  408. } else {
  409. t.id = target.id;
  410. }
  411. return t;
  412. });
  413. }
  414. expandTemplateVariable(targets: any, scopedVars: ScopedVars, templateSrv: TemplateSrv) {
  415. // Datasource and template srv logic uber-complected. This should be cleaned up.
  416. return _.chain(targets)
  417. .map(target => {
  418. if (target.id && target.id.length > 0 && target.expression && target.expression.length > 0) {
  419. return [target];
  420. }
  421. const variableIndex = _.keyBy(templateSrv.variables, 'name');
  422. const dimensionKey = _.findKey(target.dimensions, v => {
  423. const variableName = templateSrv.getVariableName(v);
  424. return templateSrv.variableExists(v) && !_.has(scopedVars, variableName) && variableIndex[variableName].multi;
  425. });
  426. if (dimensionKey) {
  427. const multiVariable = variableIndex[templateSrv.getVariableName(target.dimensions[dimensionKey])];
  428. return this.getExpandedVariables(target, dimensionKey, multiVariable, templateSrv);
  429. } else {
  430. return [target];
  431. }
  432. })
  433. .flatten()
  434. .value();
  435. }
  436. convertToCloudWatchTime(date: any, roundUp: any) {
  437. if (_.isString(date)) {
  438. date = dateMath.parse(date, roundUp);
  439. }
  440. return Math.round(date.valueOf() / 1000);
  441. }
  442. convertDimensionFormat(dimensions: any, scopedVars: ScopedVars) {
  443. const convertedDimensions: any = {};
  444. _.each(dimensions, (value, key) => {
  445. convertedDimensions[this.templateSrv.replace(key, scopedVars)] = this.templateSrv.replace(value, scopedVars);
  446. });
  447. return convertedDimensions;
  448. }
  449. }