redis-trib.rb 18.4 KB
Newer Older
1 2
#!/usr/bin/env ruby

3
# TODO (temporary here, we'll move this into the Github issues once
G
guiquanz 已提交
4
#       redis-trib initial implementation is completed).
5
#
6 7 8 9 10 11 12 13 14 15 16 17 18 19
# - Make sure that if the rehashing fails in the middle redis-trib will try
#   to recover.
# - When redis-trib performs a cluster check, if it detects a slot move in
#   progress it should prompt the user to continue the move from where it
#   stopped.
# - Gracefully handle Ctrl+C in move_slot to prompt the user if really stop
#   while rehashing, and performing the best cleanup possible if the user
#   forces the quit.
# - When doing "fix" set a global Fix to true, and prompt the user to
#   fix the problem if automatically fixable every time there is something
#   to fix. For instance:
#   1) If there is a node that pretend to receive a slot, or to migrate a
#      slot, but has no entries in that slot, fix it.
#   2) If there is a node having keys in slots that are not owned by it
G
guiquanz 已提交
20
#      fix this condition moving the entries in the same node.
21 22
#   3) Perform more possibly slow tests about the state of the cluster.
#   4) When aborted slot migration is detected, fix it.
23

24 25 26
require 'rubygems'
require 'redis'

27
ClusterHashSlots = 16384
28

29 30 31 32
def xputs(s)
    printf s
    STDOUT.flush
end
33

34 35 36
class ClusterNode
    def initialize(addr)
        s = addr.split(":")
37
        if s.length != 2
A
antirez 已提交
38
            puts "Invalid node name #{addr}"
39 40
            exit 1
        end
41
        @r = nil
42 43 44 45 46
        @info = {}
        @info[:host] = s[0]
        @info[:port] = s[1]
        @info[:slots] = {}
        @dirty = false # True if we need to flush slots info into node.
47
        @friends = []
48 49
    end

50 51 52 53 54
    def friends
        @friends
    end

    def slots 
55
        @info[:slots]
56 57
    end

58
    def to_s
59
        "#{@info[:host]}:#{@info[:port]}"
60 61
    end

62
    def connect(o={})
63
        return if @r
64
        xputs "Connecting to node #{self}: "
65
        begin
66
            @r = Redis.new(:host => @info[:host], :port => @info[:port])
67
            @r.ping
68 69
        rescue
            puts "ERROR"
70
            puts "Sorry, can't connect to node #{self}"
71 72
            exit 1 if o[:abort]
            @r = nil
73 74 75 76
        end
        puts "OK"
    end

77 78 79 80 81 82 83 84
    def assert_cluster
        info = @r.info
        if !info["cluster_enabled"] || info["cluster_enabled"].to_i == 0
            puts "Error: Node #{self} is not configured as a cluster node."
            exit 1
        end
    end

85 86 87 88 89 90 91 92
    def assert_empty
        if !(@r.cluster("info").split("\r\n").index("cluster_known_nodes:1")) ||
            (@r.info['db0'])
            puts "Error: Node #{self} is not empty. Either the node already knows other nodes (check with nodes-info) or contains some key in database 0."
            exit 1
        end
    end

93 94 95 96 97
    def load_info(o={})
        self.connect
        nodes = @r.cluster("nodes").split("\n")
        nodes.each{|n|
            # name addr flags role ping_sent ping_recv link_status slots
98 99 100
            split = n.split
            name,addr,flags,role,ping_sent,ping_recv,link_status = split[0..6]
            slots = split[7..-1]
101 102 103 104 105 106 107 108 109 110
            info = {
                :name => name,
                :addr => addr,
                :flags => flags.split(","),
                :role => role,
                :ping_sent => ping_sent.to_i,
                :ping_recv => ping_recv.to_i,
                :link_status => link_status
            }
            if info[:flags].index("myself")
111 112
                @info = @info.merge(info)
                @info[:slots] = {}
113 114 115 116
                slots.each{|s|
                    if s[0..0] == '['
                        # Fixme: for now skipping migration entries
                    elsif s.index("-")
117 118 119 120 121
                        start,stop = s.split("-")
                        self.add_slots((start.to_i)..(stop.to_i))
                    else
                        self.add_slots((s.to_i)..(s.to_i))
                    end
122
                } if slots
123
                @dirty = false
124 125 126
                @r.cluster("info").split("\n").each{|e|    
                    k,v=e.split(":")
                    k = k.to_sym
127
                    v.chop!
128 129 130 131 132 133
                    if k != :cluster_state
                        @info[k] = v.to_i
                    else
                        @info[k] = v
                    end
                }
134 135 136 137 138 139
            elsif o[:getfriends]
                @friends << info
            end
        }
    end

