datasource.ts 16 KB

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