class Ragent::Agent

Attributes

commands[R]
plugins[R]
supervisor[R]
templates_path[R]
workdir[R]

Public Class Methods

new(log_level:, workdir:) click to toggle source
# File lib/ragent.rb, line 44
def initialize(log_level:, workdir:)
  @templates_path=Pathname.new(__FILE__).join('../../templates').expand_path
  @workdir = Pathname.new(workdir).expand_path
  $LOAD_PATH << @workdir.join('lib').to_s

  init_logger(log_level)

  @commands = Ragent::Commands.new(self)
  @plugins = Plugins.new(self)

  register_commands
end

Public Instance Methods

add_plugin(name, *args, &block) click to toggle source
# File lib/ragent.rb, line 62
def add_plugin(name, *args, &block)
  plugins.load(name, *args, &block) if name.is_a?(Symbol)
end
config() click to toggle source
# File lib/ragent.rb, line 57
def config
  Ragent::Configurator.load(self, workdir.join('config.ragent'))
  self
end
run(blocking = true) click to toggle source
# File lib/ragent.rb, line 66
def run(blocking = true)
  @supervisor = Celluloid::Supervision::Container.run!
  plugins.start
  term_wait_loop if blocking
end

Private Instance Methods

handle_signal(signal) click to toggle source
EM.epoll
Thread.new { EventMachine.run } unless EventMachine.reactor_running?
sleep 0.01 until EventMachine.reactor_running?

end

# File lib/ragent.rb, line 94
def handle_signal(signal)
  info "Got signal #{signal}"
  case signal
  when 'TERM', 'INT', 'SHUTDOWN' # shutdown is an internal command
    info 'Shutting down...'
    # EM.stop if EventMachine.reactor_running?
    @plugins.stop
    @supervisor.shutdown
    true
  when 'TTIN'
    Thread.list.each do |thread|
      warn "Thread #{thread.object_id.to_s(36)} #{thread['label']}"
      if thread.backtrace
        warn thread.backtrace.join("\n")
      else
        warn 'no backtrace available'
      end
    end
    false
  end
end
init_logger(log_level) click to toggle source
# File lib/ragent.rb, line 128
def init_logger(log_level)
  Ragent::Logging.logger = ::Logging.logger['ragent']
  logger.add_appenders ::Logging.appenders.stdout
  ::Logging.logger['root'].level=log_level
end
register_commands() click to toggle source
# File lib/ragent.rb, line 120
def register_commands
  cmd = Ragent::Command.new(main: 'shutdown',
                            sub: nil,
                            recipient: self,
                            method: :shutdown_command)
  @commands.add(cmd)
end
shutdown_command(_options = {}) click to toggle source
# File lib/ragent.rb, line 116
def shutdown_command(_options = {})
  @self_write.puts('SHUTDOWN')
end
term_wait_loop() click to toggle source
# File lib/ragent.rb, line 74
def term_wait_loop
  self_read, @self_write = IO.pipe
  %w(TERM TTIN INT).each do |sig|
    Signal.trap sig do
      @self_write.puts(sig)
    end
  end
  stop = false
  while stop || readable_io = IO.select([self_read])
    signal = readable_io.first[0].gets.strip
    break if handle_signal(signal)
  end
  info 'Exiting'
end