| 1 |
"""Setup and configure remote debugging.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import abc |
| 6 |
import dataclasses |
| 7 |
import importlib |
| 8 |
import json |
| 9 |
import os |
| 10 |
import pathlib |
| 11 |
import re |
| 12 |
import sys |
| 13 |
import typing as t |
| 14 |
|
| 15 |
from .util import ( |
| 16 |
cache, |
| 17 |
display, |
| 18 |
raw_command, |
| 19 |
ApplicationError, |
| 20 |
get_subclasses, |
| 21 |
) |
| 22 |
|
| 23 |
from .util_common import ( |
| 24 |
CommonConfig, |
| 25 |
) |
| 26 |
|
| 27 |
from .processes import ( |
| 28 |
Process, |
| 29 |
get_current_process, |
| 30 |
) |
| 31 |
|
| 32 |
from .config import ( |
| 33 |
EnvironmentConfig, |
| 34 |
) |
| 35 |
|
| 36 |
from .metadata import ( |
| 37 |
DebuggerFlags, |
| 38 |
) |
| 39 |
|
| 40 |
from .data import ( |
| 41 |
data_context, |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
class DebuggerProfile(t.Protocol): |
| 46 |
"""Protocol for debugger profiles.""" |
| 47 |
|
| 48 |
@property |
| 49 |
def debugger_host(self) -> str: |
| 50 |
"""The hostname to expose to the debugger.""" |
| 51 |
|
| 52 |
@property |
| 53 |
def debugger_port(self) -> int: |
| 54 |
"""The port to expose to the debugger.""" |
| 55 |
|
| 56 |
def get_source_mapping(self) -> dict[str, str]: |
| 57 |
"""The source mapping to expose to the debugger.""" |
| 58 |
|
| 59 |
|
| 60 |
@dataclasses.dataclass(frozen=True, kw_only=True) |
| 61 |
class DebuggerSettings(metaclass=abc.ABCMeta): |
| 62 |
"""Common debugger settings.""" |
| 63 |
|
| 64 |
port: int = 5678 |
| 65 |
""" |
| 66 |
The port on the origin host which is listening for incoming connections from the debugger. |
| 67 |
SSH port forwarding will be automatically configured for non-local hosts to connect to this port as needed. |
| 68 |
""" |
| 69 |
|
| 70 |
def as_dict(self) -> dict[str, object]: |
| 71 |
"""Convert this instance to a dict.""" |
| 72 |
data = dataclasses.asdict(self) |
| 73 |
data.update(__type__=self.__class__.__name__) |
| 74 |
|
| 75 |
return data |
| 76 |
|
| 77 |
@classmethod |
| 78 |
def from_dict(cls, value: dict[str, t.Any]) -> t.Self: |
| 79 |
"""Load an instance from a dict.""" |
| 80 |
debug_cls = globals()[value.pop('__type__')] |
| 81 |
|
| 82 |
return debug_cls(**value) |
| 83 |
|
| 84 |
@classmethod |
| 85 |
def get_debug_type(cls) -> str: |
| 86 |
"""Return the name for this debugger.""" |
| 87 |
return cls.__name__.removesuffix('Settings').lower() |
| 88 |
|
| 89 |
@classmethod |
| 90 |
def get_config_env_var_name(cls) -> str: |
| 91 |
"""Return the name of the environment variable used to customize settings for this debugger.""" |
| 92 |
return f'ANSIBLE_TEST_REMOTE_DEBUGGER_{cls.get_debug_type().upper()}' |
| 93 |
|
| 94 |
@classmethod |
| 95 |
def parse(cls, value: str) -> t.Self: |
| 96 |
"""Parse debugger settings from the given JSON and apply defaults.""" |
| 97 |
try: |
| 98 |
settings = cls(**json.loads(value)) |
| 99 |
except Exception as ex: |
| 100 |
raise ApplicationError(f"Invalid {cls.get_debug_type()} settings: {ex}") from ex |
| 101 |
|
| 102 |
return cls.apply_defaults(settings) |
| 103 |
|
| 104 |
@classmethod |
| 105 |
@abc.abstractmethod |
| 106 |
def is_active(cls) -> bool: |
| 107 |
"""Detect if the debugger is active.""" |
| 108 |
|
| 109 |
@classmethod |
| 110 |
@abc.abstractmethod |
| 111 |
def apply_defaults(cls, settings: t.Self) -> t.Self: |
| 112 |
"""Apply defaults to the given settings.""" |
| 113 |
|
| 114 |
@abc.abstractmethod |
| 115 |
def get_python_package(self) -> str: |
| 116 |
"""The Python package to install for debugging.""" |
| 117 |
|
| 118 |
@abc.abstractmethod |
| 119 |
def activate_debugger(self, profile: DebuggerProfile) -> None: |
| 120 |
"""Activate the debugger in ansible-test after delegation.""" |
| 121 |
|
| 122 |
@abc.abstractmethod |
| 123 |
def get_ansiballz_config(self, profile: DebuggerProfile) -> dict[str, object]: |
| 124 |
"""Gets the extra configuration data for the AnsiballZ extension module.""" |
| 125 |
|
| 126 |
@abc.abstractmethod |
| 127 |
def get_cli_arguments(self, profile: DebuggerProfile) -> list[str]: |
| 128 |
"""Get command line arguments for the debugger when running Ansible CLI programs.""" |
| 129 |
|
| 130 |
@abc.abstractmethod |
| 131 |
def get_environment_variables(self, profile: DebuggerProfile) -> dict[str, str]: |
| 132 |
"""Get environment variables needed to configure the debugger for debugging.""" |
| 133 |
|
| 134 |
|
| 135 |
@dataclasses.dataclass(frozen=True, kw_only=True) |
| 136 |
class PydevdSettings(DebuggerSettings): |
| 137 |
"""Settings for the pydevd debugger.""" |
| 138 |
|
| 139 |
package: str | None = None |
| 140 |
""" |
| 141 |
The Python package to install for debugging. |
| 142 |
If `None` then the package will be auto-detected. |
| 143 |
If an empty string, then no package will be installed. |
| 144 |
""" |
| 145 |
|
| 146 |
module: str | None = None |
| 147 |
""" |
| 148 |
The Python module to import for debugging. |
| 149 |
This should be pydevd or a derivative. |
| 150 |
If not provided it will be auto-detected. |
| 151 |
""" |
| 152 |
|
| 153 |
settrace: dict[str, object] = dataclasses.field(default_factory=dict) |
| 154 |
""" |
| 155 |
Options to pass to the `{module}.settrace` method. |
| 156 |
Used for running AnsiballZ modules only. |
| 157 |
The `host` and `port` options will be provided by ansible-test. |
| 158 |
The `suspend` option defaults to `False`. |
| 159 |
""" |
| 160 |
|
| 161 |
args: list[str] = dataclasses.field(default_factory=list) |
| 162 |
""" |
| 163 |
Arguments to pass to `pydevd` on the command line. |
| 164 |
Used for running Ansible CLI programs only. |
| 165 |
The `--client` and `--port` options will be provided by ansible-test. |
| 166 |
""" |
| 167 |
|
| 168 |
@classmethod |
| 169 |
def is_active(cls) -> bool: |
| 170 |
return detect_pydevd_port() is not None |
| 171 |
|
| 172 |
@classmethod |
| 173 |
def apply_defaults(cls, settings: t.Self) -> t.Self: |
| 174 |
if not settings.module: |
| 175 |
if not settings.package or 'pydevd-pycharm' in settings.package: |
| 176 |
module = 'pydevd_pycharm' |
| 177 |
else: |
| 178 |
module = 'pydevd' |
| 179 |
|
| 180 |
settings = dataclasses.replace(settings, module=module) |
| 181 |
|
| 182 |
if settings.package is None: |
| 183 |
if settings.module == 'pydevd_pycharm': |
| 184 |
if pycharm_version := detect_pycharm_version(): |
| 185 |
package = f'pydevd-pycharm~={pycharm_version}' |
| 186 |
else: |
| 187 |
package = None |
| 188 |
else: |
| 189 |
package = 'pydevd' |
| 190 |
|
| 191 |
settings = dataclasses.replace(settings, package=package) |
| 192 |
|
| 193 |
settings.settrace.setdefault('suspend', False) |
| 194 |
|
| 195 |
if port := detect_pydevd_port(): |
| 196 |
settings = dataclasses.replace(settings, port=port) |
| 197 |
|
| 198 |
if detect_pycharm_process(): |
| 199 |
# This only works with the default PyCharm debugger. |
| 200 |
# Using it with PyCharm's "Python Debug Server" results in hangs in Ansible workers. |
| 201 |
# Further investigation is required to understand the cause. |
| 202 |
settings = dataclasses.replace(settings, args=settings.args + ['--multiprocess']) |
| 203 |
|
| 204 |
return settings |
| 205 |
|
| 206 |
def get_python_package(self) -> str: |
| 207 |
if self.package is None and self.module == 'pydevd_pycharm': |
| 208 |
display.warning('Skipping installation of `pydevd-pycharm` since the running PyCharm version was not detected.') |
| 209 |
|
| 210 |
return self.package |
| 211 |
|
| 212 |
def activate_debugger(self, profile: DebuggerProfile) -> None: |
| 213 |
debugging_module = importlib.import_module(self.module) |
| 214 |
debugging_module.settrace(**self._get_settrace_arguments(profile)) |
| 215 |
|
| 216 |
def get_ansiballz_config(self, profile: DebuggerProfile) -> dict[str, object]: |
| 217 |
return dict( |
| 218 |
module=self.module, |
| 219 |
settrace=self._get_settrace_arguments(profile), |
| 220 |
source_mapping=profile.get_source_mapping(), |
| 221 |
) |
| 222 |
|
| 223 |
def get_cli_arguments(self, profile: DebuggerProfile) -> list[str]: |
| 224 |
# Although `pydevd_pycharm` can be used to invoke `settrace`, it cannot be used to run the debugger on the command line. |
| 225 |
return ['-m', 'pydevd', '--client', profile.debugger_host, '--port', str(profile.debugger_port)] + self.args + ['--file'] |
| 226 |
|
| 227 |
def get_environment_variables(self, profile: DebuggerProfile) -> dict[str, str]: |
| 228 |
return dict( |
| 229 |
PATHS_FROM_ECLIPSE_TO_PYTHON=json.dumps(list(profile.get_source_mapping().items())), |
| 230 |
PYDEVD_DISABLE_FILE_VALIDATION="1", |
| 231 |
) |
| 232 |
|
| 233 |
def _get_settrace_arguments(self, profile: DebuggerProfile) -> dict[str, object]: |
| 234 |
"""Get settrace arguments for pydevd.""" |
| 235 |
return self.settrace | dict( |
| 236 |
host=profile.debugger_host, |
| 237 |
port=profile.debugger_port, |
| 238 |
) |
| 239 |
|
| 240 |
|
| 241 |
@dataclasses.dataclass(frozen=True, kw_only=True) |
| 242 |
class DebugpySettings(DebuggerSettings): |
| 243 |
"""Settings for the debugpy debugger.""" |
| 244 |
|
| 245 |
connect: dict[str, object] = dataclasses.field(default_factory=dict) |
| 246 |
""" |
| 247 |
Options to pass to the `debugpy.connect` method. |
| 248 |
Used for running AnsiballZ modules and ansible-test after delegation. |
| 249 |
The endpoint addr, `access_token`, and `parent_session_pid` options will be provided by ansible-test. |
| 250 |
""" |
| 251 |
|
| 252 |
args: list[str] = dataclasses.field(default_factory=list) |
| 253 |
""" |
| 254 |
Arguments to pass to `debugpy` on the command line. |
| 255 |
Used for running Ansible CLI programs only. |
| 256 |
The `--connect`, `--adapter-access-token`, and `--parent-session-pid` options will be provided by ansible-test. |
| 257 |
""" |
| 258 |
|
| 259 |
debugpy_package_path: str | None = None |
| 260 |
""" |
| 261 |
The path to the debugpy package to add to PYTHONPATH. |
| 262 |
""" |
| 263 |
|
| 264 |
@classmethod |
| 265 |
def is_active(cls) -> bool: |
| 266 |
return detect_debugpy_options() is not None |
| 267 |
|
| 268 |
@classmethod |
| 269 |
def apply_defaults(cls, settings: t.Self) -> t.Self: |
| 270 |
if options := detect_debugpy_options(): |
| 271 |
settings = dataclasses.replace(settings, port=options.port, debugpy_package_path=options.debugpy_package_path) |
| 272 |
settings.connect.update( |
| 273 |
access_token=options.adapter_access_token, |
| 274 |
parent_session_pid=os.getpid(), |
| 275 |
) |
| 276 |
else: |
| 277 |
display.warning('Debugging will be limited to the first connection. Run ansible-test under debugpy to support multiple connections.') |
| 278 |
|
| 279 |
return settings |
| 280 |
|
| 281 |
def get_python_package(self) -> str: |
| 282 |
return 'debugpy' |
| 283 |
|
| 284 |
def activate_debugger(self, profile: DebuggerProfile) -> None: |
| 285 |
import debugpy # pylint: disable=import-error |
| 286 |
|
| 287 |
debugpy.connect((profile.debugger_host, profile.debugger_port), **self.connect) |
| 288 |
|
| 289 |
def get_ansiballz_config(self, profile: DebuggerProfile) -> dict[str, object]: |
| 290 |
return dict( |
| 291 |
host=profile.debugger_host, |
| 292 |
port=profile.debugger_port, |
| 293 |
connect=self.connect, |
| 294 |
source_mapping=profile.get_source_mapping(), |
| 295 |
) |
| 296 |
|
| 297 |
def get_cli_arguments(self, profile: DebuggerProfile) -> list[str]: |
| 298 |
cli_args = ['-m', 'debugpy', '--connect', f"{profile.debugger_host}:{profile.debugger_port}"] |
| 299 |
|
| 300 |
if access_token := self.connect.get('access_token'): |
| 301 |
cli_args += ['--adapter-access-token', str(access_token)] |
| 302 |
|
| 303 |
if session_pid := self.connect.get('parent_session_pid'): |
| 304 |
cli_args += ['--parent-session-pid', str(session_pid)] |
| 305 |
|
| 306 |
if self.args: |
| 307 |
cli_args += self.args |
| 308 |
|
| 309 |
return cli_args |
| 310 |
|
| 311 |
def get_environment_variables(self, profile: DebuggerProfile) -> dict[str, str]: |
| 312 |
env = dict( |
| 313 |
PATHS_FROM_ECLIPSE_TO_PYTHON=json.dumps(list(profile.get_source_mapping().items())), |
| 314 |
PYDEVD_DISABLE_FILE_VALIDATION="1", |
| 315 |
) |
| 316 |
|
| 317 |
if self.debugpy_package_path: |
| 318 |
python_path = os.environ.get('PYTHONPATH', '') |
| 319 |
if python_path: |
| 320 |
python_path = f"{self.debugpy_package_path}{os.pathsep}{python_path}" |
| 321 |
else: |
| 322 |
python_path = self.debugpy_package_path |
| 323 |
|
| 324 |
env['PYTHONPATH'] = python_path |
| 325 |
|
| 326 |
return env |
| 327 |
|
| 328 |
|
| 329 |
def initialize_debugger(args: CommonConfig) -> None: |
| 330 |
"""Initialize the debugger settings before delegation.""" |
| 331 |
if not isinstance(args, EnvironmentConfig): |
| 332 |
return |
| 333 |
|
| 334 |
if args.metadata.loaded: |
| 335 |
return # after delegation |
| 336 |
|
| 337 |
if collection := data_context().content.collection: |
| 338 |
args.metadata.collection_root = collection.root |
| 339 |
|
| 340 |
load_debugger_settings(args) |
| 341 |
|
| 342 |
|
| 343 |
def load_debugger_settings(args: EnvironmentConfig) -> None: |
| 344 |
"""Load the remote debugger settings.""" |
| 345 |
use_debugger: type[DebuggerSettings] | None = None |
| 346 |
|
| 347 |
if args.metadata.debugger_flags.on_demand: |
| 348 |
# On-demand debugging only enables debugging if we're running under a debugger, otherwise it's a no-op. |
| 349 |
|
| 350 |
for candidate_debugger in get_subclasses(DebuggerSettings): |
| 351 |
if candidate_debugger.is_active(): |
| 352 |
use_debugger = candidate_debugger |
| 353 |
break |
| 354 |
else: |
| 355 |
display.info('Debugging disabled because no debugger was detected.', verbosity=1) |
| 356 |
args.metadata.debugger_flags = DebuggerFlags.all(False) |
| 357 |
return |
| 358 |
|
| 359 |
display.info('Enabling on-demand debugging.', verbosity=1) |
| 360 |
|
| 361 |
if not args.metadata.debugger_flags.enable: |
| 362 |
# Assume the user wants all debugging features enabled, since on-demand debugging with no features is pointless. |
| 363 |
args.metadata.debugger_flags = DebuggerFlags.all(True) |
| 364 |
|
| 365 |
if not args.metadata.debugger_flags.enable: |
| 366 |
return |
| 367 |
|
| 368 |
if not use_debugger: # detect debug type based on env var |
| 369 |
for candidate_debugger in get_subclasses(DebuggerSettings): |
| 370 |
if candidate_debugger.get_config_env_var_name() in os.environ: |
| 371 |
use_debugger = candidate_debugger |
| 372 |
break |
| 373 |
else: |
| 374 |
display.info('Debugging disabled because no debugger configuration was provided.', verbosity=1) |
| 375 |
args.metadata.debugger_flags = DebuggerFlags.all(False) |
| 376 |
return |
| 377 |
|
| 378 |
config = os.environ.get(use_debugger.get_config_env_var_name()) or '{}' |
| 379 |
settings = use_debugger.parse(config) |
| 380 |
args.metadata.debugger_settings = settings |
| 381 |
|
| 382 |
display.info(f'>>> Debugger Settings ({use_debugger.get_debug_type()})\n{json.dumps(dataclasses.asdict(settings), indent=4)}', verbosity=3) |
| 383 |
|
| 384 |
|
| 385 |
@cache |
| 386 |
def detect_pydevd_port() -> int | None: |
| 387 |
"""Return the port for the pydevd instance hosting this process, or `None` if not detected.""" |
| 388 |
current_process = get_current_process_cached() |
| 389 |
args = current_process.args |
| 390 |
|
| 391 |
if any('/pydevd.py' in arg for arg in args) and (port_idx := args.index('--port')): |
| 392 |
port = int(args[port_idx + 1]) |
| 393 |
display.info(f'Detected pydevd debugger port {port}.', verbosity=1) |
| 394 |
return port |
| 395 |
|
| 396 |
return None |
| 397 |
|
| 398 |
|
| 399 |
@cache |
| 400 |
def detect_pycharm_version() -> str | None: |
| 401 |
"""Return the version of PyCharm running ansible-test, or `None` if PyCharm was not detected. The result is cached.""" |
| 402 |
if pycharm := detect_pycharm_process(): |
| 403 |
output = raw_command([pycharm.args[0], '--version'], capture=True)[0] |
| 404 |
|
| 405 |
if match := re.search('^Build #PY-(?P<version>[0-9.]+)$', output, flags=re.MULTILINE): |
| 406 |
version = match.group('version') |
| 407 |
display.info(f'Detected PyCharm version {version}.', verbosity=1) |
| 408 |
return version |
| 409 |
|
| 410 |
return None |
| 411 |
|
| 412 |
|
| 413 |
@cache |
| 414 |
def detect_pycharm_process() -> Process | None: |
| 415 |
"""Return the PyCharm process running ansible-test, or `None` if PyCharm was not detected. The result is cached.""" |
| 416 |
current_process = get_current_process_cached() |
| 417 |
parent = current_process.parent |
| 418 |
|
| 419 |
while parent: |
| 420 |
if parent.path.name == 'pycharm': |
| 421 |
return parent |
| 422 |
|
| 423 |
parent = parent.parent |
| 424 |
|
| 425 |
return None |
| 426 |
|
| 427 |
|
| 428 |
@cache |
| 429 |
def get_current_process_cached() -> Process: |
| 430 |
"""Return the current process. The result is cached.""" |
| 431 |
return get_current_process() |
| 432 |
|
| 433 |
|
| 434 |
@dataclasses.dataclass(frozen=True, kw_only=True) |
| 435 |
class DebugpyOptions: |
| 436 |
"""Options detected from the debugpy instance hosting this process.""" |
| 437 |
|
| 438 |
port: int |
| 439 |
adapter_access_token: str | None |
| 440 |
debugpy_package_path: str |
| 441 |
|
| 442 |
|
| 443 |
@cache |
| 444 |
def detect_debugpy_options() -> DebugpyOptions | None: |
| 445 |
"""Return the options for the debugpy instance hosting this process, or `None` if not detected.""" |
| 446 |
if "debugpy" not in sys.modules: |
| 447 |
return None |
| 448 |
|
| 449 |
import debugpy # pylint: disable=import-error |
| 450 |
|
| 451 |
# get_cli_options is the new public API introduced after debugpy 1.8.15. |
| 452 |
# We should remove the debugpy.server cli fallback once the new version is |
| 453 |
# released. |
| 454 |
if hasattr(debugpy, 'get_cli_options'): |
| 455 |
opts = debugpy.get_cli_options() |
| 456 |
else: |
| 457 |
from debugpy.server import cli # pylint: disable=import-error |
| 458 |
opts = cli.options |
| 459 |
|
| 460 |
# address can be None if the debugger is not configured through the CLI as |
| 461 |
# we expected. |
| 462 |
if not opts.address: |
| 463 |
return None |
| 464 |
|
| 465 |
port = opts.address[1] |
| 466 |
|
| 467 |
display.info(f'Detected debugpy debugger port {port}.', verbosity=1) |
| 468 |
|
| 469 |
return DebugpyOptions( |
| 470 |
port=port, |
| 471 |
adapter_access_token=opts.adapter_access_token, |
| 472 |
debugpy_package_path=str(pathlib.Path(debugpy.__file__).resolve().parent.parent), |
| 473 |
) |