sidekiq 5.1.3 → 6.4.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of sidekiq might be problematic. Click here for more details.

Files changed (106) hide show
  1. checksums.yaml +5 -5
  2. data/Changes.md +391 -1
  3. data/LICENSE +3 -3
  4. data/README.md +23 -34
  5. data/bin/sidekiq +27 -3
  6. data/bin/sidekiqload +68 -62
  7. data/bin/sidekiqmon +8 -0
  8. data/lib/generators/sidekiq/job_generator.rb +57 -0
  9. data/lib/generators/sidekiq/templates/{worker.rb.erb → job.rb.erb} +2 -2
  10. data/lib/generators/sidekiq/templates/{worker_spec.rb.erb → job_spec.rb.erb} +1 -1
  11. data/lib/generators/sidekiq/templates/{worker_test.rb.erb → job_test.rb.erb} +1 -1
  12. data/lib/sidekiq/api.rb +344 -243
  13. data/lib/sidekiq/cli.rb +209 -221
  14. data/lib/sidekiq/client.rb +62 -64
  15. data/lib/sidekiq/delay.rb +7 -6
  16. data/lib/sidekiq/exception_handler.rb +10 -12
  17. data/lib/sidekiq/extensions/action_mailer.rb +13 -22
  18. data/lib/sidekiq/extensions/active_record.rb +13 -10
  19. data/lib/sidekiq/extensions/class_methods.rb +14 -11
  20. data/lib/sidekiq/extensions/generic_proxy.rb +6 -4
  21. data/lib/sidekiq/fetch.rb +40 -32
  22. data/lib/sidekiq/job.rb +13 -0
  23. data/lib/sidekiq/job_logger.rb +35 -9
  24. data/lib/sidekiq/job_retry.rb +88 -68
  25. data/lib/sidekiq/job_util.rb +65 -0
  26. data/lib/sidekiq/launcher.rb +170 -73
  27. data/lib/sidekiq/logger.rb +170 -0
  28. data/lib/sidekiq/manager.rb +18 -22
  29. data/lib/sidekiq/middleware/chain.rb +20 -8
  30. data/lib/sidekiq/middleware/current_attributes.rb +57 -0
  31. data/lib/sidekiq/middleware/i18n.rb +5 -7
  32. data/lib/sidekiq/monitor.rb +133 -0
  33. data/lib/sidekiq/paginator.rb +20 -16
  34. data/lib/sidekiq/processor.rb +135 -83
  35. data/lib/sidekiq/rails.rb +42 -38
  36. data/lib/sidekiq/redis_connection.rb +49 -30
  37. data/lib/sidekiq/scheduled.rb +94 -31
  38. data/lib/sidekiq/sd_notify.rb +149 -0
  39. data/lib/sidekiq/systemd.rb +24 -0
  40. data/lib/sidekiq/testing/inline.rb +2 -1
  41. data/lib/sidekiq/testing.rb +40 -31
  42. data/lib/sidekiq/util.rb +57 -15
  43. data/lib/sidekiq/version.rb +2 -1
  44. data/lib/sidekiq/web/action.rb +15 -11
  45. data/lib/sidekiq/web/application.rb +109 -74
  46. data/lib/sidekiq/web/csrf_protection.rb +180 -0
  47. data/lib/sidekiq/web/helpers.rb +117 -93
  48. data/lib/sidekiq/web/router.rb +23 -19
  49. data/lib/sidekiq/web.rb +61 -105
  50. data/lib/sidekiq/worker.rb +257 -99
  51. data/lib/sidekiq.rb +81 -46
  52. data/sidekiq.gemspec +23 -23
  53. data/web/assets/images/apple-touch-icon.png +0 -0
  54. data/web/assets/javascripts/application.js +83 -64
  55. data/web/assets/javascripts/dashboard.js +66 -75
  56. data/web/assets/stylesheets/application-dark.css +143 -0
  57. data/web/assets/stylesheets/application-rtl.css +0 -4
  58. data/web/assets/stylesheets/application.css +77 -231
  59. data/web/assets/stylesheets/bootstrap.css +2 -2
  60. data/web/locales/ar.yml +9 -2
  61. data/web/locales/de.yml +14 -2
  62. data/web/locales/en.yml +7 -1
  63. data/web/locales/es.yml +21 -5
  64. data/web/locales/fr.yml +10 -3
  65. data/web/locales/ja.yml +7 -1
  66. data/web/locales/lt.yml +83 -0
  67. data/web/locales/pl.yml +4 -4
  68. data/web/locales/ru.yml +4 -0
  69. data/web/locales/vi.yml +83 -0
  70. data/web/views/_footer.erb +1 -1
  71. data/web/views/_job_info.erb +3 -2
  72. data/web/views/_nav.erb +3 -17
  73. data/web/views/_poll_link.erb +2 -5
  74. data/web/views/_summary.erb +7 -7
  75. data/web/views/busy.erb +54 -20
  76. data/web/views/dashboard.erb +22 -14
  77. data/web/views/dead.erb +3 -3
  78. data/web/views/layout.erb +4 -2
  79. data/web/views/morgue.erb +9 -6
  80. data/web/views/queue.erb +20 -10
  81. data/web/views/queues.erb +11 -3
  82. data/web/views/retries.erb +14 -7
  83. data/web/views/retry.erb +3 -3
  84. data/web/views/scheduled.erb +5 -2
  85. metadata +39 -136
  86. data/.github/contributing.md +0 -32
  87. data/.github/issue_template.md +0 -11
  88. data/.gitignore +0 -13
  89. data/.travis.yml +0 -14
  90. data/3.0-Upgrade.md +0 -70
  91. data/4.0-Upgrade.md +0 -53
  92. data/5.0-Upgrade.md +0 -56
  93. data/COMM-LICENSE +0 -95
  94. data/Ent-Changes.md +0 -216
  95. data/Gemfile +0 -8
  96. data/Pro-2.0-Upgrade.md +0 -138
  97. data/Pro-3.0-Upgrade.md +0 -44
  98. data/Pro-4.0-Upgrade.md +0 -35
  99. data/Pro-Changes.md +0 -729
  100. data/Rakefile +0 -8
  101. data/bin/sidekiqctl +0 -99
  102. data/code_of_conduct.md +0 -50
  103. data/lib/generators/sidekiq/worker_generator.rb +0 -49
  104. data/lib/sidekiq/core_ext.rb +0 -1
  105. data/lib/sidekiq/logging.rb +0 -122
  106. data/lib/sidekiq/middleware/server/active_record.rb +0 -23