140 141
    def add_slots(slots)
        slots.each{|s|
142
            @info[:slots][s] = :new
143 144 145 146 147 148 149
        }
        @dirty = true
    end

    def flush_node_config
        return if !@dirty
        new = []
150
        @info[:slots].each{|s,val|
151 152
            if val == :new
                new << s
153
                @info[:slots][s] = true
154 155 156 157 158 159
            end
        }
        @r.cluster("addslots",*new)
        @dirty = false
    end

160
    def info_string
161
        # We want to display the hash slots assigned to this node
A
antirez 已提交
162
        # as ranges, like in: "1-5,8-9,20-25,30"
163 164 165 166 167 168
        #
        # Note: this could be easily written without side effects,
        # we use 'slots' just to split the computation into steps.
        
        # First step: we want an increasing array of integers
        # for instance: [1,2,3,4,5,8,9,20,21,22,23,24,25,30]
169
        slots = @info[:slots].keys.sort
170

G
guiquanz 已提交
171
        # As we want to aggregate adjacent slots we convert all the
172 173
        # slot integers into ranges (with just one element)
        # So we have something like [1..1,2..2, ... and so forth.
A
antirez 已提交
174
        slots.map!{|x| x..x}
175

G
guiquanz 已提交
176
        # Finally we group ranges with adjacent elements.
177 178 179
        slots = slots.reduce([]) {|a,b|
            if !a.empty? && b.first == (a[-1].last)+1
                a[0..-2] + [(a[-1].first)..(b.last)]
180
            else
181
                a + [b]
182
            end
183 184 185 186 187 188 189
        }

        # Now our task is easy, we just convert ranges with just one
        # element into a number, and a real range into a start-end format.
        # Finally we join the array using the comma as separator.
        slots = slots.map{|x|
            x.count == 1 ? x.first.to_s : "#{x.first}-#{x.last}"
190
        }.join(",")
191

192
        "[#{@info[:cluster_state].upcase}] #{self.info[:name]} #{self.to_s} slots:#{slots} (#{self.slots.length} slots)"
193
    end
194 195

    def info
196
        @info
197
    end
198 199 200 201 202
    
    def is_dirty?
        @dirty
    end

203 204 205 206 207 208
    def r
        @r
    end
end

class RedisTrib
209 210
    def initialize
        @nodes = []
211 212
        @fix = false
        @errors = []
213 214
    end

215 216 217 218 219 220 221 222
    def check_arity(req_args, num_args)
        if ((req_args > 0 and num_args != req_args) ||
           (req_args < 0 and num_args < req_args.abs))
           puts "Wrong number of arguments for specified sub command"
           exit 1
        end
    end

223 224 225 226
    def add_node(node)
        @nodes << node
    end

227 228 229 230 231 232 233
    def get_node_by_name(name)
        @nodes.each{|n|
            return n if n.info[:name] == name.downcase
        }
        return nil
    end

234
    def check_cluster
235
        puts "Performing Cluster Check (using node #{@nodes[0]})"
236
        show_nodes
237 238 239 240 241 242
        check_slots_coverage
    end

    # Merge slots of every known node. If the resulting slots are equal
    # to ClusterHashSlots, then all slots are served.
    def covered_slots
243 244 245 246
        slots = {}
        @nodes.each{|n|
            slots = slots.merge(n.slots)
        }
