datasource.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. const s = { target: series.name, datapoints: series.points } as any;
  125. if (queryRes.meta.unit) {
  126. s.unit = queryRes.meta.unit;
  127. }
  128. data.push(s);
  129. });
  130. });
  131. }
  132. return { data: data };
  133. });
  134. }
  135. transformSuggestDataFromTable(suggestData) {
  136. return _.map(suggestData.results['metricFindQuery'].tables[0].rows, v => {
  137. return {
  138. text: v[0],
  139. value: v[1],
  140. };
  141. });
  142. }
  143. doMetricQueryRequest(subtype, parameters) {
  144. const range = this.timeSrv.timeRange();
  145. return this.awsRequest('/api/tsdb/query', {
  146. from: range.from.valueOf().toString(),
  147. to: range.to.valueOf().toString(),
  148. queries: [
  149. _.extend(
  150. {
  151. refId: 'metricFindQuery',
  152. intervalMs: 1, // dummy
  153. maxDataPoints: 1, // dummy
  154. datasourceId: this.instanceSettings.id,
  155. type: 'metricFindQuery',
  156. subtype: subtype,
  157. },
  158. parameters
  159. ),
  160. ],
  161. }).then(r => {
  162. return this.transformSuggestDataFromTable(r);
  163. });
  164. }
  165. getRegions() {
  166. return this.doMetricQueryRequest('regions', null);
  167. }
  168. getNamespaces() {
  169. return this.doMetricQueryRequest('namespaces', null);
  170. }
  171. getMetrics(namespace, region) {
  172. return this.doMetricQueryRequest('metrics', {
  173. region: this.templateSrv.replace(this.getActualRegion(region)),
  174. namespace: this.templateSrv.replace(namespace),
  175. });
  176. }
  177. getDimensionKeys(namespace, region) {
  178. return this.doMetricQueryRequest('dimension_keys', {
  179. region: this.templateSrv.replace(this.getActualRegion(region)),
  180. namespace: this.templateSrv.replace(namespace),
  181. });
  182. }
  183. getDimensionValues(region, namespace, metricName, dimensionKey, filterDimensions) {
  184. return this.doMetricQueryRequest('dimension_values', {
  185. region: this.templateSrv.replace(this.getActualRegion(region)),
  186. namespace: this.templateSrv.replace(namespace),
  187. metricName: this.templateSrv.replace(metricName),
  188. dimensionKey: this.templateSrv.replace(dimensionKey),
  189. dimensions: this.convertDimensionFormat(filterDimensions, {}),
  190. });
  191. }
  192. getEbsVolumeIds(region, instanceId) {
  193. return this.doMetricQueryRequest('ebs_volume_ids', {
  194. region: this.templateSrv.replace(this.getActualRegion(region)),
  195. instanceId: this.templateSrv.replace(instanceId),
  196. });
  197. }
  198. getEc2InstanceAttribute(region, attributeName, filters) {
  199. return this.doMetricQueryRequest('ec2_instance_attribute', {
  200. region: this.templateSrv.replace(this.getActualRegion(region)),
  201. attributeName: this.templateSrv.replace(attributeName),
  202. filters: filters,
  203. });
  204. }
  205. metricFindQuery(query) {
  206. let region;
  207. let namespace;
  208. let metricName;
  209. let filterJson;
  210. const regionQuery = query.match(/^regions\(\)/);
  211. if (regionQuery) {
  212. return this.getRegions();
  213. }
  214. const namespaceQuery = query.match(/^namespaces\(\)/);
  215. if (namespaceQuery) {
  216. return this.getNamespaces();
  217. }
  218. const metricNameQuery = query.match(/^metrics\(([^\)]+?)(,\s?([^,]+?))?\)/);
  219. if (metricNameQuery) {
  220. namespace = metricNameQuery[1];
  221. region = metricNameQuery[3];
  222. return this.getMetrics(namespace, region);
  223. }
  224. const dimensionKeysQuery = query.match(/^dimension_keys\(([^\)]+?)(,\s?([^,]+?))?\)/);
  225. if (dimensionKeysQuery) {
  226. namespace = dimensionKeysQuery[1];
  227. region = dimensionKeysQuery[3];
  228. return this.getDimensionKeys(namespace, region);
  229. }
  230. const dimensionValuesQuery = query.match(
  231. /^dimension_values\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)(,\s?(.+))?\)/
  232. );
  233. if (dimensionValuesQuery) {
  234. region = dimensionValuesQuery[1];
  235. namespace = dimensionValuesQuery[2];
  236. metricName = dimensionValuesQuery[3];
  237. const dimensionKey = dimensionValuesQuery[4];
  238. filterJson = {};
  239. if (dimensionValuesQuery[6]) {
  240. filterJson = JSON.parse(this.templateSrv.replace(dimensionValuesQuery[6]));
  241. }
  242. return this.getDimensionValues(region, namespace, metricName, dimensionKey, filterJson);
  243. }
  244. const ebsVolumeIdsQuery = query.match(/^ebs_volume_ids\(([^,]+?),\s?([^,]+?)\)/);
  245. if (ebsVolumeIdsQuery) {
  246. region = ebsVolumeIdsQuery[1];
  247. const instanceId = ebsVolumeIdsQuery[2];
  248. return this.getEbsVolumeIds(region, instanceId);
  249. }
  250. const ec2InstanceAttributeQuery = query.match(/^ec2_instance_attribute\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/);
  251. if (ec2InstanceAttributeQuery) {
  252. region = ec2InstanceAttributeQuery[1];
  253. const targetAttributeName = ec2InstanceAttributeQuery[2];
  254. filterJson = JSON.parse(this.templateSrv.replace(ec2InstanceAttributeQuery[3]));
  255. return this.getEc2InstanceAttribute(region, targetAttributeName, filterJson);
  256. }
  257. return this.$q.when([]);
  258. }
  259. annotationQuery(options) {
  260. const annotation = options.annotation;
  261. const statistics = _.map(annotation.statistics, s => {
  262. return this.templateSrv.replace(s);
  263. });
  264. const defaultPeriod = annotation.prefixMatching ? '' : '300';
  265. let period = annotation.period || defaultPeriod;
  266. period = parseInt(period, 10);
  267. const parameters = {
  268. prefixMatching: annotation.prefixMatching,
  269. region: this.templateSrv.replace(this.getActualRegion(annotation.region)),
  270. namespace: this.templateSrv.replace(annotation.namespace),
  271. metricName: this.templateSrv.replace(annotation.metricName),
  272. dimensions: this.convertDimensionFormat(annotation.dimensions, {}),
  273. statistics: statistics,
  274. period: period,
  275. actionPrefix: annotation.actionPrefix || '',
  276. alarmNamePrefix: annotation.alarmNamePrefix || '',
  277. };
  278. return this.awsRequest('/api/tsdb/query', {
  279. from: options.range.from.valueOf().toString(),
  280. to: options.range.to.valueOf().toString(),
  281. queries: [
  282. _.extend(
  283. {
  284. refId: 'annotationQuery',
  285. intervalMs: 1, // dummy
  286. maxDataPoints: 1, // dummy
  287. datasourceId: this.instanceSettings.id,
  288. type: 'annotationQuery',
  289. },
  290. parameters
  291. ),
  292. ],
  293. }).then(r => {
  294. return _.map(r.results['annotationQuery'].tables[0].rows, v => {
  295. return {
  296. annotation: annotation,
  297. time: Date.parse(v[0]),
  298. title: v[1],
  299. tags: [v[2]],
  300. text: v[3],
  301. };
  302. });
  303. });
  304. }
  305. targetContainsTemplate(target) {
  306. return (
  307. this.templateSrv.variableExists(target.region) ||
  308. this.templateSrv.variableExists(target.namespace) ||
  309. this.templateSrv.variableExists(target.metricName) ||
  310. _.find(target.dimensions, (v, k) => {
  311. return this.templateSrv.variableExists(k) || this.templateSrv.variableExists(v);
  312. })
  313. );
  314. }
  315. testDatasource() {
  316. /* use billing metrics for test */
  317. const region = this.defaultRegion;
  318. const namespace = 'AWS/Billing';
  319. const metricName = 'EstimatedCharges';
  320. const dimensions = {};
  321. return this.getDimensionValues(region, namespace, metricName, 'ServiceName', dimensions).then(
  322. () => {
  323. return { status: 'success', message: 'Data source is working' };
  324. },
  325. err => {
  326. return { status: 'error', message: err.message };
  327. }
  328. );
  329. }
  330. awsRequest(url, data) {
  331. const options = {
  332. method: 'POST',
  333. url: url,
  334. data: data,
  335. };
  336. return this.backendSrv.datasourceRequest(options).then(result => {
  337. return result.data;
  338. });
  339. }
  340. getDefaultRegion() {
  341. return this.defaultRegion;
  342. }
  343. getActualRegion(region) {
  344. if (region === 'default' || _.isEmpty(region)) {
  345. return this.getDefaultRegion();
  346. }
  347. return region;
  348. }
  349. getExpandedVariables(target, dimensionKey, variable, templateSrv) {
  350. /* if the all checkbox is marked we should add all values to the targets */
  351. const allSelected = _.find(variable.options, { selected: true, text: 'All' });
  352. const selectedVariables = _.filter(variable.options, v => {
  353. if (allSelected) {
  354. return v.text !== 'All';
  355. } else {
  356. return v.selected;
  357. }
  358. });
  359. const currentVariables = !_.isArray(variable.current.value)
  360. ? [variable.current]
  361. : variable.current.value.map(v => {
  362. return {
  363. text: v,
  364. value: v,
  365. };
  366. });
  367. const useSelectedVariables =
  368. selectedVariables.some(s => {
  369. return s.value === currentVariables[0].value;
  370. }) || currentVariables[0].value === '$__all';
  371. return (useSelectedVariables ? selectedVariables : currentVariables).map(v => {
  372. const t = angular.copy(target);
  373. const scopedVar = {};
  374. scopedVar[variable.name] = v;
  375. t.refId = target.refId + '_' + v.value;
  376. t.dimensions[dimensionKey] = templateSrv.replace(t.dimensions[dimensionKey], scopedVar);
  377. if (variable.multi && target.id) {
  378. t.id = target.id + window.btoa(v.value).replace(/=/g, '0'); // generate unique id
  379. } else {
  380. t.id = target.id;
  381. }
  382. return t;
  383. });
  384. }
  385. expandTemplateVariable(targets, scopedVars, templateSrv) {
  386. // Datasource and template srv logic uber-complected. This should be cleaned up.
  387. return _.chain(targets)
  388. .map(target => {
  389. const dimensionKey = _.findKey(target.dimensions, v => {
  390. return templateSrv.variableExists(v) && !_.has(scopedVars, templateSrv.getVariableName(v));
  391. });
  392. if (dimensionKey) {
  393. const multiVariable = _.find(templateSrv.variables, variable => {
  394. return (
  395. templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name) && variable.multi
  396. );
  397. });
  398. const variable = _.find(templateSrv.variables, variable => {
  399. return templatingVariable.containsVariable(target.dimensions[dimensionKey], variable.name);
  400. });
  401. return this.getExpandedVariables(target, dimensionKey, multiVariable || variable, templateSrv);
  402. } else {
  403. return [target];
  404. }
  405. })
  406. .flatten()
  407. .value();
  408. }
  409. convertToCloudWatchTime(date, roundUp) {
  410. if (_.isString(date)) {
  411. date = dateMath.parse(date, roundUp);
  412. }
  413. return Math.round(date.valueOf() / 1000);
  414. }
  415. convertDimensionFormat(dimensions, scopedVars) {
  416. const convertedDimensions = {};
  417. _.each(dimensions, (value, key) => {
  418. convertedDimensions[this.templateSrv.replace(key, scopedVars)] = this.templateSrv.replace(value, scopedVars);
  419. });
  420. return convertedDimensions;
  421. }
  422. }