3 * Copyright 2017 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
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.
26 "golang.org/x/net/context"
27 "google.golang.org/grpc"
28 "google.golang.org/grpc/codes"
29 healthpb "google.golang.org/grpc/health/grpc_health_v1"
32 // Server implements `service Health`.
35 // statusMap stores the serving status of the services this Server monitors.
36 statusMap map[string]healthpb.HealthCheckResponse_ServingStatus
39 // NewServer returns a new Server.
40 func NewServer() *Server {
42 statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus),
46 // Check implements `service Health`.
47 func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
51 // check the server overall health status.
52 return &healthpb.HealthCheckResponse{
53 Status: healthpb.HealthCheckResponse_SERVING,
56 if status, ok := s.statusMap[in.Service]; ok {
57 return &healthpb.HealthCheckResponse{
61 return nil, grpc.Errorf(codes.NotFound, "unknown service")
64 // SetServingStatus is called when need to reset the serving status of a service
65 // or insert a new service entry into the statusMap.
66 func (s *Server) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) {
68 s.statusMap[service] = status