datasource.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. this.profile = datasource.jsonData.profile;
  19. }
  20. CloudWatchDatasource.prototype.query = function(options) {
  21. var start = convertToCloudWatchTime(options.range.from);
  22. var end = convertToCloudWatchTime(options.range.to);
  23. var queries = [];
  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 = convertDimensionFormat(target.dimensions);
  33. query.statistics = target.statistics;
  34. query.period = parseInt(target.period, 10);
  35. var range = end - start;
  36. // CloudWatch limit datapoints up to 1440
  37. if (range / query.period >= 1440) {
  38. query.period = Math.floor(range / 1440 / 60) * 60;
  39. }
  40. queries.push(query);
  41. }, this));
  42. // No valid targets, return the empty result to save a round trip.
  43. if (_.isEmpty(queries)) {
  44. var d = $q.defer();
  45. d.resolve({ data: [] });
  46. return d.promise;
  47. }
  48. var allQueryPromise = _.map(queries, function(query) {
  49. return this.performTimeSeriesQuery(query, start, end);
  50. }, this);
  51. return $q.all(allQueryPromise).then(function(allResponse) {
  52. var result = [];
  53. _.each(allResponse, function(response, index) {
  54. var metrics = transformMetricData(response, options.targets[index]);
  55. result = result.concat(metrics);
  56. });
  57. return { data: result };
  58. });
  59. };
  60. CloudWatchDatasource.prototype.performTimeSeriesQuery = function(query, start, end) {
  61. return this.awsRequest({
  62. region: query.region,
  63. profile: this.profile,
  64. action: 'GetMetricStatistics',
  65. parameters: {
  66. namespace: query.namespace,
  67. metricName: query.metricName,
  68. dimensions: query.dimensions,
  69. statistics: query.statistics,
  70. startTime: start,
  71. endTime: end,
  72. period: query.period
  73. }
  74. });
  75. };
  76. CloudWatchDatasource.prototype.getRegions = function() {
  77. return this.awsRequest({action: '__GetRegions'});
  78. };
  79. CloudWatchDatasource.prototype.getNamespaces = function() {
  80. return this.awsRequest({action: '__GetNamespaces'});
  81. };
  82. CloudWatchDatasource.prototype.getMetrics = function(namespace) {
  83. return this.awsRequest({
  84. action: '__GetMetrics',
  85. parameters: {
  86. namespace: templateSrv.replace(namespace)
  87. }
  88. });
  89. };
  90. CloudWatchDatasource.prototype.getDimensionKeys = function(namespace) {
  91. return this.awsRequest({
  92. action: '__GetDimensions',
  93. parameters: {
  94. namespace: templateSrv.replace(namespace)
  95. }
  96. });
  97. };
  98. CloudWatchDatasource.prototype.getDimensionValues = function(region, namespace, metricName, dimensions) {
  99. var request = {
  100. region: templateSrv.replace(region),
  101. profile: this.profile,
  102. action: 'ListMetrics',
  103. parameters: {
  104. namespace: templateSrv.replace(namespace),
  105. metricName: templateSrv.replace(metricName),
  106. dimensions: convertDimensionFormat(dimensions),
  107. }
  108. };
  109. return this.awsRequest(request).then(function(result) {
  110. return _.chain(result.Metrics).map(function(metric) {
  111. return _.pluck(metric.Dimensions, 'Value');
  112. }).flatten().uniq().sortBy(function(name) {
  113. return name;
  114. }).map(function(value) {
  115. return {value: value, text: value};
  116. }).value();
  117. });
  118. };
  119. CloudWatchDatasource.prototype.performEC2DescribeInstances = function(region, filters, instanceIds) {
  120. return this.awsRequest({
  121. region: region,
  122. action: 'DescribeInstances',
  123. parameters: { filter: filters, instanceIds: instanceIds }
  124. });
  125. };
  126. CloudWatchDatasource.prototype.metricFindQuery = function(query) {
  127. var region;
  128. var namespace;
  129. var metricName;
  130. var transformSuggestData = function(suggestData) {
  131. return _.map(suggestData, function(v) {
  132. return { text: v };
  133. });
  134. };
  135. var regionQuery = query.match(/^regions\(\)/);
  136. if (regionQuery) {
  137. return this.getRegions();
  138. }
  139. var namespaceQuery = query.match(/^namespaces\(\)/);
  140. if (namespaceQuery) {
  141. return this.getNamespaces();
  142. }
  143. var metricNameQuery = query.match(/^metrics\(([^\)]+?)\)/);
  144. if (metricNameQuery) {
  145. return this.getMetrics(metricNameQuery[1]);
  146. }
  147. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)\)/);
  148. if (dimensionKeysQuery) {
  149. return this.getDimensionKeys(dimensionKeysQuery[1]);
  150. }
  151. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?([^)]*))?\)/);
  152. if (dimensionValuesQuery) {
  153. region = templateSrv.replace(dimensionValuesQuery[1]);
  154. namespace = templateSrv.replace(dimensionValuesQuery[2]);
  155. metricName = templateSrv.replace(dimensionValuesQuery[3]);
  156. var dimensionPart = templateSrv.replace(dimensionValuesQuery[5]);
  157. var dimensions = {};
  158. if (!_.isEmpty(dimensionPart)) {
  159. _.each(dimensionPart.split(','), function(v) {
  160. var t = v.split('=');
  161. if (t.length !== 2) {
  162. throw new Error('Invalid query format');
  163. }
  164. dimensions[t[0]] = t[1];
  165. });
  166. }
  167. return this.getDimensionValues(region, namespace, metricName, dimensions);
  168. }
  169. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  170. if (ebsVolumeIdsQuery) {
  171. region = templateSrv.replace(ebsVolumeIdsQuery[1]);
  172. var instanceId = templateSrv.replace(ebsVolumeIdsQuery[2]);
  173. var instanceIds = [
  174. instanceId
  175. ];
  176. return this.performEC2DescribeInstances(region, [], instanceIds).then(function(result) {
  177. var volumeIds = _.map(result.Reservations[0].Instances[0].BlockDeviceMappings, function(mapping) {
  178. return mapping.EBS.VolumeID;
  179. });
  180. return transformSuggestData(volumeIds);
  181. });
  182. }
  183. return $q.when([]);
  184. };
  185. CloudWatchDatasource.prototype.testDatasource = function() {
  186. /* use billing metrics for test */
  187. var region = 'us-east-1';
  188. var namespace = 'AWS/Billing';
  189. var metricName = 'EstimatedCharges';
  190. var dimensions = {};
  191. return this.getDimensionValues(region, namespace, metricName, dimensions).then(function () {
  192. return { status: 'success', message: 'Data source is working', title: 'Success' };
  193. });
  194. };
  195. CloudWatchDatasource.prototype.awsRequest = function(data) {
  196. var options = {
  197. method: 'POST',
  198. url: this.proxyUrl,
  199. data: data
  200. };
  201. return backendSrv.datasourceRequest(options).then(function(result) {
  202. return result.data;
  203. });
  204. };
  205. CloudWatchDatasource.prototype.getDefaultRegion = function() {
  206. return this.defaultRegion;
  207. };
  208. function transformMetricData(md, options) {
  209. var aliasRegex = /\{\{(.+?)\}\}/g;
  210. var aliasPattern = options.alias || '{{metric}}_{{stat}}';
  211. var aliasData = {
  212. region: templateSrv.replace(options.region),
  213. namespace: templateSrv.replace(options.namespace),
  214. metric: templateSrv.replace(options.metricName),
  215. };
  216. _.extend(aliasData, options.dimensions);
  217. return _.map(options.statistics, function(stat) {
  218. var dps = _.chain(md.Datapoints).map(function(dp) {
  219. return [dp[stat], new Date(dp.Timestamp).getTime()];
  220. })
  221. .sortBy(function(dp) {
  222. return dp[1];
  223. }).value();
  224. aliasData.stat = stat;
  225. var seriesName = aliasPattern.replace(aliasRegex, function(match, g1) {
  226. if (aliasData[g1]) {
  227. return aliasData[g1];
  228. }
  229. return g1;
  230. });
  231. return {target: seriesName, datapoints: dps};
  232. });
  233. }
  234. function convertToCloudWatchTime(date) {
  235. return Math.round(date.valueOf() / 1000);
  236. }
  237. function convertDimensionFormat(dimensions) {
  238. return _.map(dimensions, function(value, key) {
  239. return {
  240. Name: templateSrv.replace(key),
  241. Value: templateSrv.replace(value)
  242. };
  243. });
  244. }
  245. return CloudWatchDatasource;
  246. });
  247. });