1# Copyright 2015 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Reference implementation for health checking in gRPC Python.""" 15 16import threading 17 18import grpc 19 20from grpc_health.v1 import health_pb2 as _health_pb2 21from grpc_health.v1 import health_pb2_grpc as _health_pb2_grpc 22 23SERVICE_NAME = _health_pb2.DESCRIPTOR.services_by_name['Health'].full_name 24 25 26class HealthServicer(_health_pb2_grpc.HealthServicer): 27 """Servicer handling RPCs for service statuses.""" 28 29 def __init__(self): 30 self._server_status_lock = threading.Lock() 31 self._server_status = {} 32 33 def Check(self, request, context): 34 with self._server_status_lock: 35 status = self._server_status.get(request.service) 36 if status is None: 37 context.set_code(grpc.StatusCode.NOT_FOUND) 38 return _health_pb2.HealthCheckResponse() 39 else: 40 return _health_pb2.HealthCheckResponse(status=status) 41 42 def set(self, service, status): 43 """Sets the status of a service. 44 45 Args: 46 service: string, the name of the service. 47 NOTE, '' must be set. 48 status: HealthCheckResponse.status enum value indicating 49 the status of the service 50 """ 51 with self._server_status_lock: 52 self._server_status[service] = status 53