datasource.ts 17 KB

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