main.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "net/http"
  18. "os"
  19. "github.com/spf13/pflag"
  20. cliflag "k8s.io/component-base/cli/flag"
  21. "k8s.io/component-base/logs"
  22. )
  23. // This Pod's /checknosnat takes `target` and `ips` arguments, and queries {target}/checknosnat?ips={ips}
  24. type masqTestProxy struct {
  25. Port string
  26. }
  27. func newMasqTestProxy() *masqTestProxy {
  28. return &masqTestProxy{
  29. Port: "31235",
  30. }
  31. }
  32. func (m *masqTestProxy) AddFlags(fs *pflag.FlagSet) {
  33. fs.StringVar(&m.Port, "port", m.Port, "The port to serve /checknosnat endpoint on.")
  34. }
  35. func main() {
  36. m := newMasqTestProxy()
  37. m.AddFlags(pflag.CommandLine)
  38. cliflag.InitFlags()
  39. logs.InitLogs()
  40. defer logs.FlushLogs()
  41. if err := m.Run(); err != nil {
  42. fmt.Fprintf(os.Stderr, "%v\n", err)
  43. os.Exit(1)
  44. }
  45. }
  46. func (m *masqTestProxy) Run() error {
  47. // register handler
  48. http.HandleFunc("/checknosnat", checknosnat)
  49. // spin up the server
  50. return http.ListenAndServe(":"+m.Port, nil)
  51. }
  52. func checknosnatURL(pip, ips string) string {
  53. return fmt.Sprintf("http://%s/checknosnat?ips=%s", pip, ips)
  54. }
  55. func checknosnat(w http.ResponseWriter, req *http.Request) {
  56. url := checknosnatURL(req.URL.Query().Get("target"), req.URL.Query().Get("ips"))
  57. resp, err := http.Get(url)
  58. if err != nil {
  59. w.WriteHeader(500)
  60. fmt.Fprintf(w, "error querying %q, err: %v", url, err)
  61. } else {
  62. body, err := ioutil.ReadAll(resp.Body)
  63. if err != nil {
  64. w.WriteHeader(500)
  65. fmt.Fprintf(w, "error reading body of response from %q, err: %v", url, err)
  66. } else {
  67. // Respond the same status code and body as /checknosnat on the internal Pod
  68. w.WriteHeader(resp.StatusCode)
  69. w.Write(body)
  70. }
  71. }
  72. resp.Body.Close()
  73. }