Class: Switchman::Shard

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/switchman/shard_internal.rb

Constant Summary collapse

IDS_PER_SHARD =

ten trillion possible ids per shard. yup.

10_000_000_000_000
NIL_NIL_ID =

takes an id-ish, and returns a local id and the shard it’s local to. [nil, nil] if it can’t be interpreted. [id, nil] if it’s already a local ID

[nil, nil].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

._load(str) ⇒ Object



570
571
572
# File 'app/models/switchman/shard_internal.rb', line 570

def self._load(str)
  lookup(str.to_i)
end

.activate(shards) ⇒ Object



77
78
79
80
81
82
# File 'app/models/switchman/shard_internal.rb', line 77

def activate(shards)
  old_shards = activate!(shards)
  yield
ensure
  active_shards.merge!(old_shards) if old_shards
end

.activate!(shards) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'app/models/switchman/shard_internal.rb', line 84

def activate!(shards)
  old_shards = nil
  currently_active_shards = active_shards
  shards.each do |category, shard|
    next if category == :unsharded
    unless currently_active_shards[category] == shard
      old_shards ||= {}
      old_shards[category] = currently_active_shards[category]
      currently_active_shards[category] = shard
    end
  end
  old_shards
end

.categoriesObject



32
33
34
# File 'app/models/switchman/shard_internal.rb', line 32

def categories
  CATEGORIES.keys
end

.clear_cacheObject



141
142
143
# File 'app/models/switchman/shard_internal.rb', line 141

def clear_cache
  cached_shards.clear
end

.current(category = :default) ⇒ Object



73
74
75
# File 'app/models/switchman/shard_internal.rb', line 73

def current(category = :default)
  active_shards[category] || Shard.default
end

.default(reload_deprecated = false, reload: false, with_fallback: false) ⇒ Object



36
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
# File 'app/models/switchman/shard_internal.rb', line 36

def default(reload_deprecated = false, reload: false, with_fallback: false)
  reload = reload_deprecated if reload_deprecated
  if !@default || reload
    # Have to create a dummy object so that several key methods still work
    # (it's easier to do this in one place here, and just assume that sharding
    # is up and running everywhere else).  This includes for looking up the
    # default shard itself. This also needs to be a local so that this method
    # can be re-entrant
    default = DefaultShard.instance

    # if we already have a default shard in place, and the caller wants
    # to use it as a fallback, use that instead of the dummy instance
    if with_fallback && @default
      default = @default
    end

    # the first time we need a dummy dummy for re-entrancy to avoid looping on ourselves
    @default ||= default

    # Now find the actual record, if it exists; rescue the fake default if the table doesn't exist
    @default = begin
      Shard.where(default: true).first || default
    rescue
      default
    end

    # rebuild current shard activations - it might have "another" default shard serialized there
    active_shards.replace(active_shards.map do |category, shard|
      shard = Shard.lookup((!shard || shard.default?) ? 'default' : shard.id)
      [category, shard]
    end.to_h)

    activate!(default: @default) if active_shards.empty?
  end
  @default
end

.determine_max_procs(max_procs_input, parallel_input = 2) ⇒ Object

given the provided option, determines whether we need to (and whether it’s possible) to determine a reasonable default.



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'app/models/switchman/shard_internal.rb', line 480

def determine_max_procs(max_procs_input, parallel_input=2)
  max_procs = nil
  if max_procs_input
    max_procs = max_procs_input.to_i
    max_procs = nil if max_procs == 0
  else
    return 1 if parallel_input.nil? || parallel_input < 1
    cpus = Environment.cpu_count
    if cpus && cpus > 0
      max_procs = cpus * parallel_input
    end
  end

  return max_procs
end

.global_id_for(any_id, source_shard = nil) ⇒ Object

takes an id-ish, and returns an integral global id. returns nil if it can’t be interpreted



461
462
463
464
465
466
467
468
469
470
# File 'app/models/switchman/shard_internal.rb', line 461

def global_id_for(any_id, source_shard = nil)
  id = integral_id_for(any_id)
  return any_id unless id
  if id >= IDS_PER_SHARD
    id
  else
    source_shard ||= Shard.current
    source_shard.global_id_for(id)
  end
