Troubleshooting BGP peering between Kubernetes eBPF CNI and Cisco/ISP routers with Python: a real-world playbook

Troubleshooting BGP peering between Kubernetes eBPF CNI and Cisco/ISP routers with Python: a real-world playbook

BGP between a Kubernetes eBPF CNI (commonly Cilium) and Cisco/ISP routers can fail in ways that look identical at first glance: sessions flap, prefixes appear and disappear, and traffic blackholes despite “Established” neighbors. This playbook focuses on troubleshooting: what to capture, how to correlate control-plane and data-plane evidence, and how to automate detection with Python so you can move from “it’s broken” to a specific root cause quickly.

Map the failure surface: how Kubernetes eBPF CNI interacts with BGP and what to capture first — control plane vs data plane symptoms

The moving parts (what can break)

When using an eBPF CNI that speaks BGP (directly or via a BGP agent), you typically have:

  • BGP speaker on each node or a subset of nodes (Cilium’s BGP control plane, FRR, GoBGP, etc.)
  • Kernel routing table updated by the speaker (routes for Service IPs, Pod CIDRs, or LoadBalancer VIPs)
  • eBPF datapath enforcing forwarding, encapsulation, SNAT, and/or DSR
  • Upstream peers (Cisco/ISP) consuming routes and sending traffic back

Split symptoms into control plane vs data plane

This is the fastest way to avoid rabbit holes.

Control plane symptoms (BGP/RIB):
- BGP session not Established / flapping
- Prefixes not advertised or not accepted
- Route-map/policy filtering on Cisco/ISP
- AS path / next-hop attributes unexpected
- RPKI/IRR-based rejection (common with ISPs)

Data plane symptoms (forwarding/encapsulation/MTU):
- BGP shows routes installed everywhere, but traffic fails
- One-way traffic (return path issues)
- Blackholes only for specific MTUs or protocols
- Intermittent drops during reschedules/withdraws
- ECMP inconsistencies (hashing, asymmetric return)

What to capture first (minimal “first 10 minutes” checklist)

Collect these immediately during an incident (or set up automation to gather them):

  • From Kubernetes nodes
  • BGP neighbor state + updates (speaker logs)
  • ip route, ip rule, ip -6 route (if dual-stack)
  • ip link, ip addr (MTU and addressing)
  • eBPF program/map state (Cilium/TC/XDP) relevant to LB/NodePort/routing
  • From Cisco/ISP
  • BGP summary + per-neighbor routes and policy decisions
  • Interface counters and MTU
  • Logs around session state changes
  • From traffic
  • Targeted tcpdump (BGP TCP/179 and data-plane flows)
  • ICMP “frag needed” / PMTUD signals if MTU suspected

Collecting telemetry: BGP RIB/Adj-RIB snapshots, eBPF maps, Linux kernel route tables, and Cisco show commands to gather in a repeatable way

Kubernetes node collection (repeatable commands)

Assuming Cilium (adjust if using FRR/GoBGP directly):

BGP and routing:
- cilium bgp peers (or your speaker’s equivalent)
- cilium bgp routes (advertised/received if supported)
- ip -br addr
- ip -d link show
- ip route show table all
- ip rule show
- sysctl net.ipv4.ip_forward net.ipv4.conf.all.rp_filter net.ipv4.conf.default.rp_filter

eBPF datapath (high-signal artifacts):
- cilium status --verbose
- cilium bpf lb list (Service VIP programming)
- cilium bpf tunnel list (if encapsulation is used)
- cilium bpf ipcache list (identity/IP mappings)
- bpftool prog show and bpftool map show for low-level validation

Logs (time-aligned):
- journalctl -u cilium --since "30 min ago" --no-pager
- BGP speaker/container logs if separate

Cisco/ISP collection (IOS-XE / IOS / NX-OS style)

Use consistent “show” output and include policy context.

Session + capabilities:
- show ip bgp summary
- show ip bgp neighbors <PEER-IP>
- show ip bgp neighbors <PEER-IP> advertised-routes
- show ip bgp neighbors <PEER-IP> received-routes (if enabled / soft-reconfig)
- show ip bgp neighbors <PEER-IP> routes (platform-dependent)

