Skip to content

✨ Allow address exclusion #182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 15, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions api/v1alpha1/zz_generated.conversion.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions api/v1alpha2/inclusterippool_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ type InClusterIPPoolSpec struct {
// subnet) when IPv6.
// +optional
AllocateReservedIPAddresses bool `json:"allocateReservedIPAddresses,omitempty"`

// ExcludedAddresses is a list of IP addresses, which will be excluded from
// the set of assignable IP addresses.
// +optional
ExcludedAddresses []string `json:"excludedAddresses,omitempty"`
}

// InClusterIPPoolStatus defines the observed state of InClusterIPPool.
Expand Down
5 changes: 5 additions & 0 deletions api/v1alpha2/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ spec:
IPv4. The provider will allocate the anycast address address (the
first address in the inferred subnet) when IPv6.
type: boolean
excludedAddresses:
description: ExcludedAddresses is a list of IP addresses, which will
be excluded from the set of assignable IP addresses.
items:
type: string
type: array
gateway:
description: Gateway
type: string
Expand Down
6 changes: 6 additions & 0 deletions config/crd/bases/ipam.cluster.x-k8s.io_inclusterippools.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ spec:
IPv4. The provider will allocate the anycast address address (the
first address in the inferred subnet) when IPv6.
type: boolean
excludedAddresses:
description: ExcludedAddresses is a list of IP addresses, which will
be excluded from the set of assignable IP addresses.
items:
type: string
type: array
gateway:
description: Gateway
type: string
Expand Down
5 changes: 5 additions & 0 deletions config/samples/ipam_v1alpha2_globalinclusterippool.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@ spec:
- 10.0.0.2-10.0.0.254
prefix: 24
gateway: 10.0.0.1
excludedAddresses:
- 10.0.0.3-10.0.1.6
- 10.0.0.10
- 10.0.0.192/26

4 changes: 4 additions & 0 deletions config/samples/ipam_v1alpha2_inclusterippool.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ spec:
- 10.0.0.2-10.0.0.254
prefix: 24
gateway: 10.0.0.1
excludedAddresses:
- 10.0.0.3-10.0.1.6
- 10.0.0.10
- 10.0.0.192/26
103 changes: 102 additions & 1 deletion internal/controllers/ipaddressclaim_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ var _ = Describe("IPAddressClaimReconciler", func() {
"10.0.1.0", // reserved network addr
"10.0.1.1", // reserved gateway addr
"10.0.1.2",
"10.0.1.255", // rerved broadcast addr
"10.0.1.255", // reserved broadcast addr
},
},
}
Expand Down Expand Up @@ -284,6 +284,107 @@ var _ = Describe("IPAddressClaimReconciler", func() {
})
})

When("the referenced namespaced pool exists and has exlcuded ip addresses", func() {
const poolName = "test-pool"

BeforeEach(func() {
pool := v1alpha2.InClusterIPPool{
ObjectMeta: metav1.ObjectMeta{
Name: poolName,
Namespace: namespace,
},
Spec: v1alpha2.InClusterIPPoolSpec{
Prefix: 24,
Gateway: "10.0.1.1",
Addresses: []string{
"10.0.1.0/24",
},
ExcludedAddresses: []string{
"10.0.1.2-10.0.1.5",
"10.0.1.7",
},
},
}
Expect(k8sClient.Create(context.Background(), &pool)).To(Succeed())
Eventually(Get(&pool)).Should(Succeed())
})

AfterEach(func() {
deleteClaim("test", namespace)
deleteClaim("test1", namespace)
deleteClaim("test2", namespace)
deleteNamespacedPool(poolName, namespace)
})

It("should not allocate excluded ip addresses", func() {
claim := newClaim("test", namespace, "InClusterIPPool", poolName)
Expect(k8sClient.Create(context.Background(), &claim)).To(Succeed())

expectedIPAddress := ipamv1.IPAddress{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: namespace,
Finalizers: []string{ProtectAddressFinalizer},
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "ipam.cluster.x-k8s.io/v1alpha1",
BlockOwnerDeletion: pointer.Bool(true),
Controller: pointer.Bool(true),
Kind: "IPAddressClaim",
Name: "test",
},
{
APIVersion: "ipam.cluster.x-k8s.io/v1alpha2",
BlockOwnerDeletion: pointer.Bool(true),
Controller: pointer.Bool(false),
Kind: "InClusterIPPool",
Name: poolName,
},
},
},
Spec: ipamv1.IPAddressSpec{
ClaimRef: corev1.LocalObjectReference{
Name: "test",
},
PoolRef: corev1.TypedLocalObjectReference{
APIGroup: pointer.String("ipam.cluster.x-k8s.io"),
Kind: "InClusterIPPool",
Name: poolName,
},
Address: "10.0.1.6",
Prefix: 24,
Gateway: "10.0.1.1",
},
}

Eventually(findAddress("test", namespace)).
WithTimeout(time.Second).WithPolling(100 * time.Millisecond).Should(
EqualObject(&expectedIPAddress, IgnoreAutogeneratedMetadata, IgnoreUIDsOnIPAddress),
)

claim1 := newClaim("test1", namespace, "InClusterIPPool", poolName)
Expect(k8sClient.Create(context.Background(), &claim1)).To(Succeed())

expectedIPAddress1 := expectedIPAddress.DeepCopy()
expectedIPAddress1.Spec.Address = "10.0.1.8"

Eventually(findAddress("test", namespace)).
WithTimeout(time.Second).WithPolling(100 * time.Millisecond).Should(
EqualObject(&expectedIPAddress, IgnoreAutogeneratedMetadata, IgnoreUIDsOnIPAddress),
)

claim2 := newClaim("test2", namespace, "InClusterIPPool", poolName)
Expect(k8sClient.Create(context.Background(), &claim2)).To(Succeed())

expectedIPAddress2 := expectedIPAddress.DeepCopy()
expectedIPAddress2.Spec.Address = "10.0.1.9"
Eventually(findAddress("test", namespace)).
WithTimeout(time.Second).WithPolling(100 * time.Millisecond).Should(
EqualObject(&expectedIPAddress, IgnoreAutogeneratedMetadata, IgnoreUIDsOnIPAddress),
)
})
})

