Commit 60a3074f57 for frr
commit 60a3074f57fda1b3cc8e904f36dd1a863f359a7a
Author: Lincoln Thurlow <lincoln@isi.edu>
Date: Tue Dec 1 11:00:46 2026 -0800
tests: add pathd PCEP name and timeout topotest
pathd has no topotest that runs a PCEP session, so the handling of
PCE-initiated symbolic path names and of the PCEP session timeout is
not tested.
This commit adds pathd_pcep_names_topo1, where a scripted PCE inside
RT1's namespace initiates SR policies and logs pathd's replies. It
checks that pathd refuses duplicate, reserved and too long names and
segment list names taken by the configuration, reports a refused PCUpd
in a PCRpt, removes a PCE's paths at its session timeout, lets
another PCE take them over, and gives configured paths whose segment
list names do not fit distinct hashed names.
Signed-off-by: Lincoln Thurlow <lincoln@isi.edu>
diff --git a/tests/topotests/pathd_pcep_names_topo1/mock_pce.py b/tests/topotests/pathd_pcep_names_topo1/mock_pce.py
new file mode 100644
index 0000000000..be10f90819
--- /dev/null
+++ b/tests/topotests/pathd_pcep_names_topo1/mock_pce.py
@@ -0,0 +1,651 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: ISC
+
+#
+# mock_pce.py
+#
+
+"""
+Minimal scripted PCE for the pathd PCEP topotests.
+
+Implements just enough of RFC 5440 (PCEP), RFC 8231 (stateful),
+RFC 8281 (PCE-initiated) and RFC 8664 (SR ERO) to drive FRR's pathd
+as a PCC:
+
+1. Accept the PCC's TCP connection and exchange Open/Keepalive.
+2. Wait for the PCC's end-of-state-sync PCRpt (an LSP object with
+ PLSP-ID 0 and the SYNC flag clear). pathd silently discards any
+ PCInitiate received before that point.
+3. Send a PCInitiate for each --policy (SRP + LSP with symbolic name +
+ IPv4 or IPv6 END-POINTS + ERO with one SID-only SR subobject; a
+ VENDOR-INFO object sets the color).
+4. Keep the session alive with periodic Keepalives.
+
+The test adds, removes and updates policies through --command-file.
+State transitions are appended to a log file, which the test prints
+when a check fails.
+"""
+
+import argparse
+import os
+import select
+import socket
+import struct
+import time
+
+PCEP_VERSION_BYTE = 0x20 # version 1, flags 0
+KEEPALIVE_SECONDS = 10 # well inside the 30s keepalive its Open advertises
+
+MSG_OPEN = 1
+MSG_KEEPALIVE = 2
+MSG_REQUEST = 3
+MSG_REPLY = 4
+MSG_ERROR = 6
+MSG_REPORT = 10
+MSG_UPDATE = 11
+MSG_INITIATE = 12
+
+CLASS_OPEN = 1
+CLASS_RP = 2
+CLASS_ENDPOINTS = 4
+CLASS_ERO = 7
+CLASS_ERROR = 13
+CLASS_LSP = 32
+CLASS_SRP = 33
+CLASS_VENDOR_INFO = 34
+
+# FRR reads the policy color from a VENDOR-INFO object carrying this
+# enterprise number and enterprise-specific info value.
+VENDOR_ENTERPRISE_CISCO = 9
+VENDOR_ESI_COLOR = 0x00010004
+
+TLV_STATEFUL_CAP = 16
+TLV_SYMBOLIC_NAME = 17
+TLV_LSP_ERROR_CODE = 20
+TLV_SR_CAP = 26
+TLV_PATH_SETUP_TYPE = 28
+TLV_PST_CAP = 34
+
+LSP_FLAG_SYNC = 0x02
+
+
+def parse_policy(spec):
+ """Parse an endpoint,label,name[,color] --policy argument."""
+ fields = spec.split(",")
+ if len(fields) not in (3, 4):
+ raise argparse.ArgumentTypeError(
+ "--policy takes endpoint,label,name[,color]: %s" % spec
+ )
+ return {
+ "endpoint": fields[0],
+ "label": int(fields[1]),
+ "name": fields[2],
+ "color": int(fields[3]) if len(fields) == 4 else None,
+ }
+
+
+class MockPce:
+ def __init__(self, args):
+ self.args = args
+ self.logfile = open(args.log, "a", buffering=1)
+ self.sock = None
+ self.conn = None
+ self.sync_done = False
+ self.initiated = False
+ self.next_srp_id = 1
+ self.srp_to_name = {}
+ self.plsp_by_name = {}
+ self.plsp_by_report_name = {}
+ self.command_pos = 0
+ self.deferred_removes = []
+
+ self.policies = list(args.policy or [])
+ if args.endpoint:
+ self.policies.insert(
+ 0,
+ {
+ "endpoint": args.endpoint,
+ "label": args.label,
+ "name": args.name,
+ "color": args.color,
+ },
+ )
+
+ def log(self, text):
+ self.logfile.write("%.3f %s\n" % (time.time(), text))
+
+ # ------------------------------------------------------------------
+ # Message builders, each the RFC wire layout of its message
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _obj(oclass, otype, body):
+ """Wrap body in the PCEP common object header (RFC 5440 S7.2):
+
+ Object-Class (1) | Object-Type(4 bits)+flags(4 bits) (1) |
+ Object Length (2, includes this header)
+ """
+ # object header: class(1) type<<4(1) total-length(2)
+ return struct.pack(">BBH", oclass, otype << 4, 4 + len(body)) + body
+
+ @staticmethod
+ def _msg(mtype, body):
+ """Wrap body in the PCEP common message header (RFC 5440 S6.1):
+
+ Version(3 bits)+Flags(5 bits) (1) | Message-Type (1) |
+ Message-Length (2, includes this header)
+ """
+ # message header: version/flags(1) type(1) total-length(2)
+ return struct.pack(">BBH", PCEP_VERSION_BYTE, mtype, 4 + len(body)) + body
+
+ def build_open(self):
+ """Open message (RFC 5440 S6.2), one OPEN object:
+
+ <Common Header> type 1 (Open)
+ <OPEN> Ver/Flags(1) Keepalive(1) DeadTimer(1) SID(1)
+ <STATEFUL-PCE-CAPABILITY> RFC 8231: U|I flag bits
+ <SR-PCE-CAPABILITY> RFC 8664: reserved/flags/MSD
+ <PATH-SETUP-TYPE-CAPABILITY> RFC 8408: PST list = [SR-TE]
+
+ pathd requires at least one TLV in the Open and needs the
+ STATEFUL-PCE-CAPABILITY U bit to send any PCRpt at all.
+ """
+ # TLV header type(2) len(2) + flags word(4): U|I = 0x05
+ tlvs = struct.pack(">HHI", TLV_STATEFUL_CAP, 4, 0x05)
+ # TLV header type(2) len(2) + reserved(1) flags(2 as two B) MSD(1),
+ # all zero
+ tlvs += struct.pack(">HHBBBB", TLV_SR_CAP, 4, 0, 0, 0, 0)
+ # TLV header type(2) len(2)=5 + reserved(3) NumPSTs(1)=1 PST#1(1)=1
+ # (SR-TE) + padding(3). With no sub-TLVs the Length MUST be four
+ # plus the PST list, excluding the padding (RFC 8408 S3).
+ tlvs += struct.pack(">HHBBBBBBBB", TLV_PST_CAP, 5, 0, 0, 0, 1, 1, 0, 0, 0)
+ # OPEN object body: version/flags(1) keepalive(1)=30
+ # deadtimer(1)=120 session-id(1)=1
+ body = struct.pack(">BBBB", PCEP_VERSION_BYTE, 30, 120, 1)
+ return self._msg(MSG_OPEN, self._obj(CLASS_OPEN, 1, body + tlvs))
+
+ def build_keepalive(self):
+ """Keepalive message (RFC 5440 S6.3): the common header alone."""
+ return self._msg(MSG_KEEPALIVE, b"")
+
+ def build_initiate(self, policy, srp_id):
+ """PCInitiate message (RFC 8281 S5.1) creating one SR policy:
+
+ <Common Header> type 12 (PCInitiate)
+ <SRP> Flags(4, R clear = create) SRP-ID(4)
+ <PATH-SETUP-TYPE> PST 1 = SR-TE (RFC 8408)
+ <LSP> PLSP-ID(20 bits)=0 (create) |
+ Flags(12 bits)=D|A|C
+ <SYMBOLIC-PATH-NAME> the policy name, 4-byte padded
+ <END-POINTS> source addr (PCC), destination addr
+ (object type 1 = IPv4, 2 = IPv6)
+ <ERO> one SR subobject (RFC 8664 S4.3.1):
+ label-only SID, NAI absent
+ [<VENDOR-INFO>] Cisco enterprise TLV carrying the color
+
+ pathd reads the policy color from the VENDOR-INFO object;
+ without it every initiated policy gets INITIATED_POLICY_COLOR
+ (1).
+ """
+ # PATH-SETUP-TYPE TLV: type(2) len(2) + reserved(3) PST(1)=1
+ srp_tlv = struct.pack(">HHBBBB", TLV_PATH_SETUP_TYPE, 4, 0, 0, 0, 1)
+ # SRP object body: flags(4)=0 (R clear = create) srp-id(4)
+ srp = self._obj(CLASS_SRP, 1, struct.pack(">II", 0, srp_id) + srp_tlv)
+
+ name = policy["name"].encode()
+ pad = (-len(name)) % 4
+ # SYMBOLIC-PATH-NAME TLV: type(2) len(2) + name, padded to 4
+ lsp_tlv = (
+ struct.pack(">HH", TLV_SYMBOLIC_NAME, len(name)) + name + b"\x00" * pad
+ )
+ # LSP object word: PLSP-ID in the top 20 bits (0 = create),
+ # flags in the low 12 (0x81 = Create|Delegate, RFC 8281 section 5.3.1)
+ lsp = self._obj(CLASS_LSP, 1, struct.pack(">I", (0 << 12) | 0x81) + lsp_tlv)
+
+ # END-POINTS body: raw source then destination address,
+ # object type picked by the endpoint's family
+ if ":" in policy["endpoint"]:
+ ep_body = socket.inet_pton(socket.AF_INET6, self.args.pcc_address6)
+ ep_body += socket.inet_pton(socket.AF_INET6, policy["endpoint"])
+ ep = self._obj(CLASS_ENDPOINTS, 2, ep_body)
+ else:
+ ep_body = socket.inet_aton(self.args.pcc_address)
+ ep_body += socket.inet_aton(policy["endpoint"])
+ ep = self._obj(CLASS_ENDPOINTS, 1, ep_body)
+
+ # SR-ERO subobject: the 20-bit MPLS label sits in the TOP bits
+ # of the 32-bit SID field (RFC 8664), hence the shift
+ sid = (policy["label"] << 12) & 0xFFFFFFFF
+ # subobject: type(1)=0x24(SR) length(1)=8 NT/flags(1)=0(NAI
+ # absent) flags(1)=0x09(F|M: no NAI, SID is an MPLS label) SID(4)
+ sub = struct.pack(">BBBBI", 0x24, 8, 0x00, 0x09, sid)
+ ero = self._obj(CLASS_ERO, 1, sub)
+
+ msg = srp + lsp + ep + ero
+
+ if policy["color"] is not None:
+ # VENDOR-INFO body: enterprise(4)=9(Cisco)
+ # enterprise-specific-info(4)=color-type color-value(4)
+ vendor = self._obj(
+ CLASS_VENDOR_INFO,
+ 1,
+ struct.pack(
+ ">III",
+ VENDOR_ENTERPRISE_CISCO,
+ VENDOR_ESI_COLOR,
+ policy["color"],
+ ),
+ )
+ msg += vendor
+
+ return self._msg(MSG_INITIATE, msg)
+
+ def build_remove(self, name, plsp_id, srp_id):
+ """PCInitiate removal (RFC 8281 S5.4), R flag set:
+
+ <Common Header> type 12 (PCInitiate)
+ <SRP> Flags(4, R set = remove) SRP-ID(4)
+ <LSP> PLSP-ID(20 bits) = the PCC's id for the
+ path | Flags(12 bits) = D
+ <SYMBOLIC-PATH-NAME> repeated for good measure
+
+ A removal is addressed by the PLSP-ID the PCC assigned (learned
+ from its PCRpt); no END-POINTS/ERO are carried.
+ """
+ # SRP object body: flags(4)=1 (R set = remove) srp-id(4)
+ srp = self._obj(CLASS_SRP, 1, struct.pack(">II", 0x00000001, srp_id))
+
+ encoded = name.encode()
+ pad = (-len(encoded)) % 4
+ # SYMBOLIC-PATH-NAME TLV: type(2) len(2) + name, padded to 4
+ lsp_tlv = (
+ struct.pack(">HH", TLV_SYMBOLIC_NAME, len(encoded))
+ + encoded
+ + b"\x00" * pad
+ )
+ # LSP object word: PLSP-ID in the top 20 bits, flags in the low
+ # 12 (0x01 = Delegate)
+ lsp = self._obj(
+ CLASS_LSP, 1, struct.pack(">I", (plsp_id << 12) | 0x01) + lsp_tlv
+ )
+
+ return self._msg(MSG_INITIATE, srp + lsp)
+
+ def build_takeover(self, plsp_id, srp_id):
+ """PCInitiate taking over an orphaned LSP (RFC 8281 S6): only the
+ SRP and LSP objects, the LSP carrying the PCC's PLSP-ID (D set)"""
+ srp = self._obj(CLASS_SRP, 1, struct.pack(">II", 0, srp_id))
+ lsp = self._obj(CLASS_LSP, 1, struct.pack(">I", (plsp_id << 12) | 0x01))
+ return self._msg(MSG_INITIATE, srp + lsp)
+
+ def build_update(self, name, plsp_id, srp_id, label):
+ """PCUpd (RFC 8231 S6.2): SRP, LSP (D|A) with name, one-label ERO"""
+ srp_tlv = struct.pack(">HHBBBB", TLV_PATH_SETUP_TYPE, 4, 0, 0, 0, 1)
+ srp = self._obj(CLASS_SRP, 1, struct.pack(">II", 0, srp_id) + srp_tlv)
+
+ encoded = name.encode()
+ pad = (-len(encoded)) % 4
+ lsp_tlv = (
+ struct.pack(">HH", TLV_SYMBOLIC_NAME, len(encoded))
+ + encoded
+ + b"\x00" * pad
+ )
+ lsp = self._obj(
+ CLASS_LSP, 1, struct.pack(">I", (plsp_id << 12) | 0x09) + lsp_tlv
+ )
+
+ sid = (label << 12) & 0xFFFFFFFF
+ ero = self._obj(CLASS_ERO, 1, struct.pack(">BBBBI", 0x24, 8, 0x00, 0x09, sid))
+
+ return self._msg(MSG_UPDATE, srp + lsp + ero)
+
+ # ------------------------------------------------------------------
+ # Receive path
+ # ------------------------------------------------------------------
+ def handle_report(self, body):
+ """Walk a PCRpt's objects (the mirror of the builders above):
+ each starts with the common object header class(1) type(1)
+ length(2); the SRP object carries the echoed SRP-ID at body
+ offset 4, the LSP object packs PLSP-ID(20 bits)|flags(12 bits)
+ into its first word."""
+ index = 0
+ srp_id = None
+ while index + 4 <= len(body):
+ oclass = body[index]
+ # object header length field: bytes 2-3, includes the header
+ olen = struct.unpack(">H", body[index + 2 : index + 4])[0]
+ if olen < 4 or index + olen > len(body):
+ break
+ if oclass == CLASS_SRP and index + 12 <= len(body):
+ # SRP body: flags(4) then srp-id(4)
+ srp_id = struct.unpack(">I", body[index + 8 : index + 12])[0]
+ if oclass == CLASS_LSP and index + 8 <= len(body):
+ # LSP first word: PLSP-ID(20 bits) | flags(12 bits)
+ word0 = struct.unpack(">I", body[index + 4 : index + 8])[0]
+ plsp_id = word0 >> 12
+ flags = word0 & 0xFF
+ oper = (flags >> 4) & 0x07
+ lsp_error = None
+ name = None
+ tlv = index + 8
+ while tlv + 4 <= index + olen:
+ ttype, tlen = struct.unpack(">HH", body[tlv : tlv + 4])
+ if ttype == TLV_LSP_ERROR_CODE and tlen >= 4:
+ lsp_error = struct.unpack(">I", body[tlv + 4 : tlv + 8])[0]
+ if ttype == TLV_SYMBOLIC_NAME:
+ name = (
+ body[tlv + 4 : tlv + 4 + tlen]
+ .decode(errors="replace")
+ .rstrip("\x00")
+ )
+ tlv += 4 + tlen + (-tlen) % 4
+ self.log(
+ "REPORT plsp-id=%u flags=0x%02x oper=%u srp=%s lsp-error=%s"
+ % (plsp_id, flags, oper, srp_id, lsp_error)
+ )
+ if plsp_id == 0 and not flags & LSP_FLAG_SYNC:
+ self.sync_done = True
+ # For adopt: the PLSP-ID of each name the PCC reports
+ if name and plsp_id != 0:
+ self.plsp_by_report_name[name] = plsp_id
+ # A report echoing one of our SRP-IDs tells us the
+ # PLSP-ID the PCC assigned to that policy.
+ if srp_id in self.srp_to_name and plsp_id != 0:
+ name = self.srp_to_name[srp_id]
+ if name not in self.plsp_by_name:
+ self.plsp_by_name[name] = plsp_id
+ self.log("MAPPED name=%s plsp-id=%u" % (name, plsp_id))
+ index += olen
+
+ def handle_error(self, body):
+ """Log a PCErr: its PCEP-ERROR objects (class 13) carry the
+ error-type and error-value in the 3rd and 4th bytes of their
+ body, and an SRP object echoes the SRP-ID of the failed request.
+ The whole message is read first, so the SRP is found before or
+ after the PCEP-ERROR."""
+ index = 0
+ srp_id = None
+ errors = []
+ while index + 4 <= len(body):
+ oclass = body[index]
+ olen = struct.unpack(">H", body[index + 2 : index + 4])[0]
+ if olen < 4 or index + olen > len(body):
+ break
+ if oclass == CLASS_SRP and index + 12 <= len(body):
+ # SRP body: flags(4) then srp-id(4)
+ srp_id = struct.unpack(">I", body[index + 8 : index + 12])[0]
+ if oclass == CLASS_ERROR and index + 8 <= len(body):
+ # PCEP-ERROR body: reserved(1) flags(1) type(1) value(1)
+ errors.append((body[index + 6], body[index + 7]))
+ index += olen
+ for error_type, error_value in errors:
+ self.log(
+ "RECV-ERROR type=%u value=%u srp=%s name=%s"
+ % (error_type, error_value, srp_id, self.srp_to_name.get(srp_id))
+ )
+
+ def handle_request(self, body):
+ """Answer a PCReq (RFC 5440 section 6.4) with a PCRep echoing its
+ RP object and an ERO of the first policy's label"""
+ index = 0
+ while index + 4 <= len(body):
+ oclass = body[index]
+ olen = struct.unpack(">H", body[index + 2 : index + 4])[0]
+ if olen < 4 or index + olen > len(body):
+ break
+ if oclass == CLASS_RP and olen >= 12:
+ rp = body[index : index + olen]
+ # RP body: flags(4) then request-id(4)
+ req_id = struct.unpack(">I", rp[8:12])[0]
+ sid = (self.policies[0]["label"] << 12) & 0xFFFFFFFF
+ ero = self._obj(
+ CLASS_ERO, 1, struct.pack(">BBBBI", 0x24, 8, 0x00, 0x09, sid)
+ )
+ self.send(self._msg(MSG_REPLY, rp + ero))
+ self.log("REPLY-SENT req-id=%u" % req_id)
+ index += olen
+
+ def handle_message(self, mtype, body):
+ if mtype == MSG_OPEN:
+ self.log("RECV-OPEN")
+ elif mtype == MSG_KEEPALIVE:
+ self.log("RECV-KEEPALIVE")
+ elif mtype == MSG_REPORT:
+ self.handle_report(body)
+ elif mtype == MSG_ERROR:
+ self.handle_error(body)
+ elif mtype == MSG_REQUEST:
+ self.handle_request(body)
+ else:
+ self.log("RECV-TYPE-%u" % mtype)
+
+ def poll_commands(self):
+ """Act on new lines in the command file:
+
+ remove <name>
+ add <endpoint,label,name[,color]>
+ update <name,label>
+ adopt <name> (take over a path another PCE initiated, RFC 8281 S6)
+
+ add is only meaningful once the PCC's state-sync is done (pathd
+ silently discards earlier PCInitiates); the tests churn well
+ after session establishment.
+ """
+ if not self.args.command_file:
+ return
+ if not os.path.exists(self.args.command_file):
+ return
+
+ with open(self.args.command_file) as cmds:
+ lines = cmds.readlines()
+
+ # Retry removes whose PLSP-ID mapping had not arrived yet: the
+ # PCRpt that (re-)establishes it can still be in flight when the
+ # remove command lands.
+ deferred = self.deferred_removes
+ self.deferred_removes = []
+ for name in deferred:
+ self.send_remove(name)
+
+ for line in lines[self.command_pos :]:
+ self.command_pos += 1
+ fields = line.split()
+ if len(fields) == 2 and fields[0] == "remove":
+ self.send_remove(fields[1])
+ elif len(fields) == 2 and fields[0] == "adopt":
+ plsp_id = self.plsp_by_report_name.get(fields[1])
+ if plsp_id is None:
+ self.log("ADOPT-UNKNOWN name=%s" % fields[1])
+ continue
+ self.plsp_by_name[fields[1]] = plsp_id
+ srp_id = self.next_srp_id
+ self.next_srp_id += 1
+ self.send(self.build_takeover(plsp_id, srp_id))
+ self.log(
+ "ADOPT-SENT name=%s plsp-id=%u srp=%u"
+ % (fields[1], plsp_id, srp_id)
+ )
+ elif len(fields) == 2 and fields[0] == "update":
+ name, label = fields[1].split(",")
+ self.send_update(name, int(label))
+ elif len(fields) == 2 and fields[0] == "add":
+ try:
+ policy = parse_policy(fields[1])
+ except argparse.ArgumentTypeError:
+ self.log("ADD-BAD-SPEC %s" % fields[1])
+ continue
+ srp_id = self.next_srp_id
+ self.next_srp_id += 1
+ self.srp_to_name[srp_id] = policy["name"]
+ self.send(self.build_initiate(policy, srp_id))
+ self.log(
+ "ADD-SENT endpoint=%s label=%u name=%s color=%s"
+ % (
+ policy["endpoint"],
+ policy["label"],
+ policy["name"],
+ policy["color"],
+ )
+ )
+
+ def send_remove(self, name):
+ """Send a PCInitiate R-flag remove, deferring until the name's
+ PLSP-ID mapping is known."""
+ if name not in self.plsp_by_name:
+ self.log("REMOVE-DEFERRED name=%s" % name)
+ self.deferred_removes.append(name)
+ return
+ srp_id = self.next_srp_id
+ self.next_srp_id += 1
+ plsp_id = self.plsp_by_name.pop(name)
+ self.send(self.build_remove(name, plsp_id, srp_id))
+ self.log("REMOVE-SENT name=%s plsp-id=%u" % (name, plsp_id))
+
+ def send_update(self, name, label):
+ """Send a PCUpd for a mapped policy, or one the PCC reported"""
+ plsp_id = self.plsp_by_name.get(name, self.plsp_by_report_name.get(name))
+ if plsp_id is None:
+ self.log("UPDATE-UNKNOWN name=%s" % name)
+ return
+ srp_id = self.next_srp_id
+ self.next_srp_id += 1
+ self.send(self.build_update(name, plsp_id, srp_id, label))
+ self.log("UPDATE-SENT name=%s plsp-id=%u srp=%u" % (name, plsp_id, srp_id))
+
+ def send(self, data):
+ self.conn.sendall(data)
+
+ def reset_session_state(self):
+ # A reconnected PCC starts a new PCEP session: sync again, and
+ # replay the command file from the top. The tests restart a PCE
+ # with a fresh command file, so only a dropped session replays.
+ self.sync_done = False
+ self.initiated = False
+ self.next_srp_id = 1
+ self.srp_to_name = {}
+ self.plsp_by_name = {}
+ self.plsp_by_report_name = {}
+ self.command_pos = 0
+ self.deferred_removes = []
+
+ def run(self):
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.sock.bind((self.args.address, self.args.port))
+ self.sock.listen(1)
+ self.log("LISTENING %s:%u" % (self.args.address, self.args.port))
+
+ # Accept loop: a real PCE survives a session going down and lets
+ # the PCC reconnect. Without this a single transient drop ends
+ # the mock for good and strands pathd retrying a dead socket.
+ while True:
+ self.conn, peer = self.sock.accept()
+ self.log("CONNECT %s:%u" % peer)
+ self.reset_session_state()
+ try:
+ self.serve_session()
+ except OSError as e:
+ # Broken pipe / connection reset: the PCC went away. Log
+ # it and wait for the reconnect instead of crashing.
+ self.log("SESSION-ERROR err=%r" % e)
+ try:
+ self.conn.close()
+ except OSError:
+ pass
+ self.log("SESSION-END awaiting-reconnect")
+
+ def serve_session(self):
+ # Both Open-first and Keepalive-first orders are accepted by
+ # pceplib; send both back to back.
+ self.send(self.build_open())
+ self.send(self.build_keepalive())
+ self.log("SENT-OPEN-KEEPALIVE")
+
+ # Keepalives go out from this loop, which wakes at least every second
+ next_keepalive = time.monotonic() + KEEPALIVE_SECONDS
+ buffer = b""
+ while True:
+ readable, _, _ = select.select([self.conn], [], [], 1.0)
+
+ if time.monotonic() >= next_keepalive:
+ self.send(self.build_keepalive())
+ next_keepalive = time.monotonic() + KEEPALIVE_SECONDS
+
+ # Drain and process input BEFORE acting on commands, so a
+ # remove issued right after its policy's PCRpt does not race
+ # the mapping that report establishes.
+ if readable:
+ data = self.conn.recv(65536)
+ if not data:
+ self.log("DISCONNECT")
+ return
+ buffer += data
+ while len(buffer) >= 4:
+ # common message header length field: bytes 2-3,
+ # includes the 4-byte header itself
+ mlen = struct.unpack(">H", buffer[2:4])[0]
+ if mlen < 4 or len(buffer) < mlen:
+ break
+ self.handle_message(buffer[1], buffer[4:mlen])
+ buffer = buffer[mlen:]
+
+ # pathd discards PCInitiates received before its state sync
+ # completes, and a reconnect replays the command file from
+ # the top, so commands wait for the sync like the base
+ # policies do.
+ if not self.sync_done:
+ continue
+
+ if not self.initiated:
+ self.initiated = True
+ for policy in self.policies:
+ srp_id = self.next_srp_id
+ self.next_srp_id += 1
+ self.srp_to_name[srp_id] = policy["name"]
+ self.send(self.build_initiate(policy, srp_id))
+ self.log(
+ "INITIATE-SENT endpoint=%s label=%u name=%s color=%s"
+ % (
+ policy["endpoint"],
+ policy["label"],
+ policy["name"],
+ policy["color"],
+ )
+ )
+
+ self.poll_commands()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--address", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=4189)
+ parser.add_argument("--pcc-address", default="192.0.2.1")
+ parser.add_argument("--pcc-address6", default="2001:db8::1")
+ parser.add_argument("--endpoint")
+ parser.add_argument("--label", type=int)
+ parser.add_argument("--name", default="test-steer")
+ parser.add_argument("--color", type=int)
+ parser.add_argument(
+ "--policy",
+ action="append",
+ type=parse_policy,
+ help="endpoint,label,name[,color]; may be repeated",
+ )
+ parser.add_argument(
+ "--command-file",
+ help="poll this file for commands, one per line: 'remove <name>' "
+ "or 'add <endpoint,label,name[,color]>'",
+ )
+ parser.add_argument("--log", required=True)
+ args = parser.parse_args()
+
+ if not args.policy and not args.endpoint:
+ parser.error("at least one --policy or --endpoint is required")
+ if args.endpoint and args.label is None:
+ parser.error("--endpoint requires --label")
+
+ MockPce(args).run()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/topotests/pathd_pcep_names_topo1/rt1/frr.conf b/tests/topotests/pathd_pcep_names_topo1/rt1/frr.conf
new file mode 100644
index 0000000000..a7d61a2de8
--- /dev/null
+++ b/tests/topotests/pathd_pcep_names_topo1/rt1/frr.conf
@@ -0,0 +1,46 @@
+hostname rt1
+!
+interface lo
+ ip address 192.0.2.1/32
+ ipv6 address 2001:db8::1/128
+ ip router isis 1
+ ipv6 router isis 1
+ isis passive
+exit
+!
+interface eth-rt2
+ ip address 203.0.113.1/24
+ ipv6 address 2001:db8:10:1::1/64
+ ip router isis 1
+ ipv6 router isis 1
+ isis network point-to-point
+ isis hello-multiplier 10
+exit
+!
+ip forwarding
+ipv6 forwarding
+!
+router isis 1
+ net 49.0000.0000.0000.0001.00
+ is-type level-1
+ topology ipv6-unicast
+ segment-routing on
+ segment-routing global-block 16000 23999
+ segment-routing prefix 192.0.2.1/32 index 10
+ segment-routing prefix 2001:db8::1/128 index 11
+exit
+!
+segment-routing
+ traffic-eng
+ pcep
+ pce PCE1
+ address ip 127.0.0.1 port 4189
+ pce-initiated
+ exit
+ pcc
+ peer PCE1
+ exit
+ exit
+ exit
+exit
+!
diff --git a/tests/topotests/pathd_pcep_names_topo1/rt2/frr.conf b/tests/topotests/pathd_pcep_names_topo1/rt2/frr.conf
new file mode 100644
index 0000000000..591dfaa6f8
--- /dev/null
+++ b/tests/topotests/pathd_pcep_names_topo1/rt2/frr.conf
@@ -0,0 +1,32 @@
+hostname rt2
+!
+interface lo
+ ip address 192.0.2.2/32
+ ipv6 address 2001:db8::2/128
+ ip router isis 1
+ ipv6 router isis 1
+ isis passive
+exit
+!
+interface eth-rt1
+ ip address 203.0.113.2/24
+ ipv6 address 2001:db8:10:1::2/64
+ ip router isis 1
+ ipv6 router isis 1
+ isis network point-to-point
+ isis hello-multiplier 10
+exit
+!
+ip forwarding
+ipv6 forwarding
+!
+router isis 1
+ net 49.0000.0000.0000.0002.00
+ is-type level-1
+ topology ipv6-unicast
+ segment-routing on
+ segment-routing global-block 16000 23999
+ segment-routing prefix 192.0.2.2/32 index 20
+ segment-routing prefix 2001:db8::2/128 index 21
+exit
+!
diff --git a/tests/topotests/pathd_pcep_names_topo1/test_pathd_pcep_names_topo1.py b/tests/topotests/pathd_pcep_names_topo1/test_pathd_pcep_names_topo1.py
new file mode 100644
index 0000000000..b3356812f5
--- /dev/null
+++ b/tests/topotests/pathd_pcep_names_topo1/test_pathd_pcep_names_topo1.py
@@ -0,0 +1,783 @@
+#!/usr/bin/env python
+# SPDX-License-Identifier: ISC
+
+#
+# test_pathd_pcep_names_topo1.py
+#
+
+"""
+test_pathd_pcep_names_topo1.py:
+
+Verify how pathd handles the names of PCE-initiated SR policies and the
+PCEP session timeout.
+
+ +-------------+ +-------------+
+ | |eth-rt2 eth-rt1| |
+ | RT1 +-----------------------+ RT2 |
+ | 192.0.2.1 | 203.0.113.0/24 | 192.0.2.2 |
+ | 2001:db8::1 | 2001:db8:10:1::/64 | 2001:db8::2 |
+ +-------------+ +-------------+
+ |
+ mock PCE (127.0.0.1:4189, inside RT1's namespace)
+
+RT1 runs pathd with the PCEP module. A scripted PCE (mock_pce.py) runs
+inside RT1's network namespace and initiates two SR policies towards
+RT2's loopbacks, one per address family, each with a single prefix-SID
+label (IPv4: 16020, IPv6: 16021). The tests check that pathd refuses
+duplicate, too long and reserved names, reports a refused PCUpd in a
+PCRpt, and removes or hands over a PCE's paths at its session timeout.
+"""
+
+import os
+import re
+import sys
+import json
+import subprocess
+import pytest
+
+CWD = os.path.dirname(os.path.realpath(__file__))
+sys.path.append(os.path.join(CWD, "../"))
+
+# pylint: disable=C0413
+from lib import topotest
+from lib.topogen import Topogen, get_topogen
+from lib.topolog import logger
+
+pytestmark = [pytest.mark.isisd, pytest.mark.pathd]
+
+ENDPOINT = "192.0.2.2"
+LABEL = 16020
+
+ENDPOINT6 = "2001:db8::2"
+LABEL6 = 16021
+
+
+def build_topo(tgen):
+ "Build function"
+
+ for router in ["rt1", "rt2"]:
+ tgen.add_router(router)
+
+ switch = tgen.add_switch("s1")
+ switch.add_link(tgen.gears["rt1"], nodeif="eth-rt2")
+ switch.add_link(tgen.gears["rt2"], nodeif="eth-rt1")
+
+
+def setup_module(mod):
+ "Sets up the pytest environment"
+
+ tgen = Topogen(build_topo, mod.__name__)
+
+ # The test depends on IS-IS SR labels and MPLS steering routes.
+ if not tgen.hasmpls:
+ logger.info("MPLS is not available, skipping test")
+ pytest.skip("MPLS is not available, skipping")
+
+ tgen.start_topology()
+
+ # pathd is not inferred from frr.conf (there are no candidate paths,
+ # the policies are PCE-initiated) and needs the PCEP module, so it
+ # is named explicitly on rt1.
+ for rname, router in tgen.routers().items():
+ if rname == "rt1":
+ router.load_frr_config(extra_daemons=[("pathd", " -M pathd_pcep")])
+ else:
+ router.load_frr_config()
+
+ tgen.start_router()
+
+ # Start the scripted PCE inside rt1's network namespace. pathd
+ # retries the PCEP connection, so starting it after the routers
+ # is fine. The command file drives the churn tests: the PCE polls
+ # it for 'add'/'remove' lines.
+ start_pce()
+
+
+def teardown_module():
+ "Teardown the pytest environment"
+
+ tgen = get_topogen()
+ for name in list(PCES):
+ stop_mock_pce(name)
+ tgen.stop_topology()
+
+
+def print_pce_log():
+ "Dump the mock PCE's session log to the test log for debugging"
+
+ tgen = get_topogen()
+ pce_log = os.path.join(tgen.logdir, "rt1", "mock_pce.log")
+ try:
+ with open(pce_log) as log:
+ logger.info("mock PCE log:\n%s", log.read())
+ except IOError:
+ logger.info("mock PCE log %s not found", pce_log)
+
+
+def check_label_installed():
+ "Check that RT2's prefix-SID labels are in RT1's LFIB"
+
+ tgen = get_topogen()
+ output = json.loads(tgen.gears["rt1"].vtysh_cmd("show mpls table json"))
+ for label in [LABEL, LABEL6]:
+ if str(label) not in output:
+ return "label {} not in LFIB".format(label)
+ return None
+
+
+def test_isis_sr_convergence():
+ "Wait for IS-IS SR to install RT2's prefix-SID label on RT1"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ logger.info("waiting for labels %u and %u in rt1's LFIB", LABEL, LABEL6)
+ _, result = topotest.run_and_expect(check_label_installed, None, count=60, wait=1)
+ assert result is None, "IS-IS SR did not install labels: {}".format(result)
+
+
+# Bumped on every PCE restart so each PCE instance polls a fresh
+# command file instead of replaying the previous instance's history.
+PCE_GEN = [0]
+
+
+def pce_command_file():
+ "The current PCE instance's command file"
+
+ tgen = get_topogen()
+ suffix = "" if PCE_GEN[0] == 0 else "_{}".format(PCE_GEN[0])
+ return os.path.join(tgen.logdir, "rt1", "pce_commands" + suffix)
+
+
+# The running scripted PCEs, by log name
+PCES = {}
+
+
+def start_mock_pce(name, args):
+ "Start a scripted PCE in rt1's namespace, logging to <name>.log and <name>.err"
+
+ tgen = get_topogen()
+ logdir = os.path.join(tgen.logdir, "rt1")
+ command = [sys.executable, os.path.join(CWD, "mock_pce.py")] + args
+ command += ["--log", os.path.join(logdir, name + ".log")]
+ with open(os.path.join(logdir, name + ".err"), "a") as err:
+ PCES[name] = tgen.gears["rt1"].popen(
+ command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=err
+ )
+
+
+def stop_mock_pce(name):
+ "Stop a scripted PCE and wait for it, so that its port is free again"
+
+ proc = PCES.pop(name, None)
+ if proc is not None and proc.poll() is None:
+ proc.terminate()
+ proc.wait()
+
+
+def start_pce():
+ "Start PCE1, the scripted PCE on port 4189"
+
+ start_mock_pce(
+ "mock_pce",
+ [
+ "--policy",
+ "{},{},test-steer".format(ENDPOINT, LABEL),
+ "--policy",
+ "{},{},test-steer-v6".format(ENDPOINT6, LABEL6),
+ "--pcc-address",
+ "192.0.2.1",
+ "--pcc-address6",
+ "2001:db8::1",
+ "--command-file",
+ pce_command_file(),
+ ],
+ )
+
+
+def kill_pce():
+ "Stop PCE1"
+
+ stop_mock_pce("mock_pce")
+
+
+def pce_command(line):
+ "Append one command line for the mock PCE to act on"
+
+ with open(pce_command_file(), "a") as cmds:
+ cmds.write(line + "\n")
+
+
+def check_policy_count(expected):
+ "Check the number of Active SR-TE policies on RT1"
+
+ tgen = get_topogen()
+ active = tgen.gears["rt1"].vtysh_cmd("show sr-te policy").count("Active")
+ if active != expected:
+ return "expected {} Active policies, have {}".format(expected, active)
+ return None
+
+
+def mock_pce_log_text():
+ "The mock PCE's log so far (empty when not yet written)"
+
+ tgen = get_topogen()
+ try:
+ with open(os.path.join(tgen.logdir, "rt1", "mock_pce.log")) as log:
+ return log.read()
+ except IOError:
+ return ""
+
+
+def count_pce_errors(error_type, error_value):
+ "Number of PCErr messages of the given type/value the PCE received"
+
+ return mock_pce_log_text().count(
+ "RECV-ERROR type=%d value=%d" % (error_type, error_value)
+ )
+
+
+def get_plsp_id(name):
+ "The last PLSP-ID the PCC reported for the named policy"
+
+ matches = re.findall(
+ r"MAPPED name=%s plsp-id=(\d+)" % re.escape(name), mock_pce_log_text()
+ )
+ if not matches:
+ return None
+ return int(matches[-1])
+
+
+def segment_list_of(name):
+ "The segment list pathd made for the named PCEP path, <name>-<PLSP-ID>"
+
+ output = (
+ get_topogen()
+ .gears["rt1"]
+ .vtysh_cmd("show yang operational-data /frr-pathd:pathd with-config pathd")
+ )
+ names = sorted(set(re.findall(r'"(%s-\d+)"' % re.escape(name), output)))
+ return names[0] if len(names) == 1 else None
+
+
+def configure_segment_list(name, no=False):
+ "Configure (or unconfigure) an empty segment list on RT1"
+
+ tgen = get_topogen()
+ return tgen.gears["rt1"].vtysh_cmd(
+ """
+ configure terminal
+ segment-routing
+ traffic-eng
+ {}segment-list {}
+ """.format(
+ "no " if no else "", name
+ )
+ )
+
+
+def test_duplicate_symbolic_name_rejected():
+ "A PCInitiate reusing a live symbolic name must get PCErr 23/1"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ errors_before = count_pce_errors(23, 1)
+
+ # test-steer has been alive since setup; a different color makes
+ # this a create of a NEW LSP with an in-use name, not a
+ # re-initiate of the existing one.
+ logger.info("initiating a duplicate of test-steer (different color)")
+ pce_command("add {},{},test-steer,4242".format(ENDPOINT, LABEL))
+
+ check = lambda: (
+ None if count_pce_errors(23, 1) > errors_before else "no PCErr 23/1 yet"
+ )
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "duplicate name was not rejected: {}".format(result)
+
+ # Nothing new may have come up, and the session must still work.
+ result = check_policy_count(2)
+ assert result is None, result
+
+ logger.info("verifying the session still accepts a unique name")
+ pce_command("add {},{},post-dup-check,4243".format(ENDPOINT, LABEL))
+ check = lambda: check_policy_count(3)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ assert result is None, "session unusable after rejection: {}".format(result)
+
+ pce_command("remove post-dup-check")
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "cleanup remove failed: {}".format(result)
+
+
+def test_cli_rejected_on_pcep_name():
+ "Configuring a segment list named like a PCEP one must be refused"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ # A PCInitiate names the list "<name>-0" and a PCUpd renames it
+ # "<name>-<PLSP-ID>", so ask pathd
+ name = segment_list_of("test-steer")
+ assert name is not None, "no single segment list for test-steer"
+
+ logger.info("trying to configure segment list %s", name)
+ output = configure_segment_list(name)
+ assert "already exists" in output, "config of {} was not refused: {}".format(
+ name, output
+ )
+
+ running = tgen.gears["rt1"].vtysh_cmd("show running-config")
+ assert (
+ "segment-list %s" % name not in running
+ ), "refused segment list {} still appeared in the config".format(name)
+
+
+def test_reserved_prefix_rejected():
+ "Names starting with the reserved pcep-hash- prefix are refused"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ output = configure_segment_list("pcep-hash-cli")
+ assert "reserved for PCEP" in output, "reserved name was configured: {}".format(
+ output
+ )
+
+ errors_before = count_pce_errors(24, 1)
+ pce_command("add {},{},pcep-hash-pce,4350".format(ENDPOINT, LABEL))
+ check = lambda: (
+ None if count_pce_errors(24, 1) > errors_before else "no PCErr 24/1 yet"
+ )
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "reserved name was initiated: {}".format(result)
+ result = check_policy_count(2)
+ assert result is None, result
+
+
+def test_pcep_rejected_on_cli_name():
+ "A PCEP path whose segment list name is taken by config gets 24/1"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ # A PCInitiate-created segment list is named "<name>-0" (see the
+ # previous test), so taking that name in the configuration first
+ # makes the collision deterministic.
+ name = "cli-clash-0"
+ logger.info("configuring segment list %s to squat the name", name)
+ output = configure_segment_list(name)
+ assert (
+ "already exists" not in output
+ ), "config of {} was unexpectedly refused: {}".format(name, output)
+
+ errors_before = count_pce_errors(24, 1)
+ logger.info("initiating cli-clash against the squatted name")
+ pce_command("add {},{},cli-clash,4300".format(ENDPOINT, LABEL))
+ check = lambda: (
+ None if count_pce_errors(24, 1) > errors_before else "no PCErr 24/1 yet"
+ )
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "colliding path was not rejected: {}".format(result)
+ result = check_policy_count(2)
+ assert result is None, result
+
+ # Free the name: the same add must now succeed, and a remove
+ # returns the topology to its baseline.
+ logger.info("releasing %s and re-initiating", name)
+ configure_segment_list(name, no=True)
+ pce_command("add {},{},cli-clash,4300".format(ENDPOINT, LABEL))
+ check = lambda: check_policy_count(3)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "path did not recover after name was freed: {}".format(
+ result
+ )
+
+ pce_command("remove cli-clash")
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "final cleanup failed: {}".format(result)
+
+
+def test_long_symbolic_names():
+ "Names up to the supported length work; longer ones get PCErr 24/1"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ # pathd's policy, candidate and segment list names are limited to 64
+ # characters by its YANG model, and a PCEP path's segment list is
+ # named "<name>-<plsp_id>" with a PLSP-ID of up to 7 digits, so 56 is
+ # the longest symbolic name pathd accepts. Both lengths below are
+ # multiples of 4, so the SYMBOLIC-PATH-NAME TLV needs no padding.
+ name_max = "L" * 56
+ name_long = "L" * 60
+
+ logger.info("initiating a policy with a %d-byte name", len(name_max))
+ pce_command("add {},{},{},4501".format(ENDPOINT, LABEL, name_max))
+ check = lambda: check_policy_count(3)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "longest supported name did not come up: {}".format(result)
+
+ # The longest name must be readable back in full through the northbound
+ output = tgen.gears["rt1"].vtysh_cmd(
+ "show yang operational-data /frr-pathd:pathd with-config pathd"
+ )
+ assert name_max + "-0" in output, "pathd northbound data is not readable"
+
+ errors_before = count_pce_errors(24, 1)
+ logger.info("initiating a policy with a %d-byte name", len(name_long))
+ pce_command("add {},{},{},4502".format(ENDPOINT, LABEL, name_long))
+ check = lambda: (
+ None if count_pce_errors(24, 1) > errors_before else "no PCErr 24/1 yet"
+ )
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "over-long name was not rejected: {}".format(result)
+ result = check_policy_count(3)
+ assert result is None, result
+
+ pce_command("remove {}".format(name_max))
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "long-name cleanup failed: {}".format(result)
+
+
+def configure_dynamic_policy(name, color, no=False):
+ "Configure (or remove) a policy on RT1 whose candidate path the PCE computes"
+
+ policy = "policy color {} endpoint {}".format(color, ENDPOINT)
+ if no:
+ body = "no " + policy
+ else:
+ body = "{}\n name {}\n candidate-path preference 100 name dyn dynamic".format(
+ policy, name
+ )
+ get_topogen().gears["rt1"].vtysh_cmd(
+ "configure terminal\nsegment-routing\ntraffic-eng\n" + body
+ )
+
+
+def test_long_local_names_hashed():
+ "Configured paths whose segment list names do not fit get distinct hashes"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ # "<policy>-dyn-<PLSP-ID>" is over 64 characters, and the names only
+ # differ past the part a hashed segment list name keeps
+ names = ["hash-" + "x" * 53 + "-" + suffix for suffix in ["aa", "bb"]]
+ for color, name in enumerate(names, 4701):
+ configure_dynamic_policy(name, color)
+
+ # pathd asks the PCE to compute each path, and the mock answers
+ def check_hashed():
+ output = tgen.gears["rt1"].vtysh_cmd(
+ "show yang operational-data /frr-pathd:pathd with-config pathd"
+ )
+ hashed = set(
+ re.findall(r'"(pcep-hash-%s-[0-9a-f]{8}-\d+)"' % names[0][:34], output)
+ )
+ if len(hashed) != 2:
+ return "hashed segment lists: {}".format(sorted(hashed))
+ return None
+
+ _, result = topotest.run_and_expect(check_hashed, None, count=60, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, result
+
+ for color, name in enumerate(names, 4701):
+ configure_dynamic_policy(name, color, no=True)
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ assert result is None, "hash test policies not removed: {}".format(result)
+
+
+def test_pcupd_rejected_in_report():
+ "A refused PCUpd is reported in a PCRpt LSP-ERROR-CODE, not a PCErr"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ name = "upd-clash"
+ pce_command("add {},{},{},4600".format(ENDPOINT, LABEL, name))
+ check = lambda: None if get_plsp_id(name) else "no PLSP-ID for {} yet".format(name)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ assert result is None, result
+ check = lambda: check_policy_count(3)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ assert result is None, result
+
+ # The PCUpd renames "<name>-0" to "<name>-<plsp_id>": take that name first
+ plsp_id = get_plsp_id(name)
+ squat = "{}-{}".format(name, plsp_id)
+ output = configure_segment_list(squat)
+ assert "already exists" not in output, output
+
+ errors_before = mock_pce_log_text().count("RECV-ERROR type=24")
+ pce_command("update {},{}".format(name, LABEL))
+
+ def check_report():
+ sent = re.findall(
+ r"UPDATE-SENT name=%s plsp-id=\d+ srp=(\d+)" % re.escape(name),
+ mock_pce_log_text(),
+ )
+ if not sent:
+ return "PCUpd not sent yet"
+ expected = "REPORT plsp-id={} ".format(plsp_id)
+ for line in mock_pce_log_text().splitlines():
+ if expected in line and "srp={} lsp-error=4".format(sent[-1]) in line:
+ return None
+ return "no PCRpt with LSP-ERROR-CODE 4 for SRP {}".format(sent[-1])
+
+ _, result = topotest.run_and_expect(check_report, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, result
+ assert (
+ mock_pce_log_text().count("RECV-ERROR type=24") == errors_before
+ ), "a refused PCUpd must not be answered with PCErr type 24"
+ result = check_policy_count(3)
+ assert result is None, result
+
+ configure_segment_list(squat, no=True)
+ pce_command("remove {}".format(name))
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "cleanup remove failed: {}".format(result)
+
+
+def restart_pce():
+ "Start a new PCE instance and wait for it to initiate the base policies"
+
+ initiated = mock_pce_log_text().count("INITIATE-SENT")
+ PCE_GEN[0] += 1
+ start_pce()
+
+ def check_new_session():
+ sent = mock_pce_log_text().count("INITIATE-SENT") - initiated
+ return None if sent >= 2 else "new PCE sent {} of 2 base policies".format(sent)
+
+ _, result = topotest.run_and_expect(check_new_session, None, count=120, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "PCE session did not re-establish: {}".format(result)
+
+
+def sr_te_policies():
+ return get_topogen().gears["rt1"].vtysh_cmd("show sr-te policy")
+
+
+def test_orphans_removed_at_timeout():
+ "PCE-initiated paths are removed at the session timeout, freeing names"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ pce_command("add {},{},orphan-b,4800".format(ENDPOINT, LABEL))
+ check = lambda: check_policy_count(3)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ assert result is None, result
+
+ kill_pce()
+
+ # session-timeout-interval defaults to 30 seconds
+ check = lambda: (
+ None if "orphan-b" not in sr_te_policies() else "orphan-b still present"
+ )
+ _, result = topotest.run_and_expect(check, None, count=90, wait=1)
+ assert result is None, result
+
+ restart_pce()
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "base policies did not come back: {}".format(result)
+
+ # The name is free again: a different color is a new LSP, not a 23/1
+ errors_before = count_pce_errors(23, 1)
+ pce_command("add {},{},orphan-b,4801".format(ENDPOINT, LABEL))
+ check = lambda: check_policy_count(3)
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ if result is not None:
+ print_pce_log()
+ assert result is None, "freed name was not reusable: {}".format(result)
+ assert count_pce_errors(23, 1) == errors_before, "got PCErr 23/1"
+
+ pce_command("remove orphan-b")
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "cleanup remove failed: {}".format(result)
+
+
+def configure_pce2(no=False):
+ "Add or remove a second PCE, PCE2, on port 4190"
+
+ pce = "pce PCE2\n address ip 127.0.0.1 port 4190\n pce-initiated\n exit"
+ peer = "pcc\n peer PCE2\n exit"
+ # The PCE must exist before the PCC peers with it
+ steps = ["pcc\n no peer PCE2\n exit", "no pce PCE2"] if no else [pce, peer]
+ for step in steps:
+ get_topogen().gears["rt1"].vtysh_cmd(
+ "configure terminal\nsegment-routing\ntraffic-eng\npcep\n" + step
+ )
+
+
+def test_session_timeout_per_pce():
+ "A PCE's session timeout removes its own paths, unless another PCE adopted them"
+
+ tgen = get_topogen()
+ if tgen.routers_have_failure():
+ pytest.skip(tgen.errors)
+
+ rt1 = tgen.gears["rt1"]
+ pce2_log = os.path.join(tgen.logdir, "rt1", "mock_pce2.log")
+ pce2_commands = os.path.join(tgen.logdir, "rt1", "pce2_commands")
+
+ def pce2_command(line):
+ with open(pce2_commands, "a") as cmds:
+ cmds.write(line + "\n")
+
+ def pce2_log_text():
+ try:
+ with open(pce2_log) as log:
+ return log.read()
+ except IOError:
+ return ""
+
+ def present(name, expected=True):
+ if (name in sr_te_policies()) == expected:
+ return None
+ return "{} {}".format(name, "missing" if expected else "still present")
+
+ def last_srp(kind, name):
+ sent = re.findall(
+ r"{}-SENT name={} plsp-id=\d+ srp=(\d+)".format(kind, name),
+ pce2_log_text(),
+ )
+ return sent[-1] if sent else None
+
+ def answered(srp):
+ "'ok' for a PCRpt echoing srp, 'error' for a PCErr, else None"
+ if "srp={} lsp-error=None".format(srp) in pce2_log_text():
+ return "ok"
+ if re.search(
+ r"RECV-ERROR type=\d+ value=\d+ srp={} ".format(srp), pce2_log_text()
+ ):
+ return "error"
+ return None
+
+ # PCE1 initiates two paths: PCE2 adopts one and only updates the other
+ pce_command("add {},{},taken-path,4901".format(ENDPOINT, LABEL))
+ pce_command("add {},{},lost-path,4902".format(ENDPOINT, LABEL))
+ for name in ["taken-path", "lost-path"]:
+ _, result = topotest.run_and_expect(
+ lambda: present(name), None, count=30, wait=1
+ )
+ assert result is None, result
+
+ configure_pce2()
+ start_mock_pce(
+ "mock_pce2",
+ [
+ "--port",
+ "4190",
+ "--policy",
+ "{},{},pce2-path,4900".format(ENDPOINT, LABEL),
+ "--command-file",
+ pce2_commands,
+ ],
+ )
+ _, result = topotest.run_and_expect(
+ lambda: present("pce2-path"), None, count=60, wait=1
+ )
+ assert result is None, result
+
+ # PCE1 is up, so its paths are not orphans: 19/1 (RFC 8281 section 5.4)
+ pce2_command("adopt test-steer")
+ _, result = topotest.run_and_expect(
+ lambda: (
+ None
+ if "RECV-ERROR type=19 value=1" in pce2_log_text()
+ else "no PCErr 19/1 for adopting a path of a connected PCE"
+ ),
+ None,
+ count=30,
+ wait=1,
+ )
+ assert result is None, result
+
+ # Only PCE1 goes away; its timeout must fire while PCE2 is connected
+ kill_pce()
+
+ def until_accepted(kind, name, command):
+ "Resend command until pathd accepts it, as PCE1 may not be seen down yet"
+
+ def check():
+ srp = last_srp(kind, name)
+ state = answered(srp) if srp else "error"
+ if state == "ok":
+ return None
+ if state == "error":
+ pce2_command(command)
+ return "{} of {} not accepted yet".format(kind, name)
+
+ _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+ assert result is None, result
+
+ until_accepted("ADOPT", "taken-path", "adopt taken-path")
+ until_accepted("UPDATE", "lost-path", "update lost-path,{}".format(LABEL))
+
+ _, result = topotest.run_and_expect(
+ lambda: present("test-steer", False), None, count=90, wait=1
+ )
+ assert result is None, result
+ assert present("pce2-path") is None, "PCE1's session timeout removed pce2-path"
+ assert present("taken-path") is None, "PCE1's session timeout removed taken-path"
+ assert present("lost-path", False) is None, "lost-path survived without adoption"
+
+ # Removing PCE2 from the configuration removes its paths right away,
+ # well before a session timeout could
+ configure_pce2(no=True)
+ for name in ["pce2-path", "taken-path"]:
+ _, result = topotest.run_and_expect(
+ lambda: present(name, False), None, count=10, wait=1
+ )
+ assert result is None, result
+
+ stop_mock_pce("mock_pce2")
+ restart_pce()
+ check = lambda: check_policy_count(2)
+ _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+ assert result is None, "base policies did not come back: {}".format(result)
+
+
+def test_memory_leak():
+ "Run the memory leak test and report results."
+
+ tgen = get_topogen()
+ if not tgen.is_memleak_enabled():
+ pytest.skip("Memory leak test/report is disabled")
+ tgen.report_memory_leaks()