language_provider.ts 8.7 KB

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