knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/network/domain.go (about) 1 /* 2 Copyright 2019 The Knative 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 network 18 19 import ( 20 "bufio" 21 "fmt" 22 "io" 23 "os" 24 "strings" 25 "sync" 26 ) 27 28 const ( 29 resolverFileName = "/etc/resolv.conf" 30 clusterDomainEnvKey = "CLUSTER_DOMAIN" 31 defaultDomainName = "cluster.local" 32 ) 33 34 var ( 35 domainName = defaultDomainName 36 once sync.Once 37 ) 38 39 // GetServiceHostname returns the fully qualified service hostname 40 func GetServiceHostname(name, namespace string) string { 41 return fmt.Sprintf("%s.%s.svc.%s", name, namespace, GetClusterDomainName()) 42 } 43 44 // GetClusterDomainName returns cluster's domain name or an error 45 // Closes issue: https://github.com/knative/eventing/issues/714 46 func GetClusterDomainName() string { 47 once.Do(func() { 48 f, err := os.Open(resolverFileName) 49 if err != nil { 50 return 51 } 52 defer f.Close() 53 domainName = getClusterDomainName(f) 54 }) 55 return domainName 56 } 57 58 func getClusterDomainName(r io.Reader) string { 59 // First check the ENV variable (allows override). 60 if domain := os.Getenv(clusterDomainEnvKey); len(domain) > 0 { 61 return domain 62 } 63 64 // Then look in the conf file. 65 for scanner := bufio.NewScanner(r); scanner.Scan(); { 66 elements := strings.Split(scanner.Text(), " ") 67 if elements[0] != "search" { 68 continue 69 } 70 for _, e := range elements[1:] { 71 if strings.HasPrefix(e, "svc.") { 72 return strings.TrimSuffix(e[4:], ".") 73 } 74 } 75 } 76 77 // For all abnormal cases return default domain name. 78 return defaultDomainName 79 }