language_provider.ts 11 KB

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