PromQueryField.tsx 15 KB

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