debian-mirror-gitlab/app/workers/concerns/limited_capacity/job_tracker.rb

69 lines
1.5 KiB
Ruby
Raw Normal View History

2021-01-03 14:25:43 +05:30
# frozen_string_literal: true
module LimitedCapacity
class JobTracker # rubocop:disable Scalability/IdempotentWorker
include Gitlab::Utils::StrongMemoize
2021-06-08 01:23:25 +05:30
LUA_REGISTER_SCRIPT = <<~EOS
local set_key, element, max_elements = KEYS[1], ARGV[1], ARGV[2]
if redis.call("scard", set_key) < tonumber(max_elements) then
redis.call("sadd", set_key, element)
return true
end
return false
EOS
2021-01-03 14:25:43 +05:30
def initialize(namespace)
@namespace = namespace
end
2021-06-08 01:23:25 +05:30
def register(jid, max_jids)
with_redis do |redis|
redis.eval(LUA_REGISTER_SCRIPT, keys: [counter_key], argv: [jid, max_jids])
end.present?
2021-01-03 14:25:43 +05:30
end
def remove(jid)
2021-06-08 01:23:25 +05:30
with_redis do |redis|
2021-01-03 14:25:43 +05:30
remove_job_keys(redis, jid)
end
end
def clean_up
completed_jids = Gitlab::SidekiqStatus.completed_jids(running_jids)
return unless completed_jids.any?
2021-06-08 01:23:25 +05:30
with_redis do |redis|
2021-01-03 14:25:43 +05:30
remove_job_keys(redis, completed_jids)
end
end
def count
2021-06-08 01:23:25 +05:30
with_redis { |redis| redis.scard(counter_key) }
2021-01-03 14:25:43 +05:30
end
def running_jids
with_redis do |redis|
redis.smembers(counter_key)
end
end
private
attr_reader :namespace
def counter_key
"worker:#{namespace.to_s.underscore}:running"
end
def remove_job_keys(redis, keys)
redis.srem(counter_key, keys)
end
def with_redis(&block)
Gitlab::Redis::Queues.with(&block) # rubocop: disable CodeReuse/ActiveRecord
end
end
end