data/lib/sidekiq/rails.rb CHANGED
@@ -1,37 +1,9 @@
1
1
  # frozen_string_literal: true
2
- module Sidekiq
3
- class Rails < ::Rails::Engine
4
- # We need to setup this up before any application configuration which might
5
- # change Sidekiq middleware.
6
- #
7
- # This hook happens after `Rails::Application` is inherited within
8
- # config/application.rb and before config is touched, usually within the
9
- # class block. Definitely before config/environments/*.rb and
10
- # config/initializers/*.rb.
11
- config.before_configuration do
12
- if ::Rails::VERSION::MAJOR < 5 && defined?(::ActiveRecord)
13
- Sidekiq.server_middleware do |chain|
14
- require 'sidekiq/middleware/server/active_record'
15
- chain.add Sidekiq::Middleware::Server::ActiveRecord
16
- end
17
- end
18
- end
19
2
 
20
- config.after_initialize do
21
- # This hook happens after all initializers are run, just before returning
22
- # from config/environment.rb back to sidekiq/cli.rb.
23
- # We have to add the reloader after initialize to see if cache_classes has
24
- # been turned on.
25
- #
26
- # None of this matters on the client-side, only within the Sidekiq process itself.
27
- #
28
- Sidekiq.configure_server do |_|
29
- if ::Rails::VERSION::MAJOR >= 5
30
- Sidekiq.options[:reloader] = Sidekiq::Rails::Reloader.new
31
- end
32
- end
33
- end
3
+ require "sidekiq/worker"
34
4
 
