github.com/kaisenlinux/docker@v0.0.0-20230510090727-ea55db55fac7/swarmkit/manager/health/health.go (about) 1 // Package health provides some utility functions to health-check a server. The implementation 2 // is based on protobuf. Users need to write their own implementations if other IDLs are used. 3 // 4 // See original source: https://github.com/grpc/grpc-go/blob/master/health/health.go 5 // 6 // We use our own implementation of grpc server health check to include the authorization 7 // wrapper necessary for the Managers. 8 package health 9 10 import ( 11 "context" 12 "sync" 13 14 "github.com/docker/swarmkit/api" 15 "google.golang.org/grpc/codes" 16 "google.golang.org/grpc/status" 17 ) 18 19 // Server represents a Health Check server to check 20 // if a service is running or not on some host. 21 type Server struct { 22 mu sync.Mutex 23 // statusMap stores the serving status of the services this HealthServer monitors. 24 statusMap map[string]api.HealthCheckResponse_ServingStatus 25 } 26 27 // NewHealthServer creates a new health check server for grpc services. 28 func NewHealthServer() *Server { 29 return &Server{ 30 statusMap: make(map[string]api.HealthCheckResponse_ServingStatus), 31 } 32 } 33 34 // Check checks if the grpc server is healthy and running. 35 func (s *Server) Check(ctx context.Context, in *api.HealthCheckRequest) (*api.HealthCheckResponse, error) { 36 s.mu.Lock() 37 defer s.mu.Unlock() 38 if in.Service == "" { 39 // check the server overall health status. 40 return &api.HealthCheckResponse{ 41 Status: api.HealthCheckResponse_SERVING, 42 }, nil 43 } 44 if status, ok := s.statusMap[in.Service]; ok { 45 return &api.HealthCheckResponse{ 46 Status: status, 47 }, nil 48 } 49 return nil, status.Errorf(codes.NotFound, "unknown service") 50 } 51 52 // SetServingStatus is called when need to reset the serving status of a service 53 // or insert a new service entry into the statusMap. 54 func (s *Server) SetServingStatus(service string, status api.HealthCheckResponse_ServingStatus) { 55 s.mu.Lock() 56 s.statusMap[service] = status 57 s.mu.Unlock() 58 }