datasource.js 14 KB

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