5
+ module Sidekiq
6
+ class Rails < ::Rails::Engine
35
7
  class Reloader
36
8
  def initialize(app = ::Rails.application)
37
9
  @app = app
@@ -47,11 +19,43 @@ module Sidekiq
47
19
  "#<Sidekiq::Rails::Reloader @app=#{@app.class.name}>"
48
20
  end
49
21
  end
50
- end if defined?(::Rails)
51
- end
52
22
 
53
- if defined?(::Rails) && ::Rails::VERSION::MAJOR < 4
54
- $stderr.puts("**************************************************")
55
- $stderr.puts("⛔️ WARNING: Sidekiq server is no longer supported by Rails 3.2 - please ensure your server/workers are updated")
56
- $stderr.puts("**************************************************")
57
- end
23
+ # By including the Options module, we allow AJs to directly control sidekiq features
24
+ # via the *sidekiq_options* class method and, for instance, not use AJ's retry system.
25
+ # AJ retries don't show up in the Sidekiq UI Retries tab, save any error data, can't be
26
+ # manually retried, don't automatically die, etc.
27
+ #
28
+ # class SomeJob < ActiveJob::Base
29
+ # queue_as :default
30
+ # sidekiq_options retry: 3, backtrace: 10
31
+ # def perform
32
+ # end
33
+ # end
34
+ initializer "sidekiq.active_job_integration" do
35
+ ActiveSupport.on_load(:active_job) do
36
+ include ::Sidekiq::Worker::Options unless respond_to?(:sidekiq_options)
37
+ end
38
+ end
39
+
40
+ initializer "sidekiq.rails_logger" do
41
+ Sidekiq.configure_server do |_|
42
+ # This is the integration code necessary so that if code uses `Rails.logger.info "Hello"`,
43
+ # it will appear in the Sidekiq console with all of the job context. See #5021 and
44
+ # https://github.com/rails/rails/blob/b5f2b550f69a99336482739000c58e4e04e033aa/railties/lib/rails/commands/server/server_command.rb#L82-L84
45
+ unless ::Rails.logger == ::Sidekiq.logger || ::ActiveSupport::Logger.logger_outputs_to?(::Rails.logger, $stdout)
46
+ ::Rails.logger.extend(::ActiveSupport::Logger.broadcast(::Sidekiq.logger))
47
+ end
48
+ end
49
+ end
50
+
51
+ # This hook happens after all initializers are run, just before returning
52
+ # from config/environment.rb back to sidekiq/cli.rb.
53
+ #
54
+ # None of this matters on the client-side, only within the Sidekiq process itself.
55
+ config.after_initialize do
56
+ Sidekiq.configure_server do |_|
57
+ Sidekiq.options[:reloader] = Sidekiq::Rails::Reloader.new
58
+ end
59
+ end
60
+ end
61
+ end
@@ -1,37 +1,38 @@
1
1
  # frozen_string_literal: true
2
- require 'connection_pool'
3
- require 'redis'
4
- require 'uri'
2
+
3
+ require "connection_pool"
4
+ require "redis"
5
+ require "uri"
5
6
 
6
7
  module Sidekiq
7
8
  class RedisConnection
8
9
  class << self
10
+ def create(options = {})
11
+ symbolized_options = options.transform_keys(&:to_sym)
9
12
 
10
- def create(options={})
11
- options.keys.each do |key|
12
- options[key.to_sym] = options.delete(key)
13
+ if !symbolized_options[:url] && (u = determine_redis_provider)
14
+ symbolized_options[:url] = u
13
15
  end
14
16
 
