language_provider.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. logLabelOptions: any[];
  43. supportsLogs?: boolean;
  44. started: boolean;
  45. constructor(datasource: any, initialValues?: any) {
  46. super();
  47. this.datasource = datasource;
  48. this.histogramMetrics = [];
  49. this.labelKeys = {};
  50. this.labelValues = {};
  51. this.metrics = [];
  52. this.supportsLogs = false;
  53. this.started = false;
  54. Object.assign(this, initialValues);
  55. }
  56. // Strip syntax chars
  57. cleanText = s => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim();
  58. getSyntax() {
  59. return PromqlSyntax;
  60. }
  61. request = url => {
  62. return this.datasource.metadataRequest(url);
  63. };
  64. start = () => {
  65. if (!this.started) {
  66. this.started = true;
  67. return Promise.all([this.fetchMetricNames(), this.fetchHistogramMetrics()]);
  68. }
  69. return Promise.resolve([]);
  70. };
  71. // Keep this DOM-free for testing
  72. provideCompletionItems({ prefix, wrapperClasses, text }: TypeaheadInput, context?: any): TypeaheadOutput {
  73. // Syntax spans have 3 classes by default. More indicate a recognized token
  74. const tokenRecognized = wrapperClasses.length > 3;
  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 (
  85. // Show default suggestions in a couple of scenarios
  86. (prefix && !tokenRecognized) || // Non-empty prefix, but not inside known token
  87. (prefix === '' && !text.match(/^[\]})\s]+$/)) || // Empty prefix, but not following a closing brace
  88. text.match(/[+\-*/^%]/) // Anything after binary operator
  89. ) {
  90. return this.getEmptyCompletionItems(context || {});
  91. }
  92. return {
  93. suggestions: [],
  94. };
  95. }
  96. getEmptyCompletionItems(context: any): TypeaheadOutput {
  97. const { history } = context;
  98. const { metrics } = this;
  99. const suggestions: CompletionItemGroup[] = [];
  100. if (history && history.length > 0) {
  101. const historyItems = _.chain(history)
  102. .uniqBy('query')
  103. .take(HISTORY_ITEM_COUNT)
  104. .map(h => h.query)
  105. .map(wrapLabel)
  106. .map(item => addHistoryMetadata(item, history))
  107. .value();
  108. suggestions.push({
  109. prefixMatch: true,
  110. skipSort: true,
  111. label: 'History',
  112. items: historyItems,
  113. });
  114. }
  115. suggestions.push({
  116. prefixMatch: true,
  117. label: 'Functions',
  118. items: FUNCTIONS.map(setFunctionMove),
  119. });
  120. if (metrics) {
  121. suggestions.push({
  122. label: 'Metrics',
  123. items: metrics.map(wrapLabel),
  124. });
  125. }
  126. return { suggestions };
  127. }
  128. getRangeCompletionItems(): TypeaheadOutput {
  129. return {
  130. context: 'context-range',
  131. suggestions: [
  132. {
  133. label: 'Range vector',
  134. items: [...RATE_RANGES].map(wrapLabel),
  135. },
  136. ],
  137. };
  138. }
  139. getAggregationCompletionItems({ value }: TypeaheadInput): TypeaheadOutput {
  140. let refresher: Promise<any> = null;
  141. const suggestions: CompletionItemGroup[] = [];
  142. // sum(foo{bar="1"}) by (|)
  143. const line = value.anchorBlock.getText();
  144. const cursorOffset: number = value.anchorOffset;
  145. // sum(foo{bar="1"}) by (
  146. const leftSide = line.slice(0, cursorOffset);
  147. const openParensAggregationIndex = leftSide.lastIndexOf('(');
  148. const openParensSelectorIndex = leftSide.slice(0, openParensAggregationIndex).lastIndexOf('(');
  149. const closeParensSelectorIndex = leftSide.slice(openParensSelectorIndex).indexOf(')') + openParensSelectorIndex;
  150. // foo{bar="1"}
  151. const selectorString = leftSide.slice(openParensSelectorIndex + 1, closeParensSelectorIndex);
  152. const selector = parseSelector(selectorString, selectorString.length - 2).selector;
  153. const labelKeys = this.labelKeys[selector];
  154. if (labelKeys) {
  155. suggestions.push({ label: 'Labels', items: labelKeys.map(wrapLabel) });
  156. } else {
  157. refresher = this.fetchSeriesLabels(selector);
  158. }
  159. return {
  160. refresher,
  161. suggestions,
  162. context: 'context-aggregation',
  163. };
  164. }
  165. getLabelCompletionItems({ text, wrapperClasses, labelKey, value }: TypeaheadInput): TypeaheadOutput {
  166. let context: string;
  167. let refresher: Promise<any> = null;
  168. const suggestions: CompletionItemGroup[] = [];
  169. const line = value.anchorBlock.getText();
  170. const cursorOffset: number = value.anchorOffset;
  171. // Get normalized selector
  172. let selector;
  173. let parsedSelector;
  174. try {
  175. parsedSelector = parseSelector(line, cursorOffset);
  176. selector = parsedSelector.selector;
  177. } catch {
  178. selector = EMPTY_SELECTOR;
  179. }
  180. const containsMetric = selector.indexOf('__name__=') > -1;
  181. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  182. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  183. // Label values
  184. if (labelKey && this.labelValues[selector] && this.labelValues[selector][labelKey]) {
  185. const labelValues = this.labelValues[selector][labelKey];
  186. context = 'context-label-values';
  187. suggestions.push({
  188. label: `Label values for "${labelKey}"`,
  189. items: labelValues.map(wrapLabel),
  190. });
  191. }
  192. } else {
  193. // Label keys
  194. const labelKeys = this.labelKeys[selector] || (containsMetric ? null : DEFAULT_KEYS);
  195. if (labelKeys) {
  196. const possibleKeys = _.difference(labelKeys, existingKeys);
  197. if (possibleKeys.length > 0) {
  198. context = 'context-labels';
  199. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  200. }
  201. }
  202. }
  203. // Query labels for selector
  204. // Temporarily add skip for logging
  205. if (selector && !this.labelValues[selector] && !this.supportsLogs) {
  206. if (selector === EMPTY_SELECTOR) {
  207. // Query label values for default labels
  208. refresher = Promise.all(DEFAULT_KEYS.map(key => this.fetchLabelValues(key)));
  209. } else {
  210. refresher = this.fetchSeriesLabels(selector, !containsMetric);
  211. }
  212. }
  213. return { context, refresher, suggestions };
  214. }
  215. async fetchMetricNames() {
  216. const url = '/api/v1/label/__name__/values';
  217. try {
  218. const res = await this.request(url);
  219. const body = await (res.data || res.json());
  220. this.metrics = body.data;
  221. } catch (error) {
  222. console.error(error);
  223. }
  224. }
  225. async fetchHistogramMetrics() {
  226. await this.fetchSeriesLabels(HISTOGRAM_SELECTOR, true);
  227. const histogramSeries = this.labelValues[HISTOGRAM_SELECTOR];
  228. if (histogramSeries && histogramSeries['__name__']) {
  229. this.histogramMetrics = histogramSeries['__name__'].slice().sort();
  230. }
  231. }
  232. // Temporarily here while reusing this field for logging
  233. async fetchLogLabels() {
  234. const url = '/api/prom/label';
  235. try {
  236. const res = await this.request(url);
  237. const body = await (res.data || res.json());
  238. const labelKeys = body.data.slice().sort();
  239. const labelKeysBySelector = {
  240. ...this.labelKeys,
  241. [EMPTY_SELECTOR]: labelKeys,
  242. };
  243. const labelValuesByKey = {};
  244. this.logLabelOptions = [];
  245. for (const key of labelKeys) {
  246. const valuesUrl = `/api/prom/label/${key}/values`;
  247. const res = await this.request(valuesUrl);
  248. const body = await (res.data || res.json());
  249. const values = body.data.slice().sort();
  250. labelValuesByKey[key] = values;
  251. this.logLabelOptions.push({
  252. label: key,
  253. value: key,
  254. children: values.map(value => ({ label: value, value })),
  255. });
  256. }
  257. this.labelValues = { [EMPTY_SELECTOR]: labelValuesByKey };
  258. this.labelKeys = labelKeysBySelector;
  259. } catch (e) {
  260. console.error(e);
  261. }
  262. }
  263. async fetchLabelValues(key: string) {
  264. const url = `/api/v1/label/${key}/values`;
  265. try {
  266. const res = await this.request(url);
  267. const body = await (res.data || res.json());
  268. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  269. const values = {
  270. ...exisingValues,
  271. [key]: body.data,
  272. };
  273. this.labelValues = {
  274. ...this.labelValues,
  275. [EMPTY_SELECTOR]: values,
  276. };
  277. } catch (e) {
  278. console.error(e);
  279. }
  280. }
  281. async fetchSeriesLabels(name: string, withName?: boolean) {
  282. const url = `/api/v1/series?match[]=${name}`;
  283. try {
  284. const res = await this.request(url);
  285. const body = await (res.data || res.json());
  286. const { keys, values } = processLabels(body.data, withName);
  287. this.labelKeys = {
  288. ...this.labelKeys,
  289. [name]: keys,
  290. };
  291. this.labelValues = {
  292. ...this.labelValues,
  293. [name]: values,
  294. };
  295. } catch (e) {
  296. console.error(e);
  297. }
  298. }
  299. }