22
33require 'ci/queue/static'
44require 'concurrent/set'
5+ require 'securerandom'
56
67module CI
78 module Queue
@@ -38,19 +39,41 @@ def populate(tests, random: Random.new)
3839 @index = tests . map { |t | [ t . id , t ] } . to_h
3940 @total = tests . size
4041
41- if acquire_master_role?
42- executables = reorder_tests ( tests , random : random )
42+ election_attempts = 0
4343
44- chunks = executables . select { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
45- individual_tests = executables . reject { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
44+ loop do
45+ begin
46+ if acquire_master_role?
47+ all_ids = with_master_lock_renewal do
48+ executables = reorder_tests ( tests , random : random )
4649
47- store_chunk_metadata ( chunks ) if chunks . any?
50+ chunks = executables . select { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
51+ individual_tests = executables . reject { |e | e . is_a? ( CI ::Queue ::TestChunk ) }
4852
49- all_ids = chunks . map ( &:id ) + individual_tests . map ( &:id )
50- push ( all_ids )
51- end
53+ store_chunk_metadata ( chunks ) if chunks . any?
54+
55+ chunks . map ( &:id ) + individual_tests . map ( &:id )
56+ end
57+ push ( all_ids )
58+ else
59+ wait_for_master ( timeout : config . queue_init_timeout , fail_if_unclaimed : true )
60+ end
61+
62+ register_worker_presence
63+ break
64+ rescue MasterDied => error
65+ election_attempts += 1
66+ if election_attempts >= config . max_election_attempts
67+ raise LostMaster ,
68+ "Failed to recover queue setup after #{ election_attempts } election attempts: #{ error . message } "
69+ end
5270
53- register_worker_presence
71+ warn 'Master worker died during setup; retrying election ' \
72+ "(#{ election_attempts } /#{ config . max_election_attempts } )."
73+ @master = nil
74+ @generation = nil
75+ end
76+ end
5477
5578 self
5679 end
@@ -441,15 +464,23 @@ def push(tests)
441464 @total = tests . size
442465
443466 if @master
444- redis . multi do |transaction |
445- transaction . lpush ( key ( 'queue' ) , tests ) unless tests . empty?
446- transaction . set ( key ( 'total' ) , @total )
447- transaction . set ( key ( 'master-status' ) , 'ready' )
448-
449- transaction . expire ( key ( 'queue' ) , config . redis_ttl )
450- transaction . expire ( key ( 'total' ) , config . redis_ttl )
451- transaction . expire ( key ( 'master-status' ) , config . redis_ttl )
452- end
467+ result = eval_script (
468+ :push_queue ,
469+ keys : [
470+ key ( 'master-status' ) ,
471+ key ( 'queue' ) ,
472+ key ( 'total' ) ,
473+ key ( 'current-generation' )
474+ ] ,
475+ argv : [
476+ master_lock_value ,
477+ @generation ,
478+ @total ,
479+ config . redis_ttl ,
480+ *tests
481+ ]
482+ )
483+ raise MasterDied , 'The master lease was lost before the queue could be published.' unless result == 1
453484 end
454485 rescue *CONNECTION_ERRORS
455486 raise if @master
@@ -462,24 +493,89 @@ def register
462493 def acquire_master_role?
463494 return true if @master
464495
465- @master = redis . setnx ( key ( 'master-status' ) , 'setup' )
496+ @generation = SecureRandom . uuid
497+ @master = redis . set (
498+ key ( 'master-status' ) ,
499+ master_lock_value ,
500+ nx : true ,
501+ ex : config . master_lock_ttl
502+ )
466503 if @master
467504 begin
468- redis . set ( key ( 'master-worker-id' ) , worker_id )
469- redis . expire ( key ( 'master-worker-id' ) , config . redis_ttl )
470- warn "Worker #{ worker_id } elected as master"
505+ redis . multi do |transaction |
506+ transaction . set ( key ( 'master-worker-id' ) , worker_id )
507+ transaction . expire ( key ( 'master-worker-id' ) , config . redis_ttl )
508+ end
509+ warn "Worker #{ worker_id } elected as master (generation #{ @generation } )"
471510 rescue *CONNECTION_ERRORS
472511 # If setting master-worker-id fails, we still have master status
473512 # Log but don't lose master role
474513 warn ( "Failed to set master-worker-id: #{ $!. message } " )
475514 end
515+ else
516+ @generation = nil
476517 end
477518 @master
478519 rescue *CONNECTION_ERRORS
479520 @master = nil
521+ @generation = nil
480522 false
481523 end
482524
525+ def master_lock_value
526+ "setup:#{ @generation } "
527+ end
528+
529+ def renew_master_lock!
530+ result = eval_script (
531+ :renew_master_lock ,
532+ keys : [ key ( 'master-status' ) ] ,
533+ argv : [ master_lock_value , config . master_lock_ttl ]
534+ )
535+ raise MasterDied , 'The master lease expired while the queue was being populated.' unless result == 1
536+ end
537+
538+ def with_master_lock_renewal
539+ renewal_interval = [ config . master_lock_ttl / 3.0 , 0.1 ] . max
540+ lock_lost = false
541+ stop_renewal = false
542+ script = read_script ( :renew_master_lock )
543+ status_key = key ( 'master-status' )
544+ expected_lock = master_lock_value
545+
546+ renewal_thread = Thread . new do
547+ renewal_redis = ::Redis . new ( url : redis_url )
548+ until stop_renewal
549+ sleep renewal_interval
550+ break if stop_renewal
551+
552+ result = renewal_redis . eval (
553+ script ,
554+ keys : [ status_key ] ,
555+ argv : [ expected_lock , config . master_lock_ttl ]
556+ )
557+ unless result == 1
558+ lock_lost = true
559+ break
560+ end
561+ end
562+ rescue *CONNECTION_ERRORS => error
563+ warn "Failed to renew the master lease: #{ error . message } "
564+ ensure
565+ renewal_redis &.close
566+ end
567+
568+ result = yield
569+ raise MasterDied , 'The master lease expired while the queue was being populated.' if lock_lost
570+
571+ renew_master_lock!
572+ result
573+ ensure
574+ stop_renewal = true
575+ renewal_thread &.kill
576+ renewal_thread &.join
577+ end
578+
483579 def register_worker_presence
484580 register
485581 redis . expire ( key ( 'workers' ) , config . redis_ttl )
@@ -493,31 +589,29 @@ def store_chunk_metadata(chunks)
493589 batch_size = 5 # 5 chunks = 20 commands + 2 expires = 22 commands per batch
494590
495591 chunks . each_slice ( batch_size ) do |chunk_batch |
496- redis . multi do |transaction |
497- chunk_batch . each do |chunk |
498- # Store chunk metadata with TTL
499- transaction . set (
500- key ( 'chunk' , chunk . id ) ,
501- chunk . to_json
502- )
503- transaction . expire ( key ( 'chunk' , chunk . id ) , config . redis_ttl )
504-
505- # Track all chunks for cleanup
506- transaction . sadd ( key ( 'chunks' ) , chunk . id )
507-
508- # Store dynamic timeout for this chunk
509- # Timeout = estimated_duration (in ms) converted to seconds + buffer
510- # estimated_duration is in milliseconds, convert to seconds and add 10% buffer
511- buffer_percent = 10
512- estimated_duration_seconds = chunk . estimated_duration / 1000.0
513- chunk_timeout = ( estimated_duration_seconds * ( 1 + buffer_percent / 100.0 ) ) . round ( 2 )
514- # Format to string to avoid floating point precision issues in Redis
515- # Use %g to remove trailing zeros
516- transaction . hset ( key ( 'test-group-timeout' ) , chunk . id , format ( '%g' , chunk_timeout ) )
517- end
518- transaction . expire ( key ( 'chunks' ) , config . redis_ttl )
519- transaction . expire ( key ( 'test-group-timeout' ) , config . redis_ttl )
592+ chunk_keys = chunk_batch . map { |chunk | key ( 'chunk' , chunk . id ) }
593+ chunk_data = chunk_batch . flat_map do |chunk |
594+ # Timeout = estimated duration in seconds plus a 10% buffer.
595+ chunk_timeout = ( chunk . estimated_duration / 1000.0 * 1.1 ) . round ( 2 )
596+ [ chunk . id , chunk . to_json , format ( '%g' , chunk_timeout ) ]
520597 end
598+
599+ result = eval_script (
600+ :store_chunk_metadata ,
601+ keys : [
602+ key ( 'master-status' ) ,
603+ key ( 'chunks' ) ,
604+ key ( 'test-group-timeout' ) ,
605+ *chunk_keys
606+ ] ,
607+ argv : [
608+ master_lock_value ,
609+ config . master_lock_ttl ,
610+ config . redis_ttl ,
611+ *chunk_data
612+ ]
613+ )
614+ raise MasterDied , 'The master lease was lost while storing chunk metadata.' unless result == 1
521615 end
522616 end
523617
0 commit comments