|
| 1 | +"""Backend discovery utilities. |
| 2 | +
|
| 3 | +This module provides functions for discovering scheduler backends registered |
| 4 | +via Python entry points. The entry point group "jupyter_scheduler.backends" |
| 5 | +is scanned at startup to find all available backend implementations. |
| 6 | +
|
| 7 | +The discovery system supports: |
| 8 | +- Automatic registration of pip-installed backend packages |
| 9 | +- Allow/block lists for filtering available backends |
| 10 | +- Graceful handling of missing dependencies |
| 11 | +""" |
| 12 | + |
| 13 | +import logging |
| 14 | +from importlib.metadata import entry_points |
| 15 | +from typing import Dict, List, Optional, Type |
| 16 | + |
| 17 | +from jupyter_scheduler.base_backend import BaseBackend |
| 18 | + |
| 19 | +ENTRY_POINT_GROUP = "jupyter_scheduler.backends" |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +def discover_backends( |
| 25 | + log: Optional[logging.Logger] = None, |
| 26 | + allowed_backends: Optional[List[str]] = None, |
| 27 | + blocked_backends: Optional[List[str]] = None, |
| 28 | +) -> Dict[str, Type[BaseBackend]]: |
| 29 | + """Discover all registered backends via entry points. |
| 30 | +
|
| 31 | + Scans the "jupyter_scheduler.backends" entry point group for registered |
| 32 | + backend classes. Each entry point should reference a class that inherits |
| 33 | + from BaseBackend. |
| 34 | +
|
| 35 | + Parameters |
| 36 | + ---------- |
| 37 | + log : logging.Logger, optional |
| 38 | + Logger for status messages. If None, uses module logger. |
| 39 | + allowed_backends : list of str, optional |
| 40 | + If provided, only backends with IDs in this list are included. |
| 41 | + Takes precedence over blocked_backends for the same ID. |
| 42 | + blocked_backends : list of str, optional |
| 43 | + If provided, backends with IDs in this list are excluded. |
| 44 | +
|
| 45 | + Returns |
| 46 | + ------- |
| 47 | + dict |
| 48 | + Mapping of backend_id -> backend class for all discovered backends. |
| 49 | +
|
| 50 | + Notes |
| 51 | + ----- |
| 52 | + Backends are filtered in this order: |
| 53 | + 1. Entry point is loaded (skip on ImportError with warning) |
| 54 | + 2. Backend ID is checked against blocked_backends (skip if blocked) |
| 55 | + 3. Backend ID is checked against allowed_backends (skip if not allowed) |
| 56 | +
|
| 57 | + Example entry point registration in pyproject.toml: |
| 58 | +
|
| 59 | + [project.entry-points."jupyter_scheduler.backends"] |
| 60 | + local = "jupyter_scheduler.backends:LocalBackend" |
| 61 | + k8s = "jupyter_scheduler_k8s:K8sBackend" |
| 62 | + """ |
| 63 | + if log is None: |
| 64 | + log = logger |
| 65 | + |
| 66 | + backends: Dict[str, Type[BaseBackend]] = {} |
| 67 | + |
| 68 | + # Get entry points for the backends group |
| 69 | + # Compatible with Python 3.9+ importlib.metadata |
| 70 | + eps = entry_points() |
| 71 | + if hasattr(eps, "select"): |
| 72 | + # Python 3.10+ / importlib_metadata style |
| 73 | + backend_eps = eps.select(group=ENTRY_POINT_GROUP) |
| 74 | + else: |
| 75 | + # Python 3.9 style (returns dict) |
| 76 | + backend_eps = eps.get(ENTRY_POINT_GROUP, []) |
| 77 | + |
| 78 | + for ep in backend_eps: |
| 79 | + # Attempt to load the backend class |
| 80 | + try: |
| 81 | + backend_class = ep.load() |
| 82 | + except ImportError as e: |
| 83 | + # Missing dependency - provide actionable message |
| 84 | + missing_package = getattr(e, "name", str(e)) |
| 85 | + log.warning( |
| 86 | + f"Unable to load backend '{ep.name}': missing dependency '{missing_package}'. " |
| 87 | + f"Install the required package to enable this backend." |
| 88 | + ) |
| 89 | + continue |
| 90 | + except Exception as e: |
| 91 | + log.warning(f"Unable to load backend '{ep.name}': {e}") |
| 92 | + continue |
| 93 | + |
| 94 | + # Validate the backend class has required attributes |
| 95 | + if not hasattr(backend_class, "id"): |
| 96 | + log.warning( |
| 97 | + f"Backend '{ep.name}' does not define 'id' attribute. Skipping." |
| 98 | + ) |
| 99 | + continue |
| 100 | + |
| 101 | + backend_id = backend_class.id |
| 102 | + |
| 103 | + # Apply block list |
| 104 | + if blocked_backends and backend_id in blocked_backends: |
| 105 | + log.debug(f"Backend '{backend_id}' is blocked by configuration.") |
| 106 | + continue |
| 107 | + |
| 108 | + # Apply allow list (if specified, only allowed backends pass) |
| 109 | + if allowed_backends is not None and backend_id not in allowed_backends: |
| 110 | + log.debug(f"Backend '{backend_id}' is not in allowed list.") |
| 111 | + continue |
| 112 | + |
| 113 | + backends[backend_id] = backend_class |
| 114 | + log.info(f"Registered backend '{backend_id}' ({backend_class.name})") |
| 115 | + |
| 116 | + return backends |
| 117 | + |
| 118 | + |
| 119 | +def get_default_backend_id( |
| 120 | + available_backends: Dict[str, Type[BaseBackend]], |
| 121 | + configured_default: Optional[str] = None, |
| 122 | +) -> str: |
| 123 | + """Determine the default backend ID. |
| 124 | +
|
| 125 | + Selection priority: |
| 126 | + 1. Explicitly configured default (if available) |
| 127 | + 2. "local" backend (if available) |
| 128 | + 3. First available backend (sorted by ID for determinism) |
| 129 | +
|
| 130 | + Parameters |
| 131 | + ---------- |
| 132 | + available_backends : dict |
| 133 | + Mapping of backend_id -> backend class from discover_backends(). |
| 134 | + configured_default : str, optional |
| 135 | + Administrator-configured default backend ID. |
| 136 | +
|
| 137 | + Returns |
| 138 | + ------- |
| 139 | + str |
| 140 | + The backend ID to use as default. |
| 141 | +
|
| 142 | + Raises |
| 143 | + ------ |
| 144 | + ValueError |
| 145 | + If no backends are available. |
| 146 | + """ |
| 147 | + if not available_backends: |
| 148 | + raise ValueError( |
| 149 | + "No scheduler backends available. " |
| 150 | + "Ensure at least one backend package is installed." |
| 151 | + ) |
| 152 | + |
| 153 | + # Explicit configuration takes precedence |
| 154 | + if configured_default and configured_default in available_backends: |
| 155 | + return configured_default |
| 156 | + |
| 157 | + # Warn if configured default is not available |
| 158 | + if configured_default and configured_default not in available_backends: |
| 159 | + logger.warning( |
| 160 | + f"Configured default_backend '{configured_default}' not found. " |
| 161 | + f"Available backends: {list(available_backends.keys())}" |
| 162 | + ) |
| 163 | + |
| 164 | + # Fall back to "local" if available |
| 165 | + if "local" in available_backends: |
| 166 | + return "local" |
| 167 | + |
| 168 | + # Last resort: first available (sorted for determinism) |
| 169 | + return sorted(available_backends.keys())[0] |
0 commit comments