Skip to content

A platform for community discussion. Free, open, simple.

FIX: Safely restart Sidekiq when mem usage is high (#31883)

Bianca Nenciue0a4adb22481
diff --git a/lib/demon/base.rb b/lib/demon/base.rb
index 10a4ebbc771..993da1716f3 100644
--- a/lib/demon/base.rb
+++ b/lib/demon/base.rb
@@ -50,14 +50,12 @@ class Demon::Base
end
attr_reader :pid, :parent_pid, :started, :index
- attr_accessor :stop_timeout
def initialize(index, rails_root: nil, parent_pid: nil, verbose: false, logger: nil)
@index = index
@pid = nil
@parent_pid = parent_pid || Process.pid
@started = false
- @stop_timeout = 10
@rails_root = rails_root || Rails.root
@verbose = verbose
@logger = logger || Logger.new(STDERR)
@@ -88,6 +86,10 @@ class Demon::Base
"HUP"
end
+ def stop_timeout
+ 10
+ end
+
def restart
stop
start
@@ -101,11 +103,11 @@ class Demon::Base
wait_for_stop =
lambda do
- timeout = @stop_timeout
+ timeout = stop_timeout
while alive? && timeout > 0
- timeout -= (@stop_timeout / 10.0)
- sleep(@stop_timeout / 10.0)
+ timeout -= (stop_timeout / 10.0)
+ sleep(stop_timeout / 10.0)
begin
Process.waitpid(@pid, Process::WNOHANG)
rescue StandardError
diff --git a/lib/demon/sidekiq.rb b/lib/demon/sidekiq.rb
index d90daac5aa1..fb3fdbfbb1b 100644
--- a/lib/demon/sidekiq.rb
+++ b/lib/demon/sidekiq.rb
@@ -11,6 +11,10 @@ class Demon::Sidekiq < ::Demon::Base
blk ? (@blk = blk) : @blk
end
+ # Number of seconds Sidekiq waits for jobs to finish before forcefully
+ # terminating them. See the "-t" CLI option.
+ SIDEKIQ_SHUTDOWN_TIMEOUT_SECONDS = 5
+
# By default Sidekiq does a heartbeat check every 5 seconds. If the processes misses 20 heartbeat checks, we consider it
# dead and kill the process.
SIDEKIQ_HEARTBEAT_CHECK_MISS_THRESHOLD_SECONDS = 5.seconds * 20
@@ -70,6 +74,19 @@ class Demon::Sidekiq < ::Demon::Base
[ENV["UNICORN_SIDEKIQ_MAX_RSS"].to_i, DEFAULT_MAX_ALLOWED_SIDEKIQ_RSS_MEGABYTES].max.megabytes
end
+ def stop_signal
+ "TERM"
+ end
+
+ def stop_timeout
+ # Official documentation says that Sidekiq should be given shutdown timeout
+ # plus 5 seconds to shutdown cleanly.
+ #
+ # See https://github.com/sidekiq/sidekiq/wiki/Deployment.
+
+ SIDEKIQ_SHUTDOWN_TIMEOUT_SECONDS + 5
+ end
+
private
def suppress_stdout
@@ -100,7 +117,12 @@ class Demon::Sidekiq < ::Demon::Base
reopen_logs
end
- options = ["-c", GlobalSetting.sidekiq_workers.to_s]
+ options = [
+ "-c",
+ GlobalSetting.sidekiq_workers.to_s,
+ "-t",
+ SIDEKIQ_SHUTDOWN_TIMEOUT_SECONDS.to_s,
+ ]
[["critical", 8], ["default", 4], ["low", 2], ["ultra_low", 1]].each do |queue_name, weight|
custom_queue_hostname = ENV["UNICORN_SIDEKIQ_#{queue_name.upcase}_QUEUE_HOSTNAME"]