end

.integral_id_for(any_id) ⇒ Object

converts an AR object, integral id, string id, or string short-global-id to a integral id. nil if it can’t be interpreted



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'app/models/switchman/shard_internal.rb', line 403

def integral_id_for(any_id)
  if ::Rails.version >= '4.2' && any_id.is_a?(::Arel::Nodes::Casted)
    any_id = any_id.val
  end

  case any_id
  when ::ActiveRecord::Base
    any_id.id
  when /^(\d+)~(\d+)$/
    local_id = $2.to_i
    # doesn't make sense to have a double-global id
    return nil if local_id > IDS_PER_SHARD
    $1.to_i * IDS_PER_SHARD + local_id
  when Integer, /^\d+$/
    any_id.to_i
  else
    nil
  end
end

.local_id_for(any_id) ⇒ Object



427
428
429
430
431
432
433
434
435
436
437
# File 'app/models/switchman/shard_internal.rb', line 427

def local_id_for(any_id)
  id = integral_id_for(any_id)
  return NIL_NIL_ID unless id
  if id < IDS_PER_SHARD
    [id, nil]
  elsif shard = lookup(id / IDS_PER_SHARD)
    [id % IDS_PER_SHARD, shard]
  else
    NIL_NIL_ID
  end
end

.lookup(id) ⇒ Object

Raises:

  • (ArgumentError)


98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'app/models/switchman/shard_internal.rb', line 98

def lookup(id)
  id_i = id.to_i
  return current if id_i == current.id || id == 'self'
  return default if id_i == default.id || id.nil? || id == 'default'
  id = id_i
  raise ArgumentError if id == 0

  unless cached_shards.has_key?(id)
    cached_shards[id] = Shard.default.activate do
      # can't simply cache the AR object since Shard has a custom serializer
      # that calls this method
      attributes = Switchman.cache.fetch(['shard', id].join('/')) do
        shard = find_by_id(id)
        if shard
          attributes = shard.attributes
          if ::Rails.version < '4.2'
            attributes.each_key do |key|
              attributes[key] = attributes[key].unserialize if attributes[key].is_a?(::ActiveRecord::AttributeMethods::Serialization::Attribute)
            end
          end
          attributes
        else
          :nil
        end
      end
      if attributes == :nil
        nil
      else
        shard = Shard.new
        attributes.each do |attr, value|
          shard.send(:"#{attr}=", value)
        end
        shard.instance_variable_set(:@new_record, false)
        # connection info doesn't exist in database.yml;
        # pretend the shard doesn't exist either
        shard = nil unless shard.database_server
        shard
      end
    end
  end
  cached_shards[id]
end

.partition_by_shard(array, partition_proc = nil) ⇒ Object



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'app/models/switchman/shard_internal.rb', line 368

def partition_by_shard(array, partition_proc = nil)
  shard_arrays = {}
  array.each do |object|
    partition_object = partition_proc ? partition_proc.call(object) : object
    case partition_object
      when Shard
        shard = partition_object
      when ::ActiveRecord::Base
        if partition_object.respond_to?(:associated_shards)
          partition_object.associated_shards.each do |a_shard|
            shard_arrays[a_shard] ||= []
            shard_arrays[a_shard] << object
          end
          next
        else
          shard = partition_object.shard
        end
      when Integer, /^\d+$/, /^(\d+)~(\d+)$/
        local_id, shard = Shard.local_id_for(partition_object)
        local_id ||= partition_object
        object = local_id if !partition_proc
    end
    shard ||= Shard.current
    shard_arrays[shard] ||= []
    shard_arrays[shard] << object
  end
  # TODO: use with_each_shard (or vice versa) to get
  # connection management and parallelism benefits
  shard_arrays.inject([]) do |results, (shard, objects)|
    results.concat shard.activate { Array.wrap(yield objects) }
  end
end

.relative_id_for(any_id, source_shard, target_shard) ⇒ Object

