class AppMonit::Worker

Constants

MAX_MULTIPLIER
MUTEX

Attributes

events[RW]

Public Class Methods

instance() click to toggle source
# File lib/app_monit/worker.rb, line 9
def instance
  return @instance if @instance
  MUTEX.synchronize do
    return @instance if @instance
    @instance = new.start
  end
end
new() click to toggle source
# File lib/app_monit/worker.rb, line 18
def initialize
  @queue      = Queue.new
  @multiplier = 1
  @flush_rate = AppMonit::Config.flush_rate
  reset
end

Public Instance Methods

logger() click to toggle source
# File lib/app_monit/worker.rb, line 71
def logger
  AppMonit.logger
end
push(event) click to toggle source
# File lib/app_monit/worker.rb, line 67
def push(event)
  @queue << event
end
reset() click to toggle source
# File lib/app_monit/worker.rb, line 25
def reset
  @events      = []
  @allow_flush = true
end
send_to_collector() click to toggle source
# File lib/app_monit/worker.rb, line 75
def send_to_collector
  if @events.any?
    logger.debug 'Sending to collector'
    begin
      AppMonit::Http.post('/v1/events', event: events)
    rescue Net::ReadTimeout
      logger.debug "Response took to longer than #{AppMonit::Config.timeout} second(s), but we assume it's been send"
    end
  end
  reset
end
start() click to toggle source
# File lib/app_monit/worker.rb, line 30
def start
  logger.debug('Start collecting')
  Thread.new do
    AppMonit.logger.debug('Waiting for queue')
    while (event = @queue.pop)
      begin
        case event
          when :flush
            @allow_flush = true
            send_to_collector
          else
            logger.debug 'Received event'
            events << event
            if @allow_flush && events.count > 10
              send_to_collector
            end
        end
      rescue Exception => e
        logger.debug ['Event error:', event.inspect, e.message]
        @allow_flush = false
      end
    end
  end
  start_flusher

  self
end
start_flusher() click to toggle source
# File lib/app_monit/worker.rb, line 58
def start_flusher
  Thread.new do
    loop do
      sleep @multiplier * @flush_rate
      push(:flush)
    end
  end
end