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



118
119
120
121
122
123
124
125
126
127
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 118

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



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

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

.add_validation_callback(proc) ⇒ Object



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

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

.blocked_by_migrator?(job_scope) ⇒ Boolean

Returns:

  • (Boolean)


302
303
304
305
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 302

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



363
364
365
366
367
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 363

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



298
299
300
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 298

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

.blocked_singletonsObject



336
337
338
339
340
341
342
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 336

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

.blocked_strandsObject



307
308
309
310
311
312
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 307

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

.clear_callbacks!Object



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

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

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



107
108
109
110
111
112
113
114
115
116
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 107

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.



94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 94

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



283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 283

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:,
      source_shard:,
      scope: scope.where(shard_id: source_shard_ids).where(locked_by: nil),
      batch_size:
    )
  end
end

.migrate_shards(shard_map) ⇒ Object



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

def migrate_shards(shard_map)
  effective_map = shard_map.dup
  source_shards = Hash.new([].freeze)
  target_shards = Hash.new([].freeze)
  # Also add any incomplete moves to the source shards to ensure we clean up appropriately
  ::Switchman::Shard.where.not(migrate_from_delayed_jobs_shard_id: nil).find_each do |shard|
    effective_map[shard.id] ||= shard.delayed_jobs_shard.id
  end
  effective_map.each do |(shard, target_shard)|
    shard = ::Switchman::Shard.find(shard) unless shard.is_a?(::Switchman::Shard)
    target_shard = target_shard.try(:id) || target_shard
    # if a move was interrupted, the new shard is already set as the delayed_jobs_shard
    # but we still have the old shard stored in migrate_from_delayed_jobs_shard and should
    # act as if we are moving from there in the first place
    if shard.migrate_from_delayed_jobs_shard_id && shard.delayed_jobs_shard.id == target_shard
      source_shards[shard.migrate_from_delayed_jobs_shard_id] += [shard.id]
    else
      source_shards[shard.delayed_jobs_shard.id] += [shard.id]
    end
    target_shards[target_shard] += [shard.id]

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

  ::Switchman::Shard.transaction do
    # Do the updates in batches and then just clear redis instead of clearing them one at a time
    source_shards.each do |source_shard, shards|
      updates = { migrate_from_delayed_jobs_shard_id: source_shard }
      ::Switchman::Shard.where(id: shards).update_all(updates)
    end
    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
  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_key do |s|
    ::Switchman::Shard.lookup(s).activate(::Delayed::Backend::ActiveRecord::AbstractJob) { migrate_strands }
  end

  source_shards.each_key do |s|
    ::Switchman::Shard.lookup(s).activate(::Delayed::Backend::ActiveRecord::AbstractJob) { migrate_everything }
  end
  ensure_unblock_stranded_for(effective_map.map(&:first))
  # rubocop:enable Style/CombinableLoops
  ::Switchman::Shard.where(id: effective_map.map(&:first)).update_all(migrate_from_delayed_jobs_shard_id: nil)
end

.migrate_strands(batch_size: 1_000) ⇒ Object



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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 138

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:,
              source_shard:,
              scope: jobs_scope,
              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: Time.now.utc,
    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



131
132
133
134
135
136
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 131

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) ⇒ Object



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

def transaction_on(shards, &)
  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, &)
      end
    end
  end
end

.unblock_singleton!(singleton) ⇒ Object

Raises:



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 344

def unblock_singleton!(singleton)
  job_scope = ::Delayed::Job.where(strand: nil, 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:).update_all(next_in_strand: true)
    end
  end
end

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

Raises:



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 314

def unblock_strand!(strand, new_parallelism: nil)
  job_scope = ::Delayed::Job.where(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



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/switchman_inst_jobs/jobs_migrator.rb', line 247

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
        .with(all_col: ::Delayed::Job.and(scope).distinct.select(column))
        .with(blocked_col: ::Delayed::Job.from("all_col").select(column).where.not(
          ::Delayed::Job.select(1)
            .where(next_in_strand: true).or(::Delayed::Job.where(source: "JobsMigrator::StrandBlocker"))
            .where("#{column} = all_col.#{column}").arel.exists
        ))
        .select("DISTINCT ON (#{column}) id")
        .where.not(shard_id: blocked_shard_ids)
        .where({ column => ::Delayed::Job.from("blocked_col").select(column) })
        .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, ::Delayed::Job.where.not(strand: nil)).update_all(next_in_strand: true).zero?
    end

    loop do
      break if query.call(:singleton,
                          ::Delayed::Job.where(strand: nil)
                          .where.not(singleton: nil)).update_all(next_in_strand: true).zero?
    end
  end
end