takes an id-ish, and returns an integral id relative to target_shard. returns any_id itself if it can’t be interpreted



441
442
443
444
445
446
447
# File 'app/models/switchman/shard_internal.rb', line 441

def relative_id_for(any_id, source_shard, target_shard)
  local_id, shard = local_id_for(any_id)
  return any_id unless local_id
  shard ||= source_shard
  return local_id if shard == target_shard
  shard.global_id_for(local_id)
end

.shard_for(any_id, source_shard = nil) ⇒ Object



472
473
474
475
476
# File 'app/models/switchman/shard_internal.rb', line 472

def shard_for(any_id, source_shard = nil)
  return any_id.shard if any_id.is_a?(::ActiveRecord::Base)
  _, shard = local_id_for(any_id)
  shard || source_shard || Shard.current
end

.short_id_for(any_id) ⇒ Object

takes an id-ish, and returns a shortened global string id if global, and itself if local. returns any_id itself if it can’t be interpreted



452
453
454
455
456
457
# File 'app/models/switchman/shard_internal.rb', line 452

def short_id_for(any_id)
  local_id, shard = local_id_for(any_id)
  return any_id unless local_id
  return local_id unless shard
  "#{shard.id}~#{local_id}"
end

.with_each_shard(*args) ⇒ Object

Parameters

  • shards - an array or relation of Shards to iterate over

  • categories - an array of categories to activate

  • options -

    :parallel - true/false to execute in parallel, or a integer of how many
                sub-processes per database server. Note that parallel
                invocation currently uses forking, so should be used sparingly
                because errors are not raised, and you cannot get results back
    :exception - :ignore, :raise, :defer (wait until the end and raise the first
                error), or a proc
    

Raises:

  • (ArgumentError)


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
246
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'app/models/switchman/shard_internal.rb', line 156

