Class: LogStash::Runner

Inherits:
Clamp::StrictCommand show all
Includes:
Util::Loggable
Defined in:
lib/logstash/runner.rb

Constant Summary collapse

DEFAULT_BOOTSTRAP_CHECKS =

Ordered list of check to run before starting logstash theses checks can be changed by a plugin loaded into memory.

[
    LogStash::BootstrapCheck::DefaultConfig,
    LogStash::BootstrapCheck::PersistedQueueConfig
]
SYSTEM_SETTINGS =

We configure the registry and load any plugin that can register hooks with logstash, this needs to be done before any operation.

LogStash::SETTINGS.clone

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Clamp::StrictCommand

#handle_remaining_arguments

Methods included from Clamp::Option::StrictDeclaration

#define_appender_for, #define_deprecated_accessors_for, #define_deprecated_writer_for, #define_reader_for, #define_simple_writer_for

Constructor Details

#initialize(*args) ⇒ Runner

Returns a new instance of Runner.



222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/logstash/runner.rb', line 222

def initialize(*args)
  @settings = LogStash::SETTINGS
  @bootstrap_checks = DEFAULT_BOOTSTRAP_CHECKS.dup

  # Default we check local sources: `-e`, `-f` and the logstash.yml options.
  @source_loader = LogStash::Config::SourceLoader.new(@settings)
  @source_loader.add_source(LogStash::Config::Source::Local.new(@settings))
  @source_loader.add_source(LogStash::Config::Source::Modules.new(@settings))
  @source_loader.add_source(LogStash::Config::Source::MultiLocal.new(@settings))

  super(*args)
end

Instance Attribute Details

#agentObject (readonly)

Returns the value of attribute agent.



219
220
221
# File 'lib/logstash/runner.rb', line 219

def agent
  @agent
end

#bootstrap_checksObject

Returns the value of attribute bootstrap_checks.



220
221
222
# File 'lib/logstash/runner.rb', line 220

def bootstrap_checks
  @bootstrap_checks
end

#settingsObject (readonly)

Returns the value of attribute settings.



219
220
221
# File 'lib/logstash/runner.rb', line 219

def settings
  @settings
end

#source_loaderObject (readonly)

Returns the value of attribute source_loader.



219
220
221
# File 'lib/logstash/runner.rb', line 219

def source_loader
  @source_loader
end

Instance Method Details

#configure_plugin_paths(paths) ⇒ Object

add the given paths for ungemified/bare plugins lookups

Parameters:

  • paths (String, Array<String>)

    plugins path string or list of path strings to add



446
447
448
449
450
451
# File 'lib/logstash/runner.rb', line 446

def configure_plugin_paths(paths)
  Array(paths).each do |path|
    fail(I18n.t("logstash.runner.configuration.plugin_path_missing", :path => path)) unless File.directory?(path)
    LogStash::Environment.add_plugin_path(path)
  end
end

#create_agent(*args) ⇒ Object



453
454
455
# File 'lib/logstash/runner.rb', line 453

def create_agent(*args)
  LogStash::Agent.new(*args)
end

#executeObject



240
241
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/logstash/runner.rb', line 240

