PromQueryField.tsx 11 KB

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