Class: SwitchmanInstJobs::JobsMigrator

Inherits:
Object
  • Object
show all
Defined in:
lib/switchman_inst_jobs/jobs_migrator.rb

Class Method Summary collapse

Class Method Details

.acquire_advisory_lock(type, name) ⇒ Object



100
101
102
103
104
105
106
107
108
109
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 100

def acquire_advisory_lock(type, name)
  @quoted_function_name ||= ::Delayed::Job.connection.quote_table_name("half_md5_as_bigint")

  value = (type == :singleton) ? "singleton:#{name}" : name
  ::Delayed::Job.connection.execute(
    ::Delayed::Job.sanitize_sql_for_conditions(
      ["SELECT pg_advisory_xact_lock(#{@quoted_function_name}(?))", value]
    )
  )
end

.add_before_move_callback(proc) ⇒ Object



9
10
11
12
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 9

def add_before_move_callback(proc)
  @before_move_callbacks ||= []
  @before_move_callbacks << proc
end

.add_validation_callback(proc) ⇒ Object



14
15
16
17
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 14

def add_validation_callback(proc)
  @validation_callbacks ||= []
  @validation_callbacks << proc
end

.blocked_by_migrator?(job_scope) ⇒ Boolean

Returns:

  • (Boolean)


281
282
283
284
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 281

def blocked_by_migrator?(job_scope)
  job_scope.exists?(source: "JobsMigrator::StrandBlocker") ||
    blocked_shards.exists?(id: job_scope.distinct.pluck(:shard_id))
end

.blocked_job_countObject



342
343
344
345
346
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 342

def blocked_job_count
  ::Delayed::Job.from(blocked_strands.select("count(id) AS ssize")).sum("ssize").to_i +
    ::Delayed::Job.from(blocked_singletons.select("count(id) AS ssize")).sum("ssize").to_i +
    ::Delayed::Job.where(strand: nil, singleton: nil, next_in_strand: false).count
end

.blocked_shardsObject



277
278
279
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 277

def blocked_shards
  ::Switchman::Shard.where(block_stranded: true).or(::Switchman::Shard.where(jobs_held: true))
end

.blocked_singletonsObject



315
316
317
318
319
320
321
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 315

def blocked_singletons
  ::Delayed::Job
    .where(strand: nil)
    .where.not(singleton: nil)
    .group(:singleton)
    .having("NOT BOOL_OR(next_in_strand)")
end

.blocked_strandsObject



286
287
288
289
290
291
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 286

def blocked_strands
  ::Delayed::Job
    .where.not(strand: nil)
    .group(:strand)
    .having("NOT BOOL_OR(next_in_strand)")
end

.clear_callbacks!Object



19
20
21
22
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 19

def clear_callbacks!
  @before_move_callbacks = []
  @validation_callbacks = []
end

.clear_shard_cache(debug_message = nil, default:) ⇒ Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 89

def clear_shard_cache(debug_message = nil, default:)
  ::Switchman.cache.delete_matched("shard/*")
  ::Switchman.cache.delete("default_shard") if default
  Rails.logger.debug { "Waiting for caches to clear #{debug_message}" }
  # Wait a little over the 60 second in-process shard cache clearing
  # threshold to ensure that all new stranded jobs are now being
  # enqueued with next_in_strand: false
  # @skip_cache_wait is for spec usage only
  sleep(65) unless @skip_cache_wait
end

.ensure_unblock_stranded_for(shards) ⇒ Object

if :migrate_strands ran on any shards that fell into scenario 1, then block_stranded never got flipped, so do that now.



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 76

def ensure_unblock_stranded_for(shards)
  shards = ::Switchman::Shard.where(id: shards, block_stranded: true).to_a
  return unless shards.any?

  ::Switchman::Shard.where(id: shards).update_all(block_stranded: false)
  clear_shard_cache(default: shards.any?(&:default?))

  # shards is an array of shard objects that is now stale cause block_stranded has been updated.
  shards.map(&:delayed_jobs_shard).uniq.each do |dj_shard|
    unblock_strands(dj_shard)
  end
end

.migrate_everything(batch_size: 1_000) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 262

def migrate_everything(batch_size: 1_000)
  source_shard = ::Switchman::Shard.current(::Delayed::Backend::ActiveRecord::AbstractJob)
  scope = ::Delayed::Job.shard(source_shard).where(strand: nil)

  shard_map = build_shard_map(scope, source_shard)
  shard_map.each do |(target_shard, source_shard_ids)|
    batch_move_jobs(
      target_shard: target_shard,
      source_shard: source_shard,
      scope: scope.where(shard_id: source_shard_ids).where(locked_by: nil),
      batch_size: batch_size
    )
  end
end

.migrate_shards(shard_map) ⇒ Object



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
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 38

