language_provider.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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', 'namespace'];
  13. const EMPTY_SELECTOR = '{}';
  14. const HISTORY_ITEM_COUNT = 10;
  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. Object.assign(this, initialValues);
  43. }
  44. // Strip syntax chars
  45. cleanText = s => s.replace(/[{}[\]="(),!~+\-*/^%]/g, '').trim();
  46. getSyntax() {
  47. return PromqlSyntax;
  48. }
  49. request = url => {
  50. return this.datasource.metadataRequest(url);
  51. };
  52. start = () => {
  53. if (!this.startTask) {
  54. this.startTask = this.fetchLogLabels();
  55. }
  56. return this.startTask;
  57. };
  58. // Keep this DOM-free for testing
  59. provideCompletionItems({ prefix, wrapperClasses, text }: TypeaheadInput, context?: any): TypeaheadOutput {
  60. // Syntax spans have 3 classes by default. More indicate a recognized token
  61. const tokenRecognized = wrapperClasses.length > 3;
  62. // Determine candidates by CSS context
  63. if (_.includes(wrapperClasses, 'context-labels')) {
  64. // Suggestions for metric{|} and metric{foo=|}, as well as metric-independent label queries like {|}
  65. return this.getLabelCompletionItems.apply(this, arguments);
  66. } else if (
  67. // Show default suggestions in a couple of scenarios
  68. (prefix && !tokenRecognized) || // Non-empty prefix, but not inside known token
  69. (prefix === '' && !text.match(/^[\]})\s]+$/)) || // Empty prefix, but not following a closing brace
  70. text.match(/[+\-*/^%]/) // Anything after binary operator
  71. ) {
  72. return this.getEmptyCompletionItems(context || {});
  73. }
  74. return {
  75. suggestions: [],
  76. };
  77. }
  78. getEmptyCompletionItems(context: any): TypeaheadOutput {
  79. const { history } = context;
  80. const suggestions: CompletionItemGroup[] = [];
  81. if (history && history.length > 0) {
  82. const historyItems = _.chain(history)
  83. .uniqBy('query')
  84. .take(HISTORY_ITEM_COUNT)
  85. .map(h => h.query)
  86. .map(wrapLabel)
  87. .map(item => addHistoryMetadata(item, history))
  88. .value();
  89. suggestions.push({
  90. prefixMatch: true,
  91. skipSort: true,
  92. label: 'History',
  93. items: historyItems,
  94. });
  95. }
  96. return { suggestions };
  97. }
  98. getLabelCompletionItems({ text, wrapperClasses, labelKey, value }: TypeaheadInput): TypeaheadOutput {
  99. let context: string;
  100. let refresher: Promise<any> = null;
  101. const suggestions: CompletionItemGroup[] = [];
  102. const line = value.anchorBlock.getText();
  103. const cursorOffset: number = value.anchorOffset;
  104. // Use EMPTY_SELECTOR until series API is implemented for facetting
  105. const selector = EMPTY_SELECTOR;
  106. let parsedSelector;
  107. try {
  108. parsedSelector = parseSelector(line, cursorOffset);
  109. } catch {}
  110. const existingKeys = parsedSelector ? parsedSelector.labelKeys : [];
  111. if ((text && text.match(/^!?=~?/)) || _.includes(wrapperClasses, 'attr-value')) {
  112. // Label values
  113. if (labelKey && this.labelValues[selector]) {
  114. const labelValues = this.labelValues[selector][labelKey];
  115. if (labelValues) {
  116. context = 'context-label-values';
  117. suggestions.push({
  118. label: `Label values for "${labelKey}"`,
  119. items: labelValues.map(wrapLabel),
  120. });
  121. } else {
  122. refresher = this.fetchLabelValues(labelKey);
  123. }
  124. }
  125. } else {
  126. // Label keys
  127. const labelKeys = this.labelKeys[selector] || DEFAULT_KEYS;
  128. if (labelKeys) {
  129. const possibleKeys = _.difference(labelKeys, existingKeys);
  130. if (possibleKeys.length > 0) {
  131. context = 'context-labels';
  132. suggestions.push({ label: `Labels`, items: possibleKeys.map(wrapLabel) });
  133. }
  134. }
  135. }
  136. return { context, refresher, suggestions };
  137. }
  138. async fetchLogLabels() {
  139. const url = '/api/prom/label';
  140. try {
  141. const res = await this.request(url);
  142. const body = await (res.data || res.json());
  143. const labelKeys = body.data.slice().sort();
  144. this.labelKeys = {
  145. ...this.labelKeys,
  146. [EMPTY_SELECTOR]: labelKeys,
  147. };
  148. this.logLabelOptions = labelKeys.map(key => ({ label: key, value: key, isLeaf: false }));
  149. // Pre-load values for default labels
  150. return labelKeys.filter(key => DEFAULT_KEYS.indexOf(key) > -1).map(key => this.fetchLabelValues(key));
  151. } catch (e) {
  152. console.error(e);
  153. }
  154. return [];
  155. }
  156. async fetchLabelValues(key: string) {
  157. const url = `/api/prom/label/${key}/values`;
  158. try {
  159. const res = await this.request(url);
  160. const body = await (res.data || res.json());
  161. const values = body.data.slice().sort();
  162. // Add to label options
  163. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  164. if (keyOption.value === key) {
  165. return {
  166. ...keyOption,
  167. children: values.map(value => ({ label: value, value })),
  168. };
  169. }
  170. return keyOption;
  171. });
  172. // Add to key map
  173. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  174. const nextValues = {
  175. ...exisingValues,
  176. [key]: values,
  177. };
  178. this.labelValues = {
  179. ...this.labelValues,
  180. [EMPTY_SELECTOR]: nextValues,
  181. };
  182. } catch (e) {
  183. console.error(e);
  184. }
  185. }
  186. }