From 64006f964ae80e5bf6491fd9ebeffdd6ca70261f Mon Sep 17 00:00:00 2001 From: Rob Murray Date: Sun, 5 Jan 2025 12:36:55 +0000 Subject: [PATCH] Simplify selection of gateway address When setting up a gateway in IpamInfo, and reserving that address in IPAM ... the IPAM driver may return its own default gateway. That gateway address is currently always parsed, but it's only used if the user did not supply their own gateway address. If the user supplied an address, it's always reserved and used. Otherwise, the IPAM driver is asked to select and reserve an address. The logic to deal with that was a bit confusing - and it's probably better just to ignore the IPAM driver's gateway if it's not going to be used. So, simplify it little. Signed-off-by: Rob Murray --- libnetwork/network.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/libnetwork/network.go b/libnetwork/network.go index 6ea3e6acb0..466eccb21c 100644 --- a/libnetwork/network.go +++ b/libnetwork/network.go @@ -1577,16 +1577,18 @@ func (n *Network) ipamAllocateVersion(ipVer int, ipam ipamapi.Ipam) error { } }() - if gws, ok := d.Meta[netlabel.Gateway]; ok { - if d.Gateway, err = types.ParseCIDR(gws); err != nil { - return types.InvalidParameterErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err) + // If there's no user-configured gateway address but the IPAM driver returned a gw when it + // set up the pool, use it. (It doesn't need to be requested/reserved in IPAM.) + if cfg.Gateway == "" { + if gws, ok := d.Meta[netlabel.Gateway]; ok { + if d.Gateway, err = types.ParseCIDR(gws); err != nil { + return types.InvalidParameterErrorf("failed to parse gateway address (%v) returned by ipam driver: %v", gws, err) + } } } - // If user requested a specific gateway, libnetwork will allocate it - // irrespective of whether ipam driver returned a gateway already. - // If none of the above is true, libnetwork will allocate one. - if cfg.Gateway != "" || d.Gateway == nil { + // If there's still no gateway, reserve cfg.Gateway or let the IPAM driver select an address. + if d.Gateway == nil { gatewayOpts := map[string]string{ ipamapi.RequestAddressType: netlabel.Gateway, }