class Syncrony::Election

Constants

DEFAULT_OPTS

Attributes

is_leader[RW]

Public Class Methods

new(options={}) click to toggle source
# File lib/syncrony/election.rb, line 18
def initialize(options={})
  options = DEFAULT_OPTS.merge(options)
  raise if not options[:path]
  @path = options[:path]
  @server = options[:server]
  @ttl = options[:ttl]
  @interval = options[:interval]
  @identifier = options[:identifier] || SecureRandom.uuid
end

Public Instance Methods

become_leader() click to toggle source
# File lib/syncrony/election.rb, line 35
def become_leader
  @is_leader = true
  @timer = every(@interval) do
    update
  end
end
cancel() click to toggle source

Stop being leader, or stop trying to become leader.

# File lib/syncrony/election.rb, line 43
def cancel
  @observer.cancel if @observer
  if @is_leader
    @timer.cancel
    @is_leader = false
    @client.delete(@path)
  end
  return
end
request_election() click to toggle source
# File lib/syncrony/election.rb, line 53
def request_election
  @observer = Syncrony::Observer.new(@client, @path)
  @observer.run do |value, path, info|
    if value.nil?
      begin
        @client.set(@path, value: @identifier,
                           prevExist: false,
                           ttl: @ttl)
        @observer.cancel
        become_leader
      rescue Etcd::TestFailed
        # We lost the election race.
      end
    end
  end
end
run() click to toggle source
# File lib/syncrony/election.rb, line 28
def run
  @client = Etcd.client(@server)
  @is_leader = false
  request_election
  return
end
update() click to toggle source
# File lib/syncrony/election.rb, line 70
def update
  @client.set(@path, value: @identifier,
                     prevValue: @identifier,
                     ttl: @ttl)
end