가상 회선 스위칭 문서의 구현 코드다. if __name__ == "__main__": 아래가 자체 테스트다.

# 가상 회선 스위칭을 흉내 낸다: 연결 설정(신호), VC 테이블, 링크마다 바뀌는 VCI, 해제, 소프트 상태.
# 실행: python3 79_virtual-circuit_impl.py  (표준 라이브러리만 씀)
#
# 다음 약속을 따른다(Peterson & Davie 3.1.2의 신호 방식).
# - VCI(가상 회선 번호)는 링크 하나 안에서만 뜻이 있다. 같은 번호가 다른 링크에서 다른 회선을 가리킬 수 있다.
# - 그래서 스위치의 VC 테이블 열쇠는 (들어온 포트, 들어온 VCI)이고, 값은 (나갈 포트, 나갈 VCI)다.
# - 연결 설정 때 각 노드는 "자기에게 들어오는 링크"에서 쓸 VCI를 스스로 고르고, 그 번호를 앞 노드에 알려 준다.
#   앞 노드는 그 번호를 자기 테이블의 '나갈 VCI'(세 칸 표의 '다음 VC#')로 적는다.
# - 포트 번호와 토폴로지는 예제 그림(스위치 3개, 호스트 A~H)을 따른다.
from collections import deque

# (노드, 포트) <-> (노드, 포트). 호스트는 포트 0 하나만 가진다.
WIRES = [
    (("S1", 0), ("D", 0)), (("S1", 1), ("S2", 3)), (("S1", 2), ("A", 0)), (("S1", 3), ("C", 0)),
    (("S2", 0), ("S3", 0)), (("S2", 1), ("F", 0)), (("S2", 2), ("E", 0)),
    (("S3", 1), ("G", 0)), (("S3", 2), ("H", 0)), (("S3", 3), ("B", 0)),
]
PEER = {}
for a, b in WIRES:
    PEER[a], PEER[b] = b, a


def link_id(end):
    """링크 하나를 양 끝과 상관없이 같은 이름으로 부른다."""
    return frozenset([end, PEER[end]])


def path_ports(src, dst):
    """src 호스트에서 dst 호스트까지 너비 우선 탐색으로 경로를 찾고 [(노드, 들어온 포트, 나갈 포트), ...]를 돌려준다."""
    prev = {src: None}
    q = deque([src])
    while q:
        u = q.popleft()
        for (n, p), (m, mp) in PEER.items():
            if n == u and m not in prev:
                prev[m] = (u, p, mp)
                q.append(m)
    hops, v = [], dst
    while prev[v] is not None:
        u, out_p, in_p = prev[v]
        hops.append((u, out_p, v, in_p))
        v = u
    hops.reverse()                                   # [(앞 노드, 나간 포트, 뒤 노드, 들어온 포트), ...]
    res = []
    for k in range(1, len(hops)):
        node, in_p = hops[k - 1][2], hops[k - 1][3]
        res.append((node, in_p, hops[k][1]))
    return hops, res


