#!/usr/bin/env python3 # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """Describe Docker's uplink in netplan and restore its OVS bridge on boot.""" import json from pathlib import Path import subprocess import sys import yaml def run(*args: str) -> str: return subprocess.check_output(args, text=True) def main() -> None: config_path = Path("/etc/netplan/50-nke-container.yaml") config = yaml.safe_load(config_path.read_text()) if config_path.exists() else { "network": {"version": 2, "renderer": "networkd", "ethernets": {}} } network = config["network"] routes = json.loads(run("ip", "-j", "-4", "route", "show", "default")) # On restart networkd may activate the persisted bridge before this unit, # while Docker's original route still exists on the physical interface. physical_routes = [r for r in routes if r["dev"] not in network.get("bridges", {})] if not physical_routes and any(r["dev"] in network.get("bridges", {}) for r in routes): return if len(physical_routes) != 1 or not physical_routes[0].get("gateway"): raise ValueError("expected one Docker IPv4 default route with a gateway") route = physical_routes[0] uplink = route["dev"] bridge = "br" + uplink link = json.loads(run("ip", "-j", "-4", "address", "show", "dev", uplink))[0] addresses = [a for a in link["addr_info"] if a["scope"] == "global"] if len(addresses) != 1: raise ValueError("expected one Docker IPv4 address on the uplink") address = addresses[0] l3 = { "addresses": [f'{address["local"]}/{address["prefixlen"]}'], "routes": [{"to": "default", "via": route["gateway"], "on-link": True}], "mtu": link["mtu"], } restoring_bridge = bridge in network.get("bridges", {}) if restoring_bridge: # Docker recreates eth0 on every start. Refresh the persisted netplan # with Docker's current IP and MAC before activating the OVS bridge. network["bridges"][bridge].update(l3) mac = json.loads(run("ip", "-j", "link", "show", "dev", uplink))[0]["address"] network["ethernets"][uplink] = {"match": {"macaddress": mac}, "mtu": link["mtu"]} else: network["ethernets"][uplink] = l3 config_path.parent.mkdir(parents=True, exist_ok=True) config_path.write_text(yaml.safe_dump(config, sort_keys=False)) config_path.chmod(0o600) if restoring_bridge: # Remove Docker's IPv4 state so networkd can assign it to the bridge. run("ip", "-4", "route", "del", "default", "via", route["gateway"], "dev", uplink) run("ip", "-4", "address", "flush", "dev", uplink) run("netplan", "apply") if __name__ == "__main__": try: main() except (OSError, ValueError, KeyError, yaml.YAMLError, subprocess.CalledProcessError) as error: print(f"prepare container network: {error}", file=sys.stderr) raise SystemExit(1) from error