datasource.ts 14 KB

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