for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
"""Module with identifier types for Links and Interfaces"""
import hashlib
from typing import Tuple
class InterfaceID(str):
"""Interface Identifier"""
__slots__ = ("switch", "port")
def __new__(cls, switch: str, port: int):
return super().__new__(cls, f"{switch}:{port}")
def __init__(self, switch: str, port: int):
# Used for sorting, but can be accessed
self.switch = switch
self.port = port
super().__init__()
def __lt__(self, other):
# Ensures that instances are sortable in a way that maintains backwards
# compatibility when creating instances of LinkID
dpid_a = self.switch
port_a = self.port
dpid_b = other.switch
port_b = other.port
if dpid_a < dpid_b:
return True
return dpid_a == dpid_b and port_a < port_b
class LinkID(str):
"""Link Identifier"""
def __new__(cls, interface_1: str, interface_2: str):
intf_1 = InterfaceID(*LinkID.intf_id_to_tuple(interface_1))
intf_2 = InterfaceID(*LinkID.intf_id_to_tuple(interface_2))
raw_str = ":".join(sorted((intf_1, intf_2)))
digest = hashlib.sha256(raw_str.encode('utf-8')).hexdigest()
return super().__new__(cls, digest)
@staticmethod
def intf_id_to_tuple(interface_id: str) -> Tuple[str, int]:
"""Map interface id as a switch, port tuple."""
values = interface_id.split(":")
switch_id = ":".join(values[:-1])
port = int(values[-1])
return switch_id, port