datasource.js 14 KB

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