PromQueryField.tsx 11 KB

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