aboutsummaryrefslogtreecommitdiffstats
path: root/activejob/test/support/integration/adapters/sidekiq.rb
blob: ceb7fb61f2e7ce0fc996617845e9306830f14a77 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# frozen_string_literal: true

require "sidekiq/api"

require "sidekiq/testing"
Sidekiq::Testing.disable!

Sidekiq.configure_server do |config|
  config.redis = { url: "redis://:password@127.0.0.1:6379/12" }
end

Sidekiq.configure_client do |config|
  config.redis = { url: "redis://:password@127.0.0.1:6379/12" }
end

module SidekiqJobsManager
  def setup
    ActiveJob::Base.queue_adapter = :sidekiq
    unless can_run?
      puts "Cannot run integration tests for sidekiq. To be able to run integration tests for sidekiq you need to install and start redis.\n"
      exit
    end
  end

  def clear_jobs
    Sidekiq::ScheduledSet.new.clear
    Sidekiq::Queue.new("integration_tests").clear
  end

  def start_workers
    continue_read, continue_write = IO.pipe
    death_read, death_write = IO.pipe

    @pid = fork do
      continue_read.close
      death_write.close

      # Sidekiq is not warning-clean :(
      $VERBOSE = false

      $stdin.reopen(File::NULL)
      $stdout.sync = true
      $stderr.sync = true

      logfile = Rails.root.join("log/sidekiq.log").to_s
      Sidekiq::Logging.initialize_logger(logfile)

      self_read, self_write = IO.pipe
      trap "TERM" do
        self_write.puts("TERM")
      end

      Thread.new do
        begin
          death_read.read
        rescue Exception
        end
        self_write.puts("TERM")
      end

      require "sidekiq/launcher"
      sidekiq = Sidekiq::Launcher.new(queues: ["integration_tests"],
                                       environment: "test",
                                       concurrency: 1,
                                       timeout: 1)
      Sidekiq.average_scheduled_poll_interval = 0.5
      Sidekiq.options[:poll_interval_average] = 1
      begin
        sidekiq.run
        continue_write.puts "started"
        while readable_io = IO.select([self_read])
          signal = readable_io.first[0].gets.strip
          raise Interrupt if signal == "TERM"
        end
      rescue Interrupt
      end

      sidekiq.stop
      exit!
    end
    continue_write.close
    death_read.close
    @worker_lifeline = death_write

    raise "Failed to start worker" unless continue_read.gets == "started\n"
  end

  def stop_workers
    if @pid
      Process.kill "TERM", @pid
      Process.wait @pid
    end
  end

  def can_run?
    begin
      Sidekiq.redis(&:info)
      Sidekiq.logger = nil
    rescue
      return false
    end
    true
  end
end