Policy + route-map decisions:
- show run | sec router bgp
- show route-map
- show ip prefix-list
- show ip as-path access-list

Transport/underlay:
- show interface <INTF> | inc MTU|input errors|giants|drops
- show tcp brief | inc :179 (platform-dependent)
- show logging | inc BGP|%BGP|neighbor

Snapshots that scale: store “what you saw”

Troubleshooting gets much easier when you can diff snapshots.

  • Store CLI outputs in timestamped files per device/node
  • Normalize timestamps to UTC
  • Capture the same command set every time (don’t improvise mid-incident)

Example: Ansible play to pull Cisco BGP evidence

This is intentionally simple: it creates repeatable artifacts you can diff.

yaml
- name: Collect BGP telemetry from Cisco
  hosts: cisco_edges
  gather_facts: no
  connection: network_cli
  vars:
    cmds:
      - show ip bgp summary
      - show ip bgp neighbors {{ peer_ip }}
      - show ip bgp neighbors {{ peer_ip }} advertised-routes
      - show ip bgp neighbors {{ peer_ip }} received-routes
      - show interface {{ uplink_intf }} | include MTU|input errors|giants|drops
      - show logging | include BGP|%BGP|neighbor
  tasks:
    - name: Run show commands
      cisco.ios.ios_command:
        commands: "{{ cmds }}"
      register: out

    - name: Write outputs per host
      copy:
        content: |
          # {{ inventory_hostname }} {{ ansible_date_time.iso8601 }}
          {% for i in range(cmds|length) %}
          ## {{ cmds[i] }}
          {{ out.stdout[i] }}
          {% endfor %}
        dest: "./artifacts/{{ inventory_hostname }}-bgp-{{ ansible_date_time.epoch }}.txt"
      delegate_to: localhost

Python-driven correlation: parsing MRT/BGP dumps, syslogs, and eBPF metrics to automatically detect session flaps, prefix leaks, and AS path anomalies

Automation helps in two places:
- During incidents: produce a timeline and highlight deltas
- After incidents: regression tests + alert rules based on real patterns

Data sources worth correlating

  • BGP update logs (speaker logs, Cisco syslog %BGP-...)
  • RIB snapshots (Cisco “advertised/received”, node kernel routes)
  • MRT/BMP if you have collectors (route analytics)
  • eBPF metrics (drops, LB map churn, conntrack pressure)

Practical Python correlation: syslog + neighbor states

Below is a compact script pattern:
- Parse syslog lines for neighbor state changes (Cisco-ish patterns)
- Parse node-side logs for BGP FSM transitions
- Output a time-ordered flap timeline and a simple flap-rate signal

python
import re
from datetime import datetime, timezone
from pathlib import Path
from collections import defaultdict

# Adjust patterns to your platform/log format
CISCO_BGP = re.compile(
    r'(?P<ts>\w+\s+\d+\s+\d+:\d+:\d+).*(%BGP-\d+-ADJCHANGE).*neighbor (?P<peer>\S+) (?P<event>Up|Down)',
    re.IGNORECASE
)

CILIUM_BGP = re.compile(
    r'(?P<ts>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z).*peer (?P<peer>\S+).*(?P<event>Established|Idle|Active|Connect)',
    re.IGNORECASE
)

def parse_ts_syslog(ts: str, year: int) -> datetime:
    # Example: "Jan 26 12:34:56"
    return datetime.strptime(f"{year} {ts}", "%Y %b %d %H:%M:%S").replace(tzinfo=timezone.utc)

def parse_logs(paths):
    events = []
    year = datetime.now(timezone.utc).year

    for p in paths:
        for line in Path(p).read_text(errors="ignore").splitlines():
            m = CISCO_BGP.search(line)
            if m:
                events.append((
                    parse_ts_syslog(m.group("ts"), year),
                    "cisco",
                    m.group("peer"),
                    m.group("event").lower()
                ))
                continue

            m = CILIUM_BGP.search(line)
            if m:
                ts = datetime.fromisoformat(m.group("ts").replace("Z", "+00:00"))
                events.append((ts, "k8s", m.group("peer"), m.group("event").lower()))

    return sorted(events, key=lambda x: x[0])

