Class: LogStash::Pipeline

Inherits:
Object
  • Object
show all
Defined in:
lib/logstash/pipeline.rb

Constant Summary collapse

DEFAULT_SETTINGS =
{
  :default_pipeline_workers => LogStash::Config::CpuCoreStrategy.maximum,
  :pipeline_batch_size => 125,
  :pipeline_batch_delay => 5, # in milliseconds
  :flush_interval => 5, # in seconds
  :flush_timeout_interval => 60 # in seconds
}
MAX_INFLIGHT_WARN_THRESHOLD =

in seconds

10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_str, settings = {}) ⇒ Pipeline

Returns a new instance of Pipeline.



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
68
69
70
71
72
73
74
75
# File 'lib/logstash/pipeline.rb', line 31

def initialize(config_str, settings = {})
  @pipeline_id = settings[:pipeline_id] || self.object_id
  @logger = Cabin::Channel.get(LogStash)
  @settings = DEFAULT_SETTINGS.clone
  settings.each {|setting, value| configure(setting, value) }
  @reporter = LogStash::PipelineReporter.new(@logger, self)

  @inputs = nil
  @filters = nil
  @outputs = nil

  @worker_threads = []

  grammar = LogStashConfigParser.new
  @config = grammar.parse(config_str)
  if @config.nil?
    raise LogStash::ConfigurationError, grammar.failure_reason
  end
  # This will compile the config to ruby and evaluate the resulting code.
  # The code will initialize all the plugins and define the
  # filter and output methods.
  code = @config.compile
  # The config code is hard to represent as a log message...
  # So just print it.
  @logger.debug? && @logger.debug("Compiled pipeline code:\n#{code}")
  begin
    eval(code)
  rescue => e
    raise
  end

  @input_queue = LogStash::Util::WrappedSynchronousQueue.new
  @events_filtered = Concurrent::AtomicFixnum.new(0)
  @events_consumed = Concurrent::AtomicFixnum.new(0)

  # We generally only want one thread at a time able to access pop/take/poll operations
  # from this queue. We also depend on this to be able to block consumers while we snapshot
  # in-flight buffers
  @input_queue_pop_mutex = Mutex.new
  @input_threads = []
  # @ready requires thread safety since it is typically polled from outside the pipeline thread
  @ready = Concurrent::AtomicBoolean.new(false)
  @running = Concurrent::AtomicBoolean.new(false)
  @flushing = Concurrent::AtomicReference.new(false)
end

Instance Attribute Details

#events_consumedObject (readonly)

Returns the value of attribute events_consumed.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def events_consumed
  @events_consumed
end

#events_filteredObject (readonly)

Returns the value of attribute events_filtered.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def events_filtered
  @events_filtered
end

#filtersObject (readonly)

Returns the value of attribute filters.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def filters
  @filters
end

#inputsObject (readonly)

Returns the value of attribute inputs.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def inputs
  @inputs
end

#loggerObject (readonly)

Returns the value of attribute logger.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def logger
  @logger
end

#outputsObject (readonly)

Returns the value of attribute outputs.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def outputs
  @outputs
end

#pipeline_idObject (readonly)

Returns the value of attribute pipeline_id.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def pipeline_id
  @pipeline_id
end

#reporterObject (readonly)

Returns the value of attribute reporter.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def reporter
  @reporter
end

#worker_threadsObject (readonly)

Returns the value of attribute worker_threads.



20
21
22
# File 'lib/logstash/pipeline.rb', line 20

def worker_threads
  @worker_threads
end

Instance Method Details

#configure(setting, value) ⇒ Object



81
82
83
# File 'lib/logstash/pipeline.rb', line 81

def configure(setting, value)
  @settings[setting] = value
end

#default_output_workersObject



409
410
411
# File 'lib/logstash/pipeline.rb', line 409

def default_output_workers
  @settings[:pipeline_workers] || @settings[:default_pipeline_workers]
end

#filter(event, &block) ⇒ Object

for backward compatibility in devutils for the rspec helpers, this method is not used in the pipeline anymore.



415
416
417
418
# File 'lib/logstash/pipeline.rb', line 415

def filter(event, &block)
  # filter_func returns all filtered events, including cancelled ones
  filter_func(event).each { |e| block.call(e) }
end

#filter_batch(batch) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/logstash/pipeline.rb', line 253

def filter_batch(batch)
  batch.reduce([]) do |acc,e|
    if e.is_a?(LogStash::Event)
      filtered = filter_func(e)
      filtered.each {|fe| acc << fe unless fe.cancelled?}
    end
    acc
  end