class Network:
    def __init__(self, soft_timeout=None):
        self.table = {}          # 스위치 -> {(in_port, in_vci): [out_port, out_vci, 마지막 갱신 시각]}
        self.used = {}           # 링크 -> 그 링크에서 쓰는 VCI 집합
        self.soft_timeout = soft_timeout

    def _pick(self, link, wanted):
        used = self.used.setdefault(link, set())
        if wanted is None:                           # 자동: 그 링크에서 안 쓰는 가장 작은 번호
            wanted = 0
            while wanted in used:
                wanted += 1
        assert wanted not in used, f"{wanted}는 이 링크에서 이미 쓰는 VCI다"
        used.add(wanted)
        return wanted

    def setup(self, src, dst, choices=None, now=0.0):
        """연결 설정. choices[k]는 경로의 k번째 링크에서 뒤 노드가 고를 VCI(없으면 자동)."""
        hops, sw = path_ports(src, dst)
        choices = choices or [None] * len(hops)
        vcis = [self._pick(link_id((u, op)), choices[k]) for k, (u, op, v, ip) in enumerate(hops)]
        for k, (node, in_p, out_p) in enumerate(sw):
            self.table.setdefault(node, {})[(in_p, vcis[k])] = [out_p, vcis[k + 1], now]
        return dict(src=src, dst=dst, hops=hops, vcis=vcis, first_vci=vcis[0], first_port=hops[0][1])

    def send(self, vc, now=0.0, refresh=False):
        """데이터 패킷 하나를 보내고 링크마다 헤더에 적힌 VCI를 기록한다. 테이블에 줄이 없으면 버린다."""
        node, port, vci = vc["src"], vc["first_port"], vc["first_vci"]
        trace = []
        while True:
            nxt, in_p = PEER[(node, port)]
            trace.append((node, nxt, vci))
            if nxt not in self.table:                # 호스트에 닿음
                return nxt, trace
            self.expire(now)
            row = self.table[nxt].get((in_p, vci))
            if row is None:
                return None, trace                  # 상태가 없어 버림
            if refresh:
                row[2] = now
            node, port, vci = nxt, row[0], row[1]   # 열쇠로 바로 찾고(검색 없음), VCI를 바꿔 적는다

    def teardown(self, vc):
        """해제: 경로의 모든 줄과 링크별 VCI를 지운다."""
        _, sw = path_ports(vc["src"], vc["dst"])
        for k, (node, in_p, out_p) in enumerate(sw):
            self.table[node].pop((in_p, vc["vcis"][k]), None)
        for k, (u, op, v, ip) in enumerate(vc["hops"]):
            self.used[link_id((u, op))].discard(vc["vcis"][k])

    def expire(self, now):
        """소프트 상태: 마지막 갱신 뒤 soft_timeout이 지난 줄은 저절로 사라진다."""
        if self.soft_timeout is None:
            return
        for node, rows in self.table.items():
            for key in [k for k, r in rows.items() if now - r[2] > self.soft_timeout]:
                del rows[key]

    def rows(self, node):
        return {k: tuple(v[:2]) for k, v in self.table.get(node, {}).items()}


