#!/usr/bin/env python3 """Shared environment discovery for the simulation launchers and tools.""" import argparse import math import os from pathlib import Path import re import shlex import shutil import signal import subprocess import sys import tempfile import time WORKSPACE = Path(__file__).resolve().parents[1] _KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'cmd_vel_relay', 'field_localization_node', 'field_localization_record', 'field_localization_replay') _GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz') _GZ_VERSION_TIMEOUT = 5 _FIELD_PACKAGE = Path('src/guodong_sentry_sim') # 无界面 Gazebo 的 OGRE2 走 EGL。混合显卡笔记本上 glvnd 默认挑 Mesa, # gpu_lidar 于是退化成 llvmpipe 软件光栅(实测单核 84%,CPU 射线只要 30%)。 # 把 EGL vendor 指向 NVIDIA 的 json,OGRE2 才能真正用上显卡。 _EGL_NVIDIA_JSON = Path('/usr/share/glvnd/egl_vendor.d/10_nvidia.json') _NVIDIA_DEVICE_NODE = Path('/dev/nvidiactl') _GPU_EGL_MODES = ('auto', 'nvidia', 'off') class ProbeError(RuntimeError): """A required setting is missing or points to an unusable path.""" def require_file(path, name): path = Path(path).absolute() if not path.is_file(): raise ProbeError(f'{name} 必须指向普通文件: {path}') return path def require_directory(path, name): path = Path(path).absolute() if not path.is_dir(): raise ProbeError(f'{name} 必须指向目录: {path}') return path def is_executable(path): return Path(path).is_file() and os.access(path, os.X_OK) def require_executable(path, name): path = Path(path).absolute() if not is_executable(path): raise ProbeError(f'{name} 必须指向可执行的普通文件: {path}') return path def find_ros_setup(): """Return the ROS setup path, or None when ROS is already sourced.""" explicit = os.environ.get('ROS_SETUP') setup = require_file(explicit, 'ROS_SETUP') if explicit else None if os.environ.get('AMENT_PREFIX_PATH') and shutil.which('ros2'): return None if setup is not None: return setup root = os.environ.get('ROS_INSTALL_ROOT') if root: setup = Path(root) / 'setup.bash' if setup.is_file(): return setup.absolute() distro = os.environ.get('ROS_DISTRO') if distro: setup = Path('/opt/ros') / distro / 'setup.bash' if setup.is_file(): return setup candidates = sorted( (p for p in Path('/opt/ros').glob('*/setup.bash') if p.is_file()), key=lambda p: ([int(part) if i % 2 else part for i, part in enumerate(re.split(r'([0-9]+)', p.parent.name))], p.parent.name), ) if not candidates: raise ProbeError('找不到 ROS 2 setup.bash。请加载 ROS 环境或设置 ROS_SETUP。') if len(candidates) > 1: print(f'[env] 警告: 发现多个 ROS 安装,按目录名排序选择 {candidates[-1]}', file=sys.stderr) return candidates[-1] def find_bin_dir(ws=WORKSPACE): """Choose a single build directory without mixing targets from different builds.""" for name in ('SENTRY_BIN_DIR', 'NAV_BIN_DIR'): if override := os.environ.get(name): return require_directory(override, name) build = Path(ws).absolute() / 'build' unified = build / 'bin' if any(is_executable(unified / name) for name in _KNOWN_BINARIES): return unified for mode in ('release', 'debug'): for candidate in sorted(build.glob(f'*/*/{mode}')): if any(is_executable(candidate / name) for name in _KNOWN_BINARIES): return candidate return unified def find_gz_bin(): """Prefer system Gazebo, validating an explicit override before any fallback.""" if override := os.environ.get('GZ_BIN'): return require_executable(override, 'GZ_BIN') for path in _GZ_CANDIDATES: if is_executable(path): return Path(path) if path := shutil.which('gz'): return require_executable(path, 'gz') raise ProbeError('找不到 Gazebo 的 gz 可执行文件。请设置 GZ_BIN。') def run_gz(gz, *args, timeout, partition=None): """Run a Gazebo query in its own process group with a wall-clock deadline.""" env = os.environ.copy() env.pop('LD_LIBRARY_PATH', None) if partition is not None: env['GZ_PARTITION'] = partition command = [str(gz), *args] # Files let us read results after a timeout even if a descendant still holds # an output descriptor. Only the process group started here is signalled. with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: process = subprocess.Popen(command, env=env, start_new_session=True, stdout=stdout, stderr=stderr) try: process.wait(timeout=timeout) except BaseException: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass process.wait() raise stdout.seek(0) stderr.seek(0) return subprocess.CompletedProcess(command, process.returncode, stdout.read().decode(errors='replace'), stderr.read().decode(errors='replace')) def gz_version_args(gz=None): """Return force-version arguments, or warn and let Gazebo choose its default.""" if gz is None: gz = find_gz_bin() if forced := os.environ.get('GZ_FORCE_VERSION'): return ['--force-version', forced] try: result = run_gz(gz, 'sim', '--version', timeout=_GZ_VERSION_TIMEOUT) if result.returncode: reason = f'退出码 {result.returncode}' else: version = re.match(r'^\s*([0-9]+)(?=\.|\s|$)', result.stdout.strip() or result.stderr.strip()) if version: return ['--force-version', version[1]] reason = '无法解析版本' except subprocess.TimeoutExpired: reason = f'超时({_GZ_VERSION_TIMEOUT:g} 秒)' except OSError as error: reason = str(error) print(f'[env] 警告: {gz} sim --version {reason},使用 Gazebo 默认版本。' '可通过 GZ_FORCE_VERSION 指定主版本。', file=sys.stderr) return [] def wait_gz_clock(gz, gazebo_pid=None): """Wait for the selected Gazebo transport to advertise /clock.""" raw_timeout = os.environ.get('BRIDGE_WAIT_TIMEOUT') or '120' try: timeout = float(raw_timeout) except ValueError: timeout = 0 if not math.isfinite(timeout) or timeout <= 0: raise ProbeError(f'BRIDGE_WAIT_TIMEOUT 必须为正数: {raw_timeout}') deadline = time.monotonic() + timeout while (remaining := deadline - time.monotonic()) > 0: if gazebo_pid is not None: try: os.kill(gazebo_pid, 0) except ProcessLookupError as error: raise ProbeError('Gazebo 启动失败,进程已退出') from error try: # Listing topics waits for a full discovery cycle (over two seconds on this host). result = run_gz(gz, 'topic', '-e', '-t', '/clock', '-n', '1', timeout=min(2, remaining)) if result.returncode == 0 and result.stdout.strip(): return except subprocess.TimeoutExpired: pass time.sleep(max(0, min(1, deadline - time.monotonic()))) raise ProbeError( f'等待 Gazebo /clock 超时({timeout:g} 秒),请检查 GZ_PARTITION=' f'{os.environ.get("GZ_PARTITION") or "sentry"}') def egl_vendor_json(): """NVIDIA 的 EGL vendor 描述文件。 `SENTRY_EGL_VENDOR_JSON` 可覆盖 —— 发行版把 glvnd 配置放别处时用。 """ override = os.environ.get('SENTRY_EGL_VENDOR_JSON') return Path(override) if override else _EGL_NVIDIA_JSON def gpu_env(): """Return the EGL environment that makes OGRE2 (and gpu_lidar) use the dGPU. `SENTRY_GPU_EGL` selects the behaviour: auto enable only when an NVIDIA device node and the vendor json exist nvidia always enable; missing vendor json is an error off never touch the environment `SENTRY_EGL_PLATFORM` additionally exports `EGL_PLATFORM` when set (some hosts only reach the surfaceless platform that way). An empty dict means "leave the environment alone" so callers can splat it unconditionally. """ mode = (os.environ.get('SENTRY_GPU_EGL') or 'auto').strip().lower() if mode not in _GPU_EGL_MODES: raise ProbeError( f'SENTRY_GPU_EGL 只能是 {"|".join(_GPU_EGL_MODES)},当前为 {mode!r}') if mode == 'off': return {} vendor = egl_vendor_json() if mode == 'nvidia' and not vendor.is_file(): raise ProbeError(f'SENTRY_GPU_EGL=nvidia 但找不到 {vendor}') if mode == 'auto' and not (_NVIDIA_DEVICE_NODE.exists() and vendor.is_file()): return {} env = { '__EGL_VENDOR_LIBRARY_FILENAMES': str(vendor), 'NVIDIA_DRIVER_CAPABILITIES': os.environ.get('NVIDIA_DRIVER_CAPABILITIES') or 'all', } if platform := os.environ.get('SENTRY_EGL_PLATFORM'): env['EGL_PLATFORM'] = platform return env def describe_gpu_env(): """One-line human summary of what `gpu_env()` decided and why.""" mode = (os.environ.get('SENTRY_GPU_EGL') or 'auto').strip().lower() env = gpu_env() if env: return 'nvidia → ' + ' '.join(f'{k}={v}' for k, v in env.items()) if mode == 'off': return 'off(SENTRY_GPU_EGL=off,不改环境)' reasons = [] if not _NVIDIA_DEVICE_NODE.exists(): reasons.append(f'{_NVIDIA_DEVICE_NODE} 不存在') vendor = egl_vendor_json() if not vendor.is_file(): reasons.append(f'{vendor} 不存在') return 'off(' + ';'.join(reasons or ['未找到可用显卡']) + ')' def find_field_root(ws=WORKSPACE, *, explicit=None): if explicit: return require_directory(explicit, 'field_root') if override := os.environ.get('SENTRY_FIELD_ROOT'): return require_directory(override, 'SENTRY_FIELD_ROOT') for parent, pattern in ((Path(ws).absolute() / 'field', '*'), (Path.home() / 'Gazebo_projects', '*map_transfer*')): for candidate in sorted(parent.glob(pattern)): if (candidate / _FIELD_PACKAGE).is_dir(): return candidate raise ProbeError('找不到场地迁移包。请设置 SENTRY_FIELD_ROOT。') def find_map_yaml(field_root=None, *, explicit=None, ws=WORKSPACE): if explicit: return require_file(explicit, 'map') if override := os.environ.get('SENTRY_MAP_YAML'): return require_file(override, 'SENTRY_MAP_YAML') if field_root is None: field_root = find_field_root(ws) maps = Path(field_root) / _FIELD_PACKAGE / 'maps' preferred = maps / 'rmul_2027' / 'rmul_2027.yaml' if preferred.is_file(): return preferred candidates = sorted(p for p in maps.glob('*/*.yaml') if p.is_file()) for candidate in candidates: if candidate.name == 'rmul_2027.yaml': return candidate if candidates: return candidates[0] raise ProbeError(f'{maps} 下找不到栅格图 YAML。请设置 SENTRY_MAP_YAML。') def report(ws): setup = find_ros_setup() bin_dir = find_bin_dir(ws) field_root = find_field_root(ws) map_yaml = find_map_yaml(field_root) gz = find_gz_bin() versions = ' '.join(gz_version_args(gz)) print(f'仓库根: {ws}') print(f' ROS setup : {setup or "<已 source>"}') print(f' BIN_DIR : {bin_dir}') print(f' GZ_BIN : {gz}') print(f' gz 版本参数 : {versions or "<无>"}') print(f' FIELD_ROOT : {field_root}') print(f' MAP_YAML : {map_yaml}') print(f' GPU EGL : {describe_gpu_env()}') def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('workspace', type=Path, nargs='?', default=WORKSPACE) queries = parser.add_mutually_exclusive_group() for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup', 'gpu', 'gpu-shell'): queries.add_argument(f'--{query}', dest='query', action='store_const', const=query) for query in ('gz-version-args-lines', 'wait-gz-clock'): queries.add_argument(f'--{query}', dest='query', action='store_const', const=query, help=argparse.SUPPRESS) parser.add_argument('--field-root', type=Path, help=argparse.SUPPRESS) parser.add_argument('--gazebo-pid', type=int, help=argparse.SUPPRESS) args = parser.parse_args(argv) if args.field_root is not None and args.query != 'map': parser.error('--field-root requires --map') if args.gazebo_pid is not None and (args.query != 'wait-gz-clock' or args.gazebo_pid <= 0): parser.error('--gazebo-pid requires --wait-gz-clock and a positive PID') try: ws = require_directory(args.workspace, 'workspace') match args.query: case 'bin-dir': print(find_bin_dir(ws)) case 'field': print(find_field_root(ws)) case 'map': print(find_map_yaml(args.field_root, ws=ws)) case 'gz': print(find_gz_bin()) case 'gz-version-args' | 'gz-version-args-lines': separator = '\n' if args.query == 'gz-version-args-lines' else ' ' versions = gz_version_args() if versions: print(separator.join(versions)) elif args.query == 'gz-version-args': print() case 'ros-setup': print(find_ros_setup() or '') case 'gpu': print(describe_gpu_env()) case 'gpu-shell': for name, value in gpu_env().items(): print(f'export {name}={shlex.quote(value)}') case 'wait-gz-clock': wait_gz_clock(find_gz_bin(), args.gazebo_pid) case None: report(ws) except (ProbeError, OSError) as error: print(f'[env] {error}', file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())