Skip to content

Instantly share code, notes, and snippets.

@fabrizioc1
Created July 10, 2013 05:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fabrizioc1/5963754 to your computer and use it in GitHub Desktop.
Save fabrizioc1/5963754 to your computer and use it in GitHub Desktop.
Zookeeper leader election using Ruby
# http://zookeeper.apache.org/doc/r3.3.4/recipes.html#sc_leaderElection
require 'rubygems'
require 'bundler/setup'
require 'zookeeper'
require 'hashie'
class ElectionCandidate
ROOT_PATH = "/election"
NODE_PATH = "candidate_"
attr_reader :zookeeper, :children, :node_path
def initialize
@zookeeper = Zookeeper.new("localhost:2181")
root_path_create! unless root_path_exists?
register!
end
def root_path_create!
@zookeeper.create(path:ROOT_PATH, data:ROOT_PATH)
end
def root_path_exists?
Hashie::Mash.new(@zookeeper.get(path:ROOT_PATH)).stat.exists?
end
def register!
path = "#{ROOT_PATH}/#{NODE_PATH}"
result = Hashie::Mash.new(@zookeeper.create(path:path, data:path, ephemeral:true, sequence:true))
if result.rc == 0
@node_path = result.path
end
end
def registered?
!self.node_path.nil?
end
def leader?
result = Hashie::Mash.new(@zookeeper.get_children(path:ROOT_PATH))
@children = result.children
puts "ERROR: #{result}" if result.rc != 0
leader = result.children.select{|c| c[/#{NODE_PATH}/] }.sort.first
leader_path = "#{ROOT_PATH}/#{leader}"
result.rc == 0 && result.children && self.node_path == leader_path
end
end
candidate = ElectionCandidate.new
loop do
system "clear"
puts "candidate '#{candidate.node_path}'"
if candidate.leader?
puts "I am the leader!"
else
puts "candidates: #{candidate.children}"
end
sleep 5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment