datasource.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'app/core/utils/datemath',
  6. 'app/core/utils/kbn',
  7. 'app/features/templating/variable',
  8. './annotation_query',
  9. ],
  10. function (angular, _, moment, dateMath, kbn, templatingVariable, CloudWatchAnnotationQuery) {
  11. 'use strict';
  12. /** @ngInject */
  13. function CloudWatchDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  14. this.type = 'cloudwatch';
  15. this.name = instanceSettings.name;
  16. this.supportMetrics = true;
  17. this.proxyUrl = instanceSettings.url;
  18. this.defaultRegion = instanceSettings.jsonData.defaultRegion;
  19. this.standardStatistics = [
  20. 'Average',
  21. 'Maximum',
  22. 'Minimum',
  23. 'Sum',
  24. 'SampleCount'
  25. ];
  26. var self = this;
  27. this.query = function(options) {
  28. var start = self.convertToCloudWatchTime(options.range.from, false);
  29. var end = self.convertToCloudWatchTime(options.range.to, true);
  30. var queries = [];
  31. options = angular.copy(options);
  32. options.targets = this.expandTemplateVariable(options.targets, options.scopedVars, templateSrv);
  33. _.each(options.targets, function(target) {
  34. if (target.hide || !target.namespace || !target.metricName || _.isEmpty(target.statistics)) {
  35. return;
  36. }
  37. var query = {};
  38. query.region = templateSrv.replace(target.region, options.scopedVars);
  39. query.namespace = templateSrv.replace(target.namespace, options.scopedVars);
  40. query.metricName = templateSrv.replace(target.metricName, options.scopedVars);
  41. query.dimensions = self.convertDimensionFormat(target.dimensions, options.scopedVars);
  42. query.statistics = target.statistics;
  43. var now = Math.round(Date.now() / 1000);
  44. var period = this.getPeriod(target, query, options, start, end, now);
  45. target.period = period;
  46. query.period = period;
  47. queries.push(query);
  48. }.bind(this));
  49. // No valid targets, return the empty result to save a round trip.
  50. if (_.isEmpty(queries)) {
  51. var d = $q.defer();
  52. d.resolve({ data: [] });
  53. return d.promise;
  54. }
  55. var allQueryPromise = _.map(queries, function(query) {
  56. return this.performTimeSeriesQuery(query, start, end);
  57. }.bind(this));
  58. return $q.all(allQueryPromise).then(function(allResponse) {
  59. var result = [];
  60. _.each(allResponse, function(response, index) {
  61. var metrics = transformMetricData(response, options.targets[index], options.scopedVars);
  62. result = result.concat(metrics);
  63. });
  64. return {data: result};
  65. });
  66. };
  67. this.getPeriod = function(target, query, options, start, end, now) {
  68. var period;
  69. var range = end - start;
  70. var hourSec = 60 * 60;
  71. var daySec = hourSec * 24;
  72. var periodUnit = 60;
  73. if (!target.period) {
  74. if (now - start <= (daySec * 15)) { // until 15 days ago
  75. if (query.namespace === 'AWS/EC2') {
  76. periodUnit = period = 300;
  77. } else {
  78. periodUnit = period = 60;
  79. }
  80. } else if (now - start <= (daySec * 63)) { // until 63 days ago
  81. periodUnit = period = 60 * 5;
  82. } else if (now - start <= (daySec * 455)) { // until 455 days ago
  83. periodUnit = period = 60 * 60;
  84. } else { // over 455 days, should return error, but try to long period
  85. periodUnit = period = 60 * 60;
  86. }
  87. } else {
  88. if (/^\d+$/.test(target.period)) {
  89. period = parseInt(target.period, 10);
  90. } else {
  91. period = kbn.interval_to_seconds(templateSrv.replace(target.period, options.scopedVars));
  92. }
  93. }
  94. if (period < 1) {
  95. period = 1;
  96. }
  97. if (range / period >= 1440) {
  98. period = Math.ceil(range / 1440 / periodUnit) * periodUnit;
  99. }
  100. return period;
  101. };
  102. this.performTimeSeriesQuery = function(query, start, end) {
  103. var statistics = _.filter(query.statistics, function(s) { return _.includes(self.standardStatistics, s); });
  104. var extendedStatistics = _.reject(query.statistics, function(s) { return _.includes(self.standardStatistics, s); });
  105. return this.awsRequest({
  106. region: query.region,
  107. action: 'GetMetricStatistics',
  108. parameters: {
  109. namespace: query.namespace,
  110. metricName: query.metricName,
  111. dimensions: query.dimensions,
  112. statistics: statistics,
  113. extendedStatistics: extendedStatistics,
  114. startTime: start,
  115. endTime: end,
  116. period: query.period
  117. }
  118. });
  119. };
  120. this.getRegions = function() {
  121. return this.awsRequest({action: '__GetRegions'});
  122. };
  123. this.getNamespaces = function() {
  124. return this.awsRequest({action: '__GetNamespaces'});
  125. };
  126. this.getMetrics = function(namespace, region) {
  127. return this.awsRequest({
  128. action: '__GetMetrics',
  129. region: region,
  130. parameters: {
  131. namespace: templateSrv.replace(namespace)
  132. }
  133. });
  134. };
  135. this.getDimensionKeys = function(namespace, region) {
  136. return this.awsRequest({
  137. action: '__GetDimensions',
  138. region: region,
  139. parameters: {
  140. namespace: templateSrv.replace(namespace)
  141. }
  142. });
  143. };
  144. this.getDimensionValues = function(region, namespace, metricName, dimensionKey, filterDimensions) {
  145. var request = {
  146. region: templateSrv.replace(region),
  147. action: 'ListMetrics',
  148. parameters: {
  149. namespace: templateSrv.replace(namespace),
  150. metricName: templateSrv.replace(metricName),
  151. dimensions: this.convertDimensionFormat(filterDimensions, {}),
  152. }
  153. };
  154. return this.awsRequest(request).then(function(result) {
  155. return _.chain(result.Metrics)
  156. .map('Dimensions')
  157. .flatten()
  158. .filter(function(dimension) {
  159. return dimension !== null && dimension.Name === dimensionKey;
  160. })
  161. .map('Value')
  162. .uniq()
  163. .sortBy()
  164. .map(function(value) {
  165. return {value: value, text: value};
  166. }).value();
  167. });
  168. };
  169. this.performEC2DescribeInstances = function(region, filters, instanceIds) {
  170. return this.awsRequest({
  171. region: region,
  172. action: 'DescribeInstances',
  173. parameters: { filters: filters, instanceIds: instanceIds }
  174. });
  175. };
  176. this.metricFindQuery = function(query) {
  177. var region;
  178. var namespace;
  179. var metricName;
  180. var transformSuggestData = function(suggestData) {
  181. return _.map(suggestData, function(v) {
  182. return { text: v };
  183. });
  184. };
  185. var regionQuery = query.match(/^regions\(\)/);
  186. if (regionQuery) {
  187. return this.getRegions();
  188. }
  189. var namespaceQuery = query.match(/^namespaces\(\)/);
  190. if (namespaceQuery) {
  191. return this.getNamespaces();
  192. }
  193. var metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
  194. if (metricNameQuery) {
  195. return this.getMetrics(templateSrv.replace(metricNameQuery[1]), templateSrv.replace(metricNameQuery[3]));
  196. }
  197. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
  198. if (dimensionKeysQuery) {
  199. return this.getDimensionKeys(templateSrv.replace(dimensionKeysQuery[1]), templateSrv.replace(dimensionKeysQuery[3]));
  200. }
  201. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/);
  202. if (dimensionValuesQuery) {
  203. region = templateSrv.replace(dimensionValuesQuery[1]);
  204. namespace = templateSrv.replace(dimensionValuesQuery[2]);
  205. metricName = templateSrv.replace(dimensionValuesQuery[3]);
  206. var dimensionKey = templateSrv.replace(dimensionValuesQuery[4]);
  207. return this.getDimensionValues(region, namespace, metricName, dimensionKey, {});
  208. }
  209. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  210. if (ebsVolumeIdsQuery) {
  211. region = templateSrv.replace(ebsVolumeIdsQuery[1]);
  212. var instanceId = templateSrv.replace(ebsVolumeIdsQuery[2]);
  213. var instanceIds = [
  214. instanceId
  215. ];
  216. return this.performEC2DescribeInstances(region, [], instanceIds).then(function(result) {
  217. var volumeIds = _.map(result.Reservations[0].Instances[0].BlockDeviceMappings, function(mapping) {
  218. return mapping.Ebs.VolumeId;
  219. });
  220. return transformSuggestData(volumeIds);
  221. });
  222. }
  223. var ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
  224. if (ec2InstanceAttributeQuery) {
  225. region = templateSrv.replace(ec2InstanceAttributeQuery[1]);
  226. var filterJson = JSON.parse(templateSrv.replace(ec2InstanceAttributeQuery[3]));
  227. var filters = _.map(filterJson, function(values, name) {
  228. return {
  229. Name: name,
  230. Values: values
  231. };
  232. });
  233. var targetAttributeName = templateSrv.replace(ec2InstanceAttributeQuery[2]);
  234. return this.performEC2DescribeInstances(region, filters, null).then(function(result) {
  235. var attributes = _.chain(result.Reservations)
  236. .map(function(reservations) {
  237. return _.map(reservations.Instances, function(instance) {
  238. var tags = {};
  239. _.each(instance.Tags, function(tag) {
  240. tags[tag.Key] = tag.Value;
  241. });
  242. instance.Tags = tags;
  243. return instance;
  244. });
  245. })
  246. .map(function(instances) {
  247. return _.map(instances, targetAttributeName);
  248. })
  249. .flatten().uniq().sortBy().value();
  250. return transformSuggestData(attributes);
  251. });
  252. }
  253. return $q.when([]);
  254. };
  255. this.performDescribeAlarms = function(region, actionPrefix, alarmNamePrefix, alarmNames, stateValue) {
  256. return this.awsRequest({
  257. region: region,
  258. action: 'DescribeAlarms',
  259. parameters: { actionPrefix: actionPrefix, alarmNamePrefix: alarmNamePrefix, alarmNames: alarmNames, stateValue: stateValue }
  260. });
  261. };
  262. this.performDescribeAlarmsForMetric = function(region, namespace, metricName, dimensions, statistic, period) {
  263. var s = _.includes(self.standardStatistics, statistic) ? statistic : '';
  264. var es = _.includes(self.standardStatistics, statistic) ? '' : statistic;
  265. return this.awsRequest({
  266. region: region,
  267. action: 'DescribeAlarmsForMetric',
  268. parameters: {
  269. namespace: namespace,
  270. metricName: metricName,
  271. dimensions: dimensions,
  272. statistic: s,
  273. extendedStatistic: es,
  274. period: period
  275. }
  276. });
  277. };
  278. this.performDescribeAlarmHistory = function(region, alarmName, startDate, endDate) {
  279. return this.awsRequest({
  280. region: region,
  281. action: 'DescribeAlarmHistory',
  282. parameters: { alarmName: alarmName, startDate: startDate, endDate: endDate }
  283. });
  284. };
  285. this.annotationQuery = function(options) {
  286. var annotationQuery = new CloudWatchAnnotationQuery(this, options.annotation, $q, templateSrv);
  287. return annotationQuery.process(options.range.from, options.range.to);
  288. };
  289. this.testDatasource = function() {
  290. /* use billing metrics for test */
  291. var region = this.defaultRegion;
  292. var namespace = 'AWS/Billing';
  293. var metricName = 'EstimatedCharges';
  294. var dimensions = {};
  295. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(function () {
  296. return { status: 'success', message: 'Data source is working', title: 'Success' };
  297. });
  298. };
  299. this.awsRequest = function(data) {
  300. var options = {
  301. method: 'POST',
  302. url: this.proxyUrl,
  303. data: data
  304. };
  305. return backendSrv.datasourceRequest(options).then(function(result) {
  306. return result.data;
  307. });
  308. };
  309. this.getDefaultRegion = function() {
  310. return this.defaultRegion;
  311. };
  312. function transformMetricData(md, options, scopedVars) {
  313. var aliasRegex = /\{\{(.+?)\}\}/g;
  314. var aliasPattern = options.alias || '{{metric}}_{{stat}}';
  315. var aliasData = {
  316. region: templateSrv.replace(options.region, scopedVars),
  317. namespace: templateSrv.replace(options.namespace, scopedVars),
  318. metric: templateSrv.replace(options.metricName, scopedVars),
  319. };
  320. var aliasDimensions = {};
  321. _.each(_.keys(options.dimensions), function(origKey) {
  322. var key = templateSrv.replace(origKey, scopedVars);
  323. var value = templateSrv.replace(options.dimensions[origKey], scopedVars);
  324. aliasDimensions[key] = value;
  325. });
  326. _.extend(aliasData, aliasDimensions);
  327. var periodMs = options.period * 1000;
  328. return _.map(options.statistics, function(stat) {
  329. var extended = !_.includes(self.standardStatistics, stat);
  330. var dps = [];
  331. var lastTimestamp = null;
  332. _.chain(md.Datapoints)
  333. .sortBy(function(dp) {
  334. return dp.Timestamp;
  335. })
  336. .each(function(dp) {
  337. var timestamp = new Date(dp.Timestamp).getTime();
  338. if (lastTimestamp && (timestamp - lastTimestamp) > periodMs) {
  339. dps.push([null, lastTimestamp + periodMs]);
  340. }
  341. lastTimestamp = timestamp;
  342. if (!extended) {
  343. dps.push([dp[stat], timestamp]);
  344. } else {
  345. dps.push([dp.ExtendedStatistics[stat], timestamp]);
  346. }
  347. })
  348. .value();
  349. aliasData.stat = stat;
  350. var seriesName = aliasPattern.replace(aliasRegex, function(match, g1) {
  351. if (aliasData[g1]) {
  352. return aliasData[g1];
  353. }
  354. return g1;
  355. });
  356. return {target: seriesName, datapoints: dps};
  357. });
  358. }
  359. this.getExpandedVariables = function(target, dimensionKey, variable, templateSrv) {
  360. /* if the all checkbox is marked we should add all values to the targets */
  361. var allSelected = _.find(variable.options, {'selected': true, 'text': 'All'});
  362. return _.chain(variable.options)
  363. .filter(function(v) {
  364. if (allSelected) {
  365. return v.text !== 'All';
  366. } else {
  367. return v.selected;
  368. }
  369. })
  370. .map(function(v) {
  371. var t = angular.copy(target);
  372. var scopedVar = {};
  373. scopedVar[variable.name] = v;
  374. t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
  375. return t;
  376. }).value();
  377. };
  378. this.expandTemplateVariable = function(targets, scopedVars, templateSrv) {
  379. var self = this;
  380. return _.chain(targets)
  381. .map(function(target) {
  382. var dimensionKey = _.findKey(target.dimensions, function(v) {
  383. return templateSrv.variableExists(v) && !_.has(scopedVars, templateSrv.getVariableName(v));
  384. });
  385. if (dimensionKey) {
  386. var multiVariable = _.find(templateSrv.variables, function(variable) {
  387. return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name) && variable.multi;
  388. });
  389. var variable = _.find(templateSrv.variables, function(variable) {
  390. return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name);
  391. });
  392. return self.getExpandedVariables(target, dimensionKey, multiVariable || variable, templateSrv);
  393. } else {
  394. return [target];
  395. }
  396. }).flatten().value();
  397. };
  398. this.convertToCloudWatchTime = function(date, roundUp) {
  399. if (_.isString(date)) {
  400. date = dateMath.parse(date, roundUp);
  401. }
  402. return Math.round(date.valueOf() / 1000);
  403. };
  404. this.convertDimensionFormat = function(dimensions, scopedVars) {
  405. return _.map(dimensions, function(value, key) {
  406. return {
  407. Name: templateSrv.replace(key, scopedVars),
  408. Value: templateSrv.replace(value, scopedVars)
  409. };
  410. });
  411. };
  412. }
  413. return {
  414. CloudWatchDatasource: CloudWatchDatasource
  415. };
  416. });