PromQueryField.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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, TypeaheadFieldState } 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(
  46. suggestion: string,
  47. { typeaheadContext, typeaheadText }: TypeaheadFieldState
  48. ): 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 {
  79. datasource: any;
  80. error?: string | JSX.Element;
  81. hint?: any;
  82. history?: any[];
  83. initialQuery?: string | null;
  84. metricsByPrefix?: CascaderOption[];
  85. onClickHintFix?: (action: any) => void;
  86. onPressEnter?: () => void;
  87. onQueryChange?: (value: string, override?: boolean) => void;
  88. supportsLogs?: boolean; // To be removed after Logging gets its own query field
  89. }
  90. interface PromQueryFieldState {
  91. logLabelOptions: any[];
  92. metricsOptions: any[];
  93. metricsByPrefix: CascaderOption[];
  94. syntaxLoaded: boolean;
  95. }
  96. class PromQueryField extends React.PureComponent<PromQueryFieldProps, PromQueryFieldState> {
  97. plugins: any[];
  98. languageProvider: any;
  99. constructor(props: PromQueryFieldProps, context) {
  100. super(props, context);
  101. if (props.datasource.languageProvider) {
  102. this.languageProvider = props.datasource.languageProvider;
  103. }
  104. this.plugins = [
  105. BracesPlugin(),
  106. RunnerPlugin({ handler: props.onPressEnter }),
  107. PluginPrism({
  108. onlyIn: node => node.type === 'code_block',
  109. getSyntax: node => 'promql',
  110. }),
  111. ];
  112. this.state = {
  113. logLabelOptions: [],
  114. metricsByPrefix: [],
  115. metricsOptions: [],
  116. syntaxLoaded: false,
  117. };
  118. }
  119. componentDidMount() {
  120. if (this.languageProvider) {
  121. this.languageProvider.start().then(() => this.onReceiveMetrics());
  122. }
  123. }
  124. onChangeLogLabels = (values: string[], selectedOptions: CascaderOption[]) => {
  125. let query;
  126. if (selectedOptions.length === 1) {
  127. if (selectedOptions[0].children.length === 0) {
  128. query = selectedOptions[0].value;
  129. } else {
  130. // Ignore click on group
  131. return;
  132. }
  133. } else {
  134. const key = selectedOptions[0].value;
  135. const value = selectedOptions[1].value;
  136. query = `{${key}="${value}"}`;
  137. }
  138. this.onChangeQuery(query, true);
  139. };
  140. onChangeMetrics = (values: string[], selectedOptions: CascaderOption[]) => {
  141. let query;
  142. if (selectedOptions.length === 1) {
  143. if (selectedOptions[0].children.length === 0) {
  144. query = selectedOptions[0].value;
  145. } else {
  146. // Ignore click on group
  147. return;
  148. }
  149. } else {
  150. const prefix = selectedOptions[0].value;
  151. const metric = selectedOptions[1].value;
  152. if (prefix === HISTOGRAM_GROUP) {
  153. query = `histogram_quantile(0.95, sum(rate(${metric}[5m])) by (le))`;
  154. } else {
  155. query = metric;
  156. }
  157. }
  158. this.onChangeQuery(query, true);
  159. };
  160. onChangeQuery = (value: string, override?: boolean) => {
  161. // Send text change to parent
  162. const { onQueryChange } = this.props;
  163. if (onQueryChange) {
  164. onQueryChange(value, override);
  165. }
  166. };
  167. onClickHintFix = () => {
  168. const { hint, onClickHintFix } = this.props;
  169. if (onClickHintFix && hint && hint.fix) {
  170. onClickHintFix(hint.fix.action);
  171. }
  172. };
  173. onReceiveMetrics = () => {
  174. const { histogramMetrics, metrics } = this.languageProvider;
  175. if (!metrics) {
  176. return;
  177. }
  178. Prism.languages[PRISM_SYNTAX] = this.languageProvider.getSyntax();
  179. Prism.languages[PRISM_SYNTAX][METRIC_MARK] = {
  180. alias: 'variable',
  181. pattern: new RegExp(`(?:^|\\s)(${metrics.join('|')})(?:$|\\s)`),
  182. };
  183. // Build metrics tree
  184. const metricsByPrefix = groupMetricsByPrefix(metrics);
  185. const histogramOptions = histogramMetrics.map(hm => ({ label: hm, value: hm }));
  186. const metricsOptions = [
  187. { label: 'Histograms', value: HISTOGRAM_GROUP, children: histogramOptions },
  188. ...metricsByPrefix,
  189. ];
  190. this.setState({ metricsOptions, syntaxLoaded: true });
  191. };
  192. onTypeahead = (typeahead: TypeaheadInput): TypeaheadOutput => {
  193. if (!this.languageProvider) {
  194. return { suggestions: [] };
  195. }
  196. const { history } = this.props;
  197. const { prefix, text, value, wrapperNode } = typeahead;
  198. // Get DOM-dependent context
  199. const wrapperClasses = Array.from(wrapperNode.classList);
  200. const labelKeyNode = getPreviousCousin(wrapperNode, '.attr-name');
  201. const labelKey = labelKeyNode && labelKeyNode.textContent;
  202. const nextChar = getNextCharacter();
  203. const result = this.languageProvider.provideCompletionItems(
  204. { text, value, prefix, wrapperClasses, labelKey },
  205. { history }
  206. );
  207. console.log('handleTypeahead', wrapperClasses, text, prefix, nextChar, labelKey, result.context);
  208. return result;
  209. };
  210. render() {
  211. const { error, hint, initialQuery, supportsLogs } = this.props;
  212. const { logLabelOptions, metricsOptions, syntaxLoaded } = this.state;
  213. const cleanText = this.languageProvider ? this.languageProvider.cleanText : undefined;
  214. return (
  215. <div className="prom-query-field">
  216. <div className="prom-query-field-tools">
  217. {supportsLogs ? (
  218. <Cascader options={logLabelOptions} onChange={this.onChangeLogLabels}>
  219. <button className="btn navbar-button navbar-button--tight">Log labels</button>
  220. </Cascader>
  221. ) : (
  222. <Cascader options={metricsOptions} onChange={this.onChangeMetrics}>
  223. <button className="btn navbar-button navbar-button--tight">Metrics</button>
  224. </Cascader>
  225. )}
  226. </div>
  227. <div className="prom-query-field-wrapper">
  228. <TypeaheadField
  229. additionalPlugins={this.plugins}
  230. cleanText={cleanText}
  231. initialValue={initialQuery}
  232. onTypeahead={this.onTypeahead}
  233. onWillApplySuggestion={willApplySuggestion}
  234. onValueChanged={this.onChangeQuery}
  235. placeholder="Enter a PromQL query"
  236. portalOrigin="prometheus"
  237. syntaxLoaded={syntaxLoaded}
  238. />
  239. {error ? <div className="prom-query-field-info text-error">{error}</div> : null}
  240. {hint ? (
  241. <div className="prom-query-field-info text-warning">
  242. {hint.label}{' '}
  243. {hint.fix ? (
  244. <a className="text-link muted" onClick={this.onClickHintFix}>
  245. {hint.fix.label}
  246. </a>
  247. ) : null}
  248. </div>
  249. ) : null}
  250. </div>
  251. </div>
  252. );
  253. }
  254. }
  255. export default PromQueryField;