github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/pjutil/health.go (about) 1 /* 2 Copyright 2019 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 pjutil contains helpers for working with ProwJobs. 18 package pjutil 19 20 import ( 21 "fmt" 22 "net/http" 23 "strconv" 24 "time" 25 26 "sigs.k8s.io/prow/pkg/interrupts" 27 ) 28 29 const healthPort = 8081 30 31 // Health keeps a request multiplexer for health liveness and readiness endpoints 32 type Health struct { 33 healthMux *http.ServeMux 34 } 35 36 // NewHealth creates a new health request multiplexer and starts serving the liveness endpoint 37 // on the default port 38 func NewHealth() *Health { 39 return NewHealthOnPort(healthPort) 40 } 41 42 // NewHealth creates a new health request multiplexer and starts serving the liveness endpoint 43 // on the given port 44 func NewHealthOnPort(port int) *Health { 45 healthMux := http.NewServeMux() 46 healthMux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") }) 47 server := &http.Server{Addr: ":" + strconv.Itoa(port), Handler: healthMux} 48 interrupts.ListenAndServe(server, 5*time.Second) 49 return &Health{ 50 healthMux: healthMux, 51 } 52 } 53 54 type ReadynessCheck func() bool 55 56 // ServeReady starts serving the readiness endpoint 57 func (h *Health) ServeReady(readynessChecks ...ReadynessCheck) { 58 h.healthMux.HandleFunc("/healthz/ready", func(w http.ResponseWriter, r *http.Request) { 59 for _, readynessCheck := range readynessChecks { 60 if !readynessCheck() { 61 w.WriteHeader(http.StatusServiceUnavailable) 62 fmt.Fprint(w, "ReadynessCheck failed") 63 return 64 } 65 } 66 fmt.Fprint(w, "OK") 67 }) 68 }