PromQueryField.tsx 7.8 KB

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