From ecf17798e7a84129e136f1ce33d0282f614ec61b Mon Sep 17 00:00:00 2001 From: Hardik Dodiya Date: Wed, 2 Oct 2024 11:16:57 +0200 Subject: [PATCH] Set host bits to zero for PodCIDRs (#19) --- .../node_ipam_controller.go | 19 ++++++++++++++++++- .../node_ipam_controller_test.go | 4 ++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/internal/metal-load-balancer-controller/node_ipam_controller.go b/internal/metal-load-balancer-controller/node_ipam_controller.go index 32ffdf5..e779af7 100644 --- a/internal/metal-load-balancer-controller/node_ipam_controller.go +++ b/internal/metal-load-balancer-controller/node_ipam_controller.go @@ -6,6 +6,7 @@ package metal_load_balancer_controller import ( "context" "fmt" + "net" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" @@ -37,7 +38,13 @@ func (r *NodeIPAMReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c for _, addr := range node.Status.Addresses { if addr.Type == corev1.NodeInternalIP { - podCIDR := fmt.Sprintf("%s/%d", addr.Address, r.NodeCIDRMaskSize) + ip := net.ParseIP(addr.Address) + if ip == nil { + return ctrl.Result{}, fmt.Errorf("invalid IP address format") + } + + maskedIP := zeroHostBits(ip, r.NodeCIDRMaskSize) + podCIDR := fmt.Sprintf("%s/%d", maskedIP, r.NodeCIDRMaskSize) nodeBase := node.DeepCopy() node.Spec.PodCIDR = podCIDR @@ -58,6 +65,16 @@ func (r *NodeIPAMReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c return ctrl.Result{}, nil } +func zeroHostBits(ip net.IP, maskSize int) net.IP { + if ip.To4() != nil { + mask := net.CIDRMask(maskSize, 32) + return ip.Mask(mask) + } else { + mask := net.CIDRMask(maskSize, 128) + return ip.Mask(mask) + } +} + // SetupWithManager sets up the controller with the Manager. func (r *NodeIPAMReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). diff --git a/internal/metal-load-balancer-controller/node_ipam_controller_test.go b/internal/metal-load-balancer-controller/node_ipam_controller_test.go index 0b44be4..373fad5 100644 --- a/internal/metal-load-balancer-controller/node_ipam_controller_test.go +++ b/internal/metal-load-balancer-controller/node_ipam_controller_test.go @@ -36,8 +36,8 @@ var _ = Describe("Node IPAM Controller", func() { DeferCleanup(k8sClient.Delete, node) Eventually(Object(node)).Should(SatisfyAll( - HaveField("Spec.PodCIDR", Equal("1a10:c0de::1/64")), - HaveField("Spec.PodCIDRs", ContainElement("1a10:c0de::1/64")), + HaveField("Spec.PodCIDR", Equal("1a10:c0de::/64")), + HaveField("Spec.PodCIDRs", ContainElement("1a10:c0de::/64")), )) })