Module: Fluent::ServerModule

Defined in:
lib/fluent/supervisor.rb

Instance Method Summary collapse

Instance Method Details

#after_runObject



91
92
93
94
95
96
97
98
99
# File 'lib/fluent/supervisor.rb', line 91

def after_run
  stop_windows_event_thread if Fluent.windows?
  stop_rpc_server if @rpc_endpoint
  stop_counter_server if @counter
  cleanup_lock_dir
  Fluent::Supervisor.cleanup_socketmanager_path unless @starting_new_supervisor_with_zero_downtime
ensure
  notify_new_supervisor_that_old_one_has_stopped if @starting_new_supervisor_with_zero_downtime
end

#before_runObject



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/fluent/supervisor.rb', line 42

def before_run
  @fluentd_conf = config[:fluentd_conf]
  @rpc_endpoint = nil
  @rpc_server = nil
  @counter = nil
  @socket_manager_server = nil
  @starting_new_supervisor_with_zero_downtime = false
  @new_supervisor_pid = nil
  start_in_parallel = ENV.key?("FLUENT_RUNNING_IN_PARALLEL_WITH_OLD")
  @zero_downtime_restart_mutex = Mutex.new

  @fluentd_lock_dir = Dir.mktmpdir("fluentd-lock-")
  ENV['FLUENTD_LOCK_DIR'] = @fluentd_lock_dir

  if config[:rpc_endpoint] and not start_in_parallel
    @rpc_endpoint = config[:rpc_endpoint]
    @enable_get_dump = config[:enable_get_dump]
    run_rpc_server
  end

  if Fluent.windows?
    install_windows_event_handler
  else
    install_supervisor_signal_handlers
  end

  if counter = config[:counter_server] and not start_in_parallel
    run_counter_server(counter)
  end

  if config[:disable_shared_socket]
    $log.info "shared socket for multiple workers is disabled"
  elsif start_in_parallel
    begin
      raise "[BUG] SERVERENGINE_SOCKETMANAGER_PATH env var must exist when starting in parallel" unless ENV.key?('SERVERENGINE_SOCKETMANAGER_PATH')
      @socket_manager_server = ServerEngine::SocketManager::Server.share_sockets_with_another_server(ENV['SERVERENGINE_SOCKETMANAGER_PATH'])
      $log.info "zero-downtime-restart: took over the shared sockets", path: ENV['SERVERENGINE_SOCKETMANAGER_PATH']
    rescue => e
      $log.error "zero-downtime-restart: cancel sequence because failed to take over the shared sockets", error: e
      raise
    end
  else
    @socket_manager_server = ServerEngine::SocketManager::Server.open
    ENV['SERVERENGINE_SOCKETMANAGER_PATH'] = @socket_manager_server.path.to_s
  end

  stop_parallel_old_supervisor_after_delay if start_in_parallel
end

#cancel_source_onlyObject



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/fluent/supervisor.rb', line 431

def cancel_source_only
  if ENV.key?("FLUENT_RUNNING_IN_PARALLEL_WITH_OLD")
    if config[:rpc_endpoint]
      begin
        @rpc_endpoint = config[:rpc_endpoint]
        @enable_get_dump = config[:enable_get_dump]
        run_rpc_server
      rescue => e
        $log.error "failed to start RPC server", error: e
      end
    end

    if counter = config[:counter_server]
      begin
        run_counter_server(counter)
      rescue => e
        $log.error "failed to start counter server", error: e
      end
    end

    $log.info "zero-downtime-restart: done all sequences, now new processes start to work fully"
    ENV.delete("FLUENT_RUNNING_IN_PARALLEL_WITH_OLD")
  end

  send_signal_to_workers(:WINCH)
end

#cleanup_lock_dirObject



101
102
103
104
# File 'lib/fluent/supervisor.rb', line 101

def cleanup_lock_dir
  FileUtils.rm(Dir.glob(File.join(@fluentd_lock_dir, "fluentd-*.lock")))
  FileUtils.rmdir(@fluentd_lock_dir)
end

#dumpObject



500
501
502
# File 'lib/fluent/supervisor.rb', line 500

def dump
  super unless @stop
end

#graceful_reloadObject



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
# File 'lib/fluent/supervisor.rb', line 357

