datasource.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'app/core/utils/datemath',
  6. './query_ctrl',
  7. './directives',
  8. ],
  9. function (angular, _, moment, dateMath) {
  10. 'use strict';
  11. var module = angular.module('grafana.services');
  12. module.factory('CloudWatchDatasource', function($q, backendSrv, templateSrv) {
  13. function CloudWatchDatasource(datasource) {
  14. this.type = 'cloudwatch';
  15. this.name = datasource.name;
  16. this.supportMetrics = true;
  17. this.proxyUrl = datasource.url;
  18. this.defaultRegion = datasource.jsonData.defaultRegion;
  19. }
  20. CloudWatchDatasource.prototype.query = function(options) {
  21. var start = convertToCloudWatchTime(options.range.from, false);
  22. var end = convertToCloudWatchTime(options.range.to, true);
  23. var queries = [];
  24. options = angular.copy(options);
  25. _.each(options.targets, _.bind(function(target) {
  26. if (target.hide || !target.namespace || !target.metricName || _.isEmpty(target.statistics)) {
  27. return;
  28. }
  29. var query = {};
  30. query.region = templateSrv.replace(target.region, options.scopedVars);
  31. query.namespace = templateSrv.replace(target.namespace, options.scopedVars);
  32. query.metricName = templateSrv.replace(target.metricName, options.scopedVars);
  33. query.dimensions = convertDimensionFormat(target.dimensions, options.scopedVars);
  34. query.statistics = target.statistics;
  35. var range = end - start;
  36. query.period = parseInt(target.period, 10) || (query.namespace === 'AWS/EC2' ? 300 : 60);
  37. if (range / query.period >= 1440) {
  38. query.period = Math.ceil(range / 1440 / 60) * 60;
  39. }
  40. target.period = query.period;
  41. queries.push(query);
  42. }, this));
  43. // No valid targets, return the empty result to save a round trip.
  44. if (_.isEmpty(queries)) {
  45. var d = $q.defer();
  46. d.resolve({ data: [] });
  47. return d.promise;
  48. }
  49. var allQueryPromise = _.map(queries, function(query) {
  50. return this.performTimeSeriesQuery(query, start, end);
  51. }, this);
  52. return $q.all(allQueryPromise).then(function(allResponse) {
  53. var result = [];
  54. _.each(allResponse, function(response, index) {
  55. var metrics = transformMetricData(response, options.targets[index]);
  56. result = result.concat(metrics);
  57. });
  58. return { data: result };
  59. });
  60. };
  61. CloudWatchDatasource.prototype.performTimeSeriesQuery = function(query, start, end) {
  62. return this.awsRequest({
  63. region: query.region,
  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, 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: 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. CloudWatchDatasource.prototype.performEC2DescribeInstances = function(region, filters, instanceIds) {
  124. return this.awsRequest({
  125. region: region,
  126. action: 'DescribeInstances',
  127. parameters: { filter: filters, instanceIds: instanceIds }
  128. });
  129. };
  130. CloudWatchDatasource.prototype.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\(([^\)]+?)\)/);
  148. if (metricNameQuery) {
  149. return this.getMetrics(metricNameQuery[1]);
  150. }
  151. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)\)/);
  152. if (dimensionKeysQuery) {
  153. return this.getDimensionKeys(dimensionKeysQuery[1]);
  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. return $q.when([]);
  178. };
  179. CloudWatchDatasource.prototype.performDescribeAlarmsForMetric = function(region, namespace, metricName, dimensions, statistic, period) {
  180. return this.awsRequest({
  181. region: region,
  182. action: 'DescribeAlarmsForMetric',
  183. parameters: { namespace: namespace, metricName: metricName, dimensions: dimensions, statistic: statistic, period: period }
  184. });
  185. };
  186. CloudWatchDatasource.prototype.performDescribeAlarmHistory = function(region, alarmName, startDate, endDate) {
  187. return this.awsRequest({
  188. region: region,
  189. action: 'DescribeAlarmHistory',
  190. parameters: { alarmName: alarmName, startDate: startDate, endDate: endDate }
  191. });
  192. };
  193. CloudWatchDatasource.prototype.annotationQuery = function(options) {
  194. var annotation = options.annotation;
  195. var region = templateSrv.replace(annotation.region);
  196. var namespace = templateSrv.replace(annotation.namespace);
  197. var metricName = templateSrv.replace(annotation.metricName);
  198. var dimensions = convertDimensionFormat(annotation.dimensions);
  199. var statistics = _.map(annotation.statistics, function(s) { return templateSrv.replace(s); });
  200. var period = annotation.period || '300';
  201. period = parseInt(period, 10);
  202. if (!region || !namespace || !metricName || _.isEmpty(statistics)) { return $q.when([]); }
  203. var d = $q.defer();
  204. var self = this;
  205. var allQueryPromise = _.map(statistics, function(statistic) {
  206. return self.performDescribeAlarmsForMetric(region, namespace, metricName, dimensions, statistic, period);
  207. });
  208. $q.all(allQueryPromise).then(function(alarms) {
  209. var eventList = [];
  210. var start = convertToCloudWatchTime(options.range.from, false);
  211. var end = convertToCloudWatchTime(options.range.to, true);
  212. _.chain(alarms)
  213. .pluck('MetricAlarms')
  214. .flatten()
  215. .each(function(alarm) {
  216. if (!alarm) {
  217. d.resolve(eventList);
  218. return;
  219. }
  220. self.performDescribeAlarmHistory(region, alarm.AlarmName, start, end).then(function(history) {
  221. _.each(history.AlarmHistoryItems, function(h) {
  222. var event = {
  223. annotation: annotation,
  224. time: Date.parse(h.Timestamp),
  225. title: h.AlarmName,
  226. tags: [h.HistoryItemType],
  227. text: h.HistorySummary
  228. };
  229. eventList.push(event);
  230. });
  231. d.resolve(eventList);
  232. });
  233. });
  234. });
  235. return d.promise;
  236. };
  237. CloudWatchDatasource.prototype.testDatasource = function() {
  238. /* use billing metrics for test */
  239. var region = this.defaultRegion;
  240. var namespace = 'AWS/Billing';
  241. var metricName = 'EstimatedCharges';
  242. var dimensions = {};
  243. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(function () {
  244. return { status: 'success', message: 'Data source is working', title: 'Success' };
  245. });
  246. };
  247. CloudWatchDatasource.prototype.awsRequest = function(data) {
  248. var options = {
  249. method: 'POST',
  250. url: this.proxyUrl,
  251. data: data
  252. };
  253. return backendSrv.datasourceRequest(options).then(function(result) {
  254. return result.data;
  255. });
  256. };
  257. CloudWatchDatasource.prototype.getDefaultRegion = function() {
  258. return this.defaultRegion;
  259. };
  260. function transformMetricData(md, options) {
  261. var aliasRegex = /\{\{(.+?)\}\}/g;
  262. var aliasPattern = options.alias || '{{metric}}_{{stat}}';
  263. var aliasData = {
  264. region: templateSrv.replace(options.region),
  265. namespace: templateSrv.replace(options.namespace),
  266. metric: templateSrv.replace(options.metricName),
  267. };
  268. _.extend(aliasData, options.dimensions);
  269. var periodMs = options.period * 1000;
  270. return _.map(options.statistics, function(stat) {
  271. var dps = [];
  272. var lastTimestamp = null;
  273. _.chain(md.Datapoints)
  274. .sortBy(function(dp) {
  275. return dp.Timestamp;
  276. })
  277. .each(function(dp) {
  278. var timestamp = new Date(dp.Timestamp).getTime();
  279. if (lastTimestamp && (timestamp - lastTimestamp) > periodMs) {
  280. dps.push([null, lastTimestamp + periodMs]);
  281. }
  282. lastTimestamp = timestamp;
  283. dps.push([dp[stat], timestamp]);
  284. });
  285. aliasData.stat = stat;
  286. var seriesName = aliasPattern.replace(aliasRegex, function(match, g1) {
  287. if (aliasData[g1]) {
  288. return aliasData[g1];
  289. }
  290. return g1;
  291. });
  292. return {target: seriesName, datapoints: dps};
  293. });
  294. }
  295. function convertToCloudWatchTime(date, roundUp) {
  296. if (_.isString(date)) {
  297. date = dateMath.parse(date, roundUp);
  298. }
  299. return Math.round(date.valueOf() / 1000);
  300. }
  301. function convertDimensionFormat(dimensions, scopedVars) {
  302. return _.map(dimensions, function(value, key) {
  303. return {
  304. Name: templateSrv.replace(key, scopedVars),
  305. Value: templateSrv.replace(value, scopedVars)
  306. };
  307. });
  308. }
  309. return CloudWatchDatasource;
  310. });
  311. });