PromQueryField.tsx 14 KB

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