Class: Logbook::Agent

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/logbook/agent.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAgent

Returns a new instance of Agent.



8
9
10
11
12
13
# File 'lib/logbook/agent.rb', line 8

def initialize
  @client = Logbook::Client.new(Logbook.api_key)
  @entries = []
  @semaphore = Mutex.new
  Logbook.logger.info('Logbook agent started')
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



6
7
8
# File 'lib/logbook/agent.rb', line 6

def client
  @client
end

#entriesObject (readonly)

Returns the value of attribute entries.



6
7
8
# File 'lib/logbook/agent.rb', line 6

def entries
  @entries
end

#stop_processingObject (readonly)

Returns the value of attribute stop_processing.



6
7
8
# File 'lib/logbook/agent.rb', line 6

def stop_processing
  @stop_processing
end

Instance Method Details

#add_entry(severity, facility, payload) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/logbook/agent.rb', line 64

def add_entry(severity, facility, payload)
  entries.push(
    :severity  => severity,
    :facility  => facility,
    :payload   => payload,
    :timestamp => Time.now.to_s
  )
end

#processObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/logbook/agent.rb', line 40

def process
  @semaphore.synchronize {
    return if entries.empty?

    # Copying the queue
    @entries_to_send = entries.dup
    Logbook.logger.info("Sending #{@entries_to_send.size} entries to the server")

    begin
      @client.send_entries(@entries_to_send)
    rescue => e
      Logbook.logger.error("Error when sending data to the server: #{e.message}")

      case e
        when Logbook::Client::NotAuthorized
          @stop_processing = true
      end
    ensure
      # Removing sent items from the queue anyway
      entries.shift(@entries_to_send.size)
    end
  }
end

#resetObject



29
30
31
# File 'lib/logbook/agent.rb', line 29

def reset
  entries.clear
end

#run_loopObject



33
34
35
36
37
38
# File 'lib/logbook/agent.rb', line 33

def run_loop
  while keep_running?
    process
    sleep Logbook.delay_between_requests
  end
end

#startObject



15
16
17
18
19
20
21
# File 'lib/logbook/agent.rb', line 15

def start
  @keep_running = true
  @loop = Thread.new do
    run_loop
  end
  @loop['label'] = 'Logbook loop'
end

#stopObject



23
24
25
26
27
# File 'lib/logbook/agent.rb', line 23

def stop
  Logbook.logger.info 'Stopping logbook agent. Checking if there is anything to send'
  @keep_running = false
  @loop.join
end