PromQueryField.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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. portalPrefix?: 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. metricsByPrefix: CascaderOption[];
  144. }
  145. interface PromTypeaheadInput {
  146. text: string;
  147. prefix: string;
  148. wrapperClasses: string[];
  149. labelKey?: string;
  150. value?: Value;
  151. }
  152. class PromQueryField extends React.Component<PromQueryFieldProps, PromQueryFieldState> {
  153. plugins: any[];
  154. constructor(props: PromQueryFieldProps, context) {
  155. super(props, context);
  156. this.plugins = [
  157. BracesPlugin(),
  158. RunnerPlugin({ handler: props.onPressEnter }),
  159. PluginPrism({
  160. onlyIn: node => node.type === 'code_block',
  161. getSyntax: node => 'promql',
  162. }),
  163. ];
  164. this.state = {
  165. histogramMetrics: props.histogramMetrics || [],
  166. labelKeys: props.labelKeys || {},
  167. labelValues: props.labelValues || {},
  168. logLabelOptions: [],
  169. metrics: props.metrics || [],
  170. metricsByPrefix: props.metricsByPrefix || [],
  171. };
  172. }
  173. componentDidMount() {
  174. // Temporarily reused by logging
  175. const { supportsLogs } = this.props;
  176. if (supportsLogs) {
  177. this.fetchLogLabels();
  178. } else {
  179. // Usual actions
  180. this.fetchMetricNames();
  181. this.fetchHistogramMetrics();
  182. }
  183. }
  184. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  185. let query;
  186. if (selectedOptions.length === 1) {
  187. if (selectedOptions[0].children.length === 0) {
  188. query = selectedOptions[0].value;
  189. } else {
  190. // Ignore click on group
  191. return;
  192. }
  193. } else {
  194. const key = selectedOptions[0].value;
  195. const value = selectedOptions[1].value;
  196. query = `{${key}="${value}"}`;
  197. }
  198. this.onChangeQuery(query, true);
  199. };
  200. onChangeMetrics = (values: string[], selectedOptions: CascaderOption[]) => {
  201. let query;
  202. if (selectedOptions.length === 1) {
  203. if (selectedOptions[0].children.length === 0) {
  204. query = selectedOptions[0].value;
  205. } else {
  206. // Ignore click on group
  207. return;
  208. }
  209. } else {
  210. const prefix = selectedOptions[0].value;
  211. const metric = selectedOptions[1].value;
  212. if (prefix === HISTOGRAM_GROUP) {
  213. query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;
  214. } else {
  215. query = metric;
  216. }
  217. }
  218. this.onChangeQuery(query, true);
  219. };
  220. onChangeQuery = (value: string, override?: boolean) => {
  221. // Send text change to parent
  222. const { onQueryChange } = this.props;
  223. if (onQueryChange) {
  224. onQueryChange(value, override);
  225. }
  226. };
  227. onClickHintFix = () => {
  228. const { hint, onClickHintFix } = this.props;
  229. if (onClickHintFix && hint && hint.fix) {
  230. onClickHintFix(hint.fix.action);
  231. }
  232. };
  233. onReceiveMetrics = () => {
  234. if (!this.state.metrics) {
  235. return;
  236. }
  237. setPrismTokens(PRISM_SYNTAX, METRIC_MARK, this.state.metrics);
  238. };
  239. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  240. const { prefix, text, value, wrapperNode } = typeahead;
  241. // Get DOM-dependent context
  242. const wrapperClasses = Array.from(wrapperNode.classList);
  243. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  244. const labelKey = labelKeyNode && labelKeyNode.textContent;
  245. const nextChar = getNextCharacter();
  246. const result = this.getTypeahead({ text, value, prefix, wrapperClasses, labelKey });
  247. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  248. return result;
  249. };
  250. // Keep this DOM-free for testing
  251. getTypeahead({ prefix, wrapperClasses, text }: PromTypeaheadInput): TypeaheadOutput {
  252. // Syntax spans have 3 classes by default. More indicate a recognized token
  253. const tokenRecognized = wrapperClasses.length > 3;
  254. // Determine candidates by CSS context
  255. if (_.includes(wrapperClasses, 'context-range')) {
  256. // Suggestions for metric[|]
  257. return this.getRangeTypeahead();
  258. } else if (_.includes(wrapperClasses, 'context-labels')) {
  259. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  260. return this.getLabelTypeahead.apply(this, arguments);
  261. } else if (_.includes(wrapperClasses, 'context-aggregation')) {
  262. return this.getAggregationTypeahead.apply(this, arguments);
  263. } else if (
  264. // Non-empty but not inside known token
  265. (prefix && !tokenRecognized) ||
  266. (prefix === '' && !text.match(/^[)\s]+$/)) || // Empty context or after ')'
  267. text.match(/[+\-*/^%]/) // After binary operator
  268. ) {
  269. return this.getEmptyTypeahead();
  270. }
  271. return {
  272. suggestions: [],
  273. };
  274. }
  275. getEmptyTypeahead(): TypeaheadOutput {
  276. const { history } = this.props;
  277. const { metrics } = this.state;
  278. const suggestions: SuggestionGroup[] = [];
  279. if (history && history.length > 0) {
  280. const historyItems = _.chain(history)
  281. .uniqBy('query')
  282. .take(HISTORY_ITEM_COUNT)
  283. .map(h => h.query)
  284. .map(wrapLabel)
  285. .map(item => addHistoryMetadata(item, history))
  286. .value();
  287. suggestions.push({
  288. prefixMatch: true,
  289. skipSort: true,
  290. label: 'History',
  291. items: historyItems,
  292. });
  293. }
  294. suggestions.push({
  295. prefixMatch: true,
  296. label: 'Functions',
  297. items: FUNCTIONS.map(setFunctionMove),
  298. });
  299. if (metrics) {
  300. suggestions.push({
  301. label: 'Metrics',
  302. items: metrics.map(wrapLabel),
  303. });
  304. }
  305. return { suggestions };
  306. }
  307. getRangeTypeahead(): TypeaheadOutput {
  308. return {
  309. context: 'context-range',
  310. suggestions: [
  311. {
  312. label: 'Range vector',
  313. items: [...RATE_RANGES].map(wrapLabel),
  314. },
  315. ],
  316. };
  317. }
  318. getAggregationTypeahead({ value }: PromTypeaheadInput): TypeaheadOutput {
  319. let refresher: Promise<any> = null;
  320. const suggestions: SuggestionGroup[] = [];
  321. // sum(foo{bar="1"}) by (|)
  322. const line = value.anchorBlock.getText();
  323. const cursorOffset: number = value.anchorOffset;
  324. // sum(foo{bar="1"}) by (
  325. const leftSide = line.slice(0, cursorOffset);
  326. const openParensAggregationIndex = leftSide.lastIndexOf('(');
  327. const openParensSelectorIndex = leftSide.slice(0, openParensAggregationIndex).lastIndexOf('(');
  328. const closeParensSelectorIndex = leftSide.slice(openParensSelectorIndex).indexOf(')') + openParensSelectorIndex;
  329. // foo{bar="1"}
  330. const selectorString = leftSide.slice(openParensSelectorIndex + 1, closeParensSelectorIndex);
  331. const selector = parseSelector(selectorString, selectorString.length - 2).selector;
  332. const labelKeys = this.state.labelKeys[selector];
  333. if (labelKeys) {
  334. suggestions.push({ label: 'Labels', items: labelKeys.map(wrapLabel) });
  335. } else {
  336. refresher = this.fetchSeriesLabels(selector);
  337. }
  338. return {
  339. refresher,
  340. suggestions,
  341. context: 'context-aggregation',
  342. };
  343. }
  344. getLabelTypeahead({ text, wrapperClasses, labelKey, value }: PromTypeaheadInput): TypeaheadOutput {
  345. let context: string;
  346. let refresher: Promise<any> = null;
  347. const suggestions: SuggestionGroup[] = [];
  348. const line = value.anchorBlock.getText();
  349. const cursorOffset: number = value.anchorOffset;
  350. // Get normalized selector
  351. let selector;
  352. let parsedSelector;
  353. try {
  354. parsedSelector = parseSelector(line, cursorOffset);
  355. selector = parsedSelector.selector;
  356. } catch {
  357. selector = EMPTY_SELECTOR;
  358. }
  359. const containsMetric = selector.indexOf('__name__=') > -1;
  360. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  361. if ((text && text.startsWith('=')) || _.includes(wrapperClasses, 'attr-value')) {
  362. // Label values
  363. if (labelKey && this.state.labelValues[selector] && this.state.labelValues[selector][labelKey]) {
  364. const labelValues = this.state.labelValues[selector][labelKey];
  365. context = 'context-label-values';
  366. suggestions.push({
  367. label: `Label values for "${labelKey}"`,
  368. items: labelValues.map(wrapLabel),
  369. });
  370. }
  371. } else {
  372. // Label keys
  373. const labelKeys = this.state.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  374. if (labelKeys) {
  375. const possibleKeys = _.difference(labelKeys, existingKeys);
  376. if (possibleKeys.length > 0) {
  377. context = 'context-labels';
  378. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  379. }
  380. }
  381. }
  382. // Query labels for selector
  383. // Temporarily add skip for logging
  384. if (selector && !this.state.labelValues[selector] && !this.props.supportsLogs) {
  385. if (selector === EMPTY_SELECTOR) {
  386. // Query label values for default labels
  387. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  388. } else {
  389. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  390. }
  391. }
  392. return { context, refresher, suggestions };
  393. }
  394. request = url => {
  395. if (this.props.request) {
  396. return this.props.request(url);
  397. }
  398. return fetch(url);
  399. };
  400. fetchHistogramMetrics() {
  401. this.fetchSeriesLabels(HISTOGRAM_SELECTOR, true, () => {
  402. const histogramSeries = this.state.labelValues[HISTOGRAM_SELECTOR];
  403. if (histogramSeries && histogramSeries['__name__']) {
  404. const histogramMetrics = histogramSeries['__name__'].slice().sort();
  405. this.setState({ histogramMetrics });
  406. }
  407. });
  408. }
  409. // Temporarily here while reusing this field for logging
  410. async fetchLogLabels() {
  411. const url = '/api/prom/label';
  412. try {
  413. const res = await this.request(url);
  414. const body = await (res.data || res.json());
  415. const labelKeys = body.data.slice().sort();
  416. const labelKeysBySelector = {
  417. ...this.state.labelKeys,
  418. [EMPTY_SELECTOR]: labelKeys,
  419. };
  420. const labelValuesByKey = {};
  421. const logLabelOptions = [];
  422. for (const key of labelKeys) {
  423. const valuesUrl = `/api/prom/label/${key}/values`;
  424. const res = await this.request(valuesUrl);
  425. const body = await (res.data || res.json());
  426. const values = body.data.slice().sort();
  427. labelValuesByKey[key] = values;
  428. logLabelOptions.push({
  429. label: key,
  430. value: key,
  431. children: values.map(value => ({ label: value, value })),
  432. });
  433. }
  434. const labelValues = { [EMPTY_SELECTOR]: labelValuesByKey };
  435. this.setState({ labelKeys: labelKeysBySelector, labelValues, logLabelOptions });
  436. } catch (e) {
  437. console.error(e);
  438. }
  439. }
  440. async fetchLabelValues(key: string) {
  441. const url = `/api/v1/label/${key}/values`;
  442. try {
  443. const res = await this.request(url);
  444. const body = await (res.data || res.json());
  445. const exisingValues = this.state.labelValues[EMPTY_SELECTOR];
  446. const values = {
  447. ...exisingValues,
  448. [key]: body.data,
  449. };
  450. const labelValues = {
  451. ...this.state.labelValues,
  452. [EMPTY_SELECTOR]: values,
  453. };
  454. this.setState({ labelValues });
  455. } catch (e) {
  456. console.error(e);
  457. }
  458. }
  459. async fetchSeriesLabels(name: string, withName?: boolean, callback?: () => void) {
  460. const url = `/api/v1/series?match[]=${name}`;
  461. try {
  462. const res = await this.request(url);
  463. const body = await (res.data || res.json());
  464. const { keys, values } = processLabels(body.data, withName);
  465. const labelKeys = {
  466. ...this.state.labelKeys,
  467. [name]: keys,
  468. };
  469. const labelValues = {
  470. ...this.state.labelValues,
  471. [name]: values,
  472. };
  473. this.setState({ labelKeys, labelValues }, callback);
  474. } catch (e) {
  475. console.error(e);
  476. }
  477. }
  478. async fetchMetricNames() {
  479. const url = '/api/v1/label/__name__/values';
  480. try {
  481. const res = await this.request(url);
  482. const body = await (res.data || res.json());
  483. const metrics = body.data;
  484. const metricsByPrefix = groupMetricsByPrefix(metrics);
  485. this.setState({ metrics, metricsByPrefix }, this.onReceiveMetrics);
  486. } catch (error) {
  487. console.error(error);
  488. }
  489. }
  490. render() {
  491. const { error, hint, supportsLogs } = this.props;
  492. const { histogramMetrics, logLabelOptions, metricsByPrefix } = this.state;
  493. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  494. const metricsOptions = [
  495. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions },
  496. ...metricsByPrefix,
  497. ];
  498. return (
  499. <div className="prom-query-field">
  500. <div className="prom-query-field-tools">
  501. {supportsLogs ? (
  502. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels}>
  503. <button className="btn navbar-button navbar-button--tight">Log labels</button>
  504. </Cascader>
  505. ) : (
  506. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  507. <button className="btn navbar-button navbar-button--tight">Metrics</button>
  508. </Cascader>
  509. )}
  510. </div>
  511. <div className="prom-query-field-wrapper">
  512. <div className="slate-query-field-wrapper">
  513. <TypeaheadField
  514. additionalPlugins={this.plugins}
  515. cleanText={cleanText}
  516. initialValue={this.props.initialQuery}
  517. onTypeahead={this.onTypeahead}
  518. onWillApplySuggestion={willApplySuggestion}
  519. onValueChanged={this.onChangeQuery}
  520. placeholder="Enter a PromQL query"
  521. portalPrefix="prometheus"
  522. />
  523. </div>
  524. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  525. {hint ? (
  526. <div className="prom-query-field-info text-warning">
  527. {hint.label}{' '}
  528. {hint.fix ? (
  529. <a className="text-link muted" onClick={this.onClickHintFix}>
  530. {hint.fix.label}
  531. </a>
  532. ) : null}
  533. </div>
  534. ) : null}
  535. </div>
  536. </div>
  537. );
  538. }
  539. }
  540. export default PromQueryField;