redis-trib.rb 5.1 KB
Newer Older
1 2 3 4 5
#!/usr/bin/env ruby

require 'rubygems'
require 'redis'

6 7
ClusterHashSlots = 4096

8 9 10 11
def xputs(s)
    printf s
    STDOUT.flush
end
12

13 14 15
class ClusterNode
    def initialize(addr)
        s = addr.split(":")
16 17 18 19
        if s.length != 2
            puts "Invalid node name #{node}"
            exit 1
        end
20 21
        @host = s[0]
        @port = s[1]
22 23
        @slots = {}
        @dirty = false
24 25
    end

26 27 28 29 30 31
    def to_s
        "#{@host}:#{@port}"
    end

    def connect
        xputs "Connecting to node #{self}: "
32
        begin
33 34
            @r = Redis.new(:host => @ost, :port => @port)
            @r.ping
35 36
        rescue
            puts "ERROR"
37
            puts "Sorry, can't connect to node #{self}"
38 39 40 41
        end
        puts "OK"
    end

42 43 44 45 46 47 48 49
    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

50 51 52 53 54 55 56 57
    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

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    def add_slots(slots)
        slots.each{|s|
            @slots[s] = :new
        }
        @dirty = true
    end

    def flush_node_config
        return if !@dirty
        new = []
        @slots.each{|s,val|
            if val == :new
                new << s
                @slots[s] = true
            end
        }
        @r.cluster("addslots",*new)
        @dirty = false
    end

78
    def info_string
79 80 81 82 83 84 85 86 87 88 89 90 91
        slots = @slots.map{|k,v| k}.reduce{|a,b|
            a = [(a..a)] if !a.is_a?(Array)
            if b == (a[-1].last)+1
                a[-1] = (a[-1].first)..b
                a
            else
                a << (b..b)
            end
        }.map{|x|
            (x.first == x.last) ? x.first.to_s : "#{x.first}-#{x.last}"
        }.join(",")
        "#{self.to_s.ljust(25)} slots:#{slots}"
    end
92 93 94 95 96 97 98 99 100

    def info
        {
            :host => @host,
            :port => @port,
            :slots => @slots,
            :dirty => @dirty
        }
    end
101 102 103 104 105
    
    def is_dirty?
        @dirty
    end

106 107 108 109 110 111
    def r
        @r
    end
end

class RedisTrib
112 113 114 115
    def initialize
        @nodes = []
    end

116 117 118 119 120 121 122 123
    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

124 125
    def create_cluster
        puts "Creating cluster"
126 127 128 129
        ARGV[1..-1].each{|n|
            node = ClusterNode.new(n)
            node.connect
            node.assert_cluster
130
            node.assert_empty
131
            @nodes << node
132
        }
133 134 135 136 137 138
        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"
139
        puts "** Sending CLUSTER MEET messages to join the cluster"
140
        join_cluster
141 142 143 144 145
        check_cluster
    end

    def check_cluster
        puts "Check if the cluster looks sane"
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    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|
168
            puts n.info_string
169 170 171 172
        }
    end

    def join_cluster
173 174 175 176 177 178 179 180 181 182
        # 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])
        }
183 184 185 186 187 188 189 190 191
    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
192 193 194 195
    end
end

COMMANDS={
196 197
    "create" => ["create_cluster", -2, "host1:port host2:port ... hostN:port"],
    "check" =>  ["check_cluster", 1, "host:port"]
198 199 200 201 202
}

# Sanity check
if ARGV.length == 0
    puts "Usage: redis-trib <command> <arguments ...>"
A
antirez 已提交
203 204 205 206 207
    puts
    COMMANDS.each{|k,v|
        puts "  #{k.ljust(20)} #{v[2]}"
    }
    puts
208 209 210 211 212 213 214 215 216 217 218 219 220
    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])