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
40 changes: 20 additions & 20 deletions docs/sources/about.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,26 @@ A source in ExternalDNS defines where DNS records are discovered from within you
ExternalDNS watches the specified sources for hostname information and uses it to create, update, or delete DNS records accordingly. Multiple sources can be configured simultaneously to support diverse environments.

| Source | Resources | annotation-filter | label-filter |
| --------------------------------------- | ----------------------------------------------------------------------------- | ----------------- | ------------ |
| ambassador-host | Host.getambassador.io | Yes | Yes |
|-----------------------------------------|-------------------------------------------------------------------------------|:-----------------:|:------------:|
| ambassador-host | Host.getambassador.io | Yes | Yes |
| connector | | | |
| contour-httpproxy | HttpProxy.projectcontour.io | Yes | |
| contour-httpproxy | HttpProxy.projectcontour.io | Yes | |
| cloudfoundry | | | |
| [crd](crd.md) | DNSEndpoint.externaldns.k8s.io | Yes | Yes |
| [f5-virtualserver](f5-virtualserver.md) | VirtualServer.cis.f5.com | Yes | |
| [gateway-grpcroute](gateway.md) | GRPCRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-httproute](gateway.md) | HTTPRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-tcproute](gateway.md) | TCPRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-tlsroute](gateway.md) | TLSRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-udproute](gateway.md) | UDPRoute.gateway.networking.k8s.io | Yes | Yes |
| [crd](crd.md) | DNSEndpoint.externaldns.k8s.io | Yes | Yes |
| [f5-virtualserver](f5-virtualserver.md) | VirtualServer.cis.f5.com | Yes | |
| [gateway-grpcroute](gateway.md) | GRPCRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-httproute](gateway.md) | HTTPRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-tcproute](gateway.md) | TCPRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-tlsroute](gateway.md) | TLSRoute.gateway.networking.k8s.io | Yes | Yes |
| [gateway-udproute](gateway.md) | UDPRoute.gateway.networking.k8s.io | Yes | Yes |
| [gloo-proxy](gloo-proxy.md) | Proxy.gloo.solo.io | | |
| [ingress](ingress.md) | Ingress.networking.k8s.io | Yes | Yes |
| [istio-gateway](istio.md) | Gateway.networking.istio.io | Yes | |
| [istio-virtualservice](istio.md) | VirtualService.networking.istio.io | Yes | |
| [kong-tcpingress](kong.md) | TCPIngress.configuration.konghq.com | Yes | |
| [node](nodes.md) | Node | Yes | Yes |
| [openshift-route](openshift.md) | Route.route.openshift.io | Yes | Yes |
| [pod](pod.md) | Pod | | |
| [service](service.md) | Service | Yes | Yes |
| skipper-routegroup | RouteGroup.zalando.org | Yes | |
| [traefik-proxy](traefik-proxy.md) | IngressRoute.traefik.io IngressRouteTCP.traefik.io IngressRouteUDP.traefik.io | Yes | |
| [ingress](ingress.md) | Ingress.networking.k8s.io | Yes | Yes |
| [istio-gateway](istio.md) | Gateway.networking.istio.io | Yes | |
| [istio-virtualservice](istio.md) | VirtualService.networking.istio.io | Yes | |
| [kong-tcpingress](kong.md) | TCPIngress.configuration.konghq.com | Yes | |
| [node](nodes.md) | Node | Yes | Yes |
| [openshift-route](openshift.md) | Route.route.openshift.io | Yes | Yes |
| [pod](pod.md) | Pod | Yes | Yes |
| [service](service.md) | Service | Yes | Yes |
| skipper-routegroup | RouteGroup.zalando.org | Yes | |
| [traefik-proxy](traefik-proxy.md) | IngressRoute.traefik.io IngressRouteTCP.traefik.io IngressRouteUDP.traefik.io | Yes | |
6 changes: 6 additions & 0 deletions source/annotations/processors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ func TestParseAnnotationFilter(t *testing.T) {
expectedSelector: labels.Set{}.AsSelector(),
expectError: false,
},
{
name: "wrong annotation filter",
annotationFilter: "=test",
expectedSelector: nil,
expectError: true,
},
}

