Module: Etcd::Mod::Lock

Defined in:
lib/etcd/mod/lock.rb

Overview

implement etcd lock module

Instance Method Summary collapse

Instance Method Details

#acquire_lock(key, ttl, opts = {}) ⇒ Object



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

def acquire_lock(key, ttl, opts = {})
  path = mod_lock_endpoint + key + "?ttl=#{ttl}"
  timeout = opts[:timeout] || 60
  Timeout.timeout(timeout) do
    return api_execute(path, :post, params: opts).body
  end
end

#delete_lock(key, opts = {}) ⇒ Object Also known as: release_lock



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

def delete_lock(key, opts = {})
  unless opts.key?(:index) || opts.key?(:value)
    fail ArgumentError, 'You must pass index or value'
  end
  api_execute(mod_lock_endpoint + key, :delete, params: opts)
end

#get_lock(key, opts = {}) ⇒ Object Also known as: retrive_lock



32
33
34
# File 'lib/etcd/mod/lock.rb', line 32

def get_lock(key, opts = {})
  api_execute(mod_lock_endpoint + key, :get, params: opts).body
end

#lock(key, ttl, opts = {}) ⇒ Object

rubocop:disable RescueException



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/etcd/mod/lock.rb', line 44

def lock(key, ttl, opts = {})
  key = "/" + key unless key.start_with? '/'
  lock_index = acquire_lock(key, ttl, opts)
  begin
    yield key
  rescue Exception => e
    raise e
  ensure
    delete_lock(key, index: lock_index)
  end
end

#mod_lock_endpointObject



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

def mod_lock_endpoint
  '/mod/v2/lock'
end

#renew_lock(key, ttl, opts = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/etcd/mod/lock.rb', line 21

def renew_lock(key, ttl, opts = {})
  unless opts.key?(:index) || opts.key?(:value)
    fail ArgumentError, 'You mast pass index or value'
  end
  path = mod_lock_endpoint + key + "?ttl=#{ttl}"
  timeout = opts[:timeout] || 60
  Timeout.timeout(timeout) do
    api_execute(path, :put, params: opts).body
  end
end