language_provider.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 } from 'app/plugins/datasource/prometheus/language_utils';
  11. import PromqlSyntax from 'app/plugins/datasource/prometheus/promql';
  12. const DEFAULT_KEYS = ['job', 'instance'];
  13. const EMPTY_SELECTOR = '{}';
  14. const HISTORY_ITEM_COUNT = 5;
  15. const HISTORY_COUNT_CUTOFF = 1000 * 60 * 60 * 24; // 24h
  16. const wrapLabel = (label: string) => ({ label });
  17. export function addHistoryMetadata(item: CompletionItem, history: any[]): CompletionItem {
  18. const cutoffTs = Date.now() - HISTORY_COUNT_CUTOFF;
  19. const historyForItem = history.filter(h => h.ts > cutoffTs && h.query === item.label);
  20. const count = historyForItem.length;
  21. const recent = historyForItem[0];
  22. let hint = `Queried ${count} times in the last 24h.`;
  23. if (recent) {
  24. const lastQueried = moment(recent.ts).fromNow();
  25. hint = `${hint} Last queried ${lastQueried}.`;
  26. }
  27. return {
  28. ...item,
  29. documentation: hint,
  30. };
  31. }
  32. export default class LoggingLanguageProvider extends LanguageProvider {
  33. labelKeys?: { [index: string]: string[] }; // metric -> [labelKey,...]
  34. labelValues?: { [index: string]: { [index: string]: string[] } }; // metric -> labelKey -> [labelValue,...]
  35. logLabelOptions: any[];
  36. started: boolean;
  37. constructor(datasource: any, initialValues?: any) {
  38. super();
  39. this.datasource = datasource;
  40. this.labelKeys = {};
  41. this.labelValues = {};
  42. this.started = false;
  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.started) {
  55. this.started = true;
  56. return Promise.all([this.fetchLogLabels()]);
  57. }
  58. return Promise.resolve([]);
  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')
  86. .take(HISTORY_ITEM_COUNT)
  87. .map(h => h.query)
  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. const suggestions: CompletionItemGroup[] = [];
  103. const line = value.anchorBlock.getText();
  104. const cursorOffset: number = value.anchorOffset;
  105. // Get normalized selector
  106. let selector;
  107. let parsedSelector;
  108. try {
  109. parsedSelector = parseSelector(line, cursorOffset);
  110. selector = parsedSelector.selector;
  111. } catch {
  112. selector = EMPTY_SELECTOR;
  113. }
  114. const containsMetric = selector.indexOf('__name__=') > -1;
  115. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  116. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  117. // Label values
  118. if (labelKey && this.labelValues[selector] && this.labelValues[selector][labelKey]) {
  119. const labelValues = this.labelValues[selector][labelKey];
  120. context = 'context-label-values';
  121. suggestions.push({
  122. label: `Label values for "${labelKey}"`,
  123. items: labelValues.map(wrapLabel),
  124. });
  125. }
  126. } else {
  127. // Label keys
  128. const labelKeys = this.labelKeys[selector] || (containsMetric ? null : 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, suggestions };
  138. }
  139. async fetchLogLabels() {
  140. const url = '/api/prom/label';
  141. try {
  142. const res = await this.request(url);
  143. const body = await (res.data || res.json());
  144. const labelKeys = body.data.slice().sort();
  145. const labelKeysBySelector = {
  146. ...this.labelKeys,
  147. [EMPTY_SELECTOR]: labelKeys,
  148. };
  149. const labelValuesByKey = {};
  150. this.logLabelOptions = [];
  151. for (const key of labelKeys) {
  152. const valuesUrl = `/api/prom/label/${key}/values`;
  153. const res = await this.request(valuesUrl);
  154. const body = await (res.data || res.json());
  155. const values = body.data.slice().sort();
  156. labelValuesByKey[key] = values;
  157. this.logLabelOptions.push({
  158. label: key,
  159. value: key,
  160. children: values.map(value => ({ label: value, value })),
  161. });
  162. }
  163. this.labelValues = { [EMPTY_SELECTOR]: labelValuesByKey };
  164. this.labelKeys = labelKeysBySelector;
  165. } catch (e) {
  166. console.error(e);
  167. }
  168. }
  169. async fetchLabelValues(key: string) {
  170. const url = `/api/prom/label/${key}/values`;
  171. try {
  172. const res = await this.request(url);
  173. const body = await (res.data || res.json());
  174. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  175. const values = {
  176. ...exisingValues,
  177. [key]: body.data,
  178. };
  179. this.labelValues = {
  180. ...this.labelValues,
  181. [EMPTY_SELECTOR]: values,
  182. };
  183. } catch (e) {
  184. console.error(e);
  185. }
  186. }
  187. }