Class: Syncrony::Election
- Inherits:
-
Object
- Object
- Syncrony::Election
- 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
-
#is_leader ⇒ Object
Returns the value of attribute is_leader.
Instance Method Summary collapse
- #become_leader ⇒ Object
-
#cancel ⇒ Object
Stop being leader, or stop trying to become leader.
-
#initialize(options = {}) ⇒ Election
constructor
A new instance of Election.
- #request_election ⇒ Object
- #run ⇒ Object
- #update ⇒ Object
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(={}) = DEFAULT_OPTS.merge() raise if not [:path] @path = [:path] @server = [:server] @ttl = [:ttl] @interval = [:interval] @identifier = [:identifier] || SecureRandom.uuid end |
Instance Attribute Details
#is_leader ⇒ Object
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_leader ⇒ Object
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 |
#cancel ⇒ Object
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_election ⇒ Object
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 |
#run ⇒ Object
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 |
#update ⇒ Object
70 71 72 73 74 |
# File 'lib/syncrony/election.rb', line 70 def update @client.set(@path, value: @identifier, prevValue: @identifier, ttl: @ttl) end |