language_provider.ts 12 KB

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