def summarize(events):
    flaps = defaultdict(int)
    for ts, src, peer, event in events:
        if event in ("down", "idle", "active", "connect"):
            flaps[peer] += 1

    print("=== Timeline (UTC) ===")
    for ts, src, peer, event in events:
        print(f"{ts.isoformat()} [{src}] {peer} -> {event}")

    print("\n=== Flap counts (proxy) ===")
    for peer, n in sorted(flaps.items(), key=lambda x: -x[1]):
        print(f"{peer}: {n}")

if __name__ == "__main__":
    # Example: python correlate_bgp.py cisco.log cilium.log
    import sys
    ev = parse_logs(sys.argv[1:])
    summarize(ev)

What “good” automation detects

Build detectors that match how bgp failures show up in the real world:

  • Session flaps: N transitions per 10 minutes; correlate with interface errors/MTU issues
  • Prefix leaks: more specifics than expected, or unexpected RFC1918/ULA exported
  • AS path anomalies: unexpected prepends, private AS removal behavior differences, or wrong local-as
  • Next-hop anomalies: next-hop is not reachable in underlay, or changes unexpectedly during node churn
  • Churn amplification: Kubernetes reschedules cause repeated withdraw/announce storms

Common root causes and fixes: MTU/fragmentation, next-hop rewriting, route reflection misconfigurations, and ISP-specific quirks — real examples and remediation steps

1) MTU / fragmentation / PMTUD failure (looks like “random” packet loss)

Typical pattern
- bgp session comes up, but large data flows stall
- TCP MSS/PMTUD issues: SYN works, larger payloads blackhole
- Interface counters show giants, drops, or fragmentation-related ICMP filtered

How to prove
- On node: ip link show and confirm MTU across NIC, VLAN, bond, VxLAN/Geneve (if used)
- Packet capture for ICMP type 3 code 4 (frag needed) on path
- On Cisco: show interface counters and MTU, look for giants/drops

Fixes
- Set consistent MTU end-to-end (including encapsulation overhead)
- Clamp TCP MSS at edge if you must (as a mitigation, not a first choice)
- Ensure ICMP “frag needed” is not blocked (PMTUD must work)

2) Next-hop rewriting / next-hop reachability (control plane looks fine, forwarding fails)

Typical pattern
- Cisco shows received prefixes, installs them
- Traffic to Service/Pod CIDRs blackholes because next-hop is a node IP that isn’t reachable from that VRF/segment
- In multi-homed nodes, next-hop picks the “wrong” interface IP

How to prove
- On Cisco: inspect next-hop for installed routes (show ip route <prefix> and BGP path details)
- From Cisco: ping <next-hop> in correct VRF/source interface
- On node: check ip addr and routing rules—ensure correct source selection

Fixes
- On the Kubernetes side: set explicit router-id / local address selection if supported
- Use policies to advertise with a next-hop that is reachable (or use next-hop self on a route-reflector design where appropriate)
- Ensure upstream has routes back to the node IPs being used as next-hop

3) Route reflection and iBGP/eBGP confusion (especially in mixed designs)

Typical pattern
- Some nodes advertise, others don’t
- Prefixes appear on RR but not on edge, or only one path propagates
- Inconsistent communities/attributes and bestpath decisions

How to prove
- Identify whether the speaker is doing eBGP to the router or iBGP via RR
- On Cisco/RR: verify cluster-id, route-reflector-client, and whether next-hop is preserved/changed as expected
- Check if policies inadvertently drop routes learned from certain neighbors

Fixes
- Keep the design simple: prefer direct eBGP from node (or node group) to edge where feasible
- If using route reflection, validate:
- RR clients configured correctly
- next-hop handling is correct
- outbound policy is symmetric and explicit