if __name__ == "__main__":
    # 1) 그림의 가상 회선 A -> B. 링크마다 뒤 노드가 고른 번호: S1 5, S2 11, S3 7, B 4.
    net = Network()
    vc1 = net.setup("A", "B", choices=[5, 11, 7, 4])
    assert [h[:2] for h in vc1["hops"]] == [("A", 0), ("S1", 1), ("S2", 0), ("S3", 3)]
    assert net.rows("S1") == {(2, 5): (1, 11)}
    assert net.rows("S2") == {(3, 11): (0, 7)}
    assert net.rows("S3") == {(0, 7): (3, 4)}
    dst, tr = net.send(vc1)
    assert dst == "B" and [x[2] for x in tr] == [5, 11, 7, 4]
    print("A->B 링크별 VCI:", [(a, b, v) for a, b, v in tr])

    # 2) 카드 C3: C -> B를 하나 더 연다. S1 5, S2 12, S3 9, B 6.
    vc2 = net.setup("C", "B", choices=[5, 12, 9, 6])
    assert net.rows("S1") == {(2, 5): (1, 11), (3, 5): (1, 12)}
    assert net.rows("S2") == {(3, 11): (0, 7), (3, 12): (0, 9)}
    assert net.rows("S3") == {(0, 7): (3, 4), (0, 9): (3, 6)}
    dst, tr = net.send(vc2)
    assert dst == "B" and [x[2] for x in tr] == [5, 12, 9, 6]
    print("C->B 링크별 VCI:", [x[2] for x in tr])
    # S1에 VCI 5가 두 줄 있다. 열쇠에서 들어온 포트를 빼면 두 줄이 한 칸에 겹친다.
    only_vci = {}
    for (p, v), row in net.rows("S1").items():
        only_vci.setdefault(v, []).append(row)
    assert len(only_vci[5]) == 2
    # 같은 링크(B 쪽)에서 이미 쓰는 4를 다시 고르면 거절한다.
    try:
        net.setup("D", "B", choices=[1, 13, 10, 4])
        raise SystemExit("중복 VCI를 받아들였다")
    except AssertionError:
        pass
    # 거절된 설정이 남긴 번호를 정리하고 다시 연다(앞 링크에서 고른 번호는 해제).
    net.used[link_id(("S1", 0))].discard(1)
    net.used[link_id(("S1", 1))].discard(13)
    net.used[link_id(("S2", 0))].discard(10)

    # 2-1) 문서의 예제: A -> B가 열린 상태에서 E -> H를 연다. S3가 S2-S3 링크에 7을 고르면 거절된다
    #      (A -> B가 그 링크에서 7을 쓰고 있다). 8로 고르면 된다.
    ex = Network()
    ex.setup("A", "B", choices=[5, 11, 7, 4])
    try:
        ex.setup("E", "H", choices=[3, 7, 2])
        raise SystemExit("같은 링크의 중복 VCI 7을 받아들였다")
    except AssertionError:
        pass
    ex.used[link_id(("E", 0))].discard(3)            # 거절된 설정이 앞 링크에 남긴 번호를 정리
    vc_eh = ex.setup("E", "H", choices=[3, 8, 2])
    assert [h[:2] for h in vc_eh["hops"]] == [("E", 0), ("S2", 0), ("S3", 2)]
    assert ex.rows("S2") == {(3, 11): (0, 7), (2, 3): (0, 8)}
    assert ex.rows("S3") == {(0, 7): (3, 4), (0, 8): (2, 2)}
    assert ex.send(vc_eh)[0] == "H" and [x[2] for x in ex.send(vc_eh)[1]] == [3, 8, 2]
    # E -> H의 VCI 3은 S1-A 링크의 5와 상관없다. 다른 링크에서는 7을 다시 써도 된다.
    ex2 = Network()
    ex2.setup("A", "B", choices=[5, 11, 7, 4])
    assert ex2.setup("E", "H", choices=[7, 8, 2])["vcis"] == [7, 8, 2]
    # 링크 고장: S2-S3가 끊겨 S2의 (3, 11) 줄이 가리키는 출력 링크가 사라지면, S1의 줄은 남아 있어도
    # 패킷은 B에 닿지 못한다. 상태를 지우고 다른 길로 새로 설정해야 한다(이 토폴로지에는 다른 길이 없다).

    # 3) 자동 번호: 링크마다 안 쓰는 가장 작은 번호를 고른다.
    vc3 = net.setup("D", "H")
    assert vc3["vcis"] == [0, 0, 0, 0]
    vc4 = net.setup("D", "H")
    assert vc4["vcis"] == [1, 1, 1, 1]

    # 4) 해제하면 줄과 번호가 사라지고, 그 뒤 패킷은 버려진다.
    net.teardown(vc1)
    assert (2, 5) not in net.rows("S1") and 11 not in net.used[link_id(("S1", 1))]
    assert net.send(vc1)[0] is None

    # 5) 하드 상태: 해제 없이 A가 사라지면 줄이 끝없이 남는다(쓰레기).
    hard = Network()
    hard.setup("A", "B", choices=[5, 11, 7, 4], now=0.0)
    hard.expire(1000.0)
    assert hard.rows("S2") == {(3, 11): (0, 7)}
    # 소프트 상태: 30초 안에 패킷(또는 갱신)이 오지 않으면 줄이 저절로 사라진다.
    soft = Network(soft_timeout=30.0)
    v = soft.setup("A", "B", choices=[5, 11, 7, 4], now=0.0)
    for t in [10.0, 20.0, 45.0]:                     # 쓰는 동안은 계속 갱신되어 살아 있다
        assert soft.send(v, now=t, refresh=True)[0] == "B"
    soft.expire(80.0)                                # 마지막 갱신 45초 + 30초 < 80초
    assert soft.rows("S1") == {} and soft.rows("S2") == {} and soft.rows("S3") == {}
    print("ALL CHECKS PASSED")