PromQueryField.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom';
  12. import BracesPlugin from 'app/features/explore/slate-plugins/braces';
  13. import RunnerPlugin from 'app/features/explore/slate-plugins/runner';
  14. import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField';
  15. import { PromQuery } from '../types';
  16. import { CancelablePromise, makePromiseCancelable } from 'app/core/utils/CancelablePromise';
  17. import { ExploreDataSourceApi, ExploreQueryFieldProps, DataSourceStatus, QueryHint } from '@grafana/ui';
  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 = 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 (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<ExploreDataSourceApi<PromQuery>, PromQuery> {
  93. history: HistoryItem[];
  94. }
  95. interface PromQueryFieldState {
  96. metricsOptions: any[];
  97. syntaxLoaded: boolean;
  98. hint: QueryHint;
  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. RunnerPlugin({ handler: props.onRunQuery }),
  112. PluginPrism({
  113. onlyIn: (node: any) => node.type === 'code_block',
  114. getSyntax: (node: any) => 'promql',
  115. }),
  116. ];
  117. this.state = {
  118. metricsOptions: [],
  119. syntaxLoaded: false,
  120. hint: null,
  121. };
  122. }
  123. componentDidMount() {
  124. if (this.languageProvider) {
  125. this.refreshMetrics(makePromiseCancelable(this.languageProvider.start()));
  126. }
  127. this.refreshHint();
  128. }
  129. componentWillUnmount() {
  130. if (this.languageProviderInitializationPromise) {
  131. this.languageProviderInitializationPromise.cancel();
  132. }
  133. }
  134. componentDidUpdate(prevProps: PromQueryFieldProps) {
  135. const currentHasSeries = this.props.queryResponse.series && this.props.queryResponse.series.length > 0;
  136. if (currentHasSeries && prevProps.queryResponse.series !== this.props.queryResponse.series) {
  137. this.refreshHint();
  138. }
  139. const reconnected =
  140. prevProps.datasourceStatus === DataSourceStatus.Disconnected &&
  141. this.props.datasourceStatus === DataSourceStatus.Connected;
  142. if (!reconnected) {
  143. return;
  144. }
  145. if (this.languageProviderInitializationPromise) {
  146. this.languageProviderInitializationPromise.cancel();
  147. }
  148. if (this.languageProvider) {
  149. this.refreshMetrics(makePromiseCancelable(this.languageProvider.fetchMetrics()));
  150. }
  151. }
  152. refreshHint = () => {
  153. const { datasource, query, queryResponse } = this.props;
  154. if (queryResponse.series && queryResponse.series.length === 0) {
  155. return;
  156. }
  157. const hints = datasource.getQueryHints(query, queryResponse.series);
  158. const hint = hints && hints.length > 0 ? hints[0] : null;
  159. this.setState({ hint });
  160. };
  161. refreshMetrics = (cancelablePromise: CancelablePromise<any>) => {
  162. this.languageProviderInitializationPromise = cancelablePromise;
  163. this.languageProviderInitializationPromise.promise
  164. .then(remaining => {
  165. remaining.map((task: Promise<any>) => task.then(this.onUpdateLanguage).catch(() => {}));
  166. })
  167. .then(() => this.onUpdateLanguage())
  168. .catch(({ isCanceled }) => {
  169. if (isCanceled) {
  170. console.warn('PromQueryField has unmounted, language provider intialization was canceled');
  171. }
  172. });
  173. };
  174. onChangeMetrics = (values: string[], selectedOptions: CascaderOption[]) => {
  175. let query;
  176. if (selectedOptions.length === 1) {
  177. if (selectedOptions[0].children.length === 0) {
  178. query = selectedOptions[0].value;
  179. } else {
  180. // Ignore click on group
  181. return;
  182. }
  183. } else {
  184. const prefix = selectedOptions[0].value;
  185. const metric = selectedOptions[1].value;
  186. if (prefix === HISTOGRAM_GROUP) {
  187. query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;
  188. } else {
  189. query = metric;
  190. }
  191. }
  192. this.onChangeQuery(query, true);
  193. };
  194. onChangeQuery = (value: string, override?: boolean) => {
  195. // Send text change to parent
  196. const { query, onChange, onRunQuery } = this.props;
  197. if (onChange) {
  198. const nextQuery: PromQuery = { ...query, expr: value };
  199. onChange(nextQuery);
  200. if (override && onRunQuery) {
  201. onRunQuery();
  202. }
  203. }
  204. };
  205. onClickHintFix = () => {
  206. const { hint } = this.state;
  207. const { onHint } = this.props;
  208. if (onHint && hint && hint.fix) {
  209. onHint(hint.fix.action);
  210. }
  211. };
  212. onUpdateLanguage = () => {
  213. const { histogramMetrics, metrics } = this.languageProvider;
  214. if (!metrics) {
  215. return;
  216. }
  217. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  218. Prism.languages[PRISM_SYNTAX][METRIC_MARK] = {
  219. alias: 'variable',
  220. pattern: new RegExp(`(?:^|\\s)(${metrics.join('|')})(?:$|\\s)`),
  221. };
  222. // Build metrics tree
  223. const metricsByPrefix = groupMetricsByPrefix(metrics);
  224. const histogramOptions = histogramMetrics.map((hm: any) => ({ label: hm, value: hm }));
  225. const metricsOptions =
  226. histogramMetrics.length > 0
  227. ? [
  228. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions, isLeaf: false },
  229. ...metricsByPrefix,
  230. ]
  231. : metricsByPrefix;
  232. this.setState({ metricsOptions, syntaxLoaded: true });
  233. };
  234. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  235. if (!this.languageProvider) {
  236. return { suggestions: [] };
  237. }
  238. const { history } = this.props;
  239. const { prefix, text, value, wrapperNode } = typeahead;
  240. // Get DOM-dependent context
  241. const wrapperClasses = Array.from(wrapperNode.classList);
  242. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  243. const labelKey = labelKeyNode && labelKeyNode.textContent;
  244. const nextChar = getNextCharacter();
  245. const result = this.languageProvider.provideCompletionItems(
  246. { text, value, prefix, wrapperClasses, labelKey },
  247. { history }
  248. );
  249. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  250. return result;
  251. };
  252. render() {
  253. const { queryResponse, query, datasourceStatus } = this.props;
  254. const { metricsOptions, syntaxLoaded, hint } = this.state;
  255. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  256. const chooserText = getChooserText(syntaxLoaded, datasourceStatus);
  257. const buttonDisabled = !syntaxLoaded || datasourceStatus === DataSourceStatus.Disconnected;
  258. return (
  259. <>
  260. <div className="gf-form-inline gf-form-inline--nowrap">
  261. <div className="gf-form flex-shrink-0">
  262. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  263. <button className="gf-form-label gf-form-label--btn" disabled={buttonDisabled}>
  264. {chooserText} <i className="fa fa-caret-down" />
  265. </button>
  266. </Cascader>
  267. </div>
  268. <div className="gf-form gf-form--grow flex-shrink-1">
  269. <QueryField
  270. additionalPlugins={this.plugins}
  271. cleanText={cleanText}
  272. initialQuery={query.expr}
  273. onTypeahead={this.onTypeahead}
  274. onWillApplySuggestion={willApplySuggestion}
  275. onChange={this.onChangeQuery}
  276. onRunQuery={this.props.onRunQuery}
  277. placeholder="Enter a PromQL query"
  278. portalOrigin="prometheus"
  279. syntaxLoaded={syntaxLoaded}
  280. />
  281. </div>
  282. </div>
  283. {queryResponse && queryResponse.error ? (
  284. <div className="prom-query-field-info text-error">{queryResponse.error.message}</div>
  285. ) : null}
  286. {hint ? (
  287. <div className="prom-query-field-info text-warning">
  288. {hint.label}{' '}
  289. {hint.fix ? (
  290. <a className="text-link muted" onClick={this.onClickHintFix}>
  291. {hint.fix.label}
  292. </a>
  293. ) : null}
  294. </div>
  295. ) : null}
  296. </>
  297. );
  298. }
  299. }
  300. export default PromQueryField;