datasource.js 15 KB

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