247 248 249 250 251
        slots
    end

    def check_slots_coverage
        slots = covered_slots
252 253
        if slots.length == ClusterHashSlots
            puts "[OK] All #{ClusterHashSlots} slots covered."
254
        else
255 256 257
            @errors <<
                "[ERR] Not all #{ClusterHashSlots} slots are covered by nodes."
            puts @errors[-1]
A
antirez 已提交
258
            fix_slots_coverage if @fix
259
        end
260 261
    end

262 263 264 265 266 267 268 269
    def nodes_with_keys_in_slot(slot)
        nodes = []
        @nodes.each{|n|
            nodes << n if n.r.cluster("getkeysinslot",slot,1).length > 0
        }
        nodes
    end

270
    def fix_slots_coverage
271 272 273 274 275 276 277 278 279 280 281 282
        not_covered = (0...ClusterHashSlots).to_a - covered_slots.keys
        puts "\nFixing slots coverage..."
        puts "List of not covered slots: " + not_covered.join(",")

        # For every slot, take action depending on the actual condition:
        # 1) No node has keys for this slot.
        # 2) A single node has keys for this slot.
        # 3) Multiple nodes have keys for this slot.
        slots = {}
        not_covered.each{|slot|
            nodes = nodes_with_keys_in_slot(slot)
            slots[slot] = nodes
283
            puts "Slot #{slot} has keys in #{nodes.length} nodes: #{nodes.join}"
284 285 286 287 288 289
        }

        none = slots.select {|k,v| v.length == 0}
        single = slots.select {|k,v| v.length == 1}
        multi = slots.select {|k,v| v.length > 1}

290 291 292 293 294 295 296 297 298 299 300 301 302 303
        # Handle case "1": keys in no node.
        if none.length > 0
            puts "The folowing uncovered slots have no keys across the cluster:"
            puts none.keys.join(",")
            yes_or_die "Fix these slots by covering with a random node?"
            none.each{|slot,nodes|
                node = @nodes.sample
                puts "Covering slot #{slot} with #{node}"
                node.r.cluster("addslots",slot)
            }
        end

        # Handle case "2": keys only in one node.
        if single.length > 0
304 305
            puts "The folowing uncovered slots have keys in just one node:"
            puts single.keys.join(",")
306
            yes_or_die "Fix these slots by covering with those nodes?"
307 308 309 310 311
            single.each{|slot,nodes|
                puts "Covering slot #{slot} with #{nodes[0]}"
                nodes[0].r.cluster("addslots",slot)
            }
        end
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

        # Handle case "3": keys in multiple nodes.
        if multi.length > 0
            puts "The folowing uncovered slots have keys in multiple nodes:"
            puts multi.keys.join(",")
            yes_or_die "Fix these slots by moving keys into a single node?"
            multi.each{|slot,nodes|
                puts "Covering slot #{slot} moving keys to #{nodes[0]}"
                # TODO
                # 1) Set all nodes as "MIGRATING" for this slot, so that we
                # can access keys in the hash slot using ASKING.
                # 2) Move everything to node[0]
                # 3) Clear MIGRATING from nodes, and ADDSLOTS the slot to
                # node[0].
                raise "TODO: Work in progress"
            }
        end
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    end

    def alloc_slots
        slots_per_node = ClusterHashSlots/@nodes.length
        i = 0
        @nodes.each{|n|
            first = i*slots_per_node
            last = first+slots_per_node-1
            last = ClusterHashSlots-1 if i == @nodes.length-1
            n.add_slots first..last
            i += 1
        }
    end

    def flush_nodes_config
        @nodes.each{|n|
            n.flush_node_config
        }
    end

    def show_nodes
        @nodes.each{|n|
351
            puts n.info_string
352 353 354 355
        }
    end

    def join_cluster
