datasource.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import _ from 'lodash';
  2. import $ from 'jquery';
  3. import kbn from 'app/core/utils/kbn';
  4. import * as dateMath from 'app/core/utils/datemath';
  5. import PrometheusMetricFindQuery from './metric_find_query';
  6. import { ResultTransformer } from './result_transformer';
  7. import { BackendSrv } from 'app/core/services/backend_srv';
  8. export function alignRange(start, end, step) {
  9. const alignedEnd = Math.ceil(end / step) * step;
  10. const alignedStart = Math.floor(start / step) * step;
  11. return {
  12. end: alignedEnd,
  13. start: alignedStart,
  14. };
  15. }
  16. const keywords = 'by|without|on|ignoring|group_left|group_right';
  17. // Duplicate from mode-prometheus.js, which can't be used in tests due to global ace not being loaded.
  18. const builtInWords = [
  19. keywords,
  20. 'count|count_values|min|max|avg|sum|stddev|stdvar|bottomk|topk|quantile',
  21. 'true|false|null|__name__|job',
  22. 'abs|absent|ceil|changes|clamp_max|clamp_min|count_scalar|day_of_month|day_of_week|days_in_month|delta|deriv',
  23. 'drop_common_labels|exp|floor|histogram_quantile|holt_winters|hour|idelta|increase|irate|label_replace|ln|log2',
  24. 'log10|minute|month|predict_linear|rate|resets|round|scalar|sort|sort_desc|sqrt|time|vector|year|avg_over_time',
  25. 'min_over_time|max_over_time|sum_over_time|count_over_time|quantile_over_time|stddev_over_time|stdvar_over_time',
  26. ]
  27. .join('|')
  28. .split('|');
  29. // addLabelToQuery('foo', 'bar', 'baz') => 'foo{bar="baz"}'
  30. export function addLabelToQuery(query: string, key: string, value: string): string {
  31. if (!key || !value) {
  32. throw new Error('Need label to add to query.');
  33. }
  34. // Add empty selector to bare metric name
  35. let previousWord;
  36. query = query.replace(/(\w+)\b(?![\(\]{=",])/g, (match, word, offset) => {
  37. // Check if inside a selector
  38. const nextSelectorStart = query.slice(offset).indexOf('{');
  39. const nextSelectorEnd = query.slice(offset).indexOf('}');
  40. const insideSelector = nextSelectorEnd > -1 && (nextSelectorStart === -1 || nextSelectorStart > nextSelectorEnd);
  41. // Handle "sum by (key) (metric)"
  42. const previousWordIsKeyWord = previousWord && keywords.split('|').indexOf(previousWord) > -1;
  43. previousWord = word;
  44. if (!insideSelector && !previousWordIsKeyWord && builtInWords.indexOf(word) === -1) {
  45. return `${word}{}`;
  46. }
  47. return word;
  48. });
  49. // Adding label to existing selectors
  50. const selectorRegexp = /{([^{]*)}/g;
  51. let match = null;
  52. const parts = [];
  53. let lastIndex = 0;
  54. let suffix = '';
  55. while ((match = selectorRegexp.exec(query))) {
  56. const prefix = query.slice(lastIndex, match.index);
  57. const selectorParts = match[1].split(',');
  58. const labels = selectorParts.reduce((acc, label) => {
  59. const labelParts = label.split('=');
  60. if (labelParts.length === 2) {
  61. acc[labelParts[0]] = labelParts[1];
  62. }
  63. return acc;
  64. }, {});
  65. labels[key] = `"${value}"`;
  66. const selector = Object.keys(labels)
  67. .sort()
  68. .map(key => `${key}=${labels[key]}`)
  69. .join(',');
  70. lastIndex = match.index + match[1].length + 2;
  71. suffix = query.slice(match.index + match[0].length);
  72. parts.push(prefix, '{', selector, '}');
  73. }
  74. parts.push(suffix);
  75. return parts.join('');
  76. }
  77. export function determineQueryHints(series: any[], datasource?: any): any[] {
  78. const hints = series.map((s, i) => {
  79. const query: string = s.query;
  80. const index: number = s.responseIndex;
  81. if (query === undefined || index === undefined) {
  82. return null;
  83. }
  84. // ..._bucket metric needs a histogram_quantile()
  85. const histogramMetric = query.trim().match(/^\w+_bucket$/);
  86. if (histogramMetric) {
  87. const label = 'Time series has buckets, you probably wanted a histogram.';
  88. return {
  89. index,
  90. label,
  91. fix: {
  92. label: 'Fix by adding histogram_quantile().',
  93. action: {
  94. type: 'ADD_HISTOGRAM_QUANTILE',
  95. query,
  96. index,
  97. },
  98. },
  99. };
  100. }
  101. // Check for monotony
  102. const datapoints: number[][] = s.datapoints;
  103. if (datapoints.length > 1) {
  104. let increasing = false;
  105. const monotonic = datapoints.filter(dp => dp[0] !== null).every((dp, index) => {
  106. if (index === 0) {
  107. return true;
  108. }
  109. increasing = increasing || dp[0] > datapoints[index - 1][0];
  110. // monotonic?
  111. return dp[0] >= datapoints[index - 1][0];
  112. });
  113. if (increasing && monotonic) {
  114. const simpleMetric = query.trim().match(/^\w+$/);
  115. let label = 'Time series is monotonously increasing.';
  116. let fix;
  117. if (simpleMetric) {
  118. fix = {
  119. label: 'Fix by adding rate().',
  120. action: {
  121. type: 'ADD_RATE',
  122. query,
  123. index,
  124. },
  125. };
  126. } else {
  127. label = `${label} Try applying a rate() function.`;
  128. }
  129. return {
  130. label,
  131. index,
  132. fix,
  133. };
  134. }
  135. }
  136. // Check for recording rules expansion
  137. if (datasource && datasource.ruleMappings) {
  138. const mapping = datasource.ruleMappings;
  139. const mappingForQuery = Object.keys(mapping).reduce((acc, ruleName) => {
  140. if (query.search(ruleName) > -1) {
  141. return {
  142. ...acc,
  143. [ruleName]: mapping[ruleName],
  144. };
  145. }
  146. return acc;
  147. }, {});
  148. if (_.size(mappingForQuery) > 0) {
  149. const label = 'Query contains recording rules.';
  150. return {
  151. label,
  152. index,
  153. fix: {
  154. label: 'Expand rules',
  155. action: {
  156. type: 'EXPAND_RULES',
  157. query,
  158. index,
  159. mapping: mappingForQuery,
  160. },
  161. },
  162. };
  163. }
  164. }
  165. // No hint found
  166. return null;
  167. });
  168. return hints;
  169. }
  170. export function extractRuleMappingFromGroups(groups: any[]) {
  171. return groups.reduce(
  172. (mapping, group) =>
  173. group.rules.filter(rule => rule.type === 'recording').reduce(
  174. (acc, rule) => ({
  175. ...acc,
  176. [rule.name]: rule.query,
  177. }),
  178. mapping
  179. ),
  180. {}
  181. );
  182. }
  183. export function prometheusRegularEscape(value) {
  184. if (typeof value === 'string') {
  185. return value.replace(/'/g, "\\\\'");
  186. }
  187. return value;
  188. }
  189. export function prometheusSpecialRegexEscape(value) {
  190. if (typeof value === 'string') {
  191. return prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()]/g, '\\\\$&'));
  192. }
  193. return value;
  194. }
  195. export class PrometheusDatasource {
  196. type: string;
  197. editorSrc: string;
  198. name: string;
  199. ruleMappings: { [index: string]: string };
  200. supportsExplore: boolean;
  201. supportMetrics: boolean;
  202. url: string;
  203. directUrl: string;
  204. basicAuth: any;
  205. withCredentials: any;
  206. metricsNameCache: any;
  207. interval: string;
  208. queryTimeout: string;
  209. httpMethod: string;
  210. resultTransformer: ResultTransformer;
  211. /** @ngInject */
  212. constructor(instanceSettings, private $q, private backendSrv: BackendSrv, private templateSrv, private timeSrv) {
  213. this.type = 'prometheus';
  214. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  215. this.name = instanceSettings.name;
  216. this.supportsExplore = true;
  217. this.supportMetrics = true;
  218. this.url = instanceSettings.url;
  219. this.directUrl = instanceSettings.directUrl;
  220. this.basicAuth = instanceSettings.basicAuth;
  221. this.withCredentials = instanceSettings.withCredentials;
  222. this.interval = instanceSettings.jsonData.timeInterval || '15s';
  223. this.queryTimeout = instanceSettings.jsonData.queryTimeout;
  224. this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET';
  225. this.resultTransformer = new ResultTransformer(templateSrv);
  226. this.ruleMappings = {};
  227. }
  228. init() {
  229. this.loadRules();
  230. }
  231. _request(url, data?, options?: any) {
  232. options = _.defaults(options || {}, {
  233. url: this.url + url,
  234. method: this.httpMethod,
  235. });
  236. if (options.method === 'GET') {
  237. if (!_.isEmpty(data)) {
  238. options.url =
  239. options.url +
  240. '?' +
  241. _.map(data, (v, k) => {
  242. return encodeURIComponent(k) + '=' + encodeURIComponent(v);
  243. }).join('&');
  244. }
  245. } else {
  246. options.headers = {
  247. 'Content-Type': 'application/x-www-form-urlencoded',
  248. };
  249. options.transformRequest = data => {
  250. return $.param(data);
  251. };
  252. options.data = data;
  253. }
  254. if (this.basicAuth || this.withCredentials) {
  255. options.withCredentials = true;
  256. }
  257. if (this.basicAuth) {
  258. options.headers = {
  259. Authorization: this.basicAuth,
  260. };
  261. }
  262. return this.backendSrv.datasourceRequest(options);
  263. }
  264. // Use this for tab completion features, wont publish response to other components
  265. metadataRequest(url) {
  266. return this._request(url, null, { method: 'GET', silent: true });
  267. }
  268. interpolateQueryExpr(value, variable, defaultFormatFn) {
  269. // if no multi or include all do not regexEscape
  270. if (!variable.multi && !variable.includeAll) {
  271. return prometheusRegularEscape(value);
  272. }
  273. if (typeof value === 'string') {
  274. return prometheusSpecialRegexEscape(value);
  275. }
  276. const escapedValues = _.map(value, prometheusSpecialRegexEscape);
  277. return escapedValues.join('|');
  278. }
  279. targetContainsTemplate(target) {
  280. return this.templateSrv.variableExists(target.expr);
  281. }
  282. query(options) {
  283. const start = this.getPrometheusTime(options.range.from, false);
  284. const end = this.getPrometheusTime(options.range.to, true);
  285. const queries = [];
  286. const activeTargets = [];
  287. options = _.clone(options);
  288. for (const target of options.targets) {
  289. if (!target.expr || target.hide) {
  290. continue;
  291. }
  292. activeTargets.push(target);
  293. queries.push(this.createQuery(target, options, start, end));
  294. }
  295. // No valid targets, return the empty result to save a round trip.
  296. if (_.isEmpty(queries)) {
  297. return this.$q.when({ data: [] });
  298. }
  299. const allQueryPromise = _.map(queries, query => {
  300. if (!query.instant) {
  301. return this.performTimeSeriesQuery(query, query.start, query.end);
  302. } else {
  303. return this.performInstantQuery(query, end);
  304. }
  305. });
  306. return this.$q.all(allQueryPromise).then(responseList => {
  307. let result = [];
  308. let hints = [];
  309. _.each(responseList, (response, index) => {
  310. if (response.status === 'error') {
  311. const error = {
  312. index,
  313. ...response.error,
  314. };
  315. throw error;
  316. }
  317. // Keeping original start/end for transformers
  318. const transformerOptions = {
  319. format: activeTargets[index].format,
  320. step: queries[index].step,
  321. legendFormat: activeTargets[index].legendFormat,
  322. start: queries[index].start,
  323. end: queries[index].end,
  324. query: queries[index].expr,
  325. responseListLength: responseList.length,
  326. responseIndex: index,
  327. refId: activeTargets[index].refId,
  328. };
  329. const series = this.resultTransformer.transform(response, transformerOptions);
  330. result = [...result, ...series];
  331. if (queries[index].hinting) {
  332. const queryHints = determineQueryHints(series, this);
  333. hints = [...hints, ...queryHints];
  334. }
  335. });
  336. return { data: result, hints };
  337. });
  338. }
  339. createQuery(target, options, start, end) {
  340. const query: any = {
  341. hinting: target.hinting,
  342. instant: target.instant,
  343. };
  344. const range = Math.ceil(end - start);
  345. let interval = kbn.interval_to_seconds(options.interval);
  346. // Minimum interval ("Min step"), if specified for the query. or same as interval otherwise
  347. const minInterval = kbn.interval_to_seconds(
  348. this.templateSrv.replace(target.interval, options.scopedVars) || options.interval
  349. );
  350. const intervalFactor = target.intervalFactor || 1;
  351. // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits
  352. const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor);
  353. let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars() };
  354. // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars
  355. if (interval !== adjustedInterval) {
  356. interval = adjustedInterval;
  357. scopedVars = Object.assign({}, options.scopedVars, {
  358. __interval: { text: interval + 's', value: interval + 's' },
  359. __interval_ms: { text: interval * 1000, value: interval * 1000 },
  360. ...this.getRangeScopedVars(),
  361. });
  362. }
  363. query.step = interval;
  364. // Only replace vars in expression after having (possibly) updated interval vars
  365. query.expr = this.templateSrv.replace(target.expr, scopedVars, this.interpolateQueryExpr);
  366. query.requestId = options.panelId + target.refId;
  367. // Align query interval with step
  368. const adjusted = alignRange(start, end, query.step);
  369. query.start = adjusted.start;
  370. query.end = adjusted.end;
  371. return query;
  372. }
  373. adjustInterval(interval, minInterval, range, intervalFactor) {
  374. // Prometheus will drop queries that might return more than 11000 data points.
  375. // Calibrate interval if it is too small.
  376. if (interval !== 0 && range / intervalFactor / interval > 11000) {
  377. interval = Math.ceil(range / intervalFactor / 11000);
  378. }
  379. return Math.max(interval * intervalFactor, minInterval, 1);
  380. }
  381. performTimeSeriesQuery(query, start, end) {
  382. if (start > end) {
  383. throw { message: 'Invalid time range' };
  384. }
  385. const url = '/api/v1/query_range';
  386. const data = {
  387. query: query.expr,
  388. start: start,
  389. end: end,
  390. step: query.step,
  391. };
  392. if (this.queryTimeout) {
  393. data['timeout'] = this.queryTimeout;
  394. }
  395. return this._request(url, data, { requestId: query.requestId });
  396. }
  397. performInstantQuery(query, time) {
  398. const url = '/api/v1/query';
  399. const data = {
  400. query: query.expr,
  401. time: time,
  402. };
  403. if (this.queryTimeout) {
  404. data['timeout'] = this.queryTimeout;
  405. }
  406. return this._request(url, data, { requestId: query.requestId });
  407. }
  408. performSuggestQuery(query, cache = false) {
  409. const url = '/api/v1/label/__name__/values';
  410. if (cache && this.metricsNameCache && this.metricsNameCache.expire > Date.now()) {
  411. return this.$q.when(
  412. _.filter(this.metricsNameCache.data, metricName => {
  413. return metricName.indexOf(query) !== 1;
  414. })
  415. );
  416. }
  417. return this.metadataRequest(url).then(result => {
  418. this.metricsNameCache = {
  419. data: result.data.data,
  420. expire: Date.now() + 60 * 1000,
  421. };
  422. return _.filter(result.data.data, metricName => {
  423. return metricName.indexOf(query) !== 1;
  424. });
  425. });
  426. }
  427. metricFindQuery(query) {
  428. if (!query) {
  429. return this.$q.when([]);
  430. }
  431. const scopedVars = {
  432. __interval: { text: this.interval, value: this.interval },
  433. __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) },
  434. ...this.getRangeScopedVars(),
  435. };
  436. const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr);
  437. const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv);
  438. return metricFindQuery.process();
  439. }
  440. getRangeScopedVars() {
  441. const range = this.timeSrv.timeRange();
  442. const msRange = range.to.diff(range.from);
  443. const sRange = Math.round(msRange / 1000);
  444. const regularRange = kbn.secondsToHms(msRange / 1000);
  445. return {
  446. __range_ms: { text: msRange, value: msRange },
  447. __range_s: { text: sRange, value: sRange },
  448. __range: { text: regularRange, value: regularRange },
  449. };
  450. }
  451. annotationQuery(options) {
  452. const annotation = options.annotation;
  453. const expr = annotation.expr || '';
  454. let tagKeys = annotation.tagKeys || '';
  455. const titleFormat = annotation.titleFormat || '';
  456. const textFormat = annotation.textFormat || '';
  457. if (!expr) {
  458. return this.$q.when([]);
  459. }
  460. const step = annotation.step || '60s';
  461. const start = this.getPrometheusTime(options.range.from, false);
  462. const end = this.getPrometheusTime(options.range.to, true);
  463. // Unsetting min interval
  464. const queryOptions = {
  465. ...options,
  466. interval: '0s',
  467. };
  468. const query = this.createQuery({ expr, interval: step }, queryOptions, start, end);
  469. const self = this;
  470. return this.performTimeSeriesQuery(query, query.start, query.end).then(results => {
  471. const eventList = [];
  472. tagKeys = tagKeys.split(',');
  473. _.each(results.data.data.result, series => {
  474. const tags = _.chain(series.metric)
  475. .filter((v, k) => {
  476. return _.includes(tagKeys, k);
  477. })
  478. .value();
  479. for (const value of series.values) {
  480. if (value[1] === '1') {
  481. const event = {
  482. annotation: annotation,
  483. time: Math.floor(parseFloat(value[0])) * 1000,
  484. title: self.resultTransformer.renderTemplate(titleFormat, series.metric),
  485. tags: tags,
  486. text: self.resultTransformer.renderTemplate(textFormat, series.metric),
  487. };
  488. eventList.push(event);
  489. }
  490. }
  491. });
  492. return eventList;
  493. });
  494. }
  495. testDatasource() {
  496. const now = new Date().getTime();
  497. return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => {
  498. if (response.data.status === 'success') {
  499. return { status: 'success', message: 'Data source is working' };
  500. } else {
  501. return { status: 'error', message: response.error };
  502. }
  503. });
  504. }
  505. getExploreState(panel) {
  506. let state = {};
  507. if (panel.targets) {
  508. const queries = panel.targets.map(t => ({
  509. query: this.templateSrv.replace(t.expr, {}, this.interpolateQueryExpr),
  510. format: t.format,
  511. }));
  512. state = {
  513. ...state,
  514. queries,
  515. datasource: this.name,
  516. };
  517. }
  518. return state;
  519. }
  520. loadRules() {
  521. this.metadataRequest('/api/v1/rules')
  522. .then(res => res.data || res.json())
  523. .then(body => {
  524. const groups = _.get(body, ['data', 'groups']);
  525. if (groups) {
  526. this.ruleMappings = extractRuleMappingFromGroups(groups);
  527. }
  528. })
  529. .catch(e => {
  530. console.log('Rules API is experimental. Ignore next error.');
  531. console.error(e);
  532. });
  533. }
  534. modifyQuery(query: string, action: any): string {
  535. switch (action.type) {
  536. case 'ADD_FILTER': {
  537. return addLabelToQuery(query, action.key, action.value);
  538. }
  539. case 'ADD_HISTOGRAM_QUANTILE': {
  540. return `histogram_quantile(0.95, sum(rate(${query}[5m])) by (le))`;
  541. }
  542. case 'ADD_RATE': {
  543. return `rate(${query}[5m])`;
  544. }
  545. case 'EXPAND_RULES': {
  546. const mapping = action.mapping;
  547. if (mapping) {
  548. const ruleNames = Object.keys(mapping);
  549. const rulesRegex = new RegExp(`(\\s|^)(${ruleNames.join('|')})(\\s|$|\\()`, 'ig');
  550. return query.replace(rulesRegex, (match, pre, name, post) => mapping[name]);
  551. }
  552. }
  553. default:
  554. return query;
  555. }
  556. }
  557. getPrometheusTime(date, roundUp) {
  558. if (_.isString(date)) {
  559. date = dateMath.parse(date, roundUp);
  560. }
  561. return Math.ceil(date.valueOf() / 1000);
  562. }
  563. getOriginalMetricName(labelData) {
  564. return this.resultTransformer.getOriginalMetricName(labelData);
  565. }
  566. }