language_provider.ts 8.1 KB

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