github.com/percona/percona-xtradb-cluster-operator@v1.14.0/cmd/peer-list/main.go (about) 1 /* 2 Copyright 2014 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 // A small utility program to lookup hostnames of endpoints in a service. 18 package main 19 20 import ( 21 "flag" 22 "fmt" 23 "log" 24 "net" 25 "os" 26 "os/exec" 27 "os/signal" 28 "regexp" 29 "sort" 30 "strings" 31 "syscall" 32 "time" 33 34 "k8s.io/apimachinery/pkg/util/sets" 35 ) 36 37 const ( 38 pollPeriod = 1 * time.Second 39 ) 40 41 var ( 42 onChange = flag.String("on-change", "", "Script to run on change, must accept a new line separated list of peers via stdin.") 43 onStart = flag.String("on-start", "", "Script to run on start, must accept a new line separated list of peers via stdin.") 44 svc = flag.String("service", "", "Governing service responsible for the DNS records of the domain this pod is in.") 45 namespace = flag.String("ns", "", "The namespace this pod is running in. If unspecified, the POD_NAMESPACE env var is used.") 46 domain = flag.String("domain", "", "The Cluster Domain which is used by the Cluster, if not set tries to determine it from /etc/resolv.conf file.") 47 ) 48 49 func lookup(svcName string) (sets.String, error) { 50 endpoints := sets.NewString() 51 _, srvRecords, err := net.LookupSRV("", "", svcName) 52 if err != nil { 53 return endpoints, err 54 } 55 for _, srvRecord := range srvRecords { 56 // The SRV records ends in a "." for the root domain 57 ep := fmt.Sprintf("%v", srvRecord.Target[:len(srvRecord.Target)-1]) 58 endpoints.Insert(ep) 59 } 60 return endpoints, nil 61 } 62 63 func shellOut(sendStdin, script string) { 64 log.Printf("execing: %v with stdin: %v", script, sendStdin) 65 // TODO: Switch to sending stdin from go 66 out, err := exec.Command("bash", "-c", fmt.Sprintf("echo -e '%v' | %v", sendStdin, script)).CombinedOutput() 67 if err != nil { 68 log.Fatalf("Failed to execute %v: %v, err: %v", script, string(out), err) 69 } 70 log.Print(string(out)) 71 } 72 73 func main() { 74 // Custom signal handler for SIGUSR1. This is needed because the 75 // Docker image (percona/percona-xtradb-cluster-operator:$version-haproxy) 76 // sets the STOPSIGNAL to SIGUSR1 to shutdown HAProxy gracefully. 77 signalChan := make(chan os.Signal, 1) 78 signal.Notify(signalChan, syscall.SIGUSR1) 79 go func() { 80 <-signalChan 81 os.Exit(0) 82 }() 83 84 flag.Parse() 85 86 ns := *namespace 87 if ns == "" { 88 ns = os.Getenv("POD_NAMESPACE") 89 } 90 log.Printf("Peer finder enter") 91 var domainName string 92 93 // If domain is not provided, try to get it from resolv.conf 94 if *domain == "" { 95 resolvConfBytes, err := os.ReadFile("/etc/resolv.conf") 96 resolvConf := string(resolvConfBytes) 97 if err != nil { 98 log.Fatal("Unable to read /etc/resolv.conf") 99 } 100 101 var re *regexp.Regexp 102 if ns == "" { 103 // Looking for a domain that looks like with *.svc.** 104 re, err = regexp.Compile(`\A(.*\n)*search\s{1,}(.*\s{1,})*(?P<goal>[a-zA-Z0-9-]{1,63}.svc.([a-zA-Z0-9-]{1,63}\.)*[a-zA-Z0-9]{2,63})`) 105 } else { 106 // Looking for a domain that looks like svc.** 107 re, err = regexp.Compile(`\A(.*\n)*search\s{1,}(.*\s{1,})*(?P<goal>svc.([a-zA-Z0-9-]{1,63}\.)*[a-zA-Z0-9]{2,63})`) 108 } 109 if err != nil { 110 log.Fatalf("Failed to create regular expression: %v", err) 111 } 112 113 groupNames := re.SubexpNames() 114 result := re.FindStringSubmatch(resolvConf) 115 for k, v := range result { 116 if groupNames[k] == "goal" { 117 if ns == "" { 118 // Domain is complete if ns is empty 119 domainName = v 120 } else { 121 // Need to convert svc.** into ns.svc.** 122 domainName = ns + "." + v 123 } 124 break 125 } 126 } 127 log.Printf("Determined Domain to be %s", domainName) 128 } else { 129 domainName = strings.Join([]string{ns, "svc", *domain}, ".") 130 } 131 132 if *svc == "" || domainName == "" || (*onChange == "" && *onStart == "") { 133 log.Fatalf("Incomplete args, require -on-change and/or -on-start, -service and -ns or an env var for POD_NAMESPACE.") 134 } 135 136 script := *onStart 137 if script == "" { 138 script = *onChange 139 log.Printf("No on-start supplied, on-change %v will be applied on start.", script) 140 } 141 newPeers := sets.NewString() 142 var err error 143 for peers := sets.NewString(); script != ""; time.Sleep(pollPeriod) { 144 newPeers, err = lookup(*svc) 145 if err != nil { 146 log.Printf("%v", err) 147 148 if lerr, ok := err.(*net.DNSError); ok && lerr.IsNotFound { 149 // Service not resolved - no endpoints, so reset peers list 150 peers = sets.NewString() 151 continue 152 } 153 } 154 peerList := newPeers.List() 155 sort.Strings(peerList) 156 if strings.Join(peers.List(), ":") != strings.Join(newPeers.List(), ":") { 157 log.Printf("Peer list updated\nwas %v\nnow %v", peers.List(), newPeers.List()) 158 shellOut(strings.Join(peerList, "\n"), script) 159 peers = newPeers 160 } 161 script = *onChange 162 } 163 // TODO: Exit if there's no on-change? 164 log.Printf("Peer finder exiting") 165 }