language_provider.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. .map(h => h.query.expr)
  86. .filter()
  87. .uniq()
  88. .take(HISTORY_ITEM_COUNT)
  89. .map(wrapLabel)
  90. .map(item => addHistoryMetadata(item, history))
  91. .value();
  92. suggestions.push({
  93. prefixMatch: true,
  94. skipSort: true,
  95. label: 'History',
  96. items: historyItems,
  97. });
  98. }
  99. return { suggestions };
  100. }
  101. getLabelCompletionItems({ text, wrapperClasses, labelKey, value }: TypeaheadInput): TypeaheadOutput {
  102. let context: string;
  103. let refresher: Promise<any> = null;
  104. const suggestions: CompletionItemGroup[] = [];
  105. const line = value.anchorBlock.getText();
  106. const cursorOffset: number = value.anchorOffset;
  107. // Use EMPTY_SELECTOR until series API is implemented for facetting
  108. const selector = EMPTY_SELECTOR;
  109. let parsedSelector;
  110. try {
  111. parsedSelector = parseSelector(line, cursorOffset);
  112. } catch {}
  113. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  114. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  115. // Label values
  116. if (labelKey && this.labelValues[selector]) {
  117. const labelValues = this.labelValues[selector][labelKey];
  118. if (labelValues) {
  119. context = 'context-label-values';
  120. suggestions.push({
  121. label: `Label values for "${labelKey}"`,
  122. items: labelValues.map(wrapLabel),
  123. });
  124. } else {
  125. refresher = this.fetchLabelValues(labelKey);
  126. }
  127. }
  128. } else {
  129. // Label keys
  130. const labelKeys = this.labelKeys[selector] || DEFAULT_KEYS;
  131. if (labelKeys) {
  132. const possibleKeys = _.difference(labelKeys, existingKeys);
  133. if (possibleKeys.length > 0) {
  134. context = 'context-labels';
  135. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  136. }
  137. }
  138. }
  139. return { context, refresher, suggestions };
  140. }
  141. async importQueries(queries: DataQuery[], datasourceType: string): Promise<DataQuery[]> {
  142. if (datasourceType === 'prometheus') {
  143. return Promise.all(
  144. queries.map(async query => {
  145. const expr = await this.importPrometheusQuery(query.expr);
  146. return {
  147. ...query,
  148. expr,
  149. };
  150. })
  151. );
  152. }
  153. return queries.map(query => ({
  154. ...query,
  155. expr: '',
  156. }));
  157. }
  158. async importPrometheusQuery(query: string): Promise<string> {
  159. if (!query) {
  160. return '';
  161. }
  162. // Consider only first selector in query
  163. const selectorMatch = query.match(selectorRegexp);
  164. if (selectorMatch) {
  165. const selector = selectorMatch[0];
  166. const labels = {};
  167. selector.replace(labelRegexp, (_, key, operator, value) => {
  168. labels[key] = { value, operator };
  169. return '';
  170. });
  171. // Keep only labels that exist on origin and target datasource
  172. await this.start(); // fetches all existing label keys
  173. const existingKeys = this.labelKeys[EMPTY_SELECTOR];
  174. let labelsToKeep = {};
  175. if (existingKeys && existingKeys.length > 0) {
  176. // Check for common labels
  177. for (const key in labels) {
  178. if (existingKeys && existingKeys.indexOf(key) > -1) {
  179. // Should we check for label value equality here?
  180. labelsToKeep[key] = labels[key];
  181. }
  182. }
  183. } else {
  184. // Keep all labels by default
  185. labelsToKeep = labels;
  186. }
  187. const labelKeys = Object.keys(labelsToKeep).sort();
  188. const cleanSelector = labelKeys
  189. .map(key => `${key}${labelsToKeep[key].operator}${labelsToKeep[key].value}`)
  190. .join(',');
  191. return ['{', cleanSelector, '}'].join('');
  192. }
  193. return '';
  194. }
  195. async fetchLogLabels() {
  196. const url = '/api/prom/label';
  197. try {
  198. const res = await this.request(url);
  199. const body = await (res.data || res.json());
  200. const labelKeys = body.data.slice().sort();
  201. this.labelKeys = {
  202. ...this.labelKeys,
  203. [EMPTY_SELECTOR]: labelKeys,
  204. };
  205. this.logLabelOptions = labelKeys.map(key => ({ label: key, value: key, isLeaf: false }));
  206. // Pre-load values for default labels
  207. return labelKeys.filter(key => DEFAULT_KEYS.indexOf(key) > -1).map(key => this.fetchLabelValues(key));
  208. } catch (e) {
  209. console.error(e);
  210. }
  211. return [];
  212. }
  213. async fetchLabelValues(key: string) {
  214. const url = `/api/prom/label/${key}/values`;
  215. try {
  216. const res = await this.request(url);
  217. const body = await (res.data || res.json());
  218. const values = body.data.slice().sort();
  219. // Add to label options
  220. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  221. if (keyOption.value === key) {
  222. return {
  223. ...keyOption,
  224. children: values.map(value => ({ label: value, value })),
  225. };
  226. }
  227. return keyOption;
  228. });
  229. // Add to key map
  230. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  231. const nextValues = {
  232. ...exisingValues,
  233. [key]: values,
  234. };
  235. this.labelValues = {
  236. ...this.labelValues,
  237. [EMPTY_SELECTOR]: nextValues,
  238. };
  239. } catch (e) {
  240. console.error(e);
  241. }
  242. }
  243. }