15
- options[:id] = "Sidekiq-#{Sidekiq.server? ? "server" : "client"}-PID-#{$$}" if !options.has_key?(:id)
16
- options[:url] ||= determine_redis_provider
17
-
18
- size = if options[:size]
19
- options[:size]
20
- elsif Sidekiq.server?
21
- Sidekiq.options[:concurrency] + 5
22
- elsif ENV['RAILS_MAX_THREADS']
23
- Integer(ENV['RAILS_MAX_THREADS'])
24
- else
25
- 5
26
- end
17
+ size = if symbolized_options[:size]
18
+ symbolized_options[:size]
19
+ elsif Sidekiq.server?
20
+ # Give ourselves plenty of connections. pool is lazy
21
+ # so we won't create them until we need them.
22
+ Sidekiq.options[:concurrency] + 5
23
+ elsif ENV["RAILS_MAX_THREADS"]
24
+ Integer(ENV["RAILS_MAX_THREADS"])
25
+ else
26
+ 5
27
+ end
27
28
 
28
29
  verify_sizing(size, Sidekiq.options[:concurrency]) if Sidekiq.server?
29
30
 
30
- pool_timeout = options[:pool_timeout] || 1
31
- log_info(options)
31
+ pool_timeout = symbolized_options[:pool_timeout] || 1
32
+ log_info(symbolized_options)
32
33
 
33
- ConnectionPool.new(:timeout => pool_timeout, :size => size) do
34
- build_client(options)
34
+ ConnectionPool.new(timeout: pool_timeout, size: size) do
35
+ build_client(symbolized_options)
35
36
  end
36
37
  end
37
38
 
@@ -46,7 +47,7 @@ module Sidekiq
46
47
  # - enterprise's leader election
47
48
  # - enterprise's cron support
48
49
  def verify_sizing(size, concurrency)
49
- raise ArgumentError, "Your Redis connection pool is too small for Sidekiq to work. Your pool has #{size} connections but must have at least #{concurrency + 2}" if size <= concurrency
50
+ raise ArgumentError, "Your Redis connection pool is too small for Sidekiq to work. Your pool has #{size} connections but must have at least #{concurrency + 2}" if size < (concurrency + 2)
50
51
  end
51
52
 
52
53
  def build_client(options)
@@ -55,8 +56,8 @@ module Sidekiq
55
56
  client = Redis.new client_opts(options)
56
57
  if namespace
57
58
  begin
58
- require 'redis/namespace'
59
- Redis::Namespace.new(namespace, :redis => client)
59
+ require "redis/namespace"
60
+ Redis::Namespace.new(namespace, redis: client)
60
61
  rescue LoadError
61
62
  Sidekiq.logger.error("Your Redis configuration uses the namespace '#{namespace}' but the redis-namespace gem is not included in the Gemfile." \
62
63
  "Add the gem to your Gemfile to continue using a namespace. Otherwise, remove the namespace parameter.")
@@ -78,7 +79,7 @@ module Sidekiq
78
79
  opts.delete(:network_timeout)
79
80
  end
80
81
 
81
- opts[:driver] ||= 'ruby'
82
+ opts[:driver] ||= Redis::Connection.drivers.last || "ruby"
82
83
 
83
84
  # Issue #3303, redis-rb will silently retry an operation.
84
85
  # This can lead to duplicate jobs if Sidekiq::Client's LPUSH
@@ -91,9 +92,13 @@ module Sidekiq
91
92
  end
92
93
 
93
94
  def log_info(options)
94
- # Don't log Redis AUTH password
95
95
  redacted = "REDACTED"
96
- scrubbed_options = options.dup
96
+
97
+ # Deep clone so we can muck with these options all we want and exclude
98
+ # params from dump-and-load that may contain objects that Marshal is
99
+ # unable to safely dump.
100
+ keys = options.keys - [:logger, :ssl_params]
101
+ scrubbed_options = Marshal.load(Marshal.dump(options.slice(*keys)))
97
102
  if scrubbed_options[:url] && (uri = URI.parse(scrubbed_options[:url])) && uri.password
98
103
  uri.password = redacted
99
104
  scrubbed_options[:url] = uri.to_s
@@ -101,6 +106,9 @@ module Sidekiq
101
106
  if scrubbed_options[:password]
102
107
  scrubbed_options[:password] = redacted
103
108
  end
