language_provider.ts 11 KB

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