| 1 | /* |
| 2 | Copyright 2020 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 main |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "flag" |
| 22 | "fmt" |
| 23 | "net/http" |
| 24 | "os" |
| 25 | "os/signal" |
| 26 | "strconv" |
| 27 | "syscall" |
| 28 | "time" |
| 29 | |
| 30 | "github.com/spf13/cobra" |
| 31 | "github.com/spf13/pflag" |
| 32 | "k8s.io/klog/v2" |
| 33 | "sigs.k8s.io/apiserver-network-proxy/pkg/util" |
| 34 | ) |
| 35 | |
| 36 | func main() { |
| 37 | testServer := &TestServer{} |
| 38 | o := newTestServerRunOptions() |
| 39 | command := newTestServerCommand(testServer, o) |
| 40 | flags := command.Flags() |
| 41 | flags.AddFlagSet(o.Flags()) |
| 42 | local := flag.NewFlagSet(os.Args[0], flag.ExitOnError) |
| 43 | klog.InitFlags(local) |
| 44 | local.VisitAll(func(fl *flag.Flag) { |
| 45 | fl.Name = util.Normalize(fl.Name) |
| 46 | flags.AddGoFlag(fl) |
| 47 | }) |
| 48 | if err := command.Execute(); err != nil { |
| 49 | klog.Errorf("error: %v\n", err) |
| 50 | klog.Flush() |
| 51 | os.Exit(1) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | type TestServerRunOptions struct { |
| 56 | // Port we listen for server connections on. |
| 57 | serverPort uint |
| 58 | } |
| 59 | |
| 60 | func (o *TestServerRunOptions) Flags() *pflag.FlagSet { |
| 61 | flags := pflag.NewFlagSet("proxy-server", pflag.ContinueOnError) |
| 62 | flags.UintVar(&o.serverPort, "server-port", o.serverPort, "Port we listen for server connections on. Set to 0 for UDS.") |
| 63 | return flags |
| 64 | } |
| 65 | |
| 66 | func (o *TestServerRunOptions) Print() { |
| 67 | klog.Warningf("Server port set to %d.\n", o.serverPort) |
| 68 | } |
| 69 | |
| 70 | func (o *TestServerRunOptions) Validate() error { |
| 71 | if o.serverPort > 49151 { |
| 72 | return fmt.Errorf("please do not try to use ephemeral port %d for the server port", o.serverPort) |
| 73 | } |
| 74 | if o.serverPort < 1024 { |
| 75 | return fmt.Errorf("please do not try to use reserved port %d for the server port", o.serverPort) |
| 76 | } |
| 77 | |
| 78 | return nil |
| 79 | } |
| 80 | |
| 81 | func newTestServerRunOptions() *TestServerRunOptions { |
| 82 | o := TestServerRunOptions{ |
| 83 | serverPort: 8000, |
| 84 | } |
| 85 | return &o |
| 86 | } |
| 87 | |
| 88 | func newTestServerCommand(p *TestServer, o *TestServerRunOptions) *cobra.Command { |
| 89 | cmd := &cobra.Command{ |
| 90 | Use: "test http server", |
| 91 | Long: `A test http server, url determines behavior for certain tests.`, |
| 92 | RunE: func(_ *cobra.Command, _ []string) error { |
| 93 | return p.run(o) |
| 94 | }, |
| 95 | } |
| 96 | |
| 97 | return cmd |
| 98 | } |
| 99 | |
| 100 | type TestServer struct { |
| 101 | } |
| 102 | |
| 103 | type StopFunc func() |
| 104 | |
| 105 | func (p *TestServer) run(o *TestServerRunOptions) error { |
| 106 | o.Print() |
| 107 | if err := o.Validate(); err != nil { |
| 108 | return fmt.Errorf("failed to validate server options with %v", err) |
| 109 | } |
| 110 | ctx, cancel := context.WithCancel(context.Background()) |
| 111 | defer cancel() |
| 112 | |
| 113 | klog.Info("Starting test http server for client requests.") |
| 114 | testStop, err := p.runTestServer(ctx, o) |
| 115 | if err != nil { |
| 116 | return fmt.Errorf("failed to run the test server: %v", err) |
| 117 | } |
| 118 | |
| 119 | stopCh := SetupSignalHandler() |
| 120 | <-stopCh |
| 121 | klog.Info("Shutting down server.") |
| 122 | |
| 123 | if testStop != nil { |
| 124 | testStop() |
| 125 | } |
| 126 | |
| 127 | return nil |
| 128 | } |
| 129 | |
| 130 | var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM} |
| 131 | |
| 132 | func SetupSignalHandler() (stopCh <-chan struct{}) { |
| 133 | stop := make(chan struct{}) |
| 134 | c := make(chan os.Signal, 2) |
| 135 | signal.Notify(c, shutdownSignals...) |
| 136 | go func() { |
| 137 | <-c |
| 138 | close(stop) |
| 139 | <-c |
| 140 | os.Exit(1) // second signal. Exit directly. |
| 141 | }() |
| 142 | |
| 143 | return stop |
| 144 | } |
| 145 | |
| 146 | func returnSuccess(w http.ResponseWriter, _ *http.Request) { |
| 147 | fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n <head>\n <title>Success</title>\n </head>\n <body>\n <p>The success test page!</p>\n </body>\n</html>") |
| 148 | } |
| 149 | |
| 150 | func returnError(w http.ResponseWriter, _ *http.Request) { |
| 151 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 152 | } |
| 153 | |
| 154 | func closeNoResponse(w http.ResponseWriter, _ *http.Request) { |
| 155 | hj, ok := w.(http.Hijacker) |
| 156 | if !ok { |
| 157 | http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError) |
| 158 | return |
| 159 | } |
| 160 | conn, _, err := hj.Hijack() |
| 161 | if err != nil { |
| 162 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 163 | return |
| 164 | } |
| 165 | err = conn.Close() |
| 166 | if err != nil { |
| 167 | klog.ErrorS(err, "failed to close connection") |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | func sleepReturnSuccess(w http.ResponseWriter, req *http.Request) { |
| 172 | sleepArr := req.URL.Query()["time"] |
| 173 | sleepInt := 10 |
| 174 | var err error |
| 175 | if len(sleepArr) == 1 { |
| 176 | sleepStr := sleepArr[0] |
| 177 | sleepInt, err = strconv.Atoi(sleepStr) |
| 178 | if err != nil { |
| 179 | sleepInt = 10 |
| 180 | klog.Warningf("Failed to parse sleep time (%s), default to %d, got error %v.", sleepStr, sleepInt, err) |
| 181 | } |
| 182 | } else { |
| 183 | klog.Warningf("Sleep time(%v) was length %d defaulting to sleep %d.", sleepArr, len(sleepArr), sleepInt) |
| 184 | } |
| 185 | sleep := time.Duration(sleepInt) * time.Second |
| 186 | time.Sleep(sleep) |
| 187 | returnSuccess(w, req) |
| 188 | } |
| 189 | |
| 190 | func (p *TestServer) runTestServer(ctx context.Context, o *TestServerRunOptions) (StopFunc, error) { |
| 191 | muxHandler := http.NewServeMux() |
| 192 | muxHandler.HandleFunc("/success", returnSuccess) |
| 193 | muxHandler.HandleFunc("/sleep", sleepReturnSuccess) |
| 194 | muxHandler.HandleFunc("/error", returnError) |
| 195 | muxHandler.HandleFunc("/close", closeNoResponse) |
| 196 | server := &http.Server{ |
| 197 | Addr: fmt.Sprintf("127.0.0.1:%d", o.serverPort), |
| 198 | Handler: muxHandler, |
| 199 | MaxHeaderBytes: 1 << 20, |
| 200 | ReadHeaderTimeout: 60 * time.Second, |
| 201 | } |
| 202 | |
| 203 | go func() { |
| 204 | err := server.ListenAndServe() |
| 205 | if err != nil { |
| 206 | klog.Warningf("HTTP test server received %v.\n", err) |
| 207 | } |
| 208 | klog.Warningf("HTTP test server stopped listening\n") |
| 209 | }() |
| 210 | |
| 211 | stop := func() { |
| 212 | err := server.Shutdown(ctx) |
| 213 | if err != nil { |
| 214 | klog.ErrorS(err, "failed to shutdown server") |
| 215 | } |
| 216 | } |
| 217 | return stop, nil |
| 218 | } |