Commit 12fb48eff0 for frr

commit 12fb48eff089f2b4127eae76dbc331a6399b95df
Author: Lincoln Thurlow <lincoln@isi.edu>
Date:   Mon Nov 30 14:02:54 2026 -0800

    tests: add pathd PCEP steering topotests

    This set of topotests adds a topology test for validating pathd
    steering of pcep-initiated policies. The tests creates a scripted
    pce (mock_pce.py) that implements a minimal viable PCEP, and sends
    Open, Keepalive, and PCInitiate messages.  The purpose of the tests
    are to validate pathd is installing per-destination steering for
    policies initiated by a PCE, withdrawing it when a policy goes down
    or is deleted, and keeping it while other policies at the same
    endpoint remain.  They also check the route's SR-TE colors, the
    multipath cap, and a replacement zebra cannot install.  The tests use
    the RFC 5737 addresses recommended in topotests.rst, and
    load_frr_config.

    Signed-off-by: Lincoln Thurlow <lincoln@isi.edu>

diff --git a/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py b/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py
new file mode 100644
index 0000000000..992ef373a9
--- /dev/null
+++ b/tests/topotests/pathd_pcep_steering_topo1/mock_pce.py
@@ -0,0 +1,524 @@
+#!/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_REPORT = 10
+MSG_UPDATE = 11
+MSG_INITIATE = 12
+
+CLASS_OPEN = 1
+CLASS_ENDPOINTS = 4
+CLASS_ERO = 7
+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_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.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
+    #
+    # Every builder assembles the exact RFC wire layout with
+    # struct.pack().  The format strings read left to right, one field
+    # per letter: ">" = network (big-endian) byte order, "B" = 1 byte,
+    # "H" = 2 bytes, "I" = 4 bytes.  Fields packed into part of a byte
+    # or word (flags, PLSP-ID) are shifted/OR'd together first, since
+    # pack() only handles whole-byte fields.
+    # ------------------------------------------------------------------
+    @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 = Delegate|Administrative)
+        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_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
+                self.log(
+                    "REPORT plsp-id=%u flags=0x%02x oper=%u srp=%s"
+                    % (plsp_id, flags, oper, srp_id)
+                )
+                if plsp_id == 0 and not flags & LSP_FLAG_SYNC:
+                    self.sync_done = True
+                # 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_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)
+        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>
+
+        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] == "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"""
+        if name not in self.plsp_by_name:
+            self.log("UPDATE-UNKNOWN name=%s" % name)
+            return
+        srp_id = self.next_srp_id
+        self.next_srp_id += 1
+        plsp_id = self.plsp_by_name[name]
+        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 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))
+
+        self.conn, peer = self.sock.accept()
+        self.log("CONNECT %s:%u" % peer)
+
+        # 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:]
+
+            self.poll_commands()
+
+            if self.sync_done and 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"],
+                        )
+                    )
+
+
+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_steering_topo1/rt1/frr.conf b/tests/topotests/pathd_pcep_steering_topo1/rt1/frr.conf
new file mode 100644
index 0000000000..a7d61a2de8
--- /dev/null
+++ b/tests/topotests/pathd_pcep_steering_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_steering_topo1/rt2/frr.conf b/tests/topotests/pathd_pcep_steering_topo1/rt2/frr.conf
new file mode 100644
index 0000000000..591dfaa6f8
--- /dev/null
+++ b/tests/topotests/pathd_pcep_steering_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_steering_topo1/test_pathd_pcep_steering_topo1.py b/tests/topotests/pathd_pcep_steering_topo1/test_pathd_pcep_steering_topo1.py
new file mode 100644
index 0000000000..8c20f43e25
--- /dev/null
+++ b/tests/topotests/pathd_pcep_steering_topo1/test_pathd_pcep_steering_topo1.py
@@ -0,0 +1,620 @@
+#!/usr/bin/env python
+# SPDX-License-Identifier: ISC
+
+#
+# test_pathd_pcep_steering_topo1.py
+#
+
+"""
+test_pathd_pcep_steering_topo1.py:
+
+Verify that pathd installs a per-destination steering route for a
+PCE-initiated SR policy, withdraws it when the policy goes down, and
+reinstalls it when the policy comes back up.
+
+         +-------------+                       +-------------+
+         |             |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 is the SR-TE headend running 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).  Once IS-IS SR has installed the labels, the policies come up
+and pathd is expected to install the steering routes:
+
+    192.0.2.2/32     proto srte distance 10, resolving via SR-TE color
+    2001:db8::2/128  proto srte distance 10, resolving via SR-TE color
+
+The later tests check the route with hundreds of policies, at zebra's
+multipath limit (the lowest colors steer), when zebra cannot replace a
+policy, and when the PCE deletes the policies.
+"""
+
+import os
+import re
+import sys
+import json
+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"
+PREFIX = "192.0.2.2/32"
+LABEL = 16020
+
+ENDPOINT6 = "2001:db8::2"
+PREFIX6 = "2001:db8::2/128"
+LABEL6 = 16021
+
+# Churn scale: policies created per address family beyond the two
+# initial ones, colors well away from the initiated-policy default (1)
+# and disjoint between the families.
+CHURN_COUNT = 100
+CHURN_COLOR_BASE = 1000
+CHURN_COLOR_BASE6 = 2000
+# Colors for the multipath cap and failed replace tests, clear of churn
+CAP_COLOR_BASE = 5000
+SIBLING_COLOR = 4000
+# In the SRGB but no prefix-SID uses it, so a policy on it cannot resolve
+UNUSED_LABEL = 16999
+
+
+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.
+    pce_log = os.path.join(tgen.logdir, "rt1", "mock_pce.log")
+    pce_commands = os.path.join(tgen.logdir, "rt1", "pce_commands")
+    tgen.gears["rt1"].run(
+        "nohup python3 {}/mock_pce.py "
+        "--policy {},{},test-steer "
+        "--policy {},{},test-steer-v6 "
+        "--pcc-address 192.0.2.1 --pcc-address6 2001:db8::1 "
+        "--command-file {} "
+        "--log {} > /dev/null 2>&1 &".format(
+            CWD, ENDPOINT, LABEL, ENDPOINT6, LABEL6, pce_commands, pce_log
+        )
+    )
+
+
+def teardown_module():
+    "Teardown the pytest environment"
+
+    tgen = get_topogen()
+    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 check_steering_route_af(present, prefix, show_cmd):
+    "Check one address family's steering route on RT1"
+
+    tgen = get_topogen()
+    output = json.loads(
+        tgen.gears["rt1"].vtysh_cmd("{} {} json".format(show_cmd, prefix))
+    )
+    routes = [
+        route for route in output.get(prefix, []) if route.get("protocol") == "srte"
+    ]
+
+    if not present:
+        if routes:
+            return "steering route for {} still present".format(prefix)
+        return None
+
+    if not routes:
+        return "no srte route for {}".format(prefix)
+
+    route = routes[0]
+    if route.get("distance") != 10:
+        return "wrong distance for {}: {}".format(prefix, route.get("distance"))
+    if not route.get("installed"):
+        return "steering route for {} not installed".format(prefix)
+    if not any(nh.get("active") for nh in route.get("nexthops", [])):
+        return "no active nexthop for {}".format(prefix)
+
+    return None
+
+
+def check_steering_route(present):
+    "Check the presence/absence of both steering routes on RT1"
+
+    result = check_steering_route_af(present, PREFIX, "show ip route")
+    if result is not None:
+        return result
+
+    return check_steering_route_af(present, PREFIX6, "show ipv6 route")
+
+
+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)
+
+
+def test_steering_route_installed():
+    "PCE initiates the policy; pathd must install the steering route"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    logger.info("waiting for the PCEP session, PCInitiate and steering route")
+    check = lambda: check_steering_route(True)
+    _, result = topotest.run_and_expect(check, None, count=120, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "steering route missing: {}".format(result)
+
+    # Each route carries its policy's SR-TE color
+    for v6 in (False, True):
+        result = check_steering_colors([base_color(v6)], v6)
+        assert result is None, result
+
+
+def test_steering_route_withdrawn_on_policy_down():
+    "Take the policy down; pathd must withdraw the steering route"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    logger.info("shutting down rt2's eth-rt1")
+    tgen.gears["rt2"].vtysh_cmd(
+        """
+        configure terminal
+         interface eth-rt1
+          shutdown
+        """
+    )
+
+    check = lambda: check_steering_route(False)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "steering route not withdrawn: {}".format(result)
+
+
+def test_steering_route_reinstalled_on_policy_up():
+    "Bring the policy back up; pathd must reinstall the steering route"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    logger.info("bringing rt2's eth-rt1 back up")
+    tgen.gears["rt2"].vtysh_cmd(
+        """
+        configure terminal
+         interface eth-rt1
+          no shutdown
+        """
+    )
+
+    check = lambda: check_steering_route(True)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "steering route not reinstalled: {}".format(result)
+
+
+def pce_command(line):
+    "Append one command line for the mock PCE to act on"
+
+    tgen = get_topogen()
+    with open(os.path.join(tgen.logdir, "rt1", "pce_commands"), "a") as cmds:
+        cmds.write(line + "\n")
+
+
+def churn_name(i, v6=False):
+    return "churn6-{}".format(i) if v6 else "churn-{}".format(i)
+
+
+def churn_add(i, v6=False):
+    "Ask the PCE to initiate one churn policy for the family's endpoint"
+
+    endpoint = ENDPOINT6 if v6 else ENDPOINT
+    label = LABEL6 if v6 else LABEL
+    color = (CHURN_COLOR_BASE6 if v6 else CHURN_COLOR_BASE) + i
+    pce_command("add {},{},{},{}".format(endpoint, label, churn_name(i, v6), color))
+
+
+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 policy_colors():
+    "Each SR-TE policy on RT1 by name: (color, is Active)"
+
+    output = get_topogen().gears["rt1"].vtysh_cmd("show sr-te policy")
+    policies = {}
+    for line in output.splitlines():
+        fields = line.split()
+        if len(fields) == 5 and fields[4] in ("Active", "Inactive"):
+            if fields[1].isdigit():
+                policies[fields[2]] = (int(fields[1]), fields[4] == "Active")
+    return policies
+
+
+def base_color(v6=False):
+    "The color of the family's initial policy"
+
+    return policy_colors()["test-steer-v6" if v6 else "test-steer"][0]
+
+
+def steering_colors(v6=False):
+    """The SR-TE colors of RT1's steering route for the family (None if
+    absent).  The route's nexthops are recursive (endpoint via endpoint,
+    resolved through the policy); zebra's JSON flattens each recursive
+    parent and its resolved nexthop into the same array, so read only
+    the parents."""
+
+    prefix = PREFIX6 if v6 else PREFIX
+    show_cmd = "show ipv6 route" if v6 else "show ip route"
+    tgen = get_topogen()
+    output = json.loads(
+        tgen.gears["rt1"].vtysh_cmd("{} {} json".format(show_cmd, prefix))
+    )
+    routes = [
+        route for route in output.get(prefix, []) if route.get("protocol") == "srte"
+    ]
+    if not routes:
+        return None
+    nexthops = routes[0].get("nexthops", [])
+    return sorted(nh.get("srteColor") for nh in nexthops if nh.get("recursive"))
+
+
+def ecmp_max():
+    "zebra's runtime multipath limit, which caps the route's nexthops"
+
+    tgen = get_topogen()
+    output = tgen.gears["rt1"].vtysh_cmd("show zebra")
+    match = re.search(r"ECMP Maximum\s*\|?\s*(\d+)", output)
+    assert match is not None, "cannot read ECMP Maximum from 'show zebra'"
+    return int(match.group(1))
+
+
+def check_steering_colors(colors, v6=False):
+    "Check the family's steering route carries the lowest colors, up to the cap"
+
+    prefix = PREFIX6 if v6 else PREFIX
+    expected = sorted(colors)[: ecmp_max()]
+    have = steering_colors(v6)
+    if have != expected:
+        return "expected colors {} on {}, have {}".format(
+            short_colors(expected), prefix, short_colors(have)
+        )
+    return None
+
+
+def short_colors(colors):
+    "A short form of a color list for failure messages"
+
+    if colors is None or len(colors) <= 6:
+        return colors
+    return "{} colors {}..{}".format(len(colors), colors[:3], colors[-3:])
+
+
+def churn_colors(count, v6=False):
+    "The colors of the family's initial policy and its first count churn ones"
+
+    churn_base = CHURN_COLOR_BASE6 if v6 else CHURN_COLOR_BASE
+    return [base_color(v6)] + [churn_base + i for i in range(count)]
+
+
+def check_churn_colors_both(count):
+    "Check both families' steering routes after count churn policies each"
+
+    result = check_steering_colors(churn_colors(count, v6=False), v6=False)
+    if result is not None:
+        return result
+
+    return check_steering_colors(churn_colors(count, v6=True), v6=True)
+
+
+def test_policy_churn_scale():
+    "Initiate CHURN_COUNT extra policies per family for the endpoints"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    logger.info(
+        "initiating %u churn policies each for %s and %s",
+        CHURN_COUNT,
+        ENDPOINT,
+        ENDPOINT6,
+    )
+    for i in range(CHURN_COUNT):
+        churn_add(i, v6=False)
+        churn_add(i, v6=True)
+
+    # 2 initial policies + CHURN_COUNT churn ones per family
+    check = lambda: check_policy_count(2 + 2 * CHURN_COUNT)
+    _, result = topotest.run_and_expect(check, None, count=180, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "churn policies never came up: {}".format(result)
+
+    # Each endpoint now has 1 + CHURN_COUNT policies; its steering route
+    # aggregates one colored nexthop per policy, capped at the multipath
+    # limit (colors beyond it are logged and unrepresented).
+    check = lambda: check_churn_colors_both(CHURN_COUNT)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "steering route wrong after churn add: {}".format(result)
+
+
+def test_policy_churn_remove_readd():
+    "Remove a subset, re-add some of it, then remove all churn policies"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    # Remove the first 40 churn policies of each family.
+    logger.info("removing 40 churn policies per family")
+    for i in range(40):
+        pce_command("remove {}".format(churn_name(i, v6=False)))
+        pce_command("remove {}".format(churn_name(i, v6=True)))
+
+    check = lambda: check_policy_count(2 + 2 * (CHURN_COUNT - 40))
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "churn remove failed: {}".format(result)
+
+    # Re-add 20 of them per family (same names, same colors): pathd
+    # hands back the PLSP-IDs it retained for these keys.
+    logger.info("re-adding 20 churn policies per family")
+    for i in range(20):
+        churn_add(i, v6=False)
+        churn_add(i, v6=True)
+
+    check = lambda: check_policy_count(2 + 2 * (CHURN_COUNT - 40 + 20))
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "churn re-add failed: {}".format(result)
+
+    # Remove every churn policy; only the two initial ones remain, and
+    # both steering routes must collapse back to a single nexthop.
+    logger.info("removing all churn policies")
+    for v6 in (False, True):
+        for i in range(20):
+            pce_command("remove {}".format(churn_name(i, v6)))
+        for i in range(40, CHURN_COUNT):
+            pce_command("remove {}".format(churn_name(i, v6)))
+
+    check = lambda: check_policy_count(2)
+    _, result = topotest.run_and_expect(check, None, count=120, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "churn teardown failed: {}".format(result)
+
+    check = lambda: check_churn_colors_both(0)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "steering route wrong after churn teardown: {}".format(
+        result
+    )
+
+
+def pathd_log_text():
+    "RT1's pathd log so far"
+
+    tgen = get_topogen()
+    with open(os.path.join(tgen.logdir, "rt1", "pathd.log")) as log:
+        return log.read()
+
+
+def test_steering_route_multipath_cap():
+    "One policy more than the multipath limit: the highest color waits"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    cap = ecmp_max()
+    names = ["cap-{}".format(i) for i in range(cap)]
+    colors = [base_color()] + [CAP_COLOR_BASE + i for i in range(cap)]
+
+    logger.info(
+        "initiating %u policies for %s (multipath limit %u)", cap, ENDPOINT, cap
+    )
+    for i, name in enumerate(names):
+        pce_command("add {},{},{},{}".format(ENDPOINT, LABEL, name, CAP_COLOR_BASE + i))
+
+    check = lambda: check_policy_count(2 + cap)
+    _, result = topotest.run_and_expect(check, None, count=300, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "cap policies never came up: {}".format(result)
+
+    # The route carries the lowest cap colors; pathd logs the one left out
+    check = lambda: check_steering_colors(colors)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "steering route wrong at the cap: {}".format(result)
+    assert "not represented" in pathd_log_text(), "pathd did not log the cap"
+
+    # An included color goes: the color left out takes its place
+    logger.info("removing an included color")
+    pce_command("remove {}".format(names[0]))
+    colors.remove(CAP_COLOR_BASE)
+    check = lambda: check_steering_colors(colors)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "left out color not promoted: {}".format(result)
+
+    logger.info("removing the cap policies")
+    for name in names[1:]:
+        pce_command("remove {}".format(name))
+    check = lambda: check_policy_count(2)
+    _, result = topotest.run_and_expect(check, None, count=300, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "cap teardown failed: {}".format(result)
+
+    check = lambda: check_steering_colors([base_color()])
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "steering route wrong after cap teardown: {}".format(result)
+
+
+def test_steering_route_failed_replace():
+    "A policy zebra cannot replace leaves the route; its sibling color stays"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    base = base_color()
+    logger.info("initiating a sibling policy for %s", ENDPOINT)
+    pce_command("add {},{},sibling,{}".format(ENDPOINT, LABEL, SIBLING_COLOR))
+    check = lambda: check_steering_colors([base, SIBLING_COLOR])
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "sibling not in the steering route: {}".format(result)
+
+    # zebra cannot resolve the new first label, so it reports the policy
+    # down while pathd has it GOING_UP
+    logger.info("replacing test-steer with unresolvable label %u", UNUSED_LABEL)
+    pce_command("update test-steer,{}".format(UNUSED_LABEL))
+
+    def check_replace_failed():
+        if policy_colors()["test-steer"][1]:
+            return "test-steer still Active"
+        return check_steering_colors([SIBLING_COLOR])
+
+    _, result = topotest.run_and_expect(check_replace_failed, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "failed replace not withdrawn: {}".format(result)
+
+    logger.info("replacing test-steer with label %u again", LABEL)
+    pce_command("update test-steer,{}".format(LABEL))
+
+    def check_replace_ok():
+        if not policy_colors()["test-steer"][1]:
+            return "test-steer not Active"
+        return check_steering_colors([base, SIBLING_COLOR])
+
+    _, result = topotest.run_and_expect(check_replace_ok, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "valid replace not reinstalled: {}".format(result)
+
+    pce_command("remove sibling")
+    check = lambda: check_steering_colors([base])
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "sibling not removed: {}".format(result)
+
+
+def test_steering_route_withdrawn_on_policy_delete():
+    "The PCE deletes the last policy per endpoint; the steering route goes"
+
+    tgen = get_topogen()
+    if tgen.routers_have_failure():
+        pytest.skip(tgen.errors)
+
+    # The churn teardown left only the initial policies, still steering
+    check = lambda: check_steering_route(True)
+    _, result = topotest.run_and_expect(check, None, count=30, wait=1)
+    assert result is None, "steering route missing before delete: {}".format(result)
+
+    logger.info("removing test-steer and test-steer-v6")
+    pce_command("remove test-steer")
+    pce_command("remove test-steer-v6")
+
+    check = lambda: check_policy_count(0)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    if result is not None:
+        print_pce_log()
+    assert result is None, "policies not deleted: {}".format(result)
+
+    check = lambda: check_steering_route(False)
+    _, result = topotest.run_and_expect(check, None, count=60, wait=1)
+    assert result is None, "steering route not withdrawn: {}".format(result)
+
+
+if __name__ == "__main__":
+    args = ["-s"] + sys.argv[1:]
+    sys.exit(pytest.main(args))