github.com/cilium/cilium@v1.16.2/clustermesh-apiserver/health/health.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package health 5 6 import ( 7 "errors" 8 "fmt" 9 "net/http" 10 11 "github.com/cilium/hive/cell" 12 "github.com/sirupsen/logrus" 13 "github.com/spf13/pflag" 14 ) 15 16 type HealthAPIServerConfig struct { 17 HealthPort int 18 } 19 20 func (def HealthAPIServerConfig) Flags(flags *pflag.FlagSet) { 21 flags.Int("health-port", def.HealthPort, "TCP port for ClusterMesh health API") 22 } 23 24 var DefaultHealthAPIServerConfig = HealthAPIServerConfig{ 25 HealthPort: 9880, 26 } 27 28 var HealthAPIServerCell = cell.Module( 29 "health-api-server", 30 "ClusterMesh Health API Server", 31 32 cell.Config(DefaultHealthAPIServerConfig), 33 cell.Invoke(registerHealthAPIServer), 34 ) 35 36 type parameters struct { 37 cell.In 38 39 Config HealthAPIServerConfig 40 Logger logrus.FieldLogger 41 EndpointFuncs []EndpointFunc 42 } 43 44 type EndpointFunc struct { 45 Path string 46 HandlerFunc http.HandlerFunc 47 } 48 49 func registerHealthAPIServer(lc cell.Lifecycle, params parameters) { 50 mux := http.NewServeMux() 51 52 for _, endpoint := range params.EndpointFuncs { 53 mux.HandleFunc(endpoint.Path, endpoint.HandlerFunc) 54 } 55 56 srv := &http.Server{ 57 Handler: mux, 58 Addr: fmt.Sprintf(":%d", params.Config.HealthPort), 59 } 60 61 lc.Append(cell.Hook{ 62 OnStart: func(cell.HookContext) error { 63 go func() { 64 params.Logger.Info("Started health API") 65 if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { 66 params.Logger.WithError(err).Fatal("Unable to start health API") 67 } 68 }() 69 return nil 70 }, 71 OnStop: func(ctx cell.HookContext) error { return srv.Shutdown(ctx) }, 72 }) 73 }