sigs.k8s.io/external-dns@v0.14.1/source/fake.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 /* 18 Note: currently only supports IP targets (A records), not hostname targets 19 */ 20 21 package source 22 23 import ( 24 "context" 25 "fmt" 26 "math/rand" 27 "net" 28 29 "sigs.k8s.io/external-dns/endpoint" 30 ) 31 32 // fakeSource is an implementation of Source that provides dummy endpoints for 33 // testing/dry-running of dns providers without needing an attached Kubernetes cluster. 34 type fakeSource struct { 35 dnsName string 36 } 37 38 const ( 39 defaultFQDNTemplate = "example.com" 40 ) 41 42 // NewFakeSource creates a new fakeSource with the given config. 43 func NewFakeSource(fqdnTemplate string) (Source, error) { 44 if fqdnTemplate == "" { 45 fqdnTemplate = defaultFQDNTemplate 46 } 47 48 return &fakeSource{ 49 dnsName: fqdnTemplate, 50 }, nil 51 } 52 53 func (sc *fakeSource) AddEventHandler(ctx context.Context, handler func()) { 54 } 55 56 // Endpoints returns endpoint objects. 57 func (sc *fakeSource) Endpoints(ctx context.Context) ([]*endpoint.Endpoint, error) { 58 endpoints := make([]*endpoint.Endpoint, 10) 59 60 for i := 0; i < 10; i++ { 61 endpoints[i], _ = sc.generateEndpoint() 62 } 63 64 return endpoints, nil 65 } 66 67 func (sc *fakeSource) generateEndpoint() (*endpoint.Endpoint, error) { 68 ep := endpoint.NewEndpoint( 69 generateDNSName(4, sc.dnsName), 70 endpoint.RecordTypeA, 71 generateIPAddress(), 72 ) 73 74 return ep, nil 75 } 76 77 func generateIPAddress() string { 78 // 192.0.2.[1-255] is reserved by RFC 5737 for documentation and examples 79 return net.IPv4( 80 byte(192), 81 byte(0), 82 byte(2), 83 byte(rand.Intn(253)+1), 84 ).String() 85 } 86 87 var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz") 88 89 func generateDNSName(prefixLength int, dnsName string) string { 90 prefixBytes := make([]rune, prefixLength) 91 92 for i := range prefixBytes { 93 prefixBytes[i] = letterRunes[rand.Intn(len(letterRunes))] 94 } 95 96 prefixStr := string(prefixBytes) 97 98 return fmt.Sprintf("%s.%s", prefixStr, dnsName) 99 }