language_provider.ts 9.6 KB

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