1"""
2ZMQ-specific functions
3"""
4
5import logging
6
7from salt._compat import ipaddress
8from salt.exceptions import SaltSystemExit
9
10log = logging.getLogger(__name__)
11
12try:
13    import zmq
14except ImportError:
15    zmq = None
16    log.debug("ZMQ module is not found")
17
18ZMQDefaultLoop = None
19ZMQ_VERSION_INFO = (-1, -1, -1)
20LIBZMQ_VERSION_INFO = (-1, -1, -1)
21
22try:
23    if zmq:
24        ZMQ_VERSION_INFO = tuple([int(v_el) for v_el in zmq.__version__.split(".")])
25        LIBZMQ_VERSION_INFO = tuple(
26            [int(v_el) for v_el in zmq.zmq_version().split(".")]
27        )
28except Exception:  # pylint: disable=broad-except
29    log.exception("Error while getting LibZMQ/PyZMQ library version")
30
31
32def check_ipc_path_max_len(uri):
33    # The socket path is limited to 107 characters on Solaris and
34    # Linux, and 103 characters on BSD-based systems.
35    if zmq is None:
36        return
37    ipc_path_max_len = getattr(zmq, "IPC_PATH_MAX_LEN", 103)
38    if ipc_path_max_len and len(uri) > ipc_path_max_len:
39        raise SaltSystemExit(
40            "The socket path is longer than allowed by OS. "
41            "'{}' is longer than {} characters. "
42            "Either try to reduce the length of this setting's "
43            "path or switch to TCP; in the configuration file, "
44            'set "ipc_mode: tcp".'.format(uri, ipc_path_max_len)
45        )
46
47
48def ip_bracket(addr):
49    """
50    Ensure IP addresses are URI-compatible - specifically, add brackets
51    around IPv6 literals if they are not already present.
52    """
53    addr = str(addr)
54    addr = addr.lstrip("[")
55    addr = addr.rstrip("]")
56    addr = ipaddress.ip_address(addr)
57    return ("[{}]" if addr.version == 6 else "{}").format(addr)
58