PromQueryField.tsx 16 KB

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