PromQueryField.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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, getCleanSelector } 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 = getCleanSelector(selectorString, selectorString.length - 2);
  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. try {
  313. selector = getCleanSelector(line, cursorOffset);
  314. } catch {
  315. selector = EMPTY_SELECTOR;
  316. }
  317. const containsMetric = selector.indexOf('__name__=') > -1;
  318. if ((text && text.startsWith('=')) || _.includes(wrapperClasses, 'attr-value')) {
  319. // Label values
  320. if (labelKey && this.state.labelValues[selector] && this.state.labelValues[selector][labelKey]) {
  321. const labelValues = this.state.labelValues[selector][labelKey];
  322. context = 'context-label-values';
  323. suggestions.push({
  324. label: `Label values for "${labelKey}"`,
  325. items: labelValues.map(wrapLabel),
  326. });
  327. }
  328. } else {
  329. // Label keys
  330. const labelKeys = this.state.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  331. if (labelKeys) {
  332. context = 'context-labels';
  333. suggestions.push({ label: `Labels`, items: labelKeys.map(wrapLabel) });
  334. }
  335. }
  336. // Query labels for selector
  337. if (selector && !this.state.labelValues[selector]) {
  338. if (selector === EMPTY_SELECTOR) {
  339. // Query label values for default labels
  340. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  341. } else {
  342. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  343. }
  344. }
  345. return { context, refresher, suggestions };
  346. }
  347. request = url => {
  348. if (this.props.request) {
  349. return this.props.request(url);
  350. }
  351. return fetch(url);
  352. };
  353. fetchHistogramMetrics() {
  354. this.fetchSeriesLabels(HISTOGRAM_SELECTOR, true, () => {
  355. const histogramSeries = this.state.labelValues[HISTOGRAM_SELECTOR];
  356. if (histogramSeries && histogramSeries['__name__']) {
  357. const histogramMetrics = histogramSeries['__name__'].slice().sort();
  358. this.setState({ histogramMetrics });
  359. }
  360. });
  361. }
  362. async fetchLabelValues(key: string) {
  363. const url = `/api/v1/label/${key}/values`;
  364. try {
  365. const res = await this.request(url);
  366. const body = await (res.data || res.json());
  367. const exisingValues = this.state.labelValues[EMPTY_SELECTOR];
  368. const values = {
  369. ...exisingValues,
  370. [key]: body.data,
  371. };
  372. const labelValues = {
  373. ...this.state.labelValues,
  374. [EMPTY_SELECTOR]: values,
  375. };
  376. this.setState({ labelValues });
  377. } catch (e) {
  378. console.error(e);
  379. }
  380. }
  381. async fetchSeriesLabels(name: string, withName?: boolean, callback?: () => void) {
  382. const url = `/api/v1/series?match[]=${name}`;
  383. try {
  384. const res = await this.request(url);
  385. const body = await (res.data || res.json());
  386. const { keys, values } = processLabels(body.data, withName);
  387. const labelKeys = {
  388. ...this.state.labelKeys,
  389. [name]: keys,
  390. };
  391. const labelValues = {
  392. ...this.state.labelValues,
  393. [name]: values,
  394. };
  395. this.setState({ labelKeys, labelValues }, callback);
  396. } catch (e) {
  397. console.error(e);
  398. }
  399. }
  400. async fetchMetricNames() {
  401. const url = '/api/v1/label/__name__/values';
  402. try {
  403. const res = await this.request(url);
  404. const body = await (res.data || res.json());
  405. const metrics = body.data;
  406. const metricsByPrefix = groupMetricsByPrefix(metrics);
  407. this.setState({ metrics, metricsByPrefix }, this.onReceiveMetrics);
  408. } catch (error) {
  409. console.error(error);
  410. }
  411. }
  412. render() {
  413. const { error, hint } = this.props;
  414. const { histogramMetrics, metricsByPrefix } = this.state;
  415. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  416. const metricsOptions = [
  417. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions },
  418. ...metricsByPrefix,
  419. ];
  420. return (
  421. <div className="prom-query-field">
  422. <div className="prom-query-field-tools">
  423. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  424. <button className="btn navbar-button navbar-button--tight">Metrics</button>
  425. </Cascader>
  426. </div>
  427. <div className="prom-query-field-wrapper">
  428. <div className="slate-query-field-wrapper">
  429. <TypeaheadField
  430. additionalPlugins={this.plugins}
  431. cleanText={cleanText}
  432. initialValue={this.props.initialQuery}
  433. onTypeahead={this.onTypeahead}
  434. onWillApplySuggestion={willApplySuggestion}
  435. onValueChanged={this.onChangeQuery}
  436. placeholder="Enter a PromQL query"
  437. />
  438. </div>
  439. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  440. {hint ? (
  441. <div className="prom-query-field-info text-warning">
  442. {hint.label}{' '}
  443. {hint.fix ? (
  444. <a className="text-link muted" onClick={this.onClickHintFix}>
  445. {hint.fix.label}
  446. </a>
  447. ) : null}
  448. </div>
  449. ) : null}
  450. </div>
  451. </div>
  452. );
  453. }
  454. }
  455. export default PromQueryField;