-
Notifications
You must be signed in to change notification settings - Fork 69
/
connection.rb
71 lines (59 loc) · 2.06 KB
/
connection.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require 'puppetdb'
class PuppetDB::Connection
require 'rubygems'
require 'puppetdb/parser'
require 'uri'
require 'puppet'
require 'puppet/util/logging'
include Puppet::Util::Logging
def initialize(host = 'puppetdb', port = 443, use_ssl = true)
@host = host
@port = port
@use_ssl = use_ssl
end
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
# Execute a PuppetDB query
#
# @param endpoint [Symbol] :resources, :facts or :nodes
# @param query [Array] query to execute
# @param options [Hash] specify extract values or http connection
# @return [Array] the results of the query
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
end