Skip to content

Commit

Permalink
Set host bits to zero for PodCIDRs (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
hardikdr authored Oct 2, 2024
1 parent 194a25a commit ecf1779
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
19 changes: 18 additions & 1 deletion internal/metal-load-balancer-controller/node_ipam_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package metal_load_balancer_controller
import (
"context"
"fmt"
"net"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -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
Expand All @@ -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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")),
))

})
Expand Down

0 comments on commit ecf1779

Please sign in to comment.