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

require 'rubygems'
require 'redis'

6 7 8 9
def xputs(s)
    printf s
    STDOUT.flush
end
10

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

22 23 24 25 26 27
    def to_s
        "#{@host}:#{@port}"
    end

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

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    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

    def r
        @r
    end
end

class RedisTrib
    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

60 61
    def create_cluster
        puts "Creating cluster"
62 63 64 65 66
        ARGV[1..-1].each{|n|
            node = ClusterNode.new(n)
            node.connect
            node.assert_cluster
            # node.assert_empty
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
        }
    end
end

COMMANDS={
    "create-cluster" => ["create_cluster", -2]
}

# Sanity check
if ARGV.length == 0
    puts "Usage: redis-trib <command> <arguments ...>"
    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])