356 357 358 359 360 361 362 363 364 365
        # We use a brute force approach to make sure the node will meet
        # each other, that is, sending CLUSTER MEET messages to all the nodes
        # about the very same node.
        # Thanks to gossip this information should propagate across all the
        # cluster in a matter of seconds.
        first = false
        @nodes.each{|n|
            if !first then first = n.info; next; end # Skip the first node
            n.r.cluster("meet",first[:host],first[:port])
        }
366 367 368 369 370 371 372 373 374
    end

    def yes_or_die(msg)
        print "#{msg} (type 'yes' to accept): "
        STDOUT.flush
        if !(STDIN.gets.chomp.downcase == "yes")
            puts "Aborting..."
            exit 1
        end
375
    end
376

377
    def load_cluster_info_from_node(nodeaddr)
378 379 380
        node = ClusterNode.new(ARGV[1])
        node.connect(:abort => true)
        node.assert_cluster
381
        node.load_info(:getfriends => true)
382
        add_node(node)
383 384 385 386 387 388
        node.friends.each{|f|
            fnode = ClusterNode.new(f[:addr])
            fnode.connect()
            fnode.load_info()
            add_node(fnode)
        }
389 390
    end

391 392 393 394 395
    # Given a list of source nodes return a "resharding plan"
    # with what slots to move in order to move "numslots" slots to another
    # instance.
    def compute_reshard_table(sources,numslots)
        moved = []
396
        # Sort from bigger to smaller instance, for two reasons:
397 398 399 400 401 402
        # 1) If we take less slots than instances it is better to start
        #    getting from the biggest instances.
        # 2) We take one slot more from the first instance in the case of not
        #    perfect divisibility. Like we have 3 nodes and need to get 10
        #    slots, we take 4 from the first, and 3 from the rest. So the
        #    biggest is always the first.
403
        sources = sources.sort{|a,b| b.slots.length <=> a.slots.length}
404 405 406
        source_tot_slots = sources.inject(0) {|sum,source|
            sum+source.slots.length
        }
407
        sources.each_with_index{|s,i|
408 409
            # Every node will provide a number of slots proportional to the
            # slots it has assigned.
410
            n = (numslots.to_f/source_tot_slots*s.slots.length)
411 412 413 414 415
            if i == 0
                n = n.ceil
            else
                n = n.floor
            end
416 417 418 419 420 421 422 423 424 425 426
            s.slots.keys.sort[(0...n)].each{|slot|
                if moved.length < numslots
                    moved << {:source => s, :slot => slot}
                end
            }
        }
        return moved
    end

    def show_reshard_table(table)
        table.each{|e|
427
            puts "    Moving slot #{e[:slot]} from #{e[:source].info[:name]}"
428 429 430
        }
    end

431
    def move_slot(source,target,slot,o={})
432 433
        # We start marking the slot as importing in the destination node,
        # and the slot as migrating in the target host. Note that the order of
434 435
        # the operations is important, as otherwise a client may be redirected
        # to the target node that does not yet know it is importing this slot.
436
        print "Moving slot #{slot} from #{source.info_string}: "; STDOUT.flush
437
        target.r.cluster("setslot",slot,"importing",source.info[:name])
438
        source.r.cluster("setslot",slot,"migrating",target.info[:name])
439
        # Migrate all the keys from source to target using the MIGRATE command
440 441 442 443
        while true
            keys = source.r.cluster("getkeysinslot",slot,10)
            break if keys.length == 0
            keys.each{|key|
444
                source.r.migrate(target.info[:host],target.info[:port],key,0,1000)
445 446 447 448 449 450 451 452 453
                print "." if o[:verbose]
                STDOUT.flush
            }
        end
        puts
        # Set the new node as the owner of the slot in all the known nodes.
        @nodes.each{|n|
            n.r.cluster("setslot",slot,"node",target.info[:name])
        }
454 455
    end

456 457
    # redis-trib subcommands implementations

458 459 460 461 462 463 464
    def check_cluster_cmd
        load_cluster_info_from_node(ARGV[1])
        check_cluster
    end

    def fix_cluster_cmd
        @fix = true
465
        load_cluster_info_from_node(ARGV[1])
466 467 468
        check_cluster
    end

