Class: PuppetX::Consul::ACLBase::BaseClient

Inherits:
Object
  • Object
show all
Defined in:
lib/puppet_x/consul/acl_base.rb

Direct Known Subclasses

ConsulACLPolicyClient, ConsulACLTokenClient

Instance Method Summary collapse

Constructor Details

#initialize(hostname, port, protocol, api_token = nil) ⇒ BaseClient

Returns a new instance of BaseClient.



9
10
11
12
13
14
# File 'lib/puppet_x/consul/acl_base.rb', line 9

def initialize(hostname, port, protocol, api_token = nil)
  @global_uri = URI("#{protocol}://#{hostname}:#{port}/v1/acl")
  @http_client = Net::HTTP.new(@global_uri.host, @global_uri.port)
  @http_client.use_ssl = true if @global_uri.instance_of? URI::HTTPS
  @api_token = api_token
end

Instance Method Details

#delete(path) ⇒ Object



31
32
33
34
35
36
# File 'lib/puppet_x/consul/acl_base.rb', line 31

def delete(path)
  path = @global_uri.request_uri + path
  request = Net::HTTP::Delete.new(path)

  send_request(request, 1, false)
end

#get(path, tries = 1) ⇒ Object



16
17
18
19
20
21
# File 'lib/puppet_x/consul/acl_base.rb', line 16

def get(path, tries = 1)
  path = @global_uri.request_uri + path
  request = Net::HTTP::Get.new(path)

  send_request(request, tries)
end

#put(path, body, tries = 1) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/puppet_x/consul/acl_base.rb', line 23

def put(path, body, tries = 1)
  path = @global_uri.request_uri + path
  request = Net::HTTP::Put.new(path)
  request.body = body.to_json

  send_request(request, tries)
end

#send_request(request, tries = 1, json_response = true) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/puppet_x/consul/acl_base.rb', line 38

def send_request(request, tries = 1, json_response = true)
  response_code = nil
  response = nil

  request['X-Consul-Token'] = @api_token unless @api_token.nil?

  (1..tries).each do |i|
    unless i == 1
      Puppet.debug("retrying Consul API query in #{i} seconds")
      sleep i
    end

    begin
      response = @http_client.request(request)
      response_code = response.code
      break if response_code == '200'
    rescue Errno::ECONNREFUSED => e
      Puppet.debug("#{e.class} #{e.message}")
    end
  end

  if response_code == '200'
    json_response ? JSON.parse(response.body) : response.body
  elsif !response_code.nil?
    raise "Got negative API response (Code: #{response_code}, Response: #{response.body})"
  else
    raise "Connection refused by API after #{tries} tries"
  end
end