datasource.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. 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 = convertDimensionFormat(target.dimensions, options.scopedVars);
  33. query.statistics = target.statistics;
  34. var range = end - start;
  35. query.period = parseInt(target.period, 10) || (query.namespace === 'AWS/EC2' ? 300 : 60);
  36. if (range / query.period >= 1440) {
  37. query.period = Math.ceil(range / 1440 / 60) * 60;
  38. }
  39. target.period = query.period;
  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. action: 'GetMetricStatistics',
  64. parameters: {
  65. namespace: query.namespace,
  66. metricName: query.metricName,
  67. dimensions: query.dimensions,
  68. statistics: query.statistics,
  69. startTime: start,
  70. endTime: end,
  71. period: query.period
  72. }
  73. });
  74. };
  75. CloudWatchDatasource.prototype.getRegions = function() {
  76. return this.awsRequest({action: '__GetRegions'});
  77. };
  78. CloudWatchDatasource.prototype.getNamespaces = function() {
  79. return this.awsRequest({action: '__GetNamespaces'});
  80. };
  81. CloudWatchDatasource.prototype.getMetrics = function(namespace) {
  82. return this.awsRequest({
  83. action: '__GetMetrics',
  84. parameters: {
  85. namespace: templateSrv.replace(namespace)
  86. }
  87. });
  88. };
  89. CloudWatchDatasource.prototype.getDimensionKeys = function(namespace) {
  90. return this.awsRequest({
  91. action: '__GetDimensions',
  92. parameters: {
  93. namespace: templateSrv.replace(namespace)
  94. }
  95. });
  96. };
  97. CloudWatchDatasource.prototype.getDimensionValues = function(region, namespace, metricName, dimensionKey, filterDimensions) {
  98. var request = {
  99. region: templateSrv.replace(region),
  100. action: 'ListMetrics',
  101. parameters: {
  102. namespace: templateSrv.replace(namespace),
  103. metricName: templateSrv.replace(metricName),
  104. dimensions: convertDimensionFormat(filterDimensions, {}),
  105. }
  106. };
  107. return this.awsRequest(request).then(function(result) {
  108. return _.chain(result.Metrics)
  109. .pluck('Dimensions')
  110. .flatten()
  111. .filter(function(dimension) {
  112. return dimension !== null && dimension.Name === dimensionKey;
  113. })
  114. .pluck('Value')
  115. .uniq()
  116. .sortBy()
  117. .map(function(value) {
  118. return {value: value, text: value};
  119. }).value();
  120. });
  121. };
  122. CloudWatchDatasource.prototype.performEC2DescribeInstances = function(region, filters, instanceIds) {
  123. return this.awsRequest({
  124. region: region,
  125. action: 'DescribeInstances',
  126. parameters: { filter: filters, instanceIds: instanceIds }
  127. });
  128. };
  129. CloudWatchDatasource.prototype.metricFindQuery = function(query) {
  130. var region;
  131. var namespace;
  132. var metricName;
  133. var transformSuggestData = function(suggestData) {
  134. return _.map(suggestData, function(v) {
  135. return { text: v };
  136. });
  137. };
  138. var regionQuery = query.match(/^regions\(\)/);
  139. if (regionQuery) {
  140. return this.getRegions();
  141. }
  142. var namespaceQuery = query.match(/^namespaces\(\)/);
  143. if (namespaceQuery) {
  144. return this.getNamespaces();
  145. }
  146. var metricNameQuery = query.match(/^metrics\(([^\)]+?)\)/);
  147. if (metricNameQuery) {
  148. return this.getMetrics(metricNameQuery[1]);
  149. }
  150. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)\)/);
  151. if (dimensionKeysQuery) {
  152. return this.getDimensionKeys(dimensionKeysQuery[1]);
  153. }
  154. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/);
  155. if (dimensionValuesQuery) {
  156. region = templateSrv.replace(dimensionValuesQuery[1]);
  157. namespace = templateSrv.replace(dimensionValuesQuery[2]);
  158. metricName = templateSrv.replace(dimensionValuesQuery[3]);
  159. var dimensionKey = templateSrv.replace(dimensionValuesQuery[4]);
  160. return this.getDimensionValues(region, namespace, metricName, dimensionKey, {});
  161. }
  162. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  163. if (ebsVolumeIdsQuery) {
  164. region = templateSrv.replace(ebsVolumeIdsQuery[1]);
  165. var instanceId = templateSrv.replace(ebsVolumeIdsQuery[2]);
  166. var instanceIds = [
  167. instanceId
  168. ];
  169. return this.performEC2DescribeInstances(region, [], instanceIds).then(function(result) {
  170. var volumeIds = _.map(result.Reservations[0].Instances[0].BlockDeviceMappings, function(mapping) {
  171. return mapping.Ebs.VolumeId;
  172. });
  173. return transformSuggestData(volumeIds);
  174. });
  175. }
  176. return $q.when([]);
  177. };
  178. CloudWatchDatasource.prototype.testDatasource = function() {
  179. /* use billing metrics for test */
  180. var region = this.defaultRegion;
  181. var namespace = 'AWS/Billing';
  182. var metricName = 'EstimatedCharges';
  183. var dimensions = {};
  184. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(function () {
  185. return { status: 'success', message: 'Data source is working', title: 'Success' };
  186. });
  187. };
  188. CloudWatchDatasource.prototype.awsRequest = function(data) {
  189. var options = {
  190. method: 'POST',
  191. url: this.proxyUrl,
  192. data: data
  193. };
  194. return backendSrv.datasourceRequest(options).then(function(result) {
  195. return result.data;
  196. });
  197. };
  198. CloudWatchDatasource.prototype.getDefaultRegion = function() {
  199. return this.defaultRegion;
  200. };
  201. function transformMetricData(md, options) {
  202. var aliasRegex = /\{\{(.+?)\}\}/g;
  203. var aliasPattern = options.alias || '{{metric}}_{{stat}}';
  204. var aliasData = {
  205. region: templateSrv.replace(options.region),
  206. namespace: templateSrv.replace(options.namespace),
  207. metric: templateSrv.replace(options.metricName),
  208. };
  209. _.extend(aliasData, options.dimensions);
  210. var periodMs = options.period * 1000;
  211. return _.map(options.statistics, function(stat) {
  212. var dps = [];
  213. var lastTimestamp = null;
  214. _.chain(md.Datapoints)
  215. .sortBy(function(dp) {
  216. return dp.Timestamp;
  217. })
  218. .each(function(dp) {
  219. var timestamp = new Date(dp.Timestamp).getTime();
  220. if (lastTimestamp && (timestamp - lastTimestamp) > periodMs) {
  221. dps.push([null, lastTimestamp + periodMs]);
  222. }
  223. lastTimestamp = timestamp;
  224. dps.push([dp[stat], timestamp]);
  225. });
  226. aliasData.stat = stat;
  227. var seriesName = aliasPattern.replace(aliasRegex, function(match, g1) {
  228. if (aliasData[g1]) {
  229. return aliasData[g1];
  230. }
  231. return g1;
  232. });
  233. return {target: seriesName, datapoints: dps};
  234. });
  235. }
  236. function convertToCloudWatchTime(date) {
  237. return Math.round(date.valueOf() / 1000);
  238. }
  239. function convertDimensionFormat(dimensions, scopedVars) {
  240. return _.map(dimensions, function(value, key) {
  241. return {
  242. Name: templateSrv.replace(key, scopedVars),
  243. Value: templateSrv.replace(value, scopedVars)
  244. };
  245. });
  246. }
  247. return CloudWatchDatasource;
  248. });
  249. });