Source code for heros.helper
import hashlib
import importlib
import ipaddress
import re
import warnings
from .logging import get_logger as _get_logger
log = _get_logger("heros")
# logging helpers that moved to `heros.logging`, kept as deprecated re-exports for downstream packages
_DEPRECATED_LOGGING_NAMES = ("SPAM", "Logger", "ColoredFormatter", "get_logger")
[docs]
def __getattr__(name: str):
"""Re-export the logging helpers that moved to :py:mod:`heros.logging`, warning about their deprecation."""
if name in _DEPRECATED_LOGGING_NAMES:
warnings.warn(
f"`heros.helper.{name}` is deprecated and will be removed in a future version, "
f"import it from `heros.logging` instead",
DeprecationWarning,
stacklevel=2,
)
from . import logging as heros_logging
return getattr(heros_logging, name)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
[docs]
def object_name_from_keyexpr(key_expr, ns_objects, realm, endpoint=".*") -> str | None:
res = re.search(f"{ns_objects}/{realm}/(.*?)/{endpoint}", key_expr)
if res:
return res.groups()[0]
[docs]
def full_classname(o):
"""
Return the fully qualified class name of an object.
Args:
o: object
Returns:
fully qualified module and class name
"""
cl = o.__class__
mod = cl.__module__
if mod == "__builtin__":
return cl.__name__ # avoid outputs like '__builtin__.str'
return f"{mod}.{cl.__name__}"
[docs]
def get_heros_pkg_versions() -> dict:
"""Returns the versions of the installed heros packages
Returns:
dict: A dictionary with the package names as keys and the versions as values. If package version is not
available, the value is "n.a.", if package is not installed the value is "not installed".
"""
ver_dict = {}
for module_name in ["heros", "boss", "herosdevices", "herostools", "atomiq"]:
try:
module = importlib.import_module(module_name)
if hasattr(module, "__version__"):
ver_dict[module.__name__] = module.__version__
else:
ver_dict[module.__name__] = "n.a."
except ImportError:
ver_dict[module_name] = "not installed"
return ver_dict
[docs]
def generate_multicast_address(realm: str) -> str:
"""Generate a deterministic multicast address based on the realm name.
Note:
As the multicast range does not include an infinite number of ip addresses
there is a slim but finite probability that two realm names generate
the same multicast address.
Args:
realm: The realm name.
Returns:
str: A multicast IP address in the range 224.0.1.0 to 238.255.255.255.
"""
hash = int.from_bytes(hashlib.shake_128(realm.encode()).digest(4))
# Multicast range: 224.0.1.0 to 239.255.255.255
multicast_start = 0xE0000100 # 224.0.1.0 in integer
multicast_end = 0xEEFFFFFF # 238.255.255.255 in integer
multicast_range = multicast_end - multicast_start + 1
ip_int = multicast_start + (hash % multicast_range)
return str(ipaddress.ip_address(ip_int))