sigs.k8s.io/external-dns@v0.14.1/source/targetfiltersource.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package source 18 19 import ( 20 "context" 21 22 log "github.com/sirupsen/logrus" 23 24 "sigs.k8s.io/external-dns/endpoint" 25 ) 26 27 // targetFilterSource is a Source that removes endpoints matching the target filter from its wrapped source. 28 type targetFilterSource struct { 29 source Source 30 targetFilter endpoint.TargetFilterInterface 31 } 32 33 // NewTargetFilterSource creates a new targetFilterSource wrapping the provided Source. 34 func NewTargetFilterSource(source Source, targetFilter endpoint.TargetFilterInterface) Source { 35 return &targetFilterSource{source: source, targetFilter: targetFilter} 36 } 37 38 // Endpoints collects endpoints from its wrapped source and returns 39 // them without targets matching the target filter. 40 func (ms *targetFilterSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, error) { 41 result := []*endpoint.Endpoint{} 42 43 endpoints, err := ms.source.Endpoints(ctx) 44 if err != nil { 45 return nil, err 46 } 47 48 for _, ep := range endpoints { 49 filteredTargets := []string{} 50 51 for _, t := range ep.Targets { 52 if ms.targetFilter.Match(t) { 53 filteredTargets = append(filteredTargets, t) 54 } 55 } 56 57 // If all targets are filtered out, skip the endpoint. 58 if len(filteredTargets) == 0 { 59 log.WithField("endpoint", ep).Debugf("Skipping endpoint because all targets were filtered out") 60 continue 61 } 62 63 ep.Targets = filteredTargets 64 65 result = append(result, ep) 66 } 67 68 return result, nil 69 } 70 71 func (ms *targetFilterSource) AddEventHandler(ctx context.Context, handler func()) { 72 ms.source.AddEventHandler(ctx, handler) 73 }