]> git.saurik.com Git - redis.git/blame - src/redis-trib.rb
assert_empty in redis-trib
[redis.git] / src / redis-trib.rb
CommitLineData
407798c1
SS
1#!/usr/bin/env ruby
2
3require 'rubygems'
4require 'redis'
5
b800a3ab
SS
6def xputs(s)
7 printf s
8 STDOUT.flush
9end
407798c1 10
b800a3ab
SS
11class ClusterNode
12 def initialize(addr)
13 s = addr.split(":")
407798c1
SS
14 if s.length != 2
15 puts "Invalid node name #{node}"
16 exit 1
17 end
b800a3ab
SS
18 @host = s[0]
19 @port = s[1]
407798c1
SS
20 end
21
b800a3ab
SS
22 def to_s
23 "#{@host}:#{@port}"
24 end
25
26 def connect
27 xputs "Connecting to node #{self}: "
407798c1 28 begin
b800a3ab
SS
29 @r = Redis.new(:host => @ost, :port => @port)
30 @r.ping
407798c1
SS
31 rescue
32 puts "ERROR"
b800a3ab 33 puts "Sorry, can't connect to node #{self}"
407798c1
SS
34 end
35 puts "OK"
36 end
37
b800a3ab
SS
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
f29d1fb0
SS
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
b800a3ab
SS
54 def r
55 @r
56 end
57end
58
59class 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
407798c1
SS
68 def create_cluster
69 puts "Creating cluster"
b800a3ab
SS
70 ARGV[1..-1].each{|n|
71 node = ClusterNode.new(n)
72 node.connect
73 node.assert_cluster
f29d1fb0 74 node.assert_empty
407798c1
SS
75 }
76 end
77end
78
79COMMANDS={
80 "create-cluster" => ["create_cluster", -2]
81}
82
83# Sanity check
84if ARGV.length == 0
85 puts "Usage: redis-trib <command> <arguments ...>"
86 exit 1
87end
88
89rt = RedisTrib.new
90cmd_spec = COMMANDS[ARGV[0].downcase]
91if !cmd_spec
92 puts "Unknown redis-trib subcommand '#{ARGV[0]}'"
93 exit 1
94end
95rt.check_arity(cmd_spec[1],ARGV.length)
96
97# Dispatch
98rt.send(cmd_spec[0])