language_provider.ts 10 KB

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