Class: PuppetDB::Connection

Inherits:
Object
  • Object
show all
Includes:
Puppet::Util::Logging
Defined in:
lib/puppetdb/connection.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host = 'puppetdb', port = 443, use_ssl = true) ⇒ Connection

Returns a new instance of Connection.



12
13
14
15
16
# File 'lib/puppetdb/connection.rb', line 12

def initialize(host = 'puppetdb', port = 443, use_ssl = true)
  @host = host
  @port = port
  @use_ssl = use_ssl
end

Class Method Details

.check_versionObject



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/puppetdb/connection.rb', line 18

def self.check_version
  require 'puppet/util/puppetdb'
  unless Puppet::Util::Puppetdb.config.respond_to?('server_urls')
    Puppet.warning <<-EOT
It looks like you are using a PuppetDB version < 3.0.
This version of puppetdbquery requires at least PuppetDB 3.0 to work.
Downgrade to puppetdbquery 1.x to use it with PuppetDB 2.x.
EOT
  end
rescue LoadError
end

Instance Method Details

#query(endpoint, query = nil, options = {}, version = :v4) ⇒ Array

Execute a PuppetDB query

Parameters:

  • endpoint (Symbol)

    :resources, :facts or :nodes

  • query (Array) (defaults to: nil)

    query to execute

  • options (Hash) (defaults to: {})

    specify extract values or http connection

Returns:

  • (Array)

    the results of the query



36
37
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
67
68
69
70
# File 'lib/puppetdb/connection.rb', line 36

def query(endpoint, query = nil, options = {}, version = :v4)
  require 'json'

  default_options = {
    :http => nil,   # A HTTP object to be used for the connection
    :extract => nil # An array of fields to extract
  }

  if options.is_a? Hash
    options = default_options.merge options
  else
    Puppet.deprecation_warning 'Specify http object with :http key instead'
    options = default_options.merge(:http => options)
  end
  http = options[:http]

  unless http
    require 'puppet/network/http_pool'
    http = Puppet::Network::HttpPool.http_instance(@host, @port, @use_ssl)
  end
  headers = { 'Accept' => 'application/json' }

  if options[:extract]
    query = PuppetDB::ParserHelper.extract(*Array(options[:extract]), query)
  end

  uri = "/pdb/query/#{version}/#{endpoint}"
  uri += URI.escape "?query=#{query.to_json}" unless query.nil? || query.empty?

  debug("PuppetDB query: #{query.to_json}")

  resp = http.get(uri, headers)
  fail "PuppetDB query error: [#{resp.code}] #{resp.msg}, query: #{query.to_json}" unless resp.is_a?(Net::HTTPSuccess)
  JSON.parse(resp.body)
end