PromQueryField.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import _ from 'lodash';
  2. import React from 'react';
  3. import { Value } from 'slate';
  4. // dom also includes Element polyfills
  5. import { getNextCharacter, getPreviousCousin } from './utils/dom';
  6. import PluginPrism, { setPrismTokens } from './slate-plugins/prism/index';
  7. import PrismPromql, { FUNCTIONS } from './slate-plugins/prism/promql';
  8. import RunnerPlugin from './slate-plugins/runner';
  9. import { processLabels, RATE_RANGES, cleanText, getCleanSelector } from './utils/prometheus';
  10. import TypeaheadField, {
  11. Suggestion,
  12. SuggestionGroup,
  13. TypeaheadInput,
  14. TypeaheadFieldState,
  15. TypeaheadOutput,
  16. } from './QueryField';
  17. const DEFAULT_KEYS = ['job', 'instance'];
  18. const EMPTY_SELECTOR = '{}';
  19. const METRIC_MARK = 'metric';
  20. const PRISM_LANGUAGE = 'promql';
  21. export const wrapLabel = label => ({ label });
  22. export const setFunctionMove = (suggestion: Suggestion): Suggestion => {
  23. suggestion.move = -1;
  24. return suggestion;
  25. };
  26. export function willApplySuggestion(
  27. suggestion: string,
  28. { typeaheadContext, typeaheadText }: TypeaheadFieldState
  29. ): string {
  30. // Modify suggestion based on context
  31. switch (typeaheadContext) {
  32. case 'context-labels': {
  33. const nextChar = getNextCharacter();
  34. if (!nextChar || nextChar === '}' || nextChar === ',') {
  35. suggestion += '=';
  36. }
  37. break;
  38. }
  39. case 'context-label-values': {
  40. // Always add quotes and remove existing ones instead
  41. if (!(typeaheadText.startsWith('="') || typeaheadText.startsWith('"'))) {
  42. suggestion = `"${suggestion}`;
  43. }
  44. if (getNextCharacter() !== '"') {
  45. suggestion = `${suggestion}"`;
  46. }
  47. break;
  48. }
  49. default:
  50. }
  51. return suggestion;
  52. }
  53. interface PromQueryFieldProps {
  54. initialQuery?: string | null;
  55. labelKeys?: { [index: string]: string[] }; // metric -> [labelKey,...]
  56. labelValues?: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  57. metrics?: string[];
  58. onPressEnter?: () => void;
  59. onQueryChange?: (value: string) => void;
  60. portalPrefix?: string;
  61. request?: (url: string) => any;
  62. }
  63. interface PromQueryFieldState {
  64. labelKeys: { [index: string]: string[] }; // metric -> [labelKey,...]
  65. labelValues: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  66. metrics: string[];
  67. }
  68. interface PromTypeaheadInput {
  69. text: string;
  70. prefix: string;
  71. wrapperClasses: string[];
  72. labelKey?: string;
  73. value?: Value;
  74. }
  75. class PromQueryField extends React.Component<PromQueryFieldProps, PromQueryFieldState> {
  76. plugins: any[];
  77. constructor(props, context) {
  78. super(props, context);
  79. this.plugins = [
  80. RunnerPlugin({ handler: props.onPressEnter }),
  81. PluginPrism({ definition: PrismPromql, language: PRISM_LANGUAGE }),
  82. ];
  83. this.state = {
  84. labelKeys: props.labelKeys || {},
  85. labelValues: props.labelValues || {},
  86. metrics: props.metrics || [],
  87. };
  88. }
  89. componentDidMount() {
  90. this.fetchMetricNames();
  91. }
  92. onChangeQuery = value => {
  93. // Send text change to parent
  94. const { onQueryChange } = this.props;
  95. if (onQueryChange) {
  96. onQueryChange(value);
  97. }
  98. };
  99. onReceiveMetrics = () => {
  100. if (!this.state.metrics) {
  101. return;
  102. }
  103. setPrismTokens(PRISM_LANGUAGE, METRIC_MARK, this.state.metrics);
  104. };
  105. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  106. const { prefix, text, value, wrapperNode } = typeahead;
  107. // Get DOM-dependent context
  108. const wrapperClasses = Array.from(wrapperNode.classList);
  109. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  110. const labelKey = labelKeyNode && labelKeyNode.textContent;
  111. const nextChar = getNextCharacter();
  112. const result = this.getTypeahead({ text, value, prefix, wrapperClasses, labelKey });
  113. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  114. return result;
  115. };
  116. // Keep this DOM-free for testing
  117. getTypeahead({ prefix, wrapperClasses, text }: PromTypeaheadInput): TypeaheadOutput {
  118. // Determine candidates by CSS context
  119. if (_.includes(wrapperClasses, 'context-range')) {
  120. // Suggestions for metric[|]
  121. return this.getRangeTypeahead();
  122. } else if (_.includes(wrapperClasses, 'context-labels')) {
  123. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  124. return this.getLabelTypeahead.apply(this, arguments);
  125. } else if (_.includes(wrapperClasses, 'context-aggregation')) {
  126. return this.getAggregationTypeahead.apply(this, arguments);
  127. } else if (
  128. // Non-empty but not inside known token
  129. (prefix && !_.includes(wrapperClasses, 'token')) ||
  130. (prefix === '' && !text.match(/^[)\s]+$/)) || // Empty context or after ')'
  131. text.match(/[+\-*/^%]/) // After binary operator
  132. ) {
  133. return this.getEmptyTypeahead();
  134. }
  135. return {
  136. suggestions: [],
  137. };
  138. }
  139. getEmptyTypeahead(): TypeaheadOutput {
  140. const suggestions: SuggestionGroup[] = [];
  141. suggestions.push({
  142. prefixMatch: true,
  143. label: 'Functions',
  144. items: FUNCTIONS.map(setFunctionMove),
  145. });
  146. if (this.state.metrics) {
  147. suggestions.push({
  148. label: 'Metrics',
  149. items: this.state.metrics.map(wrapLabel),
  150. });
  151. }
  152. return { suggestions };
  153. }
  154. getRangeTypeahead(): TypeaheadOutput {
  155. return {
  156. context: 'context-range',
  157. suggestions: [
  158. {
  159. label: 'Range vector',
  160. items: [...RATE_RANGES].map(wrapLabel),
  161. },
  162. ],
  163. };
  164. }
  165. getAggregationTypeahead({ value }: PromTypeaheadInput): TypeaheadOutput {
  166. let refresher: Promise<any> = null;
  167. const suggestions: SuggestionGroup[] = [];
  168. // sum(foo{bar="1"}) by (|)
  169. const line = value.anchorBlock.getText();
  170. const cursorOffset: number = value.anchorOffset;
  171. // sum(foo{bar="1"}) by (
  172. const leftSide = line.slice(0, cursorOffset);
  173. const openParensAggregationIndex = leftSide.lastIndexOf('(');
  174. const openParensSelectorIndex = leftSide.slice(0, openParensAggregationIndex).lastIndexOf('(');
  175. const closeParensSelectorIndex = leftSide.slice(openParensSelectorIndex).indexOf(')') + openParensSelectorIndex;
  176. // foo{bar="1"}
  177. const selectorString = leftSide.slice(openParensSelectorIndex + 1, closeParensSelectorIndex);
  178. const selector = getCleanSelector(selectorString, selectorString.length - 2);
  179. const labelKeys = this.state.labelKeys[selector];
  180. if (labelKeys) {
  181. suggestions.push({ label: 'Labels', items: labelKeys.map(wrapLabel) });
  182. } else {
  183. refresher = this.fetchSeriesLabels(selector);
  184. }
  185. return {
  186. refresher,
  187. suggestions,
  188. context: 'context-aggregation',
  189. };
  190. }
  191. getLabelTypeahead({ text, wrapperClasses, labelKey, value }: PromTypeaheadInput): TypeaheadOutput {
  192. let context: string;
  193. let refresher: Promise<any> = null;
  194. const suggestions: SuggestionGroup[] = [];
  195. const line = value.anchorBlock.getText();
  196. const cursorOffset: number = value.anchorOffset;
  197. // Get normalized selector
  198. let selector;
  199. try {
  200. selector = getCleanSelector(line, cursorOffset);
  201. } catch {
  202. selector = EMPTY_SELECTOR;
  203. }
  204. const containsMetric = selector.indexOf('__name__=') > -1;
  205. if ((text && text.startsWith('=')) || _.includes(wrapperClasses, 'attr-value')) {
  206. // Label values
  207. if (labelKey && this.state.labelValues[selector] && this.state.labelValues[selector][labelKey]) {
  208. const labelValues = this.state.labelValues[selector][labelKey];
  209. context = 'context-label-values';
  210. suggestions.push({
  211. label: `Label values for "${labelKey}"`,
  212. items: labelValues.map(wrapLabel),
  213. });
  214. }
  215. } else {
  216. // Label keys
  217. const labelKeys = this.state.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  218. if (labelKeys) {
  219. context = 'context-labels';
  220. suggestions.push({ label: `Labels`, items: labelKeys.map(wrapLabel) });
  221. }
  222. }
  223. // Query labels for selector
  224. if (selector && !this.state.labelValues[selector]) {
  225. if (selector === EMPTY_SELECTOR) {
  226. // Query label values for default labels
  227. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  228. } else {
  229. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  230. }
  231. }
  232. return { context, refresher, suggestions };
  233. }
  234. request = url => {
  235. if (this.props.request) {
  236. return this.props.request(url);
  237. }
  238. return fetch(url);
  239. };
  240. async fetchLabelValues(key) {
  241. const url = `/api/v1/label/${key}/values`;
  242. try {
  243. const res = await this.request(url);
  244. const body = await (res.data || res.json());
  245. const exisingValues = this.state.labelValues[EMPTY_SELECTOR];
  246. const values = {
  247. ...exisingValues,
  248. [key]: body.data,
  249. };
  250. const labelValues = {
  251. ...this.state.labelValues,
  252. [EMPTY_SELECTOR]: values,
  253. };
  254. this.setState({ labelValues });
  255. } catch (e) {
  256. console.error(e);
  257. }
  258. }
  259. async fetchSeriesLabels(name, withName?) {
  260. const url = `/api/v1/series?match[]=${name}`;
  261. try {
  262. const res = await this.request(url);
  263. const body = await (res.data || res.json());
  264. const { keys, values } = processLabels(body.data, withName);
  265. const labelKeys = {
  266. ...this.state.labelKeys,
  267. [name]: keys,
  268. };
  269. const labelValues = {
  270. ...this.state.labelValues,
  271. [name]: values,
  272. };
  273. this.setState({ labelKeys, labelValues });
  274. } catch (e) {
  275. console.error(e);
  276. }
  277. }
  278. async fetchMetricNames() {
  279. const url = '/api/v1/label/__name__/values';
  280. try {
  281. const res = await this.request(url);
  282. const body = await (res.data || res.json());
  283. this.setState({ metrics: body.data }, this.onReceiveMetrics);
  284. } catch (error) {
  285. console.error(error);
  286. }
  287. }
  288. render() {
  289. return (
  290. <TypeaheadField
  291. additionalPlugins={this.plugins}
  292. cleanText={cleanText}
  293. initialValue={this.props.initialQuery}
  294. onTypeahead={this.onTypeahead}
  295. onWillApplySuggestion={willApplySuggestion}
  296. onValueChanged={this.onChangeQuery}
  297. placeholder="Enter a PromQL query"
  298. />
  299. );
  300. }
  301. }
  302. export default PromQueryField;