language_provider.ts 11 KB

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