PromQueryField.tsx 8.9 KB

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