]>
Commit | Line | Data |
---|---|---|
407798c1 SS |
1 | #!/usr/bin/env ruby |
2 | ||
3 | require 'rubygems' | |
4 | require 'redis' | |
5 | ||
b800a3ab SS |
6 | def xputs(s) |
7 | printf s | |
8 | STDOUT.flush | |
9 | end | |
407798c1 | 10 | |
b800a3ab SS |
11 | class 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 | |
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 | ||
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 | |
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]) |