Module: Sidekiq

Extended by:
TestingExtensions
Defined in:
lib/sidekiq/systemd.rb,
lib/sidekiq.rb,
lib/sidekiq/api.rb,
lib/sidekiq/cli.rb,
lib/sidekiq/web.rb,
lib/sidekiq/util.rb,
lib/sidekiq/delay.rb,
lib/sidekiq/fetch.rb,
lib/sidekiq/rails.rb,
lib/sidekiq/client.rb,
lib/sidekiq/logger.rb,
lib/sidekiq/worker.rb,
lib/sidekiq/manager.rb,
lib/sidekiq/testing.rb,
lib/sidekiq/version.rb,
lib/sidekiq/launcher.rb,
lib/sidekiq/job_retry.rb,
lib/sidekiq/paginator.rb,
lib/sidekiq/processor.rb,
lib/sidekiq/scheduled.rb,
lib/sidekiq/sd_notify.rb,
lib/sidekiq/job_logger.rb,
lib/sidekiq/web/action.rb,
lib/sidekiq/web/router.rb,
lib/sidekiq/web/helpers.rb,
lib/sidekiq/web/application.rb,
lib/sidekiq/middleware/chain.rb,
lib/sidekiq/redis_connection.rb,
lib/sidekiq/exception_handler.rb,
lib/sidekiq/web/csrf_protection.rb,
lib/sidekiq/extensions/action_mailer.rb,
lib/sidekiq/extensions/active_record.rb,
lib/sidekiq/extensions/class_methods.rb,
lib/sidekiq/extensions/generic_proxy.rb,
lib/generators/sidekiq/worker_generator.rb

Overview

SdNotify is a pure-Ruby implementation of sd_notify(3). It can be used to notify systemd about state changes. Methods of this package are no-op on non-systemd systems (eg. Darwin).

The API maps closely to the original implementation of sd_notify(3), therefore be sure to check the official man pages prior to using SdNotify.

Defined Under Namespace

Modules: Context, ExceptionHandler, Extensions, Generators, LoggingUtils, Middleware, Paginator, Queues, Scheduled, SdNotify, TestingClient, TestingExtensions, Util, WebHelpers, WebRouter, Worker Classes: BasicFetch, CLI, Client, DeadSet, EmptyQueueError, Job, JobLogger, JobRetry, JobSet, Launcher, Logger, Manager, Monitor, Process, ProcessSet, Processor, Queue, Rails, RedisConnection, RetrySet, ScheduledSet, Shutdown, SortedEntry, SortedSet, Stats, Testing, Web, WebAction, WebApplication, WebRoute, Workers

Constant Summary collapse

NAME =
"Sidekiq"
LICENSE =
"See LICENSE and the LGPL-3.0 for licensing details."
DEFAULTS =
{
  queues: [],
  labels: [],
  concurrency: 10,
  require: ".",
  strict: true,
  environment: nil,
  timeout: 25,
  poll_interval_average: nil,
  average_scheduled_poll_interval: 5,
  error_handlers: [],
  death_handlers: [],
  lifecycle_events: {
    startup: [],
    quiet: [],
    shutdown: [],
    heartbeat: []
  },
  dead_max_jobs: 10_000,
  dead_timeout_in_seconds: 180 * 24 * 60 * 60, # 6 months
  reloader: proc { |&block| block.call }
}
DEFAULT_WORKER_OPTIONS =
{
  "retry" => true,
  "queue" => "default"
}
FAKE_INFO =
{
  "redis_version" => "9.9.9",
  "uptime_in_days" => "9999",
  "connected_clients" => "9999",
  "used_memory_human" => "9P",
  "used_memory_peak_human" => "9P"
}
VERSION =
"6.1.2"

Class Method Summary collapse

Methods included from TestingExtensions

jobs_for

Class Method Details

.average_scheduled_poll_interval=(interval) ⇒ Object

How frequently Redis should be checked by a random Sidekiq process for scheduled and retriable jobs. Each individual process will take turns by waiting some multiple of this value.

See sidekiq/scheduled.rb for an in-depth explanation of this value


224
225
226
# File 'lib/sidekiq.rb', line 224