def with_each_shard(*args)
  raise ArgumentError, "wrong number of arguments (#{args.length} for 0...3)" if args.length > 3

  unless default.is_a?(Shard)
    return Array.wrap(yield)
  end

  options = args.extract_options!
  if args.length == 1
    if Array === args.first && args.first.first.is_a?(Symbol)
      categories = args.first
    else
      scope = args.first
    end
  else
    scope, categories = args
  end

  parallel = case options[:parallel]
               when true
                 1
               when false, nil
                 0
               else
                 options[:parallel]
             end
  options.delete(:parallel)

  scope ||= Shard.all
  if ::ActiveRecord::Relation === scope && scope.order_values.empty?
    scope = scope.order("database_server_id IS NOT NULL, database_server_id, id")
  end

  if parallel > 0
    max_procs = determine_max_procs(options.delete(:max_procs), parallel)
    if ::ActiveRecord::Relation === scope
      # still need a post-uniq, cause the default database server could be NULL or Rails.env in the db
      database_servers = scope.reorder('database_server_id').select(:database_server_id).uniq.
          map(&:database_server).compact.uniq
      parallel = [(max_procs.to_f / database_servers.count).ceil, parallel].min if max_procs

      scopes = Hash[database_servers.map do |server|
        server_scope = server.shards.merge(scope)
        if parallel == 1
          subscopes = [server_scope]
        else
          subscopes = []
          total = server_scope.count
          ranges = []
          server_scope.find_ids_in_ranges(:batch_size => (total.to_f / parallel).ceil) do |min, max|
            ranges << [min, max]
          end
          # create a half-open range on the last one
          ranges.last[1] = nil
          ranges.each do |min, max|
            subscope = server_scope.where("id>=?", min)
            subscope = subscope.where("id<=?", max) if max
            subscopes << subscope
          end
        end
        [server, subscopes]
      end]
    else
      scopes = scope.group_by(&:database_server)
      if parallel > 1
        parallel = [(max_procs.to_f / scopes.count).ceil, parallel].min if max_procs
        scopes = Hash[scopes.map do |(server, shards)|
          [server, shards.in_groups(parallel, false).compact]
        end]
      end
    end

    fd_to_name_map = {}
    out_fds = []
    err_fds = []
    pids = []

    wait_for_output = lambda do |out_fds, err_fds, fd_to_name_map|
      ready, _ = IO.select(out_fds + err_fds)
      ready.each do |fd|
        if fd.eof?
          fd.close
          out_fds.delete(fd)
          err_fds.delete(fd)
          next
        end
        line = fd.readline
        puts "#{fd_to_name_map[fd]}: #{line}"
      end
    end

    exception_pipe = IO.pipe
    scopes.each do |server, subscopes|
      if !(::ActiveRecord::Relation === subscopes.first) && subscopes.first.class != Array
        subscopes = [subscopes]
      end
      # only one process; don't bother forking
      if scopes.length == 1 && subscopes.length == 1
        exception_pipe.first.close
        exception_pipe.last.close
        return with_each_shard(subscopes.first, categories, options) { yield }
      end

      subscopes.each_with_index do |subscope, idx|
        if subscopes.length > 1
          name = "#{server.id} #{idx + 1}"
        else
          name = server.id
        end

        details = Open4.pfork4(lambda do
          begin
            ::ActiveRecord::Base.clear_all_connections!
            Switchman.config[:on_fork_proc].try(:call)
            $0 = [$0, ARGV, name].flatten.join(' ')
            with_each_shard(subscope, categories, options) { yield }
          rescue Exception => e
            exception_pipe.last.write(Marshal.dump(e))
            exception_pipe.last.flush
            exit 1
          end
        end)
        # don't care about writing to stdin
        details[1].close
        out_fds << details[2]
        err_fds << details[3]
        pids << details[0]
        fd_to_name_map[details[2]] = name
        fd_to_name_map[details[3]] = name

        while max_procs && pids.count >= max_procs
          while max_procs && out_fds.count >= max_procs
            # wait for output if we've hit the max_procs limit
            wait_for_output.call(out_fds, err_fds, fd_to_name_map)
          end
          pids.delete(Process.wait) # we've gotten all the output from one fd so wait for its child process to exit
        end
      end
    end

    exception_pipe.last.close

    while out_fds.any? || err_fds.any?
      wait_for_output.call(out_fds, err_fds, fd_to_name_map)
    end
    pids.each { |pid| Process.waitpid2(pid) }

    # I'm not sure why, but we have to do this
    ::ActiveRecord::Base.clear_all_connections!
    # check for an exception; we only re-raise the first one
    # (all the sub-processes shared the same pipe, so we only
    # have to check the one)
    begin
      exception = Marshal.load exception_pipe.first
      raise exception
    rescue EOFError
      # No exceptions
    ensure
      exception_pipe.first.close
    end
    return
  end

  categories ||= []

  previous_shard = nil
  close_connections_if_needed = lambda do |shard|
    # prune the prior connection unless it happened to be the same
    if previous_shard && shard != previous_shard &&
      (shard.database_server != previous_shard.database_server || !previous_shard.database_server.shareable?)
      previous_shard.activate do
        ::Shackles.activated_environments.each do |env|
          ::Shackles.activate(env) do
            if ::ActiveRecord::Base.connected? && ::ActiveRecord::Base.connection.open_transactions == 0
              ::ActiveRecord::Base.connection_pool.current_pool.disconnect!
            end
          end
        end
      end
    end
  end

  result = []
  exception = nil
  scope.each do |shard|
    # shard references a database server that isn't configured in this environment
    next unless shard.database_server
    close_connections_if_needed.call(shard)
    shard.activate(*categories) do
      begin
        result.concat Array.wrap(yield)
      rescue
        case options[:exception]
        when :ignore
        when :defer
          exception ||= $!
        when Proc
          options[:exception].call
        when :raise
          raise
        else
          raise
        end
      end
    end
    previous_shard = shard
  end
  close_connections_if_needed.call(Shard.current)
  raise exception if exception
  result
end

Instance Method Details

#_dump(depth) ⇒ Object

custom serialization, since shard is self-referential



566
567
568
# File 'app/models/switchman/shard_internal.rb', line 566

def _dump(depth)
  self.id.to_s
end

#activate(*categories) ⇒ Object



