datasource.ts 16 KB

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