Skip to content

Instantly share code, notes, and snippets.

@kevinpet
Created June 16, 2010 00:35
Show Gist options
  • Save kevinpet/439947 to your computer and use it in GitHub Desktop.
Save kevinpet/439947 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'rubygems'
require 'redis'
REDIS_CMD = "./redis-server"
DIR = "redis-repl-test"
FileUtils.mkdir(DIR) unless File.directory?(DIR)
class Redis
def slaveof(*args)
@client.call(:slaveof, *args)
end
end
class Node
def initialize(name, port)
@name = name
@port = port
end
def to_s
"node #{@name}"
end
def client
Redis.new(:host => "localhost", :port => @port)
end
def filename(ext)
"#{@name.to_s}.#{ext}"
end
attr_accessor :port
def clean_start
FileUtils.rm(Dir.glob("#{DIR}/#{filename('*')}"))
start
end
def start
puts "Starting #{self}"
File.open("#{DIR}/#{filename('conf')}", "w") do |out|
out.puts "daemonize yes"
out.puts "pidfile #{filename('pid')}"
out.puts "port #{@port}"
out.puts "logfile #{DIR}/#{filename('log')}"
out.puts "dir #{DIR}/"
out.puts "dbfilename #{filename('rdb')}"
end
system "#{REDIS_CMD} #{DIR}/#{filename('conf')}"
end
def stop(sig="TERM")
File.open("#{DIR}/#{filename("pid")}") do |input|
input.each do |line|
puts "Sending sig #{sig} to #{self} (#{line.to_i})"
Process.kill(sig, line.to_i)
end
end
end
def follow(master)
puts "#{self} slaveof #{master}"
client.slaveof "localhost", master.port
end
def unfollow
puts "#{self} slaveof no one"
client.slaveof "no", "one"
end
end
def set(node, key, value)
result = node.client.set key, value
puts "Storing '#{key}' => '#{value}' on #{node}"
end
def get(node, key)
result = node.client.get key
puts "Get '#{key}' from #{node}: '#{result}'"
end
def failure1
a = Node.new(:a, 6380)
b = Node.new(:b, 6381)
c = Node.new(:c, 6382)
nodes = [a, b, c]
nodes.each { |node| node.clean_start }
sleep 1
b.follow a
c.follow b
sleep 1
b.stop "KILL"
set a, "test1", "this will get lost"
b.start
sleep 1
b.follow a
set a, "test2", "this will get replicated"
sleep 5
get b, "test1"
get c, "test2"
get c, "test1"
nodes.each { |node| node.stop }
end
failure1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment