datasource.ts 15 KB

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