datasource.ts 16 KB

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