109
+ scrubbed_options[:sentinels]&.each do |sentinel|
110
+ sentinel[:password] = redacted if sentinel[:password]
111
+ end
104
112
  if Sidekiq.server?
105
113
  Sidekiq.logger.info("Booting Sidekiq #{Sidekiq::VERSION} with redis options #{scrubbed_options}")
106
114
  else
@@ -115,11 +123,22 @@ module Sidekiq
115
123
  # REDIS_PROVIDER=MY_REDIS_URL
116
124
  # and Sidekiq will find your custom URL variable with no custom
117
125
  # initialization code at all.
126
+ #
127
+ p = ENV["REDIS_PROVIDER"]
128
+ if p && p =~ /:/
129
+ raise <<~EOM
130
+ REDIS_PROVIDER should be set to the name of the variable which contains the Redis URL, not a URL itself.
131
+ Platforms like Heroku will sell addons that publish a *_URL variable. You need to tell Sidekiq with REDIS_PROVIDER, e.g.:
132
+
133
+ REDISTOGO_URL=redis://somehost.example.com:6379/4
134
+ REDIS_PROVIDER=REDISTOGO_URL
135
+ EOM
136
+ end
137
+
118
138
  ENV[
119
- ENV['REDIS_PROVIDER'] || 'REDIS_URL'
139
+ p || "REDIS_URL"
120
140
  ]
121
141
  end
122
-
123
142
  end
124
143
  end
125
144
  end
@@ -1,35 +1,64 @@
1
1
  # frozen_string_literal: true
2
- require 'sidekiq'
3
- require 'sidekiq/util'
4
- require 'sidekiq/api'
2
+
3
+ require "sidekiq"
4
+ require "sidekiq/util"
5
+ require "sidekiq/api"
5
6
 
6
7
  module Sidekiq
7
8
  module Scheduled
8
- SETS = %w(retry schedule)
9
+ SETS = %w[retry schedule]
9
10
 
10
11
  class Enq
11
- def enqueue_jobs(now=Time.now.to_f.to_s, sorted_sets=SETS)
12
+ LUA_ZPOPBYSCORE = <<~LUA
13
+ local key, now = KEYS[1], ARGV[1]
14
+ local jobs = redis.call("zrangebyscore", key, "-inf", now, "limit", 0, 1)
15
+ if jobs[1] then
16
+ redis.call("zrem", key, jobs[1])
17
+ return jobs[1]
18
+ end
19
+ LUA
20
+
21
+ def initialize
22
+ @done = false
23
+ @lua_zpopbyscore_sha = nil
24
+ end
25
+
26
+ def enqueue_jobs(sorted_sets = SETS)
12
27
  # A job's "score" in Redis is the time at which it should be processed.
13
28
  # Just check Redis for the set of jobs with a timestamp before now.
14
29
  Sidekiq.redis do |conn|
15
30
  sorted_sets.each do |sorted_set|
16
- # Get the next item in the queue if it's score (time to execute) is <= now.
31
+ # Get next item in the queue with score (time to execute) <= now.
17
32
  # We need to go through the list one at a time to reduce the risk of something
18
33
  # going wrong between the time jobs are popped from the scheduled queue and when
19
34
  # they are pushed onto a work queue and losing the jobs.
20
- while job = conn.zrangebyscore(sorted_set, '-inf', now, :limit => [0, 1]).first do
21
-
22
- # Pop item off the queue and add it to the work queue. If the job can't be popped from
23
- # the queue, it's because another process already popped it so we can move on to the
24
- # next one.
25
- if conn.zrem(sorted_set, job)
26
- Sidekiq::Client.push(Sidekiq.load_json(job))
27
- Sidekiq::Logging.logger.debug { "enqueued #{sorted_set}: #{job}" }
28
- end
35
+ while !@done && (job = zpopbyscore(conn, keys: [sorted_set], argv: [Time.now.to_f.to_s]))
36
+ Sidekiq::Client.push(Sidekiq.load_json(job))
37
+ Sidekiq.logger.debug { "enqueued #{sorted_set}: #{job}" }
29
38
  end
