Class: Etcd::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/etcd/lock.rb

Defined Under Namespace

Classes: AcqusitionFailure, ReleaseFailure

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Lock

Returns a new instance of Lock.



13
14
15
16
17
18
19
20
# File 'lib/etcd/lock.rb', line 13

def initialize(opts={})
  @client = opts[:client]
  @key = opts[:key] || '/global/lock' 
  @value = opts[:value] || 0
  @retries = opts[:retries] || 1
  @retry_interval = opts[:retry_interval] || 1
  @attempts = 0
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



10
11
12
# File 'lib/etcd/lock.rb', line 10

def attempts
  @attempts
end

#clientObject (readonly)

Returns the value of attribute client.



9
10
11
# File 'lib/etcd/lock.rb', line 9

def client
  @client
end

#keyObject (readonly)

Returns the value of attribute key.



9
10
11
# File 'lib/etcd/lock.rb', line 9

def key
  @key
end

#lock_idObject (readonly)

Returns the value of attribute lock_id.



9
10
11
# File 'lib/etcd/lock.rb', line 9

def lock_id
  @lock_id
end

#retriesObject (readonly)

Returns the value of attribute retries.



10
11
12
# File 'lib/etcd/lock.rb', line 10

def retries
  @retries
end

#retry_intervalObject (readonly)

Returns the value of attribute retry_interval.



10
11
12
# File 'lib/etcd/lock.rb', line 10

def retry_interval
  @retry_interval
end

#valueObject (readonly)

Returns the value of attribute value.



9
10
11
# File 'lib/etcd/lock.rb', line 9

def value
  @value
end

Instance Method Details

#acquireObject



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/etcd/lock.rb', line 22

def acquire
  @lock_id =  uuid.generate
  begin
    response = client.test_and_set(key, lock_id, value)
    @attempts = 0
    response
  rescue Exception => e  
    @attempts += 1
    raise AcqusitionFailure, e.message if attempts >= retries
    sleep retry_interval
    acquire
  end
end

#releaseObject



36
37
38
39
40
41
42
# File 'lib/etcd/lock.rb', line 36

def release
  begin
    response = client.test_and_set(key, value, lock_id)
  rescue Exception => e
    raise ReleaseFailure, e.message
  end
end

#uuidObject



44
45
46
# File 'lib/etcd/lock.rb', line 44

def uuid
  @uuid ||= UUID.new
end