Module: Kuroko2::Command::Executor

Defined in:
lib/autoload/kuroko2/command/executor.rb

Constant Summary collapse

DEFAULT_NUM_WORKERS =
4
NUM_SYSTEM_WORKERS =

master and monitor

2

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.num_workersObject



7
8
9
# File 'lib/autoload/kuroko2/command/executor.rb', line 7

def self.num_workers
  @num_workers ||= (ENV['NUM_WORKERS'] || DEFAULT_NUM_WORKERS).to_i + NUM_SYSTEM_WORKERS
end

Instance Method Details

#initializeObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/autoload/kuroko2/command/executor.rb', line 11

def initialize
  @stop = ServerEngine::BlockingFlag.new

  @hostname = ENV['HOSTNAME'] || Socket.gethostname
  @queue    = ENV['QUEUE'] || Execution::DEFAULT_QUEUE

  @command = if worker_id == 0
               Command::Kill.new(@hostname, worker_id)
             elsif worker_id == (Command::Executor.num_workers - 1)
               Command::Monitor.new(hostname: @hostname, worker_id: worker_id)
             else
               @worker = Worker.where(hostname: @hostname, worker_id: worker_id, queue: @queue).first_or_create!
               Command::Shell.new(hostname: @hostname, worker_id: worker_id, worker: @worker, queue: @queue)
             end
end

#runObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/autoload/kuroko2/command/executor.rb', line 27

def run
  Kuroko2.logger = logger
  Kuroko2.logger.info "[#{@hostname}-#{worker_id}] Start worker"
  toggle_worker_status(true)

  sleep worker_id

  until @stop.wait(1 + rand)
    @command.execute
  end
rescue Exception => e
  Kuroko2.logger.fatal("[#{@hostname}-#{worker_id}] #{e.class}: #{e.message}\n" +
    e.backtrace.map { |trace| "    #{trace}" }.join("\n"))

  raise e
end

#stopObject



44
45
46
47
48
49
# File 'lib/autoload/kuroko2/command/executor.rb', line 44

def stop
  Kuroko2.logger.info "[#{@hostname}-#{worker_id}] Stop worker"
  toggle_worker_status(false)

  @stop.set!
end