language_provider.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Libraries
  2. // @ts-ignore
  3. import _ from 'lodash';
  4. import moment from 'moment';
  5. // Services & Utils
  6. import { parseSelector, labelRegexp, selectorRegexp } from 'app/plugins/datasource/prometheus/language_utils';
  7. import syntax from './syntax';
  8. // Types
  9. import {
  10. CompletionItem,
  11. CompletionItemGroup,
  12. LanguageProvider,
  13. TypeaheadInput,
  14. TypeaheadOutput,
  15. HistoryItem,
  16. } from 'app/types/explore';
  17. import { LokiQuery } from './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 = moment(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. return {
  149. ...query,
  150. expr,
  151. };
  152. })
  153. );
  154. }
  155. // Return a cleaned LokiQuery
  156. return queries.map(query => ({
  157. refId: query.refId,
  158. expr: '',
  159. }));
  160. }
  161. async importPrometheusQuery(query: string): Promise<string> {
  162. if (!query) {
  163. return '';
  164. }
  165. // Consider only first selector in query
  166. const selectorMatch = query.match(selectorRegexp);
  167. if (selectorMatch) {
  168. const selector = selectorMatch[0];
  169. const labels: { [key: string]: { value: any; operator: any } } = {};
  170. selector.replace(labelRegexp, (_, key, operator, value) => {
  171. labels[key] = { value, operator };
  172. return '';
  173. });
  174. // Keep only labels that exist on origin and target datasource
  175. await this.start(); // fetches all existing label keys
  176. const existingKeys = this.labelKeys[EMPTY_SELECTOR];
  177. let labelsToKeep: { [key: string]: { value: any; operator: any } } = {};
  178. if (existingKeys && existingKeys.length > 0) {
  179. // Check for common labels
  180. for (const key in labels) {
  181. if (existingKeys && existingKeys.indexOf(key) > -1) {
  182. // Should we check for label value equality here?
  183. labelsToKeep[key] = labels[key];
  184. }
  185. }
  186. } else {
  187. // Keep all labels by default
  188. labelsToKeep = labels;
  189. }
  190. const labelKeys = Object.keys(labelsToKeep).sort();
  191. const cleanSelector = labelKeys
  192. .map(key => `${key}${labelsToKeep[key].operator}${labelsToKeep[key].value}`)
  193. .join(',');
  194. return ['{', cleanSelector, '}'].join('');
  195. }
  196. return '';
  197. }
  198. async fetchLogLabels(): Promise<any> {
  199. const url = '/api/prom/label';
  200. try {
  201. this.logLabelFetchTs = Date.now();
  202. const res = await this.request(url);
  203. const body = await (res.data || res.json());
  204. const labelKeys = body.data.slice().sort();
  205. this.labelKeys = {
  206. ...this.labelKeys,
  207. [EMPTY_SELECTOR]: labelKeys,
  208. };
  209. this.logLabelOptions = labelKeys.map((key: string) => ({ label: key, value: key, isLeaf: false }));
  210. // Pre-load values for default labels
  211. return Promise.all(
  212. labelKeys
  213. .filter((key: string) => DEFAULT_KEYS.indexOf(key) > -1)
  214. .map((key: string) => this.fetchLabelValues(key))
  215. );
  216. } catch (e) {
  217. console.error(e);
  218. }
  219. return [];
  220. }
  221. async refreshLogLabels(forceRefresh?: boolean) {
  222. if ((this.labelKeys && Date.now() - this.logLabelFetchTs > LABEL_REFRESH_INTERVAL) || forceRefresh) {
  223. await this.fetchLogLabels();
  224. }
  225. }
  226. async fetchLabelValues(key: string) {
  227. const url = `/api/prom/label/${key}/values`;
  228. try {
  229. const res = await this.request(url);
  230. const body = await (res.data || res.json());
  231. const values = body.data.slice().sort();
  232. // Add to label options
  233. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  234. if (keyOption.value === key) {
  235. return {
  236. ...keyOption,
  237. children: values.map((value: string) => ({ label: value, value })),
  238. };
  239. }
  240. return keyOption;
  241. });
  242. // Add to key map
  243. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  244. const nextValues = {
  245. ...exisingValues,
  246. [key]: values,
  247. };
  248. this.labelValues = {
  249. ...this.labelValues,
  250. [EMPTY_SELECTOR]: nextValues,
  251. };
  252. } catch (e) {
  253. console.error(e);
  254. }
  255. }
  256. }