]> git.saurik.com Git - redis.git/blob - src/redis-trib.rb
assert_empty in redis-trib
[redis.git] / src / redis-trib.rb
1 #!/usr/bin/env ruby
2
3 require 'rubygems'
4 require 'redis'
5
6 def xputs(s)
7 printf s
8 STDOUT.flush
9 end
10
11 class ClusterNode
12 def initialize(addr)
13 s = addr.split(":")
14 if s.length != 2
15 puts "Invalid node name #{node}"
16 exit 1
17 end
18 @host = s[0]
19 @port = s[1]
20 end
21
22 def to_s
23 "#{@host}:#{@port}"
24 end
25
26 def connect
27 xputs "Connecting to node #{self}: "
28 begin
29 @r = Redis.new(:host => @ost, :port => @port)
30 @r.ping
31 rescue
32 puts "ERROR"
33 puts "Sorry, can't connect to node #{self}"
34 end
35 puts "OK"
36 end
37
38 def assert_cluster
39 info = @r.info
40 if !info["cluster_enabled"] || info["cluster_enabled"].to_i == 0
41 puts "Error: Node #{self} is not configured as a cluster node."
42 exit 1
43 end
44 end
45
46 def assert_empty
47 if !(@r.cluster("info").split("\r\n").index("cluster_known_nodes:1")) ||
48 (@r.info['db0'])
49 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."
50 exit 1
51 end
52 end
53
54 def r
55 @r
56 end
57 end
58
59 class RedisTrib
60 def check_arity(req_args, num_args)
61 if ((req_args > 0 and num_args != req_args) ||
62 (req_args < 0 and num_args < req_args.abs))
63 puts "Wrong number of arguments for specified sub command"
64 exit 1
65 end
66 end
67
68 def create_cluster
69 puts "Creating cluster"
70 ARGV[1..-1].each{|n|
71 node = ClusterNode.new(n)
72 node.connect
73 node.assert_cluster
74 node.assert_empty
75 }
76 end
77 end
78
79 COMMANDS={
80 "create-cluster" => ["create_cluster", -2]
81 }
82
83 # Sanity check
84 if ARGV.length == 0
85 puts "Usage: redis-trib <command> <arguments ...>"
86 exit 1
87 end
88
89 rt = RedisTrib.new
90 cmd_spec = COMMANDS[ARGV[0].downcase]
91 if !cmd_spec
92 puts "Unknown redis-trib subcommand '#{ARGV[0]}'"
93 exit 1
94 end
95 rt.check_arity(cmd_spec[1],ARGV.length)
96
97 # Dispatch
98 rt.send(cmd_spec[0])