datasource.ts 16 KB

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