datasource.js 15 KB

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