datasource.ts 19 KB

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