rescue Exception => e
  # Plugins authors should manage their own exceptions in the plugin code
  # but if an exception is raised up to the worker thread they are considered
  # fatal and logstash will not recover from this situation.
  #
  # Users need to check their configuration or see if there is a bug in the
  # plugin.
  @logger.error("Exception in pipelineworker, the pipeline stopped processing new events, please check your filter configuration and restart Logstash.",
                "exception" => e, "backtrace" => e.backtrace)
  raise
end

#filters?Boolean

Returns:

  • (Boolean)


115
116
117
# File 'lib/logstash/pipeline.rb', line 115

def filters?
  return @filters.any?
end

#flushObject



448
449
450
451
452
453
# File 'lib/logstash/pipeline.rb', line 448

def flush
  if @flushing.compare_and_set(false, true)
    @logger.debug? && @logger.debug("Pushing flush onto pipeline")
    @input_queue.push(LogStash::FLUSH)
  end
end

#flush_filters(options = {}, &block) ⇒ Object

perform filters flush and yeild flushed event to the passed block

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :final (Boolean)

    > true to signal a final shutdown flush



424
425
426
427
428
429
430
# File 'lib/logstash/pipeline.rb', line 424

def flush_filters(options = {}, &block)
  flushers = options[:final] ? @shutdown_flushers : @periodic_flushers

  flushers.each do |flusher|
    flusher.call(options, &block)
  end
end

#flush_filters_to_batch(batch, options = {}) ⇒ Object

perform filters flush into the output queue

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :final (Boolean)

    > true to signal a final shutdown flush



458
459
460
461
462
463
464
465
466
467
# File 'lib/logstash/pipeline.rb', line 458

def flush_filters_to_batch(batch, options = {})
  flush_filters(options) do |event|
    unless event.cancelled?
      @logger.debug? and @logger.debug("Pushing flushed events", :event => event)
      batch << event
    end
  end

  @flushing.set(false)
end

#inflight_batches_synchronizeObject



297
298
299
300
301
# File 'lib/logstash/pipeline.rb', line 297

def inflight_batches_synchronize
  @input_queue_pop_mutex.synchronize do
    yield(@inflight_batches)
  end
end

#inputworker(plugin) ⇒ Object



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/logstash/pipeline.rb', line 328

def inputworker(plugin)
  LogStash::Util::set_thread_name("[#{pipeline_id}]<#{plugin.class.config_name}")
  begin
    plugin.run(@input_queue)
  rescue => e
    if plugin.stop?
      @logger.debug("Input plugin raised exception during shutdown, ignoring it.",
                    :plugin => plugin.class.config_name, :exception => e,
                    :backtrace => e.backtrace)
      return
    end

    # otherwise, report error and restart
    if @logger.debug?
      @logger.error(I18n.t("logstash.pipeline.worker-error-debug",
                           :plugin => plugin.inspect, :error => e.to_s,
                           :exception => e.class,
                           :stacktrace => e.backtrace.join("\n")))
    else
      @logger.error(I18n.t("logstash.pipeline.worker-error",
                           :plugin => plugin.inspect, :error => e))
    end

    # Assuming the failure that caused this exception is transient,
    # let's sleep for a bit and execute #run again
    sleep(1)
    retry
  ensure
    plugin.do_close
  end
end

#output_batch(batch) ⇒ Object

Take an array of events and send them to the correct output



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/logstash/pipeline.rb', line 274

def output_batch(batch)
  # Build a mapping of { output_plugin => [events...]}
  outputs_events = batch.reduce(Hash.new { |h, k| h[k] = [] }) do |acc, event|
    # We ask the AST to tell us which outputs to send each event to
    # Then, we stick it in the correct bin

    # output_func should never return anything other than an Array but we have lots of legacy specs
    # that monkeypatch it and return nil. We can deprecate  "|| []" after fixing these specs
    outputs_for_event = output_func(event) || []

    outputs_for_event.each { |output| acc[output] << event }
    acc
  end

  # Now that we have our output to event mapping we can just invoke each output
  # once with its list of events
  outputs_events.each { |output, events| output.multi_receive(events) }
end

#plugin(plugin_type, name, *args) ⇒ Object



397
398
399
400
401
402
403
404
405
406
407
# File 'lib/logstash/pipeline.rb', line 397

def plugin(plugin_type, name, *args)
  args << {} if args.empty?

  klass = LogStash::Plugin.lookup(plugin_type, name)

  if plugin_type == "output"
    LogStash::OutputDelegator.new(@logger, klass, default_output_workers, *args)
  else
    klass.new(*args)
  end
end

#plugin_threads_infoObject

flush_filters_to_output!



469
470
471
472
473
# File 'lib/logstash/pipeline.rb', line 469

def plugin_threads_info
  input_threads = @input_threads.select {|t| t.alive? }
  worker_threads = @worker_threads.select {|t| t.alive? }
  (input_threads + worker_threads).map {|t| LogStash::Util.thread_info(t) }
end