30
39
  end
31
40
  end
32
41
  end
42
+
43
+ def terminate
44
+ @done = true
45
+ end
46
+
47
+ private
48
+
49
+ def zpopbyscore(conn, keys: nil, argv: nil)
50
+ if @lua_zpopbyscore_sha.nil?
51
+ raw_conn = conn.respond_to?(:redis) ? conn.redis : conn
52
+ @lua_zpopbyscore_sha = raw_conn.script(:load, LUA_ZPOPBYSCORE)
53
+ end
54
+
55
+ conn.evalsha(@lua_zpopbyscore_sha, keys: keys, argv: argv)
56
+ rescue Redis::CommandError => e
57
+ raise unless e.message.start_with?("NOSCRIPT")
58
+
59
+ @lua_zpopbyscore_sha = nil
60
+ retry
61
+ end
33
62
  end
34
63
 
35
64
  ##
@@ -47,11 +76,14 @@ module Sidekiq
47
76
  @sleeper = ConnectionPool::TimedStack.new
48
77
  @done = false
49
78
  @thread = nil
79
+ @count_calls = 0
50
80
  end
51
81
 
52
82
  # Shut down this instance, will pause until the thread is dead.
53
83
  def terminate
54
84
  @done = true
85
+ @enq.terminate if @enq.respond_to?(:terminate)
86
+
55
87
  if @thread
56
88
  t = @thread
57
89
  @thread = nil
@@ -61,26 +93,24 @@ module Sidekiq
61
93
  end
62
94
 
63
95
  def start
64
- @thread ||= safe_thread("scheduler") do
96
+ @thread ||= safe_thread("scheduler") {
65
97
  initial_wait
66
98
 
67
- while !@done
99
+ until @done
68
100
  enqueue
69
101
  wait
70
102
  end
71
103
  Sidekiq.logger.info("Scheduler exiting...")
72
- end
104
+ }
73
105
  end
74
106
 
75
107
  def enqueue
76
- begin
77
- @enq.enqueue_jobs
78
- rescue => ex
79
- # Most likely a problem with redis networking.
80
- # Punt and try again at the next interval
81
- logger.error ex.message
82
- handle_exception(ex)
83
- end
108
+ @enq.enqueue_jobs
109
+ rescue => ex
110
+ # Most likely a problem with redis networking.
111
+ # Punt and try again at the next interval
112
+ logger.error ex.message
113
+ handle_exception(ex)
84
114
  end
85
115
 
86
116
  private
@@ -97,9 +127,34 @@ module Sidekiq
97
127
  sleep 5
98
128
  end
99
129
 
100
- # Calculates a random interval that is ±50% the desired average.
101
130
  def random_poll_interval
102
- poll_interval_average * rand + poll_interval_average.to_f / 2
131
+ # We want one Sidekiq process to schedule jobs every N seconds. We have M processes
132
+ # and **don't** want to coordinate.
133
+ #
134
+ # So in N*M second timespan, we want each process to schedule once. The basic loop is:
135
+ #
136
+ # * sleep a random amount within that N*M timespan
137
+ # * wake up and schedule
138
+ #
139
+ # We want to avoid one edge case: imagine a set of 2 processes, scheduling every 5 seconds,
140
+ # so N*M = 10. Each process decides to randomly sleep 8 seconds, now we've failed to meet
141
+ # that 5 second average. Thankfully each schedule cycle will sleep randomly so the next
142
+ # iteration could see each process sleep for 1 second, undercutting our average.
143
+ #
144
+ # So below 10 processes, we special case and ensure the processes sleep closer to the average.
145
+ # In the example above, each process should schedule every 10 seconds on average. We special
146
+ # case smaller clusters to add 50% so they would sleep somewhere between 5 and 15 seconds.
147
+ # As we run more processes, the scheduling interval average will approach an even spread
148
+ # between 0 and poll interval so we don't need this artifical boost.
149
+ #
150
+ if process_count < 10
151
+ # For small clusters, calculate a random interval that is ±50% the desired average.
152
+ poll_interval_average * rand + poll_interval_average.to_f / 2
153
+ else
154
+ # With 10+ processes, we should have enough randomness to get decent polling
155
+ # across the entire timespan
156
+ poll_interval_average * rand
157
+ end
103
158
  end
