datasource.ts 14 KB

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