datasource.js 12 KB

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