def graceful_reload
  conf = nil
  t = Thread.new do
    $log.info 'Reloading new config'

    # Validate that loading config is valid at first
    conf = Fluent::Config.build(
      config_path: config[:config_path],
      encoding: config[:conf_encoding],
      additional_config: config[:inline_config],
      use_v1_config: config[:use_v1_config],
    )

    Fluent::VariableStore.try_to_reset do
      Fluent::Engine.reload_config(conf, supervisor: true)
    end
  end

  t.report_on_exception = false # Error is handled by myself
  t.join

  reopen_log
  send_signal_to_workers(:USR2)
  @fluentd_conf = conf.to_s
rescue => e
  $log.error "Failed to reload config file: #{e}"
end

#install_supervisor_signal_handlersObject



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/fluent/supervisor.rb', line 236

def install_supervisor_signal_handlers
  return if Fluent.windows?

  trap :HUP do
    $log.debug "fluentd supervisor process get SIGHUP"
    supervisor_sighup_handler
  end

  trap :USR1 do
    $log.debug "fluentd supervisor process get SIGUSR1"
    supervisor_sigusr1_handler
  end

  trap :USR2 do
    $log.debug 'fluentd supervisor process got SIGUSR2'
    if Fluent.windows?
      graceful_reload
    else
      zero_downtime_restart
    end
  end

  trap :WINCH do
    $log.debug 'fluentd supervisor process got SIGWINCH'
    cancel_source_only
  end
end

#install_windows_event_handlerObject



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
# File 'lib/fluent/supervisor.rb', line 282

def install_windows_event_handler
  return unless Fluent.windows?

  @pid_signame = "fluentd_#{Process.pid}"
  @signame = config[:signame]

  Thread.new do
    ipc = Win32::Ipc.new(nil)
    events = [
      {win32_event: Win32::Event.new("#{@pid_signame}_STOP_EVENT_THREAD"), action: :stop_event_thread},
      {win32_event: Win32::Event.new("#{@pid_signame}"), action: :stop},
      {win32_event: Win32::Event.new("#{@pid_signame}_HUP"), action: :hup},
      {win32_event: Win32::Event.new("#{@pid_signame}_USR1"), action: :usr1},
      {win32_event: Win32::Event.new("#{@pid_signame}_USR2"), action: :usr2},
      {win32_event: Win32::Event.new("#{@pid_signame}_CONT"), action: :cont},
    ]
    if @signame
      signame_events = [
        {win32_event: Win32::Event.new("#{@signame}"), action: :stop},
        {win32_event: Win32::Event.new("#{@signame}_HUP"), action: :hup},
        {win32_event: Win32::Event.new("#{@signame}_USR1"), action: :usr1},
        {win32_event: Win32::Event.new("#{@signame}_USR2"), action: :usr2},
        {win32_event: Win32::Event.new("#{@signame}_CONT"), action: :cont},
      ]
      events.concat(signame_events)
    end
    begin
      loop do
        infinite = 0xFFFFFFFF
        ipc_idx = ipc.wait_any(events.map {|e| e[:win32_event]}, infinite)
        event_idx = ipc_idx - 1

        if event_idx >= 0 && event_idx < events.length
          $log.debug("Got Win32 event \"#{events[event_idx][:win32_event].name}\"")
        else
          $log.warn("Unexpected return value of Win32::Ipc#wait_any: #{ipc_idx}")
        end
        case events[event_idx][:action]
        when :stop
          stop(true)
        when :hup
          supervisor_sighup_handler
        when :usr1
          supervisor_sigusr1_handler
        when :usr2
          graceful_reload
        when :cont
          supervisor_dump_handler_for_windows
        when :stop_event_thread
          break
        end
      end
    ensure
      events.each { |event| event[:win32_event].close }
    end
  end
end

#kill_workerObject



478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/fluent/supervisor.rb', line 478

def kill_worker
  if config[:worker_pid]
    pids = config[:worker_pid].clone
    config[:worker_pid].clear
    pids.each_value do |pid|
      if Fluent.windows?
        Process.kill :KILL, pid
      else
        Process.kill :TERM, pid
      end
    end
  end
end

#notify_new_supervisor_that_old_one_has_stoppedObject



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/fluent/supervisor.rb', line 217

def notify_new_supervisor_that_old_one_has_stopped
  if config[:pid_path]
    new_pid = File.read(config[:pid_path]).to_i
  else
    raise "[BUG] new_supervisor_pid is not saved" unless @new_supervisor_pid
    new_pid = @new_supervisor_pid
  end

  $log.info "zero-downtime-restart: notify the new supervisor (pid: #{new_pid}) that old one has stopped"
  Process.kill :WINCH, new_pid
rescue => e
  $log.error(
    "zero-downtime-restart: failed to notify the new supervisor." +
    " Please send SIGWINCH to the new supervisor process manually" +
    " if it does not start to work fully.",
    error: e
  )
