Skip to content

Instantly share code, notes, and snippets.

@psyho
Created March 14, 2011 21:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save psyho/869902 to your computer and use it in GitHub Desktop.
Save psyho/869902 to your computer and use it in GitHub Desktop.
master election using zookeeper
#!/usr/bin/env ruby
require "rubygems"
require "zookeeper"
def log(msg)
puts "[#{Process.pid}] #{msg}"
end
def debug(obj)
log(obj.inspect)
end
def on_master_changed(&block)
loop do
wcb = Zookeeper::WatcherCallback.new
resp = @zookeeper.get_children(:path => @base_path, :watcher => wcb, :watcher_context => @base_path)
children = resp[:children].map{|name| "#{@base_path}/#{name}"}
new_master = children.sort.first
block.call(new_master)
while !wcb.completed?
sleep(0.1)
end
end
end
@zookeeper = Zookeeper.new("localhost:2181")
if @zookeeper.state != Zookeeper::ZOO_CONNECTED_STATE
log 'Unable to connect to Zookeeper!'
exit(1)
end
@base_path = "/nodes"
@zookeeper.create(:path => @base_path)
resp = @zookeeper.create(:path => "#{@base_path}/node-", :ephemeral => true, :sequence => true, :data => Process.pid.to_s)
my_node = resp[:path]
is_master = false
log "My node is: #{my_node}"
on_master_changed do |new_master|
if new_master == my_node
if is_master
log "I am still the master. Bow before me or die!"
else
log "I am the new master. Behold!"
end
is_master = true
else
pid = @zookeeper.get(:path => new_master)[:data]
log "New master is process #{pid}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment