datasource.ts 15 KB

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