PromQueryField.tsx 16 KB

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