class RailsGrpc::CLI

Constants

RAILS_LAUNCH_WAIT_TIME
WORKER_LAUNCH_RETRY_LIMIT

Attributes

mutex[RW]
server[RW]
worker_pid[RW]

Public Class Methods

new() click to toggle source
# File lib/rails_grpc/cli.rb, line 13
def initialize
  @mutex = Mutex.new
  set_environment
end

Public Instance Methods

parse() click to toggle source
# File lib/rails_grpc/cli.rb, line 18
def parse
end
run() click to toggle source
# File lib/rails_grpc/cli.rb, line 21
def run
  @worker_pid = Process.fork
  if @worker_pid
    print_banner
    puts "Start GRPC master (pid: #{$$})"
    set_master_trap
    Process.waitall
  else
    boot_grpc_server
  end
end

Private Instance Methods

boot_grpc_server() click to toggle source
# File lib/rails_grpc/cli.rb, line 48
def boot_grpc_server
  RailsGrpc::Boot.new.exec(environment)
end
environment() click to toggle source
# File lib/rails_grpc/cli.rb, line 44
def environment
  ENV["RAILS_ENV"]
end
launch_new_worker() click to toggle source
# File lib/rails_grpc/cli.rb, line 82
def launch_new_worker
  new_worker_pid = Process.fork
  if new_worker_pid
    puts "Launch new worker process (pid: #{new_worker_pid}) and kill old worker (pid:#{@worker_pid})"
    retry_limit = WORKER_LAUNCH_RETRY_LIMIT

    # FIXME: ugly code
    while !process_exists?(new_worker_pid)
      puts "waiting new worker"
      sleep 1

      retry_limit -= 1
      if retry_limit < 0
        puts "Failed to Launch new worker..."
        exit 1
      end
    end
    sleep RAILS_LAUNCH_WAIT_TIME # FIXME: bad code

    Process.kill("TERM", @worker_pid)
    @worker_pid = new_worker_pid
  else
    boot_grpc_server
  end
end
print_banner() click to toggle source
process_exists?(pid) click to toggle source
# File lib/rails_grpc/cli.rb, line 108
def process_exists?(pid)
  Process.kill(0, pid.to_i)
  true
rescue Error::SCRCH # no such process
  false
rescue Error::EPERM # process exists, no permission
  true
end
set_environment() click to toggle source
# File lib/rails_grpc/cli.rb, line 35
def set_environment
  env ||= ENV["RAILS_ENV"]
  env ||= ENV["RACK_ENV"]
  env ||= "development"

  ENV["RAILS_ENV"] = ENV["RACK_ENV"] = env
  env
end
set_master_trap() click to toggle source
# File lib/rails_grpc/cli.rb, line 70
def set_master_trap
  Signal.trap(:USR1) do
    t = Thread.new do
      @mutex.synchronize do
        launch_new_worker
      end
    end
    t.report_on_exception = false
    t.run
  end
end