datasource.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. './query_ctrl',
  6. './directives',
  7. ],
  8. function (angular, _) {
  9. 'use strict';
  10. var module = angular.module('grafana.services');
  11. module.factory('CloudWatchDatasource', function($q, backendSrv, templateSrv) {
  12. function CloudWatchDatasource(datasource) {
  13. this.type = 'cloudwatch';
  14. this.name = datasource.name;
  15. this.supportMetrics = true;
  16. this.proxyUrl = datasource.url;
  17. this.defaultRegion = datasource.jsonData.defaultRegion;
  18. }
  19. CloudWatchDatasource.prototype.query = function(options) {
  20. var start = convertToCloudWatchTime(options.range.from);
  21. var end = convertToCloudWatchTime(options.range.to);
  22. var queries = [];
  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 = convertDimensionFormat(target.dimensions);
  32. query.statistics = target.statistics;
  33. query.period = parseInt(target.period, 10);
  34. var range = end - start;
  35. // CloudWatch limit datapoints up to 1440
  36. if (range / query.period >= 1440) {
  37. query.period = Math.floor(range / 1440 / 60) * 60;
  38. }
  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]);
  54. result = result.concat(metrics);
  55. });
  56. return { data: result };
  57. });
  58. };
  59. CloudWatchDatasource.prototype.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. CloudWatchDatasource.prototype.getRegions = function() {
  75. return this.awsRequest({action: '__GetRegions'});
  76. };
  77. CloudWatchDatasource.prototype.getNamespaces = function() {
  78. return this.awsRequest({action: '__GetNamespaces'});
  79. };
  80. CloudWatchDatasource.prototype.getMetrics = function(namespace) {
  81. return this.awsRequest({
  82. action: '__GetMetrics',
  83. parameters: {
  84. namespace: templateSrv.replace(namespace)
  85. }
  86. });
  87. };
  88. CloudWatchDatasource.prototype.getDimensionKeys = function(namespace) {
  89. return this.awsRequest({
  90. action: '__GetDimensions',
  91. parameters: {
  92. namespace: templateSrv.replace(namespace)
  93. }
  94. });
  95. };
  96. CloudWatchDatasource.prototype.getDimensionValues = function(region, namespace, metricName, dimensions) {
  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(dimensions),
  104. }
  105. };
  106. return this.awsRequest(request).then(function(result) {
  107. return _.chain(result.Metrics).map(function(metric) {
  108. return _.pluck(metric.Dimensions, 'Value');
  109. }).flatten().uniq().sortBy(function(name) {
  110. return name;
  111. }).map(function(value) {
  112. return {value: value, text: value};
  113. }).value();
  114. });
  115. };
  116. CloudWatchDatasource.prototype.performEC2DescribeInstances = function(region, filters, instanceIds) {
  117. return this.awsRequest({
  118. region: region,
  119. action: 'DescribeInstances',
  120. parameters: { filter: filters, instanceIds: instanceIds }
  121. });
  122. };
  123. CloudWatchDatasource.prototype.metricFindQuery = function(query) {
  124. var region;
  125. var namespace;
  126. var metricName;
  127. var transformSuggestData = function(suggestData) {
  128. return _.map(suggestData, function(v) {
  129. return { text: v };
  130. });
  131. };
  132. var regionQuery = query.match(/^regions\(\)/);
  133. if (regionQuery) {
  134. return this.getRegions();
  135. }
  136. var namespaceQuery = query.match(/^namespaces\(\)/);
  137. if (namespaceQuery) {
  138. return this.getNamespaces();
  139. }
  140. var metricNameQuery = query.match(/^metrics\(([^\)]+?)\)/);
  141. if (metricNameQuery) {
  142. return this.getMetrics(metricNameQuery[1]);
  143. }
  144. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)\)/);
  145. if (dimensionKeysQuery) {
  146. return this.getDimensionKeys(dimensionKeysQuery[1]);
  147. }
  148. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?([^)]*))?\)/);
  149. if (dimensionValuesQuery) {
  150. region = templateSrv.replace(dimensionValuesQuery[1]);
  151. namespace = templateSrv.replace(dimensionValuesQuery[2]);
  152. metricName = templateSrv.replace(dimensionValuesQuery[3]);
  153. var dimensionPart = templateSrv.replace(dimensionValuesQuery[5]);
  154. var dimensions = {};
  155. if (!_.isEmpty(dimensionPart)) {
  156. _.each(dimensionPart.split(','), function(v) {
  157. var t = v.split('=');
  158. if (t.length !== 2) {
  159. throw new Error('Invalid query format');
  160. }
  161. dimensions[t[0]] = t[1];
  162. });
  163. }
  164. return this.getDimensionValues(region, namespace, metricName, dimensions);
  165. }
  166. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  167. if (ebsVolumeIdsQuery) {
  168. region = templateSrv.replace(ebsVolumeIdsQuery[1]);
  169. var instanceId = templateSrv.replace(ebsVolumeIdsQuery[2]);
  170. var instanceIds = [
  171. instanceId
  172. ];
  173. return this.performEC2DescribeInstances(region, [], instanceIds).then(function(result) {
  174. var volumeIds = _.map(result.Reservations[0].Instances[0].BlockDeviceMappings, function(mapping) {
  175. return mapping.EBS.VolumeID;
  176. });
  177. return transformSuggestData(volumeIds);
  178. });
  179. }
  180. return $q.when([]);
  181. };
  182. CloudWatchDatasource.prototype.testDatasource = function() {
  183. /* use billing metrics for test */
  184. var region = 'us-east-1';
  185. var namespace = 'AWS/Billing';
  186. var metricName = 'EstimatedCharges';
  187. var dimensions = {};
  188. return this.getDimensionValues(region, namespace, metricName, dimensions).then(function () {
  189. return { status: 'success', message: 'Data source is working', title: 'Success' };
  190. });
  191. };
  192. CloudWatchDatasource.prototype.awsRequest = function(data) {
  193. var options = {
  194. method: 'POST',
  195. url: this.proxyUrl,
  196. data: data
  197. };
  198. return backendSrv.datasourceRequest(options).then(function(result) {
  199. return result.data;
  200. });
  201. };
  202. CloudWatchDatasource.prototype.getDefaultRegion = function() {
  203. return this.defaultRegion;
  204. };
  205. function transformMetricData(md, options) {
  206. var aliasRegex = /\{\{(.+?)\}\}/g;
  207. var aliasPattern = options.alias || '{{metric}}_{{stat}}';
  208. var aliasData = {
  209. region: templateSrv.replace(options.region),
  210. namespace: templateSrv.replace(options.namespace),
  211. metric: templateSrv.replace(options.metricName),
  212. };
  213. _.extend(aliasData, options.dimensions);
  214. return _.map(options.statistics, function(stat) {
  215. var dps = _.chain(md.Datapoints).map(function(dp) {
  216. return [dp[stat], new Date(dp.Timestamp).getTime()];
  217. })
  218. .sortBy(function(dp) {
  219. return dp[1];
  220. }).value();
  221. aliasData.stat = stat;
  222. var seriesName = aliasPattern.replace(aliasRegex, function(match, g1) {
  223. if (aliasData[g1]) {
  224. return aliasData[g1];
  225. }
  226. return g1;
  227. });
  228. return {target: seriesName, datapoints: dps};
  229. });
  230. }
  231. function convertToCloudWatchTime(date) {
  232. return Math.round(date.valueOf() / 1000);
  233. }
  234. function convertDimensionFormat(dimensions) {
  235. return _.map(dimensions, function(value, key) {
  236. return {
  237. Name: templateSrv.replace(key),
  238. Value: templateSrv.replace(value)
  239. };
  240. });
  241. }
  242. return CloudWatchDatasource;
  243. });
  244. });