Class: LogStash::Pipeline

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

Constant Summary collapse

DEFAULT_OUTPUT_WORKERS =
1
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
RELOAD_INCOMPATIBLE_PLUGINS =
[
  "LogStash::Inputs::Stdin"
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Pipeline.



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/logstash/pipeline.rb', line 46

def initialize(config_str, settings = {})
  @config_str = config_str
  @original_settings = settings
  @logger = Cabin::Channel.get(LogStash)
  @pipeline_id = settings[:pipeline_id] || self.object_id
  @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

#config_strObject (readonly)

Returns the value of attribute config_str.



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

def config_str
  @config_str
end

#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

#original_settingsObject (readonly)

Returns the value of attribute original_settings.



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

def original_settings
  @original_settings
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

#threadObject (readonly)

Returns the value of attribute thread.



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

def thread
  @thread
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

Class Method Details

.validate_config(config_str, settings = {}) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/logstash/pipeline.rb', line 37

def self.validate_config(config_str, settings = {})
  begin
    # There should be a better way to test this
    self.new(config_str, settings)
  rescue => e
    e.message
  end
end

Instance Method Details

#configure(setting, value) ⇒ Object



98
99
100
# File 'lib/logstash/pipeline.rb', line 98

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

#filter(event, &block) ⇒ Object

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



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

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



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/logstash/pipeline.rb', line 268

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)


132
133
134
# File 'lib/logstash/pipeline.rb', line 132

def filters?
  return @filters.any?
end

#flushObject



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

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



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

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



469
470
471
472
473
474
475
476
477
478
# File 'lib/logstash/pipeline.rb', line 469

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



312
313
314
315
316
# File 'lib/logstash/pipeline.rb', line 312

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

#inputworker(plugin) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/logstash/pipeline.rb', line 343

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

#non_reloadable_pluginsObject



494
495
496
497
498
# File 'lib/logstash/pipeline.rb', line 494

def non_reloadable_plugins
  (inputs + filters + outputs).select do |plugin|
    RELOAD_INCOMPATIBLE_PLUGINS.include?(plugin.class.name)
  end
end

#output_batch(batch) ⇒ Object

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



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/logstash/pipeline.rb', line 289

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



412
413
414
415
416
417
418
419
420
421
422
# File 'lib/logstash/pipeline.rb', line 412

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!



480
481
482
483
484
# File 'lib/logstash/pipeline.rb', line 480

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)


94
95
96
# File 'lib/logstash/pipeline.rb', line 94

def ready?
  @ready.value
end

#runObject



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/logstash/pipeline.rb', line 136

def run
  @logger.terminal(LogStash::Util::DefaultsPrinter.print(@settings))
  @thread = Thread.current

  start_workers

  @logger.log("Pipeline #{@pipeline_id} started")

  # 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.log("Pipeline #{@pipeline_id} has been shutdown")

  # exit code
  return 0
end

#running?Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/logstash/pipeline.rb', line 171

def running?
  @running.true?
end

#safe_pipeline_worker_countObject



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
128
129
130
# File 'lib/logstash/pipeline.rb', line 102

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



308
309
310
# File 'lib/logstash/pipeline.rb', line 308

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



378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/logstash/pipeline.rb', line 378

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



455
456
457
# File 'lib/logstash/pipeline.rb', line 455

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



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

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



486
487
488
489
490
491
492
# File 'lib/logstash/pipeline.rb', line 486

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



443
444
445
446
447
448
449
450
451
452
453
# File 'lib/logstash/pipeline.rb', line 443

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



339
340
341
# File 'lib/logstash/pipeline.rb', line 339

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

#start_inputsObject



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/logstash/pipeline.rb', line 322

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



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/logstash/pipeline.rb', line 179

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)


175
176
177
# File 'lib/logstash/pipeline.rb', line 175

def stopped?
  @running.false?
end

#take_batch(batch_size, batch_delay) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/logstash/pipeline.rb', line 242

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



163
164
165
# File 'lib/logstash/pipeline.rb', line 163

def transition_to_running
  @running.make_true
end

#transition_to_stoppedObject



167
168
169
# File 'lib/logstash/pipeline.rb', line 167

def transition_to_stopped
  @running.make_false
end

#wait_inputsObject



318
319
320
# File 'lib/logstash/pipeline.rb', line 318

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



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/logstash/pipeline.rb', line 217

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