datasource.ts 18 KB

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