Class: Bolt::PuppetDB::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/puppetdb/instance.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config:, project: nil, load_defaults: false) ⇒ Instance

Returns a new instance of Instance.



12
13
14
15
16
17
# File 'lib/bolt/puppetdb/instance.rb', line 12

def initialize(config:, project: nil, load_defaults: false)
  @config      = Bolt::PuppetDB::Config.new(config: config, project: project, load_defaults: load_defaults)
  @bad_urls    = []
  @current_url = nil
  @logger      = Bolt::Logger.logger(self)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



10
11
12
# File 'lib/bolt/puppetdb/instance.rb', line 10

def config
  @config
end

Instance Method Details

#headersObject



139
140
141
142
143
# File 'lib/bolt/puppetdb/instance.rb', line 139

def headers
  headers = { 'Content-Type' => 'application/json' }
  headers['X-Authentication'] = @config.token if @config.token
  headers
end

#http_clientObject



106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/bolt/puppetdb/instance.rb', line 106

def http_client
  return @http if @http
  # lazy-load expensive gem code
  require 'httpclient'
  @logger.trace("Creating HTTP Client")
  @http = HTTPClient.new
  @http.ssl_config.set_client_cert_file(@config.cert, @config.key) if @config.cert
  @http.ssl_config.add_trust_ca(@config.cacert)
  @http.connect_timeout = @config.connect_timeout if @config.connect_timeout
  @http.receive_timeout = @config.read_timeout if @config.read_timeout

  @http
end

#make_query(query, path = nil) ⇒ Object



19
20
21
22
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
49
50
# File 'lib/bolt/puppetdb/instance.rb', line 19

def make_query(query, path = nil)
  body = JSON.generate(query: query)
  url = "#{uri}/pdb/query/v4"
  url += "/#{path}" if path

  begin
    @logger.debug("Sending PuppetDB query to #{url}")
    response = http_client.post(url, body: body, header: headers)
  rescue StandardError => e
    raise Bolt::PuppetDBFailoverError, "Failed to query PuppetDB: #{e}"
  end

  @logger.debug("Got response code #{response.code} from PuppetDB")
  if response.code != 200
    msg = "Failed to query PuppetDB: #{response.body}"
    if response.code == 400
      raise Bolt::PuppetDBError, msg
    else
      raise Bolt::PuppetDBFailoverError, msg
    end
  end

  begin
    JSON.parse(response.body)
  rescue JSON::ParserError
    raise Bolt::PuppetDBError, "Unable to parse response as JSON: #{response.body}"
  end
rescue Bolt::PuppetDBFailoverError => e
  @logger.error("Request to puppetdb at #{@current_url} failed with #{e}.")
  reject_url
  make_query(query, path)
end

#reject_urlObject



120
121
122
123
# File 'lib/bolt/puppetdb/instance.rb', line 120

def reject_url
  @bad_urls << @current_url if @current_url
  @current_url = nil
end

#send_command(command, version, payload) ⇒ Object

Sends a command to PuppetDB using version 1 of the commands API. puppet.com/docs/puppetdb/latest/api/command/v1/commands.html

Parameters:

  • command (String)

    The command to invoke.

  • version (Integer)

    The version of the command to invoke.

  • payload (Hash)

    The payload to send with the command.

Returns:

  • A UUID identifying the submitted command.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/bolt/puppetdb/instance.rb', line 60

def send_command(command, version, payload)
  command = command.dup.force_encoding('utf-8')
  body    = JSON.generate(payload)

  # PDB requires the following query parameters to the POST request.
  # Error early if there's no certname, as PDB does not return a
  # message indicating it's required.
  unless payload['certname']
    raise Bolt::Error.new(
      "Payload must include 'certname', unable to invoke command.",
      'bolt/pdb-command'
    )
  end

  url = uri.tap do |u|
    u.path         = 'pdb/cmd/v1'
    u.query_values = { 'command'  => command,
                       'version'  => version,
                       'certname' => payload['certname'] }
  end

  # Send the command to PDB
  begin
    @logger.debug("Sending PuppetDB command '#{command}' to #{url}")
    response = http_client.post(url.to_s, body: body, header: headers)
  rescue StandardError => e
    raise Bolt::PuppetDBFailoverError, "Failed to invoke PuppetDB command: #{e}"
  end

  @logger.debug("Got response code #{response.code} from PuppetDB")
  if response.code != 200
    raise Bolt::PuppetDBError, "Failed to invoke PuppetDB command: #{response.body}"
  end

  # Return the UUID string from the response body
  begin
    JSON.parse(response.body).fetch('uuid', nil)
  rescue JSON::ParserError
    raise Bolt::PuppetDBError, "Unable to parse response as JSON: #{response.body}"
  end
rescue Bolt::PuppetDBFailoverError => e
  @logger.error("Request to puppetdb at #{@current_url} failed with #{e}.")
  reject_url
  send_command(command, version, payload)
end

#uriObject



125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/bolt/puppetdb/instance.rb', line 125

def uri
  require 'addressable/uri'

  @current_url ||= (@config.server_urls - @bad_urls).first
  unless @current_url
    msg = "Failed to connect to all PuppetDB server_urls: #{@config.server_urls.to_a.join(', ')}."
    raise Bolt::PuppetDBError, msg
  end

  uri = Addressable::URI.parse(@current_url)
  uri.port ||= 8081
  uri
end