language_provider.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 PromqlSyntax from 'app/plugins/datasource/prometheus/promql';
  13. import { DataQuery } from 'app/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 LoggingLanguageProvider 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 PromqlSyntax;
  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 }: TypeaheadInput, context?: any): TypeaheadOutput {
  62. // Syntax spans have 3 classes by default. More indicate a recognized token
  63. const tokenRecognized = wrapperClasses.length > 3;
  64. // Determine candidates by CSS context
  65. if (_.includes(wrapperClasses, 'context-labels')) {
  66. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  67. return this.getLabelCompletionItems.apply(this, arguments);
  68. } else if (
  69. // Show default suggestions in a couple of scenarios
  70. (prefix && !tokenRecognized) || // Non-empty prefix, but not inside known token
  71. (prefix === '' && !text.match(/^[\]})\s]+$/)) || // Empty prefix, but not following a closing brace
  72. text.match(/[+\-*/^%]/) // Anything after binary operator
  73. ) {
  74. return this.getEmptyCompletionItems(context || {});
  75. }
  76. return {
  77. suggestions: [],
  78. };
  79. }
  80. getEmptyCompletionItems(context: any): TypeaheadOutput {
  81. const { history } = context;
  82. const suggestions: CompletionItemGroup[] = [];
  83. if (history && history.length > 0) {
  84. const historyItems = _.chain(history)
  85. .uniqBy('query.expr')
  86. .take(HISTORY_ITEM_COUNT)
  87. .map(h => h.query.expr)
  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: DataQuery[], datasourceType: string): Promise<DataQuery[]> {
  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 queries.map(query => ({
  153. ...query,
  154. expr: '',
  155. }));
  156. }
  157. async importPrometheusQuery(query: string): Promise<string> {
  158. if (!query) {
  159. return '';
  160. }
  161. // Consider only first selector in query
  162. const selectorMatch = query.match(selectorRegexp);
  163. if (selectorMatch) {
  164. const selector = selectorMatch[0];
  165. const labels = {};
  166. selector.replace(labelRegexp, (_, key, operator, value) => {
  167. labels[key] = { value, operator };
  168. return '';
  169. });
  170. // Keep only labels that exist on origin and target datasource
  171. await this.start(); // fetches all existing label keys
  172. const commonLabels = {};
  173. for (const key in labels) {
  174. const existingKeys = this.labelKeys[EMPTY_SELECTOR];
  175. if (existingKeys && existingKeys.indexOf(key) > -1) {
  176. // Should we check for label value equality here?
  177. commonLabels[key] = labels[key];
  178. }
  179. }
  180. const labelKeys = Object.keys(commonLabels).sort();
  181. const cleanSelector = labelKeys
  182. .map(key => `${key}${commonLabels[key].operator}${commonLabels[key].value}`)
  183. .join(',');
  184. return ['{', cleanSelector, '}'].join('');
  185. }
  186. return '';
  187. }
  188. async fetchLogLabels() {
  189. const url = '/api/prom/label';
  190. try {
  191. const res = await this.request(url);
  192. const body = await (res.data || res.json());
  193. const labelKeys = body.data.slice().sort();
  194. this.labelKeys = {
  195. ...this.labelKeys,
  196. [EMPTY_SELECTOR]: labelKeys,
  197. };
  198. this.logLabelOptions = labelKeys.map(key => ({ label: key, value: key, isLeaf: false }));
  199. // Pre-load values for default labels
  200. return labelKeys.filter(key => DEFAULT_KEYS.indexOf(key) > -1).map(key => this.fetchLabelValues(key));
  201. } catch (e) {
  202. console.error(e);
  203. }
  204. return [];
  205. }
  206. async fetchLabelValues(key: string) {
  207. const url = `/api/prom/label/${key}/values`;
  208. try {
  209. const res = await this.request(url);
  210. const body = await (res.data || res.json());
  211. const values = body.data.slice().sort();
  212. // Add to label options
  213. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  214. if (keyOption.value === key) {
  215. return {
  216. ...keyOption,
  217. children: values.map(value => ({ label: value, value })),
  218. };
  219. }
  220. return keyOption;
  221. });
  222. // Add to key map
  223. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  224. const nextValues = {
  225. ...exisingValues,
  226. [key]: values,
  227. };
  228. this.labelValues = {
  229. ...this.labelValues,
  230. [EMPTY_SELECTOR]: nextValues,
  231. };
  232. } catch (e) {
  233. console.error(e);
  234. }
  235. }
  236. }