language_provider.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Libraries
  2. import _ from 'lodash';
  3. // Services & Utils
  4. import { parseSelector, labelRegexp, selectorRegexp } from 'app/plugins/datasource/prometheus/language_utils';
  5. import syntax from './syntax';
  6. // Types
  7. import {
  8. CompletionItem,
  9. CompletionItemGroup,
  10. LanguageProvider,
  11. TypeaheadInput,
  12. TypeaheadOutput,
  13. HistoryItem,
  14. } from 'app/types/explore';
  15. import { LokiQuery } from './types';
  16. import { dateTime, AbsoluteTimeRange } from '@grafana/data';
  17. import { PromQuery } from '../prometheus/types';
  18. const DEFAULT_KEYS = ['job', 'namespace'];
  19. const EMPTY_SELECTOR = '{}';
  20. const HISTORY_ITEM_COUNT = 10;
  21. const HISTORY_COUNT_CUTOFF = 1000 * 60 * 60 * 24; // 24h
  22. const NS_IN_MS = 1000000;
  23. export const LABEL_REFRESH_INTERVAL = 1000 * 30; // 30sec
  24. const wrapLabel = (label: string) => ({ label });
  25. export const rangeToParams = (range: AbsoluteTimeRange) => ({ start: range.from * NS_IN_MS, end: range.to * NS_IN_MS });
  26. type LokiHistoryItem = HistoryItem<LokiQuery>;
  27. export function addHistoryMetadata(item: CompletionItem, history: LokiHistoryItem[]): CompletionItem {
  28. const cutoffTs = Date.now() - HISTORY_COUNT_CUTOFF;
  29. const historyForItem = history.filter(h => h.ts > cutoffTs && (h.query.expr as string) === item.label);
  30. const count = historyForItem.length;
  31. const recent = historyForItem[0];
  32. let hint = `Queried ${count} times in the last 24h.`;
  33. if (recent) {
  34. const lastQueried = dateTime(recent.ts).fromNow();
  35. hint = `${hint} Last queried ${lastQueried}.`;
  36. }
  37. return {
  38. ...item,
  39. documentation: hint,
  40. };
  41. }
  42. export default class LokiLanguageProvider extends LanguageProvider {
  43. labelKeys?: { [index: string]: string[] }; // metric -> [labelKey,...]
  44. labelValues?: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  45. logLabelOptions: any[];
  46. logLabelFetchTs?: number;
  47. started: boolean;
  48. initialRange: AbsoluteTimeRange;
  49. constructor(datasource: any, initialValues?: any) {
  50. super();
  51. this.datasource = datasource;
  52. this.labelKeys = {};
  53. this.labelValues = {};
  54. Object.assign(this, initialValues);
  55. }
  56. // Strip syntax chars
  57. cleanText = (s: string) => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim();
  58. getSyntax() {
  59. return syntax;
  60. }
  61. request = (url: string, params?: any) => {
  62. return this.datasource.metadataRequest(url, params);
  63. };
  64. start = () => {
  65. if (!this.startTask) {
  66. this.startTask = this.fetchLogLabels(this.initialRange);
  67. }
  68. return this.startTask;
  69. };
  70. // Keep this DOM-free for testing
  71. provideCompletionItems({ prefix, wrapperClasses, text, value }: TypeaheadInput, context?: any): TypeaheadOutput {
  72. // Local text properties
  73. const empty = value.document.text.length === 0;
  74. // Determine candidates by CSS context
  75. if (_.includes(wrapperClasses, 'context-labels')) {
  76. // Suggestions for {|} and {foo=|}
  77. return this.getLabelCompletionItems.apply(this, arguments);
  78. } else if (empty) {
  79. return this.getEmptyCompletionItems(context || {});
  80. }
  81. return {
  82. suggestions: [],
  83. };
  84. }
  85. getEmptyCompletionItems(context: any): TypeaheadOutput {
  86. const { history } = context;
  87. const suggestions: CompletionItemGroup[] = [];
  88. if (history && history.length > 0) {
  89. const historyItems = _.chain(history)
  90. .map((h: any) => h.query.expr)
  91. .filter()
  92. .uniq()
  93. .take(HISTORY_ITEM_COUNT)
  94. .map(wrapLabel)
  95. .map((item: CompletionItem) => addHistoryMetadata(item, history))
  96. .value();
  97. suggestions.push({
  98. prefixMatch: true,
  99. skipSort: true,
  100. label: 'History',
  101. items: historyItems,
  102. });
  103. }
  104. return { suggestions };
  105. }
  106. getLabelCompletionItems(
  107. { text, wrapperClasses, labelKey, value }: TypeaheadInput,
  108. { absoluteRange }: any
  109. ): TypeaheadOutput {
  110. let context: string;
  111. let refresher: Promise<any> = null;
  112. const suggestions: CompletionItemGroup[] = [];
  113. const line = value.anchorBlock.getText();
  114. const cursorOffset: number = value.anchorOffset;
  115. // Use EMPTY_SELECTOR until series API is implemented for facetting
  116. const selector = EMPTY_SELECTOR;
  117. let parsedSelector;
  118. try {
  119. parsedSelector = parseSelector(line, cursorOffset);
  120. } catch {}
  121. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  122. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  123. // Label values
  124. if (labelKey && this.labelValues[selector]) {
  125. const labelValues = this.labelValues[selector][labelKey];
  126. if (labelValues) {
  127. context = 'context-label-values';
  128. suggestions.push({
  129. label: `Label values for "${labelKey}"`,
  130. items: labelValues.map(wrapLabel),
  131. });
  132. } else {
  133. refresher = this.fetchLabelValues(labelKey, absoluteRange);
  134. }
  135. }
  136. } else {
  137. // Label keys
  138. const labelKeys = this.labelKeys[selector] || DEFAULT_KEYS;
  139. if (labelKeys) {
  140. const possibleKeys = _.difference(labelKeys, existingKeys);
  141. if (possibleKeys.length > 0) {
  142. context = 'context-labels';
  143. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  144. }
  145. }
  146. }
  147. return { context, refresher, suggestions };
  148. }
  149. async importQueries(queries: LokiQuery[], datasourceType: string): Promise<LokiQuery[]> {
  150. if (datasourceType === 'prometheus') {
  151. return Promise.all(
  152. queries.map(async query => {
  153. const expr = await this.importPrometheusQuery(query.expr);
  154. const { context, ...rest } = query as PromQuery;
  155. return {
  156. ...rest,
  157. expr,
  158. };
  159. })
  160. );
  161. }
  162. // Return a cleaned LokiQuery
  163. return queries.map(query => ({
  164. refId: query.refId,
  165. expr: '',
  166. }));
  167. }
  168. async importPrometheusQuery(query: string): Promise<string> {
  169. if (!query) {
  170. return '';
  171. }
  172. // Consider only first selector in query
  173. const selectorMatch = query.match(selectorRegexp);
  174. if (selectorMatch) {
  175. const selector = selectorMatch[0];
  176. const labels: { [key: string]: { value: any; operator: any } } = {};
  177. selector.replace(labelRegexp, (_, key, operator, value) => {
  178. labels[key] = { value, operator };
  179. return '';
  180. });
  181. // Keep only labels that exist on origin and target datasource
  182. await this.start(); // fetches all existing label keys
  183. const existingKeys = this.labelKeys[EMPTY_SELECTOR];
  184. let labelsToKeep: { [key: string]: { value: any; operator: any } } = {};
  185. if (existingKeys && existingKeys.length > 0) {
  186. // Check for common labels
  187. for (const key in labels) {
  188. if (existingKeys && existingKeys.includes(key)) {
  189. // Should we check for label value equality here?
  190. labelsToKeep[key] = labels[key];
  191. }
  192. }
  193. } else {
  194. // Keep all labels by default
  195. labelsToKeep = labels;
  196. }
  197. const labelKeys = Object.keys(labelsToKeep).sort();
  198. const cleanSelector = labelKeys
  199. .map(key => `${key}${labelsToKeep[key].operator}${labelsToKeep[key].value}`)
  200. .join(',');
  201. return ['{', cleanSelector, '}'].join('');
  202. }
  203. return '';
  204. }
  205. async fetchLogLabels(absoluteRange: AbsoluteTimeRange): Promise<any> {
  206. const url = '/api/prom/label';
  207. try {
  208. this.logLabelFetchTs = Date.now();
  209. const res = await this.request(url, rangeToParams(absoluteRange));
  210. const body = await (res.data || res.json());
  211. const labelKeys = body.data.slice().sort();
  212. this.labelKeys = {
  213. ...this.labelKeys,
  214. [EMPTY_SELECTOR]: labelKeys,
  215. };
  216. this.logLabelOptions = labelKeys.map((key: string) => ({ label: key, value: key, isLeaf: false }));
  217. // Pre-load values for default labels
  218. return Promise.all(
  219. labelKeys
  220. .filter((key: string) => DEFAULT_KEYS.indexOf(key) > -1)
  221. .map((key: string) => this.fetchLabelValues(key, absoluteRange))
  222. );
  223. } catch (e) {
  224. console.error(e);
  225. }
  226. return [];
  227. }
  228. async refreshLogLabels(absoluteRange: AbsoluteTimeRange, forceRefresh?: boolean) {
  229. if ((this.labelKeys && Date.now() - this.logLabelFetchTs > LABEL_REFRESH_INTERVAL) || forceRefresh) {
  230. await this.fetchLogLabels(absoluteRange);
  231. }
  232. }
  233. async fetchLabelValues(key: string, absoluteRange: AbsoluteTimeRange) {
  234. const url = `/api/prom/label/${key}/values`;
  235. try {
  236. const res = await this.request(url, rangeToParams(absoluteRange));
  237. const body = await (res.data || res.json());
  238. const values = body.data.slice().sort();
  239. // Add to label options
  240. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  241. if (keyOption.value === key) {
  242. return {
  243. ...keyOption,
  244. children: values.map((value: string) => ({ label: value, value })),
  245. };
  246. }
  247. return keyOption;
  248. });
  249. // Add to key map
  250. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  251. const nextValues = {
  252. ...exisingValues,
  253. [key]: values,
  254. };
  255. this.labelValues = {
  256. ...this.labelValues,
  257. [EMPTY_SELECTOR]: nextValues,
  258. };
  259. } catch (e) {
  260. console.error(e);
  261. }
  262. }
  263. }