Class: Bipbip::Agent

Inherits:
Object
  • Object
show all
Includes:
InterruptibleSleep
Defined in:
lib/bipbip/agent.rb

Constant Summary collapse

PLUGIN_RESPAWN_DELAY =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from InterruptibleSleep

#interrupt_sleep, #interruptible_sleep

Constructor Details

#initialize(config) ⇒ Agent

Returns a new instance of Agent.

Parameters:



12
13
14
15
16
17
18
# File 'lib/bipbip/agent.rb', line 12

def initialize(config)
  @plugins = config.plugins
  @storages = config.storages
  Bipbip.logger = config.logger

  @threads = []
end

Instance Attribute Details

#pluginsObject

Returns the value of attribute plugins.



7
8
9
# File 'lib/bipbip/agent.rb', line 7

def plugins
  @plugins
end

#storagesObject

Returns the value of attribute storages.



8
9
10
# File 'lib/bipbip/agent.rb', line 8

def storages
  @storages
end

#threadsObject

Returns the value of attribute threads.



9
10
11
# File 'lib/bipbip/agent.rb', line 9

def threads
  @threads
end

Instance Method Details

#runObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/bipbip/agent.rb', line 20

def run
  Bipbip.logger.info 'Startup...'
  Bipbip.logger.warn 'No storages configured' if @storages.empty?

  raise 'No services configured' if @plugins.empty?

  @storages.each do |storage|
    @plugins.each do |plugin|
      Bipbip.logger.info "Setting up plugin #{plugin.name} for storage #{storage.name}"
      begin
        storage.setup_plugin(plugin)
      rescue => e
        Bipbip.logger.fatal "Failed to setup plugin #{plugin.name} for storage #{storage.name}: `#{e.message}`. Retrying..."
        sleep 5
        retry
      end
    end
  end

  @plugins.each do |plugin|
    Bipbip.logger.info "Starting plugin #{plugin.name} with config #{plugin.config}"
    start_plugin(plugin, @storages)
  end

  loop do
    thread = ThreadsWait.new(@threads).next_wait
    @threads.delete(thread)
    plugin = thread['plugin']

    Bipbip.logger.error "Plugin #{plugin.name} with config #{plugin.config} terminated. Restarting..."
    interruptible_sleep(PLUGIN_RESPAWN_DELAY)

    # Re-instantiate plugin to get rid of existing database-connections etc
    plugin_new = Bipbip::Plugin.factory_from_plugin(plugin)
    @plugins.delete(plugin)
    @plugins.push(plugin_new)
    start_plugin(plugin_new, @storages)
  end
end