PromQueryField.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. // Determine candidates by CSS context
  227. if (_.includes(wrapperClasses, 'context-range')) {
  228. // Suggestions for metric[|]
  229. return this.getRangeTypeahead();
  230. } else if (_.includes(wrapperClasses, 'context-labels')) {
  231. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  232. return this.getLabelTypeahead.apply(this, arguments);
  233. } else if (_.includes(wrapperClasses, 'context-aggregation')) {
  234. return this.getAggregationTypeahead.apply(this, arguments);
  235. } else if (
  236. // Non-empty but not inside known token
  237. (prefix && !_.includes(wrapperClasses, 'token')) ||
  238. (prefix === '' && !text.match(/^[)\s]+$/)) || // Empty context or after ')'
  239. text.match(/[+\-*/^%]/) // After binary operator
  240. ) {
  241. return this.getEmptyTypeahead();
  242. }
  243. return {
  244. suggestions: [],
  245. };
  246. }
  247. getEmptyTypeahead(): TypeaheadOutput {
  248. const { history } = this.props;
  249. const { metrics } = this.state;
  250. const suggestions: SuggestionGroup[] = [];
  251. if (history && history.length > 0) {
  252. const historyItems = _.chain(history)
  253. .uniqBy('query')
  254. .take(HISTORY_ITEM_COUNT)
  255. .map(h => h.query)
  256. .map(wrapLabel)
  257. .map(item => addHistoryMetadata(item, history))
  258. .value();
  259. suggestions.push({
  260. prefixMatch: true,
  261. skipSort: true,
  262. label: 'History',
  263. items: historyItems,
  264. });
  265. }
  266. suggestions.push({
  267. prefixMatch: true,
  268. label: 'Functions',
  269. items: FUNCTIONS.map(setFunctionMove),
  270. });
  271. if (metrics) {
  272. suggestions.push({
  273. label: 'Metrics',
  274. items: metrics.map(wrapLabel),
  275. });
  276. }
  277. return { suggestions };
  278. }
  279. getRangeTypeahead(): TypeaheadOutput {
  280. return {
  281. context: 'context-range',
  282. suggestions: [
  283. {
  284. label: 'Range vector',
  285. items: [...RATE_RANGES].map(wrapLabel),
  286. },
  287. ],
  288. };
  289. }
  290. getAggregationTypeahead({ value }: PromTypeaheadInput): TypeaheadOutput {
  291. let refresher: Promise<any> = null;
  292. const suggestions: SuggestionGroup[] = [];
  293. // sum(foo{bar="1"}) by (|)
  294. const line = value.anchorBlock.getText();
  295. const cursorOffset: number = value.anchorOffset;
  296. // sum(foo{bar="1"}) by (
  297. const leftSide = line.slice(0, cursorOffset);
  298. const openParensAggregationIndex = leftSide.lastIndexOf('(');
  299. const openParensSelectorIndex = leftSide.slice(0, openParensAggregationIndex).lastIndexOf('(');
  300. const closeParensSelectorIndex = leftSide.slice(openParensSelectorIndex).indexOf(')') + openParensSelectorIndex;
  301. // foo{bar="1"}
  302. const selectorString = leftSide.slice(openParensSelectorIndex + 1, closeParensSelectorIndex);
  303. const selector = parseSelector(selectorString, selectorString.length - 2).selector;
  304. const labelKeys = this.state.labelKeys[selector];
  305. if (labelKeys) {
  306. suggestions.push({ label: 'Labels', items: labelKeys.map(wrapLabel) });
  307. } else {
  308. refresher = this.fetchSeriesLabels(selector);
  309. }
  310. return {
  311. refresher,
  312. suggestions,
  313. context: 'context-aggregation',
  314. };
  315. }
  316. getLabelTypeahead({ text, wrapperClasses, labelKey, value }: PromTypeaheadInput): TypeaheadOutput {
  317. let context: string;
  318. let refresher: Promise<any> = null;
  319. const suggestions: SuggestionGroup[] = [];
  320. const line = value.anchorBlock.getText();
  321. const cursorOffset: number = value.anchorOffset;
  322. // Get normalized selector
  323. let selector;
  324. let parsedSelector;
  325. try {
  326. parsedSelector = parseSelector(line, cursorOffset);
  327. selector = parsedSelector.selector;
  328. } catch {
  329. selector = EMPTY_SELECTOR;
  330. }
  331. const containsMetric = selector.indexOf('__name__=') > -1;
  332. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  333. if ((text && text.startsWith('=')) || _.includes(wrapperClasses, 'attr-value')) {
  334. // Label values
  335. if (labelKey && this.state.labelValues[selector] && this.state.labelValues[selector][labelKey]) {
  336. const labelValues = this.state.labelValues[selector][labelKey];
  337. context = 'context-label-values';
  338. suggestions.push({
  339. label: `Label values for "${labelKey}"`,
  340. items: labelValues.map(wrapLabel),
  341. });
  342. }
  343. } else {
  344. // Label keys
  345. const labelKeys = this.state.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  346. if (labelKeys) {
  347. const possibleKeys = _.difference(labelKeys, existingKeys);
  348. if (possibleKeys.length > 0) {
  349. context = 'context-labels';
  350. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  351. }
  352. }
  353. }
  354. // Query labels for selector
  355. if (selector && !this.state.labelValues[selector]) {
  356. if (selector === EMPTY_SELECTOR) {
  357. // Query label values for default labels
  358. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  359. } else {
  360. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  361. }
  362. }
  363. return { context, refresher, suggestions };
  364. }
  365. request = url => {
  366. if (this.props.request) {
  367. return this.props.request(url);
  368. }
  369. return fetch(url);
  370. };
  371. fetchHistogramMetrics() {
  372. this.fetchSeriesLabels(HISTOGRAM_SELECTOR, true, () => {
  373. const histogramSeries = this.state.labelValues[HISTOGRAM_SELECTOR];
  374. if (histogramSeries && histogramSeries['__name__']) {
  375. const histogramMetrics = histogramSeries['__name__'].slice().sort();
  376. this.setState({ histogramMetrics });
  377. }
  378. });
  379. }
  380. async fetchLabelValues(key: string) {
  381. const url = `/api/v1/label/${key}/values`;
  382. try {
  383. const res = await this.request(url);
  384. const body = await (res.data || res.json());
  385. const exisingValues = this.state.labelValues[EMPTY_SELECTOR];
  386. const values = {
  387. ...exisingValues,
  388. [key]: body.data,
  389. };
  390. const labelValues = {
  391. ...this.state.labelValues,
  392. [EMPTY_SELECTOR]: values,
  393. };
  394. this.setState({ labelValues });
  395. } catch (e) {
  396. console.error(e);
  397. }
  398. }
  399. async fetchSeriesLabels(name: string, withName?: boolean, callback?: () => void) {
  400. const url = `/api/v1/series?match[]=${name}`;
  401. try {
  402. const res = await this.request(url);
  403. const body = await (res.data || res.json());
  404. const { keys, values } = processLabels(body.data, withName);
  405. const labelKeys = {
  406. ...this.state.labelKeys,
  407. [name]: keys,
  408. };
  409. const labelValues = {
  410. ...this.state.labelValues,
  411. [name]: values,
  412. };
  413. this.setState({ labelKeys, labelValues }, callback);
  414. } catch (e) {
  415. console.error(e);
  416. }
  417. }
  418. async fetchMetricNames() {
  419. const url = '/api/v1/label/__name__/values';
  420. try {
  421. const res = await this.request(url);
  422. const body = await (res.data || res.json());
  423. const metrics = body.data;
  424. const metricsByPrefix = groupMetricsByPrefix(metrics);
  425. this.setState({ metrics, metricsByPrefix }, this.onReceiveMetrics);
  426. } catch (error) {
  427. console.error(error);
  428. }
  429. }
  430. render() {
  431. const { error, hint } = this.props;
  432. const { histogramMetrics, metricsByPrefix } = this.state;
  433. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  434. const metricsOptions = [
  435. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions },
  436. ...metricsByPrefix,
  437. ];
  438. return (
  439. <div className="prom-query-field">
  440. <div className="prom-query-field-tools">
  441. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  442. <button className="btn navbar-button navbar-button--tight">Metrics</button>
  443. </Cascader>
  444. </div>
  445. <div className="prom-query-field-wrapper">
  446. <div className="slate-query-field-wrapper">
  447. <TypeaheadField
  448. additionalPlugins={this.plugins}
  449. cleanText={cleanText}
  450. initialValue={this.props.initialQuery}
  451. onTypeahead={this.onTypeahead}
  452. onWillApplySuggestion={willApplySuggestion}
  453. onValueChanged={this.onChangeQuery}
  454. placeholder="Enter a PromQL query"
  455. />
  456. </div>
  457. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  458. {hint ? (
  459. <div className="prom-query-field-info text-warning">
  460. {hint.label}{' '}
  461. {hint.fix ? (
  462. <a className="text-link muted" onClick={this.onClickHintFix}>
  463. {hint.fix.label}
  464. </a>
  465. ) : null}
  466. </div>
  467. ) : null}
  468. </div>
  469. </div>
  470. );
  471. }
  472. }
  473. export default PromQueryField;