datasource.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import angular from 'angular';
  2. import _ from 'lodash';
  3. import * as dateMath from 'app/core/utils/datemath';
  4. import kbn from 'app/core/utils/kbn';
  5. import * as templatingVariable from 'app/features/templating/variable';
  6. // import * as moment from 'moment';
  7. export default class CloudWatchDatasource {
  8. type: any;
  9. name: any;
  10. supportMetrics: any;
  11. proxyUrl: any;
  12. defaultRegion: any;
  13. instanceSettings: any;
  14. standardStatistics: any;
  15. /** @ngInject */
  16. constructor(instanceSettings, private $q, private backendSrv, private templateSrv, private timeSrv) {
  17. this.type = 'cloudwatch';
  18. this.name = instanceSettings.name;
  19. this.supportMetrics = true;
  20. this.proxyUrl = instanceSettings.url;
  21. this.defaultRegion = instanceSettings.jsonData.defaultRegion;
  22. this.instanceSettings = instanceSettings;
  23. this.standardStatistics = ['Average', 'Maximum', 'Minimum', 'Sum', 'SampleCount'];
  24. }
  25. query(options) {
  26. options = angular.copy(options);
  27. options.targets = this.expandTemplateVariable(options.targets, options.scopedVars, this.templateSrv);
  28. var queries = _.filter(options.targets, item => {
  29. return (
  30. item.hide !== true && !!item.region && !!item.namespace && !!item.metricName && !_.isEmpty(item.statistics)
  31. );
  32. }).map(item => {
  33. item.region = this.templateSrv.replace(this.getActualRegion(item.region), options.scopedVars);
  34. item.namespace = this.templateSrv.replace(item.namespace, options.scopedVars);
  35. item.metricName = this.templateSrv.replace(item.metricName, options.scopedVars);
  36. item.dimensions = this.convertDimensionFormat(item.dimensions, options.scopedVars);
  37. item.period = String(this.getPeriod(item, options)); // use string format for period in graph query, and alerting
  38. return _.extend(
  39. {
  40. refId: item.refId,
  41. intervalMs: options.intervalMs,
  42. maxDataPoints: options.maxDataPoints,
  43. datasourceId: this.instanceSettings.id,
  44. type: 'timeSeriesQuery',
  45. },
  46. item
  47. );
  48. });
  49. // No valid targets, return the empty result to save a round trip.
  50. if (_.isEmpty(queries)) {
  51. var d = this.$q.defer();
  52. d.resolve({ data: [] });
  53. return d.promise;
  54. }
  55. var request = {
  56. from: options.range.from.valueOf().toString(),
  57. to: options.range.to.valueOf().toString(),
  58. queries: queries,
  59. };
  60. return this.performTimeSeriesQuery(request);
  61. }
  62. getPeriod(target, options, now?) {
  63. var start = this.convertToCloudWatchTime(options.range.from, false);
  64. var end = this.convertToCloudWatchTime(options.range.to, true);
  65. now = Math.round((now || Date.now()) / 1000);
  66. var period;
  67. var range = end - start;
  68. var hourSec = 60 * 60;
  69. var daySec = hourSec * 24;
  70. var periodUnit = 60;
  71. if (!target.period) {
  72. if (now - start <= daySec * 15) {
  73. // 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) {
  80. // until 63 days ago
  81. periodUnit = period = 60 * 5;
  82. } else if (now - start <= daySec * 455) {
  83. // until 455 days ago
  84. periodUnit = period = 60 * 60;
  85. } else {
  86. // over 455 days, should return error, but try to long period
  87. periodUnit = period = 60 * 60;
  88. }
  89. } else {
  90. if (/^\d+$/.test(target.period)) {
  91. period = parseInt(target.period, 10);
  92. } else {
  93. period = kbn.interval_to_seconds(this.templateSrv.replace(target.period, options.scopedVars));
  94. }
  95. }
  96. if (period < 1) {
  97. period = 1;
  98. }
  99. if (!target.highResolution && range / period >= 1440) {
  100. period = Math.ceil(range / 1440 / periodUnit) * periodUnit;
  101. }
  102. return period;
  103. }
  104. performTimeSeriesQuery(request) {
  105. return this.awsRequest('/api/tsdb/query', request).then(res => {
  106. var data = [];
  107. if (res.results) {
  108. _.forEach(res.results, queryRes => {
  109. _.forEach(queryRes.series, series => {
  110. data.push({ target: series.name, datapoints: series.points });
  111. });
  112. });
  113. }
  114. return { data: data };
  115. });
  116. }
  117. transformSuggestDataFromTable(suggestData) {
  118. return _.map(suggestData.results['metricFindQuery'].tables[0].rows, v => {
  119. return {
  120. text: v[0],
  121. value: v[1],
  122. };
  123. });
  124. }
  125. doMetricQueryRequest(subtype, parameters) {
  126. var range = this.timeSrv.timeRange();
  127. return this.awsRequest('/api/tsdb/query', {
  128. from: range.from.valueOf().toString(),
  129. to: range.to.valueOf().toString(),
  130. queries: [
  131. _.extend(
  132. {
  133. refId: 'metricFindQuery',
  134. intervalMs: 1, // dummy
  135. maxDataPoints: 1, // dummy
  136. datasourceId: this.instanceSettings.id,
  137. type: 'metricFindQuery',
  138. subtype: subtype,
  139. },
  140. parameters
  141. ),
  142. ],
  143. }).then(r => {
  144. return this.transformSuggestDataFromTable(r);
  145. });
  146. }
  147. getRegions() {
  148. return this.doMetricQueryRequest('regions', null);
  149. }
  150. getNamespaces() {
  151. return this.doMetricQueryRequest('namespaces', null);
  152. }
  153. getMetrics(namespace, region) {
  154. return this.doMetricQueryRequest('metrics', {
  155. region: this.templateSrv.replace(this.getActualRegion(region)),
  156. namespace: this.templateSrv.replace(namespace),
  157. });
  158. }
  159. getDimensionKeys(namespace, region) {
  160. return this.doMetricQueryRequest('dimension_keys', {
  161. region: this.templateSrv.replace(this.getActualRegion(region)),
  162. namespace: this.templateSrv.replace(namespace),
  163. });
  164. }
  165. getDimensionValues(region, namespace, metricName, dimensionKey, filterDimensions) {
  166. return this.doMetricQueryRequest('dimension_values', {
  167. region: this.templateSrv.replace(this.getActualRegion(region)),
  168. namespace: this.templateSrv.replace(namespace),
  169. metricName: this.templateSrv.replace(metricName),
  170. dimensionKey: this.templateSrv.replace(dimensionKey),
  171. dimensions: this.convertDimensionFormat(filterDimensions, {}),
  172. });
  173. }
  174. getEbsVolumeIds(region, instanceId) {
  175. return this.doMetricQueryRequest('ebs_volume_ids', {
  176. region: this.templateSrv.replace(this.getActualRegion(region)),
  177. instanceId: this.templateSrv.replace(instanceId),
  178. });
  179. }
  180. getEc2InstanceAttribute(region, attributeName, filters) {
  181. return this.doMetricQueryRequest('ec2_instance_attribute', {
  182. region: this.templateSrv.replace(this.getActualRegion(region)),
  183. attributeName: this.templateSrv.replace(attributeName),
  184. filters: filters,
  185. });
  186. }
  187. metricFindQuery(query) {
  188. var region;
  189. var namespace;
  190. var metricName;
  191. var regionQuery = query.match(/^regions\(\)/);
  192. if (regionQuery) {
  193. return this.getRegions();
  194. }
  195. var namespaceQuery = query.match(/^namespaces\(\)/);
  196. if (namespaceQuery) {
  197. return this.getNamespaces();
  198. }
  199. var metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
  200. if (metricNameQuery) {
  201. namespace = metricNameQuery[1];
  202. region = metricNameQuery[3];
  203. return this.getMetrics(namespace, region);
  204. }
  205. var dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
  206. if (dimensionKeysQuery) {
  207. namespace = dimensionKeysQuery[1];
  208. region = dimensionKeysQuery[3];
  209. return this.getDimensionKeys(namespace, region);
  210. }
  211. var dimensionValuesQuery = query.match(/^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/);
  212. if (dimensionValuesQuery) {
  213. region = dimensionValuesQuery[1];
  214. namespace = dimensionValuesQuery[2];
  215. metricName = dimensionValuesQuery[3];
  216. var dimensionKey = dimensionValuesQuery[4];
  217. return this.getDimensionValues(region, namespace, metricName, dimensionKey, {});
  218. }
  219. var ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  220. if (ebsVolumeIdsQuery) {
  221. region = ebsVolumeIdsQuery[1];
  222. var instanceId = ebsVolumeIdsQuery[2];
  223. return this.getEbsVolumeIds(region, instanceId);
  224. }
  225. var ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
  226. if (ec2InstanceAttributeQuery) {
  227. region = ec2InstanceAttributeQuery[1];
  228. var targetAttributeName = ec2InstanceAttributeQuery[2];
  229. var filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3]));
  230. return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson);
  231. }
  232. return this.$q.when([]);
  233. }
  234. annotationQuery(options) {
  235. var annotation = options.annotation;
  236. var statistics = _.map(annotation.statistics, s => {
  237. return this.templateSrv.replace(s);
  238. });
  239. var defaultPeriod = annotation.prefixMatching ? '' : '300';
  240. var period = annotation.period || defaultPeriod;
  241. period = parseInt(period, 10);
  242. var parameters = {
  243. prefixMatching: annotation.prefixMatching,
  244. region: this.templateSrv.replace(this.getActualRegion(annotation.region)),
  245. namespace: this.templateSrv.replace(annotation.namespace),
  246. metricName: this.templateSrv.replace(annotation.metricName),
  247. dimensions: this.convertDimensionFormat(annotation.dimensions, {}),
  248. statistics: statistics,
  249. period: period,
  250. actionPrefix: annotation.actionPrefix || '',
  251. alarmNamePrefix: annotation.alarmNamePrefix || '',
  252. };
  253. return this.awsRequest('/api/tsdb/query', {
  254. from: options.range.from.valueOf().toString(),
  255. to: options.range.to.valueOf().toString(),
  256. queries: [
  257. _.extend(
  258. {
  259. refId: 'annotationQuery',
  260. intervalMs: 1, // dummy
  261. maxDataPoints: 1, // dummy
  262. datasourceId: this.instanceSettings.id,
  263. type: 'annotationQuery',
  264. },
  265. parameters
  266. ),
  267. ],
  268. }).then(r => {
  269. return _.map(r.results['annotationQuery'].tables[0].rows, v => {
  270. return {
  271. annotation: annotation,
  272. time: Date.parse(v[0]),
  273. title: v[1],
  274. tags: [v[2]],
  275. text: v[3],
  276. };
  277. });
  278. });
  279. }
  280. targetContainsTemplate(target) {
  281. return (
  282. this.templateSrv.variableExists(target.region) ||
  283. this.templateSrv.variableExists(target.namespace) ||
  284. this.templateSrv.variableExists(target.metricName) ||
  285. _.find(target.dimensions, (v, k) => {
  286. return this.templateSrv.variableExists(k) || this.templateSrv.variableExists(v);
  287. })
  288. );
  289. }
  290. testDatasource() {
  291. /* use billing metrics for test */
  292. var region = this.defaultRegion;
  293. var namespace = 'AWS/Billing';
  294. var metricName = 'EstimatedCharges';
  295. var dimensions = {};
  296. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(
  297. () => {
  298. return { status: 'success', message: 'Data source is working' };
  299. },
  300. err => {
  301. return { status: 'error', message: err.message };
  302. }
  303. );
  304. }
  305. awsRequest(url, data) {
  306. var options = {
  307. method: 'POST',
  308. url: url,
  309. data: data,
  310. };
  311. return this.backendSrv.datasourceRequest(options).then(result => {
  312. return result.data;
  313. });
  314. }
  315. getDefaultRegion() {
  316. return this.defaultRegion;
  317. }
  318. getActualRegion(region) {
  319. if (region === 'default' || _.isEmpty(region)) {
  320. return this.getDefaultRegion();
  321. }
  322. return region;
  323. }
  324. getExpandedVariables(target, dimensionKey, variable, templateSrv) {
  325. /* if the all checkbox is marked we should add all values to the targets */
  326. var allSelected = _.find(variable.options, { selected: true, text: 'All' });
  327. return _.chain(variable.options)
  328. .filter(v => {
  329. if (allSelected) {
  330. return v.text !== 'All';
  331. } else {
  332. return v.selected;
  333. }
  334. })
  335. .map(v => {
  336. var t = angular.copy(target);
  337. var scopedVar = {};
  338. scopedVar[variable.name] = v;
  339. t.refId = target.refId + '_' + v.value;
  340. t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
  341. return t;
  342. })
  343. .value();
  344. }
  345. expandTemplateVariable(targets, scopedVars, templateSrv) {
  346. return _.chain(targets)
  347. .map(target => {
  348. var dimensionKey = _.findKey(target.dimensions, v => {
  349. return templateSrv.variableExists(v) && !_.has(scopedVars, templateSrv.getVariableName(v));
  350. });
  351. if (dimensionKey) {
  352. var multiVariable = _.find(templateSrv.variables, variable => {
  353. return (
  354. templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name) && variable.multi
  355. );
  356. });
  357. var variable = _.find(templateSrv.variables, variable => {
  358. return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name);
  359. });
  360. return this.getExpandedVariables(target, dimensionKey, multiVariable || variable, templateSrv);
  361. } else {
  362. return [target];
  363. }
  364. })
  365. .flatten()
  366. .value();
  367. }
  368. convertToCloudWatchTime(date, roundUp) {
  369. if (_.isString(date)) {
  370. date = dateMath.parse(date, roundUp);
  371. }
  372. return Math.round(date.valueOf() / 1000);
  373. }
  374. convertDimensionFormat(dimensions, scopedVars) {
  375. var convertedDimensions = {};
  376. _.each(dimensions, (value, key) => {
  377. convertedDimensions[this.templateSrv.replace(key, scopedVars)] = this.templateSrv.replace(value, scopedVars);
  378. });
  379. return convertedDimensions;
  380. }
  381. }