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/util/ldap/generator.rb | lib/puppet/util/ldap/generator.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/ldap'
class Puppet::Util::Ldap::Generator
# Declare the attribute we'll use to generate the value.
def from(source)
@source = source
self
end
# Actually do the generation.
def generate(value = nil)
if value.nil?
@generator.call
else
@generator.call(value)
end
end
# Initialize our generator with the name of the parameter
# being generated.
def initialize(name)
@name = name
end
def name
@name.to_s
end
def source
if @source
@source.to_s
else
nil
end
end
# Provide the code that does the generation.
def with(&block)
@generator = block
self
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/util/ldap/manager.rb | lib/puppet/util/ldap/manager.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/ldap'
require_relative '../../../puppet/util/ldap/connection'
require_relative '../../../puppet/util/ldap/generator'
# The configuration class for LDAP providers, plus
# connection handling for actually interacting with ldap.
class Puppet::Util::Ldap::Manager
attr_reader :objectclasses, :puppet2ldap, :location, :rdn
# A null-op that just returns the config.
def and
self
end
# Set the offset from the search base and return the config.
def at(location)
@location = location
self
end
# The basic search base.
def base
[location, Puppet[:ldapbase]].join(",")
end
# Convert the name to a dn, then pass the args along to
# our connection.
def create(name, attributes)
attributes = attributes.dup
# Add the objectclasses
attributes["objectClass"] = objectclasses.collect(&:to_s)
attributes["objectClass"] << "top" unless attributes["objectClass"].include?("top")
attributes[rdn.to_s] = [name]
# Generate any new values we might need.
generate(attributes)
# And create our resource.
connect { |conn| conn.add dn(name), attributes }
end
# Open, yield, and close the connection. Cannot be left
# open, at this point.
def connect
# TRANSLATORS '#connect' is a method name and and should not be translated, 'block' refers to a Ruby code block
raise ArgumentError, _("You must pass a block to #connect") unless block_given?
unless @connection
if Puppet[:ldaptls]
ssl = :tls
elsif Puppet[:ldapssl]
ssl = true
else
ssl = false
end
options = { :ssl => ssl }
user = Puppet[:ldapuser]
if user && user != ""
options[:user] = user
end
password = Puppet[:ldappassword]
if password && password != ""
options[:password] = password
end
@connection = Puppet::Util::Ldap::Connection.new(Puppet[:ldapserver], Puppet[:ldapport], options)
end
@connection.start
begin
yield @connection.connection
ensure
@connection.close
end
nil
end
# Convert the name to a dn, then pass the args along to
# our connection.
def delete(name)
connect { |connection| connection.delete dn(name) }
end
# Calculate the dn for a given resource.
def dn(name)
["#{rdn}=#{name}", base].join(",")
end
# Convert an ldap-style entry hash to a provider-style hash.
def entry2provider(entry)
# TRANSLATOR 'dn' refers to a 'distinguished name' in LDAP (Lightweight Directory Access Protocol) and they should not be translated
raise ArgumentError, _("Could not get dn from ldap entry") unless entry["dn"]
# DN is always a single-entry array. Strip off the bits before the
# first comma, then the bits after the remaining equal sign. This is the
# name.
name = entry["dn"].dup.pop.split(",").shift.split("=").pop
result = { :name => name }
@ldap2puppet.each do |ldap, puppet|
result[puppet] = entry[ldap.to_s] || :absent
end
result
end
# Create our normal search filter.
def filter
(objectclasses.length == 1 ? "objectclass=#{objectclasses[0]}" : "(&(objectclass=" + objectclasses.join(")(objectclass=") + "))")
end
# Find the associated entry for a resource. Returns a hash, minus
# 'dn', or nil if the entry cannot be found.
def find(name)
connect do |conn|
conn.search2(dn(name), 0, "objectclass=*") do |result|
# Convert to puppet-appropriate attributes
return entry2provider(result)
end
rescue
return nil
end
end
# Declare a new attribute generator.
def generates(parameter)
@generators << Puppet::Util::Ldap::Generator.new(parameter)
@generators[-1]
end
# Generate any extra values we need to make the ldap entry work.
def generate(values)
return unless @generators.length > 0
@generators.each do |generator|
# Don't override any values that might exist.
next if values[generator.name]
if generator.source
value = values[generator.source]
unless value
raise ArgumentError, _("%{source} must be defined to generate %{name}") %
{ source: generator.source, name: generator.name }
end
result = generator.generate(value)
else
result = generator.generate
end
result = [result] unless result.is_a?(Array)
result = result.collect(&:to_s)
values[generator.name] = result
end
end
def initialize
@rdn = :cn
@generators = []
end
# Specify what classes this provider models.
def manages(*classes)
@objectclasses = classes
self
end
# Specify the attribute map. Assumes the keys are the puppet
# attributes, and the values are the ldap attributes, and creates a map
# for each direction.
def maps(attributes)
# The map with the puppet attributes as the keys
@puppet2ldap = attributes
# and the ldap attributes as the keys.
@ldap2puppet = attributes.each_with_object({}) { |ary, map| map[ary[1]] = ary[0]; }
self
end
# Return the ldap name for a puppet attribute.
def ldap_name(attribute)
@puppet2ldap[attribute].to_s
end
# Convert the name to a dn, then pass the args along to
# our connection.
def modify(name, mods)
connect { |connection| connection.modify dn(name), mods }
end
# Specify the rdn that we use to build up our dn.
def named_by(attribute)
@rdn = attribute
self
end
# Return the puppet name for an ldap attribute.
def puppet_name(attribute)
@ldap2puppet[attribute]
end
# Search for all entries at our base. A potentially expensive search.
def search(sfilter = nil)
sfilter ||= filter
result = []
connect do |conn|
conn.search2(base, 1, sfilter) do |entry|
result << entry2provider(entry)
end
end
(result.empty? ? nil : result)
end
# Update the ldap entry with the desired state.
def update(name, is, should)
if should[:ensure] == :absent
Puppet.info _("Removing %{name} from ldap") % { name: dn(name) }
delete(name)
return
end
# We're creating a new entry
if is.empty? or is[:ensure] == :absent
Puppet.info _("Creating %{name} in ldap") % { name: dn(name) }
# Remove any :absent params and :ensure, then convert the names to ldap names.
attrs = ldap_convert(should)
create(name, attrs)
return
end
# We're modifying an existing entry. Yuck.
mods = []
# For each attribute we're deleting that is present, create a
# modify instance for deletion.
[is.keys, should.keys].flatten.uniq.each do |property|
# They're equal, so do nothing.
next if is[property] == should[property]
attributes = ldap_convert(should)
prop_name = ldap_name(property).to_s
# We're creating it.
if is[property] == :absent or is[property].nil?
mods << LDAP::Mod.new(LDAP::LDAP_MOD_ADD, prop_name, attributes[prop_name])
next
end
# We're deleting it
if should[property] == :absent or should[property].nil?
mods << LDAP::Mod.new(LDAP::LDAP_MOD_DELETE, prop_name, [])
next
end
# We're replacing an existing value
mods << LDAP::Mod.new(LDAP::LDAP_MOD_REPLACE, prop_name, attributes[prop_name])
end
modify(name, mods)
end
# Is this a complete ldap configuration?
def valid?
location and objectclasses and !objectclasses.empty? and puppet2ldap
end
private
# Convert a hash of attributes to ldap-like forms. This mostly means
# getting rid of :ensure and making sure everything's an array of strings.
def ldap_convert(attributes)
attributes.reject { |param, value| value == :absent or param == :ensure }.each_with_object({}) do |ary, result|
value = (ary[1].is_a?(Array) ? ary[1] : [ary[1]]).collect(&:to_s)
result[ldap_name(ary[0])] = 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/util/network_device/base.rb | lib/puppet/util/network_device/base.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/autoload'
require 'uri'
require_relative '../../../puppet/util/network_device/transport'
require_relative '../../../puppet/util/network_device/transport/base'
class Puppet::Util::NetworkDevice::Base
attr_accessor :url, :transport
def initialize(url, options = {})
@url = URI.parse(url)
@autoloader = Puppet::Util::Autoload.new(self, "puppet/util/network_device/transport")
if @autoloader.load(@url.scheme, Puppet.lookup(:current_environment))
@transport = Puppet::Util::NetworkDevice::Transport.const_get(@url.scheme.capitalize).new(options[:debug])
@transport.host = @url.host
@transport.port = @url.port || case @url.scheme; when "ssh"; 22; when "telnet"; 23; end
@transport.user = @url.user
@transport.password = @url.password
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/util/network_device/config.rb | lib/puppet/util/network_device/config.rb | # frozen_string_literal: true
require 'ostruct'
require_relative '../../../puppet/util/watched_file'
require_relative '../../../puppet/util/network_device'
class Puppet::Util::NetworkDevice::Config
def self.main
@main ||= new
end
def self.devices
main.devices || []
end
attr_reader :devices
def exists?
Puppet::FileSystem.exist?(@file.to_str)
end
def initialize
@file = Puppet::Util::WatchedFile.new(Puppet[:deviceconfig])
@devices = {}
read(true) # force reading at start
end
# Read the configuration file.
def read(force = false)
return unless exists?
parse if force or @file.changed?
end
private
def parse
begin
devices = {}
device = nil
File.open(@file) do |f|
file_line_count = 1
f.each do |line|
case line
when /^\s*#/ # skip comments
file_line_count += 1
next
when /^\s*$/ # skip blank lines
file_line_count += 1
next
when /^\[([\w.-]+)\]\s*$/ # [device.fqdn]
name = ::Regexp.last_match(1)
name.chomp!
if devices.include?(name)
file_error_location = Puppet::Util::Errors.error_location(nil, file_line_count)
device_error_location = Puppet::Util::Errors.error_location(nil, device.line)
raise Puppet::Error, _("Duplicate device found at %{file_error_location}, already found at %{device_error_location}") %
{ file_error_location: file_error_location, device_error_location: device_error_location }
end
device = OpenStruct.new
device.name = name
device.line = file_line_count
device.options = { :debug => false }
Puppet.debug "found device: #{device.name} at #{device.line}"
devices[name] = device
when /^\s*(type|url|debug)(\s+(.+)\s*)*$/
parse_directive(device, ::Regexp.last_match(1), ::Regexp.last_match(3), file_line_count)
else
error_location_str = Puppet::Util::Errors.error_location(nil, file_line_count)
raise Puppet::Error, _("Invalid entry at %{error_location}: %{file_text}") %
{ error_location: error_location_str, file_text: line }
end
end
end
rescue Errno::EACCES
Puppet.err _("Configuration error: Cannot read %{file}; cannot serve") % { file: @file }
# raise Puppet::Error, "Cannot read #{@config}"
rescue Errno::ENOENT
Puppet.err _("Configuration error: '%{file}' does not exit; cannot serve") % { file: @file }
end
@devices = devices
end
def parse_directive(device, var, value, count)
case var
when "type"
device.provider = value
when "url"
begin
URI.parse(value)
rescue URI::InvalidURIError
raise Puppet::Error, _("%{value} is an invalid url") % { value: value }
end
device.url = value
when "debug"
device.options[:debug] = true
else
error_location_str = Puppet::Util::Errors.error_location(nil, count)
raise Puppet::Error, _("Invalid argument '%{var}' at %{error_location}") % { var: var, error_location: error_location_str }
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/util/network_device/transport.rb | lib/puppet/util/network_device/transport.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/network_device'
# stub
module Puppet::Util::NetworkDevice::Transport
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/network_device/transport/base.rb | lib/puppet/util/network_device/transport/base.rb | # frozen_string_literal: true
require_relative '../../../../puppet/util/network_device'
require_relative '../../../../puppet/util/network_device/transport'
class Puppet::Util::NetworkDevice::Transport::Base
attr_accessor :user, :password, :host, :port
attr_accessor :default_prompt, :timeout
def initialize
@timeout = 10
end
def send(cmd)
end
def expect(prompt)
end
def command(cmd, options = {})
send(cmd)
expect(options[:prompt] || default_prompt) do |output|
yield output if block_given?
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/util/rdoc/parser.rb | lib/puppet/util/rdoc/parser.rb | # frozen_string_literal: true
# Puppet "parser" for the rdoc system
# The parser uses puppet parser and traverse the AST to instruct RDoc about
# our current structures. It also parses ruby files that could contain
# either custom facts or puppet plugins (functions, types...)
# rdoc2 includes
require 'rdoc/code_objects'
require_relative '../../../puppet/util/rdoc/code_objects'
require 'rdoc/token_stream'
require 'rdoc/markup/pre_process'
require 'rdoc/parser'
require_relative 'parser/puppet_parser_rdoc2'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/rdoc/code_objects.rb | lib/puppet/util/rdoc/code_objects.rb | # frozen_string_literal: true
require 'rdoc/code_objects'
module RDoc
# This modules contains various class that are used to hold information
# about the various Puppet language structures we found while parsing.
#
# Those will be mapped to their html counterparts which are defined in
# PuppetGenerator.
# PuppetTopLevel is a top level (usually a .pp/.rb file)
module PuppetTopLevel
attr_accessor :module_name, :global
end
# Add top level comments to a class or module
# @api private
module AddClassModuleComment
def add_comment(comment, location = nil)
super
end
end
# PuppetModule holds a Puppet Module
# This is mapped to an HTMLPuppetModule
# it leverage the RDoc (ruby) module infrastructure
class PuppetModule < NormalModule
include AddClassModuleComment
attr_accessor :facts, :plugins
def initialize(name, superclass = nil)
@facts = []
@plugins = []
@nodes = {}
super(name, superclass)
end
def add_plugin(plugin)
name = plugin.name
type = plugin.type
meth = AnyMethod.new("*args", name)
meth.params = "(*args)"
meth.visibility = :public
meth.document_self = true
meth.singleton = false
meth.comment = plugin.comment
case type
when 'function'
@function_container ||= add_module(NormalModule, "__functions__")
@function_container.add_method(meth)
when 'type'
@type_container ||= add_module(NormalModule, "__types__")
@type_container.add_method(meth)
end
end
def add_fact(fact)
@fact_container ||= add_module(NormalModule, "__facts__")
confine_str = fact.confine.empty? ? '' : fact.confine.to_s
const = Constant.new(fact.name, confine_str, fact.comment)
@fact_container.add_constant(const)
end
# Adds a module called __nodes__ and adds nodes to it as classes
#
def add_node(name, superclass)
cls = @nodes[name]
if cls
return cls
end
@node_container ||= add_module(NormalModule, "__nodes__")
cls = @node_container.add_class(PuppetNode, name, superclass)
@nodes[name] = cls unless @done_documenting
cls
end
def each_fact
@facts.each { |c| yield c }
end
def each_plugin
@plugins.each { |c| yield c }
end
def each_node
@nodes.each { |c| yield c }
end
def nodes
@nodes.values
end
end
# PuppetClass holds a puppet class
# It is mapped to a HTMLPuppetClass for display
# It leverages RDoc (ruby) Class
class PuppetClass < ClassModule
include AddClassModuleComment
attr_accessor :resource_list, :requires, :childs, :realizes
def initialize(name, superclass)
super(name, superclass)
@resource_list = []
@requires = []
@realizes = []
@childs = []
end
def aref_prefix
'puppet_class'
end
def add_resource(resource)
add_to(@resource_list, resource)
end
def is_module?
false
end
def superclass=(superclass)
@superclass = superclass
end
# we're (ab)using the RDoc require system here.
# we're adding a required Puppet class, overriding
# the RDoc add_require method which sees ruby required files.
def add_require(required)
add_to(@requires, required)
end
def add_realize(realized)
add_to(@realizes, realized)
end
def add_child(child)
@childs << child
end
# Look up the given symbol. RDoc only looks for class1::class2.method
# or class1::class2#method. Since our definitions are mapped to RDoc methods
# but are written class1::class2::define we need to perform the lookup by
# ourselves.
def find_symbol(symbol, method = nil)
result = super(symbol)
if !result and symbol =~ /::/
modules = symbol.split(/::/)
unless modules.empty?
module_name = modules.shift
result = find_module_named(module_name)
if result
last_name = ""
previous = nil
modules.each do |mod|
previous = result
last_name = mod
result = result.find_module_named(mod)
break unless result
end
unless result
result = previous
method = last_name
end
end
end
if result && method
unless result.respond_to?(:find_local_symbol)
p result.name
p method
fail
end
result = result.find_local_symbol(method)
end
end
result
end
end
# PuppetNode holds a puppet node
# It is mapped to a HTMLPuppetNode for display
# A node is just a variation of a class
class PuppetNode < PuppetClass
include AddClassModuleComment
def is_module?
false
end
end
# Plugin holds a native puppet plugin (function,type...)
# It is mapped to a HTMLPuppetPlugin for display
class Plugin < Context
attr_accessor :name, :type
def initialize(name, type)
super()
@name = name
@type = type
@comment = ""
end
def <=>(other)
@name <=> other.name
end
def full_name
@name
end
def http_url(prefix)
path = full_name.split("::")
File.join(prefix, *path) + ".html"
end
def is_fact?
false
end
def to_s
res = self.class.name + ": #{@name} (#{@type})\n"
res << @comment.to_s
res
end
end
# Fact holds a custom fact
# It is mapped to a HTMLPuppetPlugin for display
class Fact < Context
attr_accessor :name, :confine
def initialize(name, confine)
super()
@name = name
@confine = confine
@comment = ""
end
def <=>(other)
@name <=> other.name
end
def is_fact?
true
end
def full_name
@name
end
def to_s
res = self.class.name + ": #{@name}\n"
res << @comment.to_s
res
end
end
# PuppetResource holds a puppet resource
# It is mapped to a HTMLPuppetResource for display
# A resource is defined by its "normal" form Type[title]
class PuppetResource < CodeObject
attr_accessor :type, :title, :params
def initialize(type, title, comment, params)
super()
@type = type
@title = title
@comment = comment
@params = params
end
def <=>(other)
full_name <=> other.full_name
end
def full_name
@type + "[#{@title}]"
end
def name
full_name
end
def to_s
res = @type + "[#{@title}]\n"
res << @comment.to_s
res
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/util/rdoc/generators/puppet_generator.rb | lib/puppet/util/rdoc/generators/puppet_generator.rb | # frozen_string_literal: true
require 'rdoc/generators/html_generator'
require_relative '../../../../puppet/util/rdoc/code_objects'
require 'digest/md5'
module Generators
# This module holds all the classes needed to generate the HTML documentation
# of a bunch of puppet manifests.
#
# It works by traversing all the code objects defined by the Puppet RDoc::Parser
# and produces HTML counterparts objects that in turns are used by RDoc template engine
# to produce the final HTML.
#
# It is also responsible of creating the whole directory hierarchy, and various index
# files.
#
# It is to be noted that the whole system is built on top of ruby RDoc. As such there
# is an implicit mapping of puppet entities to ruby entitites:
#
# Puppet => Ruby
# ------------------------
# Module Module
# Class Class
# Definition Method
# Resource
# Node
# Plugin
# Fact
MODULE_DIR = "modules"
NODE_DIR = "nodes"
PLUGIN_DIR = "plugins"
# We're monkey patching RDoc markup to allow
# lowercase class1::class2::class3 crossref hyperlinking
module MarkUp
alias :old_markup :markup
def new_markup(str, remove_para = false)
first = @markup.nil?
res = old_markup(str, remove_para)
if first and !@markup.nil?
@markup.add_special(/\b([a-z]\w+(::\w+)*)/, :CROSSREF)
# we need to call it again, since we added a rule
res = old_markup(str, remove_para)
end
res
end
alias :markup :new_markup
end
# This is a specialized HTMLGenerator tailored to Puppet manifests
class PuppetGenerator < HTMLGenerator
def self.for(options)
AllReferences.reset
HtmlMethod.reset
if options.all_one_file
PuppetGeneratorInOne.new(options)
else
PuppetGenerator.new(options)
end
end
def initialize(options) # :not-new:
@options = options
load_html_template
end
# loads our own html template file
def load_html_template
require_relative '../../../../puppet/util/rdoc/generators/template/puppet/puppet'
extend RDoc::Page
rescue LoadError
$stderr.puts "Could not find Puppet template '#{template}'"
exit 99
end
def gen_method_index
# we don't generate an all define index
# as the presentation is per module/per class
end
# This is the central method, it generates the whole structures
# along with all the indices.
def generate_html
super
gen_into(@nodes)
gen_into(@plugins)
end
##
# Generate:
# the list of modules
# the list of classes and definitions of a specific module
# the list of all classes
# the list of nodes
# the list of resources
def build_indices
@allfiles = []
@nodes = []
@plugins = []
# contains all the seen modules
@modules = {}
@allclasses = {}
# remove unknown toplevels
# it can happen that RDoc triggers a different parser for some files (ie .c, .cc or .h)
# in this case RDoc generates a RDoc::TopLevel which we do not support in this generator
# So let's make sure we don't generate html for those.
@toplevels = @toplevels.select { |tl| tl.is_a? RDoc::PuppetTopLevel }
# build the modules, classes and per modules classes and define list
@toplevels.each do |toplevel|
next unless toplevel.document_self
file = HtmlFile.new(toplevel, @options, FILE_DIR)
classes = []
methods = []
modules = []
nodes = []
# find all classes of this toplevel
# store modules if we find one
toplevel.each_classmodule do |k|
generate_class_list(classes, modules, k, toplevel, CLASS_DIR)
end
# find all defines belonging to this toplevel
HtmlMethod.all_methods.each do |m|
# find parent module, check this method is not already
# defined.
if m.context.parent.toplevel === toplevel
methods << m
end
end
classes.each do |k|
@allclasses[k.index_name] = k unless @allclasses.has_key?(k.index_name)
end
# generate nodes and plugins found
classes.each do |k|
next unless k.context.is_module?
k.context.each_node do |_name, node|
nodes << HTMLPuppetNode.new(node, toplevel, NODE_DIR, @options)
@nodes << nodes.last
end
k.context.each_plugin do |plugin|
@plugins << HTMLPuppetPlugin.new(plugin, toplevel, PLUGIN_DIR, @options)
end
k.context.each_fact do |fact|
@plugins << HTMLPuppetPlugin.new(fact, toplevel, PLUGIN_DIR, @options)
end
end
@files << file
@allfiles << { "file" => file, "modules" => modules, "classes" => classes, "methods" => methods, "nodes" => nodes }
end
# scan all classes to create the child's references
@allclasses.values.each do |klass|
superklass = klass.context.superclass
next unless superklass
superklass = AllReferences[superklass]
if superklass && (superklass.is_a?(HTMLPuppetClass) || superklass.is_a?(HTMLPuppetNode))
superklass.context.add_child(klass.context)
end
end
@classes = @allclasses.values
end
# produce a class/module list of HTMLPuppetModule/HTMLPuppetClass
# based on the code object traversal.
def generate_class_list(classes, modules, from, html_file, class_dir)
if from.is_module? and !@modules.has_key?(from.name)
k = HTMLPuppetModule.new(from, html_file, class_dir, @options)
classes << k
@modules[from.name] = k
modules << @modules[from.name]
elsif from.is_module?
modules << @modules[from.name]
elsif !from.is_module?
k = HTMLPuppetClass.new(from, html_file, class_dir, @options)
classes << k
end
from.each_classmodule do |mod|
generate_class_list(classes, modules, mod, html_file, class_dir)
end
end
# generate all the subdirectories, modules, classes and files
def gen_sub_directories
super
File.makedirs(MODULE_DIR)
File.makedirs(NODE_DIR)
File.makedirs(PLUGIN_DIR)
rescue
$stderr.puts $ERROR_INFO.message
exit 1
end
# generate the index of modules
def gen_file_index
gen_top_index(@modules.values, 'All Modules', RDoc::Page::TOP_INDEX, "fr_modules_index.html")
end
# generate a top index
def gen_top_index(collection, title, template, filename)
template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template)
res = []
collection.sort.each do |f|
if f.document_self
res << { "classlist" => CGI.escapeHTML("#{MODULE_DIR}/fr_#{f.index_name}.html"), "module" => CGI.escapeHTML("#{CLASS_DIR}/#{f.index_name}.html"), "name" => CGI.escapeHTML(f.index_name) }
end
end
values = {
"entries" => res,
'list_title' => CGI.escapeHTML(title),
'index_url' => main_url,
'charset' => @options.charset,
'style_url' => style_url('', @options.css),
}
Puppet::FileSystem.open(filename, nil, "w:UTF-8") do |f|
template.write_html_on(f, values)
end
end
# generate the all classes index file and the combo index
def gen_class_index
gen_an_index(@classes, 'All Classes', RDoc::Page::CLASS_INDEX, "fr_class_index.html")
@allfiles.each do |file|
next if file['file'].context.file_relative_name =~ /\.rb$/
gen_composite_index(
file,
RDoc::Page::COMBO_INDEX,
"#{MODULE_DIR}/fr_#{file['file'].context.module_name}.html"
)
end
end
def gen_composite_index(collection, template, filename)
return if Puppet::FileSystem.exist?(filename)
template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template)
res1 = []
collection['classes'].sort.each do |f|
if f.document_self
res1 << { "href" => "../" + CGI.escapeHTML(f.path), "name" => CGI.escapeHTML(f.index_name) } unless f.context.is_module?
end
end
res2 = []
collection['methods'].sort.each do |f|
res2 << { "href" => "../#{f.path}", "name" => f.index_name.sub(/\(.*\)$/, '') } if f.document_self
end
module_name = []
res3 = []
res4 = []
collection['modules'].sort.each do |f|
module_name << { "href" => "../" + CGI.escapeHTML(f.path), "name" => CGI.escapeHTML(f.index_name) }
unless f.facts.nil?
f.facts.each do |fact|
res3 << { "href" => "../" + CGI.escapeHTML(AllReferences["PLUGIN(#{fact.name})"].path), "name" => CGI.escapeHTML(fact.name) }
end
end
next if f.plugins.nil?
f.plugins.each do |plugin|
res4 << { "href" => "../" + CGI.escapeHTML(AllReferences["PLUGIN(#{plugin.name})"].path), "name" => CGI.escapeHTML(plugin.name) }
end
end
res5 = []
collection['nodes'].sort.each do |f|
res5 << { "href" => "../" + CGI.escapeHTML(f.path), "name" => CGI.escapeHTML(f.name) } if f.document_self
end
values = {
"module" => module_name,
"classes" => res1,
'classes_title' => CGI.escapeHTML("Classes"),
'defines_title' => CGI.escapeHTML("Defines"),
'facts_title' => CGI.escapeHTML("Custom Facts"),
'plugins_title' => CGI.escapeHTML("Plugins"),
'nodes_title' => CGI.escapeHTML("Nodes"),
'index_url' => main_url,
'charset' => @options.charset,
'style_url' => style_url('', @options.css),
}
values["defines"] = res2 if res2.size > 0
values["facts"] = res3 if res3.size > 0
values["plugins"] = res4 if res4.size > 0
values["nodes"] = res5 if res5.size > 0
Puppet::FileSystem.open(filename, nil, "w:UTF-8") do |f|
template.write_html_on(f, values)
end
end
# returns the initial_page url
def main_url
main_page = @options.main_page
ref = nil
if main_page
ref = AllReferences[main_page]
if ref
ref = ref.path
else
$stderr.puts "Could not find main page #{main_page}"
end
end
unless ref
@files.each do |file|
if file.document_self and file.context.global
ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html")
break
end
end
end
unless ref
@files.each do |file|
if file.document_self and !file.context.global
ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html")
break
end
end
end
unless ref
$stderr.puts "Couldn't find anything to document"
$stderr.puts "Perhaps you've used :stopdoc: in all classes"
exit(1)
end
ref
end
end
# This module is used to generate a referenced full name list of ContextUser
module ReferencedListBuilder
def build_referenced_list(list)
res = []
list.each do |i|
ref = AllReferences[i.name] || @context.find_symbol(i.name)
ref = ref.viewer if ref and ref.respond_to?(:viewer)
name = i.respond_to?(:full_name) ? i.full_name : i.name
h_name = CGI.escapeHTML(name)
if ref and ref.document_self
path = url(ref.path)
res << { "name" => h_name, "aref" => path }
else
res << { "name" => h_name }
end
end
res
end
end
# This module is used to hold/generate a list of puppet resources
# this is used in HTMLPuppetClass and HTMLPuppetNode
module ResourceContainer
def collect_resources
list = @context.resource_list
@resources = list.collect { |m| HTMLPuppetResource.new(m, self, @options) }
end
def build_resource_summary_list(path_prefix = '')
collect_resources unless @resources
resources = @resources.sort
res = []
resources.each do |r|
res << {
"name" => CGI.escapeHTML(r.name),
"aref" => Puppet::Util.uri_encode(path_prefix) + "\#" + Puppet::Util.uri_query_encode(r.aref)
}
end
res
end
def build_resource_detail_list(section)
outer = []
resources = @resources.sort
resources.each do |r|
row = {}
next unless r.section == section and r.document_self
row["name"] = CGI.escapeHTML(r.name)
desc = r.description.strip
row["m_desc"] = desc unless desc.empty?
row["aref"] = r.aref
row["params"] = r.params
outer << row
end
outer
end
end
class HTMLPuppetClass < HtmlClass
include ResourceContainer, ReferencedListBuilder
def value_hash
super
rl = build_resource_summary_list
@values["resources"] = rl unless rl.empty?
@context.sections.each do |section|
secdata = @values["sections"].select { |s| s["secsequence"] == section.sequence }
next unless secdata.size == 1
secdata = secdata[0]
rdl = build_resource_detail_list(section)
secdata["resource_list"] = rdl unless rdl.empty?
end
rl = build_require_list(@context)
@values["requires"] = rl unless rl.empty?
rl = build_realize_list(@context)
@values["realizes"] = rl unless rl.empty?
cl = build_child_list(@context)
@values["childs"] = cl unless cl.empty?
@values
end
def build_require_list(context)
build_referenced_list(context.requires)
end
def build_realize_list(context)
build_referenced_list(context.realizes)
end
def build_child_list(context)
build_referenced_list(context.childs)
end
end
class HTMLPuppetNode < ContextUser
include ResourceContainer, ReferencedListBuilder
attr_reader :path
def initialize(context, html_file, prefix, options)
super(context, options)
@html_file = html_file
@is_module = context.is_module?
@values = {}
context.viewer = self
if options.all_one_file
@path = context.full_name
else
@path = http_url(context.full_name, prefix)
end
AllReferences.add("NODE(#{@context.full_name})", self)
end
def name
@context.name
end
# return the relative file name to store this class in,
# which is also its url
def http_url(full_name, prefix)
path = full_name.dup
path.gsub!(/<<\s*(\w*)/) { "from-#{::Regexp.last_match(1)}" } if path['<<']
File.join(prefix, path.split("::").collect { |p| Digest::MD5.hexdigest(p) }) + ".html"
end
def parent_name
@context.parent.full_name
end
def index_name
name
end
def write_on(f)
value_hash
template = TemplatePage.new(
RDoc::Page::BODYINC,
RDoc::Page::NODE_PAGE,
RDoc::Page::METHOD_LIST
)
template.write_html_on(f, @values)
end
def value_hash
class_attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
d = markup(@context.comment)
@values["description"] = d unless d.empty?
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
rl = build_resource_summary_list
@values["resources"] = rl unless rl.empty?
il = build_include_list(@context)
@values["includes"] = il unless il.empty?
rl = build_require_list(@context)
@values["requires"] = rl unless rl.empty?
rl = build_realize_list(@context)
@values["realizes"] = rl unless rl.empty?
cl = build_child_list(@context)
@values["childs"] = cl unless cl.empty?
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
al = build_alias_summary_list(section)
secdata["aliases"] = al unless al.empty?
co = build_constants_summary_list(section)
secdata["constants"] = co unless co.empty?
al = build_attribute_list(section)
secdata["attributes"] = al unless al.empty?
cl = build_class_list(0, @context, section)
secdata["classlist"] = cl unless cl.empty?
mdl = build_method_detail_list(section)
secdata["method_list"] = mdl unless mdl.empty?
rdl = build_resource_detail_list(section)
secdata["resource_list"] = rdl unless rdl.empty?
secdata
end
@values
end
def build_attribute_list(section)
atts = @context.attributes.sort
res = []
atts.each do |att|
next unless att.section == section
next unless att.visibility == :public || att.visibility == :protected || @options.show_all
entry = {
"name" => CGI.escapeHTML(att.name),
"rw" => att.rw,
"a_desc" => markup(att.comment, true)
}
unless att.visibility == :public || att.visibility == :protected
entry["rw"] << "-"
end
res << entry
end
res
end
def class_attribute_values
h_name = CGI.escapeHTML(name)
@values["classmod"] = "Node"
@values["title"] = CGI.escapeHTML("#{@values['classmod']}: #{h_name}")
c = @context
c = c.parent while c and !c.diagram
@values["diagram"] = diagram_reference(c.diagram) if c && c.diagram
@values["full_name"] = h_name
parent_class = @context.superclass
if parent_class
@values["parent"] = CGI.escapeHTML(parent_class)
if parent_name
lookup = parent_name + "::#{parent_class}"
else
lookup = parent_class
end
lookup = "NODE(#{lookup})"
parent_url = AllReferences[lookup] || AllReferences[parent_class]
@values["par_url"] = aref_to(parent_url.path) if parent_url and parent_url.document_self
end
files = []
@context.in_files.each do |f|
res = {}
full_path = CGI.escapeHTML(f.file_absolute_name)
res["full_path"] = full_path
res["full_path_url"] = aref_to(f.viewer.path) if f.document_self
res["cvsurl"] = cvs_url(@options.webcvs, full_path) if @options.webcvs
files << res
end
@values['infiles'] = files
end
def build_require_list(context)
build_referenced_list(context.requires)
end
def build_realize_list(context)
build_referenced_list(context.realizes)
end
def build_child_list(context)
build_referenced_list(context.childs)
end
def <=>(other)
name <=> other.name
end
end
class HTMLPuppetModule < HtmlClass
def value_hash
@values = super
fl = build_facts_summary_list
@values["facts"] = fl unless fl.empty?
pl = build_plugins_summary_list
@values["plugins"] = pl unless pl.empty?
nl = build_nodes_list(0, @context)
@values["nodelist"] = nl unless nl.empty?
@values
end
def build_nodes_list(level, context)
res = ""
prefix = " ::" * level;
context.nodes.sort.each do |node|
next unless node.document_self
res <<
prefix <<
"Node " <<
href(url(node.viewer.path), "link", node.full_name) <<
"<br />\n"
end
res
end
def build_facts_summary_list
potentially_referenced_list(context.facts) { |fn| ["PLUGIN(#{fn})"] }
end
def build_plugins_summary_list
potentially_referenced_list(context.plugins) { |fn| ["PLUGIN(#{fn})"] }
end
def facts
@context.facts
end
def plugins
@context.plugins
end
end
class HTMLPuppetPlugin < ContextUser
attr_reader :path
def initialize(context, html_file, prefix, options)
super(context, options)
@html_file = html_file
@is_module = false
@values = {}
context.viewer = self
if options.all_one_file
@path = context.full_name
else
@path = http_url(context.full_name, prefix)
end
AllReferences.add("PLUGIN(#{@context.full_name})", self)
end
def name
@context.name
end
# return the relative file name to store this class in,
# which is also its url
def http_url(full_name, prefix)
path = full_name.dup
path.gsub!(/<<\s*(\w*)/) { "from-#{::Regexp.last_match(1)}" } if path['<<']
File.join(prefix, path.split("::")) + ".html"
end
def parent_name
@context.parent.full_name
end
def index_name
name
end
def write_on(f)
value_hash
template = TemplatePage.new(
RDoc::Page::BODYINC,
RDoc::Page::PLUGIN_PAGE,
RDoc::Page::PLUGIN_LIST
)
template.write_html_on(f, @values)
end
def value_hash
attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
d = markup(@context.comment)
@values["description"] = d unless d.empty?
if context.is_fact?
unless context.confine.empty?
res = {}
res["type"] = context.confine[:type]
res["value"] = context.confine[:value]
@values["confine"] = [res]
end
else
@values["type"] = context.type
end
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
secdata
end
@values
end
def attribute_values
h_name = CGI.escapeHTML(name)
if @context.is_fact?
@values["classmod"] = "Fact"
else
@values["classmod"] = "Plugin"
end
@values["title"] = "#{@values['classmod']}: #{h_name}"
@values["full_name"] = h_name
files = []
@context.in_files.each do |f|
res = {}
full_path = CGI.escapeHTML(f.file_absolute_name)
res["full_path"] = full_path
res["full_path_url"] = aref_to(f.viewer.path) if f.document_self
res["cvsurl"] = cvs_url(@options.webcvs, full_path) if @options.webcvs
files << res
end
@values['infiles'] = files
end
def <=>(other)
name <=> other.name
end
end
class HTMLPuppetResource
include MarkUp
attr_reader :context
@@seq = "R000000"
def initialize(context, html_class, options)
@context = context
@html_class = html_class
@options = options
@@seq = @@seq.succ
@seq = @@seq
context.viewer = self
AllReferences.add(name, self)
end
def as_href(from_path)
if @options.all_one_file
"##{path}"
else
HTMLGenerator.gen_url(from_path, path)
end
end
def name
@context.name
end
def section
@context.section
end
def index_name
@context.name.to_s
end
def params
@context.params
end
def parent_name
if @context.parent.parent
@context.parent.parent.full_name
else
nil
end
end
def aref
@seq
end
def path
if @options.all_one_file
aref
else
@html_class.path + "##{aref}"
end
end
def description
markup(@context.comment)
end
def <=>(other)
@context <=> other.context
end
def document_self
@context.document_self
end
def find_symbol(symbol, method = nil)
res = @context.parent.find_symbol(symbol, method)
res && res.viewer
end
end
class PuppetGeneratorInOne < HTMLGeneratorInOne
def gen_method_index
gen_an_index(HtmlMethod.all_methods, 'Defines')
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/util/rdoc/generators/template/puppet/puppet.rb | lib/puppet/util/rdoc/generators/template/puppet/puppet.rb | # frozen_string_literal: true
#
# = CSS2 RDoc HTML template
#
# This is a template for RDoc that uses XHTML 1.0 Transitional and dictates a
# bit more of the appearance of the output to cascading stylesheets than the
# default. It was designed for clean inline code display, and uses DHTMl to
# toggle the visbility of each method's source with each click on the '[source]'
# link.
#
# == Authors
#
# * Michael Granger <ged@FaerieMUD.org>
#
# Copyright (c) 2002, 2003 The FaerieMUD Consortium. Some rights reserved.
#
# This work is licensed under the Creative Commons Attribution License. To view
# a copy of this license, visit http://creativecommons.org/licenses/by/1.0/ or
# send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
# 94305, USA.
#
module RDoc
module Page
FONTS = "Verdana,Arial,Helvetica,sans-serif"
STYLE = %(
/* Reset */
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;}
:focus{outline:0;}
body{line-height:1;color:#282828;background:#fff;}
ol,ul{list-style:none;}
table{border-collapse:separate;border-spacing:0;}
caption,th,td{text-align:left;font-weight:normal;}
blockquote:before,blockquote:after,q:before,q:after{content:"";}
blockquote,q{quotes:"""";}
body {
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 0.9em;
}
pre {
background: none repeat scroll 0 0 #F7F7F7;
border: 1px dashed #DDDDDD;
color: #555555;
font-family: courier;
margin: 10px 19px;
padding: 10px;
}
h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
h1 { font-size: 1.2em; }
h2,h3,h4 { margin-top: 1em; color:#558; }
h2,h3 { font-size: 1.1em; }
a { color: #037; text-decoration: none; }
a:hover { color: #04d; }
/* Override the base stylesheet's Anchor inside a table cell */
td > a {
background: transparent;
color: #039;
text-decoration: none;
}
/* and inside a section title */
.section-title > a {
background: transparent;
color: #eee;
text-decoration: none;
}
/* === Structural elements =================================== */
div#index {
padding: 0;
}
div#index a {
display:inline-block;
padding:2px 10px;
}
div#index .section-bar {
background: #ffe;
padding:10px;
}
div#classHeader, div#fileHeader {
border-bottom: 1px solid #ddd;
padding:10px;
font-size:0.9em;
}
div#classHeader a, div#fileHeader a {
background: inherit;
color: white;
}
div#classHeader td, div#fileHeader td {
color: white;
padding:3px;
font-size:0.9em;
}
div#fileHeader {
background: #057;
}
div#classHeader {
background: #048;
}
div#nodeHeader {
background: #7f7f7f;
}
.class-name-in-header {
font-weight: bold;
}
div#bodyContent {
padding: 10px;
}
div#description {
padding: 10px;
background: #f5f5f5;
border: 1px dotted #ddd;
line-height:1.2em;
}
div#description h1,h2,h3,h4,h5,h6 {
color: #125;;
background: transparent;
}
div#validator-badges {
text-align: center;
}
div#validator-badges img { border: 0; }
div#copyright {
color: #333;
background: #efefef;
font: 0.75em sans-serif;
margin-top: 5em;
margin-bottom: 0;
padding: 0.5em 2em;
}
/* === Classes =================================== */
table.header-table {
color: white;
font-size: small;
}
.type-note {
font-size: small;
color: #DEDEDE;
}
.xxsection-bar {
background: #eee;
color: #333;
padding: 3px;
}
.section-bar {
color: #333;
border-bottom: 1px solid #ddd;
padding:10px 0;
margin:5px 0 10px 0;
}
div#class-list, div#methods, div#includes, div#resources, div#requires, div#realizes, div#attribute-list { padding:10px; }
.section-title {
background: #79a;
color: #eee;
padding: 3px;
margin-top: 2em;
border: 1px solid #999;
}
.top-aligned-row { vertical-align: top }
.bottom-aligned-row { vertical-align: bottom }
/* --- Context section classes ----------------------- */
.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
.context-item-value { font-size: small; color: #448; }
.context-item-desc { color: #333; padding-left: 2em; }
/* --- Method classes -------------------------- */
.method-detail {
background: #f5f5f5;
}
.method-heading {
color: #333;
font-style:italic;
background: #ddd;
padding:5px 10px;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
.method-args { font-style: italic; }
.method-description { padding: 10px 10px 20px 10px; }
/* --- Source code sections -------------------- */
a.source-toggle { font-size: 90%; }
div.method-source-code {
background: #262626;
color: #ffdead;
margin: 1em;
padding: 0.5em;
border: 1px dashed #999;
overflow: hidden;
}
div.method-source-code pre { color: #ffdead; overflow: hidden; }
/* --- Ruby keyword styles --------------------- */
.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }
.ruby-constant { color: #7fffd4; background: transparent; }
.ruby-keyword { color: #00ffff; background: transparent; }
.ruby-ivar { color: #eedd82; background: transparent; }
.ruby-operator { color: #00ffee; background: transparent; }
.ruby-identifier { color: #ffdead; background: transparent; }
.ruby-node { color: #ffa07a; background: transparent; }
.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
.ruby-regexp { color: #ffa07a; background: transparent; }
.ruby-value { color: #7fffd4; background: transparent; }
)
#####################################################################
### H E A D E R T E M P L A T E
#####################################################################
XHTML_PREAMBLE = %(<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
)
HEADER = XHTML_PREAMBLE + %{
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\\"text/css\\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
}
#####################################################################
### C O N T E X T C O N T E N T T E M P L A T E
#####################################################################
CONTEXT_CONTENT = %(
)
#####################################################################
### F O O T E R T E M P L A T E
#####################################################################
FOOTER = %(
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
)
#####################################################################
### F I L E P A G E H E A D E R T E M P L A T E
#####################################################################
FILE_PAGE = %{
<div id="fileHeader">
<h1>%short_name%</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>%dtm_modified%</td>
</tr>
</table>
</div>
}
#####################################################################
### C L A S S P A G E H E A D E R T E M P L A T E
#####################################################################
CLASS_PAGE = %{
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
IF:parent
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
IF:par_url
<a href="%par_url%">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</div>
}
NODE_PAGE = %{
<div id="nodeHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
IF:parent
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
IF:par_url
<a href="%par_url%">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</div>
}
PLUGIN_PAGE = %{
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
</table>
</div>
}
#####################################################################
### M E T H O D L I S T T E M P L A T E
#####################################################################
PLUGIN_LIST = %(
<div id="contextContent">
IF:description
<div id="description">
%description%
</div>
ENDIF:description
IF:toc
<div id="contents-list">
<h3 class="section-bar">Contents</h3>
<ul>
START:toc
<li><a href="#%href%">%secname%</a></li>
END:toc
</ul>
ENDIF:toc
</div>
</div>
<!-- Confine -->
IF:confine
START:confine
<div id="attribute-list">
<h3 class="section-bar">Confine</h3>
%type% %value%
<div class="name-list">
</div>
</div>
END:confine
ENDIF:confine
<!-- Type -->
IF:type
<div id="attribute-list">
<h3 class="section-bar">Type</h3>
%type%
<div class="name-list">
</div>
</div>
ENDIF:type
START:sections
<div id="section">
IF:sectitle
<h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
IF:seccomment
<div class="section-comment">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
END:sections
)
METHOD_LIST = %{
<div id="contextContent">
IF:diagram
<div id="diagram">
%diagram%
</div>
ENDIF:diagram
IF:description
<div id="description">
%description%
</div>
ENDIF:description
IF:toc
<div id="contents-list">
<h3 class="section-bar">Contents</h3>
<ul>
START:toc
<li><a href="#%href%">%secname%</a></li>
END:toc
</ul>
ENDIF:toc
</div>
<!-- if childs -->
IF:childs
<div id="childs">
<h3 class="section-bar">Inherited by</h3>
<div id="childs-list">
START:childs
<span class="child-name">HREF:aref:name:</span>
END:childs
</div>
</div>
ENDIF:childs
IF:methods
<div id="method-list">
<h3 class="section-bar">Defines</h3>
<div class="name-list">
START:methods
HREF:aref:name:
END:methods
</div>
</div>
ENDIF:methods
IF:resources
<div id="method-list">
<h3 class="section-bar">Resources</h3>
<div class="name-list">
START:resources
HREF:aref:name:
END:resources
</div>
</div>
ENDIF:resources
</div>
<!-- if includes -->
IF:includes
<div id="includes">
<h3 class="section-bar">Included Classes</h3>
<div id="includes-list">
START:includes
<span class="include-name">HREF:aref:name:</span>
END:includes
</div>
</div>
ENDIF:includes
<!-- if requires -->
IF:requires
<div id="requires">
<h3 class="section-bar">Required Classes</h3>
<div id="requires-list">
START:requires
<span class="require-name">HREF:aref:name:</span>
END:requires
</div>
</div>
ENDIF:requires
<!-- if realizes -->
IF:realizes
<div id="realizes">
<h3 class="section-bar">Realized Resources</h3>
<div id="realizes-list">
START:realizes
<span class="realizes-name">HREF:aref:name:</span>
END:realizes
</div>
</div>
ENDIF:realizes
START:sections
<div id="section">
IF:sectitle
<h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
IF:seccomment
<div class="section-comment">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
<!-- if facts -->
IF:facts
<div id="class-list">
<h3 class="section-bar">Custom Facts</h3>
START:facts
HREF:aref:name:
END:facts
</div>
ENDIF:facts
<!-- if plugins -->
IF:plugins
<div id="class-list">
<h3 class="section-bar">Plugins</h3>
START:plugins
HREF:aref:name:
END:plugins
</div>
ENDIF:plugins
<!-- if nodes -->
IF:nodelist
<div id="class-list">
<h3 class="section-bar">Nodes</h3>
%nodelist%
</div>
ENDIF:nodelist
<!-- if class -->
IF:classlist
<div id="class-list">
<h3 class="section-bar">Classes and Modules</h3>
%classlist%
</div>
ENDIF:classlist
IF:constants
<div id="constants-list">
<h3 class="section-bar">Global Variables</h3>
<div class="name-list">
<table summary="Variables">
START:constants
<tr class="top-aligned-row context-row">
<td class="context-item-name">%name%</td>
<td>=</td>
<td class="context-item-value">%value%</td>
IF:desc
<td width="3em"> </td>
<td class="context-item-desc">%desc%</td>
ENDIF:desc
</tr>
END:constants
</table>
</div>
</div>
ENDIF:constants
IF:aliases
<div id="aliases-list">
<h3 class="section-bar">External Aliases</h3>
<div class="name-list">
<table summary="aliases">
START:aliases
<tr class="top-aligned-row context-row">
<td class="context-item-name">%old_name%</td>
<td>-></td>
<td class="context-item-value">%new_name%</td>
</tr>
IF:desc
<tr class="top-aligned-row context-row">
<td> </td>
<td colspan="2" class="context-item-desc">%desc%</td>
</tr>
ENDIF:desc
END:aliases
</table>
</div>
</div>
ENDIF:aliases
IF:attributes
<div id="attribute-list">
<h3 class="section-bar">Attributes</h3>
<div class="name-list">
<table>
START:attributes
<tr class="top-aligned-row context-row">
<td class="context-item-name">%name%</td>
IF:rw
<td class="context-item-value"> [%rw%] </td>
ENDIF:rw
IFNOT:rw
<td class="context-item-value"> </td>
ENDIF:rw
<td class="context-item-desc">%a_desc%</td>
</tr>
END:attributes
</table>
</div>
</div>
ENDIF:attributes
<!-- if method_list -->
IF:method_list
<div id="methods">
START:method_list
IF:methods
<h3 class="section-bar">Defines</h3>
START:methods
<div id="method-%aref%" class="method-detail">
<a name="%aref%"></a>
<div class="method-heading">
IF:codeurl
<a href="%codeurl%" target="Code" class="method-signature"
onclick="popupCode('%codeurl%');return false;">
ENDIF:codeurl
IF:sourcecode
<a href="#%aref%" class="method-signature">
ENDIF:sourcecode
IF:callseq
<span class="method-name">%callseq%</span>
ENDIF:callseq
IFNOT:callseq
<span class="method-name">%name%</span><span class="method-args">%params%</span>
ENDIF:callseq
IF:codeurl
</a>
ENDIF:codeurl
IF:sourcecode
</a>
ENDIF:sourcecode
</div>
<div class="method-description">
IF:m_desc
%m_desc%
ENDIF:m_desc
IF:sourcecode
<p><a class="source-toggle" href="#"
onclick="toggleCode('%aref%-source');return false;">[Source]</a></p>
<div class="method-source-code" id="%aref%-source">
<pre>
%sourcecode%
</pre>
</div>
ENDIF:sourcecode
</div>
</div>
END:methods
ENDIF:methods
END:method_list
</div>
ENDIF:method_list
<!-- if resource_list -->
IF:resource_list
<div id="resources">
<h3 class="section-bar">Resources</h3>
START:resource_list
<div id="method-%aref%" class="method-detail">
<a name="%aref%"></a>
<div class="method-heading">
<span class="method-name">%name%</span><br />
IF:params
START:params
<span class="method-args">%name% => %value%</span><br />
END:params
ENDIF:params
</div>
<div class="method-description">
IF:m_desc
%m_desc%
ENDIF:m_desc
</div>
</div>
END:resource_list
</div>
ENDIF:resource_list
END:sections
}
#####################################################################
### B O D Y T E M P L A T E
#####################################################################
BODY = HEADER + %(
!INCLUDE! <!-- banner header -->
<div id="bodyContent">
) + METHOD_LIST + %(
</div>
) + FOOTER
BODYINC = HEADER + %(
!INCLUDE! <!-- banner header -->
<div id="bodyContent">
!INCLUDE!
</div>
) + FOOTER
#####################################################################
### S O U R C E C O D E T E M P L A T E
#####################################################################
SRC_PAGE = XHTML_PREAMBLE + %(
<html>
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre>%code%</pre>
</body>
</html>
)
#####################################################################
### I N D E X F I L E T E M P L A T E S
#####################################################################
FR_INDEX_BODY = %(
!INCLUDE!
)
FILE_INDEX = XHTML_PREAMBLE + %(
<!--
%list_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%list_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" />
<base target="docwin" />
</head>
<body>
<div id="index">
<h1 class="section-bar">%list_title%</h1>
<div id="index-entries">
START:entries
<a href="%href%">%name%</a><br />
END:entries
</div>
</div>
</body>
</html>
)
TOP_INDEX = XHTML_PREAMBLE + %{
<!--
%list_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%list_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" />
<base target="classes" />
<SCRIPT LANGUAGE="JavaScript">
<!--
function load(classlist,module) {
parent.classes.location.href = classlist;
parent.docwin.location.href = module;
}
//--></SCRIPT>
</head>
<body>
<div id="index">
<h1 class="section-bar">%list_title%</h1>
<div id="index-entries">
START:entries
<a href="%classlist%" onclick="load('%classlist%','%module%'); return true;">%name%</a><br />
END:entries
</div>
</div>
</body>
</html>
}
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
COMBO_INDEX = XHTML_PREAMBLE + %{
<!--
%classes_title% & %defines_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%classes_title% & %defines_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="../%style_url%" type="text/css" />
<base target="docwin" />
<SCRIPT LANGUAGE="JavaScript">
<!--
function load(url) {
parent.docwin.location.href = url;
}
//--></SCRIPT>
</head>
<body>
<div id="index">
<a href="../fr_class_index.html" target="classes">All Classes</a><br />
<h1 class="section-bar">Module</h1>
<div id="index-entries">
START:module
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:module
</div>
</div>
<div id="index">
IF:nodes
<h1 class="section-bar">%nodes_title%</h1>
<div id="index-entries">
START:nodes
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:nodes
</div>
ENDIF:nodes
IF:classes
<h1 class="section-bar">%classes_title%</h1>
<div id="index-entries">
START:classes
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:classes
</div>
ENDIF:classes
IF:defines
<h1 class="section-bar">%defines_title%</h1>
<div id="index-entries">
START:defines
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:defines
</div>
ENDIF:defines
IF:facts
<h1 class="section-bar">%facts_title%</h1>
<div id="index-entries">
START:facts
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:facts
</div>
ENDIF:facts
IF:plugins
<h1 class="section-bar">%plugins_title%</h1>
<div id="index-entries">
START:plugins
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:plugins
</div>
ENDIF:plugins
</div>
</body>
</html>
}
INDEX = %(<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<!--
%title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
</head>
<frameset cols="20%, 80%">
<frameset rows="30%,70%">
<frame src="fr_modules_index.html" title="All Modules" />
<frame src="fr_class_index.html" name="classes" title="Classes & Defines" />
</frameset>
<frame src="%initial_page%" name="docwin" />
</frameset>
</html>
)
end # module Page
end # class RDoc
require 'rdoc/generators/template/html/one_page_html'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/rdoc/parser/puppet_parser_rdoc2.rb | lib/puppet/util/rdoc/parser/puppet_parser_rdoc2.rb | # frozen_string_literal: true
require_relative '../../../../puppet/util/rdoc/parser/puppet_parser_core'
module RDoc
PUPPET_RDOC_VERSION = 2
# @api private
class PuppetParserRDoc2 < Parser
include PuppetParserCore
def create_rdoc_preprocess
Markup::PreProcess.new(@input_file_name, @options.rdoc_include)
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/util/rdoc/parser/puppet_parser_core.rb | lib/puppet/util/rdoc/parser/puppet_parser_core.rb | # frozen_string_literal: true
# Functionality common to both our RDoc version 1 and 2 parsers.
module RDoc::PuppetParserCore
SITE = "__site__"
def self.included(base)
base.class_eval do
attr_accessor :input_file_name, :top_level
# parser registration into RDoc
parse_files_matching(/\.(rb)$/)
end
end
# called with the top level file
def initialize(top_level, file_name, body, options, stats)
@options = options
@stats = stats
@input_file_name = file_name
@top_level = top_level
@top_level.extend(RDoc::PuppetTopLevel)
@progress = $stderr unless options.quiet
end
# main entry point
def scan
environment = Puppet.lookup(:current_environment)
scan_top_level(@top_level, environment)
@top_level
end
# Due to a bug in RDoc, we need to roll our own find_module_named
# The issue is that RDoc tries harder by asking the parent for a class/module
# of the name. But by doing so, it can mistakenly use a module of same name
# but from which we are not descendant.
def find_object_named(container, name)
return container if container.name == name
container.each_classmodule do |m|
return m if m.name == name
end
nil
end
# walk down the namespace and lookup/create container as needed
def get_class_or_module(container, name)
# class ::A -> A is in the top level
if name =~ /^::/
container = @top_level
end
names = name.split('::')
final_name = names.pop
names.each do |n|
prev_container = container
container = find_object_named(container, n)
container ||= prev_container.add_class(RDoc::PuppetClass, n, nil)
end
[container, final_name]
end
# split_module tries to find if +path+ belongs to the module path
# if it does, it returns the module name, otherwise if we are sure
# it is part of the global manifest path, "__site__" is returned.
# And finally if this path couldn't be mapped anywhere, nil is returned.
def split_module(path, environment)
# find a module
fullpath = File.expand_path(path)
Puppet.debug "rdoc: testing #{fullpath}"
if fullpath =~ %r{(.*)/([^/]+)/(?:manifests|plugins|lib)/.+\.(rb)$}
modpath = ::Regexp.last_match(1)
name = ::Regexp.last_match(2)
Puppet.debug "rdoc: module #{name} into #{modpath} ?"
environment.modulepath.each do |mp|
if File.identical?(modpath, mp)
Puppet.debug "rdoc: found module #{name}"
return name
end
end
end
if fullpath =~ /\.(rb)$/
# there can be paths we don't want to scan under modules
# imagine a ruby or manifest that would be distributed as part as a module
# but we don't want those to be hosted under <site>
environment.modulepath.each do |mp|
# check that fullpath is a descendant of mp
dirname = fullpath
previous = dirname
while (dirname = File.dirname(previous)) != previous
previous = dirname
return nil if File.identical?(dirname, mp)
end
end
end
# we are under a global manifests
Puppet.debug "rdoc: global manifests"
SITE
end
# create documentation for the top level +container+
def scan_top_level(container, environment)
# use the module README as documentation for the module
comment = ""
%w[README README.rdoc].each do |rfile|
readme = File.join(File.dirname(File.dirname(@input_file_name)), rfile)
# module README should be UTF-8, not default system encoding
comment = File.open(readme, "r:UTF-8", &:read) if FileTest.readable?(readme)
end
look_for_directives_in(container, comment) unless comment.empty?
# infer module name from directory
name = split_module(@input_file_name, environment)
if name.nil?
# skip .pp files that are not in manifests directories as we can't guarantee they're part
# of a module or the global configuration.
# PUP-3638, keeping this while it should have no effect since no .pp files are now processed
container.document_self = false
return
end
Puppet.debug "rdoc: scanning for #{name}"
container.module_name = name
container.global = true if name == SITE
container, name = get_class_or_module(container, name)
mod = container.add_module(RDoc::PuppetModule, name)
mod.record_location(@top_level)
mod.add_comment(comment, @top_level)
if @input_file_name =~ /\.rb$/
parse_plugins(mod)
end
end
# create documentation for plugins
def parse_plugins(container)
Puppet.debug "rdoc: scanning plugin or fact"
if @input_file_name =~ %r{/facter/[^/]+\.rb$}
parse_fact(container)
else
parse_puppet_plugin(container)
end
end
# this is a poor man custom fact parser :-)
def parse_fact(container)
comments = ""
current_fact = nil
parsed_facts = []
File.open(@input_file_name) do |of|
of.each do |line|
# fetch comments
case line
when /^[ \t]*# ?(.*)$/
comments += ::Regexp.last_match(1) + "\n"
when /^[ \t]*(Facter.add|Puppet\.runtime\[:facter\].add)\(['"](.*?)['"]\)/
current_fact = RDoc::Fact.new(::Regexp.last_match(1), {})
look_for_directives_in(container, comments) unless comments.empty?
current_fact.comment = comments
parsed_facts << current_fact
comments = ""
Puppet.debug "rdoc: found custom fact #{current_fact.name}"
when /^[ \t]*confine[ \t]*:(.*?)[ \t]*=>[ \t]*(.*)$/
current_fact.confine = { :type => ::Regexp.last_match(1), :value => ::Regexp.last_match(2) } unless current_fact.nil?
else # unknown line type
comments = ""
end
end
end
parsed_facts.each do |f|
container.add_fact(f)
f.record_location(@top_level)
end
end
# this is a poor man puppet plugin parser :-)
# it doesn't extract doc nor desc :-(
def parse_puppet_plugin(container)
comments = ""
current_plugin = nil
File.open(@input_file_name) do |of|
of.each do |line|
# fetch comments
case line
when /^[ \t]*# ?(.*)$/
comments += ::Regexp.last_match(1) + "\n"
when /^[ \t]*(?:Puppet::Parser::Functions::)?newfunction[ \t]*\([ \t]*:(.*?)[ \t]*,[ \t]*:type[ \t]*=>[ \t]*(:rvalue|:lvalue)/
current_plugin = RDoc::Plugin.new(::Regexp.last_match(1), "function")
look_for_directives_in(container, comments) unless comments.empty?
current_plugin.comment = comments
current_plugin.record_location(@top_level)
container.add_plugin(current_plugin)
comments = ""
Puppet.debug "rdoc: found new function plugins #{current_plugin.name}"
when /^[ \t]*Puppet::Type.newtype[ \t]*\([ \t]*:(.*?)\)/
current_plugin = RDoc::Plugin.new(::Regexp.last_match(1), "type")
look_for_directives_in(container, comments) unless comments.empty?
current_plugin.comment = comments
current_plugin.record_location(@top_level)
container.add_plugin(current_plugin)
comments = ""
Puppet.debug "rdoc: found new type plugins #{current_plugin.name}"
when /module Puppet::Parser::Functions/
# skip
else # unknown line type
comments = ""
end
end
end
end
# New instance of the appropriate PreProcess for our RDoc version.
def create_rdoc_preprocess
raise(NotImplementedError, "This method must be overwritten for whichever version of RDoc this parser is working with")
end
# look_for_directives_in scans the current +comment+ for RDoc directives
def look_for_directives_in(context, comment)
preprocess = create_rdoc_preprocess
preprocess.handle(comment) do |directive, param|
case directive
when "stopdoc"
context.stop_doc
""
when "startdoc"
context.start_doc
context.force_documentation = true
""
when "enddoc"
# context.done_documenting = true
# ""
throw :enddoc
when "main"
options = Options.instance
options.main_page = param
""
when "title"
options = Options.instance
options.title = param
""
when "section"
context.set_current_section(param, comment)
comment.replace("") # 1.8 doesn't support #clear
break
else
warn "Unrecognized directive '#{directive}'"
break
end
end
remove_private_comments(comment)
end
def remove_private_comments(comment)
comment.gsub!(/^#--.*?^#\+\+/m, '')
comment.sub!(/^#--.*/m, '')
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/util/windows/security_descriptor.rb | lib/puppet/util/windows/security_descriptor.rb | # frozen_string_literal: true
# Windows Security Descriptor
#
# Represents a security descriptor that can be applied to any Windows securable
# object, e.g. file, registry key, service, etc. It consists of an owner, group,
# flags, DACL, and SACL. The SACL is not currently supported, though it has the
# same layout as a DACL.
#
# @see https://msdn.microsoft.com/en-us/library/windows/desktop/aa379563(v=vs.85).aspx
# @api private
class Puppet::Util::Windows::SecurityDescriptor
require_relative '../../../puppet/util/windows/security'
include Puppet::Util::Windows::SID
attr_reader :owner, :group, :dacl
attr_accessor :protect
# Construct a security descriptor
#
# @param owner [String] The SID of the owner, e.g. 'S-1-5-18'
# @param group [String] The SID of the group
# @param dacl [AccessControlList] The ACL specifying the rights granted to
# each user for accessing the object that the security descriptor refers to.
# @param protect [Boolean] If true, then inheritable access control
# entries will be blocked, and not applied to the object.
def initialize(owner, group, dacl, protect = false)
@owner = owner
@group = group
@dacl = dacl
@protect = protect
end
# Set the owner. Non-inherited access control entries assigned to the
# current owner will be assigned to the new owner.
#
# @param new_owner [String] The SID of the new owner, e.g. 'S-1-5-18'
def owner=(new_owner)
if @owner != new_owner
@dacl.reassign!(@owner, new_owner)
@owner = new_owner
end
end
# Set the group. Non-inherited access control entries assigned to the
# current group will be assigned to the new group.
#
# @param new_group [String] The SID of the new group, e.g. 'S-1-0-0'
def group=(new_group)
if @group != new_group
@dacl.reassign!(@group, new_group)
@group = new_group
end
end
def inspect
str = sid_to_name(owner)
str << "\n"
str << sid_to_name(group)
str << "\n"
str << @dacl.inspect
str
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/util/windows/security.rb | lib/puppet/util/windows/security.rb | # frozen_string_literal: true
# This class maps POSIX owner, group, and modes to the Windows
# security model, and back.
#
# The primary goal of this mapping is to ensure that owner, group, and
# modes can be round-tripped in a consistent and deterministic
# way. Otherwise, Puppet might think file resources are out-of-sync
# every time it runs. A secondary goal is to provide equivalent
# permissions for common use-cases. For example, setting the owner to
# "Administrators", group to "Users", and mode to 750 (which also
# denies access to everyone else.
#
# There are some well-known problems mapping windows and POSIX
# permissions due to differences between the two security
# models. Search for "POSIX permission mapping leak". In POSIX, access
# to a file is determined solely based on the most specific class
# (user, group, other). So a mode of 460 would deny write access to
# the owner even if they are a member of the group. But in Windows,
# the entire access control list is walked until the user is
# explicitly denied or allowed (denied take precedence, and if neither
# occurs they are denied). As a result, a user could be allowed access
# based on their group membership. To solve this problem, other people
# have used deny access control entries to more closely model POSIX,
# but this introduces a lot of complexity.
#
# In general, this implementation only supports "typical" permissions,
# where group permissions are a subset of user, and other permissions
# are a subset of group, e.g. 754, but not 467. However, there are
# some Windows quirks to be aware of.
#
# * The owner can be either a user or group SID, and most system files
# are owned by the Administrators group.
# * The group can be either a user or group SID.
# * Unexpected results can occur if the owner and group are the
# same, but the user and group classes are different, e.g. 750. In
# this case, it is not possible to allow write access to the owner,
# but not the group. As a result, the actual permissions set on the
# file would be 770.
# * In general, only privileged users can set the owner, group, or
# change the mode for files they do not own. In 2003, the user must
# be a member of the Administrators group. In Vista/2008, the user
# must be running with elevated privileges.
# * A file/dir can be deleted by anyone with the DELETE access right
# OR by anyone that has the FILE_DELETE_CHILD access right for the
# parent. See https://support.microsoft.com/kb/238018. But on Unix,
# the user must have write access to the file/dir AND execute access
# to all of the parent path components.
# * Many access control entries are inherited from parent directories,
# and it is common for file/dirs to have more than 3 entries,
# e.g. Users, Power Users, Administrators, SYSTEM, etc, which cannot
# be mapped into the 3 class POSIX model. The get_mode method will
# set the S_IEXTRA bit flag indicating that an access control entry
# was found whose SID is neither the owner, group, or other. This
# enables Puppet to detect when file/dirs are out-of-sync,
# especially those that Puppet did not create, but is attempting
# to manage.
# * A special case of this is S_ISYSTEM_MISSING, which is set when the
# SYSTEM permissions are *not* present on the DACL.
# * On Unix, the owner and group can be modified without changing the
# mode. But on Windows, an access control entry specifies which SID
# it applies to. As a result, the set_owner and set_group methods
# automatically rebuild the access control list based on the new
# (and different) owner or group.
require_relative '../../../puppet/util/windows'
require 'pathname'
require 'ffi'
module Puppet::Util::Windows::Security
include Puppet::Util::Windows::String
extend Puppet::Util::Windows::Security
extend FFI::Library
# file modes
S_IRUSR = 0o000400
S_IRGRP = 0o000040
S_IROTH = 0o000004
S_IWUSR = 0o000200
S_IWGRP = 0o000020
S_IWOTH = 0o000002
S_IXUSR = 0o000100
S_IXGRP = 0o000010
S_IXOTH = 0o000001
S_IRWXU = 0o000700
S_IRWXG = 0o000070
S_IRWXO = 0o000007
S_ISVTX = 0o001000
S_IEXTRA = 0o2000000 # represents an extra ace
S_ISYSTEM_MISSING = 0o4000000
# constants that are missing from Windows::Security
PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000
NO_INHERITANCE = 0x0
SE_DACL_PROTECTED = 0x1000
FILE = Puppet::Util::Windows::File
SE_BACKUP_NAME = 'SeBackupPrivilege'
SE_DEBUG_NAME = 'SeDebugPrivilege'
SE_RESTORE_NAME = 'SeRestorePrivilege'
DELETE = 0x00010000
READ_CONTROL = 0x20000
WRITE_DAC = 0x40000
WRITE_OWNER = 0x80000
OWNER_SECURITY_INFORMATION = 1
GROUP_SECURITY_INFORMATION = 2
DACL_SECURITY_INFORMATION = 4
# Set the owner of the object referenced by +path+ to the specified
# +owner_sid+. The owner sid should be of the form "S-1-5-32-544"
# and can either be a user or group. Only a user with the
# SE_RESTORE_NAME privilege in their process token can overwrite the
# object's owner to something other than the current user.
def set_owner(owner_sid, path)
sd = get_security_descriptor(path)
if owner_sid != sd.owner
sd.owner = owner_sid
set_security_descriptor(path, sd)
end
end
# Get the owner of the object referenced by +path+. The returned
# value is a SID string, e.g. "S-1-5-32-544". Any user with read
# access to an object can get the owner. Only a user with the
# SE_BACKUP_NAME privilege in their process token can get the owner
# for objects they do not have read access to.
def get_owner(path)
return unless supports_acl?(path)
get_security_descriptor(path).owner
end
# Set the owner of the object referenced by +path+ to the specified
# +group_sid+. The group sid should be of the form "S-1-5-32-544"
# and can either be a user or group. Any user with WRITE_OWNER
# access to the object can change the group (regardless of whether
# the current user belongs to that group or not).
def set_group(group_sid, path)
sd = get_security_descriptor(path)
if group_sid != sd.group
sd.group = group_sid
set_security_descriptor(path, sd)
end
end
# Get the group of the object referenced by +path+. The returned
# value is a SID string, e.g. "S-1-5-32-544". Any user with read
# access to an object can get the group. Only a user with the
# SE_BACKUP_NAME privilege in their process token can get the group
# for objects they do not have read access to.
def get_group(path)
return unless supports_acl?(path)
get_security_descriptor(path).group
end
FILE_PERSISTENT_ACLS = 0x00000008
def supports_acl?(path)
supported = false
root = Pathname.new(path).enum_for(:ascend).to_a.last.to_s
# 'A trailing backslash is required'
root = "#{root}\\" unless root =~ %r{[/\\]$}
FFI::MemoryPointer.new(:pointer, 1) do |flags_ptr|
if GetVolumeInformationW(wide_string(root), FFI::Pointer::NULL, 0,
FFI::Pointer::NULL, FFI::Pointer::NULL,
flags_ptr, FFI::Pointer::NULL, 0) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get volume information")
end
supported = flags_ptr.read_dword & FILE_PERSISTENT_ACLS == FILE_PERSISTENT_ACLS
end
supported
end
MASK_TO_MODE = {
FILE::FILE_GENERIC_READ => S_IROTH,
FILE::FILE_GENERIC_WRITE => S_IWOTH,
(FILE::FILE_GENERIC_EXECUTE & ~FILE::FILE_READ_ATTRIBUTES) => S_IXOTH
}
def get_aces_for_path_by_sid(path, sid)
get_security_descriptor(path).dacl.select { |ace| ace.sid == sid }
end
# Get the mode of the object referenced by +path+. The returned
# integer value represents the POSIX-style read, write, and execute
# modes for the user, group, and other classes, e.g. 0640. Any user
# with read access to an object can get the mode. Only a user with
# the SE_BACKUP_NAME privilege in their process token can get the
# mode for objects they do not have read access to.
def get_mode(path)
return unless supports_acl?(path)
well_known_world_sid = Puppet::Util::Windows::SID::Everyone
well_known_nobody_sid = Puppet::Util::Windows::SID::Nobody
well_known_system_sid = Puppet::Util::Windows::SID::LocalSystem
well_known_app_packages_sid = Puppet::Util::Windows::SID::AllAppPackages
mode = S_ISYSTEM_MISSING
sd = get_security_descriptor(path)
sd.dacl.each do |ace|
next if ace.inherit_only?
case ace.sid
when sd.owner
MASK_TO_MODE.each_pair do |k, v|
if (ace.mask & k) == k
mode |= (v << 6)
end
end
when sd.group
MASK_TO_MODE.each_pair do |k, v|
if (ace.mask & k) == k
mode |= (v << 3)
end
end
when well_known_world_sid
MASK_TO_MODE.each_pair do |k, v|
if (ace.mask & k) == k
mode |= (v << 6) | (v << 3) | v
end
end
if File.directory?(path) &&
(ace.mask & (FILE::FILE_WRITE_DATA | FILE::FILE_EXECUTE | FILE::FILE_DELETE_CHILD)) == (FILE::FILE_WRITE_DATA | FILE::FILE_EXECUTE)
mode |= S_ISVTX;
end
when well_known_nobody_sid
if (ace.mask & FILE::FILE_APPEND_DATA).nonzero?
mode |= S_ISVTX
end
when well_known_app_packages_sid, well_known_system_sid
# do nothing
else
# puts "Warning, unable to map SID into POSIX mode: #{ace.sid}"
mode |= S_IEXTRA
end
if ace.sid == well_known_system_sid
mode &= ~S_ISYSTEM_MISSING
end
# if owner and group the same, then user and group modes are the OR of both
if sd.owner == sd.group
mode |= ((mode & S_IRWXG) << 3) | ((mode & S_IRWXU) >> 3)
# puts "owner: #{sd.group}, 0x#{ace.mask.to_s(16)}, #{mode.to_s(8)}"
end
end
# puts "get_mode: #{mode.to_s(8)}"
mode
end
MODE_TO_MASK = {
S_IROTH => FILE::FILE_GENERIC_READ,
S_IWOTH => FILE::FILE_GENERIC_WRITE,
S_IXOTH => (FILE::FILE_GENERIC_EXECUTE & ~FILE::FILE_READ_ATTRIBUTES),
}
# Set the mode of the object referenced by +path+ to the specified
# +mode+. The mode should be specified as POSIX-style read, write,
# and execute modes for the user, group, and other classes,
# e.g. 0640. The sticky bit, S_ISVTX, is supported, but is only
# meaningful for directories. If set, group and others are not
# allowed to delete child objects for which they are not the owner.
# By default, the DACL is set to protected, meaning it does not
# inherit access control entries from parent objects. This can be
# changed by setting +protected+ to false. The owner of the object
# (with READ_CONTROL and WRITE_DACL access) can always change the
# mode. Only a user with the SE_BACKUP_NAME and SE_RESTORE_NAME
# privileges in their process token can change the mode for objects
# that they do not have read and write access to.
def set_mode(mode, path, protected = true, managing_owner = false, managing_group = false)
sd = get_security_descriptor(path)
well_known_world_sid = Puppet::Util::Windows::SID::Everyone
well_known_nobody_sid = Puppet::Util::Windows::SID::Nobody
well_known_system_sid = Puppet::Util::Windows::SID::LocalSystem
owner_allow = FILE::STANDARD_RIGHTS_ALL |
FILE::FILE_READ_ATTRIBUTES |
FILE::FILE_WRITE_ATTRIBUTES
# this prevents a mode that is not 7 from taking ownership of a file based
# on group membership and rewriting it / making it executable
group_allow = FILE::STANDARD_RIGHTS_READ |
FILE::FILE_READ_ATTRIBUTES |
FILE::SYNCHRONIZE
other_allow = FILE::STANDARD_RIGHTS_READ |
FILE::FILE_READ_ATTRIBUTES |
FILE::SYNCHRONIZE
nobody_allow = 0
system_allow = 0
MODE_TO_MASK.each do |k, v|
if ((mode >> 6) & k) == k
owner_allow |= v
end
if ((mode >> 3) & k) == k
group_allow |= v
end
if (mode & k) == k
other_allow |= v
end
end
# With a mode value of '7' for group / other, the value must then include
# additional perms beyond STANDARD_RIGHTS_READ to allow DACL modification
if (mode & S_IRWXG) == S_IRWXG
group_allow |= FILE::DELETE | FILE::WRITE_DAC | FILE::WRITE_OWNER
end
if (mode & S_IRWXO) == S_IRWXO
other_allow |= FILE::DELETE | FILE::WRITE_DAC | FILE::WRITE_OWNER
end
if (mode & S_ISVTX).nonzero?
nobody_allow |= FILE::FILE_APPEND_DATA;
end
isownergroup = sd.owner == sd.group
# caller is NOT managing SYSTEM by using group or owner, so set to FULL
if ![sd.owner, sd.group].include? well_known_system_sid
# we don't check S_ISYSTEM_MISSING bit, but automatically carry over existing SYSTEM perms
# by default set SYSTEM perms to full
system_allow = FILE::FILE_ALL_ACCESS
else
# It is possible to set SYSTEM with a mode other than Full Control (7) however this makes no sense and in practical terms
# should not be done. We can trap these instances and correct them before being applied.
if (sd.owner == well_known_system_sid) && (owner_allow != FILE::FILE_ALL_ACCESS)
# If owner and group are both SYSTEM but group is unmanaged the control rights of system will be set to FullControl by
# the unmanaged group, so there is no need for the warning
if managing_owner && (!isownergroup || managing_group)
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.warning _("Setting control rights for %{path} owner SYSTEM to less than Full Control rights. Setting SYSTEM rights to less than Full Control may have unintented consequences for operations on this file") % { path: path }
elsif managing_owner && isownergroup
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("%{path} owner and group both set to user SYSTEM, but group is not managed directly: SYSTEM user rights will be set to FullControl by group") % { path: path } }
else
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("An attempt to set mode %{mode} on item %{path} would result in the owner, SYSTEM, to have less than Full Control rights. This attempt has been corrected to Full Control") % { mode: mode.to_s(8), path: path } }
owner_allow = FILE::FILE_ALL_ACCESS
end
end
if (sd.group == well_known_system_sid) && (group_allow != FILE::FILE_ALL_ACCESS)
# If owner and group are both SYSTEM but owner is unmanaged the control rights of system will be set to FullControl by
# the unmanaged owner, so there is no need for the warning.
if managing_group && (!isownergroup || managing_owner)
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.warning _("Setting control rights for %{path} group SYSTEM to less than Full Control rights. Setting SYSTEM rights to less than Full Control may have unintented consequences for operations on this file") % { path: path }
elsif managing_group && isownergroup
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("%{path} owner and group both set to user SYSTEM, but owner is not managed directly: SYSTEM user rights will be set to FullControl by owner") % { path: path } }
else
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("An attempt to set mode %{mode} on item %{path} would result in the group, SYSTEM, to have less than Full Control rights. This attempt has been corrected to Full Control") % { mode: mode.to_s(8), path: path } }
group_allow = FILE::FILE_ALL_ACCESS
end
end
end
# even though FILE_DELETE_CHILD only applies to directories, it can be set on files
# this is necessary to do to ensure a file ends up with (F) FullControl
if (mode & (S_IWUSR | S_IXUSR)) == (S_IWUSR | S_IXUSR)
owner_allow |= FILE::FILE_DELETE_CHILD
end
if (mode & (S_IWGRP | S_IXGRP)) == (S_IWGRP | S_IXGRP) && (mode & S_ISVTX) == 0
group_allow |= FILE::FILE_DELETE_CHILD
end
if (mode & (S_IWOTH | S_IXOTH)) == (S_IWOTH | S_IXOTH) && (mode & S_ISVTX) == 0
other_allow |= FILE::FILE_DELETE_CHILD
end
# if owner and group the same, then map group permissions to the one owner ACE
if isownergroup
owner_allow |= group_allow
end
# if any ACE allows write, then clear readonly bit, but do this before we overwrite
# the DACl and lose our ability to set the attribute
if ((owner_allow | group_allow | other_allow) & FILE::FILE_WRITE_DATA) == FILE::FILE_WRITE_DATA
FILE.remove_attributes(path, FILE::FILE_ATTRIBUTE_READONLY)
end
isdir = File.directory?(path)
dacl = Puppet::Util::Windows::AccessControlList.new
dacl.allow(sd.owner, owner_allow)
unless isownergroup
dacl.allow(sd.group, group_allow)
end
dacl.allow(well_known_world_sid, other_allow)
dacl.allow(well_known_nobody_sid, nobody_allow)
# TODO: system should be first?
flags = !isdir ? 0 :
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE
dacl.allow(well_known_system_sid, system_allow, flags)
# add inherit-only aces for child dirs and files that are created within the dir
inherit_only = Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
if isdir
inherit = inherit_only | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
dacl.allow(Puppet::Util::Windows::SID::CreatorOwner, owner_allow, inherit)
dacl.allow(Puppet::Util::Windows::SID::CreatorGroup, group_allow, inherit)
inherit = inherit_only | Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE
# allow any previously set bits *except* for these
perms_to_strip = ~(FILE::FILE_EXECUTE + FILE::WRITE_OWNER + FILE::WRITE_DAC)
dacl.allow(Puppet::Util::Windows::SID::CreatorOwner, owner_allow & perms_to_strip, inherit)
dacl.allow(Puppet::Util::Windows::SID::CreatorGroup, group_allow & perms_to_strip, inherit)
end
new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, dacl, protected)
set_security_descriptor(path, new_sd)
nil
end
ACL_REVISION = 2
def add_access_allowed_ace(acl, mask, sid, inherit = nil)
inherit ||= NO_INHERITANCE
Puppet::Util::Windows::SID.string_to_sid_ptr(sid) do |sid_ptr|
if Puppet::Util::Windows::SID.IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
if AddAccessAllowedAceEx(acl, ACL_REVISION, inherit, mask, sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to add access control entry")
end
end
# ensure this method is void if it doesn't raise
nil
end
def add_access_denied_ace(acl, mask, sid, inherit = nil)
inherit ||= NO_INHERITANCE
Puppet::Util::Windows::SID.string_to_sid_ptr(sid) do |sid_ptr|
if Puppet::Util::Windows::SID.IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
if AddAccessDeniedAceEx(acl, ACL_REVISION, inherit, mask, sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to add access control entry")
end
end
# ensure this method is void if it doesn't raise
nil
end
def parse_dacl(dacl_ptr)
# REMIND: need to handle NULL DACL
if IsValidAcl(dacl_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid DACL")
end
dacl_struct = ACL.new(dacl_ptr)
ace_count = dacl_struct[:AceCount]
dacl = Puppet::Util::Windows::AccessControlList.new
# deny all
return dacl if ace_count == 0
0.upto(ace_count - 1) do |i|
FFI::MemoryPointer.new(:pointer, 1) do |ace_ptr|
next if GetAce(dacl_ptr, i, ace_ptr) == FFI::WIN32_FALSE
# ACE structures vary depending on the type. We are only concerned with
# ACCESS_ALLOWED_ACE and ACCESS_DENIED_ACEs, which have the same layout
ace = GENERIC_ACCESS_ACE.new(ace_ptr.get_pointer(0)) # deref LPVOID *
ace_type = ace[:Header][:AceType]
if ace_type != Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE &&
ace_type != Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
Puppet.warning _("Unsupported access control entry type: 0x%{type}") % { type: ace_type.to_s(16) }
next
end
# using pointer addition gives the FFI::Pointer a size, but that's OK here
sid = Puppet::Util::Windows::SID.sid_ptr_to_string(ace.pointer + GENERIC_ACCESS_ACE.offset_of(:SidStart))
mask = ace[:Mask]
ace_flags = ace[:Header][:AceFlags]
case ace_type
when Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE
dacl.allow(sid, mask, ace_flags)
when Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
dacl.deny(sid, mask, ace_flags)
end
end
end
dacl
end
# Open an existing file with the specified access mode, and execute a
# block with the opened file HANDLE.
def open_file(path, access, &block)
handle = CreateFileW(
wide_string(path),
access,
FILE::FILE_SHARE_READ | FILE::FILE_SHARE_WRITE,
FFI::Pointer::NULL, # security_attributes
FILE::OPEN_EXISTING,
FILE::FILE_FLAG_OPEN_REPARSE_POINT | FILE::FILE_FLAG_BACKUP_SEMANTICS,
FFI::Pointer::NULL_HANDLE
) # template
if handle == Puppet::Util::Windows::File::INVALID_HANDLE_VALUE
raise Puppet::Util::Windows::Error, _("Failed to open '%{path}'") % { path: path }
end
begin
yield handle
ensure
FFI::WIN32.CloseHandle(handle) if handle
end
# handle has already had CloseHandle called against it, nothing to return
nil
end
# Execute a block with the specified privilege enabled
def with_privilege(privilege, &block)
set_privilege(privilege, true)
yield
ensure
set_privilege(privilege, false)
end
SE_PRIVILEGE_ENABLED = 0x00000002
TOKEN_ADJUST_PRIVILEGES = 0x0020
# Enable or disable a privilege. Note this doesn't add any privileges the
# user doesn't already has, it just enables privileges that are disabled.
def set_privilege(privilege, enable)
return unless Puppet.features.root?
Puppet::Util::Windows::Process.with_process_token(TOKEN_ADJUST_PRIVILEGES) do |token|
Puppet::Util::Windows::Process.lookup_privilege_value(privilege) do |luid|
FFI::MemoryPointer.new(Puppet::Util::Windows::Process::LUID_AND_ATTRIBUTES.size) do |luid_and_attributes_ptr|
# allocate unmanaged memory for structs that we clean up afterwards
luid_and_attributes = Puppet::Util::Windows::Process::LUID_AND_ATTRIBUTES.new(luid_and_attributes_ptr)
luid_and_attributes[:Luid] = luid
luid_and_attributes[:Attributes] = enable ? SE_PRIVILEGE_ENABLED : 0
FFI::MemoryPointer.new(Puppet::Util::Windows::Process::TOKEN_PRIVILEGES.size) do |token_privileges_ptr|
token_privileges = Puppet::Util::Windows::Process::TOKEN_PRIVILEGES.new(token_privileges_ptr)
token_privileges[:PrivilegeCount] = 1
token_privileges[:Privileges][0] = luid_and_attributes
# size is correct given we only have 1 LUID, otherwise would be:
# [:PrivilegeCount].size + [:PrivilegeCount] * LUID_AND_ATTRIBUTES.size
if AdjustTokenPrivileges(token, FFI::WIN32_FALSE,
token_privileges, token_privileges.size,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to adjust process privileges")
end
end
end
end
end
# token / luid structs freed by this point, so return true as nothing raised
true
end
def get_security_descriptor(path)
sd = nil
with_privilege(SE_BACKUP_NAME) do
open_file(path, READ_CONTROL) do |handle|
FFI::MemoryPointer.new(:pointer, 1) do |owner_sid_ptr_ptr|
FFI::MemoryPointer.new(:pointer, 1) do |group_sid_ptr_ptr|
FFI::MemoryPointer.new(:pointer, 1) do |dacl_ptr_ptr|
FFI::MemoryPointer.new(:pointer, 1) do |sd_ptr_ptr|
rv = GetSecurityInfo(
handle,
:SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
owner_sid_ptr_ptr,
group_sid_ptr_ptr,
dacl_ptr_ptr,
FFI::Pointer::NULL, # sacl
sd_ptr_ptr
) # sec desc
raise Puppet::Util::Windows::Error, _("Failed to get security information") if rv != FFI::ERROR_SUCCESS
# these 2 convenience params are not freed since they point inside sd_ptr
owner = Puppet::Util::Windows::SID.sid_ptr_to_string(owner_sid_ptr_ptr.get_pointer(0))
group = Puppet::Util::Windows::SID.sid_ptr_to_string(group_sid_ptr_ptr.get_pointer(0))
FFI::MemoryPointer.new(:word, 1) do |control|
FFI::MemoryPointer.new(:dword, 1) do |revision|
sd_ptr_ptr.read_win32_local_pointer do |sd_ptr|
if GetSecurityDescriptorControl(sd_ptr, control, revision) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get security descriptor control")
end
protect = (control.read_word & SE_DACL_PROTECTED) == SE_DACL_PROTECTED
dacl = parse_dacl(dacl_ptr_ptr.get_pointer(0))
sd = Puppet::Util::Windows::SecurityDescriptor.new(owner, group, dacl, protect)
end
end
end
end
end
end
end
end
end
sd
end
def get_max_generic_acl_size(ace_count)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa378853(v=vs.85).aspx
# To calculate the initial size of an ACL, add the following together, and then align the result to the nearest DWORD:
# * Size of the ACL structure.
# * Size of each ACE structure that the ACL is to contain minus the SidStart member (DWORD) of the ACE.
# * Length of the SID that each ACE is to contain.
ACL.size + ace_count * MAXIMUM_GENERIC_ACE_SIZE
end
# setting DACL requires both READ_CONTROL and WRITE_DACL access rights,
# and their respective privileges, SE_BACKUP_NAME and SE_RESTORE_NAME.
def set_security_descriptor(path, sd)
FFI::MemoryPointer.new(:byte, get_max_generic_acl_size(sd.dacl.count)) do |acl_ptr|
if InitializeAcl(acl_ptr, acl_ptr.size, ACL_REVISION) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to initialize ACL")
end
if IsValidAcl(acl_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid DACL")
end
with_privilege(SE_BACKUP_NAME) do
with_privilege(SE_RESTORE_NAME) do
open_file(path, READ_CONTROL | WRITE_DAC | WRITE_OWNER) do |handle|
Puppet::Util::Windows::SID.string_to_sid_ptr(sd.owner) do |owner_sid_ptr|
Puppet::Util::Windows::SID.string_to_sid_ptr(sd.group) do |group_sid_ptr|
sd.dacl.each do |ace|
case ace.type
when Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE
# puts "ace: allow, sid #{Puppet::Util::Windows::SID.sid_to_name(ace.sid)}, mask 0x#{ace.mask.to_s(16)}"
add_access_allowed_ace(acl_ptr, ace.mask, ace.sid, ace.flags)
when Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
# puts "ace: deny, sid #{Puppet::Util::Windows::SID.sid_to_name(ace.sid)}, mask 0x#{ace.mask.to_s(16)}"
add_access_denied_ace(acl_ptr, ace.mask, ace.sid, ace.flags)
else
raise "We should never get here"
# TODO: this should have been a warning in an earlier commit
end
end
# protected means the object does not inherit aces from its parent
flags = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
flags |= sd.protect ? PROTECTED_DACL_SECURITY_INFORMATION : UNPROTECTED_DACL_SECURITY_INFORMATION
rv = SetSecurityInfo(handle,
:SE_FILE_OBJECT,
flags,
owner_sid_ptr,
group_sid_ptr,
acl_ptr,
FFI::MemoryPointer::NULL)
if rv != FFI::ERROR_SUCCESS
raise Puppet::Util::Windows::Error, _("Failed to set security information")
end
end
end
end
end
end
end
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
# HANDLE WINAPI CreateFile(
# _In_ LPCTSTR lpFileName,
# _In_ DWORD dwDesiredAccess,
# _In_ DWORD dwShareMode,
# _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
# _In_ DWORD dwCreationDisposition,
# _In_ DWORD dwFlagsAndAttributes,
# _In_opt_ HANDLE hTemplateFile
# );
ffi_lib :kernel32
attach_function_private :CreateFileW,
[:lpcwstr, :dword, :dword, :pointer, :dword, :dword, :handle], :handle
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx
# BOOL WINAPI GetVolumeInformation(
# _In_opt_ LPCTSTR lpRootPathName,
# _Out_opt_ LPTSTR lpVolumeNameBuffer,
# _In_ DWORD nVolumeNameSize,
# _Out_opt_ LPDWORD lpVolumeSerialNumber,
# _Out_opt_ LPDWORD lpMaximumComponentLength,
# _Out_opt_ LPDWORD lpFileSystemFlags,
# _Out_opt_ LPTSTR lpFileSystemNameBuffer,
# _In_ DWORD nFileSystemNameSize
# );
ffi_lib :kernel32
attach_function_private :GetVolumeInformationW,
[:lpcwstr, :lpwstr, :dword, :lpdword, :lpdword, :lpdword, :lpwstr, :dword], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374951(v=vs.85).aspx
# BOOL WINAPI AddAccessAllowedAceEx(
# _Inout_ PACL pAcl,
# _In_ DWORD dwAceRevision,
# _In_ DWORD AceFlags,
# _In_ DWORD AccessMask,
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :AddAccessAllowedAceEx,
[:pointer, :dword, :dword, :dword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374964(v=vs.85).aspx
# BOOL WINAPI AddAccessDeniedAceEx(
# _Inout_ PACL pAcl,
# _In_ DWORD dwAceRevision,
# _In_ DWORD AceFlags,
# _In_ DWORD AccessMask,
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :AddAccessDeniedAceEx,
[:pointer, :dword, :dword, :dword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374931(v=vs.85).aspx
# typedef struct _ACL {
# BYTE AclRevision;
# BYTE Sbz1;
# WORD AclSize;
# WORD AceCount;
# WORD Sbz2;
# } ACL, *PACL;
class ACL < FFI::Struct
layout :AclRevision, :byte,
:Sbz1, :byte,
:AclSize, :word,
:AceCount, :word,
:Sbz2, :word
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374912(v=vs.85).aspx
# ACE types
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374919(v=vs.85).aspx
# typedef struct _ACE_HEADER {
# BYTE AceType;
# BYTE AceFlags;
# WORD AceSize;
# } ACE_HEADER, *PACE_HEADER;
class ACE_HEADER < FFI::Struct
layout :AceType, :byte,
:AceFlags, :byte,
:AceSize, :word
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/eventlog.rb | lib/puppet/util/windows/eventlog.rb | # frozen_string_literal: true
require 'ffi'
# Puppet::Util::Windows::EventLog needs to be requirable without having loaded
# any other parts of Puppet so it can be leveraged independently by the code
# that runs Puppet as a service on Windows.
#
# For this reason we:
# - Define Puppet::Util::Windows
# - Replicate logic that exists elsewhere in puppet/util/windows
# - Raise generic RuntimeError instead of Puppet::Util::Windows::Error if its not defined
module Puppet; module Util; module Windows; end; end; end
class Puppet::Util::Windows::EventLog
extend FFI::Library
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx
EVENTLOG_ERROR_TYPE = 0x0001
EVENTLOG_WARNING_TYPE = 0x0002
EVENTLOG_INFORMATION_TYPE = 0x0004
# These are duplicate definitions from Puppet::Util::Windows::ApiTypes,
# established here so this class can be standalone from Puppet, and public so
# we can reference them in tests.
NULL_HANDLE = 0
WIN32_FALSE = 0
# Register an event log handle for the application
# @param source_name [String] the name of the event source to retrieve a handle for
# @return [void]
# @api public
def initialize(source_name = 'Puppet')
@eventlog_handle = RegisterEventSourceW(FFI::Pointer::NULL, wide_string(source_name))
if @eventlog_handle == NULL_HANDLE
# TRANSLATORS 'Windows' is the operating system and 'RegisterEventSourceW' is a API call and should not be translated
raise EventLogError.new(_("RegisterEventSourceW failed to open Windows eventlog"), FFI.errno)
end
end
# Close this instance's event log handle
# @return [void]
# @api public
def close
DeregisterEventSource(@eventlog_handle)
ensure
@eventlog_handle = nil
end
# Report an event to this instance's event log handle. Accepts a string to
# report (:data => <string>) and event type (:event_type => Integer) and id
# (:event_id => Integer) as returned by #to_native. The additional arguments to
# ReportEventW seen in this method aren't exposed - though ReportEventW
# technically can accept multiple strings as well as raw binary data to log,
# we accept a single string from Puppet::Util::Log
#
# @param args [Hash{Symbol=>Object}] options to the associated log event
# @return [void]
# @api public
def report_event(args = {})
unless args[:data].is_a?(String)
raise ArgumentError, _("data must be a string, not %{class_name}") % { class_name: args[:data].class }
end
from_string_to_wide_string(args[:data]) do |message_ptr|
FFI::MemoryPointer.new(:pointer) do |message_array_ptr|
message_array_ptr.write_pointer(message_ptr)
user_sid = FFI::Pointer::NULL
raw_data = FFI::Pointer::NULL
raw_data_size = 0
num_strings = 1
eventlog_category = 0
report_result = ReportEventW(@eventlog_handle, args[:event_type],
eventlog_category, args[:event_id], user_sid,
num_strings, raw_data_size, message_array_ptr, raw_data)
if report_result == WIN32_FALSE
# TRANSLATORS 'Windows' is the operating system and 'ReportEventW' is a API call and should not be translated
raise EventLogError.new(_("ReportEventW failed to report event to Windows eventlog"), FFI.errno)
end
end
end
end
class << self
# Feels more natural to do Puppet::Util::Window::EventLog.open("MyApplication")
alias :open :new
# Query event identifier info for a given log level
# @param level [Symbol] an event log level
# @return [Array] Win API Event ID, Puppet Event ID
# @api public
def to_native(level)
case level
when :debug, :info, :notice
[EVENTLOG_INFORMATION_TYPE, 0x01]
when :warning
[EVENTLOG_WARNING_TYPE, 0x02]
when :err, :alert, :emerg, :crit
[EVENTLOG_ERROR_TYPE, 0x03]
else
raise ArgumentError, _("Invalid log level %{level}") % { level: level }
end
end
end
private
# For the purposes of allowing this class to be standalone, the following are
# duplicate definitions from elsewhere in Puppet:
# If we're loaded via Puppet we should keep the previous behavior of raising
# Puppet::Util::Windows::Error on errors. If we aren't, at least concatenate
# the error code to the exception message to pass this information on to the
# user
if defined?(Puppet::Util::Windows::Error)
EventLogError = Puppet::Util::Windows::Error
else
class EventLogError < RuntimeError
def initialize(msg, code)
# TRANSLATORS 'Win32' is the Windows API and should not be translated
super(msg + ' ' + _("(Win32 error: %{detail})") % { detail: code })
end
end
end
# Private duplicate of Puppet::Util::Windows::String::wide_string
# Not for use outside of EventLog! - use Puppet::Util::Windows instead
# @api private
def wide_string(str)
# if given a nil string, assume caller wants to pass a nil pointer to win32
return nil if str.nil?
str.encode('UTF-16LE')
end
# Private duplicate of Puppet::Util::Windows::ApiTypes::from_string_to_wide_string
# Not for use outside of EventLog! - Use Puppet::Util::Windows instead
# @api private
def from_string_to_wide_string(str, &block)
str = wide_string(str)
FFI::MemoryPointer.from_wide_string(str) { |ptr| yield ptr }
# ptr has already had free called, so nothing to return
nil
end
ffi_convention :stdcall
# The following are typedefs in Puppet::Util::Winodws::ApiTypes, but here we
# use their original FFI counterparts:
# :uintptr_t for :handle
# :int32 for :win32_bool
# :uint16 for :word
# :uint32 for :dword
# :pointer for :lpvoid
# :uchar for :byte
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363678(v=vs.85).aspx
# HANDLE RegisterEventSource(
# _In_ LPCTSTR lpUNCServerName,
# _In_ LPCTSTR lpSourceName
# );
ffi_lib :advapi32
attach_function :RegisterEventSourceW, [:buffer_in, :buffer_in], :uintptr_t
private :RegisterEventSourceW
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363642(v=vs.85).aspx
# BOOL DeregisterEventSource(
# _Inout_ HANDLE hEventLog
# );
ffi_lib :advapi32
attach_function :DeregisterEventSource, [:uintptr_t], :int32
private :DeregisterEventSource
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx
# BOOL ReportEvent(
# _In_ HANDLE hEventLog,
# _In_ WORD wType,
# _In_ WORD wCategory,
# _In_ DWORD dwEventID,
# _In_ PSID lpUserSid,
# _In_ WORD wNumStrings,
# _In_ DWORD dwDataSize,
# _In_ LPCTSTR *lpStrings,
# _In_ LPVOID lpRawData
# );
ffi_lib :advapi32
attach_function :ReportEventW, [:uintptr_t, :uint16, :uint16, :uint32, :pointer, :uint16, :uint32, :pointer, :pointer], :int32
private :ReportEventW
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/daemon.rb | lib/puppet/util/windows/daemon.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows
# The Daemon class, based on the chef/win32-service implementation
class Daemon
include Puppet::FFI::Windows::Constants
extend Puppet::FFI::Windows::Constants
include Puppet::FFI::Windows::Structs
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Functions
# Service is not running
STOPPED = SERVICE_STOPPED
# Service has received a start signal but is not yet running
START_PENDING = SERVICE_START_PENDING
# Service has received a stop signal but is not yet stopped
STOP_PENDING = SERVICE_STOP_PENDING
# Service is running
RUNNING = SERVICE_RUNNING
# Service has received a signal to resume but is not yet running
CONTINUE_PENDING = SERVICE_CONTINUE_PENDING
# Service has received a signal to pause but is not yet paused
PAUSE_PENDING = SERVICE_PAUSE_PENDING
# Service is paused
PAUSED = SERVICE_PAUSED
# Service controls
# Notifies service that it should stop
CONTROL_STOP = SERVICE_CONTROL_STOP
# Notifies service that it should pause
CONTROL_PAUSE = SERVICE_CONTROL_PAUSE
# Notifies service that it should resume
CONTROL_CONTINUE = SERVICE_CONTROL_CONTINUE
# Notifies service that it should return its current status information
CONTROL_INTERROGATE = SERVICE_CONTROL_INTERROGATE
# Notifies a service that its parameters have changed
CONTROL_PARAMCHANGE = SERVICE_CONTROL_PARAMCHANGE
# Notifies a service that there is a new component for binding
CONTROL_NETBINDADD = SERVICE_CONTROL_NETBINDADD
# Notifies a service that a component for binding has been removed
CONTROL_NETBINDREMOVE = SERVICE_CONTROL_NETBINDREMOVE
# Notifies a service that a component for binding has been enabled
CONTROL_NETBINDENABLE = SERVICE_CONTROL_NETBINDENABLE
# Notifies a service that a component for binding has been disabled
CONTROL_NETBINDDISABLE = SERVICE_CONTROL_NETBINDDISABLE
IDLE = 0
# Misc
IDLE_CONTROL_CODE = 0
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 0x00000102
WAIT_FAILED = 0xFFFFFFFF
NO_ERROR = 0
# Wraps SetServiceStatus.
SetTheServiceStatus = proc do |dwCurrentState, dwWin32ExitCode, dwCheckPoint, dwWaitHint|
ss = SERVICE_STATUS.new # Current status of the service.
# Disable control requests until the service is started.
if dwCurrentState == SERVICE_START_PENDING
ss[:dwControlsAccepted] = 0
else
ss[:dwControlsAccepted] =
SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN |
SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_PARAMCHANGE
end
# Initialize ss structure.
ss[:dwServiceType] = SERVICE_WIN32_OWN_PROCESS
ss[:dwServiceSpecificExitCode] = 0
ss[:dwCurrentState] = dwCurrentState
ss[:dwWin32ExitCode] = dwWin32ExitCode
ss[:dwCheckPoint] = dwCheckPoint
ss[:dwWaitHint] = dwWaitHint
@@dwServiceState = dwCurrentState
# Send status of the service to the Service Controller.
unless SetServiceStatus(@@ssh, ss)
SetEvent(@@hStopEvent)
end
end
ERROR_CALL_NOT_IMPLEMENTED = 0x78
# Handles control signals from the service control manager.
Service_Ctrl_ex = proc do |dwCtrlCode, _dwEventType, _lpEventData, _lpContext|
@@waiting_control_code = dwCtrlCode;
return_value = NO_ERROR
begin
dwState = SERVICE_RUNNING
case dwCtrlCode
when SERVICE_CONTROL_STOP
dwState = SERVICE_STOP_PENDING
when SERVICE_CONTROL_SHUTDOWN
dwState = SERVICE_STOP_PENDING
when SERVICE_CONTROL_PAUSE
dwState = SERVICE_PAUSED
when SERVICE_CONTROL_CONTINUE
dwState = SERVICE_RUNNING
# else
# TODO: Handle other control codes? Retain the current state?
end
# Set the status of the service except on interrogation.
unless dwCtrlCode == SERVICE_CONTROL_INTERROGATE
SetTheServiceStatus.call(dwState, NO_ERROR, 0, 0)
end
# Tell service_main thread to stop.
if dwCtrlCode == SERVICE_CONTROL_STOP || dwCtrlCode == SERVICE_CONTROL_SHUTDOWN
if SetEvent(@@hStopEvent) == 0
SetTheServiceStatus.call(SERVICE_STOPPED, FFI.errno, 0, 0)
end
end
rescue
return_value = ERROR_CALL_NOT_IMPLEMENTED
end
return_value
end
# Called by the service control manager after the call to StartServiceCtrlDispatcher.
Service_Main = FFI::Function.new(:void, [:ulong, :pointer], :blocking => false) do |dwArgc, lpszArgv|
# Obtain the name of the service.
if lpszArgv.address != 0
argv = lpszArgv.get_array_of_string(0, dwArgc)
lpszServiceName = argv[0]
else
lpszServiceName = ''
end
# Args passed to Service.start
if dwArgc > 1
@@Argv = argv[1..]
else
@@Argv = nil
end
# Register the service ctrl handler.
@@ssh = RegisterServiceCtrlHandlerExW(
lpszServiceName,
Service_Ctrl_ex,
nil
)
# No service to stop, no service handle to notify, nothing to do but exit.
break if @@ssh == 0
# The service has started.
SetTheServiceStatus.call(SERVICE_RUNNING, NO_ERROR, 0, 0)
SetEvent(@@hStartEvent)
# Main loop for the service.
while WaitForSingleObject(@@hStopEvent, 1000) != WAIT_OBJECT_0
end
# Main loop for the service.
while WaitForSingleObject(@@hStopCompletedEvent, 1000) != WAIT_OBJECT_0
end
ensure
# Stop the service.
SetTheServiceStatus.call(SERVICE_STOPPED, NO_ERROR, 0, 0)
end
# This is a shortcut for Daemon.new + Daemon#mainloop.
#
def self.mainloop
new.mainloop
end
# This is the method that actually puts your code into a loop and allows it
# to run as a service. The code that is actually run while in the mainloop
# is what you defined in your own Daemon#service_main method.
#
def mainloop
@@waiting_control_code = IDLE_CONTROL_CODE
@@dwServiceState = 0
# Redirect STDIN, STDOUT and STDERR to the NUL device if they're still
# associated with a tty. This helps newbs avoid Errno::EBADF errors.
STDIN.reopen('NUL') if STDIN.isatty
STDOUT.reopen('NUL') if STDOUT.isatty
STDERR.reopen('NUL') if STDERR.isatty
# Calling init here so that init failures never even tries to start the
# service. Of course that means that init methods must be very quick
# because the SCM will be receiving no START_PENDING messages while
# init's running.
#
# TODO: Fix?
service_init() if respond_to?('service_init')
# Create the event to signal the service to start.
@@hStartEvent = CreateEventW(nil, 1, 0, nil)
if @@hStartEvent == 0
raise SystemCallError.new('CreateEvent', FFI.errno)
end
# Create the event to signal the service to stop.
@@hStopEvent = CreateEventW(nil, 1, 0, nil)
if @@hStopEvent == 0
raise SystemCallError.new('CreateEvent', FFI.errno)
end
# Create the event to signal the service that stop has completed
@@hStopCompletedEvent = CreateEventW(nil, 1, 0, nil)
if @@hStopCompletedEvent == 0
raise SystemCallError.new('CreateEvent', FFI.errno)
end
hThread = Thread.new do
ste = FFI::MemoryPointer.new(SERVICE_TABLE_ENTRYW, 2)
s = SERVICE_TABLE_ENTRYW.new(ste[0])
s[:lpServiceName] = FFI::MemoryPointer.from_string("")
s[:lpServiceProc] = Service_Main
s = SERVICE_TABLE_ENTRYW.new(ste[1])
s[:lpServiceName] = nil
s[:lpServiceProc] = nil
# No service to step, no service handle, no ruby exceptions, just terminate the thread..
StartServiceCtrlDispatcherW(ste)
end
while (index = WaitForSingleObject(@@hStartEvent, 1000)) == WAIT_TIMEOUT
# The thread exited, so the show is off.
raise "Service_Main thread exited abnormally" unless hThread.alive?
end
if index == WAIT_FAILED
raise SystemCallError.new("WaitForSingleObject", FFI.errno)
end
thr = Thread.new do
while WaitForSingleObject(@@hStopEvent, 1000) == WAIT_TIMEOUT
# Check to see if anything interesting has been signaled
case @@waiting_control_code
when SERVICE_CONTROL_PAUSE
service_pause() if respond_to?('service_pause')
when SERVICE_CONTROL_CONTINUE
service_resume() if respond_to?('service_resume')
when SERVICE_CONTROL_INTERROGATE
service_interrogate() if respond_to?('service_interrogate')
when SERVICE_CONTROL_SHUTDOWN
service_shutdown() if respond_to?('service_shutdown')
when SERVICE_CONTROL_PARAMCHANGE
service_paramchange() if respond_to?('service_paramchange')
when SERVICE_CONTROL_NETBINDADD
service_netbindadd() if respond_to?('service_netbindadd')
when SERVICE_CONTROL_NETBINDREMOVE
service_netbindremove() if respond_to?('service_netbindremove')
when SERVICE_CONTROL_NETBINDENABLE
service_netbindenable() if respond_to?('service_netbindenable')
when SERVICE_CONTROL_NETBINDDISABLE
service_netbinddisable() if respond_to?('service_netbinddisable')
end
@@waiting_control_code = IDLE_CONTROL_CODE
end
service_stop() if respond_to?('service_stop')
ensure
SetEvent(@@hStopCompletedEvent)
end
if respond_to?('service_main')
service_main(*@@Argv)
end
thr.join
end
# Returns the state of the service (as an constant integer) which can be any
# of the service status constants, e.g. RUNNING, PAUSED, etc.
#
# This method is typically used within your service_main method to setup the
# loop. For example:
#
# class MyDaemon < Daemon
# def service_main
# while state == RUNNING || state == PAUSED || state == IDLE
# # Your main loop here
# end
# end
# end
#
# See the Daemon#running? method for an abstraction of the above code.
#
def state
@@dwServiceState
end
#
# Returns whether or not the service is in a running state, i.e. the service
# status is either RUNNING, PAUSED or IDLE.
#
# This is typically used within your service_main method to setup the main
# loop. For example:
#
# class MyDaemon < Daemon
# def service_main
# while running?
# # Your main loop here
# end
# end
# end
#
def running?
[SERVICE_RUNNING, SERVICE_PAUSED, 0].include?(@@dwServiceState)
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/util/windows/file.rb | lib/puppet/util/windows/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows::File
extend Puppet::Util::Windows::String
include Puppet::FFI::Windows::Constants
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Functions
def replace_file(target, source)
target_encoded = wide_string(target.to_s)
source_encoded = wide_string(source.to_s)
flags = REPLACEFILE_IGNORE_MERGE_ERRORS
backup_file = nil
result = ReplaceFileW(
target_encoded,
source_encoded,
backup_file,
flags,
FFI::Pointer::NULL,
FFI::Pointer::NULL
)
return true if result != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "ReplaceFile(#{target}, #{source})"
end
module_function :replace_file
def move_file_ex(source, target, flags = 0)
result = MoveFileExW(wide_string(source.to_s),
wide_string(target.to_s),
flags)
return true if result != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "MoveFileEx(#{source}, #{target}, #{flags.to_s(8)})"
end
module_function :move_file_ex
def symlink(target, symlink)
flags = File.directory?(target) ? 0x1 : 0x0
result = CreateSymbolicLinkW(wide_string(symlink.to_s),
wide_string(target.to_s), flags)
return true if result != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "CreateSymbolicLink(#{symlink}, #{target}, #{flags.to_s(8)})"
end
module_function :symlink
def exist?(path)
path = path.to_str if path.respond_to?(:to_str) # support WatchedFile
path = path.to_s # support String and Pathname
seen_paths = []
# follow up to 64 symlinks before giving up
0.upto(64) do |_depth|
# return false if this path has been seen before. This is protection against circular symlinks
return false if seen_paths.include?(path.downcase)
result = get_attributes(path, false)
# return false for path not found
return false if result == INVALID_FILE_ATTRIBUTES
# return true if path exists and it's not a symlink
# Other file attributes are ignored. https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx
reparse_point = (result & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT
if reparse_point && symlink_reparse_point?(path)
# walk the symlink and try again...
seen_paths << path.downcase
path = readlink(path)
else
# file was found and its not a symlink
return true
end
end
false
end
module_function :exist?
def get_attributes(file_name, raise_on_invalid = true)
result = GetFileAttributesW(wide_string(file_name.to_s))
if raise_on_invalid && result == INVALID_FILE_ATTRIBUTES
raise Puppet::Util::Windows::Error, "GetFileAttributes(#{file_name})"
end
result
end
module_function :get_attributes
def add_attributes(path, flags)
oldattrs = get_attributes(path)
if (oldattrs | flags) != oldattrs
set_attributes(path, oldattrs | flags)
end
end
module_function :add_attributes
def remove_attributes(path, flags)
oldattrs = get_attributes(path)
if (oldattrs & ~flags) != oldattrs
set_attributes(path, oldattrs & ~flags)
end
end
module_function :remove_attributes
def set_attributes(path, flags)
success = SetFileAttributesW(wide_string(path), flags) != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to set file attributes") unless success
success
end
module_function :set_attributes
# define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)
INVALID_HANDLE_VALUE = FFI::Pointer.new(-1).address
def self.create_file(file_name, desired_access, share_mode, security_attributes,
creation_disposition, flags_and_attributes, template_file_handle)
result = CreateFileW(wide_string(file_name.to_s),
desired_access, share_mode, security_attributes, creation_disposition,
flags_and_attributes, template_file_handle)
return result unless result == INVALID_HANDLE_VALUE
raise Puppet::Util::Windows::Error, "CreateFile(#{file_name}, #{desired_access.to_s(8)}, #{share_mode.to_s(8)}, " \
"#{security_attributes}, #{creation_disposition.to_s(8)}, " \
"#{flags_and_attributes.to_s(8)}, #{template_file_handle})"
end
def self.get_reparse_point_data(handle, &block)
# must be multiple of 1024, min 10240
FFI::MemoryPointer.new(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) do |reparse_data_buffer_ptr|
device_io_control(handle, FSCTL_GET_REPARSE_POINT, nil, reparse_data_buffer_ptr)
reparse_tag = reparse_data_buffer_ptr.read_win32_ulong
buffer_type = case reparse_tag
when IO_REPARSE_TAG_SYMLINK
SYMLINK_REPARSE_DATA_BUFFER
when IO_REPARSE_TAG_MOUNT_POINT
MOUNT_POINT_REPARSE_DATA_BUFFER
when IO_REPARSE_TAG_NFS
raise Puppet::Util::Windows::Error, "Retrieving NFS reparse point data is unsupported"
else
raise Puppet::Util::Windows::Error, "DeviceIoControl(#{handle}, " \
"FSCTL_GET_REPARSE_POINT) returned unknown tag 0x#{reparse_tag.to_s(16).upcase}"
end
yield buffer_type.new(reparse_data_buffer_ptr)
end
# underlying struct MemoryPointer has been cleaned up by this point, nothing to return
nil
end
def self.get_reparse_point_tag(handle)
reparse_tag = nil
# must be multiple of 1024, min 10240
FFI::MemoryPointer.new(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) do |reparse_data_buffer_ptr|
device_io_control(handle, FSCTL_GET_REPARSE_POINT, nil, reparse_data_buffer_ptr)
# DWORD ReparseTag is the first member of the struct
reparse_tag = reparse_data_buffer_ptr.read_win32_ulong
end
reparse_tag
end
def self.device_io_control(handle, io_control_code, in_buffer = nil, out_buffer = nil)
if out_buffer.nil?
raise Puppet::Util::Windows::Error, _("out_buffer is required")
end
FFI::MemoryPointer.new(:dword, 1) do |bytes_returned_ptr|
result = DeviceIoControl(
handle,
io_control_code,
in_buffer, in_buffer.nil? ? 0 : in_buffer.size,
out_buffer, out_buffer.size,
bytes_returned_ptr,
nil
)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "DeviceIoControl(#{handle}, #{io_control_code}, " \
"#{in_buffer}, #{in_buffer ? in_buffer.size : ''}, " \
"#{out_buffer}, #{out_buffer ? out_buffer.size : ''}"
end
end
out_buffer
end
def reparse_point?(file_name)
attributes = get_attributes(file_name, false)
return false if attributes == INVALID_FILE_ATTRIBUTES
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT
end
module_function :reparse_point?
def symlink?(file_name)
# Puppet currently only handles mount point and symlink reparse points, ignores others
reparse_point?(file_name) && symlink_reparse_point?(file_name)
end
module_function :symlink?
def self.open_symlink(link_name)
begin
yield handle = create_file(
link_name,
GENERIC_READ,
FILE_SHARE_READ,
nil, # security_attributes
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
0
) # template_file
ensure
FFI::WIN32.CloseHandle(handle) if handle
end
# handle has had CloseHandle called against it, so nothing to return
nil
end
def readlink(link_name)
link = nil
open_symlink(link_name) do |handle|
link = resolve_symlink(handle)
end
link
end
module_function :readlink
def get_long_pathname(path)
converted = ''.dup
FFI::Pointer.from_string_to_wide_string(path) do |path_ptr|
# includes terminating NULL
buffer_size = GetLongPathNameW(path_ptr, FFI::Pointer::NULL, 0)
FFI::MemoryPointer.new(:wchar, buffer_size) do |converted_ptr|
if GetLongPathNameW(path_ptr, converted_ptr, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to call GetLongPathName")
end
converted = converted_ptr.read_wide_string(buffer_size - 1)
end
end
converted
end
module_function :get_long_pathname
def get_short_pathname(path)
converted = ''.dup
FFI::Pointer.from_string_to_wide_string(path) do |path_ptr|
# includes terminating NULL
buffer_size = GetShortPathNameW(path_ptr, FFI::Pointer::NULL, 0)
FFI::MemoryPointer.new(:wchar, buffer_size) do |converted_ptr|
if GetShortPathNameW(path_ptr, converted_ptr, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "Failed to call GetShortPathName"
end
converted = converted_ptr.read_wide_string(buffer_size - 1)
end
end
converted
end
module_function :get_short_pathname
def stat(file_name)
file_name = file_name.to_s # accommodate PathName or String
stat = File.stat(file_name)
singleton_class = class << stat; self; end
target_path = file_name
if symlink?(file_name)
target_path = readlink(file_name)
link_ftype = File.stat(target_path).ftype
# sigh, monkey patch instance method for instance, and close over link_ftype
singleton_class.send(:define_method, :ftype) do
link_ftype
end
end
singleton_class.send(:define_method, :mode) do
Puppet::Util::Windows::Security.get_mode(target_path)
end
stat
end
module_function :stat
def lstat(file_name)
file_name = file_name.to_s # accommodate PathName or String
# monkey'ing around!
stat = File.lstat(file_name)
singleton_class = class << stat; self; end
singleton_class.send(:define_method, :mode) do
Puppet::Util::Windows::Security.get_mode(file_name)
end
if symlink?(file_name)
def stat.ftype
"link"
end
end
stat
end
module_function :lstat
def self.resolve_symlink(handle)
path = nil
get_reparse_point_data(handle) do |reparse_data|
offset = reparse_data[:PrintNameOffset]
length = reparse_data[:PrintNameLength]
ptr = reparse_data.pointer + reparse_data.offset_of(:PathBuffer) + offset
path = ptr.read_wide_string(length / 2) # length is bytes, need UTF-16 wchars
end
path
end
private_class_method :resolve_symlink
# these reparse point types are the only ones Puppet currently understands
# so rather than raising an exception in readlink, prefer to not consider
# the path a symlink when stat'ing later
def self.symlink_reparse_point?(path)
symlink = false
open_symlink(path) do |handle|
symlink = [
IO_REPARSE_TAG_SYMLINK,
IO_REPARSE_TAG_MOUNT_POINT
].include?(get_reparse_point_tag(handle))
end
symlink
end
private_class_method :symlink_reparse_point?
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/registry.rb | lib/puppet/util/windows/registry.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
module Puppet::Util::Windows
module Registry
require 'ffi'
extend FFI::Library
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx
KEY64 = 0x100
KEY32 = 0x200
KEY_READ = 0x20019
KEY_WRITE = 0x20006
KEY_ALL_ACCESS = 0x2003f
ERROR_NO_MORE_ITEMS = 259
WCHAR_SIZE = FFI.type_size(:wchar)
def root(name)
Win32::Registry.const_get(name)
rescue NameError => e
raise Puppet::Error, _("Invalid registry key '%{name}'") % { name: name }, e.backtrace
end
def open(name, path, mode = KEY_READ | KEY64, &block)
hkey = root(name)
begin
hkey.open(path, mode) do |subkey|
return yield subkey
end
rescue Win32::Registry::Error => error
raise Puppet::Util::Windows::Error.new(_("Failed to open registry key '%{key}\\%{path}'") % { key: hkey.keyname, path: path }, error.code, error)
end
end
def keys(key)
keys = {}
each_key(key) { |subkey, filetime| keys[subkey] = filetime }
keys
end
# subkey is String which contains name of subkey.
# wtime is last write time as FILETIME (64-bit integer). (see Registry.wtime2time)
def each_key(key, &block)
index = 0
subkey = nil
subkey_max_len, _ = reg_query_info_key_max_lengths(key)
loop do
subkey, filetime = reg_enum_key(key, index, subkey_max_len)
yield subkey, filetime unless subkey.nil?
index += 1
break if subkey.nil?
end
index
end
def delete_key(key, subkey_name, mode = KEY64)
reg_delete_key_ex(key, subkey_name, mode)
end
def values(key)
vals = {}
each_value(key) { |subkey, _type, data| vals[subkey] = data }
vals
end
# Retrieve a set of values from a registry key given their names
# Value names listed but not found in the registry will not be added to the
# resultant Hashtable
#
# @param key [RegistryKey] An open handle to a Registry Key
# @param names [String[]] An array of names of registry values to return if they exist
# @return [Hashtable<String, Object>] A hashtable of all of the found values in the registry key
def values_by_name(key, names)
vals = {}
names.each do |name|
FFI::Pointer.from_string_to_wide_string(name) do |subkeyname_ptr|
_, vals[name] = read(key, subkeyname_ptr)
rescue Puppet::Util::Windows::Error => e
# ignore missing names, but raise other errors
raise e unless e.code == Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND
end
end
vals
end
def each_value(key, &block)
index = 0
subkey = nil
_, value_max_len = reg_query_info_key_max_lengths(key)
loop do
subkey, type, data = reg_enum_value(key, index, value_max_len)
yield subkey, type, data unless subkey.nil?
index += 1
break if subkey.nil?
end
index
end
def delete_value(key, subkey_name)
reg_delete_value(key, subkey_name)
end
private
# max number of wide characters including NULL terminator
MAX_KEY_CHAR_LENGTH = 255 + 1
def reg_enum_key(key, index, max_key_char_length = MAX_KEY_CHAR_LENGTH)
subkey = nil
filetime = nil
FFI::MemoryPointer.new(:dword) do |subkey_length_ptr|
FFI::MemoryPointer.new(FFI::WIN32::FILETIME.size) do |filetime_ptr|
FFI::MemoryPointer.new(:wchar, max_key_char_length) do |subkey_ptr|
subkey_length_ptr.write_dword(max_key_char_length)
# RegEnumKeyEx cannot be called twice to properly size the buffer
result = RegEnumKeyExW(key.hkey, index,
subkey_ptr, subkey_length_ptr,
FFI::Pointer::NULL, FFI::Pointer::NULL,
FFI::Pointer::NULL, filetime_ptr)
break if result == ERROR_NO_MORE_ITEMS
if result != FFI::ERROR_SUCCESS
msg = _("Failed to enumerate %{key} registry keys at index %{index}") % { key: key.keyname, index: index }
raise Puppet::Util::Windows::Error.new(msg, result)
end
filetime = FFI::WIN32::FILETIME.new(filetime_ptr)
subkey_length = subkey_length_ptr.read_dword
subkey = subkey_ptr.read_wide_string(subkey_length)
end
end
end
[subkey, filetime]
end
# max number of wide characters including NULL terminator
MAX_VALUE_CHAR_LENGTH = 16_383 + 1
def reg_enum_value(key, index, max_value_length = MAX_VALUE_CHAR_LENGTH)
subkey = nil
type = nil
data = nil
FFI::MemoryPointer.new(:dword) do |subkey_length_ptr|
FFI::MemoryPointer.new(:wchar, max_value_length) do |subkey_ptr|
# RegEnumValueW cannot be called twice to properly size the buffer
subkey_length_ptr.write_dword(max_value_length)
result = RegEnumValueW(key.hkey, index,
subkey_ptr, subkey_length_ptr,
FFI::Pointer::NULL, FFI::Pointer::NULL,
FFI::Pointer::NULL, FFI::Pointer::NULL)
break if result == ERROR_NO_MORE_ITEMS
if result != FFI::ERROR_SUCCESS
msg = _("Failed to enumerate %{key} registry values at index %{index}") % { key: key.keyname, index: index }
raise Puppet::Util::Windows::Error.new(msg, result)
end
subkey_length = subkey_length_ptr.read_dword
subkey = subkey_ptr.read_wide_string(subkey_length)
type, data = read(key, subkey_ptr)
end
end
[subkey, type, data]
end
def reg_query_info_key_max_lengths(key)
result = nil
FFI::MemoryPointer.new(:dword) do |max_subkey_name_length_ptr|
FFI::MemoryPointer.new(:dword) do |max_value_name_length_ptr|
status = RegQueryInfoKeyW(key.hkey,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL,
max_subkey_name_length_ptr, FFI::MemoryPointer::NULL,
FFI::MemoryPointer::NULL, max_value_name_length_ptr,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL,
FFI::MemoryPointer::NULL)
if status != FFI::ERROR_SUCCESS
msg = _("Failed to query registry %{key} for sizes") % { key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, status)
end
result = [
# Unicode characters *not* including trailing NULL
max_subkey_name_length_ptr.read_dword + 1,
max_value_name_length_ptr.read_dword + 1
]
end
end
result
end
# Read a registry value named name and return array of
# [ type, data ].
# When name is nil, the `default' value is read.
# type is value type. (see Win32::Registry::Constants module)
# data is value data, its class is:
# :REG_SZ, REG_EXPAND_SZ
# String
# :REG_MULTI_SZ
# Array of String
# :REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD
# Integer
# :REG_BINARY
# String (contains binary data)
#
# When rtype is specified, the value type must be included by
# rtype array, or TypeError is raised.
def read(key, name_ptr, *rtype)
result = nil
query_value_ex(key, name_ptr) do |type, data_ptr, byte_length|
unless rtype.empty? or rtype.include?(type)
raise TypeError, _("Type mismatch (expect %{rtype} but %{type} present)") % { rtype: rtype.inspect, type: type }
end
string_length = 0
# buffer is raw bytes, *not* chars - less a NULL terminator
string_length = (byte_length / WCHAR_SIZE) - 1 if byte_length > 0
begin
result = case type
when Win32::Registry::REG_SZ, Win32::Registry::REG_EXPAND_SZ
[type, data_ptr.read_wide_string(string_length, Encoding::UTF_8, true)]
when Win32::Registry::REG_MULTI_SZ
[type, data_ptr.read_wide_string(string_length).split(/\0/)]
when Win32::Registry::REG_BINARY
[type, data_ptr.read_bytes(byte_length)]
when Win32::Registry::REG_DWORD
[type, data_ptr.read_dword]
when Win32::Registry::REG_DWORD_BIG_ENDIAN
[type, data_ptr.order(:big).read_dword]
when Win32::Registry::REG_QWORD
[type, data_ptr.read_qword]
else
raise TypeError, _("Type %{type} is not supported.") % { type: type }
end
rescue IndexError => ex
raise if ex.message !~ /^Memory access .* is out of bounds$/i
parent_key_name = key.parent ? "#{key.parent.keyname}\\" : ""
Puppet.warning _("A value in the registry key %{parent_key_name}%{key} is corrupt or invalid") % { parent_key_name: parent_key_name, key: key.keyname }
end
end
result
end
def query_value_ex(key, name_ptr, &block)
FFI::MemoryPointer.new(:dword) do |type_ptr|
FFI::MemoryPointer.new(:dword) do |length_ptr|
result = RegQueryValueExW(key.hkey, name_ptr,
FFI::Pointer::NULL, type_ptr,
FFI::Pointer::NULL, length_ptr)
# The call to RegQueryValueExW below is potentially unsafe:
# https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvalueexw
#
# "If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type,
# the string may not have been stored with the proper terminating
# null characters. Therefore, even if the function returns
# ERROR_SUCCESS, the application should ensure that the string is
# properly terminated before using it; otherwise, it may overwrite a
# buffer. (Note that REG_MULTI_SZ strings should have two
# terminating null characters.)"
#
# Since we don't know if the values will be properly null terminated,
# extend the buffer to guarantee we can append one or two wide null
# characters, without overwriting any data.
base_bytes_len = length_ptr.read_dword
pad_bytes_len = case type_ptr.read_dword
when Win32::Registry::REG_SZ, Win32::Registry::REG_EXPAND_SZ
WCHAR_SIZE
when Win32::Registry::REG_MULTI_SZ
WCHAR_SIZE * 2
else
0
end
FFI::MemoryPointer.new(:byte, base_bytes_len + pad_bytes_len) do |buffer_ptr|
result = RegQueryValueExW(key.hkey, name_ptr,
FFI::Pointer::NULL, type_ptr,
buffer_ptr, length_ptr)
# Ensure buffer is null terminated with 1 or 2 wchar nulls, depending on the type
if result == FFI::ERROR_SUCCESS
case type_ptr.read_dword
when Win32::Registry::REG_SZ, Win32::Registry::REG_EXPAND_SZ
buffer_ptr.put_uint16(base_bytes_len, 0)
when Win32::Registry::REG_MULTI_SZ
buffer_ptr.put_uint16(base_bytes_len, 0)
buffer_ptr.put_uint16(base_bytes_len + WCHAR_SIZE, 0)
end
else
# buffer is raw bytes, *not* chars - less a NULL terminator
name_length = (name_ptr.size / WCHAR_SIZE) - 1 if name_ptr.size > 0
msg = _("Failed to read registry value %{value} at %{key}") % { value: name_ptr.read_wide_string(name_length), key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, result)
end
# allows caller to use FFI MemoryPointer helpers to read / shape
yield [type_ptr.read_dword, buffer_ptr, length_ptr.read_dword]
end
end
end
end
def reg_delete_value(key, name)
result = 0
FFI::Pointer.from_string_to_wide_string(name) do |name_ptr|
result = RegDeleteValueW(key.hkey, name_ptr)
if result != FFI::ERROR_SUCCESS
msg = _("Failed to delete registry value %{name} at %{key}") % { name: name, key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, result)
end
end
result
end
def reg_delete_key_ex(key, name, regsam = KEY64)
result = 0
FFI::Pointer.from_string_to_wide_string(name) do |name_ptr|
result = RegDeleteKeyExW(key.hkey, name_ptr, regsam, 0)
if result != FFI::ERROR_SUCCESS
msg = _("Failed to delete registry key %{name} at %{key}") % { name: name, key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, result)
end
end
result
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724862(v=vs.85).aspx
# LONG WINAPI RegEnumKeyEx(
# _In_ HKEY hKey,
# _In_ DWORD dwIndex,
# _Out_ LPTSTR lpName,
# _Inout_ LPDWORD lpcName,
# _Reserved_ LPDWORD lpReserved,
# _Inout_ LPTSTR lpClass,
# _Inout_opt_ LPDWORD lpcClass,
# _Out_opt_ PFILETIME lpftLastWriteTime
# );
ffi_lib :advapi32
attach_function_private :RegEnumKeyExW,
[:handle, :dword, :lpwstr, :lpdword, :lpdword, :lpwstr, :lpdword, :pointer], :win32_long
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724865(v=vs.85).aspx
# LONG WINAPI RegEnumValue(
# _In_ HKEY hKey,
# _In_ DWORD dwIndex,
# _Out_ LPTSTR lpValueName,
# _Inout_ LPDWORD lpcchValueName,
# _Reserved_ LPDWORD lpReserved,
# _Out_opt_ LPDWORD lpType,
# _Out_opt_ LPBYTE lpData,
# _Inout_opt_ LPDWORD lpcbData
# );
ffi_lib :advapi32
attach_function_private :RegEnumValueW,
[:handle, :dword, :lpwstr, :lpdword, :lpdword, :lpdword, :lpbyte, :lpdword], :win32_long
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911(v=vs.85).aspx
# LONG WINAPI RegQueryValueExW(
# _In_ HKEY hKey,
# _In_opt_ LPCTSTR lpValueName,
# _Reserved_ LPDWORD lpReserved,
# _Out_opt_ LPDWORD lpType,
# _Out_opt_ LPBYTE lpData,
# _Inout_opt_ LPDWORD lpcbData
# );
ffi_lib :advapi32
attach_function_private :RegQueryValueExW,
[:handle, :lpcwstr, :lpdword, :lpdword, :lpbyte, :lpdword], :win32_long
# LONG WINAPI RegDeleteValue(
# _In_ HKEY hKey,
# _In_opt_ LPCTSTR lpValueName
# );
ffi_lib :advapi32
attach_function_private :RegDeleteValueW,
[:handle, :lpcwstr], :win32_long
# LONG WINAPI RegDeleteKeyEx(
# _In_ HKEY hKey,
# _In_ LPCTSTR lpSubKey,
# _In_ REGSAM samDesired,
# _Reserved_ DWORD Reserved
# );
ffi_lib :advapi32
attach_function_private :RegDeleteKeyExW,
[:handle, :lpcwstr, :win32_ulong, :dword], :win32_long
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724902(v=vs.85).aspx
# LONG WINAPI RegQueryInfoKey(
# _In_ HKEY hKey,
# _Out_opt_ LPTSTR lpClass,
# _Inout_opt_ LPDWORD lpcClass,
# _Reserved_ LPDWORD lpReserved,
# _Out_opt_ LPDWORD lpcSubKeys,
# _Out_opt_ LPDWORD lpcMaxSubKeyLen,
# _Out_opt_ LPDWORD lpcMaxClassLen,
# _Out_opt_ LPDWORD lpcValues,
# _Out_opt_ LPDWORD lpcMaxValueNameLen,
# _Out_opt_ LPDWORD lpcMaxValueLen,
# _Out_opt_ LPDWORD lpcbSecurityDescriptor,
# _Out_opt_ PFILETIME lpftLastWriteTime
# );
ffi_lib :advapi32
attach_function_private :RegQueryInfoKeyW,
[:handle, :lpwstr, :lpdword, :lpdword, :lpdword,
:lpdword, :lpdword, :lpdword, :lpdword, :lpdword,
:lpdword, :pointer], :win32_long
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/util/windows/root_certs.rb | lib/puppet/util/windows/root_certs.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
require_relative '../../../puppet/ssl/openssl_loader'
require 'ffi'
# Represents a collection of trusted root certificates.
#
# @api public
class Puppet::Util::Windows::RootCerts
include Enumerable
extend FFI::Library
def initialize(roots)
@roots = roots
end
# Enumerates each root certificate.
# @yieldparam cert [OpenSSL::X509::Certificate] each root certificate
# @api public
def each
@roots.each { |cert| yield cert }
end
# Returns a new instance.
# @return [Puppet::Util::Windows::RootCerts] object constructed from current root certificates
def self.instance
new(load_certs)
end
# Returns an array of root certificates.
#
# @return [Array<[OpenSSL::X509::Certificate]>] an array of root certificates
# @api private
def self.load_certs
certs = []
# This is based on a patch submitted to openssl:
# https://www.mail-archive.com/openssl-dev@openssl.org/msg26958.html
ptr = FFI::Pointer::NULL
store = CertOpenSystemStoreA(nil, "ROOT")
begin
while (ptr = CertEnumCertificatesInStore(store, ptr)) and !ptr.null?
context = CERT_CONTEXT.new(ptr)
cert_buf = context[:pbCertEncoded].read_bytes(context[:cbCertEncoded])
begin
certs << OpenSSL::X509::Certificate.new(cert_buf)
rescue => detail
Puppet.warning(_("Failed to import root certificate: %{detail}") % { detail: detail.inspect })
end
end
ensure
CertCloseStore(store, 0)
end
certs
end
ffi_convention :stdcall
# typedef void *HCERTSTORE;
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa377189(v=vs.85).aspx
# typedef struct _CERT_CONTEXT {
# DWORD dwCertEncodingType;
# BYTE *pbCertEncoded;
# DWORD cbCertEncoded;
# PCERT_INFO pCertInfo;
# HCERTSTORE hCertStore;
# } CERT_CONTEXT, *PCERT_CONTEXT;typedef const CERT_CONTEXT *PCCERT_CONTEXT;
class CERT_CONTEXT < FFI::Struct
layout(
:dwCertEncodingType, :dword,
:pbCertEncoded, :pointer,
:cbCertEncoded, :dword,
:pCertInfo, :pointer,
:hCertStore, :handle
)
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376560(v=vs.85).aspx
# HCERTSTORE
# WINAPI
# CertOpenSystemStoreA(
# __in_opt HCRYPTPROV_LEGACY hProv,
# __in LPCSTR szSubsystemProtocol
# );
# typedef ULONG_PTR HCRYPTPROV_LEGACY;
ffi_lib :crypt32
attach_function_private :CertOpenSystemStoreA, [:ulong_ptr, :lpcstr], :handle
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376050(v=vs.85).aspx
# PCCERT_CONTEXT
# WINAPI
# CertEnumCertificatesInStore(
# __in HCERTSTORE hCertStore,
# __in_opt PCCERT_CONTEXT pPrevCertContext
# );
ffi_lib :crypt32
attach_function_private :CertEnumCertificatesInStore, [:handle, :pointer], :pointer
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376026(v=vs.85).aspx
# BOOL
# WINAPI
# CertCloseStore(
# __in_opt HCERTSTORE hCertStore,
# __in DWORD dwFlags
# );
ffi_lib :crypt32
attach_function_private :CertCloseStore, [:handle, :dword], :win32_bool
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/principal.rb | lib/puppet/util/windows/principal.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
module Puppet::Util::Windows::SID
class Principal
extend FFI::Library
attr_reader :account, :sid_bytes, :sid, :domain, :domain_account, :account_type
def initialize(account, sid_bytes, sid, domain, account_type)
# This is only ever called from lookup_account_sid which has already
# removed the potential for passing in an account like host\user
@account = account
@sid_bytes = sid_bytes
@sid = sid
@domain = domain
@account_type = account_type
# When domain is available and it is a Domain principal, use domain only
# otherwise if domain is available then combine it with parsed account
# otherwise when the domain is not available, use the account value directly
# WinNT naming standard https://msdn.microsoft.com/en-us/library/windows/desktop/aa746534(v=vs.85).aspx
if domain && !domain.empty? && @account_type == :SidTypeDomain
@domain_account = @domain
elsif domain && !domain.empty?
@domain_account = "#{domain}\\#{@account}"
else
@domain_account = account
end
end
# added for backward compatibility
def ==(compare)
compare.is_a?(Puppet::Util::Windows::SID::Principal) &&
@sid_bytes == compare.sid_bytes
end
# returns authority qualified account name
# prefer to compare Principal instances with == operator or by #sid
def to_s
@domain_account
end
# = 8 + max sub identifiers (15) * 4
MAXIMUM_SID_BYTE_LENGTH = 68
ERROR_INVALID_PARAMETER = 87
ERROR_INSUFFICIENT_BUFFER = 122
def self.lookup_account_name(system_name = nil, sanitize = true, account_name)
account_name = sanitize_account_name(account_name) if sanitize
system_name_ptr = FFI::Pointer::NULL
begin
if system_name
system_name_wide = Puppet::Util::Windows::String.wide_string(system_name)
system_name_ptr = FFI::MemoryPointer.from_wide_string(system_name_wide)
end
FFI::MemoryPointer.from_string_to_wide_string(account_name) do |account_name_ptr|
FFI::MemoryPointer.new(:byte, MAXIMUM_SID_BYTE_LENGTH) do |sid_ptr|
FFI::MemoryPointer.new(:dword, 1) do |sid_length_ptr|
FFI::MemoryPointer.new(:dword, 1) do |domain_length_ptr|
FFI::MemoryPointer.new(:uint32, 1) do |name_use_enum_ptr|
sid_length_ptr.write_dword(MAXIMUM_SID_BYTE_LENGTH)
success = LookupAccountNameW(system_name_ptr, account_name_ptr, sid_ptr, sid_length_ptr,
FFI::Pointer::NULL, domain_length_ptr, name_use_enum_ptr)
last_error = FFI.errno
if success == FFI::WIN32_FALSE && last_error != ERROR_INSUFFICIENT_BUFFER
raise Puppet::Util::Windows::Error.new(_('Failed to call LookupAccountNameW with account: %{account_name}') % { account_name: account_name }, last_error)
end
FFI::MemoryPointer.new(:lpwstr, domain_length_ptr.read_dword) do |domain_ptr|
if LookupAccountNameW(system_name_ptr, account_name_ptr,
sid_ptr, sid_length_ptr,
domain_ptr, domain_length_ptr, name_use_enum_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _('Failed to call LookupAccountNameW with account: %{account_name}') % { account_name: account_name }
end
# with a SID returned, loop back through lookup_account_sid to retrieve official name
# necessary when accounts like . or '' are passed in
return lookup_account_sid(
system_name,
sid_ptr.read_bytes(sid_length_ptr.read_dword).unpack('C*')
)
end
end
end
end
end
end
ensure
system_name_ptr.free if system_name_ptr != FFI::Pointer::NULL
end
end
def self.lookup_account_sid(system_name = nil, sid_bytes)
system_name_ptr = FFI::Pointer::NULL
if sid_bytes.nil? || (!sid_bytes.is_a? Array) || (sid_bytes.length == 0)
# TRANSLATORS `lookup_account_sid` is a variable name and should not be translated
raise Puppet::Util::Windows::Error, _('Byte array for lookup_account_sid must not be nil and must be at least 1 byte long')
end
begin
if system_name
system_name_wide = Puppet::Util::Windows::String.wide_string(system_name)
system_name_ptr = FFI::MemoryPointer.from_wide_string(system_name_wide)
end
FFI::MemoryPointer.new(:byte, sid_bytes.length) do |sid_ptr|
FFI::MemoryPointer.new(:dword, 1) do |name_length_ptr|
FFI::MemoryPointer.new(:dword, 1) do |domain_length_ptr|
FFI::MemoryPointer.new(:uint32, 1) do |name_use_enum_ptr|
sid_ptr.write_array_of_uchar(sid_bytes)
if Puppet::Util::Windows::SID.IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error.new(_('Byte array for lookup_account_sid is invalid: %{sid_bytes}') % { sid_bytes: sid_bytes }, ERROR_INVALID_PARAMETER)
end
success = LookupAccountSidW(system_name_ptr, sid_ptr, FFI::Pointer::NULL, name_length_ptr,
FFI::Pointer::NULL, domain_length_ptr, name_use_enum_ptr)
last_error = FFI.errno
if success == FFI::WIN32_FALSE && last_error != ERROR_INSUFFICIENT_BUFFER
raise Puppet::Util::Windows::Error.new(_('Failed to call LookupAccountSidW with bytes: %{sid_bytes}') % { sid_bytes: sid_bytes }, last_error)
end
FFI::MemoryPointer.new(:lpwstr, name_length_ptr.read_dword) do |name_ptr|
FFI::MemoryPointer.new(:lpwstr, domain_length_ptr.read_dword) do |domain_ptr|
if LookupAccountSidW(system_name_ptr, sid_ptr, name_ptr, name_length_ptr,
domain_ptr, domain_length_ptr, name_use_enum_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _('Failed to call LookupAccountSidW with bytes: %{sid_bytes}') % { sid_bytes: sid_bytes }
end
return new(
name_ptr.read_wide_string(name_length_ptr.read_dword),
sid_bytes,
Puppet::Util::Windows::SID.sid_ptr_to_string(sid_ptr),
domain_ptr.read_wide_string(domain_length_ptr.read_dword),
SID_NAME_USE[name_use_enum_ptr.read_uint32]
)
end
end
end
end
end
end
ensure
system_name_ptr.free if system_name_ptr != FFI::Pointer::NULL
end
end
# Sanitize the given account name for lookup to avoid known issues
def self.sanitize_account_name(account_name)
return account_name unless account_name.start_with?('APPLICATION PACKAGE AUTHORITY\\')
account_name.split('\\').last
end
private_class_method :sanitize_account_name
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379601(v=vs.85).aspx
SID_NAME_USE = enum(
:SidTypeUser, 1,
:SidTypeGroup, 2,
:SidTypeDomain, 3,
:SidTypeAlias, 4,
:SidTypeWellKnownGroup, 5,
:SidTypeDeletedAccount, 6,
:SidTypeInvalid, 7,
:SidTypeUnknown, 8,
:SidTypeComputer, 9,
:SidTypeLabel, 10
)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379159(v=vs.85).aspx
# BOOL WINAPI LookupAccountName(
# _In_opt_ LPCTSTR lpSystemName,
# _In_ LPCTSTR lpAccountName,
# _Out_opt_ PSID Sid,
# _Inout_ LPDWORD cbSid,
# _Out_opt_ LPTSTR ReferencedDomainName,
# _Inout_ LPDWORD cchReferencedDomainName,
# _Out_ PSID_NAME_USE peUse
# );
ffi_lib :advapi32
attach_function_private :LookupAccountNameW,
[:lpcwstr, :lpcwstr, :pointer, :lpdword, :lpwstr, :lpdword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379166(v=vs.85).aspx
# BOOL WINAPI LookupAccountSid(
# _In_opt_ LPCTSTR lpSystemName,
# _In_ PSID lpSid,
# _Out_opt_ LPTSTR lpName,
# _Inout_ LPDWORD cchName,
# _Out_opt_ LPTSTR lpReferencedDomainName,
# _Inout_ LPDWORD cchReferencedDomainName,
# _Out_ PSID_NAME_USE peUse
# );
ffi_lib :advapi32
attach_function_private :LookupAccountSidW,
[:lpcwstr, :pointer, :lpwstr, :lpdword, :lpwstr, :lpdword, :pointer], :win32_bool
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/util/windows/string.rb | lib/puppet/util/windows/string.rb | # frozen_string_literal: true
module Puppet
module Util
module Windows
module String
def wide_string(str)
# if given a nil string, assume caller wants to pass a nil pointer to win32
return nil if str.nil?
str.encode('UTF-16LE')
end
module_function :wide_string
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/util/windows/process.rb | lib/puppet/util/windows/process.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows/monkey_patches/process'
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows::Process
extend Puppet::FFI::Windows::Functions
include Puppet::FFI::Windows::Structs
extend Puppet::Util::Windows::String
WAIT_TIMEOUT = 0x102
WAIT_INTERVAL = 200
# https://docs.microsoft.com/en-us/windows/desktop/ProcThread/process-creation-flags
CREATE_NO_WINDOW = 0x08000000
# https://docs.microsoft.com/en-us/windows/desktop/ProcThread/process-security-and-access-rights
PROCESS_QUERY_INFORMATION = 0x0400
# https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
MAX_PATH_LENGTH = 32_767
def execute(command, arguments, stdin, stdout, stderr)
create_args = {
:command_line => command,
:startup_info => {
:stdin => stdin,
:stdout => stdout,
:stderr => stderr
},
:close_handles => false,
}
if arguments[:suppress_window]
create_args[:creation_flags] = CREATE_NO_WINDOW
end
if arguments[:cwd]
create_args[:cwd] = arguments[:cwd]
end
Process.create(create_args)
end
module_function :execute
def wait_process(handle)
while WaitForSingleObject(handle, WAIT_INTERVAL) == WAIT_TIMEOUT
sleep(0)
end
exit_status = -1
FFI::MemoryPointer.new(:dword, 1) do |exit_status_ptr|
if GetExitCodeProcess(handle, exit_status_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get child process exit code")
end
exit_status = exit_status_ptr.read_dword
# $CHILD_STATUS is not set when calling win32/process Process.create
# and since it's read-only, we can't set it. But we can execute a
# a shell that simply returns the desired exit status, which has the
# desired effect.
%x(#{ENV.fetch('COMSPEC', nil)} /c exit #{exit_status})
end
exit_status
end
module_function :wait_process
def get_current_process
# this pseudo-handle does not require closing per MSDN docs
GetCurrentProcess()
end
module_function :get_current_process
def open_process(desired_access, inherit_handle, process_id, &block)
phandle = nil
inherit = inherit_handle ? FFI::WIN32_TRUE : FFI::WIN32_FALSE
begin
phandle = OpenProcess(desired_access, inherit, process_id)
if phandle == FFI::Pointer::NULL_HANDLE
raise Puppet::Util::Windows::Error, "OpenProcess(#{desired_access.to_s(8)}, #{inherit}, #{process_id})"
end
yield phandle
ensure
FFI::WIN32.CloseHandle(phandle) if phandle
end
# phandle has had CloseHandle called against it, so nothing to return
nil
end
module_function :open_process
def open_process_token(handle, desired_access, &block)
token_handle = nil
begin
FFI::MemoryPointer.new(:handle, 1) do |token_handle_ptr|
result = OpenProcessToken(handle, desired_access, token_handle_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "OpenProcessToken(#{handle}, #{desired_access.to_s(8)}, #{token_handle_ptr})"
end
yield token_handle = token_handle_ptr.read_handle
end
token_handle
ensure
FFI::WIN32.CloseHandle(token_handle) if token_handle
end
# token_handle has had CloseHandle called against it, so nothing to return
nil
end
module_function :open_process_token
# Execute a block with the current process token
def with_process_token(access, &block)
handle = get_current_process
open_process_token(handle, access) do |token_handle|
yield token_handle
end
# all handles have been closed, so nothing to safely return
nil
end
module_function :with_process_token
def get_process_image_name_by_pid(pid)
image_name = ''.dup
Puppet::Util::Windows::Security.with_privilege(Puppet::Util::Windows::Security::SE_DEBUG_NAME) do
open_process(PROCESS_QUERY_INFORMATION, false, pid) do |phandle|
FFI::MemoryPointer.new(:dword, 1) do |exe_name_length_ptr|
# UTF is 2 bytes/char:
max_chars = MAX_PATH_LENGTH + 1
exe_name_length_ptr.write_dword(max_chars)
FFI::MemoryPointer.new(:wchar, max_chars) do |exe_name_ptr|
use_win32_path_format = 0
result = QueryFullProcessImageNameW(phandle, use_win32_path_format, exe_name_ptr, exe_name_length_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "QueryFullProcessImageNameW(phandle, #{use_win32_path_format}, " \
"exe_name_ptr, #{max_chars}"
end
image_name = exe_name_ptr.read_wide_string(exe_name_length_ptr.read_dword)
end
end
end
end
image_name
end
module_function :get_process_image_name_by_pid
def lookup_privilege_value(name, system_name = '', &block)
FFI::MemoryPointer.new(LUID.size) do |luid_ptr|
result = LookupPrivilegeValueW(
wide_string(system_name),
wide_string(name.to_s),
luid_ptr
)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "LookupPrivilegeValue(#{system_name}, #{name}, #{luid_ptr})"
end
yield LUID.new(luid_ptr)
end
# the underlying MemoryPointer for LUID is cleaned up by this point
nil
end
module_function :lookup_privilege_value
def get_token_information(token_handle, token_information, &block)
# to determine buffer size
FFI::MemoryPointer.new(:dword, 1) do |return_length_ptr|
result = GetTokenInformation(token_handle, token_information, nil, 0, return_length_ptr)
return_length = return_length_ptr.read_dword
if return_length <= 0
raise Puppet::Util::Windows::Error, "GetTokenInformation(#{token_handle}, #{token_information}, nil, 0, #{return_length_ptr})"
end
# re-call API with properly sized buffer for all results
FFI::MemoryPointer.new(return_length) do |token_information_buf|
result = GetTokenInformation(token_handle, token_information,
token_information_buf, return_length, return_length_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "GetTokenInformation(#{token_handle}, #{token_information}, #{token_information_buf}, " \
"#{return_length}, #{return_length_ptr})"
end
yield token_information_buf
end
end
# GetTokenInformation buffer has been cleaned up by this point, nothing to return
nil
end
module_function :get_token_information
def parse_token_information_as_token_privileges(token_information_buf)
raw_privileges = TOKEN_PRIVILEGES.new(token_information_buf)
privileges = { :count => raw_privileges[:PrivilegeCount], :privileges => [] }
offset = token_information_buf + TOKEN_PRIVILEGES.offset_of(:Privileges)
privilege_ptr = FFI::Pointer.new(LUID_AND_ATTRIBUTES, offset)
# extract each instance of LUID_AND_ATTRIBUTES
0.upto(privileges[:count] - 1) do |i|
privileges[:privileges] << LUID_AND_ATTRIBUTES.new(privilege_ptr[i])
end
privileges
end
module_function :parse_token_information_as_token_privileges
def parse_token_information_as_token_elevation(token_information_buf)
TOKEN_ELEVATION.new(token_information_buf)
end
module_function :parse_token_information_as_token_elevation
TOKEN_ALL_ACCESS = 0xF01FF
ERROR_NO_SUCH_PRIVILEGE = 1313
def process_privilege_symlink?
privilege_symlink = false
handle = get_current_process
open_process_token(handle, TOKEN_ALL_ACCESS) do |token_handle|
lookup_privilege_value('SeCreateSymbolicLinkPrivilege') do |luid|
get_token_information(token_handle, :TokenPrivileges) do |token_info|
token_privileges = parse_token_information_as_token_privileges(token_info)
privilege_symlink = token_privileges[:privileges].any? { |p| p[:Luid].values == luid.values }
end
end
end
privilege_symlink
rescue Puppet::Util::Windows::Error => e
if e.code == ERROR_NO_SUCH_PRIVILEGE
false # pre-Vista
else
raise e
end
end
module_function :process_privilege_symlink?
TOKEN_QUERY = 0x0008
# Returns whether or not the owner of the current process is running
# with elevated security privileges.
#
# Only supported on Windows Vista or later.
#
def elevated_security?
# default / pre-Vista
elevated = false
handle = nil
begin
handle = get_current_process
open_process_token(handle, TOKEN_QUERY) do |token_handle|
get_token_information(token_handle, :TokenElevation) do |token_info|
token_elevation = parse_token_information_as_token_elevation(token_info)
# TokenIsElevated member of the TOKEN_ELEVATION struct
elevated = token_elevation[:TokenIsElevated] != 0
end
end
elevated
rescue Puppet::Util::Windows::Error => e
raise e if e.code != ERROR_NO_SUCH_PRIVILEGE
ensure
FFI::WIN32.CloseHandle(handle) if handle
end
end
module_function :elevated_security?
def windows_major_version
ver = 0
FFI::MemoryPointer.new(OSVERSIONINFO.size) do |os_version_ptr|
os_version = OSVERSIONINFO.new(os_version_ptr)
os_version[:dwOSVersionInfoSize] = OSVERSIONINFO.size
result = GetVersionExW(os_version_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("GetVersionEx failed")
end
ver = os_version[:dwMajorVersion]
end
ver
end
module_function :windows_major_version
# Returns a hash of the current environment variables encoded as UTF-8
# The memory block returned from GetEnvironmentStringsW is double-null terminated and the vars are paired as below;
# Var1=Value1\0
# Var2=Value2\0
# VarX=ValueX\0\0
# Note - Some env variable names start with '=' and are excluded from the return value
# Note - The env_ptr MUST be freed using the FreeEnvironmentStringsW function
# Note - There is no technical limitation to the size of the environment block returned.
# However a practical limit of 64K is used as no single environment variable can exceed 32KB
def get_environment_strings
env_ptr = GetEnvironmentStringsW()
# pass :invalid => :replace to the Ruby String#encode to use replacement characters
pairs = env_ptr.read_arbitrary_wide_string_up_to(65_534, :double_null, { :invalid => :replace })
.split(?\x00)
.reject { |env_str| env_str.nil? || env_str.empty? || env_str[0] == '=' }
.reject do |env_str|
# reject any string containing the Unicode replacement character
if env_str.include?("\uFFFD")
Puppet.warning(_("Discarding environment variable %{string} which contains invalid bytes") % { string: env_str })
true
end
end
.map { |env_pair| env_pair.split('=', 2) }
pairs.to_h
ensure
if env_ptr && !env_ptr.null?
if FreeEnvironmentStringsW(env_ptr) == FFI::WIN32_FALSE
Puppet.debug "FreeEnvironmentStringsW memory leak"
end
end
end
module_function :get_environment_strings
def set_environment_variable(name, val)
raise Puppet::Util::Windows::Error(_('environment variable name must not be nil or empty')) if !name || name.empty?
FFI::MemoryPointer.from_string_to_wide_string(name) do |name_ptr|
if val.nil?
if SetEnvironmentVariableW(name_ptr, FFI::MemoryPointer::NULL) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to remove environment variable: %{name}") % { name: name }
end
else
FFI::MemoryPointer.from_string_to_wide_string(val) do |val_ptr|
if SetEnvironmentVariableW(name_ptr, val_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to set environment variable: %{name}") % { name: name }
end
end
end
end
end
module_function :set_environment_variable
def get_system_default_ui_language
GetSystemDefaultUILanguage()
end
module_function :get_system_default_ui_language
# Returns whether or not the OS has the ability to set elevated
# token information.
#
# Returns true on Windows Vista or later, otherwise false
#
def supports_elevated_security?
windows_major_version >= 6
end
module_function :supports_elevated_security?
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/access_control_list.rb | lib/puppet/util/windows/access_control_list.rb | # frozen_string_literal: true
# Windows Access Control List
#
# Represents a list of access control entries (ACEs).
#
# @see https://msdn.microsoft.com/en-us/library/windows/desktop/aa374872(v=vs.85).aspx
# @api private
class Puppet::Util::Windows::AccessControlList
include Enumerable
ACCESS_ALLOWED_ACE_TYPE = 0x0
ACCESS_DENIED_ACE_TYPE = 0x1
# Construct an ACL.
#
# @param acl [Enumerable] A list of aces to copy from.
def initialize(acl = nil)
if acl
@aces = acl.map(&:dup)
else
@aces = []
end
end
# Enumerate each ACE in the list.
#
# @yieldparam ace [Hash] the ace
def each
@aces.each { |ace| yield ace }
end
# Allow the +sid+ to access a resource with the specified access +mask+.
#
# @param sid [String] The SID that the ACE is granting access to
# @param mask [int] The access mask granted to the SID
# @param flags [int] The flags assigned to the ACE, e.g. +INHERIT_ONLY_ACE+
def allow(sid, mask, flags = 0)
@aces << Puppet::Util::Windows::AccessControlEntry.new(sid, mask, flags, ACCESS_ALLOWED_ACE_TYPE)
end
# Deny the +sid+ access to a resource with the specified access +mask+.
#
# @param sid [String] The SID that the ACE is denying access to
# @param mask [int] The access mask denied to the SID
# @param flags [int] The flags assigned to the ACE, e.g. +INHERIT_ONLY_ACE+
def deny(sid, mask, flags = 0)
@aces << Puppet::Util::Windows::AccessControlEntry.new(sid, mask, flags, ACCESS_DENIED_ACE_TYPE)
end
# Reassign all ACEs currently assigned to +old_sid+ to +new_sid+ instead.
# If an ACE is inherited or is not assigned to +old_sid+, then it will
# be copied as-is to the new ACL, preserving its order within the ACL.
#
# @param old_sid [String] The old SID, e.g. 'S-1-5-18'
# @param new_sid [String] The new SID
# @return [AccessControlList] The copied ACL.
def reassign!(old_sid, new_sid)
new_aces = []
prepend_needed = false
aces_to_prepend = []
@aces.each do |ace|
new_ace = ace.dup
if ace.sid == old_sid
if ace.inherited?
# create an explicit ACE granting or denying the
# new_sid the rights that the inherited ACE
# granted or denied the old_sid. We mask off all
# flags except those affecting inheritance of the
# ACE we're creating.
inherit_mask = Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
explicit_ace = Puppet::Util::Windows::AccessControlEntry.new(new_sid, ace.mask, ace.flags & inherit_mask, ace.type)
aces_to_prepend << explicit_ace
else
new_ace.sid = new_sid
prepend_needed = old_sid == Puppet::Util::Windows::SID::LocalSystem
end
end
new_aces << new_ace
end
@aces = []
if prepend_needed
mask = Puppet::Util::Windows::File::STANDARD_RIGHTS_ALL | Puppet::Util::Windows::File::SPECIFIC_RIGHTS_ALL
ace = Puppet::Util::Windows::AccessControlEntry.new(
Puppet::Util::Windows::SID::LocalSystem,
mask
)
@aces << ace
end
@aces.concat(aces_to_prepend)
@aces.concat(new_aces)
end
def inspect
str = ''.dup
@aces.each do |ace|
str << " #{ace.inspect}\n"
end
str
end
def ==(other)
self.class == other.class &&
to_a == other.to_a
end
alias eql? ==
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/service.rb | lib/puppet/util/windows/service.rb | # coding: utf-8
# frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows
# This module is designed to provide an API between the windows system and puppet for
# service management.
#
# for an overview of the service state transitions see: https://docs.microsoft.com/en-us/windows/desktop/Services/service-status-transitions
module Service
extend Puppet::Util::Windows::String
include Puppet::FFI::Windows::Constants
extend Puppet::FFI::Windows::Constants
include Puppet::FFI::Windows::Structs
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Functions
# Returns true if the service exists, false otherwise.
#
# @param [String] service_name name of the service
def exists?(service_name)
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |_|
true
end
rescue Puppet::Util::Windows::Error => e
return false if e.code == ERROR_SERVICE_DOES_NOT_EXIST
raise e
end
module_function :exists?
# Start a windows service
#
# @param [String] service_name name of the service to start
# @param optional [Integer] timeout the minumum number of seconds to wait before timing out
def start(service_name, timeout: DEFAULT_TIMEOUT)
Puppet.debug _("Starting the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout }
valid_initial_states = [
SERVICE_STOP_PENDING,
SERVICE_STOPPED,
SERVICE_START_PENDING
]
transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service|
if StartServiceW(service, 0, FFI::Pointer::NULL) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to start the service")
end
end
Puppet.debug _("Successfully started the %{service_name} service") % { service_name: service_name }
end
module_function :start
# Stop a windows service
#
# @param [String] service_name name of the service to stop
# @param optional [Integer] timeout the minumum number of seconds to wait before timing out
def stop(service_name, timeout: DEFAULT_TIMEOUT)
Puppet.debug _("Stopping the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout }
valid_initial_states = SERVICE_STATES.keys - [SERVICE_STOPPED]
transition_service_state(service_name, valid_initial_states, SERVICE_STOPPED, timeout) do |service|
send_service_control_signal(service, SERVICE_CONTROL_STOP)
end
Puppet.debug _("Successfully stopped the %{service_name} service") % { service_name: service_name }
end
module_function :stop
# Resume a paused windows service
#
# @param [String] service_name name of the service to resume
# @param optional [Integer] :timeout the minumum number of seconds to wait before timing out
def resume(service_name, timeout: DEFAULT_TIMEOUT)
Puppet.debug _("Resuming the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout }
valid_initial_states = [
SERVICE_PAUSE_PENDING,
SERVICE_PAUSED,
SERVICE_CONTINUE_PENDING
]
transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service|
# The SERVICE_CONTROL_CONTINUE signal can only be sent when
# the service is in the SERVICE_PAUSED state
wait_on_pending_state(service, SERVICE_PAUSE_PENDING, timeout)
send_service_control_signal(service, SERVICE_CONTROL_CONTINUE)
end
Puppet.debug _("Successfully resumed the %{service_name} service") % { service_name: service_name }
end
module_function :resume
# Query the state of a service using QueryServiceStatusEx
#
# @param [string] service_name name of the service to query
# @return [string] the status of the service
def service_state(service_name)
state = nil
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |service|
query_status(service) do |status|
state = SERVICE_STATES[status[:dwCurrentState]]
end
end
if state.nil?
raise Puppet::Error, _("Unknown Service state '%{current_state}' for '%{service_name}'") % { current_state: state.to_s, service_name: service_name }
end
state
end
module_function :service_state
# Query the configuration of a service using QueryServiceConfigW
# or QueryServiceConfig2W
#
# @param [String] service_name name of the service to query
# @return [QUERY_SERVICE_CONFIGW.struct] the configuration of the service
def service_start_type(service_name)
start_type = nil
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|
query_config(service) do |config|
start_type = SERVICE_START_TYPES[config[:dwStartType]]
end
end
# if the service has type AUTO_START, check if it's a delayed service
if start_type == :SERVICE_AUTO_START
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|
query_config2(service, SERVICE_CONFIG_DELAYED_AUTO_START_INFO) do |config|
return :SERVICE_DELAYED_AUTO_START if config[:fDelayedAutostart] == 1
end
end
end
if start_type.nil?
raise Puppet::Error, _("Unknown start type '%{start_type}' for '%{service_name}'") % { start_type: start_type.to_s, service_name: service_name }
end
start_type
end
module_function :service_start_type
# Query the configuration of a service using QueryServiceConfigW
# to find its current logon account
#
# @return [String] logon_account account currently set for the service's logon
# in the format "DOMAIN\Account" or ".\Account" if it's a local account
def logon_account(service_name)
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|
query_config(service) do |config|
return config[:lpServiceStartName].read_arbitrary_wide_string_up_to(Puppet::Util::Windows::ADSI::User::MAX_USERNAME_LENGTH)
end
end
end
module_function :logon_account
# Set the startup configuration of a windows service
#
# @param [String] service_name the name of the service to modify
# @param [Hash] options the configuration to be applied. Expected option keys:
# - [Integer] startup_type a code corresponding to a start type for
# windows service, see the "Service start type codes" section in the
# Puppet::Util::Windows::Service file for the list of available codes
# - [String] logon_account the account to be used by the service for logon
# - [String] logon_password the provided logon_account's password to be used by the service for logon
# - [Bool] delayed whether the service should be started with a delay
def set_startup_configuration(service_name, options: {})
options[:startup_type] = SERVICE_START_TYPES.key(options[:startup_type]) || SERVICE_NO_CHANGE
options[:logon_account] = wide_string(options[:logon_account]) || FFI::Pointer::NULL
options[:logon_password] = wide_string(options[:logon_password]) || FFI::Pointer::NULL
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_CONFIG) do |service|
success = ChangeServiceConfigW(
service,
SERVICE_NO_CHANGE, # dwServiceType
options[:startup_type], # dwStartType
SERVICE_NO_CHANGE, # dwErrorControl
FFI::Pointer::NULL, # lpBinaryPathName
FFI::Pointer::NULL, # lpLoadOrderGroup
FFI::Pointer::NULL, # lpdwTagId
FFI::Pointer::NULL, # lpDependencies
options[:logon_account], # lpServiceStartName
options[:logon_password], # lpPassword
FFI::Pointer::NULL # lpDisplayName
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to update service configuration")
end
end
if options[:startup_type]
options[:delayed] ||= false
set_startup_mode_delayed(service_name, options[:delayed])
end
end
module_function :set_startup_configuration
# enumerate over all services in all states and return them as a hash
#
# @return [Hash] a hash containing services:
# { 'service name' => {
# 'display_name' => 'display name',
# 'service_status_process' => SERVICE_STATUS_PROCESS struct
# }
# }
def services
services = {}
open_scm(SC_MANAGER_ENUMERATE_SERVICE) do |scm|
size_required = 0
services_returned = 0
FFI::MemoryPointer.new(:dword) do |bytes_pointer|
FFI::MemoryPointer.new(:dword) do |svcs_ret_ptr|
FFI::MemoryPointer.new(:dword) do |resume_ptr|
resume_ptr.write_dword(0)
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfigW to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
#
# return value will be false from this call, since it's designed
# to fail. Just ignore it
EnumServicesStatusExW(
scm,
:SC_ENUM_PROCESS_INFO,
ALL_SERVICE_TYPES,
SERVICE_STATE_ALL,
FFI::Pointer::NULL,
0,
bytes_pointer,
svcs_ret_ptr,
resume_ptr,
FFI::Pointer::NULL
)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |buffer_ptr|
resume_ptr.write_dword(0)
svcs_ret_ptr.write_dword(0)
success = EnumServicesStatusExW(
scm,
:SC_ENUM_PROCESS_INFO,
ALL_SERVICE_TYPES,
SERVICE_STATE_ALL,
buffer_ptr,
buffer_ptr.size,
bytes_pointer,
svcs_ret_ptr,
resume_ptr,
FFI::Pointer::NULL
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to fetch services")
end
# Now that the buffer is populated with services
# we pull the data from memory using pointer arithmetic:
# the number of services returned by the function is
# available to be read from svcs_ret_ptr, and we iterate
# that many times moving the cursor pointer the length of
# ENUM_SERVICE_STATUS_PROCESSW.size. This should iterate
# over the buffer and extract each struct.
services_returned = svcs_ret_ptr.read_dword
cursor_ptr = FFI::Pointer.new(ENUM_SERVICE_STATUS_PROCESSW, buffer_ptr)
0.upto(services_returned - 1) do |index|
service = ENUM_SERVICE_STATUS_PROCESSW.new(cursor_ptr[index])
services[service[:lpServiceName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX)] = {
:display_name => service[:lpDisplayName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX),
:service_status_process => service[:ServiceStatusProcess]
}
end
end # buffer_ptr
end # resume_ptr
end # scvs_ret_ptr
end # bytes_ptr
end # open_scm
services
end
module_function :services
class << self
# @api private
# Opens a connection to the SCManager on windows then uses that
# handle to create a handle to a specific service in windows
# corresponding to service_name
#
# this function takes a block that executes within the context of
# the open service handler, and will close the service and SCManager
# handles once the block finishes
#
# @param [string] service_name the name of the service to open
# @param [Integer] scm_access code corresponding to the access type requested for the scm
# @param [Integer] service_access code corresponding to the access type requested for the service
# @yieldparam [:handle] service the windows native handle used to access
# the service
# @return the result of the block
def open_service(service_name, scm_access, service_access, &block)
service = FFI::Pointer::NULL_HANDLE
result = nil
open_scm(scm_access) do |scm|
service = OpenServiceW(scm, wide_string(service_name), service_access)
raise Puppet::Util::Windows::Error, _("Failed to open a handle to the service") if service == FFI::Pointer::NULL_HANDLE
result = yield service
end
result
ensure
CloseServiceHandle(service)
end
private :open_service
# @api private
#
# Opens a handle to the service control manager
#
# @param [Integer] scm_access code corresponding to the access type requested for the scm
def open_scm(scm_access, &block)
scm = OpenSCManagerW(FFI::Pointer::NULL, FFI::Pointer::NULL, scm_access)
raise Puppet::Util::Windows::Error, _("Failed to open a handle to the service control manager") if scm == FFI::Pointer::NULL_HANDLE
yield scm
ensure
CloseServiceHandle(scm)
end
private :open_scm
# @api private
# Transition the service to the specified state. The block should perform
# the actual transition.
#
# @param [String] service_name the name of the service to transition
# @param [[Integer]] valid_initial_states an array of valid states that the service can transition from
# @param [Integer] final_state the state that the service will transition to
# @param [Integer] timeout the minumum number of seconds to wait before timing out
def transition_service_state(service_name, valid_initial_states, final_state, timeout, &block)
service_access = SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_QUERY_STATUS
open_service(service_name, SC_MANAGER_CONNECT, service_access) do |service|
query_status(service) do |status|
initial_state = status[:dwCurrentState]
# If the service is already in the final_state, then
# no further work needs to be done
if initial_state == final_state
Puppet.debug _("The service is already in the %{final_state} state. No further work needs to be done.") % { final_state: SERVICE_STATES[final_state] }
next
end
# Check that initial_state corresponds to a valid
# initial state
unless valid_initial_states.include?(initial_state)
valid_initial_states_str = valid_initial_states.map do |state|
SERVICE_STATES[state]
end.join(", ")
raise Puppet::Error, _("The service must be in one of the %{valid_initial_states} states to perform this transition. It is currently in the %{current_state} state.") % { valid_initial_states: valid_initial_states_str, current_state: SERVICE_STATES[initial_state] }
end
# Check if there's a pending transition to the final_state. If so, then wait for
# that transition to finish.
possible_pending_states = FINAL_STATES.keys.select do |pending_state|
# SERVICE_RUNNING has two pending states, SERVICE_START_PENDING and
# SERVICE_CONTINUE_PENDING. That is why we need the #select here
FINAL_STATES[pending_state] == final_state
end
if possible_pending_states.include?(initial_state)
Puppet.debug _("There is already a pending transition to the %{final_state} state for the %{service_name} service.") % { final_state: SERVICE_STATES[final_state], service_name: service_name }
wait_on_pending_state(service, initial_state, timeout)
next
end
# If we are in an unsafe pending state like SERVICE_START_PENDING
# or SERVICE_STOP_PENDING, then we want to wait for that pending
# transition to finish before transitioning the service state.
# The reason we do this is because SERVICE_START_PENDING is when
# the service thread is being created and initialized, while
# SERVICE_STOP_PENDING is when the service thread is being cleaned
# up and destroyed. Thus there is a chance that when the service is
# in either of these states, its service thread may not yet be ready
# to perform the state transition (it may not even exist).
if UNSAFE_PENDING_STATES.include?(initial_state)
Puppet.debug _("The service is in the %{pending_state} state, which is an unsafe pending state.") % { pending_state: SERVICE_STATES[initial_state] }
wait_on_pending_state(service, initial_state, timeout)
initial_state = FINAL_STATES[initial_state]
end
Puppet.debug _("Transitioning the %{service_name} service from %{initial_state} to %{final_state}") % { service_name: service_name, initial_state: SERVICE_STATES[initial_state], final_state: SERVICE_STATES[final_state] }
yield service
Puppet.debug _("Waiting for the transition to finish")
wait_on_state_transition(service, initial_state, final_state, timeout)
end
end
rescue => detail
raise Puppet::Error, _("Failed to transition the %{service_name} service to the %{final_state} state. Detail: %{detail}") % { service_name: service_name, final_state: SERVICE_STATES[final_state], detail: detail }, detail.backtrace
end
private :transition_service_state
# @api private
# perform QueryServiceStatusEx on a windows service and return the
# result
#
# @param [:handle] service handle of the service to query
# @return [SERVICE_STATUS_PROCESS struct] the result of the query
def query_status(service)
size_required = nil
status = nil
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfigW to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
FFI::MemoryPointer.new(:lpword) do |bytes_pointer|
# return value will be false from this call, since it's designed
# to fail. Just ignore it
QueryServiceStatusEx(
service,
:SC_STATUS_PROCESS_INFO,
FFI::Pointer::NULL,
0,
bytes_pointer
)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |ssp_ptr|
status = SERVICE_STATUS_PROCESS.new(ssp_ptr)
success = QueryServiceStatusEx(
service,
:SC_STATUS_PROCESS_INFO,
ssp_ptr,
size_required,
bytes_pointer
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Service query failed")
end
yield status
end
end
end
private :query_status
# @api private
# perform QueryServiceConfigW on a windows service and return the
# result
#
# @param [:handle] service handle of the service to query
# @return [QUERY_SERVICE_CONFIGW struct] the result of the query
def query_config(service, &block)
config = nil
size_required = nil
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfigW to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
FFI::MemoryPointer.new(:lpword) do |bytes_pointer|
# return value will be false from this call, since it's designed
# to fail. Just ignore it
QueryServiceConfigW(service, FFI::Pointer::NULL, 0, bytes_pointer)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |ssp_ptr|
config = QUERY_SERVICE_CONFIGW.new(ssp_ptr)
success = QueryServiceConfigW(
service,
ssp_ptr,
size_required,
bytes_pointer
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Service query failed")
end
yield config
end
end
end
private :query_config
# @api private
# perform QueryServiceConfig2W on a windows service and return the
# result
#
# @param [:handle] service handle of the service to query
# @param [Integer] info_level the configuration information to be queried
# @return [QUERY_SERVICE_CONFIG2W struct] the result of the query
def query_config2(service, info_level, &block)
config = nil
size_required = nil
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfig2W to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
FFI::MemoryPointer.new(:lpword) do |bytes_pointer|
# return value will be false from this call, since it's designed
# to fail. Just ignore it
QueryServiceConfig2W(service, info_level, FFI::Pointer::NULL, 0, bytes_pointer)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |ssp_ptr|
# We need to supply the appropriate struct to be created based on
# the info_level
case info_level
when SERVICE_CONFIG_DELAYED_AUTO_START_INFO
config = SERVICE_DELAYED_AUTO_START_INFO.new(ssp_ptr)
end
success = QueryServiceConfig2W(
service,
info_level,
ssp_ptr,
size_required,
bytes_pointer
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Service query for %{parameter_name} failed") % { parameter_name: SERVICE_CONFIG_TYPES[info_level] }
end
yield config
end
end
end
private :query_config2
# @api private
# Sets an optional parameter on a service by calling
# ChangeServiceConfig2W
#
# @param [String] service_name name of service
# @param [Integer] change parameter to change
# @param [struct] value appropriate struct based on the parameter to change
def set_optional_parameter(service_name, change, value)
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_CONFIG) do |service|
success = ChangeServiceConfig2W(
service,
change, # dwInfoLevel
value # lpInfo
)
if success == FFI::WIN32_FALSE
raise Puppet::Util.windows::Error, _("Failed to update service %{change} configuration") % { change: change }
end
end
end
private :set_optional_parameter
# @api private
# Controls the delayed auto-start setting of a service
#
# @param [String] service_name name of service
# @param [Bool] delayed whether the service should be started with a delay or not
def set_startup_mode_delayed(service_name, delayed)
delayed_start = SERVICE_DELAYED_AUTO_START_INFO.new
delayed_start[:fDelayedAutostart] = delayed
set_optional_parameter(service_name, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayed_start)
end
private :set_startup_mode_delayed
# @api private
# Sends a service control signal to a service
#
# @param [:handle] service handle to the service
# @param [Integer] signal the service control signal to send
def send_service_control_signal(service, signal)
FFI::MemoryPointer.new(SERVICE_STATUS.size) do |status_ptr|
status = SERVICE_STATUS.new(status_ptr)
if ControlService(service, signal, status) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to send the %{control_signal} signal to the service. Its current state is %{current_state}. Reason for failure:") % { control_signal: SERVICE_CONTROL_SIGNALS[signal], current_state: SERVICE_STATES[status[:dwCurrentState]] }
end
end
end
# @api private
# Waits for a service to transition from one state to
# another state.
#
# @param [:handle] service handle to the service to wait on
# @param [Integer] initial_state the state that the service is transitioning from.
# @param [Integer] final_state the state that the service is transitioning to
# @param [Integer] timeout the minumum number of seconds to wait before timing out
def wait_on_state_transition(service, initial_state, final_state, timeout)
# Get the pending state for this transition. Note that SERVICE_RUNNING
# has two possible pending states, which is why we need this logic.
if final_state != SERVICE_RUNNING
pending_state = FINAL_STATES.key(final_state)
elsif initial_state == SERVICE_STOPPED
# SERVICE_STOPPED => SERVICE_RUNNING
pending_state = SERVICE_START_PENDING
else
# SERVICE_PAUSED => SERVICE_RUNNING
pending_state = SERVICE_CONTINUE_PENDING
end
# Wait for the transition to finish
state = nil
elapsed_time = 0
while elapsed_time <= timeout
query_status(service) do |status|
state = status[:dwCurrentState]
return if state == final_state
if state == pending_state
Puppet.debug _("The service transitioned to the %{pending_state} state.") % { pending_state: SERVICE_STATES[pending_state] }
wait_on_pending_state(service, pending_state, timeout)
return
end
sleep(1)
elapsed_time += 1
end
end
# Timed out while waiting for the transition to finish. Raise an error
# We can still use the state variable read from the FFI struct because
# FFI creates new Integer objects during an assignment of an integer value
# stored in an FFI struct. We verified that the '=' operater is safe
# from the freed memory since the new ruby object created during the
# assignment will remain in ruby memory and remain immutable and constant.
raise Puppet::Error, _("Timed out while waiting for the service to transition from %{initial_state} to %{final_state} OR from %{initial_state} to %{pending_state} to %{final_state}. The service's current state is %{current_state}.") % { initial_state: SERVICE_STATES[initial_state], final_state: SERVICE_STATES[final_state], pending_state: SERVICE_STATES[pending_state], current_state: SERVICE_STATES[state] }
end
private :wait_on_state_transition
# @api private
# Waits for a service to finish transitioning from
# a pending state. The service must be in the pending state
# before invoking this routine.
#
# @param [:handle] service handle to the service to wait on
# @param [Integer] pending_state the pending state
# @param [Integer] timeout the minumum number of seconds to wait before timing out
def wait_on_pending_state(service, pending_state, timeout)
final_state = FINAL_STATES[pending_state]
Puppet.debug _("Waiting for the pending transition to the %{final_state} state to finish.") % { final_state: SERVICE_STATES[final_state] }
elapsed_time = 0
last_checkpoint = -1
loop do
query_status(service) do |status|
state = status[:dwCurrentState]
checkpoint = status[:dwCheckPoint]
wait_hint = status[:dwWaitHint]
# Check if our service has finished transitioning to
# the final_state OR if an unexpected transition
# has occurred
return if state == final_state
unless state == pending_state
raise Puppet::Error, _("Unexpected transition to the %{current_state} state while waiting for the pending transition from %{pending_state} to %{final_state} to finish.") % { current_state: SERVICE_STATES[state], pending_state: SERVICE_STATES[pending_state], final_state: SERVICE_STATES[final_state] }
end
# Check if any progress has been made since our last sleep
# using the dwCheckPoint. If no progress has been made then
# check if we've timed out, and raise an error if so
if checkpoint > last_checkpoint
elapsed_time = 0
last_checkpoint = checkpoint
else
wait_hint = milliseconds_to_seconds(status[:dwWaitHint])
timeout = wait_hint < timeout ? timeout : wait_hint
if elapsed_time >= timeout
raise Puppet::Error, _("Timed out while waiting for the pending transition from %{pending_state} to %{final_state} to finish. The current state is %{current_state}.") % { pending_state: SERVICE_STATES[pending_state], final_state: SERVICE_STATES[final_state], current_state: SERVICE_STATES[state] }
end
end
wait_time = wait_hint_to_wait_time(wait_hint)
# Wait a bit before rechecking the service's state
sleep(wait_time)
elapsed_time += wait_time
end
end
end
private :wait_on_pending_state
# @api private
#
# create a usable wait time to wait between querying the service.
#
# @param [Integer] wait_hint the wait hint of a service in milliseconds
# @return [Integer] the time to wait in seconds between querying the service
def wait_hint_to_wait_time(wait_hint)
# Wait 1/10th the wait_hint, but no less than 1 and
# no more than 10 seconds
wait_time = milliseconds_to_seconds(wait_hint) / 10;
wait_time = 1 if wait_time < 1
wait_time = 10 if wait_time > 10
wait_time
end
private :wait_hint_to_wait_time
# @api private
#
# process the wait hint listed by a service to something
# usable by ruby sleep
#
# @param [Integer] wait_hint the wait hint of a service in milliseconds
# @return [Integer] wait_hint in seconds
def milliseconds_to_seconds(wait_hint)
wait_hint / 1000;
end
private :milliseconds_to_seconds
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/util/windows/access_control_entry.rb | lib/puppet/util/windows/access_control_entry.rb | # frozen_string_literal: true
# Windows Access Control Entry
#
# Represents an access control entry, which grants or denies a subject,
# identified by a SID, rights to a securable object.
#
# @see https://msdn.microsoft.com/en-us/library/windows/desktop/aa374868(v=vs.85).aspx
# @api private
class Puppet::Util::Windows::AccessControlEntry
require_relative '../../../puppet/util/windows/security'
include Puppet::Util::Windows::SID
attr_accessor :sid
attr_reader :mask, :flags, :type
OBJECT_INHERIT_ACE = 0x1
CONTAINER_INHERIT_ACE = 0x2
NO_PROPAGATE_INHERIT_ACE = 0x4
INHERIT_ONLY_ACE = 0x8
INHERITED_ACE = 0x10
ACCESS_ALLOWED_ACE_TYPE = 0x0
ACCESS_DENIED_ACE_TYPE = 0x1
def initialize(sid, mask, flags = 0, type = ACCESS_ALLOWED_ACE_TYPE)
@sid = sid
@mask = mask
@flags = flags
@type = type
end
# Returns true if this ACE is inherited from a parent. If false,
# then the ACE is set directly on the object to which it refers.
#
# @return [Boolean] true if the ACE is inherited
def inherited?
(@flags & INHERITED_ACE) == INHERITED_ACE
end
# Returns true if this ACE only applies to children of the object.
# If false, it applies to the object.
#
# @return [Boolean] true if the ACE only applies to children and
# not the object itself.
def inherit_only?
(@flags & INHERIT_ONLY_ACE) == INHERIT_ONLY_ACE
end
# Returns true if this ACE applies to child directories.
#
# @return [Boolean] true if the ACE applies to child directories
def container_inherit?
(@flags & CONTAINER_INHERIT_ACE) == CONTAINER_INHERIT_ACE
end
# Returns true if this ACE applies to child files.
#
# @return [Boolean] true if the ACE applies to child files.
def object_inherit?
(@flags & OBJECT_INHERIT_ACE) == OBJECT_INHERIT_ACE
end
def inspect
inheritance = ''.dup
inheritance << '(I)' if inherited?
inheritance << '(OI)' if object_inherit?
inheritance << '(CI)' if container_inherit?
inheritance << '(IO)' if inherit_only?
left = "#{sid_to_name(sid)}:#{inheritance}"
left = left.ljust(45)
"#{left} 0x#{mask.to_s(16)}"
end
# Returns true if this ACE is equal to +other+
def ==(other)
self.class == other.class &&
sid == other.sid &&
mask == other.mask &&
flags == other.flags &&
type == other.type
end
alias eql? ==
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/error.rb | lib/puppet/util/windows/error.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
require_relative '../../../puppet/error'
# represents an error resulting from a Win32 error code
class Puppet::Util::Windows::Error < Puppet::Error
require 'ffi'
extend FFI::Library
attr_reader :code
# NOTE: FFI.errno only works properly when prior Win32 calls have been made
# through FFI bindings. Calls made through Win32API do not have their error
# codes captured by FFI.errno
def initialize(message, code = FFI.errno, original = nil)
super(message + ": #{self.class.format_error_code(code)}", original)
@code = code
end
# Helper method that wraps FormatMessage that returns a human readable string.
def self.format_error_code(code)
# specifying 0 will look for LANGID in the following order
# 1.Language neutral
# 2.Thread LANGID, based on the thread's locale value
# 3.User default LANGID, based on the user's default locale value
# 4.System default LANGID, based on the system default locale value
# 5.US English
dwLanguageId = 0
flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ARGUMENT_ARRAY |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK
error_string = ''.dup
# this pointer actually points to a :lpwstr (pointer) since we're letting Windows allocate for us
FFI::MemoryPointer.new(:pointer, 1) do |buffer_ptr|
length = FormatMessageW(flags, FFI::Pointer::NULL, code, dwLanguageId,
buffer_ptr, 0, FFI::Pointer::NULL)
if length == FFI::WIN32_FALSE
# can't raise same error type here or potentially recurse infinitely
raise Puppet::Error, _("FormatMessageW could not format code %{code}") % { code: code }
end
# returns an FFI::Pointer with autorelease set to false, which is what we want
buffer_ptr.read_win32_local_pointer do |wide_string_ptr|
if wide_string_ptr.null?
raise Puppet::Error, _("FormatMessageW failed to allocate buffer for code %{code}") % { code: code }
end
error_string = wide_string_ptr.read_wide_string(length)
end
end
error_string
end
ERROR_FILE_NOT_FOUND = 2
ERROR_ACCESS_DENIED = 5
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000
FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351(v=vs.85).aspx
# DWORD WINAPI FormatMessage(
# _In_ DWORD dwFlags,
# _In_opt_ LPCVOID lpSource,
# _In_ DWORD dwMessageId,
# _In_ DWORD dwLanguageId,
# _Out_ LPTSTR lpBuffer,
# _In_ DWORD nSize,
# _In_opt_ va_list *Arguments
# );
# NOTE: since we're not preallocating the buffer, use a :pointer for lpBuffer
ffi_lib :kernel32
attach_function_private :FormatMessageW,
[:dword, :lpcvoid, :dword, :dword, :pointer, :dword, :pointer], :dword
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/adsi.rb | lib/puppet/util/windows/adsi.rb | # frozen_string_literal: true
module Puppet::Util::Windows::ADSI
require 'ffi'
# https://docs.microsoft.com/en-us/windows/win32/api/dsrole/ne-dsrole-dsrole_machine_role
STANDALONE_WORKSTATION = 0
MEMBER_WORKSTATION = 1
STANDALONE_SERVER = 2
MEMBER_SERVER = 3
BACKUP_DOMAIN_CONTROLLER = 4
PRIMARY_DOMAIN_CONTROLLER = 5
DOMAIN_ROLES = {
STANDALONE_WORKSTATION => :STANDALONE_WORKSTATION,
MEMBER_WORKSTATION => :MEMBER_WORKSTATION,
STANDALONE_SERVER => :STANDALONE_SERVER,
MEMBER_SERVER => :MEMBER_SERVER,
BACKUP_DOMAIN_CONTROLLER => :BACKUP_DOMAIN_CONTROLLER,
PRIMARY_DOMAIN_CONTROLLER => :PRIMARY_DOMAIN_CONTROLLER,
}
class << self
extend FFI::Library
def connectable?(uri)
!!connect(uri)
rescue
false
end
def connect(uri)
WIN32OLE.connect(uri)
rescue WIN32OLERuntimeError => e
raise Puppet::Error.new(_("ADSI connection error: %{e}") % { e: e }, e)
end
def create(name, resource_type)
Puppet::Util::Windows::ADSI.connect(computer_uri).Create(resource_type, name)
end
def delete(name, resource_type)
Puppet::Util::Windows::ADSI.connect(computer_uri).Delete(resource_type, name)
end
# taken from winbase.h
MAX_COMPUTERNAME_LENGTH = 31
def computer_name
unless @computer_name
max_length = MAX_COMPUTERNAME_LENGTH + 1 # NULL terminated
FFI::MemoryPointer.new(max_length * 2) do |buffer| # wide string
FFI::MemoryPointer.new(:dword, 1) do |buffer_size|
buffer_size.write_dword(max_length) # length in TCHARs
if GetComputerNameW(buffer, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get computer name")
end
@computer_name = buffer.read_wide_string(buffer_size.read_dword)
end
end
end
@computer_name
end
def computer_uri(host = '.')
"WinNT://#{host}"
end
def wmi_resource_uri(host = '.')
"winmgmts:{impersonationLevel=impersonate}!//#{host}/root/cimv2"
end
# This method should *only* be used to generate WinNT://<SID> style monikers
# used for IAdsGroup::Add / IAdsGroup::Remove. These URIs are not usable
# to resolve an account with WIN32OLE.connect
# Valid input is a SID::Principal, S-X-X style SID string or any valid
# account name with or without domain prefix
# @api private
def sid_uri_safe(sid)
return sid_uri(sid) if sid.is_a?(Puppet::Util::Windows::SID::Principal)
begin
sid = Puppet::Util::Windows::SID.name_to_principal(sid)
sid_uri(sid)
rescue Puppet::Util::Windows::Error, Puppet::Error
nil
end
end
# This method should *only* be used to generate WinNT://<SID> style monikers
# used for IAdsGroup::Add / IAdsGroup::Remove. These URIs are not useable
# to resolve an account with WIN32OLE.connect
def sid_uri(sid)
raise Puppet::Error, _("Must use a valid SID::Principal") unless sid.is_a?(Puppet::Util::Windows::SID::Principal)
"WinNT://#{sid.sid}"
end
def uri(resource_name, resource_type, host = '.')
"#{computer_uri(host)}/#{resource_name},#{resource_type}"
end
def wmi_connection
connect(wmi_resource_uri)
end
def execquery(query)
wmi_connection.execquery(query)
end
def domain_role
unless @domain_role
query_result = Puppet::Util::Windows::ADSI.execquery('select DomainRole from Win32_ComputerSystem').to_enum.first
@domain_role = DOMAIN_ROLES[query_result.DomainRole] if query_result
end
@domain_role
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724295(v=vs.85).aspx
# BOOL WINAPI GetComputerName(
# _Out_ LPTSTR lpBuffer,
# _Inout_ LPDWORD lpnSize
# );
ffi_lib :kernel32
attach_function_private :GetComputerNameW,
[:lpwstr, :lpdword], :win32_bool
end
# Common base class shared by the User and Group
# classes below.
class ADSIObject
extend Enumerable
# Define some useful class-level methods
class << self
# Is either 'user' or 'group'
attr_reader :object_class
def localized_domains
@localized_domains ||= [
# localized version of BUILTIN
# for instance VORDEFINIERT on German Windows
Puppet::Util::Windows::SID.sid_to_name('S-1-5-32').upcase,
# localized version of NT AUTHORITY (can't use S-1-5)
# for instance AUTORITE NT on French Windows
Puppet::Util::Windows::SID.name_to_principal('SYSTEM').domain.upcase
]
end
def uri(name, host = '.')
host = '.' if (localized_domains << Socket.gethostname.upcase).include?(host.upcase)
Puppet::Util::Windows::ADSI.uri(name, @object_class, host)
end
def parse_name(name)
if name =~ %r{/}
raise Puppet::Error, _("Value must be in DOMAIN\\%{object_class} style syntax") % { object_class: @object_class }
end
matches = name.scan(/((.*)\\)?(.*)/)
domain = matches[0][1] || '.'
account = matches[0][2]
[account, domain]
end
# returns Puppet::Util::Windows::SID::Principal[]
# may contain objects that represent unresolvable SIDs
def get_sids(adsi_child_collection)
sids = []
adsi_child_collection.each do |m|
sids << Puppet::Util::Windows::SID.ads_to_principal(m)
rescue Puppet::Util::Windows::Error => e
case e.code
when Puppet::Util::Windows::SID::ERROR_TRUSTED_RELATIONSHIP_FAILURE, Puppet::Util::Windows::SID::ERROR_TRUSTED_DOMAIN_FAILURE
sids << Puppet::Util::Windows::SID.unresolved_principal(m.name, m.sid)
else
raise e
end
end
sids
end
def name_sid_hash(names, allow_unresolved = false)
return {} if names.nil? || names.empty?
sids = names.map do |name|
sid = Puppet::Util::Windows::SID.name_to_principal(name, allow_unresolved)
raise Puppet::Error, _("Could not resolve name: %{name}") % { name: name } unless sid
[sid.sid, sid]
end
sids.to_h
end
def delete(name)
Puppet::Util::Windows::ADSI.delete(name, @object_class)
end
def exists?(name_or_sid)
well_known = false
if (sid = Puppet::Util::Windows::SID.name_to_principal(name_or_sid))
# Examples of SidType include SidTypeUser, SidTypeGroup
if sid.account_type == "SidType#{@object_class.capitalize}".to_sym
# Check if we're getting back a local user when domain-joined
return true unless [:MEMBER_WORKSTATION, :MEMBER_SERVER].include?(Puppet::Util::Windows::ADSI.domain_role)
# The resource domain and the computer name are not always case-matching
return sid.domain.casecmp(Puppet::Util::Windows::ADSI.computer_name) == 0
end
# 'well known group' is special as it can be a group like Everyone OR a user like SYSTEM
# so try to resolve it
# https://msdn.microsoft.com/en-us/library/cc234477.aspx
well_known = sid.account_type == :SidTypeWellKnownGroup
return false if sid.account_type != :SidTypeAlias && !well_known
name_or_sid = "#{sid.domain}\\#{sid.account}"
end
object = Puppet::Util::Windows::ADSI.connect(uri(*parse_name(name_or_sid)))
object.Class.downcase == @object_class
rescue
# special accounts like SYSTEM or special groups like Authenticated Users cannot
# resolve via monikers like WinNT://./SYSTEM,user or WinNT://./Authenticated Users,group
# -- they'll fail to connect. thus, given a validly resolved SID, this failure is
# ambiguous as it may indicate either a group like Service or an account like SYSTEM
well_known
end
def list_all
raise NotImplementedError, _("Subclass must implement class-level method 'list_all'!")
end
def each(&block)
objects = []
list_all.each do |o|
# Setting WIN32OLE.codepage in the microsoft_windows feature ensures
# values are returned as UTF-8
objects << new(o.name)
end
objects.each(&block)
end
end
attr_reader :name
def initialize(name, native_object = nil)
@name = name
@native_object = native_object
end
def object_class
self.class.object_class
end
def uri
self.class.uri(sid.account, sid.domain)
end
def native_object
@native_object ||= Puppet::Util::Windows::ADSI.connect(self.class.uri(*self.class.parse_name(name)))
end
def sid
@sid ||= Puppet::Util::Windows::SID.octet_string_to_principal(native_object.objectSID)
end
def [](attribute)
# Setting WIN32OLE.codepage ensures values are returned as UTF-8
native_object.Get(attribute)
end
def []=(attribute, value)
native_object.Put(attribute, value)
end
def commit
begin
native_object.SetInfo
rescue WIN32OLERuntimeError => e
# ERROR_BAD_USERNAME 2202L from winerror.h
if e.message =~ /8007089A/m
raise Puppet::Error, _("Puppet is not able to create/delete domain %{object_class} objects with the %{object_class} resource.") % { object_class: object_class }
end
raise Puppet::Error.new(_("%{object_class} update failed: %{error}") % { object_class: object_class.capitalize, error: e }, e)
end
self
end
end
class User < ADSIObject
extend FFI::Library
require_relative '../../../puppet/util/windows/sid'
# https://msdn.microsoft.com/en-us/library/aa746340.aspx
# IADsUser interface
@object_class = 'user'
class << self
def list_all
Puppet::Util::Windows::ADSI.execquery('select name from win32_useraccount where localaccount = "TRUE"')
end
def logon(name, password)
Puppet::Util::Windows::User.password_is?(name, password)
end
def create(name)
# Windows error 1379: The specified local group already exists.
raise Puppet::Error, _("Cannot create user if group '%{name}' exists.") % { name: name } if Puppet::Util::Windows::ADSI::Group.exists? name
new(name, Puppet::Util::Windows::ADSI.create(name, @object_class))
end
end
def password_is?(password)
self.class.logon(name, password)
end
def add_flag(flag_name, value)
flag = begin
native_object.Get(flag_name)
rescue
0
end
native_object.Put(flag_name, flag | value)
commit
end
def password=(password)
unless password.nil?
native_object.SetPassword(password)
commit
end
fADS_UF_DONT_EXPIRE_PASSWD = 0x10000
add_flag("UserFlags", fADS_UF_DONT_EXPIRE_PASSWD)
end
def groups
# https://msdn.microsoft.com/en-us/library/aa746342.aspx
# WIN32OLE objects aren't enumerable, so no map
groups = []
# Setting WIN32OLE.codepage ensures values are returned as UTF-8
begin
native_object.Groups.each { |g| groups << g.Name }
rescue
nil
end
groups
end
def add_to_groups(*group_names)
group_names.each do |group_name|
Puppet::Util::Windows::ADSI::Group.new(group_name).add_member_sids(sid)
end
end
alias add_to_group add_to_groups
def remove_from_groups(*group_names)
group_names.each do |group_name|
Puppet::Util::Windows::ADSI::Group.new(group_name).remove_member_sids(sid)
end
end
alias remove_from_group remove_from_groups
def add_group_sids(*sids)
group_names = sids.map(&:domain_account)
add_to_groups(*group_names)
end
def remove_group_sids(*sids)
group_names = sids.map(&:domain_account)
remove_from_groups(*group_names)
end
def group_sids
self.class.get_sids(native_object.Groups)
end
# TODO: This code's pretty similar to set_members in the Group class. Would be nice
# to refactor them into the ADSIObject class at some point. This was not done originally
# because these use different methods to do stuff that are also aliased to other methods,
# so the shared code isn't exactly a 1:1 mapping.
def set_groups(desired_groups, minimum = true)
return if desired_groups.nil?
desired_groups = desired_groups.split(',').map(&:strip)
current_hash = group_sids.to_h { |sid| [sid.sid, sid] }
desired_hash = self.class.name_sid_hash(desired_groups)
# First we add the user to all the groups it should be in but isn't
unless desired_groups.empty?
groups_to_add = (desired_hash.keys - current_hash.keys).map { |sid| desired_hash[sid] }
add_group_sids(*groups_to_add)
end
# Then we remove the user from all groups it is in but shouldn't be, if
# that's been requested
unless minimum
if desired_hash.empty?
groups_to_remove = current_hash.values
else
groups_to_remove = (current_hash.keys - desired_hash.keys).map { |sid| current_hash[sid] }
end
remove_group_sids(*groups_to_remove)
end
end
# Declare all of the available user flags on the system. Note that
# ADS_UF is read as ADS_UserFlag
# https://docs.microsoft.com/en-us/windows/desktop/api/iads/ne-iads-ads_user_flag
# and
# https://support.microsoft.com/en-us/help/305144/how-to-use-the-useraccountcontrol-flags-to-manipulate-user-account-pro
# for the flag values.
ADS_USERFLAGS = {
ADS_UF_SCRIPT: 0x0001,
ADS_UF_ACCOUNTDISABLE: 0x0002,
ADS_UF_HOMEDIR_REQUIRED: 0x0008,
ADS_UF_LOCKOUT: 0x0010,
ADS_UF_PASSWD_NOTREQD: 0x0020,
ADS_UF_PASSWD_CANT_CHANGE: 0x0040,
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: 0x0080,
ADS_UF_TEMP_DUPLICATE_ACCOUNT: 0x0100,
ADS_UF_NORMAL_ACCOUNT: 0x0200,
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT: 0x0800,
ADS_UF_WORKSTATION_TRUST_ACCOUNT: 0x1000,
ADS_UF_SERVER_TRUST_ACCOUNT: 0x2000,
ADS_UF_DONT_EXPIRE_PASSWD: 0x10000,
ADS_UF_MNS_LOGON_ACCOUNT: 0x20000,
ADS_UF_SMARTCARD_REQUIRED: 0x40000,
ADS_UF_TRUSTED_FOR_DELEGATION: 0x80000,
ADS_UF_NOT_DELEGATED: 0x100000,
ADS_UF_USE_DES_KEY_ONLY: 0x200000,
ADS_UF_DONT_REQUIRE_PREAUTH: 0x400000,
ADS_UF_PASSWORD_EXPIRED: 0x800000,
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: 0x1000000
}
def userflag_set?(flag)
flag_value = ADS_USERFLAGS[flag] || 0
!(self['UserFlags'] & flag_value).zero?
end
# Common helper for set_userflags and unset_userflags.
#
# @api private
def op_userflags(*flags, &block)
# Avoid an unnecessary set + commit operation.
return if flags.empty?
unrecognized_flags = flags.reject { |flag| ADS_USERFLAGS.keys.include?(flag) }
unless unrecognized_flags.empty?
raise ArgumentError, _("Unrecognized ADS UserFlags: %{unrecognized_flags}") % { unrecognized_flags: unrecognized_flags.join(', ') }
end
self['UserFlags'] = flags.inject(self['UserFlags'], &block)
end
def set_userflags(*flags)
op_userflags(*flags) { |userflags, flag| userflags | ADS_USERFLAGS[flag] }
end
def unset_userflags(*flags)
op_userflags(*flags) { |userflags, flag| userflags & ~ADS_USERFLAGS[flag] }
end
def disabled?
userflag_set?(:ADS_UF_ACCOUNTDISABLE)
end
def locked_out?
# Note that the LOCKOUT flag is known to be inaccurate when using the
# LDAP IADsUser provider, but this class consistently uses the WinNT
# provider, which is expected to be accurate.
userflag_set?(:ADS_UF_LOCKOUT)
end
def expired?
expires = native_object.Get('AccountExpirationDate')
expires && expires < Time.now
rescue WIN32OLERuntimeError => e
# This OLE error code indicates the property can't be found in the cache
raise e unless e.message =~ /8000500D/m
false
end
# UNLEN from lmcons.h - https://stackoverflow.com/a/2155176
MAX_USERNAME_LENGTH = 256
def self.current_user_name
user_name = ''.dup
max_length = MAX_USERNAME_LENGTH + 1 # NULL terminated
FFI::MemoryPointer.new(max_length * 2) do |buffer| # wide string
FFI::MemoryPointer.new(:dword, 1) do |buffer_size|
buffer_size.write_dword(max_length) # length in TCHARs
if GetUserNameW(buffer, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get user name")
end
# buffer_size includes trailing NULL
user_name = buffer.read_wide_string(buffer_size.read_dword - 1)
end
end
user_name
end
# https://docs.microsoft.com/en-us/windows/win32/api/secext/ne-secext-extended_name_format
NameUnknown = 0
NameFullyQualifiedDN = 1
NameSamCompatible = 2
NameDisplay = 3
NameUniqueId = 6
NameCanonical = 7
NameUserPrincipal = 8
NameCanonicalEx = 9
NameServicePrincipal = 10
NameDnsDomain = 12
NameGivenName = 13
NameSurname = 14
def self.current_user_name_with_format(format)
user_name = ''.dup
max_length = 1024
FFI::MemoryPointer.new(:lpwstr, max_length * 2 + 1) do |buffer|
FFI::MemoryPointer.new(:dword, 1) do |buffer_size|
buffer_size.write_dword(max_length + 1)
if GetUserNameExW(format.to_i, buffer, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error.new(_("Failed to get user name"), FFI.errno)
end
user_name = buffer.read_wide_string(buffer_size.read_dword).chomp
end
end
user_name
end
def self.current_sam_compatible_user_name
current_user_name_with_format(NameSamCompatible)
end
def self.current_user_sid
Puppet::Util::Windows::SID.name_to_principal(current_user_name)
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724432(v=vs.85).aspx
# BOOL WINAPI GetUserName(
# _Out_ LPTSTR lpBuffer,
# _Inout_ LPDWORD lpnSize
# );
ffi_lib :advapi32
attach_function_private :GetUserNameW,
[:lpwstr, :lpdword], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/secext/nf-secext-getusernameexa
# BOOLEAN SEC_ENTRY GetUserNameExA(
# EXTENDED_NAME_FORMAT NameFormat,
# LPSTR lpNameBuffer,
# PULONG nSize
# );type
ffi_lib :secur32
attach_function_private :GetUserNameExW, [:uint16, :lpwstr, :pointer], :win32_bool
end
class UserProfile
def self.delete(sid)
Puppet::Util::Windows::ADSI.wmi_connection.Delete("Win32_UserProfile.SID='#{sid}'")
rescue WIN32OLERuntimeError => e
# https://social.technet.microsoft.com/Forums/en/ITCG/thread/0f190051-ac96-4bf1-a47f-6b864bfacee5
# Prior to Vista SP1, there's no built-in way to programmatically
# delete user profiles (except for delprof.exe). So try to delete
# but warn if we fail
raise e unless e.message.include?('80041010')
Puppet.warning _("Cannot delete user profile for '%{sid}' prior to Vista SP1") % { sid: sid }
end
end
class Group < ADSIObject
# https://msdn.microsoft.com/en-us/library/aa706021.aspx
# IADsGroup interface
@object_class = 'group'
class << self
def list_all
Puppet::Util::Windows::ADSI.execquery('select name from win32_group where localaccount = "TRUE"')
end
def create(name)
# Windows error 2224: The account already exists.
raise Puppet::Error, _("Cannot create group if user '%{name}' exists.") % { name: name } if Puppet::Util::Windows::ADSI::User.exists?(name)
new(name, Puppet::Util::Windows::ADSI.create(name, @object_class))
end
end
def add_member_sids(*sids)
sids.each do |sid|
native_object.Add(Puppet::Util::Windows::ADSI.sid_uri(sid))
end
end
def remove_member_sids(*sids)
sids.each do |sid|
native_object.Remove(Puppet::Util::Windows::ADSI.sid_uri(sid))
end
end
# returns Puppet::Util::Windows::SID::Principal[]
# may contain objects that represent unresolvable SIDs
# qualified account names are returned by calling #domain_account
def members
self.class.get_sids(native_object.Members)
end
alias member_sids members
def set_members(desired_members, inclusive = true)
return if desired_members.nil?
current_hash = member_sids.to_h { |sid| [sid.sid, sid] }
desired_hash = self.class.name_sid_hash(desired_members)
# First we add all missing members
unless desired_hash.empty?
members_to_add = (desired_hash.keys - current_hash.keys).map { |sid| desired_hash[sid] }
add_member_sids(*members_to_add)
end
# Then we remove all extra members if inclusive
if inclusive
if desired_hash.empty?
members_to_remove = current_hash.values
else
members_to_remove = (current_hash.keys - desired_hash.keys).map { |sid| current_hash[sid] }
end
remove_member_sids(*members_to_remove)
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/util/windows/sid.rb | lib/puppet/util/windows/sid.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
module Puppet::Util::Windows
module SID
require 'ffi'
extend FFI::Library
# missing from Windows::Error
ERROR_NONE_MAPPED = 1332
ERROR_INVALID_SID_STRUCTURE = 1337
ERROR_TRUSTED_DOMAIN_FAILURE = 1788
ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789
# Well Known SIDs
Null = 'S-1-0'
Nobody = 'S-1-0-0'
World = 'S-1-1'
Everyone = 'S-1-1-0'
Local = 'S-1-2'
Creator = 'S-1-3'
CreatorOwner = 'S-1-3-0'
CreatorGroup = 'S-1-3-1'
CreatorOwnerServer = 'S-1-3-2'
CreatorGroupServer = 'S-1-3-3'
NonUnique = 'S-1-4'
Nt = 'S-1-5'
Dialup = 'S-1-5-1'
Network = 'S-1-5-2'
Batch = 'S-1-5-3'
Interactive = 'S-1-5-4'
Service = 'S-1-5-6'
Anonymous = 'S-1-5-7'
Proxy = 'S-1-5-8'
EnterpriseDomainControllers = 'S-1-5-9'
PrincipalSelf = 'S-1-5-10'
AuthenticatedUsers = 'S-1-5-11'
RestrictedCode = 'S-1-5-12'
TerminalServerUsers = 'S-1-5-13'
LocalSystem = 'S-1-5-18'
NtLocal = 'S-1-5-19'
NtNetwork = 'S-1-5-20'
BuiltinAdministrators = 'S-1-5-32-544'
BuiltinUsers = 'S-1-5-32-545'
Guests = 'S-1-5-32-546'
PowerUsers = 'S-1-5-32-547'
AccountOperators = 'S-1-5-32-548'
ServerOperators = 'S-1-5-32-549'
PrintOperators = 'S-1-5-32-550'
BackupOperators = 'S-1-5-32-551'
Replicators = 'S-1-5-32-552'
AllAppPackages = 'S-1-15-2-1'
# Convert an account name, e.g. 'Administrators' into a SID string,
# e.g. 'S-1-5-32-544'. The name can be specified as 'Administrators',
# 'BUILTIN\Administrators', or 'S-1-5-32-544', and will return the
# SID. Returns nil if the account doesn't exist.
def name_to_sid(name)
sid = name_to_principal(name)
sid ? sid.sid : nil
end
module_function :name_to_sid
# Convert an account name, e.g. 'Administrators' into a Principal::SID object,
# e.g. 'S-1-5-32-544'. The name can be specified as 'Administrators',
# 'BUILTIN\Administrators', or 'S-1-5-32-544', and will return the
# SID object. Returns nil if the account doesn't exist.
# This method returns a SID::Principal with the account, domain, SID, etc
def name_to_principal(name, allow_unresolved = false)
# Apparently, we accept a symbol..
name = name.to_s.strip if name
# if name is a SID string, convert it to raw bytes for use with lookup_account_sid
raw_sid_bytes = nil
begin
string_to_sid_ptr(name) do |sid_ptr|
raw_sid_bytes = sid_ptr.read_array_of_uchar(get_length_sid(sid_ptr))
end
rescue => e
# Avoid debug logs pollution with valid account names
# https://docs.microsoft.com/en-us/windows/win32/api/sddl/nf-sddl-convertstringsidtosidw#return-value
Puppet.debug("Could not retrieve raw SID bytes from '#{name}': #{e.message}") unless e.code == ERROR_INVALID_SID_STRUCTURE
end
raw_sid_bytes ? Principal.lookup_account_sid(raw_sid_bytes) : Principal.lookup_account_name(name)
rescue => e
Puppet.debug(e.message.to_s)
(allow_unresolved && raw_sid_bytes) ? unresolved_principal(name, raw_sid_bytes) : nil
end
module_function :name_to_principal
class << self; alias name_to_sid_object name_to_principal; end
# Converts an octet string array of bytes to a SID::Principal object,
# e.g. [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0] is the representation for
# S-1-5-18, the local 'SYSTEM' account.
# Raises an Error for nil or non-array input.
# This method returns a SID::Principal with the account, domain, SID, etc
def octet_string_to_principal(bytes)
if !bytes || !bytes.respond_to?('pack') || bytes.empty?
raise Puppet::Util::Windows::Error, _("Octet string must be an array of bytes")
end
Principal.lookup_account_sid(bytes)
end
module_function :octet_string_to_principal
class << self; alias octet_string_to_sid_object octet_string_to_principal; end
# Converts a COM instance of IAdsUser or IAdsGroup to a SID::Principal object,
# Raises an Error for nil or an object without an objectSID / Name property.
# This method returns a SID::Principal with the account, domain, SID, etc
# This method will return instances even when the SID is unresolvable, as
# may be the case when domain users have been added to local groups, but
# removed from the domain
def ads_to_principal(ads_object)
if !ads_object || !ads_object.respond_to?(:ole_respond_to?) ||
!ads_object.ole_respond_to?(:objectSID) || !ads_object.ole_respond_to?(:Name)
raise Puppet::Error, "ads_object must be an IAdsUser or IAdsGroup instance"
end
octet_string_to_principal(ads_object.objectSID)
rescue Puppet::Util::Windows::Error => e
# if the error is not a lookup / mapping problem, immediately re-raise
raise if e.code != ERROR_NONE_MAPPED
# if the Name property isn't formatted like a SID, OR
if !valid_sid?(ads_object.Name) ||
# if the objectSID doesn't match the Name property, also raise
((converted = octet_string_to_sid_string(ads_object.objectSID)) != ads_object.Name)
raise Puppet::Error.new("ads_object Name: #{ads_object.Name} invalid or does not match objectSID: #{ads_object.objectSID} (#{converted})", e)
end
unresolved_principal(ads_object.Name, ads_object.objectSID)
end
module_function :ads_to_principal
# Convert a SID string, e.g. "S-1-5-32-544" to a name,
# e.g. 'BUILTIN\Administrators'. Returns nil if an account
# for that SID does not exist.
def sid_to_name(value)
sid_bytes = []
begin
string_to_sid_ptr(value) do |ptr|
sid_bytes = ptr.read_array_of_uchar(get_length_sid(ptr))
end
rescue Puppet::Util::Windows::Error => e
raise if e.code != ERROR_INVALID_SID_STRUCTURE
end
Principal.lookup_account_sid(sid_bytes).domain_account
rescue
nil
end
module_function :sid_to_name
# https://stackoverflow.com/a/1792930 - 68 bytes, 184 characters in a string
MAXIMUM_SID_STRING_LENGTH = 184
# Convert a SID pointer to a SID string, e.g. "S-1-5-32-544".
def sid_ptr_to_string(psid)
if !psid.is_a?(FFI::Pointer) || IsValidSid(psid) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
sid_string = nil
FFI::MemoryPointer.new(:pointer, 1) do |buffer_ptr|
if ConvertSidToStringSidW(psid, buffer_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to convert binary SID")
end
buffer_ptr.read_win32_local_pointer do |wide_string_ptr|
if wide_string_ptr.null?
raise Puppet::Error, _("ConvertSidToStringSidW failed to allocate buffer for sid")
end
sid_string = wide_string_ptr.read_arbitrary_wide_string_up_to(MAXIMUM_SID_STRING_LENGTH)
end
end
sid_string
end
module_function :sid_ptr_to_string
# Convert a SID string, e.g. "S-1-5-32-544" to a pointer (containing the
# address of the binary SID structure). The returned value can be used in
# Win32 APIs that expect a PSID, e.g. IsValidSid. The account for this
# SID may or may not exist.
def string_to_sid_ptr(string_sid, &block)
FFI::MemoryPointer.from_string_to_wide_string(string_sid) do |lpcwstr|
FFI::MemoryPointer.new(:pointer, 1) do |sid_ptr_ptr|
if ConvertStringSidToSidW(lpcwstr, sid_ptr_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to convert string SID: %{string_sid}") % { string_sid: string_sid }
end
sid_ptr_ptr.read_win32_local_pointer do |sid_ptr|
yield sid_ptr
end
end
end
# yielded sid_ptr has already had LocalFree called, nothing to return
nil
end
module_function :string_to_sid_ptr
# Return true if the string is a valid SID, e.g. "S-1-5-32-544", false otherwise.
def valid_sid?(string_sid)
valid = false
begin
string_to_sid_ptr(string_sid) { |ptr| valid = !ptr.nil? && !ptr.null? }
rescue Puppet::Util::Windows::Error => e
raise if e.code != ERROR_INVALID_SID_STRUCTURE
end
valid
end
module_function :valid_sid?
def get_length_sid(sid_ptr)
# MSDN states IsValidSid should be called on pointer first
if !sid_ptr.is_a?(FFI::Pointer) || IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
GetLengthSid(sid_ptr)
end
module_function :get_length_sid
def octet_string_to_sid_string(sid_bytes)
sid_string = nil
FFI::MemoryPointer.new(:byte, sid_bytes.length) do |sid_ptr|
sid_ptr.write_array_of_uchar(sid_bytes)
sid_string = Puppet::Util::Windows::SID.sid_ptr_to_string(sid_ptr)
end
sid_string
end
module_function :octet_string_to_sid_string
# @api private
def self.unresolved_principal(name, sid_bytes)
Principal.new(
name, # account
sid_bytes, # sid_bytes
name, # sid string
nil, # domain
# https://msdn.microsoft.com/en-us/library/cc245534.aspx?f=255&MSPPError=-2147217396
# Indicates that the type of object could not be determined. For example, no object with that SID exists.
:SidTypeUnknown
)
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379151(v=vs.85).aspx
# BOOL WINAPI IsValidSid(
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :IsValidSid,
[:pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376399(v=vs.85).aspx
# BOOL ConvertSidToStringSid(
# _In_ PSID Sid,
# _Out_ LPTSTR *StringSid
# );
ffi_lib :advapi32
attach_function_private :ConvertSidToStringSidW,
[:pointer, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376402(v=vs.85).aspx
# BOOL WINAPI ConvertStringSidToSid(
# _In_ LPCTSTR StringSid,
# _Out_ PSID *Sid
# );
ffi_lib :advapi32
attach_function_private :ConvertStringSidToSidW,
[:lpcwstr, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa446642(v=vs.85).aspx
# DWORD WINAPI GetLengthSid(
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :GetLengthSid, [:pointer], :dword
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/util/windows/com.rb | lib/puppet/util/windows/com.rb | # frozen_string_literal: true
require 'ffi'
module Puppet::Util::Windows::COM
extend FFI::Library
ffi_convention :stdcall
S_OK = 0
S_FALSE = 1
def SUCCEEDED(hr) hr >= 0 end
def FAILED(hr) hr < 0 end
module_function :SUCCEEDED, :FAILED
def raise_if_hresult_failed(name, *args)
failed = FAILED(result = send(name, *args)) and raise _("%{name} failed (hresult %{result}).") % { name: name, result: format('%#08x', result) }
result
ensure
yield failed if block_given?
end
module_function :raise_if_hresult_failed
CLSCTX_INPROC_SERVER = 0x1
CLSCTX_INPROC_HANDLER = 0x2
CLSCTX_LOCAL_SERVER = 0x4
CLSCTX_INPROC_SERVER16 = 0x8
CLSCTX_REMOTE_SERVER = 0x10
CLSCTX_INPROC_HANDLER16 = 0x20
CLSCTX_RESERVED1 = 0x40
CLSCTX_RESERVED2 = 0x80
CLSCTX_RESERVED3 = 0x100
CLSCTX_RESERVED4 = 0x200
CLSCTX_NO_CODE_DOWNLOAD = 0x400
CLSCTX_RESERVED5 = 0x800
CLSCTX_NO_CUSTOM_MARSHAL = 0x1000
CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000
CLSCTX_NO_FAILURE_LOG = 0x4000
CLSCTX_DISABLE_AAA = 0x8000
CLSCTX_ENABLE_AAA = 0x10000
CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000
CLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000
CLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000
CLSCTX_ENABLE_CLOAKING = 0x100000
CLSCTX_PS_DLL = -0x80000000
CLSCTX_INPROC = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER
CLSCTX_ALL = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER
CLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx
# HRESULT CoCreateInstance(
# _In_ REFCLSID rclsid,
# _In_ LPUNKNOWN pUnkOuter,
# _In_ DWORD dwClsContext,
# _In_ REFIID riid,
# _Out_ LPVOID *ppv
# );
ffi_lib :ole32
attach_function_private :CoCreateInstance,
[:pointer, :lpunknown, :dword, :pointer, :lpvoid], :hresult
# code modified from Unknownr project https://github.com/rpeev/Unknownr
# licensed under MIT
module Interface
def self.[](*args)
spec, iid, *ifaces = args.reverse
spec.each { |_name, signature| signature[0].unshift(:pointer) }
Class.new(FFI::Struct) do
const_set(:IID, iid)
vtable = Class.new(FFI::Struct) do
vtable_hash = (ifaces.map { |iface| iface::VTBL::SPEC.to_a } << spec.to_a).flatten(1).to_h
const_set(:SPEC, vtable_hash)
layout(
*self::SPEC.map { |name, signature| [name, callback(*signature)] }.flatten
)
end
const_set(:VTBL, vtable)
layout \
:lpVtbl, :pointer
end
end
end
module Helpers
def QueryInstance(klass)
instance = nil
FFI::MemoryPointer.new(:pointer) do |ppv|
QueryInterface(klass::IID, ppv)
instance = klass.new(ppv.read_pointer)
end
begin
yield instance
return self
ensure
instance.Release
end if block_given?
instance
end
def UseInstance(klass, name, *args)
instance = nil
FFI::MemoryPointer.new(:pointer) do |ppv|
send(name, *args, ppv)
yield instance = klass.new(ppv.read_pointer)
end
self
ensure
instance.Release if instance && !instance.null?
end
end
module Instance
def self.[](iface)
Class.new(iface) do
send(:include, Helpers)
def initialize(pointer)
self.pointer = pointer
@vtbl = self.class::VTBL.new(self[:lpVtbl])
end
attr_reader :vtbl
self::VTBL.members.each do |name|
define_method(name) do |*args|
if Puppet::Util::Windows::COM.FAILED((result = @vtbl[name].call(self, *args)))
raise Puppet::Util::Windows::Error.new(_("Failed to call %{klass}::%{name} with HRESULT: %{result}.") % { klass: self, name: name, result: result }, result)
end
result
end
end
layout \
:lpVtbl, :pointer
end
end
end
module Factory
def self.[](iface, clsid)
Class.new(iface) do
send(:include, Helpers)
const_set(:CLSID, clsid)
def initialize(opts = {})
@opts = opts
@opts[:clsctx] ||= CLSCTX_INPROC_SERVER
FFI::MemoryPointer.new(:pointer) do |ppv|
hr = Puppet::Util::Windows::COM.CoCreateInstance(self.class::CLSID, FFI::Pointer::NULL, @opts[:clsctx], self.class::IID, ppv)
if Puppet::Util::Windows::COM.FAILED(hr)
raise _("CoCreateInstance failed (%{klass}).") % { klass: self.class }
end
self.pointer = ppv.read_pointer
end
@vtbl = self.class::VTBL.new(self[:lpVtbl])
end
attr_reader :vtbl
self::VTBL.members.each do |name|
define_method(name) do |*args|
if Puppet::Util::Windows::COM.FAILED((result = @vtbl[name].call(self, *args)))
raise Puppet::Util::Windows::Error.new(_("Failed to call %{klass}::%{name} with HRESULT: %{result}.") % { klass: self, name: name, result: result }, result)
end
result
end
end
layout \
:lpVtbl, :pointer
end
end
end
IUnknown = Interface[
FFI::WIN32::GUID['00000000-0000-0000-C000-000000000046'],
QueryInterface: [[:pointer, :pointer], :hresult],
AddRef: [[], :win32_ulong],
Release: [[], :win32_ulong]
]
Unknown = Instance[IUnknown]
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms678543(v=vs.85).aspx
# HRESULT CoInitialize(
# _In_opt_ LPVOID pvReserved
# );
ffi_lib :ole32
attach_function_private :CoInitialize, [:lpvoid], :hresult
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms688715(v=vs.85).aspx
# void CoUninitialize(void);
ffi_lib :ole32
attach_function_private :CoUninitialize, [], :void
def InitializeCom
raise_if_hresult_failed(:CoInitialize, FFI::Pointer::NULL)
at_exit { CoUninitialize() }
end
module_function :InitializeCom
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/user.rb | lib/puppet/util/windows/user.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
require 'ffi'
module Puppet::Util::Windows::User
extend Puppet::Util::Windows::String
extend FFI::Library
def admin?
return false unless check_token_membership
# if Vista or later, check for unrestricted process token
elevated_supported = Puppet::Util::Windows::Process.supports_elevated_security?
elevated_supported ? Puppet::Util::Windows::Process.elevated_security? : true
end
module_function :admin?
# The name of the account in all locales is `LocalSystem`. `.\LocalSystem` or `ComputerName\LocalSystem' can also be used.
# This account is not recognized by the security subsystem, so you cannot specify its name in a call to the `LookupAccountName` function.
# https://docs.microsoft.com/en-us/windows/win32/services/localsystem-account
def localsystem?(name)
["LocalSystem", ".\\LocalSystem", "#{Puppet::Util::Windows::ADSI.computer_name}\\LocalSystem"].any? { |s| s.casecmp(name) == 0 }
end
module_function :localsystem?
# Check if a given user is one of the default system accounts
# These accounts do not have a password and all checks done through logon attempt will fail
# https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/local-accounts#default-local-system-accounts
def default_system_account?(name)
user_sid = Puppet::Util::Windows::SID.name_to_sid(name)
[Puppet::Util::Windows::SID::LocalSystem, Puppet::Util::Windows::SID::NtLocal, Puppet::Util::Windows::SID::NtNetwork].include?(user_sid)
end
module_function :default_system_account?
# https://msdn.microsoft.com/en-us/library/windows/desktop/ee207397(v=vs.85).aspx
SECURITY_MAX_SID_SIZE = 68
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx
# These error codes indicate successful authentication but failure to
# logon for a separate reason
ERROR_ACCOUNT_RESTRICTION = 1327
ERROR_INVALID_LOGON_HOURS = 1328
ERROR_INVALID_WORKSTATION = 1329
ERROR_ACCOUNT_DISABLED = 1331
def check_token_membership
is_admin = false
FFI::MemoryPointer.new(:byte, SECURITY_MAX_SID_SIZE) do |sid_pointer|
FFI::MemoryPointer.new(:dword, 1) do |size_pointer|
size_pointer.write_uint32(SECURITY_MAX_SID_SIZE)
if CreateWellKnownSid(:WinBuiltinAdministratorsSid, FFI::Pointer::NULL, sid_pointer, size_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to create administrators SID")
end
end
if IsValidSid(sid_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
FFI::MemoryPointer.new(:win32_bool, 1) do |ismember_pointer|
if CheckTokenMembership(FFI::Pointer::NULL_HANDLE, sid_pointer, ismember_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to check membership")
end
# Is administrators SID enabled in calling thread's access token?
is_admin = ismember_pointer.read_win32_bool
end
end
is_admin
end
module_function :check_token_membership
def password_is?(name, password, domain = '.')
logon_user(name, password, domain) { |token| }
rescue Puppet::Util::Windows::Error => detail
authenticated_error_codes = Set[
ERROR_ACCOUNT_RESTRICTION,
ERROR_INVALID_LOGON_HOURS,
ERROR_INVALID_WORKSTATION,
ERROR_ACCOUNT_DISABLED,
]
authenticated_error_codes.include?(detail.code)
end
module_function :password_is?
def logon_user(name, password, domain = '.', &block)
fLOGON32_PROVIDER_DEFAULT = 0
fLOGON32_LOGON_INTERACTIVE = 2
fLOGON32_LOGON_NETWORK = 3
token = nil
begin
FFI::MemoryPointer.new(:handle, 1) do |token_pointer|
# try logon using network else try logon using interactive mode
if logon_user_by_logon_type(name, domain, password, fLOGON32_LOGON_NETWORK, fLOGON32_PROVIDER_DEFAULT, token_pointer) == FFI::WIN32_FALSE
if logon_user_by_logon_type(name, domain, password, fLOGON32_LOGON_INTERACTIVE, fLOGON32_PROVIDER_DEFAULT, token_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to logon user %{name}") % { name: name.inspect }
end
end
yield token = token_pointer.read_handle
end
ensure
FFI::WIN32.CloseHandle(token) if token
end
# token has been closed by this point
true
end
module_function :logon_user
def self.logon_user_by_logon_type(name, domain, password, logon_type, logon_provider, token)
LogonUserW(wide_string(name), wide_string(domain), password.nil? ? FFI::Pointer::NULL : wide_string(password), logon_type, logon_provider, token)
end
private_class_method :logon_user_by_logon_type
def load_profile(user, password)
logon_user(user, password) do |token|
FFI::MemoryPointer.from_string_to_wide_string(user) do |lpUserName|
pi = PROFILEINFO.new
pi[:dwSize] = PROFILEINFO.size
pi[:dwFlags] = 1 # PI_NOUI - prevents display of profile error msgs
pi[:lpUserName] = lpUserName
# Load the profile. Since it doesn't exist, it will be created
if LoadUserProfileW(token, pi.pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to load user profile %{user}") % { user: user.inspect }
end
Puppet.debug("Loaded profile for #{user}")
if UnloadUserProfile(token, pi[:hProfile]) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to unload user profile %{user}") % { user: user.inspect }
end
end
end
end
module_function :load_profile
def get_rights(name)
user_info = Puppet::Util::Windows::SID.name_to_principal(name.sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\"))
return "" unless user_info
rights = []
rights_pointer = FFI::MemoryPointer.new(:pointer)
number_of_rights = FFI::MemoryPointer.new(:ulong)
sid_pointer = FFI::MemoryPointer.new(:byte, user_info.sid_bytes.length).write_array_of_uchar(user_info.sid_bytes)
new_lsa_policy_handle do |policy_handle|
result = LsaEnumerateAccountRights(policy_handle.read_pointer, sid_pointer, rights_pointer, number_of_rights)
check_lsa_nt_status_and_raise_failures(result, "LsaEnumerateAccountRights")
end
number_of_rights.read_ulong.times do |index|
right = LSA_UNICODE_STRING.new(rights_pointer.read_pointer + index * LSA_UNICODE_STRING.size)
rights << right[:Buffer].read_arbitrary_wide_string_up_to
end
result = LsaFreeMemory(rights_pointer.read_pointer)
check_lsa_nt_status_and_raise_failures(result, "LsaFreeMemory")
rights.join(",")
end
module_function :get_rights
def set_rights(name, rights)
rights_pointer = new_lsa_unicode_strings_pointer(rights)
user_info = Puppet::Util::Windows::SID.name_to_principal(name.sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\"))
sid_pointer = FFI::MemoryPointer.new(:byte, user_info.sid_bytes.length).write_array_of_uchar(user_info.sid_bytes)
new_lsa_policy_handle do |policy_handle|
result = LsaAddAccountRights(policy_handle.read_pointer, sid_pointer, rights_pointer, rights.size)
check_lsa_nt_status_and_raise_failures(result, "LsaAddAccountRights")
end
end
module_function :set_rights
def remove_rights(name, rights)
rights_pointer = new_lsa_unicode_strings_pointer(rights)
user_info = Puppet::Util::Windows::SID.name_to_principal(name.sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\"))
sid_pointer = FFI::MemoryPointer.new(:byte, user_info.sid_bytes.length).write_array_of_uchar(user_info.sid_bytes)
new_lsa_policy_handle do |policy_handle|
result = LsaRemoveAccountRights(policy_handle.read_pointer, sid_pointer, false, rights_pointer, rights.size)
check_lsa_nt_status_and_raise_failures(result, "LsaRemoveAccountRights")
end
end
module_function :remove_rights
# ACCESS_MASK flags for Policy Objects
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-lsad/b61b7268-987a-420b-84f9-6c75f8dc8558
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002
POLICY_GET_PRIVATE_INFORMATION = 0x00000004
POLICY_TRUST_ADMIN = 0x00000008
POLICY_CREATE_ACCOUNT = 0x00000010
POLICY_CREATE_SECRET = 0x00000020
POLICY_CREATE_PRIVILEGE = 0x00000040
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100
POLICY_AUDIT_LOG_ADMIN = 0x00000200
POLICY_SERVER_ADMIN = 0x00000400
POLICY_LOOKUP_NAMES = 0x00000800
POLICY_NOTIFICATION = 0x00001000
def self.new_lsa_policy_handle
access = 0
access |= POLICY_LOOKUP_NAMES
access |= POLICY_CREATE_ACCOUNT
policy_handle = FFI::MemoryPointer.new(:pointer)
result = LsaOpenPolicy(nil, LSA_OBJECT_ATTRIBUTES.new, access, policy_handle)
check_lsa_nt_status_and_raise_failures(result, "LsaOpenPolicy")
begin
yield policy_handle
ensure
result = LsaClose(policy_handle.read_pointer)
check_lsa_nt_status_and_raise_failures(result, "LsaClose")
end
end
private_class_method :new_lsa_policy_handle
def self.new_lsa_unicode_strings_pointer(strings)
lsa_unicode_strings_pointer = FFI::MemoryPointer.new(LSA_UNICODE_STRING, strings.size)
strings.each_with_index do |string, index|
lsa_string = LSA_UNICODE_STRING.new(lsa_unicode_strings_pointer + index * LSA_UNICODE_STRING.size)
lsa_string[:Buffer] = FFI::MemoryPointer.from_string(wide_string(string))
lsa_string[:Length] = string.length * 2
lsa_string[:MaximumLength] = lsa_string[:Length] + 2
end
lsa_unicode_strings_pointer
end
private_class_method :new_lsa_unicode_strings_pointer
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
def self.check_lsa_nt_status_and_raise_failures(status, method_name)
error_code = LsaNtStatusToWinError(status)
error_reason = case error_code.to_s(16)
when '0' # ERROR_SUCCESS
return # Method call succeded
when '2' # ERROR_FILE_NOT_FOUND
return # No rights/privilleges assigned to given user
when '5' # ERROR_ACCESS_DENIED
"Access is denied. Please make sure that puppet is running as administrator."
when '521' # ERROR_NO_SUCH_PRIVILEGE
"One or more of the given rights/privilleges are incorrect."
when '6ba' # RPC_S_SERVER_UNAVAILABLE
"The RPC server is unavailable or given domain name is invalid."
end
raise Puppet::Error, "Calling `#{method_name}` returned 'Win32 Error Code 0x%08X'. #{error_reason}" % error_code
end
private_class_method :check_lsa_nt_status_and_raise_failures
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
# BOOL LogonUser(
# _In_ LPTSTR lpszUsername,
# _In_opt_ LPTSTR lpszDomain,
# _In_opt_ LPTSTR lpszPassword,
# _In_ DWORD dwLogonType,
# _In_ DWORD dwLogonProvider,
# _Out_ PHANDLE phToken
# );
ffi_lib :advapi32
attach_function_private :LogonUserW,
[:lpwstr, :lpwstr, :lpwstr, :dword, :dword, :phandle], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb773378(v=vs.85).aspx
# typedef struct _PROFILEINFO {
# DWORD dwSize;
# DWORD dwFlags;
# LPTSTR lpUserName;
# LPTSTR lpProfilePath;
# LPTSTR lpDefaultPath;
# LPTSTR lpServerName;
# LPTSTR lpPolicyPath;
# HANDLE hProfile;
# } PROFILEINFO, *LPPROFILEINFO;
# technically
# NOTE: that for structs, buffer_* (lptstr alias) cannot be used
class PROFILEINFO < FFI::Struct
layout :dwSize, :dword,
:dwFlags, :dword,
:lpUserName, :pointer,
:lpProfilePath, :pointer,
:lpDefaultPath, :pointer,
:lpServerName, :pointer,
:lpPolicyPath, :pointer,
:hProfile, :handle
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb762281(v=vs.85).aspx
# BOOL WINAPI LoadUserProfile(
# _In_ HANDLE hToken,
# _Inout_ LPPROFILEINFO lpProfileInfo
# );
ffi_lib :userenv
attach_function_private :LoadUserProfileW,
[:handle, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb762282(v=vs.85).aspx
# BOOL WINAPI UnloadUserProfile(
# _In_ HANDLE hToken,
# _In_ HANDLE hProfile
# );
ffi_lib :userenv
attach_function_private :UnloadUserProfile,
[:handle, :handle], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85).aspx
# BOOL WINAPI CheckTokenMembership(
# _In_opt_ HANDLE TokenHandle,
# _In_ PSID SidToCheck,
# _Out_ PBOOL IsMember
# );
ffi_lib :advapi32
attach_function_private :CheckTokenMembership,
[:handle, :pointer, :pbool], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379650(v=vs.85).aspx
# rubocop:disable Layout/SpaceBeforeComma
WELL_KNOWN_SID_TYPE = enum(
:WinNullSid , 0,
:WinWorldSid , 1,
:WinLocalSid , 2,
:WinCreatorOwnerSid , 3,
:WinCreatorGroupSid , 4,
:WinCreatorOwnerServerSid , 5,
:WinCreatorGroupServerSid , 6,
:WinNtAuthoritySid , 7,
:WinDialupSid , 8,
:WinNetworkSid , 9,
:WinBatchSid , 10,
:WinInteractiveSid , 11,
:WinServiceSid , 12,
:WinAnonymousSid , 13,
:WinProxySid , 14,
:WinEnterpriseControllersSid , 15,
:WinSelfSid , 16,
:WinAuthenticatedUserSid , 17,
:WinRestrictedCodeSid , 18,
:WinTerminalServerSid , 19,
:WinRemoteLogonIdSid , 20,
:WinLogonIdsSid , 21,
:WinLocalSystemSid , 22,
:WinLocalServiceSid , 23,
:WinNetworkServiceSid , 24,
:WinBuiltinDomainSid , 25,
:WinBuiltinAdministratorsSid , 26,
:WinBuiltinUsersSid , 27,
:WinBuiltinGuestsSid , 28,
:WinBuiltinPowerUsersSid , 29,
:WinBuiltinAccountOperatorsSid , 30,
:WinBuiltinSystemOperatorsSid , 31,
:WinBuiltinPrintOperatorsSid , 32,
:WinBuiltinBackupOperatorsSid , 33,
:WinBuiltinReplicatorSid , 34,
:WinBuiltinPreWindows2000CompatibleAccessSid , 35,
:WinBuiltinRemoteDesktopUsersSid , 36,
:WinBuiltinNetworkConfigurationOperatorsSid , 37,
:WinAccountAdministratorSid , 38,
:WinAccountGuestSid , 39,
:WinAccountKrbtgtSid , 40,
:WinAccountDomainAdminsSid , 41,
:WinAccountDomainUsersSid , 42,
:WinAccountDomainGuestsSid , 43,
:WinAccountComputersSid , 44,
:WinAccountControllersSid , 45,
:WinAccountCertAdminsSid , 46,
:WinAccountSchemaAdminsSid , 47,
:WinAccountEnterpriseAdminsSid , 48,
:WinAccountPolicyAdminsSid , 49,
:WinAccountRasAndIasServersSid , 50,
:WinNTLMAuthenticationSid , 51,
:WinDigestAuthenticationSid , 52,
:WinSChannelAuthenticationSid , 53,
:WinThisOrganizationSid , 54,
:WinOtherOrganizationSid , 55,
:WinBuiltinIncomingForestTrustBuildersSid , 56,
:WinBuiltinPerfMonitoringUsersSid , 57,
:WinBuiltinPerfLoggingUsersSid , 58,
:WinBuiltinAuthorizationAccessSid , 59,
:WinBuiltinTerminalServerLicenseServersSid , 60,
:WinBuiltinDCOMUsersSid , 61,
:WinBuiltinIUsersSid , 62,
:WinIUserSid , 63,
:WinBuiltinCryptoOperatorsSid , 64,
:WinUntrustedLabelSid , 65,
:WinLowLabelSid , 66,
:WinMediumLabelSid , 67,
:WinHighLabelSid , 68,
:WinSystemLabelSid , 69,
:WinWriteRestrictedCodeSid , 70,
:WinCreatorOwnerRightsSid , 71,
:WinCacheablePrincipalsGroupSid , 72,
:WinNonCacheablePrincipalsGroupSid , 73,
:WinEnterpriseReadonlyControllersSid , 74,
:WinAccountReadonlyControllersSid , 75,
:WinBuiltinEventLogReadersGroup , 76,
:WinNewEnterpriseReadonlyControllersSid , 77,
:WinBuiltinCertSvcDComAccessGroup , 78,
:WinMediumPlusLabelSid , 79,
:WinLocalLogonSid , 80,
:WinConsoleLogonSid , 81,
:WinThisOrganizationCertificateSid , 82,
:WinApplicationPackageAuthoritySid , 83,
:WinBuiltinAnyPackageSid , 84,
:WinCapabilityInternetClientSid , 85,
:WinCapabilityInternetClientServerSid , 86,
:WinCapabilityPrivateNetworkClientServerSid , 87,
:WinCapabilityPicturesLibrarySid , 88,
:WinCapabilityVideosLibrarySid , 89,
:WinCapabilityMusicLibrarySid , 90,
:WinCapabilityDocumentsLibrarySid , 91,
:WinCapabilitySharedUserCertificatesSid , 92,
:WinCapabilityEnterpriseAuthenticationSid , 93,
:WinCapabilityRemovableStorageSid , 94
)
# rubocop:enable Layout/SpaceBeforeComma
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa446585(v=vs.85).aspx
# BOOL WINAPI CreateWellKnownSid(
# _In_ WELL_KNOWN_SID_TYPE WellKnownSidType,
# _In_opt_ PSID DomainSid,
# _Out_opt_ PSID pSid,
# _Inout_ DWORD *cbSid
# );
ffi_lib :advapi32
attach_function_private :CreateWellKnownSid,
[WELL_KNOWN_SID_TYPE, :pointer, :pointer, :lpdword], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379151(v=vs.85).aspx
# BOOL WINAPI IsValidSid(
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :IsValidSid,
[:pointer], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/lsalookup/ns-lsalookup-lsa_object_attributes
# typedef struct _LSA_OBJECT_ATTRIBUTES {
# ULONG Length;
# HANDLE RootDirectory;
# PLSA_UNICODE_STRING ObjectName;
# ULONG Attributes;
# PVOID SecurityDescriptor;
# PVOID SecurityQualityOfService;
# } LSA_OBJECT_ATTRIBUTES, *PLSA_OBJECT_ATTRIBUTES;
class LSA_OBJECT_ATTRIBUTES < FFI::Struct
layout :Length, :ulong,
:RootDirectory, :handle,
:ObjectName, :plsa_unicode_string,
:Attributes, :ulong,
:SecurityDescriptor, :pvoid,
:SecurityQualityOfService, :pvoid
end
# https://docs.microsoft.com/en-us/windows/win32/api/lsalookup/ns-lsalookup-lsa_unicode_string
# typedef struct _LSA_UNICODE_STRING {
# USHORT Length;
# USHORT MaximumLength;
# PWSTR Buffer;
# } LSA_UNICODE_STRING, *PLSA_UNICODE_STRING;
class LSA_UNICODE_STRING < FFI::Struct
layout :Length, :ushort,
:MaximumLength, :ushort,
:Buffer, :pwstr
end
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaenumerateaccountrights
# https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment
# NTSTATUS LsaEnumerateAccountRights(
# LSA_HANDLE PolicyHandle,
# PSID AccountSid,
# PLSA_UNICODE_STRING *UserRights,
# PULONG CountOfRights
# );
ffi_lib :advapi32
attach_function_private :LsaEnumerateAccountRights,
[:lsa_handle, :psid, :plsa_unicode_string, :pulong], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaaddaccountrights
# NTSTATUS LsaAddAccountRights(
# LSA_HANDLE PolicyHandle,
# PSID AccountSid,
# PLSA_UNICODE_STRING UserRights,
# ULONG CountOfRights
# );
ffi_lib :advapi32
attach_function_private :LsaAddAccountRights,
[:lsa_handle, :psid, :plsa_unicode_string, :ulong], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaremoveaccountrights
# NTSTATUS LsaRemoveAccountRights(
# LSA_HANDLE PolicyHandle,
# PSID AccountSid,
# BOOLEAN AllRights,
# PLSA_UNICODE_STRING UserRights,
# ULONG CountOfRights
# );
ffi_lib :advapi32
attach_function_private :LsaRemoveAccountRights,
[:lsa_handle, :psid, :bool, :plsa_unicode_string, :ulong], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaopenpolicy
# NTSTATUS LsaOpenPolicy(
# PLSA_UNICODE_STRING SystemName,
# PLSA_OBJECT_ATTRIBUTES ObjectAttributes,
# ACCESS_MASK DesiredAccess,
# PLSA_HANDLE PolicyHandle
# );
ffi_lib :advapi32
attach_function_private :LsaOpenPolicy,
[:plsa_unicode_string, :plsa_object_attributes, :access_mask, :plsa_handle], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaclose
# NTSTATUS LsaClose(
# LSA_HANDLE ObjectHandle
# );
ffi_lib :advapi32
attach_function_private :LsaClose,
[:lsa_handle], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsafreememory
# NTSTATUS LsaFreeMemory(
# PVOID Buffer
# );
ffi_lib :advapi32
attach_function_private :LsaFreeMemory,
[:pvoid], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsantstatustowinerror
# ULONG LsaNtStatusToWinError(
# NTSTATUS Status
# );
ffi_lib :advapi32
attach_function_private :LsaNtStatusToWinError,
[:ntstatus], :ulong
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/windows/monkey_patches/process.rb | lib/puppet/util/windows/monkey_patches/process.rb | # frozen_string_literal: true
require 'ffi'
require_relative '../../../../puppet/ffi/windows'
require_relative '../../../../puppet/util/windows/string'
module Process
extend FFI::Library
extend Puppet::Util::Windows::String
extend Puppet::FFI::Windows::APITypes
extend Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Constants
include Puppet::FFI::Windows::Structs
ProcessInfo = Struct.new(
'ProcessInfo',
:process_handle,
:thread_handle,
:process_id,
:thread_id
)
private_constant :ProcessInfo
# Disable popups. This mostly affects the Process.kill method.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX)
class << self
private :SetHandleInformation, :SetErrorMode, :CreateProcessW, :OpenProcess,
:SetPriorityClass, :CreateProcessWithLogonW, :get_osfhandle, :get_errno
# Process.create(key => value, ...) => ProcessInfo
#
# This is a wrapper for the CreateProcess() function. It executes a process,
# returning a ProcessInfo struct. It accepts a hash as an argument.
# There are several primary keys:
#
# * command_line (this or app_name must be present)
# * app_name (default: nil)
# * inherit (default: false)
# * process_inherit (default: false)
# * thread_inherit (default: false)
# * creation_flags (default: 0)
# * cwd (default: Dir.pwd)
# * startup_info (default: nil)
# * environment (default: nil)
# * close_handles (default: true)
# * with_logon (default: nil)
# * domain (default: nil)
# * password (default: nil, mandatory if with_logon)
#
# Of these, the 'command_line' or 'app_name' must be specified or an
# error is raised. Both may be set individually, but 'command_line' should
# be preferred if only one of them is set because it does not (necessarily)
# require an explicit path or extension to work.
#
# The 'domain' and 'password' options are only relevent in the context
# of 'with_logon'. If 'with_logon' is set, then the 'password' option is
# mandatory.
#
# The startup_info key takes a hash. Its keys are attributes that are
# part of the StartupInfo struct, and are generally only meaningful for
# GUI or console processes. See the documentation on CreateProcess()
# and the StartupInfo struct on MSDN for more information.
#
# * desktop
# * title
# * x
# * y
# * x_size
# * y_size
# * x_count_chars
# * y_count_chars
# * fill_attribute
# * sw_flags
# * startf_flags
# * stdin
# * stdout
# * stderr
#
# Note that the 'stdin', 'stdout' and 'stderr' options can be either Ruby
# IO objects or file descriptors (i.e. a fileno). However, StringIO objects
# are not currently supported. Unfortunately, setting these is not currently
# an option for JRuby.
#
# If 'stdin', 'stdout' or 'stderr' are specified, then the +inherit+ value
# is automatically set to true and the Process::STARTF_USESTDHANDLES flag is
# automatically OR'd to the +startf_flags+ value.
#
# The ProcessInfo struct contains the following members:
#
# * process_handle - The handle to the newly created process.
# * thread_handle - The handle to the primary thread of the process.
# * process_id - Process ID.
# * thread_id - Thread ID.
#
# If the 'close_handles' option is set to true (the default) then the
# process_handle and the thread_handle are automatically closed for you
# before the ProcessInfo struct is returned.
#
# If the 'with_logon' option is set, then the process runs the specified
# executable file in the security context of the specified credentials.
VALID_KEYS = %i[
app_name command_line inherit creation_flags cwd environment
startup_info thread_inherit process_inherit close_handles with_logon
domain password
].freeze
VALID_SI_KEYS = %i[
startf_flags desktop title x y x_size y_size x_count_chars
y_count_chars fill_attribute sw_flags stdin stdout stderr
].freeze
private_constant :VALID_KEYS, :VALID_SI_KEYS
def create(args)
# Validate that args is a Hash
validate_args(args)
initialize_defaults
# Validate the keys, and convert symbols and case to lowercase strings.
validate_keys(args)
# If the startup_info key is present, validate its subkeys
validate_startup_info if hash[:startup_info]
# validates that 'app_name' or 'command_line' is set
validate_command_line
if hash[:app_name] && !hash[:command_line]
hash[:command_line] = hash[:app_name]
hash[:app_name] = nil
end
# Setup stdin, stdout and stderr handlers
setup_std_handlers
if logon
create_process_with_logon
else
create_process
end
# Automatically close the process and thread handles in the
# PROCESS_INFORMATION struct unless explicitly told not to.
if hash[:close_handles]
FFI::WIN32.CloseHandle(procinfo[:hProcess])
FFI::WIN32.CloseHandle(procinfo[:hThread])
end
ProcessInfo.new(
procinfo[:hProcess],
procinfo[:hThread],
procinfo[:dwProcessId],
procinfo[:dwThreadId]
)
end
remove_method :setpriority
# Sets the priority class for the specified process id +int+.
#
# The +kind+ parameter is ignored but present for API compatibility.
# You can only retrieve process information, not process group or user
# information, so it is effectively always Process::PRIO_PROCESS.
#
# Possible +int_priority+ values are:
#
# * Process::NORMAL_PRIORITY_CLASS
# * Process::IDLE_PRIORITY_CLASS
# * Process::HIGH_PRIORITY_CLASS
# * Process::REALTIME_PRIORITY_CLASS
# * Process::BELOW_NORMAL_PRIORITY_CLASS
# * Process::ABOVE_NORMAL_PRIORITY_CLASS
def setpriority(kind, int, int_priority)
raise TypeError unless kind.is_a?(Integer)
raise TypeError unless int.is_a?(Integer)
raise TypeError unless int_priority.is_a?(Integer)
int = Process.pid if int == 0
handle = OpenProcess(PROCESS_SET_INFORMATION, 0, int)
if handle == 0
raise SystemCallError, FFI.errno, "OpenProcess"
end
begin
result = SetPriorityClass(handle, int_priority)
raise SystemCallError, FFI.errno, "SetPriorityClass" unless result
ensure
FFI::WIN32.CloseHandle(handle)
end
0
end
private
def initialize_defaults
@hash = {
app_name: nil,
creation_flags: 0,
close_handles: true
}
@si_hash = nil
@procinfo = nil
end
def validate_args(args)
raise TypeError, 'hash keyword arguments expected' unless args.is_a?(Hash)
end
def validate_keys(args)
args.each do |key, val|
key = key.to_s.to_sym
raise ArgumentError, "invalid key '#{key}'" unless VALID_KEYS.include?(key)
hash[key] = val
end
end
def validate_startup_info
hash[:startup_info].each do |key, val|
key = key.to_s.to_sym
raise ArgumentError, "invalid startup_info key '#{key}'" unless VALID_SI_KEYS.include?(key)
si_hash[key] = val
end
end
def validate_command_line
raise ArgumentError, 'command_line or app_name must be specified' unless hash[:app_name] || hash[:command_line]
end
def procinfo
@procinfo ||= PROCESS_INFORMATION.new
end
def hash
@hash ||= {}
end
def si_hash
@si_hash ||= {}
end
def app
wide_string(hash[:app_name])
end
def cmd
wide_string(hash[:command_line])
end
def cwd
wide_string(hash[:cwd])
end
def password
wide_string(hash[:password])
end
def logon
wide_string(hash[:with_logon])
end
def domain
wide_string(hash[:domain])
end
def env
env = hash[:environment]
return unless env
env = env.split(File::PATH_SEPARATOR) unless env.respond_to?(:join)
env = env.map { |e| e + 0.chr }.join('') + 0.chr
env = wide_string(env) if hash[:with_logon]
env
end
def process_security
return unless hash[:process_inherit]
process_security = SECURITY_ATTRIBUTES.new
process_security[:nLength] = SECURITY_ATTRIBUTES.size
process_security[:bInheritHandle] = 1
process_security
end
def thread_security
return unless hash[:thread_inherit]
thread_security = SECURITY_ATTRIBUTES.new
thread_security[:nLength] = SECURITY_ATTRIBUTES.size
thread_security[:bInheritHandle] = 1
thread_security
end
# Automatically handle stdin, stdout and stderr as either IO objects
# or file descriptors. This won't work for StringIO, however. It also
# will not work on JRuby because of the way it handles internal file
# descriptors.
def setup_std_handlers
%i[stdin stdout stderr].each do |io|
next unless si_hash[io]
handle = if si_hash[io].respond_to?(:fileno)
get_osfhandle(si_hash[io].fileno)
else
get_osfhandle(si_hash[io])
end
if handle == INVALID_HANDLE_VALUE
ptr = FFI::MemoryPointer.new(:int)
errno = if get_errno(ptr).zero?
ptr.read_int
else
FFI.errno
end
raise SystemCallError.new('get_osfhandle', errno)
end
# Most implementations of Ruby on Windows create inheritable
# handles by default, but some do not. RF bug #26988.
bool = SetHandleInformation(
handle,
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT
)
raise SystemCallError.new('SetHandleInformation', FFI.errno) unless bool
si_hash[io] = handle
si_hash[:startf_flags] ||= 0
si_hash[:startf_flags] |= STARTF_USESTDHANDLES
hash[:inherit] = true
end
end
def startinfo
startinfo = STARTUPINFO.new
return startinfo if si_hash.empty?
startinfo[:cb] = startinfo.size
startinfo[:lpDesktop] = si_hash[:desktop] if si_hash[:desktop]
startinfo[:lpTitle] = si_hash[:title] if si_hash[:title]
startinfo[:dwX] = si_hash[:x] if si_hash[:x]
startinfo[:dwY] = si_hash[:y] if si_hash[:y]
startinfo[:dwXSize] = si_hash[:x_size] if si_hash[:x_size]
startinfo[:dwYSize] = si_hash[:y_size] if si_hash[:y_size]
startinfo[:dwXCountChars] = si_hash[:x_count_chars] if si_hash[:x_count_chars]
startinfo[:dwYCountChars] = si_hash[:y_count_chars] if si_hash[:y_count_chars]
startinfo[:dwFillAttribute] = si_hash[:fill_attribute] if si_hash[:fill_attribute]
startinfo[:dwFlags] = si_hash[:startf_flags] if si_hash[:startf_flags]
startinfo[:wShowWindow] = si_hash[:sw_flags] if si_hash[:sw_flags]
startinfo[:cbReserved2] = 0
startinfo[:hStdInput] = si_hash[:stdin] if si_hash[:stdin]
startinfo[:hStdOutput] = si_hash[:stdout] if si_hash[:stdout]
startinfo[:hStdError] = si_hash[:stderr] if si_hash[:stderr]
startinfo
end
def create_process_with_logon
raise ArgumentError, 'password must be specified if with_logon is used' unless password
hash[:creation_flags] |= CREATE_UNICODE_ENVIRONMENT
bool = CreateProcessWithLogonW(
logon, # User
domain, # Domain
password, # Password
LOGON_WITH_PROFILE, # Logon flags
app, # App name
cmd, # Command line
hash[:creation_flags], # Creation flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
raise SystemCallError.new('CreateProcessWithLogonW', FFI.errno) unless bool
end
def create_process
inherit = hash[:inherit] ? 1 : 0
bool = CreateProcessW(
app, # App name
cmd, # Command line
process_security, # Process attributes
thread_security, # Thread attributes
inherit, # Inherit handles?
hash[:creation_flags], # Creation flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
raise SystemCallError.new('CreateProcess', FFI.errno) unless bool
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/util/package/version/range.rb | lib/puppet/util/package/version/range.rb | # frozen_string_literal: true
require_relative 'range/lt'
require_relative 'range/lt_eq'
require_relative 'range/gt'
require_relative 'range/gt_eq'
require_relative 'range/eq'
require_relative 'range/min_max'
module Puppet::Util::Package::Version
class Range
class ValidationFailure < ArgumentError; end
# Parses a version range string into a comparable {Range} instance.
#
# Currently parsed version range string may take any of the following
# forms:
#
# * Regular Version strings
# * ex. `"1.0.0"`, `"1.2.3-pre"`
# * Inequalities
# * ex. `">1.0.0"`, `"<3.2.0"`, `">=4.0.0"`
# * Range Intersections (min is always first)
# * ex. `">1.0.0 <=2.3.0"`
#
RANGE_SPLIT = /\s+/
FULL_REGEX = /\A((?:[<>=])*)(.+)\Z/
# @param range_string [String] the version range string to parse
# @param version_class [Version] a version class implementing comparison operators and parse method
# @return [Range] a new {Range} instance
# @api public
def self.parse(range_string, version_class)
raise ValidationFailure, "Unable to parse '#{range_string}' as a string" unless range_string.is_a?(String)
simples = range_string.split(RANGE_SPLIT).map do |simple|
match, operator, version = *simple.match(FULL_REGEX)
raise ValidationFailure, "Unable to parse '#{simple}' as a version range identifier" unless match
case operator
when '>'
Gt.new(version_class.parse(version))
when '>='
GtEq.new(version_class.parse(version))
when '<'
Lt.new(version_class.parse(version))
when '<='
LtEq.new(version_class.parse(version))
when ''
Eq.new(version_class.parse(version))
else
raise ValidationFailure, "Operator '#{operator}' is not implemented"
end
end
simples.size == 1 ? simples[0] : MinMax.new(simples[0], simples[1])
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/util/package/version/pip.rb | lib/puppet/util/package/version/pip.rb | # frozen_string_literal: true
module Puppet::Util::Package::Version
class Pip
include Comparable
VERSION_PATTERN = "
v?
(?:
(?:(?<epoch>[0-9]+)!)? # epoch
(?<release>[0-9]+(?:\\.[0-9]+)*) # release segment
(?<pre> # pre-release
[-_\\.]?
(?<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\\.]?
(?<pre_n>[0-9]+)?
)?
(?<post> # post release
(?:-(?<post_n1>[0-9]+))
|
(?:
[-_\\.]?
(?<post_l>post|rev|r)
[-_\\.]?
(?<post_n2>[0-9]+)?
)
)?
(?<dev> # dev release
[-_\\.]?
(?<dev_l>dev)
[-_\\.]?
(?<dev_n>[0-9]+)?
)?
)
(?:\\+(?<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))? # local version
"
def self.parse(version)
raise ValidationFailure, version.to_s unless version.is_a? String
matched = version.match(Regexp.new("^\\s*" + VERSION_PATTERN + "\\s*$", Regexp::EXTENDED | Regexp::MULTILINE | Regexp::IGNORECASE))
raise ValidationFailure, version unless matched
new(matched)
end
def self.compare(version_a, version_b)
version_a = parse(version_a) unless version_a.is_a?(self)
version_b = parse(version_b) unless version_b.is_a?(self)
version_a <=> version_b
end
def to_s
parts = []
parts.push("#{@epoch_data}!") if @epoch_data && @epoch_data != 0
parts.push(@release_data.join(".")) if @release_data
parts.push(@pre_data.join) if @pre_data
parts.push(".post#{@post_data[1]}") if @post_data
parts.push(".dev#{@dev_data[1]}") if @dev_data
parts.push("+#{@local_data.join('.')}") if @local_data
parts.join
end
alias inspect to_s
def eql?(other)
other.is_a?(self.class) && key.eql?(other.key)
end
alias == eql?
def <=>(other)
raise ValidationFailure, other.to_s unless other.is_a?(self.class)
compare(key, other.key)
end
attr_reader :key
private
def initialize(matched)
@epoch_data = matched[:epoch].to_i
@release_data = matched[:release].split('.').map(&:to_i) if matched[:release]
@pre_data = parse_letter_version(matched[:pre_l], matched[:pre_n]) if matched[:pre_l] || matched[:pre_n]
@post_data = parse_letter_version(matched[:post_l], matched[:post_n1] || matched[:post_n2]) if matched[:post_l] || matched[:post_n1] || matched[:post_n2]
@dev_data = parse_letter_version(matched[:dev_l], matched[:dev_n]) if matched[:dev_l] || matched[:dev_n]
@local_data = parse_local_version(matched[:local]) if matched[:local]
@key = compose_key(@epoch_data, @release_data, @pre_data, @post_data, @dev_data, @local_data)
end
def parse_letter_version(letter, number)
if letter
number ||= 0
letter.downcase!
if letter == "alpha"
letter = "a"
elsif letter == "beta"
letter = "b"
elsif %w[c pre preview].include?(letter)
letter = "rc"
elsif %w[rev r].include?(letter)
letter = "post"
end
return [letter, number.to_i]
end
["post", number.to_i] if !letter && number
end
def parse_local_version(local_version)
local_version.split(/[\\._-]/).map { |part| part =~ /[0-9]+/ && part !~ /[a-zA-Z]+/ ? part.to_i : part.downcase } if local_version
end
def compose_key(epoch, release, pre, post, dev, local)
release_key = release.reverse
release_key.each_with_index do |element, index|
break unless element == 0
release_key.delete_at(index) unless release_key.at(index + 1) != 0
end
release_key.reverse!
if !pre && !post && dev
pre_key = -Float::INFINITY
else
pre_key = pre || Float::INFINITY
end
post_key = post || -Float::INFINITY
dev_key = dev || Float::INFINITY
if !local
local_key = [[-Float::INFINITY, ""]]
else
local_key = local.map { |i| (i.is_a? Integer) ? [i, ""] : [-Float::INFINITY, i] }
end
[epoch, release_key, pre_key, post_key, dev_key, local_key]
end
def compare(this, other)
if (this.is_a? Array) && (other.is_a? Array)
this << -Float::INFINITY if this.length < other.length
other << -Float::INFINITY if this.length > other.length
this.each_with_index do |element, index|
return compare(element, other.at(index)) if element != other.at(index)
end
elsif (this.is_a? Array) && !(other.is_a? Array)
raise Puppet::Error, "Cannot compare #{this} (Array) with #{other} (#{other.class}). Only ±Float::INFINITY accepted." unless other.abs == Float::INFINITY
return other == -Float::INFINITY ? 1 : -1
elsif !(this.is_a? Array) && (other.is_a? Array)
raise Puppet::Error, "Cannot compare #{this} (#{this.class}) with #{other} (Array). Only ±Float::INFINITY accepted." unless this.abs == Float::INFINITY
return this == -Float::INFINITY ? -1 : 1
end
this <=> other
end
class ValidationFailure < ArgumentError
def initialize(version)
super("#{version} is not a valid python package version. Please refer to https://www.python.org/dev/peps/pep-0440/.")
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/util/package/version/debian.rb | lib/puppet/util/package/version/debian.rb | # frozen_string_literal: true
module Puppet::Util::Package::Version
class Debian < Numeric
include Comparable
# Version string matching regexes
REGEX_EPOCH = '(?:([0-9]+):)?'
# alphanumerics and the characters . + - ~ , starts with a digit, ~ only of debian_revision is present
REGEX_UPSTREAM_VERSION = '([\.\+~0-9a-zA-Z-]+?)'
# alphanumerics and the characters + . ~
REGEX_DEBIAN_REVISION = '(?:-([\.\+~0-9a-zA-Z]*))?'
REGEX_FULL = REGEX_EPOCH + REGEX_UPSTREAM_VERSION + REGEX_DEBIAN_REVISION.freeze
REGEX_FULL_RX = /\A#{REGEX_FULL}\Z/
class ValidationFailure < ArgumentError; end
def self.parse(ver)
raise ValidationFailure, "Unable to parse '#{ver}' as a string" unless ver.is_a?(String)
match, epoch, upstream_version, debian_revision = *ver.match(REGEX_FULL_RX)
raise ValidationFailure, "Unable to parse '#{ver}' as a debian version identifier" unless match
new(epoch.to_i, upstream_version, debian_revision).freeze
end
def to_s
s = @upstream_version
s = "#{@epoch}:#{s}" if @epoch != 0
s = "#{s}-#{@debian_revision}" if @debian_revision
s
end
alias inspect to_s
def eql?(other)
other.is_a?(self.class) &&
@epoch.eql?(other.epoch) &&
@upstream_version.eql?(other.upstream_version) &&
@debian_revision.eql?(other.debian_revision)
end
alias == eql?
def <=>(other)
return nil unless other.is_a?(self.class)
cmp = @epoch <=> other.epoch
if cmp == 0
cmp = compare_upstream_version(other)
if cmp == 0
cmp = compare_debian_revision(other)
end
end
cmp
end
attr_reader :epoch, :upstream_version, :debian_revision
private
def initialize(epoch, upstream_version, debian_revision)
@epoch = epoch
@upstream_version = upstream_version
@debian_revision = debian_revision
end
def compare_upstream_version(other)
mine = @upstream_version
yours = other.upstream_version
compare_debian_versions(mine, yours)
end
def compare_debian_revision(other)
mine = @debian_revision
yours = other.debian_revision
compare_debian_versions(mine, yours)
end
def compare_debian_versions(mine, yours)
# First the initial part of each string consisting entirely of non-digit characters is determined.
# These two parts (one of which may be empty) are compared lexically. If a difference is found it is
# returned. The lexical comparison is a comparison of ASCII values modified so that all the letters
# sort earlier than all the non-letters and so that a tilde sorts before anything, even the end of a
# part. For example, the following parts are in sorted order from earliest to latest: ~~, ~~a, ~, the
# empty part, a.
#
# Then the initial part of the remainder of each string which consists entirely of digit characters
# is determined. The numerical values of these two parts are compared, and any difference found is
# returned as the result of the comparison. For these purposes an empty string (which can only occur
# at the end of one or both version strings being compared) counts as zero.
#
# These two steps (comparing and removing initial non-digit strings and initial digit strings) are
# repeated until a difference is found or both strings are exhausted.
mine_index = 0
yours_index = 0
cmp = 0
mine ||= ''
yours ||= ''
while mine_index < mine.length && yours_index < yours.length && cmp == 0
# handle ~
_mymatch, mytilde = *match_tildes(mine.slice(mine_index..-1))
mytilde ||= ''
_yoursmatch, yourstilde = *match_tildes(yours.slice(yours_index..-1))
yourstilde ||= ''
cmp = -1 * (mytilde.length <=> yourstilde.length)
mine_index += mytilde.length
yours_index += yourstilde.length
next unless cmp == 0 # handle letters
_mymatch, myletters = *match_letters(mine.slice(mine_index..-1))
myletters ||= ''
_yoursmatch, yoursletters = *match_letters(yours.slice(yours_index..-1))
yoursletters ||= ''
cmp = myletters <=> yoursletters
mine_index += myletters.length
yours_index += yoursletters.length
next unless cmp == 0 # handle nonletters except tilde
_mymatch, mynon_letters = *match_non_letters(mine.slice(mine_index..-1))
mynon_letters ||= ''
_yoursmatch, yoursnon_letters = *match_non_letters(yours.slice(yours_index..-1))
yoursnon_letters ||= ''
cmp = mynon_letters <=> yoursnon_letters
mine_index += mynon_letters.length
yours_index += yoursnon_letters.length
next unless cmp == 0 # handle digits
_mymatch, mydigits = *match_digits(mine.slice(mine_index..-1))
mydigits ||= ''
_yoursmatch, yoursdigits = *match_digits(yours.slice(yours_index..-1))
yoursdigits ||= ''
cmp = mydigits.to_i <=> yoursdigits.to_i
mine_index += mydigits.length
yours_index += yoursdigits.length
end
if cmp == 0
if mine_index < mine.length && match_tildes(mine[mine_index])
cmp = -1
elsif yours_index < yours.length && match_tildes(yours[yours_index])
cmp = 1
else
cmp = mine.length <=> yours.length
end
end
cmp
end
def match_digits(a)
a.match(/^([0-9]+)/)
end
def match_non_letters(a)
a.match(/^([.+-]+)/)
end
def match_tildes(a)
a.match(/^(~+)/)
end
def match_letters(a)
a.match(/^([A-Za-z]+)/)
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/util/package/version/gem.rb | lib/puppet/util/package/version/gem.rb | # frozen_string_literal: true
module Puppet::Util::Package::Version
class Gem < ::Gem::Version
def self.parse(version)
raise ValidationFailure, version unless version.is_a? String
raise ValidationFailure, version unless version =~ ANCHORED_VERSION_PATTERN
new(version)
end
class ValidationFailure < ArgumentError
def initialize(version)
super("#{version} is not a valid ruby gem version.")
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/util/package/version/rpm.rb | lib/puppet/util/package/version/rpm.rb | # frozen_string_literal: true
require_relative '../../../../puppet/util/rpm_compare'
module Puppet::Util::Package::Version
class Rpm < Numeric
# provides Rpm parsing and comparison
extend Puppet::Util::RpmCompare
include Puppet::Util::RpmCompare
include Comparable
class ValidationFailure < ArgumentError; end
attr_reader :epoch, :version, :release, :arch
def self.parse(ver)
raise ValidationFailure unless ver.is_a?(String)
version = rpm_parse_evr(ver)
new(version[:epoch], version[:version], version[:release], version[:arch]).freeze
end
def to_s
version_found = ''.dup
version_found += "#{@epoch}:" if @epoch
version_found += @version
version_found += "-#{@release}" if @release
version_found
end
alias inspect to_s
def eql?(other)
other.is_a?(self.class) &&
@epoch.eql?(other.epoch) &&
@version.eql?(other.version) &&
@release.eql?(other.release) &&
@arch.eql?(other.arch)
end
alias == eql?
def <=>(other)
raise ArgumentError, _("Cannot compare, as %{other} is not a Rpm Version") % { other: other } unless other.is_a?(self.class)
rpm_compare_evr(to_s, other.to_s)
end
private
# overwrite rpm_compare_evr to treat no epoch as zero epoch
# in order to compare version correctly
#
# returns 1 if a is newer than b,
# 0 if they are identical
# -1 if a is older than b
def rpm_compare_evr(a, b)
a_hash = rpm_parse_evr(a)
b_hash = rpm_parse_evr(b)
a_hash[:epoch] ||= '0'
b_hash[:epoch] ||= '0'
rc = compare_values(a_hash[:epoch], b_hash[:epoch])
return rc unless rc == 0
super(a, b)
end
def initialize(epoch, version, release, arch)
@epoch = epoch
@version = version
@release = release
@arch = arch
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/util/package/version/range/gt_eq.rb | lib/puppet/util/package/version/range/gt_eq.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class GtEq < Simple
def to_s
">=#{@version}"
end
def include?(version)
version >= @version
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/util/package/version/range/lt.rb | lib/puppet/util/package/version/range/lt.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class Lt < Simple
def to_s
"<#{@version}"
end
def include?(version)
version < @version
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/util/package/version/range/min_max.rb | lib/puppet/util/package/version/range/min_max.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range'
module Puppet::Util::Package::Version
class Range
class MinMax
def initialize(min, max)
@min = min
@max = max
end
def to_s
"#{@min} #{@max}"
end
def to_gem_version
"#{@min}, #{@max}"
end
def include?(version)
@min.include?(version) && @max.include?(version)
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/util/package/version/range/simple.rb | lib/puppet/util/package/version/range/simple.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range'
module Puppet::Util::Package::Version
class Range
class Simple
def initialize(version)
@version = version
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/util/package/version/range/eq.rb | lib/puppet/util/package/version/range/eq.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class Eq < Simple
def to_s
@version.to_s
end
def include?(version)
version == @version
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/util/package/version/range/lt_eq.rb | lib/puppet/util/package/version/range/lt_eq.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class LtEq < Simple
def to_s
"<=#{@version}"
end
def include?(version)
version <= @version
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/util/package/version/range/gt.rb | lib/puppet/util/package/version/range/gt.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class Gt < Simple
def to_s
">#{@version}"
end
def include?(version)
version > @version
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/util/log/destinations.rb | lib/puppet/util/log/destinations.rb | # frozen_string_literal: true
Puppet::Util::Log.newdesttype :syslog do
def self.suitable?(obj)
Puppet.features.syslog?
end
def close
Syslog.close
end
def initialize
Syslog.close if Syslog.opened?
name = "puppet-#{Puppet.run_mode.name}"
options = Syslog::LOG_PID | Syslog::LOG_NDELAY
# XXX This should really be configurable.
str = Puppet[:syslogfacility]
begin
facility = Syslog.const_get("LOG_#{str.upcase}")
rescue NameError => e
raise Puppet::Error, _("Invalid syslog facility %{str}") % { str: str }, e.backtrace
end
@syslog = Syslog.open(name, options, facility)
end
def handle(msg)
# XXX Syslog currently has a bug that makes it so you
# cannot log a message with a '%' in it. So, we get rid
# of them.
if msg.source == "Puppet"
msg.to_s.split("\n").each do |line|
@syslog.send(msg.level, line.gsub("%", '%%'))
end
else
msg.to_s.split("\n").each do |line|
@syslog.send(msg.level, "(%s) %s" % [msg.source.to_s.delete("%"),
line.gsub("%", '%%')])
end
end
end
end
Puppet::Util::Log.newdesttype :file do
require 'fileutils'
def self.match?(obj)
obj.is_a?(String) && Puppet::Util.absolute_path?(obj)
end
def close
if defined?(@file)
@file.close
@file = nil
end
end
def flush
@file.flush if defined?(@file)
end
attr_accessor :autoflush
def initialize(path)
@name = path
@json = path.end_with?('.json') ? 1 : 0
@jsonl = path.end_with?('.jsonl')
# first make sure the directory exists
# We can't just use 'Config.use' here, because they've
# specified a "special" destination.
unless Puppet::FileSystem.exist?(Puppet::FileSystem.dir(path))
FileUtils.mkdir_p(File.dirname(path), :mode => 0o755)
Puppet.info _("Creating log directory %{dir}") % { dir: File.dirname(path) }
end
# create the log file, if it doesn't already exist
need_array_start = false
file_exists = Puppet::FileSystem.exist?(path)
if @json == 1
need_array_start = true
if file_exists
sz = File.size(path)
need_array_start = sz == 0
# Assume that entries have been written and that a comma
# is needed before next entry
@json = 2 if sz > 2
end
end
file = File.new(path, File::WRONLY | File::CREAT | File::APPEND)
file.puts('[') if need_array_start
@file = file
@autoflush = Puppet[:autoflush]
end
def handle(msg)
if @json > 0
@json > 1 ? @file.puts(',') : @json = 2
@file.puts(Puppet::Util::Json.dump(msg.to_structured_hash))
elsif @jsonl
@file.puts(Puppet::Util::Json.dump(msg.to_structured_hash))
else
@file.puts("#{msg.time} #{msg.source} (#{msg.level}): #{msg}")
end
@file.flush if @autoflush
end
end
Puppet::Util::Log.newdesttype :logstash_event do
require 'time'
def format(msg)
# logstash_event format is documented at
# https://logstash.jira.com/browse/LOGSTASH-675
data = msg.to_hash
data['version'] = 1
data['@timestamp'] = data['time']
data.delete('time')
data
end
def handle(msg)
message = format(msg)
$stdout.puts Puppet::Util::Json.dump(message)
end
end
Puppet::Util::Log.newdesttype :console do
require_relative '../../../puppet/util/colors'
include Puppet::Util::Colors
def initialize
# Flush output immediately.
$stderr.sync = true
$stdout.sync = true
end
def handle(msg)
levels = {
:emerg => { :name => 'Emergency', :color => :hred, :stream => $stderr },
:alert => { :name => 'Alert', :color => :hred, :stream => $stderr },
:crit => { :name => 'Critical', :color => :hred, :stream => $stderr },
:err => { :name => 'Error', :color => :hred, :stream => $stderr },
:warning => { :name => 'Warning', :color => :hyellow, :stream => $stderr },
:notice => { :name => 'Notice', :color => :reset, :stream => $stdout },
:info => { :name => 'Info', :color => :green, :stream => $stdout },
:debug => { :name => 'Debug', :color => :cyan, :stream => $stdout },
}
str = msg.respond_to?(:multiline) ? msg.multiline : msg.to_s
str = msg.source == "Puppet" ? str : "#{msg.source}: #{str}"
level = levels[msg.level]
level[:stream].puts colorize(level[:color], "#{level[:name]}: #{str}")
end
end
# Log to a transaction report.
Puppet::Util::Log.newdesttype :report do
attr_reader :report
match "Puppet::Transaction::Report"
def initialize(report)
@report = report
end
def handle(msg)
@report << msg
end
end
# Log to an array, just for testing.
module Puppet::Test
class LogCollector
def initialize(logs)
@logs = logs
end
def <<(value)
@logs << value
end
end
end
Puppet::Util::Log.newdesttype :array do
match "Puppet::Test::LogCollector"
def initialize(messages)
@messages = messages
end
def handle(msg)
@messages << msg
end
end
Puppet::Util::Log.newdesttype :eventlog do
# Leaving these in for backwards compatibility - duplicates the same in
# Puppet::Util::Windows::EventLog
Puppet::Util::Log::DestEventlog::EVENTLOG_ERROR_TYPE = 0x0001
Puppet::Util::Log::DestEventlog::EVENTLOG_WARNING_TYPE = 0x0002
Puppet::Util::Log::DestEventlog::EVENTLOG_INFORMATION_TYPE = 0x0004
Puppet::Util::Log::DestEventlog::EVENTLOG_CHARACTER_LIMIT = 31_838
def self.suitable?(obj)
Puppet::Util::Platform.windows?
end
def initialize
@eventlog = Puppet::Util::Windows::EventLog.open("Puppet")
end
def to_native(level)
Puppet::Util::Windows::EventLog.to_native(level)
end
def handle(msg)
native_type, native_id = to_native(msg.level)
stringified_msg = msg.message.to_s
if stringified_msg.length > self.class::EVENTLOG_CHARACTER_LIMIT
warning = "...Message exceeds character length limit, truncating."
truncated_message_length = self.class::EVENTLOG_CHARACTER_LIMIT - warning.length
stringified_truncated_msg = stringified_msg[0..truncated_message_length]
stringified_truncated_msg << warning
msg.message = stringified_truncated_msg
end
@eventlog.report_event(
:event_type => native_type,
:event_id => native_id,
:data => (msg.source && msg.source != 'Puppet' ? "#{msg.source}: " : '') + msg.to_s
)
end
def close
if @eventlog
@eventlog.close
@eventlog = nil
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/util/log/destination.rb | lib/puppet/util/log/destination.rb | # frozen_string_literal: true
# A type of log destination.
class Puppet::Util::Log::Destination
class << self
attr_accessor :name
end
def self.initvars
@matches = []
end
# Mark the things we're supposed to match.
def self.match(obj)
@matches ||= []
@matches << obj
end
# See whether we match a given thing.
def self.match?(obj)
# Convert single-word strings into symbols like :console and :syslog
if obj.is_a? String and obj =~ /^\w+$/
obj = obj.downcase.intern
end
@matches.each do |thing|
# Search for direct matches or class matches
return true if thing === obj or thing == obj.class.to_s
end
false
end
def name
if defined?(@name)
@name
else
self.class.name
end
end
# Set how to handle a message.
def self.sethandler(&block)
define_method(:handle, &block)
end
# Mark how to initialize our object.
def self.setinit(&block)
define_method(:initialize, &block)
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/type/component.rb | lib/puppet/type/component.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/type'
require_relative '../../puppet/transaction'
Puppet::Type.newtype(:component) do
include Enumerable
newparam(:name) do
desc "The name of the component. Generally optional."
isnamevar
end
# Override how parameters are handled so that we support the extra
# parameters that are used with defined resource types.
def [](param)
if self.class.valid_parameter?(param)
super
else
@extra_parameters[param.to_sym]
end
end
# Override how parameters are handled so that we support the extra
# parameters that are used with defined resource types.
def []=(param, value)
if self.class.valid_parameter?(param)
super
else
@extra_parameters[param.to_sym] = value
end
end
# Initialize a new component
def initialize(*args)
@extra_parameters = {}
super
end
# Component paths are special because they function as containers.
def pathbuilder
if reference.type == "Class"
myname = reference.title
else
myname = reference.to_s
end
p = parent
if p
[p.pathbuilder, myname]
else
[myname]
end
end
def ref
reference.to_s
end
# We want our title to just be the whole reference, rather than @title.
def title
ref
end
def title=(str)
@reference = Puppet::Resource.new(str)
end
def refresh
catalog.adjacent(self).each do |child|
if child.respond_to?(:refresh)
child.refresh
child.log "triggering refresh"
end
end
end
def to_s
reference.to_s
end
# Overrides the default implementation to do nothing.
# This type contains data from class/define parameters, but does
# not have actual parameters or properties at the Type level. We can
# simply ignore anything flagged as sensitive here, since any
# contained resources will handle that sensitivity themselves. There
# is no risk of this information leaking into reports, since no
# Component instances survive the graph transmutation.
#
def set_sensitive_parameters(sensitive_parameters)
end
private
attr_reader :reference
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/type/group.rb | lib/puppet/type/group.rb | # frozen_string_literal: true
require 'etc'
require_relative '../../puppet/property/keyvalue'
require_relative '../../puppet/parameter/boolean'
module Puppet
Type.newtype(:group) do
@doc = "Manage groups. On most platforms this can only create groups.
Group membership must be managed on individual users.
On some platforms such as OS X, group membership is managed as an
attribute of the group, not the user record. Providers must have
the feature 'manages_members' to manage the 'members' property of
a group record."
feature :manages_members,
"For directories where membership is an attribute of groups not users."
feature :manages_aix_lam,
"The provider can manage AIX Loadable Authentication Module (LAM) system."
feature :system_groups,
"The provider allows you to create system groups with lower GIDs."
feature :manages_local_users_and_groups,
"Allows local groups to be managed on systems that also use some other
remote Name Switch Service (NSS) method of managing accounts."
ensurable do
desc "Create or remove the group."
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.delete
end
defaultto :present
end
newproperty(:gid) do
desc "The group ID. Must be specified numerically. If no group ID is
specified when creating a new group, then one will be chosen
automatically according to local system standards. This will likely
result in the same group having different GIDs on different systems,
which is not recommended.
On Windows, this property is read-only and will return the group's security
identifier (SID)."
def retrieve
provider.gid
end
def sync
if should == :absent
raise Puppet::DevError, _("GID cannot be deleted")
else
provider.gid = should
end
end
munge do |gid|
case gid
when String
if gid =~ /^[-0-9]+$/
gid = Integer(gid)
else
self.fail _("Invalid GID %{gid}") % { gid: gid }
end
when Symbol
unless gid == :absent
devfail "Invalid GID #{gid}"
end
end
return gid
end
end
newproperty(:members, :array_matching => :all, :required_features => :manages_members) do
desc "The members of the group. For platforms or directory services where group
membership is stored in the group objects, not the users. This parameter's
behavior can be configured with `auth_membership`."
def change_to_s(currentvalue, newvalue)
newvalue = actual_should(currentvalue, newvalue)
currentvalue = currentvalue.join(",") if currentvalue != :absent
newvalue = newvalue.join(",")
super(currentvalue, newvalue)
end
def insync?(current)
if provider.respond_to?(:members_insync?)
return provider.members_insync?(current, @should)
end
super(current)
end
def is_to_s(currentvalue) # rubocop:disable Naming/PredicatePrefix
if provider.respond_to?(:members_to_s)
currentvalue = '' if currentvalue.nil?
currentvalue = currentvalue.is_a?(Array) ? currentvalue : currentvalue.split(',')
return provider.members_to_s(currentvalue)
end
super(currentvalue)
end
def should_to_s(newvalue)
is_to_s(actual_should(retrieve, newvalue))
end
# Calculates the actual should value given the current and
# new values. This is only used in should_to_s and change_to_s
# to fix the change notification issue reported in PUP-6542.
def actual_should(currentvalue, newvalue)
currentvalue = munge_members_value(currentvalue)
newvalue = munge_members_value(newvalue)
if @resource[:auth_membership]
newvalue.uniq.sort
else
(currentvalue + newvalue).uniq.sort
end
end
# Useful helper to handle the possible property value types that we can
# both pass-in and return. It munges the value into an array
def munge_members_value(value)
return [] if value == :absent
return value.split(',') if value.is_a?(String)
value
end
validate do |value|
if provider.respond_to?(:member_valid?)
return provider.member_valid?(value)
end
end
end
newparam(:auth_membership, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Configures the behavior of the `members` parameter.
* `false` (default) --- The provided list of group members is partial,
and Puppet **ignores** any members that aren't listed there.
* `true` --- The provided list of of group members is comprehensive, and
Puppet **purges** any members that aren't listed there."
defaultto false
end
newparam(:name) do
desc "The group name. While naming limitations vary by operating system,
it is advisable to restrict names to the lowest common denominator,
which is a maximum of 8 characters beginning with a letter.
Note that Puppet considers group names to be case-sensitive, regardless
of the platform's own rules; be sure to always use the same case when
referring to a given group."
isnamevar
end
newparam(:allowdupe, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to allow duplicate GIDs."
defaultto false
end
newparam(:ia_load_module, :required_features => :manages_aix_lam) do
desc "The name of the I&A module to use to manage this group.
This should be set to `files` if managing local groups."
end
newproperty(:attributes, :parent => Puppet::Property::KeyValue, :required_features => :manages_aix_lam) do
desc "Specify group AIX attributes, as an array of `'key=value'` strings. This
parameter's behavior can be configured with `attribute_membership`."
self.log_only_changed_or_new_keys = true
def membership
:attribute_membership
end
def delimiter
" "
end
end
newparam(:attribute_membership) do
desc "AIX only. Configures the behavior of the `attributes` parameter.
* `minimum` (default) --- The provided list of attributes is partial, and Puppet
**ignores** any attributes that aren't listed there.
* `inclusive` --- The provided list of attributes is comprehensive, and
Puppet **purges** any attributes that aren't listed there."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newparam(:system, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether the group is a system group with lower GID."
defaultto false
end
newparam(:forcelocal, :boolean => true,
:required_features => :manages_local_users_and_groups,
:parent => Puppet::Parameter::Boolean) do
desc "Forces the management of local accounts when accounts are also
being managed by some other Name Switch Service (NSS). For AIX, refer to the `ia_load_module` parameter.
This option relies on your operating system's implementation of `luser*` commands, such as `luseradd` , `lgroupadd`, and `lusermod`. The `forcelocal` option could behave unpredictably in some circumstances. If the tools it depends on are not available, it might have no effect at all."
defaultto false
end
# This method has been exposed for puppet to manage users and groups of
# files in its settings and should not be considered available outside of
# puppet.
#
# (see Puppet::Settings#service_group_available?)
#
# @return [Boolean] if the group exists on the system
# @api private
def exists?
provider.exists?
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/type/stage.rb | lib/puppet/type/stage.rb | # frozen_string_literal: true
Puppet::Type.newtype(:stage) do
desc "A resource type for creating new run stages. Once a stage is available,
classes can be assigned to it by declaring them with the resource-like syntax
and using
[the `stage` metaparameter](https://puppet.com/docs/puppet/latest/metaparameter.html#stage).
Note that new stages are not useful unless you also declare their order
in relation to the default `main` stage.
A complete run stage example:
stage { 'pre':
before => Stage['main'],
}
class { 'apt-updates':
stage => 'pre',
}
Individual resources cannot be assigned to run stages; you can only set stages
for classes."
newparam :name do
desc "The name of the stage. Use this as the value for the `stage` metaparameter
when assigning classes to this stage."
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/type/package.rb | lib/puppet/type/package.rb | # coding: utf-8
# frozen_string_literal: true
# Define the different packaging systems. Each package system is implemented
# in a module, which then gets used to individually extend each package object.
# This allows packages to exist on the same machine using different packaging
# systems.
require_relative '../../puppet/parameter/package_options'
require_relative '../../puppet/parameter/boolean'
module Puppet
Type.newtype(:package) do
@doc = "Manage packages. There is a basic dichotomy in package
support right now: Some package types (such as yum and apt) can
retrieve their own package files, while others (such as rpm and sun)
cannot. For those package formats that cannot retrieve their own files,
you can use the `source` parameter to point to the correct file.
Puppet will automatically guess the packaging format that you are
using based on the platform you are on, but you can override it
using the `provider` parameter; each provider defines what it
requires in order to function, and you must meet those requirements
to use a given provider.
You can declare multiple package resources with the same `name` as long
as they have unique titles, and specify different providers and commands.
Note that you must use the _title_ to make a reference to a package
resource; `Package[<NAME>]` is not a synonym for `Package[<TITLE>]` like
it is for many other resource types.
**Autorequires:** If Puppet is managing the files specified as a
package's `adminfile`, `responsefile`, or `source`, the package
resource will autorequire those files."
feature :reinstallable, "The provider can reinstall packages.",
:methods => [:reinstall]
feature :installable, "The provider can install packages.",
:methods => [:install]
feature :uninstallable, "The provider can uninstall packages.",
:methods => [:uninstall]
feature :upgradeable, "The provider can upgrade to the latest version of a
package. This feature is used by specifying `latest` as the
desired value for the package.",
:methods => [:update, :latest]
feature :purgeable, "The provider can purge packages. This generally means
that all traces of the package are removed, including
existing configuration files. This feature is thus destructive
and should be used with the utmost care.",
:methods => [:purge]
feature :versionable, "The provider is capable of interrogating the
package database for installed version(s), and can select
which out of a set of available versions of a package to
install if asked."
feature :version_ranges, "The provider can ensure version ranges."
feature :holdable, "The provider is capable of placing packages on hold
such that they are not automatically upgraded as a result of
other package dependencies unless explicit action is taken by
a user or another package.",
:methods => [:hold, :unhold]
feature :install_only, "The provider accepts options to only install packages never update (kernels, etc.)"
feature :install_options, "The provider accepts options to be
passed to the installer command."
feature :uninstall_options, "The provider accepts options to be
passed to the uninstaller command."
feature :disableable, "The provider can disable packages. This feature is used by specifying `disabled` as the
desired value for the package.",
:methods => [:disable]
feature :supports_flavors, "The provider accepts flavors, which are specific variants of packages."
feature :package_settings, "The provider accepts package_settings to be
ensured for the given package. The meaning and format of these settings is
provider-specific.",
:methods => [:package_settings_insync?, :package_settings, :package_settings=]
feature :virtual_packages, "The provider accepts virtual package names for install and uninstall."
feature :targetable, "The provider accepts a targeted package management command."
ensurable do
desc <<-EOT
What state the package should be in. On packaging systems that can
retrieve new packages on their own, you can choose which package to
retrieve by specifying a version number or `latest` as the ensure
value. On packaging systems that manage configuration files separately
from "normal" system files, you can uninstall config files by
specifying `purged` as the ensure value. This defaults to `installed`.
Version numbers must match the full version to install, including
release if the provider uses a release moniker. For
example, to install the bash package from the rpm
`bash-4.1.2-29.el6.x86_64.rpm`, use the string `'4.1.2-29.el6'`.
On supported providers, version ranges can also be ensured. For example,
inequalities: `<2.0.0`, or intersections: `>1.0.0 <2.0.0`.
EOT
attr_accessor :latest
newvalue(:present, :event => :package_installed) do
provider.install
end
newvalue(:absent, :event => :package_removed) do
provider.uninstall
end
newvalue(:purged, :event => :package_purged, :required_features => :purgeable) do
provider.purge
end
newvalue(:disabled, :required_features => :disableable) do
provider.disable
end
# Alias the 'present' value.
aliasvalue(:installed, :present)
newvalue(:latest, :required_features => :upgradeable) do
# Because yum always exits with a 0 exit code, there's a retrieve
# in the "install" method. So, check the current state now,
# to compare against later.
current = retrieve
begin
provider.update
rescue => detail
self.fail Puppet::Error, _("Could not update: %{detail}") % { detail: detail }, detail
end
if current == :absent
:package_installed
else
:package_changed
end
end
newvalue(/./, :required_features => :versionable) do
begin
provider.install
rescue => detail
self.fail Puppet::Error, _("Could not update: %{detail}") % { detail: detail }, detail
end
if retrieve == :absent
:package_installed
else
:package_changed
end
end
defaultto :installed
# Override the parent method, because we've got all kinds of
# funky definitions of 'in sync'.
def insync?(is)
@lateststamp ||= (Time.now.to_i - 1000)
# Iterate across all of the should values, and see how they
# turn out.
@should.each { |should|
case should
when :present
return true unless [:absent, :purged, :disabled].include?(is)
when :latest
# Short-circuit packages that are not present
return false if is == :absent || is == :purged
# Don't run 'latest' more than about every 5 minutes
if @latest and ((Time.now.to_i - @lateststamp) / 60) < 5
# self.debug "Skipping latest check"
else
begin
@latest = provider.latest
@lateststamp = Time.now.to_i
rescue => detail
error = Puppet::Error.new(_("Could not get latest version: %{detail}") % { detail: detail })
error.set_backtrace(detail.backtrace)
raise error
end
end
case
when is.is_a?(Array) && is.include?(@latest)
return true
when is == @latest
return true
when is == :present
# This will only happen on packaging systems
# that can't query versions.
return true
else
debug "#{@resource.name} #{is.inspect} is installed, latest is #{@latest.inspect}"
end
when :absent
return true if is == :absent || is == :purged
when :purged
return true if is == :purged
# this handles version number matches and
# supports providers that can have multiple versions installed
when *Array(is)
return true
else
# We have version numbers, and no match. If the provider has
# additional logic, run it here.
return provider.insync?(is) if provider.respond_to?(:insync?)
end
}
false
end
# This retrieves the current state. LAK: I think this method is unused.
def retrieve
provider.properties[:ensure]
end
# Provide a bit more information when logging upgrades.
def should_to_s(newvalue = @should)
if @latest
super(@latest)
else
super(newvalue)
end
end
def change_to_s(currentvalue, newvalue)
# Handle transitioning from any previous state to 'purged'
return 'purged' if newvalue == :purged
# Check for transitions from nil/purged/absent to 'created' (any state that is not absent and not purged)
return 'created' if (currentvalue.nil? || currentvalue == :absent || currentvalue == :purged) && (newvalue != :absent && newvalue != :purged)
# The base should handle the normal property transitions
super(currentvalue, newvalue)
end
end
newparam(:name) do
desc "The package name. This is the name that the packaging
system uses internally, which is sometimes (especially on Solaris)
a name that is basically useless to humans. If a package goes by
several names, you can use a single title and then set the name
conditionally:
# In the 'openssl' class
$ssl = $os['name'] ? {
solaris => SMCossl,
default => openssl
}
package { 'openssl':
ensure => installed,
name => $ssl,
}
...
$ssh = $os['name'] ? {
solaris => SMCossh,
default => openssh
}
package { 'openssh':
ensure => installed,
name => $ssh,
require => Package['openssl'],
}
"
isnamevar
validate do |value|
unless value.is_a?(String)
raise ArgumentError, _("Name must be a String not %{klass}") % { klass: value.class }
end
end
end
# We call providify here so that we can set provider as a namevar.
# Normally this method is called after newtype finishes constructing this
# Type class.
providify
paramclass(:provider).isnamevar
def self.parameters_to_include
[:provider]
end
# Specify a targeted package management command.
newparam(:command, :required_features => :targetable) do
desc <<-EOT
The targeted command to use when managing a package:
package { 'mysql':
provider => gem,
}
package { 'mysql-opt':
name => 'mysql',
provider => gem,
command => '/opt/ruby/bin/gem',
}
Each provider defines a package management command and uses the first
instance of the command found in the PATH.
Providers supporting the targetable feature allow you to specify the
absolute path of the package management command. Specifying the absolute
path is useful when multiple instances of the command are installed, or
the command is not in the PATH.
EOT
isnamevar
defaultto :default
end
# We have more than one namevar, so we need title_patterns.
# However, we cheat and set the patterns to map to name only
# and completely ignore provider (and command, for targetable providers).
# So far, the logic that determines uniqueness appears to just
# "Do The Right Thing™" when provider (and command) are explicitly set.
#
# The following resources will be seen as unique by puppet:
#
# # Uniqueness Key: ['mysql', nil]
# package {'mysql': }
#
# # Uniqueness Key: ['mysql', 'gem', nil]
# package {'gem-mysql':
# name => 'mysql,
# provider => gem,
# }
#
# # Uniqueness Key: ['mysql', 'gem', '/opt/ruby/bin/gem']
# package {'gem-mysql-opt':
# name => 'mysql,
# provider => gem
# command => '/opt/ruby/bin/gem',
# }
#
# This does not handle the case where providers like 'yum' and 'rpm' should
# clash. Also, declarations that implicitly use the default provider will
# clash with those that explicitly use the default.
def self.title_patterns
# This is the default title pattern for all types, except hard-wired to
# set only name.
[[/(.*)/m, [[:name]]]]
end
newproperty(:package_settings, :required_features => :package_settings) do
desc "Settings that can change the contents or configuration of a package.
The formatting and effects of package_settings are provider-specific; any
provider that implements them must explain how to use them in its
documentation. (Our general expectation is that if a package is
installed but its settings are out of sync, the provider should
re-install that package with the desired settings.)
An example of how package_settings could be used is FreeBSD's port build
options --- a future version of the provider could accept a hash of options,
and would reinstall the port if the installed version lacked the correct
settings.
package { 'www/apache22':
package_settings => { 'SUEXEC' => false }
}
Again, check the documentation of your platform's package provider to see
the actual usage."
validate do |value|
if provider.respond_to?(:package_settings_validate)
provider.package_settings_validate(value)
else
super(value)
end
end
munge do |value|
if provider.respond_to?(:package_settings_munge)
provider.package_settings_munge(value)
else
super(value)
end
end
def insync?(is)
provider.package_settings_insync?(should, is)
end
def should_to_s(newvalue)
if provider.respond_to?(:package_settings_should_to_s)
provider.package_settings_should_to_s(should, newvalue)
else
super(newvalue)
end
end
def is_to_s(currentvalue) # rubocop:disable Naming/PredicatePrefix
if provider.respond_to?(:package_settings_is_to_s)
provider.package_settings_is_to_s(should, currentvalue)
else
super(currentvalue)
end
end
def change_to_s(currentvalue, newvalue)
if provider.respond_to?(:package_settings_change_to_s)
provider.package_settings_change_to_s(currentvalue, newvalue)
else
super(currentvalue, newvalue)
end
end
end
newproperty(:flavor, :required_features => :supports_flavors) do
desc "OpenBSD and DNF modules support 'flavors', which are
further specifications for which type of package you want."
validate do |value|
if [:disabled, "disabled"].include?(@resource[:ensure]) && value
raise ArgumentError, _('Cannot have both `ensure => disabled` and `flavor`')
end
end
end
newparam(:source) do
desc "Where to find the package file. This is mostly used by providers that don't
automatically download packages from a central repository. (For example:
the `macports` provider ignores this attribute, `apt` provider uses it if present
and the `rpm` and `dpkg` providers require it.)
Different providers accept different values for `source`. Most providers
accept paths to local files stored on the target system. Some providers
may also accept URLs or network drive paths. Puppet will not
automatically retrieve source files for you, and usually just passes the
value of `source` to the package installation command.
You can use a `file` resource if you need to manually copy package files
to the target system."
validate do |value|
provider.validate_source(value)
end
end
newparam(:instance) do
desc "A read-only parameter set by the package."
end
newparam(:status) do
desc "A read-only parameter set by the package."
end
newparam(:adminfile) do
desc "A file containing package defaults for installing packages.
This attribute is only used on Solaris. Its value should be a path to a
local file stored on the target system. Solaris's package tools expect
either an absolute file path or a relative path to a file in
`/var/sadm/install/admin`.
The value of `adminfile` will be passed directly to the `pkgadd` or
`pkgrm` command with the `-a <ADMINFILE>` option."
end
newparam(:responsefile) do
desc "A file containing any necessary answers to questions asked by
the package. This is currently used on Solaris and Debian. The
value will be validated according to system rules, but it should
generally be a fully qualified path."
end
newparam(:configfiles) do
desc "Whether to keep or replace modified config files when installing or
upgrading a package. This only affects the `apt` and `dpkg` providers."
defaultto :keep
newvalues(:keep, :replace)
end
newparam(:category) do
desc "A read-only parameter set by the package."
end
newparam(:platform) do
desc "A read-only parameter set by the package."
end
newparam(:root) do
desc "A read-only parameter set by the package."
end
newparam(:vendor) do
desc "A read-only parameter set by the package."
end
newparam(:description) do
desc "A read-only parameter set by the package."
end
newparam(:allowcdrom) do
desc "Tells apt to allow cdrom sources in the sources.list file.
Normally apt will bail if you try this."
newvalues(:true, :false)
end
newparam(:enable_only, :boolean => false, :parent => Puppet::Parameter::Boolean) do
desc <<-EOT
Tells `dnf module` to only enable a specific module, instead
of installing its default profile.
Modules with no default profile will be enabled automatically
without the use of this parameter.
Conflicts with the `flavor` property, which selects a profile
to install.
EOT
defaultto false
validate do |value|
if [true, :true, "true"].include?(value) && @resource[:flavor]
raise ArgumentError, _('Cannot have both `enable_only => true` and `flavor`')
end
if [:disabled, "disabled"].include?(@resource[:ensure])
raise ArgumentError, _('Cannot have both `ensure => disabled` and `enable_only => true`')
end
end
end
newparam(:install_only, :boolean => false, :parent => Puppet::Parameter::Boolean, :required_features => :install_only) do
desc <<-EOT
It should be set for packages that should only ever be installed,
never updated. Kernels in particular fall into this category.
EOT
defaultto false
end
newparam(:install_options, :parent => Puppet::Parameter::PackageOptions, :required_features => :install_options) do
desc <<-EOT
An array of additional options to pass when installing a package. These
options are package-specific, and should be documented by the software
vendor. One commonly implemented option is `INSTALLDIR`:
package { 'mysql':
ensure => installed,
source => 'N:/packages/mysql-5.5.16-winx64.msi',
install_options => [ '/S', { 'INSTALLDIR' => 'C:\\mysql-5.5' } ],
}
Each option in the array can either be a string or a hash, where each
key and value pair are interpreted in a provider specific way. Each
option will automatically be quoted when passed to the install command.
With Windows packages, note that file paths in an install option must
use backslashes. (Since install options are passed directly to the
installation command, forward slashes won't be automatically converted
like they are in `file` resources.) Note also that backslashes in
double-quoted strings _must_ be escaped and backslashes in single-quoted
strings _can_ be escaped.
EOT
end
newparam(:uninstall_options, :parent => Puppet::Parameter::PackageOptions, :required_features => :uninstall_options) do
desc <<-EOT
An array of additional options to pass when uninstalling a package. These
options are package-specific, and should be documented by the software
vendor. For example:
package { 'VMware Tools':
ensure => absent,
uninstall_options => [ { 'REMOVE' => 'Sync,VSS' } ],
}
Each option in the array can either be a string or a hash, where each
key and value pair are interpreted in a provider specific way. Each
option will automatically be quoted when passed to the uninstall
command.
On Windows, this is the **only** place in Puppet where backslash
separators should be used. Note that backslashes in double-quoted
strings _must_ be double-escaped and backslashes in single-quoted
strings _may_ be double-escaped.
EOT
end
newparam(:allow_virtual, :boolean => true, :parent => Puppet::Parameter::Boolean, :required_features => :virtual_packages) do
desc 'Specifies if virtual package names are allowed for install and uninstall.'
defaultto do
provider_class = provider.class
if provider_class.respond_to?(:defaultto_allow_virtual)
provider_class.defaultto_allow_virtual
else
true
end
end
end
autorequire(:file) do
autos = []
[:responsefile, :adminfile].each { |param|
val = self[param]
if val
autos << val
end
}
source = self[:source]
if source && absolute_path?(source)
autos << source
end
autos
end
# This only exists for testing.
def clear
obj = @parameters[:ensure]
if obj
obj.latest = nil
end
end
# The 'query' method returns a hash of info if the package
# exists and returns nil if it does not.
def exists?
@provider.get(:ensure) != :absent
end
def present?(current_values)
super && current_values[:ensure] != :purged
end
# This parameter exists to ensure backwards compatibility is preserved.
# See https://github.com/puppetlabs/puppet/pull/2614 for discussion.
# If/when a metaparameter for controlling how arbitrary resources respond
# to refreshing is created, that will supersede this, and this will be
# deprecated.
newparam(:reinstall_on_refresh) do
desc "Whether this resource should respond to refresh events (via `subscribe`,
`notify`, or the `~>` arrow) by reinstalling the package. Only works for
providers that support the `reinstallable` feature.
This is useful for source-based distributions, where you may want to
recompile a package if the build options change.
If you use this, be careful of notifying classes when you want to restart
services. If the class also contains a refreshable package, doing so could
cause unnecessary re-installs."
newvalues(:true, :false)
defaultto :false
end
# When a refresh event is triggered, calls reinstall on providers
# that support the reinstall_on_refresh parameter.
def refresh
if provider.reinstallable? &&
@parameters[:reinstall_on_refresh].value == :true &&
@parameters[:ensure].value != :purged &&
@parameters[:ensure].value != :absent
provider.reinstall
end
end
newproperty(:mark, :required_features => :holdable) do
mark_doc = 'Valid values are: hold/none'
desc <<-EOT
Set to hold to tell Debian apt/Solaris pkg to hold the package version
#{mark_doc}
Default is "none". Mark can be specified with or without `ensure`,
if `ensure` is missing will default to "present".
Mark cannot be specified together with "purged", or "absent"
values for `ensure`.
EOT
newvalues(:hold, :none)
munge do |value|
case value
when "hold", :hold
:hold
when "none", :none
:none
else
raise ArgumentError, _('Invalid hold value %{value}. %{doc}') % { value: value.inspect, doc: mark_doc }
end
end
def insync?(is)
@should[0] == is
end
def should
@should[0] if @should && @should.is_a?(Array) && @should.size == 1
end
def retrieve
provider.properties[:mark]
end
def sync
if @should[0] == :hold
provider.hold
else
provider.unhold
end
end
end
validate do
if @parameters[:mark] && [:absent, :purged].include?(@parameters[:ensure].should)
raise ArgumentError, _('You cannot use "mark" property while "ensure" is one of ["absent", "purged"]')
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/type/resources.rb | lib/puppet/type/resources.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/parameter/boolean'
Puppet::Type.newtype(:resources) do
@doc = "This is a metatype that can manage other resource types. Any
metaparams specified here will be passed on to any generated resources,
so you can purge unmanaged resources but set `noop` to true so the
purging is only logged and does not actually happen."
apply_to_all
newparam(:name) do
desc "The name of the type to be managed."
validate do |name|
raise ArgumentError, _("Could not find resource type '%{name}'") % { name: name } unless Puppet::Type.type(name)
end
munge(&:to_s)
end
newparam(:purge, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to purge unmanaged resources. When set to `true`, this will
delete any resource that is not specified in your configuration and is not
autorequired by any managed resources. **Note:** The `ssh_authorized_key`
resource type can't be purged this way; instead, see the `purge_ssh_keys`
attribute of the `user` type."
defaultto :false
validate do |value|
if munge(value)
unless @resource.resource_type.respond_to?(:instances)
raise ArgumentError, _("Purging resources of type %{res_type} is not supported, since they cannot be queried from the system") % { res_type: @resource[:name] }
end
raise ArgumentError, _("Purging is only supported on types that accept 'ensure'") unless @resource.resource_type.validproperty?(:ensure)
end
end
end
newparam(:unless_system_user) do
desc "This keeps system users from being purged. By default, it
does not purge users whose UIDs are less than the minimum UID for the system (typically 500 or 1000), but you can specify
a different UID as the inclusive limit."
newvalues(:true, :false, /^\d+$/)
munge do |value|
case value
when /^\d+/
Integer(value)
when :true, true
@resource.class.system_users_max_uid
when :false, false
false
when Integer; value
else
raise ArgumentError, _("Invalid value %{value}") % { value: value.inspect }
end
end
defaultto {
if @resource[:name] == "user"
@resource.class.system_users_max_uid
else
nil
end
}
end
newparam(:unless_uid) do
desc 'This keeps specific uids or ranges of uids from being purged when purge is true.
Accepts integers, integer strings, and arrays of integers or integer strings.
To specify a range of uids, consider using the range() function from stdlib.'
munge do |value|
value = [value] unless value.is_a? Array
value.flatten.collect do |v|
case v
when Integer
v
when String
Integer(v)
else
raise ArgumentError, _("Invalid value %{value}.") % { value: v.inspect }
end
end
end
end
WINDOWS_SYSTEM_SID_REGEXES =
# Administrator, Guest, Domain Admins, Schema Admins, Enterprise Admins.
# https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
[/S-1-5-21.+-500/, /S-1-5-21.+-501/, /S-1-5-21.+-512/, /S-1-5-21.+-518/,
/S-1-5-21.+-519/]
def check(resource)
@checkmethod ||= "#{self[:name]}_check"
@hascheck ||= respond_to?(@checkmethod)
if @hascheck
send(@checkmethod, resource)
else
true
end
end
def able_to_ensure_absent?(resource)
resource[:ensure] = :absent
rescue ArgumentError, Puppet::Error
err _("The 'ensure' attribute on %{name} resources does not accept 'absent' as a value") % { name: self[:name] }
false
end
# Generate any new resources we need to manage. This is pretty hackish
# right now, because it only supports purging.
def generate
return [] unless purge?
resource_type.instances
.reject { |r| catalog.resource_refs.include? r.ref }
.select { |r| check(r) }
.select { |r| r.class.validproperty?(:ensure) }
.select { |r| able_to_ensure_absent?(r) }
.each { |resource|
resource.copy_metaparams(@parameters)
resource.purging
}
end
def resource_type
unless defined?(@resource_type)
type = Puppet::Type.type(self[:name])
unless type
raise Puppet::DevError, _("Could not find resource type")
end
@resource_type = type
end
@resource_type
end
# Make sure we don't purge users with specific uids
def user_check(resource)
return true unless self[:name] == "user"
return true unless self[:unless_system_user]
resource[:audit] = :uid
current_values = resource.retrieve_resource
current_uid = current_values[resource.property(:uid)]
unless_uids = self[:unless_uid]
return false if system_users.include?(resource[:name])
return false if unless_uids && unless_uids.include?(current_uid)
if current_uid.is_a?(String)
# Windows user; is a system user if any regex matches.
WINDOWS_SYSTEM_SID_REGEXES.none? { |regex| current_uid =~ regex }
else
current_uid > self[:unless_system_user]
end
end
def system_users
%w[root nobody bin noaccess daemon sys]
end
def self.system_users_max_uid
return @system_users_max_uid if @system_users_max_uid
# First try to read the minimum user id from login.defs
if Puppet::FileSystem.exist?('/etc/login.defs')
@system_users_max_uid = Puppet::FileSystem.each_line '/etc/login.defs' do |line|
break Regexp.last_match(1).to_i - 1 if line =~ /^\s*UID_MIN\s+(\d+)(\s*#.*)?$/
end
end
# Otherwise, use a sensible default based on the OS family
@system_users_max_uid ||=
case Puppet.runtime[:facter].value('os.family')
when 'OpenBSD', 'FreeBSD' then 999
else 499
end
@system_users_max_uid
end
def self.reset_system_users_max_uid!
@system_users_max_uid = 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/type/file.rb | lib/puppet/type/file.rb | # coding: utf-8
# frozen_string_literal: true
require 'digest/md5'
require 'cgi'
require 'etc'
require 'uri'
require 'fileutils'
require 'pathname'
require_relative '../../puppet/parameter/boolean'
require_relative '../../puppet/util/diff'
require_relative '../../puppet/util/checksums'
require_relative '../../puppet/util/backups'
require_relative '../../puppet/util/symbolic_file_mode'
Puppet::Type.newtype(:file) do
include Puppet::Util::Checksums
include Puppet::Util::Backups
include Puppet::Util::SymbolicFileMode
@doc = "Manages files, including their content, ownership, and permissions.
The `file` type can manage normal files, directories, and symlinks; the
type should be specified in the `ensure` attribute.
File contents can be managed directly with the `content` attribute, or
downloaded from a remote source using the `source` attribute; the latter
can also be used to recursively serve directories (when the `recurse`
attribute is set to `true` or `local`). On Windows, note that file
contents are managed in binary mode; Puppet never automatically translates
line endings.
**Autorequires:** If Puppet is managing the user or group that owns a
file, the file resource will autorequire them. If Puppet is managing any
parent directories of a file, the file resource autorequires them.
Warning: Enabling `recurse` on directories containing large numbers of
files slows agent runs. To manage file attributes for many files,
consider using alternative methods such as the `chmod_r`, `chown_r`,
or `recursive_file_permissions` modules from the Forge."
feature :manages_symlinks,
"The provider can manage symbolic links."
def self.title_patterns
# strip trailing slashes from path but allow the root directory, including
# for example "/" or "C:/"
[[%r{^(/|.+:/|.*[^/])/*\Z}m, [[:path]]]]
end
newparam(:path) do
desc <<-'EOT'
The path to the file to manage. Must be fully qualified.
On Windows, the path should include the drive letter and should use `/` as
the separator character (rather than `\\`).
EOT
isnamevar
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, _("File paths must be fully qualified, not '%{path}'") % { path: value }
end
end
munge do |value|
if value.start_with?('//') and ::File.basename(value) == "/"
# This is a UNC path pointing to a share, so don't add a trailing slash
::File.expand_path(value)
else
::File.join(::File.split(::File.expand_path(value)))
end
end
end
newparam(:backup) do
desc <<-EOT
Whether (and how) file content should be backed up before being replaced.
This attribute works best as a resource default in the site manifest
(`File { backup => main }`), so it can affect all file resources.
* If set to `false`, file content won't be backed up.
* If set to a string beginning with `.`, such as `.puppet-bak`, Puppet will
use copy the file in the same directory with that value as the extension
of the backup. (A value of `true` is a synonym for `.puppet-bak`.)
* If set to any other string, Puppet will try to back up to a filebucket
with that title. Puppet automatically creates a **local** filebucket
named `puppet` if one doesn't already exist. See the `filebucket` resource
type for more details.
Default value: `false`
Backing up to a local filebucket isn't particularly useful. If you want
to make organized use of backups, you will generally want to use the
primary Puppet server's filebucket service. This requires declaring a
filebucket resource and a resource default for the `backup` attribute
in site.pp:
# /etc/puppetlabs/puppet/manifests/site.pp
filebucket { 'main':
path => false, # This is required for remote filebuckets.
server => 'puppet.example.com', # Optional; defaults to the configured primary Puppet server.
}
File { backup => main, }
If you are using multiple primary servers, you will want to
centralize the contents of the filebucket. Either configure your load
balancer to direct all filebucket traffic to a single primary server, or use
something like an out-of-band rsync task to synchronize the content on all
primary servers.
> **Note**: Enabling and using the backup option, and by extension the
filebucket resource, requires appropriate planning and management to ensure
that sufficient disk space is available for the file backups. Generally, you
can implement this using one of the following two options:
- Use a `find` command and `crontab` entry to retain only the last X days
of file backups. For example:
```
find /opt/puppetlabs/server/data/puppetserver/bucket -type f -mtime +45 -atime +45 -print0 | xargs -0 rm
```
- Restrict the directory to a maximum size after which the oldest items are removed.
EOT
defaultto false
munge do |value|
# I don't really know how this is happening.
value = value.shift if value.is_a?(Array)
case value
when false, "false", :false
false
when true, "true", ".puppet-bak", :true
".puppet-bak"
when String
value
else
self.fail _("Invalid backup type %{value}") % { value: value.inspect }
end
end
end
newparam(:recurse) do
desc "Whether to recursively manage the _contents_ of a directory. This attribute
is only used when `ensure => directory` is set. The allowed values are:
* `false` --- The default behavior. The contents of the directory will not be
automatically managed.
* `remote` --- If the `source` attribute is set, Puppet will automatically
manage the contents of the source directory (or directories), ensuring
that equivalent files and directories exist on the target system and
that their contents match.
Using `remote` will disable the `purge` attribute, but results in faster
catalog application than `recurse => true`.
The `source` attribute is mandatory when `recurse => remote`.
* `true` --- If the `source` attribute is set, this behaves similarly to
`recurse => remote`, automatically managing files from the source directory.
This also enables the `purge` attribute, which can delete unmanaged
files from a directory. See the description of `purge` for more details.
The `source` attribute is not mandatory when using `recurse => true`, so you
can enable purging in directories where all files are managed individually.
By default, setting recurse to `remote` or `true` will manage _all_
subdirectories. You can use the `recurselimit` attribute to limit the
recursion depth.
"
newvalues(:true, :false, :remote)
validate { |arg| }
munge do |value|
newval = super(value)
case newval
when :true; true
when :false; false
when :remote; :remote
else
self.fail _("Invalid recurse value %{value}") % { value: value.inspect }
end
end
end
newparam(:recurselimit) do
desc "How far Puppet should descend into subdirectories, when using
`ensure => directory` and either `recurse => true` or `recurse => remote`.
The recursion limit affects which files will be copied from the `source`
directory, as well as which files can be purged when `purge => true`.
Setting `recurselimit => 0` is the same as setting `recurse => false` ---
Puppet will manage the directory, but all of its contents will be treated
as unmanaged.
Setting `recurselimit => 1` will manage files and directories that are
directly inside the directory, but will not manage the contents of any
subdirectories.
Setting `recurselimit => 2` will manage the direct contents of the
directory, as well as the contents of the _first_ level of subdirectories.
This pattern continues for each incremental value of `recurselimit`."
newvalues(/^[0-9]+$/)
munge do |value|
newval = super(value)
case newval
when Integer; value
when /^\d+$/; Integer(value)
else
self.fail _("Invalid recurselimit value %{value}") % { value: value.inspect }
end
end
end
newparam(:max_files) do
desc "In case the resource is a directory and the recursion is enabled, puppet will
generate a new resource for each file file found, possible leading to
an excessive number of resources generated without any control.
Setting `max_files` will check the number of file resources that
will eventually be created and will raise a resource argument error if the
limit will be exceeded.
Use value `0` to log a warning instead of raising an error.
Use value `-1` to disable errors and warnings due to max files."
defaultto 0
newvalues(/^[0-9]+$/, /^-1$/)
end
newparam(:replace, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to replace a file or symlink that already exists on the local system but
whose content doesn't match what the `source` or `content` attribute
specifies. Setting this to false allows file resources to initialize files
without overwriting future changes. Note that this only affects content;
Puppet will still manage ownership and permissions."
defaultto :true
end
newparam(:force, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Perform the file operation even if it will destroy one or more directories.
You must use `force` in order to:
* `purge` subdirectories
* Replace directories with files or links
* Remove a directory when `ensure => absent`"
defaultto false
end
newparam(:ignore) do
desc "A parameter which omits action on files matching
specified patterns during recursion. Uses Ruby's builtin globbing
engine, so shell metacharacters such as `[a-z]*` are fully supported.
Matches that would descend into the directory structure are ignored,
such as `*/*`."
validate do |value|
unless value.is_a?(Array) or value.is_a?(String) or value == false
devfail "Ignore must be a string or an Array"
end
end
end
newparam(:links) do
desc "How to handle links during file actions. During file copying,
`follow` will copy the target file instead of the link and `manage`
will copy the link itself. When not copying, `manage` will manage
the link, and `follow` will manage the file to which the link points."
newvalues(:follow, :manage)
defaultto :manage
end
newparam(:purge, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether unmanaged files should be purged. This option only makes
sense when `ensure => directory` and `recurse => true`.
* When recursively duplicating an entire directory with the `source`
attribute, `purge => true` will automatically purge any files
that are not in the source directory.
* When managing files in a directory as individual resources,
setting `purge => true` will purge any files that aren't being
specifically managed.
If you have a filebucket configured, the purged files will be uploaded,
but if you do not, this will destroy data.
Unless `force => true` is set, purging will **not** delete directories,
although it will delete the files they contain.
If `recurselimit` is set and you aren't using `force => true`, purging
will obey the recursion limit; files in any subdirectories deeper than the
limit will be treated as unmanaged and left alone."
defaultto :false
end
newparam(:sourceselect) do
desc "Whether to copy all valid sources, or just the first one. This parameter
only affects recursive directory copies; by default, the first valid
source is the only one used, but if this parameter is set to `all`, then
all valid sources will have all of their contents copied to the local
system. If a given file exists in more than one source, the version from
the earliest source in the list will be used."
defaultto :first
newvalues(:first, :all)
end
newparam(:show_diff, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to display differences when the file changes, defaulting to
true. This parameter is useful for files that may contain passwords or
other secret data, which might otherwise be included in Puppet reports or
other insecure outputs. If the global `show_diff` setting
is false, then no diffs will be shown even if this parameter is true."
defaultto :true
end
newparam(:staging_location) do
desc "When rendering a file first render it to this location. The default
location is the same path as the desired location with a unique filename.
This parameter is useful in conjuction with validate_cmd to test a
file before moving the file to it's final location.
WARNING: File replacement is only guaranteed to be atomic if the staging
location is on the same filesystem as the final location."
validate do |value|
unless Puppet::Util.absolute_path?(value)
fail Puppet::Error, "File paths must be fully qualified, not '#{value}'"
end
end
munge do |value|
if value.start_with?('//') and ::File.basename(value) == "/"
# This is a UNC path pointing to a share, so don't add a trailing slash
::File.expand_path(value)
else
::File.join(::File.split(::File.expand_path(value)))
end
end
end
newparam(:validate_cmd) do
desc "A command for validating the file's syntax before replacing it. If
Puppet would need to rewrite a file due to new `source` or `content`, it
will check the new content's validity first. If validation fails, the file
resource will fail.
This command must have a fully qualified path, and should contain a
percent (`%`) token where it would expect an input file. It must exit `0`
if the syntax is correct, and non-zero otherwise. The command will be
run on the target system while applying the catalog, not on the primary Puppet server.
Example:
file { '/etc/apache2/apache2.conf':
content => 'example',
validate_cmd => '/usr/sbin/apache2 -t -f %',
}
This would replace apache2.conf only if the test returned true.
Note that if a validation command requires a `%` as part of its text,
you can specify a different placeholder token with the
`validate_replacement` attribute."
end
newparam(:validate_replacement) do
desc "The replacement string in a `validate_cmd` that will be replaced
with an input file name."
defaultto '%'
end
# Autorequire the nearest ancestor directory found in the catalog.
autorequire(:file) do
req = []
path = Pathname.new(self[:path])
unless path.root?
# Start at our parent, to avoid autorequiring ourself
parents = path.parent.enum_for(:ascend)
found = parents.find { |p| catalog.resource(:file, p.to_s) }
if found
req << found.to_s
end
end
# if the resource is a link, make sure the target is created first
req << self[:target] if self[:target]
req
end
# Autorequire the owner and group of the file.
{ :user => :owner, :group => :group }.each do |type, property|
autorequire(type) do
if @parameters.include?(property)
# The user/group property automatically converts to IDs
should = @parameters[property].shouldorig
next unless should
val = should[0]
if val.is_a?(Integer) or val =~ /^\d+$/
nil
else
val
end
end
end
end
# mutually exclusive ways to create files
CREATORS = [:content, :source, :target].freeze
# This is both "checksum types that can't be used with the content property"
# and "checksum types that are not digest based"
SOURCE_ONLY_CHECKSUMS = [:none, :ctime, :mtime].freeze
validate do
creator_count = 0
CREATORS.each do |param|
creator_count += 1 if self.should(param)
end
creator_count += 1 if @parameters.include?(:source)
self.fail _("You cannot specify more than one of %{creators}") % { creators: CREATORS.collect(&:to_s).join(", ") } if creator_count > 1
self.fail _("You cannot specify a remote recursion without a source") if !self[:source] && self[:recurse] == :remote
self.fail _("You cannot specify source when using checksum 'none'") if self[:checksum] == :none && !self[:source].nil?
SOURCE_ONLY_CHECKSUMS.each do |checksum_type|
self.fail _("You cannot specify content when using checksum '%{checksum_type}'") % { checksum_type: checksum_type } if self[:checksum] == checksum_type && !self[:content].nil?
end
warning _("Possible error: recurselimit is set but not recurse, no recursion will happen") if !self[:recurse] && self[:recurselimit]
if @parameters[:content] && @parameters[:content].actual_content
# Now that we know the checksum, update content (in case it was created before checksum was known).
@parameters[:content].value = @parameters[:checksum].sum(@parameters[:content].actual_content)
end
if self[:checksum] && self[:checksum_value] && !valid_checksum?(self[:checksum], self[:checksum_value])
self.fail _("Checksum value '%{value}' is not a valid checksum type %{checksum}") % { value: self[:checksum_value], checksum: self[:checksum] }
end
warning _("Checksum value is ignored unless content or source are specified") if self[:checksum_value] && !self[:content] && !self[:source]
provider.validate if provider.respond_to?(:validate)
end
def self.[](path)
return nil unless path
super(path.gsub(%r{/+}, '/').sub(%r{/$}, ''))
end
def self.instances
[]
end
# Determine the user to write files as.
def asuser
if self.should(:owner) && !self.should(:owner).is_a?(Symbol)
writeable = Puppet::Util::SUIDManager.asuser(self.should(:owner)) {
FileTest.writable?(::File.dirname(self[:path]))
}
# If the parent directory is writeable, then we execute
# as the user in question. Otherwise we'll rely on
# the 'owner' property to do things.
asuser = self.should(:owner) if writeable
end
asuser
end
def bucket
return @bucket if @bucket
backup = self[:backup]
return nil unless backup
return nil if backup =~ /^\./
unless catalog or backup == "puppet"
fail _("Can not find filebucket for backups without a catalog")
end
filebucket = catalog.resource(:filebucket, backup) if catalog
if !catalog || (!filebucket && backup != 'puppet')
fail _("Could not find filebucket %{backup} specified in backup") % { backup: backup }
end
return default_bucket unless filebucket
@bucket = filebucket.bucket
@bucket
end
def default_bucket
Puppet::Type.type(:filebucket).mkdefaultbucket.bucket
end
# Does the file currently exist? Just checks for whether
# we have a stat
def exist?
stat ? true : false
end
def present?(current_values)
super && current_values[:ensure] != :false
end
# We have to do some extra finishing, to retrieve our bucket if
# there is one.
def finish
# Look up our bucket, if there is one
bucket
super
end
# Create any children via recursion or whatever.
def eval_generate
return [] unless recurse?
recurse
end
def ancestors
ancestors = Pathname.new(self[:path]).enum_for(:ascend).map(&:to_s)
ancestors.delete(self[:path])
ancestors
end
def flush
# We want to make sure we retrieve metadata anew on each transaction.
@parameters.each do |_name, param|
param.flush if param.respond_to?(:flush)
end
@stat = :needs_stat
end
def initialize(hash)
# Used for caching clients
@clients = {}
super
# If they've specified a source, we get our 'should' values
# from it.
unless self[:ensure]
if self[:target]
self[:ensure] = :link
elsif self[:content]
self[:ensure] = :file
end
end
@stat = :needs_stat
end
# Configure discovered resources to be purged.
def mark_children_for_purging(children)
children.each do |_name, child|
next if child[:source]
child[:ensure] = :absent
end
end
# Create a new file or directory object as a child to the current
# object.
def newchild(path)
full_path = ::File.join(self[:path], path)
# Add some new values to our original arguments -- these are the ones
# set at initialization. We specifically want to exclude any param
# values set by the :source property or any default values.
# LAK:NOTE This is kind of silly, because the whole point here is that
# the values set at initialization should live as long as the resource
# but values set by default or by :source should only live for the transaction
# or so. Unfortunately, we don't have a straightforward way to manage
# the different lifetimes of this data, so we kludge it like this.
# The right-side hash wins in the merge.
options = @original_parameters.merge(:path => full_path).compact
# These should never be passed to our children.
[:parent, :ensure, :recurse, :recurselimit, :max_files, :target, :alias, :source].each do |param|
options.delete(param) if options.include?(param)
end
self.class.new(options)
end
# Files handle paths specially, because they just lengthen their
# path names, rather than including the full parent's title each
# time.
def pathbuilder
# We specifically need to call the method here, so it looks
# up our parent in the catalog graph.
parent = parent()
if parent
# We only need to behave specially when our parent is also
# a file
if parent.is_a?(self.class)
# Remove the parent file name
list = parent.pathbuilder
list.pop # remove the parent's path info
list << ref
else
super
end
else
[ref]
end
end
# Recursively generate a list of file resources, which will
# be used to copy remote files, manage local files, and/or make links
# to map to another directory.
def recurse
children = (self[:recurse] == :remote) ? {} : recurse_local
if self[:target]
recurse_link(children)
elsif self[:source]
recurse_remote(children)
end
# If we're purging resources, then delete any resource that isn't on the
# remote system.
mark_children_for_purging(children) if purge?
result = children.values.sort_by { |a| a[:path] }
remove_less_specific_files(result)
end
def remove_less_specific_files(files)
existing_files = catalog.vertices.select { |r| r.is_a?(self.class) }
self.class.remove_less_specific_files(files, self[:path], existing_files) do |file|
file[:path]
end
end
# This is to fix bug #2296, where two files recurse over the same
# set of files. It's a rare case, and when it does happen you're
# not likely to have many actual conflicts, which is good, because
# this is a pretty inefficient implementation.
def self.remove_less_specific_files(files, parent_path, existing_files, &block)
# REVISIT: is this Windows safe? AltSeparator?
mypath = parent_path.split(::File::Separator)
other_paths = existing_files
.select { |r| (yield r) != parent_path }
.collect { |r| (yield r).split(::File::Separator) }
.select { |p| p[0, mypath.length] == mypath }
return files if other_paths.empty?
files.reject { |file|
path = (yield file).split(::File::Separator)
other_paths.any? { |p| path[0, p.length] == p }
}
end
# A simple method for determining whether we should be recursing.
def recurse?
self[:recurse] == true or self[:recurse] == :remote
end
# Recurse the target of the link.
def recurse_link(children)
perform_recursion(self[:target]).each do |meta|
if meta.relative_path == "."
self[:ensure] = :directory
next
end
children[meta.relative_path] ||= newchild(meta.relative_path)
if meta.ftype == "directory"
children[meta.relative_path][:ensure] = :directory
else
children[meta.relative_path][:ensure] = :link
children[meta.relative_path][:target] = meta.full_path
end
end
children
end
# Recurse the file itself, returning a Metadata instance for every found file.
def recurse_local
result = perform_recursion(self[:path])
return {} unless result
result.each_with_object({}) do |meta, hash|
next hash if meta.relative_path == "."
hash[meta.relative_path] = newchild(meta.relative_path)
end
end
# Recurse against our remote file.
def recurse_remote(children)
recurse_remote_metadata.each do |meta|
if meta.relative_path == "."
self[:checksum] = meta.checksum_type
parameter(:source).metadata = meta
next
end
children[meta.relative_path] ||= newchild(meta.relative_path)
children[meta.relative_path][:source] = meta.source
children[meta.relative_path][:checksum] = meta.checksum_type
children[meta.relative_path].parameter(:source).metadata = meta
end
children
end
def recurse_remote_metadata
sourceselect = self[:sourceselect]
total = self[:source].collect do |source|
# For each inlined file resource, the catalog contains a hash mapping
# source path to lists of metadata returned by a server-side search.
recursive_metadata = catalog.recursive_metadata[title]
if recursive_metadata
result = recursive_metadata[source]
else
result = perform_recursion(source)
end
next unless result
top = result.find { |r| r.relative_path == "." }
return [] if top && top.ftype != "directory"
result.each do |data|
if data.relative_path == '.'
data.source = source
else
# REMIND: appending file paths to URL may not be safe, e.g. foo+bar
data.source = "#{source}/#{data.relative_path}"
end
end
break result if result and !result.empty? and sourceselect == :first
result
end.flatten.compact
# This only happens if we have sourceselect == :all
unless sourceselect == :first
found = []
total.reject! do |data|
result = found.include?(data.relative_path)
found << data.relative_path unless result
result
end
end
total
end
def perform_recursion(path)
Puppet::FileServing::Metadata.indirection.search(
path,
:links => self[:links],
:recurse => (self[:recurse] == :remote ? true : self[:recurse]),
:recurselimit => self[:recurselimit],
:max_files => self[:max_files],
:source_permissions => self[:source_permissions],
:ignore => self[:ignore],
:checksum_type => (self[:source] || self[:content]) ? self[:checksum] : :none,
:environment => catalog.environment_instance
)
end
# Back up and remove the file or directory at `self[:path]`.
#
# @param [Symbol] should The file type replacing the current content.
# @return [Boolean] True if the file was removed, else False
# @raises [fail???] If the file could not be backed up or could not be removed.
def remove_existing(should)
wanted_type = should.to_s
current_type = read_current_type
if current_type.nil?
return false
end
if self[:backup]
if can_backup?(current_type)
backup_existing
else
warning _("Could not back up file of type %{current_type}") % { current_type: current_type }
end
end
if wanted_type != "link" and current_type == wanted_type
return false
end
case current_type
when "directory"
remove_directory(wanted_type)
when "link", "file", "fifo", "socket"
remove_file(current_type, wanted_type)
else
# Including: “blockSpecial”, “characterSpecial”, “unknown”
self.fail _("Could not remove files of type %{current_type}") % { current_type: current_type }
end
end
def retrieve
# This check is done in retrieve to ensure it happens before we try to use
# metadata in `copy_source_values`, but so it only fails the resource and not
# catalog validation (because that would be a breaking change from Puppet 4).
if Puppet::Util::Platform.windows? && parameter(:source) &&
[:use, :use_when_creating].include?(self[:source_permissions])
# TRANSLATORS "source_permissions => ignore" should not be translated
err_msg = _("Copying owner/mode/group from the source file on Windows is not supported; use source_permissions => ignore.")
if self[:owner].nil? || self[:group].nil? || self[:mode].nil?
# Fail on Windows if source permissions are being used and the file resource
# does not have mode owner, group, and mode all set (which would take precedence).
self.fail err_msg
else
# Warn if use source permissions is specified on Windows
warning err_msg
end
end
# `checksum_value` implies explicit management of all metadata, so skip metadata
# retrieval. Otherwise, if source is set, retrieve metadata for source.
if (source = parameter(:source)) && property(:checksum_value).nil?
source.copy_source_values
end
super
end
# Set the checksum, from another property. There are multiple
# properties that modify the contents of a file, and they need the
# ability to make sure that the checksum value is in sync.
def setchecksum(sum = nil)
if @parameters.include? :checksum
if sum
@parameters[:checksum].checksum = sum
else
# If they didn't pass in a sum, then tell checksum to
# figure it out.
currentvalue = @parameters[:checksum].retrieve
@parameters[:checksum].checksum = currentvalue
end
end
end
# Should this thing be a normal file? This is a relatively complex
# way of determining whether we're trying to create a normal file,
# and it's here so that the logic isn't visible in the content property.
def should_be_file?
return true if self[:ensure] == :file
# I.e., it's set to something like "directory"
return false if self[:ensure] && self[:ensure] != :present
# The user doesn't really care, apparently
if self[:ensure] == :present
return true unless stat
return(stat.ftype == "file")
end
# If we've gotten here, then :ensure isn't set
return true if self[:content]
return true if stat and stat.ftype == "file"
false
end
# Stat our file. Depending on the value of the 'links' attribute, we
# use either 'stat' or 'lstat', and we expect the properties to use the
# resulting stat object accordingly (mostly by testing the 'ftype'
# value).
#
# We use the initial value :needs_stat to ensure we only stat the file once,
# but can also keep track of a failed stat (@stat == nil). This also allows
# us to re-stat on demand by setting @stat = :needs_stat.
def stat
return @stat unless @stat == :needs_stat
method = :stat
# Files are the only types that support links
if instance_of?(Puppet::Type::File) and self[:links] != :follow
method = :lstat
end
@stat = begin
Puppet::FileSystem.send(method, self[:path])
rescue Errno::ENOENT
nil
rescue Errno::ENOTDIR
nil
rescue Errno::EACCES
warning _("Could not stat; permission denied")
nil
rescue Errno::EINVAL
warning _("Could not stat; invalid pathname")
nil
end
end
def to_resource
resource = super
resource.delete(:target) if resource[:target] == :notlink
resource
end
# Write out the file. To write content, pass the property as an argument
# to delegate writing to; must implement a #write method that takes the file
# as an argument.
def write(property = nil)
remove_existing(:file)
mode = self.should(:mode) # might be nil
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/type/notify.rb | lib/puppet/type/notify.rb | # frozen_string_literal: true
#
# Simple module for logging messages on the client-side
module Puppet
Type.newtype(:notify) do
@doc = "Sends an arbitrary message, specified as a string, to the agent run-time log. It's important to note that the notify resource type is not idempotent. As a result, notifications are shown as a change on every Puppet run."
apply_to_all
newproperty(:message, :idempotent => false) do
desc "The message to be sent to the log. Note that the value specified must be a string."
def sync
message = @sensitive ? 'Sensitive [value redacted]' : should
case @resource["withpath"]
when :true
send(@resource[:loglevel], message)
else
Puppet.send(@resource[:loglevel], message)
end
nil
end
def retrieve
:absent
end
def insync?(is)
false
end
defaultto { @resource[:name] }
end
newparam(:withpath) do
desc "Whether to show the full object path."
defaultto :false
newvalues(:true, :false)
end
newparam(:name) do
desc "An arbitrary tag for your own reference; the name of the message."
isnamevar
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/type/exec.rb | lib/puppet/type/exec.rb | # frozen_string_literal: true
module Puppet
Type.newtype(:exec) do
include Puppet::Util::Execution
require 'timeout'
@doc = "Executes external commands.
Any command in an `exec` resource **must** be able to run multiple times
without causing harm --- that is, it must be *idempotent*. There are three
main ways for an exec to be idempotent:
* The command itself is already idempotent. (For example, `apt-get update`.)
* The exec has an `onlyif`, `unless`, or `creates` attribute, which prevents
Puppet from running the command unless some condition is met. The
`onlyif` and `unless` commands of an `exec` are used in the process of
determining whether the `exec` is already in sync, therefore they must be run
during a noop Puppet run.
* The exec has `refreshonly => true`, which allows Puppet to run the
command only when some other resource is changed. (See the notes on refreshing
below.)
The state managed by an `exec` resource represents whether the specified command
_needs to be_ executed during the catalog run. The target state is always that
the command does not need to be executed. If the initial state is that the
command _does_ need to be executed, then successfully executing the command
transitions it to the target state.
The `unless`, `onlyif`, and `creates` properties check the initial state of the
resource. If one or more of these properties is specified, the exec might not
need to run. If the exec does not need to run, then the system is already in
the target state. In such cases, the exec is considered successful without
actually executing its command.
A caution: There's a widespread tendency to use collections of execs to
manage resources that aren't covered by an existing resource type. This
works fine for simple tasks, but once your exec pile gets complex enough
that you really have to think to understand what's happening, you should
consider developing a custom resource type instead, as it is much
more predictable and maintainable.
**Duplication:** Even though `command` is the namevar, Puppet allows
multiple `exec` resources with the same `command` value.
**Refresh:** `exec` resources can respond to refresh events (via
`notify`, `subscribe`, or the `~>` arrow). The refresh behavior of execs
is non-standard, and can be affected by the `refresh` and
`refreshonly` attributes:
* If `refreshonly` is set to true, the exec runs _only_ when it receives an
event. This is the most reliable way to use refresh with execs.
* If the exec has already run and then receives an event, it runs its
command **up to two times.** If an `onlyif`, `unless`, or `creates` condition
is no longer met after the first run, the second run does not occur.
* If the exec has already run, has a `refresh` command, and receives an
event, it runs its normal command. Then, if any `onlyif`, `unless`, or `creates`
conditions are still met, the exec runs its `refresh` command.
* If the exec has an `onlyif`, `unless`, or `creates` attribute that prevents it
from running, and it then receives an event, it still will not run.
* If the exec has `noop => true`, would otherwise have run, and receives
an event from a non-noop resource, it runs once. However, if it has a `refresh`
command, it runs that instead of its normal command.
In short: If there's a possibility of your exec receiving refresh events,
it is extremely important to make sure the run conditions are restricted.
**Autorequires:** If Puppet is managing an exec's cwd or the executable
file used in an exec's command, the exec resource autorequires those
files. If Puppet is managing the user that an exec should run as, the
exec resource autorequires that user."
# Create a new check mechanism. It's basically a parameter that
# provides one extra 'check' method.
def self.newcheck(name, options = {}, &block)
@checks ||= {}
check = newparam(name, options, &block)
@checks[name] = check
end
def self.checks
@checks.keys
end
newproperty(:returns, :array_matching => :all, :event => :executed_command) do |_property|
include Puppet::Util::Execution
munge(&:to_s)
def event_name
:executed_command
end
defaultto "0"
attr_reader :output
desc "The expected exit code(s). An error will be returned if the
executed command has some other exit code. Can be specified as an array
of acceptable exit codes or a single value.
On POSIX systems, exit codes are always integers between 0 and 255.
On Windows, **most** exit codes should be integers between 0
and 2147483647.
Larger exit codes on Windows can behave inconsistently across different
tools. The Win32 APIs define exit codes as 32-bit unsigned integers, but
both the cmd.exe shell and the .NET runtime cast them to signed
integers. This means some tools will report negative numbers for exit
codes above 2147483647. (For example, cmd.exe reports 4294967295 as -1.)
Since Puppet uses the plain Win32 APIs, it will report the very large
number instead of the negative number, which might not be what you
expect if you got the exit code from a cmd.exe session.
Microsoft recommends against using negative/very large exit codes, and
you should avoid them when possible. To convert a negative exit code to
the positive one Puppet will use, add it to 4294967296."
# Make output a bit prettier
def change_to_s(currentvalue, newvalue)
_("executed successfully")
end
# First verify that all of our checks pass.
def retrieve
# We need to return :notrun to trigger evaluation; when that isn't
# true, we *LIE* about what happened and return a "success" for the
# value, which causes us to be treated as in_sync?, which means we
# don't actually execute anything. I think. --daniel 2011-03-10
if @resource.check_all_attributes
:notrun
else
should
end
end
# Actually execute the command.
def sync
event = :executed_command
tries = resource[:tries]
try_sleep = resource[:try_sleep]
begin
tries.times do |try|
# Only add debug messages for tries > 1 to reduce log spam.
debug("Exec try #{try + 1}/#{tries}") if tries > 1
@output, @status = provider.run(resource[:command])
break if should.include?(@status.exitstatus.to_s)
if try_sleep > 0 and tries > 1
debug("Sleeping for #{try_sleep} seconds between tries")
sleep try_sleep
end
end
rescue Timeout::Error => e
self.fail Puppet::Error, _("Command exceeded timeout"), e
end
log = @resource[:logoutput]
if log
case log
when :true
log = @resource[:loglevel]
when :on_failure
if should.include?(@status.exitstatus.to_s)
log = :false
else
log = @resource[:loglevel]
end
end
unless log == :false
if @resource.parameter(:command).sensitive
send(log, "[output redacted]")
else
@output.split(/\n/).each { |line|
send(log, line)
}
end
end
end
unless should.include?(@status.exitstatus.to_s)
if @resource.parameter(:command).sensitive
# Don't print sensitive commands in the clear
self.fail(_("[command redacted] returned %{status} instead of one of [%{expected}]") % { status: @status.exitstatus, expected: should.join(",") })
else
self.fail(_("'%{cmd}' returned %{status} instead of one of [%{expected}]") % { cmd: resource[:command], status: @status.exitstatus, expected: should.join(",") })
end
end
event
end
end
newparam(:command) do
isnamevar
desc "The actual command to execute. Must either be fully qualified
or a search path for the command must be provided. If the command
succeeds, any output produced will be logged at the instance's
normal log level (usually `notice`), but if the command fails
(meaning its return code does not match the specified code) then
any output is logged at the `err` log level.
Multiple `exec` resources can use the same `command` value; Puppet
only uses the resource title to ensure `exec`s are unique.
On *nix platforms, the command can be specified as an array of
strings and Puppet will invoke it using the more secure method of
parameterized system calls. For example, rather than executing the
malicious injected code, this command will echo it out:
command => ['/bin/echo', 'hello world; rm -rf /']
"
validate do |command|
unless command.is_a?(String) || command.is_a?(Array)
raise ArgumentError, _("Command must be a String or Array<String>, got value of class %{klass}") % { klass: command.class }
end
end
end
newparam(:path) do
desc "The search path used for command execution.
Commands must be fully qualified if no path is specified. Paths
can be specified as an array or as a '#{File::PATH_SEPARATOR}' separated list."
# Support both arrays and colon-separated fields.
def value=(*values)
@value = values.flatten.collect { |val|
val.split(File::PATH_SEPARATOR)
}.flatten
end
end
newparam(:user) do
desc "The user to run the command as.
> **Note:** Puppet cannot execute commands as other users on Windows.
Note that if you use this attribute, any error output is not captured
due to a bug within Ruby. If you use Puppet to create this user, the
exec automatically requires the user, as long as it is specified by
name.
The $HOME environment variable is not automatically set when using
this attribute."
validate do |user|
if Puppet::Util::Platform.windows?
self.fail _("Unable to execute commands as other users on Windows")
elsif !Puppet.features.root? && resource.current_username() != user
self.fail _("Only root can execute commands as other users")
end
end
end
newparam(:group) do
desc "The group to run the command as. This seems to work quite
haphazardly on different platforms -- it is a platform issue
not a Ruby or Puppet one, since the same variety exists when
running commands as different users in the shell."
# Validation is handled by the SUIDManager class.
end
newparam(:cwd, :parent => Puppet::Parameter::Path) do
desc "The directory from which to run the command. If
this directory does not exist, the command will fail."
end
newparam(:logoutput) do
desc "Whether to log command output in addition to logging the
exit code. Defaults to `on_failure`, which only logs the output
when the command has an exit code that does not match any value
specified by the `returns` attribute. As with any resource type,
the log level can be controlled with the `loglevel` metaparameter."
defaultto :on_failure
newvalues(:true, :false, :on_failure)
end
newparam(:refresh) do
desc "An alternate command to run when the `exec` receives a refresh event
from another resource. By default, Puppet runs the main command again.
For more details, see the notes about refresh behavior above, in the
description for this resource type.
Note that this alternate command runs with the same `provider`, `path`,
`user`, and `group` as the main command. If the `path` isn't set, you
must fully qualify the command's name."
validate do |command|
provider.validatecmd(command)
end
end
newparam(:environment) do
desc "An array of any additional environment variables you want to set for a
command, such as `[ 'HOME=/root', 'MAIL=root@example.com']`.
Note that if you use this to set PATH, it will override the `path`
attribute. Multiple environment variables should be specified as an
array."
validate do |values|
values = [values] unless values.is_a? Array
values.each do |value|
unless value =~ /\w+=/
raise ArgumentError, _("Invalid environment setting '%{value}'") % { value: value }
end
end
end
end
newparam(:umask, :required_feature => :umask) do
desc "Sets the umask to be used while executing this command"
munge do |value|
if value =~ /^0?[0-7]{1,4}$/
return value.to_i(8)
else
raise Puppet::Error, _("The umask specification is invalid: %{value}") % { value: value.inspect }
end
end
end
newparam(:timeout) do
desc "The maximum time the command should take. If the command takes
longer than the timeout, the command is considered to have failed
and will be stopped. The timeout is specified in seconds. The default
timeout is 300 seconds and you can set it to 0 to disable the timeout."
munge do |value|
value = value.shift if value.is_a?(Array)
begin
value = Float(value)
rescue ArgumentError => e
raise ArgumentError, _("The timeout must be a number."), e.backtrace
end
[value, 0.0].max
end
defaultto 300
end
newparam(:tries) do
desc "The number of times execution of the command should be tried.
This many attempts will be made to execute the command until an
acceptable return code is returned. Note that the timeout parameter
applies to each try rather than to the complete set of tries."
munge do |value|
if value.is_a?(String)
unless value =~ /^\d+$/
raise ArgumentError, _("Tries must be an integer")
end
value = Integer(value)
end
raise ArgumentError, _("Tries must be an integer >= 1") if value < 1
value
end
defaultto 1
end
newparam(:try_sleep) do
desc "The time to sleep in seconds between 'tries'."
munge do |value|
if value.is_a?(String)
unless value =~ /^[-\d.]+$/
raise ArgumentError, _("try_sleep must be a number")
end
value = Float(value)
end
raise ArgumentError, _("try_sleep cannot be a negative number") if value < 0
value
end
defaultto 0
end
newcheck(:refreshonly) do
desc <<-'EOT'
The command should only be run as a
refresh mechanism for when a dependent object is changed. It only
makes sense to use this option when this command depends on some
other object; it is useful for triggering an action:
# Pull down the main aliases file
file { '/etc/aliases':
source => 'puppet://server/module/aliases',
}
# Rebuild the database, but only when the file changes
exec { newaliases:
path => ['/usr/bin', '/usr/sbin'],
subscribe => File['/etc/aliases'],
refreshonly => true,
}
Note that only `subscribe` and `notify` can trigger actions, not `require`,
so it only makes sense to use `refreshonly` with `subscribe` or `notify`.
EOT
newvalues(:true, :false)
# We always fail this test, because we're only supposed to run
# on refresh.
def check(value)
# We have to invert the values.
value != :true
end
end
newcheck(:creates, :parent => Puppet::Parameter::Path) do
desc <<-'EOT'
A file to look for before running the command. The command will
only run if the file **doesn't exist.**
This parameter doesn't cause Puppet to create a file; it is only
useful if **the command itself** creates a file.
exec { 'tar -xf /Volumes/nfs02/important.tar':
cwd => '/var/tmp',
creates => '/var/tmp/myfile',
path => ['/usr/bin', '/usr/sbin',],
}
In this example, `myfile` is assumed to be a file inside
`important.tar`. If it is ever deleted, the exec will bring it
back by re-extracting the tarball. If `important.tar` does **not**
actually contain `myfile`, the exec will keep running every time
Puppet runs.
This parameter can also take an array of files, and the command will
not run if **any** of these files exist. Consider this example:
creates => ['/tmp/file1', '/tmp/file2'],
The command is only run if both files don't exist.
EOT
accept_arrays
# If the file exists, return false (i.e., don't run the command),
# else return true
def check(value)
# TRANSLATORS 'creates' is a parameter name and should not be translated
debug(_("Checking that 'creates' path '%{creates_path}' exists") % { creates_path: value })
!Puppet::FileSystem.exist?(value)
end
end
newcheck(:unless) do
desc <<-'EOT'
A test command that checks the state of the target system and restricts
when the `exec` can run. If present, Puppet runs this test command
first, then runs the main command unless the test has an exit code of 0
(success). For example:
exec { '/bin/echo root >> /usr/lib/cron/cron.allow':
path => '/usr/bin:/usr/sbin:/bin',
unless => 'grep ^root$ /usr/lib/cron/cron.allow 2>/dev/null',
}
This would add `root` to the cron.allow file (on Solaris) unless
`grep` determines it's already there.
Note that this test command runs with the same `provider`, `path`,
`user`, `cwd`, and `group` as the main command. If the `path` isn't set, you
must fully qualify the command's name.
Since this command is used in the process of determining whether the
`exec` is already in sync, it must be run during a noop Puppet run.
This parameter can also take an array of commands. For example:
unless => ['test -f /tmp/file1', 'test -f /tmp/file2'],
or an array of arrays. For example:
unless => [['test', '-f', '/tmp/file1'], 'test -f /tmp/file2']
This `exec` would only run if every command in the array has a
non-zero exit code.
EOT
validate do |cmds|
cmds = [cmds] unless cmds.is_a? Array
cmds.each do |command|
provider.validatecmd(command)
end
end
# Return true if the command does not return 0.
def check(value)
begin
output, status = provider.run(value, true)
rescue Timeout::Error
err _("Check %{value} exceeded timeout") % { value: value.inspect }
return false
end
if sensitive
debug("[output redacted]")
else
output.split(/\n/).each { |line|
debug(line)
}
end
status.exitstatus != 0
end
end
newcheck(:onlyif) do
desc <<-'EOT'
A test command that checks the state of the target system and restricts
when the `exec` can run. If present, Puppet runs this test command
first, and only runs the main command if the test has an exit code of 0
(success). For example:
exec { 'logrotate':
path => '/usr/bin:/usr/sbin:/bin',
provider => shell,
onlyif => 'test `du /var/log/messages | cut -f1` -gt 100000',
}
This would run `logrotate` only if that test returns true.
Note that this test command runs with the same `provider`, `path`,
`user`, `cwd`, and `group` as the main command. If the `path` isn't set, you
must fully qualify the command's name.
Since this command is used in the process of determining whether the
`exec` is already in sync, it must be run during a noop Puppet run.
This parameter can also take an array of commands. For example:
onlyif => ['test -f /tmp/file1', 'test -f /tmp/file2'],
or an array of arrays. For example:
onlyif => [['test', '-f', '/tmp/file1'], 'test -f /tmp/file2']
This `exec` would only run if every command in the array has an
exit code of 0 (success).
EOT
validate do |cmds|
cmds = [cmds] unless cmds.is_a? Array
cmds.each do |command|
provider.validatecmd(command)
end
end
# Return true if the command returns 0.
def check(value)
begin
output, status = provider.run(value, true)
rescue Timeout::Error
err _("Check %{value} exceeded timeout") % { value: value.inspect }
return false
end
if sensitive
debug("[output redacted]")
else
output.split(/\n/).each { |line|
debug(line)
}
end
status.exitstatus == 0
end
end
# Exec names are not isomorphic with the objects.
@isomorphic = false
validate do
provider.validatecmd(self[:command])
end
# FIXME exec should autorequire any exec that 'creates' our cwd
autorequire(:file) do
reqs = []
# Stick the cwd in there if we have it
reqs << self[:cwd] if self[:cwd]
file_regex = Puppet::Util::Platform.windows? ? %r{^([a-zA-Z]:[\\/]\S+)} : %r{^(/\S+)}
cmd = self[:command]
cmd = cmd[0] if cmd.is_a? Array
if cmd.is_a?(Puppet::Pops::Evaluator::DeferredValue)
debug("The 'command' parameter is deferred and cannot be autorequired")
else
cmd.scan(file_regex) { |str|
reqs << str
}
cmd.scan(/^"([^"]+)"/) { |str|
reqs << str
}
end
[:onlyif, :unless].each { |param|
tmp = self[param]
next unless tmp
tmp = [tmp] unless tmp.is_a? Array
tmp.each do |line|
# And search the command line for files, adding any we
# find. This will also catch the command itself if it's
# fully qualified. It might not be a bad idea to add
# unqualified files, but, well, that's a bit more annoying
# to do.
line = line[0] if line.is_a? Array
if line.is_a?(Puppet::Pops::Evaluator::DeferredValue)
debug("The '#{param}' parameter is deferred and cannot be autorequired")
else
reqs += line.scan(file_regex)
end
end
}
# For some reason, the += isn't causing a flattening
reqs.flatten!
reqs
end
autorequire(:user) do
# Autorequire users if they are specified by name
user = self[:user]
if user && user !~ /^\d+$/
user
end
end
def self.instances
[]
end
# Verify that we pass all of the checks. The argument determines whether
# we skip the :refreshonly check, which is necessary because we now check
# within refresh
def check_all_attributes(refreshing = false)
self.class.checks.each { |check|
next if refreshing and check == :refreshonly
next unless @parameters.include?(check)
val = @parameters[check].value
val = [val] unless val.is_a? Array
val.each do |value|
next if @parameters[check].check(value)
# Give a debug message so users can figure out what command would have been
# but don't print sensitive commands or parameters in the clear
cmdstring = @parameters[:command].sensitive ? "[command redacted]" : @parameters[:command].value
debug(_("'%{cmd}' won't be executed because of failed check '%{check}'") % { cmd: cmdstring, check: check })
return false
end
}
true
end
def output
if property(:returns).nil?
nil
else
property(:returns).output
end
end
# Run the command, or optionally run a separately-specified command.
def refresh
if check_all_attributes(true)
cmd = self[:refresh]
if cmd
provider.run(cmd)
else
property(:returns).sync
end
end
end
def current_username
Etc.getpwuid(Process.uid).name
end
private
def set_sensitive_parameters(sensitive_parameters)
# If any are sensitive, mark all as sensitive
sensitive = false
parameters_to_check = [:command, :unless, :onlyif]
parameters_to_check.each do |p|
if sensitive_parameters.include?(p)
sensitive_parameters.delete(p)
sensitive = true
end
end
if sensitive
parameters_to_check.each do |p|
if parameters.include?(p)
parameter(p).sensitive = true
end
end
end
super(sensitive_parameters)
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/type/filebucket.rb | lib/puppet/type/filebucket.rb | # frozen_string_literal: true
module Puppet
require_relative '../../puppet/file_bucket/dipper'
Type.newtype(:filebucket) do
@doc = <<-EOT
A repository for storing and retrieving file content by cryptographic checksum. Can
be local to each agent node, or centralized on a primary Puppet server. All
puppet servers provide a filebucket service that agent nodes can access
via HTTP, but you must declare a filebucket resource before any agents
will do so.
Filebuckets are used for the following features:
- **Content backups.** If the `file` type's `backup` attribute is set to
the name of a filebucket, Puppet will back up the _old_ content whenever
it rewrites a file; see the documentation for the `file` type for more
details. These backups can be used for manual recovery of content, but
are more commonly used to display changes and differences in a tool like
Puppet Dashboard.
To use a central filebucket for backups, you will usually want to declare
a filebucket resource and a resource default for the `backup` attribute
in site.pp:
# /etc/puppetlabs/puppet/manifests/site.pp
filebucket { 'main':
path => false, # This is required for remote filebuckets.
server => 'puppet.example.com', # Optional; defaults to the configured primary server.
}
File { backup => main, }
Puppet Servers automatically provide the filebucket service, so
this will work in a default configuration. If you have a heavily
restricted Puppet Server `auth.conf` file, you may need to allow access to the
`file_bucket_file` endpoint.
EOT
newparam(:name) do
desc "The name of the filebucket."
isnamevar
end
newparam(:server) do
desc "The server providing the remote filebucket service.
This setting is _only_ consulted if the `path` attribute is set to `false`.
If this attribute is not specified, the first entry in the `server_list`
configuration setting is used, followed by the value of the `server` setting
if `server_list` is not set."
end
newparam(:port) do
desc "The port on which the remote server is listening.
This setting is _only_ consulted if the `path` attribute is set to `false`.
If this attribute is not specified, the first entry in the `server_list`
configuration setting is used, followed by the value of the `serverport`
setting if `server_list` is not set."
end
newparam(:path) do
desc "The path to the _local_ filebucket; defaults to the value of the
`clientbucketdir` setting. To use a remote filebucket, you _must_ set
this attribute to `false`."
defaultto { Puppet[:clientbucketdir] }
validate do |value|
if value.is_a? Array
raise ArgumentError, _("You can only have one filebucket path")
end
if value.is_a? String and !Puppet::Util.absolute_path?(value)
raise ArgumentError, _("Filebucket paths must be absolute")
end
true
end
end
# Create a default filebucket.
def self.mkdefaultbucket
new(:name => "puppet", :path => Puppet[:clientbucketdir])
end
def bucket
mkbucket unless defined?(@bucket)
@bucket
end
private
def mkbucket
# Default is a local filebucket, if no server is given.
# If the default path has been removed, too, then
# the puppetmaster is used as default server
type = "local"
args = {}
if self[:path]
args[:Path] = self[:path]
else
args[:Server] = self[:server]
args[:Port] = self[:port]
end
begin
@bucket = Puppet::FileBucket::Dipper.new(args)
rescue => detail
message = _("Could not create %{type} filebucket: %{detail}") % { type: type, detail: detail }
log_exception(detail, message)
self.fail(message)
end
@bucket.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/type/service.rb | lib/puppet/type/service.rb | # frozen_string_literal: true
# This is our main way of managing processes right now.
#
# a service is distinct from a process in that services
# can only be managed through the interface of an init script
# which is why they have a search path for initscripts and such
module Puppet
Type.newtype(:service) do
@doc = "Manage running services. Service support unfortunately varies
widely by platform --- some platforms have very little if any concept of a
running service, and some have a very codified and powerful concept.
Puppet's service support is usually capable of doing the right thing, but
the more information you can provide, the better behaviour you will get.
Puppet 2.7 and newer expect init scripts to have a working status command.
If this isn't the case for any of your services' init scripts, you will
need to set `hasstatus` to false and possibly specify a custom status
command in the `status` attribute. As a last resort, Puppet will attempt to
search the process table by calling whatever command is listed in the `ps`
fact. The default search pattern is the name of the service, but you can
specify it with the `pattern` attribute.
**Refresh:** `service` resources can respond to refresh events (via
`notify`, `subscribe`, or the `~>` arrow). If a `service` receives an
event from another resource, Puppet will restart the service it manages.
The actual command used to restart the service depends on the platform and
can be configured:
* If you set `hasrestart` to true, Puppet will use the init script's restart command.
* You can provide an explicit command for restarting with the `restart` attribute.
* If you do neither, the service's stop and start commands will be used."
feature :refreshable, "The provider can restart the service.",
:methods => [:restart]
feature :enableable, "The provider can enable and disable the service.",
:methods => [:disable, :enable, :enabled?]
feature :delayed_startable, "The provider can set service to delayed start",
:methods => [:delayed_start]
feature :manual_startable, "The provider can set service to manual start",
:methods => [:manual_start]
feature :controllable, "The provider uses a control variable."
feature :flaggable, "The provider can pass flags to the service."
feature :maskable, "The provider can 'mask' the service.",
:methods => [:mask]
feature :configurable_timeout, "The provider can specify a minumum timeout for syncing service properties"
feature :manages_logon_credentials, "The provider can specify the logon credentials used for a service"
newproperty(:enable, :required_features => :enableable) do
desc "Whether a service should be enabled to start at boot.
This property behaves differently depending on the platform;
wherever possible, it relies on local tools to enable or disable
a given service. Default values depend on the platform.
If you don't specify a value for the `enable` attribute, Puppet leaves
that aspect of the service alone and your operating system determines
the behavior."
newvalue(:true, :event => :service_enabled) do
provider.enable
end
newvalue(:false, :event => :service_disabled) do
provider.disable
end
newvalue(:manual, :event => :service_manual_start, :required_features => :manual_startable) do
provider.manual_start
end
# This only makes sense on systemd systems. Otherwise, it just defaults
# to disable.
newvalue(:mask, :event => :service_disabled, :required_features => :maskable) do
provider.mask
end
def retrieve
provider.enabled?
end
newvalue(:delayed, :event => :service_delayed_start, :required_features => :delayed_startable) do
provider.delayed_start
end
def insync?(current)
return provider.enabled_insync?(current) if provider.respond_to?(:enabled_insync?)
super(current)
end
end
# Handle whether the service should actually be running right now.
newproperty(:ensure) do
desc "Whether a service should be running. Default values depend on the platform."
newvalue(:stopped, :event => :service_stopped) do
provider.stop
end
newvalue(:running, :event => :service_started, :invalidate_refreshes => true) do
provider.start
end
aliasvalue(:false, :stopped)
aliasvalue(:true, :running)
def retrieve
provider.status
end
def sync
property = @resource.property(:logonaccount)
if property
val = property.retrieve
property.sync unless property.safe_insync?(val)
end
event = super()
property = @resource.property(:enable)
if property
val = property.retrieve
property.sync unless property.safe_insync?(val)
end
event
end
end
newproperty(:logonaccount, :required_features => :manages_logon_credentials) do
desc "Specify an account for service logon"
def insync?(current)
return provider.logonaccount_insync?(current) if provider.respond_to?(:logonaccount_insync?)
super(current)
end
end
newparam(:logonpassword, :required_features => :manages_logon_credentials) do
desc "Specify a password for service logon. Default value is an empty string (when logonaccount is specified)."
validate do |value|
raise ArgumentError, _("Passwords cannot include ':'") if value.is_a?(String) && value.include?(":")
end
sensitive true
defaultto { @resource[:logonaccount] ? "" : nil }
end
newproperty(:flags, :required_features => :flaggable) do
desc "Specify a string of flags to pass to the startup script."
end
newparam(:binary) do
desc "The path to the daemon. This is only used for
systems that do not support init scripts. This binary will be
used to start the service if no `start` parameter is
provided."
end
newparam(:hasstatus) do
desc "Declare whether the service's init script has a functional status
command. This attribute's default value changed in Puppet 2.7.0.
The init script's status command must return 0 if the service is
running and a nonzero value otherwise. Ideally, these exit codes
should conform to [the LSB's specification][lsb-exit-codes] for init
script status actions, but Puppet only considers the difference
between 0 and nonzero to be relevant.
If a service's init script does not support any kind of status command,
you should set `hasstatus` to false and either provide a specific
command using the `status` attribute or expect that Puppet will look for
the service name in the process table. Be aware that 'virtual' init
scripts (like 'network' under Red Hat systems) will respond poorly to
refresh events from other resources if you override the default behavior
without providing a status command."
newvalues(:true, :false)
defaultto :true
end
newparam(:name) do
desc <<-EOT
The name of the service to run.
This name is used to find the service; on platforms where services
have short system names and long display names, this should be the
short name. (To take an example from Windows, you would use "wuauserv"
rather than "Automatic Updates.")
EOT
isnamevar
end
newparam(:path) do
desc "The search path for finding init scripts. Multiple values should
be separated by colons or provided as an array."
munge do |value|
value = [value] unless value.is_a?(Array)
value.flatten.collect { |p| p.split(File::PATH_SEPARATOR) }.flatten
end
defaultto { provider.class.defpath if provider.class.respond_to?(:defpath) }
end
newparam(:pattern) do
desc "The pattern to search for in the process table.
This is used for stopping services on platforms that do not
support init scripts, and is also used for determining service
status on those service whose init scripts do not include a status
command.
Defaults to the name of the service. The pattern can be a simple string
or any legal Ruby pattern, including regular expressions (which should
be quoted without enclosing slashes)."
defaultto { @resource[:binary] || @resource[:name] }
end
newparam(:restart) do
desc "Specify a *restart* command manually. If left
unspecified, the service will be stopped and then started."
end
newparam(:start) do
desc "Specify a *start* command manually. Most service subsystems
support a `start` command, so this will not need to be
specified."
end
newparam(:status) do
desc "Specify a *status* command manually. This command must
return 0 if the service is running and a nonzero value otherwise.
Ideally, these exit codes should conform to [the LSB's
specification][lsb-exit-codes] for init script status actions, but
Puppet only considers the difference between 0 and nonzero to be
relevant.
If left unspecified, the status of the service will be determined
automatically, usually by looking for the service in the process
table.
[lsb-exit-codes]: http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html"
end
newparam(:stop) do
desc "Specify a *stop* command manually."
end
newparam(:control) do
desc "The control variable used to manage services (originally for HP-UX).
Defaults to the upcased service name plus `START` replacing dots with
underscores, for those providers that support the `controllable` feature."
defaultto { resource.name.tr(".", "_").upcase + "_START" if resource.provider.controllable? }
end
newparam :hasrestart do
desc "Specify that an init script has a `restart` command. If this is
false and you do not specify a command in the `restart` attribute,
the init script's `stop` and `start` commands will be used."
newvalues(:true, :false)
end
newparam(:manifest) do
desc "Specify a command to config a service, or a path to a manifest to do so."
end
newparam(:timeout, :required_features => :configurable_timeout) do
desc "Specify an optional minimum timeout (in seconds) for puppet to wait when syncing service properties"
defaultto { provider.respond_to?(:default_timeout) ? provider.default_timeout : 10 }
munge do |value|
value = value.to_i
raise if value < 1
value
rescue
raise Puppet::Error, _("\"%{value}\" is not a positive integer: the timeout parameter must be specified as a positive integer") % { value: value }
end
end
# Basically just a synonym for restarting. Used to respond
# to events.
def refresh
# Only restart if we're actually running
if (@parameters[:ensure] || newattr(:ensure)).retrieve == :running
provider.restart
else
debug "Skipping restart; service is not running"
end
end
def self.needs_ensure_retrieved
false
end
validate do
if @parameters[:logonpassword] && @parameters[:logonaccount].nil?
raise Puppet::Error, _("The 'logonaccount' parameter is mandatory when setting 'logonpassword'.")
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/type/whit.rb | lib/puppet/type/whit.rb | # frozen_string_literal: true
Puppet::Type.newtype(:whit) do
desc "Whits are internal artifacts of Puppet's current implementation, and
Puppet suppresses their appearance in all logs. We make no guarantee of
the whit's continued existence, and it should never be used in an actual
manifest. Use the `anchor` type from the puppetlabs-stdlib module if you
need arbitrary whit-like no-op resources."
newparam :name do
desc "The name of the whit, because it must have one."
end
# Hide the fact that we're a whit from logs.
#
# I hate you, milkman whit. You are so painful, so often.
#
# In this case the memoized version means we generate a new string about 1.9
# percent of the time, and we allocate about 1.6MB less memory, and generate
# a whole lot less GC churn.
#
# That number probably goes up at least O(n) with the complexity of your
# catalog, and I suspect beyond that, because that is, like, 10,000 calls
# for 200 distinct objects. Even with just linear, that is a constant
# factor of, like, 50n. --daniel 2012-07-17
def to_s
@to_s ||= name.sub(/^completed_|^admissible_/, "")
end
alias path to_s
def refresh
# We don't do anything with them, but we need this to show that we are
# "refresh aware" and not break the chain of propagation.
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/type/tidy.rb | lib/puppet/type/tidy.rb | # frozen_string_literal: true
require_relative '../../puppet/parameter/boolean'
Puppet::Type.newtype(:tidy) do
require_relative '../../puppet/file_serving/fileset'
require_relative '../../puppet/file_bucket/dipper'
@doc = "Remove unwanted files based on specific criteria. Multiple
criteria are OR'd together, so a file that is too large but is not
old enough will still get tidied. Ignores managed resources.
If you don't specify either `age` or `size`, then all files will
be removed.
This resource type works by generating a file resource for every file
that should be deleted and then letting that resource perform the
actual deletion.
"
# Tidy names are not isomorphic with the objects.
@isomorphic = false
newparam(:path) do
desc "The path to the file or directory to manage. Must be fully
qualified."
isnamevar
munge do |value|
File.expand_path(value)
end
end
newparam(:recurse) do
desc "If target is a directory, recursively descend
into the directory looking for files to tidy. Numeric values
specify a limit for the recursion depth, `true` means
unrestricted recursion."
newvalues(:true, :false, :inf, /^[0-9]+$/)
# Replace the validation so that we allow numbers in
# addition to string representations of them.
validate { |arg| }
munge do |value|
newval = super(value)
case newval
when :true, :inf; true
when :false; false
when Integer; value
when /^\d+$/; Integer(value)
else
raise ArgumentError, _("Invalid recurse value %{value}") % { value: value.inspect }
end
end
end
newparam(:max_files) do
desc "In case the resource is a directory and the recursion is enabled, puppet will
generate a new resource for each file file found, possible leading to
an excessive number of resources generated without any control.
Setting `max_files` will check the number of file resources that
will eventually be created and will raise a resource argument error if the
limit will be exceeded.
Use value `0` to disable the check. In this case, a warning is logged if
the number of files exceeds 1000."
defaultto 0
newvalues(/^[0-9]+$/)
end
newparam(:matches) do
desc <<-'EOT'
One or more (shell type) file glob patterns, which restrict
the list of files to be tidied to those whose basenames match
at least one of the patterns specified. Multiple patterns can
be specified using an array.
Example:
tidy { '/tmp':
age => '1w',
recurse => 1,
matches => [ '[0-9]pub*.tmp', '*.temp', 'tmpfile?' ],
}
This removes files from `/tmp` if they are one week old or older,
are not in a subdirectory and match one of the shell globs given.
Note that the patterns are matched against the basename of each
file -- that is, your glob patterns should not have any '/'
characters in them, since you are only specifying against the last
bit of the file.
Finally, note that you must now specify a non-zero/non-false value
for recurse if matches is used, as matches only apply to files found
by recursion (there's no reason to use static patterns match against
a statically determined path). Requiring explicit recursion clears
up a common source of confusion.
EOT
# Make sure we convert to an array.
munge do |value|
fail _("Tidy can't use matches with recurse 0, false, or undef") if (@resource[:recurse]).to_s =~ /^(0|false|)$/
[value].flatten
end
# Does a given path match our glob patterns, if any? Return true
# if no patterns have been provided.
def tidy?(path, stat)
basename = File.basename(path)
flags = File::FNM_DOTMATCH | File::FNM_PATHNAME
(value.find { |pattern| File.fnmatch(pattern, basename, flags) } ? true : false)
end
end
newparam(:backup) do
desc "Whether tidied files should be backed up. Any values are passed
directly to the file resources used for actual file deletion, so consult
the `file` type's backup documentation to determine valid values."
end
newparam(:age) do
desc "Tidy files whose age is equal to or greater than
the specified time. You can choose seconds, minutes,
hours, days, or weeks by specifying the first letter of any
of those words (for example, '1w' represents one week).
Specifying 0 will remove all files."
AgeConvertors = {
:s => 1,
:m => 60,
:h => 60 * 60,
:d => 60 * 60 * 24,
:w => 60 * 60 * 24 * 7,
}
def convert(unit, multi)
num = AgeConvertors[unit]
if num
num * multi
else
self.fail _("Invalid age unit '%{unit}'") % { unit: unit }
end
end
def tidy?(path, stat)
# If the file's older than we allow, we should get rid of it.
(Time.now.to_i - stat.send(resource[:type]).to_i) >= value
end
munge do |age|
unit = multi = nil
case age
when /^([0-9]+)(\w)\w*$/
multi = Integer(Regexp.last_match(1))
unit = Regexp.last_match(2).downcase.intern
when /^([0-9]+)$/
multi = Integer(Regexp.last_match(1))
unit = :d
else
# TRANSLATORS tidy is the name of a program and should not be translated
self.fail _("Invalid tidy age %{age}") % { age: age }
end
convert(unit, multi)
end
end
newparam(:size) do
desc "Tidy files whose size is equal to or greater than
the specified size. Unqualified values are in kilobytes, but
*b*, *k*, *m*, *g*, and *t* can be appended to specify *bytes*,
*kilobytes*, *megabytes*, *gigabytes*, and *terabytes*, respectively.
Only the first character is significant, so the full word can also
be used."
def convert(unit, multi)
num = { :b => 0, :k => 1, :m => 2, :g => 3, :t => 4 }[unit]
if num
result = multi
num.times do result *= 1024 end
result
else
self.fail _("Invalid size unit '%{unit}'") % { unit: unit }
end
end
def tidy?(path, stat)
stat.size >= value
end
munge do |size|
case size
when /^([0-9]+)(\w)\w*$/
multi = Integer(Regexp.last_match(1))
unit = Regexp.last_match(2).downcase.intern
when /^([0-9]+)$/
multi = Integer(Regexp.last_match(1))
unit = :k
else
# TRANSLATORS tidy is the name of a program and should not be translated
self.fail _("Invalid tidy size %{age}") % { age: age }
end
convert(unit, multi)
end
end
newparam(:type) do
desc "Set the mechanism for determining age."
newvalues(:atime, :mtime, :ctime)
defaultto :atime
end
newparam(:rmdirs, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Tidy directories in addition to files; that is, remove
directories whose age is older than the specified criteria.
This will only remove empty directories, so all contained
files must also be tidied before a directory gets removed."
end
# Erase PFile's validate method
validate do
end
def self.instances
[]
end
def depthfirst?
true
end
def initialize(hash)
super
# only allow backing up into filebuckets
self[:backup] = false unless self[:backup].is_a? Puppet::FileBucket::Dipper
end
# Make a file resource to remove a given file.
def mkfile(path)
# Force deletion, so directories actually get deleted.
parameters = {
:path => path, :backup => self[:backup],
:ensure => :absent, :force => true
}
new_file = Puppet::Type.type(:file).new(parameters)
new_file.copy_metaparams(@parameters)
new_file
end
def retrieve
# Our ensure property knows how to retrieve everything for us.
obj = @parameters[:ensure]
if obj
obj.retrieve
else
{}
end
end
# Hack things a bit so we only ever check the ensure property.
def properties
[]
end
def generate
return [] unless stat(self[:path])
case self[:recurse]
when Integer, /^\d+$/
parameter = { :max_files => self[:max_files],
:recurse => true,
:recurselimit => self[:recurse] }
when true, :true, :inf
parameter = { :max_files => self[:max_files],
:recurse => true }
end
if parameter
files = Puppet::FileServing::Fileset.new(self[:path], parameter).files.collect do |f|
f == "." ? self[:path] : ::File.join(self[:path], f)
end
else
files = [self[:path]]
end
found_files = files.find_all { |path| tidy?(path) }.collect { |path| mkfile(path) }
result = found_files.each { |file| debug "Tidying #{file.ref}" }.sort { |a, b| b[:path] <=> a[:path] }
if found_files.size > 0
# TRANSLATORS "Tidy" is a program name and should not be translated
notice _("Tidying %{count} files") % { count: found_files.size }
end
# No need to worry about relationships if we don't have rmdirs; there won't be
# any directories.
return result unless rmdirs?
# Now make sure that all directories require the files they contain, if all are available,
# so that a directory is emptied before we try to remove it.
files_by_name = result.each_with_object({}) { |file, hash| hash[file[:path]] = file; }
files_by_name.keys.sort { |a, b| b <=> a }.each do |path|
dir = ::File.dirname(path)
resource = files_by_name[dir]
next unless resource
if resource[:require]
resource[:require] << Puppet::Resource.new(:file, path)
else
resource[:require] = [Puppet::Resource.new(:file, path)]
end
end
result
end
# Does a given path match our glob patterns, if any? Return true
# if no patterns have been provided.
def matches?(path)
return true unless self[:matches]
basename = File.basename(path)
flags = File::FNM_DOTMATCH | File::FNM_PATHNAME
if self[:matches].find { |pattern| File.fnmatch(pattern, basename, flags) }
true
else
debug "No specified patterns match #{path}, not tidying"
false
end
end
# Should we remove the specified file?
def tidy?(path)
# ignore files that are already managed, since we can't tidy
# those files anyway
return false if catalog.resource(:file, path)
stat = self.stat(path)
return false unless stat
return false if stat.ftype == "directory" and !rmdirs?
# The 'matches' parameter isn't OR'ed with the other tests --
# it's just used to reduce the list of files we can match.
param = parameter(:matches)
return false if param && !param.tidy?(path, stat)
tested = false
[:age, :size].each do |name|
param = parameter(name)
next unless param
tested = true
return true if param.tidy?(path, stat)
end
# If they don't specify either, then the file should always be removed.
return true unless tested
false
end
def stat(path)
Puppet::FileSystem.lstat(path)
rescue Errno::ENOENT
debug _("File does not exist")
nil
rescue Errno::EACCES
# TRANSLATORS "stat" is a program name and should not be translated
warning _("Could not stat; permission denied")
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/type/schedule.rb | lib/puppet/type/schedule.rb | # frozen_string_literal: true
module Puppet
Type.newtype(:schedule) do
@doc = <<-'EOT'
Define schedules for Puppet. Resources can be limited to a schedule by using the
[`schedule`](https://puppet.com/docs/puppet/latest/metaparameter.html#schedule)
metaparameter.
Currently, **schedules can only be used to stop a resource from being
applied;** they cannot cause a resource to be applied when it otherwise
wouldn't be, and they cannot accurately specify a time when a resource
should run.
Every time Puppet applies its configuration, it will apply the
set of resources whose schedule does not eliminate them from
running right then, but there is currently no system in place to
guarantee that a given resource runs at a given time. If you
specify a very restrictive schedule and Puppet happens to run at a
time within that schedule, then the resources will get applied;
otherwise, that work may never get done.
Thus, it is advisable to use wider scheduling (for example, over a couple
of hours) combined with periods and repetitions. For instance, if you
wanted to restrict certain resources to only running once, between
the hours of two and 4 AM, then you would use this schedule:
schedule { 'maint':
range => '2 - 4',
period => daily,
repeat => 1,
}
With this schedule, the first time that Puppet runs between 2 and 4 AM,
all resources with this schedule will get applied, but they won't
get applied again between 2 and 4 because they will have already
run once that day, and they won't get applied outside that schedule
because they will be outside the scheduled range.
Puppet automatically creates a schedule for each of the valid periods
with the same name as that period (such as hourly and daily).
Additionally, a schedule named `puppet` is created and used as the
default, with the following attributes:
schedule { 'puppet':
period => hourly,
repeat => 2,
}
This will cause resources to be applied every 30 minutes by default.
The `statettl` setting on the agent affects the ability of a schedule to
determine if a resource has already been checked. If the `statettl` is
set lower than the span of the associated schedule resource, then a
resource could be checked & applied multiple times in the schedule as
the information about when the resource was last checked will have
expired from the cache.
EOT
apply_to_all
newparam(:name) do
desc <<-EOT
The name of the schedule. This name is used when assigning the schedule
to a resource with the `schedule` metaparameter:
schedule { 'everyday':
period => daily,
range => '2 - 4',
}
exec { '/usr/bin/apt-get update':
schedule => 'everyday',
}
EOT
isnamevar
end
newparam(:range) do
desc <<-EOT
The earliest and latest that a resource can be applied. This is
always a hyphen-separated range within a 24 hour period, and hours
must be specified in numbers between 0 and 23, inclusive. Minutes and
seconds can optionally be provided, using the normal colon as a
separator. For instance:
schedule { 'maintenance':
range => '1:30 - 4:30',
}
This is mostly useful for restricting certain resources to being
applied in maintenance windows or during off-peak hours. Multiple
ranges can be applied in array context. As a convenience when specifying
ranges, you can cross midnight (for example, `range => "22:00 - 04:00"`).
EOT
# This is lame; properties all use arrays as values, but parameters don't.
# That's going to hurt eventually.
validate do |values|
values = [values] unless values.is_a?(Array)
values.each { |value|
unless value.is_a?(String) and
value =~ /\d+(:\d+){0,2}\s*-\s*\d+(:\d+){0,2}/
self.fail _("Invalid range value '%{value}'") % { value: value }
end
}
end
munge do |values|
values = [values] unless values.is_a?(Array)
ret = []
values.each { |value|
range = []
# Split each range value into a hour, minute, second triad
value.split(/\s*-\s*/).each { |val|
# Add the values as an array.
range << val.split(":").collect(&:to_i)
}
self.fail _("Invalid range %{value}") % { value: value } if range.length != 2
# Fill out 0s for unspecified minutes and seconds
range.each do |time_array|
(3 - time_array.length).times { |_| time_array << 0 }
end
# Make sure the hours are valid
[range[0][0], range[1][0]].each do |n|
raise ArgumentError, _("Invalid hour '%{n}'") % { n: n } if n < 0 or n > 23
end
[range[0][1], range[1][1]].each do |n|
raise ArgumentError, _("Invalid minute '%{n}'") % { n: n } if n and (n < 0 or n > 59)
end
ret << range
}
# Now our array of arrays
ret
end
def weekday_match?(day)
if @resource[:weekday]
@resource[:weekday].has_key?(day)
else
true
end
end
def match?(previous, now)
# The lowest-level array is of the hour, minute, second triad
# then it's an array of two of those, to present the limits
# then it's an array of those ranges
@value = [@value] unless @value[0][0].is_a?(Array)
@value.any? do |range|
limit_start = Time.local(now.year, now.month, now.day, *range[0])
limit_end = Time.local(now.year, now.month, now.day, *range[1])
if limit_start < limit_end
# The whole range is in one day, simple case
now.between?(limit_start, limit_end) && weekday_match?(now.wday)
else
# The range spans days. We have to test against a range starting
# today, and a range that started yesterday.
today = Date.new(now.year, now.month, now.day)
tomorrow = today.next_day
yesterday = today.prev_day
# First check a range starting today
if now.between?(limit_start, Time.local(tomorrow.year, tomorrow.month, tomorrow.day, *range[1]))
weekday_match?(today.wday)
else
# Then check a range starting yesterday
now.between?(Time.local(yesterday.year, yesterday.month, yesterday.day, *range[0]),
limit_end) &&
weekday_match?(yesterday.wday)
end
end
end
end
end
newparam(:periodmatch) do
desc "Whether periods should be matched by a numeric value (for instance,
whether two times are in the same hour) or by their chronological
distance apart (whether two times are 60 minutes apart)."
newvalues(:number, :distance)
defaultto :distance
end
newparam(:period) do
desc <<-EOT
The period of repetition for resources on this schedule. The default is
for resources to get applied every time Puppet runs.
Note that the period defines how often a given resource will get
applied but not when; if you would like to restrict the hours
that a given resource can be applied (for instance, only at night
during a maintenance window), then use the `range` attribute.
If the provided periods are not sufficient, you can provide a
value to the *repeat* attribute, which will cause Puppet to
schedule the affected resources evenly in the period the
specified number of times. Take this schedule:
schedule { 'veryoften':
period => hourly,
repeat => 6,
}
This can cause Puppet to apply that resource up to every 10 minutes.
At the moment, Puppet cannot guarantee that level of repetition; that
is, the resource can applied _up to_ every 10 minutes, but internal
factors might prevent it from actually running that often (for instance,
if a Puppet run is still in progress when the next run is scheduled to
start, that next run will be suppressed).
See the `periodmatch` attribute for tuning whether to match
times by their distance apart or by their specific value.
> **Tip**: You can use `period => never,` to prevent a resource from being applied
in the given `range`. This is useful if you need to create a blackout window to
perform sensitive operations without interruption.
EOT
newvalues(:hourly, :daily, :weekly, :monthly, :never)
ScheduleScales = {
:hourly => 3600,
:daily => 86_400,
:weekly => 604_800,
:monthly => 2_592_000
}
ScheduleMethods = {
:hourly => :hour,
:daily => :day,
:monthly => :month,
:weekly => proc do |prev, now|
# Run the resource if the previous day was after this weekday (e.g., prev is wed, current is tue)
# or if it's been more than a week since we ran
prev.wday > now.wday or (now - prev) > (24 * 3600 * 7)
end
}
def match?(previous, now)
return false if value == :never
value = self.value
case @resource[:periodmatch]
when :number
method = ScheduleMethods[value]
if method.is_a?(Proc)
method.call(previous, now)
else
# We negate it, because if they're equal we don't run
now.send(method) != previous.send(method)
end
when :distance
scale = ScheduleScales[value]
# If the number of seconds between the two times is greater
# than the unit of time, we match. We divide the scale
# by the repeat, so that we'll repeat that often within
# the scale.
(now.to_i - previous.to_i) >= (scale / @resource[:repeat])
end
end
end
newparam(:repeat) do
desc "How often a given resource may be applied in this schedule's `period`.
Must be an integer."
defaultto 1
validate do |value|
unless value.is_a?(Integer) or value =~ /^\d+$/
raise Puppet::Error,
_("Repeat must be a number")
end
# This implicitly assumes that 'periodmatch' is distance -- that
# is, if there's no value, we assume it's a valid value.
return unless @resource[:periodmatch]
if value != 1 and @resource[:periodmatch] != :distance
raise Puppet::Error,
_("Repeat must be 1 unless periodmatch is 'distance', not '%{period}'") % { period: @resource[:periodmatch] }
end
end
munge do |value|
value = Integer(value) unless value.is_a?(Integer)
value
end
def match?(previous, now)
true
end
end
newparam(:weekday) do
desc <<-EOT
The days of the week in which the schedule should be valid.
You may specify the full day name 'Tuesday', the three character
abbreviation 'Tue', or a number (as a string or as an integer) corresponding to the day of the
week where 0 is Sunday, 1 is Monday, and so on. Multiple days can be specified
as an array. If not specified, the day of the week will not be
considered in the schedule.
If you are also using a range match that spans across midnight
then this parameter will match the day that it was at the start
of the range, not necessarily the day that it is when it matches.
For example, consider this schedule:
schedule { 'maintenance_window':
range => '22:00 - 04:00',
weekday => 'Saturday',
}
This will match at 11 PM on Saturday and 2 AM on Sunday, but not
at 2 AM on Saturday.
EOT
validate do |values|
values = [values] unless values.is_a?(Array)
values.each { |value|
if weekday_integer?(value) || weekday_string?(value)
value
else
raise ArgumentError, _("%{value} is not a valid day of the week") % { value: value }
end
}
end
def weekday_integer?(value)
value.is_a?(Integer) && (0..6).cover?(value)
end
def weekday_string?(value)
value.is_a?(String) && (value =~ /^[0-6]$/ || value =~ /^(Mon|Tues?|Wed(?:nes)?|Thu(?:rs)?|Fri|Sat(?:ur)?|Sun)(day)?$/i)
end
weekdays = {
'sun' => 0,
'mon' => 1,
'tue' => 2,
'wed' => 3,
'thu' => 4,
'fri' => 5,
'sat' => 6,
}
munge do |values|
values = [values] unless values.is_a?(Array)
ret = {}
values.each do |value|
case value
when /^[0-6]$/
index = value.to_i
when 0..6
index = value
else
index = weekdays[value[0, 3].downcase]
end
ret[index] = true
end
ret
end
def match?(previous, now)
# Special case weekday matching with ranges to a no-op here.
# If the ranges span days then we can't simply match the current
# weekday, as we want to match the weekday as it was when the range
# started. As a result, all of that logic is in range, not here.
return true if @resource[:range]
return true if value.has_key?(now.wday)
false
end
end
def self.instances
[]
end
def self.mkdefaultschedules
result = []
unless Puppet[:default_schedules]
Puppet.debug "Not creating default schedules: default_schedules is false"
return result
end
Puppet.debug "Creating default schedules"
result << new(
:name => "puppet",
:period => :hourly,
:repeat => "2"
)
# And then one for every period
@parameters.find { |p| p.name == :period }.value_collection.values.each { |value|
result << new(
:name => value.to_s,
:period => value
)
}
result
end
def match?(previous = nil, now = nil)
# If we've got a value, then convert it to a Time instance
previous &&= Time.at(previous)
now ||= Time.now
# Pull them in order
self.class.allattrs.each { |param|
if @parameters.include?(param) and
@parameters[param].respond_to?(:match?)
return false unless @parameters[param].match?(previous, now)
end
}
# If we haven't returned false, then return true; in other words,
# any provided schedules need to all match
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/type/user.rb | lib/puppet/type/user.rb | # frozen_string_literal: true
require 'etc'
require_relative '../../puppet/parameter/boolean'
require_relative '../../puppet/property/list'
require_relative '../../puppet/property/ordered_list'
require_relative '../../puppet/property/keyvalue'
module Puppet
Type.newtype(:user) do
@doc = "Manage users. This type is mostly built to manage system
users, so it is lacking some features useful for managing normal
users.
This resource type uses the prescribed native tools for creating
groups and generally uses POSIX APIs for retrieving information
about them. It does not directly modify `/etc/passwd` or anything.
**Autorequires:** If Puppet is managing the user's primary group (as
provided in the `gid` attribute) or any group listed in the `groups`
attribute then the user resource will autorequire that group. If Puppet
is managing any role accounts corresponding to the user's roles, the
user resource will autorequire those role accounts."
feature :allows_duplicates,
"The provider supports duplicate users with the same UID."
feature :manages_homedir,
"The provider can create and remove home directories."
feature :manages_passwords,
"The provider can modify user passwords, by accepting a password
hash."
feature :manages_password_age,
"The provider can set age requirements and restrictions for
passwords."
feature :manages_password_salt,
"The provider can set a password salt. This is for providers that
implement PBKDF2 passwords with salt properties."
feature :manages_solaris_rbac,
"The provider can manage normal users"
feature :manages_roles,
"The provider can manage roles"
feature :manages_expiry,
"The provider can manage the expiry date for a user."
feature :system_users,
"The provider allows you to create system users with lower UIDs."
feature :manages_aix_lam,
"The provider can manage AIX Loadable Authentication Module (LAM) system."
feature :manages_local_users_and_groups,
"Allows local users to be managed on systems that also use some other
remote Name Service Switch (NSS) method of managing accounts."
feature :manages_shell,
"The provider allows for setting shell and validates if possible"
feature :manages_loginclass,
"The provider can manage the login class for a user."
newproperty(:ensure, :parent => Puppet::Property::Ensure) do
newvalue(:present, :event => :user_created) do
provider.create
end
newvalue(:absent, :event => :user_removed) do
provider.delete
end
newvalue(:role, :event => :role_created, :required_features => :manages_solaris_rbac) do
provider.create_role
end
desc "The basic state that the object should be in."
# If they're talking about the thing at all, they generally want to
# say it should exist.
defaultto do
if @resource.managed?
:present
else
nil
end
end
def retrieve
if provider.exists?
if provider.respond_to?(:is_role?) and provider.is_role?
:role
else
:present
end
else
:absent
end
end
def sync
event = super
property = @resource.property(:roles)
if property
val = property.retrieve
property.sync unless property.safe_insync?(val)
end
event
end
end
newproperty(:home) do
desc "The home directory of the user. The directory must be created
separately and is not currently checked for existence."
end
newproperty(:uid) do
desc "The user ID; must be specified numerically. If no user ID is
specified when creating a new user, then one will be chosen
automatically. This will likely result in the same user having
different UIDs on different systems, which is not recommended. This is
especially noteworthy when managing the same user on both Darwin and
other platforms, since Puppet does UID generation on Darwin, but
the underlying tools do so on other platforms.
On Windows, this property is read-only and will return the user's
security identifier (SID)."
munge do |value|
case value
when String
if value =~ /^[-0-9]+$/
value = Integer(value)
end
end
return value
end
end
newproperty(:gid) do
desc "The user's primary group. Can be specified numerically or by name.
This attribute is not supported on Windows systems; use the `groups`
attribute instead. (On Windows, designating a primary group is only
meaningful for domain accounts, which Puppet does not currently manage.)"
munge do |value|
if value.is_a?(String) and value =~ /^[-0-9]+$/
Integer(value)
else
value
end
end
def insync?(is)
# We know the 'is' is a number, so we need to convert the 'should' to a number,
# too.
@should.each do |value|
return true if is == Puppet::Util.gid(value)
end
false
end
def sync
found = false
@should.each do |value|
number = Puppet::Util.gid(value)
next unless number
provider.gid = number
found = true
break
end
fail _("Could not find group(s) %{groups}") % { groups: @should.join(",") } unless found
# Use the default event.
end
end
newproperty(:comment) do
desc "A description of the user. Generally the user's full name."
def insync?(is)
# nameservice provider requires special attention to encoding
# Overrides Puppet::Property#insync?
if !@should.empty? && provider.respond_to?(:comments_insync?)
return provider.comments_insync?(is, @should)
end
super(is)
end
# In the case that our comments have incompatible encodings, set external
# encoding to support concatenation for display.
# overrides Puppet::Property#change_to_s
def change_to_s(currentvalue, newvalue)
if newvalue.is_a?(String) && !Encoding.compatible?(currentvalue, newvalue)
return super(currentvalue, newvalue.dup.force_encoding(currentvalue.encoding))
end
super(currentvalue, newvalue)
end
end
newproperty(:shell, :required_features => :manages_shell) do
desc "The user's login shell. The shell must exist and be
executable.
This attribute cannot be managed on Windows systems."
end
newproperty(:password, :required_features => :manages_passwords) do
desc %q{The user's password, in whatever encrypted format the local system
requires. Consult your operating system's documentation for acceptable password
encryption formats and requirements.
* Mac OS X 10.5 and 10.6, and some older Linux distributions, use salted SHA1
hashes. You can use Puppet's built-in `sha1` function to generate a salted SHA1
hash from a password.
* Mac OS X 10.7 (Lion), and many recent Linux distributions, use salted SHA512
hashes. The Puppet Labs [stdlib][] module contains a `str2saltedsha512` function
which can generate password hashes for these operating systems.
* OS X 10.8 and higher use salted SHA512 PBKDF2 hashes. When managing passwords
on these systems, the `salt` and `iterations` attributes need to be specified as
well as the password.
* macOS 10.15 and later require the salt to be 32 bytes. Because Puppet's user
resource requires the value to be hex encoded, the length of the salt's
string must be 64.
* Windows passwords can be managed only in cleartext, because there is no Windows
API for setting the password hash.
[stdlib]: https://github.com/puppetlabs/puppetlabs-stdlib/
Enclose any value that includes a dollar sign ($) in single quotes (') to avoid
accidental variable interpolation.
To redact passwords from reports to PuppetDB, use the `Sensitive` data type. For
example, this resource protects the password:
```puppet
user { 'foo':
ensure => present,
password => Sensitive("my secret password")
}
```
This results in the password being redacted from the report, as in the
`previous_value`, `desired_value`, and `message` fields below.
```yaml
events:
- !ruby/object:Puppet::Transaction::Event
audited: false
property: password
previous_value: "[redacted]"
desired_value: "[redacted]"
historical_value:
message: changed [redacted] to [redacted]
name: :password_changed
status: success
time: 2017-05-17 16:06:02.934398293 -07:00
redacted: true
corrective_change: false
corrective_change: false
```
}
validate do |value|
raise ArgumentError, _("Passwords cannot include ':'") if value.is_a?(String) and value.include?(":")
end
sensitive true
end
newproperty(:password_min_age, :required_features => :manages_password_age) do
desc "The minimum number of days a password must be used before it may be changed."
munge do |value|
case value
when String
Integer(value)
else
value
end
end
validate do |value|
if value.to_s !~ /^-?\d+$/
raise ArgumentError, _("Password minimum age must be provided as a number.")
end
end
end
newproperty(:password_max_age, :required_features => :manages_password_age) do
desc "The maximum number of days a password may be used before it must be changed."
munge do |value|
case value
when String
Integer(value)
else
value
end
end
validate do |value|
if value.to_s !~ /^-?\d+$/
raise ArgumentError, _("Password maximum age must be provided as a number.")
end
end
end
newproperty(:password_warn_days, :required_features => :manages_password_age) do
desc "The number of days before a password is going to expire (see the maximum password age) during which the user should be warned."
munge do |value|
case value
when String
Integer(value)
else
value
end
end
validate do |value|
if value.to_s !~ /^-?\d+$/
raise ArgumentError, "Password warning days must be provided as a number."
end
end
end
newproperty(:groups, :parent => Puppet::Property::List) do
desc "The groups to which the user belongs. The primary group should
not be listed, and groups should be identified by name rather than by
GID. Multiple groups should be specified as an array."
validate do |value|
if value =~ /^\d+$/
raise ArgumentError, _("Group names must be provided, not GID numbers.")
end
raise ArgumentError, _("Group names must be provided as an array, not a comma-separated list.") if value.include?(",")
raise ArgumentError, _("Group names must not be empty. If you want to specify \"no groups\" pass an empty array") if value.empty?
end
def change_to_s(currentvalue, newvalue)
newvalue = newvalue.split(",") if newvalue != :absent
if provider.respond_to?(:groups_to_s)
# for Windows ADSI
# de-dupe the "newvalue" when the sync event message is generated,
# due to final retrieve called after the resource has been modified
newvalue = provider.groups_to_s(newvalue).split(',').uniq
end
super(currentvalue, newvalue)
end
# override Puppet::Property::List#retrieve
def retrieve
if provider.respond_to?(:groups_to_s)
# Windows ADSI groups returns SIDs, but retrieve needs names
# must return qualified names for SIDs for "is" value and puppet resource
return provider.groups_to_s(provider.groups).split(',')
end
super
end
def insync?(current)
if provider.respond_to?(:groups_insync?)
return provider.groups_insync?(current, @should)
end
super(current)
end
end
newparam(:name) do
desc "The user name. While naming limitations vary by operating system,
it is advisable to restrict names to the lowest common denominator,
which is a maximum of 8 characters beginning with a letter.
Note that Puppet considers user names to be case-sensitive, regardless
of the platform's own rules; be sure to always use the same case when
referring to a given user."
isnamevar
end
newparam(:membership) do
desc "If `minimum` is specified, Puppet will ensure that the user is a
member of all specified groups, but will not remove any other groups
that the user is a part of.
If `inclusive` is specified, Puppet will ensure that the user is a
member of **only** specified groups."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newparam(:system, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether the user is a system user, according to the OS's criteria;
on most platforms, a UID less than or equal to 500 indicates a system
user. This parameter is only used when the resource is created and will
not affect the UID when the user is present."
defaultto false
end
newparam(:allowdupe, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to allow duplicate UIDs."
defaultto false
end
newparam(:managehome, :boolean => true, :parent => Puppet::Parameter::Boolean) do
desc "Whether to manage the home directory when Puppet creates or removes the user.
This creates the home directory if Puppet also creates the user account, and deletes the
home directory if Puppet also removes the user account.
This parameter has no effect unless Puppet is also creating or removing the user in the
resource at the same time. For instance, Puppet creates a home directory for a managed
user if `ensure => present` and the user does not exist at the time of the Puppet run.
If the home directory is then deleted manually, Puppet will not recreate it on the next
run.
Note that on Windows, this manages creation/deletion of the user profile instead of the
home directory. The user profile is stored in the `C:\\Users\\<username>` directory."
defaultto false
validate do |val|
if munge(val)
raise ArgumentError, _("User provider %{name} can not manage home directories") % { name: provider.class.name } if provider and !provider.class.manages_homedir?
end
end
end
newproperty(:expiry, :required_features => :manages_expiry) do
desc "The expiry date for this user. Provide as either the special
value `absent` to ensure that the account never expires, or as
a zero-padded YYYY-MM-DD format -- for example, 2010-02-19."
newvalues :absent
newvalues(/^\d{4}-\d{2}-\d{2}$/)
validate do |value|
if value.intern != :absent and value !~ /^\d{4}-\d{2}-\d{2}$/
# TRANSLATORS YYYY-MM-DD represents a date with a four-digit year, a two-digit month, and a two-digit day,
# TRANSLATORS separated by dashes.
raise ArgumentError, _("Expiry dates must be YYYY-MM-DD or the string \"absent\"")
end
end
end
# Autorequire the group, if it's around
autorequire(:group) do
autos = []
# autorequire primary group, if managed
obj = @parameters[:gid]
groups = obj.shouldorig if obj
if groups
groups = groups.collect { |group|
if group.is_a?(String) && group =~ /^\d+$/
Integer(group)
else
group
end
}
groups.each { |group|
case group
when Integer
resource = catalog.resources.find { |r| r.is_a?(Puppet::Type.type(:group)) && r.should(:gid) == group }
if resource
autos << resource
end
else
autos << group
end
}
end
# autorequire groups, excluding primary group, if managed
obj = @parameters[:groups]
if obj
groups = obj.should
if groups
autos += groups.split(",")
end
end
autos
end
# This method has been exposed for puppet to manage users and groups of
# files in its settings and should not be considered available outside of
# puppet.
#
# (see Puppet::Settings#service_user_available?)
#
# @return [Boolean] if the user exists on the system
# @api private
def exists?
provider.exists?
end
newproperty(:roles, :parent => Puppet::Property::List, :required_features => :manages_roles) do
desc "The roles the user has. Multiple roles should be
specified as an array."
def membership
:role_membership
end
validate do |value|
if value =~ /^\d+$/
raise ArgumentError, _("Role names must be provided, not numbers")
end
raise ArgumentError, _("Role names must be provided as an array, not a comma-separated list") if value.include?(",")
end
end
# autorequire the roles that the user has
autorequire(:user) do
reqs = []
roles_property = @parameters[:roles]
roles = roles_property.should if roles_property
if roles
reqs += roles.split(',')
end
reqs
end unless Puppet::Util::Platform.windows?
newparam(:role_membership) do
desc "Whether specified roles should be considered the **complete list**
(`inclusive`) or the **minimum list** (`minimum`) of roles the user
has."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newproperty(:auths, :parent => Puppet::Property::List, :required_features => :manages_solaris_rbac) do
desc "The auths the user has. Multiple auths should be
specified as an array."
def membership
:auth_membership
end
validate do |value|
if value =~ /^\d+$/
raise ArgumentError, _("Auth names must be provided, not numbers")
end
raise ArgumentError, _("Auth names must be provided as an array, not a comma-separated list") if value.include?(",")
end
end
newparam(:auth_membership) do
desc "Whether specified auths should be considered the **complete list**
(`inclusive`) or the **minimum list** (`minimum`) of auths the user
has. This setting is specific to managing Solaris authorizations."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newproperty(:profiles, :parent => Puppet::Property::OrderedList, :required_features => :manages_solaris_rbac) do
desc "The profiles the user has. Multiple profiles should be
specified as an array."
def membership
:profile_membership
end
validate do |value|
if value =~ /^\d+$/
raise ArgumentError, _("Profile names must be provided, not numbers")
end
raise ArgumentError, _("Profile names must be provided as an array, not a comma-separated list") if value.include?(",")
end
end
newparam(:profile_membership) do
desc "Whether specified roles should be treated as the **complete list**
(`inclusive`) or the **minimum list** (`minimum`) of roles
of which the user is a member."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newproperty(:keys, :parent => Puppet::Property::KeyValue, :required_features => :manages_solaris_rbac) do
desc "Specify user attributes in an array of key = value pairs."
def membership
:key_membership
end
end
newparam(:key_membership) do
desc "Whether specified key/value pairs should be considered the
**complete list** (`inclusive`) or the **minimum list** (`minimum`) of
the user's attributes."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newproperty(:project, :required_features => :manages_solaris_rbac) do
desc "The name of the project associated with a user."
end
newparam(:ia_load_module, :required_features => :manages_aix_lam) do
desc "The name of the I&A module to use to manage this user.
This should be set to `files` if managing local users."
end
newproperty(:attributes, :parent => Puppet::Property::KeyValue, :required_features => :manages_aix_lam) do
desc "Specify AIX attributes for the user in an array or hash of attribute = value pairs.
For example:
```
['minage=0', 'maxage=5', 'SYSTEM=compat']
```
or
```
attributes => { 'minage' => '0', 'maxage' => '5', 'SYSTEM' => 'compat' }
```
"
self.log_only_changed_or_new_keys = true
def membership
:attribute_membership
end
def delimiter
" "
end
end
newparam(:attribute_membership) do
desc "Whether specified attribute value pairs should be treated as the
**complete list** (`inclusive`) or the **minimum list** (`minimum`) of
attribute/value pairs for the user."
newvalues(:inclusive, :minimum)
defaultto :minimum
end
newproperty(:salt, :required_features => :manages_password_salt) do
desc "This is the 32-byte salt used to generate the PBKDF2 password used in
OS X. This field is required for managing passwords on OS X >= 10.8."
end
newproperty(:iterations, :required_features => :manages_password_salt) do
desc "This is the number of iterations of a chained computation of the
[PBKDF2 password hash](https://en.wikipedia.org/wiki/PBKDF2). This parameter
is used in OS X, and is required for managing passwords on OS X 10.8 and
newer."
munge do |value|
if value.is_a?(String) and value =~ /^[-0-9]+$/
Integer(value)
else
value
end
end
end
newparam(:forcelocal, :boolean => true,
:required_features => :manages_local_users_and_groups,
:parent => Puppet::Parameter::Boolean) do
desc "Forces the management of local accounts when accounts are also
being managed by some other Name Service Switch (NSS). For AIX, refer to the `ia_load_module` parameter.
This option relies on your operating system's implementation of `luser*` commands, such as `luseradd` , and `lgroupadd`, `lusermod`. The `forcelocal` option could behave unpredictably in some circumstances. If the tools it depends on are not available, it might have no effect at all."
defaultto false
end
def generate
unless self[:purge_ssh_keys].empty?
if Puppet::Type.type(:ssh_authorized_key).nil?
warning _("Ssh_authorized_key type is not available. Cannot purge SSH keys.")
else
return find_unmanaged_keys
end
end
[]
end
newparam(:purge_ssh_keys) do
desc "Whether to purge authorized SSH keys for this user if they are not managed
with the `ssh_authorized_key` resource type. This parameter is a noop if the
ssh_authorized_key type is not available.
Allowed values are:
* `false` (default) --- don't purge SSH keys for this user.
* `true` --- look for keys in the `.ssh/authorized_keys` file in the user's
home directory. Purge any keys that aren't managed as `ssh_authorized_key`
resources.
* An array of file paths --- look for keys in all of the files listed. Purge
any keys that aren't managed as `ssh_authorized_key` resources. If any of
these paths starts with `~` or `%h`, that token will be replaced with
the user's home directory."
defaultto :false
# Use Symbols instead of booleans until PUP-1967 is resolved.
newvalues(:true, :false)
validate do |value|
if [:true, :false].include? value.to_s.intern
return
end
value = [value] if value.is_a?(String)
if value.is_a?(Array)
value.each do |entry|
raise ArgumentError, _("Each entry for purge_ssh_keys must be a string, not a %{klass}") % { klass: entry.class } unless entry.is_a?(String)
valid_home = Puppet::Util.absolute_path?(entry) || entry =~ %r{^~/|^%h/}
raise ArgumentError, _("Paths to keyfiles must be absolute, not %{entry}") % { entry: entry } unless valid_home
end
return
end
raise ArgumentError, _("purge_ssh_keys must be true, false, or an array of file names, not %{value}") % { value: value.inspect }
end
munge do |value|
# Resolve string, boolean and symbol forms of true and false to a
# single representation.
case value
when :false, false, "false"
[]
when :true, true, "true"
home = homedir
home ? ["#{home}/.ssh/authorized_keys"] : []
else
# value can be a string or array - munge each value
[value].flatten.filter_map do |entry|
authorized_keys_path(entry)
end
end
end
private
def homedir
resource[:home] || Dir.home(resource[:name])
rescue ArgumentError
Puppet.debug("User '#{resource[:name]}' does not exist")
nil
end
def authorized_keys_path(entry)
return entry unless entry.match?(%r{^(?:~|%h)/})
# if user doesn't exist (yet), ignore nonexistent homedir
home = homedir
return nil unless home
# compiler freezes "value" so duplicate using a gsub, second mutating gsub! is then ok
entry = entry.gsub(%r{^~/}, "#{home}/")
entry.gsub!(%r{^%h/}, "#{home}/")
entry
end
end
newproperty(:loginclass, :required_features => :manages_loginclass) do
desc "The name of login class to which the user belongs."
validate do |value|
if value =~ /^\d+$/
raise ArgumentError, _("Class name must be provided.")
end
end
end
# Generate ssh_authorized_keys resources for purging. The key files are
# taken from the purge_ssh_keys parameter. The generated resources inherit
# all metaparameters from the parent user resource.
#
# @return [Array<Puppet::Type::Ssh_authorized_key] a list of resources
# representing the found keys
# @see generate
# @api private
def find_unmanaged_keys
self[:purge_ssh_keys]
.select { |f| File.readable?(f) }
.map { |f| unknown_keys_in_file(f) }
.flatten.each do |res|
res[:ensure] = :absent
res[:user] = self[:name]
res.copy_metaparams(@parameters)
end
end
# Parse an ssh authorized keys file superficially, extract the comments
# on the keys. These are considered names of possible ssh_authorized_keys
# resources. Keys that are managed by the present catalog are ignored.
#
# @see generate
# @api private
# @return [Array<Puppet::Type::Ssh_authorized_key] a list of resources
# representing the found keys
def unknown_keys_in_file(keyfile)
# The ssh_authorized_key type is distributed as a module on the Forge,
# so we shouldn't rely on it being available.
return [] unless Puppet::Type.type(:ssh_authorized_key)
names = []
name_index = 0
# RFC 4716 specifies UTF-8 allowed in public key files per https://www.ietf.org/rfc/rfc4716.txt
# the authorized_keys file may contain UTF-8 comments
Puppet::FileSystem.open(keyfile, nil, 'r:UTF-8').each do |line|
next unless line =~ Puppet::Type.type(:ssh_authorized_key).keyline_regex
# the name is stored in the 4th capture of the regex
name = ::Regexp.last_match(4)
if name.empty?
::Regexp.last_match(3).delete("\n")
# If no comment is specified for this key, generate a unique internal
# name. This uses the same rules as
# provider/ssh_authorized_key/parsed (PUP-3357)
name = "#{keyfile}:unnamed-#{name_index += 1}"
end
names << name
Puppet.debug "#{ref} parsed for purging Ssh_authorized_key[#{name}]"
end
names.map { |keyname|
Puppet::Type.type(:ssh_authorized_key).new(
:name => keyname,
:target => keyfile
)
}.reject { |res|
catalog.resource_refs.include? res.ref
}
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/type/file/ctime.rb | lib/puppet/type/file/ctime.rb | # frozen_string_literal: true
module Puppet
Puppet::Type.type(:file).newproperty(:ctime) do
desc "A read-only state to check the file ctime. On most modern \*nix-like
systems, this is the time of the most recent change to the owner, group,
permissions, or content of the file."
def retrieve
current_value = :absent
stat = @resource.stat
if stat
current_value = stat.ctime
end
current_value.to_s
end
validate do |_val|
fail "ctime is read-only"
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/type/file/target.rb | lib/puppet/type/file/target.rb | # frozen_string_literal: true
module Puppet
Puppet::Type.type(:file).newproperty(:target) do
desc "The target for creating a link. Currently, symlinks are the
only type supported. This attribute is mutually exclusive with `source`
and `content`.
Symlink targets can be relative, as well as absolute:
# (Useful on Solaris)
file { '/etc/inetd.conf':
ensure => link,
target => 'inet/inetd.conf',
}
Directories of symlinks can be served recursively by instead using the
`source` attribute, setting `ensure` to `directory`, and setting the
`links` attribute to `manage`."
newvalue(:notlink) do
# We do nothing if the value is absent
return :nochange
end
# Anything else, basically
newvalue(/./) do
@resource[:ensure] = :link unless @resource.should(:ensure)
# Only call mklink if ensure didn't call us in the first place.
currentensure = @resource.property(:ensure).retrieve
mklink if @resource.property(:ensure).safe_insync?(currentensure)
end
# Create our link.
def mklink
raise Puppet::Error, "Cannot symlink on this platform version" unless provider.feature?(:manages_symlinks)
target = should
# Clean up any existing objects. The argument is just for logging,
# it doesn't determine what's removed.
@resource.remove_existing(target)
raise Puppet::Error, "Could not remove existing file" if Puppet::FileSystem.exist?(@resource[:path])
Puppet::Util::SUIDManager.asuser(@resource.asuser) do
mode = @resource.should(:mode)
if mode
Puppet::Util.withumask(0o00) do
Puppet::FileSystem.symlink(target, @resource[:path])
end
else
Puppet::FileSystem.symlink(target, @resource[:path])
end
end
@resource.send(:property_fix)
:link_created
end
def insync?(currentvalue)
if [:nochange, :notlink].include?(should) or @resource.recurse?
true
elsif !@resource.replace? and Puppet::FileSystem.exist?(@resource[:path])
true
else
super(currentvalue)
end
end
def retrieve
stat = @resource.stat
if stat
if stat.ftype == "link"
Puppet::FileSystem.readlink(@resource[:path])
else
:notlink
end
else
:absent
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/type/file/source.rb | lib/puppet/type/file/source.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/content'
require_relative '../../../puppet/file_serving/metadata'
require_relative '../../../puppet/file_serving/terminus_helper'
require_relative '../../../puppet/http'
module Puppet
# Copy files from a local or remote source. This state *only* does any work
# when the remote file is an actual file; in that case, this state copies
# the file down. If the remote file is a dir or a link or whatever, then
# this state, during retrieval, modifies the appropriate other states
# so that things get taken care of appropriately.
Puppet::Type.type(:file).newparam(:source) do
attr_accessor :source, :local
desc <<-'EOT'
A source file, which will be copied into place on the local system. This
attribute is mutually exclusive with `content` and `target`. Allowed
values are:
* `puppet:` URIs, which point to files in modules or Puppet file server
mount points.
* Fully qualified paths to locally available files (including files on NFS
shares or Windows mapped drives).
* `file:` URIs, which behave the same as local file paths.
* `http(s):` URIs, which point to files served by common web servers.
The normal form of a `puppet:` URI is:
`puppet:///modules/<MODULE NAME>/<FILE PATH>`
This will fetch a file from a module on the Puppet master (or from a
local module when using Puppet apply). Given a `modulepath` of
`/etc/puppetlabs/code/modules`, the example above would resolve to
`/etc/puppetlabs/code/modules/<MODULE NAME>/files/<FILE PATH>`.
Unlike `content`, the `source` attribute can be used to recursively copy
directories if the `recurse` attribute is set to `true` or `remote`. If
a source directory contains symlinks, use the `links` attribute to
specify whether to recreate links or follow them.
_HTTP_ URIs cannot be used to recursively synchronize whole directory
trees. You cannot use `source_permissions` values other than `ignore`
because HTTP servers do not transfer any metadata that translates to
ownership or permission details.
Puppet determines if file content is synchronized by computing a checksum
for the local file and comparing it against the `checksum_value`
parameter. If the `checksum_value` parameter is not specified for
`puppet` and `file` sources, Puppet computes a checksum based on its
`Puppet[:digest_algorithm]`. For `http(s)` sources, Puppet uses the
first HTTP header it recognizes out of the following list:
`X-Checksum-Sha256`, `X-Checksum-Sha1`, `X-Checksum-Md5` or `Content-MD5`.
If the server response does not include one of these headers, Puppet
defaults to using the `Last-Modified` header. Puppet updates the local
file if the header is newer than the modified time (mtime) of the local
file.
_HTTP_ URIs can include a user information component so that Puppet can
retrieve file metadata and content from HTTP servers that require HTTP Basic
authentication. For example `https://<user>:<pass>@<server>:<port>/path/to/file.`
When connecting to _HTTPS_ servers, Puppet trusts CA certificates in the
puppet-agent certificate bundle and the Puppet CA. You can configure Puppet
to trust additional CA certificates using the `Puppet[:ssl_trust_store]`
setting.
Multiple `source` values can be specified as an array, and Puppet will
use the first source that exists. This can be used to serve different
files to different system types:
file { '/etc/nfs.conf':
source => [
"puppet:///modules/nfs/conf.${host}",
"puppet:///modules/nfs/conf.${os['name']}",
'puppet:///modules/nfs/conf'
]
}
Alternately, when serving directories recursively, multiple sources can
be combined by setting the `sourceselect` attribute to `all`.
EOT
validate do |sources|
sources = [sources] unless sources.is_a?(Array)
sources.each do |source|
next if Puppet::Util.absolute_path?(source)
begin
uri = URI.parse(Puppet::Util.uri_encode(source))
rescue => detail
self.fail Puppet::Error, "Could not understand source #{source}: #{detail}", detail
end
self.fail "Cannot use relative URLs '#{source}'" unless uri.absolute?
self.fail "Cannot use opaque URLs '#{source}'" unless uri.hierarchical?
unless %w[file puppet http https].include?(uri.scheme)
self.fail "Cannot use URLs of type '#{uri.scheme}' as source for fileserving"
end
end
end
SEPARATOR_REGEX = [Regexp.escape(File::SEPARATOR.to_s), Regexp.escape(File::ALT_SEPARATOR.to_s)].join
munge do |sources|
sources = [sources] unless sources.is_a?(Array)
sources.map do |source|
source = self.class.normalize(source)
if Puppet::Util.absolute_path?(source)
# CGI.unescape will butcher properly escaped URIs
uri_string = Puppet::Util.path_to_uri(source).to_s
# Ruby 1.9.3 and earlier have a URI bug in URI
# to_s returns an ASCII string despite UTF-8 fragments
# since its escaped its safe to universally call encode
# Puppet::Util.uri_unescape always returns strings in the original encoding
Puppet::Util.uri_unescape(uri_string.encode(Encoding::UTF_8))
else
source
end
end
end
def self.normalize(source)
source.sub(/[#{SEPARATOR_REGEX}]+$/, '')
end
def change_to_s(currentvalue, newvalue)
# newvalue = "{md5}#{@metadata.checksum}"
if resource.property(:ensure).retrieve == :absent
"creating from source #{metadata.source} with contents #{metadata.checksum}"
else
"replacing from source #{metadata.source} with contents #{metadata.checksum}"
end
end
def checksum
metadata && metadata.checksum
end
# Copy the values from the source to the resource. Yay.
def copy_source_values
devfail "Somehow got asked to copy source values without any metadata" unless metadata
# conditionally copy :checksum
if metadata.ftype != "directory" && !(metadata.ftype == "link" && metadata.links == :manage)
copy_source_value(:checksum)
end
# Take each of the stats and set them as states on the local file
# if a value has not already been provided.
[:owner, :mode, :group].each do |metadata_method|
next if metadata_method == :owner and !Puppet.features.root?
next if metadata_method == :group and !Puppet.features.root?
case resource[:source_permissions]
when :ignore, nil
next
when :use_when_creating
next if Puppet::FileSystem.exist?(resource[:path])
end
copy_source_value(metadata_method)
end
if resource[:ensure] == :absent
# We know all we need to
elsif metadata.ftype != "link"
resource[:ensure] = metadata.ftype
elsif resource[:links] == :follow
resource[:ensure] = :present
else
resource[:ensure] = "link"
resource[:target] = metadata.destination
end
end
attr_writer :metadata
# Provide, and retrieve if necessary, the metadata for this file. Fail
# if we can't find data about this host, and fail if there are any
# problems in our query.
def metadata
@metadata ||= resource.catalog.metadata[resource.title]
return @metadata if @metadata
return nil unless value
value.each do |source|
options = {
:environment => resource.catalog.environment_instance,
:links => resource[:links],
:checksum_type => resource[:checksum],
:source_permissions => resource[:source_permissions]
}
data = Puppet::FileServing::Metadata.indirection.find(source, options)
if data
@metadata = data
@metadata.source = source
break
end
rescue => detail
self.fail Puppet::Error, "Could not retrieve file metadata for #{source}: #{detail}", detail
end
self.fail "Could not retrieve information from environment #{resource.catalog.environment} source(s) #{value.join(', ')}" unless @metadata
@metadata
end
def local?
found? and scheme == "file"
end
def full_path
Puppet::Util.uri_to_path(uri) if found?
end
def server?
uri && uri.host && !uri.host.empty?
end
def server
server? ? uri.host : Puppet.settings[:server]
end
def port
(uri and uri.port) or Puppet.settings[:serverport]
end
def uri
@uri ||= URI.parse(Puppet::Util.uri_encode(metadata.source))
end
def write(file)
resource.parameter(:checksum).sum_stream { |sum|
each_chunk_from { |chunk|
sum << chunk
file.print chunk
}
}
end
private
def scheme
(uri and uri.scheme)
end
def found?
!(metadata.nil? or metadata.ftype.nil?)
end
def copy_source_value(metadata_method)
param_name = (metadata_method == :checksum) ? :content : metadata_method
if resource[param_name].nil? or resource[param_name] == :absent
if Puppet::Util::Platform.windows? && [:owner, :group, :mode].include?(metadata_method)
devfail "Should not have tried to use source owner/mode/group on Windows"
end
value = metadata.send(metadata_method)
# Force the mode value in file resources to be a string containing octal.
value = value.to_s(8) if param_name == :mode && value.is_a?(Numeric)
resource[param_name] = value
if metadata_method == :checksum
# If copying checksum, also copy checksum_type
resource[:checksum] = metadata.checksum_type
end
end
end
def each_chunk_from(&block)
if Puppet[:default_file_terminus] == :file_server && scheme == 'puppet' && (uri.host.nil? || uri.host.empty?)
chunk_file_from_disk(metadata.full_path, &block)
elsif local?
chunk_file_from_disk(full_path, &block)
else
chunk_file_from_source(&block)
end
end
def chunk_file_from_disk(local_path)
File.open(local_path, "rb") do |src|
while chunk = src.read(8192) # rubocop:disable Lint/AssignmentInCondition
yield chunk
end
end
end
def get_from_content_uri_source(url, &block)
session = Puppet.lookup(:http_session)
api = session.route_to(:fileserver, url: url)
api.get_static_file_content(
path: Puppet::Util.uri_unescape(url.path),
environment: resource.catalog.environment_instance.to_s,
code_id: resource.catalog.code_id,
&block
)
end
def get_from_source_uri_source(url, &block)
session = Puppet.lookup(:http_session)
api = session.route_to(:fileserver, url: url)
api.get_file_content(
path: Puppet::Util.uri_unescape(url.path),
environment: resource.catalog.environment_instance.to_s,
&block
)
end
def get_from_http_source(url, &block)
client = Puppet.runtime[:http]
client.get(url, options: { include_system_store: true }) do |response|
raise Puppet::HTTP::ResponseError, response unless response.success?
response.read_body(&block)
end
end
def chunk_file_from_source(&block)
if uri.scheme =~ /^https?/
# Historically puppet has not encoded the http(s) source URL before parsing
# it, for example, if the path contains spaces, then it must be URL encoded
# as %20 in the manifest. Puppet behaves the same when retrieving file
# metadata via http(s), see Puppet::Indirector::FileMetadata::Http#find.
url = URI.parse(metadata.source)
get_from_http_source(url, &block)
elsif metadata.content_uri
content_url = URI.parse(Puppet::Util.uri_encode(metadata.content_uri))
get_from_content_uri_source(content_url, &block)
else
get_from_source_uri_source(uri, &block)
end
rescue Puppet::HTTP::ResponseError => e
handle_response_error(e.response)
end
def handle_response_error(response)
message = "Error #{response.code} on SERVER: #{response.body.empty? ? response.reason : response.body}"
raise Net::HTTPError.new(message, Puppet::HTTP::ResponseConverter.to_ruby_response(response))
end
end
Puppet::Type.type(:file).newparam(:source_permissions) do
desc <<-'EOT'
Whether (and how) Puppet should copy owner, group, and mode permissions from
the `source` to `file` resources when the permissions are not explicitly
specified. (In all cases, explicit permissions will take precedence.)
Valid values are `use`, `use_when_creating`, and `ignore`:
* `ignore` (the default) will never apply the owner, group, or mode from
the `source` when managing a file. When creating new files without explicit
permissions, the permissions they receive will depend on platform-specific
behavior. On POSIX, Puppet will use the umask of the user it is running as.
On Windows, Puppet will use the default DACL associated with the user it is
running as.
* `use` will cause Puppet to apply the owner, group,
and mode from the `source` to any files it is managing.
* `use_when_creating` will only apply the owner, group, and mode from the
`source` when creating a file; existing files will not have their permissions
overwritten.
EOT
defaultto :ignore
newvalues(:use, :use_when_creating, :ignore)
munge do |value|
value = value ? value.to_sym : :ignore
if @resource.file && @resource.line && value != :ignore
# TRANSLATORS "source_permissions" is a parameter name and should not be translated
Puppet.puppet_deprecation_warning(_("The `source_permissions` parameter is deprecated. Explicitly set `owner`, `group`, and `mode`."), file: @resource.file, line: @resource.line)
end
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/type/file/content.rb | lib/puppet/type/file/content.rb | # frozen_string_literal: true
require 'net/http'
require 'uri'
require 'tempfile'
require_relative '../../../puppet/util/checksums'
require_relative '../../../puppet/type/file/data_sync'
module Puppet
Puppet::Type.type(:file).newproperty(:content) do
include Puppet::Util::Checksums
include Puppet::DataSync
attr_reader :actual_content
desc <<-'EOT'
The desired contents of a file, as a string. This attribute is mutually
exclusive with `source` and `target`.
Newlines and tabs can be specified in double-quoted strings using
standard escaped syntax --- \n for a newline, and \t for a tab.
With very small files, you can construct content strings directly in
the manifest...
define resolve($nameserver1, $nameserver2, $domain, $search) {
$str = "search ${search}
domain ${domain}
nameserver ${nameserver1}
nameserver ${nameserver2}
"
file { '/etc/resolv.conf':
content => $str,
}
}
...but for larger files, this attribute is more useful when combined with the
[template](https://puppet.com/docs/puppet/latest/function.html#template)
or [file](https://puppet.com/docs/puppet/latest/function.html#file)
function.
EOT
# Store a checksum as the value, rather than the actual content.
# Simplifies everything.
munge do |value|
if value == :absent
value
elsif value.is_a?(String) && checksum?(value)
# XXX This is potentially dangerous because it means users can't write a file whose
# entire contents are a plain checksum unless it is a Binary content.
Puppet.puppet_deprecation_warning([
# TRANSLATORS "content" is an attribute and should not be translated
_('Using a checksum in a file\'s "content" property is deprecated.'),
# TRANSLATORS "filebucket" is a resource type and should not be translated. The quoted occurrence of "content" is an attribute and should not be translated.
_('The ability to use a checksum to retrieve content from the filebucket using the "content" property will be removed in a future release.'),
# TRANSLATORS "content" is an attribute and should not be translated.
_('The literal value of the "content" property will be written to the file.'),
# TRANSLATORS "static catalogs" should not be translated.
_('The checksum retrieval functionality is being replaced by the use of static catalogs.'),
_('See https://puppet.com/docs/puppet/latest/static_catalogs.html for more information.')
].join(" "),
:file => @resource.file,
:line => @resource.line) if !@actual_content && !resource.parameter(:source)
value
else
@actual_content = value.is_a?(Puppet::Pops::Types::PBinaryType::Binary) ? value.binary_buffer : value
resource.parameter(:checksum).sum(@actual_content)
end
end
# Checksums need to invert how changes are printed.
def change_to_s(currentvalue, newvalue)
# Our "new" checksum value is provided by the source.
source = resource.parameter(:source)
tmp = source.checksum if source
if tmp
newvalue = tmp
end
if currentvalue == :absent
"defined content as '#{newvalue}'"
elsif newvalue == :absent
"undefined content from '#{currentvalue}'"
else
"content changed '#{currentvalue}' to '#{newvalue}'"
end
end
def length
(actual_content and actual_content.length) || 0
end
def content
should
end
# Override this method to provide diffs if asked for.
# Also, fix #872: when content is used, and replace is true, the file
# should be insync when it exists
def insync?(is)
if resource[:source] && resource[:checksum_value]
# Asserts that nothing has changed since validate ran.
devfail "content property should not exist if source and checksum_value are specified"
end
contents_prop = resource.parameter(:source) || self
checksum_insync?(contents_prop, is, !resource[:content].nil?) { |inner| super(inner) }
end
def property_matches?(current, desired)
# If checksum_value is specified, it overrides comparing the content field.
checksum_type = resource.parameter(:checksum).value
checksum_value = resource.parameter(:checksum_value)
if checksum_value
desired = "{#{checksum_type}}#{checksum_value.value}"
end
# The inherited equality is always accepted, so use it if valid.
return true if super(current, desired)
date_matches?(checksum_type, current, desired)
end
def retrieve
retrieve_checksum(resource)
end
# Make sure we're also managing the checksum property.
def should=(value)
# treat the value as a bytestring
value = value.b if value.is_a?(String)
@resource.newattr(:checksum) unless @resource.parameter(:checksum)
super
end
# Just write our content out to disk.
def sync
contents_sync(resource.parameter(:source) || self)
end
def write(file)
resource.parameter(:checksum).sum_stream { |sum|
each_chunk_from { |chunk|
sum << chunk
file.print chunk
}
}
end
private
# the content is munged so if it's a checksum source_or_content is nil
# unless the checksum indirectly comes from source
def each_chunk_from
if actual_content.is_a?(String)
yield actual_content
elsif content_is_really_a_checksum? && actual_content.nil?
yield read_file_from_filebucket
elsif actual_content.nil?
yield ''
end
end
def content_is_really_a_checksum?
checksum?(should)
end
def read_file_from_filebucket
dipper = resource.bucket
raise "Could not get filebucket from file" unless dipper
sum = should.sub(/\{\w+\}/, '')
dipper.getfile(sum)
rescue => detail
self.fail Puppet::Error, "Could not retrieve content for #{should} from filebucket: #{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/type/file/group.rb | lib/puppet/type/file/group.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/posix'
module Puppet
# Manage file group ownership.
Puppet::Type.type(:file).newproperty(:group) do
desc <<-EOT
Which group should own the file. Argument can be either a group
name or a group ID.
On Windows, a user (such as "Administrator") can be set as a file's group
and a group (such as "Administrators") can be set as a file's owner;
however, a file's owner and group shouldn't be the same. (If the owner
is also the group, files with modes like `"0640"` will cause log churn, as
they will always appear out of sync.)
EOT
validate do |group|
raise(Puppet::Error, "Invalid group name '#{group.inspect}'") unless group and group != ""
end
def insync?(current)
# We don't want to validate/munge groups until we actually start to
# evaluate this property, because they might be added during the catalog
# apply.
@should.map! do |val|
gid = provider.name2gid(val)
if gid
gid
elsif provider.resource.noop?
return false
else
raise "Could not find group #{val}"
end
end
@should.include?(current)
end
# We want to print names, not numbers
def is_to_s(currentvalue) # rubocop:disable Naming/PredicatePrefix
super(provider.gid2name(currentvalue) || currentvalue)
end
def should_to_s(newvalue)
super(provider.gid2name(newvalue) || newvalue)
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/type/file/checksum.rb | lib/puppet/type/file/checksum.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/checksums'
# Specify which checksum algorithm to use when checksumming
# files.
Puppet::Type.type(:file).newparam(:checksum) do
include Puppet::Util::Checksums
# The default is defined in Puppet.default_digest_algorithm
desc "The checksum type to use when determining whether to replace a file's contents.
The default checksum type is sha256."
# The values are defined in Puppet::Util::Checksums.known_checksum_types
newvalues(:sha256, :sha256lite, :md5, :md5lite, :sha1, :sha1lite, :sha512, :sha384, :sha224, :mtime, :ctime, :none)
defaultto do
Puppet[:digest_algorithm].to_sym
end
validate do |value|
if Puppet::Util::Platform.fips_enabled? && (value == :md5 || value == :md5lite)
raise ArgumentError, _("MD5 is not supported in FIPS mode")
end
end
def sum(content)
content = content.is_a?(Puppet::Pops::Types::PBinaryType::Binary) ? content.binary_buffer : content
type = digest_algorithm
"{#{type}}" + send(type, content)
end
def sum_file(path)
type = digest_algorithm
method = type.to_s + "_file"
"{#{type}}" + send(method, path).to_s
end
def sum_stream(&block)
type = digest_algorithm
method = type.to_s + "_stream"
checksum = send(method, &block)
"{#{type}}#{checksum}"
end
private
# Return the appropriate digest algorithm with fallbacks in case puppet defaults have not
# been initialized.
def digest_algorithm
value || Puppet[:digest_algorithm].to_sym
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/type/file/mode.rb | lib/puppet/type/file/mode.rb | # frozen_string_literal: true
# Manage file modes. This state should support different formats
# for specification (e.g., u+rwx, or -0011), but for now only supports
# specifying the full mode.
module Puppet
Puppet::Type.type(:file).newproperty(:mode) do
require_relative '../../../puppet/util/symbolic_file_mode'
include Puppet::Util::SymbolicFileMode
desc <<-'EOT'
The desired permissions mode for the file, in symbolic or numeric
notation. This value **must** be specified as a string; do not use
un-quoted numbers to represent file modes.
If the mode is omitted (or explicitly set to `undef`), Puppet does not
enforce permissions on existing files and creates new files with
permissions of `0644`.
The `file` type uses traditional Unix permission schemes and translates
them to equivalent permissions for systems which represent permissions
differently, including Windows. For detailed ACL controls on Windows,
you can leave `mode` unmanaged and use
[the puppetlabs/acl module.](https://forge.puppetlabs.com/puppetlabs/acl)
Numeric modes should use the standard octal notation of
`<SETUID/SETGID/STICKY><OWNER><GROUP><OTHER>` (for example, "0644").
* Each of the "owner," "group," and "other" digits should be a sum of the
permissions for that class of users, where read = 4, write = 2, and
execute/search = 1.
* The setuid/setgid/sticky digit is also a sum, where setuid = 4, setgid = 2,
and sticky = 1.
* The setuid/setgid/sticky digit is optional. If it is absent, Puppet will
clear any existing setuid/setgid/sticky permissions. (So to make your intent
clear, you should use at least four digits for numeric modes.)
* When specifying numeric permissions for directories, Puppet sets the search
permission wherever the read permission is set.
Symbolic modes should be represented as a string of comma-separated
permission clauses, in the form `<WHO><OP><PERM>`:
* "Who" should be any combination of u (user), g (group), and o (other), or a (all)
* "Op" should be = (set exact permissions), + (add select permissions),
or - (remove select permissions)
* "Perm" should be one or more of:
* r (read)
* w (write)
* x (execute/search)
* t (sticky)
* s (setuid/setgid)
* X (execute/search if directory or if any one user can execute)
* u (user's current permissions)
* g (group's current permissions)
* o (other's current permissions)
Thus, mode `"0664"` could be represented symbolically as either `a=r,ug+w`
or `ug=rw,o=r`. However, symbolic modes are more expressive than numeric
modes: a mode only affects the specified bits, so `mode => 'ug+w'` will
set the user and group write bits, without affecting any other bits.
See the manual page for GNU or BSD `chmod` for more details
on numeric and symbolic modes.
On Windows, permissions are translated as follows:
* Owner and group names are mapped to Windows SIDs
* The "other" class of users maps to the "Everyone" SID
* The read/write/execute permissions map to the `FILE_GENERIC_READ`,
`FILE_GENERIC_WRITE`, and `FILE_GENERIC_EXECUTE` access rights; a
file's owner always has the `FULL_CONTROL` right
* "Other" users can't have any permissions a file's group lacks,
and its group can't have any permissions its owner lacks; that is, "0644"
is an acceptable mode, but "0464" is not.
EOT
validate do |value|
unless value.is_a?(String)
raise Puppet::Error, "The file mode specification must be a string, not '#{value.class.name}'"
end
unless value.nil? or valid_symbolic_mode?(value)
raise Puppet::Error, "The file mode specification is invalid: #{value.inspect}"
end
end
munge do |value|
return nil if value.nil?
unless valid_symbolic_mode?(value)
raise Puppet::Error, "The file mode specification is invalid: #{value.inspect}"
end
# normalizes to symbolic form, e.g. u+a, an octal string without leading 0
normalize_symbolic_mode(value)
end
unmunge do |value|
# return symbolic form or octal string *with* leading 0's
display_mode(value) if value
end
def desired_mode_from_current(desired, current)
current = current.to_i(8) if current.is_a? String
is_a_directory = @resource.stat && @resource.stat.directory?
symbolic_mode_to_int(desired, current, is_a_directory)
end
# If we're a directory, we need to be executable for all cases
# that are readable. This should probably be selectable, but eh.
def dirmask(value)
if FileTest.directory?(resource[:path]) and value =~ /^\d+$/ then
value = value.to_i(8)
value |= 0o100 if value & 0o400 != 0
value |= 0o10 if value & 0o40 != 0
value |= 0o1 if value & 0o4 != 0
value = value.to_s(8)
end
value
end
# If we're not following links and we're a link, then we just turn
# off mode management entirely.
def insync?(currentvalue)
if provider.respond_to?(:munge_windows_system_group)
munged_mode = provider.munge_windows_system_group(currentvalue, @should)
return false if munged_mode.nil?
currentvalue = munged_mode
end
stat = @resource.stat
if stat && stat.ftype == "link" && @resource[:links] != :follow
debug _("Not managing symlink mode")
true
else
super(currentvalue)
end
end
def property_matches?(current, desired)
return false unless current
current_bits = normalize_symbolic_mode(current)
desired_bits = desired_mode_from_current(desired, current).to_s(8)
current_bits == desired_bits
end
# Ideally, dirmask'ing could be done at munge time, but we don't know if 'ensure'
# will eventually be a directory or something else. And unfortunately, that logic
# depends on the ensure, source, and target properties. So rather than duplicate
# that logic, and get it wrong, we do dirmask during retrieve, after 'ensure' has
# been synced.
def retrieve
if @resource.stat
@should &&= @should.collect { |s| dirmask(s) }
end
super
end
# Finally, when we sync the mode out we need to transform it; since we
# don't have access to the calculated "desired" value here, or the
# "current" value, only the "should" value we need to retrieve again.
def sync
current = @resource.stat ? @resource.stat.mode : 0o644
set(desired_mode_from_current(@should[0], current).to_s(8))
end
def change_to_s(old_value, desired)
return super if desired =~ /^\d+$/
old_bits = normalize_symbolic_mode(old_value)
new_bits = normalize_symbolic_mode(desired_mode_from_current(desired, old_bits))
super(old_bits, new_bits) + " (#{desired})"
end
def should_to_s(should_value)
"'#{should_value.rjust(4, '0')}'"
end
def is_to_s(currentvalue) # rubocop:disable Naming/PredicatePrefix
if currentvalue == :absent
# This can occur during audits---if a file is transitioning from
# present to absent the mode will have a value of `:absent`.
super
else
"'#{currentvalue.rjust(4, '0')}'"
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/type/file/type.rb | lib/puppet/type/file/type.rb | # frozen_string_literal: true
module Puppet
Puppet::Type.type(:file).newproperty(:type) do
require 'etc'
desc "A read-only state to check the file type."
def retrieve
current_value = :absent
stat = @resource.stat
if stat
current_value = stat.ftype
end
current_value
end
validate do |_val|
fail "type is read-only"
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/type/file/checksum_value.rb | lib/puppet/type/file/checksum_value.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/checksums'
require_relative '../../../puppet/type/file/data_sync'
module Puppet
Puppet::Type.type(:file).newproperty(:checksum_value) do
include Puppet::Util::Checksums
include Puppet::DataSync
desc "The checksum of the source contents. Only md5, sha256, sha224, sha384 and sha512
are supported when specifying this parameter. If this parameter is set,
source_permissions will be assumed to be false, and ownership and permissions
will not be read from source."
def insync?(is)
# If checksum_value and source are specified, manage the file contents.
# Otherwise the content property will manage syncing.
if resource.parameter(:source).nil?
return true
end
checksum_insync?(resource.parameter(:source), is, true) { |inner| super(inner) }
end
def property_matches?(current, desired)
return true if super(current, desired)
date_matches?(resource.parameter(:checksum).value, current, desired)
end
def retrieve
# If checksum_value and source are specified, manage the file contents.
# Otherwise the content property will manage syncing. Don't compute the checksum twice.
if resource.parameter(:source).nil?
return nil
end
result = retrieve_checksum(resource)
# If the returned type matches the util/checksums format (prefixed with the type),
# strip the checksum type.
result = sumdata(result) if checksum?(result)
result
end
def sync
if resource.parameter(:source).nil?
devfail "checksum_value#sync should not be called without a source parameter"
end
# insync? only returns false if it expects to manage the file content,
# so instruct the resource to write its contents.
contents_sync(resource.parameter(:source))
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/type/file/owner.rb | lib/puppet/type/file/owner.rb | # frozen_string_literal: true
module Puppet
Puppet::Type.type(:file).newproperty(:owner) do
include Puppet::Util::Warnings
desc <<-EOT
The user to whom the file should belong. Argument can be a user name or a
user ID.
On Windows, a group (such as "Administrators") can be set as a file's owner
and a user (such as "Administrator") can be set as a file's group; however,
a file's owner and group shouldn't be the same. (If the owner is also
the group, files with modes like `"0640"` will cause log churn, as they
will always appear out of sync.)
EOT
def insync?(current)
# We don't want to validate/munge users until we actually start to
# evaluate this property, because they might be added during the catalog
# apply.
@should.map! do |val|
uid = provider.name2uid(val)
if uid
uid
elsif provider.resource.noop?
return false
else
raise "Could not find user #{val}"
end
end
return true if @should.include?(current)
unless Puppet.features.root?
warnonce "Cannot manage ownership unless running as root"
return true
end
false
end
# We want to print names, not numbers
def is_to_s(currentvalue) # rubocop:disable Naming/PredicatePrefix
super(provider.uid2name(currentvalue) || currentvalue)
end
def should_to_s(newvalue)
super(provider.uid2name(newvalue) || newvalue)
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/type/file/selcontext.rb | lib/puppet/type/file/selcontext.rb | # frozen_string_literal: true
# Manage SELinux context of files.
#
# This code actually manages three pieces of data in the context.
#
# [root@delenn files]# ls -dZ /
# drwxr-xr-x root root system_u:object_r:root_t /
#
# The context of '/' here is 'system_u:object_r:root_t'. This is
# three separate fields:
#
# system_u is the user context
# object_r is the role context
# root_t is the type context
#
# All three of these fields are returned in a single string by the
# output of the stat command, but set individually with the chcon
# command. This allows the user to specify a subset of the three
# values while leaving the others alone.
#
# See https://www.nsa.gov/selinux/ for complete docs on SELinux.
module Puppet
require_relative '../../../puppet/util/selinux'
class SELFileContext < Puppet::Property
include Puppet::Util::SELinux
def retrieve
return :absent unless @resource.stat
context = get_selinux_current_context(@resource[:path])
is = parse_selinux_context(name, context)
if name == :selrange and selinux_support?
selinux_category_to_label(is)
else
is
end
end
def retrieve_default_context(property)
return nil if Puppet::Util::Platform.windows?
if @resource[:selinux_ignore_defaults] == :true
return nil
end
context = get_selinux_default_context_with_handle(@resource[:path], provider.class.selinux_handle, @resource[:ensure])
unless context
return nil
end
property_default = parse_selinux_context(property, context)
debug "Found #{property} default '#{property_default}' for #{@resource[:path]}" unless property_default.nil?
property_default
end
def insync?(value)
if !selinux_support?
debug("SELinux bindings not found. Ignoring parameter.")
true
elsif !selinux_label_support?(@resource[:path])
debug("SELinux not available for this filesystem. Ignoring parameter.")
true
else
super
end
end
def unsafe_munge(should)
unless selinux_support?
return should
end
if name == :selrange
selinux_category_to_label(should)
else
should
end
end
def sync
set_selinux_context(@resource[:path], @should, name)
:file_changed
end
end
Puppet::Type.type(:file).newparam(:selinux_ignore_defaults) do
desc "If this is set, Puppet will not call the SELinux function selabel_lookup to
supply defaults for the SELinux attributes (seluser, selrole,
seltype, and selrange). In general, you should leave this set at its
default and only set it to true when you need Puppet to not try to fix
SELinux labels automatically."
newvalues(:true, :false)
defaultto :false
end
Puppet::Type.type(:file).newproperty(:seluser, :parent => Puppet::SELFileContext) do
desc "What the SELinux user component of the context of the file should be.
Any valid SELinux user component is accepted. For example `user_u`.
If not specified, it defaults to the value returned by selabel_lookup for
the file, if any exists. Only valid on systems with SELinux support
enabled."
@event = :file_changed
defaultto { retrieve_default_context(:seluser) }
end
Puppet::Type.type(:file).newproperty(:selrole, :parent => Puppet::SELFileContext) do
desc "What the SELinux role component of the context of the file should be.
Any valid SELinux role component is accepted. For example `role_r`.
If not specified, it defaults to the value returned by selabel_lookup for
the file, if any exists. Only valid on systems with SELinux support
enabled."
@event = :file_changed
defaultto { retrieve_default_context(:selrole) }
end
Puppet::Type.type(:file).newproperty(:seltype, :parent => Puppet::SELFileContext) do
desc "What the SELinux type component of the context of the file should be.
Any valid SELinux type component is accepted. For example `tmp_t`.
If not specified, it defaults to the value returned by selabel_lookup for
the file, if any exists. Only valid on systems with SELinux support
enabled."
@event = :file_changed
defaultto { retrieve_default_context(:seltype) }
end
Puppet::Type.type(:file).newproperty(:selrange, :parent => Puppet::SELFileContext) do
desc "What the SELinux range component of the context of the file should be.
Any valid SELinux range component is accepted. For example `s0` or
`SystemHigh`. If not specified, it defaults to the value returned by
selabel_lookup for the file, if any exists. Only valid on systems with
SELinux support enabled and that have support for MCS (Multi-Category
Security)."
@event = :file_changed
defaultto { retrieve_default_context(:selrange) }
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/type/file/ensure.rb | lib/puppet/type/file/ensure.rb | # frozen_string_literal: true
module Puppet
Puppet::Type.type(:file).ensurable do
require 'etc'
require_relative '../../../puppet/util/symbolic_file_mode'
include Puppet::Util::SymbolicFileMode
desc <<-EOT
Whether the file should exist, and if so what kind of file it should be.
Possible values are `present`, `absent`, `file`, `directory`, and `link`.
* `present` accepts any form of file existence, and creates a
normal file if the file is missing. (The file will have no content
unless the `content` or `source` attribute is used.)
* `absent` ensures the file doesn't exist, and deletes it if necessary.
* `file` ensures it's a normal file, and enables use of the `content` or
`source` attribute.
* `directory` ensures it's a directory, and enables use of the `source`,
`recurse`, `recurselimit`, `ignore`, and `purge` attributes.
* `link` ensures the file is a symlink, and **requires** that you also
set the `target` attribute. Symlinks are supported on all Posix
systems and on Windows Vista / 2008 and higher. On Windows, managing
symlinks requires Puppet agent's user account to have the "Create
Symbolic Links" privilege; this can be configured in the "User Rights
Assignment" section in the Windows policy editor. By default, Puppet
agent runs as the Administrator account, which has this privilege.
Puppet avoids destroying directories unless the `force` attribute is set
to `true`. This means that if a file is currently a directory, setting
`ensure` to anything but `directory` or `present` will cause Puppet to
skip managing the resource and log either a notice or an error.
There is one other non-standard value for `ensure`. If you specify the
path to another file as the ensure value, it is equivalent to specifying
`link` and using that path as the `target`:
# Equivalent resources:
file { '/etc/inetd.conf':
ensure => '/etc/inet/inetd.conf',
}
file { '/etc/inetd.conf':
ensure => link,
target => '/etc/inet/inetd.conf',
}
However, we recommend using `link` and `target` explicitly, since this
behavior can be harder to read and is
[deprecated](https://docs.puppet.com/puppet/4.3/deprecated_language.html)
as of Puppet 4.3.0.
EOT
# Most 'ensure' properties have a default, but with files we, um, don't.
nodefault
newvalue(:absent) do
Puppet::FileSystem.unlink(@resource[:path])
end
aliasvalue(:false, :absent)
newvalue(:file, :event => :file_created) do
# Make sure we're not managing the content some other way
property = @resource.property(:content) || @resource.property(:checksum_value)
if property
property.sync
else
@resource.write
@resource.should(:mode)
end
end
# aliasvalue(:present, :file)
newvalue(:present, :event => :file_created) do
# Make a file if they want something, but this will match almost
# anything.
set_file
end
newvalue(:directory, :event => :directory_created) do
mode = @resource.should(:mode)
parent = File.dirname(@resource[:path])
unless Puppet::FileSystem.exist? parent
raise Puppet::Error,
"Cannot create #{@resource[:path]}; parent directory #{parent} does not exist"
end
if mode
Puppet::Util.withumask(0o00) do
Dir.mkdir(@resource[:path], symbolic_mode_to_int(mode, 0o755, true))
end
else
Dir.mkdir(@resource[:path])
end
@resource.send(:property_fix)
return :directory_created
end
newvalue(:link, :event => :link_created, :required_features => :manages_symlinks) do
property = resource.property(:target)
fail "Cannot create a symlink without a target" unless property
property.retrieve
property.mklink
end
# Symlinks.
newvalue(/./) do
# This code never gets executed. We need the regex to support
# specifying it, but the work is done in the 'symlink' code block.
end
munge do |value|
value = super(value)
unless value.is_a? Symbol
resource[:target] = value
value = :link
end
resource[:links] = :manage if value == :link and resource[:links] != :follow
value
end
def change_to_s(currentvalue, newvalue)
return super unless [:file, :present].include?(newvalue)
property = @resource.property(:content)
return super unless property
# We know that content is out of sync if we're here, because
# it's essentially equivalent to 'ensure' in the transaction.
source = @resource.parameter(:source)
if source
should = source.checksum
else
should = property.should
end
if should == :absent
is = property.retrieve
else
is = :absent
end
property.change_to_s(is, should)
end
# Check that we can actually create anything
def check
basedir = File.dirname(@resource[:path])
if !Puppet::FileSystem.exist?(basedir)
raise Puppet::Error,
"Can not create #{@resource.title}; parent directory does not exist"
elsif !FileTest.directory?(basedir)
raise Puppet::Error,
"Can not create #{@resource.title}; #{dirname} is not a directory"
end
end
# We have to treat :present specially, because it works with any
# type of file.
def insync?(currentvalue)
unless currentvalue == :absent or resource.replace?
return true
end
if should == :present
!(currentvalue.nil? or currentvalue == :absent)
else
super(currentvalue)
end
end
def retrieve
stat = @resource.stat
if stat
stat.ftype.intern
elsif should == :false
:false
else
:absent
end
end
def sync
@resource.remove_existing(should)
if should == :absent
return :file_removed
end
super
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/type/file/data_sync.rb | lib/puppet/type/file/data_sync.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/checksums'
require_relative '../../../puppet/util/diff'
require 'date'
require 'tempfile'
module Puppet
module DataSync
include Puppet::Util::Checksums
include Puppet::Util::Diff
def write_temporarily(param)
tempfile = Tempfile.new("puppet-file")
tempfile.open
param.write(tempfile)
tempfile.close
yield tempfile.path
ensure
tempfile.delete if tempfile
end
def checksum_insync?(param, is, has_contents, &block)
resource = param.resource
if resource.should_be_file?
return false if is == :absent
else
if resource[:ensure] == :present && has_contents && (s = resource.stat)
# TRANSLATORS 'Ensure' is an attribute and ':present' is a value and should not be translated
resource.warning _("Ensure set to :present but file type is %{file_type} so no content will be synced") % { file_type: s.ftype }
end
return true
end
return true unless resource.replace?
is_insync = yield(is)
if show_diff?(!is_insync)
if param.sensitive
send resource[:loglevel], "[diff redacted]"
else
write_temporarily(param) do |path|
diff_output = diff(resource[:path], path)
if diff_output.encoding == Encoding::BINARY || !diff_output.valid_encoding?
diff_output = "Binary files #{resource[:path]} and #{path} differ"
end
send resource[:loglevel], "\n" + diff_output
end
end
end
is_insync
end
def show_diff?(has_changes)
has_changes && Puppet[:show_diff] && resource.show_diff?
end
def date_matches?(checksum_type, current, desired)
time_types = [:mtime, :ctime]
return false unless time_types.include?(checksum_type)
return false unless current && desired
begin
if checksum?(current) || checksum?(desired)
raise if !time_types.include?(sumtype(current).to_sym) || !time_types.include?(sumtype(desired).to_sym)
current = sumdata(current)
desired = sumdata(desired)
end
DateTime.parse(current) >= DateTime.parse(desired)
rescue => detail
self.fail Puppet::Error, "Resource with checksum_type #{checksum_type} didn't contain a date in #{current} or #{desired}", detail.backtrace
end
end
def retrieve_checksum(resource)
stat = resource.stat
return :absent unless stat
ftype = stat.ftype
# Don't even try to manage the content on directories or links
return nil if %w[directory link fifo socket].include?(ftype)
begin
resource.parameter(:checksum).sum_file(resource[:path])
rescue => detail
raise Puppet::Error, "Could not read #{ftype} #{resource.title}: #{detail}", detail.backtrace
end
end
def contents_sync(param)
return_event = param.resource.stat ? :file_changed : :file_created
resource.write(param)
return_event
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/type/file/mtime.rb | lib/puppet/type/file/mtime.rb | # frozen_string_literal: true
module Puppet
Puppet::Type.type(:file).newproperty(:mtime) do
desc "A read-only state to check the file mtime. On \*nix-like systems, this
is the time of the most recent change to the content of the file."
def retrieve
current_value = :absent
stat = @resource.stat
if stat
current_value = stat.mtime
end
current_value.to_s
end
validate do |_val|
fail "mtime is read-only"
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/generate/type.rb | lib/puppet/generate/type.rb | # frozen_string_literal: true
require 'erb'
require 'fileutils'
require_relative '../../puppet/util/autoload'
require_relative '../../puppet/generate/models/type/type'
module Puppet
module Generate
# Responsible for generating type definitions in Puppet
class Type
# Represents an input to the type generator
class Input
# Gets the path to the input.
attr_reader :path
# Gets the format to use for generating the output file.
attr_reader :format
# Initializes an input.
# @param base [String] The base path where the input is located.
# @param path [String] The path to the input file.
# @param format [Symbol] The format to use for generation.
# @return [void]
def initialize(base, path, format)
@base = base
@path = path
self.format = format
end
# Gets the expected resource type name for the input.
# @return [Symbol] Returns the expected resource type name for the input.
def type_name
File.basename(@path, '.rb').to_sym
end
# Sets the format to use for this input.
# @param format [Symbol] The format to use for generation.
# @return [Symbol] Returns the new format.
def format=(format)
format = format.to_sym
raise _("unsupported format '%{format}'.") % { format: format } unless self.class.supported_format?(format)
@format = format
end
# Determines if the output file is up-to-date with respect to the input file.
# @param [String, nil] The path to output to, or nil if determined by input
# @return [Boolean] Returns true if the output is up-to-date or false if not.
def up_to_date?(outputdir)
f = effective_output_path(outputdir)
Puppet::FileSystem.exist?(f) && (Puppet::FileSystem.stat(@path) <=> Puppet::FileSystem.stat(f)) <= 0
end
# Gets the filename of the output file.
# @return [String] Returns the name to the output file.
def output_name
@output_name ||=
case @format
when :pcore
"#{File.basename(@path, '.rb')}.pp"
else
raise _("unsupported format '%{format}'.") % { format: @format }
end
end
# Gets the path to the output file.
# @return [String] Returns the path to the output file.
def output_path
@output_path ||=
case @format
when :pcore
File.join(@base, 'pcore', 'types', output_name)
else
raise _("unsupported format '%{format}'.") % { format: @format }
end
end
# Sets the path to the output file.
# @param path [String] The new path to the output file.
# @return [String] Returns the new path to the output file.
def output_path=(path)
@output_path = path
end
# Returns the outputpath to use given an outputdir that may be nil
# If outputdir is not nil, the returned path is relative to that outpudir
# otherwise determined by this input.
# @param [String, nil] The outputdirectory to use, or nil if to be determined by this Input
def effective_output_path(outputdir)
outputdir ? File.join(outputdir, output_name) : output_path
end
# Gets the path to the template to use for this input.
# @return [String] Returns the path to the template.
def template_path
File.join(File.dirname(__FILE__), 'templates', 'type', "#{@format}.erb")
end
# Gets the string representation of the input.
# @return [String] Returns the string representation of the input.
def to_s
@path
end
# Determines if the given format is supported
# @param format [Symbol] The format to use for generation.
# @return [Boolean] Returns true if the format is supported or false if not.
def self.supported_format?(format)
[:pcore].include?(format)
end
end
# Finds the inputs for the generator.
# @param format [Symbol] The format to use.
# @param environment [Puppet::Node::Environment] The environment to search for inputs. Defaults to the current environment.
# @return [Array<Input>] Returns the array of inputs.
def self.find_inputs(format = :pcore, environment = Puppet.lookup(:current_environment))
Puppet.debug "Searching environment '#{environment.name}' for custom types."
inputs = []
environment.modules.each do |mod|
directory = File.join(Puppet::Util::Autoload.cleanpath(mod.plugin_directory), 'puppet', 'type')
unless Puppet::FileSystem.exist?(directory)
Puppet.debug "Skipping '#{mod.name}' module because it contains no custom types."
next
end
Puppet.debug "Searching '#{mod.name}' module for custom types."
Dir.glob("#{directory}/*.rb") do |file|
next unless Puppet::FileSystem.file?(file)
Puppet.debug "Found custom type source file '#{file}'."
inputs << Input.new(mod.path, file, format)
end
end
# Sort the inputs by path
inputs.sort_by!(&:path)
end
def self.bad_input?
@bad_input
end
# Generates files for the given inputs.
# If a file is up to date (newer than input) it is kept.
# If a file is out of date it is regenerated.
# If there is a file for a non existing output in a given output directory it is removed.
# If using input specific output removal must be made by hand if input is removed.
#
# @param inputs [Array<Input>] The inputs to generate files for.
# @param outputdir [String, nil] the outputdir where all output should be generated, or nil if next to input
# @param force [Boolean] True to force the generation of the output files (skip up-to-date checks) or false if not.
# @return [void]
def self.generate(inputs, outputdir = nil, force = false)
# remove files for non existing inputs
unless outputdir.nil?
filenames_to_keep = inputs.map(&:output_name)
existing_files = Puppet::FileSystem.children(outputdir).map { |f| Puppet::FileSystem.basename(f) }
files_to_remove = existing_files - filenames_to_keep
files_to_remove.each do |f|
Puppet::FileSystem.unlink(File.join(outputdir, f))
end
Puppet.notice(_("Removed output '%{files_to_remove}' for non existing inputs") % { files_to_remove: files_to_remove }) unless files_to_remove.empty?
end
if inputs.empty?
Puppet.notice _('No custom types were found.')
return nil
end
templates = {}
templates.default_proc = lambda { |_hash, key|
raise _("template was not found at '%{key}'.") % { key: key } unless Puppet::FileSystem.file?(key)
template = Puppet::Util.create_erb(File.read(key))
template.filename = key
template
}
up_to_date = true
@bad_input = false
Puppet.notice _('Generating Puppet resource types.')
inputs.each do |input|
if !force && input.up_to_date?(outputdir)
Puppet.debug "Skipping '#{input}' because it is up-to-date."
next
end
up_to_date = false
type_name = input.type_name
Puppet.debug "Loading custom type '#{type_name}' in '#{input}'."
begin
require input.path
rescue SystemExit
raise
rescue Exception => e
# Log the exception and move on to the next input
@bad_input = true
Puppet.log_exception(e, _("Failed to load custom type '%{type_name}' from '%{input}': %{message}") % { type_name: type_name, input: input, message: e.message })
next
end
# HACK: there's no way to get a type without loading it (sigh); for now, just get the types hash directly
types ||= Puppet::Type.instance_variable_get('@types')
# Assume the type follows the naming convention
type = types[type_name]
unless type
Puppet.err _("Custom type '%{type_name}' was not defined in '%{input}'.") % { type_name: type_name, input: input }
next
end
# Create the model
begin
model = Models::Type::Type.new(type)
rescue Exception => e
@bad_input = true
# Move on to the next input
Puppet.log_exception(e, "#{input}: #{e.message}")
next
end
# Render the template
begin
result = model.render(templates[input.template_path])
rescue Exception => e
@bad_input = true
Puppet.log_exception(e)
raise
end
# Write the output file
begin
effective_output_path = input.effective_output_path(outputdir)
Puppet.notice _("Generating '%{effective_output_path}' using '%{format}' format.") % { effective_output_path: effective_output_path, format: input.format }
FileUtils.mkdir_p(File.dirname(effective_output_path))
Puppet::FileSystem.open(effective_output_path, nil, 'w:UTF-8') do |file|
file.write(result)
end
rescue Exception => e
@bad_input = true
Puppet.log_exception(e, _("Failed to generate '%{effective_output_path}': %{message}") % { effective_output_path: effective_output_path, message: e.message })
# Move on to the next input
next
end
end
Puppet.notice _('No files were generated because all inputs were up-to-date.') if up_to_date
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/generate/models/type/type.rb | lib/puppet/generate/models/type/type.rb | # frozen_string_literal: true
require_relative '../../../../puppet/generate/models/type/property'
module Puppet
module Generate
module Models
module Type
# A model for Puppet resource types.
class Type
# Gets the name of the type as a Puppet string literal.
attr_reader :name
# Gets the doc string of the type.
attr_reader :doc
# Gets the properties of the type.
attr_reader :properties
# Gets the parameters of the type.
attr_reader :parameters
# Gets the title patterns of the type
attr_reader :title_patterns
# Gets the isomorphic member attribute of the type
attr_reader :isomorphic
# Gets the capability member attribute of the type
attr_reader :capability
# Initializes a type model.
# @param type [Puppet::Type] The Puppet type to model.
# @return [void]
def initialize(type)
@name = Puppet::Pops::Types::StringConverter.convert(type.name.to_s, '%p')
@doc = type.doc.strip
@properties = type.properties.map { |p| Property.new(p) }
@parameters = type.parameters.map do |name|
Property.new(type.paramclass(name))
end
sc = Puppet::Pops::Types::StringConverter.singleton
@title_patterns = type.title_patterns.to_h do |mapping|
[
sc.convert(mapping[0], '%p'),
sc.convert(mapping[1].map do |names|
next if names.empty?
raise Puppet::Error, _('title patterns that use procs are not supported.') unless names.size == 1
names[0].to_s
end, '%p')
]
end
@isomorphic = type.isomorphic?
# continue to emit capability as false when rendering the ERB
# template, so that pcore modules generated prior to puppet7 can be
# read by puppet7 and vice-versa.
@capability = false
end
def render(template)
template.result(binding)
end
end
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/generate/models/type/property.rb | lib/puppet/generate/models/type/property.rb | # frozen_string_literal: true
module Puppet
module Generate
module Models
module Type
# A model for resource type properties and parameters.
class Property
# Gets the name of the property as a Puppet string literal.
attr_reader :name
# Gets the Puppet type of the property.
attr_reader :type
# Gets the doc string of the property.
attr_reader :doc
# Initializes a property model.
# @param property [Puppet::Property] The Puppet property to model.
# @return [void]
def initialize(property)
@name = Puppet::Pops::Types::StringConverter.convert(property.name.to_s, '%p')
@type = self.class.get_puppet_type(property)
@doc = property.doc.strip
@is_namevar = property.isnamevar?
end
# Determines if this property is a namevar.
# @return [Boolean] Returns true if the property is a namevar or false if not.
def is_namevar?
@is_namevar
end
# Gets the Puppet type for a property.
# @param property [Puppet::Property] The Puppet property to get the Puppet type for.
# @return [String] Returns the string representing the Puppet type.
def self.get_puppet_type(property)
# HACK: the value collection does not expose the underlying value information at all
# thus this horribleness to get the underlying values hash
regexes = []
strings = []
values = property.value_collection.instance_variable_get('@values') || {}
values.each do |_, value|
if value.regex?
regexes << Puppet::Pops::Types::StringConverter.convert(value.name, '%p')
next
end
strings << Puppet::Pops::Types::StringConverter.convert(value.name.to_s, '%p')
value.aliases.each do |a|
strings << Puppet::Pops::Types::StringConverter.convert(a.to_s, '%p')
end
end
# If no string or regexes, default to Any type
return 'Any' if strings.empty? && regexes.empty?
# Calculate a variant of supported values
# Note that boolean strings are mapped to Variant[Boolean, Enum['true', 'false']]
# because of tech debt...
enum = strings.empty? ? nil : "Enum[#{strings.join(', ')}]"
pattern = regexes.empty? ? nil : "Pattern[#{regexes.join(', ')}]"
boolean = strings.include?('\'true\'') || strings.include?('\'false\'') ? 'Boolean' : nil
variant = [boolean, enum, pattern].compact
return variant[0] if variant.size == 1
"Variant[#{variant.join(', ')}]"
end
end
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/resource/type.rb | lib/puppet/resource/type.rb | # frozen_string_literal: true
require_relative '../../puppet/parser'
require_relative '../../puppet/util/warnings'
require_relative '../../puppet/util/errors'
require_relative '../../puppet/parser/ast/leaf'
# Puppet::Resource::Type represents nodes, classes and defined types.
#
# @api public
class Puppet::Resource::Type
Puppet::ResourceType = self
include Puppet::Util::Warnings
include Puppet::Util::Errors
RESOURCE_KINDS = [:hostclass, :node, :definition]
# Map the names used in our documentation to the names used internally
RESOURCE_KINDS_TO_EXTERNAL_NAMES = {
:hostclass => "class",
:node => "node",
:definition => "defined_type"
}
RESOURCE_EXTERNAL_NAMES_TO_KINDS = RESOURCE_KINDS_TO_EXTERNAL_NAMES.invert
NAME = 'name'
TITLE = 'title'
MODULE_NAME = 'module_name'
CALLER_MODULE_NAME = 'caller_module_name'
PARAMETERS = 'parameters'
KIND = 'kind'
NODES = 'nodes'
DOUBLE_COLON = '::'
EMPTY_ARRAY = [].freeze
LOOKAROUND_OPERATORS = {
"(" => 'LP',
"?" => "QU",
"<" => "LT",
">" => "GT",
"!" => "EX",
"=" => "EQ",
")" => 'RP'
}.freeze
attr_accessor :file, :line, :doc, :code, :parent, :resource_type_collection, :override
attr_reader :namespace, :arguments, :behaves_like, :module_name
# Map from argument (aka parameter) names to Puppet Type
# @return [Hash<Symbol, Puppet::Pops::Types::PAnyType] map from name to type
#
attr_reader :argument_types
# This should probably be renamed to 'kind' eventually, in accordance with the changes
# made for serialization and API usability (#14137). At the moment that seems like
# it would touch a whole lot of places in the code, though. --cprice 2012-04-23
attr_reader :type
RESOURCE_KINDS.each do |t|
define_method("#{t}?") { type == t }
end
# Are we a child of the passed class? Do a recursive search up our
# parentage tree to figure it out.
def child_of?(klass)
return true if override
return false unless parent
(klass == parent_type ? true : parent_type.child_of?(klass))
end
# Now evaluate the code associated with this class or definition.
def evaluate_code(resource)
static_parent = evaluate_parent_type(resource)
scope = static_parent || resource.scope
scope = scope.newscope(:source => self, :resource => resource) unless resource.title == :main
scope.compiler.add_class(name) unless definition?
set_resource_parameters(resource, scope)
resource.add_edge_to_stage
if code
if @match # Only bother setting up the ephemeral scope if there are match variables to add into it
scope.with_guarded_scope do
scope.ephemeral_from(@match, file, line)
code.safeevaluate(scope)
end
else
code.safeevaluate(scope)
end
end
end
def initialize(type, name, options = {})
@type = type.to_s.downcase.to_sym
raise ArgumentError, _("Invalid resource supertype '%{type}'") % { type: type } unless RESOURCE_KINDS.include?(@type)
name = convert_from_ast(name) if name.is_a?(Puppet::Parser::AST::HostName)
set_name_and_namespace(name)
[:code, :doc, :line, :file, :parent].each do |param|
value = options[param]
next unless value
send(param.to_s + '=', value)
end
set_arguments(options[:arguments])
set_argument_types(options[:argument_types])
@match = nil
@module_name = options[:module_name]
end
# This is only used for node names, and really only when the node name
# is a regexp.
def match(string)
return string.to_s.downcase == name unless name_is_regex?
@match = @name.match(string)
end
# Add code from a new instance to our code.
def merge(other)
fail _("%{name} is not a class; cannot add code to it") % { name: name } unless type == :hostclass
fail _("%{name} is not a class; cannot add code from it") % { name: other.name } unless other.type == :hostclass
if name == "" && Puppet.settings[:freeze_main]
# It is ok to merge definitions into main even if freeze is on (definitions are nodes, classes, defines, functions, and types)
unless other.code.is_definitions_only?
fail _("Cannot have code outside of a class/node/define because 'freeze_main' is enabled")
end
end
if parent and other.parent and parent != other.parent
fail _("Cannot merge classes with different parent classes (%{name} => %{parent} vs. %{other_name} => %{other_parent})") % { name: name, parent: parent, other_name: other.name, other_parent: other.parent }
end
# We know they're either equal or only one is set, so keep whichever parent is specified.
self.parent ||= other.parent
if other.doc
self.doc ||= ""
self.doc += other.doc
end
# This might just be an empty, stub class.
return unless other.code
unless code
self.code = other.code
return
end
self.code = Puppet::Parser::ParserFactory.code_merger.concatenate([self, other])
end
# Make an instance of the resource type, and place it in the catalog
# if it isn't in the catalog already. This is only possible for
# classes and nodes. No parameters are be supplied--if this is a
# parameterized class, then all parameters take on their default
# values.
def ensure_in_catalog(scope, parameters = nil)
resource_type =
case type
when :definition
raise ArgumentError, _('Cannot create resources for defined resource types')
when :hostclass
:class
when :node
:node
end
# Do nothing if the resource already exists; this makes sure we don't
# get multiple copies of the class resource, which helps provide the
# singleton nature of classes.
# we should not do this for classes with parameters
# if parameters are passed, we should still try to create the resource
# even if it exists so that we can fail
# this prevents us from being able to combine param classes with include
if parameters.nil?
resource = scope.catalog.resource(resource_type, name)
return resource unless resource.nil?
elsif parameters.is_a?(Hash)
parameters = parameters.map { |k, v| Puppet::Parser::Resource::Param.new(:name => k, :value => v, :source => self) }
end
resource = Puppet::Parser::Resource.new(resource_type, name, :scope => scope, :source => self, :parameters => parameters)
instantiate_resource(scope, resource)
scope.compiler.add_resource(scope, resource)
resource
end
def instantiate_resource(scope, resource)
# Make sure our parent class has been evaluated, if we have one.
if parent && !scope.catalog.resource(resource.type, parent)
parent_type(scope).ensure_in_catalog(scope)
end
if %w[Class Node].include? resource.type
scope.catalog.merge_tags_from(resource)
end
end
def name
if type == :node && name_is_regex?
# Normalize lookarround regex patthern
internal_name = @name.source.downcase.gsub(/\(\?[^)]*\)/) do |str|
str.gsub(/./) { |ch| LOOKAROUND_OPERATORS[ch] || ch }
end
"__node_regexp__#{internal_name.gsub(/[^-\w:.]/, '').sub(/^\.+/, '')}"
else
@name
end
end
def name_is_regex?
@name.is_a?(Regexp)
end
def parent_type(scope = nil)
return nil unless parent
@parent_type ||= scope.environment.known_resource_types.send("find_#{type}", parent) ||
fail(Puppet::ParseError, _("Could not find parent resource type '%{parent}' of type %{parent_type} in %{env}") % { parent: parent, parent_type: type, env: scope.environment })
end
# Validate and set any arguments passed by the resource as variables in the scope.
#
# This method is known to only be used on the server/compile side.
#
# @param resource [Puppet::Parser::Resource] the resource
# @param scope [Puppet::Parser::Scope] the scope
#
# @api private
def set_resource_parameters(resource, scope)
# Inject parameters from using external lookup
modname = resource[:module_name] || module_name
scope[MODULE_NAME] = modname unless modname.nil?
caller_name = resource[:caller_module_name] || scope.parent_module_name
scope[CALLER_MODULE_NAME] = caller_name unless caller_name.nil?
inject_external_parameters(resource, scope)
if @type == :hostclass
scope[TITLE] = resource.title.to_s.downcase
scope[NAME] = resource.name.to_s.downcase
else
scope[TITLE] = resource.title
scope[NAME] = resource.name
end
scope.class_set(name, scope) if hostclass? || node?
param_hash = scope.with_parameter_scope(resource.to_s, arguments.keys) do |param_scope|
# Assign directly to the parameter scope to avoid scope parameter validation at this point. It
# will happen anyway when the values are assigned to the scope after the parameter scoped has
# been popped.
resource.each { |k, v| param_scope[k.to_s] = v.value unless k == :name || k == :title }
assign_defaults(resource, param_scope, scope)
param_scope.to_hash
end
validate_resource_hash(resource, param_hash)
# Assign parameter values to current scope
param_hash.each { |param, value| exceptwrap { scope[param] = value } }
end
# Lookup and inject parameters from external scope
# @param resource [Puppet::Parser::Resource] the resource
# @param scope [Puppet::Parser::Scope] the scope
def inject_external_parameters(resource, scope)
# Only lookup parameters for host classes
return unless type == :hostclass
parameters = resource.parameters
arguments.each do |param_name, default|
sym_name = param_name.to_sym
param = parameters[sym_name]
next unless param.nil? || param.value.nil?
catch(:no_such_key) do
bound_value = Puppet::Pops::Lookup.search_and_merge("#{name}::#{param_name}", Puppet::Pops::Lookup::Invocation.new(scope), nil)
# Assign bound value but don't let an undef trump a default expression
resource[sym_name] = bound_value unless bound_value.nil? && !default.nil?
end
end
end
private :inject_external_parameters
def assign_defaults(resource, param_scope, scope)
return unless resource.is_a?(Puppet::Parser::Resource)
parameters = resource.parameters
arguments.each do |param_name, default|
next if default.nil?
name = param_name.to_sym
param = parameters[name]
next unless param.nil? || param.value.nil?
value = exceptwrap { param_scope.evaluate3x(param_name, default, scope) }
resource[name] = value
param_scope[param_name] = value
end
end
private :assign_defaults
def validate_resource_hash(resource, resource_hash)
Puppet::Pops::Types::TypeMismatchDescriber.validate_parameters(resource.to_s, parameter_struct, resource_hash, false)
end
private :validate_resource_hash
# Validate that all parameters given to the resource are correct
# @param resource [Puppet::Resource] the resource to validate
def validate_resource(resource)
# Since Sensitive values have special encoding (in a separate parameter) an unwrapped sensitive value must be
# recreated as a Sensitive in order to perform correct type checking.
sensitives = Set.new(resource.sensitive_parameters)
validate_resource_hash(resource,
resource.parameters.to_h do |name, value|
value_to_validate = sensitives.include?(name) ? Puppet::Pops::Types::PSensitiveType::Sensitive.new(value.value) : value.value
[name.to_s, value_to_validate]
end)
end
# Check whether a given argument is valid.
def valid_parameter?(param)
parameter_struct.hashed_elements.include?(param.to_s)
end
def set_arguments(arguments)
@arguments = {}
@parameter_struct = nil
return if arguments.nil?
arguments.each do |arg, default|
arg = arg.to_s
warn_if_metaparam(arg, default)
@arguments[arg] = default
end
end
# Sets the argument name to Puppet Type hash used for type checking.
# Names must correspond to available arguments (they must be defined first).
# Arguments not mentioned will not be type-checked.
#
def set_argument_types(name_to_type_hash)
@argument_types = {}
@parameter_struct = nil
return unless name_to_type_hash
name_to_type_hash.each do |name, t|
# catch internal errors
unless @arguments.include?(name)
raise Puppet::DevError, _("Parameter '%{name}' is given a type, but is not a valid parameter.") % { name: name }
end
unless t.is_a? Puppet::Pops::Types::PAnyType
raise Puppet::DevError, _("Parameter '%{name}' is given a type that is not a Puppet Type, got %{class_name}") % { name: name, class_name: t.class }
end
@argument_types[name] = t
end
end
private
def convert_from_ast(name)
value = name.value
if value.is_a?(Puppet::Parser::AST::Regex)
value.value
else
value
end
end
def evaluate_parent_type(resource)
klass = parent_type(resource.scope)
parent_resource = resource.scope.compiler.catalog.resource(:class, klass.name) || resource.scope.compiler.catalog.resource(:node, klass.name) if klass
return unless klass && parent_resource
parent_resource.evaluate unless parent_resource.evaluated?
parent_scope(resource.scope, klass)
end
# Split an fq name into a namespace and name
def namesplit(fullname)
ary = fullname.split(DOUBLE_COLON)
n = ary.pop || ""
ns = ary.join(DOUBLE_COLON)
[ns, n]
end
def parent_scope(scope, klass)
scope.class_scope(klass) || raise(Puppet::DevError, _("Could not find scope for %{class_name}") % { class_name: klass.name })
end
def set_name_and_namespace(name)
if name.is_a?(Regexp)
@name = name
@namespace = ""
else
@name = name.to_s.downcase
# Note we're doing something somewhat weird here -- we're setting
# the class's namespace to its fully qualified name. This means
# anything inside that class starts looking in that namespace first.
@namespace, _ = @type == :hostclass ? [@name, ''] : namesplit(@name)
end
end
def warn_if_metaparam(param, default)
return unless Puppet::Type.metaparamclass(param)
if default
warnonce _("%{param} is a metaparam; this value will inherit to all contained resources in the %{name} definition") % { param: param, name: name }
else
raise Puppet::ParseError, _("%{param} is a metaparameter; please choose another parameter name in the %{name} definition") % { param: param, name: name }
end
end
def parameter_struct
@parameter_struct ||= create_params_struct
end
def create_params_struct
arg_types = argument_types
type_factory = Puppet::Pops::Types::TypeFactory
members = { type_factory.optional(type_factory.string(NAME)) => type_factory.any }
Puppet::Type.eachmetaparam do |name|
# TODO: Once meta parameters are typed, this should change to reflect that type
members[name.to_s] = type_factory.any
end
arguments.each_pair do |name, default|
key_type = type_factory.string(name.to_s)
key_type = type_factory.optional(key_type) unless default.nil?
arg_type = arg_types[name]
arg_type = type_factory.any if arg_type.nil?
members[key_type] = arg_type
end
type_factory.struct(members)
end
private :create_params_struct
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/resource/catalog.rb | lib/puppet/resource/catalog.rb | # frozen_string_literal: true
require_relative '../../puppet/node'
require_relative '../../puppet/indirector'
require_relative '../../puppet/transaction'
require_relative '../../puppet/util/tagging'
require_relative '../../puppet/graph'
require 'securerandom'
# This class models a node catalog. It is the thing meant to be passed
# from server to client, and it contains all of the information in the
# catalog, including the resources and the relationships between them.
#
# @api public
class Puppet::Resource::Catalog < Puppet::Graph::SimpleGraph
class DuplicateResourceError < Puppet::Error
include Puppet::ExternalFileError
end
extend Puppet::Indirector
indirects :catalog, :terminus_setting => :catalog_terminus
include Puppet::Util::Tagging
# The host name this is a catalog for.
attr_accessor :name
# The catalog version. Used for testing whether a catalog
# is up to date.
attr_accessor :version
# The id of the code input to the compiler.
attr_accessor :code_id
# The UUID of the catalog
attr_accessor :catalog_uuid
# @return [Integer] catalog format version number. This value is constant
# for a given version of Puppet; it is incremented when a new release of
# Puppet changes the API for the various objects that make up the catalog.
attr_accessor :catalog_format
# Inlined file metadata for non-recursive find
# A hash of title => metadata
attr_accessor :metadata
# Inlined file metadata for recursive search
# A hash of title => { source => [metadata, ...] }
attr_accessor :recursive_metadata
# How long this catalog took to retrieve. Used for reporting stats.
attr_accessor :retrieval_duration
# Whether this is a host catalog, which behaves very differently.
# In particular, reports are sent, graphs are made, and state is
# stored in the state database. If this is set incorrectly, then you often
# end up in infinite loops, because catalogs are used to make things
# that the host catalog needs.
attr_accessor :host_config
# Whether this catalog was retrieved from the cache, which affects
# whether it is written back out again.
attr_accessor :from_cache
# Some metadata to help us compile and generally respond to the current state.
attr_accessor :client_version, :server_version
# A String representing the environment for this catalog
attr_accessor :environment
# The actual environment instance that was used during compilation
attr_accessor :environment_instance
# Add classes to our class list.
def add_class(*classes)
classes.each do |klass|
@classes << klass
end
# Add the class names as tags, too.
tag(*classes)
end
# Returns [typename, title] when given a String with "Type[title]".
# Returns [nil, nil] if '[' ']' not detected.
#
def title_key_for_ref(ref)
s = ref.index('[')
e = ref.rindex(']')
if s && e && e > s
a = [ref[0, s], ref[s + 1, e - s - 1]]
else
a = [nil, nil]
end
a
end
def add_resource_before(other, *resources)
resources.each do |resource|
other_title_key = title_key_for_ref(other.ref)
idx = @resources.index(other_title_key)
if idx.nil?
raise ArgumentError, _("Cannot add resource %{resource_1} before %{resource_2} because %{resource_2} is not yet in the catalog") %
{ resource_1: resource.ref, resource_2: other.ref }
end
add_one_resource(resource, idx)
end
end
# Add `resources` to the catalog after `other`. WARNING: adding
# multiple resources will produce the reverse ordering, e.g. calling
# `add_resource_after(A, [B,C])` will result in `[A,C,B]`.
def add_resource_after(other, *resources)
resources.each do |resource|
other_title_key = title_key_for_ref(other.ref)
idx = @resources.index(other_title_key)
if idx.nil?
raise ArgumentError, _("Cannot add resource %{resource_1} after %{resource_2} because %{resource_2} is not yet in the catalog") %
{ resource_1: resource.ref, resource_2: other.ref }
end
add_one_resource(resource, idx + 1)
end
end
def add_resource(*resources)
resources.each do |resource|
add_one_resource(resource)
end
end
# @param resource [A Resource] a resource in the catalog
# @return [A Resource, nil] the resource that contains the given resource
# @api public
def container_of(resource)
adjacent(resource, :direction => :in)[0]
end
def add_one_resource(resource, idx = -1)
title_key = title_key_for_ref(resource.ref)
if @resource_table[title_key]
fail_on_duplicate_type_and_title(resource, title_key)
end
add_resource_to_table(resource, title_key, idx)
create_resource_aliases(resource)
resource.catalog = self if resource.respond_to?(:catalog=)
add_resource_to_graph(resource)
end
private :add_one_resource
def add_resource_to_table(resource, title_key, idx)
@resource_table[title_key] = resource
@resources.insert(idx, title_key)
end
private :add_resource_to_table
def add_resource_to_graph(resource)
add_vertex(resource)
@relationship_graph.add_vertex(resource) if @relationship_graph
end
private :add_resource_to_graph
def create_resource_aliases(resource)
# Explicit aliases must always be processed
# The alias setting logic checks, and does not error if the alias is set to an already set alias
# for the same resource (i.e. it is ok if alias == title
explicit_aliases = [resource[:alias]].flatten.compact
explicit_aliases.each { |given_alias| self.alias(resource, given_alias) }
# Skip creating uniqueness key alias and checking collisions for non-isomorphic resources.
return unless resource.respond_to?(:isomorphic?) and resource.isomorphic?
# Add an alias if the uniqueness key is valid and not the title, which has already been checked.
ukey = resource.uniqueness_key
if ukey.any? and ukey != [resource.title]
self.alias(resource, ukey)
end
end
private :create_resource_aliases
# Create an alias for a resource.
def alias(resource, key)
ref = resource.ref
ref =~ /^(.+)\[/
class_name = ::Regexp.last_match(1) || resource.class.name
newref = [class_name, key].flatten
if key.is_a? String
ref_string = "#{class_name}[#{key}]"
return if ref_string == ref
end
# LAK:NOTE It's important that we directly compare the references,
# because sometimes an alias is created before the resource is
# added to the catalog, so comparing inside the below if block
# isn't sufficient.
existing = @resource_table[newref]
if existing
return if existing == resource
resource_declaration = Puppet::Util::Errors.error_location(resource.file, resource.line)
msg = if resource_declaration.empty?
# TRANSLATORS 'alias' should not be translated
_("Cannot alias %{resource} to %{key}; resource %{newref} already declared") %
{ resource: ref, key: key.inspect, newref: newref.inspect }
else
# TRANSLATORS 'alias' should not be translated
_("Cannot alias %{resource} to %{key} at %{resource_declaration}; resource %{newref} already declared") %
{ resource: ref, key: key.inspect, resource_declaration: resource_declaration, newref: newref.inspect }
end
msg += Puppet::Util::Errors.error_location_with_space(existing.file, existing.line)
raise ArgumentError, msg
end
@resource_table[newref] = resource
@aliases[ref] ||= []
@aliases[ref] << newref
end
# Apply our catalog to the local host.
# @param options [Hash{Symbol => Object}] a hash of options
# @option options [Puppet::Transaction::Report] :report
# The report object to log this transaction to. This is optional,
# and the resulting transaction will create a report if not
# supplied.
#
# @return [Puppet::Transaction] the transaction created for this
# application
#
# @api public
def apply(options = {})
Puppet::Util::Storage.load if host_config?
transaction = create_transaction(options)
begin
transaction.report.as_logging_destination do
transaction_evaluate_time = Puppet::Util.thinmark do
transaction.evaluate
end
transaction.report.add_times(:transaction_evaluation, transaction_evaluate_time)
end
ensure
# Don't try to store state unless we're a host config
# too recursive.
Puppet::Util::Storage.store if host_config?
end
yield transaction if block_given?
transaction
end
# The relationship_graph form of the catalog. This contains all of the
# dependency edges that are used for determining order.
#
# @param given_prioritizer [Puppet::Graph::Prioritizer] The prioritization
# strategy to use when constructing the relationship graph. Defaults the
# being determined by the `ordering` setting.
# @return [Puppet::Graph::RelationshipGraph]
# @api public
def relationship_graph(given_prioritizer = nil)
if @relationship_graph.nil?
@relationship_graph = Puppet::Graph::RelationshipGraph.new(given_prioritizer || prioritizer)
@relationship_graph.populate_from(self)
end
@relationship_graph
end
def clear(remove_resources = true)
super()
# We have to do this so that the resources clean themselves up.
@resource_table.values.each(&:remove) if remove_resources
@resource_table.clear
@resources = []
if @relationship_graph
@relationship_graph.clear
@relationship_graph = nil
end
end
def classes
@classes.dup
end
# Create a new resource and register it in the catalog.
def create_resource(type, options)
klass = Puppet::Type.type(type)
unless klass
raise ArgumentError, _("Unknown resource type %{type}") % { type: type }
end
resource = klass.new(options)
return unless resource
add_resource(resource)
resource
end
# Make sure all of our resources are "finished".
def finalize
make_default_resources
@resource_table.values.each(&:finish)
write_graph(:resources)
end
def host_config?
host_config
end
def initialize(name = nil, environment = Puppet::Node::Environment::NONE, code_id = nil)
super()
@name = name
@catalog_uuid = SecureRandom.uuid
@catalog_format = 2
@metadata = {}
@recursive_metadata = {}
@classes = []
@resource_table = {}
@resources = []
@relationship_graph = nil
@host_config = true
@environment_instance = environment
@environment = environment.to_s
@code_id = code_id
@aliases = {}
if block_given?
yield(self)
finalize
end
end
# Make the default objects necessary for function.
def make_default_resources
# We have to add the resources to the catalog, or else they won't get cleaned up after
# the transaction.
# First create the default scheduling objects
Puppet::Type.type(:schedule).mkdefaultschedules.each { |res| add_resource(res) unless resource(res.ref) }
# And filebuckets
bucket = Puppet::Type.type(:filebucket).mkdefaultbucket
if bucket
add_resource(bucket) unless resource(bucket.ref)
end
end
# Remove the resource from our catalog. Notice that we also call
# 'remove' on the resource, at least until resource classes no longer maintain
# references to the resource instances.
def remove_resource(*resources)
resources.each do |resource|
ref = resource.ref
title_key = title_key_for_ref(ref)
@resource_table.delete(title_key)
aliases = @aliases[ref]
if aliases
aliases.each { |res_alias| @resource_table.delete(res_alias) }
@aliases.delete(ref)
end
remove_vertex!(resource) if vertex?(resource)
@relationship_graph.remove_vertex!(resource) if @relationship_graph and @relationship_graph.vertex?(resource)
@resources.delete(title_key)
# Only Puppet::Type kind of resources respond to :remove, not Puppet::Resource
resource.remove if resource.respond_to?(:remove)
end
end
# Look a resource up by its reference (e.g., File[/etc/passwd]).
def resource(type, title = nil)
# Retain type if it's a type
type_name = type.is_a?(Puppet::CompilableResourceType) || type.is_a?(Puppet::Resource::Type) ? type.name : type
type_name, title = Puppet::Resource.type_and_title(type_name, title)
type = type_name if type.is_a?(String)
title_key = [type_name, title.to_s]
result = @resource_table[title_key]
if result.nil?
# an instance has to be created in order to construct the unique key used when
# searching for aliases
res = Puppet::Resource.new(type, title, { :environment => @environment_instance })
# Must check with uniqueness key because of aliases or if resource transforms title in title
# to attribute mappings.
result = @resource_table[[type_name, res.uniqueness_key].flatten]
end
result
end
def resource_refs
resource_keys.filter_map { |type, name| name.is_a?(String) ? "#{type}[#{name}]" : nil }
end
def resource_keys
@resource_table.keys
end
def resources
@resources.collect do |key|
@resource_table[key]
end
end
def self.from_data_hash(data)
result = new(data['name'], Puppet::Node::Environment::NONE)
result.tag(*data['tags']) if data['tags']
result.version = data['version'] if data['version']
result.code_id = data['code_id'] if data['code_id']
result.catalog_uuid = data['catalog_uuid'] if data['catalog_uuid']
result.catalog_format = data['catalog_format'] || 0
environment = data['environment']
if environment
result.environment = environment
result.environment_instance = Puppet::Node::Environment.remote(environment.to_sym)
end
result.add_resource(
*data['resources'].collect do |res|
Puppet::Resource.from_data_hash(res)
end
) if data['resources']
if data['edges']
data['edges'].each do |edge_hash|
edge = Puppet::Relationship.from_data_hash(edge_hash)
source = result.resource(edge.source)
unless source
raise ArgumentError, _("Could not intern from data: Could not find relationship source %{source} for %{target}") %
{ source: edge.source.inspect, target: edge.target.to_s }
end
edge.source = source
target = result.resource(edge.target)
unless target
raise ArgumentError, _("Could not intern from data: Could not find relationship target %{target} for %{source}") %
{ target: edge.target.inspect, source: edge.source.to_s }
end
edge.target = target
result.add_edge(edge)
end
end
result.add_class(*data['classes']) if data['classes']
result.metadata = data['metadata'].transform_values { |v| Puppet::FileServing::Metadata.from_data_hash(v); } if data['metadata']
recursive_metadata = data['recursive_metadata']
if recursive_metadata
result.recursive_metadata = recursive_metadata.transform_values do |source_to_meta_hash|
source_to_meta_hash.transform_values do |metas|
metas.map { |meta| Puppet::FileServing::Metadata.from_data_hash(meta) }
end
end
end
result
end
def to_data_hash
metadata_hash = metadata.transform_values(&:to_data_hash)
recursive_metadata_hash = recursive_metadata.transform_values do |source_to_meta_hash|
source_to_meta_hash.transform_values do |metas|
metas.map(&:to_data_hash)
end
end
{
'tags' => tags.to_a,
'name' => name,
'version' => version,
'code_id' => code_id,
'catalog_uuid' => catalog_uuid,
'catalog_format' => catalog_format,
'environment' => environment.to_s,
'resources' => @resources.map { |v| @resource_table[v].to_data_hash },
'edges' => edges.map(&:to_data_hash),
'classes' => classes,
}.merge(metadata_hash.empty? ?
{} : { 'metadata' => metadata_hash }).merge(recursive_metadata_hash.empty? ?
{} : { 'recursive_metadata' => recursive_metadata_hash })
end
# Convert our catalog into a RAL catalog.
def to_ral
to_catalog :to_ral
end
# Convert our catalog into a catalog of Puppet::Resource instances.
def to_resource
to_catalog :to_resource
end
# filter out the catalog, applying +block+ to each resource.
# If the block result is false, the resource will
# be kept otherwise it will be skipped
def filter(&block)
# to_catalog must take place in a context where current_environment is set to the same env as the
# environment set in the catalog (if it is set)
# See PUP-3755
if environment_instance
Puppet.override({ :current_environment => environment_instance }) do
to_catalog :to_resource, &block
end
else
# If catalog has no environment_instance, hope that the caller has made sure the context has the
# correct current_environment
to_catalog :to_resource, &block
end
end
# Store the classes in the classfile.
def write_class_file
# classfile paths may contain UTF-8
# https://puppet.com/docs/puppet/latest/configuration.html#classfile
classfile = Puppet.settings.setting(:classfile)
Puppet::FileSystem.open(classfile.value, classfile.mode.to_i(8), "w:UTF-8") do |f|
f.puts classes.join("\n")
end
rescue => detail
Puppet.err _("Could not create class file %{file}: %{detail}") % { file: Puppet[:classfile], detail: detail }
end
# Store the list of resources we manage
def write_resource_file
# resourcefile contains resources that may be UTF-8 names
# https://puppet.com/docs/puppet/latest/configuration.html#resourcefile
resourcefile = Puppet.settings.setting(:resourcefile)
Puppet::FileSystem.open(resourcefile.value, resourcefile.mode.to_i(8), "w:UTF-8") do |f|
to_print = resources.filter_map do |resource|
next unless resource.managed?
resource.ref.downcase.to_s
end
f.puts to_print.join("\n")
end
rescue => detail
Puppet.err _("Could not create resource file %{file}: %{detail}") % { file: Puppet[:resourcefile], detail: detail }
end
# Produce the graph files if requested.
def write_graph(name)
# We only want to graph the main host catalog.
return unless host_config?
super
end
private
def prioritizer
@prioritizer = Puppet::Graph::SequentialPrioritizer.new
end
def create_transaction(options)
transaction = Puppet::Transaction.new(self, options[:report], prioritizer)
transaction.tags = options[:tags] if options[:tags]
transaction.ignoreschedules = true if options[:ignoreschedules]
transaction.for_network_device = Puppet.lookup(:network_device) { nil } || options[:network_device]
transaction
end
# Verify that the given resource isn't declared elsewhere.
def fail_on_duplicate_type_and_title(resource, title_key)
# Short-circuit the common case,
existing_resource = @resource_table[title_key]
return unless existing_resource
# If we've gotten this far, it's a real conflict
error_location_str = Puppet::Util::Errors.error_location(existing_resource.file, existing_resource.line)
msg = if error_location_str.empty?
_("Duplicate declaration: %{resource} is already declared; cannot redeclare") % { resource: resource.ref }
else
_("Duplicate declaration: %{resource} is already declared at %{error_location}; cannot redeclare") % { resource: resource.ref, error_location: error_location_str }
end
raise DuplicateResourceError.new(msg, resource.file, resource.line)
end
# An abstracted method for converting one catalog into another type of catalog.
# This pretty much just converts all of the resources from one class to another, using
# a conversion method.
def to_catalog(convert)
result = self.class.new(name, environment_instance)
result.version = version
result.code_id = code_id
result.catalog_uuid = catalog_uuid
result.catalog_format = catalog_format
result.metadata = metadata
result.recursive_metadata = recursive_metadata
map = {}
resources.each do |resource|
next if virtual_not_exported?(resource)
next if block_given? and yield resource
newres = resource.copy_as_resource
newres.catalog = result
if convert != :to_resource
newres = newres.to_ral
end
# We can't guarantee that resources don't munge their names
# (like files do with trailing slashes), so we have to keep track
# of what a resource got converted to.
map[resource.ref] = newres
result.add_resource newres
end
message = convert.to_s.tr "_", " "
edges.each do |edge|
# Skip edges between virtual resources.
next if virtual_not_exported?(edge.source)
next if block_given? and yield edge.source
next if virtual_not_exported?(edge.target)
next if block_given? and yield edge.target
source = map[edge.source.ref]
unless source
raise Puppet::DevError, _("Could not find resource %{resource} when converting %{message} resources") % { resource: edge.source.ref, message: message }
end
target = map[edge.target.ref]
unless target
raise Puppet::DevError, _("Could not find resource %{resource} when converting %{message} resources") % { resource: edge.target.ref, message: message }
end
result.add_edge(source, target, edge.label)
end
map.clear
result.add_class(*classes)
result.merge_tags_from(self)
result
end
def virtual_not_exported?(resource)
resource.virtual && !resource.exported
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/resource/type_collection.rb | lib/puppet/resource/type_collection.rb | # frozen_string_literal: true
require_relative '../../puppet/parser/type_loader'
require_relative '../../puppet/util/file_watcher'
require_relative '../../puppet/util/warnings'
require_relative '../../puppet/concurrent/lock'
# @api private
class Puppet::Resource::TypeCollection
attr_reader :environment
attr_accessor :parse_failed
include Puppet::Util::Warnings
def clear
@hostclasses.clear
@definitions.clear
@nodes.clear
@notfound.clear
end
def initialize(env)
@environment = env
@hostclasses = {}
@definitions = {}
@nodes = {}
@notfound = {}
# always lock the environment before acquiring this lock
@lock = Puppet::Concurrent::Lock.new
# So we can keep a list and match the first-defined regex
@node_list = []
end
def import_ast(ast, modname)
ast.instantiate(modname).each do |instance|
add(instance)
end
end
def inspect
"TypeCollection" + {
:hostclasses => @hostclasses.keys,
:definitions => @definitions.keys,
:nodes => @nodes.keys
}.inspect
end
# @api private
def <<(thing)
add(thing)
self
end
def add(instance)
# return a merged instance, or the given
catch(:merged) {
send("add_#{instance.type}", instance)
instance.resource_type_collection = self
instance
}
end
def add_hostclass(instance)
handle_hostclass_merge(instance)
dupe_check(instance, @hostclasses) { |dupe| _("Class '%{klass}' is already defined%{error}; cannot redefine") % { klass: instance.name, error: dupe.error_context } }
dupe_check(instance, @nodes) { |dupe| _("Node '%{klass}' is already defined%{error}; cannot be redefined as a class") % { klass: instance.name, error: dupe.error_context } }
dupe_check(instance, @definitions) { |dupe| _("Definition '%{klass}' is already defined%{error}; cannot be redefined as a class") % { klass: instance.name, error: dupe.error_context } }
@hostclasses[instance.name] = instance
instance
end
def handle_hostclass_merge(instance)
# Only main class (named '') can be merged (for purpose of merging top-scopes).
return instance unless instance.name == ''
if instance.type == :hostclass && (other = @hostclasses[instance.name]) && other.type == :hostclass
other.merge(instance)
# throw is used to signal merge - avoids dupe checks and adding it to hostclasses
throw :merged, other
end
end
# Replaces the known settings with a new instance (that must be named 'settings').
# This is primarily needed for testing purposes. Also see PUP-5954 as it makes
# it illegal to merge classes other than the '' (main) class. Prior to this change
# settings where always merged rather than being defined from scratch for many testing scenarios
# not having a complete side effect free setup for compilation.
#
def replace_settings(instance)
@hostclasses['settings'] = instance
end
def hostclass(name)
@hostclasses[munge_name(name)]
end
def add_node(instance)
dupe_check(instance, @nodes) { |dupe| _("Node '%{name}' is already defined%{error}; cannot redefine") % { name: instance.name, error: dupe.error_context } }
dupe_check(instance, @hostclasses) { |dupe| _("Class '%{klass}' is already defined%{error}; cannot be redefined as a node") % { klass: instance.name, error: dupe.error_context } }
@node_list << instance
@nodes[instance.name] = instance
instance
end
def loader
@loader ||= Puppet::Parser::TypeLoader.new(environment)
end
def node(name)
name = munge_name(name)
node = @nodes[name]
if node
return node
end
@node_list.each do |n|
next unless n.name_is_regex?
return n if n.match(name)
end
nil
end
def node_exists?(name)
@nodes[munge_name(name)]
end
def nodes?
@nodes.length > 0
end
def add_definition(instance)
dupe_check(instance, @hostclasses) { |dupe| _("'%{name}' is already defined%{error} as a class; cannot redefine as a definition") % { name: instance.name, error: dupe.error_context } }
dupe_check(instance, @definitions) { |dupe| _("Definition '%{name}' is already defined%{error}; cannot be redefined") % { name: instance.name, error: dupe.error_context } }
@definitions[instance.name] = instance
end
def definition(name)
@definitions[munge_name(name)]
end
def find_node(name)
@nodes[munge_name(name)]
end
def find_hostclass(name)
find_or_load(name, :hostclass)
end
def find_definition(name)
find_or_load(name, :definition)
end
# TODO: This implementation is wasteful as it creates a copy on each request
#
[:hostclasses, :nodes, :definitions].each do |m|
define_method(m) do
instance_variable_get("@#{m}").dup
end
end
def parse_failed?
@parse_failed
end
def version
unless defined?(@version)
if environment.config_version.nil? || environment.config_version == ""
@version = Time.now.to_i
else
@version = Puppet::Util::Execution.execute([environment.config_version]).to_s.strip
end
end
@version
rescue Puppet::ExecutionFailure => e
raise Puppet::ParseError, _("Execution of config_version command `%{cmd}` failed: %{message}") % { cmd: environment.config_version, message: e.message }, e.backtrace
end
private
COLON_COLON = "::"
# Resolve namespaces and find the given object. Autoload it if
# necessary.
def find_or_load(name, type)
# always lock the environment before locking the type collection
@environment.lock.synchronize do
@lock.synchronize do
# Name is always absolute, but may start with :: which must be removed
fqname = (name[0, 2] == COLON_COLON ? name[2..] : name)
result = send(type, fqname)
unless result
if @notfound[fqname] && Puppet[:ignoremissingtypes]
# do not try to autoload if we already tried and it wasn't conclusive
# as this is a time consuming operation. Warn the user.
# Check first if debugging is on since the call to debug_once is expensive
if Puppet[:debug]
debug_once _("Not attempting to load %{type} %{fqname} as this object was missing during a prior compilation") % { type: type, fqname: fqname }
end
else
fqname = munge_name(fqname)
result = loader.try_load_fqname(type, fqname)
@notfound[fqname] = result.nil?
end
end
result
end
end
end
def munge_name(name)
name.to_s.downcase
end
def dupe_check(instance, hash)
dupe = hash[instance.name]
return unless dupe
message = yield dupe
instance.fail Puppet::ParseError, message
end
def dupe_check_singleton(instance, set)
return if set.empty?
message = yield set[0]
instance.fail Puppet::ParseError, message
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/resource/status.rb | lib/puppet/resource/status.rb | # frozen_string_literal: true
require 'time'
require_relative '../../puppet/network/format_support'
require_relative '../../puppet/util/psych_support'
module Puppet
class Resource
# This class represents the result of evaluating a given resource. It
# contains file and line information about the source, events generated
# while evaluating the resource, timing information, and the status of the
# resource evaluation.
#
# @api private
class Status
include Puppet::Util::PsychSupport
include Puppet::Util::Tagging
include Puppet::Network::FormatSupport
# @!attribute [rw] file
# @return [String] The file where `@real_resource` was defined.
attr_accessor :file
# @!attribute [rw] line
# @return [Integer] The line number in the file where `@real_resource` was defined.
attr_accessor :line
# @!attribute [rw] evaluation_time
# @return [Float] The time elapsed in sections while evaluating `@real_resource`.
# measured in seconds.
attr_accessor :evaluation_time
# Boolean status types set while evaluating `@real_resource`.
STATES = [:skipped, :failed, :failed_to_restart, :restarted, :changed, :out_of_sync, :scheduled, :corrective_change]
attr_accessor(*STATES)
# @!attribute [r] source_description
# @return [String] The textual description of the path to `@real_resource`
# based on the containing structures. This is in contrast to
# `@containment_path` which is a list of containment path components.
# @example
# status.source_description #=> "/Stage[main]/Myclass/Exec[date]"
attr_reader :source_description
# @!attribute [r] containment_path
# @return [Array<String>] A list of resource references that contain
# `@real_resource`.
# @example A normal contained type
# status.containment_path #=> ["Stage[main]", "Myclass", "Exec[date]"]
# @example A whit associated with a class
# status.containment_path #=> ["Whit[Admissible_class[Main]]"]
attr_reader :containment_path
# @!attribute [r] time
# @return [Time] The time that this status object was created
attr_reader :time
# @!attribute [r] resource
# @return [String] The resource reference for `@real_resource`
attr_reader :resource
# @!attribute [r] change_count
# @return [Integer] A count of the successful changes made while
# evaluating `@real_resource`.
attr_reader :change_count
# @!attribute [r] out_of_sync_count
# @return [Integer] A count of the audited changes made while
# evaluating `@real_resource`.
attr_reader :out_of_sync_count
# @!attribute [r] resource_type
# @example
# status.resource_type #=> 'Notify'
# @return [String] The class name of `@real_resource`
attr_reader :resource_type
# @!attribute [rw] provider_used
# @return [String] The class name of the provider used for the resource
attr_accessor :provider_used
# @!attribute [r] title
# @return [String] The title of `@real_resource`
attr_reader :title
# @!attribute [r] events
# @return [Array<Puppet::Transaction::Event>] A list of events generated
# while evaluating `@real_resource`.
attr_reader :events
# @!attribute [r] corrective_change
# @return [Boolean] true if the resource contained a corrective change.
attr_reader :corrective_change
# @!attribute [rw] failed_dependencies
# @return [Array<Puppet::Resource>] A cache of all
# dependencies of this resource that failed to apply.
attr_accessor :failed_dependencies
def dependency_failed?
failed_dependencies && !failed_dependencies.empty?
end
def self.from_data_hash(data)
obj = allocate
obj.initialize_from_hash(data)
obj
end
# Provide a boolean method for each of the states.
STATES.each do |attr|
define_method("#{attr}?") do
!!send(attr)
end
end
def <<(event)
add_event(event)
self
end
def add_event(event)
@events << event
case event.status
when 'failure'
self.failed = true
when 'success'
@change_count += 1
@changed = true
end
if event.status != 'audit'
@out_of_sync_count += 1
@out_of_sync = true
end
if event.corrective_change
@corrective_change = true
end
end
def failed_because(detail)
@real_resource.log_exception(detail, _("Could not evaluate: %{detail}") % { detail: detail })
# There's a contract (implicit unfortunately) that a status of failed
# will always be accompanied by an event with some explanatory power. This
# is useful for reporting/diagnostics/etc. So synthesize an event here
# with the exception detail as the message.
fail_with_event(detail.to_s)
end
# Both set the status state to failed and generate a corresponding
# Puppet::Transaction::Event failure with the given message.
# @param message [String] the reason for a status failure
def fail_with_event(message)
add_event(@real_resource.event(:name => :resource_error, :status => "failure", :message => message))
end
def initialize(resource)
@real_resource = resource
@source_description = resource.path
@containment_path = resource.pathbuilder
@resource = resource.to_s
@change_count = 0
@out_of_sync_count = 0
@changed = false
@out_of_sync = false
@skipped = false
@failed = false
@corrective_change = false
@file = resource.file
@line = resource.line
merge_tags_from(resource)
@time = Time.now
@events = []
@resource_type = resource.type.to_s.capitalize
@provider_used = resource.provider.class.name.to_s unless resource.provider.nil?
@title = resource.title
end
def initialize_from_hash(data)
@resource_type = data['resource_type']
@provider_used = data['provider_used']
@title = data['title']
@resource = data['resource']
@containment_path = data['containment_path']
@file = data['file']
@line = data['line']
@evaluation_time = data['evaluation_time']
@change_count = data['change_count']
@out_of_sync_count = data['out_of_sync_count']
@tags = Puppet::Util::TagSet.new(data['tags'])
@time = data['time']
@time = Time.parse(@time) if @time.is_a? String
@out_of_sync = data['out_of_sync']
@changed = data['changed']
@skipped = data['skipped']
@failed = data['failed']
@failed_to_restart = data['failed_to_restart']
@corrective_change = data['corrective_change']
@events = data['events'].map do |event|
# Older versions contain tags that causes Psych to create instances directly
event.is_a?(Puppet::Transaction::Event) ? event : Puppet::Transaction::Event.from_data_hash(event)
end
end
def to_data_hash
{
'title' => @title,
'file' => @file,
'line' => @line,
'resource' => @resource,
'resource_type' => @resource_type,
'provider_used' => @provider_used,
'containment_path' => @containment_path,
'evaluation_time' => @evaluation_time,
'tags' => @tags.to_a,
'time' => @time.iso8601(9),
'failed' => @failed,
'failed_to_restart' => failed_to_restart?,
'changed' => @changed,
'out_of_sync' => @out_of_sync,
'skipped' => @skipped,
'change_count' => @change_count,
'out_of_sync_count' => @out_of_sync_count,
'events' => @events.map(&:to_data_hash),
'corrective_change' => @corrective_change,
}
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/vendor/require_vendored.rb | lib/puppet/vendor/require_vendored.rb | # This adds upfront requirements on vendored code found under lib/vendor/x
# Add one requirement per vendored package (or a comment if it is loaded on demand).
# The vendored library 'rgen' is loaded on demand.
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/node/environment.rb | lib/puppet/node/environment.rb | # frozen_string_literal: true
require_relative '../../puppet/util'
require 'monitor'
require_relative '../../puppet/parser/parser_factory'
require_relative '../../puppet/concurrent/lock'
# Just define it, so this class has fewer load dependencies.
class Puppet::Node
end
# Puppet::Node::Environment acts as a container for all configuration
# that is expected to vary between environments.
#
# ## The root environment
#
# In addition to normal environments that are defined by the user,there is a
# special 'root' environment. It is defined as an instance variable on the
# Puppet::Node::Environment metaclass. The environment name is `*root*` and can
# be accessed by looking up the `:root_environment` using {Puppet.lookup}.
#
# The primary purpose of the root environment is to contain parser functions
# that are not bound to a specific environment. The main case for this is for
# logging functions. Logging functions are attached to the 'root' environment
# when {Puppet::Parser::Functions.reset} is called.
class Puppet::Node::Environment
NO_MANIFEST = :no_manifest
# The create() factory method should be used instead.
private_class_method :new
# Create a new environment with the given name
#
# @param name [Symbol] the name of the environment
# @param modulepath [Array<String>] the list of paths from which to load modules
# @param manifest [String] the path to the manifest for the environment or
# the constant Puppet::Node::Environment::NO_MANIFEST if there is none.
# @param config_version [String] path to a script whose output will be added
# to report logs (optional)
# @return [Puppet::Node::Environment]
#
# @api public
def self.create(name, modulepath, manifest = NO_MANIFEST, config_version = nil)
new(name, modulepath, manifest, config_version)
end
# A remote subclass to make it easier to trace instances when debugging.
# @api private
class Remote < Puppet::Node::Environment; end
# A "reference" to a remote environment. The created environment instance
# isn't expected to exist on the local system, but is instead a reference to
# environment information on a remote system. For instance when a catalog is
# being applied, this will be used on the agent.
#
# @note This does not provide access to the information of the remote
# environment's modules, manifest, or anything else. It is simply a value
# object to pass around and use as an environment.
#
# @param name [Symbol] The name of the remote environment
#
def self.remote(name)
Remote.create(name, [], NO_MANIFEST)
end
# Instantiate a new environment
#
# @note {Puppet::Node::Environment.new} is private for historical reasons, as
# previously it had been overridden to return memoized objects and was
# replaced with {Puppet::Node::Environment.create}, so this will not be
# invoked with the normal Ruby initialization semantics.
#
# @param name [Symbol] The environment name
def initialize(name, modulepath, manifest, config_version)
@lock = Puppet::Concurrent::Lock.new
@name = name.intern
@modulepath = self.class.expand_dirs(self.class.extralibs() + modulepath)
@manifest = manifest == NO_MANIFEST ? manifest : Puppet::FileSystem.expand_path(manifest)
@config_version = config_version
end
# Creates a new Puppet::Node::Environment instance, overriding any of the passed
# parameters.
#
# @param env_params [Hash<{Symbol => String,Array<String>}>] new environment
# parameters (:modulepath, :manifest, :config_version)
# @return [Puppet::Node::Environment]
def override_with(env_params)
self.class.create(name,
env_params[:modulepath] || modulepath,
env_params[:manifest] || manifest,
env_params[:config_version] || config_version)
end
# Creates a new Puppet::Node::Environment instance, overriding :manifest,
# :modulepath, or :config_version from the passed settings if they were
# originally set from the commandline, or returns self if there is nothing to
# override.
#
# @param settings [Puppet::Settings] an initialized puppet settings instance
# @return [Puppet::Node::Environment] new overridden environment or self if
# there are no commandline changes from settings.
def override_from_commandline(settings)
overrides = {}
if settings.set_by_cli?(:modulepath)
overrides[:modulepath] = self.class.split_path(settings.value(:modulepath))
end
if settings.set_by_cli?(:config_version)
overrides[:config_version] = settings.value(:config_version)
end
if settings.set_by_cli?(:manifest)
overrides[:manifest] = settings.value(:manifest)
end
overrides.empty? ?
self :
override_with(overrides)
end
# @param [String] name Environment name to check for valid syntax.
# @return [Boolean] true if name is valid
# @api public
def self.valid_name?(name)
!!name.match(/\A\w+\Z/)
end
# @!attribute [r] name
# @api public
# @return [Symbol] the human readable environment name that serves as the
# environment identifier
attr_reader :name
# @api public
# @return [Array<String>] All directories present on disk in the modulepath
def modulepath
@modulepath.find_all do |p|
Puppet::FileSystem.directory?(p)
end
end
# @api public
# @return [Array<String>] All directories in the modulepath (even if they are not present on disk)
def full_modulepath
@modulepath
end
# @!attribute [r] manifest
# @api public
# @return [String] path to the manifest file or directory.
attr_reader :manifest
# @!attribute [r] config_version
# @api public
# @return [String] path to a script whose output will be added to report logs
# (optional)
attr_reader :config_version
# Cached loaders - management of value handled by Puppet::Pops::Loaders
# @api private
attr_accessor :loaders
# Lock for compilation that needs exclusive access to the environment
# @api private
attr_reader :lock
# For use with versioned dirs
# our environment path may contain symlinks, while we want to resolve the
# path while reading the manifests we may want to report the resources as
# coming from the configured path.
attr_accessor :configured_path
# See :configured_path above
attr_accessor :resolved_path
# Ensure the path given is of the format we want in the catalog/report.
#
# Intended for use with versioned symlinked environments. If this
# environment is configured with "/etc/puppetlabs/code/environments/production"
# but the resolved path is
#
# "/opt/puppetlabs/server/puppetserver/filesync/client/puppet-code/production_abcdef1234"
#
# this changes the filepath
#
# "/opt/puppetlabs/server/puppetserver/filesync/client/puppet-code/production_abcdef1234/modules/foo/manifests/init.pp"
#
# to
#
# "/etc/puppetlabs/code/environments/production/modules/foo/manifests/init.pp"
def externalize_path(filepath)
paths_set = configured_path && resolved_path
munging_possible = paths_set && configured_path != resolved_path
munging_desired = munging_possible &&
Puppet[:report_configured_environmentpath] &&
filepath.to_s.start_with?(resolved_path)
if munging_desired
File.join(configured_path, filepath.delete_prefix(resolved_path))
else
filepath
end
end
# Checks to make sure that this environment did not have a manifest set in
# its original environment.conf if Puppet is configured with
# +disable_per_environment_manifest+ set true. If it did, the environment's
# modules may not function as intended by the original authors, and we may
# seek to halt a puppet compilation for a node in this environment.
#
# The only exception to this would be if the environment.conf manifest is an exact,
# uninterpolated match for the current +default_manifest+ setting.
#
# @return [Boolean] true if using directory environments, and
# Puppet[:disable_per_environment_manifest] is true, and this environment's
# original environment.conf had a manifest setting that is not the
# Puppet[:default_manifest].
# @api private
def conflicting_manifest_settings?
return false unless Puppet[:disable_per_environment_manifest]
original_manifest = configuration.raw_setting(:manifest)
!original_manifest.nil? && !original_manifest.empty? && original_manifest != Puppet[:default_manifest]
end
# @api private
def static_catalogs?
if @static_catalogs.nil?
environment_conf = Puppet.lookup(:environments).get_conf(name)
@static_catalogs = (environment_conf.nil? ? Puppet[:static_catalogs] : environment_conf.static_catalogs)
end
@static_catalogs
end
# Return the environment configuration
# @return [Puppet::Settings::EnvironmentConf] The configuration
#
# @api private
def configuration
Puppet.lookup(:environments).get_conf(name)
end
# Checks the environment and settings for any conflicts
# @return [Array<String>] an array of validation errors
# @api public
def validation_errors
errors = []
if conflicting_manifest_settings?
errors << _("The 'disable_per_environment_manifest' setting is true, and the '%{env_name}' environment has an environment.conf manifest that conflicts with the 'default_manifest' setting.") % { env_name: name }
end
errors
end
def rich_data_from_env_conf
unless @checked_conf_for_rich_data
environment_conf = Puppet.lookup(:environments).get_conf(name)
@rich_data_from_conf = environment_conf&.rich_data
@checked_conf_for_rich_data = true
end
@rich_data_from_conf
end
# Checks if this environment permits use of rich data types in the catalog
# Checks the environment conf for an override on first query, then going forward
# either uses that, or if unset, uses the current value of the `rich_data` setting.
# @return [Boolean] `true` if rich data is permitted.
# @api private
def rich_data?
@rich_data = rich_data_from_env_conf.nil? ? Puppet[:rich_data] : rich_data_from_env_conf
end
# Return an environment-specific Puppet setting.
#
# @api public
#
# @param param [String, Symbol] The environment setting to look up
# @return [Object] The resolved setting value
def [](param)
Puppet.settings.value(param, name)
end
# @api public
# @return [Puppet::Resource::TypeCollection] The current global TypeCollection
def known_resource_types
@lock.synchronize do
if @known_resource_types.nil?
@known_resource_types = Puppet::Resource::TypeCollection.new(self)
@known_resource_types.import_ast(perform_initial_import(), '')
end
@known_resource_types
end
end
# Yields each modules' plugin directory if the plugin directory (modulename/lib)
# is present on the filesystem.
#
# @yield [String] Yields the plugin directory from each module to the block.
# @api public
def each_plugin_directory(&block)
modules.map(&:plugin_directory).each do |lib|
lib = Puppet::Util::Autoload.cleanpath(lib)
yield lib if File.directory?(lib)
end
end
# Locate a module instance by the module name alone.
#
# @api public
#
# @param name [String] The module name
# @return [Puppet::Module, nil] The module if found, else nil
def module(name)
modules_by_name[name]
end
# Locate a module instance by the full forge name (EG authorname/module)
#
# @api public
#
# @param forge_name [String] The module name
# @return [Puppet::Module, nil] The module if found, else nil
def module_by_forge_name(forge_name)
_, modname = forge_name.split('/')
found_mod = self.module(modname)
found_mod and found_mod.forge_name == forge_name ?
found_mod :
nil
end
# Return all modules for this environment in the order they appear in the
# modulepath.
# @note If multiple modules with the same name are present they will
# both be added, but methods like {#module} and {#module_by_forge_name}
# will return the first matching entry in this list.
# @note This value is cached so that the filesystem doesn't have to be
# re-enumerated every time this method is invoked, since that
# enumeration could be a costly operation and this method is called
# frequently. The cache expiry is determined by `Puppet[:filetimeout]`.
# @api public
# @return [Array<Puppet::Module>] All modules for this environment
def modules
if @modules.nil?
module_references = []
project = Puppet.lookup(:bolt_project) { nil }
seen_modules = if project && project.load_as_module?
module_references << project.to_h
{ project.name => true }
else
{}
end
modulepath.each do |path|
Puppet::FileSystem.children(path).map do |p|
Puppet::FileSystem.basename_string(p)
end.each do |name|
next unless Puppet::Module.is_module_directory?(name, path)
warn_about_mistaken_path(path, name)
unless seen_modules[name]
module_references << { :name => name, :path => File.join(path, name) }
seen_modules[name] = true
end
end
end
@modules = module_references.filter_map do |reference|
Puppet::Module.new(reference[:name], reference[:path], self)
rescue Puppet::Module::Error => e
Puppet.log_exception(e)
nil
end
end
@modules
end
# @api private
def modules_by_name
@modules_by_name ||= modules.to_h { |mod| [mod.name, mod] }
end
private :modules_by_name
# Generate a warning if the given directory in a module path entry is named `lib`.
#
# @api private
#
# @param path [String] The module directory containing the given directory
# @param name [String] The directory name
def warn_about_mistaken_path(path, name)
if name == "lib"
Puppet.debug {
"Warning: Found directory named 'lib' in module path ('#{path}/lib'); unless you \
are expecting to load a module named 'lib', your module path may be set incorrectly."
}
end
end
# Modules broken out by directory in the modulepath
#
# @api public
#
# @return [Hash<String, Array<Puppet::Module>>] A hash whose keys are file
# paths, and whose values is an array of Puppet Modules for that path
def modules_by_path
modules_by_path = {}
modulepath.each do |path|
if Puppet::FileSystem.exist?(path)
module_names = Puppet::FileSystem.children(path).map do |p|
Puppet::FileSystem.basename_string(p)
end.select do |name|
Puppet::Module.is_module_directory?(name, path)
end
modules_by_path[path] = module_names.sort.map do |name|
Puppet::Module.new(name, File.join(path, name), self)
end
else
modules_by_path[path] = []
end
end
modules_by_path
end
# All module requirements for all modules in the environment modulepath
#
# @api public
#
# @comment This has nothing to do with an environment. It seems like it was
# stuffed into the first convenient class that vaguely involved modules.
#
# @example
# environment.module_requirements
# # => {
# # 'username/amodule' => [
# # {
# # 'name' => 'username/moduledep',
# # 'version' => '1.2.3',
# # 'version_requirement' => '>= 1.0.0',
# # },
# # {
# # 'name' => 'username/anotherdep',
# # 'version' => '4.5.6',
# # 'version_requirement' => '>= 3.0.0',
# # }
# # ]
# # }
# #
#
# @return [Hash<String, Array<Hash<String, String>>>] See the method example
# for an explanation of the return value.
def module_requirements
deps = {}
modules.each do |mod|
next unless mod.forge_name
deps[mod.forge_name] ||= []
mod.dependencies and mod.dependencies.each do |mod_dep|
dep_name = mod_dep['name'].tr('-', '/')
(deps[dep_name] ||= []) << {
'name' => mod.forge_name,
'version' => mod.version,
'version_requirement' => mod_dep['version_requirement']
}
end
end
deps.each do |mod, mod_deps|
deps[mod] = mod_deps.sort_by { |d| d['name'] }
end
deps
end
# Loads module translations for the current environment once for
# the lifetime of the environment. Execute a block in the context
# of that translation domain.
def with_text_domain
return yield if Puppet[:disable_i18n]
if @text_domain.nil?
@text_domain = @name
Puppet::GettextConfig.reset_text_domain(@text_domain)
Puppet::ModuleTranslations.load_from_modulepath(modules)
else
Puppet::GettextConfig.use_text_domain(@text_domain)
end
yield
ensure
# Is a noop if disable_i18n is true
Puppet::GettextConfig.clear_text_domain
end
# Checks if a reparse is required (cache of files is stale).
#
def check_for_reparse
@lock.synchronize do
if Puppet[:code] != @parsed_code || @known_resource_types.parse_failed?
@parsed_code = nil
@known_resource_types = nil
end
end
end
# @return [String] The YAML interpretation of the object
# Return the name of the environment as a string interpretation of the object
def to_yaml
to_s.to_yaml
end
# @return [String] The stringified value of the `name` instance variable
# @api public
def to_s
name.to_s
end
# @api public
def inspect
%Q(<#{self.class}:#{object_id} @name="#{name}" @manifest="#{manifest}" @modulepath="#{full_modulepath.join(':')}" >)
end
# @return [Symbol] The `name` value, cast to a string, then cast to a symbol.
#
# @api public
#
# @note the `name` instance variable is a Symbol, but this casts the value
# to a String and then converts it back into a Symbol which will needlessly
# create an object that needs to be garbage collected
def to_sym
to_s.to_sym
end
def self.split_path(path_string)
path_string.split(File::PATH_SEPARATOR)
end
def ==(other)
true if other.is_a?(Puppet::Node::Environment) &&
name == other.name &&
full_modulepath == other.full_modulepath &&
manifest == other.manifest
end
alias eql? ==
def hash
[self.class, name, full_modulepath, manifest].hash
end
# not private so it can be called in tests
def self.extralibs
if ENV['PUPPETLIB']
split_path(ENV.fetch('PUPPETLIB', nil))
else
[]
end
end
# not private so it can be called in initialize
def self.expand_dirs(dirs)
dirs.collect do |dir|
Puppet::FileSystem.expand_path(dir)
end
end
private
# Reparse the manifests for the given environment
#
# There are two sources that can be used for the initial parse:
#
# 1. The value of `Puppet[:code]`: Puppet can take a string from
# its settings and parse that as a manifest. This is used by various
# Puppet applications to read in a manifest and pass it to the
# environment as a side effect. This is attempted first.
# 2. The contents of this environment's +manifest+ attribute: Puppet will
# try to load the environment manifest.
#
# @return [Puppet::Parser::AST::Hostclass] The AST hostclass object
# representing the 'main' hostclass
def perform_initial_import
parser = Puppet::Parser::ParserFactory.parser
@parsed_code = Puppet[:code]
if @parsed_code != ""
parser.string = @parsed_code
parser.parse
else
file = manifest
# if the manifest file is a reference to a directory, parse and combine
# all .pp files in that directory
if file == NO_MANIFEST
empty_parse_result
elsif File.directory?(file)
# JRuby does not properly perform Dir.glob operations with wildcards, (see PUP-11788 and https://github.com/jruby/jruby/issues/7836).
# We sort the results because Dir.glob order is inconsistent in Ruby < 3 (see PUP-10115).
parse_results = Puppet::FileSystem::PathPattern.absolute(File.join(file, '**/*')).glob.select { |globbed_file| globbed_file.end_with?('.pp') }.sort.map do |file_to_parse|
parser.file = file_to_parse
parser.parse
end
# Use a parser type specific merger to concatenate the results
Puppet::Parser::AST::Hostclass.new('', :code => Puppet::Parser::ParserFactory.code_merger.concatenate(parse_results))
else
parser.file = file
parser.parse
end
end
rescue Puppet::ParseErrorWithIssue => detail
@known_resource_types.parse_failed = true
detail.environment = name
raise
rescue => detail
@known_resource_types.parse_failed = true
msg = _("Could not parse for environment %{env}: %{detail}") % { env: self, detail: detail }
error = Puppet::Error.new(msg)
error.set_backtrace(detail.backtrace)
raise error
end
# Return an empty top-level hostclass to indicate that no file was loaded
#
# @return [Puppet::Parser::AST::Hostclass]
def empty_parse_result
Puppet::Parser::AST::Hostclass.new('')
end
# A None subclass to make it easier to trace the NONE environment when debugging.
# @api private
class None < Puppet::Node::Environment; end
# A special "null" environment
#
# This environment should be used when there is no specific environment in
# effect.
NONE = None.create(:none, [])
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/node/server_facts.rb | lib/puppet/node/server_facts.rb | # frozen_string_literal: true
class Puppet::Node::ServerFacts
def self.load
server_facts = {}
# Add implementation information
server_facts["serverimplementation"] = Puppet.implementation
# Add our server Puppet Enterprise version, if available.
pe_version_file = '/opt/puppetlabs/server/pe_version'
if File.readable?(pe_version_file) and !File.zero?(pe_version_file)
server_facts['pe_serverversion'] = File.read(pe_version_file).chomp
end
# Add our server version to the fact list
server_facts["serverversion"] = Puppet.version.to_s
# And then add the server name and IP
{ "servername" => "networking.fqdn",
"serverip" => "networking.ip",
"serverip6" => "networking.ip6" }.each do |var, fact|
value = Puppet.runtime[:facter].value(fact)
unless value.nil?
server_facts[var] = value
end
end
if server_facts["servername"].nil?
host = Puppet.runtime[:facter].value('networking.hostname')
if host.nil?
Puppet.warning _("Could not retrieve fact servername")
elsif domain = Puppet.runtime[:facter].value('networking.domain') # rubocop:disable Lint/AssignmentInCondition
server_facts["servername"] = [host, domain].join(".")
else
server_facts["servername"] = host
end
end
if server_facts["serverip"].nil? && server_facts["serverip6"].nil?
Puppet.warning _("Could not retrieve either serverip or serverip6 fact")
end
server_facts
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/node/facts.rb | lib/puppet/node/facts.rb | # frozen_string_literal: true
require 'time'
require_relative '../../puppet/node'
require_relative '../../puppet/indirector'
require_relative '../../puppet/util/psych_support'
# Manage a given node's facts. This either accepts facts and stores them, or
# returns facts for a given node.
class Puppet::Node::Facts
include Puppet::Util::PsychSupport
# Set up indirection, so that nodes can be looked for in
# the node sources.
extend Puppet::Indirector
# We want to expire any cached nodes if the facts are saved.
module NodeExpirer
def save(instance, key = nil, options = {})
Puppet::Node.indirection.expire(instance.name, options)
super
end
end
indirects :facts, :terminus_setting => :facts_terminus, :extend => NodeExpirer
attr_accessor :name, :values, :timestamp
def add_local_facts(query = [])
query = Array(query) # some use cases result in a nil being passed in
values["implementation"] = Puppet.implementation if query.empty? or query.include? 'implementation'
values["clientcert"] = Puppet.settings[:certname] if query.empty? or query.include? 'clientcert'
values["clientversion"] = Puppet.version.to_s if query.empty? or query.include? 'clientversion'
values["clientnoop"] = Puppet.settings[:noop] if query.empty? or query.include? 'clientnoop'
end
def initialize(name, values = {})
@name = name
@values = values
add_timestamp
end
def initialize_from_hash(data)
@name = data['name']
@values = data['values']
# Timestamp will be here in YAML, e.g. when reading old reports
timestamp = @values.delete('_timestamp')
# Timestamp will be here in JSON
timestamp ||= data['timestamp']
if timestamp.is_a? String
@timestamp = Time.parse(timestamp)
else
@timestamp = timestamp
end
self.expiration = data['expiration']
if expiration.is_a? String
self.expiration = Time.parse(expiration)
end
end
# Add extra values, such as facts given to lookup on the command line. The
# extra values will override existing values.
# @param extra_values [Hash{String=>Object}] the values to add
# @api private
def add_extra_values(extra_values)
@values.merge!(extra_values)
nil
end
# Sanitize fact values by converting everything not a string, Boolean
# numeric, array or hash into strings.
def sanitize
values.each do |fact, value|
values[fact] = sanitize_fact value
end
end
def ==(other)
return false unless name == other.name
values == other.values
end
def self.from_data_hash(data)
new_facts = allocate
new_facts.initialize_from_hash(data)
new_facts
end
def to_data_hash
result = {
'name' => name,
'values' => values
}
if @timestamp
if @timestamp.is_a? Time
result['timestamp'] = @timestamp.iso8601(9)
else
result['timestamp'] = @timestamp
end
end
if expiration
if expiration.is_a? Time
result['expiration'] = expiration.iso8601(9)
else
result['expiration'] = expiration
end
end
result
end
def add_timestamp
@timestamp = Time.now
end
def to_yaml
facts_to_display = Psych.parse_stream(YAML.dump(self))
quote_special_strings(facts_to_display)
end
private
def quote_special_strings(fact_hash)
fact_hash.grep(Psych::Nodes::Scalar).each do |node|
next unless node.value =~ /:/
node.plain = false
node.quoted = true
node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED
end
fact_hash.yaml
end
def sanitize_fact(fact)
case fact
when Hash
ret = {}
fact.each_pair { |k, v| ret[sanitize_fact k] = sanitize_fact v }
ret
when Array
fact.collect { |i| sanitize_fact i }
when Numeric, TrueClass, FalseClass, String
fact
else
result = fact.to_s
# The result may be ascii-8bit encoded without being a binary (low level object.inspect returns ascii-8bit string)
if result.encoding == Encoding::ASCII_8BIT
begin
result = result.encode(Encoding::UTF_8)
rescue
# return the ascii-8bit - it will be taken as a binary
result
end
end
result
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/transaction/report.rb | lib/puppet/transaction/report.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/indirector'
# This class is used to report what happens on a client.
# There are two types of data in a report; _Logs_ and _Metrics_.
#
# * **Logs** - are the output that each change produces.
# * **Metrics** - are all of the numerical data involved in the transaction.
#
# Use {Puppet::Reports} class to create a new custom report type. This class is indirectly used
# as a source of data to report in such a registered report.
#
# ##Metrics
# There are three types of metrics in each report, and each type of metric has one or more values.
#
# * Time: Keeps track of how long things took.
# * Total: Total time for the configuration run
# * File:
# * Exec:
# * User:
# * Group:
# * Config Retrieval: How long the configuration took to retrieve
# * Service:
# * Package:
# * Resources: Keeps track of the following stats:
# * Total: The total number of resources being managed
# * Skipped: How many resources were skipped, because of either tagging or scheduling restrictions
# * Scheduled: How many resources met any scheduling restrictions
# * Out of Sync: How many resources were out of sync
# * Applied: How many resources were attempted to be fixed
# * Failed: How many resources were not successfully fixed
# * Restarted: How many resources were restarted because their dependencies changed
# * Failed Restarts: How many resources could not be restarted
# * Changes: The total number of changes in the transaction.
#
# @api public
class Puppet::Transaction::Report
include Puppet::Util::PsychSupport
extend Puppet::Indirector
STATES_FOR_EXCLUSION_FROM_REPORT = [:failed, :failed_to_restart, :out_of_sync, :skipped].freeze
indirects :report, :terminus_class => :processor
# The version of the configuration
# @todo Uncertain what this is?
# @return [???] the configuration version
attr_accessor :configuration_version
# An agent generated transaction uuid, useful for connecting catalog and report
# @return [String] uuid
attr_accessor :transaction_uuid
# The id of the code input to the compiler.
attr_accessor :code_id
# The id of the job responsible for this run.
attr_accessor :job_id
# A master generated catalog uuid, useful for connecting a single catalog to multiple reports.
attr_accessor :catalog_uuid
# Whether a cached catalog was used in the run, and if so, the reason that it was used.
# @return [String] One of the values: 'not_used', 'explicitly_requested',
# or 'on_failure'
attr_accessor :cached_catalog_status
# Contains the name and port of the server that was successfully contacted
# @return [String] a string of the format 'servername:port'
attr_accessor :server_used
# The host name for which the report is generated
# @return [String] the host name
attr_accessor :host
# The name of the environment the host is in
# @return [String] the environment name
attr_accessor :environment
# The name of the environment the agent initially started in
# @return [String] the environment name
attr_accessor :initial_environment
# Whether there are changes that we decided not to apply because of noop
# @return [Boolean]
#
attr_accessor :noop_pending
# A hash with a map from resource to status
# @return [Hash{String => Puppet::Resource::Status}] Resource name to status.
attr_reader :resource_statuses
# A list of log messages.
# @return [Array<Puppet::Util::Log>] logged messages
attr_reader :logs
# A hash of metric name to metric value.
# @return [Hash<{String => Object}>] A map of metric name to value.
# @todo Uncertain if all values are numbers - now marked as Object.
#
attr_reader :metrics
# The time when the report data was generated.
# @return [Time] A time object indicating when the report data was generated
#
attr_reader :time
# The status of the client run is an enumeration: 'failed', 'changed' or 'unchanged'
# @return [String] the status of the run - one of the values 'failed', 'changed', or 'unchanged'
#
attr_reader :status
# @return [String] The Puppet version in String form.
# @see Puppet::version()
#
attr_reader :puppet_version
# @return [Integer] report format version number. This value is constant for
# a given version of Puppet; it is incremented when a new release of Puppet
# changes the API for the various objects that make up a report.
#
attr_reader :report_format
# Whether the puppet run was started in noop mode
# @return [Boolean]
#
attr_reader :noop
# @!attribute [r] corrective_change
# @return [Boolean] true if the report contains any events and resources that had
# corrective changes, including noop corrective changes.
attr_reader :corrective_change
# @return [Boolean] true if one or more resources attempted to generate
# resources and failed
#
attr_accessor :resources_failed_to_generate
# @return [Boolean] true if the transaction completed it's evaluate
#
attr_accessor :transaction_completed
TOTAL = "total"
def self.from_data_hash(data)
obj = allocate
obj.initialize_from_hash(data)
obj
end
def as_logging_destination(&block)
Puppet::Util::Log.with_destination(self, &block)
end
# @api private
def <<(msg)
@logs << msg
self
end
# @api private
def add_times(name, value, accumulate = true)
if @external_times[name] && accumulate
@external_times[name] += value
else
@external_times[name] = value
end
end
# @api private
def add_metric(name, hash)
metric = Puppet::Util::Metric.new(name)
hash.each do |metric_name, value|
metric.newvalue(metric_name, value)
end
@metrics[metric.name] = metric
metric
end
# @api private
def add_resource_status(status)
@resource_statuses[status.resource] = status
end
# @api private
def compute_status(resource_metrics, change_metric)
if resources_failed_to_generate ||
!transaction_completed ||
(resource_metrics["failed"] || 0) > 0 ||
(resource_metrics["failed_to_restart"] || 0) > 0
'failed'
elsif change_metric > 0
'changed'
else
'unchanged'
end
end
# @api private
def has_noop_events?(resource)
resource.events.any? { |event| event.status == 'noop' }
end
# @api private
def prune_internal_data
resource_statuses.delete_if { |_name, res| res.resource_type == 'Whit' }
end
# @api private
def finalize_report
prune_internal_data
calculate_report_corrective_change
resource_metrics = add_metric(:resources, calculate_resource_metrics)
add_metric(:time, calculate_time_metrics)
change_metric = calculate_change_metric
add_metric(:changes, { TOTAL => change_metric })
add_metric(:events, calculate_event_metrics)
@status = compute_status(resource_metrics, change_metric)
@noop_pending = @resource_statuses.any? { |_name, res| has_noop_events?(res) }
end
# @api private
def initialize(configuration_version = nil, environment = nil, transaction_uuid = nil, job_id = nil, start_time = Time.now)
@metrics = {}
@logs = []
@resource_statuses = {}
@external_times ||= {}
@host = Puppet[:node_name_value]
@time = start_time
@report_format = 12
@puppet_version = Puppet.version
@configuration_version = configuration_version
@transaction_uuid = transaction_uuid
@code_id = nil
@job_id = job_id
@catalog_uuid = nil
@cached_catalog_status = nil
@server_used = nil
@environment = environment
@status = 'failed' # assume failed until the report is finalized
@noop = Puppet[:noop]
@noop_pending = false
@corrective_change = false
@transaction_completed = false
end
# @api private
def initialize_from_hash(data)
@puppet_version = data['puppet_version']
@report_format = data['report_format']
@configuration_version = data['configuration_version']
@transaction_uuid = data['transaction_uuid']
@environment = data['environment']
@status = data['status']
@transaction_completed = data['transaction_completed']
@noop = data['noop']
@noop_pending = data['noop_pending']
@host = data['host']
@time = data['time']
@corrective_change = data['corrective_change']
if data['server_used']
@server_used = data['server_used']
elsif data['master_used']
@server_used = data['master_used']
end
if data['catalog_uuid']
@catalog_uuid = data['catalog_uuid']
end
if data['job_id']
@job_id = data['job_id']
end
if data['code_id']
@code_id = data['code_id']
end
if data['cached_catalog_status']
@cached_catalog_status = data['cached_catalog_status']
end
if @time.is_a? String
@time = Time.parse(@time)
end
@metrics = {}
data['metrics'].each do |name, hash|
# Older versions contain tags that causes Psych to create instances directly
@metrics[name] = hash.is_a?(Puppet::Util::Metric) ? hash : Puppet::Util::Metric.from_data_hash(hash)
end
@logs = data['logs'].map do |record|
# Older versions contain tags that causes Psych to create instances directly
record.is_a?(Puppet::Util::Log) ? record : Puppet::Util::Log.from_data_hash(record)
end
@resource_statuses = {}
data['resource_statuses'].map do |key, rs|
@resource_statuses[key] =
if rs == Puppet::Resource::EMPTY_HASH
nil
elsif rs.is_a?(Puppet::Resource::Status)
# Older versions contain tags that causes Psych to create instances
# directly
rs
else
Puppet::Resource::Status.from_data_hash(rs)
end
end
end
def resource_unchanged?(rs)
STATES_FOR_EXCLUSION_FROM_REPORT.each do |state|
return false if rs.send(state)
end
true
end
def calculate_resource_statuses
resource_statuses = if Puppet[:exclude_unchanged_resources]
@resource_statuses.reject { |_key, rs| resource_unchanged?(rs) }
else
@resource_statuses
end
resource_statuses.transform_values { |rs| rs.nil? ? nil : rs.to_data_hash }
end
def to_data_hash
hash = {
'host' => @host,
'time' => @time.iso8601(9),
'configuration_version' => @configuration_version,
'transaction_uuid' => @transaction_uuid,
'report_format' => @report_format,
'puppet_version' => @puppet_version,
'status' => @status,
'transaction_completed' => @transaction_completed,
'noop' => @noop,
'noop_pending' => @noop_pending,
'environment' => @environment,
'logs' => @logs.map(&:to_data_hash),
'metrics' => @metrics.transform_values(&:to_data_hash),
'resource_statuses' => calculate_resource_statuses,
'corrective_change' => @corrective_change,
}
# The following is include only when set
hash['server_used'] = @server_used unless @server_used.nil?
hash['catalog_uuid'] = @catalog_uuid unless @catalog_uuid.nil?
hash['code_id'] = @code_id unless @code_id.nil?
hash['job_id'] = @job_id unless @job_id.nil?
hash['cached_catalog_status'] = @cached_catalog_status unless @cached_catalog_status.nil?
hash
end
# @return [String] the host name
# @api public
#
def name
host
end
# Provide a human readable textual summary of this report.
# @note This is intended for debugging purposes
# @return [String] A string with a textual summary of this report.
# @api public
#
def summary
report = raw_summary
ret = ''.dup
report.keys.sort_by(&:to_s).each do |key|
ret += "#{Puppet::Util::Metric.labelize(key)}:\n"
report[key].keys.sort { |a, b|
# sort by label
if a == TOTAL
1
elsif b == TOTAL
-1
else
report[key][a].to_s <=> report[key][b].to_s
end
}.each do |label|
value = report[key][label]
next if value == 0
value = "%0.2f" % value if value.is_a?(Float)
ret += " %15s %s\n" % [Puppet::Util::Metric.labelize(label) + ":", value]
end
end
ret
end
# Provides a raw hash summary of this report.
# @return [Hash<{String => Object}>] A hash with metrics key to value map
# @api public
#
def raw_summary
report = {
"version" => {
"config" => configuration_version,
"puppet" => Puppet.version
},
"application" => {
"run_mode" => Puppet.run_mode.name.to_s,
"initial_environment" => initial_environment,
"converged_environment" => environment
}
}
@metrics.each do |_name, metric|
key = metric.name.to_s
report[key] = {}
metric.values.each do |metric_name, _label, value|
report[key][metric_name.to_s] = value
end
report[key][TOTAL] = 0 unless key == "time" or report[key].include?(TOTAL)
end
(report["time"] ||= {})["last_run"] = Time.now.tv_sec
report
end
# Computes a single number that represents the report's status.
# The computation is based on the contents of this report's metrics.
# The resulting number is a bitmask where
# individual bits represent the presence of different metrics.
#
# * 0x2 set if there are changes
# * 0x4 set if there are resource failures or resources that failed to restart
# @return [Integer] A bitmask where 0x2 is set if there are changes, and 0x4 is set of there are failures.
# @api public
#
def exit_status
status = 0
if @metrics["changes"] && @metrics["changes"][TOTAL] &&
@metrics["resources"] && @metrics["resources"]["failed"] &&
@metrics["resources"]["failed_to_restart"]
status |= 2 if @metrics["changes"][TOTAL] > 0
status |= 4 if @metrics["resources"]["failed"] > 0
status |= 4 if @metrics["resources"]["failed_to_restart"] > 0
else
status = -1
end
status
end
private
# Mark the report as corrective, if there are any resource_status marked corrective.
def calculate_report_corrective_change
@corrective_change = resource_statuses.any? do |_name, status|
status.corrective_change
end
end
def calculate_change_metric
resource_statuses.map { |_name, status| status.change_count || 0 }.inject(0) { |a, b| a + b }
end
def calculate_event_metrics
metrics = Hash.new(0)
%w[total failure success].each { |m| metrics[m] = 0 }
resource_statuses.each do |_name, status|
metrics[TOTAL] += status.events.length
status.events.each do |event|
metrics[event.status] += 1
end
end
metrics
end
def calculate_resource_metrics
metrics = {}
metrics[TOTAL] = resource_statuses.length
# force every resource key in the report to be present
# even if no resources is in this given state
Puppet::Resource::Status::STATES.each do |state|
metrics[state.to_s] = 0
end
resource_statuses.each do |_name, status|
Puppet::Resource::Status::STATES.each do |state|
metrics[state.to_s] += 1 if status.send(state)
end
end
metrics
end
def calculate_time_metrics
metrics = Hash.new(0)
resource_statuses.each do |_name, status|
metrics[status.resource_type.downcase] += status.evaluation_time if status.evaluation_time
end
@external_times.each do |name, value|
metrics[name.to_s.downcase] = value
end
metrics
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/transaction/persistence.rb | lib/puppet/transaction/persistence.rb | # frozen_string_literal: true
require 'yaml'
require_relative '../../puppet/util/yaml'
# A persistence store implementation for storing information between
# transaction runs for the purposes of information inference (such
# as calculating corrective_change).
# @api private
class Puppet::Transaction::Persistence
def self.allowed_classes
@allowed_classes ||= [
Symbol,
Time,
Regexp,
# URI is excluded, because it serializes all instance variables including the
# URI parser. Better to serialize the URL encoded representation.
SemanticPuppet::Version,
# SemanticPuppet::VersionRange has many nested classes and is unlikely to be
# used directly, so ignore it
Puppet::Pops::Time::Timestamp,
Puppet::Pops::Time::TimeData,
Puppet::Pops::Time::Timespan,
Puppet::Pops::Types::PBinaryType::Binary
# Puppet::Pops::Types::PSensitiveType::Sensitive values are excluded from
# the persistence store, ignore it.
].freeze
end
def initialize
@old_data = {}
@new_data = { "resources" => {} }
end
# Obtain the full raw data from the persistence store.
# @return [Hash] hash of data stored in persistence store
def data
@old_data
end
# Retrieve the system value using the resource and parameter name
# @param [String] resource_name name of resource
# @param [String] param_name name of the parameter
# @return [Object,nil] the system_value
def get_system_value(resource_name, param_name)
if !@old_data["resources"].nil? &&
!@old_data["resources"][resource_name].nil? &&
!@old_data["resources"][resource_name]["parameters"].nil? &&
!@old_data["resources"][resource_name]["parameters"][param_name].nil?
@old_data["resources"][resource_name]["parameters"][param_name]["system_value"]
else
nil
end
end
def set_system_value(resource_name, param_name, value)
@new_data["resources"] ||= {}
@new_data["resources"][resource_name] ||= {}
@new_data["resources"][resource_name]["parameters"] ||= {}
@new_data["resources"][resource_name]["parameters"][param_name] ||= {}
@new_data["resources"][resource_name]["parameters"][param_name]["system_value"] = value
end
def copy_skipped(resource_name)
@old_data["resources"] ||= {}
old_value = @old_data["resources"][resource_name]
unless old_value.nil?
@new_data["resources"][resource_name] = old_value
end
end
# Load data from the persistence store on disk.
def load
filename = Puppet[:transactionstorefile]
unless Puppet::FileSystem.exist?(filename)
return
end
unless File.file?(filename)
Puppet.warning(_("Transaction store file %{filename} is not a file, ignoring") % { filename: filename })
return
end
result = nil
Puppet::Util.benchmark(:debug, _("Loaded transaction store file in %{seconds} seconds")) do
result = Puppet::Util::Yaml.safe_load_file(filename, self.class.allowed_classes)
rescue Puppet::Util::Yaml::YamlLoadError => detail
Puppet.log_exception(detail, _("Transaction store file %{filename} is corrupt (%{detail}); replacing") % { filename: filename, detail: detail })
begin
File.rename(filename, filename + ".bad")
rescue => detail
Puppet.log_exception(detail, _("Unable to rename corrupt transaction store file: %{detail}") % { detail: detail })
raise Puppet::Error, _("Could not rename corrupt transaction store file %{filename}; remove manually") % { filename: filename }, detail.backtrace
end
result = {}
end
unless result.is_a?(Hash)
Puppet.err _("Transaction store file %{filename} is valid YAML but not returning a hash. Check the file for corruption, or remove it before continuing.") % { filename: filename }
return
end
@old_data = result
end
# Save data from internal class to persistence store on disk.
def save
Puppet::Util::Yaml.dump(@new_data, Puppet[:transactionstorefile])
end
# Use the catalog and run_mode to determine if persistence should be enabled or not
# @param [Puppet::Resource::Catalog] catalog catalog being processed
# @return [boolean] true if persistence is enabled
def enabled?(catalog)
catalog.host_config? && Puppet.run_mode.name == :agent
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/transaction/event.rb | lib/puppet/transaction/event.rb | # frozen_string_literal: true
require_relative '../../puppet/transaction'
require_relative '../../puppet/util/tagging'
require_relative '../../puppet/util/logging'
require_relative '../../puppet/network/format_support'
# A simple struct for storing what happens on the system.
class Puppet::Transaction::Event
include Puppet::Util::Tagging
include Puppet::Util::Logging
include Puppet::Network::FormatSupport
ATTRIBUTES = [:name, :resource, :property, :previous_value, :desired_value, :historical_value, :status, :message, :file, :line, :source_description, :audited, :invalidate_refreshes, :redacted, :corrective_change]
attr_accessor(*ATTRIBUTES)
attr_accessor :time
attr_reader :default_log_level
EVENT_STATUSES = %w[noop success failure audit]
def self.from_data_hash(data)
obj = allocate
obj.initialize_from_hash(data)
obj
end
def initialize(audited: false,
corrective_change: false,
desired_value: nil,
file: nil,
historical_value: nil,
invalidate_refreshes: nil,
line: nil,
message: nil,
name: nil,
previous_value: nil,
property: nil,
redacted: false,
resource: nil,
source_description: nil,
status: nil,
tags: nil)
@audited = audited
@corrective_change = corrective_change
@desired_value = desired_value
@file = file
@historical_value = historical_value
@invalidate_refreshes = invalidate_refreshes
@line = line
@message = message
@name = name
@previous_value = previous_value
@redacted = redacted
@source_description = source_description
@tags = tags
self.property = property if property
self.resource = resource if resource
self.status = status if status
@time = Time.now
end
def eql?(event)
self.class == event.class && ATTRIBUTES.all? { |attr| send(attr).eql?(event.send(attr)) }
end
alias == eql?
def initialize_from_hash(data)
data = Puppet::Pops::Serialization::FromDataConverter.convert(data, {
:allow_unresolved => true,
:loader => Puppet::Pops::Loaders.static_loader
})
@audited = data['audited']
@property = data['property']
@previous_value = data['previous_value']
@desired_value = data['desired_value']
@historical_value = data['historical_value']
@message = data['message']
@name = data['name'].intern if data['name']
@status = data['status']
@time = data['time']
@time = Time.parse(@time) if @time.is_a? String
@redacted = data.fetch('redacted', false)
@corrective_change = data['corrective_change']
end
def to_data_hash
hash = {
'audited' => @audited,
'property' => @property,
'previous_value' => @previous_value,
'desired_value' => @desired_value,
'historical_value' => @historical_value,
'message' => @message,
'name' => @name.nil? ? nil : @name.to_s,
'status' => @status,
'time' => @time.iso8601(9),
'redacted' => @redacted,
'corrective_change' => @corrective_change,
}
# Use the stringifying converter since rich data is not possible downstream.
# (This will destroy some data type information, but this is expected).
Puppet::Pops::Serialization::ToStringifiedConverter.convert(hash, :message_prefix => 'Event')
end
def property=(prop)
@property_instance = prop
@property = prop.to_s
end
def resource=(res)
level = res[:loglevel] if res.respond_to?(:[])
if level
@default_log_level = level
end
@resource = res.to_s
end
def send_log
super(log_level, message)
end
def status=(value)
raise ArgumentError, _("Event status can only be %{statuses}") % { statuses: EVENT_STATUSES.join(', ') } unless EVENT_STATUSES.include?(value)
@status = value
end
def to_s
message
end
def inspect
%Q(#<#{self.class.name} @name="#{@name.inspect}" @message="#{@message.inspect}">)
end
# Calculate and set the corrective_change parameter, based on the old_system_value of the property.
# @param [Object] old_system_value system_value from last transaction
# @return [bool] true if this is a corrective_change
def calculate_corrective_change(old_system_value)
# Only idempotent properties, and cases where we have an old system_value
# are corrective_changes.
if @property_instance.idempotent? &&
!@property_instance.sensitive &&
!old_system_value.nil?
# If the values aren't insync, we have confirmed a corrective_change
insync = @property_instance.insync_values?(old_system_value, previous_value)
# Preserve the nil state, but flip true/false
@corrective_change = insync.nil? ? nil : !insync
else
@corrective_change = false
end
end
private
# If it's a failure, use 'err', else use either the resource's log level (if available)
# or 'notice'.
def log_level
status == "failure" ? :err : (@default_log_level || :notice)
end
# Used by the Logging module
def log_source
source_description || property || resource
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/transaction/additional_resource_generator.rb | lib/puppet/transaction/additional_resource_generator.rb | # frozen_string_literal: true
# Adds additional resources to the catalog and relationship graph that are
# generated by existing resources. There are two ways that a resource can
# generate additional resources, either through the #generate method or the
# #eval_generate method.
#
# @api private
class Puppet::Transaction::AdditionalResourceGenerator
attr_writer :relationship_graph
# [boolean] true if any resource has attempted and failed to generate resources
attr_reader :resources_failed_to_generate
def initialize(catalog, relationship_graph, prioritizer)
@catalog = catalog
@relationship_graph = relationship_graph
@prioritizer = prioritizer
@resources_failed_to_generate = false
end
def generate_additional_resources(resource)
return unless resource.respond_to?(:generate)
begin
generated = resource.generate
rescue => detail
@resources_failed_to_generate = true
resource.log_exception(detail, _("Failed to generate additional resources using 'generate': %{detail}") % { detail: detail })
end
return unless generated
generated = [generated] unless generated.is_a?(Array)
generated.collect! do |res|
@catalog.resource(res.ref) || res
end
unless resource.depthfirst?
# This is reversed because PUP-1963 changed how generated
# resources were added to the catalog. It exists for backwards
# compatibility only, and can probably be removed in Puppet 5
#
# Previously, resources were given sequential priorities in the
# relationship graph. Post-1963, resources are added to the
# catalog one by one adjacent to the parent resource. This
# causes an implicit reversal of their application order from
# the old code. The reverse makes it all work like it did.
generated.reverse!
end
generated.each do |res|
add_resource(res, resource)
add_generated_directed_dependency(resource, res)
generate_additional_resources(res)
end
end
def eval_generate(resource)
return false unless resource.respond_to?(:eval_generate)
raise Puppet::DevError, _("Depthfirst resources are not supported by eval_generate") if resource.depthfirst?
begin
generated = replace_duplicates_with_catalog_resources(resource.eval_generate)
return false if generated.empty?
rescue => detail
@resources_failed_to_generate = true
# TRANSLATORS eval_generate is a method name and should be left untranslated
resource.log_exception(detail, _("Failed to generate additional resources using 'eval_generate': %{detail}") % { detail: detail })
return false
end
add_resources(generated, resource)
made = generated.map(&:name).zip(generated).to_h
contain_generated_resources_in(resource, made)
connect_resources_to_ancestors(resource, made)
true
end
private
def replace_duplicates_with_catalog_resources(generated)
generated.collect do |generated_resource|
@catalog.resource(generated_resource.ref) || generated_resource
end
end
def contain_generated_resources_in(resource, made)
sentinel = Puppet::Type.type(:whit).new(:name => "completed_#{resource.title}", :catalog => resource.catalog)
# Tag the completed whit with all of the tags of the generating resource
# except the type name to allow event propogation to succeed beyond the whit
# "boundary" when filtering resources with tags. We include auto-generated
# tags such as the type name to support implicit filtering as well as
# explicit. Note that resource#tags returns a duplicate of the resource's
# tags.
sentinel.merge_tags_from(resource)
priority = @prioritizer.generate_priority_contained_in(resource, sentinel)
@relationship_graph.add_vertex(sentinel, priority)
redirect_edges_to_sentinel(resource, sentinel, made)
made.values.each do |res|
# This resource isn't 'completed' until each child has run
add_conditional_directed_dependency(res, sentinel, Puppet::Graph::RelationshipGraph::Default_label)
end
# This edge allows the resource's events to propagate, though it isn't
# strictly necessary for ordering purposes
add_conditional_directed_dependency(resource, sentinel, Puppet::Graph::RelationshipGraph::Default_label)
end
def redirect_edges_to_sentinel(resource, sentinel, made)
@relationship_graph.adjacent(resource, :direction => :out, :type => :edges).each do |e|
next if made[e.target.name]
@relationship_graph.add_relationship(sentinel, e.target, e.label)
@relationship_graph.remove_edge! e
end
end
def connect_resources_to_ancestors(resource, made)
made.values.each do |res|
# Depend on the nearest ancestor we generated, falling back to the
# resource if we have none
parent_name = res.ancestors.find { |a| made[a] and made[a] != res }
parent = made[parent_name] || resource
add_conditional_directed_dependency(parent, res)
end
end
def add_resources(generated, resource)
generated.each do |res|
priority = @prioritizer.generate_priority_contained_in(resource, res)
add_resource(res, resource, priority)
end
end
def add_resource(res, parent_resource, priority = nil)
if @catalog.resource(res.ref).nil?
res.merge_tags_from(parent_resource)
if parent_resource.depthfirst?
@catalog.add_resource_before(parent_resource, res)
else
@catalog.add_resource_after(parent_resource, res)
end
@catalog.add_edge(@catalog.container_of(parent_resource), res) if @catalog.container_of(parent_resource)
if @relationship_graph && priority
# If we have a relationship_graph we should add the resource
# to it (this is an eval_generate). If we don't, then the
# relationship_graph has not yet been created and we can skip
# adding it.
@relationship_graph.add_vertex(res, priority)
end
res.finish
end
end
# add correct edge for depth- or breadth- first traversal of
# generated resource. Skip generating the edge if there is already
# some sort of edge between the two resources.
def add_generated_directed_dependency(parent, child, label = nil)
if parent.depthfirst?
source = child
target = parent
else
source = parent
target = child
end
# For each potential relationship metaparam, check if parent or
# child references the other. If there are none, we should add our
# edge.
edge_exists = Puppet::Type.relationship_params.any? { |param|
param_sym = param.name.to_sym
if parent[param_sym]
parent_contains = parent[param_sym].any? { |res|
res.ref == child.ref
}
else
parent_contains = false
end
if child[param_sym]
child_contains = child[param_sym].any? { |res|
res.ref == parent.ref
}
else
child_contains = false
end
parent_contains || child_contains
}
unless edge_exists
# We *cannot* use target.to_resource here!
#
# For reasons that are beyond my (and, perhaps, human)
# comprehension, to_resource will call retrieve. This is
# problematic if a generated resource needs the system to be
# changed by a previous resource (think a file on a path
# controlled by a mount resource).
#
# Instead of using to_resource, we just construct a resource as
# if the arguments to the Type instance had been passed to a
# Resource instead.
resource = ::Puppet::Resource.new(target.class, target.title,
:parameters => target.original_parameters)
source[:before] ||= []
source[:before] << resource
end
end
# Copy an important relationships from the parent to the newly-generated
# child resource.
def add_conditional_directed_dependency(parent, child, label = nil)
@relationship_graph.add_vertex(child)
edge = parent.depthfirst? ? [child, parent] : [parent, child]
if @relationship_graph.edge?(*edge.reverse)
parent.debug "Skipping automatic relationship to #{child}"
else
@relationship_graph.add_relationship(edge[0], edge[1], label)
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/transaction/event_manager.rb | lib/puppet/transaction/event_manager.rb | # frozen_string_literal: true
require_relative '../../puppet/transaction'
# This class stores, routes, and responds to events generated while evaluating
# a transaction.
#
# @api private
class Puppet::Transaction::EventManager
# @!attribute [r] transaction
# @return [Puppet::Transaction] The transaction associated with this event manager.
attr_reader :transaction
# @!attribute [r] events
# @todo Determine if this instance variable is used for anything aside from testing.
# @return [Array<Puppet::Transaction::Events>] A list of events that can be
# handled by the target resource. Events that cannot be handled by the
# target resource will be discarded.
attr_reader :events
def initialize(transaction)
@transaction = transaction
@event_queues = {}
@events = []
end
def relationship_graph
transaction.relationship_graph
end
# Respond to any queued events for this resource.
def process_events(resource)
restarted = false
queued_events(resource) do |callback, events|
r = process_callback(resource, callback, events)
restarted ||= r
end
if restarted
queue_events(resource, [resource.event(:name => :restarted, :status => "success")])
transaction.resource_status(resource).restarted = true
end
end
# Queues events for other resources to respond to. All of these events have
# to be from the same resource.
#
# @param resource [Puppet::Type] The resource generating the given events
# @param events [Array<Puppet::Transaction::Event>] All events generated by this resource
# @return [void]
def queue_events(resource, events)
# @events += events
# Do some basic normalization so we're not doing so many
# graph queries for large sets of events.
events.each_with_object({}) do |event, collection|
collection[event.name] ||= []
collection[event.name] << event
end.collect do |_name, list|
# It doesn't matter which event we use - they all have the same source
# and name here.
event = list[0]
# Collect the targets of any subscriptions to those events. We pass
# the parent resource in so it will override the source in the events,
# since eval_generated children can't have direct relationships.
received = (event.name != :restarted)
relationship_graph.matching_edges(event, resource).each do |edge|
received ||= true unless edge.target.is_a?(Puppet::Type.type(:whit))
method = edge.callback
next unless method
next unless edge.target.respond_to?(method)
queue_events_for_resource(resource, edge.target, method, list)
end
@events << event if received
queue_events_for_resource(resource, resource, :refresh, [event]) if resource.self_refresh? and !resource.deleting?
end
dequeue_events_for_resource(resource, :refresh) if events.detect(&:invalidate_refreshes)
end
def dequeue_all_events_for_resource(target)
callbacks = @event_queues[target]
if callbacks && !callbacks.empty?
target.info _("Unscheduling all events on %{target}") % { target: target }
@event_queues[target] = {}
end
end
def dequeue_events_for_resource(target, callback)
target.info _("Unscheduling %{callback} on %{target}") % { callback: callback, target: target }
@event_queues[target][callback] = [] if @event_queues[target]
end
def queue_events_for_resource(source, target, callback, events)
whit = Puppet::Type.type(:whit)
# The message that a resource is refreshing the completed-whit for its own class
# is extremely counter-intuitive. Basically everything else is easy to understand,
# if you suppress the whit-lookingness of the whit resources
refreshing_c_whit = target.is_a?(whit) && target.name =~ /^completed_/
if refreshing_c_whit
source.debug "The container #{target} will propagate my #{callback} event"
else
source.info _("Scheduling %{callback} of %{target}") % { callback: callback, target: target }
end
@event_queues[target] ||= {}
@event_queues[target][callback] ||= []
@event_queues[target][callback].concat(events)
end
def queued_events(resource)
callbacks = @event_queues[resource]
return unless callbacks
callbacks.each do |callback, events|
yield callback, events unless events.empty?
end
end
private
# Should the callback for this resource be invoked?
# @param resource [Puppet::Type] The resource to be refreshed
# @param events [Array<Puppet::Transaction::Event>] A list of events
# associated with this callback and resource.
# @return [true, false] Whether the callback should be run.
def process_callback?(resource, events)
!(events.all? { |e| e.status == "noop" } || resource.noop?)
end
# Processes callbacks for a given resource.
#
# @param resource [Puppet::Type] The resource receiving the callback.
# @param callback [Symbol] The name of the callback method that will be invoked.
# @param events [Array<Puppet::Transaction::Event>] A list of events
# associated with this callback and resource.
# @return [true, false] Whether the callback was successfully run.
def process_callback(resource, callback, events)
unless process_callback?(resource, events)
process_noop_events(resource, callback, events)
return false
end
resource.send(callback)
unless resource.is_a?(Puppet::Type.type(:whit))
message = n_("Triggered '%{callback}' from %{count} event", "Triggered '%{callback}' from %{count} events", events.length) % { count: events.length, callback: callback }
resource.notice message
add_callback_status_event(resource, callback, message, "success")
end
true
rescue => detail
resource_error_message = _("Failed to call %{callback}: %{detail}") % { callback: callback, detail: detail }
resource.err(resource_error_message)
transaction.resource_status(resource).failed_to_restart = true
transaction.resource_status(resource).fail_with_event(resource_error_message)
resource.log_exception(detail)
false
end
def add_callback_status_event(resource, callback, message, status)
options = { message: message, status: status, name: callback.to_s }
event = resource.event options
transaction.resource_status(resource) << event if event
end
def process_noop_events(resource, callback, events)
resource.notice n_("Would have triggered '%{callback}' from %{count} event", "Would have triggered '%{callback}' from %{count} events", events.length) % { count: events.length, callback: callback }
# And then add an event for it.
queue_events(resource, [resource.event(:status => "noop", :name => :noop_restart)])
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/transaction/resource_harness.rb | lib/puppet/transaction/resource_harness.rb | # frozen_string_literal: true
require_relative '../../puppet/resource/status'
class Puppet::Transaction::ResourceHarness
NO_ACTION = Object.new
extend Forwardable
def_delegators :@transaction, :relationship_graph
attr_reader :transaction
def initialize(transaction)
@transaction = transaction
@persistence = transaction.persistence
end
def evaluate(resource)
status = Puppet::Resource::Status.new(resource)
begin
context = ResourceApplicationContext.from_resource(resource, status)
perform_changes(resource, context)
if status.changed? && !resource.noop?
cache(resource, :synced, Time.now)
resource.flush if resource.respond_to?(:flush)
end
rescue => detail
status.failed_because(detail)
ensure
status.evaluation_time = Time.now - status.time
end
status
end
def scheduled?(resource)
return true if Puppet[:ignoreschedules]
schedule = schedule(resource)
return true unless schedule
# We use 'checked' here instead of 'synced' because otherwise we'll
# end up checking most resources most times, because they will generally
# have been synced a long time ago (e.g., a file only gets updated
# once a month on the server and its schedule is daily; the last sync time
# will have been a month ago, so we'd end up checking every run).
schedule.match?(cached(resource, :checked).to_i)
end
def schedule(resource)
unless resource.catalog
resource.warning _("Cannot schedule without a schedule-containing catalog")
return nil
end
name = resource[:schedule]
return nil unless name
resource.catalog.resource(:schedule, name) || resource.fail(_("Could not find schedule %{name}") % { name: name })
end
# Used mostly for scheduling and auditing at this point.
def cached(resource, name)
Puppet::Util::Storage.cache(resource)[name]
end
# Used mostly for scheduling and auditing at this point.
def cache(resource, name, value)
Puppet::Util::Storage.cache(resource)[name] = value
end
private
def perform_changes(resource, context)
cache(resource, :checked, Time.now)
# Record the current state in state.yml.
context.audited_params.each do |param|
cache(resource, param, context.current_values[param])
end
ensure_param = resource.parameter(:ensure)
if ensure_param && ensure_param.should
ensure_event = sync_if_needed(ensure_param, context)
else
ensure_event = NO_ACTION
end
if ensure_event == NO_ACTION
if context.resource_present?
resource.properties.each do |param|
sync_if_needed(param, context)
end
else
resource.debug("Nothing to manage: no ensure and the resource doesn't exist")
end
end
capture_audit_events(resource, context)
persist_system_values(resource, context)
end
# We persist the last known values for the properties of a resource after resource
# application.
# @param [Puppet::Type] resource resource whose values we are to persist.
# @param [ResourceApplicationContext] context the application context to operate on.
def persist_system_values(resource, context)
param_to_event = {}
context.status.events.each do |ev|
param_to_event[ev.property] = ev
end
context.system_value_params.each do |pname, param|
@persistence.set_system_value(resource.ref, pname.to_s,
new_system_value(param,
param_to_event[pname.to_s],
@persistence.get_system_value(resource.ref, pname.to_s)))
end
end
def sync_if_needed(param, context)
historical_value = context.historical_values[param.name]
current_value = context.current_values[param.name]
do_audit = context.audited_params.include?(param.name)
begin
if param.should && !param.safe_insync?(current_value)
event = create_change_event(param, current_value, historical_value)
if do_audit
event = audit_event(event, param, context)
end
brief_audit_message = audit_message(param, do_audit, historical_value, current_value)
if param.noop
noop(event, param, current_value, brief_audit_message)
else
sync(event, param, current_value, brief_audit_message)
end
event
else
NO_ACTION
end
rescue => detail
# Execution will continue on StandardErrors, just store the event
Puppet.log_exception(detail)
event = create_change_event(param, current_value, historical_value)
event.status = "failure"
event.message = param.format(_("change from %s to %s failed: "),
param.is_to_s(current_value),
param.should_to_s(param.should)) + detail.to_s
event
rescue Exception => detail
# Execution will halt on Exceptions, they get raised to the application
event = create_change_event(param, current_value, historical_value)
event.status = "failure"
event.message = param.format(_("change from %s to %s failed: "),
param.is_to_s(current_value),
param.should_to_s(param.should)) + detail.to_s
raise
ensure
if event
name = param.name.to_s
event.message ||= _("could not create change error message for %{name}") % { name: name }
event.calculate_corrective_change(@persistence.get_system_value(context.resource.ref, name))
event.message << ' (corrective)' if event.corrective_change
context.record(event)
event.send_log
context.synced_params << param.name
end
end
end
def create_change_event(property, current_value, historical_value)
options = {}
should = property.should
if property.sensitive
options[:previous_value] = current_value.nil? ? nil : '[redacted]'
options[:desired_value] = should.nil? ? nil : '[redacted]'
options[:historical_value] = historical_value.nil? ? nil : '[redacted]'
else
options[:previous_value] = current_value
options[:desired_value] = should
options[:historical_value] = historical_value
end
property.event(options)
end
# This method is an ugly hack because, given a Time object with nanosecond
# resolution, roundtripped through YAML serialization, the Time object will
# be truncated to microseconds.
# For audit purposes, this code special cases this comparison, and compares
# the two objects by their second and microsecond components. tv_sec is the
# number of seconds since the epoch, and tv_usec is only the microsecond
# portion of time.
def are_audited_values_equal(a, b)
a == b || (a.is_a?(Time) && b.is_a?(Time) && a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec)
end
private :are_audited_values_equal
# Populate an existing event with audit information.
#
# @param event [Puppet::Transaction::Event] The event to be populated.
# @param property [Puppet::Property] The property being audited.
# @param context [ResourceApplicationContext]
#
# @return [Puppet::Transaction::Event] The given event, populated with the audit information.
def audit_event(event, property, context)
event.audited = true
event.status = "audit"
# The event we've been provided might have been redacted so we need to use the state stored within
# the resource application context to see if an event was actually generated.
unless are_audited_values_equal(context.historical_values[property.name], context.current_values[property.name])
event.message = property.format(_("audit change: previously recorded value %s has been changed to %s"),
property.is_to_s(event.historical_value),
property.is_to_s(event.previous_value))
end
event
end
def audit_message(param, do_audit, historical_value, current_value)
if do_audit && historical_value && !are_audited_values_equal(historical_value, current_value)
param.format(_(" (previously recorded value was %s)"), param.is_to_s(historical_value))
else
""
end
end
def noop(event, param, current_value, audit_message)
if param.sensitive
event.message = param.format(_("current_value %s, should be %s (noop)"),
param.is_to_s(current_value),
param.should_to_s(param.should)) + audit_message.to_s
else
event.message = "#{param.change_to_s(current_value, param.should)} (noop)#{audit_message}"
end
event.status = "noop"
end
def sync(event, param, current_value, audit_message)
param.sync
if param.sensitive
event.message = param.format(_("changed %s to %s"),
param.is_to_s(current_value),
param.should_to_s(param.should)) + audit_message.to_s
else
event.message = "#{param.change_to_s(current_value, param.should)}#{audit_message}"
end
event.status = "success"
end
def capture_audit_events(resource, context)
context.audited_params.each do |param_name|
if context.historical_values.include?(param_name)
if !are_audited_values_equal(context.historical_values[param_name], context.current_values[param_name]) && !context.synced_params.include?(param_name)
parameter = resource.parameter(param_name)
event = audit_event(create_change_event(parameter,
context.current_values[param_name],
context.historical_values[param_name]),
parameter, context)
event.send_log
context.record(event)
end
else
property = resource.property(param_name)
property.notice(property.format(_("audit change: newly-recorded value %s"), context.current_values[param_name]))
end
end
end
# Given an event and its property, calculate the system_value to persist
# for future calculations.
# @param [Puppet::Transaction::Event] event event to use for processing
# @param [Puppet::Property] property correlating property
# @param [Object] old_system_value system_value from last transaction
# @return [Object] system_value to be used for next transaction
def new_system_value(property, event, old_system_value)
if event && event.status != "success"
# For non-success events, we persist the old_system_value if it is defined,
# or use the event previous_value.
# If we're using the event previous_value, we ensure that it's
# an array. This is needed because properties assume that their
# `should` value is an array, and we will use this value later
# on in property insync? logic.
event_value = [event.previous_value] unless event.previous_value.is_a?(Array)
old_system_value.nil? ? event_value : old_system_value
else
# For non events, or for success cases, we just want to store
# the parameters agent value.
# We use instance_variable_get here because we want this process to bypass any
# munging/unmunging or validation that the property might try to do, since those
# operations may not be correctly implemented for custom types.
property.instance_variable_get(:@should)
end
end
# @api private
ResourceApplicationContext = Struct.new(:resource,
:current_values,
:historical_values,
:audited_params,
:synced_params,
:status,
:system_value_params) do
def self.from_resource(resource, status)
ResourceApplicationContext.new(resource,
resource.retrieve_resource.to_hash,
Puppet::Util::Storage.cache(resource).dup,
(resource[:audit] || []).map(&:to_sym),
[],
status,
resource.parameters.select { |_n, p| p.is_a?(Puppet::Property) && !p.sensitive })
end
def resource_present?
resource.present?(current_values)
end
def record(event)
status << event
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/interface/action_manager.rb | lib/puppet/interface/action_manager.rb | # frozen_string_literal: true
# This class is not actually public API, but the method
# {Puppet::Interface::ActionManager#action action} is public when used
# as part of the Faces DSL (i.e. from within a
# {Puppet::Interface.define define} block).
# @api public
module Puppet::Interface::ActionManager
# Declare that this app can take a specific action, and provide
# the code to do so.
# Defines a new action. This takes a block to build the action using
# the methods on {Puppet::Interface::ActionBuilder}.
# @param name [Symbol] The name that will be used to invoke the
# action
# @overload action(name, { block })
# @return [void]
# @api public
# @dsl Faces
def action(name, &block)
@actions ||= {}
Puppet.debug _("Redefining action %{name} for %{self}") % { name: name, self: self } if action?(name)
action = Puppet::Interface::ActionBuilder.build(self, name, &block)
# REVISIT: (#18042) doesn't this mean we can't redefine the default action? -- josh
current = get_default_action if action.default
if current
raise "Actions #{current.name} and #{name} cannot both be default"
end
@actions[action.name] = action
end
# Returns the list of available actions for this face.
# @return [Array<Symbol>] The names of the actions for this face
# @api private
def actions
@actions ||= {}
result = @actions.keys
if is_a?(Class) and superclass.respond_to?(:actions)
result += superclass.actions
elsif self.class.respond_to?(:actions)
result += self.class.actions
end
# We need to uniq the result, because we duplicate actions when they are
# fetched to ensure that they have the correct bindings; they shadow the
# parent, and uniq implements that. --daniel 2011-06-01
(result - @deactivated_actions.to_a).uniq.sort
end
# Retrieves a named action
# @param name [Symbol] The name of the action
# @return [Puppet::Interface::Action] The action object
# @api private
def get_action(name)
@actions ||= {}
result = @actions[name.to_sym]
if result.nil?
if is_a?(Class) and superclass.respond_to?(:get_action)
found = superclass.get_action(name)
elsif self.class.respond_to?(:get_action)
found = self.class.get_action(name)
end
if found then
# This is not the nicest way to make action equivalent to the Ruby
# Method object, rather than UnboundMethod, but it will do for now,
# and we only have to make this change in *one* place. --daniel 2011-04-12
result = @actions[name.to_sym] = found.__dup_and_rebind_to(self)
end
end
result
end
# Retrieves the default action for the face
# @return [Puppet::Interface::Action]
# @api private
def get_default_action
default = actions.map { |x| get_action(x) }.select(&:default)
if default.length > 1
raise "The actions #{default.map(&:name).join(', ')} cannot all be default"
end
default.first
end
# Deactivate a named action
# @return [Puppet::Interface::Action]
# @api public
def deactivate_action(name)
@deactivated_actions ||= Set.new
@deactivated_actions.add name.to_sym
end
# @api private
def action?(name)
actions.include?(name.to_sym)
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/interface/option_builder.rb | lib/puppet/interface/option_builder.rb | # frozen_string_literal: true
# @api public
class Puppet::Interface::OptionBuilder
# The option under construction
# @return [Puppet::Interface::Option]
# @api private
attr_reader :option
# Build an option
# @return [Puppet::Interface::Option]
# @api private
def self.build(face, *declaration, &block)
new(face, *declaration, &block).option
end
def initialize(face, *declaration, &block)
@face = face
@option = Puppet::Interface::Option.new(face, *declaration)
instance_eval(&block) if block_given?
end
# Metaprogram the simple DSL from the option class.
Puppet::Interface::Option.instance_methods.grep(/=$/).each do |setter|
next if setter =~ /^=/
dsl = setter.to_s.chomp('=')
unless private_method_defined? dsl
define_method(dsl) do |value| @option.send(setter, value) end
end
end
# Override some methods that deal in blocks, not objects.
# Sets a block to be executed when an action is invoked before the
# main action code. This is most commonly used to validate an option.
# @yieldparam action [Puppet::Interface::Action] The action being
# invoked
# @yieldparam args [Array] The arguments given to the action
# @yieldparam options [Hash<Symbol=>Object>] Any options set
# @api public
# @dsl Faces
def before_action(&block)
unless block
# TRANSLATORS 'before_action' is a method name and should not be translated
raise ArgumentError, _("%{option} before_action requires a block") % { option: @option }
end
if @option.before_action
# TRANSLATORS 'before_action' is a method name and should not be translated
raise ArgumentError, _("%{option} already has a before_action set") % { option: @option }
end
unless block.arity == 3 then
# TRANSLATORS 'before_action' is a method name and should not be translated
raise ArgumentError, _("before_action takes three arguments, action, args, and options")
end
@option.before_action = block
end
# Sets a block to be executed after an action is invoked.
# !(see before_action)
# @api public
# @dsl Faces
def after_action(&block)
unless block
# TRANSLATORS 'after_action' is a method name and should not be translated
raise ArgumentError, _("%{option} after_action requires a block") % { option: @option }
end
if @option.after_action
# TRANSLATORS 'after_action' is a method name and should not be translated
raise ArgumentError, _("%{option} already has an after_action set") % { option: @option }
end
unless block.arity == 3 then
# TRANSLATORS 'after_action' is a method name and should not be translated
raise ArgumentError, _("after_action takes three arguments, action, args, and options")
end
@option.after_action = block
end
# Sets whether the option is required. If no argument is given it
# defaults to setting it as a required option.
# @api public
# @dsl Faces
def required(value = true)
@option.required = value
end
# Sets a block that will be used to compute the default value for this
# option. It will be evaluated when the action is invoked. The block
# should take no arguments.
# @api public
# @dsl Faces
def default_to(&block)
unless block
# TRANSLATORS 'default_to' is a method name and should not be translated
raise ArgumentError, _("%{option} default_to requires a block") % { option: @option }
end
if @option.has_default?
raise ArgumentError, _("%{option} already has a default value") % { option: @option }
end
unless block.arity == 0
# TRANSLATORS 'default_to' is a method name and should not be translated
raise ArgumentError, _("%{option} default_to block should not take any arguments") % { option: @option }
end
@option.default = block
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/interface/face_collection.rb | lib/puppet/interface/face_collection.rb | # frozen_string_literal: true
module Puppet::Interface::FaceCollection
@faces = Hash.new { |hash, key| hash[key] = {} }
@loader = Puppet::Util::Autoload.new(:application, 'puppet/face')
def self.faces
unless @loaded
@loaded = true
names = @loader.files_to_load(Puppet.lookup(:current_environment)).map do |fn|
::File.basename(fn, '.rb')
end.uniq
names.each { |name| self[name, :current] }
end
@faces.keys.select { |name| @faces[name].length > 0 }
end
def self.[](name, version)
name = underscorize(name)
get_face(name, version) or load_face(name, version)
end
def self.get_action_for_face(name, action_name, version)
name = underscorize(name)
# If the version they request specifically doesn't exist, don't search
# elsewhere. Usually this will start from :current and all...
face = self[name, version]
return nil unless face
action = face.get_action(action_name)
unless action
# ...we need to search for it bound to an o{lder,ther} version. Since
# we load all actions when the face is first references, this will be in
# memory in the known set of versions of the face.
(@faces[name].keys - [:current]).sort.reverse_each do |vers|
action = @faces[name][vers].get_action(action_name)
break if action
end
end
action
end
# get face from memory, without loading.
def self.get_face(name, pattern)
return nil unless @faces.has_key? name
return @faces[name][:current] if pattern == :current
versions = @faces[name].keys - [:current]
range = pattern.is_a?(SemanticPuppet::Version) ? SemanticPuppet::VersionRange.new(pattern, pattern) : SemanticPuppet::VersionRange.parse(pattern)
found = find_matching(range, versions)
@faces[name][found]
end
def self.find_matching(range, versions)
versions.select { |v| range === v }.max
end
# try to load the face, and return it.
def self.load_face(name, version)
# We always load the current version file; the common case is that we have
# the expected version and any compatibility versions in the same file,
# the default. Which means that this is almost always the case.
#
# We use require to avoid executing the code multiple times, like any
# other Ruby library that we might want to use. --daniel 2011-04-06
if safely_require name then
# If we wanted :current, we need to index to find that; direct version
# requests just work as they go. --daniel 2011-04-06
if version == :current then
# We need to find current out of this. This is the largest version
# number that doesn't have a dedicated on-disk file present; those
# represent "experimental" versions of faces, which we don't fully
# support yet.
#
# We walk the versions from highest to lowest and take the first version
# that is not defined in an explicitly versioned file on disk as the
# current version.
#
# This constrains us to only ship experimental versions with *one*
# version in the file, not multiple, but given you can't reliably load
# them except by side-effect when you ignore that rule this seems safe
# enough...
#
# Given those constraints, and that we are not going to ship a versioned
# interface that is not :current in this release, we are going to leave
# these thoughts in place, and just punt on the actual versioning.
#
# When we upgrade the core to support multiple versions we can solve the
# problems then; as lazy as possible.
#
# We do support multiple versions in the same file, though, so we sort
# versions here and return the last item in that set.
#
# --daniel 2011-04-06
latest_ver = @faces[name].keys.max
@faces[name][:current] = @faces[name][latest_ver]
end
end
unless version == :current or get_face(name, version)
# Try an obsolete version of the face, if needed, to see if that helps?
safely_require name, version
end
get_face(name, version)
end
def self.safely_require(name, version = nil)
path = @loader.expand(version ? ::File.join(version.to_s, name.to_s) : name)
require path
true
rescue LoadError => e
raise unless e.message =~ /-- #{path}$/
# ...guess we didn't find the file; return a much better problem.
nil
rescue SyntaxError => e
raise unless e.message =~ /#{path}\.rb:\d+: /
Puppet.err _("Failed to load face %{name}:\n%{detail}") % { name: name, detail: e }
# ...but we just carry on after complaining.
nil
end
def self.register(face)
@faces[underscorize(face.name)][face.version] = face
end
def self.underscorize(name)
unless name.to_s =~ /^[-_a-z][-_a-z0-9]*$/i then
# TRANSLATORS 'face' refers to a programming API in Puppet
raise ArgumentError, _("%{name} (%{class_name}) is not a valid face name") %
{ name: name.inspect, class_name: name.class }
end
name.to_s.downcase.split(/[-_]/).join('_').to_sym
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/interface/documentation.rb | lib/puppet/interface/documentation.rb | # frozen_string_literal: true
class Puppet::Interface
# @api private
module DocGen
require_relative '../../puppet/util/docs'
# @api private
def self.strip_whitespace(text)
# I don't want no...
Puppet::Util::Docs.scrub(text)
end
# The documentation attributes all have some common behaviours; previously
# we open-coded them across the set of six things, but that seemed
# wasteful - especially given that they were literally the same, and had
# the same bug hidden in them.
#
# This feels a bit like overkill, but at least the common code is common
# now. --daniel 2011-04-29
# @api private
def attr_doc(name, &validate)
# Now, which form of the setter do we want, validated or not?
get_arg = "value.to_s"
if validate
define_method(:"_validate_#{name}", validate)
get_arg = "_validate_#{name}(#{get_arg})"
end
# We use module_eval, which I don't like much, because we can't have an
# argument to a block with a default value in Ruby 1.8, and I don't like
# the side-effects (eg: no argument count validation) of using blocks
# without as methods. When we are 1.9 only (hah!) you can totally
# replace this with some up-and-up define_method. --daniel 2011-04-29
module_eval(<<-EOT, __FILE__, __LINE__ + 1)
def #{name}(value = nil) # def attribute(value=nil)
self.#{name} = value unless value.nil? # self.attribute = value unless value.nil?
@#{name} # @value
end # end
def #{name}=(value) # def attribute=(value)
@#{name} = Puppet::Interface::DocGen.strip_whitespace(#{get_arg}) # @value = Puppet::Interface::DocGen.strip_whitespace(#{get_arg})
end # end
EOT
end
end
# This module can be mixed in to provide a minimal set of
# documentation attributes.
# @api public
module TinyDocs
extend Puppet::Interface::DocGen
# @!method summary(summary)
# Sets a summary of this object.
# @api public
# @dsl Faces
attr_doc :summary do |value|
value =~ /\n/ and
# TRANSLATORS 'Face' refers to a programming API in Puppet, 'summary' and 'description' are specifc attribute names and should not be translated
raise ArgumentError, _("Face summary should be a single line; put the long text in 'description' instead.")
value
end
# @!method description(description)
# Sets the long description of this object.
# @param description [String] The description of this object.
# @api public
# @dsl Faces
attr_doc :description
# @api private
def build_synopsis(face, action = nil, arguments = nil)
PrettyPrint.format do |s|
s.text("puppet #{face}")
s.text(" #{action}") unless action.nil?
s.text(" ")
options.each do |option|
option = get_option(option)
wrap = option.required? ? %w[< >] : %w{[ ]}
s.group(0, *wrap) do
option.optparse.each do |item|
unless s.current_group.first?
s.breakable
s.text '|'
s.breakable
end
s.text item
end
end
s.breakable
end
display_global_options.sort.each do |option|
wrap = %w{[ ]}
s.group(0, *wrap) do
type = Puppet.settings.setting(option).default
type ||= Puppet.settings.setting(option).type.to_s.upcase
s.text "--#{option} #{type}"
s.breakable
end
s.breakable
end
if arguments then
s.text arguments.to_s
end
end
end
end
# This module can be mixed in to provide a full set of documentation
# attributes. It is intended to be used for {Puppet::Interface}.
# @api public
module FullDocs
extend Puppet::Interface::DocGen
include TinyDocs
# @!method examples
# @overload examples(text)
# Sets examples.
# @param text [String] Example text
# @api public
# @return [void]
# @dsl Faces
# @overload examples
# Returns documentation of examples
# @return [String] The examples
# @api private
attr_doc :examples
# @!method notes(text)
# @overload notes(text)
# Sets optional notes.
# @param text [String] The notes
# @api public
# @return [void]
# @dsl Faces
# @overload notes
# Returns any optional notes
# @return [String] The notes
# @api private
attr_doc :notes
# @!method license(text)
# @overload license(text)
# Sets the license text
# @param text [String] the license text
# @api public
# @return [void]
# @dsl Faces
# @overload license
# Returns the license
# @return [String] The license
# @api private
attr_doc :license
attr_doc :short_description
# @overload short_description(value)
# Sets a short description for this object.
# @param value [String, nil] A short description (about a paragraph)
# of this component. If `value` is `nil` the short_description
# will be set to the shorter of the first paragraph or the first
# five lines of {description}.
# @return [void]
# @api public
# @dsl Faces
# @overload short_description
# Get the short description for this object
# @return [String, nil] The short description of this object. If none is
# set it will be derived from {description}. Returns `nil` if
# {description} is `nil`.
# @api private
def short_description(value = nil)
self.short_description = value unless value.nil?
if @short_description.nil? then
return nil if @description.nil?
lines = @description.split("\n")
first_paragraph_break = lines.index('') || 5
grab = [5, first_paragraph_break].min
@short_description = lines[0, grab].join("\n")
@short_description += ' [...]' if grab < lines.length and first_paragraph_break >= 5
end
@short_description
end
# @overload author(value)
# Adds an author to the documentation for this object. To set
# multiple authors, call this once for each author.
# @param value [String] the name of the author
# @api public
# @dsl Faces
# @overload author
# Returns a list of authors
# @return [String, nil] The names of all authors separated by
# newlines, or `nil` if no authors have been set.
# @api private
def author(value = nil)
unless value.nil? then
unless value.is_a? String
# TRANSLATORS 'author' is an attribute name and should not be translated
raise ArgumentError, _('author must be a string; use multiple statements for multiple authors')
end
if value =~ /\n/ then
# TRANSLATORS 'author' is an attribute name and should not be translated
raise ArgumentError, _('author should be a single line; use multiple statements for multiple authors')
end
@authors.push(Puppet::Interface::DocGen.strip_whitespace(value))
end
@authors.empty? ? nil : @authors.join("\n")
end
# Returns a list of authors. See {author}.
# @return [String] The list of authors, separated by newlines.
# @api private
def authors
@authors
end
# @api private
def author=(value)
# I think it's a bug that this ends up being the exposed
# version of `author` on ActionBuilder
if Array(value).any? { |x| x =~ /\n/ } then
# TRANSLATORS 'author' is an attribute name and should not be translated
raise ArgumentError, _('author should be a single line; use multiple statements')
end
@authors = Array(value).map { |x| Puppet::Interface::DocGen.strip_whitespace(x) }
end
alias :authors= :author=
# Sets the copyright owner and year. This returns the copyright
# string, so it can be called with no arguments retrieve that string
# without side effects.
# @param owner [String, Array<String>] The copyright owner or an
# array of owners
# @param years [Integer, Range<Integer>, Array<Integer,Range<Integer>>]
# The copyright year or years. Years can be specified with integers,
# a range of integers, or an array of integers and ranges of
# integers.
# @return [String] A string describing the copyright on this object.
# @api public
# @dsl Faces
def copyright(owner = nil, years = nil)
if years.nil? and !owner.nil? then
# TRANSLATORS 'copyright' is an attribute name and should not be translated
raise ArgumentError, _('copyright takes the owners names, then the years covered')
end
self.copyright_owner = owner unless owner.nil?
self.copyright_years = years unless years.nil?
if copyright_years or copyright_owner then
"Copyright #{copyright_years} by #{copyright_owner}"
else
"Unknown copyright owner and years."
end
end
# Sets the copyright owner
# @param value [String, Array<String>] The copyright owner or
# owners.
# @return [String] Comma-separated list of copyright owners
# @api private
attr_reader :copyright_owner
def copyright_owner=(value)
case value
when String then @copyright_owner = value
when Array then @copyright_owner = value.join(", ")
else
# TRANSLATORS 'copyright' is an attribute name and should not be translated
raise ArgumentError, _("copyright owner must be a string or an array of strings")
end
end
# Sets the copyright year
# @param value [Integer, Range<Integer>, Array<Integer, Range>] The
# copyright year or years.
# @return [String]
# @api private
attr_reader :copyright_years
def copyright_years=(value)
years = munge_copyright_year value
years = (years.is_a?(Array) ? years : [years])
.sort_by do |x| x.is_a?(Range) ? x.first : x end
@copyright_years = years.map do |year|
if year.is_a? Range then
"#{year.first}-#{year.last}"
else
year
end
end.join(", ")
end
# @api private
def munge_copyright_year(input)
case input
when Range then input
when Integer then
if input < 1970 then
fault = "before 1970"
elsif input > (future = Time.now.year + 2) then
fault = "after #{future}"
end
if fault then
# TRANSLATORS 'copyright' is an attribute name and should not be translated
raise ArgumentError, _("copyright with a year %{value} is very strange; did you accidentally add or subtract two years?") %
{ value: fault }
end
input
when String then
input.strip.split(/,/).map do |part|
part = part.strip
if part =~ /^\d+$/
part.to_i
else
found = part.split(/-/)
if found
unless found.length == 2 and found.all? { |x| x.strip =~ /^\d+$/ }
# TRANSLATORS 'copyright' is an attribute name and should not be translated
raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect }
end
Range.new(found[0].to_i, found[1].to_i)
else
# TRANSLATORS 'copyright' is an attribute name and should not be translated
raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect }
end
end
end
when Array then
result = []
input.each do |item|
item = munge_copyright_year item
if item.is_a? Array
result.concat item
else
result << item
end
end
result
else
# TRANSLATORS 'copyright' is an attribute name and should not be translated
raise ArgumentError, _("%{value} is not a good copyright year, set, or range") % { value: input.inspect }
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/interface/option.rb | lib/puppet/interface/option.rb | # frozen_string_literal: true
# This represents an option on an action or face (to be globally applied
# to its actions). Options should be constructed by calling
# {Puppet::Interface::OptionManager#option}, which is available on
# {Puppet::Interface}, and then calling methods of
# {Puppet::Interface::OptionBuilder} in the supplied block.
# @api public
class Puppet::Interface::Option
include Puppet::Interface::TinyDocs
# @api private
def initialize(parent, *declaration, &block)
@parent = parent
@optparse = []
@default = nil
# Collect and sort the arguments in the declaration.
dups = {}
declaration.each do |item|
if item.is_a? String and item.to_s =~ /^-/ then
unless item =~ /^-[a-z]\b/ or item =~ /^--[^-]/ then
raise ArgumentError, _("%{option}: long options need two dashes (--)") % { option: item.inspect }
end
@optparse << item
# Duplicate checking...
# for our duplicate checking purpose, we don't make a check with the
# translated '-' -> '_'. Right now, we do that on purpose because of
# a duplicated option made publicly available on certificate and ca
# faces for dns alt names. Puppet defines 'dns_alt_names', those
# faces include 'dns-alt-names'. We can't get rid of 'dns-alt-names'
# yet, so we need to do our duplicate checking on the untranslated
# version of the option.
# jeffweiss 17 april 2012
name = optparse_to_optionname(item)
if Puppet.settings.include? name then
raise ArgumentError, _("%{option}: already defined in puppet") % { option: item.inspect }
end
dup = dups[name]
if dup
raise ArgumentError, _("%{option}: duplicates existing alias %{duplicate} in %{parent}") %
{ option: item.inspect, duplicate: dup.inspect, parent: @parent }
else
dups[name] = item
end
else
raise ArgumentError, _("%{option} is not valid for an option argument") % { option: item.inspect }
end
end
if @optparse.empty? then
raise ArgumentError, _("No option declarations found while building")
end
# Now, infer the name from the options; we prefer the first long option as
# the name, rather than just the first option.
@name = optparse_to_name(@optparse.find do |a| a =~ /^--/ end || @optparse.first)
@aliases = @optparse.map { |o| optparse_to_name(o) }
# Do we take an argument? If so, are we consistent about it, because
# incoherence here makes our life super-difficult, and we can more easily
# relax this rule later if we find a valid use case for it. --daniel 2011-03-30
@argument = @optparse.any? { |o| o =~ /[ =]/ }
if @argument and !@optparse.all? { |o| o =~ /[ =]/ } then
raise ArgumentError, _("Option %{name} is inconsistent about taking an argument") % { name: @name }
end
# Is our argument optional? The rules about consistency apply here, also,
# just like they do to taking arguments at all. --daniel 2011-03-30
@optional_argument = @optparse.any? { |o| o =~ /[ =]\[/ }
if @optional_argument
raise ArgumentError, _("Options with optional arguments are not supported")
end
if @optional_argument and !@optparse.all? { |o| o =~ /[ =]\[/ } then
raise ArgumentError, _("Option %{name} is inconsistent about the argument being optional") % { name: @name }
end
end
# to_s and optparse_to_name are roughly mirrored, because they are used to
# transform options to name symbols, and vice-versa. This isn't a full
# bidirectional transformation though. --daniel 2011-04-07
def to_s
@name.to_s.tr('_', '-')
end
# @api private
def optparse_to_optionname(declaration)
found = declaration.match(/^-+(?:\[no-\])?([^ =]+)/)
unless found
raise ArgumentError, _("Can't find a name in the declaration %{declaration}") % { declaration: declaration.inspect }
end
found.captures.first
end
# @api private
def optparse_to_name(declaration)
name = optparse_to_optionname(declaration).tr('-', '_')
unless name.to_s =~ /^[a-z]\w*$/
raise _("%{name} is an invalid option name") % { name: name.inspect }
end
name.to_sym
end
def takes_argument?
!!@argument
end
def optional_argument?
!!@optional_argument
end
def required?
!!@required
end
def has_default?
!!@default
end
def default=(proc)
if required
raise ArgumentError, _("%{name} can't be optional and have a default value") % { name: self }
end
unless proc.is_a? Proc
# TRANSLATORS 'proc' is a Ruby block of code
raise ArgumentError, _("default value for %{name} is a %{class_name}, not a proc") %
{ name: self, class_name: proc.class.name.inspect }
end
@default = proc
end
def default
@default and @default.call
end
attr_reader :parent, :name, :aliases, :optparse, :required
def required=(value)
if has_default?
raise ArgumentError, _("%{name} can't be optional and have a default value") % { name: self }
end
@required = value
end
attr_reader :before_action
def before_action=(proc)
unless proc.is_a? Proc
# TRANSLATORS 'proc' is a Ruby block of code
raise ArgumentError, _("before action hook for %{name} is a %{class_name}, not a proc") %
{ name: self, class_name: proc.class.name.inspect }
end
@before_action =
@parent.__send__(:__add_method, __decoration_name(:before), proc)
end
attr_reader :after_action
def after_action=(proc)
unless proc.is_a? Proc
# TRANSLATORS 'proc' is a Ruby block of code
raise ArgumentError, _("after action hook for %{name} is a %{class_name}, not a proc") %
{ name: self, class_name: proc.class.name.inspect }
end
@after_action =
@parent.__send__(:__add_method, __decoration_name(:after), proc)
end
def __decoration_name(type)
if @parent.is_a? Puppet::Interface::Action then
:"option #{name} from #{parent.name} #{type} decoration"
else
:"option #{name} #{type} decoration"
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/interface/option_manager.rb | lib/puppet/interface/option_manager.rb | # frozen_string_literal: true
# This class is not actually public API, but the method
# {Puppet::Interface::OptionManager#option option} is public when used
# as part of the Faces DSL (i.e. from within a
# {Puppet::Interface.define define} block).
# @api public
module Puppet::Interface::OptionManager
# @api private
def display_global_options(*args)
@display_global_options ||= []
[args].flatten.each do |refopt|
unless Puppet.settings.include?(refopt)
# TRANSLATORS 'Puppet.settings' references to the Puppet settings options and should not be translated
raise ArgumentError, _("Global option %{option} does not exist in Puppet.settings") % { option: refopt }
end
@display_global_options << refopt if refopt
end
@display_global_options.uniq!
@display_global_options
end
alias :display_global_option :display_global_options
def all_display_global_options
walk_inheritance_tree(@display_global_options, :all_display_global_options)
end
# @api private
def walk_inheritance_tree(start, sym)
result = start || []
if is_a?(Class) and superclass.respond_to?(sym)
result = superclass.send(sym) + result
elsif self.class.respond_to?(sym)
result = self.class.send(sym) + result
end
result
end
# Declare that this app can take a specific option, and provide the
# code to do so. See {Puppet::Interface::ActionBuilder#option} for
# details.
#
# @api public
# @dsl Faces
def option(*declaration, &block)
add_option Puppet::Interface::OptionBuilder.build(self, *declaration, &block)
end
# @api private
def add_option(option)
# @options collects the added options in the order they're declared.
# @options_hash collects the options keyed by alias for quick lookups.
@options ||= []
@options_hash ||= {}
option.aliases.each do |name|
conflict = get_option(name)
if conflict
raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict}") %
{ option: option, conflict: conflict }
end
actions.each do |action|
action = get_action(action)
conflict = action.get_option(name)
if conflict
raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{action}") %
{ option: option, conflict: conflict, action: action }
end
end
end
@options << option.name
option.aliases.each do |name|
@options_hash[name] = option
end
option
end
# @api private
def options
walk_inheritance_tree(@options, :options)
end
# @api private
def get_option(name, with_inherited_options = true)
@options_hash ||= {}
result = @options_hash[name.to_sym]
if result.nil? and with_inherited_options then
if is_a?(Class) and superclass.respond_to?(:get_option)
result = superclass.get_option(name)
elsif self.class.respond_to?(:get_option)
result = self.class.get_option(name)
end
end
result
end
# @api private
def option?(name)
options.include? name.to_sym
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/interface/action_builder.rb | lib/puppet/interface/action_builder.rb | # frozen_string_literal: true
# This class is used to build {Puppet::Interface::Action actions}.
# When an action is defined with
# {Puppet::Interface::ActionManager#action} the block is evaluated
# within the context of a new instance of this class.
# @api public
class Puppet::Interface::ActionBuilder
extend Forwardable
# The action under construction
# @return [Puppet::Interface::Action]
# @api private
attr_reader :action
# Builds a new action.
# @return [Puppet::Interface::Action]
# @api private
def self.build(face, name, &block)
raise "Action #{name.inspect} must specify a block" unless block
new(face, name, &block).action
end
# Deprecates the action
# @return [void]
# @api private
# @dsl Faces
def deprecate
@action.deprecate
end
# Ideally the method we're defining here would be added to the action, and a
# method on the face would defer to it, but we can't get scope correct, so
# we stick with this. --daniel 2011-03-24
# Sets what the action does when it is invoked. This takes a block
# which will be called when the action is invoked. The action will
# accept arguments based on the arity of the block. It should always
# take at least one argument for options. Options will be the last
# argument.
#
# @overload when_invoked({|options| ... })
# An action with no arguments
# @overload when_invoked({|arg1, arg2, options| ... })
# An action with two arguments
# @return [void]
# @api public
# @dsl Faces
def when_invoked(&block)
@action.when_invoked = block
end
# Sets a block to be run at the rendering stage, for a specific
# rendering type (eg JSON, YAML, console), after the block for
# when_invoked gets run. This manipulates the value returned by the
# action. It makes it possible to work around limitations in the
# underlying object returned, and should be avoided in favor of
# returning a more capable object.
# @api private
# @todo this needs more
# @dsl Faces
def when_rendering(type = nil, &block)
if type.nil? then # the default error message sucks --daniel 2011-04-18
# TRANSLATORS 'when_rendering' is a method name and should not be translated
raise ArgumentError, _('You must give a rendering format to when_rendering')
end
if block.nil? then
# TRANSLATORS 'when_rendering' is a method name and should not be translated
raise ArgumentError, _('You must give a block to when_rendering')
end
@action.set_rendering_method_for(type, block)
end
# Declare that this action can take a specific option, and provide the
# code to do so. One or more strings are given, in the style of
# OptionParser (see example). These strings are parsed to derive a
# name for the option. Any `-` characters within the option name (ie
# excluding the initial `-` or `--` for an option) will be translated
# to `_`.The first long option will be used as the name, and the rest
# are retained as aliases. The original form of the option is used
# when invoking the face, the translated form is used internally.
#
# When the action is invoked the value of the option is available in
# a hash passed to the {Puppet::Interface::ActionBuilder#when_invoked
# when_invoked} block, using the option name in symbol form as the
# hash key.
#
# The block to this method is used to set attributes for the option
# (see {Puppet::Interface::OptionBuilder}).
#
# @param declaration [String] Option declarations, as described above
# and in the example.
#
# @example Say hi
# action :say_hi do
# option "-u USER", "--user-name USER" do
# summary "Who to say hi to"
# end
#
# when_invoked do |options|
# "Hi, #{options[:user_name]}"
# end
# end
# @api public
# @dsl Faces
def option(*declaration, &block)
option = Puppet::Interface::OptionBuilder.build(@action, *declaration, &block)
@action.add_option(option)
end
# Set this as the default action for the face.
# @api public
# @dsl Faces
# @return [void]
def default(value = true)
@action.default = !!value
end
# @api private
def display_global_options(*args)
@action.add_display_global_options args
end
alias :display_global_option :display_global_options
# Sets the default rendering format
# @api private
def render_as(value = nil)
if value.nil?
# TRANSLATORS 'render_as' is a method name and should not be translated
raise ArgumentError, _("You must give a rendering format to render_as")
end
formats = Puppet::Network::FormatHandler.formats
unless formats.include? value
raise ArgumentError, _("%{value} is not a valid rendering format: %{formats_list}") %
{ value: value.inspect, formats_list: formats.sort.join(", ") }
end
@action.render_as = value
end
# Metaprogram the simple DSL from the target class.
Puppet::Interface::Action.instance_methods.grep(/=$/).each do |setter|
next if setter =~ /^=/
property = setter.to_s.chomp('=')
unless method_defined? property
# ActionBuilder#<property> delegates to Action#<setter>
def_delegator :@action, setter, property
end
end
private
def initialize(face, name, &block)
@face = face
@action = Puppet::Interface::Action.new(face, name)
instance_eval(&block)
unless @action.when_invoked
# TRANSLATORS 'when_invoked' is a method name and should not be translated and 'block' is a Ruby code block
raise ArgumentError, _("actions need to know what to do when_invoked; please add the 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/interface/action.rb | lib/puppet/interface/action.rb | # coding: utf-8
# frozen_string_literal: true
require 'prettyprint'
# This represents an action that is attached to a face. Actions should
# be constructed by calling {Puppet::Interface::ActionManager#action},
# which is available on {Puppet::Interface}, and then calling methods of
# {Puppet::Interface::ActionBuilder} in the supplied block.
# @api private
class Puppet::Interface::Action
extend Puppet::Interface::DocGen
include Puppet::Interface::FullDocs
# @api private
def initialize(face, name)
raise "#{name.inspect} is an invalid action name" unless name.to_s =~ /^[a-z]\w*$/
@face = face
@name = name.to_sym
# The few bits of documentation we actually demand. The default license
# is a favour to our end users; if you happen to get that in a core face
# report it as a bug, please. --daniel 2011-04-26
@authors = []
@license = 'All Rights Reserved'
# @options collects the added options in the order they're declared.
# @options_hash collects the options keyed by alias for quick lookups.
@options = []
@display_global_options = []
@options_hash = {}
@when_rendering = {}
end
# This is not nice, but it is the easiest way to make us behave like the
# Ruby Method object rather than UnboundMethod. Duplication is vaguely
# annoying, but at least we are a shallow clone. --daniel 2011-04-12
# @return [void]
# @api private
def __dup_and_rebind_to(to)
bound_version = dup
bound_version.instance_variable_set(:@face, to)
bound_version
end
def to_s() "#{@face}##{@name}" end
# The name of this action
# @return [Symbol]
attr_reader :name
# The face this action is attached to
# @return [Puppet::Interface]
attr_reader :face
# Whether this is the default action for the face
# @return [Boolean]
# @api private
attr_accessor :default
def default?
!!@default
end
########################################################################
# Documentation...
attr_doc :returns
attr_doc :arguments
def synopsis
build_synopsis(@face.name, default? ? nil : name, arguments)
end
########################################################################
# Support for rendering formats and all.
# @api private
def when_rendering(type)
unless type.is_a? Symbol
raise ArgumentError, _("The rendering format must be a symbol, not %{class_name}") % { class_name: type.class.name }
end
# Do we have a rendering hook for this name?
return @when_rendering[type].bind(@face) if @when_rendering.has_key? type
# How about by another name?
alt = type.to_s.sub(/^to_/, '').to_sym
return @when_rendering[alt].bind(@face) if @when_rendering.has_key? alt
# Guess not, nothing to run.
nil
end
# @api private
def set_rendering_method_for(type, proc)
unless proc.is_a? Proc
msg = if proc.nil?
# TRANSLATORS 'set_rendering_method_for' and 'Proc' should not be translated
_("The second argument to set_rendering_method_for must be a Proc")
else
# TRANSLATORS 'set_rendering_method_for' and 'Proc' should not be translated
_("The second argument to set_rendering_method_for must be a Proc, not %{class_name}") %
{ class_name: proc.class.name }
end
raise ArgumentError, msg
end
if proc.arity != 1 and proc.arity != (@positional_arg_count + 1)
msg = if proc.arity < 0 then
# TRANSLATORS 'when_rendering', 'when_invoked' are method names and should not be translated
_("The when_rendering method for the %{face} face %{name} action takes either just one argument,"\
" the result of when_invoked, or the result plus the %{arg_count} arguments passed to the"\
" when_invoked block, not a variable number") %
{ face: @face.name, name: name, arg_count: @positional_arg_count }
else
# TRANSLATORS 'when_rendering', 'when_invoked' are method names and should not be translated
_("The when_rendering method for the %{face} face %{name} action takes either just one argument,"\
" the result of when_invoked, or the result plus the %{arg_count} arguments passed to the"\
" when_invoked block, not %{string}") %
{ face: @face.name, name: name, arg_count: @positional_arg_count, string: proc.arity.to_s }
end
raise ArgumentError, msg
end
unless type.is_a? Symbol
raise ArgumentError, _("The rendering format must be a symbol, not %{class_name}") % { class_name: type.class.name }
end
if @when_rendering.has_key? type then
raise ArgumentError, _("You can't define a rendering method for %{type} twice") % { type: type }
end
# Now, the ugly bit. We add the method to our interface object, and
# retrieve it, to rotate through the dance of getting a suitable method
# object out of the whole process. --daniel 2011-04-18
@when_rendering[type] =
@face.__send__(:__add_method, __render_method_name_for(type), proc)
end
# @return [void]
# @api private
def __render_method_name_for(type)
:"#{name}_when_rendering_#{type}"
end
private :__render_method_name_for
# @api private
# @return [Symbol]
attr_reader :render_as
def render_as=(value)
@render_as = value.to_sym
end
# @api private
# @return [void]
def deprecate
@deprecated = true
end
# @api private
# @return [Boolean]
def deprecated?
@deprecated
end
########################################################################
# Initially, this was defined to allow the @action.invoke pattern, which is
# a very natural way to invoke behaviour given our introspection
# capabilities. Heck, our initial plan was to have the faces delegate to
# the action object for invocation and all.
#
# It turns out that we have a binding problem to solve: @face was bound to
# the parent class, not the subclass instance, and we don't pass the
# appropriate context or change the binding enough to make this work.
#
# We could hack around it, by either mandating that you pass the context in
# to invoke, or try to get the binding right, but that has probably got
# subtleties that we don't instantly think of – especially around threads.
#
# So, we are pulling this method for now, and will return it to life when we
# have the time to resolve the problem. For now, you should replace...
#
# @action = @face.get_action(name)
# @action.invoke(arg1, arg2, arg3)
#
# ...with...
#
# @action = @face.get_action(name)
# @face.send(@action.name, arg1, arg2, arg3)
#
# I understand that is somewhat cumbersome, but it functions as desired.
# --daniel 2011-03-31
#
# PS: This code is left present, but commented, to support this chunk of
# documentation, for the benefit of the reader.
#
# def invoke(*args, &block)
# @face.send(name, *args, &block)
# end
# We need to build an instance method as a wrapper, using normal code, to be
# able to expose argument defaulting between the caller and definer in the
# Ruby API. An extra method is, sadly, required for Ruby 1.8 to work since
# it doesn't expose bind on a block.
#
# Hopefully we can improve this when we finally shuffle off the last of Ruby
# 1.8 support, but that looks to be a few "enterprise" release eras away, so
# we are pretty stuck with this for now.
#
# Patches to make this work more nicely with Ruby 1.9 using runtime version
# checking and all are welcome, provided that they don't change anything
# outside this little ol' bit of code and all.
#
# Incidentally, we though about vendoring evil-ruby and actually adjusting
# the internal C structure implementation details under the hood to make
# this stuff work, because it would have been cleaner. Which gives you an
# idea how motivated we were to make this cleaner. Sorry.
# --daniel 2011-03-31
# The arity of the action
# @return [Integer]
attr_reader :positional_arg_count
# The block that is executed when the action is invoked
# @return [block]
attr_reader :when_invoked
def when_invoked=(block)
internal_name = "#{@name} implementation, required on Ruby 1.8".to_sym
arity = @positional_arg_count = block.arity
if arity == 0 then
# This will never fire on 1.8.7, which treats no arguments as "*args",
# but will on 1.9.2, which treats it as "no arguments". Which bites,
# because this just begs for us to wind up in the horrible situation
# where a 1.8 vs 1.9 error bites our end users. --daniel 2011-04-19
# TRANSLATORS 'when_invoked' should not be translated
raise ArgumentError, _("when_invoked requires at least one argument (options) for action %{name}") % { name: @name }
elsif arity > 0 then
range = Range.new(1, arity - 1)
decl = range.map { |x| "arg#{x}" } << "options = {}"
optn = ""
args = "[" + (range.map { |x| "arg#{x}" } << "options").join(", ") + "]"
else
range = Range.new(1, arity.abs - 1)
decl = range.map { |x| "arg#{x}" } << "*rest"
optn = "rest << {} unless rest.last.is_a?(Hash)"
if arity == -1 then
args = "rest"
else
args = "[" + range.map { |x| "arg#{x}" }.join(", ") + "] + rest"
end
end
file = __FILE__ + "+eval[wrapper]"
line = __LINE__ + 2 # <== points to the same line as 'def' in the wrapper.
wrapper = <<~WRAPPER
def #{@name}(#{decl.join(', ')})
#{optn}
args = #{args}
action = get_action(#{name.inspect})
args << action.validate_and_clean(args.pop)
__invoke_decorations(:before, action, args, args.last)
rval = self.__send__(#{internal_name.inspect}, *args)
__invoke_decorations(:after, action, args, args.last)
return rval
end
WRAPPER
# It should be possible to rewrite this code to use `define_method`
# instead of `class/instance_eval` since Ruby 1.8 is long dead.
if @face.is_a?(Class)
@face.class_eval do eval wrapper, nil, file, line end # rubocop:disable Security/Eval
@face.send(:define_method, internal_name, &block)
@when_invoked = @face.instance_method(name)
else
@face.instance_eval do eval wrapper, nil, file, line end # rubocop:disable Security/Eval
@face.meta_def(internal_name, &block)
@when_invoked = @face.method(name).unbind
end
end
def add_option(option)
option.aliases.each do |name|
conflict = get_option(name)
if conflict
raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict}") %
{ option: option, conflict: conflict }
else
conflict = @face.get_option(name)
if conflict
raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{face}") %
{ option: option, conflict: conflict, face: @face }
end
end
end
@options << option.name
option.aliases.each do |name|
@options_hash[name] = option
end
option
end
def option?(name)
@options_hash.include? name.to_sym
end
def options
@face.options + @options
end
def add_display_global_options(*args)
@display_global_options ||= []
[args].flatten.each do |refopt|
unless Puppet.settings.include? refopt
# TRANSLATORS 'Puppet.settings' should not be translated
raise ArgumentError, _("Global option %{option} does not exist in Puppet.settings") % { option: refopt }
end
@display_global_options << refopt
end
@display_global_options.uniq!
@display_global_options
end
def display_global_options(*args)
args ? add_display_global_options(args) : @display_global_options + @face.display_global_options
end
alias :display_global_option :display_global_options
def get_option(name, with_inherited_options = true)
option = @options_hash[name.to_sym]
if option.nil? and with_inherited_options
option = @face.get_option(name)
end
option
end
def validate_and_clean(original)
# The final set of arguments; effectively a hand-rolled shallow copy of
# the original, which protects the caller from the surprises they might
# get if they passed us a hash and we mutated it...
result = {}
# Check for multiple aliases for the same option, and canonicalize the
# name of the argument while we are about it.
overlap = Hash.new do |h, k| h[k] = [] end
unknown = []
original.keys.each do |name|
option = get_option(name)
if option
canonical = option.name
if result.has_key? canonical
overlap[canonical] << name
else
result[canonical] = original[name]
end
elsif Puppet.settings.include? name
result[name] = original[name]
else
unknown << name
end
end
unless overlap.empty?
overlap_list = overlap.map { |k, v| "(#{k}, #{v.sort.join(', ')})" }.join(", ")
raise ArgumentError, _("Multiple aliases for the same option passed: %{overlap_list}") %
{ overlap_list: overlap_list }
end
unless unknown.empty?
unknown_list = unknown.sort.join(", ")
raise ArgumentError, _("Unknown options passed: %{unknown_list}") % { unknown_list: unknown_list }
end
# Inject default arguments and check for missing mandating options.
missing = []
options.map { |x| get_option(x) }.each do |option|
name = option.name
next if result.has_key? name
if option.has_default?
result[name] = option.default
elsif option.required?
missing << name
end
end
unless missing.empty?
missing_list = missing.sort.join(', ')
raise ArgumentError, _("The following options are required: %{missing_list}") % { missing_list: missing_list }
end
# All done.
result
end
########################################################################
# Support code for action decoration; see puppet/interface.rb for the gory
# details of why this is hidden away behind private. --daniel 2011-04-15
private
# @return [void]
# @api private
def __add_method(name, proc)
@face.__send__ :__add_method, name, proc
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/sequential_prioritizer.rb | lib/puppet/graph/sequential_prioritizer.rb | # frozen_string_literal: true
# This implements a priority in which keys are given values that will keep them
# in the same priority in which they priorities are requested. Nested
# structures (those in which a key is contained within another key) are
# preserved in such a way that child keys are after the parent and before the
# key after the parent.
#
# @api private
class Puppet::Graph::SequentialPrioritizer < Puppet::Graph::Prioritizer
def initialize
super
@container = {}
@count = Puppet::Graph::Key.new
end
def generate_priority_for(key)
if priority_of(key).nil?
@count = @count.next
record_priority_for(key, @count)
else
priority_of(key)
end
end
def generate_priority_contained_in(container, key)
@container[container] ||= priority_of(container).down
priority = @container[container].next
record_priority_for(key, priority)
@container[container] = priority
priority
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/rb_tree_map.rb | lib/puppet/graph/rb_tree_map.rb | # frozen_string_literal: true
# Algorithms and Containers project is Copyright (c) 2009 Kanwei Li
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# A RbTreeMap is a map that is stored in sorted order based on the order of its keys. This ordering is
# determined by applying the function <=> to compare the keys. No duplicate values for keys are allowed,
# so duplicate values are overwritten.
#
# A major advantage of RBTreeMap over a Hash is the fact that keys are stored in order and can thus be
# iterated over in order. This is useful for many datasets.
#
# The implementation is adapted from Robert Sedgewick's Left Leaning Red-Black Tree implementation,
# which can be found at https://www.cs.princeton.edu/~rs/talks/LLRB/Java/RedBlackBST.java
#
# Most methods have O(log n) complexity.
class Puppet::Graph::RbTreeMap
include Enumerable
attr_reader :size
alias_method :length, :size
# Create and initialize a new empty TreeMap.
def initialize
@root = nil
@size = 0
end
# Insert an item with an associated key into the TreeMap, and returns the item inserted
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts") #=> "Massachusetts"
# map.get("MA") #=> "Massachusetts"
def push(key, value)
@root = insert(@root, key, value)
@root.color = :black
value
end
alias_method :[]=, :push
# Return true if key is found in the TreeMap, false otherwise
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.has_key?("GA") #=> true
# map.has_key?("DE") #=> false
def has_key?(key)
!get_recursive(@root, key).nil?
end
# Return the item associated with the key, or nil if none found.
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.get("GA") #=> "Georgia"
def get(key)
node = get_recursive(@root, key)
node ? node.value : nil
node.value if node
end
alias_method :[], :get
# Return the smallest key in the map.
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.min_key #=> "GA"
def min_key
@root.nil? ? nil : min_recursive(@root).key
end
# Return the largest key in the map.
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.max_key #=> "MA"
def max_key
@root.nil? ? nil : max_recursive(@root).key
end
# Deletes the item and key if it's found, and returns the item. Returns nil
# if key is not present.
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.delete("MA") #=> "Massachusetts"
def delete(key)
result = nil
if @root
return unless has_key? key
@root, result = delete_recursive(@root, key)
@root.color = :black if @root
@size -= 1
end
result
end
# Returns true if the tree is empty, false otherwise
def empty?
@root.nil?
end
# Deletes the item with the smallest key and returns the item. Returns nil
# if key is not present.
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.delete_min #=> "Massachusetts"
# map.size #=> 1
def delete_min
result = nil
if @root
@root, result = delete_min_recursive(@root)
@root.color = :black if @root
@size -= 1
end
result
end
# Deletes the item with the largest key and returns the item. Returns nil
# if key is not present.
#
# Complexity: O(log n)
#
# map = Containers::TreeMap.new
# map.push("MA", "Massachusetts")
# map.push("GA", "Georgia")
# map.delete_max #=> "Georgia"
# map.size #=> 1
def delete_max
result = nil
if @root
@root, result = delete_max_recursive(@root)
@root.color = :black if @root
@size -= 1
end
result
end
# Yields [key, value] pairs in order by key.
def each(&blk)
recursive_yield(@root, &blk)
end
def first
return nil unless @root
node = min_recursive(@root)
[node.key, node.value]
end
def last
return nil unless @root
node = max_recursive(@root)
[node.key, node.value]
end
def to_hash
@root ? @root.to_hash : {}
end
class Node # :nodoc: all
attr_accessor :color, :key, :value, :left, :right
def initialize(key, value)
@key = key
@value = value
@color = :red
@left = nil
@right = nil
end
def to_hash
h = {
:node => {
:key => @key,
:value => @value,
:color => @color,
}
}
h[:left] = left.to_hash if @left
h[:right] = right.to_hash if @right
h
end
def red?
@color == :red
end
def colorflip
@color = @color == :red ? :black : :red
@left.color = @left.color == :red ? :black : :red
@right.color = @right.color == :red ? :black : :red
end
def rotate_left
r = @right
r_key = r.key
r_value = r.value
b = r.left
r.left = @left
@left = r
@right = r.right
r.right = b
r.color = :red
r.key = @key
r.value = @value
@key = r_key
@value = r_value
self
end
def rotate_right
l = @left
l_key = l.key
l_value = l.value
b = l.right
l.right = @right
@right = l
@left = l.left
l.left = b
l.color = :red
l.key = @key
l.value = @value
@key = l_key
@value = l_value
self
end
def move_red_left
colorflip
if @right.left && @right.left.red?
@right.rotate_right
rotate_left
colorflip
end
self
end
def move_red_right
colorflip
if @left.left && @left.left.red?
rotate_right
colorflip
end
self
end
def fixup
rotate_left if @right && @right.red?
rotate_right if (@left && @left.red?) && (@left.left && @left.left.red?)
colorflip if (@left && @left.red?) && (@right && @right.red?)
self
end
end
private
def recursive_yield(node, &blk)
return unless node
recursive_yield(node.left, &blk)
yield node.key, node.value
recursive_yield(node.right, &blk)
end
def delete_recursive(node, key)
if (key <=> node.key) == -1
node.move_red_left if !isred(node.left) && !isred(node.left.left)
node.left, result = delete_recursive(node.left, key)
else
node.rotate_right if isred(node.left)
if ((key <=> node.key) == 0) && node.right.nil?
return nil, node.value
end
if !isred(node.right) && !isred(node.right.left)
node.move_red_right
end
if (key <=> node.key) == 0
result = node.value
min_child = min_recursive(node.right)
node.value = min_child.value
node.key = min_child.key
node.right = delete_min_recursive(node.right).first
else
node.right, result = delete_recursive(node.right, key)
end
end
[node.fixup, result]
end
def delete_min_recursive(node)
if node.left.nil?
return nil, node.value
end
if !isred(node.left) && !isred(node.left.left)
node.move_red_left
end
node.left, result = delete_min_recursive(node.left)
[node.fixup, result]
end
def delete_max_recursive(node)
if isred(node.left)
node = node.rotate_right
end
return nil, node.value if node.right.nil?
if !isred(node.right) && !isred(node.right.left)
node.move_red_right
end
node.right, result = delete_max_recursive(node.right)
[node.fixup, result]
end
def get_recursive(node, key)
return nil if node.nil?
case key <=> node.key
when 0 then node
when -1 then get_recursive(node.left, key)
when 1 then get_recursive(node.right, key)
end
end
def min_recursive(node)
return node if node.left.nil?
min_recursive(node.left)
end
def max_recursive(node)
return node if node.right.nil?
max_recursive(node.right)
end
def insert(node, key, value)
unless node
@size += 1
return Node.new(key, value)
end
case key <=> node.key
when 0 then node.value = value
when -1 then node.left = insert(node.left, key, value)
when 1 then node.right = insert(node.right, key, value)
end
node.rotate_left if node.right && node.right.red?
node.rotate_right if node.left && node.left.red? && node.left.left && node.left.left.red?
node.colorflip if node.left && node.left.red? && node.right && node.right.red?
node
end
def isred(node)
return false if node.nil?
node.color == :red
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.