language_provider.ts 11 KB

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