k8s.io/kubernetes@v1.29.3/test/images/agnhost/no-snat-test-proxy/main.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 nosnatproxy 18 19 import ( 20 "fmt" 21 "io" 22 "net/http" 23 "os" 24 25 "github.com/spf13/cobra" 26 "k8s.io/component-base/logs" 27 ) 28 29 // CmdNoSnatTestProxy is used by agnhost Cobra. 30 var CmdNoSnatTestProxy = &cobra.Command{ 31 Use: "no-snat-test-proxy", 32 Short: "Creates a proxy for the /checknosnat endpoint", 33 Long: `Creates the /checknosnat endpoint which proxies the request to the given target (/checknosnat?target=target_ip&ips=ip1,ip2) and returns its response, or a 500 response on error.`, 34 Args: cobra.MaximumNArgs(0), 35 Run: main, 36 } 37 38 var port string 39 40 func init() { 41 CmdNoSnatTestProxy.Flags().StringVar(&port, "port", "31235", "The port to serve /checknosnat endpoint on.") 42 } 43 44 // This Pod's /checknosnat takes `target` and `ips` arguments, and queries {target}/checknosnat?ips={ips} 45 46 type masqTestProxy struct { 47 Port string 48 } 49 50 func main(cmd *cobra.Command, args []string) { 51 m := &masqTestProxy{ 52 Port: port, 53 } 54 55 logs.InitLogs() 56 defer logs.FlushLogs() 57 58 if err := m.Run(); err != nil { 59 fmt.Fprintf(os.Stderr, "%v\n", err) 60 os.Exit(1) 61 } 62 } 63 64 func (m *masqTestProxy) Run() error { 65 // register handler 66 http.HandleFunc("/checknosnat", checknosnat) 67 68 // spin up the server 69 return http.ListenAndServe(":"+m.Port, nil) 70 } 71 72 func checknosnatURL(pip, ips string) string { 73 return fmt.Sprintf("http://%s/checknosnat?ips=%s", pip, ips) 74 } 75 76 func checknosnat(w http.ResponseWriter, req *http.Request) { 77 url := checknosnatURL(req.URL.Query().Get("target"), req.URL.Query().Get("ips")) 78 resp, err := http.Get(url) 79 if err != nil { 80 w.WriteHeader(500) 81 fmt.Fprintf(w, "error querying %q, err: %v", url, err) 82 return 83 } 84 defer resp.Body.Close() 85 86 body, err := io.ReadAll(resp.Body) 87 if err != nil { 88 w.WriteHeader(500) 89 fmt.Fprintf(w, "error reading body of response from %q, err: %v", url, err) 90 return 91 } 92 93 // Respond the same status code and body as /checknosnat on the internal Pod 94 w.WriteHeader(resp.StatusCode) 95 w.Write(body) 96 }