datasource.js 14 KB

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