def execute
  LogStash::Util::SettingsHelper.post_process

  require "logstash/util"
  require "logstash/util/java_version"
  require "stud/task"

  # Configure Logstash logging facility, this need to be done before everything else to
  # make sure the logger has the correct settings and the log level is correctly defined.
  java.lang.System.setProperty("ls.logs", setting("path.logs"))
  java.lang.System.setProperty("ls.log.format", setting("log.format"))
  java.lang.System.setProperty("ls.log.level", setting("log.level"))
  unless java.lang.System.getProperty("log4j.configurationFile")
    log4j_config_location = ::File.join(setting("path.settings"), "log4j2.properties")

    # Windows safe way to produce a file: URI.
    file_schema = "file://" + (LogStash::Environment.windows? ? "/" : "")
    LogStash::Logging::Logger::reconfigure(URI.encode(file_schema + File.absolute_path(log4j_config_location)))
  end
  # override log level that may have been introduced from a custom log4j config file
  LogStash::Logging::Logger::configure_logging(setting("log.level"))

  if setting("config.debug") && !logger.debug?
    logger.warn("--config.debug was specified, but log.level was not set to \'debug\'! No config info will be logged.")
  end

  # Skip any validation and just return the version
  if version?
    show_version
    return 0
  end

  # Add local modules to the registry before everything else
  LogStash::Modules::Util.register_local_modules(LogStash::Environment::LOGSTASH_HOME)

  @dispatcher = LogStash::EventDispatcher.new(self)
  LogStash::PLUGIN_REGISTRY.hooks.register_emitter(self.class, @dispatcher)

  @settings.validate_all

  if @settings.registered?("xpack.monitoring.enabled")
    verify_deprecated_setting("xpack.monitoring.elasticsearch.url", "xpack.monitoring.elasticsearch.hosts")
    verify_deprecated_setting("xpack.monitoring.elasticsearch.ssl.ca", "xpack.monitoring.elasticsearch.ssl.certificate_authority")
  end

  if @settings.registered?("xpack.management.enabled")
    verify_deprecated_setting("xpack.management.elasticsearch.url", "xpack.management.elasticsearch.hosts")
    verify_deprecated_setting("xpack.management.elasticsearch.ssl.ca", "xpack.management.elasticsearch.ssl.certificate_authority")
  end

  @dispatcher.fire(:before_bootstrap_checks)

  return start_shell(setting("interactive"), binding) if setting("interactive")

  module_parser = LogStash::Modules::CLIParser.new(setting("modules_list"), setting("modules_variable_list"))
  # Now populate Setting for modules.list with our parsed array.
  @settings.set("modules.cli", module_parser.output)

  begin
    @bootstrap_checks.each { |bootstrap| bootstrap.check(@settings) }
  rescue LogStash::BootstrapCheckError => e
    signal_usage_error(e.message)
    return 1
  end
  @dispatcher.fire(:after_bootstrap_checks)

  LogStash::Util::set_thread_name(self.class.name)

  LogStash::ShutdownWatcher.unsafe_shutdown = setting("pipeline.unsafe_shutdown")

  configure_plugin_paths(setting("path.plugins"))


  @settings.format_settings.each {|line| logger.debug(line) }

  # Check for absence of any configuration
  # not bulletproof because we don't know yet if there
  # are no pipelines from pipelines.yml
  sources_without_conflict = []
  unmatched_sources_conflict_messages = []
  @source_loader.sources do |source|
    if source.config_conflict?
      if source.conflict_messages.any?
        unmatched_sources_conflict_messages << source.conflict_messages.join(", ")
      end
    else
      sources_without_conflict << source
    end
  end
  if unmatched_sources_conflict_messages.any?
    # i18n should be done at the sources side
    signal_usage_error(unmatched_sources_conflict_messages.join(" "))
    return 1
  elsif sources_without_conflict.empty?
    signal_usage_error(I18n.t("logstash.runner.missing-configuration"))
    return 1
  end

  if setting("config.test_and_exit")
    begin
      results = @source_loader.fetch

      # TODO(ph): make it better for multiple pipeline
      if results.success?
        results.response.each do |pipeline_config|
          LogStash::BasePipeline.new(pipeline_config)
        end
        puts "Configuration OK"
        logger.info "Using config.test_and_exit mode. Config Validation Result: OK. Exiting Logstash"
      else
        raise "Could not load the configuration file"
      end
      return 0
    rescue => e
      logger.fatal I18n.t("logstash.runner.invalid-configuration", :error => e.message)
      return 1
    end
  end

  # lock path.data before starting the agent
  @data_path_lock = FileLockFactory.obtainLock(java.nio.file.Paths.get(setting("path.data")).to_absolute_path, ".lock")

  logger.info("Starting Logstash", "logstash.version" => LOGSTASH_VERSION)

  @dispatcher.fire(:before_agent)
  @agent = create_agent(@settings, @source_loader)
  @dispatcher.fire(:after_agent)

  # enable sigint/sigterm before starting the agent
  # to properly handle a stalled agent
  sigint_id = trap_sigint()
  sigterm_id = trap_sigterm()

  @agent_task = Stud::Task.new { @agent.execute }

  # no point in enabling config reloading before the agent starts
  # also windows doesn't have SIGHUP. we can skip it
  sighup_id = LogStash::Environment.windows? ? nil : trap_sighup()

  agent_return = @agent_task.wait

  @agent.shutdown

  logger.info("Logstash shut down.")

  # flush any outstanding log messages during shutdown
  org.apache.logging.log4j.LogManager.shutdown

  agent_return

rescue org.logstash.LockException => e
  logger.fatal(I18n.t("logstash.runner.locked-data-path", :path => setting("path.data")))
  return 1
rescue Clamp::UsageError => e
  $stderr.puts "ERROR: #{e.message}"
  show_short_help
  return 1
rescue => e
  # if logger itself is not initialized
  if LogStash::Logging::Logger.get_logging_context.nil?
    $stderr.puts "#{I18n.t("oops")} :error => #{e}, :backtrace => #{e.backtrace}"
  else
    logger.fatal(I18n.t("oops"), :error => e, :backtrace => e.backtrace)
  end
  return 1
