language_provider.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import _ from 'lodash';
  2. import moment from 'moment';
  3. import {
  4. CompletionItem,
  5. CompletionItemGroup,
  6. LanguageProvider,
  7. TypeaheadInput,
  8. TypeaheadOutput,
  9. } from 'app/types/explore';
  10. import { parseSelector, processLabels, processHistogramLabels } from './language_utils';
  11. import PromqlSyntax, { FUNCTIONS, RATE_RANGES } from './promql';
  12. const DEFAULT_KEYS = ['job', 'instance'];
  13. const EMPTY_SELECTOR = '{}';
  14. const HISTORY_ITEM_COUNT = 5;
  15. const HISTORY_COUNT_CUTOFF = 1000 * 60 * 60 * 24; // 24h
  16. const wrapLabel = (label: string) => ({ label });
  17. const setFunctionKind = (suggestion: CompletionItem): CompletionItem => {
  18. suggestion.kind = 'function';
  19. return suggestion;
  20. };
  21. export function addHistoryMetadata(item: CompletionItem, history: any[]): CompletionItem {
  22. const cutoffTs = Date.now() - HISTORY_COUNT_CUTOFF;
  23. const historyForItem = history.filter(h => h.ts > cutoffTs && h.query === item.label);
  24. const count = historyForItem.length;
  25. const recent = historyForItem[0];
  26. let hint = `Queried ${count} times in the last 24h.`;
  27. if (recent) {
  28. const lastQueried = moment(recent.ts).fromNow();
  29. hint = `${hint} Last queried ${lastQueried}.`;
  30. }
  31. return {
  32. ...item,
  33. documentation: hint,
  34. };
  35. }
  36. export default class PromQlLanguageProvider extends LanguageProvider {
  37. histogramMetrics?: string[];
  38. labelKeys?: { [index: string]: string[] }; // metric -> [labelKey,...]
  39. labelValues?: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  40. metrics?: string[];
  41. startTask: Promise<any>;
  42. constructor(datasource: any, initialValues?: any) {
  43. super();
  44. this.datasource = datasource;
  45. this.histogramMetrics = [];
  46. this.labelKeys = {};
  47. this.labelValues = {};
  48. this.metrics = [];
  49. Object.assign(this, initialValues);
  50. }
  51. // Strip syntax chars
  52. cleanText = (s: string) => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim();
  53. getSyntax() {
  54. return PromqlSyntax;
  55. }
  56. request = async (url: string) => {
  57. try {
  58. const res = await this.datasource.metadataRequest(url);
  59. const body = await (res.data || res.json());
  60. return body.data;
  61. } catch (error) {
  62. console.error(error);
  63. }
  64. return [];
  65. };
  66. start = () => {
  67. if (!this.startTask) {
  68. this.startTask = this.fetchMetrics();
  69. }
  70. return this.startTask;
  71. };
  72. fetchMetrics = async () => {
  73. this.metrics = await this.fetchMetricNames();
  74. this.processHistogramMetrics(this.metrics);
  75. return Promise.resolve([]);
  76. };
  77. fetchMetricNames = async (): Promise<string[]> => {
  78. return this.request('/api/v1/label/__name__/values');
  79. };
  80. processHistogramMetrics = (data: string[]) => {
  81. const { values } = processHistogramLabels(data);
  82. if (values && values['__name__']) {
  83. this.histogramMetrics = values['__name__'].slice().sort();
  84. }
  85. };
  86. // Keep this DOM-free for testing
  87. provideCompletionItems({ prefix, wrapperClasses, text, value }: TypeaheadInput, context?: any): TypeaheadOutput {
  88. // Local text properties
  89. const empty = value.document.text.length === 0;
  90. const selectedLines = value.document.getTextsAtRangeAsArray(value.selection);
  91. const currentLine = selectedLines.length === 1 ? selectedLines[0] : null;
  92. const nextCharacter = currentLine ? currentLine.text[value.selection.anchorOffset] : null;
  93. // Syntax spans have 3 classes by default. More indicate a recognized token
  94. const tokenRecognized = wrapperClasses.length > 3;
  95. // Non-empty prefix, but not inside known token
  96. const prefixUnrecognized = prefix && !tokenRecognized;
  97. // Prevent suggestions in `function(|suffix)`
  98. const noSuffix = !nextCharacter || nextCharacter === ')';
  99. // Empty prefix is safe if it does not immediately folllow a complete expression and has no text after it
  100. const safeEmptyPrefix = prefix === '' && !text.match(/^[\]})\s]+$/) && noSuffix;
  101. // About to type next operand if preceded by binary operator
  102. const isNextOperand = text.match(/[+\-*/^%]/);
  103. // Determine candidates by CSS context
  104. if (_.includes(wrapperClasses, 'context-range')) {
  105. // Suggestions for metric[|]
  106. return this.getRangeCompletionItems();
  107. } else if (_.includes(wrapperClasses, 'context-labels')) {
  108. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  109. return this.getLabelCompletionItems.apply(this, arguments);
  110. } else if (_.includes(wrapperClasses, 'context-aggregation')) {
  111. // Suggestions for sum(metric) by (|)
  112. return this.getAggregationCompletionItems.apply(this, arguments);
  113. } else if (empty) {
  114. // Suggestions for empty query field
  115. return this.getEmptyCompletionItems(context || {});
  116. } else if (prefixUnrecognized || safeEmptyPrefix || isNextOperand) {
  117. // Show term suggestions in a couple of scenarios
  118. return this.getTermCompletionItems();
  119. }
  120. return {
  121. suggestions: [],
  122. };
  123. }
  124. getEmptyCompletionItems(context: any): TypeaheadOutput {
  125. const { history } = context;
  126. let suggestions: CompletionItemGroup[] = [];
  127. if (history && history.length > 0) {
  128. const historyItems = _.chain(history)
  129. .map((h: any) => h.query.expr)
  130. .filter()
  131. .uniq()
  132. .take(HISTORY_ITEM_COUNT)
  133. .map(wrapLabel)
  134. .map((item: CompletionItem) => addHistoryMetadata(item, history))
  135. .value();
  136. suggestions.push({
  137. prefixMatch: true,
  138. skipSort: true,
  139. label: 'History',
  140. items: historyItems,
  141. });
  142. }
  143. const termCompletionItems = this.getTermCompletionItems();
  144. suggestions = [...suggestions, ...termCompletionItems.suggestions];
  145. return { suggestions };
  146. }
  147. getTermCompletionItems(): TypeaheadOutput {
  148. const { metrics } = this;
  149. const suggestions: CompletionItemGroup[] = [];
  150. suggestions.push({
  151. prefixMatch: true,
  152. label: 'Functions',
  153. items: FUNCTIONS.map(setFunctionKind),
  154. });
  155. if (metrics && metrics.length > 0) {
  156. suggestions.push({
  157. label: 'Metrics',
  158. items: metrics.map(wrapLabel),
  159. });
  160. }
  161. return { suggestions };
  162. }
  163. getRangeCompletionItems(): TypeaheadOutput {
  164. return {
  165. context: 'context-range',
  166. suggestions: [
  167. {
  168. label: 'Range vector',
  169. items: [...RATE_RANGES],
  170. },
  171. ],
  172. };
  173. }
  174. getAggregationCompletionItems({ value }: TypeaheadInput): TypeaheadOutput {
  175. const refresher: Promise<any> = null;
  176. const suggestions: CompletionItemGroup[] = [];
  177. // Stitch all query lines together to support multi-line queries
  178. let queryOffset;
  179. const queryText = value.document.getBlocks().reduce((text: string, block: any) => {
  180. const blockText = block.getText();
  181. if (value.anchorBlock.key === block.key) {
  182. // Newline characters are not accounted for but this is irrelevant
  183. // for the purpose of extracting the selector string
  184. queryOffset = value.anchorOffset + text.length;
  185. }
  186. text += blockText;
  187. return text;
  188. }, '');
  189. // Try search for selector part on the left-hand side, such as `sum (m) by (l)`
  190. const openParensAggregationIndex = queryText.lastIndexOf('(', queryOffset);
  191. let openParensSelectorIndex = queryText.lastIndexOf('(', openParensAggregationIndex - 1);
  192. let closeParensSelectorIndex = queryText.indexOf(')', openParensSelectorIndex);
  193. // Try search for selector part of an alternate aggregation clause, such as `sum by (l) (m)`
  194. if (openParensSelectorIndex === -1) {
  195. const closeParensAggregationIndex = queryText.indexOf(')', queryOffset);
  196. closeParensSelectorIndex = queryText.indexOf(')', closeParensAggregationIndex + 1);
  197. openParensSelectorIndex = queryText.lastIndexOf('(', closeParensSelectorIndex);
  198. }
  199. const result = {
  200. refresher,
  201. suggestions,
  202. context: 'context-aggregation',
  203. };
  204. // Suggestions are useless for alternative aggregation clauses without a selector in context
  205. if (openParensSelectorIndex === -1) {
  206. return result;
  207. }
  208. let selectorString = queryText.slice(openParensSelectorIndex + 1, closeParensSelectorIndex);
  209. // Range vector syntax not accounted for by subsequent parse so discard it if present
  210. selectorString = selectorString.replace(/\[[^\]]+\]$/, '');
  211. const selector = parseSelector(selectorString, selectorString.length - 2).selector;
  212. const labelKeys = this.labelKeys[selector];
  213. if (labelKeys) {
  214. suggestions.push({ label: 'Labels', items: labelKeys.map(wrapLabel) });
  215. } else {
  216. result.refresher = this.fetchSeriesLabels(selector);
  217. }
  218. return result;
  219. }
  220. getLabelCompletionItems({ text, wrapperClasses, labelKey, value }: TypeaheadInput): TypeaheadOutput {
  221. let context: string;
  222. let refresher: Promise<any> = null;
  223. const suggestions: CompletionItemGroup[] = [];
  224. const line = value.anchorBlock.getText();
  225. const cursorOffset: number = value.anchorOffset;
  226. // Get normalized selector
  227. let selector;
  228. let parsedSelector;
  229. try {
  230. parsedSelector = parseSelector(line, cursorOffset);
  231. selector = parsedSelector.selector;
  232. } catch {
  233. selector = EMPTY_SELECTOR;
  234. }
  235. const containsMetric = selector.indexOf('__name__=') > -1;
  236. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  237. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  238. // Label values
  239. if (labelKey && this.labelValues[selector] && this.labelValues[selector][labelKey]) {
  240. const labelValues = this.labelValues[selector][labelKey];
  241. context = 'context-label-values';
  242. suggestions.push({
  243. label: `Label values for "${labelKey}"`,
  244. items: labelValues.map(wrapLabel),
  245. });
  246. }
  247. } else {
  248. // Label keys
  249. const labelKeys = this.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  250. if (labelKeys) {
  251. const possibleKeys = _.difference(labelKeys, existingKeys);
  252. if (possibleKeys.length > 0) {
  253. context = 'context-labels';
  254. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  255. }
  256. }
  257. }
  258. // Query labels for selector
  259. if (selector && !this.labelValues[selector]) {
  260. if (selector === EMPTY_SELECTOR) {
  261. // Query label values for default labels
  262. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  263. } else {
  264. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  265. }
  266. }
  267. return { context, refresher, suggestions };
  268. }
  269. fetchLabelValues = async (key: string) => {
  270. try {
  271. const data = await this.request(`/api/v1/label/${key}/values`);
  272. const existingValues = this.labelValues[EMPTY_SELECTOR];
  273. const values = {
  274. ...existingValues,
  275. [key]: data,
  276. };
  277. this.labelValues[EMPTY_SELECTOR] = values;
  278. } catch (e) {
  279. console.error(e);
  280. }
  281. };
  282. fetchSeriesLabels = async (name: string, withName?: boolean) => {
  283. try {
  284. const data = await this.request(`/api/v1/series?match[]=${name}`);
  285. const { keys, values } = processLabels(data, withName);
  286. this.labelKeys[name] = keys;
  287. this.labelValues[name] = values;
  288. } catch (e) {
  289. console.error(e);
  290. }
  291. };
  292. }