class Consul::Client::Agent

Public Instance Methods

check(id) click to toggle source

Public: Returns a check by a given id. Returns: nil if no such check exists, or the check instance with the correct id

# File lib/consul/client/agent.rb, line 81
def check(id)
  c = checks
  c.keep_if {|c| c.check_id == id}.first unless c.nil?
end
checks() click to toggle source
# File lib/consul/client/agent.rb, line 67
def checks
  begin
    resp = _get build_agent_url('checks')
  rescue
    logger.warn('Unable to request all the checks on this through the HTTP API')
    return nil
  end
  # Consul returns id => ConsulServiceObjects.
  s_hash = JSON.parse(resp)
  s_hash.keys.map { |n| Consul::Model::HealthCheck.new.extend(Consul::Model::HealthCheck::Representer).from_hash(s_hash[n]) }
end
deregister(entity) click to toggle source

Public: deregisters an existing ConsulHealthCheck or ConsulService

entity - Consul::Model::HealthCheck or Consul::Model::ConsulService to unregister from this

Returns - the HTTP Response

# File lib/consul/client/agent.rb, line 135
def deregister(entity)
  unless entity.nil?
    raise TypeError unless entity.kind_of? Consul::Model::HealthCheck or entity.kind_of? Consul::Model::Service
    case entity
      when Consul::Model::HealthCheck
        url = build_check_url('deregister')
      else
        url = build_service_url('deregister')
    end
    _get "#{url}/#{entity.id}"
  end
end
describe() click to toggle source

Public: Describes the agent. It is actually the same method as /v1/agent/self

Example:

a = Agent.new
a.describe =>
   <Consul::Model::Agent config=#<Consul::Model::Config bootstrap=true, server=true,
     datacenter="dc1", datadir="/path/to/data", dns_recursor="", dns_recursors=[],
     domain="consul.", log_level="INFO", node_name="MyComputer.local", client_addr="127.0.0.1",
     bind_addr="0.0.0.0", advertise_addr="172.19.12.106", ports={"DNS"=>8600, "HTTP"=>8500, "HTTPS"=>-1,
     "RPC"=>8400, "SerfLan"=>8301, "SerfWan"=>8302, "Server"=>8300}, leave_on_term=false,
     skip_leave_on_int=false, stat_site_addr="", protocol=2, enable_debug=false, verify_incoming=false,
     verify_outgoing=false, ca_file="", cert_file="", key_file="", start_join=[], ui_dir="", pid_file="",
     enable_syslog=false, rejoin_after_leave=false>, member=#<Consul::Model::Member name="MyComputer.local",
     addr="172.19.12.106", port=8301, tags={"bootstrap"=>"1", "build"=>"0.5.0:0c7ca91c", "dc"=>"dc1", "port"=>"8300",
     "role"=>"consul", "vsn"=>"2", "vsn_max"=>"2", "vsn_min"=>"1"}, status=1, protocol_min=1, protocol_max=2,
     protocol_cur=2, delegate_min=2, delegate_max=4, delegate_cur=4>>
 a.describe.config.node_name =>
   "MyComputer.local"
 a.describe.member.name =>
   "MyComputer.local"

Return: Consul::Model::Agent instance that represents this agent.

# File lib/consul/client/agent.rb, line 34
def describe
  begin
    resp = _get build_agent_url('self')
  rescue
    logger.warn('Unable to request all the services on this through the HTTP API')
    return nil
  end
  Consul::Model::Agent.new.extend(Consul::Model::Agent::Representer).from_json(resp)
end
fail(check) click to toggle source

Public: Fails a health check

check - Consul::Model::HealthCheck to pass. Cannot be nil or wrong type

# File lib/consul/client/agent.rb, line 168
def fail(check)
  update_check_status(check, 'fail')
end
maintenance(enable, service = nil, reason = nil) click to toggle source

Public: Enter maintenance mode.

enable - Flag to indicate to enable maintanence mode or not service - Set maintanence for a particular service is set. reason - Optional reason.

# File lib/consul/client/agent.rb, line 177
def maintenance(enable, service = nil, reason = nil)
  if service.nil?
    url = build_agent_url('maintenance')
  else
    if service.instance_of?(Consul::Model::Service)
      service = service.id
    end
    raise ArgumentError.new "Unable to create request for #{service}" unless service.respond_to?(:to_str)
    url = build_service_url("maintenance/#{service}")
  end
  params = {:enable => enable}
  params[:reason] = reason unless reason.nil?
  _get url, params
end
pass(check) click to toggle source

Public: Pass a health check.

check - Consul::Model::HealthCheck to pass. Cannot be nil or wrong type

# File lib/consul/client/agent.rb, line 152
def pass(check)
  update_check_status(check, 'pass')
end
register(entity) click to toggle source

Public: Registers either a service or a Health check with configured consul agent.

entity - Consul::Model::Service or Consul::Model::HealthCheck instance.

Example

