@@ -3,6 +3,7 @@ package node
33import (
44 "context"
55 "fmt"
6+ "net"
67 "os/exec"
78 "strings"
89
@@ -11,31 +12,29 @@ import (
1112
1213const cni0Bridge = "cni0"
1314
14- // setupBridge creates the cni0 bridge and assigns the gateway IP.
1515func setupBridge (ctx context.Context , gatewayIP , subnetCIDR string ) error {
1616 logger := log .WithFunc ("node.setupBridge" )
1717
18- // Create bridge if it does not exist.
1918 addCmd := exec .CommandContext (ctx , "ip" , "link" , "add" , cni0Bridge , "type" , "bridge" )
2019 out , err := addCmd .CombinedOutput ()
2120 if err != nil && ! strings .Contains (string (out ), "File exists" ) {
2221 return fmt .Errorf ("create bridge %s: %w: %s" , cni0Bridge , err , out )
2322 }
2423
25- // Assign gateway address (idempotent via replace).
26- _ , mask , err := parseCIDR (subnetCIDR )
24+ _ , ipNet , err := net .ParseCIDR (subnetCIDR )
2725 if err != nil {
2826 return fmt .Errorf ("parse subnet cidr: %w" , err )
2927 }
30- cidr := fmt .Sprintf ("%s/%s" , gatewayIP , mask )
28+ ones , _ := ipNet .Mask .Size ()
29+ cidr := fmt .Sprintf ("%s/%d" , gatewayIP , ones )
30+
3131 //nolint:gosec // ip args from trusted config
3232 addrCmd := exec .CommandContext (ctx , "ip" , "addr" , "replace" , cidr , "dev" , cni0Bridge )
3333 out , err = addrCmd .CombinedOutput ()
3434 if err != nil {
3535 return fmt .Errorf ("assign %s to %s: %w: %s" , cidr , cni0Bridge , err , out )
3636 }
3737
38- // Bring up the bridge.
3938 upCmd := exec .CommandContext (ctx , "ip" , "link" , "set" , cni0Bridge , "up" )
4039 out , err = upCmd .CombinedOutput ()
4140 if err != nil {
@@ -45,12 +44,3 @@ func setupBridge(ctx context.Context, gatewayIP, subnetCIDR string) error {
4544 logger .Infof (ctx , "bridge %s configured with gateway %s" , cni0Bridge , cidr )
4645 return nil
4746}
48-
49- // parseCIDR extracts the mask prefix from a CIDR string (e.g. "24" from "172.20.100.0/24").
50- func parseCIDR (cidr string ) (network , mask string , err error ) {
51- parts := strings .SplitN (cidr , "/" , 2 )
52- if len (parts ) != 2 {
53- return "" , "" , fmt .Errorf ("invalid cidr: %s" , cidr )
54- }
55- return parts [0 ], parts [1 ], nil
56- }
0 commit comments