def migrate_shards(shard_map)
  source_shards = Set[]
  target_shards = Hash.new([])
  shard_map.each do |(shard, target_shard)|
    shard = ::Switchman::Shard.find(shard) unless shard.is_a?(::Switchman::Shard)
    source_shards << shard.delayed_jobs_shard.id
    target_shard = target_shard.try(:id) || target_shard
    target_shards[target_shard] += [shard.id]

    @validation_callbacks&.each do |proc|
      proc.call(shard: shard, target_shard: ::Switchman::Shard.find(target_shard))
    end
  end

  # Do the updates in batches and then just clear redis instead of clearing them one at a time
  target_shards.each do |target_shard, shards|
    updates = { delayed_jobs_shard_id: target_shard, block_stranded: true }
    updates[:updated_at] = Time.zone.now if ::Switchman::Shard.column_names.include?("updated_at")
    ::Switchman::Shard.where(id: shards).update_all(updates)
  end
  clear_shard_cache(default: ::Switchman::Shard.exists?(id: target_shards.values.flatten, default: true))

  ::Switchman::Shard.clear_cache
  # rubocop:disable Style/CombinableLoops
  # We first migrate strands so that we can stop blocking strands before we migrate unstranded jobs
  source_shards.each do |s|
    ::Switchman::Shard.lookup(s).activate(::Delayed::Backend::ActiveRecord::AbstractJob) { migrate_strands }
  end

  source_shards.each do |s|
    ::Switchman::Shard.lookup(s).activate(::Delayed::Backend::ActiveRecord::AbstractJob) { migrate_everything }
  end
  ensure_unblock_stranded_for(shard_map.map(&:first))
  # rubocop:enable Style/CombinableLoops
end

.migrate_strands(batch_size: 1_000) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 120

def migrate_strands(batch_size: 1_000)
  source_shard = ::Switchman::Shard.current(::Delayed::Backend::ActiveRecord::AbstractJob)

  # there are 4 scenarios to deal with here
  # 1) no running job, no jobs moved: do nothing
  # 2) running job, no jobs moved; create blocker with next_in_strand=false
  #    to prevent new jobs from immediately executing
  # 3) running job, jobs moved; set next_in_strand=false on the first of
  #    those (= do nothing since it should already be false)
  # 4) no running job, jobs moved: set next_in_strand=true on the first of
  #    those (= do nothing since it should already be true)
  handler = lambda { |scope, column, blocker_job_kwargs = {}, advisory_lock_cb = nil|
    shard_map = build_shard_map(scope, source_shard)
    shard_map.each do |(target_shard, source_shard_ids)|
      shard_scope = scope.where(shard_id: source_shard_ids)

      # 1) is taken care of because it should not show up here in strands
      values = shard_scope.distinct.order(column).pluck(column)

      target_shard.activate(::Delayed::Backend::ActiveRecord::AbstractJob) do
        values.each do |value|
          transaction_on([source_shard, target_shard]) do
            source_shard.activate(::Delayed::Backend::ActiveRecord::AbstractJob) do
              advisory_lock_cb&.call(value)
            end

            value_scope = shard_scope.where(**{ column => value })
            # we want to copy all the jobs except the one that is still running.
            jobs_scope = value_scope.where(locked_by: nil)

            # 2) and part of 3) are taken care of here by creating a blocker
            # job with next_in_strand = false. as soon as the current
            # running job is finished it should set next_in_strand
            # We lock it to ensure that the jobs worker can't delete it until we are done moving the strand
            # Since we only unlock it on the new jobs queue *after* deleting from the original
            # the lock ensures the blocker always gets unlocked
            first = value_scope.where.not(locked_by: nil).next_in_strand_order.lock.first
            if first
              create_blocker_job(
                queue: first.queue,
                shard_id: first.shard_id,
                **{ column => value },
                **blocker_job_kwargs
              )

              # the rest of 3) is taken care of here
              # make sure that all the jobs moved over are NOT next in strand
              ::Delayed::Job.where(next_in_strand: true, locked_by: nil, **{ column => value })
                            .update_all(next_in_strand: false)
            end

            # 4) is taken care of here, by leaving next_in_strand alone and
            # it should execute on the new shard
            batch_move_jobs(
              target_shard: target_shard,
              source_shard: source_shard,
              scope: jobs_scope,
              batch_size: batch_size
            ) do |job, new_job|
              # This ensures jobs enqueued on the old jobs shard run before jobs on the new jobs queue
              new_job.strand_order_override = job.strand_order_override - 1
            end
          end
        end
      end
    end
  }

  strand_scope = ::Delayed::Job.shard(source_shard).where.not(strand: nil)
  singleton_scope = ::Delayed::Job.shard(source_shard).where("strand IS NULL AND singleton IS NOT NULL")
  all_scope = ::Delayed::Job.shard(source_shard).where("strand IS NOT NULL OR singleton IS NOT NULL")

  singleton_blocker_additional_kwargs = {
    locked_at: DateTime.now,
    locked_by: ::Delayed::Backend::Base::ON_HOLD_BLOCKER
  }

  strand_advisory_lock_fn = lambda do |value|
    acquire_advisory_lock(:strand, value)
  end

  singleton_advisory_lock_fn = lambda do |value|
    acquire_advisory_lock(:singleton, value)
  end

  handler.call(strand_scope, :strand, {}, strand_advisory_lock_fn)
  handler.call(singleton_scope, :singleton, singleton_blocker_additional_kwargs, singleton_advisory_lock_fn)

  shard_map = build_shard_map(all_scope, source_shard)
  shard_map.each do |(target_shard, source_shard_ids)|
    target_shard.activate(::Delayed::Backend::ActiveRecord::AbstractJob) do
      updated = ::Switchman::Shard.where(id: source_shard_ids, block_stranded: true)
                                  .update_all(block_stranded: false)
      # If this is being manually re-run for some reason to clean something up, don't wait for nothing to happen
      unless updated.zero?
        clear_shard_cache("(#{source_shard.id} -> #{target_shard.id})",
                          default: ::Switchman::Shard.exists?(id: source_shard_ids,
                                                              default: true))
      end

      ::Switchman::Shard.clear_cache
      # At this time, let's unblock all the strands on the target shard that aren't being held by a blocker
      # but actually could have run and we just didn't know it because we didn't know if they had jobs
      # on the source shard
      unblock_strands(target_shard)
    end
  end
