datasource.js 12 KB

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