language_provider.ts 9.7 KB

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