agent = Consul::Client::Agent.new('dc1')
# Register a service
agent.register(Consul::Client::Agent::Service.for_name('cat'))
# Register a HealthCheck
agent.register(Consul::Client::HealthCheck.ttl('my_check_name', '15m'))
# Register a service with a Consul Health Check
agent.register(Consul::Client::Agent::Service.for_name('cat', Consul::Client::Agent::Service.ttl_health_check('15m')))

Returns true upon success, false upon failure

# File lib/consul/client/agent.rb, line 107
def register(entity)
  raise TypeError unless entity.kind_of? Consul::Model::HealthCheck or entity.kind_of? Consul::Model::Service
  case entity
    when Consul::Model::HealthCheck
      return register_with_backoff(build_check_url('register'), entity.extend(Consul::Model::HealthCheck::Representer), 0, 3)
    else
      entity = entity.extend(Consul::Model::Service::Representer)
      success, body = _put build_service_url('register'), entity.to_json
      if success
        logger.info("Successfully registered service #{entity.name}.")
        c = check("service:#{entity.name}") unless entity.check.nil?
        unless c.nil?
          # Pass the first health check
          logger.info("Updating status for health check #{c.check_id} to \"pass\".")
          _get build_check_status_url(c.check_id, 'pass')
        end
      else
        logger.warn("Unable to register #{entity}. Reason: #{body}")
      end
      return success
  end
end
service(id) click to toggle source

Public: Returns the service that has the associated name.

Returns: ConsulService if exists, nil if no service by this name exists.

# File lib/consul/client/agent.rb, line 62
def service(id)
  ss = services
  ss.keep_if {|s| s.id == id}.first unless ss.nil?
end
service_check(service_id) click to toggle source

Public: Returns a Health Check for a specific service.

service_id - The ID of the service.

# File lib/consul/client/agent.rb, line 89
def service_check(service_id)
  check("service:#{service_id}")
end
services() click to toggle source

Public: Returns all the services registered with this Agent.

Returns: An array of all the ConsulService(s) registered on this agent.

# File lib/consul/client/agent.rb, line 47
def services
  begin
    resp = _get build_agent_url('services')
  rescue
    logger.warn('Unable to request all the services on this through the HTTP API')
    return nil
  end
  # Consul returns id => ConsulServiceObjects.
  s_hash = JSON.parse(resp)
  s_hash.keys.map { |n| Consul::Model::Service.new.extend(Consul::Model::Service::Representer).from_hash(s_hash[n]) }
end
warn(check) click to toggle source

Public: Warn a health check

check - Consul::Model::HealthCheck to pass. Cannot be nil or wrong type

# File lib/consul/client/agent.rb, line 160
def warn(check)
  update_check_status(check, 'warn')
end

Private Instance Methods

build_agent_url(suffix) click to toggle source

Returns host:port/v1/agent/suffix

# File lib/consul/client/agent.rb, line 348
def build_agent_url(suffix)
  "#{base_versioned_url}/agent/#{suffix}"
end
build_check_status_url(check_id, status) click to toggle source

status : “pass”, “warn”, or “fail”

# File lib/consul/client/agent.rb, line 343
def build_check_status_url(check_id, status)
  build_check_url("#{status}/#{check_id}")
end
build_check_url(suffix) click to toggle source
# File lib/consul/client/agent.rb, line 338
def build_check_url(suffix)
  build_agent_url("check/#{suffix}")
end
build_service_url(suffix) click to toggle source
# File lib/consul/client/agent.rb, line 334
def build_service_url(suffix)
  build_agent_url("service/#{suffix}")
end
register_with_backoff(url, entity, iteration, threshold) click to toggle source

Private: Register a consul entity with the existing agent but attempts and exponentially increasing interval if fails.

url - The url to make the register request through. entity - JSON representation of the entity iteration - The current attempt iteration threshold - Number of attempts to try

# File lib/consul/client/agent.rb, line 314
def register_with_backoff(url, entity, iteration, threshold)
  # Checking a greater iteration just to be on the safe side.
  unless iteration > threshold or threshold <= 0 or iteration < 0
    sleep((1.0/2.0*(2.0**iteration - 1.0)).ceil) if iteration > 0
    success, _ = _put(url, entity.to_json)
    unless success # Unless we successfully registered.
      if threshold == iteration
        logger.error("Unable to complete registration after #{threshold + 1} attempts")
        return false
      else
        # Attempt to register again using the exponential backoff.
        logger.warn("Unable to complete registration after #{iteration + 1} attempts, Retrying up to #{threshold+1} attempts")
        register_with_backoff(url, entity, iteration + 1, threshold)
      end
    end
    return true
  end
  false
end
update_check_status(check, status) click to toggle source

Private: Updates the check with the argument status.

# File lib/consul/client/agent.rb, line 296
def update_check_status(check, status)
  unless check.instance_of?(Consul::Model::HealthCheck) and check.respond_to?(:to_str)
    check = check(check.to_str)
  end
  return false if check.nil?
  raise ArgumentError.new "Illegal Status #{status}" unless status == 'pass' or status == 'warn' or status == 'fail'
  resp = _get build_check_url("#{status}/#{check.check_id}")
  resp.code == 200
end