...

Source file src/k8s.io/kubernetes/test/images/agnhost/liveness/server.go

Documentation: k8s.io/kubernetes/test/images/agnhost/liveness

     1  /*
     2  Copyright 2014 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  // A simple server that is alive for 10 seconds, then reports unhealthy for
    18  // the rest of its (hopefully) short existence.
    19  
    20  package liveness
    21  
    22  import (
    23  	"fmt"
    24  	"log"
    25  	"net/http"
    26  	"net/url"
    27  	"time"
    28  
    29  	"github.com/spf13/cobra"
    30  )
    31  
    32  // CmdLiveness is used by agnhost Cobra.
    33  var CmdLiveness = &cobra.Command{
    34  	Use:   "liveness",
    35  	Short: "Starts a server that is alive for 10 seconds",
    36  	Long:  "A simple server that is alive for 10 seconds, then reports unhealthy for the rest of its (hopefully) short existence",
    37  	Args:  cobra.MaximumNArgs(0),
    38  	Run:   main,
    39  }
    40  
    41  func main(cmd *cobra.Command, args []string) {
    42  	started := time.Now()
    43  	http.HandleFunc("/started", func(w http.ResponseWriter, r *http.Request) {
    44  		w.WriteHeader(200)
    45  		data := (time.Since(started)).String()
    46  		w.Write([]byte(data))
    47  	})
    48  	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
    49  		duration := time.Since(started)
    50  		if duration.Seconds() > 10 {
    51  			w.WriteHeader(500)
    52  			w.Write([]byte(fmt.Sprintf("error: %v", duration.Seconds())))
    53  		} else {
    54  			w.WriteHeader(200)
    55  			w.Write([]byte("ok"))
    56  		}
    57  	})
    58  	http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
    59  		loc, err := url.QueryUnescape(r.URL.Query().Get("loc"))
    60  		if err != nil {
    61  			http.Error(w, fmt.Sprintf("invalid redirect: %q", r.URL.Query().Get("loc")), http.StatusBadRequest)
    62  			return
    63  		}
    64  		http.Redirect(w, r, loc, http.StatusFound)
    65  	})
    66  	log.Fatal(http.ListenAndServe(":8080", nil))
    67  }
    68  

View as plain text