datasource.ts 16 KB

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