datasource.js 13 KB

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