PromQueryField.tsx 8.9 KB

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