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