104
159
 
105
160
  # We do our best to tune the poll interval to the size of the active Sidekiq
@@ -123,9 +178,18 @@ module Sidekiq
123
178
  # This minimizes a single point of failure by dispersing check-ins but without taxing
124
179
  # Redis if you run many Sidekiq processes.
125
180
  def scaled_poll_interval
126
- pcount = Sidekiq::ProcessSet.new.size
181
+ process_count * Sidekiq.options[:average_scheduled_poll_interval]
182
+ end
183
+
184
+ def process_count
185
+ # The work buried within Sidekiq::ProcessSet#cleanup can be
186
+ # expensive at scale. Cut it down by 90% with this counter.
187
+ # NB: This method is only called by the scheduler thread so we
188
+ # don't need to worry about the thread safety of +=.
189
+ pcount = Sidekiq::ProcessSet.new(@count_calls % 10 == 0).size
127
190
  pcount = 1 if pcount == 0
128
- pcount * Sidekiq.options[:average_scheduled_poll_interval]
191
+ @count_calls += 1
192
+ pcount
129
193
  end
130
194
 
131
195
  def initial_wait
@@ -139,7 +203,6 @@ module Sidekiq
139
203
  @sleeper.pop(total)
140
204
  rescue Timeout::Error
141
205
  end
142
-
143
206
  end
144
207
  end
145
208
  end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The MIT License