4) ISP-specific quirks: max-prefix, RPKI/IRR filtering, private AS behavior

Typical pattern
- Session established, but ISP accepts zero prefixes
- ISP resets session due to max-prefix
- Routes accepted only after adding communities or matching IRR/RPKI

How to prove
- On Cisco/ISP side (or your edge): look for max-prefix hits and policy denies
- Compare advertised prefix-set vs allowed prefix-list
- Check for private ASNs in AS_PATH if the ISP rejects them

Fixes
- Enforce strict export filters on Kubernetes side (only intended CIDRs)
- Aggregate where possible (avoid accidental more-specific explosions)
- Align with ISP requirements:
- Register IRR objects if required
- Ensure RPKI ROAs are correct for the origin ASN/prefix
- Confirm community requirements for acceptance/blackholing, etc.

Hardening and automation: automated regression tests, alert tuning, playbooks to re-establish peering, and preventive checks to add to CI for network changes

Automated regression tests (before and after changes)

Treat bgp peering like an API contract. Add tests that run:
- after CNI upgrades
- after node kernel changes
- after router policy changes
- after MTU/VLAN/underlay modifications

Regression checklist
- BGP session state: all required peers Established within X seconds
- Advertised prefix-set equals expected set (no more, no less)
- Next-hop is reachable from the upstream VRF
- Data-plane probe: reachability to a test VIP/Pod from an external vantage point
- MTU probe: verify max payload across the path (or at least validate MSS/PMTUD behavior)

Alert tuning that reduces noise

  • Alert on flap rate (e.g., >3 transitions/10m) rather than single down/up
  • Alert on prefix count deltas (sudden jump could be leak or churn)
  • Alert on bestpath changes for critical prefixes (indicates upstream instability)
  • Correlate with node lifecycle events (cordon/drain/scale) to avoid paging on expected churn

Playbooks to re-establish peering safely

When sessions break, avoid “clear everything everywhere” without evidence.

Order of operations
1. Confirm underlay reachability (L3 adjacency, ACLs, TCP/179)
2. Validate BGP config parity (ASNs, timers, MD5 auth, update-source)
3. Inspect policy rejects (prefix-list/route-map, max-prefix, RPKI)
4. Validate next-hop reachability
5. Only then do targeted clears:
- Clear one neighbor (soft in/out if supported), not all
- Re-advertise only intended routes

Preventive checks to add to CI for network changes

If you have network configuration stored as code, add guardrails:

  • Prefix budget: fail CI if proposed changes would advertise more than N prefixes
  • Explicit allow-list for exported CIDRs (no RFC1918/ULA leakage unless intended)
  • MTU invariants: validate configured MTUs across interfaces/overlays
  • BGP policy unit tests: for a given neighbor, expected action on representative routes
  • Attribute sanity: ensure no private ASNs leak to ISP unless permitted, communities set correctly

Common pitfalls

  • Treating an “Established” bgp session as proof the network works (it only proves TCP + FSM).
  • Troubleshooting only on one side (Kubernetes or Cisco). Most failures require correlating both.
  • Ignoring next-hop reachability: routes can be present but unusable.
  • Allowing uncontrolled prefix growth (per-node or per-pod advertisements) until hitting max-prefix.
  • Mixing iBGP and eBGP assumptions (next-hop, propagation rules, and policy defaults differ).
  • Debugging from “latest state” only—without time-aligned snapshots, you miss churn and transient rejects.

Key takeaways

  • Start by classifying the failure: control plane (bgp session/policy/RIB) vs data plane (MTU/forwarding/eBPF behavior).
  • Make telemetry collection repeatable: consistent snapshots from nodes and Cisco devices are more valuable than ad-hoc commands.
  • Use Python correlation to turn logs and dumps into a timeline: session flaps, prefix deltas, and attribute anomalies become obvious.
  • The most common real-world causes are MTU/PMTUD issues, next-hop reachability problems, route-reflection design mistakes, and ISP policy constraints.
  • Harden bgp peering with regression tests and CI checks: prevent leaks, limit churn, and catch misconfigurations before production changes land.