Class: PuppetDBQuery::PuppetDB

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/puppetdb_query/puppetdb.rb

Overview

access puppetdb data

Constant Summary collapse

NODES =
"/pdb/query/v4/nodes".freeze
FACTS =
"/pdb/query/v4/facts".freeze

Instance Method Summary collapse

Methods included from Logging

included, #logger, #logger=

Constructor Details

#initialize(host = HOST, port = 443, protocol = "https", nodes = NODES, facts = FACTS) ⇒ PuppetDB

Returns a new instance of PuppetDB.



14
15
16
17
18
# File 'lib/puppetdb_query/puppetdb.rb', line 14

def initialize(host = HOST, port = 443, protocol = "https", nodes = NODES, facts = FACTS)
  @nodes_url = "#{protocol}://#{host}:#{port}#{nodes}"
  @facts_url = "#{protocol}://#{host}:#{port}#{facts}"
  @lock = Mutex.new
end

Instance Method Details

#all_nodesObject

get array of node names



21
22
23
# File 'lib/puppetdb_query/puppetdb.rb', line 21

def all_nodes
  api_nodes.reject { |data| data['deactivated'] }.map { |data| data['certname'] }
end

#api_nodesObject



67
68
69
# File 'lib/puppetdb_query/puppetdb.rb', line 67

def api_nodes
  get_json(@nodes_url, 10)
end

#factsObject

get all nodes with all facts



56
57
58
59
60
61
62
63
64
65
# File 'lib/puppetdb_query/puppetdb.rb', line 56

def facts
  json = get_json(@facts_url, 60)
  result = {}
  json.each do |fact|
    data = result[fact["certname"]]
    result[fact["certname"]] = data = {} unless data
    data[fact["name"]] = fact["value"]
  end
  result
end

#node_propertiesObject

get hash of node update properties



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/puppetdb_query/puppetdb.rb', line 26

def node_properties
  result = {}
  api_nodes.each do |data|
    next if data['deactivated']
    # in '/v3/nodes' we must take 'name'
    name = data['certname']
    values = data.dup
    %w[deactivated certname].each { |key| values.delete(key) }
    result[name] = values
  end
  result
end

#nodes_update_facts_since(timestamp) ⇒ Object

get all nodes that have updated facts



40
41
42
43
44
45
46
# File 'lib/puppetdb_query/puppetdb.rb', line 40

def nodes_update_facts_since(timestamp)
  ts = (timestamp.is_a?(String) ? Time.iso8601(ts) : timestamp)
  node_properties.delete_if do |_k, data|
    # in '/v3/nodes' we must take 'facts-timestamp'
    !data["facts_timestamp"] || Time.iso8601(data["facts_timestamp"]) < ts
  end.keys
end

#single_node_facts(node) ⇒ Object

get hash of facts for given node name



49
50
51
52
53
# File 'lib/puppetdb_query/puppetdb.rb', line 49

def single_node_facts(node)
  json = get_json("#{@nodes_url}/#{node}/facts", 10)
  return nil if json.include?("error")
  Hash[json.map { |data| [data["name"], data["value"]] }]
end