language_provider.ts 7.9 KB

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