Class: Syncrony::Election

Inherits:
Object
  • Object
show all
Includes:
Celluloid
Defined in:
lib/syncrony/election.rb

Constant Summary collapse

DEFAULT_OPTS =
{
  server: { host: '127.0.0.1', port: 4001 },
  ttl: 15,
  interval: 5
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Election

Returns a new instance of Election.



18
19
20
21
22
23
24
25
26
# 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

Instance Attribute Details

#is_leaderObject

Returns the value of attribute is_leader.



10
11
12
# File 'lib/syncrony/election.rb', line 10

def is_leader
  @is_leader
end

Instance Method Details

#become_leaderObject



35
36
37
38
39
40
# File 'lib/syncrony/election.rb', line 35

def become_leader
  @is_leader = true
  @timer = every(@interval) do
    update
  end
end

#cancelObject

Stop being leader, or stop trying to become leader.



43
44
45
46
47
48
49
50
51
# 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_electionObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 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

#runObject



28
29
30
31
32
33
# File 'lib/syncrony/election.rb', line 28

def run
  @client = Etcd.client(@server)
  @is_leader = false
  request_election
  return
end

#updateObject



70
71
72
73
74
# File 'lib/syncrony/election.rb', line 70

def update
  @client.set(@path, value: @identifier,
                     prevValue: @identifier,
                     ttl: @ttl)
end