ensure
  Stud::untrap("INT", sigint_id) unless sigint_id.nil?
  Stud::untrap("TERM", sigterm_id) unless sigterm_id.nil?
  Stud::untrap("HUP", sighup_id) unless sighup_id.nil?
  FileLockFactory.releaseLock(@data_path_lock) if @data_path_lock
  @log_fd.close if @log_fd
end

#fail(message) ⇒ Object

Emit a failure message and abort.



458
459
460
# File 'lib/logstash/runner.rb', line 458

def fail(message)
  signal_usage_error(message)
end

#run(args) ⇒ Object



235
236
237
238
# File 'lib/logstash/runner.rb', line 235

def run(args)
  return 1 unless LogStash::Util::SettingsHelper.from_yaml(args)
  super(*[args])
end

#setting(key) ⇒ Object



513
514
515
# File 'lib/logstash/runner.rb', line 513

def setting(key)
  @settings.get_value(key)
end

#show_gemsObject

def show_version_java



437
438
439
440
441
442
# File 'lib/logstash/runner.rb', line 437

def show_gems
  require "rubygems"
  Gem::Specification.each do |spec|
    puts "gem #{spec.name} #{spec.version}"
  end
end

#show_short_helpObject

def fail



462
463
464
# File 'lib/logstash/runner.rb', line 462

def show_short_help
  puts I18n.t("logstash.runner.short-help")
end

#show_versionObject

def self.main



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

def show_version
  show_version_logstash

  if logger.info?
    show_version_ruby
    show_version_java
    show_gems if logger.debug?
  end
end

#show_version_javaObject

def show_version_ruby



431
432
433
434
435
# File 'lib/logstash/runner.rb', line 431

def show_version_java
  properties = java.lang.System.getProperties
  puts "java #{properties["java.version"]} (#{properties["java.vendor"]})"
  puts "jvm #{properties["java.vm.name"]} / #{properties["java.vm.version"]}"
end

#show_version_logstashObject

def show_version



423
424
425
# File 'lib/logstash/runner.rb', line 423

def show_version_logstash
  puts "logstash #{LOGSTASH_VERSION}"
end

#show_version_rubyObject

def show_version_logstash



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

def show_version_ruby
  puts RUBY_DESCRIPTION
end

#start_shell(shell, start_binding) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/logstash/runner.rb', line 466

def start_shell(shell, start_binding)
  case shell
  when "pry"
    require 'pry'
    start_binding.pry
  when "irb"
    require 'irb'
    ARGV.clear
    # TODO: set binding to this instance of Runner
    # currently bugged as per https://github.com/jruby/jruby/issues/384
    IRB.start(__FILE__)
  else
    fail(I18n.t("logstash.runner.invalid-shell"))
  end
end

#trap_sighupObject



482
483
484
485
486
487
# File 'lib/logstash/runner.rb', line 482

def trap_sighup
  Stud::trap("HUP") do
    logger.warn(I18n.t("logstash.agent.sighup"))
    @agent.converge_state_and_update
  end
end

#trap_sigintObject



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/logstash/runner.rb', line 496

def trap_sigint
  Stud::trap("INT") do
    if @interrupted_once
      logger.fatal(I18n.t("logstash.agent.forced_sigint"))
      # calling just Kernel.exit only raises SystemExit exception
      # and doesn't guarantee the process will terminate
      # We must call Kernel.exit! so java.lang.System.exit is called
      exit!(1)
    else
      logger.warn(I18n.t("logstash.agent.sigint"))
      Thread.new(logger) {|lg| sleep 5; lg.warn(I18n.t("logstash.agent.slow_shutdown")) }
      @interrupted_once = true
      @agent_task.stop!
    end
  end
end

#trap_sigtermObject



489
490
491
492
493
494
# File 'lib/logstash/runner.rb', line 489

def trap_sigterm
  Stud::trap("TERM") do
    logger.warn(I18n.t("logstash.agent.sigterm"))
    @agent_task.stop!
  end
end

#verify_deprecated_setting(old_setting, new_setting) ⇒ Object



517
518
519
520
521
522
523
524
525
526
# File 'lib/logstash/runner.rb', line 517

def verify_deprecated_setting(old_setting, new_setting)
  if @settings.set?(old_setting)
    logger.warn("Deprecated setting `#{old_setting}` please use `#{new_setting}`")
    if @settings.set?(new_setting)
      signal_usage_error("Both `#{new_setting}` and the deprecated `#{old_setting}` settings are set, please remove `#{old_setting}`")
    else
      @settings.set_value(new_setting, @settings.get_value(old_setting))
    end
  end
end