datasource.ts 14 KB

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