#ready?Boolean

def initialize

Returns:

  • (Boolean)


77
78
79
# File 'lib/logstash/pipeline.rb', line 77

def ready?
  @ready.value
end

#runObject



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/logstash/pipeline.rb', line 119

def run
  LogStash::Util.set_thread_name("[#{pipeline_id}]-pipeline-manager")
  @logger.terminal(LogStash::Util::DefaultsPrinter.print(@settings))

  start_workers

  @logger.info("Pipeline started")
  @logger.terminal("Logstash startup completed")

  # Block until all inputs have stopped
  # Generally this happens if SIGINT is sent and `shutdown` is called from an external thread

  transition_to_running
  start_flusher # Launches a non-blocking thread for flush events
  wait_inputs
  transition_to_stopped

  @logger.info("Input plugins stopped! Will shutdown filter/output workers.")

  shutdown_flusher
  shutdown_workers

  @logger.info("Pipeline shutdown complete.")
  @logger.terminal("Logstash shutdown completed")

  # exit code
  return 0
end

#running?Boolean

Returns:

  • (Boolean)


156
157
158
# File 'lib/logstash/pipeline.rb', line 156

def running?
  @running.true?
end

#safe_pipeline_worker_countObject



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/logstash/pipeline.rb', line 85

def safe_pipeline_worker_count
  default = DEFAULT_SETTINGS[:default_pipeline_workers]
  thread_count = @settings[:pipeline_workers] #override from args "-w 8" or config
  safe_filters, unsafe_filters = @filters.partition(&:threadsafe?)

  if unsafe_filters.any?
    plugins = unsafe_filters.collect { |f| f.class.config_name }
    case thread_count
    when nil
      # user did not specify a worker thread count
      # warn if the default is multiple

      if default > 1
        @logger.warn("Defaulting pipeline worker threads to 1 because there are some filters that might not work with multiple worker threads",
                     :count_was => default, :filters => plugins)
      end

      1 # can't allow the default value to propagate if there are unsafe filters
    when 0, 1
      1
    else
      @logger.warn("Warning: Manual override - there are filters that might not work with multiple worker threads",
                   :worker_threads => thread_count, :filters => plugins)
      thread_count # allow user to force this even if there are unsafe filters
    end
  else
    thread_count || default
  end
end

#set_current_thread_inflight_batch(batch) ⇒ Object



293
294
295
# File 'lib/logstash/pipeline.rb', line 293

def set_current_thread_inflight_batch(batch)
  @inflight_batches[Thread.current] = batch
end

#shutdown(&before_stop) ⇒ Object

initiate the pipeline shutdown sequence this method is intended to be called from outside the pipeline thread

Parameters:

  • before_stop (Proc)

    code block called before performing stop operation on input plugins



363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/logstash/pipeline.rb', line 363

def shutdown(&before_stop)
  # shutdown can only start once the pipeline has completed its startup.
  # avoid potential race conditoon between the startup sequence and this
  # shutdown method which can be called from another thread at any time
  sleep(0.1) while !ready?

  # TODO: should we also check against calling shutdown multiple times concurently?

  before_stop.call if block_given?

  @logger.info "Closing inputs"
  @inputs.each(&:do_stop)
  @logger.info "Closed inputs"
end

#shutdown_flusherObject



444
445
446
# File 'lib/logstash/pipeline.rb', line 444

def shutdown_flusher
  @flusher_thread.join
end

#shutdown_workersObject

