Class: Slnky::Service::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/slnky/service.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, env = 'development') ⇒ Base

Returns a new instance of Base.



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/slnky/service.rb', line 10

def initialize(url, env='development')
  @server = url
  @environment = env
  @name = self.class.name.split('::').last.downcase
  json = open("#{@server}/configs/#{@name}") {|f| f.read }
  @config = JSON.parse(json)
  @host = @config['rabbit']['host']
  @port = @config['rabbit']['port']
  @subscriptions = {}
  @periodics = []
  @exchanges = {}
end

Instance Method Details

#startObject



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
59
60
61
62
63
64
65
66
67
# File 'lib/slnky/service.rb', line 23

def start
  AMQP.start("amqp://#{@host}:#{@port}") do |connection|
    @channel = AMQP::Channel.new(connection)
    @channel.on_error do |ch, channel_close|
      raise "Channel-level exception: #{channel_close.reply_text}"
    end
    @exchanges['events'] = @channel.fanout("slnky.events")
    @exchanges['logs'] = @channel.fanout("slnky.logs")

    log :info, "slnky.service.#{@name}: running"

    run

    @subscriptions.each do |name, block|
      log :info, "slnky.service.#{@name}: subscribed to: #{name}"
    end

    @channel.queue("service.#{@name}.events", durable: true).bind(@exchanges['events']).subscribe do |raw|
      payload = parse(raw)
      if @subscriptions[payload.name]
        @subscriptions[payload.name].call(payload)
      end
      # TODO: support this better
      if @subscriptions['*']
        @subscriptions['*'].call(payload)
      end
    end

    @periodics.each do |p|
      EventMachine.add_periodic_timer(p[:timer]) do
        b = p[:block]
        instance_eval &b
      end
    end

    stopper = Proc.new do
      puts 'stopping'
      # TODO: log :warn, "slnky.service.#{@name}: stopping"
      connection.close { EventMachine.stop }
    end

    Signal.trap("INT", stopper)
    Signal.trap("TERM", stopper)
  end
end