Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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 {
Expand All @@ -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),
Expand Down
75 changes: 57 additions & 18 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"errors"
"fmt"
"net/netip"
"strings"
"time"
"unicode"
)

const (
Expand Down Expand Up @@ -93,7 +95,7 @@ type LoggingConfig struct {

type Validated struct {
Config
PodCIDR netip.Prefix
PodCIDRs []netip.Prefix
ServiceCIDR netip.Prefix
RouterCIDR netip.Prefix
}
Expand Down Expand Up @@ -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)
}
Expand All @@ -145,26 +147,35 @@ func (cfg Config) Validate() (Validated, error) {

validationErrors = append(
validationErrors,
validatePrefixRelationships(podCIDR, serviceCIDR, routerCIDR)...,
validatePrefixRelationships(podCIDRs, serviceCIDR, routerCIDR)...,
)

if err := errors.Join(validationErrors...); err != nil {
return Validated{}, fmt.Errorf("invalid configuration: %w", err)
}

// 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 == "" {
Expand Down Expand Up @@ -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) {
Expand All @@ -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())
}
57 changes: 54 additions & 3 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config_test

import (
"net/netip"
"os"
"path/filepath"
"testing"
Expand All @@ -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())
}
Expand All @@ -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()

Expand All @@ -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) {
Expand Down
6 changes: 5 additions & 1 deletion internal/config/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion internal/controller/reconciler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
)
Expand Down
52 changes: 40 additions & 12 deletions internal/discovery/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/netip"
"slices"
"strings"
"unicode"

"github.com/labring-sigs/route-controller/internal/config"
corev1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -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 {
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand All @@ -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"]
Expand Down
Loading
Loading