PromQueryField.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. import _ from 'lodash';
  2. import moment from 'moment';
  3. import React from 'react';
  4. import { Value } from 'slate';
  5. import Cascader from 'rc-cascader';
  6. import PluginPrism from 'slate-prism';
  7. import Prism from 'prismjs';
  8. // dom also includes Element polyfills
  9. import { getNextCharacter, getPreviousCousin } from './utils/dom';
  10. import PrismPromql, { FUNCTIONS } from './slate-plugins/prism/promql';
  11. import BracesPlugin from './slate-plugins/braces';
  12. import RunnerPlugin from './slate-plugins/runner';
  13. import { processLabels, RATE_RANGES, cleanText, parseSelector } from './utils/prometheus';
  14. import TypeaheadField, {
  15. Suggestion,
  16. SuggestionGroup,
  17. TypeaheadInput,
  18. TypeaheadFieldState,
  19. TypeaheadOutput,
  20. } from './QueryField';
  21. const DEFAULT_KEYS = ['job', 'instance'];
  22. const EMPTY_SELECTOR = '{}';
  23. const HISTOGRAM_GROUP = '__histograms__';
  24. const HISTOGRAM_SELECTOR = '{le!=""}'; // Returns all timeseries for histograms
  25. const HISTORY_ITEM_COUNT = 5;
  26. const HISTORY_COUNT_CUTOFF = 1000 * 60 * 60 * 24; // 24h
  27. const METRIC_MARK = 'metric';
  28. const PRISM_SYNTAX = 'promql';
  29. export const RECORDING_RULES_GROUP = '__recording_rules__';
  30. export const wrapLabel = (label: string) => ({ label });
  31. export const setFunctionMove = (suggestion: Suggestion): Suggestion => {
  32. suggestion.move = -1;
  33. return suggestion;
  34. };
  35. // Syntax highlighting
  36. Prism.languages[PRISM_SYNTAX] = PrismPromql;
  37. function setPrismTokens(language, field, values, alias = 'variable') {
  38. Prism.languages[language][field] = {
  39. alias,
  40. pattern: new RegExp(`(?:^|\\s)(${values.join('|')})(?:$|\\s)`),
  41. };
  42. }
  43. export function addHistoryMetadata(item: Suggestion, history: any[]): Suggestion {
  44. const cutoffTs = Date.now() - HISTORY_COUNT_CUTOFF;
  45. const historyForItem = history.filter(h => h.ts > cutoffTs && h.query === item.label);
  46. const count = historyForItem.length;
  47. const recent = historyForItem[0];
  48. let hint = `Queried ${count} times in the last 24h.`;
  49. if (recent) {
  50. const lastQueried = moment(recent.ts).fromNow();
  51. hint = `${hint} Last queried ${lastQueried}.`;
  52. }
  53. return {
  54. ...item,
  55. documentation: hint,
  56. };
  57. }
  58. export function groupMetricsByPrefix(metrics: string[], delimiter = '_'): CascaderOption[] {
  59. // Filter out recording rules and insert as first option
  60. const ruleRegex = /:\w+:/;
  61. const ruleNames = metrics.filter(metric => ruleRegex.test(metric));
  62. const rulesOption = {
  63. label: 'Recording rules',
  64. value: RECORDING_RULES_GROUP,
  65. children: ruleNames
  66. .slice()
  67. .sort()
  68. .map(name => ({ label: name, value: name })),
  69. };
  70. const options = ruleNames.length > 0 ? [rulesOption] : [];
  71. const metricsOptions = _.chain(metrics)
  72. .filter(metric => !ruleRegex.test(metric))
  73. .groupBy(metric => metric.split(delimiter)[0])
  74. .map((metricsForPrefix: string[], prefix: string): CascaderOption => {
  75. const prefixIsMetric = metricsForPrefix.length === 1 && metricsForPrefix[0] === prefix;
  76. const children = prefixIsMetric ? [] : metricsForPrefix.sort().map(m => ({ label: m, value: m }));
  77. return {
  78. children,
  79. label: prefix,
  80. value: prefix,
  81. };
  82. })
  83. .sortBy('label')
  84. .value();
  85. return [...options, ...metricsOptions];
  86. }
  87. export function willApplySuggestion(
  88. suggestion: string,
  89. { typeaheadContext, typeaheadText }: TypeaheadFieldState
  90. ): string {
  91. // Modify suggestion based on context
  92. switch (typeaheadContext) {
  93. case 'context-labels': {
  94. const nextChar = getNextCharacter();
  95. if (!nextChar || nextChar === '}' || nextChar === ',') {
  96. suggestion += '=';
  97. }
  98. break;
  99. }
  100. case 'context-label-values': {
  101. // Always add quotes and remove existing ones instead
  102. if (!(typeaheadText.startsWith('="') || typeaheadText.startsWith('"'))) {
  103. suggestion = `"${suggestion}`;
  104. }
  105. if (getNextCharacter() !== '"') {
  106. suggestion = `${suggestion}"`;
  107. }
  108. break;
  109. }
  110. default:
  111. }
  112. return suggestion;
  113. }
  114. interface CascaderOption {
  115. label: string;
  116. value: string;
  117. children?: CascaderOption[];
  118. disabled?: boolean;
  119. }
  120. interface PromQueryFieldProps {
  121. error?: string;
  122. hint?: any;
  123. histogramMetrics?: string[];
  124. history?: any[];
  125. initialQuery?: string | null;
  126. labelKeys?: { [index: string]: string[] }; // metric -> [labelKey,...]
  127. labelValues?: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  128. metrics?: string[];
  129. metricsByPrefix?: CascaderOption[];
  130. onClickHintFix?: (action: any) => void;
  131. onPressEnter?: () => void;
  132. onQueryChange?: (value: string, override?: boolean) => void;
  133. portalOrigin?: string;
  134. request?: (url: string) => any;
  135. supportsLogs?: boolean; // To be removed after Logging gets its own query field
  136. }
  137. interface PromQueryFieldState {
  138. histogramMetrics: string[];
  139. labelKeys: { [index: string]: string[] }; // metric -> [labelKey,...]
  140. labelValues: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  141. logLabelOptions: any[];
  142. metrics: string[];
  143. metricsOptions: any[];
  144. metricsByPrefix: CascaderOption[];
  145. syntaxLoaded: boolean;
  146. }
  147. interface PromTypeaheadInput {
  148. text: string;
  149. prefix: string;
  150. wrapperClasses: string[];
  151. labelKey?: string;
  152. value?: Value;
  153. }
  154. class PromQueryField extends React.PureComponent<PromQueryFieldProps, PromQueryFieldState> {
  155. plugins: any[];
  156. constructor(props: PromQueryFieldProps, context) {
  157. super(props, context);
  158. this.plugins = [
  159. BracesPlugin(),
  160. RunnerPlugin({ handler: props.onPressEnter }),
  161. PluginPrism({
  162. onlyIn: node => node.type === 'code_block',
  163. getSyntax: node => 'promql',
  164. }),
  165. ];
  166. this.state = {
  167. histogramMetrics: props.histogramMetrics || [],
  168. labelKeys: props.labelKeys || {},
  169. labelValues: props.labelValues || {},
  170. logLabelOptions: [],
  171. metrics: props.metrics || [],
  172. metricsByPrefix: props.metricsByPrefix || [],
  173. metricsOptions: [],
  174. syntaxLoaded: false,
  175. };
  176. }
  177. componentDidMount() {
  178. // Temporarily reused by logging
  179. const { supportsLogs } = this.props;
  180. if (supportsLogs) {
  181. this.fetchLogLabels();
  182. } else {
  183. // Usual actions
  184. this.fetchMetricNames();
  185. this.fetchHistogramMetrics();
  186. }
  187. }
  188. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  189. let query;
  190. if (selectedOptions.length === 1) {
  191. if (selectedOptions[0].children.length === 0) {
  192. query = selectedOptions[0].value;
  193. } else {
  194. // Ignore click on group
  195. return;
  196. }
  197. } else {
  198. const key = selectedOptions[0].value;
  199. const value = selectedOptions[1].value;
  200. query = `{${key}="${value}"}`;
  201. }
  202. this.onChangeQuery(query, true);
  203. };
  204. onChangeMetrics = (values: string[], selectedOptions: CascaderOption[]) => {
  205. let query;
  206. if (selectedOptions.length === 1) {
  207. if (selectedOptions[0].children.length === 0) {
  208. query = selectedOptions[0].value;
  209. } else {
  210. // Ignore click on group
  211. return;
  212. }
  213. } else {
  214. const prefix = selectedOptions[0].value;
  215. const metric = selectedOptions[1].value;
  216. if (prefix === HISTOGRAM_GROUP) {
  217. query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;
  218. } else {
  219. query = metric;
  220. }
  221. }
  222. this.onChangeQuery(query, true);
  223. };
  224. onChangeQuery = (value: string, override?: boolean) => {
  225. // Send text change to parent
  226. const { onQueryChange } = this.props;
  227. if (onQueryChange) {
  228. onQueryChange(value, override);
  229. }
  230. };
  231. onClickHintFix = () => {
  232. const { hint, onClickHintFix } = this.props;
  233. if (onClickHintFix && hint && hint.fix) {
  234. onClickHintFix(hint.fix.action);
  235. }
  236. };
  237. onReceiveMetrics = () => {
  238. const { histogramMetrics, metrics, metricsByPrefix } = this.state;
  239. if (!metrics) {
  240. return;
  241. }
  242. // Update global prism config
  243. setPrismTokens(PRISM_SYNTAX, METRIC_MARK, metrics);
  244. // Build metrics tree
  245. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  246. const metricsOptions = [
  247. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions },
  248. ...metricsByPrefix,
  249. ];
  250. this.setState({ metricsOptions, syntaxLoaded: true });
  251. };
  252. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  253. const { prefix, text, value, wrapperNode } = typeahead;
  254. // Get DOM-dependent context
  255. const wrapperClasses = Array.from(wrapperNode.classList);
  256. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  257. const labelKey = labelKeyNode && labelKeyNode.textContent;
  258. const nextChar = getNextCharacter();
  259. const result = this.getTypeahead({ text, value, prefix, wrapperClasses, labelKey });
  260. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  261. return result;
  262. };
  263. // Keep this DOM-free for testing
  264. getTypeahead({ prefix, wrapperClasses, text }: PromTypeaheadInput): TypeaheadOutput {
  265. // Syntax spans have 3 classes by default. More indicate a recognized token
  266. const tokenRecognized = wrapperClasses.length > 3;
  267. // Determine candidates by CSS context
  268. if (_.includes(wrapperClasses, 'context-range')) {
  269. // Suggestions for metric[|]
  270. return this.getRangeTypeahead();
  271. } else if (_.includes(wrapperClasses, 'context-labels')) {
  272. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  273. return this.getLabelTypeahead.apply(this, arguments);
  274. } else if (_.includes(wrapperClasses, 'context-aggregation')) {
  275. return this.getAggregationTypeahead.apply(this, arguments);
  276. } else if (
  277. // Show default suggestions in a couple of scenarios
  278. (prefix && !tokenRecognized) || // Non-empty prefix, but not inside known token
  279. (prefix === '' && !text.match(/^[\]})\s]+$/)) || // Empty prefix, but not following a closing brace
  280. text.match(/[+\-*/^%]/) // Anything after binary operator
  281. ) {
  282. return this.getEmptyTypeahead();
  283. }
  284. return {
  285. suggestions: [],
  286. };
  287. }
  288. getEmptyTypeahead(): TypeaheadOutput {
  289. const { history } = this.props;
  290. const { metrics } = this.state;
  291. const suggestions: SuggestionGroup[] = [];
  292. if (history && history.length > 0) {
  293. const historyItems = _.chain(history)
  294. .uniqBy('query')
  295. .take(HISTORY_ITEM_COUNT)
  296. .map(h => h.query)
  297. .map(wrapLabel)
  298. .map(item => addHistoryMetadata(item, history))
  299. .value();
  300. suggestions.push({
  301. prefixMatch: true,
  302. skipSort: true,
  303. label: 'History',
  304. items: historyItems,
  305. });
  306. }
  307. suggestions.push({
  308. prefixMatch: true,
  309. label: 'Functions',
  310. items: FUNCTIONS.map(setFunctionMove),
  311. });
  312. if (metrics) {
  313. suggestions.push({
  314. label: 'Metrics',
  315. items: metrics.map(wrapLabel),
  316. });
  317. }
  318. return { suggestions };
  319. }
  320. getRangeTypeahead(): TypeaheadOutput {
  321. return {
  322. context: 'context-range',
  323. suggestions: [
  324. {
  325. label: 'Range vector',
  326. items: [...RATE_RANGES].map(wrapLabel),
  327. },
  328. ],
  329. };
  330. }
  331. getAggregationTypeahead({ value }: PromTypeaheadInput): TypeaheadOutput {
  332. let refresher: Promise<any> = null;
  333. const suggestions: SuggestionGroup[] = [];
  334. // sum(foo{bar="1"}) by (|)
  335. const line = value.anchorBlock.getText();
  336. const cursorOffset: number = value.anchorOffset;
  337. // sum(foo{bar="1"}) by (
  338. const leftSide = line.slice(0, cursorOffset);
  339. const openParensAggregationIndex = leftSide.lastIndexOf('(');
  340. const openParensSelectorIndex = leftSide.slice(0, openParensAggregationIndex).lastIndexOf('(');
  341. const closeParensSelectorIndex = leftSide.slice(openParensSelectorIndex).indexOf(')') + openParensSelectorIndex;
  342. // foo{bar="1"}
  343. const selectorString = leftSide.slice(openParensSelectorIndex + 1, closeParensSelectorIndex);
  344. const selector = parseSelector(selectorString, selectorString.length - 2).selector;
  345. const labelKeys = this.state.labelKeys[selector];
  346. if (labelKeys) {
  347. suggestions.push({ label: 'Labels', items: labelKeys.map(wrapLabel) });
  348. } else {
  349. refresher = this.fetchSeriesLabels(selector);
  350. }
  351. return {
  352. refresher,
  353. suggestions,
  354. context: 'context-aggregation',
  355. };
  356. }
  357. getLabelTypeahead({ text, wrapperClasses, labelKey, value }: PromTypeaheadInput): TypeaheadOutput {
  358. let context: string;
  359. let refresher: Promise<any> = null;
  360. const suggestions: SuggestionGroup[] = [];
  361. const line = value.anchorBlock.getText();
  362. const cursorOffset: number = value.anchorOffset;
  363. // Get normalized selector
  364. let selector;
  365. let parsedSelector;
  366. try {
  367. parsedSelector = parseSelector(line, cursorOffset);
  368. selector = parsedSelector.selector;
  369. } catch {
  370. selector = EMPTY_SELECTOR;
  371. }
  372. const containsMetric = selector.indexOf('__name__=') > -1;
  373. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  374. if ((text && text.startsWith('=')) || _.includes(wrapperClasses, 'attr-value')) {
  375. // Label values
  376. if (labelKey && this.state.labelValues[selector] && this.state.labelValues[selector][labelKey]) {
  377. const labelValues = this.state.labelValues[selector][labelKey];
  378. context = 'context-label-values';
  379. suggestions.push({
  380. label: `Label values for "${labelKey}"`,
  381. items: labelValues.map(wrapLabel),
  382. });
  383. }
  384. } else {
  385. // Label keys
  386. const labelKeys = this.state.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  387. if (labelKeys) {
  388. const possibleKeys = _.difference(labelKeys, existingKeys);
  389. if (possibleKeys.length > 0) {
  390. context = 'context-labels';
  391. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  392. }
  393. }
  394. }
  395. // Query labels for selector
  396. // Temporarily add skip for logging
  397. if (selector && !this.state.labelValues[selector] && !this.props.supportsLogs) {
  398. if (selector === EMPTY_SELECTOR) {
  399. // Query label values for default labels
  400. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  401. } else {
  402. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  403. }
  404. }
  405. return { context, refresher, suggestions };
  406. }
  407. request = url => {
  408. if (this.props.request) {
  409. return this.props.request(url);
  410. }
  411. return fetch(url);
  412. };
  413. fetchHistogramMetrics() {
  414. this.fetchSeriesLabels(HISTOGRAM_SELECTOR, true, () => {
  415. const histogramSeries = this.state.labelValues[HISTOGRAM_SELECTOR];
  416. if (histogramSeries && histogramSeries['__name__']) {
  417. const histogramMetrics = histogramSeries['__name__'].slice().sort();
  418. this.setState({ histogramMetrics }, this.onReceiveMetrics);
  419. }
  420. });
  421. }
  422. // Temporarily here while reusing this field for logging
  423. async fetchLogLabels() {
  424. const url = '/api/prom/label';
  425. try {
  426. const res = await this.request(url);
  427. const body = await (res.data || res.json());
  428. const labelKeys = body.data.slice().sort();
  429. const labelKeysBySelector = {
  430. ...this.state.labelKeys,
  431. [EMPTY_SELECTOR]: labelKeys,
  432. };
  433. const labelValuesByKey = {};
  434. const logLabelOptions = [];
  435. for (const key of labelKeys) {
  436. const valuesUrl = `/api/prom/label/${key}/values`;
  437. const res = await this.request(valuesUrl);
  438. const body = await (res.data || res.json());
  439. const values = body.data.slice().sort();
  440. labelValuesByKey[key] = values;
  441. logLabelOptions.push({
  442. label: key,
  443. value: key,
  444. children: values.map(value => ({ label: value, value })),
  445. });
  446. }
  447. const labelValues = { [EMPTY_SELECTOR]: labelValuesByKey };
  448. this.setState({ labelKeys: labelKeysBySelector, labelValues, logLabelOptions });
  449. } catch (e) {
  450. console.error(e);
  451. }
  452. }
  453. async fetchLabelValues(key: string) {
  454. const url = `/api/v1/label/${key}/values`;
  455. try {
  456. const res = await this.request(url);
  457. const body = await (res.data || res.json());
  458. const exisingValues = this.state.labelValues[EMPTY_SELECTOR];
  459. const values = {
  460. ...exisingValues,
  461. [key]: body.data,
  462. };
  463. const labelValues = {
  464. ...this.state.labelValues,
  465. [EMPTY_SELECTOR]: values,
  466. };
  467. this.setState({ labelValues });
  468. } catch (e) {
  469. console.error(e);
  470. }
  471. }
  472. async fetchSeriesLabels(name: string, withName?: boolean, callback?: () => void) {
  473. const url = `/api/v1/series?match[]=${name}`;
  474. try {
  475. const res = await this.request(url);
  476. const body = await (res.data || res.json());
  477. const { keys, values } = processLabels(body.data, withName);
  478. const labelKeys = {
  479. ...this.state.labelKeys,
  480. [name]: keys,
  481. };
  482. const labelValues = {
  483. ...this.state.labelValues,
  484. [name]: values,
  485. };
  486. this.setState({ labelKeys, labelValues }, callback);
  487. } catch (e) {
  488. console.error(e);
  489. }
  490. }
  491. async fetchMetricNames() {
  492. const url = '/api/v1/label/__name__/values';
  493. try {
  494. const res = await this.request(url);
  495. const body = await (res.data || res.json());
  496. const metrics = body.data;
  497. const metricsByPrefix = groupMetricsByPrefix(metrics);
  498. this.setState({ metrics, metricsByPrefix }, this.onReceiveMetrics);
  499. } catch (error) {
  500. console.error(error);
  501. }
  502. }
  503. render() {
  504. const { error, hint, initialQuery, supportsLogs } = this.props;
  505. const { logLabelOptions, metricsOptions, syntaxLoaded } = this.state;
  506. return (
  507. <div className="prom-query-field">
  508. <div className="prom-query-field-tools">
  509. {supportsLogs ? (
  510. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels}>
  511. <button className="btn navbar-button navbar-button--tight">Log labels</button>
  512. </Cascader>
  513. ) : (
  514. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  515. <button className="btn navbar-button navbar-button--tight">Metrics</button>
  516. </Cascader>
  517. )}
  518. </div>
  519. <div className="prom-query-field-wrapper">
  520. <div className="slate-query-field-wrapper">
  521. <TypeaheadField
  522. additionalPlugins={this.plugins}
  523. cleanText={cleanText}
  524. initialValue={initialQuery}
  525. onTypeahead={this.onTypeahead}
  526. onWillApplySuggestion={willApplySuggestion}
  527. onValueChanged={this.onChangeQuery}
  528. placeholder="Enter a PromQL query"
  529. portalOrigin="prometheus"
  530. syntaxLoaded={syntaxLoaded}
  531. />
  532. </div>
  533. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  534. {hint ? (
  535. <div className="prom-query-field-info text-warning">
  536. {hint.label}{' '}
  537. {hint.fix ? (
  538. <a className="text-link muted" onClick={this.onClickHintFix}>
  539. {hint.fix.label}
  540. </a>
  541. ) : null}
  542. </div>
  543. ) : null}
  544. </div>
  545. </div>
  546. );
  547. }
  548. }
  549. export default PromQueryField;