PromQueryField.tsx 8.3 KB

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