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 15require 'grpc' 16require 'grpc/health/v1/health_services_pb' 17require 'thread' 18 19module Grpc 20 # Health contains classes and modules that support providing a health check 21 # service. 22 module Health 23 # Checker is implementation of the schema-specified health checking service. 24 class Checker < V1::Health::Service 25 StatusCodes = GRPC::Core::StatusCodes 26 HealthCheckResponse = V1::HealthCheckResponse 27 28 # Initializes the statuses of participating services 29 def initialize 30 @statuses = {} 31 @status_mutex = Mutex.new # guards access to @statuses 32 end 33 34 # Implements the rpc IDL API method 35 def check(req, _call) 36 status = nil 37 @status_mutex.synchronize do 38 status = @statuses["#{req.service}"] 39 end 40 if status.nil? 41 fail GRPC::BadStatus.new_status_exception(StatusCodes::NOT_FOUND) 42 end 43 HealthCheckResponse.new(status: status) 44 end 45 46 # Adds the health status for a given service. 47 def add_status(service, status) 48 @status_mutex.synchronize { @statuses["#{service}"] = status } 49 end 50 51 # Adds given health status for all given services 52 def set_status_for_services(status, *services) 53 @status_mutex.synchronize do 54 services.each { |service| @statuses["#{service}"] = status } 55 end 56 end 57 58 # Adds health status for each service given within hash 59 def add_statuses(service_statuses = {}) 60 @status_mutex.synchronize do 61 service_statuses.each_pair { |service, status| @statuses["#{service}"] = status } 62 end 63 end 64 65 # Clears the status for the given service. 66 def clear_status(service) 67 @status_mutex.synchronize { @statuses.delete("#{service}") } 68 end 69 70 # Clears alls the statuses. 71 def clear_all 72 @status_mutex.synchronize { @statuses = {} } 73 end 74 end 75 end 76end 77