PromQueryField.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import { LanguageMap, languages as prismLanguages } from 'prismjs';
  2. import React, { ReactNode } from 'react';
  3. import { Plugin } from 'slate';
  4. import { QueryEditorProps, QueryHint, isDataFrame, toLegacyResponseData, TimeRange, CoreApp } from '@grafana/data';
  5. import {
  6. SlatePrism,
  7. TypeaheadInput,
  8. TypeaheadOutput,
  9. BracesPlugin,
  10. DOMUtil,
  11. SuggestionsState,
  12. Icon,
  13. } from '@grafana/ui';
  14. import { LocalStorageValueProvider } from 'app/core/components/LocalStorageValueProvider';
  15. import { CancelablePromise, makePromiseCancelable } from 'app/core/utils/CancelablePromise';
  16. import { PrometheusDatasource } from '../datasource';
  17. import { roundMsToMin } from '../language_utils';
  18. import { PromQuery, PromOptions } from '../types';
  19. import { PrometheusMetricsBrowser } from './PrometheusMetricsBrowser';
  20. import { MonacoQueryFieldWrapper } from './monaco-query-field/MonacoQueryFieldWrapper';
  21. export const RECORDING_RULES_GROUP = '__recording_rules__';
  22. const LAST_USED_LABELS_KEY = 'grafana.datasources.prometheus.browser.labels';
  23. function getChooserText(metricsLookupDisabled: boolean, hasSyntax: boolean, hasMetrics: boolean) {
  24. if (metricsLookupDisabled) {
  25. return '(Disabled)';
  26. }
  27. if (!hasSyntax) {
  28. return 'Loading metrics...';
  29. }
  30. if (!hasMetrics) {
  31. return '(No metrics found)';
  32. }
  33. return 'Metrics browser';
  34. }
  35. export function willApplySuggestion(suggestion: string, { typeaheadContext, typeaheadText }: SuggestionsState): string {
  36. // Modify suggestion based on context
  37. switch (typeaheadContext) {
  38. case 'context-labels': {
  39. const nextChar = DOMUtil.getNextCharacter();
  40. if (!nextChar || nextChar === '}' || nextChar === ',') {
  41. suggestion += '=';
  42. }
  43. break;
  44. }
  45. case 'context-label-values': {
  46. // Always add quotes and remove existing ones instead
  47. if (!typeaheadText.match(/^(!?=~?"|")/)) {
  48. suggestion = `"${suggestion}`;
  49. }
  50. if (DOMUtil.getNextCharacter() !== '"') {
  51. suggestion = `${suggestion}"`;
  52. }
  53. break;
  54. }
  55. default:
  56. }
  57. return suggestion;
  58. }
  59. interface PromQueryFieldProps extends QueryEditorProps<PrometheusDatasource, PromQuery, PromOptions> {
  60. ExtraFieldElement?: ReactNode;
  61. 'data-testid'?: string;
  62. }
  63. interface PromQueryFieldState {
  64. labelBrowserVisible: boolean;
  65. syntaxLoaded: boolean;
  66. hint: QueryHint | null;
  67. }
  68. class PromQueryField extends React.PureComponent<PromQueryFieldProps, PromQueryFieldState> {
  69. plugins: Plugin[];
  70. declare languageProviderInitializationPromise: CancelablePromise<any>;
  71. constructor(props: PromQueryFieldProps, context: React.Context<any>) {
  72. super(props, context);
  73. this.plugins = [
  74. BracesPlugin(),
  75. SlatePrism(
  76. {
  77. onlyIn: (node: any) => node.type === 'code_block',
  78. getSyntax: (node: any) => 'promql',
  79. },
  80. { ...(prismLanguages as LanguageMap), promql: this.props.datasource.languageProvider.syntax }
  81. ),
  82. ];
  83. this.state = {
  84. labelBrowserVisible: false,
  85. syntaxLoaded: false,
  86. hint: null,
  87. };
  88. }
  89. componentDidMount() {
  90. if (this.props.datasource.languageProvider) {
  91. this.refreshMetrics();
  92. }
  93. this.refreshHint();
  94. }
  95. componentWillUnmount() {
  96. if (this.languageProviderInitializationPromise) {
  97. this.languageProviderInitializationPromise.cancel();
  98. }
  99. }
  100. componentDidUpdate(prevProps: PromQueryFieldProps) {
  101. const {
  102. data,
  103. datasource: { languageProvider },
  104. range,
  105. } = this.props;
  106. if (languageProvider !== prevProps.datasource.languageProvider) {
  107. // We reset this only on DS change so we do not flesh loading state on every rangeChange which happens on every
  108. // query run if using relative range.
  109. this.setState({
  110. syntaxLoaded: false,
  111. });
  112. }
  113. const changedRangeToRefresh = this.rangeChangedToRefresh(range, prevProps.range);
  114. // We want to refresh metrics when language provider changes and/or when range changes (we round up intervals to a minute)
  115. if (languageProvider !== prevProps.datasource.languageProvider || changedRangeToRefresh) {
  116. this.refreshMetrics();
  117. }
  118. if (data && prevProps.data && prevProps.data.series !== data.series) {
  119. this.refreshHint();
  120. }
  121. }
  122. refreshHint = () => {
  123. const { datasource, query, data } = this.props;
  124. const initHints = datasource.getInitHints();
  125. const initHint = initHints.length > 0 ? initHints[0] : null;
  126. if (!data || data.series.length === 0) {
  127. this.setState({
  128. hint: initHint,
  129. });
  130. return;
  131. }
  132. const result = isDataFrame(data.series[0]) ? data.series.map(toLegacyResponseData) : data.series;
  133. const queryHints = datasource.getQueryHints(query, result);
  134. let queryHint = queryHints.length > 0 ? queryHints[0] : null;
  135. this.setState({ hint: queryHint ?? initHint });
  136. };
  137. refreshMetrics = async () => {
  138. const {
  139. datasource: { languageProvider },
  140. } = this.props;
  141. this.languageProviderInitializationPromise = makePromiseCancelable(languageProvider.start());
  142. try {
  143. const remainingTasks = await this.languageProviderInitializationPromise.promise;
  144. await Promise.all(remainingTasks);
  145. this.onUpdateLanguage();
  146. } catch (err) {
  147. if (!err.isCanceled) {
  148. throw err;
  149. }
  150. }
  151. };
  152. rangeChangedToRefresh(range?: TimeRange, prevRange?: TimeRange): boolean {
  153. if (range && prevRange) {
  154. const sameMinuteFrom = roundMsToMin(range.from.valueOf()) === roundMsToMin(prevRange.from.valueOf());
  155. const sameMinuteTo = roundMsToMin(range.to.valueOf()) === roundMsToMin(prevRange.to.valueOf());
  156. // If both are same, don't need to refresh.
  157. return !(sameMinuteFrom && sameMinuteTo);
  158. }
  159. return false;
  160. }
  161. /**
  162. * TODO #33976: Remove this, add histogram group (query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;)
  163. */
  164. onChangeLabelBrowser = (selector: string) => {
  165. this.onChangeQuery(selector, true);
  166. this.setState({ labelBrowserVisible: false });
  167. };
  168. onChangeQuery = (value: string, override?: boolean) => {
  169. // Send text change to parent
  170. const { query, onChange, onRunQuery } = this.props;
  171. if (onChange) {
  172. const nextQuery: PromQuery = { ...query, expr: value };
  173. onChange(nextQuery);
  174. if (override && onRunQuery) {
  175. onRunQuery();
  176. }
  177. }
  178. };
  179. onClickChooserButton = () => {
  180. this.setState((state) => ({ labelBrowserVisible: !state.labelBrowserVisible }));
  181. };
  182. onClickHintFix = () => {
  183. const { datasource, query, onChange, onRunQuery } = this.props;
  184. const { hint } = this.state;
  185. onChange(datasource.modifyQuery(query, hint!.fix!.action));
  186. onRunQuery();
  187. };
  188. onUpdateLanguage = () => {
  189. const {
  190. datasource: { languageProvider },
  191. } = this.props;
  192. const { metrics } = languageProvider;
  193. if (!metrics) {
  194. return;
  195. }
  196. this.setState({ syntaxLoaded: true });
  197. };
  198. onTypeahead = async (typeahead: TypeaheadInput): Promise<TypeaheadOutput> => {
  199. const {
  200. datasource: { languageProvider },
  201. } = this.props;
  202. if (!languageProvider) {
  203. return { suggestions: [] };
  204. }
  205. const { history } = this.props;
  206. const { prefix, text, value, wrapperClasses, labelKey } = typeahead;
  207. const result = await languageProvider.provideCompletionItems(
  208. { text, value, prefix, wrapperClasses, labelKey },
  209. { history }
  210. );
  211. return result;
  212. };
  213. render() {
  214. const {
  215. datasource,
  216. datasource: { languageProvider },
  217. query,
  218. ExtraFieldElement,
  219. history = [],
  220. } = this.props;
  221. const { labelBrowserVisible, syntaxLoaded, hint } = this.state;
  222. const hasMetrics = languageProvider.metrics.length > 0;
  223. const chooserText = getChooserText(datasource.lookupsDisabled, syntaxLoaded, hasMetrics);
  224. const buttonDisabled = !(syntaxLoaded && hasMetrics);
  225. return (
  226. <LocalStorageValueProvider<string[]> storageKey={LAST_USED_LABELS_KEY} defaultValue={[]}>
  227. {(lastUsedLabels, onLastUsedLabelsSave, onLastUsedLabelsDelete) => {
  228. return (
  229. <>
  230. <div
  231. className="gf-form-inline gf-form-inline--xs-view-flex-column flex-grow-1"
  232. data-testid={this.props['data-testid']}
  233. >
  234. <button
  235. className="gf-form-label query-keyword pointer"
  236. onClick={this.onClickChooserButton}
  237. disabled={buttonDisabled}
  238. >
  239. {chooserText}
  240. <Icon name={labelBrowserVisible ? 'angle-down' : 'angle-right'} />
  241. </button>
  242. <div className="gf-form gf-form--grow flex-shrink-1 min-width-15">
  243. <MonacoQueryFieldWrapper
  244. runQueryOnBlur={this.props.app !== CoreApp.Explore}
  245. languageProvider={languageProvider}
  246. history={history}
  247. onChange={this.onChangeQuery}
  248. onRunQuery={this.props.onRunQuery}
  249. initialValue={query.expr ?? ''}
  250. />
  251. </div>
  252. </div>
  253. {labelBrowserVisible && (
  254. <div className="gf-form">
  255. <PrometheusMetricsBrowser
  256. languageProvider={languageProvider}
  257. onChange={this.onChangeLabelBrowser}
  258. lastUsedLabels={lastUsedLabels || []}
  259. storeLastUsedLabels={onLastUsedLabelsSave}
  260. deleteLastUsedLabels={onLastUsedLabelsDelete}
  261. />
  262. </div>
  263. )}
  264. {ExtraFieldElement}
  265. {hint ? (
  266. <div className="query-row-break">
  267. <div className="prom-query-field-info text-warning">
  268. {hint.label}{' '}
  269. {hint.fix ? (
  270. <a className="text-link muted" onClick={this.onClickHintFix}>
  271. {hint.fix.label}
  272. </a>
  273. ) : null}
  274. </div>
  275. </div>
  276. ) : null}
  277. </>
  278. );
  279. }}
  280. </LocalStorageValueProvider>
  281. );
  282. }
  283. }
  284. export default PromQueryField;