datasource.ts 16 KB

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