PromQueryField.tsx 8.3 KB

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