import atexit
import json
import os
import zenoh
from .helper import generate_multicast_address, log
zenoh_default_config = {}
DEFAULT_SEP_MULTICAST: bool = True
_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 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_mode_and_connect(config)
for key, value in (overrides or {}).items():
config.insert_json5(key, json.dumps(value))
return config
[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 = []
[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)
atexit.register(self._sessions[realm].close)
if obj not in self._referrers:
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
"""
if obj in self._referrers:
ref_idx = self._referrers.index(obj)
del self._referrers[ref_idx]
realm = self._referrer_realms.pop(ref_idx)
else:
return
if realm not in self._referrer_realms and realm in self._sessions:
try:
self._sessions[realm].close()
except zenoh.ZError:
msg = "Timeout occurred when closing Zenoh session. This can lead to stale peers and indicates connection issues."
log.exception(msg)
del self._sessions[realm]
[docs]
def update_config(self, config_dict: dict) -> None:
self._config_dict.update(config_dict)
[docs]
def force_close(self) -> None:
for session in self._sessions.values():
session.close()
self._sessions = {}
self._referrers = []
self._referrer_realms = []
zenoh.try_init_log_from_env()
session_manager = ZenohSessionManager()