Class: SemanticLogger::QueueProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/semantic_logger/queue_processor.rb,
lib/semantic_logger/queue_processor/inbox.rb,
lib/semantic_logger/queue_processor/backoff.rb,
lib/semantic_logger/queue_processor/request.rb,
lib/semantic_logger/queue_processor/reopener.rb,
lib/semantic_logger/queue_processor/reporter.rb,
lib/semantic_logger/queue_processor/held_write.rb,
lib/semantic_logger/queue_processor/batch_failure.rb,
lib/semantic_logger/queue_processor/throttled_counter.rb

Overview

Internal class that processes log messages from a queue on a separate thread.

Internal use only: it owns the worker thread and the in-memory queue that back the asynchronous appender proxy (SemanticLogger::Appender::Async). It is never returned to application code.

Supports two processing modes, selected by the batch: option:

* Streaming (batch: false): each log message is written to the appender as it is dequeued.
* Batching  (batch: true):  log messages are grouped and written via the appender's #batch
                          method, either once batch_size messages have accumulated, or
                          batch_seconds have elapsed since the previous batch.

Defined Under Namespace

Classes: Backoff, BatchFailure, HeldWrite, Inbox, Reopener, Reporter, Request, ThrottledCounter

Constant Summary collapse

STOPPED_WORKER_WAIT_SECONDS =

Internal: seconds that #reopen waits for a worker thread that has stopped to end.

0.1

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(appender:, max_queue_size: 10_000, lag_check_interval: 1_000, lag_threshold_s: 30, batch: false, batch_size: 300, batch_seconds: 5, non_blocking: false, dropped_message_report_seconds: 30, async_max_retries: 100) ⇒ QueueProcessor

Parameters:

appender: [SemanticLogger::Subscriber]
The appender to forward log messages to from the worker thread.

max_queue_size: [Integer]
The maximum number of log messages to hold on the queue before blocking attempts to add to the queue.
-1: The queue size is uncapped and will never block no matter how long the queue is.
Default: 10,000

lag_threshold_s: [Float]
Log a warning when a log message has been on the queue for longer than this period in seconds.
Default: 30

lag_check_interval: [Integer]
Number of messages to process before checking for slow logging.
Default: 1,000
Note: Not applicable when batch: true.

batch: [true|false]
Process log messages in batches via the appender's #batch method.
Default: false
Note: The appender must implement #batch.

batch_size: [Integer]
Maximum number of messages to batch up before sending.
Default: 300
Note: Only applicable when batch: true.

batch_seconds: [Integer]
Maximum number of seconds between sending batches.
Default: 5
Note: Only applicable when batch: true.

non_blocking: [true|false]
Whether to drop log messages instead of blocking the calling thread when the queue is full.
Only applies to a capped queue.
Default: false

dropped_message_report_seconds: [Integer]
Log the count of messages dropped because the queue was full, with non_blocking or once
the worker thread has stopped (see async_max_retries), to the internal logger at most once
every this number of seconds. Also limits how often messages discarded because they could
not be written are reported, after the first.
Default: 30

