Two SONiC switches, one BGP session, and a first PR
SONiC is the open-source network OS that runs on whitebox switches in hyperscaler data centers. What pulled me in was not the networking. It was the architecture: all configuration lives in Redis, and a set of containers subscribe to changes on it. Coming from Kafka, that shape was immediately familiar. It is pub/sub over shared state.
I didn't want to read about it though. I wanted two switches talking BGP on my machine, and then I wanted to change something real in the codebase. This is both halves of that. An afternoon of lab work, then a fix for a bug that had been sitting open since 2019.
If you also come from software rather than networking, some of the "obvious" facts below were not obvious to me at all, so I am writing the version I would have wanted.
Part one: the lab
The tool that makes this painless is containerlab. Think docker-compose for network topologies. It came out of Nokia — they needed a way to test their own container-based NOS. You describe nodes and the links between them in YAML and it wires up the "cables" as veth pairs.
My topology is two nodes and one link:
sonic1 sonic2
AS 65001 AS 65002
lo 10.10.10.1/32 lo 10.10.10.2/32
Ethernet0 192.168.1.1/24 <--eBGP--> Ethernet0 192.168.1.2/24
name: sonic-bgp
mgmt:
network: sonic-mgmt
ipv4-subnet: 172.30.30.0/24
topology:
kinds:
sonic-vs:
image: docker-sonic-vs:latest
nodes:
sonic1: { kind: sonic-vs, mgmt-ipv4: 172.30.30.11 }
sonic2: { kind: sonic-vs, mgmt-ipv4: 172.30.30.12 }
links:
- endpoints: ["sonic1:eth1", "sonic2:eth1"]
eth0 is the management interface and containerlab assigns it. eth1 is the first front-panel port, which SONiC calls Ethernet0, and that is the one we configure by hand.
The friction is getting the image. There is no clean docker pull from an official registry. The docker-sonic-vs.gz you want lives either on the unofficial sonic.software mirror or, when that is down, several scrolls deep in the artifacts of an Azure pipeline. I spent longer on this than on the actual lab. It is also a fair preview of the ecosystem, and a cheap way to find out early whether the domain annoys you or not.
Once it is loaded and tagged, one command:
sudo containerlab deploy -t sonic-bgp.clab.yml
Then addresses on each node. This goes through the SONiC config CLI and not ip addr add, because the orchestration layer will overwrite anything written straight to the kernel. Config goes through the database or it does not count.
config interface startup Ethernet0
config interface ip add Ethernet0 192.168.1.1/24
config interface ip add Loopback0 10.10.10.1/32
BGP goes through vtysh, the CLI of FRR, which is the routing engine running inside SONiC:
router bgp 65001
bgp router-id 10.10.10.1
neighbor 192.168.1.2 remote-as 65002
address-family ipv4 unicast
network 10.10.10.1/32
"Established", and nothing works
I checked the session and got this:
Neighbor V AS ... State/PfxRcd
192.168.1.2 4 65002 ... (Policy)
Established, up for minutes — and both routing tables empty. Zero prefixes. I assumed I had broken something in the config and spent a while re-reading it. The neighbour detail is where the answer was:
0 accepted, 0 sent prefixes
Inbound updates discarded due to missing policy
Outbound updates discarded due to missing policy
A BGP session being up tells you the two routers are talking. It does not tell you they are saying anything. Those are two separate layers. The session is a TCP connection on port 179 plus the BGP handshake. The prefix exchange on top of it is governed by policy, and one can be fine while the other moves nothing.
The rule behind this is RFC 8212. In this lab, FRR required explicit import and export policies for eBGP. That behavior is controlled by bgp ebgp-requires-policy: FRR documents it as enabled by default for the traditional profile and disabled for the datacenter profile. It is not a universal default across all FRR configurations. FRR BGP documentation. "No policy" is not a permissive default, it is a deny-all. Sessions with no policy used to leak routes and break large parts of the internet, so at some point the default got flipped.
I was glad to hit this. In a data center fabric you want explicit control over what leaks where.
What a loopback actually is
Before fixing the policy I had to sort out something that had been quietly confusing me.
I knew 127.0.0.1, the loopback that never leaves your machine. So when I saw Loopback0 10.10.10.1/32 on a switch I assumed it was the same kind of thing and therefore unroutable. That is wrong. They share a name for historical reasons, and behave differently. 127.0.0.1 is deliberately host-local. A router loopback is a normal routable address that happens to live on a virtual interface, one with no cable attached to it.
The "no cable" part is the whole point. A physical interface is up only while there is carrier on its cable. Pull the cable and its IP is unreachable. A loopback has nothing to pull, so it stays up as long as the switch is alive, which makes it a stable identity for the router.
In a real fabric a switch has many links, and you want one identity that is reachable through any of them. If a link dies the switch is still there under the same address. In a two-node lab that is not strictly necessary, but it is the mechanism I wanted to see working.
Next-hop
IP routing is hop-by-hop. Each router knows the next step and not the whole path. A route reads 10.10.10.1/32 via 192.168.1.1. The destination is where the packet eventually goes, the next-hop is who I hand it to right now. The destination here is a loopback, and is not directly connected to me. The next-hop is the neighbour's physical IP — which is. So I hand the packet to something I can actually reach and the chain of next-hops walks it the rest of the way.
The part that briefly confused me: on the switch originating the route, the next-hop shows up as 0.0.0.0. In this local BGP table display, 0.0.0.0 denotes a locally originated route rather than a remote next hop to forward to. In this directly connected eBGP exchange, the advertised next hop becomes the sender's link address. That rewriting is specific to the session/configuration; it is not a universal rule for every BGP advertisement. The same route therefore reads 0.0.0.0 on sonic1 and 192.168.1.1 on sonic2, and both are correct from where they are standing.
prefix-list, route-map, attach
The fix comes in three pieces and it is worth keeping them separate in your head.
A prefix-list is the vocabulary. It only says which prefixes we are talking about:
ip prefix-list LOOPBACKS seq 5 permit 10.10.10.0/24 le 32
The /24 here tripped me up. It is not a route being matched, it is the address range to look inside. The le 32 is a mask-length filter meaning anything in that range up to a /32. My loopbacks are /32 host routes, so without le 32 they never match, because a bare /24 matches only the exact 10.10.10.0/24. Base prefix is where you look, le and ge are which mask lengths you accept there.
A route-map is the logic:
route-map ALLOW_LOOPBACKS permit 10
match ip address prefix-list LOOPBACKS
Every route-map ends in an implicit deny. So this permits the loopbacks and drops everything else, rather than permitting the loopbacks and passing the rest through.
And a route-map does nothing at all until you attach it to a neighbour with a direction, in for received routes and out for sent ones. Both directions were being discarded, so both were needed:
router bgp 65001
address-family ipv4 unicast
neighbor 192.168.1.2 route-map ALLOW_LOOPBACKS in
neighbor 192.168.1.2 route-map ALLOW_LOOPBACKS out
Why ipv4 unicast? BGP is multi-protocol. One session can carry IPv4, IPv6, EVPN for VXLAN fabrics and others, each in its own address-family with its own table and its own policy. My loopbacks are IPv4, so that is the channel the policy belongs in.
Then the same thing, mirrored, on sonic2.
The payoff
B>* 10.10.10.1/32 [20/0] via 192.168.1.1, Ethernet0, rmapsrc 10.10.10.2
B means learned via BGP. > and * identify the selected route and FRR's FIB route flag. On SONiC this alone is not proof of hardware forwarding-table programming; checking forwarding behavior is a separate step. The 20 in [20/0] is eBGP's administrative distance. And via 192.168.1.1 is the next-hop, rewritten to sonic1's physical IP, which is the thing I had just read about and was pleased to see actually happen.
Then a real packet:
docker exec -it clab-sonic-bgp-sonic2 ping 10.10.10.1 -c 3
It replied, which is a slightly better test than it looks, because ping needs both directions. The echo request needs sonic2 to reach 10.10.10.1; the reply needs sonic1 to reach the source address chosen for that ping. The command shown does not force a loopback source, so it does not by itself prove the reverse loopback route. To check that explicitly, source the ping from 10.10.10.2 and inspect both route tables.
What I took from this half is an order of operations rather than a config snippet. Is the packet arriving, did the session come up, are routes passing. My lab failed at the third one, and the confusing part was only confusing because I was asking "why no routes" before I had established which layer was actually broken.
Part two: the contribution
The lab is not where the code change happened. It is what made me comfortable enough with the CLI and with CONFIG_DB to go and read the source.
The CLI I had been typing all afternoon lives in sonic-utilities, which is Python. I went through the open issues looking for something small and found #756, from November 2019:
when using CLI to configure Asymmetric PFC user can enter any string in Interface name.
The reporter's repro was pfc config asymmetric on ?, which created an interface named ? that then appeared in show interfaces status. My first assumption was that this had been fixed years ago and nobody closed the issue. It had not been.
The bug is worse than a bad error message
The handler, before my change:
@multi_asic_util.run_on_multi_asic
def configPfcAsym(self, interface, pfc_asym):
"""
PFC handler to configure asymmetric PFC.
"""
self.config_db.mod_entry(PORT_TABLE_NAME, interface, {'pfc_asym': pfc_asym})
self.dump_config_to_json(PORT_TABLE_NAME, self.multi_asic.current_namespace)
No validation anywhere. The interesting bit is mod_entry(), which is not update-only. If the key does not exist it creates it. So a typo does not produce a bad error message, it writes garbage into the configuration database:
$ pfc config asymmetric on Ethernet1234
$ echo $?
0
PORT|Ethernet1234 = {'pfc_asym': 'on'}
No lanes, no alias, no speed. A PORT row for a port that does not exist — created silently, exit code 0, no output. And config interface pfc asymmetric <intf> <on|off> shells out to this same handler, so both ways into the CLI do the same thing. Quiet corruption of persisted state is worse than a crash, because a crash at least tells you that something happened.
The fix is sitting about 30 lines below in the same class. configPfcPrio() already does the check, against the table it writes to:
if interface not in self.config_db.get_keys(PORT_QOS_MAP_TABLE_NAME):
click.echo('Cannot find interface {0}'.format(interface))
return
So configPfcPrio validates against PORT_QOS_MAP and writes to PORT_QOS_MAP, while configPfcAsym writes to PORT and validates against nothing. That asymmetry between two neighbouring functions is the whole bug. Four lines:
if interface not in self.config_db.get_keys(PORT_TABLE_NAME):
click.echo('Cannot find interface {0}'.format(interface))
return
PORT is the right table to check against. It is the table this handler writes to, and it is also the one showPfcAsym() reads, so config and show end up agreeing on what a valid interface is. There is a general interface_name_is_valid() over in config/main.py, but using it would add a pfc/ to config/ dependency and would diverge from the function directly next door, which felt like the wrong trade for a bug fix.
An existing test encoded the bug
This is the part that made the change worth writing up, and it is not the if.
With only the four-line source fix applied and the tests untouched, exactly one test failed:
FAILED tests/multi_asic_pfc_test.py::TestPfcMultiAsic::test_pfc_config_asymmetric_all_masic
E KeyError: 'asic1'
The vector behind it:
'pfc_config_asymmetric_all_masic': {'cmd': ['config', 'asymmetric', 'on', 'Ethernet0'],
'rc': 0,
'cmp_args': [['asic0', 'PORT', 'Ethernet0', 'pfc_asym', 'on'],
['asic1', 'PORT', 'Ethernet0', 'pfc_asym', 'on']]}
It asserts that config asymmetric on Ethernet0 with no --namespace writes PORT|Ethernet0 in both ASIC namespaces. But Ethernet0 only exists in asic0's mock config_db. The one for asic1 has Ethernet64, Ethernet-BP256 and Ethernet-BP260. A port lives in exactly one namespace, that is more or less what a namespace is.
The second half of that assertion was passing because of the bug. The multi-ASIC decorator loops over every namespace, and in asic1 mod_entry() created the missing key so the assertion could then find it. The test was not testing the feature, it was holding the defect in place, and had been doing so since it was added in 2024.
I think this is the genuinely interesting failure mode here, more than the missing validation. It is not a sloppy test. It reads fine, and I would not have flagged it in review either. It encodes the bug because the fixture and the code under test are wrong in the same direction, and a test cannot tell you about a wrongness it shares with the thing it is testing.
The corrected expectation is a write in asic0 and a no-op in asic1, which is what show asymmetric Ethernet0 had been reporting the whole time:
'cmp_args': [['asic0', 'PORT', 'Ethernet0', 'pfc_asym', 'on']],
'rc_msg': 'Cannot find interface Ethernet0'
The rc_msg is doing real work there. Without it, asic1 would simply be missing from cmp_args, which is indistinguishable from a test that forgot to check. With it, the rejection is asserted instead of merely absent.
Showing that the tests aren't decorative
Getting a suite green is easy and on its own says very little, so the PR describes four runs rather than one:
| state | result |
|---|---|
| master, unmodified | 29 passed |
| source fix only, tests untouched | 1 failed, 28 passed |
| source fix + test changes | 32 passed |
| test changes only, source reverted | 4 failed, 28 passed |
+ show_test.py, trimming_test.py | 204 passed, no collateral |
The fourth row is the one that matters. Revert the four-line fix and the four asymmetric tests fail, so they are exercising the change rather than restating whatever the code happens to do today. A test that passes with and without your fix is not testing your fix.
One environment note, because it cost me an evening. swsscommon and sonic_py_common are C++/SWIG bindings and do not come from PyPI, so pip install will not get you to a working test run. I ended up running the suite inside the same docker-sonic-vs image the lab uses, with the repo bind-mounted:
docker run -d --name sonic-ut-pfc --entrypoint sleep \
-v "$PWD:/work" -w /work docker-sonic-vs:latest infinity
docker exec sonic-ut-pfc bash -c 'cd /work && python3 -m pytest \
-o addopts="" -p no:cacheprovider \
tests/pfc_test.py tests/multi_asic_pfc_test.py -v'
-o addopts="" drops the coverage, xdist and junitxml defaults from pytest.ini so that a test run does not scatter artifacts through the checkout.
Two things I left for the reviewer
The error path still exits 0. configPfcPrio() does click.echo and return with exit code 0 and I matched it. A reviewer might reasonably want a non-zero code, but then configPfcPrio() has to change too or the inconsistency just moves somewhere else, and a four-line fix turns into a behavioural change across the module. I said I was happy to do it either way.
The message has no namespace label. On a multi-ASIC box without -n it prints once per namespace that lacks the port. showPfcPrio() uses a longer 'Cannot find interface {0} for Namespace {1}'. I kept the plain form to match the neighbouring function, again with a note that it is easy to change.
Both of those are "here is the seam, tell me which side you want" rather than decisions made quietly. The broader habit of mod_entry() creating keys shows up elsewhere in the repo too, and that is well out of scope for this.
Prior art
While reading around the issue I found PR #1316, from December 2020, attempting the same fix. It targets the old module-level swsssdk code, predates the refactor of pfc into a class with @run_on_multi_asic, and has no tests. It also has two unanswered pings from the author and zero reviews. Nobody objected to it — nobody looked at it.
I mentioned that in both the issue and the PR, along with the test I had changed. A first-time contributor editing the test suite is a pattern reviewers should be suspicious of, so the only sensible move is to lead with it: here is the test, here is why it was wrong, and here is the show command that already agreed with me.
The PR is sonic-net/sonic-utilities#4798. As I write this it is open, CI is green across Azure, CodeQL, DCO and the CLA check, and it has no human review yet. Given what happened to #1316, that is a slightly awkward place to end a post.
I am fine with it. What #1316 suggests is that reviewer attention, not correctness, is the scarce thing in a large OSS project, and no amount of care in a diff manufactures attention. Care does mean that whenever someone does open the tab, the context is already there: why the bug matters, why the fix is the boring one, which existing test was wrong and why, and evidence that the new tests fail without the change.
Six-year-old issues get fixed when somebody decides to look at them. The lab is what got me looking.