551
552
553
554
555
556
# File 'app/models/switchman/shard_internal.rb', line 551

def activate(*categories)
  shards = hashify_categories(categories)
  Shard.activate(shards) do
    yield
  end
end

#activate!(*categories) ⇒ Object

for use from console ONLY



559
560
561
562
563
# File 'app/models/switchman/shard_internal.rb', line 559

def activate!(*categories)
  shards = hashify_categories(categories)
  Shard.activate!(shards)
  nil
end

#database_serverObject



529
530
531
# File 'app/models/switchman/shard_internal.rb', line 529

def database_server
  @database_server ||= DatabaseServer.find(self.database_server_id)
end

#database_server=(database_server) ⇒ Object



533
534
535
536
# File 'app/models/switchman/shard_internal.rb', line 533

def database_server=(database_server)
  self.database_server_id = database_server.id
  @database_server = database_server
end

#descriptionObject



542
543
544
# File 'app/models/switchman/shard_internal.rb', line 542

def description
  [database_server.id, name].compact.join(':')
end

#destroyObject



633
634
635
636
# File 'app/models/switchman/shard_internal.rb', line 633

def destroy
  raise("Cannot destroy the default shard") if self.default?
  super
end

#drop_databaseObject



574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'app/models/switchman/shard_internal.rb', line 574

def drop_database
  raise("Cannot drop the database of the default shard") if self.default?
  return unless read_attribute(:name)

  begin
    adapter = self.database_server.config[:adapter]
    sharding_config = Switchman.config || {}
    drop_statement = sharding_config[adapter].try(:[], :drop_statement)
    drop_statement ||= sharding_config[:drop_statement]
    if drop_statement
      drop_statement = Array(drop_statement).dup.
          map { |statement| statement.gsub('%{name}', self.name) }
    end

    case adapter
      when 'mysql', 'mysql2'
        self.activate do
          ::Shackles.activate(:deploy) do
            drop_statement ||= "DROP DATABASE #{self.name}"
            Array(drop_statement).each do |stmt|
              ::ActiveRecord::Base.connection.execute(stmt)
            end
          end
        end
      when 'postgresql'
        self.activate do
          ::Shackles.activate(:deploy) do
            # Shut up, Postgres!
            conn = ::ActiveRecord::Base.connection
            old_proc = conn.raw_connection.set_notice_processor {}
            begin
              drop_statement ||= "DROP SCHEMA #{self.name} CASCADE"
              Array(drop_statement).each do |stmt|
                ::ActiveRecord::Base.connection.execute(stmt)
              end
            ensure
              conn.raw_connection.set_notice_processor(&old_proc) if old_proc
            end
          end
        end
      when 'sqlite3'
        File.delete(self.name) unless self.name == ':memory:'
    end
  rescue
    logger.info "Drop failed: #{$!}"
  end
end

#global_id_for(local_id) ⇒ Object

takes an id local to this shard, and returns a global id



623
624
625
626
# File 'app/models/switchman/shard_internal.rb', line 623

def global_id_for(local_id)
  return nil unless local_id
  local_id + self.id * IDS_PER_SHARD
end

#hashObject

skip global_id.hash



629
630
631
# File 'app/models/switchman/shard_internal.rb', line 629

def hash
  id.hash
end

#nameObject



515
516
517
518
519
520
521
522
# File 'app/models/switchman/shard_internal.rb', line 515

def name
  unless instance_variable_defined?(:@name)
    # protect against re-entrancy
    @name = nil
    @name = read_attribute(:name) || default_name
  end
  @name
end

#name=(name) ⇒ Object



524
525
526
527
# File 'app/models/switchman/shard_internal.rb', line 524

def name=(name)
  write_attribute(:name, @name = name)
  remove_instance_variable(:@name) if name == nil
end

#primary?Boolean

Returns:

  • (Boolean)


538
539
540
# File 'app/models/switchman/shard_internal.rb', line 538

def primary?
  self == database_server.primary_shard
end

#shardObject

Shards are always on the default shard



547
548
549
# File 'app/models/switchman/shard_internal.rb', line 547

def shard
  Shard.default
end