datasource.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'app/core/utils/datemath',
  6. ],
  7. function (angular, _, moment, dateMath) {
  8. 'use strict';
  9. /** @ngInject */
  10. function CloudWatchDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  11. this.type = 'cloudwatch';
  12. this.name = instanceSettings.name;
  13. this.supportMetrics = true;
  14. this.proxyUrl = instanceSettings.url;
  15. this.defaultRegion = instanceSettings.jsonData.defaultRegion;
  16. this.query = function(options) {
  17. var start = convertToCloudWatchTime(options.range.from, false);
  18. var end = convertToCloudWatchTime(options.range.to, true);
  19. var queries = [];
  20. options = angular.copy(options);
  21. _.each(options.targets, _.bind(function(target) {
  22. if (target.hide || !target.namespace || !target.metricName || _.isEmpty(target.statistics)) {
  23. return;
  24. }
  25. var query = {};
  26. query.region = templateSrv.replace(target.region, options.scopedVars);
  27. query.namespace = templateSrv.replace(target.namespace, options.scopedVars);
  28. query.metricName = templateSrv.replace(target.metricName, options.scopedVars);
  29. query.dimensions = convertDimensionFormat(target.dimensions, options.scopedVars);
  30. query.statistics = target.statistics;
  31. var range = end - start;
  32. query.period = parseInt(target.period, 10) || (query.namespace === 'AWS/EC2' ? 300 : 60);
  33. if (range / query.period >= 1440) {
  34. query.period = Math.ceil(range / 1440 / 60) * 60;
  35. }
  36. target.period = query.period;
  37. queries.push(query);
  38. }, this));
  39. // No valid targets, return the empty result to save a round trip.
  40. if (_.isEmpty(queries)) {
  41. var d = $q.defer();
  42. d.resolve({ data: [] });
  43. return d.promise;
  44. }
  45. var allQueryPromise = _.map(queries, function(query) {
  46. return this.performTimeSeriesQuery(query, start, end);
  47. }, this);
  48. return $q.all(allQueryPromise).then(function(allResponse) {
  49. var result = [];
  50. _.each(allResponse, function(response, index) {
  51. var metrics = transformMetricData(response, options.targets[index], options.scopedVars);
  52. result = result.concat(metrics);
  53. });
  54. return { data: result };
  55. });
  56. };
  57. this.performTimeSeriesQuery = function(query, start, end) {
  58. return this.awsRequest({
  59. region: query.region,
  60. action: 'GetMetricStatistics',
  61. parameters: {
  62. namespace: query.namespace,
  63. metricName: query.metricName,
  64. dimensions: query.dimensions,
  65. statistics: query.statistics,
  66. startTime: start,
  67. endTime: end,
  68. period: query.period
  69. }
  70. });
  71. };
  72. this.getRegions = function() {
  73. return this.awsRequest({action: '__GetRegions'});
  74. };
  75. this.getNamespaces = function() {
  76. return this.awsRequest({action: '__GetNamespaces'});
  77. };
  78. this.getMetrics = function(namespace, region) {
  79. return this.awsRequest({
  80. action: '__GetMetrics',
  81. region: region,
  82. parameters: {
  83. namespace: templateSrv.replace(namespace)
  84. }
  85. });
  86. };
  87. this.getDimensionKeys = function(namespace, region) {
  88. return this.awsRequest({
  89. action: '__GetDimensions',
  90. region: region,
  91. parameters: {
  92. namespace: templateSrv.replace(namespace)
  93. }
  94. });
  95. };
  96. this.getDimensionValues = function(region, namespace, metricName, dimensionKey, filterDimensions) {
  97. var request = {
  98. region: templateSrv.replace(region),
  99. action: 'ListMetrics',
  100. parameters: {
  101. namespace: templateSrv.replace(namespace),
  102. metricName: templateSrv.replace(metricName),
  103. dimensions: convertDimensionFormat(filterDimensions, {}),
  104. }
  105. };
  106. return this.awsRequest(request).then(function(result) {
  107. return _.chain(result.Metrics)
  108. .pluck('Dimensions')
  109. .flatten()
  110. .filter(function(dimension) {
  111. return dimension !== null && dimension.Name === dimensionKey;
  112. })
  113. .pluck('Value')
  114. .uniq()
  115. .sortBy()
  116. .map(function(value) {
  117. return {value: value, text: value};
  118. }).value();
  119. });
  120. };
  121. this.performEC2DescribeInstances = function(region, filters, instanceIds) {
  122. return this.awsRequest({
  123. region: region,
  124. action: 'DescribeInstances',
  125. parameters: { filter: filters, instanceIds: instanceIds }
  126. });
  127. };
  128. this.metricFindQuery = function(query) {
  129. var region;
  130. var namespace;
  131. var metricName;
  132. var transformSuggestData = function(suggestData) {
  133. return _.map(suggestData, function(v) {
  134. return { text: v };
  135. });
  136. };
  137. var regionQuery = query.match(/^regions\(\)/);
  138. if (regionQuery) {
  139. return this.getRegions();
  140. }
  141. var namespaceQuery = query.match(/^namespaces\(\)/);
  142. if (namespaceQuery) {
  143. return this.getNamespaces();
  144. }
  145. var metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
  146. if (metricNameQuery) {
  147. return this.getMetrics(metricNameQuery[1], metricNameQuery[3]);
  148. }
  149. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
  150. if (dimensionKeysQuery) {
  151. return this.getDimensionKeys(dimensionKeysQuery[1], dimensionKeysQuery[3]);
  152. }
  153. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/);
  154. if (dimensionValuesQuery) {
  155. region = templateSrv.replace(dimensionValuesQuery[1]);
  156. namespace = templateSrv.replace(dimensionValuesQuery[2]);
  157. metricName = templateSrv.replace(dimensionValuesQuery[3]);
  158. var dimensionKey = templateSrv.replace(dimensionValuesQuery[4]);
  159. return this.getDimensionValues(region, namespace, metricName, dimensionKey, {});
  160. }
  161. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  162. if (ebsVolumeIdsQuery) {
  163. region = templateSrv.replace(ebsVolumeIdsQuery[1]);
  164. var instanceId = templateSrv.replace(ebsVolumeIdsQuery[2]);
  165. var instanceIds = [
  166. instanceId
  167. ];
  168. return this.performEC2DescribeInstances(region, [], instanceIds).then(function(result) {
  169. var volumeIds = _.map(result.Reservations[0].Instances[0].BlockDeviceMappings, function(mapping) {
  170. return mapping.Ebs.VolumeId;
  171. });
  172. return transformSuggestData(volumeIds);
  173. });
  174. }
  175. return $q.when([]);
  176. };
  177. this.performDescribeAlarmsForMetric = function(region, namespace, metricName, dimensions, statistic, period) {
  178. return this.awsRequest({
  179. region: region,
  180. action: 'DescribeAlarmsForMetric',
  181. parameters: { namespace: namespace, metricName: metricName, dimensions: dimensions, statistic: statistic, period: period }
  182. });
  183. };
  184. this.performDescribeAlarmHistory = function(region, alarmName, startDate, endDate) {
  185. return this.awsRequest({
  186. region: region,
  187. action: 'DescribeAlarmHistory',
  188. parameters: { alarmName: alarmName, startDate: startDate, endDate: endDate }
  189. });
  190. };
  191. this.annotationQuery = function(options) {
  192. var annotation = options.annotation;
  193. var region = templateSrv.replace(annotation.region);
  194. var namespace = templateSrv.replace(annotation.namespace);
  195. var metricName = templateSrv.replace(annotation.metricName);
  196. var dimensions = convertDimensionFormat(annotation.dimensions);
  197. var statistics = _.map(annotation.statistics, function(s) { return templateSrv.replace(s); });
  198. var period = annotation.period || '300';
  199. period = parseInt(period, 10);
  200. if (!region || !namespace || !metricName || _.isEmpty(statistics)) { return $q.when([]); }
  201. var d = $q.defer();
  202. var self = this;
  203. var allQueryPromise = _.map(statistics, function(statistic) {
  204. return self.performDescribeAlarmsForMetric(region, namespace, metricName, dimensions, statistic, period);
  205. });
  206. $q.all(allQueryPromise).then(function(alarms) {
  207. var eventList = [];
  208. var start = convertToCloudWatchTime(options.range.from, false);
  209. var end = convertToCloudWatchTime(options.range.to, true);
  210. _.chain(alarms)
  211. .pluck('MetricAlarms')
  212. .flatten()
  213. .each(function(alarm) {
  214. if (!alarm) {
  215. d.resolve(eventList);
  216. return;
  217. }
  218. self.performDescribeAlarmHistory(region, alarm.AlarmName, start, end).then(function(history) {
  219. _.each(history.AlarmHistoryItems, function(h) {
  220. var event = {
  221. annotation: annotation,
  222. time: Date.parse(h.Timestamp),
  223. title: h.AlarmName,
  224. tags: [h.HistoryItemType],
  225. text: h.HistorySummary
  226. };
  227. eventList.push(event);
  228. });
  229. d.resolve(eventList);
  230. });
  231. });
  232. });
  233. return d.promise;
  234. };
  235. this.testDatasource = function() {
  236. /* use billing metrics for test */
  237. var region = this.defaultRegion;
  238. var namespace = 'AWS/Billing';
  239. var metricName = 'EstimatedCharges';
  240. var dimensions = {};
  241. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(function () {
  242. return { status: 'success', message: 'Data source is working', title: 'Success' };
  243. });
  244. };
  245. this.awsRequest = function(data) {
  246. var options = {
  247. method: 'POST',
  248. url: this.proxyUrl,
  249. data: data
  250. };
  251. return backendSrv.datasourceRequest(options).then(function(result) {
  252. return result.data;
  253. });
  254. };
  255. this.getDefaultRegion = function() {
  256. return this.defaultRegion;
  257. };
  258. function transformMetricData(md, options, scopedVars) {
  259. var aliasRegex = /\{\{(.+?)\}\}/g;
  260. var aliasPattern = options.alias || '{{metric}}_{{stat}}';
  261. var aliasData = {
  262. region: templateSrv.replace(options.region, scopedVars),
  263. namespace: templateSrv.replace(options.namespace, scopedVars),
  264. metric: templateSrv.replace(options.metricName, scopedVars),
  265. };
  266. var aliasDimensions = {};
  267. _.each(_.keys(options.dimensions), function(origKey) {
  268. var key = templateSrv.replace(origKey, scopedVars);
  269. var value = templateSrv.replace(options.dimensions[origKey], scopedVars);
  270. aliasDimensions[key] = value;
  271. });
  272. _.extend(aliasData, aliasDimensions);
  273. var periodMs = options.period * 1000;
  274. return _.map(options.statistics, function(stat) {
  275. var dps = [];
  276. var lastTimestamp = null;
  277. _.chain(md.Datapoints)
  278. .sortBy(function(dp) {
  279. return dp.Timestamp;
  280. })
  281. .each(function(dp) {
  282. var timestamp = new Date(dp.Timestamp).getTime();
  283. if (lastTimestamp && (timestamp - lastTimestamp) > periodMs) {
  284. dps.push([null, lastTimestamp + periodMs]);
  285. }
  286. lastTimestamp = timestamp;
  287. dps.push([dp[stat], timestamp]);
  288. });
  289. aliasData.stat = stat;
  290. var seriesName = aliasPattern.replace(aliasRegex, function(match, g1) {
  291. if (aliasData[g1]) {
  292. return aliasData[g1];
  293. }
  294. return g1;
  295. });
  296. return {target: seriesName, datapoints: dps};
  297. });
  298. }
  299. function convertToCloudWatchTime(date, roundUp) {
  300. if (_.isString(date)) {
  301. date = dateMath.parse(date, roundUp);
  302. }
  303. return Math.round(date.valueOf() / 1000);
  304. }
  305. function convertDimensionFormat(dimensions, scopedVars) {
  306. return _.map(dimensions, function(value, key) {
  307. return {
  308. Name: templateSrv.replace(key, scopedVars),
  309. Value: templateSrv.replace(value, scopedVars)
  310. };
  311. });
  312. }
  313. }
  314. return {
  315. CloudWatchDatasource: CloudWatchDatasource
  316. };
  317. });