async_max_retries: [Integer]
Maximum number of consecutive times to restart the worker thread after it raises an
exception while processing messages. Each restart first sleeps for `retry_count` seconds
(1s, then 2s, ...) as a back-off, unless a flush or close is waiting (see #flush), or the
process is exiting (see #process_exiting=). Once this many consecutive retries are
exhausted the thread stops instead of restarting. The counter resets to zero whenever a
message is processed successfully. A message or batch that the destination failed is
written again after the back-off when the appender says that the write wrote none of it
(see Subscriber#wrote_nothing?), up to HeldWrite::MAX_RESENDS times after the destination
answered with a failure, and is otherwise discarded.
-1: Retry indefinitely and never stop the thread (the pre-v5 behaviour). The back-off
    still applies, and still resets after any successful message.
A worker thread started again by #reopen in the same process carries on with the count, so
that one that had used all its retries stops again at its first failure, rather than hold
up the threads logging to it with a back-off as long again while the destination is still
unavailable; one that stopped before, such as after a fatal exception, has the retries it
had left. Only the worker thread of a child process, after a fork, starts counting afresh.
Default: 100

Raises:

  • (ArgumentError)


96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/semantic_logger/queue_processor.rb', line 96

def initialize(appender:,
               max_queue_size: 10_000,
               lag_check_interval: 1_000,
               lag_threshold_s: 30,
               batch: false,
               batch_size: 300,
               batch_seconds: 5,
               non_blocking: false,
               dropped_message_report_seconds: 30,
               async_max_retries: 100)
  @appender                       = appender
  @lag_check_interval             = lag_check_interval
  @lag_threshold_s                = lag_threshold_s
  @batch                          = batch
  @batch_size                     = batch_size
  @batch_seconds                  = batch_seconds
  @non_blocking                   = non_blocking
  @dropped_message_report_seconds = dropped_message_report_seconds
  @backoff                        = Backoff.new(async_max_retries)
  @thread                         = nil
  # Only batch mode parks the worker on the signal; streaming mode never touches it.
  @signal                         = Concurrent::Event.new if batch
  @reporter                       = Reporter.new(appender)
  @reopener                       = Reopener.new(appender, @reporter)
  @processed_count                = 0
  @inbox                          = Inbox.new(max_queue_size)
  @held                           = HeldWrite.new

  return unless batch? && !appender.respond_to?(:batch)

  raise(ArgumentError, "#{appender.class.name} does not support batching. It must implement #batch")
end

Instance Attribute Details

#appender ⇒ Object (readonly)

Returns the value of attribute appender.



28
29
30
# File 'lib/semantic_logger/queue_processor.rb', line 28

def appender
  @appender
end

#batch_seconds ⇒ Object

Returns the value of attribute batch_seconds.



26
27
28
# File 'lib/semantic_logger/queue_processor.rb', line 26

def batch_seconds
  @batch_seconds
end

#batch_size ⇒ Object

Returns the value of attribute batch_size.



26
27
28
# File 'lib/semantic_logger/queue_processor.rb', line 26

def batch_size
  @batch_size
end

#dropped_message_report_seconds ⇒ Object

Returns the value of attribute dropped_message_report_seconds.



26
27
28
# File 'lib/semantic_logger/queue_processor.rb', line 26

def dropped_message_report_seconds
  @dropped_message_report_seconds
end

#lag_check_interval ⇒ Object

Returns the value of attribute lag_check_interval.



26
27
28
# File 'lib/semantic_logger/queue_processor.rb', line 26

def lag_check_interval
  @lag_check_interval
end

#lag_threshold_s ⇒ Object

Returns the value of attribute lag_threshold_s.



26
27
28
# File 'lib/semantic_logger/queue_processor.rb', line 26

def lag_threshold_s
  @lag_threshold_s
end

#non_blocking ⇒ Object

Returns the value of attribute non_blocking.



26
27
28
# File 'lib/semantic_logger/queue_processor.rb', line 26

def non_blocking
  @non_blocking
end

#processed_count ⇒ Object (readonly)

Returns the value of attribute processed_count.



28
29
30
# File 'lib/semantic_logger/queue_processor.rb', line 28

def processed_count
  @processed_count
end

#signal ⇒ Object (readonly)

Returns the value of attribute signal.



28
29
30
# File 'lib/semantic_logger/queue_processor.rb', line 28

def signal
  @signal
end

Class Method Details

.start(**args) ⇒ Object

Create a new processor and start its worker thread.



31
# File 'lib/semantic_logger/queue_processor.rb', line 31

def self.start(**args) = new(**args).tap(&:thread)

Instance Method Details

#active? ⇒ Boolean

Returns [true|false] whether the worker thread is running.

Returns:

  • (Boolean)


145
# File 'lib/semantic_logger/queue_processor.rb', line 145

def active? = @thread&.alive?

#async_max_retries ⇒ Object

Returns [Integer] the maximum number of consecutive retries after a failure (see #initialize).



133
# File 'lib/semantic_logger/queue_processor.rb', line 133

def async_max_retries = @backoff.max_retries

#await_reopen ⇒ Object

Wait until the worker thread has reopened the appender, when a reopen has been asked for (see #reopen) and it has not yet finished it, such as in a forked child whose worker thread has not yet written anything. Returns at once when none is pending, so that it costs nothing otherwise.

The worker thread reopens the appender before it takes anything off the queue, so a flush submitted now runs after the reopen, and returns once it has (see #flush). Like #flush, it returns without waiting when called on the worker thread itself, or once that thread has stopped. Takes no lock, as #flush takes none, so that it can be called from a signal trap.



291
# File 'lib/semantic_logger/queue_processor.rb', line 291

def await_reopen = !@reopener.pending? || flush

#batch? ⇒ Boolean

Returns [true|false] whether messages are processed in batches.

Returns:

  • (Boolean)


178
# File 'lib/semantic_logger/queue_processor.rb', line 178

def batch? = @batch

#capped? ⇒ Boolean

Returns [true|false] whether the queue has a capped size.

Returns:

  • (Boolean)


164
# File 'lib/semantic_logger/queue_processor.rb', line 164

def capped? = @inbox.capped?

#close ⇒ Object

Flush any outstanding messages and close the appender.



220
# File 'lib/semantic_logger/queue_processor.rb', line 220

def close = submit_request(:close)

#dropped_count ⇒ Object

Returns [Integer] the number of log messages dropped because the queue was full.



171
# File 'lib/semantic_logger/queue_processor.rb', line 171

def dropped_count = @reporter.dropped_count

#failed_count ⇒ Object

Returns [Integer] the number of log messages discarded because they could not be written, whether their content or the destination was at fault (see Subscriber#message_error?).



175
# File 'lib/semantic_logger/queue_processor.rb', line 175

def failed_count = @reporter.failed_count

#flush ⇒ Object

Flush all queued log entries to the appender. All queued log messages are written and then the appender is flushed.

A flush or close does not wait out back-offs after the destination failed, nor each message ahead of it failing in turn: submitting it ends the back-off under way, and until it has run, a message or batch that the destination fails is discarded, rather than written again after a back-off, and so are the messages queued after that one, ahead of the flush or close, without being written (see Backoff#give_up?).



217
# File 'lib/semantic_logger/queue_processor.rb', line 217

def flush = submit_request(:flush)

#hand_over(&task) ⇒ Object

Hand the block over to the worker thread, which runs it between writes, after the entries already queued, without waiting for it to run. The block reports its own errors: one that it raises is handled as a failure of the appender.

Never waits, so that it can be called on a thread that the worker thread may itself be waiting for, such as the worker thread of an appender that it hands entries to, whose full queue it waits on. When the queue is full, a new thread adds the block to the queue, waiting for room, rather than the calling thread: once the calling thread returns, the worker thread can make room (see Inbox#push_aside). When the worker thread is not running, or has stopped (see #stopped?), or stops while that thread waits, a new thread runs the block instead, since nothing then writes to the appender. Takes no lock, so that it can be called from a signal trap.

A batching worker thread is not woken up, since that would write a partial batch: it runs the block at its next batch, at most batch_seconds later.



236
# File 'lib/semantic_logger/queue_processor.rb', line 236

def hand_over(&task) = pass_on([Request.new(task)])

#holding_up?(thread = Thread.current) ⇒ Boolean

Returns [true|false] whether the thread is the worker thread while another thread may be waiting for it: the queue is full, so that a thread adding to it waits for it to make room, or a request, such as a flush or close, is waiting for it to run it (see Backoff#request_waiting?), whoever submitted it, so a message it logs that could wait may be dropped (see #waited_on?). Lock free.

Returns:

  • (Boolean)


155
# File 'lib/semantic_logger/queue_processor.rb', line 155

def holding_up?(thread = Thread.current) = worker_thread?(thread) && (@inbox.full? || @backoff.request_waiting?)

#log(log) ⇒ Object

Add a log message to the queue for processing.

When non-blocking and the queue is full, the message is dropped instead of blocking the calling thread, and the count of dropped messages is reported periodically.

Once the worker thread has stopped for good (see async_max_retries), nothing will empty the queue, so messages are also dropped instead of blocking the calling thread forever. That includes a message already waiting for room on the full queue when the worker thread stops.

Nor does a thread that the worker thread may itself be waiting for wait for room on the full queue (see #waited_on?): the message is dropped instead.



195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/semantic_logger/queue_processor.rb', line 195

def log(log)
  enqueued = @inbox.push(log, wait: !(non_blocking? || stopped?)) { !stopped? && !waited_on? }
  # Reported at most once every dropped_message_report_seconds, with whether it was dropped
  # because the worker thread has stopped for good.
  message_dropped unless enqueued

  # For batches wake up the processing thread once the number of queued messages has been
  # exceeded. Also wake it on a drop so it drains the full queue rather than waiting out the
  # batch interval.
  signal.set if batch? && (queue.size >= batch_size)

  enqueued
end

#logger ⇒ Object

Internal logger used to report problems encountered while processing log messages.



130
# File 'lib/semantic_logger/queue_processor.rb', line 130

def logger = @reporter.logger

#max_queue_size ⇒ Object

Returns [Integer] the most entries the queue holds, or -1 for no limit.



161
# File 'lib/semantic_logger/queue_processor.rb', line 161

def max_queue_size = @inbox.max_queue_size

#non_blocking? ⇒ Boolean

Returns [true|false] whether messages are dropped instead of blocking when the queue is full. Only a capped queue can drop messages.

Returns:

  • (Boolean)


168
# File 'lib/semantic_logger/queue_processor.rb', line 168

def non_blocking? = @non_blocking && capped?

#process_exiting=(exiting) ⇒ Object

Tell the worker thread whether the process is exiting, before and after the flush at exit (see Backoff#exiting=). While it is, the worker thread acts as though a flush were waiting (see #flush), already before the flush at exit reaches this queue: it stops backing off and writing again what the destination failed, and once the destination fails, discards the messages queued ahead of the next request, such as the flush at exit, so that the process exits promptly during an outage. Takes no lock, so that it can be called from any thread, or a signal trap.



245
246
247
# File 'lib/semantic_logger/queue_processor.rb', line 245

def process_exiting=(exiting)
  @backoff.exiting = exiting
end

#queue ⇒ Object

Returns [Queue|SizedQueue] the queue of log messages and requests waiting for the worker thread.



158
# File 'lib/semantic_logger/queue_processor.rb', line 158

def queue = @inbox.queue

#renew_after_fork ⇒ Object

After a fork, the queue holds the entries that the parent process had queued, which the parent's worker thread writes, so the child starts again with an empty queue and a worker thread of its own, rather than write them a second time. Does nothing in the process that created the queue. Asks for no reopen of the appender: #reopen asks before it calls this.

Called on the thread that reopens after the fork, which takes no lock (see #reopen). Called by Processor#reopen, through Appenders#renew_after_fork, before the appender is asked to reopen: the new worker thread has nothing to write until the processor's worker thread, which asks first, hands it entries.



302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/semantic_logger/queue_processor.rb', line 302

def renew_after_fork
  return unless @inbox.forked?

  # Workaround CRuby crash on fork by recreating queue on reopen
  #   https://github.com/reidmorrison/semantic_logger/issues/103
  @inbox.recreate
  # The parent process writes the messages it held to write again.
  @held.release
  @thread&.kill if @thread&.alive?
  # A worker thread new to this process, which has not failed to write yet.
  @backoff.restart
  spawn_worker
end

#reopen ⇒ Object

Reopen the appender, on the worker thread, and the queue and worker thread after a fork (see #renew_after_fork), or start the worker thread again within the same process once it has ended or stopped.

The worker thread reopens the appender before it next takes messages off the queue, or writes again the ones it holds (see Reopener), so that it is never reopened while it is writing, and this returns before it has. After a fork, the reopen is asked for before the child's new worker thread starts, so that it reopens the appender before it writes anything. To wake up a streaming worker thread waiting for the next message, :reopen is added to the queue, without waiting for room: one that is not waiting has messages to write, and reopens the appender before them. A batching worker thread is not woken up, since that would write a partial batch, so nothing is added to its queue: it reopens the appender at its next batch, at most batch_seconds later, or when a flush or close wakes it up, before running them.

Within the same process, such as after a log rotation, the queue and its entries are kept, and so is the worker thread while it runs (see #thread). It writes the queued entries in order, starting with one it has already taken off the queue, and no other thread writes to the appender meanwhile. A worker thread that has ended is replaced by one that carries on with the queued entries, and with the count of failures in a row (see async_max_retries). So is one that has stopped (see #stopped?), which may still be reporting that it stopped: it is given a moment to end first, so that its report comes before the new thread's. A worker thread that has stopped no longer writes to the appender, nor changes the state of this processor, so none that was replaced can change it once a new one has started.

Also called from a signal trap, such as one that reopens the log files after a rotation, where Ruby does not allow a Mutex to be locked, so it takes none: it uses only Queue and Thread methods, which Ruby allows there.



276
277
278
279
280
281
# File 'lib/semantic_logger/queue_processor.rb', line 276

def reopen
  @reopener.ask
  renew_after_fork
  @inbox.push(:reopen, wait: false) unless batch?
  restart_worker
end

#retry_count ⇒ Object

Returns [Integer] the number of consecutive failures, since a message was last processed.



136
# File 'lib/semantic_logger/queue_processor.rb', line 136

def retry_count = @backoff.retry_count

#stopped? ⇒ Boolean

Returns [true|false] whether the worker thread gave up after an error, so that queued messages are no longer being processed.

Returns:

  • (Boolean)


182
# File 'lib/semantic_logger/queue_processor.rb', line 182

def stopped? = @stopped == true

#thread ⇒ Object

Returns [Thread] the worker thread.

Starts the worker thread if it is not currently running. It carries on with the count of failures in a row (see async_max_retries).



142
# File 'lib/semantic_logger/queue_processor.rb', line 142

def thread = active? ? @thread : spawn_worker

#worker_thread?(thread = Thread.current) ⇒ Boolean

Returns [true|false] whether the thread is the worker thread, the one that writes to the appender. Takes no lock, so that it can be called from a signal trap.

Returns:

  • (Boolean)


149
# File 'lib/semantic_logger/queue_processor.rb', line 149

def worker_thread?(thread = Thread.current) = @thread.equal?(thread)