PromQueryField.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import _ from 'lodash';
  2. import React from 'react';
  3. import Cascader from 'rc-cascader';
  4. import PluginPrism from 'slate-prism';
  5. import Prism from 'prismjs';
  6. import { TypeaheadOutput } from 'app/types/explore';
  7. // dom also includes Element polyfills
  8. import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom';
  9. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  10. import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
  11. import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
  12. import { PromQuery } from '../types';
  13. import { CancelablePromise, makePromiseCancelable } from 'app/core/utils/CancelablePromise';
  14. const HISTOGRAM_GROUP = '__histograms__';
  15. const METRIC_MARK = 'metric';
  16. const PRISM_SYNTAX = 'promql';
  17. export const RECORDING_RULES_GROUP = '__recording_rules__';
  18. export function groupMetricsByPrefix(metrics: string[], delimiter = '_'): CascaderOption[] {
  19. // Filter out recording rules and insert as first option
  20. const ruleRegex = /:\w+:/;
  21. const ruleNames = metrics.filter(metric => ruleRegex.test(metric));
  22. const rulesOption = {
  23. label: 'Recording rules',
  24. value: RECORDING_RULES_GROUP,
  25. children: ruleNames
  26. .slice()
  27. .sort()
  28. .map(name => ({ label: name, value: name })),
  29. };
  30. const options = ruleNames.length > 0 ? [rulesOption] : [];
  31. const metricsOptions = _.chain(metrics)
  32. .filter(metric => !ruleRegex.test(metric))
  33. .groupBy(metric => metric.split(delimiter)[0])
  34. .map((metricsForPrefix: string[], prefix: string): CascaderOption => {
  35. const prefixIsMetric = metricsForPrefix.length === 1 && metricsForPrefix[0] === prefix;
  36. const children = prefixIsMetric ? [] : metricsForPrefix.sort().map(m => ({ label: m, value: m }));
  37. return {
  38. children,
  39. label: prefix,
  40. value: prefix,
  41. };
  42. })
  43. .sortBy('label')
  44. .value();
  45. return [...options, ...metricsOptions];
  46. }
  47. export function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: QueryFieldState): 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.match(/^(!?=~?"|")/)) {
  60. suggestion = `"${suggestion}`;
  61. }
  62. if (getNextCharacter() !== '"') {
  63. suggestion = `${suggestion}"`;
  64. }
  65. break;
  66. }
  67. default:
  68. }
  69. return suggestion;
  70. }
  71. interface CascaderOption {
  72. label: string;
  73. value: string;
  74. children?: CascaderOption[];
  75. disabled?: boolean;
  76. }
  77. interface PromQueryFieldProps {
  78. datasource: any;
  79. error?: string | JSX.Element;
  80. initialQuery: PromQuery;
  81. hint?: any;
  82. history?: any[];
  83. onClickHintFix?: (action: any) => void;
  84. onPressEnter?: () => void;
  85. onQueryChange?: (value: PromQuery, override?: boolean) => void;
  86. }
  87. interface PromQueryFieldState {
  88. metricsOptions: any[];
  89. syntaxLoaded: boolean;
  90. }
  91. class PromQueryField extends React.PureComponent<PromQueryFieldProps, PromQueryFieldState> {
  92. plugins: any[];
  93. languageProvider: any;
  94. languageProviderInitializationPromise: CancelablePromise<any>;
  95. constructor(props: PromQueryFieldProps, context) {
  96. super(props, context);
  97. if (props.datasource.languageProvider) {
  98. this.languageProvider = props.datasource.languageProvider;
  99. }
  100. this.plugins = [
  101. BracesPlugin(),
  102. RunnerPlugin({ handler: props.onPressEnter }),
  103. PluginPrism({
  104. onlyIn: node => node.type === 'code_block',
  105. getSyntax: node => 'promql',
  106. }),
  107. ];
  108. this.state = {
  109. metricsOptions: [],
  110. syntaxLoaded: false,
  111. };
  112. }
  113. componentDidMount() {
  114. if (this.languageProvider) {
  115. this.languageProviderInitializationPromise = makePromiseCancelable(this.languageProvider.start());
  116. this.languageProviderInitializationPromise.promise
  117. .then(remaining => {
  118. remaining.map(task => task.then(this.onUpdateLanguage).catch(() => {}));
  119. })
  120. .then(() => this.onUpdateLanguage())
  121. .catch(({ isCanceled }) => {
  122. if (isCanceled) {
  123. console.warn('PromQueryField has unmounted, language provider intialization was canceled');
  124. }
  125. });
  126. }
  127. }
  128. componentWillUnmount() {
  129. if (this.languageProviderInitializationPromise) {
  130. this.languageProviderInitializationPromise.cancel();
  131. }
  132. }
  133. onChangeMetrics = (values: string[], selectedOptions: CascaderOption[]) => {
  134. let query;
  135. if (selectedOptions.length === 1) {
  136. if (selectedOptions[0].children.length === 0) {
  137. query = selectedOptions[0].value;
  138. } else {
  139. // Ignore click on group
  140. return;
  141. }
  142. } else {
  143. const prefix = selectedOptions[0].value;
  144. const metric = selectedOptions[1].value;
  145. if (prefix === HISTOGRAM_GROUP) {
  146. query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;
  147. } else {
  148. query = metric;
  149. }
  150. }
  151. this.onChangeQuery(query, true);
  152. };
  153. onChangeQuery = (value: string, override?: boolean) => {
  154. // Send text change to parent
  155. const { initialQuery, onQueryChange } = this.props;
  156. if (onQueryChange) {
  157. const query: PromQuery = {
  158. ...initialQuery,
  159. expr: value,
  160. };
  161. onQueryChange(query, override);
  162. }
  163. };
  164. onClickHintFix = () => {
  165. const { hint, onClickHintFix } = this.props;
  166. if (onClickHintFix && hint && hint.fix) {
  167. onClickHintFix(hint.fix.action);
  168. }
  169. };
  170. onUpdateLanguage = () => {
  171. const { histogramMetrics, metrics } = this.languageProvider;
  172. if (!metrics) {
  173. return;
  174. }
  175. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  176. Prism.languages[PRISM_SYNTAX][METRIC_MARK] = {
  177. alias: 'variable',
  178. pattern: new RegExp(`(?:^|\\s)(${metrics.join('|')})(?:$|\\s)`),
  179. };
  180. // Build metrics tree
  181. const metricsByPrefix = groupMetricsByPrefix(metrics);
  182. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  183. const metricsOptions =
  184. histogramMetrics.length > 0
  185. ? [
  186. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions, isLeaf: false },
  187. ...metricsByPrefix,
  188. ]
  189. : metricsByPrefix;
  190. this.setState({ metricsOptions, syntaxLoaded: true });
  191. };
  192. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  193. if (!this.languageProvider) {
  194. return { suggestions: [] };
  195. }
  196. const { history } = this.props;
  197. const { prefix, text, value, wrapperNode } = typeahead;
  198. // Get DOM-dependent context
  199. const wrapperClasses = Array.from(wrapperNode.classList);
  200. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  201. const labelKey = labelKeyNode && labelKeyNode.textContent;
  202. const nextChar = getNextCharacter();
  203. const result = this.languageProvider.provideCompletionItems(
  204. { text, value, prefix, wrapperClasses, labelKey },
  205. { history }
  206. );
  207. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  208. return result;
  209. };
  210. render() {
  211. const { error, hint, initialQuery } = this.props;
  212. const { metricsOptions, syntaxLoaded } = this.state;
  213. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  214. const chooserText = syntaxLoaded ? 'Metrics' : 'Loading metrics...';
  215. return (
  216. <>
  217. <div className="gf-form-inline gf-form-inline--nowrap">
  218. <div className="gf-form flex-shrink-0">
  219. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  220. <button className="gf-form-label gf-form-label--btn" disabled={!syntaxLoaded}>
  221. {chooserText} <i className="fa fa-caret-down" />
  222. </button>
  223. </Cascader>
  224. </div>
  225. <div className="gf-form gf-form--grow flex-shrink-1">
  226. <QueryField
  227. additionalPlugins={this.plugins}
  228. cleanText={cleanText}
  229. initialQuery={initialQuery.expr}
  230. onTypeahead={this.onTypeahead}
  231. onWillApplySuggestion={willApplySuggestion}
  232. onValueChanged={this.onChangeQuery}
  233. placeholder="Enter a PromQL query"
  234. portalOrigin="prometheus"
  235. syntaxLoaded={syntaxLoaded}
  236. />
  237. </div>
  238. </div>
  239. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  240. {hint ? (
  241. <div className="prom-query-field-info text-warning">
  242. {hint.label}{' '}
  243. {hint.fix ? (
  244. <a className="text-link muted" onClick={this.onClickHintFix}>
  245. {hint.fix.label}
  246. </a>
  247. ) : null}
  248. </div>
  249. ) : null}
  250. </>
  251. );
  252. }
  253. }
  254. export default PromQueryField;