When("the referenced namespaced pool has out of order Addresses", func() {
const poolName = "test-pool"

Expand Down
9 changes: 9 additions & 0 deletions internal/poolutil/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,15 @@ func PoolSpecToIPSet(poolSpec *v1alpha2.InClusterIPPoolSpec) (*netipx.IPSet, err
builder := &netipx.IPSetBuilder{}
builder.AddSet(addressesIPSet)

if len(poolSpec.ExcludedAddresses) > 0 {
excludedAddressesIPSet, err := AddressesToIPSet(poolSpec.ExcludedAddresses)
if err != nil {
return nil, err
}

builder.RemoveSet(excludedAddressesIPSet)
}

if !poolSpec.AllocateReservedIPAddresses {
subnet := netip.PrefixFrom(addressesIPSet.Ranges()[0].From(), poolSpec.Prefix) // safe because of webhook validation
subnetRange := netipx.RangeOfPrefix(subnet)
Expand Down
63 changes: 63 additions & 0 deletions internal/poolutil/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,69 @@ var _ = Describe("PoolSpecToIPSet", func() {
Expect(ipSet.Contains(mustParse("192.168.0.1"))).To(BeFalse())
})
})
Context("With excluded ipv4 addresses", func() {
It("excludes ip addresses from the address pool", func() {
spec := &v1alpha2.InClusterIPPoolSpec{
Gateway: "192.168.0.1",
Prefix: 24,
Addresses: []string{
"192.168.0.0-192.168.0.10",
},
ExcludedAddresses: []string{
"192.168.0.5",
"192.168.0.6",
"192.168.0.7",
},
}
ipSet, err := PoolSpecToIPSet(spec)
Expect(err).ToNot(HaveOccurred())
Expect(ipSet.Contains(mustParse("192.168.0.2"))).To(BeTrue())
Expect(ipSet.Contains(mustParse("192.168.0.3"))).To(BeTrue())
Expect(ipSet.Contains(mustParse("192.168.0.4"))).To(BeTrue())
Expect(ipSet.Contains(mustParse("192.168.0.5"))).To(BeFalse())
Expect(ipSet.Contains(mustParse("192.168.0.6"))).To(BeFalse())
Expect(ipSet.Contains(mustParse("192.168.0.7"))).To(BeFalse())
Expect(ipSet.Contains(mustParse("192.168.0.8"))).To(BeTrue())
Expect(ipSet.Contains(mustParse("192.168.0.9"))).To(BeTrue())
Expect(ipSet.Contains(mustParse("192.168.0.10"))).To(BeTrue())
Expect(ipSet.Contains(mustParse("192.168.0.11"))).To(BeFalse())
Expect(IPSetCount(ipSet)).To(Equal(6))
})
It("excludes ip subnet from the address pool", func() {
spec := &v1alpha2.InClusterIPPoolSpec{
Gateway: "192.168.0.1",
Prefix: 24,
Addresses: []string{
"192.168.0.0/24",
},
ExcludedAddresses: []string{
"192.168.0.128/25",
},
}
ipSet, err := PoolSpecToIPSet(spec)
Expect(err).ToNot(HaveOccurred())
Expect(ipSet.ContainsRange(netipx.MustParseIPRange("192.168.0.2-192.168.0.127"))).To(BeTrue())
Expect(ipSet.ContainsRange(netipx.MustParseIPRange("192.168.0.128-192.168.0.255"))).To(BeFalse())
Expect(IPSetCount(ipSet)).To(Equal(126))
})
It("excludes ip range from the address pool", func() {
spec := &v1alpha2.InClusterIPPoolSpec{
Gateway: "192.168.0.1",
Prefix: 24,
Addresses: []string{
"192.168.0.0/24",
},
ExcludedAddresses: []string{
"192.168.0.2-192.168.0.20",
},
}
ipSet, err := PoolSpecToIPSet(spec)
Expect(err).ToNot(HaveOccurred())
Expect(ipSet.ContainsRange(netipx.MustParseIPRange("192.168.0.2-192.168.0.20"))).To(BeFalse())
Expect(ipSet.ContainsRange(netipx.MustParseIPRange("192.168.0.21-192.168.0.254"))).To(BeTrue())
Expect(IPSetCount(ipSet)).To(Equal(234))
})
})

Context("with IPv6 addresses", func() {
It("converts a pool spec to a set", func() {
Expand Down
23 changes: 19 additions & 4 deletions internal/webhooks/inclusterippool.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ func (webhook *InClusterIPPool) ValidateCreate(_ context.Context, obj runtime.Ob
func (webhook *InClusterIPPool) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) error {
newPool, ok := newObj.(types.GenericInClusterPool)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a InClusterIPPool or an GlobalInClusterIPPool but got a %T", newObj))
return apierrors.NewBadRequest(fmt.Sprintf("expected an InClusterIPPool or a GlobalInClusterIPPool but got a %T", newObj))
}
oldPool, ok := oldObj.(types.GenericInClusterPool)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a InClusterIPPool or an GlobalInClusterIPPool but got a %T", oldObj))
return apierrors.NewBadRequest(fmt.Sprintf("expected an InClusterIPPool or a GlobalInClusterIPPool but got a %T", oldObj))
}

err := webhook.validate(oldPool, newPool)
Expand Down Expand Up @@ -135,7 +135,7 @@ func (webhook *InClusterIPPool) ValidateUpdate(ctx context.Context, oldObj, newO
}

if outOfRange := outOfRangeIPSet.Ranges(); len(outOfRange) > 0 {
return apierrors.NewBadRequest(fmt.Sprintf("pool addresses does not contain allocated addresses: %v", outOfRange))
return apierrors.NewBadRequest(fmt.Sprintf("pool addresses do not contain allocated addresses: %v", outOfRange))
}

return nil
Expand All @@ -145,7 +145,7 @@ func (webhook *InClusterIPPool) ValidateUpdate(ctx context.Context, oldObj, newO
func (webhook *InClusterIPPool) ValidateDelete(ctx context.Context, obj runtime.Object) (reterr error) {
pool, ok := obj.(types.GenericInClusterPool)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a InClusterIPPool or an GlobalInClusterIPPool but got a %T", obj))
return apierrors.NewBadRequest(fmt.Sprintf("expected an InClusterIPPool or a GlobalInClusterIPPool but got a %T", obj))
}

if _, ok := pool.GetAnnotations()[SkipValidateDeleteWebhookAnnotation]; ok {
Expand Down Expand Up @@ -212,6 +212,21 @@ func (webhook *InClusterIPPool) validate(_, newPool types.GenericInClusterPool)
}
}

for _, address := range newPool.PoolSpec().ExcludedAddresses {
ipSet, err := poolutil.AddressToIPSet(address)
if err != nil {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "excludedAddresses"), address, "provided address is not a valid IP, range, nor CIDR"))
continue
}
from := ipSet.Ranges()[0].From()
hasIPv4Addr = hasIPv4Addr || from.Is4()
hasIPv6Addr = hasIPv6Addr || from.Is6()
}

if hasIPv4Addr && hasIPv6Addr {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "excludedAddresses"), newPool.PoolSpec().ExcludedAddresses, "provided addresses are of mixed IP families"))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to make sure that the family of excludedAddresses matches the family of addresses, and not that the family is the same for all. This approach should work, but it would be good to be a bit more explicit about it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem, will add an additional check.

I initially thought that it wouldn't really matter as we are creating a set of IPs from the provided addresses and then just removing whatever is being found in the excluded addresses. Therefore if you attempt to remove ipv6 addresses from ipv4 addresses and vice versa, nothing will happen.

}

if len(allErrs) == 0 {
errs := validateAddressesAreWithinPrefix(newPool.PoolSpec())
if len(errs) != 0 {
Expand Down
Loading