datasource.js 14 KB

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