repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/graph/simple_graph.rb | lib/puppet/graph/simple_graph.rb | # frozen_string_literal: true
require_relative '../../puppet/external/dot'
require_relative '../../puppet/relationship'
require 'set'
# A hopefully-faster graph class to replace the use of GRATR.
class Puppet::Graph::SimpleGraph
include Puppet::Util::PsychSupport
#
# All public methods of this class must maintain (assume ^ ensure) the following invariants, where "=~=" means
# equiv. up to order:
#
# @in_to.keys =~= @out_to.keys =~= all vertices
# @in_to.values.collect { |x| x.values }.flatten =~= @out_from.values.collect { |x| x.values }.flatten =~= all edges
# @in_to[v1][v2] =~= @out_from[v2][v1] =~= all edges from v1 to v2
# @in_to [v].keys =~= vertices with edges leading to v
# @out_from[v].keys =~= vertices with edges leading from v
# no operation may shed reference loops (for gc)
# recursive operation must scale with the depth of the spanning trees, or better (e.g. no recursion over the set
# of all vertices, etc.)
#
# This class is intended to be used with DAGs. However, if the
# graph has a cycle, it will not cause non-termination of any of the
# algorithms.
#
def initialize
@in_to = {}
@out_from = {}
@upstream_from = {}
@downstream_from = {}
end
# Clear our graph.
def clear
@in_to.clear
@out_from.clear
@upstream_from.clear
@downstream_from.clear
end
# Which resources the given resource depends on.
def dependencies(resource)
vertex?(resource) ? upstream_from_vertex(resource).keys : []
end
# Which resources depend upon the given resource.
def dependents(resource)
vertex?(resource) ? downstream_from_vertex(resource).keys : []
end
# Whether our graph is directed. Always true. Used to produce dot files.
def directed?
true
end
# Determine all of the leaf nodes below a given vertex.
def leaves(vertex, direction = :out)
tree_from_vertex(vertex, direction).keys.find_all { |c| adjacent(c, :direction => direction).empty? }
end
# Collect all of the edges that the passed events match. Returns
# an array of edges.
def matching_edges(event, base = nil)
source = base || event.resource
unless vertex?(source)
Puppet.warning _("Got an event from invalid vertex %{source}") % { source: source.ref }
return []
end
# Get all of the edges that this vertex should forward events
# to, which is the same thing as saying all edges directly below
# This vertex in the graph.
@out_from[source].values.flatten.find_all { |edge| edge.match?(event.name) }
end
# Return a reversed version of this graph.
def reversal
result = self.class.new
vertices.each { |vertex| result.add_vertex(vertex) }
edges.each do |edge|
result.add_edge edge.class.new(edge.target, edge.source, edge.label)
end
result
end
# Return the size of the graph.
def size
vertices.size
end
def to_a
vertices
end
# This is a simple implementation of Tarjan's algorithm to find strongly
# connected components in the graph; this is a fairly ugly implementation,
# because I can't just decorate the vertices themselves.
#
# This method has an unhealthy relationship with the find_cycles_in_graph
# method below, which contains the knowledge of how the state object is
# maintained.
def tarjan(root, s)
# initialize the recursion stack we use to work around the nasty lack of a
# decent Ruby stack.
recur = [{ :node => root }]
until recur.empty?
frame = recur.last
vertex = frame[:node]
case frame[:step]
when nil then
s[:index][vertex] = s[:number]
s[:lowlink][vertex] = s[:number]
s[:number] = s[:number] + 1
s[:stack].push(vertex)
s[:seen][vertex] = true
frame[:children] = adjacent(vertex)
frame[:step] = :children
when :children then
if frame[:children].length > 0 then
child = frame[:children].shift
if !s[:index][child] then
# Never seen, need to recurse.
frame[:step] = :after_recursion
frame[:child] = child
recur.push({ :node => child })
elsif s[:seen][child] then
s[:lowlink][vertex] = [s[:lowlink][vertex], s[:index][child]].min
end
else
if s[:lowlink][vertex] == s[:index][vertex] then
this_scc = []
loop do
top = s[:stack].pop
s[:seen][top] = false
this_scc << top
break if top == vertex
end
s[:scc] << this_scc
end
recur.pop # done with this node, finally.
end
when :after_recursion then
s[:lowlink][vertex] = [s[:lowlink][vertex], s[:lowlink][frame[:child]]].min
frame[:step] = :children
else
fail "#{frame[:step]} is an unknown step"
end
end
end
# Find all cycles in the graph by detecting all the strongly connected
# components, then eliminating everything with a size of one as
# uninteresting - which it is, because it can't be a cycle. :)
#
# This has an unhealthy relationship with the 'tarjan' method above, which
# it uses to implement the detection of strongly connected components.
def find_cycles_in_graph
state = {
:number => 0, :index => {}, :lowlink => {}, :scc => [],
:stack => [], :seen => {}
}
# we usually have a disconnected graph, must walk all possible roots
vertices.each do |vertex|
unless state[:index][vertex] then
tarjan vertex, state
end
end
# To provide consistent results to the user, given that a hash is never
# assured to return the same order, and given our graph processing is
# based on hash tables, we need to sort the cycles internally, as well as
# the set of cycles.
#
# Given we are in a failure state here, any extra cost is more or less
# irrelevant compared to the cost of a fix - which is on a human
# time-scale.
state[:scc].select do |component|
multi_vertex_component?(component) || single_vertex_referring_to_self?(component)
end.map(&:sort).sort
end
# Perform a BFS on the sub graph representing the cycle, with a view to
# generating a sufficient set of paths to report the cycle meaningfully, and
# ideally usefully, for the end user.
#
# BFS is preferred because it will generally report the shortest paths
# through the graph first, which are more likely to be interesting to the
# user. I think; it would be interesting to verify that. --daniel 2011-01-23
def paths_in_cycle(cycle, max_paths = 1)
# TRANSLATORS "negative or zero" refers to the count of paths
raise ArgumentError, _("negative or zero max_paths") if max_paths < 1
# Calculate our filtered outbound vertex lists...
adj = {}
cycle.each do |vertex|
adj[vertex] = adjacent(vertex).select { |s| cycle.member? s }
end
found = []
# frame struct is vertex, [path]
stack = [[cycle.first, []]]
while frame = stack.shift # rubocop:disable Lint/AssignmentInCondition
if frame[1].member?(frame[0]) then
found << frame[1] + [frame[0]]
break if found.length >= max_paths
else
adj[frame[0]].each do |to|
stack.push [to, frame[1] + [frame[0]]]
end
end
end
found.sort
end
# @return [Array] array of dependency cycles (arrays)
def report_cycles_in_graph
cycles = find_cycles_in_graph
number_of_cycles = cycles.length
return if number_of_cycles == 0
message = n_("Found %{num} dependency cycle:\n", "Found %{num} dependency cycles:\n", number_of_cycles) % { num: number_of_cycles }
cycles.each do |cycle|
paths = paths_in_cycle(cycle)
message += paths.map { |path| '(' + path.join(' => ') + ')' }.join('\n') + '\n'
end
if Puppet[:graph] then
filename = write_cycles_to_graph(cycles)
message += _("Cycle graph written to %{filename}.") % { filename: filename }
else
# TRANSLATORS '--graph' refers to a command line option and OmniGraffle and GraphViz are program names and should not be translated
message += _("Try the '--graph' option and opening the resulting '.dot' file in OmniGraffle or GraphViz")
end
Puppet.err(message)
cycles
end
def write_cycles_to_graph(cycles)
# This does not use the DOT graph library, just writes the content
# directly. Given the complexity of this, there didn't seem much point
# using a heavy library to generate exactly the same content. --daniel 2011-01-27
graph = ["digraph Resource_Cycles {"]
graph << ' label = "Resource Cycles"'
cycles.each do |cycle|
paths_in_cycle(cycle, 10).each do |path|
graph << path.map { |v| '"' + v.to_s.gsub(/"/, '\\"') + '"' }.join(" -> ")
end
end
graph << '}'
filename = File.join(Puppet[:graphdir], "cycles.dot")
# DOT files are assumed to be UTF-8 by default - http://www.graphviz.org/doc/info/lang.html
File.open(filename, "w:UTF-8") { |f| f.puts graph }
filename
end
# Add a new vertex to the graph.
def add_vertex(vertex)
@in_to[vertex] ||= {}
@out_from[vertex] ||= {}
end
# Remove a vertex from the graph.
def remove_vertex!(v)
return unless vertex?(v)
@upstream_from.clear
@downstream_from.clear
(@in_to[v].values + @out_from[v].values).flatten.each { |e| remove_edge!(e) }
@in_to.delete(v)
@out_from.delete(v)
end
# Test whether a given vertex is in the graph.
def vertex?(v)
@in_to.include?(v)
end
# Return a list of all vertices.
def vertices
@in_to.keys
end
# Add a new edge. The graph user has to create the edge instance,
# since they have to specify what kind of edge it is.
def add_edge(e, *a)
return add_relationship(e, *a) unless a.empty?
e = Puppet::Relationship.from_data_hash(e) if e.is_a?(Hash)
@upstream_from.clear
@downstream_from.clear
add_vertex(e.source)
add_vertex(e.target)
# Avoid multiple lookups here. This code is performance critical
arr = (@in_to[e.target][e.source] ||= [])
arr << e unless arr.include?(e)
arr = (@out_from[e.source][e.target] ||= [])
arr << e unless arr.include?(e)
end
def add_relationship(source, target, label = nil)
add_edge Puppet::Relationship.new(source, target, label)
end
# Find all matching edges.
def edges_between(source, target)
(@out_from[source] || {})[target] || []
end
# Is there an edge between the two vertices?
def edge?(source, target)
vertex?(source) and vertex?(target) and @out_from[source][target]
end
def edges
@in_to.values.collect(&:values).flatten
end
def each_edge
@in_to.each { |_t, ns| ns.each { |_s, es| es.each { |e| yield e } } }
end
# Remove an edge from our graph.
def remove_edge!(e)
if edge?(e.source, e.target)
@upstream_from.clear
@downstream_from.clear
@in_to[e.target].delete e.source if (@in_to[e.target][e.source] -= [e]).empty?
@out_from[e.source].delete e.target if (@out_from[e.source][e.target] -= [e]).empty?
end
end
# Find adjacent edges.
def adjacent(v, options = {})
ns = (options[:direction] == :in) ? @in_to[v] : @out_from[v]
return [] unless ns
(options[:type] == :edges) ? ns.values.flatten : ns.keys
end
# Just walk the tree and pass each edge.
def walk(source, direction)
# Use an iterative, breadth-first traversal of the graph. One could do
# this recursively, but Ruby's slow function calls and even slower
# recursion make the shorter, recursive algorithm cost-prohibitive.
stack = [source]
seen = Set.new
until stack.empty?
node = stack.shift
next if seen.member? node
connected = adjacent(node, :direction => direction)
connected.each do |target|
yield node, target
end
stack.concat(connected)
seen << node
end
end
# A different way of walking a tree, and a much faster way than the
# one that comes with GRATR.
def tree_from_vertex(start, direction = :out)
predecessor = {}
walk(start, direction) do |parent, child|
predecessor[child] = parent
end
predecessor
end
def downstream_from_vertex(v)
return @downstream_from[v] if @downstream_from[v]
result = @downstream_from[v] = {}
@out_from[v].keys.each do |node|
result[node] = 1
result.update(downstream_from_vertex(node))
end
result
end
def direct_dependents_of(v)
(@out_from[v] || {}).keys
end
def upstream_from_vertex(v)
return @upstream_from[v] if @upstream_from[v]
result = @upstream_from[v] = {}
@in_to[v].keys.each do |node|
result[node] = 1
result.update(upstream_from_vertex(node))
end
result
end
def direct_dependencies_of(v)
(@in_to[v] || {}).keys
end
# Return an array of the edge-sets between a series of n+1 vertices (f=v0,v1,v2...t=vn)
# connecting the two given vertices. The ith edge set is an array containing all the
# edges between v(i) and v(i+1); these are (by definition) never empty.
#
# * if f == t, the list is empty
# * if they are adjacent the result is an array consisting of
# a single array (the edges from f to t)
# * and so on by induction on a vertex m between them
# * if there is no path from f to t, the result is nil
#
# This implementation is not particularly efficient; it's used in testing where clarity
# is more important than last-mile efficiency.
#
def path_between(f, t)
if f == t
[]
elsif direct_dependents_of(f).include?(t)
[edges_between(f, t)]
elsif dependents(f).include?(t)
m = (dependents(f) & direct_dependencies_of(t)).first
path_between(f, m) + path_between(m, t)
else
nil
end
end
# LAK:FIXME This is just a paste of the GRATR code with slight modifications.
# Return a DOT::DOTDigraph for directed graphs or a DOT::DOTSubgraph for an
# undirected Graph. _params_ can contain any graph property specified in
# rdot.rb. If an edge or vertex label is a kind of Hash then the keys
# which match +dot+ properties will be used as well.
def to_dot_graph(params = {})
params['name'] ||= self.class.name.tr(':', '_')
fontsize = params['fontsize'] || '8'
graph = (directed? ? DOT::DOTDigraph : DOT::DOTSubgraph).new(params)
edge_klass = directed? ? DOT::DOTDirectedEdge : DOT::DOTEdge
vertices.each do |v|
name = v.ref
params = { 'name' => stringify(name),
'fontsize' => fontsize,
'label' => name }
v_label = v.ref
params.merge!(v_label) if v_label and v_label.is_a? Hash
graph << DOT::DOTNode.new(params)
end
edges.each do |e|
params = { 'from' => stringify(e.source.ref),
'to' => stringify(e.target.ref),
'fontsize' => fontsize }
e_label = e.ref
params.merge!(e_label) if e_label and e_label.is_a? Hash
graph << edge_klass.new(params)
end
graph
end
def stringify(s)
%("#{s.gsub('"', '\\"')}")
end
# Output the dot format as a string
def to_dot(params = {}) to_dot_graph(params).to_s; end
# Produce the graph files if requested.
def write_graph(name)
return unless Puppet[:graph]
file = File.join(Puppet[:graphdir], "#{name}.dot")
# DOT files are assumed to be UTF-8 by default - http://www.graphviz.org/doc/info/lang.html
File.open(file, "w:UTF-8") { |f|
f.puts to_dot("name" => name.to_s.capitalize)
}
end
# This flag may be set to true to use the new YAML serialization
# format (where @vertices is a simple list of vertices rather than a
# list of VertexWrapper objects). Deserialization supports both
# formats regardless of the setting of this flag.
class << self
attr_accessor :use_new_yaml_format
end
self.use_new_yaml_format = false
def initialize_from_hash(hash)
initialize
vertices = hash['vertices']
edges = hash['edges']
if vertices.is_a?(Hash)
# Support old (2.6) format
vertices = vertices.keys
end
vertices.each { |v| add_vertex(v) } unless vertices.nil?
edges.each { |e| add_edge(e) } unless edges.nil?
end
def to_data_hash
hash = { 'edges' => edges.map(&:to_data_hash) }
hash['vertices'] = if self.class.use_new_yaml_format
vertices
else
# Represented in YAML using the old (version 2.6) format.
result = {}
vertices.each do |vertex|
adjacencies = {}
[:in, :out].each do |direction|
direction_hash = {}
adjacencies[direction.to_s] = direction_hash
adjacent(vertex, :direction => direction, :type => :edges).each do |edge|
other_vertex = direction == :in ? edge.source : edge.target
(direction_hash[other_vertex.to_s] ||= []) << edge
end
direction_hash.each_pair { |key, edges| direction_hash[key] = edges.uniq.map(&:to_data_hash) }
end
vname = vertex.to_s
result[vname] = { 'adjacencies' => adjacencies, 'vertex' => vname }
end
result
end
hash
end
def multi_vertex_component?(component)
component.length > 1
end
private :multi_vertex_component?
def single_vertex_referring_to_self?(component)
if component.length == 1
vertex = component[0]
adjacent(vertex).include?(vertex)
else
false
end
end
private :single_vertex_referring_to_self?
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/graph/relationship_graph.rb | lib/puppet/graph/relationship_graph.rb | # frozen_string_literal: true
# The relationship graph is the final form of a puppet catalog in
# which all dependency edges are explicitly in the graph. This form of the
# catalog is used to traverse the graph in the order in which resources are
# managed.
#
# @api private
class Puppet::Graph::RelationshipGraph < Puppet::Graph::SimpleGraph
attr_reader :blockers
def initialize(prioritizer)
super()
@prioritizer = prioritizer
@ready = Puppet::Graph::RbTreeMap.new
@generated = {}
@done = {}
@blockers = {}
@providerless_types = []
end
def populate_from(catalog)
add_all_resources_as_vertices(catalog)
build_manual_dependencies
build_autorelation_dependencies(catalog)
write_graph(:relationships) if catalog.host_config?
replace_containers_with_anchors(catalog)
write_graph(:expanded_relationships) if catalog.host_config?
end
def add_vertex(vertex, priority = nil)
super(vertex)
if priority
@prioritizer.record_priority_for(vertex, priority)
else
@prioritizer.generate_priority_for(vertex)
end
end
def add_relationship(f, t, label = nil)
super(f, t, label)
@ready.delete(@prioritizer.priority_of(t))
end
def remove_vertex!(vertex)
super
@prioritizer.forget(vertex)
end
def resource_priority(resource)
@prioritizer.priority_of(resource)
end
# Enqueue the initial set of resources, those with no dependencies.
def enqueue_roots
vertices.each do |v|
@blockers[v] = direct_dependencies_of(v).length
enqueue(v) if @blockers[v] == 0
end
end
# Decrement the blocker count for the resource by 1. If the number of
# blockers is unknown, count them and THEN decrement by 1.
def unblock(resource)
@blockers[resource] ||= direct_dependencies_of(resource).select { |r2| !@done[r2] }.length
if @blockers[resource] > 0
@blockers[resource] -= 1
else
resource.warning _("appears to have a negative number of dependencies")
end
@blockers[resource] <= 0
end
def clear_blockers
@blockers.clear
end
def enqueue(*resources)
resources.each do |resource|
@ready[@prioritizer.priority_of(resource)] = resource
end
end
def finish(resource)
direct_dependents_of(resource).each do |v|
enqueue(v) if unblock(v)
end
@done[resource] = true
end
def next_resource
@ready.delete_min
end
def traverse(options = {}, &block)
continue_while = options[:while] || -> { true }
pre_process = options[:pre_process] || ->(resource) {}
overly_deferred_resource_handler = options[:overly_deferred_resource_handler] || ->(resource) {}
canceled_resource_handler = options[:canceled_resource_handler] || ->(resource) {}
teardown = options[:teardown] || -> {}
graph_cycle_handler = options[:graph_cycle_handler] || -> { [] }
cycles = report_cycles_in_graph
if cycles
graph_cycle_handler.call(cycles)
end
enqueue_roots
deferred_resources = []
while continue_while.call() && (resource = next_resource)
if resource.suitable?
made_progress = true
pre_process.call(resource)
yield resource
finish(resource)
else
deferred_resources << resource
end
next unless @ready.empty? and deferred_resources.any?
if made_progress
enqueue(*deferred_resources)
else
deferred_resources.each do |res|
overly_deferred_resource_handler.call(res)
finish(res)
end
end
made_progress = false
deferred_resources = []
end
unless continue_while.call()
while (resource = next_resource)
canceled_resource_handler.call(resource)
finish(resource)
end
end
teardown.call()
end
private
def add_all_resources_as_vertices(catalog)
catalog.resources.each do |vertex|
add_vertex(vertex)
end
end
def build_manual_dependencies
vertices.each do |vertex|
vertex.builddepends.each do |edge|
add_edge(edge)
end
end
end
def build_autorelation_dependencies(catalog)
vertices.each do |vertex|
[:require, :subscribe].each do |rel_type|
vertex.send("auto#{rel_type}".to_sym, catalog).each do |edge|
# don't let automatic relationships conflict with manual ones.
next if edge?(edge.source, edge.target)
if edge?(edge.target, edge.source)
vertex.debug "Skipping automatic relationship with #{edge.source}"
else
vertex.debug "Adding auto#{rel_type} relationship with #{edge.source}"
if rel_type == :require
edge.event = :NONE
else
edge.callback = :refresh
edge.event = :ALL_EVENTS
end
add_edge(edge)
end
end
end
[:before, :notify].each do |rel_type|
vertex.send("auto#{rel_type}".to_sym, catalog).each do |edge|
# don't let automatic relationships conflict with manual ones.
next if edge?(edge.target, edge.source)
if edge?(edge.source, edge.target)
vertex.debug "Skipping automatic relationship with #{edge.target}"
else
vertex.debug "Adding auto#{rel_type} relationship with #{edge.target}"
if rel_type == :before
edge.event = :NONE
else
edge.callback = :refresh
edge.event = :ALL_EVENTS
end
add_edge(edge)
end
end
end
end
end
# Impose our container information on another graph by using it
# to replace any container vertices X with a pair of vertices
# { admissible_X and completed_X } such that
#
# 0) completed_X depends on admissible_X
# 1) contents of X each depend on admissible_X
# 2) completed_X depends on each on the contents of X
# 3) everything which depended on X depends on completed_X
# 4) admissible_X depends on everything X depended on
# 5) the containers and their edges must be removed
#
# Note that this requires attention to the possible case of containers
# which contain or depend on other containers, but has the advantage
# that the number of new edges created scales linearly with the number
# of contained vertices regardless of how containers are related;
# alternatives such as replacing container-edges with content-edges
# scale as the product of the number of external dependencies, which is
# to say geometrically in the case of nested / chained containers.
#
Default_label = { :callback => :refresh, :event => :ALL_EVENTS }
def replace_containers_with_anchors(catalog)
stage_class = Puppet::Type.type(:stage)
whit_class = Puppet::Type.type(:whit)
component_class = Puppet::Type.type(:component)
containers = catalog.resources.find_all { |v| (v.is_a?(component_class) or v.is_a?(stage_class)) and vertex?(v) }
#
# These two hashes comprise the aforementioned attention to the possible
# case of containers that contain / depend on other containers; they map
# containers to their sentinels but pass other vertices through. Thus we
# can "do the right thing" for references to other vertices that may or
# may not be containers.
#
admissible = Hash.new { |_h, k| k }
completed = Hash.new { |_h, k| k }
containers.each { |x|
admissible[x] = whit_class.new(:name => "admissible_#{x.ref}", :catalog => catalog)
completed[x] = whit_class.new(:name => "completed_#{x.ref}", :catalog => catalog)
# This copies the original container's tags over to the two anchor whits.
# Without this, tags are not propagated to the container's resources.
admissible[x].set_tags(x)
completed[x].set_tags(x)
priority = @prioritizer.priority_of(x)
add_vertex(admissible[x], priority)
add_vertex(completed[x], priority)
}
#
# Implement the six requirements listed above
#
containers.each { |x|
contents = catalog.adjacent(x, :direction => :out)
add_edge(admissible[x], completed[x]) if contents.empty? # (0)
contents.each { |v|
add_edge(admissible[x], admissible[v], Default_label) # (1)
add_edge(completed[v], completed[x], Default_label) # (2)
}
# (3) & (5)
adjacent(x, :direction => :in, :type => :edges).each { |e|
add_edge(completed[e.source], admissible[x], e.label)
remove_edge! e
}
# (4) & (5)
adjacent(x, :direction => :out, :type => :edges).each { |e|
add_edge(completed[x], admissible[e.target], e.label)
remove_edge! e
}
}
containers.each { |x| remove_vertex! x } # (5)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/graph/prioritizer.rb | lib/puppet/graph/prioritizer.rb | # frozen_string_literal: true
# Base, template method, class for Prioritizers. This provides the basic
# tracking facilities used.
#
# @api private
class Puppet::Graph::Prioritizer
def initialize
@priority = {}
end
def forget(key)
@priority.delete(key)
end
def record_priority_for(key, priority)
@priority[key] = priority
end
def generate_priority_for(key)
raise NotImplementedError
end
def generate_priority_contained_in(container, key)
raise NotImplementedError
end
def priority_of(key)
@priority[key]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/graph/key.rb | lib/puppet/graph/key.rb | # frozen_string_literal: true
# Sequential, nestable keys for tracking order of insertion in "the graph"
# @api private
class Puppet::Graph::Key
include Comparable
attr_reader :value
protected :value
def initialize(value = [0])
@value = value
end
def next
next_values = @value.clone
next_values[-1] += 1
Puppet::Graph::Key.new(next_values)
end
def down
Puppet::Graph::Key.new(@value + [0])
end
def <=>(other)
@value <=> other.value
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/enum_setting.rb | lib/puppet/settings/enum_setting.rb | # frozen_string_literal: true
class Puppet::Settings::EnumSetting < Puppet::Settings::BaseSetting
attr_accessor :values
def type
:enum
end
def munge(value)
if values.include?(value)
value
else
raise Puppet::Settings::ValidationError,
_("Invalid value '%{value}' for parameter %{name}. Allowed values are '%{allowed_values}'") % { value: value, name: @name, allowed_values: values.join("', '") }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/priority_setting.rb | lib/puppet/settings/priority_setting.rb | # frozen_string_literal: true
require_relative '../../puppet/settings/base_setting'
# A setting that represents a scheduling priority, and evaluates to an
# OS-specific priority level.
class Puppet::Settings::PrioritySetting < Puppet::Settings::BaseSetting
PRIORITY_MAP =
if Puppet::Util::Platform.windows?
require_relative '../../puppet/util/windows/process'
require_relative '../../puppet/ffi/windows/constants'
{
:high => Puppet::FFI::Windows::Constants::HIGH_PRIORITY_CLASS,
:normal => Puppet::FFI::Windows::Constants::NORMAL_PRIORITY_CLASS,
:low => Puppet::FFI::Windows::Constants::BELOW_NORMAL_PRIORITY_CLASS,
:idle => Puppet::FFI::Windows::Constants::IDLE_PRIORITY_CLASS
}
else
{
:high => -10,
:normal => 0,
:low => 10,
:idle => 19
}
end
def type
:priority
end
def munge(value)
return unless value
if value.is_a?(Integer)
value
elsif value.is_a?(String) and value =~ /\d+/
value.to_i
elsif value.is_a?(String) and PRIORITY_MAP[value.to_sym]
PRIORITY_MAP[value.to_sym]
else
raise Puppet::Settings::ValidationError, _("Invalid priority format '%{value}' for parameter: %{name}") % { value: value.inspect, name: @name }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/base_setting.rb | lib/puppet/settings/base_setting.rb | # frozen_string_literal: true
require 'set'
require_relative '../../puppet/settings/errors'
# The base setting type
class Puppet::Settings::BaseSetting
attr_writer :default
attr_accessor :name, :desc, :section
attr_reader :short, :deprecated, :call_hook
# Hooks are called during different parts of the settings lifecycle:
#
# * :on_write_only - This is the default hook type. The hook will be called
# if its value is set in `main` or programmatically. If its value is set in
# a section that doesn't match the application's run mode, it will be
# ignored entirely. If the section does match the run mode, the value will
# be used, but the hook will not be called!
#
# * :on_define_and_write - The hook behaves the same as above, except it is
# also called immediately when the setting is defined in
# {Puppet::Settings.define_settings}. In that case, the hook receives the
# default value as specified.
#
# * :on_initialize_and_write - The hook will be called if the value is set in
# `main`, the section that matches the run mode, or programmatically.
#
HOOK_TYPES = Set.new([:on_define_and_write, :on_initialize_and_write, :on_write_only]).freeze
def self.available_call_hook_values
HOOK_TYPES.to_a
end
# Registers a hook to be called later based on the type of hook specified in `value`.
#
# @param value [Symbol] One of {HOOK_TYPES}
def call_hook=(value)
if value.nil?
# TRANSLATORS ':%{name}', ':call_hook', and ':on_write_only' should not be translated
Puppet.warning _("Setting :%{name} :call_hook is nil, defaulting to :on_write_only") % { name: name }
value = :on_write_only
end
unless HOOK_TYPES.include?(value)
# TRANSLATORS 'call_hook' is a Puppet option name and should not be translated
raise ArgumentError, _("Invalid option %{value} for call_hook") % { value: value }
end
@call_hook = value
end
# @see {HOOK_TYPES}
def call_hook_on_define?
call_hook == :on_define_and_write
end
# @see {HOOK_TYPES}
def call_hook_on_initialize?
call_hook == :on_initialize_and_write
end
# get the arguments in getopt format
def getopt_args
if short
[["--#{name}", "-#{short}", GetoptLong::REQUIRED_ARGUMENT]]
else
[["--#{name}", GetoptLong::REQUIRED_ARGUMENT]]
end
end
# get the arguments in OptionParser format
def optparse_args
if short
["--#{name}", "-#{short}", desc, :REQUIRED]
else
["--#{name}", desc, :REQUIRED]
end
end
def hook=(block)
@has_hook = true
meta_def :handle, &block
end
def has_hook?
@has_hook
end
# Create the new element. Pretty much just sets the name.
def initialize(args = {})
@settings = args.delete(:settings)
unless @settings
raise ArgumentError, "You must refer to a settings object"
end
# explicitly set name prior to calling other param= methods to provide meaningful feedback during
# other warnings
@name = args[:name] if args.include? :name
# set the default value for call_hook
@call_hook = :on_write_only if args[:hook] and !(args[:call_hook])
@has_hook = false
if args[:call_hook] and !(args[:hook])
# TRANSLATORS ':call_hook' and ':hook' are specific setting names and should not be translated
raise ArgumentError, _("Cannot reference :call_hook for :%{name} if no :hook is defined") % { name: @name }
end
args.each do |param, value|
method = param.to_s + "="
unless respond_to? method
raise ArgumentError, _("%{class_name} (setting '%{setting}') does not accept %{parameter}") %
{ class_name: self.class, setting: args[:name], parameter: param }
end
send(method, value)
end
unless desc
raise ArgumentError, _("You must provide a description for the %{class_name} config option") % { class_name: name }
end
end
def iscreated
@iscreated = true
end
def iscreated?
@iscreated
end
# short name for the element
def short=(value)
raise ArgumentError, _("Short names can only be one character.") if value.to_s.length != 1
@short = value.to_s
end
def default(check_application_defaults_first = false)
if @default.is_a? Proc
# Give unit tests a chance to reevaluate the call by removing the instance variable
unless instance_variable_defined?(:@evaluated_default)
@evaluated_default = @default.call
end
default_value = @evaluated_default
else
default_value = @default
end
return default_value unless check_application_defaults_first
@settings.value(name, :application_defaults, true) || default_value
end
# Convert the object to a config statement.
def to_config
require_relative '../../puppet/util/docs'
# Scrub any funky indentation; comment out description.
str = Puppet::Util::Docs.scrub(@desc).gsub(/^/, "# ") + "\n"
# Add in a statement about the default.
str << "# The default value is '#{default(true)}'.\n" if default(true)
# If the value has not been overridden, then print it out commented
# and unconverted, so it's clear that that's the default and how it
# works.
value = @settings.value(name)
if value != @default
line = "#{@name} = #{value}"
else
line = "# #{@name} = #{@default}"
end
str << (line + "\n")
# Indent
str.gsub(/^/, " ")
end
# @param bypass_interpolation [Boolean] Set this true to skip the
# interpolation step, returning the raw setting value. Defaults to false.
# @return [String] Retrieves the value, or if it's not set, retrieves the default.
# @api public
def value(bypass_interpolation = false)
@settings.value(name, nil, bypass_interpolation)
end
# Modify the value when it is first evaluated
def munge(value)
value
end
# Print the value for the user in a config compatible format
def print(value)
munge(value)
end
def set_meta(meta)
Puppet.notice("#{name} does not support meta data. Ignoring.")
end
def deprecated=(deprecation)
unless [:completely, :allowed_on_commandline].include?(deprecation)
# TRANSLATORS 'deprecated' is a Puppet setting and ':completely' and ':allowed_on_commandline' are possible values and should not be translated
raise ArgumentError, _("Unsupported deprecated value '%{deprecation}'.") % { deprecation: deprecation } +
' ' + _("Supported values for deprecated are ':completely' or ':allowed_on_commandline'")
end
@deprecated = deprecation
end
def deprecated?
!!@deprecated
end
# True if we should raise a deprecation_warning if the setting is submitted
# on the commandline or is set in puppet.conf.
def completely_deprecated?
@deprecated == :completely
end
# True if we should raise a deprecation_warning if the setting is found in
# puppet.conf, but not if the user sets it on the commandline
def allowed_on_commandline?
@deprecated == :allowed_on_commandline
end
def inspect
%Q(<#{self.class}:#{object_id} @name="#{@name}" @section="#{@section}" @default="#{@default}" @call_hook="#{@call_hook}">)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/file_or_directory_setting.rb | lib/puppet/settings/file_or_directory_setting.rb | # frozen_string_literal: true
class Puppet::Settings::FileOrDirectorySetting < Puppet::Settings::FileSetting
def type
if Puppet::FileSystem.directory?(value) || @path_ends_with_slash
:directory
else
:file
end
end
# Overrides munge to be able to read the un-munged value (the FileSetting.munch removes trailing slash)
#
def munge(value)
if value.is_a?(String) && value =~ %r{[\\/]$}
@path_ends_with_slash = true
end
super
end
# @api private
#
# @param option [String] Extra file operation mode information to use
# (defaults to read-only mode 'r')
# This is the standard mechanism Ruby uses in the IO class, and therefore
# encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*"
# for example, a:ASCII or w+:UTF-8
def open_file(filename, option = 'r', &block)
if type == :file
super
else
controlled_access do |mode|
Puppet::FileSystem.open(filename, mode, option, &block)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/array_setting.rb | lib/puppet/settings/array_setting.rb | # frozen_string_literal: true
class Puppet::Settings::ArraySetting < Puppet::Settings::BaseSetting
def type
:array
end
def munge(value)
case value
when String
value.split(/\s*,\s*/)
when Array
value
else
raise ArgumentError, _("Expected an Array or String, got a %{klass}") % { klass: value.class }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/environment_conf.rb | lib/puppet/settings/environment_conf.rb | # frozen_string_literal: true
# Configuration settings for a single directory Environment.
# @api private
class Puppet::Settings::EnvironmentConf
ENVIRONMENT_CONF_ONLY_SETTINGS = [:modulepath, :manifest, :config_version].freeze
VALID_SETTINGS = (ENVIRONMENT_CONF_ONLY_SETTINGS + [:environment_timeout, :environment_data_provider, :static_catalogs, :rich_data]).freeze
# Given a path to a directory environment, attempts to load and parse an
# environment.conf in ini format, and return an EnvironmentConf instance.
#
# An environment.conf is optional, so if the file itself is missing, or
# empty, an EnvironmentConf with default values will be returned.
#
# @note logs warnings if the environment.conf contains any ini sections,
# or has settings other than the three handled for directory environments
# (:manifest, :modulepath, :config_version)
#
# @param path_to_env [String] path to the directory environment
# @param global_module_path [Array<String>] the installation's base modulepath
# setting, appended to default environment modulepaths
# @return [EnvironmentConf] the parsed EnvironmentConf object
def self.load_from(path_to_env, global_module_path)
path_to_env = File.expand_path(path_to_env)
conf_file = File.join(path_to_env, 'environment.conf')
begin
config = Puppet.settings.parse_file(conf_file)
validate(conf_file, config)
section = config.sections[:main]
rescue Errno::ENOENT
# environment.conf is an optional file
Puppet.debug { "Path to #{path_to_env} does not exist, using default environment.conf" }
end
new(path_to_env, section, global_module_path)
end
# Provides a configuration object tied directly to the passed environment.
# Configuration values are exactly those returned by the environment object,
# without interpolation. This is a special case for the default configured
# environment returned by the Puppet::Environments::StaticPrivate loader.
def self.static_for(environment, environment_timeout = 0, static_catalogs = false, rich_data = false)
Static.new(environment, environment_timeout, static_catalogs, nil, rich_data)
end
attr_reader :section, :path_to_env, :global_modulepath
# Create through EnvironmentConf.load_from()
def initialize(path_to_env, section, global_module_path)
@path_to_env = path_to_env
@section = section
@global_module_path = global_module_path
end
def manifest
puppet_conf_manifest = Pathname.new(Puppet.settings.value(:default_manifest))
disable_per_environment_manifest = Puppet.settings.value(:disable_per_environment_manifest)
fallback_manifest_directory =
if puppet_conf_manifest.absolute?
puppet_conf_manifest.to_s
else
File.join(@path_to_env, puppet_conf_manifest.to_s)
end
if disable_per_environment_manifest
environment_conf_manifest = absolute(raw_setting(:manifest))
if environment_conf_manifest && fallback_manifest_directory != environment_conf_manifest
# TRANSLATORS 'disable_per_environment_manifest' is a setting and 'environment.conf' is a file name and should not be translated
message = _("The 'disable_per_environment_manifest' setting is true, but the environment located at %{path_to_env} has a manifest setting in its environment.conf of '%{environment_conf}' which does not match the default_manifest setting '%{puppet_conf}'.") %
{ path_to_env: @path_to_env, environment_conf: environment_conf_manifest, puppet_conf: puppet_conf_manifest }
message += ' ' + _("If this environment is expecting to find modules in '%{environment_conf}', they will not be available!") % { environment_conf: environment_conf_manifest }
Puppet.err(message)
end
fallback_manifest_directory.to_s
else
get_setting(:manifest, fallback_manifest_directory) do |manifest|
absolute(manifest)
end
end
end
def environment_timeout
# gen env specific config or use the default value
get_setting(:environment_timeout, Puppet.settings.value(:environment_timeout)) do |ttl|
# munges the string form statically without really needed the settings system, only
# its ability to munge "4s, 3m, 5d, and 'unlimited' into seconds - if already munged into
# numeric form, the TTLSetting handles that.
Puppet::Settings::TTLSetting.munge(ttl, 'environment_timeout')
end
end
def environment_data_provider
get_setting(:environment_data_provider, Puppet.settings.value(:environment_data_provider)) do |value|
value
end
end
def modulepath
default_modulepath = [File.join(@path_to_env, "modules")] + @global_module_path
get_setting(:modulepath, default_modulepath) do |modulepath|
path = modulepath.is_a?(String) ?
modulepath.split(File::PATH_SEPARATOR) :
modulepath
path.map { |p| expand_glob(absolute(p)) }.flatten.join(File::PATH_SEPARATOR)
end
end
def rich_data
get_setting(:rich_data, Puppet.settings.value(:rich_data)) do |value|
value
end
end
def static_catalogs
get_setting(:static_catalogs, Puppet.settings.value(:static_catalogs)) do |value|
value
end
end
def config_version
get_setting(:config_version) do |config_version|
absolute(config_version)
end
end
def raw_setting(setting_name)
setting = section.setting(setting_name) if section
setting.value if setting
end
private
def self.validate(path_to_conf_file, config)
valid = true
section_keys = config.sections.keys
main = config.sections[:main]
if section_keys.size > 1
# warn once per config file path
Puppet.warn_once(
:invalid_settings_section, "EnvironmentConf-section:#{path_to_conf_file}",
_("Invalid sections in environment.conf at '%{path_to_conf_file}'. Environment conf may not have sections. The following sections are being ignored: '%{sections}'") % {
path_to_conf_file: path_to_conf_file,
sections: (section_keys - [:main]).join(',')
}
)
valid = false
end
extraneous_settings = main.settings.map(&:name) - VALID_SETTINGS
unless extraneous_settings.empty?
# warn once per config file path
Puppet.warn_once(
:invalid_settings, "EnvironmentConf-settings:#{path_to_conf_file}",
_("Invalid settings in environment.conf at '%{path_to_conf_file}'. The following unknown setting(s) are being ignored: %{ignored_settings}") % {
path_to_conf_file: path_to_conf_file,
ignored_settings: extraneous_settings.join(', ')
}
)
valid = false
end
valid
end
private_class_method :validate
def get_setting(setting_name, default = nil)
value = raw_setting(setting_name)
value = default if value.nil?
yield value
end
def expand_glob(path)
return nil if path.nil?
if path =~ /[*?\[{]/
Dir.glob(path)
else
path
end
end
def absolute(path)
return nil if path.nil?
if path =~ /^\$/
# Path begins with $something interpolatable
path
else
Puppet::FileSystem.expand_path(path, @path_to_env)
end
end
# Models configuration for an environment that is not loaded from a directory.
#
# @api private
class Static
attr_reader :environment_timeout
attr_reader :environment_data_provider
attr_reader :rich_data
attr_reader :static_catalogs
def initialize(environment, environment_timeout, static_catalogs, environment_data_provider = nil, rich_data = false)
@environment = environment
@environment_timeout = environment_timeout
@static_catalogs = static_catalogs
@environment_data_provider = environment_data_provider
@rich_data = rich_data
end
def path_to_env
nil
end
def manifest
@environment.manifest
end
def modulepath
@environment.modulepath.join(File::PATH_SEPARATOR)
end
def config_version
@environment.config_version
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/config_file.rb | lib/puppet/settings/config_file.rb | # frozen_string_literal: true
require_relative '../../puppet/settings/ini_file'
##
# @api private
#
# Parses puppet configuration files
#
class Puppet::Settings::ConfigFile
##
# @param value_converter [Proc] a function that will convert strings into ruby types
def initialize(value_converter)
@value_converter = value_converter
end
# @param file [String, File] pointer to the file whose text we are parsing
# @param text [String] the actual text of the inifile to be parsed
# @param allowed_section_names [Array] an optional array of accepted section
# names; if this list is non-empty, sections outside of it will raise an
# error.
# @return A Struct with a +sections+ array representing each configuration section
def parse_file(file, text, allowed_section_names = [])
result = Conf.new
unless allowed_section_names.empty?
allowed_section_names << 'main' unless allowed_section_names.include?('main')
end
ini = Puppet::Settings::IniFile.parse(text.encode(Encoding::UTF_8))
unique_sections_in(ini, file, allowed_section_names).each do |section_name|
section = Section.new(section_name.to_sym)
result.with_section(section)
ini.lines_in(section_name).each do |line|
if line.is_a?(Puppet::Settings::IniFile::SettingLine)
parse_setting(line, section)
elsif line.text !~ /^\s*#|^\s*$/
raise Puppet::Settings::ParseError.new(_("Could not match line %{text}") % { text: line.text }, file, line.line_number)
end
end
end
result
end
Conf = Struct.new(:sections) do
def initialize
super({})
end
def with_section(section)
sections[section.name] = section
self
end
end
Section = Struct.new(:name, :settings) do
def initialize(name)
super(name, [])
end
def with_setting(name, value, meta)
settings << Setting.new(name, value, meta)
self
end
def setting(name)
settings.find { |setting| setting.name == name }
end
end
Setting = Struct.new(:name, :value, :meta) do
def has_metadata?
meta != NO_META
end
end
Meta = Struct.new(:owner, :group, :mode)
NO_META = Meta.new(nil, nil, nil)
private
def unique_sections_in(ini, file, allowed_section_names)
ini.section_lines.collect do |section|
if !allowed_section_names.empty? && !allowed_section_names.include?(section.name)
error_location_str = Puppet::Util::Errors.error_location(file, section.line_number)
message = _("Illegal section '%{name}' in config file at %{error_location}.") %
{ name: section.name, error_location: error_location_str }
# TRANSLATORS 'puppet.conf' is the name of the puppet configuration file and should not be translated.
message += ' ' + _("The only valid puppet.conf sections are: [%{allowed_sections_list}].") %
{ allowed_sections_list: allowed_section_names.join(", ") }
message += ' ' + _("Please use the directory environments feature to specify environments.")
message += ' ' + _("(See https://puppet.com/docs/puppet/latest/environments_about.html)")
raise(Puppet::Error, message)
end
section.name
end.uniq
end
def parse_setting(setting, section)
var = setting.name.intern
value = @value_converter[setting.value]
# Check to see if this is a file argument and it has extra options
begin
options = extract_fileinfo(value) if value.is_a?(String)
if options
section.with_setting(var, options[:value], Meta.new(options[:owner],
options[:group],
options[:mode]))
else
section.with_setting(var, value, NO_META)
end
rescue Puppet::Error => detail
raise Puppet::Settings::ParseError.new(detail.message, file, setting.line_number, detail)
end
end
def empty_section
{ :_meta => {} }
end
def extract_fileinfo(string)
result = {}
value = string.sub(/\{\s*([^}]+)\s*\}/) do
params = ::Regexp.last_match(1)
params.split(/\s*,\s*/).each do |str|
if str =~ /^\s*(\w+)\s*=\s*(\w+)\s*$/
param = ::Regexp.last_match(1).intern
value = ::Regexp.last_match(2)
result[param] = value
unless [:owner, :mode, :group].include?(param)
raise ArgumentError, _("Invalid file option '%{parameter}'") % { parameter: param }
end
if param == :mode and value !~ /^\d+$/
raise ArgumentError, _("File modes must be numbers")
end
else
raise ArgumentError, _("Could not parse '%{string}'") % { string: string }
end
end
''
end
result[:value] = value.sub(/\s*$/, '')
result
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/errors.rb | lib/puppet/settings/errors.rb | # frozen_string_literal: true
# Exceptions for the settings module
require_relative '../../puppet/error'
class Puppet::Settings
class SettingsError < Puppet::Error; end
class ValidationError < SettingsError; end
class InterpolationError < SettingsError; end
class ParseError < SettingsError
include Puppet::ExternalFileError
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/directory_setting.rb | lib/puppet/settings/directory_setting.rb | # frozen_string_literal: true
class Puppet::Settings::DirectorySetting < Puppet::Settings::FileSetting
def type
:directory
end
# @api private
#
# @param option [String] Extra file operation mode information to use
# (defaults to read-only mode 'r')
# This is the standard mechanism Ruby uses in the IO class, and therefore
# encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*"
# for example, a:ASCII or w+:UTF-8
def open_file(filename, option = 'r', &block)
controlled_access do |mode|
Puppet::FileSystem.open(filename, mode, option, &block)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/terminus_setting.rb | lib/puppet/settings/terminus_setting.rb | # frozen_string_literal: true
class Puppet::Settings::TerminusSetting < Puppet::Settings::BaseSetting
def munge(value)
case value
when '', nil
nil
when String
value.intern
when Symbol
value
else
raise Puppet::Settings::ValidationError, _("Invalid terminus setting: %{value}") % { value: value }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/boolean_setting.rb | lib/puppet/settings/boolean_setting.rb | # frozen_string_literal: true
# A simple boolean.
class Puppet::Settings::BooleanSetting < Puppet::Settings::BaseSetting
# get the arguments in getopt format
def getopt_args
if short
[["--#{name}", "-#{short}", GetoptLong::NO_ARGUMENT], ["--no-#{name}", GetoptLong::NO_ARGUMENT]]
else
[["--#{name}", GetoptLong::NO_ARGUMENT], ["--no-#{name}", GetoptLong::NO_ARGUMENT]]
end
end
def optparse_args
if short
["--[no-]#{name}", "-#{short}", desc, :NONE]
else
["--[no-]#{name}", desc, :NONE]
end
end
def munge(value)
case value
when true, "true"; true
when false, "false"; false
else
raise Puppet::Settings::ValidationError, _("Invalid value '%{value}' for boolean parameter: %{name}") % { value: value.inspect, name: @name }
end
end
def type
:boolean
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/integer_setting.rb | lib/puppet/settings/integer_setting.rb | # frozen_string_literal: true
class Puppet::Settings::IntegerSetting < Puppet::Settings::BaseSetting
def munge(value)
return value if value.is_a?(Integer)
begin
value = Integer(value)
rescue ArgumentError, TypeError
raise Puppet::Settings::ValidationError, _("Cannot convert '%{value}' to an integer for parameter: %{name}") % { value: value.inspect, name: @name }
end
value
end
def type
:integer
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/string_setting.rb | lib/puppet/settings/string_setting.rb | # frozen_string_literal: true
class Puppet::Settings::StringSetting < Puppet::Settings::BaseSetting
def type
:string
end
def validate(value)
value.nil? or value.is_a?(String)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/http_extra_headers_setting.rb | lib/puppet/settings/http_extra_headers_setting.rb | # frozen_string_literal: true
class Puppet::Settings::HttpExtraHeadersSetting < Puppet::Settings::BaseSetting
def type
:http_extra_headers
end
def munge(headers)
return headers if headers.is_a?(Hash)
headers = headers.split(/\s*,\s*/) if headers.is_a?(String)
raise ArgumentError, _("Expected an Array, String, or Hash, got a %{klass}") % { klass: headers.class } unless headers.is_a?(Array)
headers.map! { |header|
case header
when String
header.split(':')
when Array
header
else
raise ArgumentError, _("Expected an Array or String, got a %{klass}") % { klass: header.class }
end
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/duration_setting.rb | lib/puppet/settings/duration_setting.rb | # frozen_string_literal: true
# A setting that represents a span of time, and evaluates to an integer
# number of seconds after being parsed
class Puppet::Settings::DurationSetting < Puppet::Settings::BaseSetting
# How we convert from various units to seconds.
UNITMAP = {
# 365 days isn't technically a year, but is sufficient for most purposes
"y" => 365 * 24 * 60 * 60,
"d" => 24 * 60 * 60,
"h" => 60 * 60,
"m" => 60,
"s" => 1
}
# A regex describing valid formats with groups for capturing the value and units
FORMAT = /^(\d+)(y|d|h|m|s)?$/
def type
:duration
end
# Convert the value to an integer, parsing numeric string with units if necessary.
def munge(value)
if value.is_a?(Integer) || value.nil?
value
elsif value.is_a?(String) and value =~ FORMAT
::Regexp.last_match(1).to_i * UNITMAP[::Regexp.last_match(2) || 's']
else
raise Puppet::Settings::ValidationError, _("Invalid duration format '%{value}' for parameter: %{name}") % { value: value.inspect, name: @name }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/port_setting.rb | lib/puppet/settings/port_setting.rb | # frozen_string_literal: true
class Puppet::Settings::PortSetting < Puppet::Settings::IntegerSetting
def munge(value)
value = super(value)
if value < 0 || value > 65_535
raise Puppet::Settings::ValidationError, _("Value '%{value}' is not a valid port number for parameter: %{name}") % { value: value.inspect, name: @name }
end
value
end
def type
:port
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/alias_setting.rb | lib/puppet/settings/alias_setting.rb | # frozen_string_literal: true
class Puppet::Settings::AliasSetting
attr_reader :name, :alias_name
def initialize(args = {})
@name = args[:name]
@alias_name = args[:alias_for]
@alias_for = Puppet.settings.setting(alias_name)
end
def optparse_args
args = @alias_for.optparse_args
args[0].gsub!(alias_name.to_s, name.to_s)
args
end
def getopt_args
args = @alias_for.getopt_args
args[0].gsub!(alias_name.to_s, name.to_s)
args
end
def type
:alias
end
def method_missing(method, *args)
alias_for.send(method, *args)
rescue => e
Puppet.log_exception(self.class, e.message)
end
private
attr_reader :alias_for
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/ini_file.rb | lib/puppet/settings/ini_file.rb | # frozen_string_literal: true
# @api private
class Puppet::Settings::IniFile
DEFAULT_SECTION_NAME = "main"
def self.update(config_fh, &block)
config = parse(config_fh)
manipulator = Manipulator.new(config)
yield manipulator
config.write(config_fh)
end
def self.parse(config_fh)
config = new([DefaultSection.new])
config_fh.each_line do |line|
case line.chomp
when /^(\s*)\[([[:word:]]+)\](\s*)$/
config.append(SectionLine.new(::Regexp.last_match(1), ::Regexp.last_match(2), ::Regexp.last_match(3)))
when /^(\s*)([[:word:]]+)(\s*=\s*)(.*?)(\s*)$/
config.append(SettingLine.new(::Regexp.last_match(1), ::Regexp.last_match(2), ::Regexp.last_match(3), ::Regexp.last_match(4), ::Regexp.last_match(5)))
else
config.append(Line.new(line))
end
end
config
end
def initialize(lines = [])
@lines = lines
end
def append(line)
line.previous = @lines.last
@lines << line
end
def delete(section, name)
delete_offset = @lines.index(setting(section, name))
next_offset = delete_offset + 1
if next_offset < @lines.length
@lines[next_offset].previous = @lines[delete_offset].previous
end
@lines.delete_at(delete_offset)
end
def insert_after(line, new_line)
new_line.previous = line
insertion_point = @lines.index(line)
@lines.insert(insertion_point + 1, new_line)
if @lines.length > insertion_point + 2
@lines[insertion_point + 2].previous = new_line
end
end
def section_lines
@lines.select { |line| line.is_a?(SectionLine) }
end
def section_line(name)
section_lines.find { |section| section.name == name }
end
def setting(section, name)
settings_in(lines_in(section)).find do |line|
line.name == name
end
end
def lines_in(section_name)
section_lines = []
current_section_name = DEFAULT_SECTION_NAME
@lines.each do |line|
if line.is_a?(SectionLine)
current_section_name = line.name
elsif current_section_name == section_name
section_lines << line
end
end
section_lines
end
def settings_in(lines)
lines.select { |line| line.is_a?(SettingLine) }
end
def settings_exist_in_default_section?
lines_in(DEFAULT_SECTION_NAME).any? { |line| line.is_a?(SettingLine) }
end
def section_exists_with_default_section_name?
section_lines.any? do |section|
!section.is_a?(DefaultSection) && section.name == DEFAULT_SECTION_NAME
end
end
def set_default_section_write_sectionline(value)
index = @lines.find_index { |line| line.is_a?(DefaultSection) }
if index
@lines[index].write_sectionline = true
end
end
def write(fh)
# If no real section line for the default section exists, configure the
# DefaultSection object to write its section line. (DefaultSection objects
# don't write the section line unless explicitly configured to do so)
if settings_exist_in_default_section? && !section_exists_with_default_section_name?
set_default_section_write_sectionline(true)
end
fh.truncate(0)
fh.rewind
@lines.each do |line|
line.write(fh)
end
fh.flush
end
class Manipulator
def initialize(config)
@config = config
end
def set(section, name, value)
setting = @config.setting(section, name)
if setting
setting.value = value
else
add_setting(section, name, value)
end
end
def delete(section_name, name)
setting = @config.setting(section_name, name)
if setting
@config.delete(section_name, name)
setting.to_s.chomp
end
end
private
def add_setting(section_name, name, value)
section = @config.section_line(section_name)
if section.nil?
previous_line = SectionLine.new("", section_name, "")
@config.append(previous_line)
else
previous_line = @config.settings_in(@config.lines_in(section_name)).last || section
end
@config.insert_after(previous_line, SettingLine.new("", name, " = ", value, ""))
end
end
module LineNumber
attr_accessor :previous
def line_number
line = 0
previous_line = previous
while previous_line
line += 1
previous_line = previous_line.previous
end
line
end
end
Line = Struct.new(:text) do
include LineNumber
def to_s
text
end
def write(fh)
fh.puts(to_s)
end
end
SettingLine = Struct.new(:prefix, :name, :infix, :value, :suffix) do
include LineNumber
def to_s
"#{prefix}#{name}#{infix}#{value}#{suffix}"
end
def write(fh)
fh.puts(to_s)
end
def ==(other)
super(other) && line_number == other.line_number
end
end
SectionLine = Struct.new(:prefix, :name, :suffix) do
include LineNumber
def to_s
"#{prefix}[#{name}]#{suffix}"
end
def write(fh)
fh.puts(to_s)
end
end
class DefaultSection < SectionLine
attr_accessor :write_sectionline
def initialize
@write_sectionline = false
super("", DEFAULT_SECTION_NAME, "")
end
def write(fh)
if @write_sectionline
super(fh)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/ttl_setting.rb | lib/puppet/settings/ttl_setting.rb | # frozen_string_literal: true
# A setting that represents a span of time to live, and evaluates to Numeric
# seconds to live where 0 means shortest possible time to live, a positive numeric value means time
# to live in seconds, and the symbolic entry 'unlimited' is an infinite amount of time.
#
class Puppet::Settings::TTLSetting < Puppet::Settings::BaseSetting
# How we convert from various units to seconds.
UNITMAP = {
# 365 days isn't technically a year, but is sufficient for most purposes
"y" => 365 * 24 * 60 * 60,
"d" => 24 * 60 * 60,
"h" => 60 * 60,
"m" => 60,
"s" => 1
}
# A regex describing valid formats with groups for capturing the value and units
FORMAT = /^(\d+)(y|d|h|m|s)?$/
def type
:ttl
end
# Convert the value to Numeric, parsing numeric string with units if necessary.
def munge(value)
self.class.munge(value, @name)
end
def print(value)
val = munge(value)
val == Float::INFINITY ? 'unlimited' : val
end
# Convert the value to Numeric, parsing numeric string with units if necessary.
def self.munge(value, param_name)
if value.is_a?(Numeric)
if value < 0
raise Puppet::Settings::ValidationError, _("Invalid negative 'time to live' %{value} - did you mean 'unlimited'?") % { value: value.inspect }
end
value
elsif value == 'unlimited'
Float::INFINITY
elsif value.is_a?(String) and value =~ FORMAT
::Regexp.last_match(1).to_i * UNITMAP[::Regexp.last_match(2) || 's']
else
raise Puppet::Settings::ValidationError, _("Invalid 'time to live' format '%{value}' for parameter: %{param_name}") % { value: value.inspect, param_name: param_name }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/value_translator.rb | lib/puppet/settings/value_translator.rb | # frozen_string_literal: true
# Convert arguments into booleans, integers, or whatever.
class Puppet::Settings::ValueTranslator
def [](value)
# Handle different data types correctly
case value
when /^false$/i; false
when /^true$/i; true
when true; true
when false; false
else
value.gsub(/^["']|["']$/, '').sub(/\s+$/, '')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/symbolic_enum_setting.rb | lib/puppet/settings/symbolic_enum_setting.rb | # frozen_string_literal: true
class Puppet::Settings::SymbolicEnumSetting < Puppet::Settings::BaseSetting
attr_accessor :values
def type
:symbolic_enum
end
def munge(value)
sym = value.to_sym
if values.include?(sym)
sym
else
raise Puppet::Settings::ValidationError,
_("Invalid value '%{value}' for parameter %{name}. Allowed values are '%{allowed_values}'") % { value: value, name: @name, allowed_values: values.join("', '") }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/certificate_revocation_setting.rb | lib/puppet/settings/certificate_revocation_setting.rb | # frozen_string_literal: true
require_relative '../../puppet/settings/base_setting'
class Puppet::Settings::CertificateRevocationSetting < Puppet::Settings::BaseSetting
def type
:certificate_revocation
end
def munge(value)
case value
when 'chain', 'true', TrueClass
:chain
when 'leaf'
:leaf
when 'false', FalseClass, NilClass
false
else
raise Puppet::Settings::ValidationError, _("Invalid certificate revocation value %{value}: must be one of 'true', 'chain', 'leaf', or 'false'") % { value: value }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/server_list_setting.rb | lib/puppet/settings/server_list_setting.rb | # frozen_string_literal: true
class Puppet::Settings::ServerListSetting < Puppet::Settings::ArraySetting
def type
:server_list
end
def print(value)
if value.is_a?(Array)
# turn into a string
value.map { |item| item.join(":") }.join(",")
else
value
end
end
def munge(value)
servers = super
servers.map! { |server|
case server
when String
server.split(':')
when Array
server
else
raise ArgumentError, _("Expected an Array of String, got a %{klass}") % { klass: value.class }
end
}
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/path_setting.rb | lib/puppet/settings/path_setting.rb | # frozen_string_literal: true
class Puppet::Settings::PathSetting < Puppet::Settings::StringSetting
def munge(value)
if value.is_a?(String)
value = value.split(File::PATH_SEPARATOR).map { |d| File.expand_path(d) }.join(File::PATH_SEPARATOR)
end
value
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/autosign_setting.rb | lib/puppet/settings/autosign_setting.rb | # frozen_string_literal: true
require_relative '../../puppet/settings/base_setting'
# A specialization of the file setting to allow boolean values.
#
# The autosign value can be either a boolean or a file path, and if the setting
# is a file path then it may have a owner/group/mode specified.
#
# @api private
class Puppet::Settings::AutosignSetting < Puppet::Settings::FileSetting
def munge(value)
if ['true', true].include? value
true
elsif ['false', false, nil].include? value
false
elsif Puppet::Util.absolute_path?(value)
value
else
raise Puppet::Settings::ValidationError, _("Invalid autosign value %{value}: must be 'true'/'false' or an absolute path") % { value: value }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/settings/file_setting.rb | lib/puppet/settings/file_setting.rb | # frozen_string_literal: true
# A file.
class Puppet::Settings::FileSetting < Puppet::Settings::StringSetting
class SettingError < StandardError; end
# An unspecified user or group
#
# @api private
class Unspecified
def value
nil
end
end
# A "root" user or group
#
# @api private
class Root
def value
"root"
end
end
# A "service" user or group that picks up values from settings when the
# referenced user or group is safe to use (it exists or will be created), and
# uses the given fallback value when not safe.
#
# @api private
class Service
# @param name [Symbol] the name of the setting to use as the service value
# @param fallback [String, nil] the value to use when the service value cannot be used
# @param settings [Puppet::Settings] the puppet settings object
# @param available_method [Symbol] the name of the method to call on
# settings to determine if the value in settings is available on the system
#
def initialize(name, fallback, settings, available_method)
@settings = settings
@available_method = available_method
@name = name
@fallback = fallback
end
def value
if safe_to_use_settings_value?
@settings[@name]
else
@fallback
end
end
private
def safe_to_use_settings_value?
@settings[:mkusers] or @settings.send(@available_method)
end
end
attr_accessor :mode
def initialize(args)
@group = Unspecified.new
@owner = Unspecified.new
super(args)
end
# @param value [String] the group to use on the created file (can only be "root" or "service")
# @api public
def group=(value)
@group = case value
when "root"
Root.new
when "service"
# Group falls back to `nil` because we cannot assume that a "root" group exists.
# Some systems have root group, others have wheel, others have something else.
Service.new(:group, nil, @settings, :service_group_available?)
else
unknown_value(':group', value)
end
end
# @param value [String] the owner to use on the created file (can only be "root" or "service")
# @api public
def owner=(value)
@owner = case value
when "root"
Root.new
when "service"
Service.new(:user, "root", @settings, :service_user_available?)
else
unknown_value(':owner', value)
end
end
# @return [String, nil] the name of the group to use for the file or nil if the group should not be managed
# @api public
def group
@group.value
end
# @return [String, nil] the name of the user to use for the file or nil if the user should not be managed
# @api public
def owner
@owner.value
end
def set_meta(meta)
self.owner = meta.owner if meta.owner
self.group = meta.group if meta.group
self.mode = meta.mode if meta.mode
end
def munge(value)
if value.is_a?(String) and value != ':memory:' # for sqlite3 in-memory tests
value = File.expand_path(value)
end
value
end
def type
:file
end
# Turn our setting thing into a Puppet::Resource instance.
def to_resource
type = self.type
return nil unless type
path = value
return nil unless path.is_a?(String)
# Make sure the paths are fully qualified.
path = File.expand_path(path)
return nil unless type == :directory || Puppet::FileSystem.exist?(path)
return nil if path =~ %r{^/dev} || path =~ %r{^[A-Z]:/dev}i
resource = Puppet::Resource.new(:file, path)
if Puppet[:manage_internal_file_permissions]
if mode
# This ends up mimicking the munge method of the mode
# parameter to make sure that we're always passing the string
# version of the octal number. If we were setting the
# 'should' value for mode rather than the 'is', then the munge
# method would be called for us automatically. Normally, one
# wouldn't need to call the munge method manually, since
# 'should' gets set by the provider and it should be able to
# provide the data in the appropriate format.
mode = self.mode
mode = mode.to_i(8) if mode.is_a?(String)
mode = mode.to_s(8)
resource[:mode] = mode
end
# REMIND fails on Windows because chown/chgrp functionality not supported yet
if Puppet.features.root? and !Puppet::Util::Platform.windows?
resource[:owner] = owner if owner
resource[:group] = group if group
end
end
resource[:ensure] = type
resource[:loglevel] = :debug
resource[:links] = :follow
resource[:backup] = false
resource.tag(section, name, "settings")
resource
end
# @api private
# @param option [String] Extra file operation mode information to use
# (defaults to read-only mode 'r')
# This is the standard mechanism Ruby uses in the IO class, and therefore
# encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*"
# for example, a:ASCII or w+:UTF-8
def exclusive_open(option = 'r', &block)
controlled_access do |mode|
Puppet::FileSystem.exclusive_open(file(), mode, option, &block)
end
end
# @api private
# @param option [String] Extra file operation mode information to use
# (defaults to read-only mode 'r')
# This is the standard mechanism Ruby uses in the IO class, and therefore
# encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*"
# for example, a:ASCII or w+:UTF-8
def open(option = 'r', &block)
controlled_access do |mode|
Puppet::FileSystem.open(file, mode, option, &block)
end
end
private
def file
Puppet::FileSystem.pathname(value)
end
def unknown_value(parameter, value)
raise SettingError, _("The %{parameter} parameter for the setting '%{name}' must be either 'root' or 'service', not '%{value}'") % { parameter: parameter, name: name, value: value }
end
def controlled_access(&block)
chown = nil
if Puppet.features.root?
chown = [owner, group]
else
chown = [nil, nil]
end
Puppet::Util::SUIDManager.asuser(*chown) do
# Update the umask to make non-executable files
Puppet::Util.withumask(File.umask ^ 0o111) do
yielded_value = case mode
when String
mode.to_i(8)
when NilClass
0o640
else
mode
end
yield yielded_value
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/forge/repository.rb | lib/puppet/forge/repository.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl/openssl_loader'
require 'digest/sha1'
require 'uri'
require_relative '../../puppet/forge'
require_relative '../../puppet/forge/errors'
require_relative '../../puppet/network/http'
class Puppet::Forge
# = Repository
#
# This class is a file for accessing remote repositories with modules.
class Repository
include Puppet::Forge::Errors
attr_reader :uri, :cache
# Instantiate a new repository instance rooted at the +url+.
# The library will report +for_agent+ in the User-Agent to the repository.
def initialize(host, for_agent)
@host = host
@agent = for_agent
@cache = Cache.new(self)
@uri = URI.parse(host)
ssl_provider = Puppet::SSL::SSLProvider.new
@ssl_context = ssl_provider.create_system_context(cacerts: [])
end
# Return a Net::HTTPResponse read for this +path+.
def make_http_request(path, io = nil)
raise ArgumentError, "Path must start with forward slash" unless path.start_with?('/')
begin
str = @uri.to_s
str.chomp!('/')
str += Puppet::Util.uri_encode(path)
uri = URI(str)
headers = { "User-Agent" => user_agent }
if forge_authorization
uri.user = nil
uri.password = nil
headers["Authorization"] = forge_authorization
end
http = Puppet.runtime[:http]
response = http.get(uri, headers: headers, options: { ssl_context: @ssl_context })
io.write(response.body) if io.respond_to?(:write)
response
rescue Puppet::SSL::CertVerifyError => e
raise SSLVerifyError.new(:uri => @uri.to_s, :original => e.cause)
rescue => e
raise CommunicationError.new(:uri => @uri.to_s, :original => e)
end
end
def forge_authorization
if Puppet[:forge_authorization]
Puppet[:forge_authorization]
elsif Puppet.features.pe_license?
PELicense.load_license_key.authorization_token
end
end
# Return the local file name containing the data downloaded from the
# repository at +release+ (e.g. "myuser-mymodule").
def retrieve(release)
path = @host.chomp('/') + release
cache.retrieve(path)
end
# Return the URI string for this repository.
def to_s
"#<#{self.class} #{@host}>"
end
# Return the cache key for this repository, this a hashed string based on
# the URI.
def cache_key
@cache_key ||= [
@host.to_s.gsub(/[^[:alnum:]]+/, '_').sub(/_$/, ''),
Digest::SHA1.hexdigest(@host.to_s)
].join('-').freeze
end
private
def user_agent
@user_agent ||= [
@agent,
Puppet[:http_user_agent]
].join(' ').freeze
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/forge/errors.rb | lib/puppet/forge/errors.rb | # frozen_string_literal: true
require_relative '../../puppet/util/json'
require_relative '../../puppet/error'
require_relative '../../puppet/forge'
# Puppet::Forge specific exceptions
module Puppet::Forge::Errors
# This exception is the parent for all Forge API errors
class ForgeError < Puppet::Error
# This is normally set by the child class, but if it is not this will
# fall back to displaying the message as a multiline.
#
# @return [String] the multiline version of the error message
def multiline
message
end
end
# This exception is raised when there is an SSL verification error when
# communicating with the forge.
class SSLVerifyError < ForgeError
# @option options [String] :uri The URI that failed
# @option options [String] :original the original exception
def initialize(options)
@uri = options[:uri]
original = options[:original]
super(_("Unable to verify the SSL certificate at %{uri}") % { uri: @uri }, original)
end
# Return a multiline version of the error message
#
# @return [String] the multiline version of the error message
def multiline
message = []
message << _('Could not connect via HTTPS to %{uri}') % { uri: @uri }
message << _(' Unable to verify the SSL certificate')
message << _(' The certificate may not be signed by a valid CA')
message << _(' The CA bundle included with OpenSSL may not be valid or up to date')
message.join("\n")
end
end
# This exception is raised when there is a communication error when connecting
# to the forge
class CommunicationError < ForgeError
# @option options [String] :uri The URI that failed
# @option options [String] :original the original exception
def initialize(options)
@uri = options[:uri]
original = options[:original]
@detail = original.message
message = _("Unable to connect to the server at %{uri}. Detail: %{detail}.") % { uri: @uri, detail: @detail }
super(message, original)
end
# Return a multiline version of the error message
#
# @return [String] the multiline version of the error message
def multiline
message = []
message << _('Could not connect to %{uri}') % { uri: @uri }
message << _(' There was a network communications problem')
message << _(" The error we caught said '%{detail}'") % { detail: @detail }
message << _(' Check your network connection and try again')
message.join("\n")
end
end
# This exception is raised when there is a bad HTTP response from the forge
# and optionally a message in the response.
class ResponseError < ForgeError
# @option options [String] :uri The URI that failed
# @option options [String] :input The user's input (e.g. module name)
# @option options [String] :message Error from the API response (optional)
# @option options [Puppet::HTTP::Response] :response The original HTTP response
def initialize(options)
@uri = options[:uri]
@message = options[:message]
response = options[:response]
@response = "#{response.code} #{response.reason.strip}"
begin
body = Puppet::Util::Json.load(response.body)
if body['message']
@message ||= body['message'].strip
end
rescue Puppet::Util::Json::ParseError
end
message = if @message
_("Request to Puppet Forge failed.") + ' ' + _("Detail: %{detail}.") % { detail: "#{@message} / #{@response}" }
else
_("Request to Puppet Forge failed.") + ' ' + _("Detail: %{detail}.") % { detail: @response }
end
super(message, original)
end
# Return a multiline version of the error message
#
# @return [String] the multiline version of the error message
def multiline
message = []
message << _('Request to Puppet Forge failed.')
message << _(' The server being queried was %{uri}') % { uri: @uri }
message << _(" The HTTP response we received was '%{response}'") % { response: @response }
message << _(" The message we received said '%{message}'") % { message: @message } if @message
message.join("\n")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/forge/cache.rb | lib/puppet/forge/cache.rb | # frozen_string_literal: true
require 'uri'
require_relative '../../puppet/forge'
class Puppet::Forge
# = Cache
#
# Provides methods for reading files from local cache, filesystem or network.
class Cache
# Instantiate new cache for the +repository+ instance.
def initialize(repository, options = {})
@repository = repository
@options = options
end
# Return filename retrieved from +uri+ instance. Will download this file and
# cache it if needed.
#
# TODO: Add checksum support.
# TODO: Add error checking.
def retrieve(url)
(path + File.basename(url.to_s)).tap do |cached_file|
uri = url.is_a?(::URI) ? url : ::URI.parse(url)
unless cached_file.file?
if uri.scheme == 'file'
# CGI.unescape butchers Uris that are escaped properly
FileUtils.cp(Puppet::Util.uri_unescape(uri.path), cached_file)
else
# TODO: Handle HTTPS; probably should use repository.contact
data = read_retrieve(uri)
cached_file.open('wb') { |f| f.write data }
end
end
end
end
# Return contents of file at the given URI's +uri+.
def read_retrieve(uri)
uri.read
end
# Return Pathname for repository's cache directory, create it if needed.
def path
(self.class.base_path + @repository.cache_key).tap(&:mkpath)
end
# Return the base Pathname for all the caches.
def self.base_path
(Pathname(Puppet.settings[:module_working_dir]) + 'cache').cleanpath.tap do |o|
o.mkpath unless o.exist?
end
end
# Clean out all the caches.
def self.clean
base_path.rmtree if base_path.exist?
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/info_service/plan_information_service.rb | lib/puppet/info_service/plan_information_service.rb | # frozen_string_literal: true
class Puppet::InfoService::PlanInformationService
require_relative '../../puppet/module'
def self.plans_per_environment(environment_name)
# get the actual environment object, raise error if the named env doesn't exist
env = Puppet.lookup(:environments).get!(environment_name)
env.modules.map do |mod|
mod.plans.map do |plan|
{ :module => { :name => plan.module.name }, :name => plan.name }
end
end.flatten
end
def self.plan_data(environment_name, module_name, plan_name)
# raise EnvironmentNotFound if applicable
Puppet.lookup(:environments).get!(environment_name)
pup_module = Puppet::Module.find(module_name, environment_name)
if pup_module.nil?
raise Puppet::Module::MissingModule, _("Module %{module_name} not found in environment %{environment_name}.") %
{ module_name: module_name, environment_name: environment_name }
end
plan = pup_module.plans.find { |t| t.name == plan_name }
if plan.nil?
raise Puppet::Module::Plan::PlanNotFound.new(plan_name, module_name)
end
begin
plan.validate
{ :metadata => plan.metadata, :files => plan.files }
rescue Puppet::Module::Plan::Error => err
{ :metadata => nil, :files => [], :error => err.to_h }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/info_service/class_information_service.rb | lib/puppet/info_service/class_information_service.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/pops'
require_relative '../../puppet/pops/evaluator/json_strict_literal_evaluator'
class Puppet::InfoService::ClassInformationService
def initialize
@file_to_result = {}
@parser = Puppet::Pops::Parser::EvaluatingParser.new()
end
def classes_per_environment(env_file_hash)
# In this version of puppet there is only one way to parse manifests, as feature switches per environment
# are added or removed, this logic needs to change to compute the result per environment with the correct
# feature flags in effect.
unless env_file_hash.is_a?(Hash)
raise ArgumentError, _('Given argument must be a Hash')
end
result = {}
# for each environment
# for each file
# if file already processed, use last result or error
#
env_file_hash.each do |env, files|
env_result = result[env] = {}
files.each do |f|
env_result[f] = result_of(f)
end
end
result
end
private
def type_parser
Puppet::Pops::Types::TypeParser.singleton
end
def literal_evaluator
@@literal_evaluator ||= Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator.new
end
def result_of(f)
entry = @file_to_result[f]
if entry.nil?
@file_to_result[f] = entry = parse_file(f)
end
entry
end
def parse_file(f)
return { :error => _("The file %{f} does not exist") % { f: f } } unless Puppet::FileSystem.exist?(f)
begin
parse_result = @parser.parse_file(f)
{ :classes =>
parse_result.definitions.select { |d| d.is_a?(Puppet::Pops::Model::HostClassDefinition) }.map do |d|
{ :name => d.name,
:params => d.parameters.map { |p| extract_param(p) } }
end }
rescue StandardError => e
{ :error => e.message }
end
end
def extract_param(p)
extract_default(extract_type({ :name => p.name }, p), p)
end
def extract_type(structure, p)
return structure if p.type_expr.nil?
structure[:type] = typeexpr_to_string(p.name, p.type_expr)
structure
end
def extract_default(structure, p)
value_expr = p.value
return structure if value_expr.nil?
default_value = value_as_literal(value_expr)
structure[:default_literal] = default_value unless default_value.nil?
structure[:default_source] = extract_value_source(value_expr)
structure
end
def typeexpr_to_string(name, type_expr)
type_parser.interpret_any(type_expr, nil).to_s
rescue Puppet::ParseError => e
raise Puppet::Error, "The parameter '$#{name}' is invalid: #{e.message}", e.backtrace
end
def value_as_literal(value_expr)
catch(:not_literal) do
return literal_evaluator.literal(value_expr)
end
nil
end
# Extracts the source for the expression
def extract_value_source(value_expr)
value_expr.locator.extract_tree_text(value_expr)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/info_service/task_information_service.rb | lib/puppet/info_service/task_information_service.rb | # frozen_string_literal: true
class Puppet::InfoService::TaskInformationService
require_relative '../../puppet/module'
def self.tasks_per_environment(environment_name)
# get the actual environment object, raise error if the named env doesn't exist
env = Puppet.lookup(:environments).get!(environment_name)
env.modules.map do |mod|
mod.tasks.map do |task|
# If any task is malformed continue to list other tasks in module
task.validate
{ :module => { :name => task.module.name }, :name => task.name, :metadata => task.metadata }
rescue Puppet::Module::Task::Error => err
Puppet.log_exception(err)
nil
end
end.flatten.compact
end
def self.task_data(environment_name, module_name, task_name)
# raise EnvironmentNotFound if applicable
Puppet.lookup(:environments).get!(environment_name)
pup_module = Puppet::Module.find(module_name, environment_name)
if pup_module.nil?
raise Puppet::Module::MissingModule, _("Module %{module_name} not found in environment %{environment_name}.") %
{ module_name: module_name, environment_name: environment_name }
end
task = pup_module.tasks.find { |t| t.name == task_name }
if task.nil?
raise Puppet::Module::Task::TaskNotFound.new(task_name, module_name)
end
begin
task.validate
{ :metadata => task.metadata, :files => task.files }
rescue Puppet::Module::Task::Error => err
{ :metadata => nil, :files => [], :error => err.to_h }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/metatype/manager.rb | lib/puppet/metatype/manager.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/util/classgen'
require_relative '../../puppet/node/environment'
# This module defines methods dealing with Type management.
# This module gets included into the Puppet::Type class, it's just split out here for clarity.
# @api public
#
module Puppet::MetaType
module Manager
include Puppet::Util::ClassGen
# An implementation specific method that removes all type instances during testing.
# @note Only use this method for testing purposes.
# @api private
#
def allclear
@types.each { |_name, type|
type.clear
}
end
# Clears any types that were used but absent when types were last loaded.
# @note Used after each catalog compile when always_retry_plugins is false
# @api private
#
def clear_misses
unless @types.nil?
@types.compact
end
end
# Iterates over all already loaded Type subclasses.
# @yield [t] a block receiving each type
# @yieldparam t [Puppet::Type] each defined type
# @yieldreturn [Object] the last returned object is also returned from this method
# @return [Object] the last returned value from the block.
def eachtype
@types.each do |_name, type|
# Only consider types that have names
# if ! type.parameters.empty? or ! type.validproperties.empty?
yield type
# end
end
end
# Loads all types.
# @note Should only be used for purposes such as generating documentation as this is potentially a very
# expensive operation.
# @return [void]
#
def loadall
typeloader.loadall(Puppet.lookup(:current_environment))
end
# Defines a new type or redefines an existing type with the given name.
# A convenience method on the form `new<name>` where name is the name of the type is also created.
# (If this generated method happens to clash with an existing method, a warning is issued and the original
# method is kept).
#
# @param name [String] the name of the type to create or redefine.
# @param options [Hash] options passed on to {Puppet::Util::ClassGen#genclass} as the option `:attributes`.
# @option options [Puppet::Type]
# Puppet::Type. This option is not passed on as an attribute to genclass.
# @yield [ ] a block evaluated in the context of the created class, thus allowing further detailing of
# that class.
# @return [Class<inherits Puppet::Type>] the created subclass
# @see Puppet::Util::ClassGen.genclass
#
# @dsl type
# @api public
def newtype(name, options = {}, &block)
@manager_lock.synchronize do
# Handle backward compatibility
unless options.is_a?(Hash)
# TRANSLATORS 'Puppet::Type.newtype' should not be translated
Puppet.warning(_("Puppet::Type.newtype(%{name}) now expects a hash as the second argument, not %{argument}") %
{ name: name, argument: options.inspect })
end
# First make sure we don't have a method sitting around
name = name.intern
newmethod = "new#{name}"
# Used for method manipulation.
selfobj = singleton_class
if @types.include?(name)
if respond_to?(newmethod)
# Remove the old newmethod
selfobj.send(:remove_method, newmethod)
end
end
# Then create the class.
klass = genclass(
name,
:parent => Puppet::Type,
:overwrite => true,
:hash => @types,
:attributes => options,
&block
)
# Now define a "new<type>" method for convenience.
if respond_to? newmethod
# Refuse to overwrite existing methods like 'newparam' or 'newtype'.
# TRANSLATORS 'new%{method}' will become a method name, do not translate this string
Puppet.warning(_("'new%{method}' method already exists; skipping") % { method: name.to_s })
else
selfobj.send(:define_method, newmethod) do |*args|
klass.new(*args)
end
end
# If they've got all the necessary methods defined and they haven't
# already added the property, then do so now.
klass.ensurable if klass.ensurable? and !klass.validproperty?(:ensure)
# Now set up autoload any providers that might exist for this type.
klass.providerloader = Puppet::Util::Autoload.new(klass, "puppet/provider/#{klass.name}")
# We have to load everything so that we can figure out the default provider.
klass.providerloader.loadall(Puppet.lookup(:current_environment))
klass.providify unless klass.providers.empty?
loc = block_given? ? block.source_location : nil
uri = loc.nil? ? nil : URI("#{Puppet::Util.path_to_uri(loc[0])}?line=#{loc[1]}")
Puppet::Pops::Loaders.register_runtime3_type(name, uri)
klass
end
end
# Removes an existing type.
# @note Only use this for testing.
# @api private
def rmtype(name)
# Then create the class.
rmclass(name, :hash => @types)
singleton_class.send(:remove_method, "new#{name}") if respond_to?("new#{name}")
end
# Returns a Type instance by name.
# This will load the type if not already defined.
# @param [String, Symbol] name of the wanted Type
# @return [Puppet::Type, nil] the type or nil if the type was not defined and could not be loaded
#
def type(name)
@manager_lock.synchronize do
# Avoid loading if name obviously is not a type name
if name.to_s.include?(':')
return nil
end
# We are overwhelmingly symbols here, which usually match, so it is worth
# having this special-case to return quickly. Like, 25K symbols vs. 300
# strings in this method. --daniel 2012-07-17
return @types[name] if @types.include? name
# Try mangling the name, if it is a string.
if name.is_a? String
name = name.downcase.intern
return @types[name] if @types.include? name
end
# Try loading the type.
if typeloader.load(name, Puppet.lookup(:current_environment))
# TRANSLATORS 'puppet/type/%{name}' should not be translated
Puppet.warning(_("Loaded puppet/type/%{name} but no class was created") % { name: name }) unless @types.include? name
elsif !Puppet[:always_retry_plugins]
# PUP-5482 - Only look for a type once if plugin retry is disabled
@types[name] = nil
end
# ...and I guess that is that, eh.
return @types[name]
end
end
# Creates a loader for Puppet types.
# Defaults to an instance of {Puppet::Util::Autoload} if no other auto loader has been set.
# @return [Puppet::Util::Autoload] the loader to use.
# @api private
def typeloader
unless defined?(@typeloader)
@typeloader = Puppet::Util::Autoload.new(self, "puppet/type")
end
@typeloader
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parameter/path.rb | lib/puppet/parameter/path.rb | # frozen_string_literal: true
require_relative '../../puppet/parameter'
# This specialized {Puppet::Parameter} handles validation and munging of paths.
# By default, a single path is accepted, and by calling {accept_arrays} it is possible to
# allow an array of paths.
#
class Puppet::Parameter::Path < Puppet::Parameter
# Specifies whether multiple paths are accepted or not.
# @dsl type
#
def self.accept_arrays(bool = true)
@accept_arrays = !!bool
end
def self.arrays?
@accept_arrays
end
# Performs validation of the given paths.
# If the concrete parameter defines a validation method, it may call this method to perform
# path validation.
# @raise [Puppet::Error] if this property is configured for single paths and an array is given
# @raise [Puppet::Error] if a path is not an absolute path
# @return [Array<String>] the given paths
#
def validate_path(paths)
if paths.is_a?(Array) and !self.class.arrays? then
fail _("%{name} only accepts a single path, not an array of paths") % { name: name }
end
fail(_("%{name} must be a fully qualified path") % { name: name }) unless Array(paths).all? { |path| absolute_path?(path) }
paths
end
# This is the default implementation of the `validate` method.
# It will be overridden if the validate option is used when defining the parameter.
# @return [void]
#
def unsafe_validate(paths)
validate_path(paths)
end
# This is the default implementation of `munge`.
# If the concrete parameter defines a `munge` method, this default implementation will be overridden.
# This default implementation does not perform any munging, it just checks the one/many paths
# constraints. A derived implementation can perform this check as:
# `paths.is_a?(Array) and ! self.class.arrays?` and raise a {Puppet::Error}.
# @param paths [String, Array<String>] one of multiple paths
# @return [String, Array<String>] the given paths
# @raise [Puppet::Error] if the given paths does not comply with the on/many paths rule.
def unsafe_munge(paths)
if paths.is_a?(Array) and !self.class.arrays? then
fail _("%{name} only accepts a single path, not an array of paths") % { name: name }
end
paths
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parameter/value.rb | lib/puppet/parameter/value.rb | # frozen_string_literal: true
require_relative '../../puppet/parameter/value_collection'
# Describes an acceptable value for a parameter or property.
# An acceptable value is either specified as a literal value or a regular expression.
# @note this class should be used via the api methods in {Puppet::Parameter} and {Puppet::Property}
# @api private
#
class Puppet::Parameter::Value
attr_reader :name, :options, :event
attr_accessor :block, :method, :required_features, :invalidate_refreshes
# Adds an alias for this value.
# Makes the given _name_ be an alias for this acceptable value.
# @param name [Symbol] the additional alias this value should be known as
# @api private
#
def alias(name)
@aliases << convert(name)
end
# @return [Array<Symbol>] Returns all aliases (or an empty array).
# @api private
#
def aliases
@aliases.dup
end
# Stores the event that our value generates, if it does so.
# @api private
#
def event=(value)
@event = convert(value)
end
# Initializes the instance with a literal accepted value, or a regular expression.
# If anything else is passed, it is turned into a String, and then made into a Symbol.
# @param name [Symbol, Regexp, Object] the value to accept, Symbol, a regular expression, or object to convert.
# @api private
#
def initialize(name)
if name.is_a?(Regexp)
@name = name
else
# Convert to a string and then a symbol, so things like true/false
# still show up as symbols.
@name = convert(name)
end
@aliases = []
end
# Checks if the given value matches the acceptance rules (literal value, regular expression, or one
# of the aliases.
# @api private
#
def match?(value)
if regex?
true if name =~ value.to_s
else
(name == convert(value) ? true : @aliases.include?(convert(value)))
end
end
# @return [Boolean] whether the accepted value is a regular expression or not.
# @api private
#
def regex?
@name.is_a?(Regexp)
end
private
# A standard way of converting all of our values, so we're always
# comparing apples to apples.
# @api private
#
def convert(value)
case value
when Symbol, '' # can't intern an empty string
value
when String
value.intern
when true
:true
when false
:false
else
value.to_s.intern
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parameter/boolean.rb | lib/puppet/parameter/boolean.rb | # frozen_string_literal: true
require_relative '../../puppet/coercion'
# This specialized {Puppet::Parameter} handles Boolean options, accepting lots
# of strings and symbols for both truth and falsehood.
#
class Puppet::Parameter::Boolean < Puppet::Parameter
def unsafe_munge(value)
Puppet::Coercion.boolean(value)
end
def self.initvars
super
@value_collection.newvalues(*Puppet::Coercion.boolean_values)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parameter/package_options.rb | lib/puppet/parameter/package_options.rb | # frozen_string_literal: true
require_relative '../../puppet/parameter'
# This specialized {Puppet::Parameter} handles munging of package options.
# Package options are passed as an array of key value pairs. Special munging is
# required as the keys and values needs to be quoted in a safe way.
#
class Puppet::Parameter::PackageOptions < Puppet::Parameter
def unsafe_munge(values)
values = [values] unless values.is_a? Array
values.collect do |val|
case val
when Hash
safe_hash = {}
val.each_pair do |k, v|
safe_hash[quote(k)] = quote(v)
end
safe_hash
when String
quote(val)
else
fail(_("Expected either a string or hash of options"))
end
end
end
# @api private
def quote(value)
value.include?(' ') ? %Q("#{value.gsub(/"/, '\"')}") : value
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parameter/value_collection.rb | lib/puppet/parameter/value_collection.rb | # frozen_string_literal: true
require_relative '../../puppet/parameter/value'
# A collection of values and regular expressions, used for specifying allowed values
# in a given parameter.
# @note This class is considered part of the internal implementation of {Puppet::Parameter}, and
# {Puppet::Property} and the functionality provided by this class should be used via their interfaces.
# @comment This class probably have several problems when trying to use it with a combination of
# regular expressions and aliases as it finds an acceptable value holder vi "name" which may be
# a regular expression...
#
# @api private
#
class Puppet::Parameter::ValueCollection
# Aliases the given existing _other_ value with the additional given _name_.
# @return [void]
# @api private
#
def aliasvalue(name, other)
other = other.to_sym
value = match?(other)
raise Puppet::DevError, _("Cannot alias nonexistent value %{value}") % { value: other } unless value
value.alias(name)
end
# Returns a doc string (enumerating the acceptable values) for all of the values in this parameter/property.
# @return [String] a documentation string.
# @api private
#
def doc
unless defined?(@doc)
@doc = ''.dup
unless values.empty?
@doc << "Valid values are "
@doc << @strings.collect do |value|
aliases = value.aliases
if aliases && !aliases.empty?
"`#{value.name}` (also called `#{aliases.join(', ')}`)"
else
"`#{value.name}`"
end
end.join(", ") << ". "
end
unless regexes.empty?
@doc << "Values can match `#{regexes.join('`, `')}`."
end
end
@doc
end
# @return [Boolean] Returns whether the set of allowed values is empty or not.
# @api private
#
def empty?
@values.empty?
end
# @api private
#
def initialize
# We often look values up by name, so a hash makes more sense.
@values = {}
# However, we want to retain the ability to match values in order,
# but we always prefer directly equality (i.e., strings) over regex matches.
@regexes = []
@strings = []
end
# Checks if the given value is acceptable (matches one of the literal values or patterns) and returns
# the "matcher" that matched.
# Literal string matchers are tested first, if both a literal and a regexp match would match, the literal
# match wins.
#
# @param test_value [Object] the value to test if it complies with the configured rules
# @return [Puppet::Parameter::Value, nil] The instance of Puppet::Parameter::Value that matched the given value, or nil if there was no match.
# @api private
#
def match?(test_value)
# First look for normal values
value = @strings.find { |v| v.match?(test_value) }
return value if value
# Then look for a regex match
@regexes.find { |v| v.match?(test_value) }
end
# Munges the value if it is valid, else produces the same value.
# @param value [Object] the value to munge
# @return [Object] the munged value, or the given value
# @todo This method does not seem to do any munging. It just returns the value if it matches the
# regexp, or the (most likely Symbolic) allowed value if it matches (which is more of a replacement
# of one instance with an equal one. Is the intent that this method should be specialized?
# @api private
#
def munge(value)
return value if empty?
instance = match?(value)
if instance
if instance.regex?
value
else
instance.name
end
else
value
end
end
# Defines a new valid value for a {Puppet::Property}.
# A valid value is specified as a literal (typically a Symbol), but can also be
# specified with a regexp.
#
# @param name [Symbol, Regexp] a valid literal value, or a regexp that matches a value
# @param options [Hash] a hash with options
# @option options [Symbol] :event The event that should be emitted when this value is set.
# @todo Option :event original comment says "event should be returned...", is "returned" the correct word
# to use?
# @option options [Symbol] :invalidate_refreshes True if a change on this property should invalidate and
# remove any scheduled refreshes (from notify or subscribe) targeted at the same resource. For example, if
# a change in this property takes into account any changes that a scheduled refresh would have performed,
# then the scheduled refresh would be deleted.
# @option options [Object] _any_ Any other option is treated as a call to a setter having the given
# option name (e.g. `:required_features` calls `required_features=` with the option's value as an
# argument).
# @api private
#
def newvalue(name, options = {}, &block)
call_opt = options[:call]
unless call_opt.nil?
devfail "Cannot use obsolete :call value '#{call_opt}' for property '#{self.class.name}'" unless call_opt == :none || call_opt == :instead
# TRANSLATORS ':call' is a property and should not be translated
message = _("Property option :call is deprecated and no longer used.")
message += ' ' + _("Please remove it.")
Puppet.deprecation_warning(message)
options = options.reject { |k, _v| k == :call }
end
value = Puppet::Parameter::Value.new(name)
@values[value.name] = value
if value.regex?
@regexes << value
else
@strings << value
end
options.each { |opt, arg| value.send(opt.to_s + "=", arg) }
if block_given?
devfail "Cannot use :call value ':none' in combination with a block for property '#{self.class.name}'" if call_opt == :none
value.block = block
value.method ||= "set_#{value.name}" unless value.regex?
elsif call_opt == :instead
devfail "Cannot use :call value ':instead' without a block for property '#{self.class.name}'"
end
value
end
# Defines one or more valid values (literal or regexp) for a parameter or property.
# @return [void]
# @dsl type
# @api private
#
def newvalues(*names)
names.each { |name| newvalue(name) }
end
# @return [Array<String>] An array of the regular expressions in string form, configured as matching valid values.
# @api private
#
def regexes
@regexes.collect { |r| r.name.inspect }
end
# Validates the given value against the set of valid literal values and regular expressions.
# @raise [ArgumentError] if the value is not accepted
# @return [void]
# @api private
#
def validate(value)
return if empty?
unless @values.detect { |_name, v| v.match?(value) }
str = _("Invalid value %{value}.") % { value: value.inspect }
str += " " + _("Valid values are %{value_list}.") % { value_list: values.join(", ") } unless values.empty?
str += " " + _("Valid values match %{pattern}.") % { pattern: regexes.join(", ") } unless regexes.empty?
raise ArgumentError, str
end
end
# Returns a valid value matcher (a literal or regular expression)
# @todo This looks odd, asking for an instance that matches a symbol, or an instance that has
# a regexp. What is the intention here? Marking as api private...
#
# @return [Puppet::Parameter::Value] a valid value matcher
# @api private
#
def value(name)
@values[name]
end
# @return [Array<Symbol>] Returns a list of valid literal values.
# @see regexes
# @api private
#
def values
@strings.collect(&:name)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/test/test_helper.rb | lib/puppet/test/test_helper.rb | # frozen_string_literal: true
require 'tmpdir'
require 'fileutils'
module Puppet::Test
# This class is intended to provide an API to be used by external projects
# when they are running tests that depend on puppet core. This should
# allow us to vary the implementation details of managing puppet's state
# for testing, from one version of puppet to the next--without forcing
# the external projects to do any of that state management or be aware of
# the implementation details.
#
# For now, this consists of a few very simple signatures. The plan is
# that it should be the responsibility of the puppetlabs_spec_helper
# to broker between external projects and this API; thus, if any
# hacks are required (e.g. to determine whether or not a particular)
# version of puppet supports this API, those hacks will be consolidated in
# one place and won't need to be duplicated in every external project.
#
# This should also alleviate the anti-pattern that we've been following,
# wherein each external project starts off with a copy of puppet core's
# test_helper.rb and is exposed to risk of that code getting out of
# sync with core.
#
# Since this class will be "library code" that ships with puppet, it does
# not use API from any existing test framework such as rspec. This should
# theoretically allow it to be used with other unit test frameworks in the
# future, if desired.
#
# Note that in the future this API could potentially be expanded to handle
# other features such as "around_test", but we didn't see a compelling
# reason to deal with that right now.
class TestHelper
# Call this method once, as early as possible, such as before loading tests
# that call Puppet.
# @return nil
def self.initialize
# This meta class instance variable is used as a guard to ensure that
# before_each, and after_each are only called once. This problem occurs
# when there are more than one puppet test infrastructure orchestrator in use.
# The use of both puppetabs-spec_helper, and rodjek-rspec_puppet will cause
# two resets of the puppet environment, and will cause problem rolling back to
# a known point as there is no way to differentiate where the calls are coming
# from. See more information in #before_each_test, and #after_each_test
# Note that the variable is only initialized to 0 if nil. This is important
# as more than one orchestrator will call initialize. A second call can not
# simply set it to 0 since that would potentially destroy an active guard.
#
@@reentry_count ||= 0
@environmentpath = Dir.mktmpdir('environments')
Dir.mkdir("#{@environmentpath}/production")
owner = Process.pid
Puppet.push_context(Puppet.base_context({
:environmentpath => @environmentpath,
:basemodulepath => "",
}), "Initial for specs")
Puppet::Parser::Functions.reset
ObjectSpace.define_finalizer(Puppet.lookup(:environments), proc {
if Process.pid == owner
FileUtils.rm_rf(@environmentpath)
end
})
Puppet::SSL::Oids.register_puppet_oids
end
# Call this method once, when beginning a test run--prior to running
# any individual tests.
# @return nil
def self.before_all_tests
# The process environment is a shared, persistent resource.
$old_env = ENV.to_hash
end
# Call this method once, at the end of a test run, when no more tests
# will be run.
# @return nil
def self.after_all_tests
end
# The name of the rollback mark used in the Puppet.context. This is what
# the test infrastructure returns to for each test.
#
ROLLBACK_MARK = "initial testing state"
# Call this method once per test, prior to execution of each individual test.
# @return nil
def self.before_each_test
# When using both rspec-puppet and puppet-rspec-helper, there are two packages trying
# to be helpful and orchestrate the callback sequence. We let only the first win, the
# second callback results in a no-op.
# Likewise when entering after_each_test(), a check is made to make tear down happen
# only once.
#
return unless @@reentry_count == 0
@@reentry_count = 1
Puppet.mark_context(ROLLBACK_MARK)
# We need to preserve the current state of all our indirection cache and
# terminus classes. This is pretty important, because changes to these
# are global and lead to order dependencies in our testing.
#
# We go direct to the implementation because there is no safe, sane public
# API to manage restoration of these to their default values. This
# should, once the value is proved, be moved to a standard API on the
# indirector.
#
# To make things worse, a number of the tests stub parts of the
# indirector. These stubs have very specific expectations that what
# little of the public API we could use is, well, likely to explode
# randomly in some tests. So, direct access. --daniel 2011-08-30
$saved_indirection_state = {}
indirections = Puppet::Indirector::Indirection.send(:class_variable_get, :@@indirections)
indirections.each do |indirector|
$saved_indirection_state[indirector.name] = {
:@terminus_class => indirector.instance_variable_get(:@terminus_class).value,
:@cache_class => indirector.instance_variable_get(:@cache_class).value,
# dup the termini hash so termini created and registered during
# the test aren't stored in our saved_indirection_state
:@termini => indirector.instance_variable_get(:@termini).dup
}
end
# So is the load_path
$old_load_path = $LOAD_PATH.dup
initialize_settings_before_each()
Puppet.push_context(
{
trusted_information:
Puppet::Context::TrustedInformation.new('local', 'testing', {}, { "trusted_testhelper" => true }),
ssl_context: Puppet::SSL::SSLContext.new(cacerts: []).freeze,
http_session: proc { Puppet.runtime[:http].create_session }
},
"Context for specs"
)
# trigger `require 'facter'`
Puppet.runtime[:facter]
Puppet::Parser::Functions.reset
Puppet::Application.clear!
Puppet::Util::Profiler.clear
Puppet::Node::Facts.indirection.terminus_class = :memory
facts = Puppet::Node::Facts.new(Puppet[:node_name_value])
Puppet::Node::Facts.indirection.save(facts)
Puppet.clear_deprecation_warnings
end
# Call this method once per test, after execution of each individual test.
# @return nil
def self.after_each_test
# Ensure that a matching tear down only happens once per completed setup
# (see #before_each_test).
return unless @@reentry_count == 1
@@reentry_count = 0
Puppet.settings.send(:clear_everything_for_tests)
Puppet::Util::Storage.clear
Puppet::Util::ExecutionStub.reset
Puppet.runtime.clear
Puppet.clear_deprecation_warnings
# uncommenting and manipulating this can be useful when tracking down calls to deprecated code
# Puppet.log_deprecations_to_file("deprecations.txt", /^Puppet::Util.exec/)
# Restore the indirector configuration. See before hook.
indirections = Puppet::Indirector::Indirection.send(:class_variable_get, :@@indirections)
indirections.each do |indirector|
$saved_indirection_state.fetch(indirector.name, {}).each do |variable, value|
if variable == :@termini
indirector.instance_variable_set(variable, value)
else
indirector.instance_variable_get(variable).value = value
end
end
end
$saved_indirection_state = nil
# Restore the global process environment.
ENV.replace($old_env)
# Clear all environments
Puppet.lookup(:environments).clear_all
# Restore the load_path late, to avoid messing with stubs from the test.
$LOAD_PATH.clear
$old_load_path.each { |x| $LOAD_PATH << x }
Puppet.rollback_context(ROLLBACK_MARK)
end
#########################################################################################
# PRIVATE METHODS (not part of the public TestHelper API--do not call these from outside
# of this class!)
#########################################################################################
def self.app_defaults_for_tests
{
:logdir => "/dev/null",
:confdir => "/dev/null",
:publicdir => "/dev/null",
:codedir => "/dev/null",
:vardir => "/dev/null",
:rundir => "/dev/null",
:hiera_config => "/dev/null",
}
end
private_class_method :app_defaults_for_tests
def self.initialize_settings_before_each
Puppet.settings.preferred_run_mode = "user"
# Initialize "app defaults" settings to a good set of test values
Puppet.settings.initialize_app_defaults(app_defaults_for_tests)
# We don't want to depend upon the reported domain name of the
# machine running the tests, nor upon the DNS setup of that
# domain.
Puppet.settings[:use_srv_records] = false
# Longer keys are secure, but they sure make for some slow testing - both
# in terms of generating keys, and in terms of anything the next step down
# the line doing validation or whatever. Most tests don't care how long
# or secure it is, just that it exists, so these are better and faster
# defaults, in testing only.
#
# I would make these even shorter, but OpenSSL doesn't support anything
# below 512 bits. Sad, really, because a 0 bit key would be just fine.
Puppet[:keylength] = 512
# Although we setup a testing context during initialization, some tests
# will end up creating their own context using the real context objects
# and use the setting for the environments. In order to avoid those tests
# having to deal with a missing environmentpath we can just set it right
# here.
Puppet[:environmentpath] = @environmentpath
Puppet[:environment_timeout] = 0
end
private_class_method :initialize_settings_before_each
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/store_configs.rb | lib/puppet/indirector/store_configs.rb | # frozen_string_literal: true
class Puppet::Indirector::StoreConfigs < Puppet::Indirector::Terminus
def initialize
super
# This will raise if the indirection can't be found, so we can assume it
# is always set to a valid instance from here on in.
@target = indirection.terminus Puppet[:storeconfigs_backend]
end
attr_reader :target
def head(request)
target.head request
end
def find(request)
target.find request
end
def search(request)
target.search request
end
def save(request)
target.save request
end
def destroy(request)
target.save request
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/direct_file_server.rb | lib/puppet/indirector/direct_file_server.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving/terminus_helper'
require_relative '../../puppet/indirector/terminus'
class Puppet::Indirector::DirectFileServer < Puppet::Indirector::Terminus
include Puppet::FileServing::TerminusHelper
def find(request)
return nil unless Puppet::FileSystem.exist?(request.key)
path2instance(request, request.key)
end
def search(request)
return nil unless Puppet::FileSystem.exist?(request.key)
path2instances(request, request.key)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/envelope.rb | lib/puppet/indirector/envelope.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector'
# Provide any attributes or functionality needed for indirected
# instances.
module Puppet::Indirector::Envelope
attr_accessor :expiration
def expired?
expiration and expiration < Time.now
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/plain.rb | lib/puppet/indirector/plain.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
# An empty terminus type, meant to just return empty objects.
class Puppet::Indirector::Plain < Puppet::Indirector::Terminus
# Just return nothing.
def find(request)
indirection.model.new(request.key)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/memory.rb | lib/puppet/indirector/memory.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
# Manage a memory-cached list of instances.
class Puppet::Indirector::Memory < Puppet::Indirector::Terminus
def initialize
clear
end
def clear
@instances = {}
end
def destroy(request)
raise ArgumentError, _("Could not find %{request} to destroy") % { request: request.key } unless @instances.include?(request.key)
@instances.delete(request.key)
end
def find(request)
@instances[request.key]
end
def search(request)
found_keys = @instances.keys.find_all { |key| key.include?(request.key) }
found_keys.collect { |key| @instances[key] }
end
def head(request)
!find(request).nil?
end
def save(request)
@instances[request.key] = request.instance
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/errors.rb | lib/puppet/indirector/errors.rb | # frozen_string_literal: true
require_relative '../../puppet/error'
module Puppet::Indirector
class ValidationError < Puppet::Error; end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/msgpack.rb | lib/puppet/indirector/msgpack.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
require_relative '../../puppet/util'
# The base class for MessagePack indirection terminus implementations.
#
# This should generally be preferred to the PSON base for any future
# implementations, since it is ~ 30 times faster
class Puppet::Indirector::Msgpack < Puppet::Indirector::Terminus
def initialize(*args)
unless Puppet.features.msgpack?
raise _("MessagePack terminus not supported without msgpack library")
end
super
end
def find(request)
load_msgpack_from_file(path(request.key), request.key)
end
def save(request)
filename = path(request.key)
FileUtils.mkdir_p(File.dirname(filename))
Puppet::FileSystem.replace_file(filename, 0o660) { |f| f.print to_msgpack(request.instance) }
rescue TypeError => detail
Puppet.log_exception(detail, _("Could not save %{name} %{request}: %{detail}") % { name: name, request: request.key, detail: detail })
end
def destroy(request)
Puppet::FileSystem.unlink(path(request.key))
rescue => detail
unless detail.is_a? Errno::ENOENT
raise Puppet::Error, _("Could not destroy %{name} %{request}: %{detail}") % { name: name, request: request.key, detail: detail }, detail.backtrace
end
1 # emulate success...
end
def search(request)
Dir.glob(path(request.key)).collect do |file|
load_msgpack_from_file(file, request.key)
end
end
# Return the path to a given node's file.
def path(name, ext = '.msgpack')
if name =~ Puppet::Indirector::BadNameRegexp then
Puppet.crit(_("directory traversal detected in %{indirection}: %{name}") % { indirection: self.class, name: name.inspect })
raise ArgumentError, _("invalid key")
end
base = Puppet.run_mode.server? ? Puppet[:server_datadir] : Puppet[:client_datadir]
File.join(base, self.class.indirection_name.to_s, name.to_s + ext)
end
private
def load_msgpack_from_file(file, key)
msgpack = nil
begin
msgpack = Puppet::FileSystem.read(file, :encoding => 'utf-8')
rescue Errno::ENOENT
return nil
rescue => detail
# TRANSLATORS "MessagePack" is a program name and should not be translated
raise Puppet::Error, _("Could not read MessagePack data for %{indirection} %{key}: %{detail}") % { indirection: indirection.name, key: key, detail: detail }, detail.backtrace
end
begin
from_msgpack(msgpack)
rescue => detail
raise Puppet::Error, _("Could not parse MessagePack data for %{indirection} %{key}: %{detail}") % { indirection: indirection.name, key: key, detail: detail }, detail.backtrace
end
end
def from_msgpack(text)
model.convert_from('msgpack', text)
end
def to_msgpack(object)
object.render('msgpack')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/terminus.rb | lib/puppet/indirector/terminus.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector'
require_relative '../../puppet/indirector/errors'
require_relative '../../puppet/indirector/indirection'
require_relative '../../puppet/util/instance_loader'
# A simple class that can function as the base class for indirected types.
class Puppet::Indirector::Terminus
require_relative '../../puppet/util/docs'
extend Puppet::Util::Docs
class << self
include Puppet::Util::InstanceLoader
attr_accessor :name, :terminus_type
attr_reader :abstract_terminus, :indirection
# Are we an abstract terminus type, rather than an instance with an
# associated indirection?
def abstract_terminus?
abstract_terminus
end
# Convert a constant to a short name.
def const2name(const)
const.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern
end
# Look up the indirection if we were only provided a name.
def indirection=(name)
if name.is_a?(Puppet::Indirector::Indirection)
@indirection = name
else
ind = Puppet::Indirector::Indirection.instance(name)
if ind
@indirection = ind
else
raise ArgumentError, _("Could not find indirection instance %{name} for %{terminus}") % { name: name, terminus: self.name }
end
end
end
def indirection_name
@indirection.name
end
# Register our subclass with the appropriate indirection.
# This follows the convention that our terminus is named after the
# indirection.
def inherited(subclass)
longname = subclass.to_s
if longname =~ /#<Class/
raise Puppet::DevError, _("Terminus subclasses must have associated constants")
end
names = longname.split("::")
# Convert everything to a lower-case symbol, converting camelcase to underscore word separation.
name = names.pop.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern
subclass.name = name
# Short-circuit the abstract types, which are those that directly subclass
# the Terminus class.
if self == Puppet::Indirector::Terminus
subclass.mark_as_abstract_terminus
return
end
# Set the terminus type to be the name of the abstract terminus type.
# Yay, class/instance confusion.
subclass.terminus_type = self.name
# This subclass is specifically associated with an indirection.
raise("Invalid name #{longname}") unless names.length > 0
processed_name = names.pop.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }
if processed_name.empty?
raise Puppet::DevError, _("Could not discern indirection model from class constant")
end
# This will throw an exception if the indirection instance cannot be found.
# Do this last, because it also registers the terminus type with the indirection,
# which needs the above information.
subclass.indirection = processed_name.intern
# And add this instance to the instance hash.
Puppet::Indirector::Terminus.register_terminus_class(subclass)
end
# Mark that this instance is abstract.
def mark_as_abstract_terminus
@abstract_terminus = true
end
def model
indirection.model
end
# Convert a short name to a constant.
def name2const(name)
name.to_s.capitalize.sub(/_(.)/) { |_i| ::Regexp.last_match(1).upcase }
end
# Register a class, probably autoloaded.
def register_terminus_class(klass)
setup_instance_loading klass.indirection_name
instance_hash(klass.indirection_name)[klass.name] = klass
end
# Return a terminus by name, using the autoloader.
def terminus_class(indirection_name, terminus_type)
setup_instance_loading indirection_name
loaded_instance(indirection_name, terminus_type)
end
# Return all terminus classes for a given indirection.
def terminus_classes(indirection_name)
setup_instance_loading indirection_name
instance_loader(indirection_name).files_to_load(Puppet.lookup(:current_environment)).map do |file|
File.basename(file).chomp(".rb").intern
end
end
private
def setup_instance_loading(type)
instance_load type, "puppet/indirector/#{type}" unless instance_loading?(type)
end
end
def indirection
self.class.indirection
end
def initialize
raise Puppet::DevError, _("Cannot create instances of abstract terminus types") if self.class.abstract_terminus?
end
def model
self.class.model
end
def name
self.class.name
end
def require_environment?
true
end
def allow_remote_requests?
true
end
def terminus_type
self.class.terminus_type
end
def validate(request)
if request.instance
validate_model(request)
validate_key(request)
end
end
def validate_key(request)
unless request.key == request.instance.name
raise Puppet::Indirector::ValidationError, _("Instance name %{name} does not match requested key %{key}") % { name: request.instance.name.inspect, key: request.key.inspect }
end
end
def validate_model(request)
unless model === request.instance
raise Puppet::Indirector::ValidationError, _("Invalid instance type %{klass}, expected %{model_type}") % { klass: request.instance.class.inspect, model_type: model.inspect }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/rest.rb | lib/puppet/indirector/rest.rb | # frozen_string_literal: true
# Access objects via REST
class Puppet::Indirector::REST < Puppet::Indirector::Terminus
def find(request)
raise NotImplementedError
end
def head(request)
raise NotImplementedError
end
def search(request)
raise NotImplementedError
end
def destroy(request)
raise NotImplementedError
end
def save(request)
raise NotImplementedError
end
def validate_key(request)
# Validation happens on the remote end
end
private
def convert_to_http_error(response)
if response.body.to_s.empty? && response.reason
returned_message = response.reason
elsif response['content-type'].is_a?(String)
content_type, body = parse_response(response)
if content_type =~ /[pj]son/
returned_message = Puppet::Util::Json.load(body)["message"]
else
returned_message = response.body
end
else
returned_message = response.body
end
message = _("Error %{code} on SERVER: %{returned_message}") % { code: response.code, returned_message: returned_message }
Net::HTTPError.new(message, Puppet::HTTP::ResponseConverter.to_ruby_response(response))
end
# Returns the content_type, stripping any appended charset, and the
# body, decompressed if necessary
def parse_response(response)
if response['content-type']
[response['content-type'].gsub(/\s*;.*$/, ''), response.body]
else
raise _("No content type in http response; cannot parse")
end
end
def elide(string, length)
if Puppet::Util::Log.level == :debug || string.length <= length
string
else
string[0, length - 3] + "..."
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/code.rb | lib/puppet/indirector/code.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
# Do nothing, requiring that the back-end terminus do all
# of the work.
class Puppet::Indirector::Code < Puppet::Indirector::Terminus
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/yaml.rb | lib/puppet/indirector/yaml.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
require_relative '../../puppet/util/yaml'
# The base class for YAML indirection termini.
class Puppet::Indirector::Yaml < Puppet::Indirector::Terminus
# Read a given name's file in and convert it from YAML.
def find(request)
file = path(request.key)
return nil unless Puppet::FileSystem.exist?(file)
begin
load_file(file)
rescue Puppet::Util::Yaml::YamlLoadError => detail
raise Puppet::Error, _("Could not parse YAML data for %{indirection} %{request}: %{detail}") % { indirection: indirection.name, request: request.key, detail: detail }, detail.backtrace
end
end
# Convert our object to YAML and store it to the disk.
def save(request)
raise ArgumentError, _("You can only save objects that respond to :name") unless request.instance.respond_to?(:name)
file = path(request.key)
basedir = File.dirname(file)
# This is quite likely a bad idea, since we're not managing ownership or modes.
Dir.mkdir(basedir) unless Puppet::FileSystem.exist?(basedir)
begin
Puppet::Util::Yaml.dump(request.instance, file)
rescue TypeError => detail
Puppet.err _("Could not save %{indirection} %{request}: %{detail}") % { indirection: name, request: request.key, detail: detail }
end
end
# Return the path to a given node's file.
def path(name, ext = '.yaml')
if name =~ Puppet::Indirector::BadNameRegexp then
Puppet.crit(_("directory traversal detected in %{indirection}: %{name}") % { indirection: self.class, name: name.inspect })
raise ArgumentError, _("invalid key")
end
base = Puppet.run_mode.server? ? Puppet[:yamldir] : Puppet[:clientyamldir]
File.join(base, self.class.indirection_name.to_s, name.to_s + ext)
end
def destroy(request)
file_path = path(request.key)
Puppet::FileSystem.unlink(file_path) if Puppet::FileSystem.exist?(file_path)
end
def search(request)
Dir.glob(path(request.key, '')).collect do |file|
load_file(file)
end
end
protected
def load_file(file)
Puppet::Util::Yaml.safe_load_file(file, [model, Symbol])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/json.rb | lib/puppet/indirector/json.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
require_relative '../../puppet/util'
# The base class for JSON indirection terminus implementations.
#
# This should generally be preferred to the YAML base for any future
# implementations, since it is faster and can load untrusted data safely.
class Puppet::Indirector::JSON < Puppet::Indirector::Terminus
def find(request)
load_json_from_file(path(request.key), request.key)
end
def save(request)
filename = path(request.key)
FileUtils.mkdir_p(File.dirname(filename))
Puppet::FileSystem.replace_file(filename, 0o660) { |f| f.print to_json(request.instance).force_encoding(Encoding::BINARY) }
rescue TypeError => detail
Puppet.log_exception(detail, _("Could not save %{json} %{request}: %{detail}") % { json: name, request: request.key, detail: detail })
end
def destroy(request)
Puppet::FileSystem.unlink(path(request.key))
rescue => detail
unless detail.is_a? Errno::ENOENT
raise Puppet::Error, _("Could not destroy %{json} %{request}: %{detail}") % { json: name, request: request.key, detail: detail }, detail.backtrace
end
1 # emulate success...
end
def search(request)
Dir.glob(path(request.key)).collect do |file|
load_json_from_file(file, request.key)
end
end
# Return the path to a given node's file.
def path(name, ext = '.json')
if name =~ Puppet::Indirector::BadNameRegexp then
Puppet.crit(_("directory traversal detected in %{json}: %{name}") % { json: self.class, name: name.inspect })
raise ArgumentError, _("invalid key")
end
base = data_dir
File.join(base, self.class.indirection_name.to_s, name.to_s + ext)
end
private
def data_dir
Puppet.run_mode.server? ? Puppet[:server_datadir] : Puppet[:client_datadir]
end
def load_json_from_file(file, key)
json = nil
begin
json = Puppet::FileSystem.read(file, :encoding => Encoding::BINARY)
rescue Errno::ENOENT
return nil
rescue => detail
raise Puppet::Error, _("Could not read JSON data for %{name} %{key}: %{detail}") % { name: indirection.name, key: key, detail: detail }, detail.backtrace
end
begin
from_json(json)
rescue => detail
raise Puppet::Error, _("Could not parse JSON data for %{name} %{key}: %{detail}") % { name: indirection.name, key: key, detail: detail }, detail.backtrace
end
end
def from_json(text)
model.convert_from('json', text.force_encoding(Encoding::UTF_8))
end
def to_json(object)
object.render('json')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/hiera.rb | lib/puppet/indirector/hiera.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
require 'hiera/scope'
# This class can't be collapsed into Puppet::Indirector::DataBindings::Hiera
# because some community plugins rely on this class directly, see PUP-1843.
# This class is deprecated and will be deleted in a future release.
# Use `Puppet::DataBinding.indirection.terminus(:hiera)` instead.
class Puppet::Indirector::Hiera < Puppet::Indirector::Terminus
def initialize(*args)
unless Puppet.features.hiera?
# TRANSLATORS "Hiera" is the name of a code library and should not be translated
raise _("Hiera terminus not supported without hiera library")
end
super
end
if defined?(::Psych::SyntaxError)
DataBindingExceptions = [::StandardError, ::Psych::SyntaxError]
else
DataBindingExceptions = [::StandardError]
end
def find(request)
not_found = Object.new
options = request.options
Puppet.debug { "Performing a hiera indirector lookup of #{request.key} with options #{options.inspect}" }
value = hiera.lookup(request.key, not_found, Hiera::Scope.new(options[:variables]), nil, convert_merge(options[:merge]))
throw :no_such_key if value.equal?(not_found)
value
rescue *DataBindingExceptions => detail
error = Puppet::DataBinding::LookupError.new("DataBinding 'hiera': #{detail.message}")
error.set_backtrace(detail.backtrace)
raise error
end
private
# Converts a lookup 'merge' parameter argument into a Hiera 'resolution_type' argument.
#
# @param merge [String,Hash,nil] The lookup 'merge' argument
# @return [Symbol,Hash,nil] The Hiera 'resolution_type'
def convert_merge(merge)
case merge
when nil, 'first'
# Nil is OK. Defaults to Hiera :priority
nil
when Puppet::Pops::MergeStrategy
convert_merge(merge.configuration)
when 'unique'
# Equivalent to Hiera :array
:array
when 'hash'
# Equivalent to Hiera :hash with default :native merge behavior. A Hash must be passed here
# to override possible Hiera deep merge config settings.
{ :behavior => :native }
when 'deep'
# Equivalent to Hiera :hash with :deeper merge behavior.
{ :behavior => :deeper }
when Hash
strategy = merge['strategy']
if strategy == 'deep'
result = { :behavior => :deeper }
# Remaining entries must have symbolic keys
merge.each_pair { |k, v| result[k.to_sym] = v unless k == 'strategy' }
result
else
convert_merge(strategy)
end
else
# TRANSLATORS "merge" is a parameter name and should not be translated
raise Puppet::DataBinding::LookupError, _("Unrecognized value for request 'merge' parameter: '%{merge}'") % { merge: merge }
end
end
public
def self.hiera_config
hiera_config = Puppet.settings[:hiera_config]
config = {}
if Puppet::FileSystem.exist?(hiera_config)
config = Hiera::Config.load(hiera_config)
else
Puppet.warning _("Config file %{hiera_config} not found, using Hiera defaults") % { hiera_config: hiera_config }
end
config[:logger] = 'puppet'
config
end
def self.hiera
@hiera ||= Hiera.new(:config => hiera_config)
end
def hiera
self.class.hiera
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/exec.rb | lib/puppet/indirector/exec.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
require_relative '../../puppet/util'
class Puppet::Indirector::Exec < Puppet::Indirector::Terminus
# Look for external node definitions.
def find(request)
name = request.key
external_command = command
# Make sure it's an array
raise Puppet::DevError, _("Exec commands must be an array") unless external_command.is_a?(Array)
# Make sure it's fully qualified.
raise ArgumentError, _("You must set the exec parameter to a fully qualified command") unless Puppet::Util.absolute_path?(external_command[0])
# Add our name to it.
external_command << name
begin
output = execute(external_command, :failonfail => true, :combine => false)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Failed to find %{name} via exec: %{detail}") % { name: name, detail: detail }, detail.backtrace
end
if output =~ /\A\s*\Z/ # all whitespace
Puppet.debug { "Empty response for #{name} from #{self.name} terminus" }
nil
else
output
end
end
private
# Proxy the execution, so it's easier to test.
def execute(command, arguments)
Puppet::Util::Execution.execute(command, arguments)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/generic_http.rb | lib/puppet/indirector/generic_http.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving/terminus_helper'
class Puppet::Indirector::GenericHttp < Puppet::Indirector::Terminus
desc "Retrieve data from a remote HTTP server."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/face.rb | lib/puppet/indirector/face.rb | # frozen_string_literal: true
require_relative '../../puppet/face'
class Puppet::Indirector::Face < Puppet::Face
option "--terminus _" + _("TERMINUS") do
summary _("The indirector terminus to use.")
description <<-EOT
Indirector faces expose indirected subsystems of Puppet. These
subsystems are each able to retrieve and alter a specific type of data
(with the familiar actions of `find`, `search`, `save`, and `destroy`)
from an arbitrary number of pluggable backends. In Puppet parlance,
these backends are called terminuses.
Almost all indirected subsystems have a `rest` terminus that interacts
with the puppet master's data. Most of them have additional terminuses
for various local data models, which are in turn used by the indirected
subsystem on the puppet master whenever it receives a remote request.
The terminus for an action is often determined by context, but
occasionally needs to be set explicitly. See the "Notes" section of this
face's manpage for more details.
EOT
before_action do |_action, _args, options|
set_terminus(options[:terminus])
end
after_action do |_action, _args, _options|
indirection.reset_terminus_class
end
end
def self.indirections
Puppet::Indirector::Indirection.instances.collect(&:to_s).sort
end
def self.terminus_classes(indirection)
Puppet::Indirector::Terminus.terminus_classes(indirection.to_sym).collect(&:to_s).sort
end
def call_indirection_method(method, key, options)
begin
if method == :save
# key is really the instance to save
result = indirection.__send__(method, key, nil, options)
else
result = indirection.__send__(method, key, options)
end
rescue => detail
message = _("Could not call '%{method}' on '%{indirection}': %{detail}") % { method: method, indirection: indirection_name, detail: detail }
Puppet.log_exception(detail, message)
raise RuntimeError, message, detail.backtrace
end
result
end
action :destroy do
summary _("Delete an object.")
arguments _("<key>")
when_invoked { |key, _options| call_indirection_method :destroy, key, {} }
end
action :find do
summary _("Retrieve an object by name.")
arguments _("[<key>]")
when_invoked do |*args|
# Default the key to Puppet[:certname] if none is supplied
if args.length == 1
key = Puppet[:certname]
else
key = args.first
end
call_indirection_method :find, key, {}
end
end
action :save do
summary _("API only: create or overwrite an object.")
arguments _("<key>")
description <<-EOT
API only: create or overwrite an object. As the Faces framework does not
currently accept data from STDIN, save actions cannot currently be invoked
from the command line.
EOT
when_invoked { |key, _options| call_indirection_method :save, key, {} }
end
action :search do
summary _("Search for an object or retrieve multiple objects.")
arguments _("<query>")
when_invoked { |key, _options| call_indirection_method :search, key, {} }
end
# Print the configuration for the current terminus class
action :info do
summary _("Print the default terminus class for this face.")
description <<-EOT
Prints the default terminus class for this subcommand. Note that different
run modes may have different default termini; when in doubt, specify the
run mode with the '--run_mode' option.
EOT
when_invoked do |_options|
if indirection.terminus_class
_("Run mode '%{mode}': %{terminus}") % { mode: Puppet.run_mode.name, terminus: indirection.terminus_class }
else
_("No default terminus class for run mode '%{mode}'") % { mode: Puppet.run_mode.name }
end
end
end
attr_accessor :from
def indirection_name
@indirection_name || name.to_sym
end
# Here's your opportunity to override the indirection name. By default it
# will be the same name as the face.
def set_indirection_name(name)
@indirection_name = name
end
# Return an indirection associated with a face, if one exists;
# One usually does.
def indirection
unless @indirection
@indirection = Puppet::Indirector::Indirection.instance(indirection_name)
@indirection or raise _("Could not find terminus for %{indirection}") % { indirection: indirection_name }
end
@indirection
end
def set_terminus(from)
indirection.terminus_class = from
rescue => detail
msg = _("Could not set '%{indirection}' terminus to '%{from}' (%{detail}); valid terminus types are %{types}") % { indirection: indirection.name, from: from, detail: detail, types: self.class.terminus_classes(indirection.name).join(", ") }
raise detail, msg, detail.backtrace
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/fact_search.rb | lib/puppet/indirector/fact_search.rb | # frozen_string_literal: true
# module containing common methods used by json and yaml facts indirection terminus
module Puppet::Indirector::FactSearch
def node_matches?(facts, options)
options.each do |key, value|
type, name, operator = key.to_s.split(".")
operator ||= 'eq'
return false unless node_matches_option?(type, name, operator, value, facts)
end
true
end
def node_matches_option?(type, name, operator, value, facts)
case type
when "meta"
case name
when "timestamp"
compare_timestamp(operator, facts.timestamp, Time.parse(value))
end
when "facts"
compare_facts(operator, facts.values[name], value)
end
end
def compare_facts(operator, value1, value2)
return false unless value1
case operator
when "eq"
value1.to_s == value2.to_s
when "le"
value1.to_f <= value2.to_f
when "ge"
value1.to_f >= value2.to_f
when "lt"
value1.to_f < value2.to_f
when "gt"
value1.to_f > value2.to_f
when "ne"
value1.to_s != value2.to_s
end
end
def compare_timestamp(operator, value1, value2)
case operator
when "eq"
value1 == value2
when "le"
value1 <= value2
when "ge"
value1 >= value2
when "lt"
value1 < value2
when "gt"
value1 > value2
when "ne"
value1 != value2
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_content.rb | lib/puppet/indirector/file_content.rb | # frozen_string_literal: true
# A stub class, so our constants work.
class Puppet::Indirector::FileContent # :nodoc:
end
require_relative '../../puppet/file_serving/content'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/indirection.rb | lib/puppet/indirector/indirection.rb | # frozen_string_literal: true
require_relative '../../puppet/util/docs'
require_relative '../../puppet/util/profiler'
require_relative '../../puppet/indirector/envelope'
require_relative '../../puppet/indirector/request'
require_relative '../../puppet/thread_local'
# The class that connects functional classes with their different collection
# back-ends. Each indirection has a set of associated terminus classes,
# each of which is a subclass of Puppet::Indirector::Terminus.
class Puppet::Indirector::Indirection
include Puppet::Util::Docs
attr_accessor :name, :model
attr_reader :termini
@@indirections = []
# Find an indirection by name. This is provided so that Terminus classes
# can specifically hook up with the indirections they are associated with.
def self.instance(name)
@@indirections.find { |i| i.name == name }
end
# Return a list of all known indirections. Used to generate the
# reference.
def self.instances
@@indirections.collect(&:name)
end
# Find an indirected model by name. This is provided so that Terminus classes
# can specifically hook up with the indirections they are associated with.
def self.model(name)
match = @@indirections.find { |i| i.name == name }
return nil unless match
match.model
end
# Create and return our cache terminus.
def cache
raise Puppet::DevError, _("Tried to cache when no cache class was set") unless cache_class
terminus(cache_class)
end
# Should we use a cache?
def cache?
cache_class ? true : false
end
def cache_class
@cache_class.value
end
# Define a terminus class to be used for caching.
def cache_class=(class_name)
validate_terminus_class(class_name) if class_name
@cache_class.value = class_name
end
# This is only used for testing.
def delete
@@indirections.delete(self) if @@indirections.include?(self)
end
# Set the time-to-live for instances created through this indirection.
def ttl=(value)
# TRANSLATORS "TTL" stands for "time to live" and refers to a duration of time
raise ArgumentError, _("Indirection TTL must be an integer") unless value.is_a?(Integer)
@ttl = value
end
# Default to the runinterval for the ttl.
def ttl
@ttl ||= Puppet[:runinterval]
end
# Calculate the expiration date for a returned instance.
def expiration
Time.now + ttl
end
# Generate the full doc string.
def doc
text = ''.dup
text << scrub(@doc) << "\n\n" if @doc
text << "* **Indirected Class**: `#{@indirected_class}`\n";
if terminus_setting
text << "* **Terminus Setting**: #{terminus_setting}\n"
end
text
end
def initialize(model, name, doc: nil, indirected_class: nil, cache_class: nil, terminus_class: nil, terminus_setting: nil, extend: nil)
@model = model
@name = name
@termini = {}
@doc = doc
raise(ArgumentError, _("Indirection %{name} is already defined") % { name: @name }) if @@indirections.find { |i| i.name == @name }
@@indirections << self
@indirected_class = indirected_class
self.extend(extend) if extend
# Setting these depend on the indirection already being installed so they have to be at the end
set_global_setting(:cache_class, cache_class)
set_global_setting(:terminus_class, terminus_class)
set_global_setting(:terminus_setting, terminus_setting)
end
# Use this to set indirector settings globally across threads.
def set_global_setting(setting, value)
case setting
when :cache_class
validate_terminus_class(value) unless value.nil?
@cache_class = Puppet::ThreadLocal.new(value)
when :terminus_class
validate_terminus_class(value) unless value.nil?
@terminus_class = Puppet::ThreadLocal.new(value)
when :terminus_setting
@terminus_setting = Puppet::ThreadLocal.new(value)
else
raise(ArgumentError, _("The setting %{setting} is not a valid indirection setting.") % { setting: setting })
end
end
# Set up our request object.
def request(*args)
Puppet::Indirector::Request.new(name, *args)
end
# Return the singleton terminus for this indirection.
def terminus(terminus_name = nil)
# Get the name of the terminus.
raise Puppet::DevError, _("No terminus specified for %{name}; cannot redirect") % { name: name } unless terminus_name ||= terminus_class
termini[terminus_name] ||= make_terminus(terminus_name)
end
# These can be used to select the terminus class.
def terminus_setting
@terminus_setting.value
end
def terminus_setting=(setting)
@terminus_setting.value = setting
end
# Determine the terminus class.
def terminus_class
unless @terminus_class.value
setting = terminus_setting
if setting
self.terminus_class = Puppet.settings[setting]
else
raise Puppet::DevError, _("No terminus class nor terminus setting was provided for indirection %{name}") % { name: name }
end
end
@terminus_class.value
end
def reset_terminus_class
@terminus_class.value = nil
end
# Specify the terminus class to use.
def terminus_class=(klass)
validate_terminus_class(klass)
@terminus_class.value = klass
end
# This is used by terminus_class= and cache=.
def validate_terminus_class(terminus_class)
unless terminus_class and terminus_class.to_s != ""
raise ArgumentError, _("Invalid terminus name %{terminus_class}") % { terminus_class: terminus_class.inspect }
end
unless Puppet::Indirector::Terminus.terminus_class(name, terminus_class)
raise ArgumentError, _("Could not find terminus %{terminus_class} for indirection %{name}") %
{ terminus_class: terminus_class, name: name }
end
end
# Expire a cached object, if one is cached. Note that we don't actually
# remove it, we expire it and write it back out to disk. This way people
# can still use the expired object if they want.
def expire(key, options = {})
request = request(:expire, key, nil, options)
return nil unless cache? && !request.ignore_cache_save?
instance = cache.find(request(:find, key, nil, options))
return nil unless instance
Puppet.info _("Expiring the %{cache} cache of %{instance}") % { cache: name, instance: instance.name }
# Set an expiration date in the past
instance.expiration = Time.now - 60
cache.save(request(:save, nil, instance, options))
end
def allow_remote_requests?
terminus.allow_remote_requests?
end
# Search for an instance in the appropriate terminus, caching the
# results if caching is configured..
def find(key, options = {})
request = request(:find, key, nil, options)
terminus = prepare(request)
result = find_in_cache(request)
if !result.nil?
result
elsif request.ignore_terminus?
nil
else
# Otherwise, return the result from the terminus, caching if
# appropriate.
result = terminus.find(request)
unless result.nil?
result.expiration ||= expiration if result.respond_to?(:expiration)
if cache? && !request.ignore_cache_save?
Puppet.info _("Caching %{indirection} for %{request}") % { indirection: name, request: request.key }
begin
cache.save request(:save, key, result, options)
rescue => detail
Puppet.log_exception(detail)
raise detail
end
end
filtered = result
if terminus.respond_to?(:filter)
Puppet::Util::Profiler.profile(_("Filtered result for %{indirection} %{request}") % { indirection: name, request: request.key }, [:indirector, :filter, name, request.key]) do
filtered = terminus.filter(result)
rescue Puppet::Error => detail
Puppet.log_exception(detail)
raise detail
end
end
filtered
end
end
end
# Search for an instance in the appropriate terminus, and return a
# boolean indicating whether the instance was found.
def head(key, options = {})
request = request(:head, key, nil, options)
terminus = prepare(request)
# Look in the cache first, then in the terminus. Force the result
# to be a boolean.
!!(find_in_cache(request) || terminus.head(request))
end
def find_in_cache(request)
# See if our instance is in the cache and up to date.
cached = cache.find(request) if cache? && !request.ignore_cache?
return nil unless cached
if cached.expired?
Puppet.info _("Not using expired %{indirection} for %{request} from cache; expired at %{expiration}") % { indirection: name, request: request.key, expiration: cached.expiration }
return nil
end
Puppet.debug { "Using cached #{name} for #{request.key}" }
cached
rescue => detail
Puppet.log_exception(detail, _("Cached %{indirection} for %{request} failed: %{detail}") % { indirection: name, request: request.key, detail: detail })
nil
end
# Remove something via the terminus.
def destroy(key, options = {})
request = request(:destroy, key, nil, options)
terminus = prepare(request)
result = terminus.destroy(request)
if cache? and cache.find(request(:find, key, nil, options))
# Reuse the existing request, since it's equivalent.
cache.destroy(request)
end
result
end
# Search for more than one instance. Should always return an array.
def search(key, options = {})
request = request(:search, key, nil, options)
terminus = prepare(request)
result = terminus.search(request)
if result
raise Puppet::DevError, _("Search results from terminus %{terminus_name} are not an array") % { terminus_name: terminus.name } unless result.is_a?(Array)
result.each do |instance|
next unless instance.respond_to? :expiration
instance.expiration ||= expiration
end
result
end
end
# Save the instance in the appropriate terminus. This method is
# normally an instance method on the indirected class.
def save(instance, key = nil, options = {})
request = request(:save, key, instance, options)
terminus = prepare(request)
result = terminus.save(request) unless request.ignore_terminus?
# If caching is enabled, save our document there
cache.save(request) if cache? && !request.ignore_cache_save?
result
end
private
# Check authorization if there's a hook available; fail if there is one
# and it returns false.
def check_authorization(request, terminus)
# At this point, we're assuming authorization makes no sense without
# client information.
return unless request.node
# This is only to authorize via a terminus-specific authorization hook.
return unless terminus.respond_to?(:authorized?)
unless terminus.authorized?(request)
msg = if request.options.empty?
_("Not authorized to call %{method} on %{description}") %
{ method: request.method, description: request.description }
else
_("Not authorized to call %{method} on %{description} with %{option}") %
{ method: request.method, description: request.description, option: request.options.inspect }
end
raise ArgumentError, msg
end
end
# Pick the appropriate terminus, check the request's authorization, and return it.
# @param [Puppet::Indirector::Request] request instance
# @return [Puppet::Indirector::Terminus] terminus instance (usually a subclass
# of Puppet::Indirector::Terminus) for this request
def prepare(request)
# Pick our terminus.
terminus_name = terminus_class
dest_terminus = terminus(terminus_name)
check_authorization(request, dest_terminus)
dest_terminus.validate(request)
dest_terminus
end
# Create a new terminus instance.
def make_terminus(terminus_class)
# Load our terminus class.
klass = Puppet::Indirector::Terminus.terminus_class(name, terminus_class)
unless klass
raise ArgumentError, _("Could not find terminus %{terminus_class} for indirection %{indirection}") % { terminus_class: terminus_class, indirection: name }
end
klass.new
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/none.rb | lib/puppet/indirector/none.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/terminus'
# A none terminus type, meant to always return nil
class Puppet::Indirector::None < Puppet::Indirector::Terminus
def find(request)
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/request.rb | lib/puppet/indirector/request.rb | # frozen_string_literal: true
require 'cgi'
require 'uri'
require_relative '../../puppet/indirector'
require_relative '../../puppet/util/psych_support'
require_relative '../../puppet/util/warnings'
# This class encapsulates all of the information you need to make an
# Indirection call, and as a result also handles REST calls. It's somewhat
# analogous to an HTTP Request object, except tuned for our Indirector.
class Puppet::Indirector::Request
include Puppet::Util::PsychSupport
include Puppet::Util::Warnings
attr_accessor :key, :method, :options, :instance, :node, :ip, :authenticated, :ignore_cache, :ignore_cache_save, :ignore_terminus
attr_accessor :server, :port, :uri, :protocol
attr_reader :indirection_name
# trusted_information is specifically left out because we can't serialize it
# and keep it "trusted"
OPTION_ATTRIBUTES = [:ip, :node, :authenticated, :ignore_terminus, :ignore_cache, :ignore_cache_save, :instance, :environment]
# Is this an authenticated request?
def authenticated?
# Double negative, so we just get true or false
!!authenticated
end
def environment
# If environment has not been set directly, we should use the application's
# current environment
@environment ||= Puppet.lookup(:current_environment)
end
def environment=(env)
@environment =
if env.is_a?(Puppet::Node::Environment)
env
else
Puppet.lookup(:environments).get!(env)
end
end
# LAK:NOTE This is a messy interface to the cache, and it's only
# used by the Configurer class. I decided it was better to implement
# it now and refactor later, when we have a better design, than
# to spend another month coming up with a design now that might
# not be any better.
def ignore_cache?
ignore_cache
end
def ignore_cache_save?
ignore_cache_save
end
def ignore_terminus?
ignore_terminus
end
def initialize(indirection_name, method, key, instance, options = {})
@instance = instance
options ||= {}
self.indirection_name = indirection_name
self.method = method
options = options.each_with_object({}) { |ary, hash| hash[ary[0].to_sym] = ary[1]; }
set_attributes(options)
@options = options
if key
# If the request key is a URI, then we need to treat it specially,
# because it rewrites the key. We could otherwise strip server/port/etc
# info out in the REST class, but it seemed bad design for the REST
# class to rewrite the key.
if key.to_s =~ %r{^\w+:/} and !Puppet::Util.absolute_path?(key.to_s) # it's a URI
set_uri_key(key)
else
@key = key
end
end
@key = @instance.name if !@key and @instance
end
# Look up the indirection based on the name provided.
def indirection
Puppet::Indirector::Indirection.instance(indirection_name)
end
def indirection_name=(name)
@indirection_name = name.to_sym
end
def model
ind = indirection
raise ArgumentError, _("Could not find indirection '%{indirection}'") % { indirection: indirection_name } unless ind
ind.model
end
# Are we trying to interact with multiple resources, or just one?
def plural?
method == :search
end
def initialize_from_hash(hash)
@indirection_name = hash['indirection_name'].to_sym
@method = hash['method'].to_sym
@key = hash['key']
@instance = hash['instance']
@options = hash['options']
end
def to_data_hash
{ 'indirection_name' => @indirection_name.to_s,
'method' => @method.to_s,
'key' => @key,
'instance' => @instance,
'options' => @options }
end
def to_hash
result = options.dup
OPTION_ATTRIBUTES.each do |attribute|
value = send(attribute)
if value
result[attribute] = value
end
end
result
end
def description
uri || "/#{indirection_name}/#{key}"
end
def remote?
node or ip
end
private
def set_attributes(options)
OPTION_ATTRIBUTES.each do |attribute|
if options.include?(attribute.to_sym)
send(attribute.to_s + "=", options[attribute])
options.delete(attribute)
end
end
end
# Parse the key as a URI, setting attributes appropriately.
def set_uri_key(key)
@uri = key
begin
# calling uri_encode for UTF-8 characters will % escape them and keep them UTF-8
uri = URI.parse(Puppet::Util.uri_encode(key))
rescue => detail
raise ArgumentError, _("Could not understand URL %{key}: %{detail}") % { key: key, detail: detail }, detail.backtrace
end
# Just short-circuit these to full paths
if uri.scheme == "file"
@key = Puppet::Util.uri_to_path(uri)
return
end
@server = uri.host if uri.host && !uri.host.empty?
# If the URI class can look up the scheme, it will provide a port,
# otherwise it will default to '0'.
if uri.port.to_i == 0 and uri.scheme == "puppet"
@port = Puppet.settings[:serverport].to_i
else
@port = uri.port.to_i
end
# filebucket:// is only used internally to pass request details
# from Dipper objects to the indirector. The wire always uses HTTPS.
if uri.scheme == 'filebucket'
@protocol = 'https'
else
@protocol = uri.scheme
end
@key = Puppet::Util.uri_unescape(uri.path.sub(%r{^/}, ''))
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_metadata.rb | lib/puppet/indirector/file_metadata.rb | # frozen_string_literal: true
# A stub class, so our constants work.
class Puppet::Indirector::FileMetadata # :nodoc:
end
require_relative '../../puppet/file_serving/metadata'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_server.rb | lib/puppet/indirector/file_server.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving/configuration'
require_relative '../../puppet/file_serving/fileset'
require_relative '../../puppet/file_serving/terminus_helper'
require_relative '../../puppet/indirector/terminus'
# Look files up using the file server.
class Puppet::Indirector::FileServer < Puppet::Indirector::Terminus
include Puppet::FileServing::TerminusHelper
# Is the client authorized to perform this action?
def authorized?(request)
return false unless [:find, :search].include?(request.method)
mount, _ = configuration.split_path(request)
# If we're not serving this mount, then access is denied.
return false unless mount
true
end
# Find our key using the fileserver.
def find(request)
mount, relative_path = configuration.split_path(request)
return nil unless mount
# The mount checks to see if the file exists, and returns nil
# if not.
path = mount.find(relative_path, request)
return nil unless path
path2instance(request, path)
end
# Search for files. This returns an array rather than a single
# file.
def search(request)
mount, relative_path = configuration.split_path(request)
paths = mount.search(relative_path, request) if mount
unless paths
Puppet.info _("Could not find filesystem info for file '%{request}' in environment %{env}") % { request: request.key, env: request.environment }
return nil
end
path2instances(request, *paths)
end
private
# Our fileserver configuration, if needed.
def configuration
Puppet::FileServing::Configuration.configuration
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/catalog/store_configs.rb | lib/puppet/indirector/catalog/store_configs.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/store_configs'
require_relative '../../../puppet/resource/catalog'
class Puppet::Resource::Catalog::StoreConfigs < Puppet::Indirector::StoreConfigs
desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/catalog/compiler.rb | lib/puppet/indirector/catalog/compiler.rb | # frozen_string_literal: true
require_relative '../../../puppet/environments'
require_relative '../../../puppet/node'
require_relative '../../../puppet/node/server_facts'
require_relative '../../../puppet/resource/catalog'
require_relative '../../../puppet/indirector/code'
require_relative '../../../puppet/util/profiler'
require_relative '../../../puppet/util/checksums'
require 'yaml'
require 'uri'
class Puppet::Resource::Catalog::Compiler < Puppet::Indirector::Code
desc "Compiles catalogs on demand using Puppet's compiler."
include Puppet::Util
include Puppet::Util::Checksums
attr_accessor :code
# @param request [Puppet::Indirector::Request] an indirection request
# (possibly) containing facts
# @return [Puppet::Node::Facts] facts object corresponding to facts in request
def extract_facts_from_request(request)
text_facts = request.options[:facts]
return unless text_facts
format = request.options[:facts_format]
unless format
raise ArgumentError, _("Facts but no fact format provided for %{request}") % { request: request.key }
end
Puppet::Util::Profiler.profile(_("Found facts"), [:compiler, :find_facts]) do
facts = text_facts.is_a?(Puppet::Node::Facts) ? text_facts :
convert_wire_facts(text_facts, format)
unless facts.name == request.key
raise Puppet::Error, _("Catalog for %{request} was requested with fact definition for the wrong node (%{fact_name}).") % { request: request.key.inspect, fact_name: facts.name.inspect }
end
return facts
end
end
def save_facts_from_request(facts, request)
Puppet::Node::Facts.indirection.save(facts, nil,
:environment => request.environment,
:transaction_uuid => request.options[:transaction_uuid])
end
# Compile a node's catalog.
def find(request)
facts = extract_facts_from_request(request)
save_facts_from_request(facts, request) unless facts.nil?
node = node_from_request(facts, request)
node.trusted_data = Puppet.lookup(:trusted_information) { Puppet::Context::TrustedInformation.local(node) }.to_h
if node.environment
# If the requested environment name doesn't match the server specified environment
# name, as determined by the node terminus, and the request wants us to check for an
# environment mismatch, then return an empty catalog with the server-specified
# enviroment.
if request.remote? && request.options[:check_environment]
# The "environment" may be same while environment objects differ. This
# is most likely because the environment cache was flushed between the request
# processing and node lookup. Environment overrides `==` but requires the
# name and modulepath to be the same. When using versioned environment dirs the
# same "environment" can have different modulepaths so simply compare names here.
if node.environment.name != request.environment.name
Puppet.warning _("Requested environment '%{request_env}' did not match server specified environment '%{server_env}'") % { request_env: request.environment.name, server_env: node.environment.name }
return Puppet::Resource::Catalog.new(node.name, node.environment)
end
end
node.environment.with_text_domain do
envs = Puppet.lookup(:environments)
envs.guard(node.environment.name)
begin
compile(node, request.options)
ensure
envs.unguard(node.environment.name)
end
end
else
compile(node, request.options)
end
end
# filter-out a catalog to remove exported resources
def filter(catalog)
return catalog.filter(&:virtual?) if catalog.respond_to?(:filter)
catalog
end
def initialize
Puppet::Util::Profiler.profile(_("Setup server facts for compiling"), [:compiler, :init_server_facts]) do
set_server_facts
end
end
# Is our compiler part of a network, or are we just local?
def networked?
Puppet.run_mode.server?
end
def require_environment?
false
end
private
# @param facts [String] facts in a wire format for decoding
# @param format [String] a content-type string
# @return [Puppet::Node::Facts] facts object deserialized from supplied string
# @api private
def convert_wire_facts(facts, format)
case format
when 'pson'
# We unescape here because the corresponding code in Puppet::Configurer::FactHandler encodes with Puppet::Util.uri_query_encode
# PSON is deprecated, but continue to accept from older agents
Puppet::Node::Facts.convert_from('pson', CGI.unescape(facts))
when 'application/json'
Puppet::Node::Facts.convert_from('json', CGI.unescape(facts))
else
raise ArgumentError, _("Unsupported facts format")
end
end
# Add any extra data necessary to the node.
def add_node_data(node)
# Merge in our server-side facts, so they can be used during compilation.
node.add_server_facts(@server_facts)
end
# Determine which checksum to use; if agent_checksum_type is not nil,
# use the first entry in it that is also in known_checksum_types.
# If no match is found, return nil.
def common_checksum_type(agent_checksum_type)
if agent_checksum_type
agent_checksum_types = agent_checksum_type.split('.').map(&:to_sym)
checksum_type = agent_checksum_types.drop_while do |type|
!known_checksum_types.include? type
end.first
end
checksum_type
end
def get_content_uri(metadata, source, environment_path)
# The static file content server doesn't know how to expand mountpoints, so
# we need to do that ourselves from the actual system path of the source file.
# This does that, while preserving any user-specified server or port.
source_path = Pathname.new(metadata.full_path)
path = source_path.relative_path_from(environment_path).to_s
source_as_uri = URI.parse(Puppet::Util.uri_encode(source))
server = source_as_uri.host
port = ":#{source_as_uri.port}" if source_as_uri.port
"puppet://#{server}#{port}/#{path}"
end
# Helper method to decide if a file resource's metadata can be inlined.
# Also used to profile/log reasons for not inlining.
def inlineable?(resource, sources)
if resource[:ensure] == 'absent'
# TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining)
Puppet::Util::Profiler.profile(_("Not inlining absent resource"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :absent]) { false }
elsif sources.empty?
# TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining)
Puppet::Util::Profiler.profile(_("Not inlining resource without sources"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :no_sources]) { false }
elsif !sources.all? { |source| source =~ /^puppet:/ }
# TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining)
Puppet::Util::Profiler.profile(_("Not inlining unsupported source scheme"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :unsupported_scheme]) { false }
else
true
end
end
# Return true if metadata is inlineable, meaning the request's source is
# for the 'modules' mount and the resolved path is of the form:
# $codedir/environments/$environment/*/*/files/**
def inlineable_metadata?(metadata, source, environment_path)
source_as_uri = URI.parse(Puppet::Util.uri_encode(source))
location = Puppet::Module::FILETYPES['files']
!!(source_as_uri.path =~ %r{^/modules/} &&
metadata.full_path =~ %r{#{environment_path}/[^/]+/[^/]+/#{location}/.+})
end
# Helper method to log file resources that could not be inlined because they
# fall outside of an environment.
def log_file_outside_environment
# TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining)
Puppet::Util::Profiler.profile(_("Not inlining file outside environment"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :file_outside_environment]) { true }
end
# Helper method to log file resources that were successfully inlined.
def log_metadata_inlining
# TRANSLATORS Inlining refers to adding additional metadata
Puppet::Util::Profiler.profile(_("Inlining file metadata"), [:compiler, :static_compile_inlining, :inlined_file_metadata]) { true }
end
# Inline file metadata for static catalogs
# Initially restricted to files sourced from codedir via puppet:/// uri.
def inline_metadata(catalog, checksum_type)
environment_path = Pathname.new File.join(Puppet[:environmentpath], catalog.environment)
environment_path = Puppet::Environments::Directories.real_path(environment_path)
list_of_resources = catalog.resources.find_all { |res| res.type == "File" }
# TODO: get property/parameter defaults if entries are nil in the resource
# For now they're hard-coded to match the File type.
list_of_resources.each do |resource|
sources = [resource[:source]].flatten.compact
next unless inlineable?(resource, sources)
# both need to handle multiple sources
if resource[:recurse] == true || resource[:recurse] == 'true' || resource[:recurse] == 'remote'
# Construct a hash mapping sources to arrays (list of files found recursively) of metadata
options = {
:environment => catalog.environment_instance,
:links => resource[:links] ? resource[:links].to_sym : :manage,
:checksum_type => resource[:checksum] ? resource[:checksum].to_sym : checksum_type.to_sym,
:source_permissions => resource[:source_permissions] ? resource[:source_permissions].to_sym : :ignore,
:recurse => true,
:recurselimit => resource[:recurselimit],
:max_files => resource[:max_files],
:ignore => resource[:ignore],
}
sources_in_environment = true
source_to_metadatas = {}
sources.each do |source|
source = Puppet::Type.type(:file).attrclass(:source).normalize(source)
list_of_data = Puppet::FileServing::Metadata.indirection.search(source, options)
next unless list_of_data
basedir_meta = list_of_data.find { |meta| meta.relative_path == '.' }
devfail "FileServing::Metadata search should always return the root search path" if basedir_meta.nil?
unless inlineable_metadata?(basedir_meta, source, environment_path)
# If any source is not in the environment path, skip inlining this resource.
log_file_outside_environment
sources_in_environment = false
break
end
base_content_uri = get_content_uri(basedir_meta, source, environment_path)
list_of_data.each do |metadata|
if metadata.relative_path == '.'
metadata.content_uri = base_content_uri
else
metadata.content_uri = "#{base_content_uri}/#{metadata.relative_path}"
end
end
source_to_metadatas[source] = list_of_data
# Optimize for returning less data if sourceselect is first
if resource[:sourceselect] == 'first' || resource[:sourceselect].nil?
break
end
end
if sources_in_environment && !source_to_metadatas.empty?
log_metadata_inlining
catalog.recursive_metadata[resource.title] = source_to_metadatas
end
else
options = {
:environment => catalog.environment_instance,
:links => resource[:links] ? resource[:links].to_sym : :manage,
:checksum_type => resource[:checksum] ? resource[:checksum].to_sym : checksum_type.to_sym,
:source_permissions => resource[:source_permissions] ? resource[:source_permissions].to_sym : :ignore
}
metadata = nil
sources.each do |source|
source = Puppet::Type.type(:file).attrclass(:source).normalize(source)
data = Puppet::FileServing::Metadata.indirection.find(source, options)
next unless data
metadata = data
metadata.source = source
break
end
raise _("Could not get metadata for %{resource}") % { resource: resource[:source] } unless metadata
if inlineable_metadata?(metadata, metadata.source, environment_path)
metadata.content_uri = get_content_uri(metadata, metadata.source, environment_path)
log_metadata_inlining
# If the file is in the environment directory, we can safely inline
catalog.metadata[resource.title] = metadata
else
# Log a profiler event that we skipped this file because it is not in an environment.
log_file_outside_environment
end
end
end
end
# Compile the actual catalog.
def compile(node, options)
if node.environment && node.environment.static_catalogs? && options[:static_catalog] && options[:code_id]
# Check for errors before compiling the catalog
checksum_type = common_checksum_type(options[:checksum_type])
raise Puppet::Error, _("Unable to find a common checksum type between agent '%{agent_type}' and master '%{master_type}'.") % { agent_type: options[:checksum_type], master_type: known_checksum_types } unless checksum_type
end
escaped_node_name = node.name.gsub(/%/, '%%')
if checksum_type
if node.environment
escaped_node_environment = node.environment.to_s.gsub(/%/, '%%')
benchmark_str = _("Compiled static catalog for %{node} in environment %{environment} in %%{seconds} seconds") % { node: escaped_node_name, environment: escaped_node_environment }
profile_str = _("Compiled static catalog for %{node} in environment %{environment}") % { node: node.name, environment: node.environment }
else
benchmark_str = _("Compiled static catalog for %{node} in %%{seconds} seconds") % { node: escaped_node_name }
profile_str = _("Compiled static catalog for %{node}") % { node: node.name }
end
elsif node.environment
escaped_node_environment = node.environment.to_s.gsub(/%/, '%%')
benchmark_str = _("Compiled catalog for %{node} in environment %{environment} in %%{seconds} seconds") % { node: escaped_node_name, environment: escaped_node_environment }
profile_str = _("Compiled catalog for %{node} in environment %{environment}") % { node: node.name, environment: node.environment }
else
benchmark_str = _("Compiled catalog for %{node} in %%{seconds} seconds") % { node: escaped_node_name }
profile_str = _("Compiled catalog for %{node}") % { node: node.name }
end
config = nil
benchmark(:notice, benchmark_str) do
compile_type = checksum_type ? :static_compile : :compile
Puppet::Util::Profiler.profile(profile_str, [:compiler, compile_type, node.environment, node.name]) do
begin
config = Puppet::Parser::Compiler.compile(node, options[:code_id])
rescue Puppet::Error => detail
Puppet.err(detail.to_s) if networked?
raise
ensure
Puppet::Type.clear_misses unless Puppet[:always_retry_plugins]
end
if checksum_type && config.is_a?(model)
escaped_node_name = node.name.gsub(/%/, '%%')
if node.environment
escaped_node_environment = node.environment.to_s.gsub(/%/, '%%')
# TRANSLATORS Inlined refers to adding additional metadata
benchmark_str = _("Inlined resource metadata into static catalog for %{node} in environment %{environment} in %%{seconds} seconds") % { node: escaped_node_name, environment: escaped_node_environment }
# TRANSLATORS Inlined refers to adding additional metadata
profile_str = _("Inlined resource metadata into static catalog for %{node} in environment %{environment}") % { node: node.name, environment: node.environment }
else
# TRANSLATORS Inlined refers to adding additional metadata
benchmark_str = _("Inlined resource metadata into static catalog for %{node} in %%{seconds} seconds") % { node: escaped_node_name }
# TRANSLATORS Inlined refers to adding additional metadata
profile_str = _("Inlined resource metadata into static catalog for %{node}") % { node: node.name }
end
benchmark(:notice, benchmark_str) do
Puppet::Util::Profiler.profile(profile_str, [:compiler, :static_compile_postprocessing, node.environment, node.name]) do
inline_metadata(config, checksum_type)
end
end
end
end
end
config
end
# Use indirection to find the node associated with a given request
def find_node(name, environment, transaction_uuid, configured_environment, facts)
Puppet::Util::Profiler.profile(_("Found node information"), [:compiler, :find_node]) do
node = nil
begin
node = Puppet::Node.indirection.find(name, :environment => environment,
:transaction_uuid => transaction_uuid,
:configured_environment => configured_environment,
:facts => facts)
rescue => detail
message = _("Failed when searching for node %{name}: %{detail}") % { name: name, detail: detail }
Puppet.log_exception(detail, message)
raise Puppet::Error, message, detail.backtrace
end
# Add any external data to the node.
if node
add_node_data(node)
end
node
end
end
# Extract the node from the request, or use the request
# to find the node.
def node_from_request(facts, request)
node = request.options[:use_node]
if node
if request.remote?
raise Puppet::Error, _("Invalid option use_node for a remote request")
else
return node
end
end
# We rely on our authorization system to determine whether the connected
# node is allowed to compile the catalog's node referenced by key.
# By default the REST authorization system makes sure only the connected node
# can compile his catalog.
# This allows for instance monitoring systems or puppet-load to check several
# node's catalog with only one certificate and a modification to auth.conf
# If no key is provided we can only compile the currently connected node.
name = request.key || request.node
node = find_node(name, request.environment, request.options[:transaction_uuid], request.options[:configured_environment], facts)
if node
return node
end
raise ArgumentError, _("Could not find node '%{name}'; cannot compile") % { name: name }
end
# Initialize our server fact hash; we add these to each client, and they
# won't change while we're running, so it's safe to cache the values.
#
# See also set_server_facts in Puppet::Server::Compiler in puppetserver.
def set_server_facts
@server_facts = Puppet::Node::ServerFacts.load
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/catalog/msgpack.rb | lib/puppet/indirector/catalog/msgpack.rb | # frozen_string_literal: true
require_relative '../../../puppet/resource/catalog'
require_relative '../../../puppet/indirector/msgpack'
class Puppet::Resource::Catalog::Msgpack < Puppet::Indirector::Msgpack
desc "Store catalogs as flat files, serialized using MessagePack."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/catalog/rest.rb | lib/puppet/indirector/catalog/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/resource/catalog'
require_relative '../../../puppet/indirector/rest'
class Puppet::Resource::Catalog::Rest < Puppet::Indirector::REST
desc "Find resource catalogs over HTTP via REST."
def find(request)
checksum_type = if request.options[:checksum_type]
request.options[:checksum_type].split('.')
else
Puppet[:supported_checksum_types]
end
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
unless Puppet.settings[:skip_logging_catalog_request_destination]
ip_address = begin
" (#{Resolv.getaddress(api.url.host)})"
rescue Resolv::ResolvError
nil
end
Puppet.notice("Requesting catalog from #{api.url.host}:#{api.url.port}#{ip_address}")
end
_, catalog = api.post_catalog(
request.key,
facts: request.options[:facts_for_catalog],
environment: request.environment.to_s,
configured_environment: request.options[:configured_environment],
check_environment: request.options[:check_environment],
transaction_uuid: request.options[:transaction_uuid],
job_uuid: request.options[:job_id],
static_catalog: request.options[:static_catalog],
checksum_type: checksum_type
)
catalog
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
return nil unless request.options[:fail_on_404]
_, body = parse_response(e.response)
msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body }
raise Puppet::Error, msg
else
raise convert_to_http_error(e.response)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/catalog/yaml.rb | lib/puppet/indirector/catalog/yaml.rb | # frozen_string_literal: true
require_relative '../../../puppet/resource/catalog'
require_relative '../../../puppet/indirector/yaml'
class Puppet::Resource::Catalog::Yaml < Puppet::Indirector::Yaml
desc "Store catalogs as flat files, serialized using YAML."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/catalog/json.rb | lib/puppet/indirector/catalog/json.rb | # frozen_string_literal: true
require_relative '../../../puppet/resource/catalog'
require_relative '../../../puppet/indirector/json'
class Puppet::Resource::Catalog::Json < Puppet::Indirector::JSON
desc "Store catalogs as flat files, serialized using JSON."
def from_json(text)
utf8 = text.force_encoding(Encoding::UTF_8)
if utf8.valid_encoding?
model.convert_from(json_format, utf8)
else
Puppet.info(_("Unable to deserialize catalog from json, retrying with pson"))
model.convert_from('pson', text.force_encoding(Encoding::BINARY))
end
end
def to_json(object)
object.render(json_format)
rescue Puppet::Network::FormatHandler::FormatError => err
if Puppet[:allow_pson_serialization]
Puppet.info(_("Unable to serialize catalog to json, retrying with pson. PSON is deprecated and will be removed in a future release"))
Puppet.log_exception(err, err.message, level: :debug)
object.render('pson').force_encoding(Encoding::BINARY)
else
Puppet.info(_("Unable to serialize catalog to json, no other acceptable format"))
Puppet.log_exception(err, err.message, level: :err)
end
end
private
def json_format
if Puppet[:rich_data]
'rich_data_json'
else
'json'
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/resource/store_configs.rb | lib/puppet/indirector/resource/store_configs.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/store_configs'
require_relative '../../../puppet/indirector/resource/validator'
class Puppet::Resource::StoreConfigs < Puppet::Indirector::StoreConfigs
include Puppet::Resource::Validator
desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.'
def allow_remote_requests?
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/resource/validator.rb | lib/puppet/indirector/resource/validator.rb | # frozen_string_literal: true
module Puppet::Resource::Validator
def validate_key(request)
type, title = request.key.split('/', 2)
unless type.casecmp(request.instance.type).zero? and title == request.instance.title
raise Puppet::Indirector::ValidationError, _("Resource instance does not match request key")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/resource/ral.rb | lib/puppet/indirector/resource/ral.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/resource/validator'
class Puppet::Resource::Ral < Puppet::Indirector::Code
include Puppet::Resource::Validator
desc "Manipulate resources with the resource abstraction layer. Only used internally."
def allow_remote_requests?
false
end
def find(request)
# find by name
res = type(request).instances.find { |o| o.name == resource_name(request) }
res ||= type(request).new(:name => resource_name(request), :audit => type(request).properties.collect(&:name))
res.to_resource
end
def search(request)
conditions = request.options.dup
conditions[:name] = resource_name(request) if resource_name(request)
type(request).instances.map(&:to_resource).find_all do |res|
conditions.all? do |property, value|
# even though `res` is an instance of Puppet::Resource, calling
# `res[:name]` on it returns nil, and for some reason it is necessary
# to invoke the Puppet::Resource#copy_as_resource copy constructor...
res.copy_as_resource[property].to_s == value.to_s
end
end.sort_by(&:title)
end
def save(request)
# In RAL-land, to "save" means to actually try to change machine state
res = request.instance
ral_res = res.to_ral
catalog = Puppet::Resource::Catalog.new(nil, request.environment)
catalog.add_resource ral_res
transaction = catalog.apply
[ral_res.to_resource, transaction.report]
end
private
# {type,resource}_name: the resource name may contain slashes:
# File["/etc/hosts"]. To handle, assume the type name does
# _not_ have any slashes in it, and split only on the first.
def type_name(request)
request.key.split('/', 2)[0]
end
def resource_name(request)
name = request.key.split('/', 2)[1]
name unless name == ""
end
def type(request)
Puppet::Type.type(type_name(request)) or raise Puppet::Error, _("Could not find type %{request_type}") % { request_type: type_name(request) }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/store_configs.rb | lib/puppet/indirector/node/store_configs.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/store_configs'
require_relative '../../../puppet/node'
class Puppet::Node::StoreConfigs < Puppet::Indirector::StoreConfigs
desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/plain.rb | lib/puppet/indirector/node/plain.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/plain'
class Puppet::Node::Plain < Puppet::Indirector::Plain
desc "Always return an empty node object. Assumes you keep track of nodes
in flat file manifests. You should use it when you don't have some other,
functional source you want to use, as the compiler will not work without a
valid node terminus.
Note that class is responsible for merging the node's facts into the
node instance before it is returned."
# Just return an empty node.
def find(request)
node = super
node.environment = request.environment
facts = request.options[:facts].is_a?(Puppet::Node::Facts) ? request.options[:facts] : nil
node.fact_merge(facts)
node
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/memory.rb | lib/puppet/indirector/node/memory.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/memory'
class Puppet::Node::Memory < Puppet::Indirector::Memory
desc "Keep track of nodes in memory but nowhere else. This is used for
one-time compiles, such as what the stand-alone `puppet` does.
To use this terminus, you must load it with the data you want it
to contain; it is only useful for developers and should generally not
be chosen by a normal user."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/msgpack.rb | lib/puppet/indirector/node/msgpack.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/msgpack'
class Puppet::Node::Msgpack < Puppet::Indirector::Msgpack
desc "Store node information as flat files, serialized using MessagePack,
or deserialize stored MessagePack nodes."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/rest.rb | lib/puppet/indirector/node/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/rest'
class Puppet::Node::Rest < Puppet::Indirector::REST
desc "Get a node via REST. Puppet agent uses this to allow the puppet master
to override its environment."
def find(request)
session = Puppet.lookup(:http_session)
api = session.route_to(:puppet)
_, node = api.get_node(
request.key,
environment: request.environment.to_s,
configured_environment: request.options[:configured_environment],
transaction_uuid: request.options[:transaction_uuid]
)
node
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
return nil unless request.options[:fail_on_404]
_, body = parse_response(e.response)
msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body }
raise Puppet::Error, msg
else
raise convert_to_http_error(e.response)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/yaml.rb | lib/puppet/indirector/node/yaml.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/yaml'
class Puppet::Node::Yaml < Puppet::Indirector::Yaml
desc "Store node information as flat files, serialized using YAML,
or deserialize stored YAML nodes."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/json.rb | lib/puppet/indirector/node/json.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/json'
class Puppet::Node::Json < Puppet::Indirector::JSON
desc "Store node information as flat files, serialized using JSON,
or deserialize stored JSON nodes."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/node/exec.rb | lib/puppet/indirector/node/exec.rb | # frozen_string_literal: true
require_relative '../../../puppet/node'
require_relative '../../../puppet/indirector/exec'
class Puppet::Node::Exec < Puppet::Indirector::Exec
desc "Call an external program to get node information. See
the [External Nodes](https://puppet.com/docs/puppet/latest/lang_write_functions_in_puppet.html) page for more information."
include Puppet::Util
def command
command = Puppet[:external_nodes]
raise ArgumentError, _("You must set the 'external_nodes' parameter to use the external node terminus") unless command != _("none")
command.split
end
# Look for external node definitions.
def find(request)
output = super or return nil
# Translate the output to ruby.
result = translate(request.key, output)
facts = request.options[:facts].is_a?(Puppet::Node::Facts) ? request.options[:facts] : nil
# Set the requested environment if it wasn't overridden
# If we don't do this it gets set to the local default
result[:environment] ||= request.environment
create_node(request.key, result, facts)
end
private
# Proxy the execution, so it's easier to test.
def execute(command, arguments)
Puppet::Util::Execution.execute(command, arguments)
end
# Turn our outputted objects into a Puppet::Node instance.
def create_node(name, result, facts = nil)
node = Puppet::Node.new(name)
[:parameters, :classes, :environment].each do |param|
value = result[param]
if value
node.send(param.to_s + "=", value)
end
end
node.fact_merge(facts)
node
end
# Translate the yaml string into Ruby objects.
def translate(name, output)
Puppet::Util::Yaml.safe_load(output, [Symbol]).each_with_object({}) do |data, hash|
case data[0]
when String
hash[data[0].intern] = data[1]
when Symbol
hash[data[0]] = data[1]
else
raise Puppet::Error, _("key is a %{klass}, not a string or symbol") % { klass: data[0].class }
end
end
rescue => detail
raise Puppet::Error, _("Could not load external node results for %{name}: %{detail}") % { name: name, detail: detail }, detail.backtrace
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_content/selector.rb | lib/puppet/indirector/file_content/selector.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/content'
require_relative '../../../puppet/indirector/file_content'
require_relative '../../../puppet/indirector/code'
require_relative '../../../puppet/file_serving/terminus_selector'
class Puppet::Indirector::FileContent::Selector < Puppet::Indirector::Code
desc "Select the terminus based on the request"
include Puppet::FileServing::TerminusSelector
def get_terminus(request)
indirection.terminus(select(request))
end
def find(request)
get_terminus(request).find(request)
end
def search(request)
get_terminus(request).search(request)
end
def authorized?(request)
terminus = get_terminus(request)
if terminus.respond_to?(:authorized?)
terminus.authorized?(request)
else
true
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_content/rest.rb | lib/puppet/indirector/file_content/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/content'
require_relative '../../../puppet/indirector/file_content'
require_relative '../../../puppet/indirector/rest'
class Puppet::Indirector::FileContent::Rest < Puppet::Indirector::REST
desc "Retrieve file contents via a REST HTTP interface."
def find(request)
content = StringIO.new
content.binmode
url = URI.parse(Puppet::Util.uri_encode(request.uri))
session = Puppet.lookup(:http_session)
api = session.route_to(:fileserver, url: url)
api.get_file_content(
path: Puppet::Util.uri_unescape(url.path),
environment: request.environment.to_s
) do |data|
content << data
end
Puppet::FileServing::Content.from_binary(content.string)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
return nil unless request.options[:fail_on_404]
_, body = parse_response(e.response)
msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body }
raise Puppet::Error, msg
else
raise convert_to_http_error(e.response)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_content/file.rb | lib/puppet/indirector/file_content/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/content'
require_relative '../../../puppet/indirector/file_content'
require_relative '../../../puppet/indirector/direct_file_server'
class Puppet::Indirector::FileContent::File < Puppet::Indirector::DirectFileServer
desc "Retrieve file contents from disk."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_content/file_server.rb | lib/puppet/indirector/file_content/file_server.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/content'
require_relative '../../../puppet/indirector/file_content'
require_relative '../../../puppet/indirector/file_server'
class Puppet::Indirector::FileContent::FileServer < Puppet::Indirector::FileServer
desc "Retrieve file contents using Puppet's fileserver."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/report/msgpack.rb | lib/puppet/indirector/report/msgpack.rb | # frozen_string_literal: true
require_relative '../../../puppet/transaction/report'
require_relative '../../../puppet/indirector/msgpack'
class Puppet::Transaction::Report::Msgpack < Puppet::Indirector::Msgpack
desc "Store last report as a flat file, serialized using MessagePack."
# Force report to be saved there
def path(name, ext = '.msgpack')
Puppet[:lastrunreport]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/report/processor.rb | lib/puppet/indirector/report/processor.rb | # frozen_string_literal: true
require_relative '../../../puppet/transaction/report'
require_relative '../../../puppet/indirector/code'
require_relative '../../../puppet/reports'
class Puppet::Transaction::Report::Processor < Puppet::Indirector::Code
desc "Puppet's report processor. Processes the report with each of
the report types listed in the 'reports' setting."
def initialize
Puppet.settings.use(:main, :reporting, :metrics)
end
def save(request)
process(request.instance)
end
def destroy(request)
processors do |mod|
mod.destroy(request.key) if mod.respond_to?(:destroy)
end
end
private
# Process the report with each of the configured report types.
# LAK:NOTE This isn't necessarily the best design, but it's backward
# compatible and that's good enough for now.
def process(report)
Puppet.debug { "Received report to process from #{report.host}" }
processors do |mod|
Puppet.debug { "Processing report from #{report.host} with processor #{mod}" }
# We have to use a dup because we're including a module in the
# report.
newrep = report.dup
begin
newrep.extend(mod)
newrep.process
rescue => detail
Puppet.log_exception(detail, _("Report %{report} failed: %{detail}") % { report: name, detail: detail })
end
end
end
# Handle the parsing of the reports attribute.
def reports
Puppet[:reports].gsub(/(^\s+)|(\s+$)/, '').split(/\s*,\s*/)
end
def processors(&blk)
return [] if Puppet[:reports] == "none"
reports.each do |name|
mod = Puppet::Reports.report(name)
if mod
yield(mod)
else
Puppet.warning _("No report named '%{name}'") % { name: name }
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/report/rest.rb | lib/puppet/indirector/report/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/rest'
require 'semantic_puppet'
class Puppet::Transaction::Report::Rest < Puppet::Indirector::REST
desc "Get server report over HTTP via REST."
def save(request)
session = Puppet.lookup(:http_session)
api = session.route_to(:report)
response = api.put_report(
request.key,
request.instance,
environment: request.environment.to_s
)
content_type, body = parse_response(response)
deserialize_save(content_type, body)
rescue Puppet::HTTP::ResponseError => e
return nil if e.response.code == 404
raise convert_to_http_error(e.response)
end
private
def deserialize_save(content_type, body)
format = Puppet::Network::FormatHandler.format_for(content_type)
format.intern(Array, body)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/report/yaml.rb | lib/puppet/indirector/report/yaml.rb | # frozen_string_literal: true
require_relative '../../../puppet/transaction/report'
require_relative '../../../puppet/indirector/yaml'
class Puppet::Transaction::Report::Yaml < Puppet::Indirector::Yaml
include Puppet::Util::SymbolicFileMode
desc "Store last report as a flat file, serialized using YAML."
# Force report to be saved there
def path(name, ext = '.yaml')
Puppet[:lastrunreport]
end
def save(request)
filename = path(request.key)
mode = Puppet.settings.setting(:lastrunreport).mode
unless valid_symbolic_mode?(mode)
raise Puppet::DevError, _("replace_file mode: %{mode} is invalid") % { mode: mode }
end
mode = symbolic_mode_to_int(normalize_symbolic_mode(mode))
FileUtils.mkdir_p(File.dirname(filename))
begin
Puppet::FileSystem.replace_file(filename, mode) do |fh|
fh.print YAML.dump(request.instance)
end
rescue TypeError => detail
Puppet.err _("Could not save %{indirection} %{request}: %{detail}") % { indirection: name, request: request.key, detail: detail }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/report/json.rb | lib/puppet/indirector/report/json.rb | # frozen_string_literal: true
require_relative '../../../puppet/transaction/report'
require_relative '../../../puppet/indirector/json'
class Puppet::Transaction::Report::Json < Puppet::Indirector::JSON
include Puppet::Util::SymbolicFileMode
desc "Store last report as a flat file, serialized using JSON."
# Force report to be saved there
def path(name, ext = '.json')
Puppet[:lastrunreport]
end
def save(request)
filename = path(request.key)
mode = Puppet.settings.setting(:lastrunreport).mode
unless valid_symbolic_mode?(mode)
raise Puppet::DevError, _("replace_file mode: %{mode} is invalid") % { mode: mode }
end
mode = symbolic_mode_to_int(normalize_symbolic_mode(mode))
FileUtils.mkdir_p(File.dirname(filename))
begin
Puppet::FileSystem.replace_file(filename, mode) do |fh|
fh.print JSON.dump(request.instance)
end
rescue TypeError => detail
Puppet.err _("Could not save %{indirection} %{request}: %{detail}") % { indirection: name, request: request.key, detail: detail }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_metadata/selector.rb | lib/puppet/indirector/file_metadata/selector.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/metadata'
require_relative '../../../puppet/indirector/file_metadata'
require_relative '../../../puppet/indirector/code'
require_relative '../../../puppet/file_serving/terminus_selector'
class Puppet::Indirector::FileMetadata::Selector < Puppet::Indirector::Code
desc "Select the terminus based on the request"
include Puppet::FileServing::TerminusSelector
def get_terminus(request)
indirection.terminus(select(request))
end
def find(request)
get_terminus(request).find(request)
end
def search(request)
get_terminus(request).search(request)
end
def authorized?(request)
terminus = get_terminus(request)
if terminus.respond_to?(:authorized?)
terminus.authorized?(request)
else
true
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_metadata/rest.rb | lib/puppet/indirector/file_metadata/rest.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/metadata'
require_relative '../../../puppet/indirector/file_metadata'
require_relative '../../../puppet/indirector/rest'
class Puppet::Indirector::FileMetadata::Rest < Puppet::Indirector::REST
desc "Retrieve file metadata via a REST HTTP interface."
def find(request)
url = URI.parse(Puppet::Util.uri_encode(request.uri))
session = Puppet.lookup(:http_session)
api = session.route_to(:fileserver, url: url)
_, file_metadata = api.get_file_metadata(
path: Puppet::Util.uri_unescape(url.path),
environment: request.environment.to_s,
links: request.options[:links],
checksum_type: request.options[:checksum_type],
source_permissions: request.options[:source_permissions]
)
file_metadata
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
return nil unless request.options[:fail_on_404]
_, body = parse_response(e.response)
msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body }
raise Puppet::Error, msg
else
raise convert_to_http_error(e.response)
end
end
def search(request)
url = URI.parse(Puppet::Util.uri_encode(request.uri))
session = Puppet.lookup(:http_session)
api = session.route_to(:fileserver, url: url)
_, file_metadatas = api.get_file_metadatas(
path: Puppet::Util.uri_unescape(url.path),
environment: request.environment.to_s,
recurse: request.options[:recurse],
recurselimit: request.options[:recurselimit],
max_files: request.options[:max_files],
ignore: request.options[:ignore],
links: request.options[:links],
checksum_type: request.options[:checksum_type],
source_permissions: request.options[:source_permissions]
)
file_metadatas
rescue Puppet::HTTP::ResponseError => e
# since it's search, return empty array instead of nil
return [] if e.response.code == 404
raise convert_to_http_error(e.response)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_metadata/file.rb | lib/puppet/indirector/file_metadata/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/metadata'
require_relative '../../../puppet/indirector/file_metadata'
require_relative '../../../puppet/indirector/direct_file_server'
class Puppet::Indirector::FileMetadata::File < Puppet::Indirector::DirectFileServer
desc "Retrieve file metadata directly from the local filesystem."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_metadata/http.rb | lib/puppet/indirector/file_metadata/http.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/http_metadata'
require_relative '../../../puppet/indirector/generic_http'
require_relative '../../../puppet/indirector/file_metadata'
require 'net/http'
class Puppet::Indirector::FileMetadata::Http < Puppet::Indirector::GenericHttp
desc "Retrieve file metadata from a remote HTTP server."
include Puppet::FileServing::TerminusHelper
def find(request)
checksum_type = request.options[:checksum_type]
# See URL encoding comment in Puppet::Type::File::ParamSource#chunk_file_from_source
uri = URI(request.uri)
client = Puppet.runtime[:http]
head = client.head(uri, options: { include_system_store: true })
return create_httpmetadata(head, checksum_type) if head.success?
case head.code
when 403, 405
# AMZ presigned URL and puppetserver may return 403
# instead of 405. Fallback to partial get
get = partial_get(client, uri)
return create_httpmetadata(get, checksum_type) if get.success?
end
nil
end
def search(request)
raise Puppet::Error, _("cannot lookup multiple files")
end
private
def partial_get(client, uri)
client.get(uri, headers: { 'Range' => 'bytes=0-0' }, options: { include_system_store: true })
end
def create_httpmetadata(http_request, checksum_type)
metadata = Puppet::FileServing::HttpMetadata.new(http_request)
metadata.checksum_type = checksum_type if checksum_type
metadata.collect
metadata
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/file_metadata/file_server.rb | lib/puppet/indirector/file_metadata/file_server.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/metadata'
require_relative '../../../puppet/indirector/file_metadata'
require_relative '../../../puppet/indirector/file_server'
class Puppet::Indirector::FileMetadata::FileServer < Puppet::Indirector::FileServer
desc "Retrieve file metadata using Puppet's fileserver."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/data_binding/hiera.rb | lib/puppet/indirector/data_binding/hiera.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/hiera'
require 'hiera/scope'
class Puppet::DataBinding::Hiera < Puppet::Indirector::Hiera
desc "Retrieve data using Hiera."
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/data_binding/none.rb | lib/puppet/indirector/data_binding/none.rb | # frozen_string_literal: true
require_relative '../../../puppet/indirector/none'
class Puppet::DataBinding::None < Puppet::Indirector::None
desc "A Dummy terminus that always throws :no_such_key for data lookups."
def find(request)
throw :no_such_key
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector/facts/store_configs.rb | lib/puppet/indirector/facts/store_configs.rb | # frozen_string_literal: true
require_relative '../../../puppet/node/facts'
require_relative '../../../puppet/indirector/store_configs'
class Puppet::Node::Facts::StoreConfigs < Puppet::Indirector::StoreConfigs
desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.'
def allow_remote_requests?
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.