language_provider.ts 8.0 KB

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