From d01a1bd2d8ceabe1d9e95e4aed43a4e693739fae Mon Sep 17 00:00:00 2001 From: zijiren233 Date: Mon, 19 Oct 2026 22:01:24 +0800 Subject: [PATCH] fix(discovery): accept multiple Cilium cluster-pool Pod CIDRs Cilium stores every cluster-pool IPv4 CIDR in a single space-separated cilium-config value (cluster-pool-ipv4-cidr). The resolver required exactly one CIDR, so multi-pool clusters silently fell back to the kubeadm podSubnet, which often no longer matches the Cilium pools. Every worker then failed validation (PodCIDR outside allowed CIDR) and no routes were programmed. Parse comma- or whitespace-separated CIDR lists everywhere the Pod CIDR is configured: Cilium and kubeadm discovery, --pod-cidr, and the config file. A worker is now accepted when its PodCIDR falls inside any configured pool, and per-pool overlap checks against the Service and router CIDRs replace the single-prefix checks. --- internal/app/app.go | 6 +-- internal/config/config.go | 75 +++++++++++++++++++------- internal/config/config_test.go | 57 ++++++++++++++++++-- internal/config/load.go | 6 ++- internal/controller/reconciler_test.go | 2 +- internal/discovery/resolver.go | 52 +++++++++++++----- internal/discovery/resolver_test.go | 54 ++++++++++++++++++- internal/planner/planner.go | 26 ++++++--- internal/planner/planner_test.go | 51 +++++++++++++++++- internal/route/model.go | 11 ++++ internal/route/netlink_linux.go | 12 ++--- internal/route/netlink_linux_test.go | 8 +-- internal/route/netlink_unsupported.go | 2 +- test/integration/netlink_linux_test.go | 2 +- 14 files changed, 305 insertions(+), 59 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index d92d3e8..49bebd5 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -60,7 +60,7 @@ func Run(ctx context.Context, loaded config.Config) error { "interface", cfg.Routes.Interface, "podCIDR", - cfg.PodCIDR, + cfg.Routes.PodCIDR, "serviceCIDR", cfg.ServiceCIDR, "routerCIDR", @@ -71,7 +71,7 @@ func Run(ctx context.Context, loaded config.Config) error { cfg.Routes.Interface, cfg.Routes.Table, cfg.Routes.Protocol, - cfg.PodCIDR, + cfg.PodCIDRs, cfg.ServiceCIDR, ) if err != nil { @@ -98,7 +98,7 @@ func Run(ctx context.Context, loaded config.Config) error { reconciler := controller.NewReconciler( manager.GetClient(), - planner.New(cfg.PodCIDR, cfg.ServiceCIDR, cfg.RouterCIDR), + planner.New(cfg.PodCIDRs, cfg.ServiceCIDR, cfg.RouterCIDR), backend, probe.NewHTTP(cfg.Probe.Timeout, cfg.Probe.Port), planner.NewProbeTracker(cfg.Probe.FailureThreshold, cfg.Probe.SuccessThreshold), diff --git a/internal/config/config.go b/internal/config/config.go index c138d44..64ec1b8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -5,7 +5,9 @@ import ( "errors" "fmt" "net/netip" + "strings" "time" + "unicode" ) const ( @@ -93,7 +95,7 @@ type LoggingConfig struct { type Validated struct { Config - PodCIDR netip.Prefix + PodCIDRs []netip.Prefix ServiceCIDR netip.Prefix RouterCIDR netip.Prefix } @@ -128,7 +130,7 @@ func Defaults() Config { func (cfg Config) Validate() (Validated, error) { validationErrors := cfg.validateScalars() - podCIDR, err := parseIPv4Prefix("routes.pod-cidr", cfg.Routes.PodCIDR) + podCIDRs, err := parseIPv4PrefixList("routes.pod-cidr", cfg.Routes.PodCIDR) if err != nil { validationErrors = append(validationErrors, err) } @@ -145,7 +147,7 @@ func (cfg Config) Validate() (Validated, error) { validationErrors = append( validationErrors, - validatePrefixRelationships(podCIDR, serviceCIDR, routerCIDR)..., + validatePrefixRelationships(podCIDRs, serviceCIDR, routerCIDR)..., ) if err := errors.Join(validationErrors...); err != nil { @@ -153,18 +155,27 @@ func (cfg Config) Validate() (Validated, error) { } // Keep the serializable configuration aligned with the parsed prefixes. - cfg.Routes.PodCIDR = podCIDR.String() + cfg.Routes.PodCIDR = joinPrefixes(podCIDRs) cfg.Routes.ServiceCIDR = serviceCIDR.String() cfg.Routes.RouterCIDR = routerCIDR.String() return Validated{ Config: cfg, - PodCIDR: podCIDR, + PodCIDRs: podCIDRs, ServiceCIDR: serviceCIDR, RouterCIDR: routerCIDR, }, nil } +func joinPrefixes(prefixes []netip.Prefix) string { + values := make([]string, 0, len(prefixes)) + for _, prefix := range prefixes { + values = append(values, prefix.String()) + } + + return strings.Join(values, ",") +} + func (cfg Config) validateScalars() []error { validationErrors := make([]error, 0) if cfg.Kubernetes.Kubeconfig == "" { @@ -260,20 +271,25 @@ func (cfg Config) validateScalars() []error { return validationErrors } -func validatePrefixRelationships(podCIDR, serviceCIDR, routerCIDR netip.Prefix) []error { +func validatePrefixRelationships( + podCIDRs []netip.Prefix, + serviceCIDR, routerCIDR netip.Prefix, +) []error { validationErrors := make([]error, 0, 3) - if podCIDR.IsValid() && serviceCIDR.IsValid() && prefixesOverlap(podCIDR, serviceCIDR) { - validationErrors = append( - validationErrors, - errors.New("routes.pod-cidr and routes.service-cidr overlap"), - ) - } - - if podCIDR.IsValid() && routerCIDR.IsValid() && prefixesOverlap(podCIDR, routerCIDR) { - validationErrors = append( - validationErrors, - errors.New("routes.pod-cidr and routes.router-cidr overlap"), - ) + for _, podCIDR := range podCIDRs { + if podCIDR.IsValid() && serviceCIDR.IsValid() && prefixesOverlap(podCIDR, serviceCIDR) { + validationErrors = append( + validationErrors, + fmt.Errorf("pod CIDR %s overlaps routes.service-cidr %s", podCIDR, serviceCIDR), + ) + } + + if podCIDR.IsValid() && routerCIDR.IsValid() && prefixesOverlap(podCIDR, routerCIDR) { + validationErrors = append( + validationErrors, + fmt.Errorf("pod CIDR %s overlaps routes.router-cidr %s", podCIDR, routerCIDR), + ) + } } if serviceCIDR.IsValid() && routerCIDR.IsValid() && prefixesOverlap(serviceCIDR, routerCIDR) { @@ -295,6 +311,29 @@ func parseIPv4Prefix(name, value string) (netip.Prefix, error) { return prefix.Masked(), nil } +// parseIPv4PrefixList parses a comma- or whitespace-separated list of IPv4 +// CIDRs. Cilium writes multiple cluster-pool CIDRs into one ConfigMap value +// separated by spaces, while the CLI accepts comma-separated lists. +func parseIPv4PrefixList(name, value string) ([]netip.Prefix, error) { + prefixes := make([]netip.Prefix, 0, 1) + for _, part := range strings.FieldsFunc(value, func(r rune) bool { + return r == ',' || unicode.IsSpace(r) + }) { + prefix, err := parseIPv4Prefix(name, part) + if err != nil { + return nil, err + } + + prefixes = append(prefixes, prefix) + } + + if len(prefixes) == 0 { + return nil, fmt.Errorf("%s must be a valid IPv4 CIDR list", name) + } + + return prefixes, nil +} + func prefixesOverlap(first, second netip.Prefix) bool { return first.Contains(second.Addr()) || second.Contains(first.Addr()) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 71e06c0..1b9243a 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -1,6 +1,7 @@ package config_test import ( + "net/netip" "os" "path/filepath" "testing" @@ -18,7 +19,7 @@ func TestValidate(t *testing.T) { cfg := validConfig() validated, err := cfg.Validate() require.NoError(t, err) - assert.Equal(t, "10.0.0.0/10", validated.PodCIDR.String()) + assert.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, validated.PodCIDRs) assert.Equal(t, "10.192.0.0/12", validated.ServiceCIDR.String()) assert.Equal(t, "192.0.2.0/24", validated.RouterCIDR.String()) } @@ -39,6 +40,56 @@ func TestValidateNormalizesCIDRs(t *testing.T) { assert.Equal(t, "192.0.2.0/24", validated.Routes.RouterCIDR) } +func TestValidateAcceptsMultiplePodCIDRs(t *testing.T) { + t.Parallel() + + cfg := validConfig() + cfg.Routes.PodCIDR = "10.107.0.0/16 10.108.0.0/16, 10.109.0.0/16" + + validated, err := cfg.Validate() + require.NoError(t, err) + assert.Equal( + t, + []netip.Prefix{ + netip.MustParsePrefix("10.107.0.0/16"), + netip.MustParsePrefix("10.108.0.0/16"), + netip.MustParsePrefix("10.109.0.0/16"), + }, + validated.PodCIDRs, + ) + assert.Equal( + t, + "10.107.0.0/16,10.108.0.0/16,10.109.0.0/16", + validated.Routes.PodCIDR, + ) +} + +func TestValidateReportsPerPoolOverlap(t *testing.T) { + t.Parallel() + + cfg := validConfig() + cfg.Routes.PodCIDR = "10.0.0.0/10,10.193.0.0/16" + + _, err := cfg.Validate() + require.Error(t, err) + assert.ErrorContains( + t, + err, + "pod CIDR 10.193.0.0/16 overlaps routes.service-cidr 10.192.0.0/12", + ) +} + +func TestValidateRejectsInvalidPoolEntry(t *testing.T) { + t.Parallel() + + cfg := validConfig() + cfg.Routes.PodCIDR = "10.0.0.0/10 2001:db8::/32" + + _, err := cfg.Validate() + require.Error(t, err) + assert.ErrorContains(t, err, "routes.pod-cidr must be a valid IPv4 CIDR") +} + func TestValidateReportsAllImportantErrors(t *testing.T) { t.Parallel() @@ -55,8 +106,8 @@ func TestValidateReportsAllImportantErrors(t *testing.T) { assert.ErrorContains(t, err, "routes.protocol") assert.ErrorContains(t, err, "probe.timeout") assert.ErrorContains(t, err, "logging.level") - assert.ErrorContains(t, err, "routes.pod-cidr and routes.service-cidr overlap") - assert.ErrorContains(t, err, "routes.pod-cidr and routes.router-cidr overlap") + assert.ErrorContains(t, err, "pod CIDR 10.0.0.0/8 overlaps routes.service-cidr 10.192.0.0/12") + assert.ErrorContains(t, err, "pod CIDR 10.0.0.0/8 overlaps routes.router-cidr 10.1.0.0/16") } func TestLoaderPrecedence(t *testing.T) { diff --git a/internal/config/load.go b/internal/config/load.go index ff66962..2262784 100644 --- a/internal/config/load.go +++ b/internal/config/load.go @@ -100,7 +100,11 @@ func addFlags(flags *pflag.FlagSet, values *viper.Viper) error { defaults.Routes.Interface, "host interface used to reach worker next hops (automatically discovered when empty)", ) - flags.String("pod-cidr", "", "allowed cluster Pod CIDR (automatically discovered when empty)") + flags.String( + "pod-cidr", + "", + "allowed cluster Pod CIDRs, comma- or space-separated (automatically discovered when empty)", + ) flags.String("service-cidr", "", "cluster Service CIDR (automatically discovered when empty)") flags.String( "router-cidr", diff --git a/internal/controller/reconciler_test.go b/internal/controller/reconciler_test.go index 6c7dbbc..d68ae0e 100644 --- a/internal/controller/reconciler_test.go +++ b/internal/controller/reconciler_test.go @@ -151,7 +151,7 @@ func testScheme(t *testing.T) *runtime.Scheme { func testPlanner() *planner.Planner { return planner.New( - netip.MustParsePrefix("10.0.0.0/10"), + []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, netip.MustParsePrefix("10.192.0.0/12"), netip.MustParsePrefix("192.0.2.0/24"), ) diff --git a/internal/discovery/resolver.go b/internal/discovery/resolver.go index 784c036..64df190 100644 --- a/internal/discovery/resolver.go +++ b/internal/discovery/resolver.go @@ -8,6 +8,7 @@ import ( "net/netip" "slices" "strings" + "unicode" "github.com/labring-sigs/route-controller/internal/config" corev1 "k8s.io/api/core/v1" @@ -98,19 +99,19 @@ func (resolver *Resolver) podCIDR(ctx context.Context) (string, error) { configMap, ) if ciliumErr == nil { - var prefix netip.Prefix + var prefixes []netip.Prefix - prefix, ciliumErr = singleIPv4Prefix(configMap.Data[ciliumPodCIDRKey]) + prefixes, ciliumErr = ipv4Prefixes(configMap.Data[ciliumPodCIDRKey]) if ciliumErr == nil { - return prefix.String(), nil + return joinPrefixes(prefixes), nil } } networking, kubeadmErr := resolver.kubeadmNetworking(ctx) - var prefix netip.Prefix + var prefixes []netip.Prefix if kubeadmErr == nil { - prefix, kubeadmErr = singleIPv4Prefix(networking.PodSubnet) + prefixes, kubeadmErr = ipv4Prefixes(networking.PodSubnet) } if kubeadmErr != nil { @@ -120,7 +121,7 @@ func (resolver *Resolver) podCIDR(ctx context.Context) (string, error) { ) } - return prefix.String(), nil + return joinPrefixes(prefixes), nil } func (resolver *Resolver) serviceCIDR(ctx context.Context) (string, error) { @@ -280,12 +281,9 @@ func (resolver *Resolver) routerCIDR( } func singleIPv4Prefix(value string) (netip.Prefix, error) { - prefixes := make([]netip.Prefix, 0, 1) - for part := range strings.SplitSeq(value, ",") { - prefix, err := netip.ParsePrefix(strings.TrimSpace(part)) - if err == nil && prefix.Addr().Is4() { - prefixes = append(prefixes, prefix.Masked()) - } + prefixes, err := ipv4Prefixes(value) + if err != nil { + return netip.Prefix{}, err } if len(prefixes) != 1 { @@ -295,6 +293,36 @@ func singleIPv4Prefix(value string) (netip.Prefix, error) { return prefixes[0], nil } +// ipv4Prefixes parses a comma- or whitespace-separated list of IPv4 CIDRs. +// Cilium stores every cluster-pool CIDR in one ConfigMap value separated by +// spaces, so any of the parts failing to parse invalidates the whole value. +func ipv4Prefixes(value string) ([]netip.Prefix, error) { + prefixes := make([]netip.Prefix, 0, 1) + for _, part := range strings.FieldsFunc(value, func(r rune) bool { return r == ',' || unicode.IsSpace(r) }) { + prefix, err := netip.ParsePrefix(strings.TrimSpace(part)) + if err != nil || !prefix.Addr().Is4() { + return nil, fmt.Errorf("invalid IPv4 CIDR %q in %q", part, value) + } + + prefixes = append(prefixes, prefix.Masked()) + } + + if len(prefixes) == 0 { + return nil, fmt.Errorf("expected at least one IPv4 CIDR in %q", value) + } + + return prefixes, nil +} + +func joinPrefixes(prefixes []netip.Prefix) string { + values := make([]string, 0, len(prefixes)) + for _, prefix := range prefixes { + values = append(values, prefix.String()) + } + + return strings.Join(values, ",") +} + func isControlPlane(node *corev1.Node) bool { _, controlPlane := node.Labels["node-role.kubernetes.io/control-plane"] _, legacyControlPlane := node.Labels["node-role.kubernetes.io/master"] diff --git a/internal/discovery/resolver_test.go b/internal/discovery/resolver_test.go index 36218d6..cbdb547 100644 --- a/internal/discovery/resolver_test.go +++ b/internal/discovery/resolver_test.go @@ -37,7 +37,7 @@ func TestResolveDiscoversRouteConfiguration(t *testing.T) { require.NoError(t, err) assert.Equal(t, "ens18", resolved.Routes.Interface) - assert.Equal(t, "10.0.0.0/10", resolved.PodCIDR.String()) + assert.Equal(t, "10.0.0.0/10", resolved.Routes.PodCIDR) assert.Equal(t, "10.192.0.0/12", resolved.ServiceCIDR.String()) assert.Equal(t, "192.0.2.0/24", resolved.RouterCIDR.String()) } @@ -79,7 +79,7 @@ func TestResolveFallsBackToKubeadmPodCIDR(t *testing.T) { resolved, err := resolver.Resolve(context.Background(), config.Defaults()) require.NoError(t, err) - assert.Equal(t, "10.0.0.0/10", resolved.PodCIDR.String()) + assert.Equal(t, "10.0.0.0/10", resolved.Routes.PodCIDR) } func TestResolveRejectsWorkersOnDifferentInterfaces(t *testing.T) { @@ -124,6 +124,16 @@ type fakeNetwork struct { prefixCalls int } +func workerNetwork() *fakeNetwork { + return &fakeNetwork{ + interfaces: map[netip.Addr]string{ + netip.MustParseAddr("192.0.2.10"): "ens18", + netip.MustParseAddr("192.0.2.11"): "ens18", + }, + prefixes: []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}, + } +} + func (network *fakeNetwork) InterfaceFor(address netip.Addr) (string, error) { network.interfaceCalls++ return network.interfaces[address], nil @@ -143,6 +153,46 @@ func fakeReader(t *testing.T, objects ...client.Object) client.Reader { return fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build() } +func TestResolveParsesMultipleCiliumPodCIDRPools(t *testing.T) { + t.Parallel() + + objects := discoveryObjects() + ciliumConfig, ok := objects[0].(*corev1.ConfigMap) + require.True(t, ok) + + ciliumConfig.Data["cluster-pool-ipv4-cidr"] = "10.107.0.0/16 10.108.0.0/16 10.109.0.0/16 10.110.0.0/16\n 10.111.0.0/16" + + resolver := discovery.NewResolver(fakeReader(t, objects...), workerNetwork()) + + resolved, err := resolver.Resolve(context.Background(), config.Defaults()) + + require.NoError(t, err) + assert.Equal( + t, + "10.107.0.0/16,10.108.0.0/16,10.109.0.0/16,10.110.0.0/16,10.111.0.0/16", + resolved.Routes.PodCIDR, + ) +} + +func TestResolveRejectsCiliumPoolListWithInvalidEntry(t *testing.T) { + t.Parallel() + + objects := discoveryObjects() + ciliumConfig, ok := objects[0].(*corev1.ConfigMap) + require.True(t, ok) + + ciliumConfig.Data["cluster-pool-ipv4-cidr"] = "10.107.0.0/16 not-a-cidr" + + resolver := discovery.NewResolver(fakeReader(t, objects...), workerNetwork()) + + resolved, err := resolver.Resolve(context.Background(), config.Defaults()) + + // The invalid Cilium value is rejected as a whole; kubeadm podSubnet still + // provides a fallback instead of failing discovery. + require.NoError(t, err) + assert.Equal(t, "10.0.0.0/10", resolved.Routes.PodCIDR) +} + func discoveryObjects() []client.Object { return []client.Object{ &corev1.ConfigMap{ diff --git a/internal/planner/planner.go b/internal/planner/planner.go index b89cdd5..a335050 100644 --- a/internal/planner/planner.go +++ b/internal/planner/planner.go @@ -6,19 +6,30 @@ import ( "fmt" "net/netip" "slices" + "strings" "github.com/labring-sigs/route-controller/internal/route" corev1 "k8s.io/api/core/v1" ) type Planner struct { - podCIDR netip.Prefix + podCIDRs []netip.Prefix serviceCIDR netip.Prefix routerCIDR netip.Prefix } -func New(podCIDR, serviceCIDR, routerCIDR netip.Prefix) *Planner { - return &Planner{podCIDR: podCIDR, serviceCIDR: serviceCIDR, routerCIDR: routerCIDR} +func New(podCIDRs []netip.Prefix, serviceCIDR, routerCIDR netip.Prefix) *Planner { + return &Planner{podCIDRs: podCIDRs, serviceCIDR: serviceCIDR, routerCIDR: routerCIDR} +} + +// podCIDRList renders the allowed Pod CIDRs for validation messages. +func (planner *Planner) podCIDRList() string { + values := make([]string, 0, len(planner.podCIDRs)) + for _, prefix := range planner.podCIDRs { + values = append(values, prefix.String()) + } + + return strings.Join(values, ",") } func (planner *Planner) Workers( @@ -182,9 +193,12 @@ func (planner *Planner) validateWorker( } podCIDR = podCIDR.Masked() - if !route.PrefixWithin(podCIDR, planner.podCIDR) { - return WorkerStatePodCIDRInvalid, - fmt.Sprintf("PodCIDR %s is outside allowed CIDR %s", podCIDR, planner.podCIDR) + if !route.PrefixWithinAny(podCIDR, planner.podCIDRs) { + return WorkerStatePodCIDRInvalid, fmt.Sprintf( + "PodCIDR %s is outside allowed CIDRs %s", + podCIDR, + planner.podCIDRList(), + ) } if prefixesOverlap(podCIDR, planner.serviceCIDR) { diff --git a/internal/planner/planner_test.go b/internal/planner/planner_test.go index ce49c09..c1b5c67 100644 --- a/internal/planner/planner_test.go +++ b/internal/planner/planner_test.go @@ -32,6 +32,55 @@ func TestPlannerUsesCiliumNodePodCIDR(t *testing.T) { assert.Equal(t, netip.MustParsePrefix("10.0.3.0/24"), routes[0].Destination) } +func TestPlannerAcceptsPodCIDRFromAnyConfiguredPool(t *testing.T) { + t.Parallel() + + routePlanner := planner.New( + []netip.Prefix{ + netip.MustParsePrefix("10.107.0.0/16"), + netip.MustParsePrefix("10.108.0.0/16"), + }, + netip.MustParsePrefix("10.192.0.0/12"), + netip.MustParsePrefix("192.0.2.0/24"), + ) + node := readyNode("worker-pool-b", "192.0.2.190") + + workers := routePlanner.Workers( + []corev1.Node{node}, + []corev1.Pod{readyCiliumPod("worker-pool-b")}, + []planner.CiliumNodeState{{ + Name: "worker-pool-b", NodeIP: "192.0.2.190", HealthIP: "10.108.5.1", + PodCIDRs: []string{"10.108.5.0/24"}, + }}, + ) + + require.Len(t, workers, 1) + assert.Equal(t, planner.WorkerStateReady, workers[0].State) + assert.True(t, workers[0].APIReady) + + routes, err := routePlanner.PodRoutes(workers) + require.NoError(t, err) + require.Len(t, routes, 1) + assert.Equal(t, netip.MustParsePrefix("10.108.5.0/24"), routes[0].Destination) + + outside := routePlanner.Workers( + []corev1.Node{node}, + []corev1.Pod{readyCiliumPod("worker-pool-b")}, + []planner.CiliumNodeState{{ + Name: "worker-pool-b", NodeIP: "192.0.2.190", HealthIP: "10.109.5.1", + PodCIDRs: []string{"10.109.5.0/24"}, + }}, + ) + require.Len(t, outside, 1) + assert.False(t, outside[0].APIReady) + assert.Equal(t, planner.WorkerStatePodCIDRInvalid, outside[0].State) + assert.Contains( + t, + outside[0].Reason, + "PodCIDR 10.109.5.0/24 is outside allowed CIDRs 10.107.0.0/16,10.108.0.0/16", + ) +} + func TestPlannerRejectsUnsafeWorkerData(t *testing.T) { t.Parallel() @@ -127,7 +176,7 @@ func TestProbeTrackerThresholds(t *testing.T) { func testPlanner() *planner.Planner { return planner.New( - netip.MustParsePrefix("10.0.0.0/10"), + []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, netip.MustParsePrefix("10.192.0.0/12"), netip.MustParsePrefix("192.0.2.0/24"), ) diff --git a/internal/route/model.go b/internal/route/model.go index 0260387..f4750a5 100644 --- a/internal/route/model.go +++ b/internal/route/model.go @@ -95,3 +95,14 @@ func PrefixWithin(child, parent netip.Prefix) bool { return child.IsValid() && parent.IsValid() && child.Addr().BitLen() == parent.Addr().BitLen() && child.Bits() >= parent.Bits() && parent.Contains(child.Addr()) } + +// PrefixWithinAny reports whether child falls inside any of the parents. +func PrefixWithinAny(child netip.Prefix, parents []netip.Prefix) bool { + for _, parent := range parents { + if PrefixWithin(child, parent) { + return true + } + } + + return false +} diff --git a/internal/route/netlink_linux.go b/internal/route/netlink_linux.go index d561cc0..68959f4 100644 --- a/internal/route/netlink_linux.go +++ b/internal/route/netlink_linux.go @@ -49,7 +49,7 @@ type NetlinkBackend struct { linkIndex int table int protocol netlink.RouteProtocol - podCIDR netip.Prefix + podCIDRs []netip.Prefix serviceCIDR netip.Prefix } @@ -57,10 +57,10 @@ func NewNetlinkBackend( interfaceName string, table int, protocol int, - podCIDR netip.Prefix, + podCIDRs []netip.Prefix, serviceCIDR netip.Prefix, ) (Backend, error) { - return newNetlinkBackend(systemNetlink{}, interfaceName, table, protocol, podCIDR, serviceCIDR) + return newNetlinkBackend(systemNetlink{}, interfaceName, table, protocol, podCIDRs, serviceCIDR) } func newNetlinkBackend( @@ -68,7 +68,7 @@ func newNetlinkBackend( interfaceName string, table int, protocol int, - podCIDR netip.Prefix, + podCIDRs []netip.Prefix, serviceCIDR netip.Prefix, ) (*NetlinkBackend, error) { link, err := api.LinkByName(interfaceName) @@ -81,7 +81,7 @@ func newNetlinkBackend( linkIndex: link.Attrs().Index, table: table, protocol: netlink.RouteProtocol(protocol), - podCIDR: podCIDR, + podCIDRs: podCIDRs, serviceCIDR: serviceCIDR, }, nil } @@ -211,7 +211,7 @@ func (backend *NetlinkBackend) checkConflicts( } func (backend *NetlinkBackend) managedDestination(destination netip.Prefix) bool { - return destination == backend.serviceCIDR || PrefixWithin(destination, backend.podCIDR) + return destination == backend.serviceCIDR || PrefixWithinAny(destination, backend.podCIDRs) } func indexByDestination(routes []netlink.Route) map[netip.Prefix][]netlink.Route { diff --git a/internal/route/netlink_linux_test.go b/internal/route/netlink_linux_test.go index 9c07c9d..6a2bb06 100644 --- a/internal/route/netlink_linux_test.go +++ b/internal/route/netlink_linux_test.go @@ -22,7 +22,7 @@ func TestNetlinkBackendReconcile(t *testing.T) { "test0", 254, 99, - netip.MustParsePrefix("10.0.0.0/10"), + []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, netip.MustParsePrefix("10.192.0.0/12"), ) require.NoError(t, err) @@ -56,7 +56,7 @@ func TestNetlinkBackendRejectsForeignProtocolBeforeMutation(t *testing.T) { "test0", 254, 99, - netip.MustParsePrefix("10.0.0.0/10"), + []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, netip.MustParsePrefix("10.192.0.0/12"), ) require.NoError(t, err) @@ -85,7 +85,7 @@ func TestNetlinkBackendRepairsOwnedRouteMetadataDrift(t *testing.T) { "test0", 254, 99, - netip.MustParsePrefix("10.0.0.0/10"), + []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, netip.MustParsePrefix("10.192.0.0/12"), ) require.NoError(t, err) @@ -131,7 +131,7 @@ func TestNetlinkBackendPrunesOnlyOwnedManagedRoutes(t *testing.T) { "test0", 254, 99, - netip.MustParsePrefix("10.0.0.0/10"), + []netip.Prefix{netip.MustParsePrefix("10.0.0.0/10")}, netip.MustParsePrefix("10.192.0.0/12"), ) require.NoError(t, err) diff --git a/internal/route/netlink_unsupported.go b/internal/route/netlink_unsupported.go index 0a66197..20baf9a 100644 --- a/internal/route/netlink_unsupported.go +++ b/internal/route/netlink_unsupported.go @@ -7,6 +7,6 @@ import ( "net/netip" ) -func NewNetlinkBackend(_ string, _, _ int, _, _ netip.Prefix) (Backend, error) { +func NewNetlinkBackend(_ string, _, _ int, _ []netip.Prefix, _ netip.Prefix) (Backend, error) { return nil, errors.New("the netlink route backend requires Linux") } diff --git a/test/integration/netlink_linux_test.go b/test/integration/netlink_linux_test.go index 76cd491..acffa84 100644 --- a/test/integration/netlink_linux_test.go +++ b/test/integration/netlink_linux_test.go @@ -40,7 +40,7 @@ func TestNetlinkLifecycle(t *testing.T) { integrationLinkName, integrationTable, integrationProtocol, - netip.MustParsePrefix("10.240.0.0/16"), + []netip.Prefix{netip.MustParsePrefix("10.240.0.0/16")}, netip.MustParsePrefix("10.241.0.0/16"), ) require.NoError(t, err)