After ‘shutdown` is called from an external thread this is called from the main thread to tell the worker threads to stop and then block until they’ve fully stopped This also stops all filter and output plugins



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/logstash/pipeline.rb', line 381

def shutdown_workers
  # Each worker thread will receive this exactly once!
  @worker_threads.each do |t|
    @logger.debug("Pushing shutdown", :thread => t)
    @input_queue.push(LogStash::SHUTDOWN)
  end

  @worker_threads.each do |t|
    @logger.debug("Shutdown waiting for worker thread #{t}")
    t.join
  end

  @filters.each(&:do_close)
  @outputs.each(&:do_close)
end

#stalling_threads_infoObject



475
476
477
478
479
480
481
# File 'lib/logstash/pipeline.rb', line 475

def stalling_threads_info
  plugin_threads_info
    .reject {|t| t["blocked_on"] } # known benign blocking statuses
    .each {|t| t.delete("backtrace") }
    .each {|t| t.delete("blocked_on") }
    .each {|t| t.delete("status") }
end

#start_flusherObject



432
433
434
435
436
437
438
439
440
441
442
# File 'lib/logstash/pipeline.rb', line 432

def start_flusher
  # Invariant to help detect improper initialization
  raise "Attempted to start flusher on a stopped pipeline!" if stopped?

  @flusher_thread = Thread.new do
    while Stud.stoppable_sleep(5, 0.1) { stopped? }
      flush
      break if stopped?
    end
  end
end

#start_input(plugin) ⇒ Object



324
325
326
# File 'lib/logstash/pipeline.rb', line 324

def start_input(plugin)
  @input_threads << Thread.new { inputworker(plugin) }
end

#start_inputsObject



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/logstash/pipeline.rb', line 307

def start_inputs
  moreinputs = []
  @inputs.each do |input|
    if input.threadable && input.threads > 1
      (input.threads - 1).times do |i|
        moreinputs << input.clone
      end
    end
  end
  @inputs += moreinputs

  @inputs.each do |input|
    input.register
    start_input(input)
  end
end

#start_workersObject



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/logstash/pipeline.rb', line 164

def start_workers
  @inflight_batches = {}

  @worker_threads.clear # In case we're restarting the pipeline
  begin
    start_inputs
    @outputs.each {|o| o.register }
    @filters.each {|f| f.register}

    pipeline_workers = safe_pipeline_worker_count
    batch_size = @settings[:pipeline_batch_size]
    batch_delay = @settings[:pipeline_batch_delay]
    max_inflight = batch_size * pipeline_workers
    @logger.info("Starting pipeline",
                 :id => self.pipeline_id,
                 :pipeline_workers => pipeline_workers,
                 :batch_size => batch_size,
                 :batch_delay => batch_delay,
                 :max_inflight => max_inflight)
    if max_inflight > MAX_INFLIGHT_WARN_THRESHOLD
      @logger.warn "CAUTION: Recommended inflight events max exceeded! Logstash will run with up to #{max_inflight} events in memory in your current configuration. If your message sizes are large this may cause instability with the default heap size. Please consider setting a non-standard heap size, changing the batch size (currently #{batch_size}), or changing the number of pipeline workers (currently #{pipeline_workers})"
    end

    pipeline_workers.times do |t|
      @worker_threads << Thread.new do
        LogStash::Util.set_thread_name("[#{pipeline_id}]>worker#{t}")
        worker_loop(batch_size, batch_delay)
      end
    end
  ensure
    # it is important to garantee @ready to be true after the startup sequence has been completed
    # to potentially unblock the shutdown method which may be waiting on @ready to proceed
    @ready.make_true
  end
end

#stopped?Boolean

Returns:

  • (Boolean)


160
161
162
# File 'lib/logstash/pipeline.rb', line 160

def stopped?
  @running.false?
end

#take_batch(batch_size, batch_delay) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/logstash/pipeline.rb', line 227

def take_batch(batch_size, batch_delay)
  batch = []
  # Since this is externally synchronized in `worker_look` wec can guarantee that the visibility of an insight batch
  # guaranteed to be a full batch not a partial batch
  set_current_thread_inflight_batch(batch)

  signal = false
  batch_size.times do |t|
    event = (t == 0) ? @input_queue.take : @input_queue.poll(batch_delay)

    if event.nil?
      next
    elsif event == LogStash::SHUTDOWN || event == LogStash::FLUSH
      # We MUST break here. If a batch consumes two SHUTDOWN events
      # then another worker may have its SHUTDOWN 'stolen', thus blocking
      # the pipeline. We should stop doing work after flush as well.
      signal = event
      break
    else
      batch << event
    end
  end

  [batch, signal]
end

#transition_to_runningObject

def run



148
149
150
# File 'lib/logstash/pipeline.rb', line 148

def transition_to_running
  @running.make_true
end

#transition_to_stoppedObject



152
153
154
# File 'lib/logstash/pipeline.rb', line 152

def transition_to_stopped
  @running.make_false
end

#wait_inputsObject



303
304
305
# File 'lib/logstash/pipeline.rb', line 303

def wait_inputs
  @input_threads.each(&:join)
end

#worker_loop(batch_size, batch_delay) ⇒ Object

Main body of what a worker thread does Repeatedly takes batches off the queu, filters, then outputs them



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/logstash/pipeline.rb', line 202

def worker_loop(batch_size, batch_delay)
  running = true

  while running
    # To understand the purpose behind this synchronize please read the body of take_batch
    input_batch, signal = @input_queue_pop_mutex.synchronize { take_batch(batch_size, batch_delay) }
    running = false if signal == LogStash::SHUTDOWN

    @events_consumed.increment(input_batch.size)

    filtered_batch = filter_batch(input_batch)

    if signal # Flush on SHUTDOWN or FLUSH
      flush_options = (signal == LogStash::SHUTDOWN) ? {:final => true} : {}
      flush_filters_to_batch(filtered_batch, flush_options)
    end

    @events_filtered.increment(filtered_batch.size)

    output_batch(filtered_batch)

    inflight_batches_synchronize { set_current_thread_inflight_batch(nil) }
  end
end