end

#reloadObject



275
276
277
278
279
# File 'lib/fluent/supervisor.rb', line 275

def reload
  @monitors.each do |m|
    m.send_command("RELOAD\n")
  end
end

#restart(graceful) ⇒ Object

Override some methods of ServerEngine::MultiSpawnWorker Since Fluentd’s Supervisor doesn’t use ServerEngine’s HUP, USR1 and USR2 handlers (see install_supervisor_signal_handlers), they should be disabled also on Windows, just send commands to workers instead.



269
270
271
272
273
# File 'lib/fluent/supervisor.rb', line 269

def restart(graceful)
  @monitors.each do |m|
    m.send_command(graceful ? "GRACEFUL_RESTART\n" : "IMMEDIATE_RESTART\n")
  end
end

#run_counter_server(counter_conf) ⇒ Object



186
187
188
189
190
191
192
# File 'lib/fluent/supervisor.rb', line 186

def run_counter_server(counter_conf)
  @counter = Fluent::Counter::Server.new(
    counter_conf.scope,
    {host: counter_conf.bind, port: counter_conf.port, log: $log, path: counter_conf.backup_path}
  )
  @counter.start
end

#run_rpc_serverObject



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
131
132
133
134
135
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/fluent/supervisor.rb', line 106

def run_rpc_server
  @rpc_server = RPC::Server.new(@rpc_endpoint, $log)

  # built-in RPC for signals
  @rpc_server.mount_proc('/api/processes.interruptWorkers') { |req, res|
    $log.debug "fluentd RPC got /api/processes.interruptWorkers request"
    Process.kill :INT, Process.pid
    nil
  }
  @rpc_server.mount_proc('/api/processes.killWorkers') { |req, res|
    $log.debug "fluentd RPC got /api/processes.killWorkers request"
    Process.kill :TERM, Process.pid
    nil
  }
  @rpc_server.mount_proc('/api/processes.flushBuffersAndKillWorkers') { |req, res|
    $log.debug "fluentd RPC got /api/processes.flushBuffersAndKillWorkers request"
    if Fluent.windows?
      supervisor_sigusr1_handler
      stop(true)
    else
      Process.kill :USR1, Process.pid
      Process.kill :TERM, Process.pid
    end
    nil
  }
  unless Fluent.windows?
    @rpc_server.mount_proc('/api/processes.zeroDowntimeRestart') { |req, res|
      $log.debug "fluentd RPC got /api/processes.zeroDowntimeRestart request"
      Process.kill :USR2, Process.pid
      nil
    }
  end
  @rpc_server.mount_proc('/api/plugins.flushBuffers') { |req, res|
    $log.debug "fluentd RPC got /api/plugins.flushBuffers request"
    if Fluent.windows?
      supervisor_sigusr1_handler
    else
      Process.kill :USR1, Process.pid
    end
    nil
  }
  @rpc_server.mount_proc('/api/config.reload') { |req, res|
    $log.debug "fluentd RPC got /api/config.reload request"
    if Fluent.windows?
      # restart worker with auto restarting by killing
      kill_worker
    else
      Process.kill :HUP, Process.pid
    end
    nil
  }
  @rpc_server.mount_proc('/api/config.dump') { |req, res|
    $log.debug "fluentd RPC got /api/config.dump request"
    $log.info "dump in-memory config"
    supervisor_dump_config_handler
    nil
  }

  @rpc_server.mount_proc('/api/config.gracefulReload') { |req, res|
    $log.debug "fluentd RPC got /api/config.gracefulReload request"
    graceful_reload
    nil
  }

  if @enable_get_dump
    @rpc_server.mount_proc('/api/config.getDump') { |req, res|
      $log.debug "fluentd RPC got /api/config.getDump request"
      $log.info "get dump in-memory config via HTTP"
      res.body = supervisor_get_dump_config_handler
      [nil, nil, res]
    }
  end

  @rpc_server.start
end

#stop_counter_serverObject



194
195
196
# File 'lib/fluent/supervisor.rb', line 194

def stop_counter_server
  @counter.stop
end

#stop_parallel_old_supervisor_after_delayObject



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/fluent/supervisor.rb', line 198

