Class: Switchman::Shard
- Inherits:
-
UnshardedRecord
- Object
- ActiveRecord::Base
- UnshardedRecord
- Switchman::Shard
- Defined in:
- app/models/switchman/shard.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] if it’s a well formed id, but the shard it refers to does not exist
[nil, nil].freeze
Class Method Summary collapse
- ._load(str) ⇒ Object
- .activate(shards) ⇒ Object
- .activate!(shards) ⇒ Object
- .clear_cache ⇒ Object
- .current(klass = ::ActiveRecord::Base) ⇒ Object
- .default(reload: false, with_fallback: false) ⇒ Object
-
.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.
-
.global_id_for(any_id, source_shard = nil) ⇒ Object
takes an id-ish, and returns an integral global id.
-
.integral_id_for(any_id) ⇒ Object
converts an AR object, integral id, string id, or string short-global-id to a integral id.
- .local_id_for(any_id) ⇒ Object
- .lookup(id) ⇒ Object
- .partition_by_shard(array, partition_proc = nil) ⇒ Object
-
.relative_id_for(any_id, source_shard, target_shard) ⇒ Object
takes an id-ish, and returns an integral id relative to target_shard.
- .shard_for(any_id, source_shard = nil) ⇒ Object
- .sharded_models ⇒ Object
-
.short_id_for(any_id) ⇒ Object
takes an id-ish, and returns a shortened global string id if global, and itself if local.
-
.signed_id_operation(input_id) ⇒ Object
it’s tedious to hold onto this same kind of sign state and transform the result in multiple places, so here we can operate on the absolute value in a provided block and trust the sign will stay as provided.
-
.with_each_shard(*args, parallel: false, max_procs: nil, exception: :raise, &block) ⇒ Object
Parameters.
Instance Method Summary collapse
-
#_dump(_depth) ⇒ Object
custom serialization, since shard is self-referential.
- #activate(*classes, &block) ⇒ Object
-
#activate!(*classes) ⇒ Object
for use from console ONLY.
- #database_server ⇒ Object
- #database_server=(database_server) ⇒ Object
- #description ⇒ Object
- #destroy ⇒ Object
- #drop_database ⇒ Object
-
#global_id_for(local_id) ⇒ Object
takes an id local to this shard, and returns a global id.
-
#hash ⇒ Object
skip global_id.hash.
- #name ⇒ Object
- #name=(name) ⇒ Object
- #primary? ⇒ Boolean
-
#shard ⇒ Object
Shards are always on the default shard.
Class Method Details
._load(str) ⇒ Object
616 617 618 |
# File 'app/models/switchman/shard.rb', line 616 def self._load(str) lookup(str.to_i) end |
.activate(shards) ⇒ Object
65 66 67 68 69 70 71 72 73 |
# File 'app/models/switchman/shard.rb', line 65 def activate(shards) activated_classes = activate!(shards) yield ensure activated_classes.each do |klass| klass.connection_pool.shard_stack.pop klass.connected_to_stack.pop end end |
.activate!(shards) ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'app/models/switchman/shard.rb', line 75 def activate!(shards) activated_classes = [] shards.each do |klass, shard| next if klass == UnshardedRecord next unless klass.current_shard != shard.database_server.id.to_sym || klass.connection_pool.shard != shard activated_classes << klass klass.connected_to_stack << { shard: shard.database_server.id.to_sym, klasses: [klass] } klass.connection_pool.shard_stack << shard end activated_classes end |
.clear_cache ⇒ Object
106 107 108 |
# File 'app/models/switchman/shard.rb', line 106 def clear_cache cached_shards.clear end |
.current(klass = ::ActiveRecord::Base) ⇒ Object
60 61 62 63 |
# File 'app/models/switchman/shard.rb', line 60 def current(klass = ::ActiveRecord::Base) klass ||= ::ActiveRecord::Base klass.connection_pool.shard end |
.default(reload: false, with_fallback: false) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'app/models/switchman/shard.rb', line 26 def default(reload: false, with_fallback: false) 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 default = @default if with_fallback && @default # 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 find_cached('default_shard') { Shard.where(default: true).take } || default rescue default end # make sure this is not erroneously cached @default.database_server.remove_instance_variable(:@primary_shard) if @default.database_server.instance_variable_defined?(:@primary_shard) # and finally, check for cached references to the default shard on the existing connection sharded_models.each do |klass| klass.connection.shard = @default if klass.connected? && klass.connection.shard.default? end 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.
485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
# File 'app/models/switchman/shard.rb', line 485 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.zero? else return 1 if parallel_input.nil? || parallel_input < 1 cpus = Environment.cpu_count max_procs = cpus * parallel_input if cpus&.positive? end 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
462 463 464 465 466 467 468 469 470 471 472 473 474 |
# File 'app/models/switchman/shard.rb', line 462 def global_id_for(any_id, source_shard = nil) id = integral_id_for(any_id) return any_id unless id signed_id_operation(id) do |abs_id| if abs_id >= IDS_PER_SHARD abs_id else source_shard ||= Shard.current source_shard.global_id_for(abs_id) end 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
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'app/models/switchman/shard.rb', line 389 def integral_id_for(any_id) case any_id when ::Arel::Nodes::Casted any_id = any_id.value when ::Arel::Nodes::BindParam any_id = any_id.value.value_before_type_cast end case any_id when ::ActiveRecord::Base any_id.id when /^(\d+)~(-?\d+)$/ local_id = $2.to_i signed_id_operation(local_id) do |id| return nil if id > IDS_PER_SHARD $1.to_i * IDS_PER_SHARD + id end when Integer, /^-?\d+$/ any_id.to_i end end |
.local_id_for(any_id) ⇒ Object
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'app/models/switchman/shard.rb', line 417 def local_id_for(any_id) id = integral_id_for(any_id) return NIL_NIL_ID unless id return_shard = nil local_id = signed_id_operation(id) do |abs_id| if abs_id < IDS_PER_SHARD abs_id elsif (return_shard = lookup(abs_id / IDS_PER_SHARD)) abs_id % IDS_PER_SHARD else return NIL_NIL_ID end end [local_id, return_shard] end |
.lookup(id) ⇒ Object
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'app/models/switchman/shard.rb', line 90 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.zero? unless cached_shards.key?(id) cached_shards[id] = Shard.default.activate do find_cached(['shard', id]) { find_by(id: id) } end end cached_shards[id] end |
.partition_by_shard(array, partition_proc = nil) ⇒ Object
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 367 368 369 370 371 372 |
# File 'app/models/switchman/shard.rb', line 341 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 unless 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 nil if it can’t be interpreted, or the integral version of the id if it refers to a shard that does not exist
438 439 440 441 442 443 444 445 446 447 |
# File 'app/models/switchman/shard.rb', line 438 def relative_id_for(any_id, source_shard, target_shard) integral_id = integral_id_for(any_id) local_id, shard = local_id_for(integral_id) return integral_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
476 477 478 479 480 481 |
# File 'app/models/switchman/shard.rb', line 476 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 |
.sharded_models ⇒ Object
22 23 24 |
# File 'app/models/switchman/shard.rb', line 22 def sharded_models @sharded_models ||= [::ActiveRecord::Base, UnshardedRecord].freeze 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 458 |
# File 'app/models/switchman/shard.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 |
.signed_id_operation(input_id) ⇒ Object
it’s tedious to hold onto this same kind of sign state and transform the result in multiple places, so here we can operate on the absolute value in a provided block and trust the sign will stay as provided. This assumes no consumer will return a nil value from the block.
381 382 383 384 385 |
# File 'app/models/switchman/shard.rb', line 381 def signed_id_operation(input_id) sign = input_id.negative? ? -1 : 1 output = yield input_id.abs output * sign end |
.with_each_shard(*args, parallel: false, max_procs: nil, exception: :raise, &block) ⇒ Object
Parameters
-
shards
- an array or relation of Shards to iterate over -
classes
- an array of classes to activateparallel: - 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 max_procs: - only run this many parallel processes at a time exception: - :ignore, :raise, :defer (wait until the end and raise the first error), or a proc
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 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 |
# File 'app/models/switchman/shard.rb', line 121 def with_each_shard(*args, parallel: false, max_procs: nil, exception: :raise, &block) raise ArgumentError, "wrong number of arguments (#{args.length} for 0...2)" if args.length > 2 return Array.wrap(yield) unless default.is_a?(Shard) if args.length == 1 if Array === args.first && args.first.first.is_a?(Class) classes = args.first else scope = args.first end else scope, classes = args end parallel = 1 if parallel == true parallel = 0 if parallel == false || parallel.nil? scope ||= Shard.all scope = scope.order(::Arel.sql('database_server_id IS NOT NULL, database_server_id, id')) if ::ActiveRecord::Relation === scope && scope.order_values.empty? if parallel.positive? max_procs = determine_max_procs(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).distinct. map(&:database_server).compact.uniq # nothing to do return if database_servers.count.zero? parallel = [(max_procs.to_f / database_servers.count).ceil, parallel].min if max_procs scopes = 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.to_h else scopes = scope.group_by(&:database_server) if parallel > 1 parallel = [(max_procs.to_f / scopes.count).ceil, parallel].min if max_procs scopes = scopes.map do |(server, shards)| [server, shards.in_groups(parallel, false).compact] end.to_h else scopes = scopes.map { |(server, shards)| [server, [shards]] }.to_h end end exception_pipes = [] pids = [] out_fds = [] err_fds = [] pid_to_name_map = {} fd_to_name_map = {} errors = [] wait_for_output = lambda do 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 # only one process; don't bother forking if scopes.length == 1 && parallel == 1 return with_each_shard(scopes.first.last.first, classes, exception: exception, &block) end # clear connections prior to forking (no more queries will be executed in the parent, # and we want them gone so that we don't accidentally use them post-fork doing something # silly like dealloc'ing prepared statements) ::ActiveRecord::Base.clear_all_connections! scopes.each do |server, subscopes| subscopes.each_with_index do |subscope, idx| name = if subscopes.length > 1 "#{server.id} #{idx + 1}" else server.id end exception_pipe = IO.pipe exception_pipes << exception_pipe pid, io_in, io_out, io_err = Open4.pfork4(lambda do Switchman.config[:on_fork_proc]&.call # set a pretty name for the process title, up to 128 characters # (we don't actually know the limit, depending on how the process # was started) # first, simplify the binary name by stripping directories, # then truncate arguments as necessary bin = File.basename($0) # Process.argv0 doesn't work on Ruby 2.5 (https://bugs.ruby-lang.org/issues/15887) max_length = 128 - bin.length - name.length - 3 args = ARGV.join(' ') args = args[0..max_length] if max_length >= 0 new_title = [bin, args, name].join(' ') Process.setproctitle(new_title) with_each_shard(subscope, classes, exception: exception, &block) exception_pipe.last.close rescue => e begin dumped = Marshal.dump(e) rescue # couldn't dump the exception; create a copy with just # the message and the backtrace e2 = e.class.new(e.) e2.set_backtrace(e.backtrace) e2.instance_variable_set(:@active_shards, e.instance_variable_get(:@active_shards)) dumped = Marshal.dump(e2) end exception_pipe.last.set_encoding(dumped.encoding) exception_pipe.last.write(dumped) exception_pipe.last.flush exception_pipe.last.close exit! 1 end) exception_pipe.last.close pids << pid io_in.close # don't care about writing to stdin out_fds << io_out err_fds << io_err pid_to_name_map[pid] = name fd_to_name_map[io_out] = name fd_to_name_map[io_err] = 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 end # we've gotten all the output from one fd so wait for its child process to exit found_pid, status = Process.wait2 pids.delete(found_pid) errors << pid_to_name_map[found_pid] if status.exitstatus != 0 end end end wait_for_output.call while out_fds.any? || err_fds.any? pids.each do |pid| _, status = Process.waitpid2(pid) errors << pid_to_name_map[pid] if status.exitstatus != 0 end # check for an exception; we only re-raise the first one exception_pipes.each do |exception_pipe| serialized_exception = exception_pipe.first.read next if serialized_exception.empty? ex = Marshal.load(serialized_exception) # rubocop:disable Security/MarshalLoad raise ex ensure exception_pipe.first.close end unless errors.empty? raise ParallelShardExecError, "The following subprocesses did not exit cleanly: #{errors.sort.join(', ')}" end return end classes ||= [] previous_shard = nil result = [] ex = nil scope.each do |shard| # shard references a database server that isn't configured in this environment next unless shard.database_server shard.activate(*classes) do result.concat Array.wrap(yield) rescue case exception when :ignore # ignore when :defer ex ||= $! when Proc exception.call # when :raise else raise end end previous_shard = shard end raise ex if ex result end |
Instance Method Details
#_dump(_depth) ⇒ Object
custom serialization, since shard is self-referential
612 613 614 |
# File 'app/models/switchman/shard.rb', line 612 def _dump(_depth) id.to_s end |
#activate(*classes, &block) ⇒ Object
599 600 601 602 |
# File 'app/models/switchman/shard.rb', line 599 def activate(*classes, &block) shards = hashify_classes(classes) Shard.activate(shards, &block) end |
#activate!(*classes) ⇒ Object
for use from console ONLY
605 606 607 608 609 |
# File 'app/models/switchman/shard.rb', line 605 def activate!(*classes) shards = hashify_classes(classes) Shard.activate!(shards) nil end |
#database_server ⇒ Object
577 578 579 |
# File 'app/models/switchman/shard.rb', line 577 def database_server @database_server ||= DatabaseServer.find(database_server_id) end |
#database_server=(database_server) ⇒ Object
581 582 583 584 |
# File 'app/models/switchman/shard.rb', line 581 def database_server=(database_server) self.database_server_id = database_server.id @database_server = database_server end |
#description ⇒ Object
590 591 592 |
# File 'app/models/switchman/shard.rb', line 590 def description [database_server.id, name].compact.join(':') end |
#destroy ⇒ Object
680 681 682 683 684 |
# File 'app/models/switchman/shard.rb', line 680 def destroy raise('Cannot destroy the default shard') if default? super end |
#drop_database ⇒ Object
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 |
# File 'app/models/switchman/shard.rb', line 620 def drop_database raise('Cannot drop the database of the default shard') if default? return unless read_attribute(:name) begin adapter = database_server.config[:adapter] sharding_config = Switchman.config || {} drop_statement = sharding_config[adapter]&.[](:drop_statement) drop_statement ||= sharding_config[:drop_statement] if drop_statement drop_statement = Array(drop_statement).dup. map { |statement| statement.gsub('%{name}', name) } end case adapter when 'mysql', 'mysql2' activate do ::GuardRail.activate(:deploy) do drop_statement ||= "DROP DATABASE #{name}" Array(drop_statement).each do |stmt| ::ActiveRecord::Base.connection.execute(stmt) end end end when 'postgresql' activate do ::GuardRail.activate(:deploy) do # Shut up, Postgres! conn = ::ActiveRecord::Base.connection old_proc = conn.raw_connection.set_notice_processor {} begin drop_statement ||= "DROP SCHEMA #{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 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
667 668 669 670 671 672 673 |
# File 'app/models/switchman/shard.rb', line 667 def global_id_for(local_id) return nil unless local_id self.class.signed_id_operation(local_id) do |abs_id| abs_id + id * IDS_PER_SHARD end end |
#hash ⇒ Object
skip global_id.hash
676 677 678 |
# File 'app/models/switchman/shard.rb', line 676 def hash id.hash end |
#name ⇒ Object
563 564 565 566 567 568 569 570 |
# File 'app/models/switchman/shard.rb', line 563 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
572 573 574 575 |
# File 'app/models/switchman/shard.rb', line 572 def name=(name) write_attribute(:name, @name = name) remove_instance_variable(:@name) if name.nil? end |
#primary? ⇒ Boolean
586 587 588 |
# File 'app/models/switchman/shard.rb', line 586 def primary? self == database_server.primary_shard end |