|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "strconv" |
| 9 | + |
| 10 | + "github.com/spf13/cobra" |
| 11 | + |
| 12 | + canarycontroller "github.com/openshift/cluster-ingress-operator/pkg/operator/controller/canary" |
| 13 | +) |
| 14 | + |
| 15 | +func healthCheckHandler(w http.ResponseWriter, r *http.Request) { |
| 16 | + response := os.Getenv("RESPONSE") |
| 17 | + if len(response) == 0 { |
| 18 | + response = canarycontroller.CanaryHealthcheckResponse |
| 19 | + } |
| 20 | + |
| 21 | + // Echo back the port the request was received on |
| 22 | + // via a "request-port" header. |
| 23 | + addr := r.Context().Value(http.LocalAddrContextKey).(net.Addr) |
| 24 | + if tcpAddr, ok := addr.(*net.TCPAddr); ok { |
| 25 | + w.Header().Set("x-request-port", strconv.Itoa(tcpAddr.Port)) |
| 26 | + } |
| 27 | + |
| 28 | + _, err := fmt.Fprintln(w, response) |
| 29 | + if err == nil { |
| 30 | + fmt.Println("Serving canary healthcheck request") |
| 31 | + } else { |
| 32 | + fmt.Printf("Could not serve canary healthcheck: %v\n", err) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +func listenAndServe(port string) { |
| 37 | + fmt.Printf("serving on %s\n", port) |
| 38 | + err := http.ListenAndServe(":"+port, nil) |
| 39 | + if err != nil { |
| 40 | + panic("ListenAndServe: " + err.Error()) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func NewServeHealthCheckCommand() *cobra.Command { |
| 45 | + var command = &cobra.Command{ |
| 46 | + Use: canarycontroller.CanaryHealthcheckCommand, |
| 47 | + Short: "Certify canary server health by echoing a response", |
| 48 | + Long: canarycontroller.CanaryHealthcheckCommand + ` echoes a response when queried, thus certifying health of the canary service.`, |
| 49 | + Run: func(cmd *cobra.Command, args []string) { |
| 50 | + serveHealthCheck() |
| 51 | + }, |
| 52 | + } |
| 53 | + |
| 54 | + return command |
| 55 | +} |
| 56 | + |
| 57 | +func serveHealthCheck() { |
| 58 | + http.HandleFunc("/", healthCheckHandler) |
| 59 | + port := os.Getenv("PORT") |
| 60 | + if len(port) == 0 { |
| 61 | + port = "8080" |
| 62 | + } |
| 63 | + go listenAndServe(port) |
| 64 | + |
| 65 | + port = os.Getenv("SECOND_PORT") |
| 66 | + if len(port) == 0 { |
| 67 | + port = "8888" |
| 68 | + } |
| 69 | + go listenAndServe(port) |
| 70 | + |
| 71 | + select {} |
| 72 | +} |
0 commit comments