469 470
    def reshard_cluster_cmd
        load_cluster_info_from_node(ARGV[1])
471 472
        check_cluster
        if @errors.length != 0
473 474 475
            puts "Please fix your cluster problems before resharding."
            exit 1
        end
476
        numslots = 0
477 478
        while numslots <= 0 or numslots > ClusterHashSlots
            print "How many slots do you want to move (from 1 to #{ClusterHashSlots})? "
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
            numslots = STDIN.gets.to_i
        end
        target = nil
        while not target
            print "What is the receiving node ID? "
            target = get_node_by_name(STDIN.gets.chop)
            if not target
                puts "The specified node is not known, please retry."
            end
        end
        sources = []
        puts "Please enter all the source node IDs."
        puts "  Type 'all' to use all the nodes as source nodes for the hash slots."
        puts "  Type 'done' once you entered all the source nodes IDs."
        while true
            print "Source node ##{sources.length+1}:"
            line = STDIN.gets.chop
            src = get_node_by_name(line)
            if line == "done"
                if sources.length == 0
                    puts "No source nodes given, operation aborted"
                    exit 1
                else
                    break
                end
            elsif line == "all"
                @nodes.each{|n|
                    next if n.info[:name] == target.info[:name]
                    sources << n
                }
                break
            elsif not src
                puts "The specified node is not known, please retry."
            elsif src.info[:name] == target.info[:name]
                puts "It is not possible to use the target node as source node."
            else
                sources << src
            end
517
        end
518 519 520 521 522 523
        puts "\nReady to move #{numslots} slots."
        puts "  Source nodes:"
        sources.each{|s| puts "    "+s.info_string}
        puts "  Destination node:"
        puts "    #{target.info_string}"
        reshard_table = compute_reshard_table(sources,numslots)
524
        puts "  Resharding plan:"
525
        show_reshard_table(reshard_table)
526 527 528 529
        print "Do you want to proceed with the proposed reshard plan (yes/no)? "
        yesno = STDIN.gets.chop
        exit(1) if (yesno != "yes")
        reshard_table.each{|e|
530
            move_slot(e[:source],target,e[:slot],:verbose=>true)
531
        }
532 533
    end

534 535 536 537 538 539
    def create_cluster_cmd
        puts "Creating cluster"
        ARGV[1..-1].each{|n|
            node = ClusterNode.new(n)
            node.connect(:abort => true)
            node.assert_cluster
540
            node.load_info
541 542 543 544 545 546 547 548 549 550 551 552 553
            node.assert_empty
            add_node(node)
        }
        puts "Performing hash slots allocation on #{@nodes.length} nodes..."
        alloc_slots
        show_nodes
        yes_or_die "Can I set the above configuration?"
        flush_nodes_config
        puts "** Nodes configuration updated"
        puts "** Sending CLUSTER MEET messages to join the cluster"
        join_cluster
        check_cluster
    end
554 555 556
end

COMMANDS={
557 558 559 560
    "create"  => ["create_cluster_cmd", -2, "host1:port1 ... hostN:portN"],
    "check"   => ["check_cluster_cmd", 2, "host:port"],
    "fix"     => ["fix_cluster_cmd", 2, "host:port"],
    "reshard" => ["reshard_cluster_cmd", 2, "host:port"]
561 562 563 564 565
}

# Sanity check
if ARGV.length == 0
    puts "Usage: redis-trib <command> <arguments ...>"
A
antirez 已提交
566 567
    puts
    COMMANDS.each{|k,v|
568
        puts "  #{k.ljust(10)} #{v[2]}"
A
antirez 已提交
569 570
    }
    puts
571 572 573 574 575 576 577 578 579 580 581 582 583
    exit 1
end

rt = RedisTrib.new
cmd_spec = COMMANDS[ARGV[0].downcase]
if !cmd_spec
    puts "Unknown redis-trib subcommand '#{ARGV[0]}'"
    exit 1
end
rt.check_arity(cmd_spec[1],ARGV.length)

# Dispatch
rt.send(cmd_spec[0])