language_provider.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. 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 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. 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 fetchLogLabels() {
  141. const url = '/api/prom/label';
  142. try {
  143. const res = await this.request(url);
  144. const body = await (res.data || res.json());
  145. const labelKeys = body.data.slice().sort();
  146. this.labelKeys = {
  147. ...this.labelKeys,
  148. [EMPTY_SELECTOR]: labelKeys,
  149. };
  150. this.logLabelOptions = labelKeys.map(key => ({ label: key, value: key, isLeaf: false }));
  151. // Pre-load values for default labels
  152. return labelKeys.filter(key => DEFAULT_KEYS.indexOf(key) > -1).map(key => this.fetchLabelValues(key));
  153. } catch (e) {
  154. console.error(e);
  155. }
  156. return [];
  157. }
  158. async fetchLabelValues(key: string) {
  159. const url = `/api/prom/label/${key}/values`;
  160. try {
  161. const res = await this.request(url);
  162. const body = await (res.data || res.json());
  163. const values = body.data.slice().sort();
  164. // Add to label options
  165. this.logLabelOptions = this.logLabelOptions.map(keyOption => {
  166. if (keyOption.value === key) {
  167. return {
  168. ...keyOption,
  169. children: values.map(value => ({ label: value, value })),
  170. };
  171. }
  172. return keyOption;
  173. });
  174. // Add to key map
  175. const exisingValues = this.labelValues[EMPTY_SELECTOR];
  176. const nextValues = {
  177. ...exisingValues,
  178. [key]: values,
  179. };
  180. this.labelValues = {
  181. ...this.labelValues,
  182. [EMPTY_SELECTOR]: nextValues,
  183. };
  184. } catch (e) {
  185. console.error(e);
  186. }
  187. }
  188. }