|
| 1 | +#!/usr/bin/env ruby |
| 2 | + |
| 3 | +require 'grpc' |
| 4 | +require 'optparse' |
| 5 | +require 'grpc/health/v1/health_services_pb' |
| 6 | + |
| 7 | +options = { |
| 8 | + retries: 5, |
| 9 | + backoff: 3, |
| 10 | + service: '', |
| 11 | +} |
| 12 | + |
| 13 | +optparse = OptionParser.new do |opts| |
| 14 | + opts.banner = 'Usage: grpc_check_health [options]' |
| 15 | + |
| 16 | + opts.on('-h', '--host [HOST]', String, 'Host of the grpc server to check') do |host| |
| 17 | + options[:host] = host |
| 18 | + end |
| 19 | + |
| 20 | + opts.on('-r', '--retries [RETRIES]', Integer, "Amount of retries (Default: #{options[:retries]})") do |retries| |
| 21 | + options[:retries] = retries |
| 22 | + end |
| 23 | + |
| 24 | + opts.on('-b', '--backoff [BACKOFF]', Integer, "Backoff in seconds for each attempt (Default: #{options[:backoff]})") do |backoff| |
| 25 | + options[:backoff] = backoff |
| 26 | + end |
| 27 | + |
| 28 | + opts.on('-s', '--service [SERVICE]', String, "Service check health for (Default: '#{options[:service]}')") do |service| |
| 29 | + options[:service] = service |
| 30 | + end |
| 31 | +end |
| 32 | +optparse.parse! |
| 33 | + |
| 34 | +missing = %i[host].select{ |param| options[param].nil? } |
| 35 | +unless missing.empty? |
| 36 | + puts "Missing arguments: #{missing.join(', ')}" |
| 37 | + puts |
| 38 | + puts optparse |
| 39 | + exit |
| 40 | +end |
| 41 | + |
| 42 | +RetryException = Class.new(StandardError) |
| 43 | + |
| 44 | +attempt = 1 |
| 45 | + |
| 46 | +begin |
| 47 | + puts |
| 48 | + puts "Attempt #{attempt}/#{options[:retries]} to check if '#{options[:service]}' on #{options[:host]} is serving" |
| 49 | + stub = Grpc::Health::V1::Health::Stub.new(options[:host], :this_channel_is_insecure) |
| 50 | + message = Grpc::Health::V1::HealthCheckRequest.new(service: options[:service]) |
| 51 | + |
| 52 | + response = stub.check(message) |
| 53 | + |
| 54 | + if response.status == :SERVING |
| 55 | + puts "Service '#{options[:service]}' on #{options[:host]} is #{response.status}" |
| 56 | + else |
| 57 | + raise RetryException |
| 58 | + end |
| 59 | +rescue GRPC::BadStatus, RetryException => e |
| 60 | + if e.is_a?(GRPC::BadStatus) |
| 61 | + message = e.inspect |
| 62 | + else |
| 63 | + message = "Service #{options[:service]} on #{options[:host]} is not SERVING (status is #{response&.status})" |
| 64 | + end |
| 65 | + |
| 66 | + puts message |
| 67 | + |
| 68 | + if attempt < options[:retries] |
| 69 | + attempt += 1 |
| 70 | + puts "Retrying in #{options[:backoff]}s" |
| 71 | + sleep options[:backoff] |
| 72 | + retry |
| 73 | + end |
| 74 | + |
| 75 | + abort |
| 76 | +end |
0 commit comments