def self.average_scheduled_poll_interval=(interval)
  options[:average_scheduled_poll_interval] = interval
end

.client_middleware {|@client_chain| ... } ⇒ Object

Yields:

  • (@client_chain)

141
142
143
144
145
# File 'lib/sidekiq.rb', line 141

def self.client_middleware
  @client_chain ||= Middleware::Chain.new
  yield @client_chain if block_given?
  @client_chain
end

.configure_client {|_self| ... } ⇒ Object

Configuration for Sidekiq client, use like:

Sidekiq.configure_client do |config|
  config.redis = { :namespace => 'myapp', :size => 1, :url => 'redis://myhost:8877/0' }
end

Yields:

  • (_self)

Yield Parameters:

  • _self (Sidekiq)

    the object that the method was called on


85
86
87
# File 'lib/sidekiq.rb', line 85

def self.configure_client
  yield self unless server?
end

.configure_server {|_self| ... } ⇒ Object

Configuration for Sidekiq server, use like:

Sidekiq.configure_server do |config|
  config.redis = { :namespace => 'myapp', :size => 25, :url => 'redis://myhost:8877/0' }
  config.server_middleware do |chain|
    chain.add MyServerHook
  end
end

Yields:

  • (_self)

Yield Parameters:

  • _self (Sidekiq)

    the object that the method was called on


75
76
77
# File 'lib/sidekiq.rb', line 75

def self.configure_server
  yield self if server?
end

.death_handlersObject

Death handlers are called when all retries for a job have been exhausted and the job dies. It's the notification to your application that this job will not succeed without manual intervention.

Sidekiq.configure_server do |config|

config.death_handlers << ->(job, ex) do
end

end


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

def self.death_handlers
  options[:death_handlers]
end

.default_server_middlewareObject


153
154
155
# File 'lib/sidekiq.rb', line 153

def self.default_server_middleware
  Middleware::Chain.new
end

.default_worker_optionsObject


162
163
164
# File 'lib/sidekiq.rb', line 162

def self.default_worker_options
  defined?(@default_worker_options) ? @default_worker_options : DEFAULT_WORKER_OPTIONS
end

.default_worker_options=(hash) ⇒ Object


157
158
159
160
# File 'lib/sidekiq.rb', line 157

def self.default_worker_options=(hash)
  # stringify
  @default_worker_options = default_worker_options.merge(hash.transform_keys(&:to_s))
end

.dump_json(object) ⇒ Object


183
184
185
# File 'lib/sidekiq.rb', line 183

def self.dump_json(object)
  JSON.generate(object)
end

.error_handlersObject

Register a proc to handle any error which occurs within the Sidekiq process.

Sidekiq.configure_server do |config|
  config.error_handlers << proc {|ex,ctx_hash| MyErrorService.notify(ex, ctx_hash) }
end

The default error handler logs errors to Sidekiq.logger.


235
236
237
# File 'lib/sidekiq.rb', line 235

def self.error_handlers
  options[:error_handlers]
end

.load_json(string) ⇒ Object


179
180
181
# File 'lib/sidekiq.rb', line 179

def self.load_json(string)
  JSON.parse(string)
end

.log_formatterObject


187
188
189
190
191
192
193
# File 'lib/sidekiq.rb', line 187

def self.log_formatter
  @log_formatter ||= if ENV["DYNO"]
    Sidekiq::Logger::Formatters::WithoutTimestamp.new
  else
    Sidekiq::Logger::Formatters::Pretty.new
  end
end

.log_formatter=(log_formatter) ⇒ Object


195
196
197
198
# File 'lib/sidekiq.rb', line 195

def self.log_formatter=(log_formatter)
  @log_formatter = log_formatter
  logger.formatter = log_formatter
end

.loggerObject


200
201
202
# File 'lib/sidekiq.rb', line 200

def self.logger
  @logger ||= Sidekiq::Logger.new(STDOUT, level: Logger::INFO)
end

.logger=(logger) ⇒ Object


204
205
206
207
208
209
210
211
212
213
# File 'lib/sidekiq.rb', line 204

def self.logger=(logger)
  if logger.nil?
    self.logger.level = Logger::FATAL
    return self.logger
  end

  logger.extend(Sidekiq::LoggingUtils)

  @logger = logger
