language_provider.ts 8.3 KB

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