for _, tt := range tests {
Expand Down
113 changes: 113 additions & 0 deletions source/informers/indexers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
Copyright 2025 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package informers

import (
"fmt"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"

"sigs.k8s.io/external-dns/source/annotations"
)

const (
IndexWithSelectors = "withSelectors"
)

type IndexSelectorOptions struct {
annotationFilter labels.Selector
labelSelector labels.Selector
}

func IndexSelectorWithAnnotationFilter(input string) func(options *IndexSelectorOptions) {
return func(options *IndexSelectorOptions) {
if input == "" {
return
}
selector, err := annotations.ParseFilter(input)
if err != nil {
return
}
options.annotationFilter = selector
}
}

func IndexSelectorWithLabelSelector(input labels.Selector) func(options *IndexSelectorOptions) {
return func(options *IndexSelectorOptions) {
options.labelSelector = input
}
}

// IndexerWithOptions is a generic function that allows adding multiple indexers
// to a SharedIndexInformer for a specific Kubernetes resource type T. It accepts
// a variadic list of indexer functions, which define custom indexing logic.
//
// Each indexer function is applied to objects of type T, enabling flexible and
// reusable indexing based on annotations, labels, or other criteria.
//
// Example usage:
// err := IndexerWithOptions[*v1.Pod](
//
// IndexSelectorWithAnnotationFilter("example-annotation"),
// IndexSelectorWithLabelSelector(labels.SelectorFromSet(labels.Set{"app": "my-app"})),
//
// )
//
// This function ensures type safety and simplifies the process of adding
// custom indexers to informers.
func IndexerWithOptions[T metav1.Object](optFns ...func(options *IndexSelectorOptions)) cache.Indexers {
options := IndexSelectorOptions{}
for _, fn := range optFns {
fn(&options)
}

return cache.Indexers{
IndexWithSelectors: func(obj interface{}) ([]string, error) {
entity, ok := obj.(T)
if !ok {
return nil, fmt.Errorf("object is not of type %T", new(T))
}

if options.annotationFilter != nil && !options.annotationFilter.Matches(labels.Set(entity.GetAnnotations())) {
return nil, nil
}

if options.labelSelector != nil && !options.labelSelector.Matches(labels.Set(entity.GetLabels())) {
return nil, nil
}
key := types.NamespacedName{Namespace: entity.GetNamespace(), Name: entity.GetName()}.String()
return []string{key}, nil
},
}
}

// GetByKey retrieves an object of type T (metav1.Object) from the given cache.Indexer by its key.
// It returns the object and an error if the retrieval or type assertion fails.
// If the object does not exist, it returns the zero value of T and nil.
func GetByKey[T metav1.Object](indexer cache.Indexer, key string) (T, error) {
var entity T
obj, exists, err := indexer.GetByKey(key)
if err != nil || !exists {
return entity, err
}

entity, ok := obj.(T)
if !ok {
return entity, fmt.Errorf("object is not of type %T", new(T))
}
return entity, nil
}
185 changes: 185 additions & 0 deletions source/informers/indexers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/*
Copyright 2025 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package informers

import (
"testing"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/external-dns/source/annotations"
)

func TestIndexerWithOptions_FilterByAnnotation(t *testing.T) {
indexers := IndexerWithOptions[*unstructured.Unstructured](
IndexSelectorWithAnnotationFilter("example-annotation"),
)

obj := &unstructured.Unstructured{}
obj.SetAnnotations(map[string]string{"example-annotation": "value"})
obj.SetNamespace("default")
obj.SetName("test-object")

keys, err := indexers[IndexWithSelectors](obj)
assert.NoError(t, err)
assert.Equal(t, []string{"default/test-object"}, keys)
}

func TestIndexerWithOptions_FilterByLabel(t *testing.T) {
labelSelector := labels.SelectorFromSet(labels.Set{"app": "nginx"})
indexers := IndexerWithOptions[*corev1.Pod](
IndexSelectorWithLabelSelector(labelSelector),
)

obj := &corev1.Pod{}
obj.SetLabels(map[string]string{"app": "nginx"})
obj.SetNamespace("default")
obj.SetName("test-object")

keys, err := indexers[IndexWithSelectors](obj)
assert.NoError(t, err)
assert.Equal(t, []string{"default/test-object"}, keys)
}

func TestIndexerWithOptions_NoMatch(t *testing.T) {
labelSelector := labels.SelectorFromSet(labels.Set{"app": "nginx"})
indexers := IndexerWithOptions[*unstructured.Unstructured](
IndexSelectorWithLabelSelector(labelSelector),
)

obj := &unstructured.Unstructured{}
obj.SetLabels(map[string]string{"app": "apache"})
obj.SetNamespace("default")
obj.SetName("test-object")

keys, err := indexers[IndexWithSelectors](obj)
assert.NoError(t, err)
assert.Nil(t, keys)
}

func TestIndexerWithOptions_InvalidType(t *testing.T) {
indexers := IndexerWithOptions[*unstructured.Unstructured]()

obj := "invalid-object"

keys, err := indexers[IndexWithSelectors](obj)
assert.Error(t, err)
assert.Nil(t, keys)
assert.Contains(t, err.Error(), "object is not of type")
}

func TestIndexerWithOptions_EmptyOptions(t *testing.T) {
indexers := IndexerWithOptions[*unstructured.Unstructured]()

obj := &unstructured.Unstructured{}
obj.SetNamespace("default")
obj.SetName("test-object")

keys, err := indexers["withSelectors"](obj)
assert.NoError(t, err)
assert.Equal(t, []string{"default/test-object"}, keys)
}

func TestIndexerWithOptions_AnnotationFilterNoMatch(t *testing.T) {
indexers := IndexerWithOptions[*unstructured.Unstructured](
IndexSelectorWithAnnotationFilter("example-annotation=value"),
)

obj := &unstructured.Unstructured{}
obj.SetAnnotations(map[string]string{"other-annotation": "value"})
obj.SetNamespace("default")
obj.SetName("test-object")

keys, err := indexers[IndexWithSelectors](obj)
assert.NoError(t, err)
assert.Nil(t, keys)
}

func TestIndexSelectorWithAnnotationFilter(t *testing.T) {
tests := []struct {
name string
input string
expectedFilter labels.Selector
}{
{
name: "valid input",
input: "key=value",
expectedFilter: func() labels.Selector { s, _ := annotations.ParseFilter("key=value"); return s }(),
},
{
name: "empty input",
input: "",
expectedFilter: nil,
},
{
name: "key only filter",
input: "app",
expectedFilter: func() labels.Selector { s, _ := annotations.ParseFilter("app"); return s }(),
},
{
name: "poisoned input",
input: "=app",
expectedFilter: nil,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
options := &IndexSelectorOptions{}
IndexSelectorWithAnnotationFilter(tt.input)(options)
assert.Equal(t, tt.expectedFilter, options.annotationFilter)
})
}
}

func TestGetByKey_ObjectExists(t *testing.T) {
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
pod := &corev1.Pod{}
pod.SetNamespace("default")
pod.SetName("test-pod")

err := indexer.Add(pod)
assert.NoError(t, err)

result, err := GetByKey[*corev1.Pod](indexer, "default/test-pod")
assert.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, "test-pod", result.GetName())
}

func TestGetByKey_ObjectDoesNotExist(t *testing.T) {
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})

result, err := GetByKey[*corev1.Pod](indexer, "default/non-existent-pod")
assert.NoError(t, err)
assert.Nil(t, result)
}

func TestGetByKey_TypeAssertionFailure(t *testing.T) {
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})
service := &corev1.Service{}
service.SetNamespace("default")
service.SetName("test-service")

err := indexer.Add(service)
assert.NoError(t, err)

result, err := GetByKey[*corev1.Pod](indexer, "default/test-service")
assert.Error(t, err)
assert.Contains(t, err.Error(), "object is not of type")
assert.Nil(t, result)
}
Loading
Loading