datasource.ts 15 KB

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