11# frozen_string_literal: true
22
33require 'ci/queue/static'
4+ require 'concurrent/atomic/event'
45require 'concurrent/set'
6+ require 'securerandom'
57
68module CI
79 module Queue
@@ -17,6 +19,8 @@ class << self
1719
1820 class Worker < Base
1921 DEFAULT_SLEEP_SECONDS = 0.5
22+ InitializationLeaseLost = Class . new ( StandardError )
23+ private_constant :InitializationLeaseLost
2024 attr_reader :total
2125
2226 def initialize ( redis , config )
@@ -37,18 +41,8 @@ def populate(tests, random: Random.new)
3741 # All workers need an index of tests to resolve IDs
3842 @index = tests . map { |t | [ t . id , t ] } . to_h
3943 @total = tests . size
40-
41- if acquire_master_role?
42- executables = reorder_tests ( tests , random : random )
43-
44- chunks = executables . select { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
45- individual_tests = executables . reject { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
46-
47- store_chunk_metadata ( chunks ) if chunks . any?
48-
49- all_ids = chunks . map ( &:id ) + individual_tests . map ( &:id )
50- push ( all_ids )
51- end
44+ @ordering_random = random . dup
45+ initialize_queue ( tests )
5246
5347 register_worker_presence
5448
@@ -76,7 +70,9 @@ def idle?
7670 end
7771
7872 def poll
79- wait_for_master
73+ wait_for_master ( timeout : config . queue_init_timeout ) do
74+ initialize_queue ( index . values )
75+ end
8076 if master?
8177 warn "Worker #{ worker_id } is the master"
8278 else
@@ -274,6 +270,66 @@ def heartbeat(test_or_id = nil)
274270
275271 attr_reader :index
276272
273+ def initialize_queue ( tests )
274+ return unless acquire_master_role?
275+
276+ stop_renewal = Concurrent ::Event . new
277+ renewal = Thread . new do
278+ until stop_renewal . wait ( master_lease_milliseconds / 3000.0 )
279+ begin
280+ with_master_lease do |transaction |
281+ transaction . pexpire ( key ( 'master-lease' ) , master_lease_milliseconds )
282+ end
283+ rescue InitializationLeaseLost
284+ break
285+ rescue *CONNECTION_ERRORS => e
286+ warn "Failed to renew queue initialization lease: #{ e . message } "
287+ end
288+ end
289+ end
290+
291+ executables = reorder_tests ( tests , random : @ordering_random . dup )
292+ chunks , individual_tests = executables . partition { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
293+ store_chunk_metadata ( chunks ) if chunks . any?
294+ push ( chunks . map ( &:id ) + individual_tests . map ( &:id ) )
295+ rescue InitializationLeaseLost
296+ # Another process took over. Join its queue instead of publishing ours.
297+ @master = false
298+ ensure
299+ if renewal
300+ stop_renewal . set
301+ renewal . join
302+ release_initialization_lease
303+ end
304+ end
305+
306+ def master_lease_milliseconds
307+ # Leave time for a surviving worker to take over within its setup wait.
308+ [ ( config . queue_init_timeout . to_f * 500 ) . ceil , 1 ] . max
309+ end
310+
311+ def with_master_lease
312+ redis . watch ( key ( 'master-lease' ) , key ( 'master-status' ) ) do
313+ unless redis . get ( key ( 'master-lease' ) ) == @master_token && master_status == 'setup'
314+ raise InitializationLeaseLost
315+ end
316+
317+ result = redis . multi { |transaction | yield transaction }
318+ raise InitializationLeaseLost unless result
319+
320+ result
321+ end
322+ end
323+
324+ def release_initialization_lease
325+ with_master_lease do |transaction |
326+ transaction . del ( key ( 'master-lease' ) , key ( 'master-status' ) , key ( 'master-worker-id' ) )
327+ end
328+ @master = false
329+ rescue InitializationLeaseLost , *CONNECTION_ERRORS
330+ # Published queues and replacement owners must remain untouched.
331+ end
332+
277333 # Runs a block while sending periodic heartbeats in a background thread.
278334 # This prevents other workers from stealing the test while it's being executed.
279335 def with_heartbeat ( test_id )
@@ -451,14 +507,15 @@ def push(tests)
451507 @total = tests . size
452508
453509 if @master
454- redis . multi do |transaction |
510+ with_master_lease do |transaction |
455511 transaction . lpush ( key ( 'queue' ) , tests ) unless tests . empty?
456512 transaction . set ( key ( 'total' ) , @total )
457513 transaction . set ( key ( 'master-status' ) , 'ready' )
458514
459515 transaction . expire ( key ( 'queue' ) , config . redis_ttl )
460516 transaction . expire ( key ( 'total' ) , config . redis_ttl )
461517 transaction . expire ( key ( 'master-status' ) , config . redis_ttl )
518+ transaction . del ( key ( 'master-lease' ) )
462519 end
463520 end
464521 rescue *CONNECTION_ERRORS
@@ -470,20 +527,21 @@ def register
470527 end
471528
472529 def acquire_master_role?
473- return true if @master
474-
475- @master = redis . setnx ( key ( 'master-status' ) , 'setup' )
476- if @master
477- begin
478- redis . set ( key ( 'master-worker-id' ) , worker_id )
479- redis . expire ( key ( 'master-worker-id' ) , config . redis_ttl )
480- warn "Worker #{ worker_id } elected as master"
481- rescue * CONNECTION_ERRORS
482- # If setting master-worker-id fails, we still have master status
483- # Log but don't lose master role
484- warn ( "Failed to set master-worker-id: #{ $! . message } " )
530+ @master_token = SecureRandom . hex ( 16 )
531+ @master = !! redis . watch ( key ( 'master-status' ) , key ( 'master-lease' ) ) do
532+ if %w[ ready finished ] . include? ( master_status ) || redis . get ( key ( 'master-lease' ) )
533+ redis . unwatch
534+ false
535+ else
536+ redis . multi do | transaction |
537+ transaction . set ( key ( 'master-lease' ) , @master_token , px : master_lease_milliseconds )
538+ transaction . set ( key ( 'master-status' ) , 'setup' )
539+ transaction . set ( key ( ' master-worker-id' ) , worker_id )
540+ transaction . expire ( key ( ' master-worker-id' ) , config . redis_ttl )
541+ end
485542 end
486543 end
544+ warn "Worker #{ worker_id } elected as master" if @master
487545 @master
488546 rescue *CONNECTION_ERRORS
489547 @master = nil
@@ -503,7 +561,7 @@ def store_chunk_metadata(chunks)
503561 batch_size = 5 # 5 chunks = 20 commands + 2 expires = 22 commands per batch
504562
505563 chunks . each_slice ( batch_size ) do |chunk_batch |
506- redis . multi do |transaction |
564+ with_master_lease do |transaction |
507565 chunk_batch . each do |chunk |
508566 # Store chunk metadata with TTL
509567 transaction . set (
0 commit comments