language_provider.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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);
  76. }
  77. return this.startTask;
  78. };
  79. /**
  80. * Return suggestions based on input that can be then plugged into a typeahead dropdown.
  81. * Keep this DOM-free for testing
  82. * @param input
  83. * @param context Is optional in types but is required in case we are doing getLabelCompletionItems
  84. * @param context.absoluteRange Required in case we are doing getLabelCompletionItems
  85. * @param context.history Optional used only in getEmptyCompletionItems
  86. */
  87. provideCompletionItems(input: TypeaheadInput, context?: TypeaheadContext): TypeaheadOutput {
  88. const { wrapperClasses, value } = input;
  89. // Local text properties
  90. const empty = value.document.text.length === 0;
  91. // Determine candidates by CSS context
  92. if (_.includes(wrapperClasses, 'context-labels')) {
  93. // Suggestions for {|} and {foo=|}
  94. return this.getLabelCompletionItems(input, context);
  95. } else if (empty) {
  96. return this.getEmptyCompletionItems(context || {});
  97. }
  98. return {
  99. suggestions: [],
  100. };
  101. }
  102. getEmptyCompletionItems(context: any): TypeaheadOutput {
  103. const { history } = context;
  104. const suggestions: CompletionItemGroup[] = [];
  105. if (history && history.length > 0) {
  106. const historyItems = _.chain(history)
  107. .map((h: any) => h.query.expr)
  108. .filter()
  109. .uniq()
  110. .take(HISTORY_ITEM_COUNT)
  111. .map(wrapLabel)
  112. .map((item: CompletionItem) => addHistoryMetadata(item, history))
  113. .value();
  114. suggestions.push({
  115. prefixMatch: true,
  116. skipSort: true,
  117. label: 'History',
  118. items: historyItems,
  119. });
  120. }
  121. return { suggestions };
  122. }
  123. getLabelCompletionItems(
  124. { text, wrapperClasses, labelKey, value }: TypeaheadInput,
  125. { absoluteRange }: any
  126. ): TypeaheadOutput {
  127. let context: string;
  128. let refresher: Promise<any> = null;
  129. const suggestions: CompletionItemGroup[] = [];
  130. const line = value.anchorBlock.getText();
  131. const cursorOffset: number = value.anchorOffset;
  132. // Use EMPTY_SELECTOR until series API is implemented for facetting
  133. const selector = EMPTY_SELECTOR;
  134. let parsedSelector;
  135. try {
  136. parsedSelector = parseSelector(line, cursorOffset);
  137. } catch {}
  138. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  139. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  140. // Label values
  141. if (labelKey && this.labelValues[selector]) {
  142. const labelValues = this.labelValues[selector][labelKey];
  143. if (labelValues) {
  144. context = 'context-label-values';
  145. suggestions.push({
  146. label: `Label values for "${labelKey}"`,
  147. items: labelValues.map(wrapLabel),
  148. });
  149. } else {
  150. refresher = this.fetchLabelValues(labelKey, absoluteRange);
  151. }
  152. }
  153. } else {
  154. // Label keys
  155. const labelKeys = this.labelKeys[selector] || DEFAULT_KEYS;
  156. if (labelKeys) {
  157. const possibleKeys = _.difference(labelKeys, existingKeys);
  158. if (possibleKeys.length > 0) {
  159. context = 'context-labels';
  160. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  161. }
  162. }
  163. }
  164. return { context, refresher, suggestions };
  165. }
  166. async importQueries(queries: LokiQuery[], datasourceType: string): Promise<LokiQuery[]> {
  167. if (datasourceType === 'prometheus') {
  168. return Promise.all(
  169. queries.map(async query => {
  170. const expr = await this.importPrometheusQuery(query.expr);
  171. const { context, ...rest } = query as PromQuery;
  172. return {
  173. ...rest,
  174. expr,
  175. };
  176. })
  177. );
  178. }
  179. // Return a cleaned LokiQuery
  180. return queries.map(query => ({
  181. refId: query.refId,
  182. expr: '',
  183. }));
  184. }
  185. async importPrometheusQuery(query: string): Promise<string> {
  186. if (!query) {
  187. return '';
  188. }
  189. // Consider only first selector in query
  190. const selectorMatch = query.match(selectorRegexp);
  191. if (selectorMatch) {
  192. const selector = selectorMatch[0];
  193. const labels: { [key: string]: { value: any; operator: any } } = {};
  194. selector.replace(labelRegexp, (_, key, operator, value) => {
  195. labels[key] = { value, operator };
  196. return '';
  197. });
  198. // Keep only labels that exist on origin and target datasource
  199. await this.start(); // fetches all existing label keys
  200. const existingKeys = this.labelKeys[EMPTY_SELECTOR];
  201. let labelsToKeep: { [key: string]: { value: any; operator: any } } = {};
  202. if (existingKeys && existingKeys.length > 0) {
  203. // Check for common labels
  204. for (const key in labels) {
  205. if (existingKeys && existingKeys.includes(key)) {
  206. // Should we check for label value equality here?
  207. labelsToKeep[key] = labels[key];
  208. }
  209. }
  210. } else {
  211. // Keep all labels by default
  212. labelsToKeep = labels;
  213. }
  214. const labelKeys = Object.keys(labelsToKeep).sort();
  215. const cleanSelector = labelKeys
  216. .map(key => `${key}${labelsToKeep[key].operator}${labelsToKeep[key].value}`)
  217. .join(',');
  218. return ['{', cleanSelector, '}'].join('');
  219. }
  220. return '';
  221. }
  222. async fetchLogLabels(absoluteRange: AbsoluteTimeRange): Promise<any> {
  223. const url = '/api/prom/label';
  224. try {
  225. this.logLabelFetchTs = Date.now();
  226. const res = await this.request(url, rangeToParams(absoluteRange));
  227. const body = await (res.data || res.json());
  228. const labelKeys = body.data.slice().sort();
  229. this.labelKeys = {
  230. ...this.labelKeys,
  231. [EMPTY_SELECTOR]: labelKeys,
  232. };
  233. this.labelValues = {
  234. [EMPTY_SELECTOR]: {},
  235. };
  236. this.logLabelOptions = labelKeys.map((key: string) => ({ label: key, value: key, isLeaf: false }));
  237. } catch (e) {
  238. console.error(e);
  239. }
  240. return [];
  241. }
  242. async refreshLogLabels(absoluteRange: AbsoluteTimeRange, forceRefresh?: boolean) {
  243. if ((this.labelKeys && Date.now() - this.logLabelFetchTs > LABEL_REFRESH_INTERVAL) || forceRefresh) {
  244. await this.fetchLogLabels(absoluteRange);
  245. }
  246. }
  247. async fetchLabelValues(key: string, absoluteRange: AbsoluteTimeRange) {
  248. const url = `/api/prom/label/${key}/values`;
  249. try {
  250. const res = await this.request(url, rangeToParams(absoluteRange));
  251. const body = await (res.data || res.json());
  252. const values = body.data.slice().sort();
  253. // Add to label options
  254. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  255. if (keyOption.value === key) {
  256. return {
  257. ...keyOption,
  258. children: values.map((value: string) => ({ label: value, value })),
  259. };
  260. }
  261. return keyOption;
  262. });
  263. // Add to key map
  264. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  265. const nextValues = {
  266. ...exisingValues,
  267. [key]: values,
  268. };
  269. this.labelValues = {
  270. ...this.labelValues,
  271. [EMPTY_SELECTOR]: nextValues,
  272. };
  273. } catch (e) {
  274. console.error(e);
  275. }
  276. }
  277. }