health.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. //go:generate ./regenerate.sh
  19. // Package health provides some utility functions to health-check a server. The implementation
  20. // is based on protobuf. Users need to write their own implementations if other IDLs are used.
  21. package health
  22. import (
  23. "sync"
  24. "golang.org/x/net/context"
  25. "google.golang.org/grpc/codes"
  26. healthpb "google.golang.org/grpc/health/grpc_health_v1"
  27. "google.golang.org/grpc/status"
  28. )
  29. // Server implements `service Health`.
  30. type Server struct {
  31. mu sync.Mutex
  32. // statusMap stores the serving status of the services this Server monitors.
  33. statusMap map[string]healthpb.HealthCheckResponse_ServingStatus
  34. }
  35. // NewServer returns a new Server.
  36. func NewServer() *Server {
  37. return &Server{
  38. statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus),
  39. }
  40. }
  41. // Check implements `service Health`.
  42. func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
  43. s.mu.Lock()
  44. defer s.mu.Unlock()
  45. if in.Service == "" {
  46. // check the server overall health status.
  47. return &healthpb.HealthCheckResponse{
  48. Status: healthpb.HealthCheckResponse_SERVING,
  49. }, nil
  50. }
  51. if status, ok := s.statusMap[in.Service]; ok {
  52. return &healthpb.HealthCheckResponse{
  53. Status: status,
  54. }, nil
  55. }
  56. return nil, status.Error(codes.NotFound, "unknown service")
  57. }
  58. // SetServingStatus is called when need to reset the serving status of a service
  59. // or insert a new service entry into the statusMap.
  60. func (s *Server) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) {
  61. s.mu.Lock()
  62. s.statusMap[service] = status
  63. s.mu.Unlock()
  64. }