datasource.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. // Libraries
  2. import _ from 'lodash';
  3. import $ from 'jquery';
  4. // Services & Utils
  5. import kbn from 'app/core/utils/kbn';
  6. import * as dateMath from 'app/core/utils/datemath';
  7. import PrometheusMetricFindQuery from './metric_find_query';
  8. import { ResultTransformer } from './result_transformer';
  9. import PrometheusLanguageProvider from './language_provider';
  10. import { BackendSrv } from 'app/core/services/backend_srv';
  11. import addLabelToQuery from './add_label_to_query';
  12. import { getQueryHints } from './query_hints';
  13. import { expandRecordingRules } from './language_utils';
  14. // Types
  15. import { PromQuery } from './types';
  16. import { DataQueryOptions, DataSourceApi, AnnotationEvent } from '@grafana/ui/src/types';
  17. import { ExploreUrlState } from 'app/types/explore';
  18. export class PrometheusDatasource implements DataSourceApi<PromQuery> {
  19. type: string;
  20. editorSrc: string;
  21. name: string;
  22. ruleMappings: { [index: string]: string };
  23. url: string;
  24. directUrl: string;
  25. basicAuth: any;
  26. withCredentials: any;
  27. metricsNameCache: any;
  28. interval: string;
  29. queryTimeout: string;
  30. httpMethod: string;
  31. languageProvider: PrometheusLanguageProvider;
  32. resultTransformer: ResultTransformer;
  33. /** @ngInject */
  34. constructor(instanceSettings, private $q, private backendSrv: BackendSrv, private templateSrv, private timeSrv) {
  35. this.type = 'prometheus';
  36. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  37. this.name = instanceSettings.name;
  38. this.url = instanceSettings.url;
  39. this.directUrl = instanceSettings.directUrl;
  40. this.basicAuth = instanceSettings.basicAuth;
  41. this.withCredentials = instanceSettings.withCredentials;
  42. this.interval = instanceSettings.jsonData.timeInterval || '15s';
  43. this.queryTimeout = instanceSettings.jsonData.queryTimeout;
  44. this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET';
  45. this.resultTransformer = new ResultTransformer(templateSrv);
  46. this.ruleMappings = {};
  47. this.languageProvider = new PrometheusLanguageProvider(this);
  48. }
  49. init() {
  50. this.loadRules();
  51. }
  52. getQueryDisplayText(query: PromQuery) {
  53. return query.expr;
  54. }
  55. _request(url, data?, options?: any) {
  56. options = _.defaults(options || {}, {
  57. url: this.url + url,
  58. method: this.httpMethod,
  59. });
  60. if (options.method === 'GET') {
  61. if (!_.isEmpty(data)) {
  62. options.url =
  63. options.url +
  64. '?' +
  65. _.map(data, (v, k) => {
  66. return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  67. }).join('&');
  68. }
  69. } else {
  70. options.headers = {
  71. 'Content-Type': 'application/x-www-form-urlencoded',
  72. };
  73. options.transformRequest = data => {
  74. return $.param(data);
  75. };
  76. options.data = data;
  77. }
  78. if (this.basicAuth || this.withCredentials) {
  79. options.withCredentials = true;
  80. }
  81. if (this.basicAuth) {
  82. options.headers = {
  83. Authorization: this.basicAuth,
  84. };
  85. }
  86. return this.backendSrv.datasourceRequest(options);
  87. }
  88. // Use this for tab completion features, wont publish response to other components
  89. metadataRequest(url) {
  90. return this._request(url, null, { method: 'GET', silent: true });
  91. }
  92. interpolateQueryExpr(value, variable, defaultFormatFn) {
  93. // if no multi or include all do not regexEscape
  94. if (!variable.multi && !variable.includeAll) {
  95. return prometheusRegularEscape(value);
  96. }
  97. if (typeof value === 'string') {
  98. return prometheusSpecialRegexEscape(value);
  99. }
  100. const escapedValues = _.map(value, prometheusSpecialRegexEscape);
  101. return escapedValues.join('|');
  102. }
  103. targetContainsTemplate(target) {
  104. return this.templateSrv.variableExists(target.expr);
  105. }
  106. query(options: DataQueryOptions<PromQuery>) {
  107. const start = this.getPrometheusTime(options.range.from, false);
  108. const end = this.getPrometheusTime(options.range.to, true);
  109. const queries = [];
  110. const activeTargets = [];
  111. options = _.clone(options);
  112. for (const target of options.targets) {
  113. if (!target.expr || target.hide) {
  114. continue;
  115. }
  116. activeTargets.push(target);
  117. queries.push(this.createQuery(target, options, start, end));
  118. }
  119. // No valid targets, return the empty result to save a round trip.
  120. if (_.isEmpty(queries)) {
  121. return this.$q.when({ data: [] });
  122. }
  123. const allQueryPromise = _.map(queries, query => {
  124. if (!query.instant) {
  125. return this.performTimeSeriesQuery(query, query.start, query.end);
  126. } else {
  127. return this.performInstantQuery(query, end);
  128. }
  129. });
  130. return this.$q.all(allQueryPromise).then(responseList => {
  131. let result = [];
  132. _.each(responseList, (response, index) => {
  133. if (response.status === 'error') {
  134. const error = {
  135. index,
  136. ...response.error,
  137. };
  138. throw error;
  139. }
  140. // Keeping original start/end for transformers
  141. const transformerOptions = {
  142. format: activeTargets[index].format,
  143. step: queries[index].step,
  144. legendFormat: activeTargets[index].legendFormat,
  145. start: queries[index].start,
  146. end: queries[index].end,
  147. query: queries[index].expr,
  148. responseListLength: responseList.length,
  149. refId: activeTargets[index].refId,
  150. valueWithRefId: activeTargets[index].valueWithRefId,
  151. };
  152. const series = this.resultTransformer.transform(response, transformerOptions);
  153. result = [...result, ...series];
  154. });
  155. return { data: result };
  156. });
  157. }
  158. createQuery(target, options, start, end) {
  159. const query: any = {
  160. hinting: target.hinting,
  161. instant: target.instant,
  162. };
  163. const range = Math.ceil(end - start);
  164. // options.interval is the dynamically calculated interval
  165. let interval = kbn.interval_to_seconds(options.interval);
  166. // Minimum interval ("Min step"), if specified for the query or datasource. or same as interval otherwise
  167. const minInterval = kbn.interval_to_seconds(
  168. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  169. );
  170. const intervalFactor = target.intervalFactor || 1;
  171. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  172. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  173. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() };
  174. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  175. if (interval !== adjustedInterval) {
  176. interval = adjustedInterval;
  177. scopedVars = Object.assign({}, options.scopedVars, {
  178. __interval: { text: interval + 's', value: interval + 's' },
  179. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  180. ...this.getRangeScopedVars(),
  181. });
  182. }
  183. query.step = interval;
  184. let expr = target.expr;
  185. // Apply adhoc filters
  186. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  187. expr = adhocFilters.reduce((acc, filter) => {
  188. const { key, operator } = filter;
  189. let { value } = filter;
  190. if (operator === '=~' || operator === '!~') {
  191. value = prometheusRegularEscape(value);
  192. }
  193. return addLabelToQuery(acc, key, value, operator);
  194. }, expr);
  195. // Only replace vars in expression after having (possibly) updated interval vars
  196. query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr);
  197. query.requestId = options.panelId + target.refId;
  198. // Align query interval with step to allow query caching and to ensure
  199. // that about-same-time query results look the same.
  200. const adjusted = alignRange(start, end, query.step);
  201. query.start = adjusted.start;
  202. query.end = adjusted.end;
  203. return query;
  204. }
  205. adjustInterval(interval, minInterval, range, intervalFactor) {
  206. // Prometheus will drop queries that might return more than 11000 data points.
  207. // Calibrate interval if it is too small.
  208. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  209. interval = Math.ceil(range / intervalFactor / 11000);
  210. }
  211. return Math.max(interval * intervalFactor, minInterval, 1);
  212. }
  213. performTimeSeriesQuery(query, start, end) {
  214. if (start > end) {
  215. throw { message: 'Invalid time range' };
  216. }
  217. const url = '/api/v1/query_range';
  218. const data = {
  219. query: query.expr,
  220. start: start,
  221. end: end,
  222. step: query.step,
  223. };
  224. if (this.queryTimeout) {
  225. data['timeout'] = this.queryTimeout;
  226. }
  227. return this._request(url, data, { requestId: query.requestId });
  228. }
  229. performInstantQuery(query, time) {
  230. const url = '/api/v1/query';
  231. const data = {
  232. query: query.expr,
  233. time: time,
  234. };
  235. if (this.queryTimeout) {
  236. data['timeout'] = this.queryTimeout;
  237. }
  238. return this._request(url, data, { requestId: query.requestId });
  239. }
  240. performSuggestQuery(query, cache = false) {
  241. const url = '/api/v1/label/__name__/values';
  242. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  243. return this.$q.when(
  244. _.filter(this.metricsNameCache.data, metricName => {
  245. return metricName.indexOf(query) !== 1;
  246. })
  247. );
  248. }
  249. return this.metadataRequest(url).then(result => {
  250. this.metricsNameCache = {
  251. data: result.data.data,
  252. expire: Date.now() + 60 * 1000,
  253. };
  254. return _.filter(result.data.data, metricName => {
  255. return metricName.indexOf(query) !== 1;
  256. });
  257. });
  258. }
  259. metricFindQuery(query) {
  260. if (!query) {
  261. return this.$q.when([]);
  262. }
  263. const scopedVars = {
  264. __interval: { text: this.interval, value: this.interval },
  265. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  266. ...this.getRangeScopedVars(),
  267. };
  268. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  269. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  270. return metricFindQuery.process();
  271. }
  272. getRangeScopedVars() {
  273. const range = this.timeSrv.timeRange();
  274. const msRange = range.to.diff(range.from);
  275. const sRange = Math.round(msRange / 1000);
  276. const regularRange = kbn.secondsToHms(msRange / 1000);
  277. return {
  278. __range_ms: { text: msRange, value: msRange },
  279. __range_s: { text: sRange, value: sRange },
  280. __range: { text: regularRange, value: regularRange },
  281. };
  282. }
  283. annotationQuery(options) {
  284. const annotation = options.annotation;
  285. const expr = annotation.expr || '';
  286. let tagKeys = annotation.tagKeys || '';
  287. const titleFormat = annotation.titleFormat || '';
  288. const textFormat = annotation.textFormat || '';
  289. if (!expr) {
  290. return this.$q.when([]);
  291. }
  292. const step = annotation.step || '60s';
  293. const start = this.getPrometheusTime(options.range.from, false);
  294. const end = this.getPrometheusTime(options.range.to, true);
  295. const queryOptions = {
  296. ...options,
  297. interval: step,
  298. };
  299. // Unsetting min interval for accurate event resolution
  300. const minStep = '1s';
  301. const query = this.createQuery({ expr, interval: minStep }, queryOptions, start, end);
  302. const self = this;
  303. return this.performTimeSeriesQuery(query, query.start, query.end).then(results => {
  304. const eventList = [];
  305. tagKeys = tagKeys.split(',');
  306. _.each(results.data.data.result, series => {
  307. const tags = _.chain(series.metric)
  308. .filter((v, k) => {
  309. return _.includes(tagKeys, k);
  310. })
  311. .value();
  312. const dupCheck = {};
  313. for (const value of series.values) {
  314. const valueIsTrue = value[1] === '1'; // e.g. ALERTS
  315. if (valueIsTrue || annotation.useValueForTime) {
  316. const event: AnnotationEvent = {
  317. annotation: annotation,
  318. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  319. tags: tags,
  320. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  321. };
  322. if (annotation.useValueForTime) {
  323. const timestampValue = Math.floor(parseFloat(value[1]));
  324. if (dupCheck[timestampValue]) {
  325. continue;
  326. }
  327. dupCheck[timestampValue] = true;
  328. event.time = timestampValue;
  329. } else {
  330. event.time = Math.floor(parseFloat(value[0])) * 1000;
  331. }
  332. eventList.push(event);
  333. }
  334. }
  335. });
  336. return eventList;
  337. });
  338. }
  339. getTagKeys(options) {
  340. const url = '/api/v1/labels';
  341. return this.metadataRequest(url).then(result => {
  342. return _.map(result.data.data, value => {
  343. return { text: value };
  344. });
  345. });
  346. }
  347. getTagValues(options) {
  348. const url = '/api/v1/label/' + options.key + '/values';
  349. return this.metadataRequest(url).then(result => {
  350. return _.map(result.data.data, value => {
  351. return { text: value };
  352. });
  353. });
  354. }
  355. testDatasource() {
  356. const now = new Date().getTime();
  357. return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => {
  358. if (response.data.status === 'success') {
  359. return { status: 'success', message: 'Data source is working' };
  360. } else {
  361. return { status: 'error', message: response.error };
  362. }
  363. });
  364. }
  365. getExploreState(queries: PromQuery[]): Partial<ExploreUrlState> {
  366. let state: Partial<ExploreUrlState> = { datasource: this.name };
  367. if (queries && queries.length > 0) {
  368. const expandedQueries = queries.map(query => ({
  369. ...query,
  370. expr: this.templateSrv.replace(query.expr, {}, this.interpolateQueryExpr),
  371. // null out values we don't support in Explore yet
  372. legendFormat: null,
  373. step: null,
  374. }));
  375. state = {
  376. ...state,
  377. queries: expandedQueries,
  378. };
  379. }
  380. return state;
  381. }
  382. getQueryHints(query: PromQuery, result: any[]) {
  383. return getQueryHints(query.expr || '', result, this);
  384. }
  385. loadRules() {
  386. this.metadataRequest('/api/v1/rules')
  387. .then(res => res.data || res.json())
  388. .then(body => {
  389. const groups = _.get(body, ['data', 'groups']);
  390. if (groups) {
  391. this.ruleMappings = extractRuleMappingFromGroups(groups);
  392. }
  393. })
  394. .catch(e => {
  395. console.log('Rules API is experimental. Ignore next error.');
  396. console.error(e);
  397. });
  398. }
  399. modifyQuery(query: PromQuery, action: any): PromQuery {
  400. let expression = query.expr || '';
  401. switch (action.type) {
  402. case 'ADD_FILTER': {
  403. expression = addLabelToQuery(expression, action.key, action.value);
  404. break;
  405. }
  406. case 'ADD_HISTOGRAM_QUANTILE': {
  407. expression = `histogram_quantile(0.95, sum(rate(${expression}[5m])) by (le))`;
  408. break;
  409. }
  410. case 'ADD_RATE': {
  411. expression = `rate(${expression}[5m])`;
  412. break;
  413. }
  414. case 'ADD_SUM': {
  415. expression = `sum(${expression.trim()}) by ($1)`;
  416. break;
  417. }
  418. case 'EXPAND_RULES': {
  419. if (action.mapping) {
  420. expression = expandRecordingRules(expression, action.mapping);
  421. }
  422. break;
  423. }
  424. default:
  425. break;
  426. }
  427. return { ...query, expr: expression };
  428. }
  429. getPrometheusTime(date, roundUp) {
  430. if (_.isString(date)) {
  431. date = dateMath.parse(date, roundUp);
  432. }
  433. return Math.ceil(date.valueOf() / 1000);
  434. }
  435. getTimeRange(): { start: number; end: number } {
  436. const range = this.timeSrv.timeRange();
  437. return {
  438. start: this.getPrometheusTime(range.from, false),
  439. end: this.getPrometheusTime(range.to, true),
  440. };
  441. }
  442. getOriginalMetricName(labelData) {
  443. return this.resultTransformer.getOriginalMetricName(labelData);
  444. }
  445. }
  446. /**
  447. * Align query range to step.
  448. * Rounds start and end down to a multiple of step.
  449. * @param start Timestamp marking the beginning of the range.
  450. * @param end Timestamp marking the end of the range.
  451. * @param step Interval to align start and end with.
  452. */
  453. export function alignRange(start: number, end: number, step: number): { end: number; start: number } {
  454. const alignedEnd = Math.floor(end / step) * step;
  455. const alignedStart = Math.floor(start / step) * step;
  456. return {
  457. end: alignedEnd,
  458. start: alignedStart,
  459. };
  460. }
  461. export function extractRuleMappingFromGroups(groups: any[]) {
  462. return groups.reduce(
  463. (mapping, group) =>
  464. group.rules
  465. .filter(rule => rule.type === 'recording')
  466. .reduce(
  467. (acc, rule) => ({
  468. ...acc,
  469. [rule.name]: rule.query,
  470. }),
  471. mapping
  472. ),
  473. {}
  474. );
  475. }
  476. export function prometheusRegularEscape(value) {
  477. if (typeof value === 'string') {
  478. return value.replace(/'/g, "\\\\'");
  479. }
  480. return value;
  481. }
  482. export function prometheusSpecialRegexEscape(value) {
  483. if (typeof value === 'string') {
  484. return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()]/g, '\\\\$&'));
  485. }
  486. return value;
  487. }