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