end

.runObject

This method expects that all relevant shards already have block_stranded: true but otherwise jobs can be running normally



113
114
115
116
117
118
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 113

def run
  # Ensure this is never run with a dirty in-memory shard cache
  ::Switchman::Shard.clear_cache
  migrate_strands
  migrate_everything
end

.transaction_on(shards, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 24

def transaction_on(shards, &block)
  return yield if shards.empty?

  shard = shards.pop
  current_shard = ::Switchman::Shard.current(::Delayed::Backend::ActiveRecord::AbstractJob)
  shard.activate(::Delayed::Backend::ActiveRecord::AbstractJob) do
    ::Delayed::Job.transaction do
      current_shard.activate(::Delayed::Backend::ActiveRecord::AbstractJob) do
        transaction_on(shards, &block)
      end
    end
  end
end

.unblock_singleton!(singleton) ⇒ Object

Raises:



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 323

def unblock_singleton!(singleton)
  job_scope = ::Delayed::Job.where(strand: nil, singleton: singleton)
  raise JobsBlockedError if blocked_by_migrator?(job_scope)

  ::Delayed::Job.transaction do
    acquire_advisory_lock(:singleton, singleton)

    id, next_in_strand = job_scope
                         .group(:singleton)
                         .pick("MIN(id), BOOL_OR(next_in_strand)")

    if next_in_strand
      0
    elsif id
      ::Delayed::Job.where(id: id).update_all(next_in_strand: true)
    end
  end
end

.unblock_strand!(strand, new_parallelism: nil) ⇒ Object

Raises:



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 293

def unblock_strand!(strand, new_parallelism: nil)
  job_scope = ::Delayed::Job.where(strand: strand)
  raise JobsBlockedError if blocked_by_migrator?(job_scope)

  ::Delayed::Job.transaction do
    acquire_advisory_lock(:strand, strand)

    new_parallelism ||= job_scope.pick("MAX(max_concurrent)")
    if new_parallelism
      needed_jobs = new_parallelism - job_scope.where(next_in_strand: true).count
      if needed_jobs.positive?
        job_scope.where(next_in_strand: false,
                        locked_by: nil,
                        singleton: nil).order(:strand_order_override, :id)
                 .limit(needed_jobs).update_all(next_in_strand: true)
      else
        0
      end
    end
  end
end

.unblock_strands(target_shard, batch_size: 10_000) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 229

def unblock_strands(target_shard, batch_size: 10_000)
  blocked_shard_ids = blocked_shards.pluck(:id)
  query = lambda { |column, scope|
    ::Delayed::Job
      .where(id: ::Delayed::Job.select("DISTINCT ON (#{column}) id")
        .where(scope)
        .where.not(shard_id: blocked_shard_ids)
        .where(
          ::Delayed::Job.select(1).from("#{::Delayed::Job.quoted_table_name} dj2")
          .where("dj2.next_in_strand = true OR dj2.source = 'JobsMigrator::StrandBlocker'")
          .where("dj2.#{column} = delayed_jobs.#{column}").arel.exists.not
        )
        .order(column, :strand_order_override, :id)).limit(batch_size)
  }

  target_shard.activate(::Delayed::Backend::ActiveRecord::AbstractJob) do
    # We only want to unlock stranded jobs where they don't belong to a blocked shard (if they *do* belong)
    # to a blocked shard, they must be part of a concurrent jobs migration from a different source shard to
    # this target shard, so we shouldn't unlock them yet.  We only ever unlock one job here to keep the
    # logic cleaner; if the job is n-stranded, after the first one runs, the trigger will unlock larger
    # batches

    loop do
      break if query.call(:strand, "strand IS NOT NULL").update_all(next_in_strand: true).zero?
    end

    loop do
      break if query.call(:singleton,
                          "strand IS NULL AND singleton IS NOT NULL").update_all(next_in_strand: true).zero?
    end
  end
end