4
+ #
5
+ # Copyright (c) 2017, 2018, 2019, 2020 Agis Anastasopoulos
6
+ #
7
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
8
+ # this software and associated documentation files (the "Software"), to deal in
9
+ # the Software without restriction, including without limitation the rights to
10
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11
+ # the Software, and to permit persons to whom the Software is furnished to do so,
12
+ # subject to the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be included in all
15
+ # copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ # This is a copy of https://github.com/agis/ruby-sdnotify as of commit a7d52ee
25
+ # The only changes made was "rehoming" it within the Sidekiq module to avoid
26
+ # namespace collisions and applying standard's code formatting style.
27
+
28
+ require "socket"
29
+
30
+ # SdNotify is a pure-Ruby implementation of sd_notify(3). It can be used to
31
+ # notify systemd about state changes. Methods of this package are no-op on
32
+ # non-systemd systems (eg. Darwin).
33
+ #
34
+ # The API maps closely to the original implementation of sd_notify(3),
35
+ # therefore be sure to check the official man pages prior to using SdNotify.
36
+ #
37
+ # @see https://www.freedesktop.org/software/systemd/man/sd_notify.html
38
+ module Sidekiq
39
+ module SdNotify
40
+ # Exception raised when there's an error writing to the notification socket
41
+ class NotifyError < RuntimeError; end
42
+
43
+ READY = "READY=1"
44
+ RELOADING = "RELOADING=1"
45
+ STOPPING = "STOPPING=1"
46
+ STATUS = "STATUS="
47
+ ERRNO = "ERRNO="
48
+ MAINPID = "MAINPID="
49
+ WATCHDOG = "WATCHDOG=1"
50
+ FDSTORE = "FDSTORE=1"
51
+
52
+ def self.ready(unset_env = false)
53
+ notify(READY, unset_env)
54
+ end
55
+
56
+ def self.reloading(unset_env = false)
57
+ notify(RELOADING, unset_env)
58
+ end
59
+
60
+ def self.stopping(unset_env = false)
61
+ notify(STOPPING, unset_env)
62
+ end
63
+
64
+ # @param status [String] a custom status string that describes the current
65
+ # state of the service
66
+ def self.status(status, unset_env = false)
67
+ notify("#{STATUS}#{status}", unset_env)
68
+ end
69
+
70
+ # @param errno [Integer]
71
+ def self.errno(errno, unset_env = false)
72
+ notify("#{ERRNO}#{errno}", unset_env)
73
+ end
74
+
75
+ # @param pid [Integer]
76
+ def self.mainpid(pid, unset_env = false)
77
+ notify("#{MAINPID}#{pid}", unset_env)
78
+ end
79
+
80
+ def self.watchdog(unset_env = false)
81
+ notify(WATCHDOG, unset_env)
82
+ end
83
+
84
+ def self.fdstore(unset_env = false)
85
+ notify(FDSTORE, unset_env)
86
+ end
87
+
88
+ # @return [Boolean] true if the service manager expects watchdog keep-alive
89
+ # notification messages to be sent from this process.
90
+ #
91
+ # If the $WATCHDOG_USEC environment variable is set,
92
+ # and the $WATCHDOG_PID variable is unset or set to the PID of the current
93
+ # process
94
+ #
95
+ # @note Unlike sd_watchdog_enabled(3), this method does not mutate the
96
+ # environment.
97
+ def self.watchdog?
98
+ wd_usec = ENV["WATCHDOG_USEC"]
99
+ wd_pid = ENV["WATCHDOG_PID"]
100
+
101
+ return false unless wd_usec
102
+
103
+ begin
104
+ wd_usec = Integer(wd_usec)
105
+ rescue
106
+ return false
107
+ end
108
+
109
+ return false if wd_usec <= 0
110
+ return true if !wd_pid || wd_pid == $$.to_s
111
+
112
+ false
113
+ end
114
+
115
+ # Notify systemd with the provided state, via the notification socket, if
116
+ # any.
117
+ #
118
+ # Generally this method will be used indirectly through the other methods
119
+ # of the library.
120
+ #
121
+ # @param state [String]
122
+ # @param unset_env [Boolean]
123
+ #
124
+ # @return [Fixnum, nil] the number of bytes written to the notification
125
+ # socket or nil if there was no socket to report to (eg. the program wasn't
126
+ # started by systemd)
127
+ #
128
+ # @raise [NotifyError] if there was an error communicating with the systemd
129
+ # socket
130
+ #
131
+ # @see https://www.freedesktop.org/software/systemd/man/sd_notify.html
132
+ def self.notify(state, unset_env = false)
133
+ sock = ENV["NOTIFY_SOCKET"]
134
+
135
+ return nil unless sock
136
+
137
+ ENV.delete("NOTIFY_SOCKET") if unset_env
138
+
139
+ begin
140
+ Addrinfo.unix(sock, :DGRAM).connect do |s|
141
+ s.close_on_exec = true
142
+ s.write(state)
143
+ end
144
+ rescue => e
145
+ raise NotifyError, "#{e.class}: #{e.message}", e.backtrace
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,24 @@
1
+ #
2
+ # Sidekiq's systemd integration allows Sidekiq to inform systemd:
3
+ # 1. when it has successfully started
4
+ # 2. when it is starting shutdown
5
+ # 3. periodically for a liveness check with a watchdog thread
6
+ #
7
+ module Sidekiq
8
+ def self.start_watchdog
9
+ usec = Integer(ENV["WATCHDOG_USEC"])
10
+ return Sidekiq.logger.error("systemd Watchdog too fast: " + usec) if usec < 1_000_000
11
+
12
+ sec_f = usec / 1_000_000.0
13
+ # "It is recommended that a daemon sends a keep-alive notification message
14
+ # to the service manager every half of the time returned here."
15
+ ping_f = sec_f / 2
16
+ Sidekiq.logger.info "Pinging systemd watchdog every #{ping_f.round(1)} sec"
17
+ Thread.new do
18
+ loop do
19
+ sleep ping_f
20
+ Sidekiq::SdNotify.watchdog
21
+ end
22
+ end
23
+ end
24
+ end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
- require 'sidekiq/testing'
2
+
3
+ require "sidekiq/testing"
3
4
 
4
5
  ##
5
6
  # The Sidekiq inline infrastructure overrides perform_async so that it