end

.on(event, &block) ⇒ Object

Register a block to run at a point in the Sidekiq lifecycle. :startup, :quiet or :shutdown are valid events.

Sidekiq.configure_server do |config|
  config.on(:shutdown) do
    puts "Goodbye cruel world!"
  end
end

Raises:

  • (ArgumentError)

247
248
249
250
251
# File 'lib/sidekiq.rb', line 247

def self.on(event, &block)
  raise ArgumentError, "Symbols only please: #{event}" unless event.is_a?(Symbol)
  raise ArgumentError, "Invalid event name: #{event}" unless options[:lifecycle_events].key?(event)
  options[:lifecycle_events][event] << block
end

.optionsObject


58
59
60
# File 'lib/sidekiq.rb', line 58

def self.options
  @options ||= DEFAULTS.dup
end

.options=(opts) ⇒ Object


62
63
64
# File 'lib/sidekiq.rb', line 62

def self.options=(opts)
  @options = opts
end

.pro?Boolean

Returns:

  • (Boolean)

215
216
217
# File 'lib/sidekiq.rb', line 215

def self.pro?
  defined?(Sidekiq::Pro)
end

.redisObject

Raises:

  • (ArgumentError)

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/sidekiq.rb', line 93

def self.redis
  raise ArgumentError, "requires a block" unless block_given?
  redis_pool.with do |conn|
    retryable = true
    begin
      yield conn
    rescue Redis::BaseError => ex
      # 2550 Failover can cause the server to become a replica, need
      # to disconnect and reopen the socket to get back to the primary.
      # 4495 Use the same logic if we have a "Not enough replicas" error from the primary
      if retryable && ex.message =~ /READONLY|NOREPLICAS/
        conn.disconnect!
        retryable = false
        retry
      end
      raise
    end
  end
end

.redis=(hash) ⇒ Object


133
134
135
136
137
138
139
# File 'lib/sidekiq.rb', line 133

def self.redis=(hash)
  @redis = if hash.is_a?(ConnectionPool)
    hash
  else
    Sidekiq::RedisConnection.create(hash)
  end
end

.redis_infoObject


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/sidekiq.rb', line 113

def self.redis_info
  redis do |conn|
    # admin commands can't go through redis-namespace starting
    # in redis-namespace 2.0
    if conn.respond_to?(:namespace)
      conn.redis.info
    else
      conn.info
    end
  rescue Redis::CommandError => ex
    # 2850 return fake version when INFO command has (probably) been renamed
    raise unless /unknown command/.match?(ex.message)
    FAKE_INFO
  end
end

.redis_poolObject


129
130
131
# File 'lib/sidekiq.rb', line 129

def self.redis_pool
  @redis ||= Sidekiq::RedisConnection.create
end

.server?Boolean

Returns:

  • (Boolean)

89
90
91
# File 'lib/sidekiq.rb', line 89

def self.server?
  defined?(Sidekiq::CLI)
end

.server_middleware {|@server_chain| ... } ⇒ Object

Yields:

  • (@server_chain)

147
148
149
150
151
# File 'lib/sidekiq.rb', line 147

def self.server_middleware
  @server_chain ||= default_server_middleware
  yield @server_chain if block_given?
  @server_chain
end

.start_watchdogObject


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/sidekiq/systemd.rb', line 8

def self.start_watchdog
  usec = Integer(ENV["WATCHDOG_USEC"])
  return Sidekiq.logger.error("systemd Watchdog too fast: " + usec) if usec < 1_000_000

  sec_f = usec / 1_000_000.0
  # "It is recommended that a daemon sends a keep-alive notification message
  # to the service manager every half of the time returned here."
  ping_f = sec_f / 2
  Sidekiq.logger.info "Pinging systemd watchdog every #{ping_f.round(1)} sec"
  Thread.new do
    loop do
      sleep ping_f
      Sidekiq::SdNotify.watchdog
    end
  end
end

.❨╯°□°❩╯︵┻━┻Object


54
55
56
# File 'lib/sidekiq.rb', line 54

def self.❨╯°□°❩╯︵┻━┻
  puts "Calm down, yo."
end