Class: Consul::Client::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/consul/client/service.rb

Overview

Provides cluster coordination features. Do not instantiate this class directly, instead use the appropriate factory methods.

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(name, consul: Consul::Client.v1.http) ⇒ Service

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Service.



9
10
11
12
# File 'lib/consul/client/service.rb', line 9

def initialize(name, consul: Consul::Client.v1.http)
  @name   = name
  @consul = consul
end

Instance Method Details

#lock(key, checks: ["service:#{name}"], &block) ⇒ Object

Creates a session tied to this cluster, then blocks indefinitely until the requested lock can be acquired, then yields. The lock is released and the session destroyed when the block completes.

Parameters:

  • key (String)

    the name of the lock to acquire. This is namespace under the service name and stored directly in the KV store, so make sure it does not conflict with other names. For instance, the leader lock for the web service would be stored at /kv/web/leader.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/consul/client/service.rb', line 23

def lock(key, checks: ["service:#{name}"], &block)
  session = consul.put("/session/create",
    LockDelay: '3s',
    Checks:    ["serfHealth"] + checks
  )["ID"]
  loop do
    locked = consul.put("/kv/#{name}/#{key}?acquire=#{session}")

    if locked
      begin
        block.call
      ensure
        consul.put("/kv/#{name}/#{key}?release=#{session}")
        consul.put("/session/destroy/#{session}")
      end
      return
    else
      consul.get_while("/kv/#{name}/#{key}") do |body|
        body[0]["Session"]
      end
    end
    # TODO: Figure out why long poll doesn't work.
    # https://gist.github.com/xaviershay/30128b968bde0e2d3e0b/edit
    sleep 3
  end
end

#wait_until_healthy!(min_nodes: 1) ⇒ Object

Block indefinitely until the cluster is healthy.

Parameters:

  • min_nodes (Integer) (defaults to: 1)

    minimum number of nodes required to be healthy for the cluster as a whole to be considered healthy. This method will block until there is at least one more than this number, assuming that the caller is about to terminate.



56
57
58
59
60
# File 'lib/consul/client/service.rb', line 56

def wait_until_healthy!(min_nodes: 1)
  consul.get_while("/health/service/#{name}?passing") do |data|
    data.size <= min_nodes
  end
end