main.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /*
  2. Copyright 2014 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 net
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "log"
  20. "net/http"
  21. "os"
  22. "strings"
  23. "github.com/spf13/cobra"
  24. "k8s.io/kubernetes/test/images/agnhost/net/common"
  25. "k8s.io/kubernetes/test/images/agnhost/net/nat"
  26. )
  27. type runnerMap map[string]common.Runner
  28. var (
  29. // flags for the command line. See usage args below for
  30. // descriptions.
  31. flags struct {
  32. Serve string
  33. Runner string
  34. Options string
  35. }
  36. // runners is a map from runner name to runner instance.
  37. runners = makeRunnerMap()
  38. )
  39. type logOutput struct {
  40. b bytes.Buffer
  41. }
  42. // CmdNet is used by agnhost Cobra.
  43. var CmdNet = &cobra.Command{
  44. Use: "net",
  45. Short: "Creates webserver or runner for various networking tests",
  46. Long: `The subcommand will run the network tester in server mode if the "--serve" flag is given, and the runners are triggered through HTTP requests.
  47. Alternatively, if the "--runner" flag is given, it will execute the given runner directly. Note that "--runner" and "--serve" flags cannot be given at the same time.
  48. Examples:
  49. agnhost net --runner nat-closewait-client --options '{"RemoteAddr":"127.0.0.1:9999"}'
  50. agnhost net --serve :8889 && curl -v -X POST localhost:8889/run/nat-closewait-server -d '{"LocalAddr":"127.0.0.1:9999"}'
  51. `,
  52. Args: cobra.MaximumNArgs(0),
  53. Run: main,
  54. }
  55. func init() {
  56. legalRunners := ""
  57. for k := range runners {
  58. legalRunners += " " + k
  59. }
  60. CmdNet.Flags().StringVar(&flags.Serve, "serve", "",
  61. "Address and port to bind to (e.g. 127.0.0.1:8080). Setting this will "+
  62. "run the network tester in server mode runner are triggered through "+
  63. "HTTP requests.")
  64. CmdNet.Flags().StringVar(&flags.Runner, "runner", "", "Runner to execute (available:"+legalRunners+")")
  65. CmdNet.Flags().StringVar(&flags.Options, "options", "", "JSON options to the Runner")
  66. }
  67. func main(cmd *cobra.Command, args []string) {
  68. if flags.Runner == "" && flags.Serve == "" {
  69. log.Fatalf("Must set either --runner or --serve, see --help")
  70. }
  71. log.SetFlags(log.Flags() | log.Lshortfile)
  72. if flags.Serve == "" {
  73. output, err := executeRunner(flags.Runner, flags.Options)
  74. if err == nil {
  75. fmt.Print("output:\n\n" + output.b.String())
  76. os.Exit(0)
  77. } else {
  78. log.Printf("Error: %v", err)
  79. fmt.Print("output:\n\n" + output.b.String())
  80. os.Exit(1)
  81. }
  82. } else {
  83. http.HandleFunc("/run/", handleRunRequest)
  84. log.Printf("Running server on %v", flags.Serve)
  85. log.Fatal(http.ListenAndServe(flags.Serve, nil))
  86. }
  87. }
  88. func makeRunnerMap() runnerMap {
  89. // runner name is <pkg>-<file>-<specific>.
  90. return runnerMap{
  91. "nat-closewait-client": nat.NewCloseWaitClient(),
  92. "nat-closewait-server": nat.NewCloseWaitServer(),
  93. }
  94. }
  95. func executeRunner(name string, rawOptions string) (logOutput, error) {
  96. runner, ok := runners[name]
  97. if ok {
  98. options := runner.NewOptions()
  99. if err := json.Unmarshal([]byte(rawOptions), options); err != nil {
  100. return logOutput{}, fmt.Errorf("Invalid options JSON: %v", err)
  101. }
  102. log.Printf("Options: %+v", options)
  103. output := logOutput{}
  104. logger := log.New(&output.b, "# ", log.Lshortfile)
  105. return output, runner.Run(logger, options)
  106. }
  107. return logOutput{}, fmt.Errorf("Invalid runner: '%v', see --help", runner)
  108. }
  109. // handleRunRequest handles a request JSON to the network tester.
  110. func handleRunRequest(w http.ResponseWriter, r *http.Request) {
  111. log.Printf("handleRunRequest %v", *r)
  112. urlParts := strings.Split(r.URL.Path, "/")
  113. if len(urlParts) != 3 {
  114. http.Error(w, fmt.Sprintf("invalid request to run: %v", urlParts), 400)
  115. return
  116. }
  117. runner := urlParts[2]
  118. if r.Body == nil {
  119. http.Error(w, "Missing request body", 400)
  120. return
  121. }
  122. body, err := ioutil.ReadAll(r.Body)
  123. if err != nil {
  124. http.Error(w, fmt.Sprintf("error reading body: %v", err), 400)
  125. return
  126. }
  127. var output logOutput
  128. if output, err = executeRunner(runner, string(body)); err != nil {
  129. contents := fmt.Sprintf("Error from runner: %v\noutput:\n\n%s",
  130. err, output.b.String())
  131. http.Error(w, contents, 500)
  132. return
  133. }
  134. fmt.Fprintf(w, "ok\noutput:\n\n"+output.b.String())
  135. }