unicorn.rb 1.71 KB
Newer Older
1 2
# frozen_string_literal: true

3
require_relative "load_config"
4

5 6
port = ENV["PORT"]
port = port && !port.empty? ? port.to_i : nil
7

8
listen port || AppConfig.server.listen.get unless RACKUP[:set_listener]
9
pid AppConfig.server.pid.get
10
worker_processes AppConfig.server.unicorn_worker.to_i
11
timeout AppConfig.server.unicorn_timeout.to_i
12 13
stderr_path AppConfig.server.stderr_log.get if AppConfig.server.stderr_log?
stdout_path AppConfig.server.stdout_log.get if AppConfig.server.stdout_log?
14

15 16 17 18 19
preload_app true
@sidekiq_pid = nil

before_fork do |_server, _worker|
  ActiveRecord::Base.connection.disconnect! # preloading app in master, so reconnect to DB
danielgrippi's avatar
danielgrippi committed
20 21

  # disconnect redis if in use
22
  unless AppConfig.environment.single_process_mode?
Jonne Haß's avatar
Jonne Haß committed
23
    Sidekiq.redis {|redis| redis.client.disconnect }
danielgrippi's avatar
danielgrippi committed
24
  end
25

Jonne Haß's avatar
Jonne Haß committed
26
  if AppConfig.server.embed_sidekiq_worker?
27
    @sidekiq_pid ||= spawn("bin/bundle exec sidekiq")
28 29 30
  end
end

31
after_fork do |server, worker|
32 33
  Logging.reopen # reopen logfiles to obtain a new file descriptor

34
  ActiveRecord::Base.establish_connection # preloading app in master, so reconnect to DB
35 36 37

  # We don't generate uuids in the frontend, but let's be on the safe side
  UUID.generator.next_sequence
38 39 40 41 42 43 44 45 46 47 48 49 50 51

  # Check for an old master process from a graceful restart
  old_pid = "#{AppConfig.server.pid.get}.oldbin"

  if File.exist?(old_pid) && server.pid != old_pid
    begin
      # Remove a worker from the old master when we fork a new one (TTOU)
      # Except for the last worker forked by this server, which kills the old master (QUIT)
      signal = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(signal, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      # someone else did our job for us
    end
  end
52
end