Source code for heros.zenoh

import json
import os
import weakref

import zenoh

from .helper import generate_multicast_address, log

zenoh_default_config = {}

DEFAULT_SEP_MULTICAST: bool = True

# milliseconds a zenoh link open may take before it is given up on. `zenoh.Session.close` waits
# for the open attempts that are still in flight, and zenoh aborts a close that takes longer than
# 10 s, so the zenoh default of 10000 makes every close of a busy realm fail. Overridden by
# `transport/unicast/open_timeout` in `HEROS_ZENOH_CONFIG`.
DEFAULT_OPEN_TIMEOUT: int = 1000

_OPEN_TIMEOUT_KEY = "transport/unicast/open_timeout"


[docs] def _zenoh_default_open_timeout() -> int: """Return the link open timeout of an untouched zenoh config, in milliseconds.""" return json.loads(zenoh.Config().get_json(_OPEN_TIMEOUT_KEY))
_TRUE_FLAGS = ("1", "true", "yes", "on") _FALSE_FLAGS = ("0", "false", "no", "off") _ZENOH_MODES = ("peer", "client", "router")
[docs] def _parse_sep_multicast_env() -> bool | None: """ Parse `HEROS_SEP_MULTICAST` strictly. Returns: True or False for a recognized value, None if the variable is unset or empty Raises: ValueError: If the value is not one of 1/true/yes/on or 0/false/no/off (case-insensitive) """ raw = os.environ.get("HEROS_SEP_MULTICAST", "") value = raw.strip().lower() if not value: return None if value in _TRUE_FLAGS: return True if value in _FALSE_FLAGS: return False msg = f"Invalid HEROS_SEP_MULTICAST {raw!r}: use one of {', '.join(_TRUE_FLAGS + _FALSE_FLAGS)}" raise ValueError(msg)
[docs] def _apply_mode_and_connect(config: zenoh.Config) -> None: """ Apply `HEROS_ZENOH_MODE` and `HEROS_ZENOH_CONNECT` to a config, unset or empty variables change nothing. Raises: ValueError: If the mode is not peer, client or router, a connect item is empty or zenoh rejects a value """ raw_mode = os.environ.get("HEROS_ZENOH_MODE", "") mode = raw_mode.strip().lower() if mode: if mode not in _ZENOH_MODES: msg = f"Invalid HEROS_ZENOH_MODE {raw_mode!r}: use one of {', '.join(_ZENOH_MODES)}" raise ValueError(msg) config.insert_json5("mode", json.dumps(mode)) raw_connect = os.environ.get("HEROS_ZENOH_CONNECT", "") if raw_connect.strip(): endpoints = [item.strip() for item in raw_connect.split(",")] if "" in endpoints: msg = f"Invalid HEROS_ZENOH_CONNECT {raw_connect!r}: empty endpoint in a comma-separated list" raise ValueError(msg) try: config.insert_json5("connect/endpoints", json.dumps(endpoints)) except zenoh.ZError as exc: msg = f"Invalid HEROS_ZENOH_CONNECT {raw_connect!r}: expected endpoints like tcp/<host>:7447" raise ValueError(msg) from exc
[docs] def _apply_open_timeout(config: zenoh.Config) -> None: """ Lower the link open timeout to DEFAULT_OPEN_TIMEOUT, unless the config already sets its own. A value is treated as the caller's own as soon as it differs from the zenoh default, so `HEROS_ZENOH_CONFIG` keeps the last word. """ if json.loads(config.get_json(_OPEN_TIMEOUT_KEY)) == _zenoh_default_open_timeout(): config.insert_json5(_OPEN_TIMEOUT_KEY, json.dumps(DEFAULT_OPEN_TIMEOUT))
[docs] def build_config(realm: str, overrides: dict | None = None, *, sep_multicast: bool | None = None) -> zenoh.Config: """ Assemble the zenoh config for a realm without opening a session. Environment variables are read at call time. Later layers win over earlier ones: zenoh defaults, then `HEROS_ZENOH_CONFIG`, then the realm specific multicast address (non-`heros` realms only), then `HEROS_ZENOH_MODE` and `HEROS_ZENOH_CONNECT`, then `overrides`. `HEROS_ZENOH_CONNECT` sets only `connect/endpoints`. The multicast address is used if `sep_multicast` is true. If it is None, `HEROS_SEP_MULTICAST` decides, and if that is unset, the module default does. Args: realm: The realm the session is opened for overrides: Config keys and values applied last sep_multicast: Whether to use a realm specific multicast address, None to use the environment Returns: The assembled zenoh config Raises: ValueError: If `HEROS_ZENOH_CONFIG` is not a valid zenoh config, `HEROS_SEP_MULTICAST` is not a recognized flag, or `HEROS_ZENOH_MODE` or `HEROS_ZENOH_CONNECT` hold an invalid value """ env_config = os.environ.get("HEROS_ZENOH_CONFIG", "") if not env_config.strip(): config = zenoh.Config() else: try: config = zenoh.Config.from_json5(env_config) except zenoh.ZError as exc: msg = f"Invalid HEROS_ZENOH_CONFIG: {exc}" raise ValueError(msg) from exc if sep_multicast is None: sep_multicast = _parse_sep_multicast_env() if sep_multicast is None: sep_multicast = DEFAULT_SEP_MULTICAST if realm != "heros" and sep_multicast: # use a realm specific multicast address, the default heros realm keeps the zenoh default config.insert_json5("scouting/multicast/address", json.dumps(f"{generate_multicast_address(realm)}:7446")) _apply_open_timeout(config) _apply_mode_and_connect(config) for key, value in (overrides or {}).items(): config.insert_json5(key, json.dumps(value)) return config
[docs] def _close(session: zenoh.Session) -> None: """ Close a zenoh session, logging rather than raising if zenoh gives up on it. Args: session: The session to close """ try: session.close() except zenoh.ZError: log.exception( "Closing the zenoh session timed out, which can leave stale peers behind. See the HEROS " "documentation on sessions that fail to close." )
# every manager ever created, so that shutdown can reach the sessions they still hold _managers: weakref.WeakSet = weakref.WeakSet()
[docs] def close_all_sessions() -> None: """Tear down every HERO and close every zenoh session of this process.""" for manager in list(_managers): manager.force_close()
[docs] class ZenohSessionManager: """ Share one zenoh session per realm between all HEROs of a process. The zenoh config is built when the first session of a realm opens and stays in use until every HERO of that realm has released it. Args: config_dict: Zenoh config keys and values, applied over the environment sep_multicast: Whether sessions use a realm specific multicast address. None defers to `HEROS_SEP_MULTICAST` and then to the default. Can be changed later via the `sep_multicast` attribute and applies to sessions opened afterwards. """ def __init__(self, config_dict: dict | None = None, *, sep_multicast: bool | None = None): self.sep_multicast = sep_multicast config_dict = {} if config_dict is None else config_dict self._config_dict = {} self._config_dict.update(zenoh_default_config) self._config_dict.update(config_dict) self._sessions = {} self._referrers = [] self._referrer_realms = [] _managers.add(self)
[docs] def _referrer_index(self, obj: object) -> int | None: """Return the index of `obj` in the referrers, or None. By identity, as HEROs of the same name compare equal.""" return next((idx for idx, referrer in enumerate(self._referrers) if referrer is obj), None)
[docs] def request_session(self, obj: object, realm: str) -> zenoh.Session: """ Request the global zenoh session. Args: obj: The object that requests the session """ if realm not in self._sessions: config = build_config(realm, self._config_dict, sep_multicast=self.sep_multicast) self._sessions[realm] = zenoh.open(config) if self._referrer_index(obj) is None: self._referrers.append(obj) self._referrer_realms.append(realm) return self._sessions[realm]
[docs] def release_session(self, obj: object) -> None: """ Release from the global zenoh session. Args: obj: The object that wants to release from the global zenoh session """ ref_idx = self._referrer_index(obj) if ref_idx is None: return del self._referrers[ref_idx] realm = self._referrer_realms.pop(ref_idx) if realm not in self._referrer_realms and realm in self._sessions: _close(self._sessions.pop(realm))
[docs] def update_config(self, config_dict: dict) -> None: self._config_dict.update(config_dict)
[docs] def force_close(self) -> None: """ Tear down every HERO that holds a session of this manager, then close the sessions. Closing a session does not reliably release the callback threads of the declarations made on it, undeclaring does. The HEROs therefore have to go first, which is why this does more than close the sessions. """ for referrer in list(self._referrers): destroy = getattr(referrer, "_destroy_hero", None) if destroy is None: continue try: destroy() except Exception: # noqa: BLE001 log.exception("could not destroy HERO while closing its session") for session in self._sessions.values(): _close(session) self._sessions = {} self._referrers = [] self._referrer_realms = []
zenoh.try_init_log_from_env() session_manager = ZenohSessionManager()