def stop_parallel_old_supervisor_after_delay
  Thread.new do
    # Delay to wait the new workers to start up.
    # Even if it takes a long time to start the new workers and stop the old Fluentd first,
    # it is no problem because the socket buffer works, as long as the capacity is not exceeded.
    sleep 10
    old_pid = ENV["FLUENT_RUNNING_IN_PARALLEL_WITH_OLD"]&.to_i
    if old_pid
      $log.info "zero-downtime-restart: stop the old supervisor"
      Process.kill :TERM, old_pid
    end
  rescue => e
    $log.warn "zero-downtime-restart: failed to stop the old supervisor." +
              " If the old one does not exist, please send SIGWINCH to this new process to start to work fully." +
              " If it exists, something went wrong. Please kill the old one manually.",
              error: e
  end
end

#stop_rpc_serverObject



182
183
184
# File 'lib/fluent/supervisor.rb', line 182

def stop_rpc_server
  @rpc_server&.shutdown
end

#stop_windows_event_threadObject



340
341
342
343
344
345
346
# File 'lib/fluent/supervisor.rb', line 340

def stop_windows_event_thread
  if Fluent.windows?
    ev = Win32::Event.open("#{@pid_signame}_STOP_EVENT_THREAD")
    ev.set
    ev.close
  end
end

#supervisor_dump_config_handlerObject



492
493
494
# File 'lib/fluent/supervisor.rb', line 492

def supervisor_dump_config_handler
  $log.info @fluentd_conf
end

#supervisor_dump_handler_for_windowsObject



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/fluent/supervisor.rb', line 458

def supervisor_dump_handler_for_windows
  # As for UNIX-like, SIGCONT signal to each process makes the process output its dump-file,
  # and it is implemented before the implementation of the function for Windows.
  # It is possible to trap SIGCONT and handle it here also on UNIX-like,
  # but for backward compatibility, this handler is currently for a Windows-only.
  raise "[BUG] This function is for Windows ONLY." unless Fluent.windows?

  Thread.new do
    begin
      FluentSigdump.dump_windows
    rescue => e
      $log.error "failed to dump: #{e}"
    end
  end

  send_signal_to_workers(:CONT)
rescue => e
  $log.error "failed to dump: #{e}"
end

#supervisor_get_dump_config_handlerObject



496
497
498
# File 'lib/fluent/supervisor.rb', line 496

def supervisor_get_dump_config_handler
  { conf: @fluentd_conf }
end

#supervisor_sighup_handlerObject



348
349
350
# File 'lib/fluent/supervisor.rb', line 348

def supervisor_sighup_handler
  kill_worker
end

#supervisor_sigusr1_handlerObject



352
353
354
355
# File 'lib/fluent/supervisor.rb', line 352

def supervisor_sigusr1_handler
  reopen_log
  send_signal_to_workers(:USR1)
end

#zero_downtime_restartObject



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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/fluent/supervisor.rb', line 385

def zero_downtime_restart
  Thread.new do
    @zero_downtime_restart_mutex.synchronize do
      $log.info "start zero-downtime-restart sequence"

      if @starting_new_supervisor_with_zero_downtime
        $log.warn "zero-downtime-restart: canceled because it is already starting"
        Thread.exit
      end
      if ENV.key?("FLUENT_RUNNING_IN_PARALLEL_WITH_OLD")
        $log.warn "zero-downtime-restart: canceled because the previous sequence is still running"
        Thread.exit
      end

      @starting_new_supervisor_with_zero_downtime = true
      commands = [ServerEngine.ruby_bin_path, $0] + ARGV
      env_to_add = {
        "SERVERENGINE_SOCKETMANAGER_INTERNAL_TOKEN" => ServerEngine::SocketManager::INTERNAL_TOKEN,
        "FLUENT_RUNNING_IN_PARALLEL_WITH_OLD" => "#{Process.pid}",
      }
      pid = Process.spawn(env_to_add, commands.join(" "))
      @new_supervisor_pid = pid unless config[:daemonize]

      if config[:daemonize]
        Thread.new(pid) do |pid|
          _, status = Process.wait2(pid)
          # check if `ServerEngine::Daemon#daemonize_with_double_fork` succeeded or not
          unless status.success?
            @starting_new_supervisor_with_zero_downtime = false
            $log.error "zero-downtime-restart: failed because new supervisor exits unexpectedly"
          end
        end
      else
        Thread.new(pid) do |pid|
          _, status = Process.wait2(pid)
          @starting_new_supervisor_with_zero_downtime = false
          $log.error "zero-downtime-restart: failed because new supervisor exits unexpectedly", status: status
        end
      end
    end
  rescue => e
    $log.error "zero-downtime-restart: failed", error: e
    @starting_new_supervisor_with_zero_downtime = false
  end
end