Class: Diplomat::Lock

Inherits:
RestClient show all
Includes:
ApiOptions
Defined in:
lib/diplomat/lock.rb

Overview

Methods for interacting with the Consul lock API endpoint

Instance Method Summary collapse

Methods included from ApiOptions

#check_acl_token, #use_cas, #use_consistency, #valid_transaction_verbs, #valid_value_transactions

Methods inherited from RestClient

access_method?, #concat_url, #initialize, method_missing, respond_to?, respond_to_missing?, #use_named_parameter

Constructor Details

This class inherits a constructor from Diplomat::RestClient

Instance Method Details

#acquire(key, session, value = nil, options = nil) ⇒ Boolean

Acquire a lock rubocop:disable AbcSize

Parameters:

  • key (String)

    the key

  • session (String)

    the session, generated from Diplomat::Session.create

  • value (String) (defaults to: nil)

    the value for the key

  • options (Hash) (defaults to: nil)

    :dc string for dc specific query

Returns:

  • (Boolean)

    If the lock was acquired



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/diplomat/lock.rb', line 15

def acquire(key, session, value = nil, options = nil)
  raw = @conn.put do |req|
    url = ["/v1/kv/#{key}"]
    url += use_named_parameter('acquire', session)
    url += check_acl_token
    url += use_named_parameter('dc', options[:dc]) if options && options[:dc]

    req.url concat_url url
    req.body = value unless value.nil?
  end
  raw.body.chomp == 'true'
end

#release(key, session, options = nil) ⇒ nil

Release a lock

Parameters:

  • key (String)

    the key

  • session (String)

    the session, generated from Diplomat::Session.create

  • options (Hash) (defaults to: nil)

    :dc string for dc specific query

Returns:

  • (nil)


50
51
52
53
54
55
56
57
58
59
60
# File 'lib/diplomat/lock.rb', line 50

def release(key, session, options = nil)
  raw = @conn.put do |req|
    url = ["/v1/kv/#{key}"]
    url += use_named_parameter('release', session)
    url += check_acl_token
    url += use_named_parameter('dc', options[:dc]) if options && options[:dc]

    req.url concat_url url
  end
  raw.body
end

#wait_to_acquire(key, session, value = nil, check_interval = 10, options = nil) ⇒ Boolean

wait to aquire a lock

Parameters:

  • key (String)

    the key

  • session (String)

    the session, generated from Diplomat::Session.create

  • value (String) (defaults to: nil)

    the value for the key

  • check_interval (Integer) (defaults to: 10)

    number of seconds to wait between retries

  • options (Hash) (defaults to: nil)

    :dc string for dc specific query

Returns:

  • (Boolean)

    If the lock was acquired



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

def wait_to_acquire(key, session, value = nil, check_interval = 10, options = nil)
  acquired = false
  until acquired
    acquired = acquire(key, session, value, options)
    sleep(check_interval) unless acquired
    return true if acquired
  end
end