datasource.js 11 KB

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