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/property.rb
lib/puppet/property.rb
# frozen_string_literal: true # The virtual base class for properties, which are the self-contained building # blocks for actually doing work on the system. require_relative '../puppet' require_relative '../puppet/parameter' # The Property class is the implementation of a resource's attributes of _property_ kind. # A Property is a specialized Resource Type Parameter that has both an 'is' (current) state, and # a 'should' (wanted state). However, even if this is conceptually true, the current _is_ value is # obtained by asking the associated provider for the value, and hence it is not actually part of a # property's state, and only available when a provider has been selected and can obtain the value (i.e. when # running on an agent). # # A Property (also in contrast to a parameter) is intended to describe a managed attribute of # some system entity, such as the name or mode of a file. # # The current value _(is)_ is read and written with the methods {#retrieve} and {#set}, and the wanted # value _(should)_ is read and written with the methods {#value} and {#value=} which delegate to # {#should} and {#should=}, i.e. when a property is used like any other parameter, it is the _should_ value # that is operated on. # # All resource type properties in the puppet system are derived from this class. # # The intention is that new parameters are created by using the DSL method {Puppet::Type.newproperty}. # # @abstract # @note Properties of Types are expressed using subclasses of this class. Such a class describes one # named property of a particular Type (as opposed to describing a type of property in general). This # limits the use of one (concrete) property class instance to occur only once for a given type's inheritance # chain. An instance of a Property class is the value holder of one instance of the resource type (e.g. the # mode of a file resource instance). # A Property class may server as the superclass _(parent)_ of another; e.g. a Size property that describes # handling of measurements such as kb, mb, gb. If a type requires two different size measurements it requires # one concrete class per such measure; e.g. MinSize (:parent => Size), and MaxSize (:parent => Size). # # @see Puppet::Type # @see Puppet::Parameter # # @api public # class Puppet::Property < Puppet::Parameter require_relative 'property/ensure' # Returns the original wanted value(s) _(should)_ unprocessed by munging/unmunging. # The original values are set by {#value=} or {#should=}. # @return (see #should) # attr_reader :shouldorig # The noop mode for this property. # By setting a property's noop mode to `true`, any management of this property is inhibited. Calculation # and reporting still takes place, but if a change of the underlying managed entity's state # should take place it will not be carried out. This noop # setting overrides the overall `Puppet[:noop]` mode as well as the noop mode in the _associated resource_ # attr_writer :noop class << self # @todo Figure out what this is used for. Can not find any logic in the puppet code base that # reads or writes this attribute. # ??? Probably Unused attr_accessor :unmanaged # @return [Symbol] The name of the property as given when the property was created. # attr_reader :name # @!attribute [rw] array_matching # @comment note that $#46; is a period - char code require to not terminate sentence. # The `is` vs&#46; `should` array matching mode; `:first`, or `:all`. # # @comment there are two blank chars after the symbols to cause a break - do not remove these. # * `:first` # This is primarily used for single value properties. When matched against an array of values # a match is true if the `is` value matches any of the values in the `should` array. When the `is` value # is also an array, the matching is performed against the entire array as the `is` value. # * `:all` # : This is primarily used for multi-valued properties. When matched against an array of # `should` values, the size of `is` and `should` must be the same, and all values in `is` must match # a value in `should`. # # @note The semantics of these modes are implemented by the method {#insync?}. That method is the default # implementation and it has a backwards compatible behavior that imposes additional constraints # on what constitutes a positive match. A derived property may override that method. # @return [Symbol] (:first) the mode in which matching is performed # @see #insync? # @dsl type # @api public # def array_matching @array_matching ||= :first end # @comment This is documented as an attribute - see the {array_matching} method. # def array_matching=(value) value = value.intern if value.is_a?(String) # TRANSLATORS 'Property#array_matching', 'first', and 'all' should not be translated raise ArgumentError, _("Supported values for Property#array_matching are 'first' and 'all'") unless [:first, :all].include?(value) @array_matching = value end # Used to mark a type property as having or lacking idempotency (on purpose # generally). This is used to avoid marking the property as a # corrective_change when there is known idempotency issues with the property # rendering a corrective_change flag as useless. # @return [Boolean] true if the property is marked as idempotent def idempotent @idempotent.nil? ? @idempotent = true : @idempotent end # Attribute setter for the idempotent attribute. # @param [bool] value boolean indicating if the property is idempotent. # @see idempotent def idempotent=(value) @idempotent = value end end # Looks up a value's name among valid values, to enable option lookup with result as a key. # @param name [Object] the parameter value to match against valid values (names). # @return {Symbol, Regexp} a value matching predicate # @api private # def self.value_name(name) value = value_collection.match?(name) value.name if value end # Returns the value of the given option (set when a valid value with the given "name" was defined). # @param name [Symbol, Regexp] the valid value predicate as returned by {value_name} # @param option [Symbol] the name of the wanted option # @return [Object] value of the option # @raise [NoMethodError] if the option is not supported # @todo Guessing on result of passing a non supported option (it performs send(option)). # @api private # def self.value_option(name, option) value = value_collection.value(name) value.send(option) if value end # Defines a new valid value for this property. # A valid value is specified as a literal (typically a Symbol), but can also be # specified with a Regexp. # # @param name [Symbol, Regexp] a valid literal value, or a regexp that matches a value # @param options [Hash] a hash with options # @option options [Symbol] :event The event that should be emitted when this value is set. # @todo Option :event original comment says "event should be returned...", is "returned" the correct word # to use? # @option options [Symbol] :invalidate_refreshes Indicates a change on this property should invalidate and # remove any scheduled refreshes (from notify or subscribe) targeted at the same resource. For example, if # a change in this property takes into account any changes that a scheduled refresh would have performed, # then the scheduled refresh would be deleted. # @option options [Object] any Any other option is treated as a call to a setter having the given # option name (e.g. `:required_features` calls `required_features=` with the option's value as an # argument). # # @dsl type # @api public def self.newvalue(name, options = {}, &block) value = value_collection.newvalue(name, options, &block) unless value.method.nil? method = value.method.to_sym if value.block if instance_methods(false).include?(method) raise ArgumentError, _("Attempt to redefine method %{method} with block") % { method: method } end define_method(method, &value.block) else # Let the method be an alias for calling the providers setter unless we already have this method alias_method(method, :call_provider) unless method_defined?(method) end end value end # Calls the provider setter method for this property with the given value as argument. # @return [Object] what the provider returns when calling a setter for this property's name # @raise [Puppet::Error] when the provider can not handle this property. # @see #set # @api private # def call_provider(value) # We have no idea how to handle this unless our parent have a provider self.fail "#{self.class.name} cannot handle values of type #{value.inspect}" unless @resource.provider method = self.class.name.to_s + "=" unless provider.respond_to? method self.fail "The #{provider.class.name} provider can not handle attribute #{self.class.name}" end provider.send(method, value) end # Formats a message for a property change from the given `current_value` to the given `newvalue`. # @return [String] a message describing the property change. # @note If called with equal values, this is reported as a change. # @raise [Puppet::DevError] if there were issues formatting the message # def change_to_s(current_value, newvalue) if current_value == :absent "defined '#{name}' as #{should_to_s(newvalue)}" elsif newvalue == :absent or newvalue == [:absent] "undefined '#{name}' from #{is_to_s(current_value)}" else "#{name} changed #{is_to_s(current_value)} to #{should_to_s(newvalue)}" end rescue Puppet::Error raise rescue => detail message = _("Could not convert change '%{name}' to string: %{detail}") % { name: name, detail: detail } Puppet.log_exception(detail, message) raise Puppet::DevError, message, detail.backtrace end # Produces the name of the event to use to describe a change of this property's value. # The produced event name is either the event name configured for this property, or a generic # event based on the name of the property with suffix `_changed`, or if the property is # `:ensure`, the name of the resource type and one of the suffixes `_created`, `_removed`, or `_changed`. # @return [String] the name of the event that describes the change # def event_name value = should event_name = self.class.value_option(value, :event) and return event_name name == :ensure or return (name.to_s + "_changed").to_sym (resource.type.to_s + case value when :present; "_created" when :absent; "_removed" else "_changed" end).to_sym end # Produces an event describing a change of this property. # In addition to the event attributes set by the resource type, this method adds: # # * `:name` - the event_name # * `:desired_value` - a.k.a _should_ or _wanted value_ # * `:property` - reference to this property # * `:source_description` - The containment path of this property, indicating what resource this # property is associated with and in what stage and class that resource # was declared, e.g. "/Stage[main]/Myclass/File[/tmp/example]/ensure" # * `:invalidate_refreshes` - if scheduled refreshes should be invalidated # * `:redacted` - if the event will be redacted (due to this property being sensitive) # # @return [Puppet::Transaction::Event] the created event # @see Puppet::Type#event def event(options = {}) attrs = { :name => event_name, :desired_value => should, :property => self, :source_description => path }.merge(options) value = self.class.value_collection.match?(should) if should attrs[:invalidate_refreshes] = true if value && value.invalidate_refreshes attrs[:redacted] = @sensitive resource.event attrs end # Determines whether the property is in-sync or not in a way that is protected against missing value. # @note If the wanted value _(should)_ is not defined or is set to a non-true value then this is # a state that can not be fixed and the property is reported to be in sync. # @return [Boolean] the protected result of `true` or the result of calling {#insync?}. # # @api private # @note Do not override this method. # def safe_insync?(is) # If there is no @should value, consider the property to be in sync. return true unless @should # Otherwise delegate to the (possibly derived) insync? method. insync?(is) end # Protects against override of the {#safe_insync?} method. # @raise [RuntimeError] if the added method is `:safe_insync?` # @api private # def self.method_added(sym) raise "Puppet::Property#safe_insync? shouldn't be overridden; please override insync? instead" if sym == :safe_insync? end # Checks if the current _(is)_ value is in sync with the wanted _(should)_ value. # The check if the two values are in sync is controlled by the result of {#match_all?} which # specifies a match of `:first` or `:all`). The matching of the _is_ value against the entire _should_ value # or each of the _should_ values (as controlled by {#match_all?} is performed by {#property_matches?}. # # A derived property typically only needs to override the {#property_matches?} method, but may also # override this method if there is a need to have more control over the array matching logic. # # @note The array matching logic in this method contains backwards compatible logic that performs the # comparison in `:all` mode by checking equality and equality of _is_ against _should_ converted to array of String, # and that the lengths are equal, and in `:first` mode by checking if one of the _should_ values # is included in the _is_ values. This means that the _is_ value needs to be carefully arranged to # match the _should_. # @todo The implementation should really do return is.zip(@should).all? {|a, b| property_matches?(a, b) } # instead of using equality check and then check against an array with converted strings. # @param is [Object] The current _(is)_ value to check if it is in sync with the wanted _(should)_ value(s) # @return [Boolean] whether the values are in sync or not. # @raise [Puppet::DevError] if wanted value _(should)_ is not an array. # @api public # def insync?(is) devfail "#{self.class.name}'s should is not array" unless @should.is_a?(Array) # an empty array is analogous to no should values return true if @should.empty? # Look for a matching value, either for all the @should values, or any of # them, depending on the configuration of this property. if match_all? then # Emulate Array#== using our own comparison function. # A non-array was not equal to an array, which @should always is. return false unless is.is_a? Array # If they were different lengths, they are not equal. return false unless is.length == @should.length # Finally, are all the elements equal? In order to preserve the # behaviour of previous 2.7.x releases, we need to impose some fun rules # on "equality" here. # # Specifically, we need to implement *this* comparison: the two arrays # are identical if the is values are == the should values, or if the is # values are == the should values, stringified. # # This does mean that property equality is not commutative, and will not # work unless the `is` value is carefully arranged to match the should. (is == @should or is == @should.map(&:to_s)) # When we stop being idiots about this, and actually have meaningful # semantics, this version is the thing we actually want to do. # # return is.zip(@should).all? {|a, b| property_matches?(a, b) } else @should.any? { |want| property_matches?(is, want) } end end # This method tests if two values are insync? outside of the properties current # should value. This works around the requirement for corrective_change analysis # that requires two older values to be compared with the properties potentially # custom insync? code. # # @param [Object] should the value it should be # @param [Object] is the value it is # @return [Boolean] whether or not the values are in sync or not # @api private def insync_values?(should, is) # Here be dragons. We're setting the should value of a property purely just to # call its insync? method, as it lacks a way to pass in a should. # Unfortunately there isn't an API compatible way of avoiding this, as both should # an insync? behaviours are part of the public API. Future API work should factor # this kind of arbitrary comparisons into the API to remove this complexity. -ken # Backup old should, set it to the new value, then call insync? on the property. old_should = @should begin @should = should insync?(is) rescue # Certain operations may fail, but we don't want to fail the transaction if we can # avoid it # TRANSLATORS 'insync_values?' should not be translated msg = _("Unknown failure using insync_values? on type: %{type} / property: %{name} to compare values %{should} and %{is}") % { type: resource.ref, name: name, should: should, is: is } Puppet.info(msg) # Return nil, ie. unknown nil ensure # Always restore old should @should = old_should end end # Checks if the given current and desired values are equal. # This default implementation performs this check in a backwards compatible way where # the equality of the two values is checked, and then the equality of current with desired # converted to a string. # # A derived implementation may override this method to perform a property specific equality check. # # The intent of this method is to provide an equality check suitable for checking if the property # value is in sync or not. It is typically called from {#insync?}. # def property_matches?(current, desired) # This preserves the older Puppet behaviour of doing raw and string # equality comparisons for all equality. I am not clear this is globally # desirable, but at least it is not a breaking change. --daniel 2011-11-11 current == desired or current == desired.to_s end # Produces a pretty printing string for the given value. # This default implementation calls {#format_value_for_display} on the class. A derived # implementation may perform property specific pretty printing when the _is_ values # are not already in suitable form. # @param value [Object] the value to format as a string # @return [String] a pretty printing string def is_to_s(value) # rubocop:disable Naming/PredicatePrefix self.class.format_value_for_display(value) end # Emits a log message at the log level specified for the associated resource. # The log entry is associated with this property. # @param msg [String] the message to log # @return [void] # def log(msg) Puppet::Util::Log.create( :level => resource[:loglevel], :message => msg, :source => self ) end # @return [Boolean] whether the {array_matching} mode is set to `:all` or not def match_all? self.class.array_matching == :all end # @return [Boolean] whether the property is marked as idempotent for the purposes # of calculating corrective change. def idempotent? self.class.idempotent end # @return [Symbol] the name of the property as stated when the property was created. # @note A property class (just like a parameter class) describes one specific property and # can only be used once within one type's inheritance chain. def name self.class.name end # @return [Boolean] whether this property is in noop mode or not. # Returns whether this property is in noop mode or not; if a difference between the # _is_ and _should_ values should be acted on or not. # The noop mode is a transitive setting. The mode is checked in this property, then in # the _associated resource_ and finally in Puppet[:noop]. # @todo This logic is different than Parameter#noop in that the resource noop mode overrides # the property's mode - in parameter it is the other way around. Bug or feature? # def noop # This is only here to make testing easier. if @resource.respond_to?(:noop?) @resource.noop? elsif defined?(@noop) @noop else Puppet[:noop] end end # Retrieves the current value _(is)_ of this property from the provider. # This implementation performs this operation by calling a provider method with the # same name as this property (i.e. if the property name is 'gid', a call to the # 'provider.gid' is expected to return the current value. # @return [Object] what the provider returns as the current value of the property # def retrieve provider.send(self.class.name) end # Sets the current _(is)_ value of this property. # The _name_ associated with the value is first obtained by calling {value_name}. A dynamically created setter # method associated with this _name_ is called if it exists, otherwise the value is set using using the provider's # setter method for this property by calling ({#call_provider}). # # @param value [Object] the value to set # @return [Object] returns the result of calling the setter method or {#call_provider} # @raise [Puppet::Error] if there were problems setting the value using the setter method or when the provider # setter should be used but there is no provider in the associated resource_ # @raise [Puppet::ResourceError] if there was a problem setting the value and it was not raised # as a Puppet::Error. The original exception is wrapped and logged. # @api public # def set(value) # Set a name for looking up associated options like the event. name = self.class.value_name(value) method = self.class.value_option(name, :method) if method && respond_to?(method) begin send(method) rescue Puppet::Error raise rescue => detail error = Puppet::ResourceError.new(_("Could not set '%{value}' on %{class_name}: %{detail}") % { value: value, class_name: self.class.name, detail: detail }, @resource.file, @resource.line, detail) error.set_backtrace detail.backtrace Puppet.log_exception(detail, error.message) raise error end else block = self.class.value_option(name, :block) if block # FIXME It'd be better here to define a method, so that # the blocks could return values. instance_eval(&block) else call_provider(value) end end end # Returns the wanted _(should)_ value of this property. # If the _array matching mode_ {#match_all?} is true, an array of the wanted values in unmunged format # is returned, else the first value in the array of wanted values in unmunged format is returned. # @return [Array<Object>, Object, nil] Array of values if {#match_all?} else a single value, or nil if there are no # wanted values. # @raise [Puppet::DevError] if the wanted value is non nil and not an array # # @note This method will potentially return different values than the original values as they are # converted via munging/unmunging. If the original values are wanted, call {#shouldorig}. # # @see #shouldorig # @api public # def should return nil unless defined?(@should) devfail "should for #{self.class.name} on #{resource.name} is not an array" unless @should.is_a?(Array) if match_all? @should.collect { |val| unmunge(val) } else unmunge(@should[0]) end end # Sets the wanted _(should)_ value of this property. # If the given value is not already an Array, it will be wrapped in one before being set. # This method also sets the cached original _should_ values returned by {#shouldorig}. # # @param values [Array<Object>, Object] the value(s) to set as the wanted value(s) # @raise [StandardError] when validation of a value fails (see {#validate}). # @api public # def should=(values) values = [values] unless values.is_a?(Array) @shouldorig = values values.each { |val| validate(val) } @should = values.collect { |val| munge(val) } end # Produces a pretty printing string for the given value. # This default implementation calls {#format_value_for_display} on the class. A derived # implementation may perform property specific pretty printing when the _should_ values # are not already in suitable form. # @param value [Object] the value to format as a string # @return [String] a pretty printing string def should_to_s(value) self.class.format_value_for_display(value) end # Synchronizes the current value _(is)_ and the wanted value _(should)_ by calling {#set}. # @raise [Puppet::DevError] if {#should} is nil # @todo The implementation of this method is somewhat inefficient as it computes the should # array twice. def sync devfail "Got a nil value for should" unless should set(should) end # Asserts that the given value is valid. # If the developer uses a 'validate' hook, this method will get overridden. # @raise [Exception] if the value is invalid, or value can not be handled. # @return [void] # @api private # def unsafe_validate(value) super validate_features_per_value(value) end # Asserts that all required provider features are present for the given property value. # @raise [ArgumentError] if a required feature is not present # @return [void] # @api private # def validate_features_per_value(value) features = self.class.value_option(self.class.value_name(value), :required_features) if features features = Array(features) needed_features = features.collect(&:to_s).join(", ") unless provider.satisfies?(features) # TRANSLATORS 'Provider' refers to a Puppet provider class raise ArgumentError, _("Provider %{provider} must have features '%{needed_features}' to set '%{property}' to '%{value}'") % { provider: provider.class.name, needed_features: needed_features, property: self.class.name, value: value } end end end # @return [Object, nil] Returns the wanted _(should)_ value of this property. def value should end # (see #should=) def value=(values) self.should = values end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/runtime.rb
lib/puppet/runtime.rb
# frozen_string_literal: true require_relative '../puppet/http' require_relative '../puppet/facter_impl' require 'singleton' # Provides access to runtime implementations. # # @api private class Puppet::Runtime include Singleton def initialize @runtime_services = { http: proc do klass = Puppet::Network::HttpPool.http_client_class if klass == Puppet::Network::HTTP::Connection Puppet::HTTP::Client.new else Puppet::HTTP::ExternalClient.new(klass) end end, facter: proc { Puppet::FacterImpl.new } } end private :initialize # Loads all runtime implementations. # # @return Array[Symbol] the names of loaded implementations # @api private def load_services @runtime_services.keys.each { |key| self[key] } end # Get a runtime implementation. # # @param name [Symbol] the name of the implementation # @return [Object] the runtime implementation # @api private def [](name) service = @runtime_services[name] raise ArgumentError, "Unknown service #{name}" unless service if service.is_a?(Proc) @runtime_services[name] = service.call else service end end # Register a runtime implementation. # # @param name [Symbol] the name of the implementation # @param impl [Object] the runtime implementation # @api private def []=(name, impl) @runtime_services[name] = impl end # Clears all implementations. This is used for testing. # # @api private def clear initialize 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/facter_impl.rb
lib/puppet/facter_impl.rb
# frozen_string_literal: true # # @api private # Default Facter implementation that delegates to Facter API # module Puppet class FacterImpl def initialize require 'facter' setup_logging end def value(fact_name) ::Facter.value(fact_name) end def add(name, &block) ::Facter.add(name, &block) end def to_hash ::Facter.to_hash end def clear ::Facter.clear end def reset ::Facter.reset end def resolve(options) ::Facter.resolve(options) end def search_external(dirs) ::Facter.search_external(dirs) end def search(*dirs) ::Facter.search(*dirs) end def trace(value) ::Facter.trace(value) if ::Facter.respond_to? :trace end def debugging(value) ::Facter.debugging(value) if ::Facter.respond_to?(:debugging) end def load_external? ::Facter.respond_to?(:load_external) end def load_external(value) ::Facter.load_external(value) if load_external? end private def setup_logging return unless ::Facter.respond_to? :on_message ::Facter.on_message do |level, message| case level when :trace, :debug level = :debug when :info # Same as Puppet when :warn level = :warning when :error level = :err when :fatal level = :crit else next end Puppet::Util::Log.create( { :level => level, :source => 'Facter', :message => message } ) nil 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/file_system.rb
lib/puppet/file_system.rb
# frozen_string_literal: true module Puppet::FileSystem require_relative '../puppet/util' require_relative 'file_system/path_pattern' require_relative 'file_system/file_impl' require_relative 'file_system/memory_file' require_relative 'file_system/memory_impl' require_relative 'file_system/uniquefile' # create instance of the file system implementation to use for the current platform @impl = if Puppet::Util::Platform.windows? require_relative 'file_system/windows' Puppet::FileSystem::Windows elsif Puppet::Util::Platform.jruby? require_relative 'file_system/jruby' Puppet::FileSystem::JRuby else require_relative 'file_system/posix' Puppet::FileSystem::Posix end.new() # Allows overriding the filesystem for the duration of the given block. # The filesystem will only contain the given file(s). # # @param files [Puppet::FileSystem::MemoryFile] the files to have available # # @api private # def self.overlay(*files, &block) old_impl = @impl @impl = Puppet::FileSystem::MemoryImpl.new(*files) yield ensure @impl = old_impl end # Opens the given path with given mode, and options and optionally yields it to the given block. # # @param path [String, Pathname] the path to the file to operate on # @param mode [Integer] The mode to apply to the file if it is created # @param options [String] Extra file operation mode information to use # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be specified explicitly as fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 # @yield The file handle, in the mode given by options, else read-write mode # @return [Void] # # @api public # def self.open(path, mode, options, &block) @impl.open(assert_path(path), mode, options, &block) end # @return [Object] The directory of this file as an opaque handle # # @api public # def self.dir(path) @impl.dir(assert_path(path)) end # @return [String] The directory of this file as a String # # @api public # def self.dir_string(path) @impl.path_string(@impl.dir(assert_path(path))) end # @return [Boolean] Does the directory of the given path exist? def self.dir_exist?(path) @impl.exist?(@impl.dir(assert_path(path))) end # Creates all directories down to (inclusive) the dir of the given path def self.dir_mkpath(path) @impl.mkpath(@impl.dir(assert_path(path))) end # @return [Object] the name of the file as a opaque handle # # @api public # def self.basename(path) @impl.basename(assert_path(path)) end # @return [String] the name of the file # # @api public # def self.basename_string(path) @impl.path_string(@impl.basename(assert_path(path))) end # Allows exclusive updates to a file to be made by excluding concurrent # access using flock. This means that if the file is on a filesystem that # does not support flock, this method will provide no protection. # # While polling to acquire the lock the process will wait ever increasing # amounts of time in order to prevent multiple processes from wasting # resources. # # @param path [Pathname] the path to the file to operate on # @param mode [Integer] The mode to apply to the file if it is created # @param options [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be specified explicitly as fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 # @param timeout [Integer] Number of seconds to wait for the lock (defaults to 300) # @yield The file handle, in the mode given by options, else read-write mode # @return [Void] # @raise [Timeout::Error] If the timeout is exceeded while waiting to acquire the lock # # @api public # def self.exclusive_open(path, mode, options = 'r', timeout = 300, &block) @impl.exclusive_open(assert_path(path), mode, options, timeout, &block) end # Processes each line of the file by yielding it to the given block # # @api public # def self.each_line(path, &block) @impl.each_line(assert_path(path), &block) end # @return [String] The contents of the file # # @api public # def self.read(path, opts = {}) @impl.read(assert_path(path), opts) end # Read a file keeping the original line endings intact. This # attempts to open files using binary mode using some encoding # overrides and falling back to IO.read when none of the # encodings are valid. # # @return [String] The contents of the file # # @api public # def self.read_preserve_line_endings(path) @impl.read_preserve_line_endings(assert_path(path)) end # @return [String] The binary contents of the file # # @api public # def self.binread(path) @impl.binread(assert_path(path)) end # Determines if a file exists by verifying that the file can be stat'd. # Will follow symlinks and verify that the actual target path exists. # # @return [Boolean] true if the named file exists. # # @api public # def self.exist?(path) @impl.exist?(assert_path(path)) end # Determines if a file is a directory. # # @return [Boolean] true if the given file is a directory. # # @api public def self.directory?(path) @impl.directory?(assert_path(path)) end # Determines if a file is a file. # # @return [Boolean] true if the given file is a file. # # @api public def self.file?(path) @impl.file?(assert_path(path)) end # Determines if a file is executable. # # @todo Should this take into account extensions on the windows platform? # # @return [Boolean] true if this file can be executed # # @api public # def self.executable?(path) @impl.executable?(assert_path(path)) end # @return [Boolean] Whether the file is writable by the current process # # @api public # def self.writable?(path) @impl.writable?(assert_path(path)) end # Touches the file. On most systems this updates the mtime of the file. # # @param mtime [Time] The last modified time or nil to use the current time # # @api public # def self.touch(path, mtime: nil) @impl.touch(assert_path(path), mtime: mtime) end # Creates directories for all parts of the given path. # # @api public # def self.mkpath(path) @impl.mkpath(assert_path(path)) end # @return [Array<Object>] references to all of the children of the given # directory path, excluding `.` and `..`. # @api public def self.children(path) @impl.children(assert_path(path)) end # Creates a symbolic link dest which points to the current file. # If dest already exists: # # * and is a file, will raise Errno::EEXIST # * and is a directory, will return 0 but perform no action # * and is a symlink referencing a file, will raise Errno::EEXIST # * and is a symlink referencing a directory, will return 0 but perform no action # # With the :force option set to true, when dest already exists: # # * and is a file, will replace the existing file with a symlink (DANGEROUS) # * and is a directory, will return 0 but perform no action # * and is a symlink referencing a file, will modify the existing symlink # * and is a symlink referencing a directory, will return 0 but perform no action # # @param dest [String] The path to create the new symlink at # @param [Hash] options the options to create the symlink with # @option options [Boolean] :force overwrite dest # @option options [Boolean] :noop do not perform the operation # @option options [Boolean] :verbose verbose output # # @raise [Errno::EEXIST] dest already exists as a file and, :force is not set # # @return [Integer] 0 # # @api public # def self.symlink(path, dest, options = {}) @impl.symlink(assert_path(path), dest, options) end # @return [Boolean] true if the file is a symbolic link. # # @api public # def self.symlink?(path) @impl.symlink?(assert_path(path)) end # @return [String] the name of the file referenced by the given link. # # @api public # def self.readlink(path) @impl.readlink(assert_path(path)) end # Deletes the given paths, returning the number of names passed as arguments. # See also Dir::rmdir. # # @raise an exception on any error. # # @return [Integer] the number of paths passed as arguments # # @api public # def self.unlink(*paths) @impl.unlink(*paths.map { |p| assert_path(p) }) end # @return [File::Stat] object for the named file. # # @api public # def self.stat(path) @impl.stat(assert_path(path)) end # @return [Integer] the size of the file # # @api public # def self.size(path) @impl.size(assert_path(path)) end # @return [File::Stat] Same as stat, but does not follow the last symbolic # link. Instead, reports on the link itself. # # @api public # def self.lstat(path) @impl.lstat(assert_path(path)) end # Compares the contents of this file against the contents of a stream. # # @param stream [IO] The stream to compare the contents against # @return [Boolean] Whether the contents were the same # # @api public # def self.compare_stream(path, stream) @impl.compare_stream(assert_path(path), stream) end # Produces an opaque pathname "handle" object representing the given path. # Different implementations of the underlying file system may use different runtime # objects. The produced "handle" should be used in all other operations # that take a "path". No operation should be directly invoked on the returned opaque object # # @param path [String] The string representation of the path # @return [Object] An opaque path handle on which no operations should be directly performed # # @api public # def self.pathname(path) @impl.pathname(path) end # Produces a string representation of the opaque path handle, with expansions # performed on ~. For Windows, this means that C:\Users\Admini~1\AppData will # be expanded to C:\Users\Administrator\AppData. On POSIX filesystems, the # value ~ will be expanded to something like /Users/Foo # # This method exists primarlily to resolve a Ruby deficiency where # File.expand_path doesn't convert short paths to long paths, which is # important when resolving the path to load. # # @param path [Object] a path handle produced by {#pathname} # @return [String] a string representation of the path # def self.expand_path(path, dir_string = nil) @impl.expand_path(path, dir_string) end # Asserts that the given path is of the expected type produced by #pathname # # @raise [ArgumentError] when path is not of the expected type # # @api public # def self.assert_path(path) @impl.assert_path(path) end # Produces a string representation of the opaque path handle. # # @param path [Object] a path handle produced by {#pathname} # @return [String] a string representation of the path # def self.path_string(path) @impl.path_string(path) end # Create and open a file for write only if it doesn't exist. # # @see Puppet::FileSystem::open # # @raise [Errno::EEXIST] path already exists. # # @api public # def self.exclusive_create(path, mode, &block) @impl.exclusive_create(assert_path(path), mode, &block) end # Changes permission bits on the named path to the bit pattern represented # by mode. # # @param mode [Integer] The mode to apply to the file if it is created # @param path [String] The path to the file, can also accept [PathName] # # @raise [Errno::ENOENT]: path doesn't exist # # @api public # def self.chmod(mode, path) @impl.chmod(mode, assert_path(path)) end # Replace the contents of a file atomically, creating the file if necessary. # If a `mode` is specified, then it will always be applied to the file. If # a `mode` is not specified and the file exists, its mode will be preserved. # If the file doesn't exist, the mode will be set to a platform-specific # default. # # @param path [String] The path to the file, can also accept [PathName] # @param mode [Integer] Optional mode for the file. # # @raise [Errno::EISDIR]: path is a directory # # @api public # def self.replace_file(path, mode = nil, &block) @impl.replace_file(assert_path(path), mode, &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/thread_local.rb
lib/puppet/thread_local.rb
# frozen_string_literal: true require 'concurrent' class Puppet::ThreadLocal < Concurrent::ThreadLocalVar end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/environments.rb
lib/puppet/environments.rb
# frozen_string_literal: true require_relative '../puppet/concurrent/synchronized' # @api private module Puppet::Environments class EnvironmentNotFound < Puppet::Error def initialize(environment_name, original = nil) environmentpath = Puppet[:environmentpath] super("Could not find a directory environment named '#{environment_name}' anywhere in the path: #{environmentpath}. Does the directory exist?", original) end end # @api private module EnvironmentCreator # Create an anonymous environment. # # @param module_path [String] A list of module directories separated by the # PATH_SEPARATOR # @param manifest [String] The path to the manifest # @return A new environment with the `name` `:anonymous` # # @api private def for(module_path, manifest) Puppet::Node::Environment.create(:anonymous, module_path.split(File::PATH_SEPARATOR), manifest) end end # Provide any common methods that loaders should have. It requires that any # classes that include this module implement get # @api private module EnvironmentLoader # @!macro loader_get_or_fail def get!(name) environment = get(name) environment || raise(EnvironmentNotFound, name) end def clear_all root = Puppet.lookup(:root_environment) { nil } unless root.nil? root.instance_variable_set(:@static_catalogs, nil) root.instance_variable_set(:@rich_data, nil) end end # The base implementation is a noop, because `get` returns a new environment # each time. # # @see Puppet::Environments::Cached#guard def guard(name); end def unguard(name); end end # @!macro [new] loader_search_paths # A list of indicators of where the loader is getting its environments from. # @return [Array<String>] The URIs of the load locations # # @!macro [new] loader_list # @return [Array<Puppet::Node::Environment>] All of the environments known # to the loader # # @!macro [new] loader_get # Find a named environment # # @param name [String,Symbol] The name of environment to find # @return [Puppet::Node::Environment, nil] the requested environment or nil # if it wasn't found # # @!macro [new] loader_get_conf # Attempt to obtain the initial configuration for the environment. Not all # loaders can provide this. # # @param name [String,Symbol] The name of the environment whose configuration # we are looking up # @return [Puppet::Setting::EnvironmentConf, nil] the configuration for the # requested environment, or nil if not found or no configuration is available # # @!macro [new] loader_get_or_fail # Find a named environment or raise # Puppet::Environments::EnvironmentNotFound when the named environment is # does not exist. # # @param name [String,Symbol] The name of environment to find # @return [Puppet::Node::Environment] the requested environment # A source of pre-defined environments. # # @api private class Static include EnvironmentCreator include EnvironmentLoader def initialize(*environments) @environments = environments end # @!macro loader_search_paths def search_paths ["data:text/plain,internal"] end # @!macro loader_list def list @environments end # @!macro loader_get def get(name) @environments.find do |env| env.name == name.intern end end # Returns a basic environment configuration object tied to the environment's # implementation values. Will not interpolate. # # @!macro loader_get_conf def get_conf(name) env = get(name) if env Puppet::Settings::EnvironmentConf.static_for(env, Puppet[:environment_timeout], Puppet[:static_catalogs], Puppet[:rich_data]) else nil end end end # A source of unlisted pre-defined environments. # # Used only for internal bootstrapping environments which are not relevant # to an end user (such as the fall back 'configured' environment). # # @api private class StaticPrivate < Static # Unlisted # # @!macro loader_list def list [] end end class StaticDirectory < Static # Accepts a single environment in the given directory having the given name (not required to be reflected as the name # of the directory) def initialize(env_name, env_dir, environment) super(environment) @env_dir = env_dir @env_name = env_name.intern end # @!macro loader_get_conf def get_conf(name) return nil unless name.intern == @env_name Puppet::Settings::EnvironmentConf.load_from(@env_dir, []) end end # Reads environments from a directory on disk. Each environment is # represented as a sub-directory. The environment's manifest setting is the # `manifest` directory of the environment directory. The environment's # modulepath setting is the global modulepath (from the `[server]` section # for the server) prepended with the `modules` directory of the environment # directory. # # @api private class Directories include EnvironmentLoader def initialize(environment_dir, global_module_path) @environment_dir = Puppet::FileSystem.expand_path(environment_dir) @global_module_path = global_module_path ? global_module_path.map { |p| Puppet::FileSystem.expand_path(p) } : nil end # Generate an array of directory loaders from a path string. # @param path [String] path to environment directories # @param global_module_path [Array<String>] the global modulepath setting # @return [Array<Puppet::Environments::Directories>] An array # of configured directory loaders. def self.from_path(path, global_module_path) environments = path.split(File::PATH_SEPARATOR) environments.map do |dir| Puppet::Environments::Directories.new(dir, global_module_path) end end def self.real_path(dir) if Puppet::FileSystem.symlink?(dir) && Puppet[:versioned_environment_dirs] dir = Pathname.new Puppet::FileSystem.expand_path(Puppet::FileSystem.readlink(dir)) end dir end # @!macro loader_search_paths def search_paths ["file://#{@environment_dir}"] end # @!macro loader_list def list valid_environment_names.collect do |name| create_environment(name) end end # @!macro loader_get def get(name) if validated_directory(File.join(@environment_dir, name.to_s)) create_environment(name) end end # @!macro loader_get_conf def get_conf(name) envdir = validated_directory(File.join(@environment_dir, name.to_s)) if envdir Puppet::Settings::EnvironmentConf.load_from(envdir, @global_module_path) else nil end end private def create_environment(name) # interpolated modulepaths may be cached from prior environment instances Puppet.settings.clear_environment_settings(name) env_symbol = name.intern setting_values = Puppet.settings.values(env_symbol, Puppet.settings.preferred_run_mode) env = Puppet::Node::Environment.create( env_symbol, Puppet::Node::Environment.split_path(setting_values.interpolate(:modulepath)), setting_values.interpolate(:manifest), setting_values.interpolate(:config_version) ) configured_path = File.join(@environment_dir, name.to_s) env.configured_path = configured_path if Puppet.settings[:report_configured_environmentpath] env.resolved_path = validated_directory(configured_path) else env.resolved_path = configured_path end env end def validated_directory(envdir) env_name = Puppet::FileSystem.basename_string(envdir) envdir = Puppet::Environments::Directories.real_path(envdir).to_s if Puppet::FileSystem.directory?(envdir) && Puppet::Node::Environment.valid_name?(env_name) envdir else nil end end def valid_environment_names return [] unless Puppet::FileSystem.directory?(@environment_dir) Puppet::FileSystem.children(@environment_dir).filter_map do |child| Puppet::FileSystem.basename_string(child).intern if validated_directory(child) end end end # Combine together multiple loaders to act as one. # @api private class Combined include EnvironmentLoader def initialize(*loaders) @loaders = loaders end # @!macro loader_search_paths def search_paths @loaders.collect(&:search_paths).flatten end # @!macro loader_list def list @loaders.collect(&:list).flatten end # @!macro loader_get def get(name) @loaders.each do |loader| env = loader.get(name) if env return env end end nil end # @!macro loader_get_conf def get_conf(name) @loaders.each do |loader| conf = loader.get_conf(name) if conf return conf end end nil end def clear_all @loaders.each(&:clear_all) end end class Cached include EnvironmentLoader include Puppet::Concurrent::Synchronized class DefaultCacheExpirationService # Called when the environment is created. # # @param [Puppet::Node::Environment] env def created(env) end # Is the environment with this name expired? # # @param [Symbol] env_name The symbolic environment name # @return [Boolean] def expired?(env_name) false end # The environment with this name was evicted. # # @param [Symbol] env_name The symbolic environment name def evicted(env_name) end end def self.cache_expiration_service=(service) @cache_expiration_service_singleton = service end def self.cache_expiration_service @cache_expiration_service_singleton || DefaultCacheExpirationService.new end def initialize(loader) @loader = loader @cache_expiration_service = Puppet::Environments::Cached.cache_expiration_service @cache = {} end # @!macro loader_list def list # Evict all that have expired, in the same way as `get` clear_all_expired # Evict all that was removed from disk cached_envs = @cache.keys.map!(&:to_sym) loader_envs = @loader.list.map!(&:name) removed_envs = cached_envs - loader_envs removed_envs.each do |env_name| Puppet.debug { "Environment no longer exists '#{env_name}'" } clear(env_name) end @loader.list.map do |env| name = env.name old_entry = @cache[name] if old_entry old_entry.value else add_entry(name, entry(env)) env end end end # @!macro loader_search_paths def search_paths @loader.search_paths end # @!macro loader_get def get(name) entry = get_entry(name) entry ? entry.value : nil end # Get a cache entry for an envionment. It returns nil if the # environment doesn't exist. def get_entry(name, check_expired = true) # Aggressively evict all that has expired # This strategy favors smaller memory footprint over environment # retrieval time. clear_all_expired if check_expired name = name.to_sym entry = @cache[name] if entry Puppet.debug { "Found in cache #{name.inspect} #{entry.label}" } # found in cache entry.touch elsif (env = @loader.get(name)) # environment loaded, cache it entry = entry(env) add_entry(name, entry) end entry end private :get_entry # Adds a cache entry to the cache def add_entry(name, cache_entry) Puppet.debug { "Caching environment #{name.inspect} #{cache_entry.label}" } @cache[name] = cache_entry @cache_expiration_service.created(cache_entry.value) end private :add_entry def clear_entry(name, entry) @cache.delete(name) Puppet.debug { "Evicting cache entry for environment #{name.inspect}" } @cache_expiration_service.evicted(name.to_sym) Puppet::GettextConfig.delete_text_domain(name) Puppet.settings.clear_environment_settings(name) end private :clear_entry # Clears the cache of the environment with the given name. # (The intention is that this could be used from a MANUAL cache eviction command (TBD) def clear(name) name = name.to_sym entry = @cache[name] clear_entry(name, entry) if entry end # Clears all cached environments. # (The intention is that this could be used from a MANUAL cache eviction command (TBD) def clear_all super @cache.each_pair do |name, entry| clear_entry(name, entry) end @cache = {} Puppet::GettextConfig.delete_environment_text_domains end # Clears all environments that have expired, either by exceeding their time to live, or # through an explicit eviction determined by the cache expiration service. # def clear_all_expired t = Time.now @cache.each_pair do |name, entry| clear_if_expired(name, entry, t) end end private :clear_all_expired # Clear an environment if it is expired, either by exceeding its time to live, or # through an explicit eviction determined by the cache expiration service. # def clear_if_expired(name, entry, t = Time.now) return unless entry return if entry.guarded? if entry.expired?(t) || @cache_expiration_service.expired?(name.to_sym) clear_entry(name, entry) end end private :clear_if_expired # This implementation evicts the cache, and always gets the current # configuration of the environment # # TODO: While this is wasteful since it # needs to go on a search for the conf, it is too disruptive to optimize # this. # # @!macro loader_get_conf def get_conf(name) name = name.to_sym clear_if_expired(name, @cache[name]) @loader.get_conf(name) end # Guard an environment so it can't be evicted while it's in use. The method # may be called multiple times, provided it is unguarded the same number of # times. If you call this method, you must call `unguard` in an ensure block. def guard(name) entry = get_entry(name, false) entry.guard if entry end # Unguard an environment. def unguard(name) entry = get_entry(name, false) entry.unguard if entry end # Creates a suitable cache entry given the time to live for one environment # def entry(env) ttl = if (conf = get_conf(env.name)) conf.environment_timeout else Puppet[:environment_timeout] end case ttl when 0 NotCachedEntry.new(env) # Entry that is always expired (avoids syscall to get time) when Float::INFINITY Entry.new(env) # Entry that never expires (avoids syscall to get time) else MRUEntry.new(env, ttl) # Entry that expires in ttl from when it was last touched end end # Never evicting entry class Entry attr_reader :value def initialize(value) @value = value @guards = 0 end def touch end def expired?(now) false end def label "" end # These are not protected with a lock, because all of the Cached # methods are protected. def guarded? @guards > 0 end def guard @guards += 1 end def unguard @guards -= 1 end end # Always evicting entry class NotCachedEntry < Entry def expired?(now) true end def label "(ttl = 0 sec)" end end # Policy that expires if it hasn't been touched within ttl_seconds class MRUEntry < Entry def initialize(value, ttl_seconds) super(value) @ttl = Time.now + ttl_seconds @ttl_seconds = ttl_seconds touch end def touch @ttl = Time.now + @ttl_seconds end def expired?(now) now > @ttl end def label "(ttl = #{@ttl_seconds} sec)" 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/compilable_resource_type.rb
lib/puppet/compilable_resource_type.rb
# frozen_string_literal: true require_relative '../puppet' # The CompilableResourceType module should be either included in a class or used as a class extension # to mark that the instance used as the 'resource type' of a resource instance # is an object that is compatible with Puppet::Type's API wrt. compiling. # Puppet Resource Types written in Ruby use a meta programmed Ruby Class as the type. Those classes # are subtypes of Puppet::Type. Meta data (Pcore/puppet language) based resource types uses instances of # a class instead. # module Puppet::CompilableResourceType # All 3.x resource types implemented in Ruby using Puppet::Type respond true. # Other kinds of implementations should reimplement and return false. def is_3x_ruby_plugin? true 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/module.rb
lib/puppet/module.rb
# frozen_string_literal: true require_relative '../puppet/util/logging' require_relative 'module/task' require_relative 'module/plan' require_relative '../puppet/util/json' require 'semantic_puppet/gem_version' # Support for modules class Puppet::Module class Error < Puppet::Error; end class MissingModule < Error; end class IncompatibleModule < Error; end class UnsupportedPlatform < Error; end class IncompatiblePlatform < Error; end class MissingMetadata < Error; end class FaultyMetadata < Error; end class InvalidName < Error; end class InvalidFilePattern < Error; end include Puppet::Util::Logging FILETYPES = { "manifests" => "manifests", "files" => "files", "templates" => "templates", "plugins" => "lib", "pluginfacts" => "facts.d", "locales" => "locales", "scripts" => "scripts", } # Find and return the +module+ that +path+ belongs to. If +path+ is # absolute, or if there is no module whose name is the first component # of +path+, return +nil+ def self.find(modname, environment = nil) return nil unless modname # Unless a specific environment is given, use the current environment env = environment ? Puppet.lookup(:environments).get!(environment) : Puppet.lookup(:current_environment) env.module(modname) end def self.is_module_directory?(name, path) # it must be a directory fullpath = File.join(path, name) return false unless Puppet::FileSystem.directory?(fullpath) is_module_directory_name?(name) end def self.is_module_directory_name?(name) # it must match an installed module name according to forge validator return true if name =~ /^[a-z][a-z0-9_]*$/ false end def self.is_module_namespaced_name?(name) # it must match the full module name according to forge validator return true if name =~ /^[a-zA-Z0-9]+-[a-z][a-z0-9_]*$/ false end # @api private def self.parse_range(range) SemanticPuppet::VersionRange.parse(range) end attr_reader :name, :environment, :path, :metadata attr_writer :environment attr_accessor :dependencies, :forge_name attr_accessor :source, :author, :version, :license, :summary, :description, :project_page def initialize(name, path, environment) @name = name @path = path @environment = environment assert_validity load_metadata @absolute_path_to_manifests = Puppet::FileSystem::PathPattern.absolute(manifests) end # @deprecated The puppetversion module metadata field is no longer used. def puppetversion nil end # @deprecated The puppetversion module metadata field is no longer used. def puppetversion=(something) end # @deprecated The puppetversion module metadata field is no longer used. def validate_puppet_version nil end def has_metadata? load_metadata @metadata.is_a?(Hash) && !@metadata.empty? rescue Puppet::Module::MissingMetadata false end FILETYPES.each do |type, location| # A boolean method to let external callers determine if # we have files of a given type. define_method(type + '?') do type_subpath = subpath(location) unless Puppet::FileSystem.exist?(type_subpath) Puppet.debug { "No #{type} found in subpath '#{type_subpath}' (file / directory does not exist)" } return false end true end # A method for returning a given file of a given type. # e.g., file = mod.manifest("my/manifest.pp") # # If the file name is nil, then the base directory for the # file type is passed; this is used for fileserving. define_method(type.sub(/s$/, '')) do |file| # If 'file' is nil then they're asking for the base path. # This is used for things like fileserving. if file full_path = File.join(subpath(location), file) else full_path = subpath(location) end return nil unless Puppet::FileSystem.exist?(full_path) full_path end # Return the base directory for the given type define_method(type) do subpath(location) end end def tasks_directory subpath("tasks") end def tasks return @tasks if instance_variable_defined?(:@tasks) if Puppet::FileSystem.exist?(tasks_directory) @tasks = Puppet::Module::Task.tasks_in_module(self) else @tasks = [] end end # This is a re-implementation of the Filetypes singular type method (e.g. # `manifest('my/manifest.pp')`. We don't implement the full filetype "API" for # tasks since tasks don't map 1:1 onto files. def task_file(name) # If 'file' is nil then they're asking for the base path. # This is used for things like fileserving. if name full_path = File.join(tasks_directory, name) else full_path = tasks_directory end if Puppet::FileSystem.exist?(full_path) full_path else nil end end def plans_directory subpath("plans") end def plans return @plans if instance_variable_defined?(:@plans) if Puppet::FileSystem.exist?(plans_directory) @plans = Puppet::Module::Plan.plans_in_module(self) else @plans = [] end end # This is a re-implementation of the Filetypes singular type method (e.g. # `manifest('my/manifest.pp')`. We don't implement the full filetype "API" for # plans. def plan_file(name) # If 'file' is nil then they're asking for the base path. # This is used for things like fileserving. if name full_path = File.join(plans_directory, name) else full_path = plans_directory end if Puppet::FileSystem.exist?(full_path) full_path else nil end end def license_file return @license_file if defined?(@license_file) return @license_file = nil unless path @license_file = File.join(path, "License") end def read_metadata md_file = metadata_file return {} if md_file.nil? content = File.read(md_file, :encoding => 'utf-8') content.empty? ? {} : Puppet::Util::Json.load(content) rescue Errno::ENOENT {} rescue Puppet::Util::Json::ParseError => e # TRANSLATORS 'metadata.json' is a specific file name and should not be translated. msg = _("%{name} has an invalid and unparsable metadata.json file. The parse error: %{error}") % { name: name, error: e.message } case Puppet[:strict] when :off Puppet.debug(msg) when :warning Puppet.warning(msg) when :error raise FaultyMetadata, msg end {} end def load_metadata return if instance_variable_defined?(:@metadata) @metadata = data = read_metadata return if data.empty? @forge_name = data['name'].tr('-', '/') if data['name'] [:source, :author, :version, :license, :dependencies].each do |attr| value = data[attr.to_s] raise MissingMetadata, "No #{attr} module metadata provided for #{name}" if value.nil? if attr == :dependencies unless value.is_a?(Array) raise MissingMetadata, "The value for the key dependencies in the file metadata.json of the module #{name} must be an array, not: '#{value}'" end value.each do |dep| name = dep['name'] dep['name'] = name.tr('-', '/') unless name.nil? dep['version_requirement'] ||= '>= 0.0.0' end end send(attr.to_s + "=", value) end end # Return the list of manifests matching the given glob pattern, # defaulting to 'init.pp' for empty modules. def match_manifests(rest) if rest wanted_manifests = wanted_manifests_from(rest) searched_manifests = wanted_manifests.glob.reject { |f| FileTest.directory?(f) } else searched_manifests = [] end # (#4220) Always ensure init.pp in case class is defined there. init_manifest = manifest("init.pp") if !init_manifest.nil? && !searched_manifests.include?(init_manifest) searched_manifests.unshift(init_manifest) end searched_manifests end def all_manifests return [] unless Puppet::FileSystem.exist?(manifests) Dir.glob(File.join(manifests, '**', '*.pp')) end def metadata_file return @metadata_file if defined?(@metadata_file) return @metadata_file = nil unless path @metadata_file = File.join(path, "metadata.json") end def hiera_conf_file unless defined?(@hiera_conf_file) @hiera_conf_file = path.nil? ? nil : File.join(path, Puppet::Pops::Lookup::HieraConfig::CONFIG_FILE_NAME) end @hiera_conf_file end def has_hiera_conf? hiera_conf_file.nil? ? false : Puppet::FileSystem.exist?(hiera_conf_file) end def modulepath File.dirname(path) if path end # Find all plugin directories. This is used by the Plugins fileserving mount. def plugin_directory subpath("lib") end def plugin_fact_directory subpath("facts.d") end # @return [String] def locale_directory subpath("locales") end # Returns true if the module has translation files for the # given locale. # @param [String] locale the two-letter language code to check # for translations # @return true if the module has a directory for the locale, false # false otherwise def has_translations?(locale) Puppet::FileSystem.exist?(File.join(locale_directory, locale)) end def has_external_facts? File.directory?(plugin_fact_directory) end def supports(name, version = nil) @supports ||= [] @supports << [name, version] end def to_s result = "Module #{name}" result += "(#{path})" if path result end def dependencies_as_modules dependent_modules = [] dependencies and dependencies.each do |dep| _, dep_name = dep["name"].split('/') found_module = environment.module(dep_name) dependent_modules << found_module if found_module end dependent_modules end def required_by environment.module_requirements[forge_name] || {} end # Identify and mark unmet dependencies. A dependency will be marked unmet # for the following reasons: # # * not installed and is thus considered missing # * installed and does not meet the version requirements for this module # * installed and doesn't use semantic versioning # # Returns a list of hashes representing the details of an unmet dependency. # # Example: # # [ # { # :reason => :missing, # :name => 'puppetlabs-mysql', # :version_constraint => 'v0.0.1', # :mod_details => { # :installed_version => '0.0.1' # } # :parent => { # :name => 'puppetlabs-bacula', # :version => 'v1.0.0' # } # } # ] # def unmet_dependencies unmet_dependencies = [] return unmet_dependencies unless dependencies dependencies.each do |dependency| name = dependency['name'] version_string = dependency['version_requirement'] || '>= 0.0.0' dep_mod = begin environment.module_by_forge_name(name) rescue nil end error_details = { :name => name, :version_constraint => version_string.gsub(/^(?=\d)/, "v"), :parent => { :name => forge_name, :version => version.gsub(/^(?=\d)/, "v") }, :mod_details => { :installed_version => dep_mod.nil? ? nil : dep_mod.version } } unless dep_mod error_details[:reason] = :missing unmet_dependencies << error_details next end next unless version_string begin required_version_semver_range = self.class.parse_range(version_string) actual_version_semver = SemanticPuppet::Version.parse(dep_mod.version) rescue ArgumentError error_details[:reason] = :non_semantic_version unmet_dependencies << error_details next end next if required_version_semver_range.include? actual_version_semver error_details[:reason] = :version_mismatch unmet_dependencies << error_details next end unmet_dependencies end def ==(other) name == other.name && version == other.version && path == other.path && environment == other.environment end private def wanted_manifests_from(pattern) begin extended = File.extname(pattern).empty? ? "#{pattern}.pp" : pattern relative_pattern = Puppet::FileSystem::PathPattern.relative(extended) rescue Puppet::FileSystem::PathPattern::InvalidPattern => error raise Puppet::Module::InvalidFilePattern.new( "The pattern \"#{pattern}\" to find manifests in the module \"#{name}\" " \ "is invalid and potentially unsafe.", error ) end relative_pattern.prefix_with(@absolute_path_to_manifests) end def subpath(type) File.join(path, type) end def assert_validity if !Puppet::Module.is_module_directory_name?(@name) && !Puppet::Module.is_module_namespaced_name?(@name) raise InvalidName, _(<<-ERROR_STRING).chomp % { name: @name } Invalid module name '%{name}'; module names must match either: An installed module name (ex. modulename) matching the expression /^[a-z][a-z0-9_]*$/ -or- A namespaced module name (ex. author-modulename) matching the expression /^[a-zA-Z0-9]+[-][a-z][a-z0-9_]*$/ ERROR_STRING 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/context.rb
lib/puppet/context.rb
# frozen_string_literal: true require_relative '../puppet/thread_local' # Puppet::Context is a system for tracking services and contextual information # that puppet needs to be able to run. Values are "bound" in a context when it is created # and cannot be changed; however a child context can be created, using # {#override}, that provides a different value. # # When binding a {Proc}, the proc is called when the value is looked up, and the result # is memoized for subsequent lookups. This provides a lazy mechanism that can be used to # delay expensive production of values until they are needed. # # @api private class Puppet::Context require_relative 'context/trusted_information' class UndefinedBindingError < Puppet::Error; end class StackUnderflow < Puppet::Error; end class UnknownRollbackMarkError < Puppet::Error; end class DuplicateRollbackMarkError < Puppet::Error; end # @api private def initialize(initial_bindings) @stack = Puppet::ThreadLocal.new(EmptyStack.new.push(initial_bindings)) # By initializing @rollbacks to nil and creating a hash lazily when #mark or # #rollback are called we ensure that the hashes are never shared between # threads and it's safe to mutate them @rollbacks = Puppet::ThreadLocal.new(nil) end # @api private def push(overrides, description = '') @stack.value = @stack.value.push(overrides, description) end # Push a context and make this global across threads # Do not use in a context where multiple threads may already exist # # @api private def unsafe_push_global(overrides, description = '') @stack = Puppet::ThreadLocal.new( @stack.value.push(overrides, description) ) end # @api private def pop @stack.value = @stack.value.pop end # @api private def lookup(name, &block) @stack.value.lookup(name, &block) end # @api private def override(bindings, description = '', &block) saved_point = @stack.value push(bindings, description) yield ensure @stack.value = saved_point end # Mark a place on the context stack to later return to with {rollback}. # # @param name [Object] The identifier for the mark # # @api private def mark(name) @rollbacks.value ||= {} if @rollbacks.value[name].nil? @rollbacks.value[name] = @stack.value else raise DuplicateRollbackMarkError, _("Mark for '%{name}' already exists") % { name: name } end end # Roll back to a mark set by {mark}. # # Rollbacks can only reach a mark accessible via {pop}. If the mark is not on # the current context stack the behavior of rollback is undefined. # # @param name [Object] The identifier for the mark # # @api private def rollback(name) @rollbacks.value ||= {} if @rollbacks.value[name].nil? raise UnknownRollbackMarkError, _("Unknown mark '%{name}'") % { name: name } end @stack.value = @rollbacks.value.delete(name) end # Base case for Puppet::Context::Stack. # # @api private class EmptyStack # Lookup a binding. Since there are none in EmptyStack, this always raises # an exception unless a block is passed, in which case the block is called # and its return value is used. # # @api private def lookup(name, &block) if block block.call else raise UndefinedBindingError, _("Unable to lookup '%{name}'") % { name: name } end end # Base case of #pop always raises an error since this is the bottom # # @api private def pop raise(StackUnderflow, _('Attempted to pop, but already at root of the context stack.')) end # Push bindings onto the stack by creating a new Stack object with `self` as # the parent # # @api private def push(overrides, description = '') Puppet::Context::Stack.new(self, overrides, description) end # Return the bindings table, which is always empty here # # @api private def bindings {} end end # Internal implementation of the bindings stack used by Puppet::Context. An # instance of Puppet::Context::Stack represents one level of bindings. It # caches a merged copy of all the bindings in the stack up to this point. # Each element of the stack is immutable, allowing the base to be shared # between threads. # # @api private class Stack attr_reader :bindings def initialize(parent, bindings, description = '') @parent = parent @bindings = parent.bindings.merge(bindings || {}) @description = description end # Lookup a binding in the current stack. Return the value if it is present. # If the value is a stored Proc, evaluate, cache, and return the result. If # no binding is found and a block is passed evaluate it and return the # result. Otherwise an exception is raised. # # @api private def lookup(name, &block) if @bindings.include?(name) value = @bindings[name] value.is_a?(Proc) ? (@bindings[name] = value.call) : value elsif block block.call else raise UndefinedBindingError, _("Unable to lookup '%{name}'") % { name: name } end end # Pop one level off the stack by returning the parent object. # # @api private def pop @parent end # Push bindings onto the stack by creating a new Stack object with `self` as # the parent # # @api private def push(overrides, description = '') Puppet::Context::Stack.new(self, overrides, description) 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/defaults.rb
lib/puppet/defaults.rb
# frozen_string_literal: true require_relative '../puppet/util/platform' module Puppet def self.default_diffargs '-u' end # If you modify this, update puppet/type/file/checksum.rb too def self.default_digest_algorithm 'sha256' end def self.valid_digest_algorithms Puppet::Util::Platform.fips_enabled? ? %w[sha256 sha384 sha512 sha224] : %w[sha256 sha384 sha512 sha224 md5] end def self.default_file_checksum_types Puppet::Util::Platform.fips_enabled? ? %w[sha256 sha384 sha512 sha224] : %w[sha256 sha384 sha512 sha224 md5] end def self.valid_file_checksum_types Puppet::Util::Platform.fips_enabled? ? %w[sha256 sha256lite sha384 sha512 sha224 sha1 sha1lite mtime ctime] : %w[sha256 sha256lite sha384 sha512 sha224 sha1 sha1lite md5 md5lite mtime ctime] end def self.default_cadir return "" if Puppet::Util::Platform.windows? old_ca_dir = "#{Puppet[:ssldir]}/ca" new_ca_dir = "/etc/puppetlabs/puppetserver/ca" if File.exist?(old_ca_dir) if File.symlink?(old_ca_dir) File.readlink(old_ca_dir) else old_ca_dir end else new_ca_dir end end def self.default_basemodulepath path = ['$codedir/modules'] if (run_mode_dir = Puppet.run_mode.common_module_dir) path << run_mode_dir end path.join(File::PATH_SEPARATOR) end def self.default_vendormoduledir Puppet.run_mode.vendor_module_dir end ############################################################################################ # NOTE: For information about the available values for the ":type" property of settings, # see the docs for Settings.define_settings ############################################################################################ AS_DURATION = 'This setting can be a time interval in seconds (30 or 30s), minutes (30m), hours (6h), days (2d), or years (5y).' # @api public # @param args [Puppet::Settings] the settings object to define default settings for # @return void def self.initialize_default_settings!(settings) settings.define_settings(:main, :confdir => { :default => nil, :type => :directory, :desc => "The main Puppet configuration directory. The default for this setting is calculated based on the user. If the process is running as root or the user that Puppet is supposed to run as, it defaults to a system directory, but if it's running as any other user, it defaults to being in the user's home directory.", }, :codedir => { :default => nil, :type => :directory, :desc => "The main Puppet code directory. The default for this setting is calculated based on the user. If the process is running as root or the user that Puppet is supposed to run as, it defaults to a system directory, but if it's running as any other user, it defaults to being in the user's home directory.", }, :vardir => { :default => nil, :type => :directory, :owner => "service", :group => "service", :desc => "Where Puppet stores dynamic and growing data. The default for this setting is calculated specially, like `confdir`_.", }, ### NOTE: this setting is usually being set to a symbol value. We don't officially have a ### setting type for that yet, but we might want to consider creating one. :name => { :default => nil, :desc => "The name of the application, if we are running as one. The default is essentially $0 without the path or `.rb`.", } ) settings.define_settings(:main, :logdir => { :default => nil, :type => :directory, :mode => "0750", :owner => "service", :group => "service", :desc => "The directory in which to store log files", }, :log_level => { :default => 'notice', :type => :enum, :values => %w[debug info notice warning err alert emerg crit], :desc => "Default logging level for messages from Puppet. Allowed values are: * debug * info * notice * warning * err * alert * emerg * crit ", :hook => proc {|value| Puppet::Util::Log.level = value }, :call_hook => :on_initialize_and_write, }, :disable_warnings => { :default => [], :type => :array, :desc => "A comma-separated list of warning types to suppress. If large numbers of warnings are making Puppet's logs too large or difficult to use, you can temporarily silence them with this setting. If you are preparing to upgrade Puppet to a new major version, you should re-enable all warnings for a while. Valid values for this setting are: * `deprecations` --- disables deprecation warnings. * `undefined_variables` --- disables warnings about non existing variables. * `undefined_resources` --- disables warnings about non existing resources.", :hook => proc do |value| values = munge(value) valid = %w[deprecations undefined_variables undefined_resources] invalid = values - (values & valid) unless invalid.empty? raise ArgumentError, _("Cannot disable unrecognized warning types '%{invalid}'.") % { invalid: invalid.join(',') } + ' ' + _("Valid values are '%{values}'.") % { values: valid.join(', ') } end end }, :skip_logging_catalog_request_destination => { :default => false, :type => :boolean, :desc => "Specifies whether to suppress the notice of which compiler supplied the catalog. A value of `true` suppresses the notice.", }, :merge_dependency_warnings => { :default => false, :type => :boolean, :desc => "Whether to merge class-level dependency failure warnings. When a class has a failed dependency, every resource in the class generates a notice level message about the dependency failure, and a warning level message about skipping the resource. If true, all messages caused by a class dependency failure are merged into one message associated with the class. ", }, :strict => { :default => :error, :type => :symbolic_enum, :values => [:off, :warning, :error], :desc => "The strictness level of puppet. Allowed values are: * off - do not perform extra validation, do not report * warning - perform extra validation, report as warning * error - perform extra validation, fail with error (default) The strictness level is for both language semantics and runtime evaluation validation. In addition to controlling the behavior with this primary server switch some individual warnings may also be controlled by the disable_warnings setting. No new validations will be added to a micro (x.y.z) release, but may be added in minor releases (x.y.0). In major releases it expected that most (if not all) strictness validation become standard behavior.", :hook => proc do |value| munge(value) value.to_sym end }, :disable_i18n => { :default => true, :type => :boolean, :desc => "If true, turns off all translations of Puppet and module log messages, which affects error, warning, and info log messages, as well as any translations in the report and CLI.", :hook => proc do |value| if value require_relative '../puppet/gettext/stubs' Puppet::GettextConfig.disable_gettext end end } ) settings.define_settings(:main, :priority => { :default => nil, :type => :priority, :desc => "The scheduling priority of the process. Valid values are 'high', 'normal', 'low', or 'idle', which are mapped to platform-specific values. The priority can also be specified as an integer value and will be passed as is, e.g. -5. Puppet must be running as a privileged user in order to increase scheduling priority.", }, :trace => { :default => false, :type => :boolean, :desc => "Whether to print stack traces on some errors. Will print internal Ruby stack trace interleaved with Puppet function frames.", :hook => proc do |value| # Enable or disable Facter's trace option too Puppet.runtime[:facter].trace(value) end }, :puppet_trace => { :default => false, :type => :boolean, :desc => "Whether to print the Puppet stack trace on some errors. This is a noop if `trace` is also set.", }, :profile => { :default => false, :type => :boolean, :desc => "Whether to enable experimental performance profiling", }, :versioned_environment_dirs => { :default => false, :type => :boolean, :desc => "Whether or not to look for versioned environment directories, symlinked from `$environmentpath/<environment>`. This is an experimental feature and should be used with caution." }, :static_catalogs => { :default => true, :type => :boolean, :desc => "Whether to compile a [static catalog](https://puppet.com/docs/puppet/latest/static_catalogs.html#enabling-or-disabling-static-catalogs), which occurs only on Puppet Server when the `code-id-command` and `code-content-command` settings are configured in its `puppetserver.conf` file.", }, :settings_catalog => { :default => true, :type => :boolean, :desc => "Whether to compile and apply the settings catalog", }, :strict_environment_mode => { :default => false, :type => :boolean, :desc => "Whether the agent specified environment should be considered authoritative, causing the run to fail if the retrieved catalog does not match it.", }, :autoflush => { :default => true, :type => :boolean, :desc => "Whether log files should always flush to disk.", :hook => proc { |value| Log.autoflush = value } }, :syslogfacility => { :default => "daemon", :desc => "What syslog facility to use when logging to syslog. Syslog has a fixed list of valid facilities, and you must choose one of those; you cannot just make one up." }, :statedir => { :default => "$vardir/state", :type => :directory, :mode => "01755", :desc => "The directory where Puppet state is stored. Generally, this directory can be removed without causing harm (although it might result in spurious service restarts)." }, :rundir => { :default => nil, :type => :directory, :mode => "0755", :owner => "service", :group => "service", :desc => "Where Puppet PID files are kept." }, :genconfig => { :default => false, :type => :boolean, :desc => "When true, causes Puppet applications to print an example config file to stdout and exit. The example will include descriptions of each setting, and the current (or default) value of each setting, incorporating any settings overridden on the CLI (with the exception of `genconfig` itself). This setting only makes sense when specified on the command line as `--genconfig`.", }, :genmanifest => { :default => false, :type => :boolean, :desc => "Whether to just print a manifest to stdout and exit. Only makes sense when specified on the command line as `--genmanifest`. Takes into account arguments specified on the CLI.", }, :configprint => { :default => "", :deprecated => :completely, :desc => "Prints the value of a specific configuration setting. If the name of a setting is provided for this, then the value is printed and puppet exits. Comma-separate multiple values. For a list of all values, specify 'all'. This setting is deprecated, the 'puppet config' command replaces this functionality.", }, :color => { :default => "ansi", :type => :string, :desc => "Whether to use colors when logging to the console. Valid values are `ansi` (equivalent to `true`), `html`, and `false`, which produces no color." }, :mkusers => { :default => false, :type => :boolean, :desc => "Whether to create the necessary user and group that puppet agent will run as.", }, :manage_internal_file_permissions => { :default => ! Puppet::Util::Platform.windows?, :type => :boolean, :desc => "Whether Puppet should manage the owner, group, and mode of files it uses internally. **Note**: For Windows agents, the default is `false` for versions 4.10.13 and greater, versions 5.5.6 and greater, and versions 6.0 and greater.", }, :onetime => { :default => false, :type => :boolean, :desc => "Perform one configuration run and exit, rather than spawning a long-running daemon. This is useful for interactively running puppet agent, or running puppet agent from cron.", :short => 'o', }, :path => { :default => "none", :desc => "The shell search path. Defaults to whatever is inherited from the parent process. This setting can only be set in the `[main]` section of puppet.conf; it cannot be set in `[server]`, `[agent]`, or an environment config section.", :call_hook => :on_define_and_write, :hook => proc do |value| ENV['PATH'] = '' if ENV['PATH'].nil? ENV['PATH'] = value unless value == 'none' paths = ENV['PATH'].split(File::PATH_SEPARATOR) Puppet::Util::Platform.default_paths.each do |path| next if paths.include?(path) ENV['PATH'] = ENV.fetch('PATH', nil) + File::PATH_SEPARATOR + path end value end }, :libdir => { :type => :directory, :default => "$vardir/lib", :desc => "An extra search path for Puppet. This is only useful for those files that Puppet will load on demand, and is only guaranteed to work for those cases. In fact, the autoload mechanism is responsible for making sure this directory is in Ruby's search path\n" }, :environment => { :default => "production", :desc => "The environment in which Puppet is running. For clients, such as `puppet agent`, this determines the environment itself, which Puppet uses to find modules and much more. For servers, such as `puppet server`, this provides the default environment for nodes that Puppet knows nothing about. When defining an environment in the `[agent]` section, this refers to the environment that the agent requests from the primary server. The environment doesn't have to exist on the local filesystem because the agent fetches it from the primary server. This definition is used when running `puppet agent`. When defined in the `[user]` section, the environment refers to the path that Puppet uses to search for code and modules related to its execution. This requires the environment to exist locally on the filesystem where puppet is being executed. Puppet subcommands, including `puppet module` and `puppet apply`, use this definition. Given that the context and effects vary depending on the [config section](https://puppet.com/docs/puppet/latest/config_file_main.html#config-sections) in which the `environment` setting is defined, do not set it globally.", :short => "E" }, :environmentpath => { :default => "$codedir/environments", :desc => "A search path for directory environments, as a list of directories separated by the system path separator character. (The POSIX path separator is ':', and the Windows path separator is ';'.) This setting must have a value set to enable **directory environments.** The recommended value is `$codedir/environments`. For more details, see <https://puppet.com/docs/puppet/latest/environments_about.html>", :type => :path, }, :report_configured_environmentpath => { :type => :boolean, :default => true, :desc => <<-'EOT' Specifies how environment paths are reported. When the value of `versioned_environment_dirs` is `true`, Puppet applies the readlink function to the `environmentpath` setting when constructing the environment's modulepath. The full readlinked path is referred to as the "resolved path," and the configured path potentially containing symlinks is the "configured path." When reporting where resources come from, users may choose between the configured and resolved path. When set to `false`, the resolved paths are reported instead of the configured paths. EOT }, :use_last_environment => { :type => :boolean, :default => true, :desc => <<-'EOT' Puppet saves both the initial and converged environment in the last_run_summary file. If they differ, and this setting is set to true, we will use the last converged environment and skip the node request. When set to false, we will do the node request and ignore the environment data from the last_run_summary file. EOT }, :always_retry_plugins => { :type => :boolean, :default => true, :desc => <<-'EOT' Affects how we cache attempts to load Puppet resource types and features. If true, then calls to `Puppet.type.<type>?` `Puppet.feature.<feature>?` will always attempt to load the type or feature (which can be an expensive operation) unless it has already been loaded successfully. This makes it possible for a single agent run to, e.g., install a package that provides the underlying capabilities for a type or feature, and then later load that type or feature during the same run (even if the type or feature had been tested earlier and had not been available). If this setting is set to false, then types and features will only be checked once, and if they are not available, the negative result is cached and returned for all subsequent attempts to load the type or feature. This behavior is almost always appropriate for the server, and can result in a significant performance improvement for types and features that are checked frequently. EOT }, :diff_args => { :default => -> { default_diffargs }, :desc => "Which arguments to pass to the diff command when printing differences between files. The command to use can be chosen with the `diff` setting.", }, :diff => { :default => (Puppet::Util::Platform.windows? ? "" : "diff"), :desc => "Which diff command to use when printing differences between files. This setting has no default value on Windows, as standard `diff` is not available, but Puppet can use many third-party diff tools.", }, :show_diff => { :type => :boolean, :default => false, :desc => "Whether to log and report a contextual diff when files are being replaced. This causes partial file contents to pass through Puppet's normal logging and reporting system, so this setting should be used with caution if you are sending Puppet's reports to an insecure destination. This feature currently requires the `diff/lcs` Ruby library.", }, :daemonize => { :type => :boolean, :default => !Puppet::Util::Platform.windows?, :desc => "Whether to send the process into the background. This defaults to true on POSIX systems, and to false on Windows (where Puppet currently cannot daemonize).", :short => "D", :hook => proc do |value| if value and Puppet::Util::Platform.windows? raise "Cannot daemonize on Windows" end end }, :maximum_uid => { :default => 4_294_967_290, :type => :integer, :desc => "The maximum allowed UID. Some platforms use negative UIDs but then ship with tools that do not know how to handle signed ints, so the UIDs show up as huge numbers that can then not be fed back into the system. This is a hackish way to fail in a slightly more useful way when that happens.", }, :route_file => { :default => "$confdir/routes.yaml", :desc => "The YAML file containing indirector route configuration.", }, :node_terminus => { :type => :terminus, :default => "plain", :desc => <<-'EOT', Which node data plugin to use when compiling node catalogs. When Puppet compiles a catalog, it combines two primary sources of info: the main manifest, and a node data plugin (often called a "node terminus," for historical reasons). Node data plugins provide three things for a given node name: 1. A list of classes to add to that node's catalog (and, optionally, values for their parameters). 2. Which Puppet environment the node should use. 3. A list of additional top-scope variables to set. The three main node data plugins are: * `plain` --- Returns no data, so that the main manifest controls all node configuration. * `exec` --- Uses an [external node classifier (ENC)](https://puppet.com/docs/puppet/latest/nodes_external.html), configured by the `external_nodes` setting. This lets you pull a list of Puppet classes from any external system, using a small glue script to perform the request and format the result as YAML. * `classifier` (formerly `console`) --- Specific to Puppet Enterprise. Uses the PE console for node data." EOT }, :node_cache_terminus => { :type => :terminus, :default => nil, :desc => "How to store cached nodes. Valid values are (none), 'json', 'msgpack', or 'yaml'.", }, :data_binding_terminus => { :type => :terminus, :default => "hiera", :desc => "This setting has been deprecated. Use of any value other than 'hiera' should instead be configured in a version 5 hiera.yaml. Until this setting is removed, it controls which data binding terminus to use for global automatic data binding (across all environments). By default this value is 'hiera'. A value of 'none' turns off the global binding.", :call_hook => :on_initialize_and_write, :hook => proc do |value| if Puppet[:strict] != :off s_val = value.to_s # because sometimes the value is a symbol unless s_val == 'hiera' || s_val == 'none' || value == '' || value.nil? #TRANSLATORS 'data_binding_terminus' is a setting and should not be translated message = _("Setting 'data_binding_terminus' is deprecated.") #TRANSLATORS 'hiera' should not be translated message += ' ' + _("Convert custom terminus to hiera 5 API.") Puppet.deprecation_warning(message) end end end }, :hiera_config => { :default => lambda do config = nil codedir = settings[:codedir] if codedir.is_a?(String) config = File.expand_path(File.join(codedir, 'hiera.yaml')) config = nil unless Puppet::FileSystem.exist?(config) end config = File.expand_path(File.join(settings[:confdir], 'hiera.yaml')) if config.nil? config end, :desc => "The hiera configuration file. Puppet only reads this file on startup, so you must restart the puppet server every time you edit it.", :type => :file, }, :binder_config => { :default => nil, :desc => "The binder configuration file. Puppet reads this file on each request to configure the bindings system. If set to nil (the default), a $confdir/binder_config.yaml is optionally loaded. If it does not exists, a default configuration is used. If the setting :binding_config is specified, it must reference a valid and existing yaml file.", :type => :file, }, :catalog_terminus => { :type => :terminus, :default => "compiler", :desc => "Where to get node catalogs. This is useful to change if, for instance, you'd like to pre-compile catalogs and store them in memcached or some other easily-accessed store.", }, :catalog_cache_terminus => { :type => :terminus, :default => nil, :desc => "How to store cached catalogs. Valid values are 'json', 'msgpack' and 'yaml'. The agent application defaults to 'json'." }, :facts_terminus => { :default => 'facter', :desc => "The node facts terminus.", }, :trusted_external_command => { :default => nil, :type => :file_or_directory, :desc => "The external trusted facts script or directory to use. This setting's value can be set to the path to an executable command that can produce external trusted facts or to a directory containing those executable commands. The command(s) must: * Take the name of a node as a command-line argument. * Return a JSON hash with the external trusted facts for this node. * For unknown or invalid nodes, exit with a non-zero exit code. If the setting points to an executable command, then the external trusted facts will be stored in the 'external' key of the trusted facts hash. Otherwise for each executable file in the directory, the external trusted facts will be stored in the `<basename>` key of the `trusted['external']` hash. For example, if the files foo.rb and bar.sh are in the directory, then `trusted['external']` will be the hash `{ 'foo' => <foo.rb output>, 'bar' => <bar.sh output> }`.", }, :default_file_terminus => { :type => :terminus, :default => "rest", :desc => "The default source for files if no server is given in a uri, e.g. puppet:///file. The default of `rest` causes the file to be retrieved using the `server` setting. When running `apply` the default is `file_server`, causing requests to be filled locally." }, :http_proxy_host => { :default => "none", :desc => "The HTTP proxy host to use for outgoing connections. The proxy will be bypassed if the server's hostname matches the NO_PROXY environment variable or `no_proxy` setting. Note: You may need to use a FQDN for the server hostname when using a proxy. Environment variable http_proxy or HTTP_PROXY will override this value. ", }, :http_proxy_port => { :default => 3128, :type => :port, :desc => "The HTTP proxy port to use for outgoing connections", }, :http_proxy_user => { :default => "none", :desc => "The user name for an authenticated HTTP proxy. Requires the `http_proxy_host` setting.", }, :http_proxy_password => { :default => "none", :hook => proc do |value| if value =~ %r{[@!# /]} raise "Passwords set in the http_proxy_password setting must be valid as part of a URL, and any reserved characters must be URL-encoded. We received: #{value}" end end, :desc => "The password for the user of an authenticated HTTP proxy. Requires the `http_proxy_user` setting. Note that passwords must be valid when used as part of a URL. If a password contains any characters with special meanings in URLs (as specified by RFC 3986 section 2.2), they must be URL-encoded. (For example, `#` would become `%23`.)", }, :no_proxy => { :default => "localhost, 127.0.0.1", :desc => "List of host or domain names that should not go through `http_proxy_host`. Environment variable no_proxy or NO_PROXY will override this value. Names can be specified as an FQDN `host.example.com`, wildcard `*.example.com`, dotted domain `.example.com`, or suffix `example.com`.", }, :http_keepalive_timeout => { :default => "4s", :type => :duration, :desc => "The maximum amount of time a persistent HTTP connection can remain idle in the connection pool, before it is closed. This timeout should be shorter than the keepalive timeout used on the HTTP server, e.g. Apache KeepAliveTimeout directive. #{AS_DURATION}" }, :http_debug => { :default => false, :type => :boolean, :desc => "Whether to write HTTP request and responses to stderr. This should never be used in a production environment." }, :http_connect_timeout => { :default => "2m", :type => :duration, :desc => "The maximum amount of time to wait when establishing an HTTP connection. The default value is 2 minutes. #{AS_DURATION}", }, :http_read_timeout => { :default => "10m", :type => :duration, :desc => "The time to wait for data to be read from an HTTP connection. If nothing is read after the elapsed interval then the connection will be closed. The default value is 10 minutes. #{AS_DURATION}", }, :http_user_agent => { :default => "Puppet/#{Puppet.version} Ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})", :desc => "The HTTP User-Agent string to send when making network requests." }, :filetimeout => { :default => "15s", :type => :duration, :desc => "The minimum time to wait between checking for updates in configuration files. This timeout determines how quickly Puppet checks whether a file (such as manifests or puppet.conf) has changed on disk. The default will change in a future release to be 'unlimited', requiring a reload of the Puppet service to pick up changes to its internal configuration. Currently we do not accept a value of 'unlimited'. To reparse files within an environment in Puppet Server please use the environment_cache endpoint", :hook => proc do |val| unless [0, 15, '15s'].include?(val) Puppet.deprecation_warning(<<-WARNING) Fine grained control of filetimeouts is deprecated. In future releases this value will only determine if file content is cached. Valid values are 0 (never cache) and 15 (15 second minimum wait time). WARNING end end }, :environment_timeout => { :default => "0", :type => :ttl, :desc => "How long the Puppet server should cache data it loads from an environment. A value of `0` will disable caching. This setting can also be set to `unlimited`, which will cache environments until the server is restarted or told to refresh the cache. All other values will result in Puppet server evicting environments that haven't been used within the last `environment_timeout` seconds. You should change this setting once your Puppet deployment is doing non-trivial work. We chose the default value of `0` because it lets new users update their code without any extra steps, but it lowers the performance of your Puppet server. We recommend either: * Setting this to `unlimited` and explicitly refreshing your Puppet server
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/coercion.rb
lib/puppet/coercion.rb
# frozen_string_literal: true # Various methods used to coerce values into a canonical form. # # @api private module Puppet::Coercion # Try to coerce various input values into boolean true/false # # Only a very limited subset of values are allowed. This method does not try # to provide a generic "truthiness" system. # # @param value [Boolean, Symbol, String] # @return [Boolean] # @raise # @api private def self.boolean(value) # downcase strings if value.respond_to? :downcase value = value.downcase end case value when true, :true, 'true', :yes, 'yes' # rubocop:disable Lint/BooleanSymbol true when false, :false, 'false', :no, 'no' # rubocop:disable Lint/BooleanSymbol false else fail('expected a boolean value') end end # Return the list of acceptable boolean values. # # This is limited to lower-case, even though boolean() is case-insensitive. # # @return [Array] # @raise # @api private def self.boolean_values %w[true false yes no] 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/functions.rb
lib/puppet/functions.rb
# frozen_string_literal: true # Functions in the puppet language can be written in Ruby and distributed in # puppet modules. The function is written by creating a file in the module's # `lib/puppet/functions/<modulename>` directory, where `<modulename>` is # replaced with the module's name. The file should have the name of the function. # For example, to create a function named `min` in a module named `math` create # a file named `lib/puppet/functions/math/min.rb` in the module. # # A function is implemented by calling {Puppet::Functions.create_function}, and # passing it a block that defines the implementation of the function. # # Functions are namespaced inside the module that contains them. The name of # the function is prefixed with the name of the module. For example, # `math::min`. # # @example A simple function # Puppet::Functions.create_function('math::min') do # def min(a, b) # a <= b ? a : b # end # end # # Anatomy of a function # --- # # Functions are composed of four parts: the name, the implementation methods, # the signatures, and the dispatches. # # The name is the string given to the {Puppet::Functions.create_function} # method. It specifies the name to use when calling the function in the puppet # language, or from other functions. # # The implementation methods are ruby methods (there can be one or more) that # provide that actual implementation of the function's behavior. In the # simplest case the name of the function (excluding any namespace) and the name # of the method are the same. When that is done no other parts (signatures and # dispatches) need to be used. # # Signatures are a way of specifying the types of the function's parameters. # The types of any arguments will be checked against the types declared in the # signature and an error will be produced if they don't match. The types are # defined by using the same syntax for types as in the puppet language. # # Dispatches are how signatures and implementation methods are tied together. # When the function is called, puppet searches the signatures for one that # matches the supplied arguments. Each signature is part of a dispatch, which # specifies the method that should be called for that signature. When a # matching signature is found, the corresponding method is called. # # Special dispatches designed to create error messages for an argument mismatch # can be added using the keyword `argument_mismatch` instead of `dispatch`. The # method appointed by an `argument_mismatch` will be called with arguments # just like a normal `dispatch` would, but the method must produce a string. # The string is then used as the message in the `ArgumentError` that is raised # when the method returns. A block parameter can be given, but it is not # propagated in the method call. # # Documentation for the function should be placed as comments to the # implementation method(s). # # @todo Documentation for individual instances of these new functions is not # yet tied into the puppet doc system. # # @example Dispatching to different methods by type # Puppet::Functions.create_function('math::min') do # dispatch :numeric_min do # param 'Numeric', :a # param 'Numeric', :b # end # # dispatch :string_min do # param 'String', :a # param 'String', :b # end # # def numeric_min(a, b) # a <= b ? a : b # end # # def string_min(a, b) # a.downcase <= b.downcase ? a : b # end # end # # @example Using an argument mismatch handler # Puppet::Functions.create_function('math::min') do # dispatch :numeric_min do # param 'Numeric', :a # param 'Numeric', :b # end # # argument_mismatch :on_error do # param 'Any', :a # param 'Any', :b # end # # def numeric_min(a, b) # a <= b ? a : b # end # # def on_error(a, b) # 'both arguments must be of type Numeric' # end # end # # Specifying Signatures # --- # # If nothing is specified, the number of arguments given to the function must # be the same as the number of parameters, and all of the parameters are of # type 'Any'. # # The following methods can be used to define a parameter # # - _param_ - the argument must be given in the call. # - _optional_param_ - the argument may be missing in the call. May not be followed by a required parameter # - _repeated_param_ - the type specifies a repeating type that occurs 0 to "infinite" number of times. It may only appear last or just before a block parameter. # - _block_param_ - a block must be given in the call. May only appear last. # - _optional_block_param_ - a block may be given in the call. May only appear last. # # The method name _required_param_ is an alias for _param_ and _required_block_param_ is an alias for _block_param_ # # A parameter definition takes 2 arguments: # - _type_ A string that must conform to a type in the puppet language # - _name_ A symbol denoting the parameter name # # Both arguments are optional when defining a block parameter. The _type_ defaults to "Callable" # and the _name_ to :block. # # Note that the dispatch definition is used to match arguments given in a call to the function with the defined # parameters. It then dispatches the call to the implementation method simply passing the given arguments on to # that method without any further processing and it is the responsibility of that method's implementor to ensure # that it can handle those arguments. # # @example Variable number of arguments # Puppet::Functions.create_function('foo') do # dispatch :foo do # param 'Numeric', :first # repeated_param 'Numeric', :values # end # # def foo(first, *values) # # do something # end # end # # There is no requirement for direct mapping between parameter definitions and the parameters in the # receiving implementation method so the following example is also legal. Here the dispatch will ensure # that `*values` in the receiver will be an array with at least one entry of type String and that any # remaining entries are of type Numeric: # # @example Inexact mapping or parameters # Puppet::Functions.create_function('foo') do # dispatch :foo do # param 'String', :first # repeated_param 'Numeric', :values # end # # def foo(*values) # # do something # end # end # # Access to Scope # --- # In general, functions should not need access to scope; they should be # written to act on their given input only. If they absolutely must look up # variable values, they should do so via the closure scope (the scope where # they are defined) - this is done by calling `closure_scope()`. # # Calling other Functions # --- # Calling other functions by name is directly supported via # {Puppet::Pops::Functions::Function#call_function}. This allows a function to # call other functions visible from its loader. # # @api public module Puppet::Functions # @param func_name [String, Symbol] a simple or qualified function name # @param block [Proc] the block that defines the methods and dispatch of the # Function to create # @return [Class<Function>] the newly created Function class # # @api public def self.create_function(func_name, function_base = Function, &block) # Ruby < 2.1.0 does not have method on Binding, can only do eval # and it will fail unless protected with an if defined? if the local # variable does not exist in the block's binder. # loader = block.binding.eval('loader_injected_arg if defined?(loader_injected_arg)') create_loaded_function(func_name, loader, function_base, &block) rescue StandardError => e raise ArgumentError, _("Function Load Error for function '%{function_name}': %{message}") % { function_name: func_name, message: e.message } end # Creates a function in, or in a local loader under the given loader. # This method should only be used when manually creating functions # for the sake of testing. Functions that are autoloaded should # always use the `create_function` method and the autoloader will supply # the correct loader. # # @param func_name [String, Symbol] a simple or qualified function name # @param loader [Puppet::Pops::Loaders::Loader] the loader loading the function # @param block [Proc] the block that defines the methods and dispatch of the # Function to create # @return [Class<Function>] the newly created Function class # # @api public def self.create_loaded_function(func_name, loader, function_base = Function, &block) if function_base.ancestors.none? { |s| s == Puppet::Pops::Functions::Function } raise ArgumentError, _("Functions must be based on Puppet::Pops::Functions::Function. Got %{function_base}") % { function_base: function_base } end func_name = func_name.to_s # Creates an anonymous class to represent the function # The idea being that it is garbage collected when there are no more # references to it. # # (Do not give the class the block here, as instance variables should be set first) the_class = Class.new(function_base) unless loader.nil? the_class.instance_variable_set(:'@loader', loader.private_loader) end # Make the anonymous class appear to have the class-name <func_name> # Even if this class is not bound to such a symbol in a global ruby scope and # must be resolved via the loader. # This also overrides any attempt to define a name method in the given block # (Since it redefines it) # # TODO, enforce name in lower case (to further make it stand out since Ruby # class names are upper case) # the_class.instance_eval do @func_name = func_name def name @func_name end def loader @loader end end # The given block can now be evaluated and have access to name and loader # the_class.class_eval(&block) # Automatically create an object dispatcher based on introspection if the # loaded user code did not define any dispatchers. Fail if function name # does not match a given method name in user code. # if the_class.dispatcher.empty? simple_name = func_name.split(/::/)[-1] type, names = default_dispatcher(the_class, simple_name) last_captures_rest = (type.size_range[1] == Float::INFINITY) the_class.dispatcher.add(Puppet::Pops::Functions::Dispatch.new(type, simple_name, names, last_captures_rest)) end # The function class is returned as the result of the create function method the_class end # Creates a default dispatcher configured from a method with the same name as the function # # @api private def self.default_dispatcher(the_class, func_name) unless the_class.method_defined?(func_name) raise ArgumentError, _("Function Creation Error, cannot create a default dispatcher for function '%{func_name}', no method with this name found") % { func_name: func_name } end any_signature(*min_max_param(the_class.instance_method(func_name))) end # @api private def self.min_max_param(method) result = { :req => 0, :opt => 0, :rest => 0 } # count per parameter kind, and get array of names names = method.parameters.map { |p| result[p[0]] += 1; p[1].to_s } from = result[:req] to = result[:rest] > 0 ? :default : from + result[:opt] [from, to, names] end # Construct a signature consisting of Object type, with min, and max, and given names. # (there is only one type entry). # # @api private def self.any_signature(from, to, names) # Construct the type for the signature # Tuple[Object, from, to] param_types = Puppet::Pops::Types::PTupleType.new([Puppet::Pops::Types::PAnyType::DEFAULT], Puppet::Pops::Types::PIntegerType.new(from, to)) [Puppet::Pops::Types::PCallableType.new(param_types), names] end # Function # === # This class is the base class for all Puppet 4x Function API functions. A # specialized class is created for each puppet function. # # @api public class Function < Puppet::Pops::Functions::Function # @api private def self.builder DispatcherBuilder.new(dispatcher, Puppet::Pops::Types::PCallableType::DEFAULT, loader) end # Dispatch any calls that match the signature to the provided method name. # # @param meth_name [Symbol] The name of the implementation method to call # when the signature defined in the block matches the arguments to a call # to the function. # @return [Void] # # @api public def self.dispatch(meth_name, &block) builder().instance_eval do dispatch(meth_name, false, &block) end end # Like `dispatch` but used for a specific type of argument mismatch. Will not be include in the list of valid # parameter overloads for the function. # # @param meth_name [Symbol] The name of the implementation method to call # when the signature defined in the block matches the arguments to a call # to the function. # @return [Void] # # @api public def self.argument_mismatch(meth_name, &block) builder().instance_eval do dispatch(meth_name, true, &block) end end # Allows types local to the function to be defined to ease the use of complex types # in a 4.x function. Within the given block, calls to `type` can be made with a string # 'AliasType = ExistingType` can be made to define aliases. The defined aliases are # available for further aliases, and in all dispatchers. # # @since 4.5.0 # @api public # def self.local_types(&block) if loader.nil? raise ArgumentError, _("No loader present. Call create_loaded_function(:myname, loader,...), instead of 'create_function' if running tests") end aliases = LocalTypeAliasesBuilder.new(loader, name) aliases.instance_eval(&block) # Add the loaded types to the builder aliases.local_types.each do |type_alias_expr| # Bind the type alias to the local_loader using the alias t = Puppet::Pops::Loader::TypeDefinitionInstantiator.create_from_model(type_alias_expr, aliases.loader) # Also define a method for convenient access to the defined type alias. # Since initial capital letter in Ruby means a Constant these names use a prefix of # `type`. As an example, the type 'MyType' is accessed by calling `type_MyType`. define_method("type_#{t.name}") { t } end # Store the loader in the class @loader = aliases.loader end # Creates a new function instance in the given closure scope (visibility to variables), and a loader # (visibility to other definitions). The created function will either use the `given_loader` or # (if it has local type aliases) a loader that was constructed from the loader used when loading # the function's class. # # TODO: It would be of value to get rid of the second parameter here, but that would break API. # def self.new(closure_scope, given_loader) super(closure_scope, @loader || given_loader) end end # Base class for all functions implemented in the puppet language class PuppetFunction < Function def self.init_dispatch(a_closure) # A closure is compatible with a dispatcher - they are both callable signatures dispatcher.add(a_closure) end end # Public api methods of the DispatcherBuilder are available within dispatch() # blocks declared in a Puppet::Function.create_function() call. # # @api public class DispatcherBuilder attr_reader :loader # @api private def initialize(dispatcher, all_callables, loader) @all_callables = all_callables @dispatcher = dispatcher @loader = loader end # Defines a required positional parameter with _type_ and _name_. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def param(type, name) internal_param(type, name) raise ArgumentError, _('A required parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max += 1 end alias required_param param # Defines an optional positional parameter with _type_ and _name_. # May not be followed by a required parameter. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def optional_param(type, name) internal_param(type, name) @max += 1 end # Defines a repeated positional parameter with _type_ and _name_ that may occur 0 to "infinite" number of times. # It may only appear last or just before a block parameter. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def repeated_param(type, name) internal_param(type, name, true) @max = :default end alias optional_repeated_param repeated_param # Defines a repeated positional parameter with _type_ and _name_ that may occur 1 to "infinite" number of times. # It may only appear last or just before a block parameter. # # @param type [String] The type specification for the parameter. # @param name [Symbol] The name of the parameter. This is primarily used # for error message output and does not have to match an implementation # method parameter. # @return [Void] # # @api public def required_repeated_param(type, name) internal_param(type, name, true) raise ArgumentError, _('A required repeated parameter cannot be added after an optional parameter') if @min != @max @min += 1 @max = :default end # Defines one required block parameter that may appear last. If type and name is missing the # default type is "Callable", and the name is "block". If only one # parameter is given, then that is the name and the type is "Callable". # # @api public def block_param(*type_and_name) case type_and_name.size when 0 type = @all_callables name = :block when 1 type = @all_callables name = type_and_name[0] when 2 type, name = type_and_name type = Puppet::Pops::Types::TypeParser.singleton.parse(type, loader) unless type.is_a?(Puppet::Pops::Types::PAnyType) else raise ArgumentError, _("block_param accepts max 2 arguments (type, name), got %{size}.") % { size: type_and_name.size } end unless Puppet::Pops::Types::TypeCalculator.is_kind_of_callable?(type, false) raise ArgumentError, _("Expected PCallableType or PVariantType thereof, got %{type_class}") % { type_class: type.class } end unless name.is_a?(Symbol) raise ArgumentError, _("Expected block_param name to be a Symbol, got %{name_class}") % { name_class: name.class } end if @block_type.nil? @block_type = type @block_name = name else raise ArgumentError, _('Attempt to redefine block') end end alias required_block_param block_param # Defines one optional block parameter that may appear last. If type or name is missing the # defaults are "any callable", and the name is "block". The implementor of the dispatch target # must use block = nil when it is optional (or an error is raised when the call is made). # # @api public def optional_block_param(*type_and_name) # same as required, only wrap the result in an optional type required_block_param(*type_and_name) @block_type = Puppet::Pops::Types::TypeFactory.optional(@block_type) end # Defines the return type. Defaults to 'Any' # @param [String] type a reference to a Puppet Data Type # # @api public def return_type(type) unless type.is_a?(String) || type.is_a?(Puppet::Pops::Types::PAnyType) raise ArgumentError, _("Argument to 'return_type' must be a String reference to a Puppet Data Type. Got %{type_class}") % { type_class: type.class } end @return_type = type end private # @api private def internal_param(type, name, repeat = false) raise ArgumentError, _('Parameters cannot be added after a block parameter') unless @block_type.nil? raise ArgumentError, _('Parameters cannot be added after a repeated parameter') if @max == :default if name.is_a?(String) raise ArgumentError, _("Parameter name argument must be a Symbol. Got %{name_class}") % { name_class: name.class } end if type.is_a?(String) || type.is_a?(Puppet::Pops::Types::PAnyType) @types << type @names << name # mark what should be picked for this position when dispatching if repeat @weaving << -@names.size() else @weaving << @names.size() - 1 end else raise ArgumentError, _("Parameter 'type' must be a String reference to a Puppet Data Type. Got %{type_class}") % { type_class: type.class } end end # @api private def dispatch(meth_name, argument_mismatch_handler, &block) # an array of either an index into names/types, or an array with # injection information [type, name, injection_name] used when the call # is being made to weave injections into the given arguments. # @types = [] @names = [] @weaving = [] @injections = [] @min = 0 @max = 0 @block_type = nil @block_name = nil @return_type = nil @argument_mismatch_hander = argument_mismatch_handler instance_eval(&block) callable_t = create_callable(@types, @block_type, @return_type, @min, @max) @dispatcher.add(Puppet::Pops::Functions::Dispatch.new(callable_t, meth_name, @names, @max == :default, @block_name, @injections, @weaving, @argument_mismatch_hander)) end # Handles creation of a callable type from strings specifications of puppet # types and allows the min/max occurs of the given types to be given as one # or two integer values at the end. The given block_type should be # Optional[Callable], Callable, or nil. # # @api private def create_callable(types, block_type, return_type, from, to) mapped_types = types.map do |t| t.is_a?(Puppet::Pops::Types::PAnyType) ? t : internal_type_parse(t, loader) end param_types = Puppet::Pops::Types::PTupleType.new(mapped_types, from > 0 && from == to ? nil : Puppet::Pops::Types::PIntegerType.new(from, to)) return_type = internal_type_parse(return_type, loader) unless return_type.nil? || return_type.is_a?(Puppet::Pops::Types::PAnyType) Puppet::Pops::Types::PCallableType.new(param_types, block_type, return_type) end def internal_type_parse(type_string, loader) Puppet::Pops::Types::TypeParser.singleton.parse(type_string, loader) rescue StandardError => e raise ArgumentError, _("Parsing of type string '\"%{type_string}\"' failed with message: <%{message}>.\n") % { type_string: type_string, message: e.message } end private :internal_type_parse end # The LocalTypeAliasBuilder is used by the 'local_types' method to collect the individual # type aliases given by the function's author. # class LocalTypeAliasesBuilder attr_reader :local_types, :parser, :loader def initialize(loader, name) @loader = Puppet::Pops::Loader::PredefinedLoader.new(loader, :"local_function_#{name}", loader.environment) @local_types = [] # get the shared parser used by puppet's compiler @parser = Puppet::Pops::Parser::EvaluatingParser.singleton() end # Defines a local type alias, the given string should be a Puppet Language type alias expression # in string form without the leading 'type' keyword. # Calls to local_type must be made before the first parameter definition or an error will # be raised. # # @param assignment_string [String] a string on the form 'AliasType = ExistingType' # @api public # def type(assignment_string) # Get location to use in case of error - this produces ruby filename and where call to 'type' occurred # but strips off the rest of the internal "where" as it is not meaningful to user. # rb_location = caller(1, 1).first begin result = parser.parse_string("type #{assignment_string}", nil) rescue StandardError => e rb_location = rb_location.gsub(/:in.*$/, '') # Create a meaningful location for parse errors - show both what went wrong with the parsing # and in which ruby file it was found. raise ArgumentError, _("Parsing of 'type \"%{assignment_string}\"' failed with message: <%{message}>.\n" \ "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, message: e.message, ruby_file_location: rb_location } end unless result.body.is_a?(Puppet::Pops::Model::TypeAlias) rb_location = rb_location.gsub(/:in.*$/, '') raise ArgumentError, _("Expected a type alias assignment on the form 'AliasType = T', got '%{assignment_string}'.\n" \ "Called from <%{ruby_file_location}>") % { assignment_string: assignment_string, ruby_file_location: rb_location } end @local_types << result.body end end # @note WARNING: This style of creating functions is not public. It is a system # under development that will be used for creating "system" functions. # # This is a private, internal, system for creating functions. It supports # everything that the public function definition system supports as well as a # few extra features such as injection of well known parameters. # # @api private class InternalFunction < Function # @api private def self.builder InternalDispatchBuilder.new(dispatcher, Puppet::Pops::Types::PCallableType::DEFAULT, loader) end # Allows the implementation of a function to call other functions by name and pass the caller # scope. The callable functions are those visible to the same loader that loaded this function # (the calling function). # # @param scope [Puppet::Parser::Scope] The caller scope # @param function_name [String] The name of the function # @param *args [Object] splat of arguments # @return [Object] The result returned by the called function # # @api public def call_function_with_scope(scope, function_name, *args, &block) internal_call_function(scope, function_name, args, &block) end end class Function3x < InternalFunction # Table of optimized parameter names - 0 to 5 parameters PARAM_NAMES = [ [], ['p0'].freeze, %w[p0 p1].freeze, %w[p0 p1 p2].freeze, %w[p0 p1 p2 p3].freeze, %w[p0 p1 p2 p3 p4].freeze ] # Creates an anonymous Function3x class that wraps a 3x function # # @api private def self.create_function(func_name, func_info, loader) func_name = func_name.to_s # Creates an anonymous class to represent the function # The idea being that it is garbage collected when there are no more # references to it. # # (Do not give the class the block here, as instance variables should be set first) the_class = Class.new(Function3x) unless loader.nil? the_class.instance_variable_set(:'@loader', loader.private_loader) end the_class.instance_variable_set(:'@func_name', func_name) the_class.instance_variable_set(:'@method3x', :"function_#{func_name}") # Make the anonymous class appear to have the class-name <func_name> # Even if this class is not bound to such a symbol in a global ruby scope and # must be resolved via the loader. # This also overrides any attempt to define a name method in the given block # (Since it redefines it) # the_class.instance_eval do def name @func_name end def loader @loader end def method3x @method3x end end # Add the method that is called - it simply delegates to # the 3.x function by calling it via the calling scope using the @method3x symbol # :"function_#{name}". # # When function is not an rvalue function, make sure it produces nil # the_class.class_eval do # Bypasses making the call via the dispatcher to make sure errors # are reported exactly the same way as in 3x. The dispatcher is still needed as it is # used to support other features than calling. # def call(scope, *args, &block) result = catch(:return) do mapped_args = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.map_args(args, scope, '') # this is the scope.function_xxx(...) call return scope.send(self.class.method3x, mapped_args) end result.value rescue Puppet::Pops::Evaluator::Next => jumper begin throw :next, jumper.value rescue Puppet::Parser::Scope::UNCAUGHT_THROW_EXCEPTION raise Puppet::ParseError.new("next() from context where this is illegal", jumper.file, jumper.line) end rescue Puppet::Pops::Evaluator::Return => jumper begin throw :return, jumper rescue Puppet::Parser::Scope::UNCAUGHT_THROW_EXCEPTION raise Puppet::ParseError.new("return() from context where this is illegal", jumper.file, jumper.line) end end end # Create a dispatcher based on func_info type, names = Puppet::Functions.any_signature(*from_to_names(func_info)) last_captures_rest = (type.size_range[1] == Float::INFINITY) # The method '3x_function' here is a dummy as the dispatcher is not used for calling, only for information. the_class.dispatcher.add(Puppet::Pops::Functions::Dispatch.new(type, '3x_function', names, last_captures_rest)) # The function class is returned as the result of the create function method the_class end # Compute min and max number of arguments and a list of constructed # parameter names p0 - pn (since there are no parameter names in 3x functions). # # @api private def self.from_to_names(func_info) arity = func_info[:arity] if arity.nil? arity = -1 end if arity < 0 from = -arity - 1 # arity -1 is 0 min param, -2 is min 1 param to = :default # infinite range count = -arity # the number of named parameters else count = from = to = arity end # Names of parameters, up to 5 are optimized and use frozen version # Note that (0..count-1) produces expected empty array for count == 0, 0-n for count >= 1 names = count <= 5 ? PARAM_NAMES[count] : (0..count - 1).map { |n| "p#{n}" } [from, to, names] end end # Injection and Weaving of parameters # --- # It is possible to inject and weave a set of well known parameters into a call. # These extra parameters are not part of the parameters passed from the Puppet # logic, and they can not be overridden by parameters given as arguments in the # call. They are invisible to the Puppet Language. # # @example using injected parameters # Puppet::Functions.create_function('test') do # dispatch :test do # param 'Scalar', 'a' # param 'Scalar', 'b' # scope_param # end # def test(a, b, scope) # a > b ? scope['a'] : scope['b'] # end # end # # The function in the example above is called like this: # # test(10, 20) # # @api private class InternalDispatchBuilder < DispatcherBuilder # Inject parameter for `Puppet::Parser::Scope` def scope_param
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/info_service.rb
lib/puppet/info_service.rb
# frozen_string_literal: true module Puppet::InfoService require_relative 'info_service/class_information_service' require_relative 'info_service/task_information_service' require_relative 'info_service/plan_information_service' def self.classes_per_environment(env_file_hash) Puppet::InfoService::ClassInformationService.new.classes_per_environment(env_file_hash) end def self.tasks_per_environment(environment_name) Puppet::InfoService::TaskInformationService.tasks_per_environment(environment_name) end def self.task_data(environment_name, module_name, task_name) Puppet::InfoService::TaskInformationService.task_data(environment_name, module_name, task_name) end def self.plans_per_environment(environment_name) Puppet::InfoService::PlanInformationService.plans_per_environment(environment_name) end def self.plan_data(environment_name, module_name, plan_name) Puppet::InfoService::PlanInformationService.plan_data(environment_name, module_name, plan_name) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/data_binding.rb
lib/puppet/data_binding.rb
# frozen_string_literal: true require_relative '../puppet/indirector' # A class for managing data lookups class Puppet::DataBinding # Set up indirection, so that data can be looked for in the compiler extend Puppet::Indirector indirects(:data_binding, :terminus_setting => :data_binding_terminus, :doc => "Where to find external data bindings.") class LookupError < Puppet::PreformattedError; end class RecursiveLookupError < Puppet::DataBinding::LookupError; 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/configurer.rb
lib/puppet/configurer.rb
# frozen_string_literal: true # The client for interacting with the puppetmaster config server. require 'timeout' require_relative '../puppet/util' require 'securerandom' # require 'puppet/parser/script_compiler' require_relative '../puppet/pops/evaluator/deferred_resolver' class Puppet::Configurer require_relative 'configurer/fact_handler' require_relative 'configurer/plugin_handler' include Puppet::Configurer::FactHandler # For benchmarking include Puppet::Util attr_reader :environment # Provide more helpful strings to the logging that the Agent does def self.to_s _("Puppet configuration client") end def self.should_pluginsync? if Puppet[:use_cached_catalog] false else true end end def execute_postrun_command execute_from_setting(:postrun_command) end def execute_prerun_command execute_from_setting(:prerun_command) end # Initialize and load storage def init_storage Puppet::Util::Storage.load rescue => detail Puppet.log_exception(detail, _("Removing corrupt state file %{file}: %{detail}") % { file: Puppet[:statefile], detail: detail }) begin Puppet::FileSystem.unlink(Puppet[:statefile]) retry rescue => detail raise Puppet::Error.new(_("Cannot remove %{file}: %{detail}") % { file: Puppet[:statefile], detail: detail }, detail) end end def initialize(transaction_uuid = nil, job_id = nil) @running = false @splayed = false @running_failure = false @cached_catalog_status = 'not_used' @environment = Puppet[:environment] @transaction_uuid = transaction_uuid || SecureRandom.uuid @job_id = job_id @static_catalog = true @checksum_type = Puppet[:supported_checksum_types] @handler = Puppet::Configurer::PluginHandler.new() end # Get the remote catalog, yo. Returns nil if no catalog can be found. def retrieve_catalog(facts, query_options) query_options ||= {} if Puppet[:use_cached_catalog] || @running_failure result = retrieve_catalog_from_cache(query_options) end if result if Puppet[:use_cached_catalog] @cached_catalog_status = 'explicitly_requested' elsif @running_failure @cached_catalog_status = 'on_failure' end Puppet.info _("Using cached catalog from environment '%{environment}'") % { environment: result.environment } else result = retrieve_new_catalog(facts, query_options) unless result unless Puppet[:usecacheonfailure] Puppet.warning _("Not using cache on failed catalog") return nil end result = retrieve_catalog_from_cache(query_options) if result # don't use use cached catalog if it doesn't match server specified environment if result.environment != @environment Puppet.err _("Not using cached catalog because its environment '%{catalog_env}' does not match '%{local_env}'") % { catalog_env: result.environment, local_env: @environment } return nil end @cached_catalog_status = 'on_failure' Puppet.info _("Using cached catalog from environment '%{catalog_env}'") % { catalog_env: result.environment } end end end result end # Convert a plain resource catalog into our full host catalog. def convert_catalog(result, duration, facts, options = {}) catalog = nil catalog_conversion_time = thinmark do # Will mutate the result and replace all Deferred values with resolved values if facts Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(facts, result, Puppet.lookup(:current_environment), Puppet[:preprocess_deferred]) end catalog = result.to_ral catalog.finalize catalog.retrieval_duration = duration if Puppet[:write_catalog_summary] catalog.write_class_file catalog.write_resource_file end end options[:report].add_times(:convert_catalog, catalog_conversion_time) if options[:report] catalog end def warn_number_of_facts(size, max_number) Puppet.warning _("The current total number of fact values: %{size} exceeds the fact values limit: %{max_size}") % { size: size, max_size: max_number } end def warn_fact_name_length(name, max_length, fact_name_length) Puppet.warning _("Fact %{name} with length: %{length} exceeds the fact name length limit: %{limit}") % { name: name, length: fact_name_length, limit: max_length } end def warn_number_of_top_level_facts(size, max_number) Puppet.warning _("The current number of top level facts: %{size} exceeds the top facts limit: %{max_size}") % { size: size, max_size: max_number } end def warn_fact_value_length(name, value, max_length) Puppet.warning _("Fact %{name} with value %{value} with the value length: %{length} exceeds the value length limit: %{max_length}") % { name: name, value: value, length: value.to_s.bytesize, max_length: max_length } end def warn_fact_payload_size(payload, max_size) Puppet.warning _("Payload with the current size of: %{payload} exceeds the payload size limit: %{max_size}") % { payload: payload, max_size: max_size } end def check_fact_name_length(fact_path, number_of_dots) max_length = Puppet[:fact_name_length_soft_limit] return if max_length.zero? name_without_dots = fact_path.join() # rough byte size estimations of fact path as a postgresql btree index size_as_btree_index = 8 + (number_of_dots * 2) + name_without_dots.to_s.bytesize warn_fact_name_length(fact_path.join('.'), max_length, size_as_btree_index) if size_as_btree_index > max_length end def check_fact_values_length(name, values) max_length = Puppet[:fact_value_length_soft_limit] return if max_length.zero? warn_fact_value_length(name, values, max_length) if values.to_s.bytesize > max_length end def check_top_level_number_limit(size) max_size = Puppet[:top_level_facts_soft_limit] return if max_size.zero? warn_number_of_top_level_facts(size, max_size) if size > max_size end def check_total_number_limit(size) max_size = Puppet[:number_of_facts_soft_limit] return if max_size.zero? warn_number_of_facts(size, max_size) if size > max_size end def check_payload_size(payload) max_size = Puppet[:payload_soft_limit] return if max_size.zero? warn_fact_payload_size(payload, max_size) if payload > max_size Puppet.debug _("The size of the payload is %{payload}") % { payload: payload } end def parse_fact_name_and_value_limits(object, path = []) case object when Hash object.each do |key, value| path.push(key) parse_fact_name_and_value_limits(value, path) path.pop end when Array object.each_with_index do |e, idx| path.push(idx) parse_fact_name_and_value_limits(e, path) path.pop end else check_fact_name_length(path, path.size) check_fact_values_length(path.join('.'), object) @number_of_facts += 1 end end def check_facts_limits(facts) @number_of_facts = 0 check_top_level_number_limit(facts.size) parse_fact_name_and_value_limits(facts) check_total_number_limit(@number_of_facts) Puppet.debug _("The total number of facts registered is %{number_of_facts}") % { number_of_facts: @number_of_facts } end def get_facts(options) if options[:pluginsync] plugin_sync_time = thinmark do remote_environment_for_plugins = Puppet::Node::Environment.remote(@environment) download_plugins(remote_environment_for_plugins) Puppet::GettextConfig.reset_text_domain('agent') Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir]) end options[:report].add_times(:plugin_sync, plugin_sync_time) if options[:report] end facts_hash = {} facts = nil if Puppet::Resource::Catalog.indirection.terminus_class == :rest # This is a bit complicated. We need the serialized and escaped facts, # and we need to know which format they're encoded in. Thus, we # get a hash with both of these pieces of information. # # facts_for_uploading may set Puppet[:node_name_value] as a side effect facter_time = thinmark do facts = find_facts check_facts_limits(facts.to_data_hash['values']) facts_hash = encode_facts(facts) # encode for uploading # was: facts_for_uploading check_payload_size(facts_hash[:facts].bytesize) end options[:report].add_times(:fact_generation, facter_time) if options[:report] end [facts_hash, facts] end def prepare_and_retrieve_catalog(cached_catalog, facts, options, query_options) # set report host name now that we have the fact options[:report].host = Puppet[:node_name_value] query_options[:transaction_uuid] = @transaction_uuid query_options[:job_id] = @job_id query_options[:static_catalog] = @static_catalog # Query params don't enforce ordered evaluation, so munge this list into a # dot-separated string. query_options[:checksum_type] = @checksum_type.join('.') # apply passes in ral catalog catalog = cached_catalog || options[:catalog] unless catalog # retrieve_catalog returns resource catalog catalog = retrieve_catalog(facts, query_options) Puppet.err _("Could not retrieve catalog; skipping run") unless catalog end catalog end def prepare_and_retrieve_catalog_from_cache(options = {}) result = retrieve_catalog_from_cache({ :transaction_uuid => @transaction_uuid, :static_catalog => @static_catalog }) Puppet.info _("Using cached catalog from environment '%{catalog_env}'") % { catalog_env: result.environment } if result result end # Apply supplied catalog and return associated application report def apply_catalog(catalog, options) report = options[:report] report.configuration_version = catalog.version benchmark(:notice, _("Applied catalog in %{seconds} seconds")) do apply_catalog_time = thinmark do catalog.apply(options) end options[:report].add_times(:catalog_application, apply_catalog_time) end report end # The code that actually runs the catalog. # This just passes any options on to the catalog, # which accepts :tags and :ignoreschedules. def run(options = {}) # We create the report pre-populated with default settings for # environment and transaction_uuid very early, this is to ensure # they are sent regardless of any catalog compilation failures or # exceptions. options[:report] ||= Puppet::Transaction::Report.new(nil, @environment, @transaction_uuid, @job_id, options[:start_time] || Time.now) report = options[:report] init_storage Puppet::Util::Log.newdestination(report) completed = nil begin # Skip failover logic if the server_list setting is empty do_failover = Puppet.settings[:server_list] && !Puppet.settings[:server_list].empty? # When we are passed a catalog, that means we're in apply # mode. We shouldn't try to do any failover in that case. if options[:catalog].nil? && do_failover server, port = find_functional_server if server.nil? detail = _("Could not select a functional puppet server from server_list: '%{server_list}'") % { server_list: Puppet.settings.value(:server_list, Puppet[:environment].to_sym, true) } if Puppet[:usecacheonfailure] options[:pluginsync] = false @running_failure = true server = Puppet[:server_list].first[0] port = Puppet[:server_list].first[1] || Puppet[:serverport] Puppet.err(detail) else raise Puppet::Error, detail end else # TRANSLATORS 'server_list' is the name of a setting and should not be translated Puppet.debug _("Selected puppet server from the `server_list` setting: %{server}:%{port}") % { server: server, port: port } report.server_used = "#{server}:#{port}" end Puppet.override(server: server, serverport: port) do completed = run_internal(options) end else completed = run_internal(options) end ensure # we may sleep for awhile, close connections now Puppet.runtime[:http].close end completed ? report.exit_status : nil end def run_internal(options) report = options[:report] report.initial_environment = Puppet[:environment] if options[:start_time] startup_time = Time.now - options[:start_time] report.add_times(:startup_time, startup_time) end # If a cached catalog is explicitly requested, attempt to retrieve it. Skip the node request, # don't pluginsync and switch to the catalog's environment if we successfully retrieve it. if Puppet[:use_cached_catalog] Puppet::GettextConfig.reset_text_domain('agent') Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir]) cached_catalog = prepare_and_retrieve_catalog_from_cache(options) if cached_catalog @cached_catalog_status = 'explicitly_requested' if @environment != cached_catalog.environment && !Puppet[:strict_environment_mode] Puppet.notice _("Local environment: '%{local_env}' doesn't match the environment of the cached catalog '%{catalog_env}', switching agent to '%{catalog_env}'.") % { local_env: @environment, catalog_env: cached_catalog.environment } @environment = cached_catalog.environment end report.environment = @environment else # Don't try to retrieve a catalog from the cache again after we've already # failed to do so the first time. Puppet[:use_cached_catalog] = false Puppet[:usecacheonfailure] = false options[:pluginsync] = Puppet::Configurer.should_pluginsync? end end begin unless Puppet[:node_name_fact].empty? query_options, facts = get_facts(options) end configured_environment = Puppet[:environment] if Puppet.settings.set_by_config?(:environment) # We only need to find out the environment to run in if we don't already have a catalog unless cached_catalog || options[:catalog] || Puppet.settings.set_by_cli?(:environment) || Puppet[:strict_environment_mode] Puppet.debug(_("Environment not passed via CLI and no catalog was given, attempting to find out the last server-specified environment")) initial_environment, loaded_last_environment = last_server_specified_environment unless Puppet[:use_last_environment] && loaded_last_environment Puppet.debug(_("Requesting environment from the server")) initial_environment = current_server_specified_environment(@environment, configured_environment, options) end if initial_environment @environment = initial_environment report.environment = initial_environment push_current_environment_and_loaders else Puppet.debug(_("Could not find a usable environment in the lastrunfile. Either the file does not exist, does not have the required keys, or the values of 'initial_environment' and 'converged_environment' are identical.")) end end Puppet.info _("Using environment '%{env}'") % { env: @environment } # This is to maintain compatibility with anyone using this class # aside from agent, apply, device. unless Puppet.lookup(:loaders) { nil } push_current_environment_and_loaders end temp_value = options[:pluginsync] # only validate server environment if pluginsync is requested options[:pluginsync] = valid_server_environment? if options[:pluginsync] query_options, facts = get_facts(options) unless query_options options[:pluginsync] = temp_value query_options[:configured_environment] = configured_environment catalog = prepare_and_retrieve_catalog(cached_catalog, facts, options, query_options) unless catalog return nil end if Puppet[:strict_environment_mode] && catalog.environment != @environment Puppet.err _("Not using catalog because its environment '%{catalog_env}' does not match agent specified environment '%{local_env}' and strict_environment_mode is set") % { catalog_env: catalog.environment, local_env: @environment } return nil end # Here we set the local environment based on what we get from the # catalog. Since a change in environment means a change in facts, and # facts may be used to determine which catalog we get, we need to # rerun the process if the environment is changed. tries = 0 while catalog.environment and !catalog.environment.empty? and catalog.environment != @environment if tries > 3 raise Puppet::Error, _("Catalog environment didn't stabilize after %{tries} fetches, aborting run") % { tries: tries } end Puppet.notice _("Local environment: '%{local_env}' doesn't match server specified environment '%{catalog_env}', restarting agent run with environment '%{catalog_env}'") % { local_env: @environment, catalog_env: catalog.environment } @environment = catalog.environment report.environment = @environment push_current_environment_and_loaders query_options, facts = get_facts(options) query_options[:configured_environment] = configured_environment # if we get here, ignore the cached catalog catalog = prepare_and_retrieve_catalog(nil, facts, options, query_options) return nil unless catalog tries += 1 end # now that environment has converged, convert resource catalog into ral catalog # unless we were given a RAL catalog if !cached_catalog && options[:catalog] ral_catalog = options[:catalog] else # Ordering here matters. We have to resolve deferred resources in the # resource catalog, convert the resource catalog to a RAL catalog (which # triggers type/provider validation), and only if that is successful, # should we cache the *original* resource catalog. However, deferred # evaluation mutates the resource catalog, so we need to make a copy of # it here. If PUP-9323 is ever implemented so that we resolve deferred # resources in the RAL catalog as they are needed, then we could eliminate # this step. catalog_to_cache = Puppet.override(:rich_data => Puppet[:rich_data]) do Puppet::Resource::Catalog.from_data_hash(catalog.to_data_hash) end # REMIND @duration is the time spent loading the last catalog, and doesn't # account for things like we failed to download and fell back to the cache ral_catalog = convert_catalog(catalog, @duration, facts, options) # Validation succeeded, so commit the `catalog_to_cache` for non-noop runs. Don't # commit `catalog` since it contains the result of deferred evaluation. Ideally # we'd just copy the downloaded response body, instead of serializing the # in-memory catalog, but that's hard due to the indirector. indirection = Puppet::Resource::Catalog.indirection if !Puppet[:noop] && indirection.cache? request = indirection.request(:save, nil, catalog_to_cache, environment: Puppet::Node::Environment.remote(catalog_to_cache.environment)) Puppet.info("Caching catalog for #{request.key}") indirection.cache.save(request) end end execute_prerun_command or return nil options[:report].code_id = ral_catalog.code_id options[:report].catalog_uuid = ral_catalog.catalog_uuid options[:report].cached_catalog_status = @cached_catalog_status apply_catalog(ral_catalog, options) true rescue => detail Puppet.log_exception(detail, _("Failed to apply catalog: %{detail}") % { detail: detail }) nil ensure execute_postrun_command or return nil # rubocop:disable Lint/EnsureReturn end ensure if Puppet[:resubmit_facts] # TODO: Should mark the report as "failed" if an error occurs and # resubmit_facts returns false. There is currently no API for this. resubmit_facts_time = thinmark { resubmit_facts } report.add_times(:resubmit_facts, resubmit_facts_time) end report.cached_catalog_status ||= @cached_catalog_status report.add_times(:total, Time.now - report.time) report.finalize_report Puppet::Util::Log.close(report) send_report(report) Puppet.pop_context end private :run_internal def valid_server_environment? session = Puppet.lookup(:http_session) begin fs = session.route_to(:fileserver) fs.get_file_metadatas(path: URI(Puppet[:pluginsource]).path, recurse: :false, environment: @environment) # rubocop:disable Lint/BooleanSymbol true rescue Puppet::HTTP::ResponseError => detail if detail.response.code == 404 if Puppet[:strict_environment_mode] raise Puppet::Error, _("Environment '%{environment}' not found on server, aborting run.") % { environment: @environment } else Puppet.notice(_("Environment '%{environment}' not found on server, skipping initial pluginsync.") % { environment: @environment }) end else Puppet.log_exception(detail, detail.message) end false rescue => detail Puppet.log_exception(detail, detail.message) false end end def find_functional_server begin session = Puppet.lookup(:http_session) service = session.route_to(:puppet) return [service.url.host, service.url.port] rescue Puppet::HTTP::ResponseError => e Puppet.debug(_("Puppet server %{host}:%{port} is unavailable: %{code} %{reason}") % { host: e.response.url.host, port: e.response.url.port, code: e.response.code, reason: e.response.reason }) rescue => detail # TRANSLATORS 'server_list' is the name of a setting and should not be translated Puppet.debug _("Unable to connect to server from server_list setting: %{detail}") % { detail: detail } end [nil, nil] end private :find_functional_server # # @api private # # Read the last server-specified environment from the lastrunfile. The # environment is considered to be server-specified if the values of # `initial_environment` and `converged_environment` are different. # # @return [String, Boolean] An array containing a string with the environment # read from the lastrunfile in case the server is authoritative, and a # boolean marking whether the last environment was correctly loaded. def last_server_specified_environment return @last_server_specified_environment, @loaded_last_environment if @last_server_specified_environment if Puppet::FileSystem.exist?(Puppet[:lastrunfile]) summary = Puppet::Util::Yaml.safe_load_file(Puppet[:lastrunfile]) return [nil, nil] unless summary['application']['run_mode'] == 'agent' initial_environment = summary['application']['initial_environment'] converged_environment = summary['application']['converged_environment'] @last_server_specified_environment = converged_environment if initial_environment != converged_environment Puppet.debug(_("Successfully loaded last environment from the lastrunfile")) @loaded_last_environment = true end Puppet.debug(_("Found last server-specified environment: %{environment}") % { environment: @last_server_specified_environment }) if @last_server_specified_environment [@last_server_specified_environment, @loaded_last_environment] rescue => detail Puppet.debug(_("Could not find last server-specified environment: %{detail}") % { detail: detail }) [nil, nil] end private :last_server_specified_environment def current_server_specified_environment(current_environment, configured_environment, options) return @server_specified_environment if @server_specified_environment begin node_retr_time = thinmark do node = Puppet::Node.indirection.find(Puppet[:node_name_value], :environment => Puppet::Node::Environment.remote(current_environment), :configured_environment => configured_environment, :ignore_cache => true, :transaction_uuid => @transaction_uuid, :fail_on_404 => true) @server_specified_environment = node.environment_name.to_s if @server_specified_environment != @environment Puppet.notice _("Local environment: '%{local_env}' doesn't match server specified node environment '%{node_env}', switching agent to '%{node_env}'.") % { local_env: @environment, node_env: @server_specified_environment } end end options[:report].add_times(:node_retrieval, node_retr_time) @server_specified_environment rescue => detail Puppet.warning(_("Unable to fetch my node definition, but the agent run will continue:")) Puppet.warning(detail) nil end end private :current_server_specified_environment def send_report(report) puts report.summary if Puppet[:summarize] save_last_run_summary(report) if Puppet[:report] remote = Puppet::Node::Environment.remote(@environment) begin Puppet::Transaction::Report.indirection.save(report, nil, ignore_cache: true, environment: remote) ensure Puppet::Transaction::Report.indirection.save(report, nil, ignore_terminus: true, environment: remote) end end rescue => detail Puppet.log_exception(detail, _("Could not send report: %{detail}") % { detail: detail }) end def save_last_run_summary(report) mode = Puppet.settings.setting(:lastrunfile).mode Puppet::Util.replace_file(Puppet[:lastrunfile], mode) do |fh| fh.print YAML.dump(report.raw_summary) end rescue => detail Puppet.log_exception(detail, _("Could not save last run local report: %{detail}") % { detail: detail }) end # Submit updated facts to the Puppet Server # # This method will clear all current fact values, load a fresh set of # fact data, and then submit it to the Puppet Server. # # @return [true] If fact submission succeeds. # @return [false] If an exception is raised during fact generation or # submission. def resubmit_facts Puppet.runtime[:facter].clear facts = find_facts client = Puppet.runtime[:http] session = client.create_session puppet = session.route_to(:puppet) Puppet.info(_("Uploading facts for %{node} to %{server}") % { node: facts.name, server: puppet.url.hostname }) puppet.put_facts(facts.name, facts: facts, environment: Puppet.lookup(:current_environment).name.to_s) true rescue => detail Puppet.log_exception(detail, _("Failed to submit facts: %{detail}") % { detail: detail }) false end private def execute_from_setting(setting) return true if (command = Puppet[setting]) == "" begin Puppet::Util::Execution.execute([command]) true rescue => detail Puppet.log_exception(detail, _("Could not run command from %{setting}: %{detail}") % { setting: setting, detail: detail }) false end end def push_current_environment_and_loaders new_env = Puppet::Node::Environment.remote(@environment) Puppet.push_context( { :current_environment => new_env, :loaders => Puppet::Pops::Loaders.new(new_env, true) }, "Local node environment #{@environment} for configurer transaction" ) end def retrieve_catalog_from_cache(query_options) result = nil @duration = thinmark do result = Puppet::Resource::Catalog.indirection.find( Puppet[:node_name_value], query_options.merge( :ignore_terminus => true, :environment => Puppet::Node::Environment.remote(@environment) ) ) end result rescue => detail Puppet.log_exception(detail, _("Could not retrieve catalog from cache: %{detail}") % { detail: detail }) nil end def retrieve_new_catalog(facts, query_options) result = nil @duration = thinmark do result = Puppet::Resource::Catalog.indirection.find( Puppet[:node_name_value], query_options.merge( :ignore_cache => true, # don't update cache until after environment converges :ignore_cache_save => true, :environment => Puppet::Node::Environment.remote(@environment), :check_environment => true, :fail_on_404 => true, :facts_for_catalog => facts ) ) end result rescue StandardError => detail Puppet.log_exception(detail, _("Could not retrieve catalog from remote server: %{detail}") % { detail: detail }) nil end def download_plugins(remote_environment_for_plugins) @handler.download_plugins(remote_environment_for_plugins) rescue Puppet::Error => detail if !Puppet[:ignore_plugin_errors] && Puppet[:usecacheonfailure] @running_failure = true else raise 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/application_support.rb
lib/puppet/application_support.rb
# frozen_string_literal: true require 'yaml' require_relative '../puppet' require_relative '../puppet/node/environment' require_relative '../puppet/file_system' require_relative '../puppet/indirector' module Puppet module ApplicationSupport # Pushes a Puppet Context configured with a remote environment for an agent # (one that exists at the master end), and a regular environment for other # modes. The configuration is overridden with options from the command line # before being set in a pushed Puppet Context. # # @param run_mode [Puppet::Util::RunMode] Puppet's current Run Mode. # @param environment_mode [Symbol] optional, Puppet's # current Environment Mode. Defaults to :local # @return [void] # @api private def self.push_application_context(run_mode, environment_mode = :local) Puppet.push_context_global(Puppet.base_context(Puppet.settings), "Update for application settings (#{run_mode})") # This use of configured environment is correct, this is used to establish # the defaults for an application that does not override, or where an override # has not been made from the command line. # configured_environment_name = Puppet[:environment] if run_mode.name == :agent configured_environment = Puppet::Node::Environment.remote(configured_environment_name) elsif environment_mode == :not_required configured_environment = Puppet.lookup(:environments).get(configured_environment_name) || Puppet::Node::Environment.remote(configured_environment_name) else configured_environment = Puppet.lookup(:environments).get!(configured_environment_name) end configured_environment = configured_environment.override_from_commandline(Puppet.settings) # Setup a new context using the app's configuration Puppet.push_context({ :current_environment => configured_environment }, "Update current environment from application's configuration") end # Reads the routes YAML settings from the file specified by Puppet[:route_file] # and resets indirector termini for the current application class if listed. # # For instance, PE uses this to set the master facts terminus # to 'puppetdb' and its cache terminus to 'yaml'. # # @param application_name [String] The name of the current application. # @return [void] # @api private def self.configure_indirector_routes(application_name) route_file = Puppet[:route_file] if Puppet::FileSystem.exist?(route_file) routes = Puppet::Util::Yaml.safe_load_file(route_file, [Symbol]) if routes["server"] && routes["master"] Puppet.warning("Route file #{route_file} contains both server and master route settings.") elsif routes["server"] && !routes["master"] routes["master"] = routes["server"] elsif routes["master"] && !routes["server"] routes["server"] = routes["master"] end application_routes = routes[application_name] Puppet::Indirector.configure_routes(application_routes) if application_routes 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/error.rb
lib/puppet/error.rb
# frozen_string_literal: true module Puppet # The base class for all Puppet errors. It can wrap another exception class Error < RuntimeError attr_accessor :original def initialize(message, original = nil) super(message.scrub) @original = original end end module ExternalFileError # This module implements logging with a filename and line number. Use this # for errors that need to report a location in a non-ruby file that we # parse. attr_accessor :line, :file, :pos, :puppetstack # May be called with 3 arguments for message, file, line, and exception, or # 4 args including the position on the line. # def initialize(message, file = nil, line = nil, pos = nil, original = nil) if pos.is_a? Exception original = pos pos = nil end super(message, original) @file = file unless file.is_a?(String) && file.empty? @line = line @pos = pos if original && original.respond_to?(:puppetstack) @puppetstack = original.puppetstack else @puppetstack = Puppet::Pops::PuppetStack.stacktrace() end end def to_s msg = super @file = nil if @file.is_a?(String) && @file.empty? msg += Puppet::Util::Errors.error_location_with_space(@file, @line, @pos) msg end end class ParseError < Puppet::Error include ExternalFileError end class ResourceError < Puppet::Error include ExternalFileError end # Contains an issue code and can be annotated with an environment and a node class ParseErrorWithIssue < Puppet::ParseError attr_reader :issue_code, :basic_message, :arguments attr_accessor :environment, :node # @param message [String] The error message # @param file [String] The path to the file where the error was found # @param line [Integer] The line in the file # @param pos [Integer] The position on the line # @param original [Exception] Original exception # @param issue_code [Symbol] The issue code # @param arguments [Hash{Symbol=>Object}] Issue arguments # def initialize(message, file = nil, line = nil, pos = nil, original = nil, issue_code = nil, arguments = nil) super(message, file, line, pos, original) @issue_code = issue_code @basic_message = message @arguments = arguments end def to_s msg = super msg = _("Could not parse for environment %{environment}: %{message}") % { environment: environment, message: msg } if environment msg = _("%{message} on node %{node}") % { message: msg, node: node } if node msg end def to_h { :issue_code => issue_code, :message => basic_message, :full_message => to_s, :file => file, :line => line, :pos => pos, :environment => environment.to_s, :node => node.to_s, } end def self.from_issue_and_stack(issue, args = {}) filename, line = Puppet::Pops::PuppetStack.top_of_stack new( issue.format(args), filename, line, nil, nil, issue.issue_code, args ) end end # An error that already contains location information in the message text class PreformattedError < Puppet::ParseErrorWithIssue end # An error class for when I don't know what happened. Automatically # prints a stack trace when in debug mode. class DevError < Puppet::Error include ExternalFileError end class MissingCommand < Puppet::Error end # Raised when we failed to acquire a lock class LockError < Puppet::Error end # An Error suitable for raising an error with details in a Puppet::Datatypes::Error # that can be used as a value in the Puppet Language # class ErrorWithData < Puppet::Error include ExternalFileError attr_reader :error_data def initialize(error_data, message, file: nil, line: nil, pos: nil, original: nil) super(message, file, line, pos, original) @error_data = error_data end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/indirector.rb
lib/puppet/indirector.rb
# frozen_string_literal: true # Manage indirections to termini. They are organized in terms of indirections - # - e.g., configuration, node, file, certificate -- and each indirection has one # or more terminus types defined. The indirection is configured via the # +indirects+ method, which will be called by the class extending itself # with this module. module Puppet::Indirector # LAK:FIXME We need to figure out how to handle documentation for the # different indirection types. require_relative 'indirector/indirection' require_relative 'indirector/terminus' require_relative 'indirector/code' require_relative 'indirector/envelope' require_relative '../puppet/network/format_support' def self.configure_routes(application_routes) application_routes.each do |indirection_name, termini| indirection_name = indirection_name.to_sym terminus_name = termini["terminus"] cache_name = termini["cache"] Puppet::Indirector::Terminus.terminus_class(indirection_name, terminus_name || cache_name) indirection = Puppet::Indirector::Indirection.instance(indirection_name) raise _("Indirection %{indirection_name} does not exist") % { indirection_name: indirection_name } unless indirection indirection.set_global_setting(:terminus_class, terminus_name) if terminus_name indirection.set_global_setting(:cache_class, cache_name) if cache_name end end # Declare that the including class indirects its methods to # this terminus. The terminus name must be the name of a Puppet # default, not the value -- if it's the value, then it gets # evaluated at parse time, which is before the user has had a chance # to override it. def indirects(indirection, options = {}) raise(ArgumentError, _("Already handling indirection for %{current}; cannot also handle %{next}") % { current: @indirection.name, next: indirection }) if @indirection # populate this class with the various new methods extend ClassMethods include Puppet::Indirector::Envelope include Puppet::Network::FormatSupport # record the indirected class name for documentation purposes options[:indirected_class] = name # instantiate the actual Terminus for that type and this name (:ldap, w/ args :node) # & hook the instantiated Terminus into this class (Node: @indirection = terminus) @indirection = Puppet::Indirector::Indirection.new(self, indirection, **options) end module ClassMethods attr_reader :indirection end # Helper definition for indirections that handle filenames. BadNameRegexp = Regexp.union(/^\.\./, %r{[\\/]}, "\0", /(?i)^[a-z]:/) end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/pops.rb
lib/puppet/pops.rb
# frozen_string_literal: true module Puppet # The Pops language system. This includes the parser, evaluator, AST model, and # Binder. # # @todo Explain how a user should use this to parse and evaluate the puppet # language. # # @note Warning: Pops is still considered experimental, as such the API may # change at any time. # # @api public module Pops EMPTY_HASH = {}.freeze EMPTY_ARRAY = [].freeze EMPTY_STRING = '' MAX_INTEGER = 0x7fffffffffffffff MIN_INTEGER = -0x8000000000000000 DOUBLE_COLON = '::' USCORE = '_' require 'semantic_puppet' require_relative 'pops/patterns' require_relative 'pops/utils' require_relative 'pops/puppet_stack' require_relative 'pops/adaptable' require_relative 'pops/adapters' require_relative 'pops/visitable' require_relative 'pops/visitor' require_relative 'pops/issues' require_relative 'pops/semantic_error' require_relative 'pops/label_provider' require_relative 'pops/validation' require_relative 'pops/issue_reporter' require_relative 'pops/time/timespan' require_relative 'pops/time/timestamp' # (the Types module initializes itself) require_relative 'pops/types/types' require_relative 'pops/types/string_converter' require_relative 'pops/lookup' require_relative 'pops/merge_strategy' module Model require_relative 'pops/model/ast' require_relative 'pops/model/tree_dumper' require_relative 'pops/model/ast_transformer' require_relative 'pops/model/factory' require_relative 'pops/model/model_tree_dumper' require_relative 'pops/model/model_label_provider' end module Resource require_relative 'pops/resource/resource_type_impl' end module Evaluator require_relative 'pops/evaluator/literal_evaluator' require_relative 'pops/evaluator/callable_signature' require_relative 'pops/evaluator/runtime3_converter' require_relative 'pops/evaluator/runtime3_resource_support' require_relative 'pops/evaluator/runtime3_support' require_relative 'pops/evaluator/evaluator_impl' require_relative 'pops/evaluator/epp_evaluator' require_relative 'pops/evaluator/collector_transformer' require_relative 'pops/evaluator/puppet_proc' require_relative 'pops/evaluator/deferred_resolver' module Collectors require_relative 'pops/evaluator/collectors/abstract_collector' require_relative 'pops/evaluator/collectors/fixed_set_collector' require_relative 'pops/evaluator/collectors/catalog_collector' require_relative 'pops/evaluator/collectors/exported_collector' end end module Parser require_relative 'pops/parser/eparser' require_relative 'pops/parser/parser_support' require_relative 'pops/parser/locator' require_relative 'pops/parser/locatable' require_relative 'pops/parser/lexer2' require_relative 'pops/parser/evaluating_parser' require_relative 'pops/parser/epp_parser' require_relative 'pops/parser/code_merger' end module Validation require_relative 'pops/validation/checker4_0' require_relative 'pops/validation/validator_factory_4_0' end # Subsystem for puppet functions defined in ruby. # # @api public module Functions require_relative 'pops/functions/function' require_relative 'pops/functions/dispatch' require_relative 'pops/functions/dispatcher' end module Migration require_relative 'pops/migration/migration_checker' end module Serialization require_relative 'pops/serialization' end end require_relative '../puppet/parser/ast/pops_bridge' require_relative '../puppet/functions' require_relative '../puppet/datatypes' Puppet::Pops::Model.register_pcore_types 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.rb
lib/puppet/util.rb
# frozen_string_literal: true # A module to collect utility functions. require 'English' require_relative '../puppet/error' require_relative 'util/execution_stub' require 'uri' require 'pathname' require 'ostruct' require_relative 'util/platform' require_relative 'util/windows' require_relative 'util/symbolic_file_mode' require_relative '../puppet/file_system/uniquefile' require 'securerandom' require_relative 'util/character_encoding' module Puppet module Util require_relative 'util/monkey_patches' require 'benchmark' # These are all for backward compatibility -- these are methods that used # to be in Puppet::Util but have been moved into external modules. require_relative 'util/posix' extend Puppet::Util::POSIX require_relative 'util/windows/process' if Puppet::Util::Platform.windows? extend Puppet::Util::SymbolicFileMode def default_env Puppet.features.microsoft_windows? ? :windows : :posix end module_function :default_env def create_erb(content) ERB.new(content, trim_mode: '-') end module_function :create_erb # @deprecated Use ENV instead # @api private def get_env(name, mode = default_env) ENV.fetch(name, nil) end module_function :get_env # @deprecated Use ENV instead # @api private def get_environment(mode = default_env) ENV.to_hash end module_function :get_environment # @deprecated Use ENV instead # @api private def clear_environment(mode = default_env) ENV.clear end module_function :clear_environment # @deprecated Use ENV instead # @api private def set_env(name, value = nil, mode = default_env) ENV[name] = value end module_function :set_env # @deprecated Use ENV instead # @api private def merge_environment(env_hash, mode = default_env) ENV.merge!(hash.transform_keys(&:to_s)) end module_function :merge_environment # Run some code with a specific environment. Resets the environment back to # what it was at the end of the code. # # @param hash [Hash{String,Symbol => String}] Environment variables to override the current environment. # @param mode [Symbol] ignored def withenv(hash, mode = :posix) saved = ENV.to_hash begin ENV.merge!(hash.transform_keys(&:to_s)) yield ensure ENV.replace(saved) end end module_function :withenv # Execute a given chunk of code with a new umask. def self.withumask(mask) cur = File.umask(mask) begin yield ensure File.umask(cur) end end # Change the process to a different user def self.chuser group = Puppet[:group] if group begin Puppet::Util::SUIDManager.change_group(group, true) rescue => detail Puppet.warning _("could not change to group %{group}: %{detail}") % { group: group.inspect, detail: detail } $stderr.puts _("could not change to group %{group}") % { group: group.inspect } # Don't exit on failed group changes, since it's # not fatal # exit(74) end end user = Puppet[:user] if user begin Puppet::Util::SUIDManager.change_user(user, true) rescue => detail $stderr.puts _("Could not change to user %{user}: %{detail}") % { user: user, detail: detail } exit(74) end end end # Create instance methods for each of the log levels. This allows # the messages to be a little richer. Most classes will be calling this # method. def self.logmethods(klass, useself = true) Puppet::Util::Log.eachlevel { |level| klass.send(:define_method, level, proc { |args| args = args.join(" ") if args.is_a?(Array) if useself Puppet::Util::Log.create( :level => level, :source => self, :message => args ) else Puppet::Util::Log.create( :level => level, :message => args ) end }) } end # execute a block of work and based on the logging level provided, log the provided message with the seconds taken # The message 'msg' should include string ' in %{seconds} seconds' as part of the message and any content should escape # any percent signs '%' so that they are not interpreted as formatting commands # escaped_str = str.gsub(/%/, '%%') # # @param msg [String] the message to be formated to assigned the %{seconds} seconds take to execute, # other percent signs '%' need to be escaped # @param level [Symbol] the logging level for this message # @param object [Object] The object use for logging the message def benchmark(*args) msg = args.pop level = args.pop object = if args.empty? if respond_to?(level) self else Puppet end else args.pop end # TRANSLATORS 'benchmark' is a method name and should not be translated raise Puppet::DevError, _("Failed to provide level to benchmark") unless level unless level == :none or object.respond_to? level raise Puppet::DevError, _("Benchmarked object does not respond to %{value}") % { value: level } end # Only benchmark if our log level is high enough if level != :none and Puppet::Util::Log.sendlevel?(level) seconds = Benchmark.realtime { yield } object.send(level, msg % { seconds: "%0.2f" % seconds }) seconds else yield end end module_function :benchmark # Resolve a path for an executable to the absolute path. This tries to behave # in the same manner as the unix `which` command and uses the `PATH` # environment variable. # # @api public # @param bin [String] the name of the executable to find. # @return [String] the absolute path to the found executable. def which(bin) if absolute_path?(bin) return bin if FileTest.file? bin and FileTest.executable? bin else exts = ENV.fetch('PATHEXT', nil) exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD] ENV.fetch('PATH').split(File::PATH_SEPARATOR).each do |dir| dest = File.expand_path(File.join(dir, bin)) rescue ArgumentError => e # if the user's PATH contains a literal tilde (~) character and HOME is not set, we may get # an ArgumentError here. Let's check to see if that is the case; if not, re-raise whatever error # was thrown. if e.to_s =~ /HOME/ and (ENV['HOME'].nil? || ENV.fetch('HOME', nil) == "") # if we get here they have a tilde in their PATH. We'll issue a single warning about this and then # ignore this path element and carry on with our lives. # TRANSLATORS PATH and HOME are environment variables and should not be translated Puppet::Util::Warnings.warnonce(_("PATH contains a ~ character, and HOME is not set; ignoring PATH element '%{dir}'.") % { dir: dir }) elsif e.to_s =~ /doesn't exist|can't find user/ # ...otherwise, we just skip the non-existent entry, and do nothing. # TRANSLATORS PATH is an environment variable and should not be translated Puppet::Util::Warnings.warnonce(_("Couldn't expand PATH containing a ~ character; ignoring PATH element '%{dir}'.") % { dir: dir }) else raise end else if Puppet::Util::Platform.windows? && File.extname(dest).empty? exts.each do |ext| destext = File.expand_path(dest + ext) return destext if FileTest.file? destext and FileTest.executable? destext end end return dest if FileTest.file? dest and FileTest.executable? dest end end nil end module_function :which # Determine in a platform-specific way whether a path is absolute. This # defaults to the local platform if none is specified. # # Escape once for the string literal, and once for the regex. slash = '[\\\\/]' label = '[^\\\\/]+' AbsolutePathWindows = /^(?:(?:[A-Z]:#{slash})|(?:#{slash}#{slash}#{label}#{slash}#{label})|(?:#{slash}#{slash}\?#{slash}#{label}))/io AbsolutePathPosix = %r{^/} def absolute_path?(path, platform = nil) unless path.is_a?(String) Puppet.warning("Cannot check if #{path} is an absolute path because it is a '#{path.class}' and not a String'") return false end # Ruby only sets File::ALT_SEPARATOR on Windows and the Ruby standard # library uses that to test what platform it's on. Normally in Puppet we # would use Puppet.features.microsoft_windows?, but this method needs to # be called during the initialization of features so it can't depend on # that. # # @deprecated Use ruby's built-in methods to determine if a path is absolute. platform ||= Puppet::Util::Platform.windows? ? :windows : :posix regex = case platform when :windows AbsolutePathWindows when :posix AbsolutePathPosix else raise Puppet::DevError, _("unknown platform %{platform} in absolute_path") % { platform: platform } end !!(path =~ regex) end module_function :absolute_path? # Convert a path to a file URI def path_to_uri(path) return unless path params = { :scheme => 'file' } if Puppet::Util::Platform.windows? path = path.tr('\\', '/') unc = %r{^//([^/]+)(/.+)}.match(path) if unc params[:host] = unc[1] path = unc[2] elsif path =~ %r{^[a-z]:/}i path = '/' + path end end # have to split *after* any relevant escaping params[:path], params[:query] = uri_encode(path).split('?') search_for_fragment = params[:query] ? :query : :path if params[search_for_fragment].include?('#') params[search_for_fragment], _, params[:fragment] = params[search_for_fragment].rpartition('#') end begin URI::Generic.build(params) rescue => detail raise Puppet::Error, _("Failed to convert '%{path}' to URI: %{detail}") % { path: path, detail: detail }, detail.backtrace end end module_function :path_to_uri # Get the path component of a URI def uri_to_path(uri) return unless uri.is_a?(URI) # CGI.unescape doesn't handle space rules properly in uri paths # URI.unescape does, but returns strings in their original encoding path = uri_unescape(uri.path.encode(Encoding::UTF_8)) if Puppet::Util::Platform.windows? && uri.scheme == 'file' if uri.host && !uri.host.empty? path = "//#{uri.host}" + path # UNC else path.sub!(%r{^/}, '') end end path end module_function :uri_to_path RFC_3986_URI_REGEX = %r{^(?<scheme>(?:[^:/?#]+):)?(?<authority>//(?:[^/?#]*))?(?<path>[^?#]*)(?:\?(?<query>[^#]*))?(?:#(?<fragment>.*))?$} # Percent-encodes a URI query parameter per RFC3986 - https://tools.ietf.org/html/rfc3986 # # The output will correctly round-trip through URI.unescape # # @param [String query_string] A URI query parameter that may contain reserved # characters that must be percent encoded for the key or value to be # properly decoded as part of a larger query string: # # query # encodes as : query # # query_with_special=chars like&and * and# plus+this # encodes as: # query_with_special%3Dchars%20like%26and%20%2A%20and%23%20plus%2Bthis # # Note: Also usable by fragments, but not suitable for paths # # @return [String] a new string containing an encoded query string per the # rules of RFC3986. # # In particular, # query will encode + as %2B and space as %20 def uri_query_encode(query_string) return nil if query_string.nil? # query can encode space to %20 OR + # + MUST be encoded as %2B # in RFC3968 both query and fragment are defined as: # = *( pchar / "/" / "?" ) # CGI.escape turns space into + which is the most backward compatible # however it doesn't roundtrip through URI.unescape which prefers %20 CGI.escape(query_string).gsub('+', '%20') end module_function :uri_query_encode # Percent-encodes a URI string per RFC3986 - https://tools.ietf.org/html/rfc3986 # # Properly handles escaping rules for paths, query strings and fragments # independently # # The output is safe to pass to URI.parse or URI::Generic.build and will # correctly round-trip through URI.unescape # # @param [String path] A URI string that may be in the form of: # # http://foo.com/bar?query # file://tmp/foo bar # //foo.com/bar?query # /bar?query # bar?query # bar # . # C:\Windows\Temp # # Note that with no specified scheme, authority or query parameter delimiter # ? that a naked string will be treated as a path. # # Note that if query parameters need to contain data such as & or = # that this method should not be used, as there is no way to differentiate # query parameter data from query delimiters when multiple parameters # are specified # # @param [Hash{Symbol=>String} opts] Options to alter encoding # @option opts [Array<Symbol>] :allow_fragment defaults to false. When false # will treat # as part of a path or query and not a fragment delimiter # # @return [String] a new string containing appropriate portions of the URI # encoded per the rules of RFC3986. # In particular, # path will not encode +, but will encode space as %20 # query will encode + as %2B and space as %20 # fragment behaves like query def uri_encode(path, opts = { :allow_fragment => false }) raise ArgumentError, _('path may not be nil') if path.nil? encoded = ''.dup # parse uri into named matches, then reassemble properly encoded parts = path.match(RFC_3986_URI_REGEX) encoded += parts[:scheme] unless parts[:scheme].nil? encoded += parts[:authority] unless parts[:authority].nil? # path requires space to be encoded as %20 (NEVER +) # + should be left unencoded # URI::parse and URI::Generic.build don't like paths encoded with CGI.escape # URI.escape does not change / to %2F and : to %3A like CGI.escape # encoded += rfc2396_escape(parts[:path]) unless parts[:path].nil? # each query parameter unless parts[:query].nil? query_string = parts[:query].split('&').map do |pair| # can optionally be separated by an = pair.split('=').map do |v| uri_query_encode(v) end.join('=') end.join('&') encoded += '?' + query_string end encoded += ((opts[:allow_fragment] ? '#' : '%23') + uri_query_encode(parts[:fragment])) unless parts[:fragment].nil? encoded end module_function :uri_encode # From https://github.com/ruby/ruby/blob/v2_7_3/lib/uri/rfc2396_parser.rb#L24-L46 ALPHA = "a-zA-Z" ALNUM = "#{ALPHA}\\d" UNRESERVED = "\\-_.!~*'()#{ALNUM}" RESERVED = ";/?:@&=+$,\\[\\]" UNSAFE = Regexp.new("[^#{UNRESERVED}#{RESERVED}]").freeze HEX = "a-fA-F\\d" ESCAPED = Regexp.new("%[#{HEX}]{2}").freeze def rfc2396_escape(str) str.gsub(UNSAFE) do |match| tmp = ''.dup match.each_byte do |uc| tmp << sprintf('%%%02X', uc) end tmp end.force_encoding(Encoding::US_ASCII) end module_function :rfc2396_escape def uri_unescape(str) enc = str.encoding enc = Encoding::UTF_8 if enc == Encoding::US_ASCII str.gsub(ESCAPED) { [::Regexp.last_match(0)[1, 2]].pack('H2').force_encoding(enc) } end module_function :uri_unescape def safe_posix_fork(stdin = $stdin, stdout = $stdout, stderr = $stderr, &block) Kernel.fork do STDIN.reopen(stdin) STDOUT.reopen(stdout) STDERR.reopen(stderr) $stdin = STDIN $stdout = STDOUT $stderr = STDERR begin d = Dir.new('/proc/self/fd') ignore_fds = ['.', '..', d.fileno.to_s] d.each_child do |f| next if ignore_fds.include?(f) || f.to_i < 3 begin IO.new(f.to_i).close rescue nil end end rescue Errno::ENOENT, Errno::ENOTDIR # /proc/self/fd not found, /proc/self not a dir 3.upto(256) { |fd| begin IO.new(fd).close rescue nil end } end block.call if block end end module_function :safe_posix_fork def symbolizehash(hash) newhash = {} hash.each do |name, val| name = name.intern if name.respond_to? :intern newhash[name] = val end newhash end module_function :symbolizehash # Just benchmark, with no logging. def thinmark Benchmark.realtime { yield } end module_function :thinmark PUPPET_STACK_INSERTION_FRAME = if RUBY_VERSION >= '3.4' /.*puppet_stack\.rb.*in.*'Puppet::Pops::PuppetStack\.stack'/ else /.*puppet_stack\.rb.*in.*`stack'/ end # utility method to get the current call stack and format it to a human-readable string (which some IDEs/editors # will recognize as links to the line numbers in the trace) def self.pretty_backtrace(backtrace = caller(1), puppetstack = []) format_backtrace_array(backtrace, puppetstack).join("\n") end # arguments may be a Ruby stack, with an optional Puppet stack argument, # or just a Puppet stack. # stacks may be an Array of Strings "/foo.rb:0 in `blah'" or # an Array of Arrays that represent a frame: ["/foo.pp", 0] def self.format_backtrace_array(primary_stack, puppetstack = []) primary_stack.flat_map do |frame| frame = format_puppetstack_frame(frame) if frame.is_a?(Array) primary_frame = resolve_stackframe(frame) if primary_frame =~ PUPPET_STACK_INSERTION_FRAME && !puppetstack.empty? [resolve_stackframe(format_puppetstack_frame(puppetstack.shift)), primary_frame] else primary_frame end end end def self.resolve_stackframe(frame) _, path, rest = /^(.*):(\d+.*)$/.match(frame).to_a if path path = begin Pathname(path).realpath rescue path end "#{path}:#{rest}" else frame end end def self.format_puppetstack_frame(file_and_lineno) file_and_lineno.join(':') end # Replace a file, securely. This takes a block, and passes it the file # handle of a file open for writing. Write the replacement content inside # the block and it will safely replace the target file. # # This method will make no changes to the target file until the content is # successfully written and the block returns without raising an error. # # As far as possible the state of the existing file, such as mode, is # preserved. This works hard to avoid loss of any metadata, but will result # in an inode change for the file. # # Arguments: `filename`, `default_mode`, `staging_location` # # The filename is the file we are going to replace. # # The default_mode is the mode to use when the target file doesn't already # exist; if the file is present we copy the existing mode/owner/group values # across. The default_mode can be expressed as an octal integer, a numeric string (ie '0664') # or a symbolic file mode. # # The staging_location is a location to render the temporary file before # moving the file to it's final location. DEFAULT_POSIX_MODE = 0o644 DEFAULT_WINDOWS_MODE = nil def replace_file(file, default_mode, staging_location: nil, validate_callback: nil, &block) raise Puppet::DevError, _("replace_file requires a block") unless block_given? if default_mode unless valid_symbolic_mode?(default_mode) raise Puppet::DevError, _("replace_file default_mode: %{default_mode} is invalid") % { default_mode: default_mode } end mode = symbolic_mode_to_int(normalize_symbolic_mode(default_mode)) elsif Puppet::Util::Platform.windows? mode = DEFAULT_WINDOWS_MODE else mode = DEFAULT_POSIX_MODE end begin file = Puppet::FileSystem.pathname(file) # encoding for Uniquefile is not important here because the caller writes to it as it sees fit if staging_location tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(file), staging_location) else tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(file), Puppet::FileSystem.dir_string(file)) end effective_mode = unless Puppet::Util::Platform.windows? # Grab the current file mode, and fall back to the defaults. if Puppet::FileSystem.exist?(file) stat = Puppet::FileSystem.lstat(file) tempfile.chown(stat.uid, stat.gid) stat.mode else mode end end # OK, now allow the caller to write the content of the file. yield tempfile if effective_mode # We only care about the bottom four slots, which make the real mode, # and not the rest of the platform stat call fluff and stuff. tempfile.chmod(effective_mode & 0o7777) end # Now, make sure the data (which includes the mode) is safe on disk. tempfile.flush begin tempfile.fsync rescue NotImplementedError # fsync may not be implemented by Ruby on all platforms, but # there is absolutely no recovery path if we detect that. So, we just # ignore the return code. # # However, don't be fooled: that is accepting that we are running in # an unsafe fashion. If you are porting to a new platform don't stub # that out. end tempfile.close if validate_callback validate_callback.call(tempfile.path) end if Puppet::Util::Platform.windows? # Windows ReplaceFile needs a file to exist, so touch handles this unless Puppet::FileSystem.exist?(file) Puppet::FileSystem.touch(file) if mode Puppet::Util::Windows::Security.set_mode(mode, Puppet::FileSystem.path_string(file)) end end # Yes, the arguments are reversed compared to the rename in the rest # of the world. Puppet::Util::Windows::File.replace_file(FileSystem.path_string(file), tempfile.path) else # MRI Ruby checks for this and raises an error, while JRuby removes the directory # and replaces it with a file. This makes the our version of replace_file() consistent if Puppet::FileSystem.exist?(file) && Puppet::FileSystem.directory?(file) raise Errno::EISDIR, _("Is a directory: %{directory}") % { directory: file } end File.rename(tempfile.path, Puppet::FileSystem.path_string(file)) end ensure # in case an error occurred before we renamed the temp file, make sure it # gets deleted if tempfile tempfile.close! end end # Ideally, we would now fsync the directory as well, but Ruby doesn't # have support for that, and it doesn't matter /that/ much... # Return something true, and possibly useful. file end module_function :replace_file # Executes a block of code, wrapped with some special exception handling. Causes the ruby interpreter to # exit if the block throws an exception. # # @api public # @param [String] message a message to log if the block fails # @param [Integer] code the exit code that the ruby interpreter should return if the block fails # @yield def exit_on_fail(message, code = 1) yield # First, we need to check and see if we are catching a SystemExit error. These will be raised # when we daemonize/fork, and they do not necessarily indicate a failure case. rescue SystemExit => err raise err # Now we need to catch *any* other kind of exception, because we may be calling third-party # code (e.g. webrick), and we have no idea what they might throw. rescue Exception => err ## NOTE: when debugging spec failures, these two lines can be very useful # puts err.inspect # puts Puppet::Util.pretty_backtrace(err.backtrace) Puppet.log_exception(err, "#{message}: #{err}") Puppet::Util::Log.force_flushqueue() exit(code) end module_function :exit_on_fail def deterministic_rand(seed, max) deterministic_rand_int(seed, max).to_s end module_function :deterministic_rand def deterministic_rand_int(seed, max) Random.new(seed).rand(max) end module_function :deterministic_rand_int # Executes a block of code, wrapped around Facter.load_external(false) and # Facter.load_external(true) which will cause Facter to not evaluate external facts. def skip_external_facts return yield unless Puppet.runtime[:facter].load_external? begin Puppet.runtime[:facter].load_external(false) yield ensure Puppet.runtime[:facter].load_external(true) end end module_function :skip_external_facts end end require_relative 'util/errors' require_relative 'util/metaid' require_relative 'util/classgen' require_relative 'util/docs' require_relative 'util/execution' require_relative 'util/logging' require_relative 'util/package' require_relative 'util/warnings'
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/confine.rb
lib/puppet/confine.rb
# frozen_string_literal: true # The class that handles testing whether our providers # actually work or not. require_relative '../puppet/util' class Puppet::Confine include Puppet::Util @tests = {} class << self attr_accessor :name end def self.inherited(klass) name = klass.to_s.split("::").pop.downcase.to_sym raise "Test #{name} is already defined" if @tests.include?(name) klass.name = name @tests[name] = klass end def self.test(name) unless @tests.include?(name) begin require "puppet/confine/#{name}" rescue LoadError => detail unless detail.to_s =~ /No such file|cannot load such file/i Puppet.warning("Could not load confine test '#{name}': #{detail}") end # Could not find file unless Puppet[:always_retry_plugins] @tests[name] = nil end end end @tests[name] end attr_reader :values # Mark that this confine is used for testing binary existence. attr_accessor :for_binary def for_binary? for_binary end # Used for logging. attr_accessor :label def initialize(values) values = [values] unless values.is_a?(Array) @values = values end # Provide a hook for the message when there's a failure. def message(value) "" end # Collect the results of all of them. def result values.collect { |value| pass?(value) } end # Test whether our confine matches. def valid? values.each do |value| unless pass?(value) Puppet.debug { label + ": " + message(value) } return false end end true ensure reset end # Provide a hook for subclasses. def reset 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/x509/pem_store.rb
lib/puppet/x509/pem_store.rb
# frozen_string_literal: true require_relative '../../puppet/x509' # Methods for managing PEM encoded files. While PEM encoded strings are # always ASCII, the files may contain user specified comments, so they are # UTF-8 encoded. # # @api private module Puppet::X509::PemStore # Load a pem encoded object. # # @param path [String] file path # @return [String, nil] The PEM encoded object or nil if the # path does not exist # @raise [Errno::EACCES] if permission is denied # @api private def load_pem(path) Puppet::FileSystem.read(path, encoding: 'UTF-8') rescue Errno::ENOENT nil end # Save pem encoded content to a file. If the file doesn't exist, it # will be created. Otherwise, the file will be overwritten. In both # cases the contents will be overwritten atomically so other # processes don't see a partially written file. # # @param pem [String] The PEM encoded object to write # @param path [String] The file path to write to # @raise [Errno::EACCES] if permission is denied # @raise [Errno::EPERM] if the operation cannot be completed # @api private def save_pem(pem, path, owner: nil, group: nil, mode: 0o644) Puppet::FileSystem.replace_file(path, mode) do |f| f.set_encoding('UTF-8') f.write(pem.encode('UTF-8')) end if !Puppet::Util::Platform.windows? && Puppet.features.root? && (owner || group) FileUtils.chown(owner, group, path) end end # Delete a pem encoded object, if it exists. # # @param path [String] The file path to delete # @return [Boolean] Returns true if the file was deleted, false otherwise # @raise [Errno::EACCES] if permission is denied # @api private def delete_pem(path) Puppet::FileSystem.unlink(path) true rescue Errno::ENOENT false end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/x509/cert_provider.rb
lib/puppet/x509/cert_provider.rb
# frozen_string_literal: true require_relative '../../puppet/x509' # Class for loading and saving cert related objects. By default the provider # loads and saves based on puppet's default settings, such as `Puppet[:localcacert]`. # The providers sets the permissions on files it saves, such as the private key. # All of the `load_*` methods take an optional `required` parameter. If an object # doesn't exist, then by default the provider returns `nil`. However, if the # `required` parameter is true, then an exception will be raised instead. # # @api private class Puppet::X509::CertProvider include Puppet::X509::PemStore # Only allow printing ascii characters, excluding / VALID_CERTNAME = /\A[ -.0-~]+\Z/ CERT_DELIMITERS = /-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m CRL_DELIMITERS = /-----BEGIN X509 CRL-----.*?-----END X509 CRL-----/m def initialize(capath: Puppet[:localcacert], crlpath: Puppet[:hostcrl], privatekeydir: Puppet[:privatekeydir], certdir: Puppet[:certdir], requestdir: Puppet[:requestdir], hostprivkey: Puppet.settings.set_by_config?(:hostprivkey) ? Puppet[:hostprivkey] : nil, hostcert: Puppet.settings.set_by_config?(:hostcert) ? Puppet[:hostcert] : nil) @capath = capath @crlpath = crlpath @privatekeydir = privatekeydir @certdir = certdir @requestdir = requestdir @hostprivkey = hostprivkey @hostcert = hostcert end # Save `certs` to the configured `capath`. # # @param certs [Array<OpenSSL::X509::Certificate>] Array of CA certs to save # @raise [Puppet::Error] if the certs cannot be saved # # @api private def save_cacerts(certs) save_pem(certs.map(&:to_pem).join, @capath, **permissions_for_setting(:localcacert)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save CA certificates to '%{capath}'") % { capath: @capath }, e) end # Load CA certs from the configured `capath`. # # @param required [Boolean] If true, raise if they are missing # @return (see #load_cacerts_from_pem) # @raise (see #load_cacerts_from_pem) # @raise [Puppet::Error] if the certs cannot be loaded # # @api private def load_cacerts(required: false) pem = load_pem(@capath) if !pem && required raise Puppet::Error, _("The CA certificates are missing from '%{path}'") % { path: @capath } end pem ? load_cacerts_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load CA certificates from '%{capath}'") % { capath: @capath }, e) end # Load PEM encoded CA certificates. # # @param pem [String] PEM encoded certificate(s) # @return [Array<OpenSSL::X509::Certificate>] Array of CA certs # @raise [OpenSSL::X509::CertificateError] The `pem` text does not contain a valid cert # # @api private def load_cacerts_from_pem(pem) # TRANSLATORS 'PEM' is an acronym and shouldn't be translated raise OpenSSL::X509::CertificateError, _("Failed to parse CA certificates as PEM") if pem !~ CERT_DELIMITERS pem.scan(CERT_DELIMITERS).map do |text| OpenSSL::X509::Certificate.new(text) end end # Save `crls` to the configured `crlpath`. # # @param crls [Array<OpenSSL::X509::CRL>] Array of CRLs to save # @raise [Puppet::Error] if the CRLs cannot be saved # # @api private def save_crls(crls) save_pem(crls.map(&:to_pem).join, @crlpath, **permissions_for_setting(:hostcrl)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save CRLs to '%{crlpath}'") % { crlpath: @crlpath }, e) end # Load CRLs from the configured `crlpath` path. # # @param required [Boolean] If true, raise if they are missing # @return (see #load_crls_from_pem) # @raise (see #load_crls_from_pem) # @raise [Puppet::Error] if the CRLs cannot be loaded # # @api private def load_crls(required: false) pem = load_pem(@crlpath) if !pem && required raise Puppet::Error, _("The CRL is missing from '%{path}'") % { path: @crlpath } end pem ? load_crls_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load CRLs from '%{crlpath}'") % { crlpath: @crlpath }, e) end # Load PEM encoded CRL(s). # # @param pem [String] PEM encoded CRL(s) # @return [Array<OpenSSL::X509::CRL>] Array of CRLs # @raise [OpenSSL::X509::CRLError] The `pem` text does not contain a valid CRL # # @api private def load_crls_from_pem(pem) # TRANSLATORS 'PEM' is an acronym and shouldn't be translated raise OpenSSL::X509::CRLError, _("Failed to parse CRLs as PEM") if pem !~ CRL_DELIMITERS pem.scan(CRL_DELIMITERS).map do |text| OpenSSL::X509::CRL.new(text) end end # Return the time when the CRL was last updated. # # @return [Time, nil] Time when the CRL was last updated, or nil if we don't # have a CRL # # @api private def crl_last_update stat = Puppet::FileSystem.stat(@crlpath) Time.at(stat.mtime) rescue Errno::ENOENT nil end # Set the CRL last updated time. # # @param time [Time] The last updated time # # @api private def crl_last_update=(time) Puppet::FileSystem.touch(@crlpath, mtime: time) end # Return the time when the CA bundle was last updated. # # @return [Time, nil] Time when the CA bundle was last updated, or nil if we don't # have a CA bundle # # @api private def ca_last_update stat = Puppet::FileSystem.stat(@capath) Time.at(stat.mtime) rescue Errno::ENOENT nil end # Set the CA bundle last updated time. # # @param time [Time] The last updated time # # @api private def ca_last_update=(time) Puppet::FileSystem.touch(@capath, mtime: time) end # Save named private key in the configured `privatekeydir`. For # historical reasons, names are case insensitive. # # @param name [String] The private key identity # @param key [OpenSSL::PKey::RSA] private key # @param password [String, nil] If non-nil, derive an encryption key # from the password, and use that to encrypt the private key. If nil, # save the private key unencrypted. # @raise [Puppet::Error] if the private key cannot be saved # # @api private def save_private_key(name, key, password: nil) pem = if password cipher = OpenSSL::Cipher.new('aes-128-cbc') key.export(cipher, password) else key.to_pem end path = @hostprivkey || to_path(@privatekeydir, name) save_pem(pem, path, **permissions_for_setting(:hostprivkey)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save private key for '%{name}'") % { name: name }, e) end # Load a private key from the configured `privatekeydir`. For # historical reasons, names are case-insensitive. # # @param name [String] The private key identity # @param required [Boolean] If true, raise if it is missing # @param password [String, nil] If the private key is encrypted, decrypt # it using the password. If the key is encrypted, but a password is # not specified, then the key cannot be loaded. # @return (see #load_private_key_from_pem) # @raise (see #load_private_key_from_pem) # @raise [Puppet::Error] if the private key cannot be loaded # # @api private def load_private_key(name, required: false, password: nil) path = @hostprivkey || to_path(@privatekeydir, name) pem = load_pem(path) if !pem && required raise Puppet::Error, _("The private key is missing from '%{path}'") % { path: path } end pem ? load_private_key_from_pem(pem, password: password) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load private key for '%{name}'") % { name: name }, e) end # Load a PEM encoded private key. # # @param pem [String] PEM encoded private key # @param password [String, nil] If the private key is encrypted, decrypt # it using the password. If the key is encrypted, but a password is # not specified, then the key cannot be loaded. # @return [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] The private key # @raise [OpenSSL::PKey::PKeyError] The `pem` text does not contain a valid key # # @api private def load_private_key_from_pem(pem, password: nil) # set a non-nil password to ensure openssl doesn't prompt password ||= '' OpenSSL::PKey.read(pem, password) end # Load the private key password. # # @return [String, nil] The private key password as a binary string or nil # if there is none. # # @api private def load_private_key_password Puppet::FileSystem.read(Puppet[:passfile], :encoding => Encoding::BINARY) rescue Errno::ENOENT nil end # Save a named client cert to the configured `certdir`. # # @param name [String] The client cert identity # @param cert [OpenSSL::X509::Certificate] The cert to save # @raise [Puppet::Error] if the client cert cannot be saved # # @api private def save_client_cert(name, cert) path = @hostcert || to_path(@certdir, name) save_pem(cert.to_pem, path, **permissions_for_setting(:hostcert)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save client certificate for '%{name}'") % { name: name }, e) end # Load a named client cert from the configured `certdir`. # # @param name [String] The client cert identity # @param required [Boolean] If true, raise it is missing # @return (see #load_request_from_pem) # @raise (see #load_client_cert_from_pem) # @raise [Puppet::Error] if the client cert cannot be loaded # # @api private def load_client_cert(name, required: false) path = @hostcert || to_path(@certdir, name) pem = load_pem(path) if !pem && required raise Puppet::Error, _("The client certificate is missing from '%{path}'") % { path: path } end pem ? load_client_cert_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load client certificate for '%{name}'") % { name: name }, e) end # Load a PEM encoded certificate. # # @param pem [String] PEM encoded cert # @return [OpenSSL::X509::Certificate] the certificate # @raise [OpenSSL::X509::CertificateError] The `pem` text does not contain a valid cert # # @api private def load_client_cert_from_pem(pem) OpenSSL::X509::Certificate.new(pem) end # Create a certificate signing request (CSR). # # @param name [String] the request identity # @param private_key [OpenSSL::PKey::RSA] private key # @return [Puppet::X509::Request] The request # # @api private def create_request(name, private_key) options = {} if Puppet[:dns_alt_names] && Puppet[:dns_alt_names] != '' options[:dns_alt_names] = Puppet[:dns_alt_names] end csr_attributes = Puppet::SSL::CertificateRequestAttributes.new(Puppet[:csr_attributes]) if csr_attributes.load options[:csr_attributes] = csr_attributes.custom_attributes options[:extension_requests] = csr_attributes.extension_requests end # Adds auto-renew attribute to CSR if the agent supports auto-renewal of # certificates if Puppet[:hostcert_renewal_interval] && Puppet[:hostcert_renewal_interval] > 0 options[:csr_attributes] ||= {} options[:csr_attributes].merge!({ '1.3.6.1.4.1.34380.1.3.2' => 'true' }) end csr = Puppet::SSL::CertificateRequest.new(name) csr.generate(private_key, options) end # Save a certificate signing request (CSR) to the configured `requestdir`. # # @param name [String] the request identity # @param csr [OpenSSL::X509::Request] the request # @raise [Puppet::Error] if the cert request cannot be saved # # @api private def save_request(name, csr) path = to_path(@requestdir, name) save_pem(csr.to_pem, path, **permissions_for_setting(:hostcsr)) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to save certificate request for '%{name}'") % { name: name }, e) end # Load a named certificate signing request (CSR) from the configured `requestdir`. # # @param name [String] The request identity # @return (see #load_request_from_pem) # @raise (see #load_request_from_pem) # @raise [Puppet::Error] if the cert request cannot be saved # # @api private def load_request(name) path = to_path(@requestdir, name) pem = load_pem(path) pem ? load_request_from_pem(pem) : nil rescue SystemCallError => e raise Puppet::Error.new(_("Failed to load certificate request for '%{name}'") % { name: name }, e) end # Delete a named certificate signing request (CSR) from the configured `requestdir`. # # @param name [String] The request identity # @return [Boolean] true if the CSR was deleted # # @api private def delete_request(name) path = to_path(@requestdir, name) delete_pem(path) rescue SystemCallError => e raise Puppet::Error.new(_("Failed to delete certificate request for '%{name}'") % { name: name }, e) end # Load a PEM encoded certificate signing request (CSR). # # @param pem [String] PEM encoded request # @return [OpenSSL::X509::Request] the request # @raise [OpenSSL::X509::RequestError] The `pem` text does not contain a valid request # # @api private def load_request_from_pem(pem) OpenSSL::X509::Request.new(pem) end # Return the path to the cert related object (key, CSR, cert, etc). # # @param base [String] base directory # @param name [String] the name associated with the cert related object def to_path(base, name) raise _("Certname %{name} must not contain unprintable or non-ASCII characters") % { name: name.inspect } unless name =~ VALID_CERTNAME File.join(base, "#{name.downcase}.pem") end private def permissions_for_setting(name) setting = Puppet.settings.setting(name) perm = { mode: setting.mode.to_i(8) } if Puppet.features.root? && !Puppet::Util::Platform.windows? perm[:owner] = setting.owner perm[:group] = setting.group end perm 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/storage.rb
lib/puppet/util/storage.rb
# frozen_string_literal: true require 'yaml' require 'singleton' require_relative '../../puppet/util/yaml' # a class for storing state class Puppet::Util::Storage include Singleton include Puppet::Util def self.state @@state end def initialize self.class.load end # Return a hash that will be stored to disk. It's worth noting # here that we use the object's full path, not just the name/type # combination. At the least, this is useful for those non-isomorphic # types like exec, but it also means that if an object changes locations # in the configuration it will lose its cache. def self.cache(object) if object.is_a?(Symbol) name = object else name = object.to_s end @@state[name] ||= {} end def self.clear @@state.clear end def self.init @@state = {} end init def self.load Puppet.settings.use(:main) unless FileTest.directory?(Puppet[:statedir]) filename = Puppet[:statefile] unless Puppet::FileSystem.exist?(filename) init if @@state.nil? return end unless File.file?(filename) Puppet.warning(_("Checksumfile %{filename} is not a file, ignoring") % { filename: filename }) return end Puppet::Util.benchmark(:debug, "Loaded state in %{seconds} seconds") do @@state = Puppet::Util::Yaml.safe_load_file(filename, [Symbol, Time]) rescue Puppet::Util::Yaml::YamlLoadError => detail Puppet.err _("Checksumfile %{filename} is corrupt (%{detail}); replacing") % { filename: filename, detail: detail } begin File.rename(filename, filename + ".bad") rescue raise Puppet::Error, _("Could not rename corrupt %{filename}; remove manually") % { filename: filename }, detail.backtrace end end unless @@state.is_a?(Hash) Puppet.err _("State got corrupted") init end end def self.stateinspect @@state.inspect end def self.store Puppet.debug "Storing state" Puppet.info _("Creating state file %{file}") % { file: Puppet[:statefile] } unless Puppet::FileSystem.exist?(Puppet[:statefile]) if Puppet[:statettl] == 0 || Puppet[:statettl] == Float::INFINITY Puppet.debug "Not pruning old state cache entries" else Puppet::Util.benchmark(:debug, "Pruned old state cache entries in %{seconds} seconds") do ttl_cutoff = Time.now - Puppet[:statettl] @@state.reject! do |k, _v| @@state[k][:checked] && @@state[k][:checked] < ttl_cutoff end end end Puppet::Util.benchmark(:debug, "Stored state in %{seconds} seconds") do Puppet::Util::Yaml.dump(@@state, Puppet[:statefile]) 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/reference.rb
lib/puppet/util/reference.rb
# frozen_string_literal: true require_relative '../../puppet/util/instance_loader' require 'fileutils' # Manage Reference Documentation. class Puppet::Util::Reference include Puppet::Util include Puppet::Util::Docs extend Puppet::Util::InstanceLoader instance_load(:reference, 'puppet/reference') def self.modes %w[text] end def self.newreference(name, options = {}, &block) ref = new(name, **options, &block) instance_hash(:reference)[name.intern] = ref ref end def self.page(*sections) depth = 4 # Use the minimum depth sections.each do |name| section = reference(name) or raise _("Could not find section %{name}") % { name: name } depth = section.depth if section.depth < depth end end def self.references(environment) instance_loader(:reference).loadall(environment) loaded_instances(:reference).sort_by(&:to_s) end attr_accessor :page, :depth, :header, :title, :dynamic attr_writer :doc def doc if defined?(@doc) "#{@name} - #{@doc}" else @title end end def dynamic? dynamic end def initialize(name, title: nil, depth: nil, dynamic: nil, doc: nil, &block) @name = name @title = title @depth = depth @dynamic = dynamic @doc = doc meta_def(:generate, &block) # Now handle the defaults @title ||= _("%{name} Reference") % { name: @name.to_s.capitalize } @page ||= @title.gsub(/\s+/, '') @depth ||= 2 @header ||= "" end # Indent every line in the chunk except those which begin with '..'. def indent(text, tab) text.gsub(/(^|\A)/, tab).gsub(/^ +\.\./, "..") end def option(name, value) ":#{name.to_s.capitalize}: #{value}\n" end def text puts output end def to_markdown(withcontents = true) # First the header text = markdown_header(@title, 1) text << @header text << generate text 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/platform.rb
lib/puppet/util/platform.rb
# frozen_string_literal: true module Puppet module Util module Platform FIPS_STATUS_FILE = "/proc/sys/crypto/fips_enabled" WINDOWS_FIPS_REGISTRY_KEY = 'System\\CurrentControlSet\\Control\\Lsa\\FipsAlgorithmPolicy' def windows? # Ruby only sets File::ALT_SEPARATOR on Windows and the Ruby standard # library uses that to test what platform it's on. In some places we # would use Puppet.features.microsoft_windows?, but this method can be # used to determine the behavior of the underlying system without # requiring features to be initialized and without side effect. !!File::ALT_SEPARATOR end module_function :windows? def solaris? RUBY_PLATFORM.include?('solaris') end module_function :solaris? def default_paths return [] if windows? %w[/usr/sbin /sbin] end module_function :default_paths @fips_enabled = if windows? require 'win32/registry' begin Win32::Registry::HKEY_LOCAL_MACHINE.open(WINDOWS_FIPS_REGISTRY_KEY) do |reg| reg.values.first == 1 end rescue Win32::Registry::Error false end else File.exist?(FIPS_STATUS_FILE) && File.read(FIPS_STATUS_FILE, 1) == '1' end def fips_enabled? @fips_enabled end module_function :fips_enabled? def self.jruby? RUBY_PLATFORM == 'java' end def jruby_fips? @@jruby_fips ||= if RUBY_PLATFORM == 'java' require 'java' begin require 'openssl' false rescue LoadError, NameError true end else false end end module_function :jruby_fips? 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/json_lockfile.rb
lib/puppet/util/json_lockfile.rb
# frozen_string_literal: true require_relative '../../puppet/util/lockfile' # This class provides a simple API for managing a lock file # whose contents are a serialized JSON object. In addition # to querying the basic state (#locked?) of the lock, managing # the lock (#lock, #unlock), the contents can be retrieved at # any time while the lock is held (#lock_data). This can be # used to store structured data (state messages, etc.) about # the lock. # # @see Puppet::Util::Lockfile class Puppet::Util::JsonLockfile < Puppet::Util::Lockfile # Lock the lockfile. You may optionally pass a data object, which will be # retrievable for the duration of time during which the file is locked. # # @param [Hash] lock_data an optional Hash of data to associate with the lock. # This may be used to store pids, descriptive messages, etc. The # data may be retrieved at any time while the lock is held by # calling the #lock_data method. <b>NOTE</b> that the JSON serialization # does NOT support Symbol objects--if you pass them in, they will be # serialized as Strings, so you should plan accordingly. # @return [boolean] true if lock is successfully acquired, false otherwise. def lock(lock_data = nil) return false if locked? super(Puppet::Util::Json.dump(lock_data)) end # Retrieve the (optional) lock data that was specified at the time the file # was locked. # @return [Object] the data object. Remember that the serialization does not # support Symbol objects, so if your data Object originally contained symbols, # they will be converted to Strings. def lock_data return nil unless file_locked? file_contents = super return nil if file_contents.nil? or file_contents.empty? Puppet::Util::Json.load(file_contents) rescue Puppet::Util::Json::ParseError Puppet.warning _("Unable to read lockfile data from %{path}: not in JSON") % { path: @file_path } 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/util/watcher.rb
lib/puppet/util/watcher.rb
# frozen_string_literal: true module Puppet::Util::Watcher require_relative 'watcher/timer' require_relative 'watcher/change_watcher' require_relative 'watcher/periodic_watcher' module Common def self.file_ctime_change_watcher(filename) Puppet::Util::Watcher::ChangeWatcher.watch(lambda do Puppet::FileSystem.stat(filename).ctime rescue Errno::ENOENT, Errno::ENOTDIR :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/util/limits.rb
lib/puppet/util/limits.rb
# frozen_string_literal: true require_relative '../../puppet/util' module Puppet::Util::Limits # @api private def setpriority(priority) return unless priority Process.setpriority(0, Process.pid, priority) rescue Errno::EACCES, NotImplementedError Puppet.warning(_("Failed to set process priority to '%{priority}'") % { 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/util/autoload.rb
lib/puppet/util/autoload.rb
# frozen_string_literal: true require 'pathname' require_relative '../../puppet/util/rubygems' require_relative '../../puppet/util/warnings' require_relative '../../puppet/pops/adaptable' require_relative '../../puppet/concurrent/synchronized' # An adapter that ties the module_directories cache to the environment where the modules are parsed. This # adapter ensures that the life-cycle of this cache doesn't exceed the life-cycle of the environment. # # @api private class Puppet::Util::ModuleDirectoriesAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :directories def self.create_adapter(env) adapter = super(env) adapter.directories = env.modulepath.flat_map do |dir| Dir.glob(File.join(dir, '*', 'lib')) end adapter end end # Autoload paths, either based on names or all at once. class Puppet::Util::Autoload include Puppet::Concurrent::Synchronized extend Puppet::Concurrent::Synchronized @loaded = {} class << self attr_accessor :loaded def gem_source @gem_source ||= Puppet::Util::RubyGems::Source.new end # Has a given path been loaded? This is used for testing whether a # changed file should be loaded or just ignored. This is only # used in network/client/master, when downloading plugins, to # see if a given plugin is currently loaded and thus should be # reloaded. def loaded?(path) path = cleanpath(path).chomp('.rb') loaded.include?(path) end # Save the fact that a given path has been loaded. This is so # we can load downloaded plugins if they've already been loaded # into memory. # @api private def mark_loaded(name, file) name = cleanpath(name).chomp('.rb') file = File.expand_path(file) $LOADED_FEATURES << file unless $LOADED_FEATURES.include?(file) loaded[name] = [file, File.mtime(file)] end # @api private def changed?(name, env) name = cleanpath(name).chomp('.rb') return true unless loaded.include?(name) file, old_mtime = loaded[name] return true unless file == get_file(name, env) begin old_mtime.to_i != File.mtime(file).to_i rescue Errno::ENOENT true end end # Load a single plugin by name. We use 'load' here so we can reload a # given plugin. def load_file(name, env) file = get_file(name.to_s, env) return false unless file begin mark_loaded(name, file) Kernel.load file true rescue SystemExit, NoMemoryError raise rescue Exception => detail message = _("Could not autoload %{name}: %{detail}") % { name: name, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end end def loadall(path, env) # Load every instance of everything we can find. files_to_load(path, env).each do |file| name = file.chomp(".rb") load_file(name, env) unless loaded?(name) end end def reload_changed(env) loaded.keys.each do |file| if changed?(file, env) load_file(file, env) end end end # Get the correct file to load for a given path # returns nil if no file is found # @api private def get_file(name, env) name += '.rb' unless name =~ /\.rb$/ path = search_directories(env).find { |dir| Puppet::FileSystem.exist?(File.join(dir, name)) } path and File.join(path, name) end def files_to_load(path, env) search_directories(env).map { |dir| files_in_dir(dir, path) }.flatten.uniq end # @api private def files_in_dir(dir, path) dir = Pathname.new(Puppet::FileSystem.expand_path(dir)) Dir.glob(File.join(dir, path, "*.rb")).collect do |file| Pathname.new(file).relative_path_from(dir).to_s end end # @api private def module_directories(env) raise ArgumentError, "Autoloader requires an environment" unless env Puppet::Util::ModuleDirectoriesAdapter.adapt(env).directories end # @api private def gem_directories gem_source.directories end # @api private def search_directories(env) # This is a little bit of a hack. Basically, the autoloader is being # called indirectly during application bootstrapping when we do things # such as check "features". However, during bootstrapping, we haven't # yet parsed all of the command line parameters nor the config files, # and thus we don't yet know with certainty what the module path is. # This should be irrelevant during bootstrapping, because anything that # we are attempting to load during bootstrapping should be something # that we ship with puppet, and thus the module path is irrelevant. # # In the long term, I think the way that we want to handle this is to # have the autoloader ignore the module path in all cases where it is # not specifically requested (e.g., by a constructor param or # something)... because there are very few cases where we should # actually be loading code from the module path. However, until that # happens, we at least need a way to prevent the autoloader from # attempting to access the module path before it is initialized. For # now we are accomplishing that by calling the # "app_defaults_initialized?" method on the main puppet Settings object. # --cprice 2012-03-16 if Puppet.settings.app_defaults_initialized? gem_directories + module_directories(env) + $LOAD_PATH else gem_directories + $LOAD_PATH end end # Normalize a path. This converts ALT_SEPARATOR to SEPARATOR on Windows # and eliminates unnecessary parts of a path. def cleanpath(path) Pathname.new(path).cleanpath.to_s end end attr_accessor :object, :path def initialize(obj, path) @path = path.to_s raise ArgumentError, _("Autoload paths cannot be fully qualified") if Puppet::Util.absolute_path?(@path) @object = obj end def load(name, env) self.class.load_file(expand(name), env) end # Load all instances from a path of Autoload.search_directories matching the # relative path this Autoloader was initialized with. For example, if we # have created a Puppet::Util::Autoload for Puppet::Type::User with a path of # 'puppet/provider/user', the search_directories path will be searched for # all ruby files matching puppet/provider/user/*.rb and they will then be # loaded from the first directory in the search path providing them. So # earlier entries in the search path may shadow later entries. # # This uses require, rather than load, so that already-loaded files don't get # reloaded unnecessarily. def loadall(env) self.class.loadall(@path, env) end def loaded?(name) self.class.loaded?(expand(name)) end # @api private def changed?(name, env) self.class.changed?(expand(name), env) end def files_to_load(env) self.class.files_to_load(@path, env) end def expand(name) ::File.join(@path, name.to_s) 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/diff.rb
lib/puppet/util/diff.rb
# frozen_string_literal: true require 'tempfile' # Provide a diff between two strings. module Puppet::Util::Diff include Puppet::Util::Execution require 'tempfile' def diff(old, new) diff_cmd = Puppet[:diff] return '' unless diff_cmd && diff_cmd != "" command = [diff_cmd] args = Puppet[:diff_args] if args && args != "" args.split(' ').each do |arg| command << arg end end command << old << new Puppet::Util::Execution.execute(command, :failonfail => false, :combine => false) end module_function :diff # return diff string of two input strings # format defaults to unified # context defaults to 3 lines def lcs_diff(data_old, data_new, format = :unified, context_lines = 3) unless Puppet.features.diff? Puppet.warning _("Cannot provide diff without the diff/lcs Ruby library") return "" end data_old = data_old.split(/\n/).map!(&:chomp) data_new = data_new.split(/\n/).map!(&:chomp) output = ''.dup diffs = ::Diff::LCS.diff(data_old, data_new) return output if diffs.empty? oldhunk = hunk = nil file_length_difference = 0 diffs.each do |piece| hunk = ::Diff::LCS::Hunk.new( data_old, data_new, piece, context_lines, file_length_difference ) file_length_difference = hunk.file_length_difference next unless oldhunk # Hunks may overlap, which is why we need to be careful when our # diff includes lines of context. Otherwise, we might print # redundant lines. if (context_lines > 0) and hunk.overlaps?(oldhunk) hunk.unshift(oldhunk) else output << oldhunk.diff(format) end ensure oldhunk = hunk output << "\n" end # Handle the last remaining hunk output << oldhunk.diff(format) << "\n" end def string_file_diff(path, string) tempfile = Tempfile.new("puppet-diffing") tempfile.open tempfile.print string tempfile.close notice "\n" + diff(path, tempfile.path) tempfile.delete 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/monkey_patches.rb
lib/puppet/util/monkey_patches.rb
# frozen_string_literal: true require_relative '../../puppet/util/platform' module Puppet::Util::MonkeyPatches end begin Process.maxgroups = 1024 rescue NotImplementedError # Actually, I just want to ignore it, since various platforms - JRuby, # Windows, and so forth - don't support it, but only because it isn't a # meaningful or implementable concept there. end module RDoc def self.caller(skip = nil) in_gem_wrapper = false Kernel.caller.reject { |call| in_gem_wrapper ||= call =~ /#{Regexp.escape $PROGRAM_NAME}:\d+:in `load'/ } end end class Object # ActiveSupport 2.3.x mixes in a dangerous method # that can cause rspec to fork bomb # and other strange things like that. def daemonize raise NotImplementedError, "Kernel.daemonize is too dangerous, please don't try to use it." end end unless Dir.singleton_methods.include?(:exists?) class Dir def self.exists?(file_name) warn("Dir.exists?('#{file_name}') is deprecated, use Dir.exist? instead") if $VERBOSE Dir.exist?(file_name) end end end unless File.singleton_methods.include?(:exists?) class File def self.exists?(file_name) warn("File.exists?('#{file_name}') is deprecated, use File.exist? instead") if $VERBOSE File.exist?(file_name) end end end require_relative '../../puppet/ssl/openssl_loader' unless Puppet::Util::Platform.jruby_fips? class OpenSSL::SSL::SSLContext alias __original_initialize initialize private :__original_initialize def initialize(*args) __original_initialize(*args) params = { :options => DEFAULT_PARAMS[:options], :ciphers => DEFAULT_PARAMS[:ciphers], } set_params(params) end end end if Puppet::Util::Platform.windows? class OpenSSL::X509::Store @puppet_certs_loaded = false alias __original_set_default_paths set_default_paths def set_default_paths # This can be removed once openssl integrates with windows # cert store, see https://rt.openssl.org/Ticket/Display.html?id=2158 unless @puppet_certs_loaded @puppet_certs_loaded = true Puppet::Util::Windows::RootCerts.instance.to_a.uniq(&:to_der).each do |x509| add_cert(x509) rescue OpenSSL::X509::StoreError warn "Failed to add #{x509.subject.to_utf8}" end end __original_set_default_paths end end end unless Puppet::Util::Platform.jruby_fips? unless defined?(OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH) module OpenSSL::X509 OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH = 0x3E end end # jruby-openssl doesn't support this unless OpenSSL::X509::Name.instance_methods.include?(:to_utf8) class OpenSSL::X509::Name def to_utf8 # https://github.com/ruby/ruby/blob/v2_5_5/ext/openssl/ossl_x509name.c#L317 str = to_s(OpenSSL::X509::Name::RFC2253) str.force_encoding(Encoding::UTF_8) 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/execution_stub.rb
lib/puppet/util/execution_stub.rb
# frozen_string_literal: true module Puppet::Util class ExecutionStub class << self # Set a stub block that Puppet::Util::Execution.execute() should invoke instead # of actually executing commands on the target machine. Intended # for spec testing. # # The arguments passed to the block are |command, options|, where # command is an array of strings and options is an options hash. def set(&block) @value = block end # Uninstall any execution stub, so that calls to # Puppet::Util::Execution.execute() behave normally again. def reset @value = nil end # Retrieve the current execution stub, or nil if there is no stub. def current_value @value end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/plist.rb
lib/puppet/util/plist.rb
# frozen_string_literal: true require 'cfpropertylist' if Puppet.features.cfpropertylist? require_relative '../../puppet/util/execution' module Puppet::Util::Plist class FormatError < RuntimeError; end # So I don't have to prepend every method name with 'self.' Most of the # methods are going to be Provider methods (as opposed to methods of the # INSTANCE of the provider). class << self # Defines the magic number for binary plists # # @api private def binary_plist_magic_number "bplist00" end # Defines a default doctype string that should be at the top of most plist # files. Useful if we need to modify an invalid doctype string in memory. # In version 10.9 and lower of OS X the plist at # /System/Library/LaunchDaemons/org.ntp.ntpd.plist had an invalid doctype # string. This corrects for that. def plist_xml_doctype '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' end # Read a plist file, whether its format is XML or in Apple's "binary1" # format, using the CFPropertyList gem. def read_plist_file(file_path) # We can't really read the file until we know the source encoding in # Ruby 1.9.x, so we use the magic number to detect it. # NOTE: We used IO.read originally to be Ruby 1.8.x compatible. if read_file_with_offset(file_path, binary_plist_magic_number.length) == binary_plist_magic_number plist_obj = new_cfpropertylist(:file => file_path) return convert_cfpropertylist_to_native_types(plist_obj) else plist_data = open_file_with_args(file_path, "r:UTF-8") plist = parse_plist(plist_data, file_path) return plist if plist Puppet.debug "Plist #{file_path} ill-formatted, converting with plutil" begin plist = Puppet::Util::Execution.execute(['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', file_path], { :failonfail => true, :combine => true }) return parse_plist(plist) rescue Puppet::ExecutionFailure => detail message = _("Cannot read file %{file_path}; Puppet is skipping it.") % { file_path: file_path } message += '\n' + _("Details: %{detail}") % { detail: detail } Puppet.warning(message) end end nil end # Read plist text using the CFPropertyList gem. def parse_plist(plist_data, file_path = '') bad_xml_doctype = %r{^.*<!DOCTYPE plist PUBLIC -//Apple Computer.*$} # Depending on where parse_plist is called from, plist_data can be either XML or binary. # If we get XML, make sure ruby knows it's UTF-8 so we avoid invalid byte sequence errors. if plist_data.include?('encoding="UTF-8"') && plist_data.encoding != Encoding::UTF_8 plist_data.force_encoding(Encoding::UTF_8) end begin if plist_data =~ bad_xml_doctype plist_data.gsub!(bad_xml_doctype, plist_xml_doctype) Puppet.debug("Had to fix plist with incorrect DOCTYPE declaration: #{file_path}") end rescue ArgumentError => e Puppet.debug "Failed with #{e.class} on #{file_path}: #{e.inspect}" return nil end begin plist_obj = new_cfpropertylist(:data => plist_data) # CFPropertyList library will raise NoMethodError for invalid data rescue CFFormatError, NoMethodError => e Puppet.debug "Failed with #{e.class} on #{file_path}: #{e.inspect}" return nil end convert_cfpropertylist_to_native_types(plist_obj) end # Helper method to assist in reading a file. It's its own method for # stubbing purposes # # @api private # # @param args [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 def open_file_with_args(file, args) File.open(file, args).read end # Helper method to assist in generating a new CFPropertyList Plist. It's # its own method for stubbing purposes # # @api private def new_cfpropertylist(plist_opts) CFPropertyList::List.new(plist_opts) end # Helper method to assist in converting a native CFPropertyList object to a # native Ruby object (hash). It's its own method for stubbing purposes # # @api private def convert_cfpropertylist_to_native_types(plist_obj) CFPropertyList.native_types(plist_obj.value) end # Helper method to convert a string into a CFProperty::Blob, which is # needed to properly handle binary strings # # @api private def string_to_blob(str) CFPropertyList::Blob.new(str) end # Helper method to assist in reading a file with an offset value. It's its # own method for stubbing purposes # # @api private def read_file_with_offset(file_path, offset) IO.read(file_path, offset) end def to_format(format) case format.to_sym when :xml CFPropertyList::List::FORMAT_XML when :binary CFPropertyList::List::FORMAT_BINARY when :plain CFPropertyList::List::FORMAT_PLAIN else raise FormatError, "Unknown plist format #{format}" end end # This method will write a plist file using a specified format (or XML # by default) def write_plist_file(plist, file_path, format = :xml) plist_to_save = CFPropertyList::List.new plist_to_save.value = CFPropertyList.guess(plist) plist_to_save.save(file_path, to_format(format), :formatted => true) rescue IOError => e Puppet.err(_("Unable to write the file %{file_path}. %{error}") % { file_path: file_path, error: e.inspect }) end def dump_plist(plist_data, format = :xml) plist_to_save = CFPropertyList::List.new plist_to_save.value = CFPropertyList.guess(plist_data) plist_to_save.to_str(to_format(format), :formatted => 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/util/libuser.rb
lib/puppet/util/libuser.rb
# frozen_string_literal: true module Puppet::Util::Libuser def self.getconf File.expand_path('libuser.conf', __dir__) end def self.getenv newenv = {} newenv['LIBUSER_CONF'] = getconf newenv 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/http_proxy.rb
lib/puppet/util/http_proxy.rb
# frozen_string_literal: true require_relative '../../puppet/http' # for backwards compatibility Puppet::Util::HttpProxy = Puppet::HTTP::Proxy
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/errors.rb
lib/puppet/util/errors.rb
# frozen_string_literal: true # Some helper methods for throwing and populating errors. # # @api public module Puppet::Util::Errors # Throw a Puppet::DevError with the specified message. Used for unknown or # internal application failures. # # @param msg [String] message used in raised error # @raise [Puppet::DevError] always raised with the supplied message def devfail(msg) self.fail(Puppet::DevError, msg) end # Add line and file info to the supplied exception if info is available from # this object, is appropriately populated and the supplied exception supports # it. When other is supplied, the backtrace will be copied to the error # object and the 'original' will be dropped from the error. # # @param error [Exception] exception that is populated with info # @param other [Exception] original exception, source of backtrace info # @return [Exception] error parameter def adderrorcontext(error, other = nil) error.line ||= line if error.respond_to?(:line=) and respond_to?(:line) and line error.file ||= file if error.respond_to?(:file=) and respond_to?(:file) and file error.original ||= other if error.respond_to?(:original=) error.set_backtrace(other.backtrace) if other and other.respond_to?(:backtrace) # It is not meaningful to keep the wrapped exception since its backtrace has already # been adopted by the error. (The instance variable is private for good reasons). error.instance_variable_set(:@original, nil) error end # Return a human-readable string of this object's file, line, and pos attributes, # if set. # # @param file [String] the file path for the error (nil or "", for not known) # @param line [String] the line number for the error (nil or "", for not known) # @param column [String] the column number for the error (nil or "", for not known) # @return [String] description of file, line, and column # def self.error_location(file, line = nil, column = nil) file = nil if file.is_a?(String) && file.empty? line = nil if line.is_a?(String) && line.empty? column = nil if column.is_a?(String) && column.empty? if file and line and column _("(file: %{file}, line: %{line}, column: %{column})") % { file: file, line: line, column: column } elsif file and line _("(file: %{file}, line: %{line})") % { file: file, line: line } elsif line and column _("(line: %{line}, column: %{column})") % { line: line, column: column } elsif line _("(line: %{line})") % { line: line } elsif file _("(file: %{file})") % { file: file } else '' end end # Return a human-readable string of this object's file, line, and pos attributes, # with a proceeding space in the output # if set. # # @param file [String] the file path for the error (nil or "", for not known) # @param line [String] the line number for the error (nil or "", for not known) # @param column [String] the column number for the error (nil or "", for not known) # @return [String] description of file, line, and column # def self.error_location_with_space(file, line = nil, column = nil) error_location_str = error_location(file, line, column) if error_location_str.empty? '' else ' ' + error_location_str end end # Return a human-readable string of this object's file and line # where unknown entries are listed as 'unknown' # # @param file [String] the file path for the error (nil or "", for not known) # @param line [String] the line number for the error (nil or "", for not known) # @return [String] description of file, and line def self.error_location_with_unknowns(file, line) file = nil if file.is_a?(String) && file.empty? line = nil if line.is_a?(String) && line.empty? file ||= _('unknown') line ||= _('unknown') error_location(file, line) end # Return a human-readable string of this object's file and line attributes, # if set. # # @return [String] description of file and line with a leading space def error_context Puppet::Util::Errors.error_location_with_space(file, line) end # Wrap a call in such a way that we always throw the right exception and keep # as much context as possible. # # @param options [Hash<Symbol,Object>] options used to create error # @option options [Class] :type error type to raise, defaults to # Puppet::DevError # @option options [String] :message message to use in error, default mentions # the name of this class # @raise [Puppet::Error] re-raised with extra context if the block raises it # @raise [Error] of type options[:type], when the block raises other # exceptions def exceptwrap(options = {}) options[:type] ||= Puppet::DevError begin return yield rescue Puppet::Error => detail raise adderrorcontext(detail) rescue => detail message = options[:message] || _("%{klass} failed with error %{error_type}: %{detail}") % { klass: self.class, error_type: detail.class, detail: detail } error = options[:type].new(message) # We can't use self.fail here because it always expects strings, # not exceptions. raise adderrorcontext(error, detail) end retval end # Throw an error, defaulting to a Puppet::Error. # # @overload fail(message, ..) # Throw a Puppet::Error with a message concatenated from the given # arguments. # @param [String] message error message(s) # @overload fail(error_klass, message, ..) # Throw an exception of type error_klass with a message concatenated from # the given arguments. # @param [Class] type of error # @param [String] message error message(s) # @overload fail(error_klass, message, ..) # Throw an exception of type error_klass with a message concatenated from # the given arguments. # @param [Class] type of error # @param [String] message error message(s) # @param [Exception] original exception, source of backtrace info def fail(*args) if args[0].is_a?(Class) type = args.shift else type = Puppet::Error end other = args.count > 1 ? args.pop : nil error = adderrorcontext(type.new(args.join(" ")), other) raise error end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/lockfile.rb
lib/puppet/util/lockfile.rb
# frozen_string_literal: true # This class provides a simple API for managing a lock file # whose contents are an (optional) String. In addition # to querying the basic state (#locked?) of the lock, managing # the lock (#lock, #unlock), the contents can be retrieved at # any time while the lock is held (#lock_data). This can be # used to store pids, messages, etc. # # @see Puppet::Util::JsonLockfile class Puppet::Util::Lockfile attr_reader :file_path def initialize(file_path) @file_path = file_path end # Lock the lockfile. You may optionally pass a data object, which will be # retrievable for the duration of time during which the file is locked. # # @param [String] lock_data an optional String data object to associate # with the lock. This may be used to store pids, descriptive messages, # etc. The data may be retrieved at any time while the lock is held by # calling the #lock_data method. # @return [boolean] true if lock is successfully acquired, false otherwise. def lock(lock_data = nil) Puppet::FileSystem.exclusive_create(@file_path, nil) do |fd| fd.print(lock_data) end true rescue Errno::EEXIST false end def unlock if locked? Puppet::FileSystem.unlink(@file_path) true else false end end def locked? # delegate logic to a more explicit private method file_locked? end # Retrieve the (optional) lock data that was specified at the time the file # was locked. # @return [String] the data object. def lock_data File.read(@file_path) if file_locked? end # Private, internal utility method for encapsulating the logic about # whether or not the file is locked. This method can be called # by other methods in this class without as much risk of accidentally # being overridden by child classes. # @return [boolean] true if the file is locked, false if it is not. def file_locked? Puppet::FileSystem.exist? @file_path end private :file_locked? 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/profiler.rb
lib/puppet/util/profiler.rb
# frozen_string_literal: true require 'benchmark' # A simple profiling callback system. # # @api public module Puppet::Util::Profiler require_relative 'profiler/wall_clock' require_relative 'profiler/object_counts' require_relative 'profiler/around_profiler' @profiler = Puppet::Util::Profiler::AroundProfiler.new # Reset the profiling system to the original state # # @api private def self.clear @profiler.clear end # Retrieve the current list of profilers # # @api private def self.current @profiler.current end # @param profiler [#profile] A profiler for the current thread # @api private def self.add_profiler(profiler) @profiler.add_profiler(profiler) end # @param profiler [#profile] A profiler to remove from the current thread # @api private def self.remove_profiler(profiler) @profiler.remove_profiler(profiler) end # Profile a block of code and log the time it took to execute. # # This outputs logs entries to the Puppet masters logging destination # providing the time it took, a message describing the profiled code # and a leaf location marking where the profile method was called # in the profiled hierarchy. # # @param message [String] A description of the profiled event # @param metric_id [Array] A list of strings making up the ID of a metric to profile # @param block [Block] The segment of code to profile # @api public def self.profile(message, metric_id, &block) @profiler.profile(message, metric_id, &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/util/at_fork.rb
lib/puppet/util/at_fork.rb
# frozen_string_literal: true require_relative '../../puppet' # A module for building AtFork handlers. These handlers are objects providing # pre/post fork callbacks modeled after those registered by the `pthread_atfork` # function. # Currently there are two AtFork handler implementations: # - a noop implementation used on all platforms except Solaris (and possibly # even there as a fallback) # - a Solaris implementation which ensures the forked process runs in a different # contract than the parent process. This is necessary for agent runs started by # the puppet agent service to be able to restart that service without being # killed in the process as a consequence of running in the same contract as the # service. module Puppet::Util::AtFork @handler_class = loop do # rubocop:disable Lint/UnreachableLoop if Puppet::Util::Platform.solaris? begin require_relative 'at_fork/solaris' # using break to return a value from the loop block break Puppet::Util::AtFork::Solaris rescue LoadError => detail Puppet.log_exception(detail, _('Failed to load Solaris implementation of the Puppet::Util::AtFork handler. Child process contract management will be unavailable, which means that agent runs executed by the puppet agent service will be killed when they attempt to restart the service.')) # fall through to use the no-op implementation end end require_relative 'at_fork/noop' # using break to return a value from the loop block break Puppet::Util::AtFork::Noop end def self.get_handler @handler_class.new end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/filetype.rb
lib/puppet/util/filetype.rb
# frozen_string_literal: true # Basic classes for reading, writing, and emptying files. Not much # to see here. require_relative '../../puppet/util/selinux' require 'tempfile' require 'fileutils' class Puppet::Util::FileType attr_accessor :loaded, :path, :synced class FileReadError < Puppet::Error; end include Puppet::Util::SELinux class << self attr_accessor :name include Puppet::Util::ClassGen end # Create a new filetype. def self.newfiletype(name, &block) @filetypes ||= {} klass = genclass( name, :block => block, :prefix => "FileType", :hash => @filetypes ) # Rename the read and write methods, so that we're sure they # maintain the stats. klass.class_eval do # Rename the read method define_method(:real_read, instance_method(:read)) define_method(:read) do val = real_read @loaded = Time.now if val val.gsub(/# HEADER.*\n/, '') else "" end rescue Puppet::Error raise rescue => detail message = _("%{klass} could not read %{path}: %{detail}") % { klass: self.class, path: @path, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end # And then the write method define_method(:real_write, instance_method(:write)) define_method(:write) do |text| val = real_write(text) @synced = Time.now val rescue Puppet::Error raise rescue => detail message = _("%{klass} could not write %{path}: %{detail}") % { klass: self.class, path: @path, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end end end def self.filetype(type) @filetypes[type] end # Pick or create a filebucket to use. def bucket @bucket ||= Puppet::Type.type(:filebucket).mkdefaultbucket.bucket end def initialize(path, default_mode = nil) raise ArgumentError, _("Path is nil") if path.nil? @path = path @default_mode = default_mode end # Arguments that will be passed to the execute method. Will set the uid # to the target user if the target user and the current user are not # the same def cronargs uid = Puppet::Util.uid(@path) if uid && uid == Puppet::Util::SUIDManager.uid { :failonfail => true, :combine => true } else { :failonfail => true, :combine => true, :uid => @path } end end # Operate on plain files. newfiletype(:flat) do # Back the file up before replacing it. def backup bucket.backup(@path) if Puppet::FileSystem.exist?(@path) end # Read the file. def read if Puppet::FileSystem.exist?(@path) # this code path is used by many callers so the original default is # being explicitly preserved Puppet::FileSystem.read(@path, :encoding => Encoding.default_external) else nil end end # Remove the file. def remove Puppet::FileSystem.unlink(@path) if Puppet::FileSystem.exist?(@path) end # Overwrite the file. def write(text) # this file is managed by the OS and should be using system encoding tf = Tempfile.new("puppet", :encoding => Encoding.default_external) tf.print text; tf.flush File.chmod(@default_mode, tf.path) if @default_mode FileUtils.cp(tf.path, @path) tf.close # If SELinux is present, we need to ensure the file has its expected context set_selinux_default_context(@path) end end # Operate on plain files. newfiletype(:ram) do @@tabs = {} def self.clear @@tabs.clear end def initialize(path, default_mode = nil) # default_mode is meaningless for this filetype, # supported only for compatibility with :flat super @@tabs[@path] ||= "" end # Read the file. def read Puppet.info _("Reading %{path} from RAM") % { path: @path } @@tabs[@path] end # Remove the file. def remove Puppet.info _("Removing %{path} from RAM") % { path: @path } @@tabs[@path] = "" end # Overwrite the file. def write(text) Puppet.info _("Writing %{path} to RAM") % { path: @path } @@tabs[@path] = text end end # Handle Linux-style cron tabs. # # TODO: We can possibly eliminate the "-u <username>" option in cmdbase # by just running crontab under <username>'s uid (like we do for suntab # and aixtab). It may be worth investigating this alternative # implementation in the future. This way, we can refactor all three of # our cron file types into a common crontab file type. newfiletype(:crontab) do def initialize(user) self.path = user end def path=(user) begin @uid = Puppet::Util.uid(user) rescue Puppet::Error => detail raise FileReadError, _("Could not retrieve user %{user}: %{detail}") % { user: user, detail: detail }, detail.backtrace end # XXX We have to have the user name, not the uid, because some # systems *cough*linux*cough* require it that way @path = user end # Read a specific @path's cron tab. def read unless Puppet::Util.uid(@path) Puppet.debug _("The %{path} user does not exist. Treating their crontab file as empty in case Puppet creates them in the middle of the run.") % { path: @path } return "" end Puppet::Util::Execution.execute("#{cmdbase} -l", failonfail: true, combine: true) rescue => detail case detail.to_s when /no crontab for/ "" when /are not allowed to/ Puppet.debug _("The %{path} user is not authorized to use cron. Their crontab file is treated as empty in case Puppet authorizes them in the middle of the run (by, for example, modifying the cron.deny or cron.allow files).") % { path: @path } "" else raise FileReadError, _("Could not read crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end end # Remove a specific @path's cron tab. def remove cmd = "#{cmdbase} -r" if %w[Darwin FreeBSD DragonFly].include?(Puppet.runtime[:facter].value('os.name')) cmd = "/bin/echo yes | #{cmd}" end Puppet::Util::Execution.execute(cmd, failonfail: true, combine: true) end # Overwrite a specific @path's cron tab; must be passed the @path name # and the text with which to create the cron tab. # # TODO: We should refactor this at some point to make it identical to the # :aixtab and :suntab's write methods so that, at the very least, the pipe # is not created and the crontab command's errors are not swallowed. def write(text) unless Puppet::Util.uid(@path) raise Puppet::Error, _("Cannot write the %{path} user's crontab: The user does not exist") % { path: @path } end # this file is managed by the OS and should be using system encoding IO.popen("#{cmdbase()} -", "w", :encoding => Encoding.default_external) { |p| p.print text } end private # Only add the -u flag when the @path is different. Fedora apparently # does not think I should be allowed to set the @path to my own user name def cmdbase if @uid == Puppet::Util::SUIDManager.uid || Puppet.runtime[:facter].value('os.name') == "HP-UX" "crontab" else "crontab -u #{@path}" end end end # SunOS has completely different cron commands; this class implements # its versions. newfiletype(:suntab) do # Read a specific @path's cron tab. def read unless Puppet::Util.uid(@path) Puppet.debug _("The %{path} user does not exist. Treating their crontab file as empty in case Puppet creates them in the middle of the run.") % { path: @path } return "" end Puppet::Util::Execution.execute(%w[crontab -l], cronargs) rescue => detail case detail.to_s when /can't open your crontab/ "" when /you are not authorized to use cron/ Puppet.debug _("The %{path} user is not authorized to use cron. Their crontab file is treated as empty in case Puppet authorizes them in the middle of the run (by, for example, modifying the cron.deny or cron.allow files).") % { path: @path } "" else raise FileReadError, _("Could not read crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end end # Remove a specific @path's cron tab. def remove Puppet::Util::Execution.execute(%w[crontab -r], cronargs) rescue => detail raise FileReadError, _("Could not remove crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end # Overwrite a specific @path's cron tab; must be passed the @path name # and the text with which to create the cron tab. def write(text) # this file is managed by the OS and should be using system encoding output_file = Tempfile.new("puppet_suntab", :encoding => Encoding.default_external) begin output_file.print text output_file.close # We have to chown the stupid file to the user. File.chown(Puppet::Util.uid(@path), nil, output_file.path) Puppet::Util::Execution.execute(["crontab", output_file.path], cronargs) rescue => detail raise FileReadError, _("Could not write crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace ensure output_file.close output_file.unlink end end end # Support for AIX crontab with output different than suntab's crontab command. newfiletype(:aixtab) do # Read a specific @path's cron tab. def read unless Puppet::Util.uid(@path) Puppet.debug _("The %{path} user does not exist. Treating their crontab file as empty in case Puppet creates them in the middle of the run.") % { path: @path } return "" end Puppet::Util::Execution.execute(%w[crontab -l], cronargs) rescue => detail case detail.to_s when /open.*in.*directory/ "" when /not.*authorized.*cron/ Puppet.debug _("The %{path} user is not authorized to use cron. Their crontab file is treated as empty in case Puppet authorizes them in the middle of the run (by, for example, modifying the cron.deny or cron.allow files).") % { path: @path } "" else raise FileReadError, _("Could not read crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end end # Remove a specific @path's cron tab. def remove Puppet::Util::Execution.execute(%w[crontab -r], cronargs) rescue => detail raise FileReadError, _("Could not remove crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace end # Overwrite a specific @path's cron tab; must be passed the @path name # and the text with which to create the cron tab. def write(text) # this file is managed by the OS and should be using system encoding output_file = Tempfile.new("puppet_aixtab", :encoding => Encoding.default_external) begin output_file.print text output_file.close # We have to chown the stupid file to the user. File.chown(Puppet::Util.uid(@path), nil, output_file.path) Puppet::Util::Execution.execute(["crontab", output_file.path], cronargs) rescue => detail raise FileReadError, _("Could not write crontab for %{path}: %{detail}") % { path: @path, detail: detail }, detail.backtrace ensure output_file.close output_file.unlink 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/instance_loader.rb
lib/puppet/util/instance_loader.rb
# frozen_string_literal: true require_relative '../../puppet/util/autoload' require_relative '../../puppet/util' require_relative '../../puppet/concurrent/lock' # A module that can easily autoload things for us. Uses an instance # of Puppet::Util::Autoload module Puppet::Util::InstanceLoader include Puppet::Util # Are we instance-loading this type? def instance_loading?(type) defined?(@autoloaders) and @autoloaders.include?(type.intern) end # Define a new type of autoloading. def instance_load(type, path) @autoloaders ||= {} @instances ||= {} type = type.intern @instances[type] = {} @autoloaders[type] = Puppet::Util::Autoload.new(self, path) @instance_loader_lock = Puppet::Concurrent::Lock.new # Now define our new simple methods unless respond_to?(type) meta_def(type) do |name| loaded_instance(type, name) end end end # Return a list of the names of all instances def loaded_instances(type) @instances[type].keys end # Return the instance hash for our type. def instance_hash(type) @instances[type.intern] end # Return the Autoload object for a given type. def instance_loader(type) @autoloaders[type.intern] end # Retrieve an already-loaded instance, or attempt to load our instance. def loaded_instance(type, name) @instance_loader_lock.synchronize do name = name.intern instances = instance_hash(type) return nil unless instances unless instances.include? name if instance_loader(type).load(name, Puppet.lookup(:current_environment)) unless instances.include? name Puppet.warning(_("Loaded %{type} file for %{name} but %{type} was not defined") % { type: type, name: name }) return nil end else return nil end end instances[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/util/package.rb
lib/puppet/util/package.rb
# frozen_string_literal: true module Puppet::Util::Package def versioncmp(version_a, version_b, ignore_trailing_zeroes = false) vre = /[-.]|\d+|[^-.\d]+/ if ignore_trailing_zeroes version_a = normalize(version_a) version_b = normalize(version_b) end ax = version_a.scan(vre) bx = version_b.scan(vre) while ax.length > 0 && bx.length > 0 a = ax.shift b = bx.shift next if a == b return -1 if a == '-' return 1 if b == '-' return -1 if a == '.' return 1 if b == '.' if a =~ /^\d+$/ && b =~ /^\d+$/ return a.to_s.upcase <=> b.to_s.upcase if a =~ /^0/ || b =~ /^0/ return a.to_i <=> b.to_i end return a.upcase <=> b.upcase end version_a <=> version_b end module_function :versioncmp def self.normalize(version) version = version.split('-') version.first.sub!(/([.0]+)$/, '') version.join('-') end private_class_method :normalize 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.rb
lib/puppet/util/rdoc.rb
# frozen_string_literal: true require_relative '../../puppet/util' module Puppet::Util::RDoc module_function # launch a rdoc documentation process # with the files/dir passed in +files+ def rdoc(outputdir, files, charset = nil) # then rdoc require 'rdoc/rdoc' require 'rdoc/options' # load our parser require_relative 'rdoc/parser' r = RDoc::RDoc.new # specify our own format & where to output options = ["--fmt", "puppet", "--quiet", "--exclude", "/modules/[^/]*/spec/.*$", "--exclude", "/modules/[^/]*/files/.*$", "--exclude", "/modules/[^/]*/tests/.*$", "--exclude", "/modules/[^/]*/templates/.*$", "--op", outputdir] options << "--force-update" options += ["--charset", charset] if charset options += files # launch the documentation process r.document(options) end # launch an output to console manifest doc def manifestdoc(files) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end # Outputs to the console the documentation # of a manifest def output(file, ast) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end def output_astnode_doc(ast) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") end def output_resource_doc(code) raise _("RDOC SUPPORT FOR MANIFEST HAS BEEN REMOVED - See PUP-3638") 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.rb
lib/puppet/util/log.rb
# frozen_string_literal: true require_relative '../../puppet/util/tagging' require_relative '../../puppet/util/classgen' require_relative '../../puppet/util/psych_support' require_relative '../../puppet/network/format_support' # Pass feedback to the user. Log levels are modeled after syslog's, and it is # expected that that will be the most common log destination. Supports # multiple destinations, one of which is a remote server. class Puppet::Util::Log include Puppet::Util extend Puppet::Util::ClassGen include Puppet::Util::PsychSupport include Puppet::Util::Tagging include Puppet::Network::FormatSupport @levels = [:debug, :info, :notice, :warning, :err, :alert, :emerg, :crit] @loglevel = 2 @desttypes = {} # Create a new destination type. def self.newdesttype(name, options = {}, &block) dest = genclass( name, :parent => Puppet::Util::Log::Destination, :prefix => "Dest", :block => block, :hash => @desttypes, :attributes => options ) dest.match(dest.name) dest end require_relative 'log/destination' require_relative 'log/destinations' @destinations = {} @queued = [] class << self include Puppet::Util include Puppet::Util::ClassGen attr_reader :desttypes end # Reset log to basics. Basically just flushes and closes files and # undefs other objects. def Log.close(destination) if @destinations.include?(destination) @destinations[destination].flush if @destinations[destination].respond_to?(:flush) @destinations[destination].close if @destinations[destination].respond_to?(:close) @destinations.delete(destination) end end def self.close_all @destinations.keys.each { |dest| close(dest) } # TRANSLATORS "Log.close_all" is a method name and should not be translated raise Puppet::DevError, _("Log.close_all failed to close %{destinations}") % { destinations: @destinations.keys.inspect } unless @destinations.empty? end # Flush any log destinations that support such operations. def Log.flush @destinations.each { |_type, dest| dest.flush if dest.respond_to?(:flush) } end def Log.autoflush=(v) @destinations.each do |_type, dest| dest.autoflush = v if dest.respond_to?(:autoflush=) end end # Create a new log message. The primary role of this method is to # avoid creating log messages below the loglevel. def Log.create(hash) raise Puppet::DevError, _("Logs require a level") unless hash.include?(:level) raise Puppet::DevError, _("Invalid log level %{level}") % { level: hash[:level] } unless @levels.index(hash[:level]) @levels.index(hash[:level]) >= @loglevel ? Puppet::Util::Log.new(hash) : nil end def Log.destinations @destinations end # Yield each valid level in turn def Log.eachlevel @levels.each { |level| yield level } end # Return the current log level. def Log.level @levels[@loglevel] end # Set the current log level. def Log.level=(level) level = level.intern unless level.is_a?(Symbol) # loglevel is a 0-based index loglevel = @levels.index(level) raise Puppet::DevError, _("Invalid loglevel %{level}") % { level: level } unless loglevel return if @loglevel == loglevel # loglevel changed @loglevel = loglevel # Enable or disable Facter debugging Puppet.runtime[:facter].debugging(level == :debug) end def Log.levels @levels.dup end # Create a new log destination. def Log.newdestination(dest) # Each destination can only occur once. if @destinations.find { |_name, obj| obj.name == dest } return end _, type = @desttypes.find do |_name, klass| klass.match?(dest) end if type.respond_to?(:suitable?) and !type.suitable?(dest) return end raise Puppet::DevError, _("Unknown destination type %{dest}") % { dest: dest } unless type begin if type.instance_method(:initialize).arity == 1 @destinations[dest] = type.new(dest) else @destinations[dest] = type.new end flushqueue @destinations[dest] rescue => detail Puppet.log_exception(detail) # If this was our only destination, then add the console back in. if destinations.empty? && dest.intern != :console newdestination(:console) end # Re-raise (end exit Puppet) because we could not set up logging correctly. raise detail end end def Log.with_destination(destination, &block) if @destinations.include?(destination) yield else newdestination(destination) begin yield ensure close(destination) end end end def Log.coerce_string(str) return Puppet::Util::CharacterEncoding.convert_to_utf_8(str) if str.valid_encoding? # We only select the last 10 callers in the stack to avoid being spammy message = _("Received a Log attribute with invalid encoding:%{log_message}") % { log_message: Puppet::Util::CharacterEncoding.convert_to_utf_8(str.dump) } message += '\n' + _("Backtrace:\n%{backtrace}") % { backtrace: caller(1, 10).join("\n") } message end private_class_method :coerce_string # Route the actual message. FIXME There are lots of things this method # should do, like caching and a bit more. It's worth noting that there's # a potential for a loop here, if the machine somehow gets the destination set as # itself. def Log.newmessage(msg) return if @levels.index(msg.level) < @loglevel msg.message = coerce_string(msg.message) msg.source = coerce_string(msg.source) queuemessage(msg) if @destinations.length == 0 @destinations.each do |_name, dest| dest.handle(msg) end end def Log.queuemessage(msg) @queued.push(msg) end def Log.flushqueue return unless @destinations.size >= 1 @queued.each do |msg| Log.newmessage(msg) end @queued.clear end # Flush the logging queue. If there are no destinations available, # adds in a console logger before flushing the queue. # This is mainly intended to be used as a last-resort attempt # to ensure that logging messages are not thrown away before # the program is about to exit--most likely in a horrific # error scenario. # @return nil def Log.force_flushqueue if @destinations.empty? and !@queued.empty? newdestination(:console) end flushqueue end def Log.sendlevel?(level) @levels.index(level) >= @loglevel end # Reopen all of our logs. def Log.reopen Puppet.notice _("Reopening log files") types = @destinations.keys @destinations.each { |_type, dest| dest.close if dest.respond_to?(:close) } @destinations.clear # We need to make sure we always end up with some kind of destination begin types.each { |type| Log.newdestination(type) } rescue => detail if @destinations.empty? Log.setup_default Puppet.err detail.to_s end end end def self.setup_default Log.newdestination( if Puppet.features.syslog? :syslog else Puppet.features.eventlog? ? :eventlog : Puppet[:puppetdlog] end ) end # Is the passed level a valid log level? def self.validlevel?(level) @levels.include?(level) end def self.from_data_hash(data) obj = allocate obj.initialize_from_hash(data) obj end # Log output using scope and level # # @param [Puppet::Parser::Scope] scope # @param [Symbol] level log level # @param [Array<Object>] vals the values to log (will be converted to string and joined with space) # def self.log_func(scope, level, vals) # NOTE: 3x, does this: vals.join(" ") # New implementation uses the evaluator to get proper formatting per type vals = vals.map { |v| Puppet::Pops::Evaluator::EvaluatorImpl.new.string(v, scope) } # Bypass Puppet.<level> call since it picks up source from "self" which is not applicable in the 4x # Function API. # TODO: When a function can obtain the file, line, pos of the call merge those in (3x supports # options :file, :line. (These were never output when calling the 3x logging functions since # 3x scope does not know about the calling location at that detailed level, nor do they # appear in a report to stdout/error when included). Now, the output simply uses scope (like 3x) # as this is good enough, but does not reflect the true call-stack, but is a rough estimate # of where the logging call originates from). # Puppet::Util::Log.create({ :level => level, :source => scope, :message => vals.join(" ") }) nil end attr_accessor :time, :remote, :file, :line, :pos, :issue_code, :environment, :node, :backtrace attr_reader :level, :message, :source def initialize(args) self.level = args[:level] self.message = args[:message] self.source = args[:source] || "Puppet" @time = Time.now tags = args[:tags] if tags tags.each { |t| tag(t) } end # Don't add these unless defined (preserve 3.x API as much as possible) [:file, :line, :pos, :issue_code, :environment, :node, :backtrace].each do |attr| value = args[attr] next unless value send(attr.to_s + '=', value) end Log.newmessage(self) end def initialize_from_hash(data) @level = data['level'].intern @message = data['message'] @source = data['source'] @tags = Puppet::Util::TagSet.new(data['tags']) @time = data['time'] if @time.is_a? String @time = Time.parse(@time) end # Don't add these unless defined (preserve 3.x API as much as possible) %w[file line pos issue_code environment node backtrace].each do |name| value = data[name] next unless value send(name + '=', value) end end def to_hash to_data_hash end def to_data_hash { 'level' => @level.to_s, 'message' => to_s, 'source' => @source, 'tags' => @tags.to_a, 'time' => @time.iso8601(9), 'file' => @file, 'line' => @line, } end def to_structured_hash hash = { 'level' => @level, 'message' => @message, 'source' => @source, 'tags' => @tags.to_a, 'time' => @time.iso8601(9), } %w[file line pos issue_code environment node backtrace].each do |name| attr_name = "@#{name}" hash[name] = instance_variable_get(attr_name) if instance_variable_defined?(attr_name) end hash end def message=(msg) # TRANSLATORS 'Puppet::Util::Log' refers to a Puppet source code class raise ArgumentError, _("Puppet::Util::Log requires a message") unless msg @message = msg.to_s end def level=(level) # TRANSLATORS 'Puppet::Util::Log' refers to a Puppet source code class raise ArgumentError, _("Puppet::Util::Log requires a log level") unless level # TRANSLATORS 'Puppet::Util::Log' refers to a Puppet source code class raise ArgumentError, _("Puppet::Util::Log requires a symbol or string") unless level.respond_to? "to_sym" @level = level.to_sym raise ArgumentError, _("Invalid log level %{level}") % { level: @level } unless self.class.validlevel?(@level) # Tag myself with my log level tag(level) end # If they pass a source in to us, we make sure it is a string, and # we retrieve any tags we can. def source=(source) if defined?(Puppet::Type) && source.is_a?(Puppet::Type) @source = source.path merge_tags_from(source) self.file = source.file self.line = source.line else @source = source.to_s end end def to_report "#{time} #{source} (#{level}): #{self}" end def to_s msg = message # Issue based messages do not have details in the message. It # must be appended here unless issue_code.nil? msg = _("Could not parse for environment %{environment}: %{msg}") % { environment: environment, msg: msg } unless environment.nil? msg += Puppet::Util::Errors.error_location_with_space(file, line, pos) msg = _("%{msg} on node %{node}") % { msg: msg, node: node } unless node.nil? if @backtrace.is_a?(Array) msg += "\n" msg += @backtrace.join("\n") end end msg end end # This is for backward compatibility from when we changed the constant to # Puppet::Util::Log because the reports include the constant name. It was # considered for removal but left in due to risk of breakage (PUP-7502). Puppet::Log = Puppet::Util::Log
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/docs.rb
lib/puppet/util/docs.rb
# frozen_string_literal: true # Some simple methods for helping manage automatic documentation generation. module Puppet::Util::Docs # Specify the actual doc string. def desc(str) @doc = str end # Add a new autodoc block. We have to define these as class methods, # rather than just sticking them in a hash, because otherwise they're # too difficult to do inheritance with. def dochook(name, &block) method = "dochook_#{name}" meta_def method, &block end attr_writer :doc # Generate the full doc string. def doc extra = methods.find_all { |m| m.to_s =~ /^dochook_.+/ }.sort.filter_map { |m| send(m) }.collect { |r| "* #{r}" }.join("\n") if @doc scrub(@doc) + (extra.empty? ? '' : "\n\n#{extra}") else extra end end # Build a table def doctable(headers, data) str = "\n\n" lengths = [] # Figure out the longest field for all columns data.each do |name, values| [name, values].flatten.each_with_index do |value, i| lengths[i] ||= 0 lengths[i] = value.to_s.length if value.to_s.length > lengths[i] end end # The headers could also be longest headers.each_with_index do |value, i| lengths[i] = value.to_s.length if value.to_s.length > lengths[i] end # Add the header names str += headers.zip(lengths).collect { |value, num| pad(value, num) }.join(" | ") + " |" + "\n" # And the header row str += lengths.collect { |num| "-" * num }.join(" | ") + " |" + "\n" # Now each data row data.sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, rows| str += [name, rows].flatten.zip(lengths).collect do |value, length| pad(value, length) end.join(" | ") + " |" + "\n" end str + "\n" end # There is nothing that would ever set this. It gets read in reference/type.rb, but will never have any value but nil. attr_reader :nodoc def nodoc? nodoc end # Pad a field with spaces def pad(value, length) value.to_s + (" " * (length - value.to_s.length)) end HEADER_LEVELS = [nil, "#", "##", "###", "####", "#####"] def markdown_header(name, level) "#{HEADER_LEVELS[level]} #{name}\n\n" end def markdown_definitionlist(term, definition) lines = scrub(definition).split("\n") str = "#{term}\n: #{lines.shift}\n" lines.each do |line| str << " " if line =~ /\S/ str << "#{line}\n" end str << "\n" end # Strip indentation and trailing whitespace from embedded doc fragments. # # Multi-line doc fragments are sometimes indented in order to preserve the # formatting of the code they're embedded in. Since indents are syntactic # elements in Markdown, we need to make sure we remove any indent that was # added solely to preserve surrounding code formatting, but LEAVE any indent # that delineates a Markdown element (code blocks, multi-line bulleted list # items). We can do this by removing the *least common indent* from each line. # # Least common indent is defined as follows: # # * Find the smallest amount of leading space on any line... # * ...excluding the first line (which may have zero indent without affecting # the common indent)... # * ...and excluding lines that consist solely of whitespace. # * The least common indent may be a zero-length string, if the fragment is # not indented to match code. # * If there are hard tabs for some dumb reason, we assume they're at least # consistent within this doc fragment. # # See tests in spec/unit/util/docs_spec.rb for examples. def scrub(text) # One-liners are easy! (One-liners may be buffered with extra newlines.) return text.strip if text.strip !~ /\n/ excluding_first_line = text.partition("\n").last indent = excluding_first_line.scan(/^[ \t]*(?=\S)/).min || '' # prevent nil # Clean hanging indent, if any if indent.length > 0 text = text.gsub(/^#{indent}/, '') end # Clean trailing space text.lines.map(&:rstrip).join("\n").rstrip end module_function :scrub 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/logging.rb
lib/puppet/util/logging.rb
# frozen_string_literal: true # A module to make logging a bit easier. require_relative '../../puppet/util/log' require_relative '../../puppet/error' module Puppet::Util module Logging def send_log(level, message) Puppet::Util::Log.create({ :level => level, :source => log_source, :message => message }.merge(log_metadata)) end # Create a method for each log level. Puppet::Util::Log.eachlevel do |level| # handle debug a special way for performance reasons next if level == :debug define_method(level) do |args| args = args.join(" ") if args.is_a?(Array) send_log(level, args) end end # Output a debug log message if debugging is on (but only then) # If the output is anything except a static string, give the debug # a block - it will be called with all other arguments, and is expected # to return the single string result. # # Use a block at all times for increased performance. # # @example This takes 40% of the time compared to not using a block # Puppet.debug { "This is a string that interpolated #{x} and #{y} }" # def debug(*args) return nil unless Puppet::Util::Log.level == :debug if block_given? send_log(:debug, yield(*args)) else send_log(:debug, args.join(" ")) end end # Log an exception via Puppet.err. Will also log the backtrace if Puppet[:trace] is set. # Parameters: # [exception] an Exception to log # [message] an optional String overriding the message to be logged; by default, we log Exception.message. # If you pass a String here, your string will be logged instead. You may also pass nil if you don't # wish to log a message at all; in this case it is likely that you are only calling this method in order # to take advantage of the backtrace logging. def log_exception(exception, message = :default, options = {}) level = options[:level] || :err combined_trace = Puppet[:trace] || options[:trace] puppet_trace = Puppet[:puppet_trace] || options[:puppet_trace] if message == :default && exception.is_a?(Puppet::ParseErrorWithIssue) # Retain all detailed info and keep plain message and stacktrace separate backtrace = build_exception_trace(exception, combined_trace, puppet_trace) Puppet::Util::Log.create({ :level => level, :source => log_source, :message => exception.basic_message, :issue_code => exception.issue_code, :backtrace => backtrace.empty? ? nil : backtrace, :file => exception.file, :line => exception.line, :pos => exception.pos, :environment => exception.environment, :node => exception.node }.merge(log_metadata)) else send_log(level, format_exception(exception, message, combined_trace, puppet_trace)) end end def build_exception_trace(exception, combined_trace = true, puppet_trace = false) built_trace = format_backtrace(exception, combined_trace, puppet_trace) if exception.respond_to?(:original) original = exception.original unless original.nil? built_trace << _('Wrapped exception:') built_trace << original.message built_trace += build_exception_trace(original, combined_trace, puppet_trace) end end built_trace end private :build_exception_trace def format_exception(exception, message = :default, combined_trace = true, puppet_trace = false) arr = [] case message when :default arr << exception.message when nil # don't log anything if they passed a nil; they are just calling for the optional backtrace logging else arr << message end arr += format_backtrace(exception, combined_trace, puppet_trace) if exception.respond_to?(:original) and exception.original arr << _("Wrapped exception:") arr << format_exception(exception.original, :default, combined_trace, puppet_trace) end arr.flatten.join("\n") end def format_backtrace(exception, combined_trace, puppet_trace) puppetstack = exception.respond_to?(:puppetstack) ? exception.puppetstack : [] if combined_trace and exception.backtrace Puppet::Util.format_backtrace_array(exception.backtrace, puppetstack) elsif puppet_trace && !puppetstack.empty? Puppet::Util.format_backtrace_array(puppetstack) else [] end end def log_and_raise(exception, message) log_exception(exception, message) raise exception, message + "\n" + exception.to_s, exception.backtrace end class DeprecationWarning < Exception; end # rubocop:disable Lint/InheritException # Logs a warning indicating that the Ruby code path is deprecated. Note that # this method keeps track of the offending lines of code that triggered the # deprecation warning, and will only log a warning once per offending line of # code. It will also stop logging deprecation warnings altogether after 100 # unique deprecation warnings have been logged. Finally, if # Puppet[:disable_warnings] includes 'deprecations', it will squelch all # warning calls made via this method. # # @param message [String] The message to log (logs via warning) # @param key [String] Optional key to mark the message as unique. If not # passed in, the originating call line will be used instead. def deprecation_warning(message, key = nil) issue_deprecation_warning(message, key, nil, nil, true) end # Logs a warning whose origin comes from Puppet source rather than somewhere # internal within Puppet. Otherwise the same as deprecation_warning() # # @param message [String] The message to log (logs via warning) # @param options [Hash] # @option options [String] :file File we are warning from # @option options [Integer] :line Line number we are warning from # @option options [String] :key (:file + :line) Alternative key used to mark # warning as unique # # Either :file and :line and/or :key must be passed. def puppet_deprecation_warning(message, options = {}) key = options[:key] file = options[:file] line = options[:line] # TRANSLATORS the literals ":file", ":line", and ":key" should not be translated raise Puppet::DevError, _("Need either :file and :line, or :key") if key.nil? && (file.nil? || line.nil?) key ||= "#{file}:#{line}" issue_deprecation_warning(message, key, file, line, false) end # Logs a (non deprecation) warning once for a given key. # # @param kind [String] The kind of warning. The # kind must be one of the defined kinds for the Puppet[:disable_warnings] setting. # @param message [String] The message to log (logs via warning) # @param key [String] Key used to make this warning unique # @param file [String,:default,nil] the File related to the warning # @param line [Integer,:default,nil] the Line number related to the warning # warning as unique # @param level [Symbol] log level to use, defaults to :warning # # Either :file and :line and/or :key must be passed. def warn_once(kind, key, message, file = nil, line = nil, level = :warning) return if Puppet[:disable_warnings].include?(kind) $unique_warnings ||= {} if $unique_warnings.length < 100 then unless $unique_warnings.has_key?(key) then $unique_warnings[key] = message call_trace = if file == :default and line == :default # Suppress the file and line number output '' else error_location_str = Puppet::Util::Errors.error_location(file, line) if error_location_str.empty? "\n " + _('(file & line not available)') else "\n %{error_location}" % { error_location: error_location_str } end end send_log(level, "#{message}#{call_trace}") end end end def get_deprecation_offender # we have to put this in its own method to simplify testing; we need to be able to mock the offender results in # order to test this class, and our framework does not appear to enjoy it if you try to mock Kernel.caller # # let's find the offending line; we need to jump back up the stack a few steps to find the method that called # the deprecated method if Puppet[:trace] caller(3) else [caller(3, 1).first] end end def clear_deprecation_warnings $unique_warnings.clear if $unique_warnings $deprecation_warnings.clear if $deprecation_warnings end # TODO: determine whether there might be a potential use for adding a puppet configuration option that would # enable this deprecation logging. # utility method that can be called, e.g., from spec_helper config.after, when tracking down calls to deprecated # code. # Parameters: # [deprecations_file] relative or absolute path of a file to log the deprecations to # [pattern] (default nil) if specified, will only log deprecations whose message matches the provided pattern def log_deprecations_to_file(deprecations_file, pattern = nil) # this method may get called lots and lots of times (e.g., from spec_helper config.after) without the global # list of deprecation warnings being cleared out. We don't want to keep logging the same offenders over and over, # so, we need to keep track of what we've logged. # # It'd be nice if we could just clear out the list of deprecation warnings, but then the very next spec might # find the same offender, and we'd end up logging it again. $logged_deprecation_warnings ||= {} # Deprecation messages are UTF-8 as they are produced by Ruby Puppet::FileSystem.open(deprecations_file, nil, "a:UTF-8") do |f| if $deprecation_warnings then $deprecation_warnings.each do |offender, message| next if $logged_deprecation_warnings.has_key?(offender) $logged_deprecation_warnings[offender] = true next unless pattern.nil? || (message =~ pattern) f.puts(message) f.puts(offender) f.puts() end end end end # Sets up Facter logging. # This method causes Facter output to be forwarded to Puppet. def self.setup_facter_logging! Puppet.runtime[:facter] true end private def issue_deprecation_warning(message, key, file, line, use_caller) return if Puppet[:disable_warnings].include?('deprecations') $deprecation_warnings ||= {} if $deprecation_warnings.length < 100 key ||= (offender = get_deprecation_offender) unless $deprecation_warnings.has_key?(key) $deprecation_warnings[key] = message # split out to allow translation call_trace = if use_caller _("(location: %{location})") % { location: (offender || get_deprecation_offender).join('; ') } else Puppet::Util::Errors.error_location_with_unknowns(file, line) end warning("%{message}\n %{call_trace}" % { message: message, call_trace: call_trace }) end end end def is_resource? defined?(Puppet::Type) && is_a?(Puppet::Type) end def is_resource_parameter? defined?(Puppet::Parameter) && is_a?(Puppet::Parameter) end def log_metadata [:file, :line, :tags].each_with_object({}) do |attr, result| result[attr] = send(attr) if respond_to?(attr) end end def log_source # We need to guard the existence of the constants, since this module is used by the base Puppet module. (is_resource? or is_resource_parameter?) and respond_to?(:path) and return path.to_s to_s end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/inifile.rb
lib/puppet/util/inifile.rb
# frozen_string_literal: true # Module Puppet::IniConfig # A generic way to parse .ini style files and manipulate them in memory # One 'file' can be made up of several physical files. Changes to sections # on the file are tracked so that only the physical files in which # something has changed are written back to disk # Great care is taken to preserve comments and blank lines from the original # files # # The parsing tries to stay close to python's ConfigParser require_relative '../../puppet/util/filetype' require_relative '../../puppet/error' module Puppet::Util::IniConfig # A section in a .ini file class Section attr_reader :name, :file, :entries attr_writer :destroy def initialize(name, file) @name = name @file = file @dirty = false @entries = [] @destroy = false end # Does this section need to be updated in/removed from the associated file? # # @note This section is dirty if a key has been modified _or_ if the # section has been modified so the associated file can be rewritten # without this section. def dirty? @dirty or @destroy end def mark_dirty @dirty = true end # Should only be used internally def mark_clean @dirty = false end # Should the file be destroyed? def destroy? @destroy end # Add a line of text (e.g., a comment) Such lines # will be written back out in exactly the same # place they were read in def add_line(line) @entries << line end # Set the entry 'key=value'. If no entry with the # given key exists, one is appended to the end of the section def []=(key, value) entry = find_entry(key) @dirty = true if entry.nil? @entries << [key, value] else entry[1] = value end end # Return the value associated with KEY. If no such entry # exists, return nil def [](key) entry = find_entry(key) (entry.nil? ? nil : entry[1]) end # Format the section as text in the way it should be # written to file def format if @destroy text = ''.dup else text = "[#{name}]\n" @entries.each do |entry| if entry.is_a?(Array) key, value = entry text << "#{key}=#{value}\n" unless value.nil? else text << entry end end end text end private def find_entry(key) @entries.each do |entry| return entry if entry.is_a?(Array) && entry[0] == key end nil end end class PhysicalFile # @!attribute [r] filetype # @api private # @return [Puppet::Util::FileType::FileTypeFlat] attr_reader :filetype # @!attribute [r] contents # @api private # @return [Array<String, Puppet::Util::IniConfig::Section>] attr_reader :contents # @!attribute [rw] destroy_empty # Whether empty files should be removed if no sections are defined. # Defaults to false attr_accessor :destroy_empty # @!attribute [rw] file_collection # @return [Puppet::Util::IniConfig::FileCollection] attr_accessor :file_collection def initialize(file, options = {}) @file = file @contents = [] @filetype = Puppet::Util::FileType.filetype(:flat).new(file) @destroy_empty = options.fetch(:destroy_empty, false) end # Read and parse the on-disk file associated with this object def read text = @filetype.read if text.nil? raise IniParseError, _("Cannot read nonexistent file %{file}") % { file: @file.inspect } end parse(text) end INI_COMMENT = Regexp.union( /^\s*$/, /^[#;]/, /^\s*rem\s/i ) INI_CONTINUATION = /^[ \t\r\n\f]/ INI_SECTION_NAME = /^\[([^\]]+)\]/ INI_PROPERTY = /^\s*([^\s=]+)\s*=\s*(.*)$/ # @api private def parse(text) section = nil # The name of the current section optname = nil # The name of the last option in section line_num = 0 text.each_line do |l| line_num += 1 if l.match(INI_COMMENT) # Whitespace or comment if section.nil? @contents << l else section.add_line(l) end elsif l.match(INI_CONTINUATION) && section && optname # continuation line section[optname] += "\n#{l.chomp}" elsif (match = l.match(INI_SECTION_NAME)) # section heading section.mark_clean if section section_name = match[1] section = add_section(section_name) optname = nil elsif (match = l.match(INI_PROPERTY)) # the regex strips leading white space from the value, and here we strip the trailing white space as well key = match[1] val = match[2].rstrip if section.nil? raise IniParseError, _("Property with key %{key} outside of a section") % { key: key.inspect } end section[key] = val optname = key else raise IniParseError.new(_("Can't parse line '%{line}'") % { line: l.chomp }, @file, line_num) end end section.mark_clean unless section.nil? end # @return [Array<Puppet::Util::IniConfig::Section>] All sections defined in # this file. def sections @contents.select { |entry| entry.is_a? Section } end # @return [Puppet::Util::IniConfig::Section, nil] The section with the # given name if it exists, else nil. def get_section(name) @contents.find { |entry| entry.is_a? Section and entry.name == name } end def format text = ''.dup @contents.each do |content| if content.is_a? Section text << content.format else text << content end end text end def store if @destroy_empty and (sections.empty? or sections.all?(&:destroy?)) ::File.unlink(@file) elsif sections.any?(&:dirty?) text = self.format @filetype.write(text) end sections.each(&:mark_clean) end # Create a new section and store it in the file contents # # @api private # @param name [String] The name of the section to create # @return [Puppet::Util::IniConfig::Section] def add_section(name) if section_exists?(name) raise IniParseError.new(_("Section %{name} is already defined, cannot redefine") % { name: name.inspect }, @file) end section = Section.new(name, @file) @contents << section section end private def section_exists?(name) if get_section(name) true elsif @file_collection and @file_collection.get_section(name) true else false end end end class FileCollection attr_reader :files def initialize @files = {} end # Read and parse a file and store it in the collection. If the file has # already been read it will be destroyed and re-read. def read(file) new_physical_file(file).read end def store @files.values.each(&:store) end def each_section(&block) @files.values.each do |file| file.sections.each do |section| yield section end end end def each_file(&block) @files.keys.each do |path| yield path end end def get_section(name) sect = nil @files.values.each do |file| if (current = file.get_section(name)) sect = current end end sect end alias [] get_section def include?(name) !!get_section(name) end def add_section(name, file) get_physical_file(file).add_section(name) end private # Return a file if it's already been defined, create a new file if it hasn't # been defined. def get_physical_file(file) @files[file] || new_physical_file(file) end # Create a new physical file and set required attributes on that file. def new_physical_file(file) @files[file] = PhysicalFile.new(file) @files[file].file_collection = self @files[file] end end File = FileCollection class IniParseError < Puppet::Error include Puppet::ExternalFileError end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/warnings.rb
lib/puppet/util/warnings.rb
# frozen_string_literal: true # Methods to help with handling warnings. module Puppet::Util::Warnings module_function def notice_once(msg) Puppet::Util::Warnings.maybe_log(msg, self.class) { Puppet.notice msg } end def debug_once(msg) return nil unless Puppet[:debug] Puppet::Util::Warnings.maybe_log(msg, self.class) { Puppet.debug msg } end def warnonce(msg) Puppet::Util::Warnings.maybe_log(msg, self.class) { Puppet.warning msg } end def clear_warnings @stampwarnings = {} nil end def self.maybe_log(message, klass) @stampwarnings ||= {} @stampwarnings[klass] ||= [] return nil if @stampwarnings[klass].include? message yield @stampwarnings[klass] << message 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/util/yaml.rb
lib/puppet/util/yaml.rb
# frozen_string_literal: true require 'yaml' module Puppet::Util::Yaml YamlLoadExceptions = [::StandardError, ::Psych::Exception] class YamlLoadError < Puppet::Error; end # Safely load the content as YAML. By default only the following # classes can be deserialized: # # * TrueClass # * FalseClass # * NilClass # * Numeric # * String # * Array # * Hash # # Attempting to deserialize other classes will raise an YamlLoadError # exception unless they are specified in the array of *allowed_classes*. # @param [String] yaml The yaml content to parse. # @param [Array] allowed_classes Additional list of classes that can be deserialized. # @param [String] filename The filename to load from, used if an exception is raised. # @raise [YamlLoadException] If deserialization fails. # @return The parsed YAML, which can be Hash, Array or scalar types. def self.safe_load(yaml, allowed_classes = [], filename = nil) if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1.0') data = YAML.safe_load(yaml, permitted_classes: allowed_classes, aliases: true, filename: filename) else data = YAML.safe_load(yaml, allowed_classes, [], true, filename) end data = false if data.nil? data rescue ::Psych::DisallowedClass => detail path = filename ? "(#{filename})" : "(<unknown>)" raise YamlLoadError.new("#{path}: #{detail.message}", detail) rescue *YamlLoadExceptions => detail raise YamlLoadError.new(detail.message, detail) end # Safely load the content from a file as YAML. # # @see Puppet::Util::Yaml.safe_load def self.safe_load_file(filename, allowed_classes = []) yaml = Puppet::FileSystem.read(filename, :encoding => 'bom|utf-8') safe_load(yaml, allowed_classes, filename) end # Safely load the content from a file as YAML if # contents are in valid format. This method does not # raise error but returns `nil` when invalid file is # given. def self.safe_load_file_if_valid(filename, allowed_classes = []) safe_load_file(filename, allowed_classes) rescue YamlLoadError, ArgumentError, Errno::ENOENT => detail Puppet.debug("Could not retrieve YAML content from '#{filename}': #{detail.message}") nil end def self.dump(structure, filename) Puppet::FileSystem.replace_file(filename, 0o660) do |fh| YAML.dump(structure, fh) 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/selinux.rb
lib/puppet/util/selinux.rb
# frozen_string_literal: true # Provides utility functions to help interface Puppet to SELinux. # # This requires the very new SELinux Ruby bindings. These bindings closely # mirror the SELinux C library interface. # # Support for the command line tools is not provided because the performance # was abysmal. At this time (2008-11-02) the only distribution providing # these Ruby SELinux bindings which I am aware of is Fedora (in libselinux-ruby). Puppet.features.selinux? # check, but continue even if it's not require 'pathname' module Puppet::Util::SELinux S_IFREG = 0o100000 S_IFDIR = 0o040000 S_IFLNK = 0o120000 def self.selinux_support? return false unless defined?(Selinux) if Selinux.is_selinux_enabled == 1 return true end false end def selinux_support? Puppet::Util::SELinux.selinux_support? end # Retrieve and return the full context of the file. If we don't have # SELinux support or if the SELinux call fails then return nil. def get_selinux_current_context(file) return nil unless selinux_support? retval = Selinux.lgetfilecon(file) if retval == -1 return nil end retval[1] end # Retrieve and return the default context of the file. If we don't have # SELinux support or if the SELinux call fails to file a default then return nil. # @deprecated matchpathcon is a deprecated method, selabel_lookup is preferred def get_selinux_default_context(file, resource_ensure = nil) return nil unless selinux_support? # If the filesystem has no support for SELinux labels, return a default of nil # instead of what matchpathcon would return return nil unless selinux_label_support?(file) # If the file exists we should pass the mode to matchpathcon for the most specific # matching. If not, we can pass a mode of 0. mode = file_mode(file, resource_ensure) retval = Selinux.matchpathcon(file, mode) retval == -1 ? nil : retval[1] end # Retrieve and return the default context of the file using an selinux handle. # If we don't have SELinux support or if the SELinux call fails to file a # default then return nil. def get_selinux_default_context_with_handle(file, handle, resource_ensure = nil) return nil unless selinux_support? # If the filesystem has no support for SELinux labels, return a default of nil # instead of what selabel_lookup would return return nil unless selinux_label_support?(file) # Handle is needed for selabel_lookup raise ArgumentError, _("Cannot get default context with nil handle") unless handle # If the file exists we should pass the mode to selabel_lookup for the most specific # matching. If not, we can pass a mode of 0. mode = file_mode(file, resource_ensure) retval = Selinux.selabel_lookup(handle, file, mode) retval == -1 ? nil : retval[1] end # Take the full SELinux context returned from the tools and parse it # out to the three (or four) component parts. Supports :seluser, :selrole, # :seltype, and on systems with range support, :selrange. def parse_selinux_context(component, context) if context.nil? or context == "unlabeled" return nil end components = /^([^\s:]+):([^\s:]+):([^\s:]+)(?::([\sa-zA-Z0-9:,._-]+))?$/.match(context) unless components raise Puppet::Error, _("Invalid context to parse: %{context}") % { context: context } end case component when :seluser components[1] when :selrole components[2] when :seltype components[3] when :selrange components[4] else raise Puppet::Error, _("Invalid SELinux parameter type") end end # This updates the actual SELinux label on the file. You can update # only a single component or update the entire context. # The caveat is that since setting a partial context makes no sense the # file has to already exist. Puppet (via the File resource) will always # just try to set components, even if all values are specified by the manifest. # I believe that the OS should always provide at least a fall-through context # though on any well-running system. def set_selinux_context(file, value, component = false) return nil unless selinux_support? && selinux_label_support?(file) if component # Must first get existing context to replace a single component context = Selinux.lgetfilecon(file)[1] if context == -1 # We can't set partial context components when no context exists # unless/until we can find a way to make Puppet call this method # once for all selinux file label attributes. Puppet.warning _("Can't set SELinux context on file unless the file already has some kind of context") return nil end context = context.split(':') case component when :seluser context[0] = value when :selrole context[1] = value when :seltype context[2] = value when :selrange context[3] = value else raise ArgumentError, _("set_selinux_context component must be one of :seluser, :selrole, :seltype, or :selrange") end context = context.join(':') else context = value end retval = Selinux.lsetfilecon(file, context) if retval == 0 true else Puppet.warning _("Failed to set SELinux context %{context} on %{file}") % { context: context, file: file } false end end # Since this call relies on get_selinux_default_context it also needs a # full non-relative path to the file. Fortunately, that seems to be all # Puppet uses. This will set the file's SELinux context to the policy's # default context (if any) if it differs from the context currently on # the file. def set_selinux_default_context(file, resource_ensure = nil) new_context = get_selinux_default_context(file, resource_ensure) return nil unless new_context cur_context = get_selinux_current_context(file) if new_context != cur_context set_selinux_context(file, new_context) return new_context end nil end ## # selinux_category_to_label is an internal method that converts all # selinux categories to their internal representation, avoiding # potential issues when mcstransd is not functional. # # It is not marked private because it is needed by File's # selcontext.rb, but it is not intended for use outside of Puppet's # code. # # @param category [String] An selinux category, such as "s0" or "SystemLow" # # @return [String] the numeric category name, such as "s0" def selinux_category_to_label(category) # We don't cache this, but there's already a ton of duplicate work # in the selinux handling code. path = Selinux.selinux_translations_path begin File.open(path).each do |line| line.strip! next if line.empty? next if line[0] == "#" # skip comments line.gsub!(/[[:space:]]+/m, '') mapping = line.split("=", 2) if category == mapping[1] return mapping[0] end end rescue SystemCallError => ex log_exception(ex) raise Puppet::Error, _("Could not open SELinux category translation file %{path}.") % { context: context } end category end ######################################################################## # Internal helper methods from here on in, kids. Don't fiddle. private # Check filesystem a path resides on for SELinux support against # whitelist of known-good filesystems. # Returns true if the filesystem can support SELinux labels and # false if not. def selinux_label_support?(file) fstype = find_fs(file) return false if fstype.nil? filesystems = %w[ext2 ext3 ext4 gfs gfs2 xfs jfs btrfs tmpfs zfs] filesystems.include?(fstype) end # Get mode file type bits set based on ensure on # the file resource. This helps SELinux determine # what context a new resource being created should have. def get_create_mode(resource_ensure) mode = 0 case resource_ensure when :present, :file mode |= S_IFREG when :directory mode |= S_IFDIR when :link mode |= S_IFLNK end mode end # If the file/directory/symlink exists, return its mode. Otherwise, get the default mode # that should be used to create the file/directory/symlink taking into account the desired # file type specified in +resource_ensure+. def file_mode(file, resource_ensure) filestat = file_lstat(file) filestat.mode rescue Errno::EACCES 0 rescue Errno::ENOENT if resource_ensure get_create_mode(resource_ensure) else 0 end end # Internal helper function to read and parse /proc/mounts def read_mounts mounts = ''.dup begin if File.method_defined? "read_nonblock" # If possible we use read_nonblock in a loop rather than read to work- # a linux kernel bug. See ticket #1963 for details. mountfh = File.new("/proc/mounts") loop do mounts += mountfh.read_nonblock(1024) end else # Otherwise we shell out and let cat do it for us mountfh = IO.popen("/bin/cat /proc/mounts") mounts = mountfh.read end rescue EOFError # that's expected rescue return nil ensure mountfh.close if mountfh end mntpoint = {} # Read all entries in /proc/mounts. The second column is the # mountpoint and the third column is the filesystem type. # We skip rootfs because it is always mounted at / mounts.each_line do |line| params = line.split(' ') next if params[2] == 'rootfs' mntpoint[params[1]] = params[2] end mntpoint end # Internal helper function to return which type of filesystem a given file # path resides on def find_fs(path) mounts = read_mounts return nil unless mounts # cleanpath eliminates useless parts of the path (like '.', or '..', or # multiple slashes), without touching the filesystem, and without # following symbolic links. This gives the right (logical) tree to follow # while we try and figure out what file-system the target lives on. path = Pathname(path).cleanpath unless path.absolute? raise Puppet::DevError, _("got a relative path in SELinux find_fs: %{path}") % { path: path } end # Now, walk up the tree until we find a match for that path in the hash. path.ascend do |segment| return mounts[segment.to_s] if mounts.has_key?(segment.to_s) end # Should never be reached... mounts['/'] end ## # file_lstat is an internal, private method to allow precise stubbing and # mocking without affecting the rest of the system. # # @return [File::Stat] File.lstat result def file_lstat(path) Puppet::FileSystem.lstat(path) end private :file_lstat 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/feature.rb
lib/puppet/util/feature.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/util/warnings' class Puppet::Util::Feature include Puppet::Util::Warnings attr_reader :path # Create a new feature test. You have to pass the feature name, and it must be # unique. You can pass a block to determine if the feature is present: # # Puppet.features.add(:myfeature) do # # return true or false if feature is available # # return nil if feature may become available later # end # # The block should return true if the feature is available, false if it is # not, or nil if the state is unknown. True and false values will be cached. A # nil value will not be cached, and should be used if the feature may become # true in the future. # # Features are often used to detect if a ruby library is installed. To support # that common case, you can pass one or more ruby libraries, and the feature # will be true if all of the libraries load successfully: # # Puppet.features.add(:myfeature, libs: 'mylib') # Puppet.features.add(:myfeature, libs: ['mylib', 'myotherlib']) # # If the ruby library is not installed, then the failure is not cached, as # it's assumed puppet may install the gem during catalog application. # # If a feature is defined using `:libs` and a block, then the block is # used and the `:libs` are ignored. # # Puppet evaluates the feature test when the `Puppet.features.myfeature?` # method is called. If the feature test was defined using a block and the # block returns nil, then the feature test will be re-evaluated the next time # `Puppet.features.myfeature?` is called. # # @param [Symbol] name The unique feature name # @param [Hash<Symbol,Array<String>>] options The libraries to load def add(name, options = {}, &block) method = name.to_s + "?" @results.delete(name) meta_def(method) do # we return a cached result if: # * if we've tested this feature before # AND # * the result was true/false # OR # * we're configured to never retry unless @results.has_key?(name) && (!@results[name].nil? || !Puppet[:always_retry_plugins]) @results[name] = test(name, options, &block) end !!@results[name] end end # Create a new feature collection. def initialize(path) @path = path @results = {} @loader = Puppet::Util::Autoload.new(self, @path) end def load @loader.loadall(Puppet.lookup(:current_environment)) end def method_missing(method, *args) return super unless method.to_s =~ /\?$/ feature = method.to_s.sub(/\?$/, '') @loader.load(feature, Puppet.lookup(:current_environment)) respond_to?(method) && send(method) end # Actually test whether the feature is present. We only want to test when # someone asks for the feature, so we don't unnecessarily load # files. def test(name, options, &block) if block_given? begin result = yield rescue StandardError, ScriptError => detail warn _("Failed to load feature test for %{name}: %{detail}") % { name: name, detail: detail } result = nil end @results[name] = result result else libs = options[:libs] if libs libs = [libs] unless libs.is_a?(Array) libs.all? { |lib| load_library(lib, name) } ? true : nil else true end end end private def load_library(lib, name) raise ArgumentError, _("Libraries must be passed as strings not %{klass}") % { klass: lib.class } unless lib.is_a?(String) @rubygems ||= Puppet::Util::RubyGems::Source.new @rubygems.clear_paths begin require lib true rescue LoadError # Expected case. Required library insn't installed. debug_once(_("Could not find library '%{lib}' required to enable feature '%{name}'") % { lib: lib, name: name }) false rescue StandardError, ScriptError => detail debug_once(_("Exception occurred while loading library '%{lib}' required to enable feature '%{name}': %{detail}") % { lib: lib, name: name, detail: detail }) false 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/resource_template.rb
lib/puppet/util/resource_template.rb
# frozen_string_literal: true require_relative '../../puppet/util' require_relative '../../puppet/util/logging' require 'erb' # A template wrapper that evaluates a template in the # context of a resource, allowing the resource attributes # to be looked up from within the template. # This provides functionality essentially equivalent to # the language's template() function. You pass your file # path and the resource you want to use into the initialization # method, then call result on the instance, and you get back # a chunk of text. # The resource's parameters are available as instance variables # (as opposed to the language, where we use a method_missing trick). # For example, say you have a resource that generates a file. You would # need to implement the following style of `generate` method: # # def generate # template = Puppet::Util::ResourceTemplate.new("/path/to/template", self) # # return Puppet::Type.type(:file).new :path => "/my/file", # :content => template.evaluate # end # # This generated file gets added to the catalog (which is what `generate` does), # and its content is the result of the template. You need to use instance # variables in your template, so if your template just needs to have the name # of the generating resource, it would just have: # # <%= @name %> # # Since the ResourceTemplate class sets as instance variables all of the resource's # parameters. # # Note that this example uses the generating resource as its source of # parameters, which is generally most useful, since it allows you to configure # the generated resource via the generating resource. class Puppet::Util::ResourceTemplate include Puppet::Util::Logging def evaluate set_resource_variables Puppet::Util.create_erb(Puppet::FileSystem.read(@file, :encoding => 'utf-8')).result(binding) end def initialize(file, resource) raise ArgumentError, _("Template %{file} does not exist") % { file: file } unless Puppet::FileSystem.exist?(file) @file = file @resource = resource end private def set_resource_variables @resource.to_hash.each do |param, value| var = "@#{param}" instance_variable_set(var, 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/json.rb
lib/puppet/util/json.rb
# frozen_string_literal: true module Puppet::Util module Json class ParseError < StandardError attr_reader :cause, :data def self.build(original_exception, data) new(original_exception.message).tap do |exception| exception.instance_eval do @cause = original_exception set_backtrace original_exception.backtrace @data = data end end end end begin require 'multi_json' # Force backend detection before attempting to use the library # or load any other JSON libraries MultiJson.default_adapter # Preserve core type monkey-patching done by the built-in JSON gem require 'json' rescue LoadError require 'json' end # Load the content from a file as JSON if # contents are in valid format. This method does not # raise error but returns `nil` when invalid file is # given. def self.load_file_if_valid(filename, options = {}) load_file(filename, options) rescue Puppet::Util::Json::ParseError, ArgumentError, Errno::ENOENT => detail Puppet.debug("Could not retrieve JSON content from '#{filename}': #{detail.message}") nil end # Load the content from a file as JSON. def self.load_file(filename, options = {}) json = Puppet::FileSystem.read(filename, :encoding => 'utf-8') load(json, options) end # These methods do similar processing to the fallback implemented by MultiJson # when using the built-in JSON backend, to ensure consistent behavior # whether or not MultiJson can be loaded. def self.load(string, options = {}) if defined? MultiJson begin # This ensures that JrJackson and Oj will parse very large or very small # numbers as floats rather than BigDecimals, which are serialized as # strings by the built-in JSON gem and therefore can cause schema errors, # for example, when we are rendering reports to JSON using `to_pson` in # PuppetDB. case MultiJson.adapter.name when "MultiJson::Adapters::JrJackson" options[:use_bigdecimal] = false when "MultiJson::Adapters::Oj" options[:bigdecimal_load] = :float end MultiJson.load(string, options) rescue MultiJson::ParseError => e raise Puppet::Util::Json::ParseError.build(e, string) end else begin string = string.read if string.respond_to?(:read) options[:symbolize_names] = true if options.delete(:symbolize_keys) ::JSON.parse(string, options) rescue JSON::ParserError => e raise Puppet::Util::Json::ParseError.build(e, string) end end end def self.dump(object, options = {}) if defined? MultiJson MultiJson.dump(object, options) elsif options.is_a?(JSON::State) # we're being called recursively object.to_json(options) else options.merge!(::JSON::PRETTY_STATE_PROTOTYPE.to_h) if options.delete(:pretty) object.to_json(options) 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/suidmanager.rb
lib/puppet/util/suidmanager.rb
# frozen_string_literal: true require_relative '../../puppet/util/warnings' require 'forwardable' require 'etc' module Puppet::Util::SUIDManager include Puppet::Util::Warnings extend Forwardable # Note groups= is handled specially due to a bug in OS X 10.6, 10.7, # and probably upcoming releases... to_delegate_to_process = [:euid=, :euid, :egid=, :egid, :uid=, :uid, :gid=, :gid, :groups] to_delegate_to_process.each do |method| def_delegator Process, method module_function method end def osx_maj_ver return @osx_maj_ver unless @osx_maj_ver.nil? @osx_maj_ver = Puppet.runtime[:facter].value('os.macosx.version.major') || false end module_function :osx_maj_ver def groups=(grouplist) Process.groups = grouplist rescue Errno::EINVAL => e # We catch Errno::EINVAL as some operating systems (OS X in particular) can # cause troubles when using Process#groups= to change *this* user / process # list of supplementary groups membership. This is done via Ruby's function # "static VALUE proc_setgroups(VALUE obj, VALUE ary)" which is effectively # a wrapper for "int setgroups(size_t size, const gid_t *list)" (part of SVr4 # and 4.3BSD but not in POSIX.1-2001) that fails and sets errno to EINVAL. # # This does not appear to be a problem with Ruby but rather an issue on the # operating system side. Therefore we catch the exception and look whether # we run under OS X or not -- if so, then we acknowledge the problem and # re-throw the exception otherwise. if !osx_maj_ver || osx_maj_ver.empty? raise e end end module_function :groups= def self.root? if Puppet::Util::Platform.windows? require_relative '../../puppet/util/windows/user' Puppet::Util::Windows::User.admin? else Process.uid == 0 end end # Methods to handle changing uid/gid of the running process. In general, # these will noop or fail on Windows, and require root to change to anything # but the current uid/gid (which is a noop). # Runs block setting euid and egid if provided then restoring original ids. # If running on Windows or without root, the block will be run with the # current euid/egid. def asuser(new_uid = nil, new_gid = nil) return yield if Puppet::Util::Platform.windows? return yield unless root? return yield unless new_uid or new_gid old_euid = euid old_egid = egid begin change_privileges(new_uid, new_gid, false) yield ensure change_privileges(new_uid ? old_euid : nil, old_egid, false) end end module_function :asuser # If `permanently` is set, will permanently change the uid/gid of the # process. If not, it will only set the euid/egid. If only uid is supplied, # the primary group of the supplied gid will be used. If only gid is # supplied, only gid will be changed. This method will fail if used on # Windows. def change_privileges(uid = nil, gid = nil, permanently = false) return unless uid or gid unless gid uid = convert_xid(:uid, uid) gid = Etc.getpwuid(uid).gid end change_group(gid, permanently) change_user(uid, permanently) if uid end module_function :change_privileges # Changes the egid of the process if `permanently` is not set, otherwise # changes gid. This method will fail if used on Windows, or attempting to # change to a different gid without root. def change_group(group, permanently = false) gid = convert_xid(:gid, group) raise Puppet::Error, _("No such group %{group}") % { group: group } unless gid return if Process.egid == gid if permanently Process::GID.change_privilege(gid) else Process.egid = gid end end module_function :change_group # As change_group, but operates on uids. If changing user permanently, # supplementary groups will be set the to default groups for the new uid. def change_user(user, permanently = false) uid = convert_xid(:uid, user) raise Puppet::Error, _("No such user %{user}") % { user: user } unless uid return if Process.euid == uid if permanently # If changing uid, we must be root. So initgroups first here. initgroups(uid) Process::UID.change_privilege(uid) elsif Process.euid == 0 # We must be root to initgroups, so initgroups before dropping euid if # we're root, otherwise elevate euid before initgroups. # change euid (to root) first. initgroups(uid) Process.euid = uid else Process.euid = uid initgroups(uid) end end module_function :change_user # Make sure the passed argument is a number. def convert_xid(type, id) return id if id.is_a? Integer map = { :gid => :group, :uid => :user } raise ArgumentError, _("Invalid id type %{type}") % { type: type } unless map.include?(type) ret = Puppet::Util.send(type, id) if ret.nil? raise Puppet::Error, _("Invalid %{klass}: %{id}") % { klass: map[type], id: id } end ret end module_function :convert_xid # Initialize primary and supplemental groups to those of the target user. We # take the UID and manually look up their details in the system database, # including username and primary group. This method will fail on Windows, or # if used without root to initgroups of another user. def initgroups(uid) pwent = Etc.getpwuid(uid) Process.initgroups(pwent.name, pwent.gid) end module_function :initgroups 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/psych_support.rb
lib/puppet/util/psych_support.rb
# frozen_string_literal: true # This module should be included when a class can be serialized to yaml and # needs to handle the deserialization from Psych with more control. Psych normally # pokes values directly into an instance using `instance_variable_set` which completely # bypasses encapsulation. # # The class that includes this module must implement an instance method `initialize_from_hash` # that is given a hash with attribute to value mappings. # module Puppet::Util::PsychSupport # This method is called from the Psych Yaml deserializer when it encounters a tag # in the form !ruby/object:<class name>. # def init_with(psych_coder) # The PsychCoder has a hashmap of instance variable name (sans the @ symbol) to values # to set, and can thus directly be fed to initialize_from_hash. # initialize_from_hash(psych_coder.map) end # This method is called from the Psych Yaml serializer # The serializer will call this method to create a hash that will be serialized to YAML. # Instead of using the object itself during the mapping process we use what is # returned by calling `to_data_hash` on the object itself since some of the # objects we manage have asymmetrical serialization and deserialization. # def encode_with(psych_encoder) tag = Psych.dump_tags[self.class] || "!ruby/object:#{self.class.name}" psych_encoder.represent_map(tag, to_data_hash) 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/metaid.rb
lib/puppet/util/metaid.rb
# frozen_string_literal: true class Object # The hidden singleton lurks behind everyone def singleton_class; class << self; self; end; end def meta_eval(&blk); singleton_class.instance_eval(&blk); end # Adds methods to a singleton_class def meta_def(name, &blk) meta_eval { define_method name, &blk } end # Remove singleton_class methods. def meta_undef(name, &blk) meta_eval { remove_method name } end # Defines an instance method within a class def class_def(name, &blk) class_eval { define_method name, &blk } 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/tag_set.rb
lib/puppet/util/tag_set.rb
# frozen_string_literal: true require 'set' require_relative '../../puppet/network/format_support' class Puppet::Util::TagSet < Set include Puppet::Network::FormatSupport def self.from_yaml(yaml) new(Puppet::Util::Yaml.safe_load(yaml, [Symbol])) end def to_yaml @hash.keys.to_yaml end def self.from_data_hash(data) new(data) end # TODO: A method named #to_data_hash should not return an array def to_data_hash to_a end def join(*args) to_a.join(*args) 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/symbolic_file_mode.rb
lib/puppet/util/symbolic_file_mode.rb
# frozen_string_literal: true require_relative '../../puppet/util' module Puppet module Util module SymbolicFileMode SetUIDBit = ReadBit = 4 SetGIDBit = WriteBit = 2 StickyBit = ExecBit = 1 SymbolicMode = { 'x' => ExecBit, 'w' => WriteBit, 'r' => ReadBit } SymbolicSpecialToBit = { 't' => { 'u' => StickyBit, 'g' => StickyBit, 'o' => StickyBit }, 's' => { 'u' => SetUIDBit, 'g' => SetGIDBit, 'o' => StickyBit } } def valid_symbolic_mode?(value) value = normalize_symbolic_mode(value) return true if value =~ /^0?[0-7]{1,4}$/ return true if value =~ /^([ugoa]*[-=+][-=+rstwxXugo]*)(,[ugoa]*[-=+][-=+rstwxXugo]*)*$/ false end def display_mode(value) if value =~ /^0?[0-7]{1,4}$/ value.rjust(4, "0") else value end end def normalize_symbolic_mode(value) return nil if value.nil? # We need to treat integers as octal numbers. # # "A numeric mode is from one to four octal digits (0-7), derived by adding # up the bits with values 4, 2, and 1. Omitted digits are assumed to be # leading zeros." case value when Numeric value.to_s(8) when /^0?[0-7]{1,4}$/ value.to_i(8).to_s(8) # strip leading 0's else value end end def symbolic_mode_to_int(modification, to_mode = 0, is_a_directory = false) if modification.nil? or modification == '' raise Puppet::Error, _("An empty mode string is illegal") elsif modification =~ /^[0-7]+$/ return modification.to_i(8) elsif modification =~ /^\d+$/ raise Puppet::Error, _("Numeric modes must be in octal, not decimal!") end fail _("non-numeric current mode (%{mode})") % { mode: to_mode.inspect } unless to_mode.is_a?(Numeric) original_mode = { 's' => (to_mode & 0o7000) >> 9, 'u' => (to_mode & 0o0700) >> 6, 'g' => (to_mode & 0o0070) >> 3, 'o' => (to_mode & 0o0007) >> 0, # Are there any execute bits set in the original mode? 'any x?' => (to_mode & 0o0111) != 0 } final_mode = { 's' => original_mode['s'], 'u' => original_mode['u'], 'g' => original_mode['g'], 'o' => original_mode['o'], } modification.split(/\s*,\s*/).each do |part| _, to, dsl = /^([ugoa]*)([-+=].*)$/.match(part).to_a if dsl.nil? then raise Puppet::Error, _('Missing action') end to = "a" unless to and to.length > 0 # We want a snapshot of the mode before we start messing with it to # make actions like 'a-g' atomic. Various parts of the DSL refer to # the original mode, the final mode, or the current snapshot of the # mode, for added fun. snapshot_mode = {} final_mode.each { |k, v| snapshot_mode[k] = v } to.gsub('a', 'ugo').split('').uniq.each do |who| value = snapshot_mode[who] action = '!' actions = { '!' => ->(_, _) { raise Puppet::Error, _('Missing operation (-, =, or +)') }, '=' => ->(m, v) { m | v }, '+' => ->(m, v) { m | v }, '-' => ->(m, v) { m & ~v }, } dsl.split('').each do |op| case op when /[-+=]/ action = op # Clear all bits, if this is assignment value = 0 if op == '=' when /[ugo]/ value = actions[action].call(value, snapshot_mode[op]) when /[rwx]/ value = actions[action].call(value, SymbolicMode[op]) when 'X' # Only meaningful in combination with "set" actions. if action != '+' raise Puppet::Error, _("X only works with the '+' operator") end # As per the BSD manual page, set if this is a directory, or if # any execute bit is set on the original (unmodified) mode. # Ignored otherwise; it is "add if", not "add or clear". if is_a_directory or original_mode['any x?'] value = actions[action].call(value, ExecBit) end when /[st]/ bit = SymbolicSpecialToBit[op][who] or fail _("internal error") final_mode['s'] = actions[action].call(final_mode['s'], bit) else raise Puppet::Error, _('Unknown operation') end end # Now, assign back the value. final_mode[who] = value end rescue Puppet::Error => e if part.inspect != modification.inspect rest = " at #{part.inspect}" else rest = '' end raise Puppet::Error, _("%{error}%{rest} in symbolic mode %{modification}") % { error: e, rest: rest, modification: modification.inspect }, e.backtrace end final_mode['s'] << 9 | final_mode['u'] << 6 | final_mode['g'] << 3 | final_mode['o'] << 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/util/classgen.rb
lib/puppet/util/classgen.rb
# frozen_string_literal: true module Puppet class ConstantAlreadyDefined < Error; end class SubclassAlreadyDefined < Error; end end # This is a utility module for generating classes. # @api public # module Puppet::Util::ClassGen include Puppet::Util # Create a new class. # @param name [String] the name of the generated class # @param options [Hash] a hash of options # @option options [Array<Class>] :array if specified, the generated class is appended to this array # @option options [Hash<{String => Object}>] :attributes a hash that is applied to the generated class # by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given # block is evaluated. # @option options [Proc] :block a block to evaluate in the context of the class (this block can be provided # this way, or as a normal yield block). # @option options [String] :constant (name with first letter capitalized) what to set the constant that references # the generated class to. # @option options [Hash] :hash a hash of existing classes that this class is appended to (name => class). # This hash must be specified if the `:overwrite` option is set to `true`. # @option options [Boolean] :overwrite whether an overwrite of an existing class should be allowed (requires also # defining the `:hash` with existing classes as the test is based on the content of this hash). # @option options [Class] :parent (self) the parent class of the generated class. # @option options [String] ('') :prefix the constant prefix to prepend to the constant name referencing the # generated class. # @return [Class] the generated class # def genclass(name, options = {}, &block) genthing(name, Class, options, block) end # Creates a new module. # @param name [String] the name of the generated module # @param options [Hash] hash with options # @option options [Array<Class>] :array if specified, the generated class is appended to this array # @option options [Hash<{String => Object}>] :attributes a hash that is applied to the generated class # by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given # block is evaluated. # @option options [Proc] :block a block to evaluate in the context of the class (this block can be provided # this way, or as a normal yield block). # @option options [String] :constant (name with first letter capitalized) what to set the constant that references # the generated class to. # @option options [Hash] :hash a hash of existing classes that this class is appended to (name => class). # This hash must be specified if the `:overwrite` option is set to `true`. # @option options [Boolean] :overwrite whether an overwrite of an existing class should be allowed (requires also # defining the `:hash` with existing classes as the test is based on the content of this hash). # the capitalized name is appended and the result is set as the constant. # @option options [String] ('') :prefix the constant prefix to prepend to the constant name referencing the # generated class. # @return [Module] the generated Module def genmodule(name, options = {}, &block) genthing(name, Module, options, block) end # Removes an existing class. # @param name [String] the name of the class to remove # @param options [Hash] options # @option options [Hash] :hash a hash of existing classes from which the class to be removed is also removed # @return [Boolean] whether the class was removed or not # def rmclass(name, options) const = genconst_string(name, options) retval = false if const_defined?(const, false) remove_const(const) retval = true end hash = options[:hash] if hash && hash.include?(name) hash.delete(name) retval = true end # Let them know whether we did actually delete a subclass. retval end private # Generates the constant to create or remove. # @api private def genconst_string(name, options) const = options[:constant] unless const prefix = options[:prefix] || "" const = prefix + name2const(name) end const end # This does the actual work of creating our class or module. It's just a # slightly abstract version of genclass. # @api private def genthing(name, type, options, block) name = name.to_s.downcase.intern if type == Module # evalmethod = :module_eval evalmethod = :class_eval # Create the class, with the correct name. klass = Module.new do class << self attr_reader :name end @name = name end else options[:parent] ||= self evalmethod = :class_eval # Create the class, with the correct name. klass = Class.new(options[:parent]) do @name = name end end # Create the constant as appropriation. handleclassconst(klass, name, options) # Initialize any necessary variables. initclass(klass, options) block ||= options[:block] # Evaluate the passed block if there is one. This should usually # define all of the work. klass.send(evalmethod, &block) if block klass.postinit if klass.respond_to? :postinit # Store the class in hashes or arrays or whatever. storeclass(klass, name, options) klass end # Handle the setting and/or removing of the associated constant. # @api private # def handleclassconst(klass, name, options) const = genconst_string(name, options) if const_defined?(const, false) if options[:overwrite] Puppet.info _("Redefining %{name} in %{klass}") % { name: name, klass: self } remove_const(const) else raise Puppet::ConstantAlreadyDefined, _("Class %{const} is already defined in %{klass}") % { const: const, klass: self } end end const_set(const, klass) const end # Perform the initializations on the class. # @api private # def initclass(klass, options) klass.initvars if klass.respond_to? :initvars attrs = options[:attributes] if attrs attrs.each do |param, value| method = param.to_s + "=" klass.send(method, value) if klass.respond_to? method end end [:include, :extend].each do |method| set = options[method] next unless set set = [set] unless set.is_a?(Array) set.each do |mod| klass.send(method, mod) end end klass.preinit if klass.respond_to? :preinit end # Convert our name to a constant. # @api private def name2const(name) name.to_s.capitalize end # Store the class in the appropriate places. # @api private def storeclass(klass, klassname, options) hash = options[:hash] if hash if hash.include? klassname and !options[:overwrite] raise Puppet::SubclassAlreadyDefined, _("Already a generated class named %{klassname}") % { klassname: klassname } end hash[klassname] = klass end # If we were told to stick it in a hash, then do so array = options[:array] if array if klass.respond_to? :name and array.find { |c| c.name == klassname } and !options[:overwrite] raise Puppet::SubclassAlreadyDefined, _("Already a generated class named %{klassname}") % { klassname: klassname } end array << klass 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/fileparsing.rb
lib/puppet/util/fileparsing.rb
# frozen_string_literal: true # A mini-language for parsing files. This is only used file the ParsedFile # provider, but it makes more sense to split it out so it's easy to maintain # in one place. # # You can use this module to create simple parser/generator classes. For instance, # the following parser should go most of the way to parsing /etc/passwd: # # class Parser # include Puppet::Util::FileParsing # record_line :user, :fields => %w{name password uid gid gecos home shell}, # :separator => ":" # end # # You would use it like this: # # parser = Parser.new # lines = parser.parse(File.read("/etc/passwd")) # # lines.each do |type, hash| # type will always be :user, since we only have one # p hash # end # # Each line in this case would be a hash, with each field set appropriately. # You could then call 'parser.to_line(hash)' on any of those hashes to generate # the text line again. module Puppet::Util::FileParsing include Puppet::Util attr_writer :line_separator, :trailing_separator class FileRecord include Puppet::Util attr_accessor :absent, :joiner, :rts, :separator, :rollup, :name, :match, :block_eval attr_reader :fields, :optional, :type INVALID_FIELDS = [:record_type, :target, :on_disk] # Customize this so we can do a bit of validation. def fields=(fields) @fields = fields.collect do |field| r = field.intern raise ArgumentError, _("Cannot have fields named %{name}") % { name: r } if INVALID_FIELDS.include?(r) r end end def initialize(type, absent: nil, block_eval: nil, fields: nil, joiner: nil, match: nil, optional: nil, post_parse: nil, pre_gen: nil, rollup: nil, rts: nil, separator: nil, to_line: nil, &block) @type = type.intern raise ArgumentError, _("Invalid record type %{record_type}") % { record_type: @type } unless [:record, :text].include?(@type) @absent = absent @block_eval = block_eval @joiner = joiner @match = match @rollup = rollup if rollup @rts = rts @separator = separator self.fields = fields if fields self.optional = optional if optional self.post_parse = post_parse if post_parse self.pre_gen = pre_gen if pre_gen self.to_line = to_line if to_line if self.type == :record # Now set defaults. self.absent ||= "" self.separator ||= /\s+/ self.joiner ||= " " self.optional ||= [] @rollup = true unless defined?(@rollup) end if block_given? @block_eval ||= :process # Allow the developer to specify that a block should be instance-eval'ed. if @block_eval == :instance instance_eval(&block) else meta_def(@block_eval, &block) end end end # Convert a record into a line by joining the fields together appropriately. # This is pulled into a separate method so it can be called by the hooks. def join(details) joinchar = self.joiner fields.filter_map { |field| # If the field is marked absent, use the appropriate replacement if details[field] == :absent or details[field] == [:absent] or details[field].nil? if self.optional.include?(field) self.absent else raise ArgumentError, _("Field '%{field}' is required") % { field: field } end else details[field].to_s end }.join(joinchar) end # Customize this so we can do a bit of validation. def optional=(optional) @optional = optional.collect(&:intern) end # Create a hook that modifies the hash resulting from parsing. def post_parse=(block) meta_def(:post_parse, &block) end # Create a hook that modifies the hash just prior to generation. def pre_gen=(block) meta_def(:pre_gen, &block) end # Are we a text type? def text? type == :text end def to_line=(block) meta_def(:to_line, &block) end end # Clear all existing record definitions. Only used for testing. def clear_records @record_types.clear @record_order.clear end def fields(type) record = record_type(type) if record record.fields.dup else nil end end # Try to match a specific text line. def handle_text_line(line, record) line =~ record.match ? { :record_type => record.name, :line => line } : nil end # Try to match a record. # # @param [String] line The line to be parsed # @param [Puppet::Util::FileType] record The filetype to use for parsing # # @return [Hash<Symbol, Object>] The parsed elements of the line def handle_record_line(line, record) ret = nil if record.respond_to?(:process) ret = record.send(:process, line.dup) if ret unless ret.is_a?(Hash) raise Puppet::DevError, _("Process record type %{record_name} returned non-hash") % { record_name: record.name } end else return nil end else regex = record.match if regex # In this case, we try to match the whole line and then use the # match captures to get our fields. match = regex.match(line) if match ret = {} record.fields.zip(match.captures).each do |field, value| if value == record.absent ret[field] = :absent else ret[field] = value end end else nil end else ret = {} sep = record.separator # String "helpfully" replaces ' ' with /\s+/ in splitting, so we # have to work around it. if sep == " " sep = / / end line_fields = line.split(sep) record.fields.each do |param| value = line_fields.shift if value and value != record.absent ret[param] = value else ret[param] = :absent end end if record.rollup and !line_fields.empty? last_field = record.fields[-1] val = ([ret[last_field]] + line_fields).join(record.joiner) ret[last_field] = val end end end if ret ret[:record_type] = record.name ret else nil end end def line_separator @line_separator ||= "\n" @line_separator end # Split text into separate lines using the record separator. def lines(text) # NOTE: We do not have to remove trailing separators because split will ignore # them by default (unless you pass -1 as a second parameter) text.split(line_separator) end # Split a bunch of text into lines and then parse them individually. def parse(text) count = 1 lines(text).collect do |line| count += 1 val = parse_line(line) if val val else error = Puppet::ResourceError.new(_("Could not parse line %{line}") % { line: line.inspect }) error.line = count raise error end end end # Handle parsing a single line. def parse_line(line) raise Puppet::DevError, _("No record types defined; cannot parse lines") unless records? @record_order.each do |record| # These are basically either text or record lines. method = "handle_#{record.type}_line" if respond_to?(method) result = send(method, line, record) if result record.send(:post_parse, result) if record.respond_to?(:post_parse) return result end else raise Puppet::DevError, _("Somehow got invalid line type %{record_type}") % { record_type: record.type } end end nil end # Define a new type of record. These lines get split into hashes. Valid # options are: # * <tt>:absent</tt>: What to use as value within a line, when a field is # absent. Note that in the record object, the literal :absent symbol is # used, and not this value. Defaults to "". # * <tt>:fields</tt>: The list of fields, as an array. By default, all # fields are considered required. # * <tt>:joiner</tt>: How to join fields together. Defaults to '\t'. # * <tt>:optional</tt>: Which fields are optional. If these are missing, # you'll just get the 'absent' value instead of an ArgumentError. # * <tt>:rts</tt>: Whether to remove trailing whitespace. Defaults to false. # If true, whitespace will be removed; if a regex, then whatever matches # the regex will be removed. # * <tt>:separator</tt>: The record separator. Defaults to /\s+/. def record_line(name, options, &block) raise ArgumentError, _("Must include a list of fields") unless options.include?(:fields) record = FileRecord.new(:record, **options, &block) record.name = name.intern new_line_type(record) end # Are there any record types defined? def records? defined?(@record_types) and !@record_types.empty? end # Define a new type of text record. def text_line(name, options, &block) raise ArgumentError, _("You must provide a :match regex for text lines") unless options.include?(:match) record = FileRecord.new(:text, **options, &block) record.name = name.intern new_line_type(record) end # Generate a file from a bunch of hash records. def to_file(records) text = records.collect { |record| to_line(record) }.join(line_separator) text += line_separator if trailing_separator text end # Convert our parsed record into a text record. def to_line(details) record = record_type(details[:record_type]) unless record raise ArgumentError, _("Invalid record type %{record_type}") % { record_type: details[:record_type].inspect } end if record.respond_to?(:pre_gen) details = details.dup record.send(:pre_gen, details) end case record.type when :text; details[:line] else return record.to_line(details) if record.respond_to?(:to_line) line = record.join(details) regex = record.rts if regex # If they say true, then use whitespace; else, use their regex. if regex == true regex = /\s+$/ end line.sub(regex, '') else line end end end # Whether to add a trailing separator to the file. Defaults to true def trailing_separator if defined?(@trailing_separator) @trailing_separator else true end end def valid_attr?(type, attr) type = type.intern record = record_type(type) if record && record.fields.include?(attr.intern) true else attr.intern == :ensure end end private # Define a new type of record. def new_line_type(record) @record_types ||= {} @record_order ||= [] raise ArgumentError, _("Line type %{name} is already defined") % { name: record.name } if @record_types.include?(record.name) @record_types[record.name] = record @record_order << record record end # Retrieve the record object. def record_type(type) @record_types[type.intern] 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/rubygems.rb
lib/puppet/util/rubygems.rb
# frozen_string_literal: true require_relative '../../puppet/util' module Puppet::Util::RubyGems # Base/factory class for rubygems source. These classes introspec into # rubygems to in order to list where the rubygems system will look for files # to load. class Source class << self # @api private def has_rubygems? # Gems are not actually available when Bundler is loaded, even # though the Gem constant is defined. This is because Bundler # loads in rubygems, but then removes the custom require that # rubygems installs. So when Bundler is around we have to act # as though rubygems is not, e.g. we shouldn't be able to load # a gem that Bundler doesn't want us to see. defined? ::Gem and !defined? ::Bundler end # @api private def source if has_rubygems? Gems18Source else NoGemsSource end end def new(*args) object = source.allocate object.send(:initialize, *args) object end end end # For RubyGems >= 1.8.0 # @api private class Gems18Source < Source def directories # `require 'mygem'` will consider and potentially load # prerelease gems, so we need to match that behavior. # # Just load the stub which points to the gem path, and # delay loading the full specification until if/when the # gem is required. Gem::Specification.stubs.collect do |spec| File.join(spec.full_gem_path, 'lib') end end def clear_paths Gem.clear_paths end end # @api private class NoGemsSource < Source def directories [] end def clear_paths; 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/file_watcher.rb
lib/puppet/util/file_watcher.rb
# frozen_string_literal: true class Puppet::Util::FileWatcher include Enumerable def each(&blk) @files.keys.each(&blk) end def initialize @files = {} end def changed? @files.values.any?(&:changed?) end def watch(filename) return if watching?(filename) @files[filename] = Puppet::Util::WatchedFile.new(filename) end def watching?(filename) @files.has_key?(filename) end def clear @files.clear 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/user_attr.rb
lib/puppet/util/user_attr.rb
# frozen_string_literal: true class UserAttr def self.get_attributes_by_name(name) attributes = nil File.readlines('/etc/user_attr').each do |line| next if line =~ /^#/ token = line.split(':') next unless token[0] == name attributes = { :name => name } token[4].split(';').each do |attr| key_value = attr.split('=') attributes[key_value[0].intern] = key_value[1].strip end break end attributes 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/terminal.rb
lib/puppet/util/terminal.rb
# frozen_string_literal: true module Puppet::Util::Terminal # Attempts to determine the width of the terminal. This is currently only # supported on POSIX systems, and relies on the claims of `stty` (or `tput`). # # Inspired by code from Thor; thanks wycats! # @return [Number] The column width of the terminal. Defaults to 80 columns. def self.width if Puppet.features.posix? result = %x(stty size 2>/dev/null).split[1] || %x(tput cols 2>/dev/null).split[0] end (result || '80').to_i rescue 80 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/pidlock.rb
lib/puppet/util/pidlock.rb
# frozen_string_literal: true require 'fileutils' require_relative '../../puppet/util/lockfile' class Puppet::Util::Pidlock def initialize(lockfile) @lockfile = Puppet::Util::Lockfile.new(lockfile) end def locked? clear_if_stale @lockfile.locked? end def mine? Process.pid == lock_pid end def lock return mine? if locked? @lockfile.lock(Process.pid) end def unlock if mine? @lockfile.unlock else false end end def lock_pid pid = @lockfile.lock_data begin Integer(pid) rescue ArgumentError, TypeError nil end end def file_path @lockfile.file_path end private def ps_argument_for_current_kernel case Puppet.runtime[:facter].value(:kernel) when "Linux" "-eq" when "AIX" "-T" else "-p" end end def clear_if_stale pid = lock_pid return @lockfile.unlock if pid.nil? return if Process.pid == pid errors = [Errno::ESRCH] # Win32::Process now throws SystemCallError. Since this could be # defined anywhere, only add when on Windows. errors << SystemCallError if Puppet::Util::Platform.windows? begin Process.kill(0, pid) rescue *errors return @lockfile.unlock end # Ensure the process associated with this pid is our process. If # not, we can unlock the lockfile. CLI arguments used for identifying # on POSIX depend on the os and sometimes even version. if Puppet.features.posix? ps_argument = ps_argument_for_current_kernel # Check, obtain and use the right ps argument begin procname = Puppet::Util::Execution.execute(["ps", ps_argument, pid, "-o", "comm="]).strip rescue Puppet::ExecutionFailure ps_argument = "-p" procname = Puppet::Util::Execution.execute(["ps", ps_argument, pid, "-o", "comm="]).strip end args = Puppet::Util::Execution.execute(["ps", ps_argument, pid, "-o", "args="]).strip @lockfile.unlock unless procname =~ /ruby/ && args =~ /puppet/ || procname =~ /puppet(-.*)?$/ elsif Puppet.features.microsoft_windows? # On Windows, we're checking if the filesystem path name of the running # process is our vendored ruby: begin exe_path = Puppet::Util::Windows::Process.get_process_image_name_by_pid(pid) @lockfile.unlock unless exe_path =~ /\\bin\\ruby.exe$/ rescue Puppet::Util::Windows::Error => e Puppet.debug("Failed to read pidfile #{file_path}: #{e.message}") 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/splayer.rb
lib/puppet/util/splayer.rb
# frozen_string_literal: true # Handle splay options (sleeping for a random interval before executing) module Puppet::Util::Splayer # Have we splayed already? def splayed? !!@splayed end # Sleep when splay is enabled; else just return. def splay(do_splay = Puppet[:splay]) return unless do_splay return if splayed? time = rand(Puppet[:splaylimit] + 1) Puppet.info _("Sleeping for %{time} seconds (splay is enabled)") % { time: time } sleep(time) @splayed = true 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/command_line.rb
lib/puppet/util/command_line.rb
# frozen_string_literal: true # Bundler and rubygems maintain a set of directories from which to # load gems. If Bundler is loaded, let it determine what can be # loaded. If it's not loaded, then use rubygems. But do this before # loading any puppet code, so that our gem loading system is sane. unless defined? ::Bundler begin require 'rubygems' rescue LoadError end end require_relative '../../puppet' require_relative '../../puppet/util' require_relative '../../puppet/util/rubygems' require_relative '../../puppet/util/limits' require_relative '../../puppet/util/colors' require_relative '../../puppet/gettext/module_translations' module Puppet module Util # This is the main entry point for all puppet applications / faces; it # is basically where the bootstrapping process / lifecycle of an app # begins. class CommandLine include Puppet::Util::Limits OPTION_OR_MANIFEST_FILE = /^-|\.pp$/ # @param zero [String] the name of the executable # @param argv [Array<String>] the arguments passed on the command line # @param stdin [IO] (unused) def initialize(zero = $PROGRAM_NAME, argv = ARGV, stdin = STDIN) @command = File.basename(zero, '.rb') @argv = argv end # @return [String] name of the subcommand is being executed # @api public def subcommand_name return @command if @command != 'puppet' if @argv.first =~ OPTION_OR_MANIFEST_FILE nil else @argv.first end end # @return [Array<String>] the command line arguments being passed to the subcommand # @api public def args return @argv if @command != 'puppet' if subcommand_name.nil? @argv else @argv[1..] end end # Run the puppet subcommand. If the subcommand is determined to be an # external executable, this method will never return and the current # process will be replaced via {Kernel#exec}. # # @return [void] def execute require_config = true if @argv.first =~ /help|-h|--help|-V|--version/ require_config = false end Puppet::Util.exit_on_fail(_("Could not initialize global default settings")) do Puppet.initialize_settings(args, require_config) end setpriority(Puppet[:priority]) find_subcommand.run end # @api private def external_subcommand Puppet::Util.which("puppet-#{subcommand_name}") end private def find_subcommand if subcommand_name.nil? if args.include?("--help") || args.include?("-h") ApplicationSubcommand.new("help", CommandLine.new("puppet", ["help"])) else NilSubcommand.new(self) end elsif Puppet::Application.available_application_names.include?(subcommand_name) ApplicationSubcommand.new(subcommand_name, self) else path_to_subcommand = external_subcommand if path_to_subcommand ExternalSubcommand.new(path_to_subcommand, self) else UnknownSubcommand.new(subcommand_name, self) end end end # @api private class ApplicationSubcommand def initialize(subcommand_name, command_line) @subcommand_name = subcommand_name @command_line = command_line end def run # For most applications, we want to be able to load code from the modulepath, # such as apply, describe, resource, and faces. # For agent and device in agent mode, we only want to load pluginsync'ed code from libdir. # For master, we shouldn't ever be loading per-environment code into the master's # ruby process, but that requires fixing (#17210, #12173, #8750). So for now # we try to restrict to only code that can be autoloaded from the node's # environment. # PUP-2114 - at this point in the bootstrapping process we do not # have an appropriate application-wide current_environment set. # If we cannot find the configured environment, which may not exist, # we do not attempt to add plugin directories to the load path. unless @subcommand_name == 'master' || @subcommand_name == 'agent' || (@subcommand_name == 'device' && (['--apply', '--facts', '--resource'] - @command_line.args).empty?) configured_environment = Puppet.lookup(:environments).get(Puppet[:environment]) if configured_environment configured_environment.each_plugin_directory do |dir| $LOAD_PATH << dir unless $LOAD_PATH.include?(dir) end Puppet::ModuleTranslations.load_from_modulepath(configured_environment.modules) Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir]) # Puppet requires Facter, which initializes its lookup paths. Reset Facter to # pickup the new $LOAD_PATH. Puppet.runtime[:facter].reset end end app = Puppet::Application.find(@subcommand_name).new(@command_line) app.run end end # @api private class ExternalSubcommand def initialize(path_to_subcommand, command_line) @path_to_subcommand = path_to_subcommand @command_line = command_line end def run Kernel.exec(@path_to_subcommand, *@command_line.args) end end # @api private class NilSubcommand include Puppet::Util::Colors def initialize(command_line) @command_line = command_line end def run args = @command_line.args if args.include? "--version" or args.include? "-V" puts Puppet.version elsif @command_line.subcommand_name.nil? && args.count > 0 # If the subcommand is truly nil and there is an arg, it's an option; print out the invalid option message puts colorize(:hred, _("Error: Could not parse application options: invalid option: %{opt}") % { opt: args[0] }) exit 1 else puts _("See 'puppet help' for help on available subcommands") end end end # @api private class UnknownSubcommand < NilSubcommand def initialize(subcommand_name, command_line) @subcommand_name = subcommand_name super(command_line) end def run puts colorize(:hred, _("Error: Unknown subcommand '%{cmd}'") % { cmd: @subcommand_name }) super exit 1 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/util/ldap.rb
lib/puppet/util/ldap.rb
# frozen_string_literal: true module Puppet::Util::Ldap 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/execution.rb
lib/puppet/util/execution.rb
# frozen_string_literal: true require 'timeout' require_relative '../../puppet/file_system/uniquefile' module Puppet require 'rbconfig' require_relative '../../puppet/error' # A command failed to execute. # @api public class ExecutionFailure < Puppet::Error end end # This module defines methods for execution of system commands. It is intended for inclusion # in classes that needs to execute system commands. # @api public module Puppet::Util::Execution # This is the full output from a process. The object itself (a String) is the # stdout of the process. # # @api public class ProcessOutput < String # @return [Integer] The exit status of the process # @api public attr_reader :exitstatus # @api private def initialize(value, exitstatus) super(value) @exitstatus = exitstatus end end # The command can be a simple string, which is executed as-is, or an Array, # which is treated as a set of command arguments to pass through. # # In either case, the command is passed directly to the shell, STDOUT and # STDERR are connected together, and STDOUT will be streamed to the yielded # pipe. # # @param command [String, Array<String>] the command to execute as one string, # or as parts in an array. The parts of the array are joined with one # separating space between each entry when converting to the command line # string to execute. # @param failonfail [Boolean] (true) if the execution should fail with # Exception on failure or not. # @yield [pipe] to a block executing a subprocess # @yieldparam pipe [IO] the opened pipe # @yieldreturn [String] the output to return # @raise [Puppet::ExecutionFailure] if the executed child process did not # exit with status == 0 and `failonfail` is `true`. # @return [String] a string with the output from the subprocess executed by # the given block # # @see Kernel#open for `mode` values # @api public def self.execpipe(command, failonfail = true) # Paste together an array with spaces. We used to paste directly # together, no spaces, which made for odd invocations; the user had to # include whitespace between arguments. # # Having two spaces is really not a big drama, since this passes to the # shell anyhow, while no spaces makes for a small developer cost every # time this is invoked. --daniel 2012-02-13 command_str = command.respond_to?(:join) ? command.join(' ') : command if respond_to? :debug debug "Executing '#{command_str}'" else Puppet.debug { "Executing '#{command_str}'" } end # force the run of the command with # the user/system locale to "C" (via environment variables LANG and LC_*) # it enables to have non localized output for some commands and therefore # a predictable output english_env = ENV.to_hash.merge({ 'LANG' => 'C', 'LC_ALL' => 'C' }) output = Puppet::Util.withenv(english_env) do # We are intentionally using 'pipe' with open to launch a process open("| #{command_str} 2>&1") do |pipe| # rubocop:disable Security/Open yield pipe end end if failonfail && exitstatus != 0 raise Puppet::ExecutionFailure, output.to_s end output end def self.exitstatus $CHILD_STATUS.exitstatus end private_class_method :exitstatus # Default empty options for {execute} NoOptionsSpecified = {} # Executes the desired command, and return the status and output. # def execute(command, options) # @param command [Array<String>, String] the command to execute. If it is # an Array the first element should be the executable and the rest of the # elements should be the individual arguments to that executable. # @param options [Hash] a Hash of options # @option options [String] :cwd the directory from which to run the command. Raises an error if the directory does not exist. # This option is only available on the agent. It cannot be used on the master, meaning it cannot be used in, for example, # regular functions, hiera backends, or report processors. # @option options [Boolean] :failonfail if this value is set to true, then this method will raise an error if the # command is not executed successfully. # @option options [Integer, String] :uid (nil) the user id of the user that the process should be run as. Will be ignored if the # user id matches the effective user id of the current process. # @option options [Integer, String] :gid (nil) the group id of the group that the process should be run as. Will be ignored if the # group id matches the effective group id of the current process. # @option options [Boolean] :combine sets whether or not to combine stdout/stderr in the output, if false stderr output is discarded # @option options [String] :stdinfile (nil) sets a file that can be used for stdin. Passing a string for stdin is not currently # supported. # @option options [Boolean] :squelch (false) if true, ignore stdout / stderr completely. # @option options [Boolean] :override_locale (true) by default (and if this option is set to true), we will temporarily override # the user/system locale to "C" (via environment variables LANG and LC_*) while we are executing the command. # This ensures that the output of the command will be formatted consistently, making it predictable for parsing. # Passing in a value of false for this option will allow the command to be executed using the user/system locale. # @option options [Hash<{String => String}>] :custom_environment ({}) a hash of key/value pairs to set as environment variables for the duration # of the command. # @return [Puppet::Util::Execution::ProcessOutput] output as specified by options # @raise [Puppet::ExecutionFailure] if the executed chiled process did not exit with status == 0 and `failonfail` is # `true`. # @note Unfortunately, the default behavior for failonfail and combine (since # 0.22.4 and 0.24.7, respectively) depend on whether options are specified # or not. If specified, then failonfail and combine default to false (even # when the options specified are neither failonfail nor combine). If no # options are specified, then failonfail and combine default to true. # @comment See commits efe9a833c and d32d7f30 # @api public # def self.execute(command, options = NoOptionsSpecified) # specifying these here rather than in the method signature to allow callers to pass in a partial # set of overrides without affecting the default values for options that they don't pass in default_options = { :failonfail => NoOptionsSpecified.equal?(options), :uid => nil, :gid => nil, :combine => NoOptionsSpecified.equal?(options), :stdinfile => nil, :squelch => false, :override_locale => true, :custom_environment => {}, :sensitive => false, :suppress_window => false, } options = default_options.merge(options) case command when Array command = command.flatten.map(&:to_s) command_str = command.join(" ") when String command_str = command end # do this after processing 'command' array or string command_str = '[redacted]' if options[:sensitive] user_log_s = ''.dup if options[:uid] user_log_s << " uid=#{options[:uid]}" end if options[:gid] user_log_s << " gid=#{options[:gid]}" end if user_log_s != '' user_log_s.prepend(' with') end if respond_to? :debug debug "Executing#{user_log_s}: '#{command_str}'" else Puppet.debug { "Executing#{user_log_s}: '#{command_str}'" } end null_file = Puppet::Util::Platform.windows? ? 'NUL' : '/dev/null' cwd = options[:cwd] if cwd && !Puppet::FileSystem.directory?(cwd) raise ArgumentError, _("Working directory %{cwd} does not exist!") % { cwd: cwd } end begin stdin = Puppet::FileSystem.open(options[:stdinfile] || null_file, nil, 'r') # On Windows, continue to use the file-based approach to avoid breaking people's existing # manifests. If they use a script that doesn't background cleanly, such as # `start /b ping 127.0.0.1`, we couldn't handle it with pipes as there's no non-blocking # read available. if options[:squelch] stdout = Puppet::FileSystem.open(null_file, nil, 'w') elsif Puppet.features.posix? reader, stdout = IO.pipe else stdout = Puppet::FileSystem::Uniquefile.new('puppet') end stderr = options[:combine] ? stdout : Puppet::FileSystem.open(null_file, nil, 'w') exec_args = [command, options, stdin, stdout, stderr] output = ''.dup # We close stdin/stdout/stderr immediately after fork/exec as they're no longer needed by # this process. In most cases they could be closed later, but when `stdout` is the "writer" # pipe we must close it or we'll never reach eof on the `reader` pipe. execution_stub = Puppet::Util::ExecutionStub.current_value if execution_stub child_pid = execution_stub.call(*exec_args) [stdin, stdout, stderr].each { |io| begin io.close rescue nil end } return child_pid elsif Puppet.features.posix? child_pid = nil begin child_pid = execute_posix(*exec_args) [stdin, stdout, stderr].each { |io| begin io.close rescue nil end } if options[:squelch] exit_status = Process.waitpid2(child_pid).last.exitstatus else # Use non-blocking read to check for data. After each attempt, # check whether the child is done. This is done in case the child # forks and inherits stdout, as happens in `foo &`. # If we encounter EOF, though, then switch to a blocking wait for # the child; after EOF, IO.select will never block and the loop # below will use maximum CPU available. wait_flags = Process::WNOHANG until results = Process.waitpid2(child_pid, wait_flags) # rubocop:disable Lint/AssignmentInCondition # If not done, wait for data to read with a timeout # This timeout is selected to keep activity low while waiting on # a long process, while not waiting too long for the pathological # case where stdout is never closed. ready = IO.select([reader], [], [], 0.1) begin output << reader.read_nonblock(4096) if ready rescue Errno::EAGAIN rescue EOFError wait_flags = 0 end end # Read any remaining data. Allow for but don't expect EOF. begin loop do output << reader.read_nonblock(4096) end rescue Errno::EAGAIN rescue EOFError end # Force to external encoding to preserve prior behavior when reading a file. # Wait until after reading all data so we don't encounter corruption when # reading part of a multi-byte unicode character if default_external is UTF-8. output.force_encoding(Encoding.default_external) exit_status = results.last.exitstatus end child_pid = nil rescue Timeout::Error => e # NOTE: For Ruby 2.1+, an explicit Timeout::Error class has to be # passed to Timeout.timeout in order for there to be something for # this block to rescue. unless child_pid.nil? Process.kill(:TERM, child_pid) # Spawn a thread to reap the process if it dies. Thread.new { Process.waitpid(child_pid) } end raise e end elsif Puppet::Util::Platform.windows? process_info = execute_windows(*exec_args) begin [stdin, stderr].each { |io| begin io.close rescue nil end } exit_status = Puppet::Util::Windows::Process.wait_process(process_info.process_handle) # read output in if required unless options[:squelch] output = wait_for_output(stdout) Puppet.warning _("Could not get output") unless output end ensure FFI::WIN32.CloseHandle(process_info.process_handle) FFI::WIN32.CloseHandle(process_info.thread_handle) end end if options[:failonfail] and exit_status != 0 raise Puppet::ExecutionFailure, _("Execution of '%{str}' returned %{exit_status}: %{output}") % { str: command_str, exit_status: exit_status, output: output.strip } end ensure # Make sure all handles are closed in case an exception was thrown attempting to execute. [stdin, stdout, stderr].each { |io| begin io.close rescue nil end } unless options[:squelch] # if we opened a pipe, we need to clean it up. reader.close if reader stdout.close! if stdout && Puppet::Util::Platform.windows? end end Puppet::Util::Execution::ProcessOutput.new(output || '', exit_status) end # Returns the path to the ruby executable (available via Config object, even if # it's not in the PATH... so this is slightly safer than just using Puppet::Util.which) # @return [String] the path to the Ruby executable # @api private # def self.ruby_path File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT']) .sub(/.*\s.*/m, '"\&"') end # Because some modules provide their own version of this method. class << self alias util_execute execute end # This is private method. # @comment see call to private_class_method after method definition # @api private # def self.execute_posix(command, options, stdin, stdout, stderr) Puppet::Util.safe_posix_fork(stdin, stdout, stderr) do # We can't just call Array(command), and rely on it returning # things like ['foo'], when passed ['foo'], because # Array(command) will call command.to_a internally, which when # given a string can end up doing Very Bad Things(TM), such as # turning "/tmp/foo;\r\n /bin/echo" into ["/tmp/foo;\r\n", " /bin/echo"] command = [command].flatten Process.setsid begin # We need to chdir to our cwd before changing privileges as there's a # chance that the user may not have permissions to access the cwd, which # would cause execute_posix to fail. cwd = options[:cwd] Dir.chdir(cwd) if cwd Puppet::Util::SUIDManager.change_privileges(options[:uid], options[:gid], true) # if the caller has requested that we override locale environment variables, if options[:override_locale] then # loop over them and clear them Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |name| ENV.delete(name) } # set LANG and LC_ALL to 'C' so that the command will have consistent, predictable output # it's OK to manipulate these directly rather than, e.g., via "withenv", because we are in # a forked process. ENV['LANG'] = 'C' ENV['LC_ALL'] = 'C' end # unset all of the user-related environment variables so that different methods of starting puppet # (automatic start during boot, via 'service', via /etc/init.d, etc.) won't have unexpected side # effects relating to user / home dir environment vars. # it's OK to manipulate these directly rather than, e.g., via "withenv", because we are in # a forked process. Puppet::Util::POSIX::USER_ENV_VARS.each { |name| ENV.delete(name) } options[:custom_environment] ||= {} Puppet::Util.withenv(options[:custom_environment]) do Kernel.exec(*command) end rescue => detail Puppet.log_exception(detail, _("Could not execute posix command: %{detail}") % { detail: detail }) exit!(1) end end end private_class_method :execute_posix # This is private method. # @comment see call to private_class_method after method definition # @api private # def self.execute_windows(command, options, stdin, stdout, stderr) command = command.map do |part| part.include?(' ') ? %Q("#{part.gsub(/"/, '\"')}") : part end.join(" ") if command.is_a?(Array) options[:custom_environment] ||= {} Puppet::Util.withenv(options[:custom_environment]) do Puppet::Util::Windows::Process.execute(command, options, stdin, stdout, stderr) end end private_class_method :execute_windows # This is private method. # @comment see call to private_class_method after method definition # @api private # def self.wait_for_output(stdout) # Make sure the file's actually been written. This is basically a race # condition, and is probably a horrible way to handle it, but, well, oh # well. # (If this method were treated as private / inaccessible from outside of this file, we shouldn't have to worry # about a race condition because all of the places that we call this from are preceded by a call to "waitpid2", # meaning that the processes responsible for writing the file have completed before we get here.) 2.times do |try| if Puppet::FileSystem.exist?(stdout.path) stdout.open begin return stdout.read ensure stdout.close stdout.unlink end else time_to_sleep = try / 2.0 Puppet.warning _("Waiting for output; will sleep %{time_to_sleep} seconds") % { time_to_sleep: time_to_sleep } sleep(time_to_sleep) end end nil end private_class_method :wait_for_output 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/multi_match.rb
lib/puppet/util/multi_match.rb
# frozen_string_literal: true # MultiMatch allows multiple values to be tested at once in a case expression. # This class is needed since Array does not implement the === operator to mean # "each v === other.each v". # # This class is useful in situations when the Puppet Type System cannot be used # (e.g. in Logging, since it needs to be able to log very early in the initialization # cycle of puppet) # # Typically used with the constants # NOT_NIL # TUPLE # TRIPLE # # which test against single NOT_NIL value, Array with two NOT_NIL, and Array with three NOT_NIL # module Puppet::Util class MultiMatch attr_reader :values def initialize(*values) @values = values end def ===(other) lv = @values # local var is faster than instance var case other when MultiMatch return false unless other.values.size == values.size other.values.each_with_index { |v, i| return false unless lv[i] === v || v === lv[i] } when Array return false unless other.size == values.size other.each_with_index { |v, i| return false unless lv[i] === v || v === lv[i] } else false end true end # Matches any value that is not nil using the === operator. # class MatchNotNil def ===(v) !v.nil? end end NOT_NIL = MatchNotNil.new().freeze TUPLE = MultiMatch.new(NOT_NIL, NOT_NIL).freeze TRIPLE = MultiMatch.new(NOT_NIL, NOT_NIL, NOT_NIL).freeze 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/provider_features.rb
lib/puppet/util/provider_features.rb
# frozen_string_literal: true # Provides feature definitions. require_relative '../../puppet/util/docs' require_relative '../../puppet/util' # This module models provider features and handles checking whether the features # are present. # @todo Unclear what is api and what is private in this module. # module Puppet::Util::ProviderFeatures include Puppet::Util::Docs # This class models provider features and handles checking whether the features # are present. # @todo Unclear what is api and what is private in this class class ProviderFeature include Puppet::Util include Puppet::Util::Docs attr_accessor :name, :docs, :methods # Are all of the requirements met? # Requirements are checked by checking if feature predicate methods have been generated - see {#methods_available?}. # @param obj [Object, Class] the object or class to check if requirements are met # @return [Boolean] whether all requirements for this feature are met or not. def available?(obj) if methods !!methods_available?(obj) else # In this case, the provider has to declare support for this # feature, and that's been checked before we ever get to the # method checks. false end end def initialize(name, docs, methods: nil) self.name = name.intern self.docs = docs @methods = methods end private # Checks whether all feature predicate methods are available. # @param obj [Object, Class] the object or class to check if feature predicates are available or not. # @return [Boolean] Returns whether all of the required methods are available or not in the given object. def methods_available?(obj) methods.each do |m| if obj.is_a?(Class) return false unless obj.public_method_defined?(m) else return false unless obj.respond_to?(m) end end true end end # Defines one feature. # At a minimum, a feature requires a name # and docs, and at this point they should also specify a list of methods # required to determine if the feature is present. # @todo How methods that determine if the feature is present are specified. def feature(name, docs, hash = {}) @features ||= {} raise Puppet::DevError, _("Feature %{name} is already defined") % { name: name } if @features.include?(name) begin obj = ProviderFeature.new(name, docs, **hash) @features[obj.name] = obj rescue ArgumentError => detail error = ArgumentError.new( _("Could not create feature %{name}: %{detail}") % { name: name, detail: detail } ) error.set_backtrace(detail.backtrace) raise error end end # @return [String] Returns a string with documentation covering all features. def featuredocs str = ''.dup @features ||= {} return nil if @features.empty? names = @features.keys.sort_by(&:to_s) names.each do |name| doc = @features[name].docs.gsub(/\n\s+/, " ") str << "- *#{name}*: #{doc}\n" end if providers.length > 0 headers = ["Provider", names].flatten data = {} providers.each do |provname| data[provname] = [] prov = provider(provname) names.each do |name| if prov.feature?(name) data[provname] << "*X*" else data[provname] << "" end end end str << doctable(headers, data) end str end # @return [Array<String>] Returns a list of features. def features @features ||= {} @features.keys end # Generates a module that sets up the boolean predicate methods to test for given features. # def feature_module unless defined?(@feature_module) @features ||= {} @feature_module = ::Module.new const_set("FeatureModule", @feature_module) features = @features # Create a feature? method that can be passed a feature name and # determine if the feature is present. @feature_module.send(:define_method, :feature?) do |name| method = name.to_s + "?" return !!(respond_to?(method) and send(method)) end # Create a method that will list all functional features. @feature_module.send(:define_method, :features) do return false unless defined?(features) features.keys.find_all { |n| feature?(n) }.sort_by(&:to_s) end # Create a method that will determine if a provided list of # features are satisfied by the curred provider. @feature_module.send(:define_method, :satisfies?) do |*needed| ret = true needed.flatten.each do |feature| unless feature?(feature) ret = false break end end ret end # Create a boolean method for each feature so you can test them # individually as you might need. @features.each do |name, feature| method = name.to_s + "?" @feature_module.send(:define_method, method) do (is_a?(Class) ? declared_feature?(name) : self.class.declared_feature?(name)) or feature.available?(self) end end # Allow the provider to declare that it has a given feature. @feature_module.send(:define_method, :has_features) do |*names| @declared_features ||= [] names.each do |name| @declared_features << name.intern end end # Aaah, grammatical correctness @feature_module.send(:alias_method, :has_feature, :has_features) end @feature_module end # @return [ProviderFeature] Returns a provider feature instance by name. # @param name [String] the name of the feature to return # @note Should only be used for testing. # @api private # def provider_feature(name) return nil unless defined?(@features) @features[name] end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/skip_tags.rb
lib/puppet/util/skip_tags.rb
# frozen_string_literal: true require_relative '../../puppet/util/tagging' class Puppet::Util::SkipTags include Puppet::Util::Tagging def initialize(stags) self.tags = stags unless defined?(@tags) end def split_qualified_tags? false end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/network_device.rb
lib/puppet/util/network_device.rb
# frozen_string_literal: true class Puppet::Util::NetworkDevice class << self attr_reader :current end def self.init(device) require "puppet/util/network_device/#{device.provider}/device" @current = Puppet::Util::NetworkDevice.const_get(device.provider.capitalize).const_get(:Device).new(device.url, device.options) rescue => detail raise detail, _("Can't load %{provider} for %{device}: %{detail}") % { provider: device.provider, device: device.name, detail: detail }, detail.backtrace end # Should only be used in tests def self.teardown @current = 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/util/run_mode.rb
lib/puppet/util/run_mode.rb
# frozen_string_literal: true require 'etc' module Puppet module Util class RunMode def initialize(name) @name = name.to_sym end attr_reader :name def self.[](name) @run_modes ||= {} if Puppet::Util::Platform.windows? @run_modes[name] ||= WindowsRunMode.new(name) else @run_modes[name] ||= UnixRunMode.new(name) end end def server? name == :master || name == :server end def master? name == :master || name == :server end def agent? name == :agent end def user? name == :user end def run_dir RunMode[name].run_dir end def log_dir RunMode[name].log_dir end private ## # select the system or the user directory depending on the context of # this process. The most common use is determining filesystem path # values for confdir and vardir. The intended semantics are: # {https://projects.puppetlabs.com/issues/16637 #16637} for Puppet 3.x # # @todo this code duplicates {Puppet::Settings#which\_configuration\_file} # as described in {https://projects.puppetlabs.com/issues/16637 #16637} def which_dir(system, user) if Puppet.features.root? File.expand_path(system) else File.expand_path(user) end end end class UnixRunMode < RunMode def conf_dir which_dir("/etc/puppetlabs/puppet", "~/.puppetlabs/etc/puppet") end def code_dir which_dir("/etc/puppetlabs/code", "~/.puppetlabs/etc/code") end def var_dir which_dir("/opt/puppetlabs/puppet/cache", "~/.puppetlabs/opt/puppet/cache") end def public_dir which_dir("/opt/puppetlabs/puppet/public", "~/.puppetlabs/opt/puppet/public") end def run_dir ENV.fetch('RUNTIME_DIRECTORY') { which_dir("/var/run/puppetlabs", "~/.puppetlabs/var/run") } end def log_dir which_dir("/var/log/puppetlabs/puppet", "~/.puppetlabs/var/log") end def pkg_config_path '/opt/puppetlabs/puppet/lib/pkgconfig' end def gem_cmd '/opt/puppetlabs/puppet/bin/gem' end def common_module_dir '/opt/puppetlabs/puppet/modules' end def vendor_module_dir '/opt/puppetlabs/puppet/vendor_modules' end end class WindowsRunMode < RunMode def conf_dir which_dir(File.join(windows_common_base("puppet/etc")), "~/.puppetlabs/etc/puppet") end def code_dir which_dir(File.join(windows_common_base("code")), "~/.puppetlabs/etc/code") end def var_dir which_dir(File.join(windows_common_base("puppet/cache")), "~/.puppetlabs/opt/puppet/cache") end def public_dir which_dir(File.join(windows_common_base("puppet/public")), "~/.puppetlabs/opt/puppet/public") end def run_dir which_dir(File.join(windows_common_base("puppet/var/run")), "~/.puppetlabs/var/run") end def log_dir which_dir(File.join(windows_common_base("puppet/var/log")), "~/.puppetlabs/var/log") end def pkg_config_path nil end def gem_cmd if (puppet_dir = ENV.fetch('PUPPET_DIR', nil)) File.join(puppet_dir.to_s, 'bin', 'gem.bat') else File.join(Gem.default_bindir, 'gem.bat') end end def common_module_dir "#{installdir}/puppet/modules" if installdir end def vendor_module_dir "#{installdir}\\puppet\\vendor_modules" if installdir end private def installdir ENV.fetch('FACTER_env_windows_installdir', nil) end def windows_common_base(*extra) [ENV.fetch('ALLUSERSPROFILE', nil), "PuppetLabs"] + extra 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/tagging.rb
lib/puppet/util/tagging.rb
# frozen_string_literal: true require_relative '../../puppet/util/tag_set' module Puppet::Util::Tagging ValidTagRegex = /\A[[:alnum:]_][[:alnum:]_:.-]*\Z/u # Add a tag to the current tag set. # When a tag set is used for a scope, these tags will be added to all of # the objects contained in this scope when the objects are finished. # def tag(*ary) @tags ||= new_tags ary.flatten.compact.each do |tag| name = tag.to_s.downcase # Add the tag before testing if it's valid since this means that # we never need to test the same valid tag twice. This speeds things # up since we get a lot of duplicates and rarely fail on bad tags if @tags.add?(name) # not seen before, so now we test if it is valid if valid_tag?(name) if split_qualified_tags? # avoid adding twice by first testing if the string contains '::' @tags.merge(name.split('::')) if name.include?('::') end else @tags.delete(name) fail(Puppet::ParseError, _("Invalid tag '%{name}'") % { name: name }) end end end end # Add a name to the current tag set. Silently ignore names that does not # represent valid tags. # # Use this method instead of doing this: # # tag(name) if is_valid?(name) # # since that results in testing the same string twice # def tag_if_valid(name) if name.is_a?(String) && valid_tag?(name) name = name.downcase @tags ||= new_tags if @tags.add?(name) && name.include?('::') @tags.merge(name.split('::')) end end end # Answers if this resource is tagged with at least one of the given tags. # # The given tags are converted to downcased strings before the match is performed. # # @param *tags [String] splat of tags to look for # @return [Boolean] true if this instance is tagged with at least one of the provided tags # def tagged?(*tags) raw_tagged?(tags.collect { |t| t.to_s.downcase }) end # Answers if this resource is tagged with at least one of the tags given in downcased string form. # # The method is a faster variant of the tagged? method that does no conversion of its # arguments. # # @param tag_array [Array[String]] array of tags to look for # @return [Boolean] true if this instance is tagged with at least one of the provided tags # def raw_tagged?(tag_array) my_tags = tags !tag_array.index { |t| my_tags.include?(t) }.nil? end # Only use this method when copying known tags from one Tagging instance to another def set_tags(tag_source) @tags = tag_source.tags end # Return a copy of the tag list, so someone can't ask for our tags # and then modify them. def tags @tags ||= new_tags @tags.dup end # Merge tags from a tagged instance with no attempts to split, downcase # or verify the tags def merge_tags_from(tag_source) @tags ||= new_tags tag_source.merge_into(@tags) end # Merge the tags of this instance into the provide TagSet def merge_into(tag_set) tag_set.merge(@tags) unless @tags.nil? end def tags=(tags) @tags = new_tags return if tags.nil? tags = tags.strip.split(/\s*,\s*/) if tags.is_a?(String) tag(*tags) end def valid_tag?(maybe_tag) tag_enc = maybe_tag.encoding if tag_enc == Encoding::UTF_8 || tag_enc == Encoding::ASCII maybe_tag =~ ValidTagRegex else maybe_tag.encode(Encoding::UTF_8) =~ ValidTagRegex end rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError false end private def split_qualified_tags? true end def new_tags Puppet::Util::TagSet.new end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/rpm_compare.rb
lib/puppet/util/rpm_compare.rb
# frozen_string_literal: true require 'English' module Puppet::Util::RpmCompare ARCH_LIST = %w[ noarch i386 i686 ppc ppc64 armv3l armv4b armv4l armv4tl armv5tel armv5tejl armv6l armv7l m68kmint s390 s390x ia64 x86_64 sh3 sh4 ].freeze ARCH_REGEX = Regexp.new(ARCH_LIST.map { |arch| "\\.#{arch}" }.join('|')) # This is an attempt at implementing RPM's # lib/rpmvercmp.c rpmvercmp(a, b) in Ruby. # # Some of the things in here look REALLY # UGLY and/or arbitrary. Our goal is to # match how RPM compares versions, quirks # and all. # # I've kept a lot of C-like string processing # in an effort to keep this as identical to RPM # as possible. # # returns 1 if str1 is newer than str2, # 0 if they are identical # -1 if str1 is older than str2 def rpmvercmp(str1, str2) return 0 if str1 == str2 front_strip_re = /^[^A-Za-z0-9~]+/ while str1.length > 0 or str2.length > 0 # trim anything that's in front_strip_re and != '~' off the beginning of each string str1 = str1.gsub(front_strip_re, '') str2 = str2.gsub(front_strip_re, '') # "handle the tilde separator, it sorts before everything else" if str1 =~ /^~/ && str2 =~ /^~/ # if they both have ~, strip it str1 = str1[1..] str2 = str2[1..] next elsif str1 =~ /^~/ return -1 elsif str2 =~ /^~/ return 1 end break if str1.length == 0 or str2.length == 0 # "grab first completely alpha or completely numeric segment" isnum = false # if the first char of str1 is a digit, grab the chunk of continuous digits from each string if str1 =~ /^[0-9]+/ if str1 =~ /^[0-9]+/ segment1 = $LAST_MATCH_INFO.to_s str1 = $LAST_MATCH_INFO.post_match else segment1 = '' end if str2 =~ /^[0-9]+/ segment2 = $LAST_MATCH_INFO.to_s str2 = $LAST_MATCH_INFO.post_match else segment2 = '' end isnum = true # else grab the chunk of continuous alphas from each string (which may be '') else if str1 =~ /^[A-Za-z]+/ segment1 = $LAST_MATCH_INFO.to_s str1 = $LAST_MATCH_INFO.post_match else segment1 = '' end if str2 =~ /^[A-Za-z]+/ segment2 = $LAST_MATCH_INFO.to_s str2 = $LAST_MATCH_INFO.post_match else segment2 = '' end end # if the segments we just grabbed from the strings are different types (i.e. one numeric one alpha), # where alpha also includes ''; "numeric segments are always newer than alpha segments" if segment2.length == 0 return 1 if isnum return -1 end if isnum # "throw away any leading zeros - it's a number, right?" segment1 = segment1.gsub(/^0+/, '') segment2 = segment2.gsub(/^0+/, '') # "whichever number has more digits wins" return 1 if segment1.length > segment2.length return -1 if segment1.length < segment2.length end # "strcmp will return which one is greater - even if the two segments are alpha # or if they are numeric. don't return if they are equal because there might # be more segments to compare" rc = segment1 <=> segment2 return rc if rc != 0 end # end while loop # if we haven't returned anything yet, "whichever version still has characters left over wins" return 1 if str1.length > str2.length return -1 if str1.length < str2.length 0 end # parse a rpm "version" specification # this re-implements rpm's # rpmUtils.miscutils.stringToVersion() in ruby def rpm_parse_evr(full_version) epoch_index = full_version.index(':') if epoch_index epoch = full_version[0, epoch_index] full_version = full_version[epoch_index + 1, full_version.length] else epoch = nil end begin epoch = String(Integer(epoch)) rescue # If there are non-digits in the epoch field, default to nil epoch = nil end release_index = full_version.index('-') if release_index version = full_version[0, release_index] release = full_version[release_index + 1, full_version.length] arch = release.scan(ARCH_REGEX)[0] if arch architecture = arch.delete('.') release.gsub!(ARCH_REGEX, '') end else version = full_version release = nil end { :epoch => epoch, :version => version, :release => release, :arch => architecture } end # this method is a native implementation of the # compare_values function in rpm's python bindings, # found in python/header-py.c, as used by rpm. def compare_values(s1, s2) return 0 if s1.nil? && s2.nil? return 1 if !s1.nil? && s2.nil? return -1 if s1.nil? && !s2.nil? rpmvercmp(s1, s2) end # how rpm compares two package versions: # rpmUtils.miscutils.compareEVR(), which massages data types and then calls # rpm.labelCompare(), found in rpm.git/python/header-py.c, which # sets epoch to 0 if null, then compares epoch, then ver, then rel # using compare_values() and returns the first non-0 result, else 0. # This function combines the logic of compareEVR() and labelCompare(). # # "version_should" can be v, v-r, or e:v-r. # "version_is" will always be at least v-r, can be e:v-r # # return 1: a is newer than b # 0: a and b are the same version # -1: b is newer than a def rpm_compare_evr(should, is) # pass on to rpm labelCompare should_hash = rpm_parse_evr(should) is_hash = rpm_parse_evr(is) unless should_hash[:epoch].nil? rc = compare_values(should_hash[:epoch], is_hash[:epoch]) return rc unless rc == 0 end rc = compare_values(should_hash[:version], is_hash[:version]) return rc unless rc == 0 # here is our special case, PUP-1244. # if should_hash[:release] is nil (not specified by the user), # and comparisons up to here are equal, return equal. We need to # evaluate to whatever level of detail the user specified, so we # don't end up upgrading or *downgrading* when not intended. # # This should NOT be triggered if we're trying to ensure latest. return 0 if should_hash[:release].nil? compare_values(should_hash[:release], is_hash[:release]) 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/posix.rb
lib/puppet/util/posix.rb
# frozen_string_literal: true # Utility methods for interacting with POSIX objects; mostly user and group module Puppet::Util::POSIX # This is a list of environment variables that we will set when we want to override the POSIX locale LOCALE_ENV_VARS = %w[LANG LC_ALL LC_MESSAGES LANGUAGE LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME] # This is a list of user-related environment variables that we will unset when we want to provide a pristine # environment for "exec" runs USER_ENV_VARS = %w[HOME USER LOGNAME] class << self # Returns an array of all the groups that the user's a member of. def groups_of(user) begin require_relative '../../puppet/ffi/posix' groups = get_groups_list(user) rescue StandardError, LoadError => e Puppet.debug("Falling back to Puppet::Etc.group: #{e.message}") groups = [] Puppet::Etc.group do |group| groups << group.name if group.mem.include?(user) end end uniq_groups = groups.uniq if uniq_groups != groups Puppet.debug(_('Removing any duplicate group entries')) end uniq_groups end private def get_groups_list(user) raise LoadError, "The 'getgrouplist' method is not available" unless Puppet::FFI::POSIX::Functions.respond_to?(:getgrouplist) user_gid = Puppet::Etc.getpwnam(user).gid ngroups = Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS loop do FFI::MemoryPointer.new(:int) do |ngroups_ptr| FFI::MemoryPointer.new(:uint, ngroups) do |groups_ptr| old_ngroups = ngroups ngroups_ptr.write_int(ngroups) if Puppet::FFI::POSIX::Functions.getgrouplist(user, user_gid, groups_ptr, ngroups_ptr) != -1 groups_gids = groups_ptr.get_array_of_uint(0, ngroups_ptr.read_int) result = [] groups_gids.each do |group_gid| group_info = Puppet::Etc.getgrgid(group_gid) result |= [group_info.name] if group_info.mem.include?(user) end return result end ngroups = ngroups_ptr.read_int if ngroups <= old_ngroups ngroups *= 2 end end end end end end # Retrieve a field from a POSIX Etc object. The id can be either an integer # or a name. This only works for users and groups. It's also broken on # some platforms, unfortunately, which is why we fall back to the other # method search_posix_field in the gid and uid methods if a sanity check # fails def get_posix_field(space, field, id) raise Puppet::DevError, _("Did not get id from caller") unless id if id.is_a?(Integer) if id > Puppet[:maximum_uid].to_i Puppet.err _("Tried to get %{field} field for silly id %{id}") % { field: field, id: id } return nil end method = methodbyid(space) else method = methodbyname(space) end begin Etc.send(method, id).send(field) rescue NoMethodError, ArgumentError # ignore it; we couldn't find the object nil end end # A degenerate method of retrieving name/id mappings. The job of this method is # to retrieve all objects of a certain type, search for a specific entry # and then return a given field from that entry. def search_posix_field(type, field, id) idmethod = idfield(type) integer = false if id.is_a?(Integer) integer = true if id > Puppet[:maximum_uid].to_i Puppet.err _("Tried to get %{field} field for silly id %{id}") % { field: field, id: id } return nil end end Etc.send(type) do |object| if integer and object.send(idmethod) == id return object.send(field) elsif object.name == id return object.send(field) end end # Apparently the group/passwd methods need to get reset; if we skip # this call, then new users aren't found. case type when :passwd; Etc.send(:endpwent) when :group; Etc.send(:endgrent) end nil end # Determine what the field name is for users and groups. def idfield(space) case space.intern when :gr, :group; :gid when :pw, :user, :passwd; :uid else raise ArgumentError, _("Can only handle users and groups") end end # Determine what the method is to get users and groups by id def methodbyid(space) case space.intern when :gr, :group; :getgrgid when :pw, :user, :passwd; :getpwuid else raise ArgumentError, _("Can only handle users and groups") end end # Determine what the method is to get users and groups by name def methodbyname(space) case space.intern when :gr, :group; :getgrnam when :pw, :user, :passwd; :getpwnam else raise ArgumentError, _("Can only handle users and groups") end end # Get the GID def gid(group) get_posix_value(:group, :gid, group) end # Get the UID def uid(user) get_posix_value(:passwd, :uid, user) end private # Get the specified id_field of a given field (user or group), # whether an ID name is provided def get_posix_value(location, id_field, field) begin field = Integer(field) rescue ArgumentError # pass end if field.is_a?(Integer) name = get_posix_field(location, :name, field) return nil unless name id = get_posix_field(location, id_field, name) check_value = id else id = get_posix_field(location, id_field, field) return nil unless id name = get_posix_field(location, :name, id) check_value = name end if check_value != field check_value_id = get_posix_field(location, id_field, check_value) if check_value if id == check_value_id Puppet.debug("Multiple entries found for resource: '#{location}' with #{id_field}: #{id}") id else Puppet.debug("The value retrieved: '#{check_value}' is different than the required state: '#{field}', searching in all entries") search_posix_field(location, id_field, field) end else id 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/colors.rb
lib/puppet/util/colors.rb
# frozen_string_literal: true require_relative '../../puppet/util/platform' module Puppet::Util::Colors BLACK = { :console => "\e[0;30m", :html => "color: #FFA0A0" } RED = { :console => "\e[0;31m", :html => "color: #FFA0A0" } GREEN = { :console => "\e[0;32m", :html => "color: #00CD00" } YELLOW = { :console => "\e[0;33m", :html => "color: #FFFF60" } BLUE = { :console => "\e[0;34m", :html => "color: #80A0FF" } MAGENTA = { :console => "\e[0;35m", :html => "color: #FFA500" } CYAN = { :console => "\e[0;36m", :html => "color: #40FFFF" } WHITE = { :console => "\e[0;37m", :html => "color: #FFFFFF" } HBLACK = { :console => "\e[1;30m", :html => "color: #FFA0A0" } HRED = { :console => "\e[1;31m", :html => "color: #FFA0A0" } HGREEN = { :console => "\e[1;32m", :html => "color: #00CD00" } HYELLOW = { :console => "\e[1;33m", :html => "color: #FFFF60" } HBLUE = { :console => "\e[1;34m", :html => "color: #80A0FF" } HMAGENTA = { :console => "\e[1;35m", :html => "color: #FFA500" } HCYAN = { :console => "\e[1;36m", :html => "color: #40FFFF" } HWHITE = { :console => "\e[1;37m", :html => "color: #FFFFFF" } BG_RED = { :console => "\e[0;41m", :html => "background: #FFA0A0" } BG_GREEN = { :console => "\e[0;42m", :html => "background: #00CD00" } BG_YELLOW = { :console => "\e[0;43m", :html => "background: #FFFF60" } BG_BLUE = { :console => "\e[0;44m", :html => "background: #80A0FF" } BG_MAGENTA = { :console => "\e[0;45m", :html => "background: #FFA500" } BG_CYAN = { :console => "\e[0;46m", :html => "background: #40FFFF" } BG_WHITE = { :console => "\e[0;47m", :html => "background: #FFFFFF" } BG_HRED = { :console => "\e[1;41m", :html => "background: #FFA0A0" } BG_HGREEN = { :console => "\e[1;42m", :html => "background: #00CD00" } BG_HYELLOW = { :console => "\e[1;43m", :html => "background: #FFFF60" } BG_HBLUE = { :console => "\e[1;44m", :html => "background: #80A0FF" } BG_HMAGENTA = { :console => "\e[1;45m", :html => "background: #FFA500" } BG_HCYAN = { :console => "\e[1;46m", :html => "background: #40FFFF" } BG_HWHITE = { :console => "\e[1;47m", :html => "background: #FFFFFF" } RESET = { :console => "\e[0m", :html => "" } Colormap = { :debug => WHITE, :info => GREEN, :notice => CYAN, :warning => YELLOW, :err => HMAGENTA, :alert => RED, :emerg => HRED, :crit => HRED, :black => BLACK, :red => RED, :green => GREEN, :yellow => YELLOW, :blue => BLUE, :magenta => MAGENTA, :cyan => CYAN, :white => WHITE, :hblack => HBLACK, :hred => HRED, :hgreen => HGREEN, :hyellow => HYELLOW, :hblue => HBLUE, :hmagenta => HMAGENTA, :hcyan => HCYAN, :hwhite => HWHITE, :bg_red => BG_RED, :bg_green => BG_GREEN, :bg_yellow => BG_YELLOW, :bg_blue => BG_BLUE, :bg_magenta => BG_MAGENTA, :bg_cyan => BG_CYAN, :bg_white => BG_WHITE, :bg_hred => BG_HRED, :bg_hgreen => BG_HGREEN, :bg_hyellow => BG_HYELLOW, :bg_hblue => BG_HBLUE, :bg_hmagenta => BG_HMAGENTA, :bg_hcyan => BG_HCYAN, :bg_hwhite => BG_HWHITE, :reset => { :console => "\e[m", :html => "" } } def colorize(color, str) case Puppet[:color] when true, :ansi, "ansi", "yes" console_color(color, str) when :html, "html" html_color(color, str) else str end end def console_color(color, str) Colormap[color][:console] + str.gsub(RESET[:console], Colormap[color][:console]) + RESET[:console] end def html_color(color, str) span = '<span style="%s">' % Colormap[color][:html] "#{span}%s</span>" % str.gsub(%r{<span .*?</span>}, "</span>\\0#{span}") 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/watched_file.rb
lib/puppet/util/watched_file.rb
# frozen_string_literal: true require_relative '../../puppet/util/watcher' # Monitor a given file for changes on a periodic interval. Changes are detected # by looking for a change in the file ctime. class Puppet::Util::WatchedFile # @!attribute [r] filename # @return [String] The fully qualified path to the file. attr_reader :filename # @param filename [String] The fully qualified path to the file. # @param timer [Puppet::Util::Watcher::Timer] The polling interval for checking for file # changes. Setting the timeout to a negative value will treat the file as # always changed. Defaults to `Puppet[:filetimeout]` def initialize(filename, timer = Puppet::Util::Watcher::Timer.new(Puppet[:filetimeout])) @filename = filename @timer = timer @info = Puppet::Util::Watcher::PeriodicWatcher.new( Puppet::Util::Watcher::Common.file_ctime_change_watcher(@filename), timer ) end # @return [true, false] If the file has changed since it was last checked. def changed? @info.changed? end # Allow this to be used as the name of the file being watched in various # other methods (such as Puppet::FileSystem.exist?) def to_str @filename end def to_s "<WatchedFile: filename = #{@filename}, timeout = #{@timer.timeout}>" 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/retry_action.rb
lib/puppet/util/retry_action.rb
# frozen_string_literal: true module Puppet::Util::RetryAction class RetryException < Exception; end # rubocop:disable Lint/InheritException class RetryException::NoBlockGiven < RetryException; end class RetryException::NoRetriesGiven < RetryException; end class RetryException::RetriesExceeded < RetryException; end # Execute the supplied block retrying with exponential backoff. # # @param [Hash] options the retry options # @option options [Integer] :retries Maximum number of times to retry. # @option options [Array<Exception>] :retry_exceptions ([StandardError]) Optional array of exceptions that are allowed to be retried. # @yield The block to be executed. def self.retry_action(options = {}) # Retry actions for a specified amount of time. This method will allow the final # retry to complete even if that extends beyond the timeout period. unless block_given? raise RetryException::NoBlockGiven end retries = options[:retries] if retries.nil? raise RetryException::NoRetriesGiven end retry_exceptions = options[:retry_exceptions] || [StandardError] failures = 0 begin yield rescue *retry_exceptions => e if failures >= retries raise RetryException::RetriesExceeded, _("%{retries} exceeded") % { retries: retries }, e.backtrace end Puppet.info(_("Caught exception %{klass}:%{error} retrying") % { klass: e.class, error: e }) failures += 1 # Increase the amount of time that we sleep after every # failed retry attempt. sleep(((2**failures) - 1) * 0.1) retry 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/backups.rb
lib/puppet/util/backups.rb
# frozen_string_literal: true require 'find' require 'fileutils' module Puppet::Util::Backups # Deal with backups. def perform_backup(file = nil) # if they specifically don't want a backup, then just say # we're good return true unless self[:backup] # let the path be specified file ||= self[:path] return true unless Puppet::FileSystem.exist?(file) (bucket ? perform_backup_with_bucket(file) : perform_backup_with_backuplocal(file, self[:backup])) end private def perform_backup_with_bucket(fileobj) file = fileobj.instance_of?(String) ? fileobj : fileobj.name case Puppet::FileSystem.lstat(file).ftype when "directory" # we don't need to backup directories when recurse is on return true if self[:recurse] info _("Recursively backing up to filebucket") Find.find(self[:path]) { |f| backup_file_with_filebucket(f) if File.file?(f) } when "file"; backup_file_with_filebucket(file) when "link"; # do nothing end true end def perform_backup_with_backuplocal(fileobj, backup) file = fileobj.instance_of?(String) ? fileobj : fileobj.name newfile = file + backup remove_backup(newfile) begin bfile = file + backup # N.B. cp_r works on both files and directories FileUtils.cp_r(file, bfile, :preserve => true) true rescue => detail # since they said they want a backup, let's error out # if we couldn't make one self.fail Puppet::Error, _("Could not back %{file} up: %{message}") % { file: file, message: detail.message }, detail end end def remove_backup(newfile) if instance_of?(Puppet::Type::File) and self[:links] != :follow method = :lstat else method = :stat end begin stat = Puppet::FileSystem.send(method, newfile) rescue Errno::ENOENT return end if stat.ftype == "directory" raise Puppet::Error, _("Will not remove directory backup %{newfile}; use a filebucket") % { newfile: newfile } end info _("Removing old backup of type %{file_type}") % { file_type: stat.ftype } begin Puppet::FileSystem.unlink(newfile) rescue => detail message = _("Could not remove old backup: %{detail}") % { detail: detail } log_exception(detail, message) self.fail Puppet::Error, message, detail end end def backup_file_with_filebucket(f) sum = bucket.backup(f) info _("Filebucketed %{f} to %{filebucket} with sum %{sum}") % { f: f, filebucket: bucket.name, sum: sum } sum 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.rb
lib/puppet/util/windows.rb
# frozen_string_literal: true require_relative '../../puppet/util/platform' module Puppet::Util::Windows module ADSI class ADSIObject; end class User < ADSIObject; end class UserProfile; end class Group < ADSIObject; end end module File; end module Registry end module Service DEFAULT_TIMEOUT = 30 end module SID class Principal; end end class EventLog; end if Puppet::Util::Platform.windows? # Note: Setting codepage here globally ensures all strings returned via # WIN32OLE (Ruby's late-bound COM support) are encoded in Encoding::UTF_8 # # Also, this does not modify the value of WIN32OLE.locale - which defaults # to 2048 (at least on US English Windows) and is not listed in the MS # locales table, here: https://msdn.microsoft.com/en-us/library/ms912047(v=winembedded.10).aspx require 'win32ole'; WIN32OLE.codepage = WIN32OLE::CP_UTF8 # these reference platform specific gems require_relative '../../puppet/ffi/windows' require_relative 'windows/string' require_relative 'windows/error' require_relative 'windows/com' require_relative 'windows/sid' require_relative 'windows/principal' require_relative 'windows/file' require_relative 'windows/security' require_relative 'windows/user' require_relative 'windows/process' require_relative 'windows/root_certs' require_relative 'windows/access_control_entry' require_relative 'windows/access_control_list' require_relative 'windows/security_descriptor' require_relative 'windows/adsi' require_relative 'windows/registry' require_relative 'windows/eventlog' require_relative 'windows/service' require_relative 'windows/monkey_patches/process' 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/character_encoding.rb
lib/puppet/util/character_encoding.rb
# frozen_string_literal: true # A module to centralize heuristics/practices for managing character encoding in Puppet module Puppet::Util::CharacterEncoding class << self # Given a string, attempts to convert a copy of the string to UTF-8. Conversion uses # encode - the string's internal byte representation is modifed to UTF-8. # # This method is intended for situations where we generally trust that the # string's bytes are a faithful representation of the current encoding # associated with it, and can use it as a starting point for transcoding # (conversion) to UTF-8. # # @api public # @param [String] string a string to transcode # @return [String] copy of the original string, in UTF-8 if transcodable def convert_to_utf_8(string) original_encoding = string.encoding string_copy = string.dup begin if original_encoding == Encoding::UTF_8 unless string_copy.valid_encoding? Puppet.debug { _("%{value} is already labeled as UTF-8 but this encoding is invalid. It cannot be transcoded by Puppet.") % { value: string.dump } } end # String is already valid UTF-8 - noop string_copy else # If the string comes to us as BINARY encoded, we don't know what it # started as. However, to encode! we need a starting place, and our # best guess is whatever the system currently is (default_external). # So set external_encoding to default_external before we try to # transcode to UTF-8. string_copy.force_encoding(Encoding.default_external) if original_encoding == Encoding::BINARY string_copy.encode(Encoding::UTF_8) end rescue EncodingError => detail # Set the encoding on our copy back to its original if we modified it string_copy.force_encoding(original_encoding) if original_encoding == Encoding::BINARY # Catch both our own self-determined failure to transcode as well as any # error on ruby's part, ie Encoding::UndefinedConversionError on a # failure to encode!. Puppet.debug { _("%{error}: %{value} cannot be transcoded by Puppet.") % { error: detail.inspect, value: string.dump } } string_copy end end # Given a string, tests if that string's bytes represent valid UTF-8, and if # so return a copy of the string with external encoding set to UTF-8. Does # not modify the byte representation of the string. If the string does not # represent valid UTF-8, does not set the external encoding. # # This method is intended for situations where we do not believe that the # encoding associated with a string is an accurate reflection of its actual # bytes, i.e., effectively when we believe Ruby is incorrect in its # assertion of the encoding of the string. # # @api public # @param [String] string to set external encoding (re-label) to utf-8 # @return [String] a copy of string with external encoding set to utf-8, or # a copy of the original string if override would result in invalid encoding. def override_encoding_to_utf_8(string) string_copy = string.dup original_encoding = string_copy.encoding return string_copy if original_encoding == Encoding::UTF_8 if string_copy.force_encoding(Encoding::UTF_8).valid_encoding? string_copy else Puppet.debug { _("%{value} is not valid UTF-8 and result of overriding encoding would be invalid.") % { value: string.dump } } # Set copy back to its original encoding before returning string_copy.force_encoding(original_encoding) 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/metric.rb
lib/puppet/util/metric.rb
# frozen_string_literal: true # included so we can test object types require_relative '../../puppet' require_relative '../../puppet/network/format_support' # A class for handling metrics. This is currently ridiculously hackish. class Puppet::Util::Metric include Puppet::Util::PsychSupport include Puppet::Network::FormatSupport attr_accessor :type, :name, :value, :label attr_writer :values def self.from_data_hash(data) metric = allocate metric.initialize_from_hash(data) metric end def initialize_from_hash(data) @name = data['name'] @label = data['label'] || self.class.labelize(@name) @values = data['values'] end def to_data_hash { 'name' => @name, 'label' => @label, 'values' => @values } end # Return a specific value def [](name) value = @values.find { |v| v[0] == name } if value value[2] else 0 end end def initialize(name, label = nil) @name = name.to_s @label = label || self.class.labelize(name) @values = [] end def newvalue(name, value, label = nil) raise ArgumentError, "metric name #{name.inspect} is not a string" unless name.is_a? String label ||= self.class.labelize(name) @values.push [name, label, value] end def values @values.sort_by { |a| a[1] } end # Convert a name into a label. def self.labelize(name) name.to_s.capitalize.tr("_", " ") 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/constant_inflector.rb
lib/puppet/util/constant_inflector.rb
# frozen_string_literal: true # Created on 2008-02-12 # Copyright Luke Kanies # NOTE: I think it might be worth considering moving these methods directly into Puppet::Util. # A common module for converting between constants and # file names. module Puppet module Util module ConstantInflector def file2constant(file) file.split("/").collect(&:capitalize).join("::").gsub(/_+(.)/) { |_term| ::Regexp.last_match(1).capitalize } end module_function :file2constant def constant2file(constant) constant.to_s.gsub(/([a-z])([A-Z])/) { |_term| ::Regexp.last_match(1) + "_#{::Regexp.last_match(2)}" }.gsub("::", "/").downcase end module_function :constant2file 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/checksums.rb
lib/puppet/util/checksums.rb
# frozen_string_literal: true require 'digest/md5' require 'digest/sha1' require 'time' # A stand-alone module for calculating checksums # in a generic way. module Puppet::Util::Checksums module_function # If you modify this, update puppet/type/file/checksum.rb too KNOWN_CHECKSUMS = [ :sha256, :sha256lite, :md5, :md5lite, :sha1, :sha1lite, :sha512, :sha384, :sha224, :mtime, :ctime, :none ].freeze # It's not a good idea to use some of these in some contexts: for example, I # wouldn't try bucketing a file using the :none checksum type. def known_checksum_types KNOWN_CHECKSUMS end def valid_checksum?(type, value) !!send("#{type}?", value) rescue NoMethodError false end class FakeChecksum def <<(*args) self end end # Is the provided string a checksum? def checksum?(string) # 'sha256lite'.length == 10 string =~ /^\{(\w{3,10})\}\S+/ end # Strip the checksum type from an existing checksum def sumdata(checksum) checksum =~ /^\{(\w+)\}(.+)/ ? ::Regexp.last_match(2) : nil end # Strip the checksum type from an existing checksum def sumtype(checksum) checksum =~ /^\{(\w+)\}/ ? ::Regexp.last_match(1) : nil end # Calculate a checksum using Digest::SHA256. def sha256(content) require 'digest/sha2' Digest::SHA256.hexdigest(content) end def sha256?(string) string =~ /^\h{64}$/ end def sha256_file(filename, lite = false) require 'digest/sha2' digest = Digest::SHA256.new checksum_file(digest, filename, lite) end def sha256_stream(lite = false, &block) require 'digest/sha2' digest = Digest::SHA256.new checksum_stream(digest, block, lite) end def sha256_hex_length 64 end def sha256lite(content) sha256(content[0..511]) end def sha256lite?(string) sha256?(string) end def sha256lite_file(filename) sha256_file(filename, true) end def sha256lite_stream(&block) sha256_stream(true, &block) end def sha256lite_hex_length sha256_hex_length end # Calculate a checksum using Digest::SHA384. def sha384(content) require 'digest/sha2' Digest::SHA384.hexdigest(content) end def sha384?(string) string =~ /^\h{96}$/ end def sha384_file(filename, lite = false) require 'digest/sha2' digest = Digest::SHA384.new checksum_file(digest, filename, lite) end def sha384_stream(lite = false, &block) require 'digest/sha2' digest = Digest::SHA384.new checksum_stream(digest, block, lite) end def sha384_hex_length 96 end # Calculate a checksum using Digest::SHA512. def sha512(content) require 'digest/sha2' Digest::SHA512.hexdigest(content) end def sha512?(string) string =~ /^\h{128}$/ end def sha512_file(filename, lite = false) require 'digest/sha2' digest = Digest::SHA512.new checksum_file(digest, filename, lite) end def sha512_stream(lite = false, &block) require 'digest/sha2' digest = Digest::SHA512.new checksum_stream(digest, block, lite) end def sha512_hex_length 128 end # Calculate a checksum using Digest::SHA224. def sha224(content) require_relative '../../puppet/ssl/openssl_loader' OpenSSL::Digest.new('SHA224').hexdigest(content) end def sha224?(string) string =~ /^\h{56}$/ end def sha224_file(filename, lite = false) require_relative '../../puppet/ssl/openssl_loader' digest = OpenSSL::Digest.new('SHA224') checksum_file(digest, filename, lite) end def sha224_stream(lite = false, &block) require_relative '../../puppet/ssl/openssl_loader' digest = OpenSSL::Digest.new('SHA224') checksum_stream(digest, block, lite) end def sha224_hex_length 56 end # Calculate a checksum using Digest::MD5. def md5(content) Digest::MD5.hexdigest(content) end def md5?(string) string =~ /^\h{32}$/ end # Calculate a checksum of a file's content using Digest::MD5. def md5_file(filename, lite = false) digest = Digest::MD5.new checksum_file(digest, filename, lite) end def md5_stream(lite = false, &block) digest = Digest::MD5.new checksum_stream(digest, block, lite) end def md5_hex_length 32 end # Calculate a checksum of the first 500 chars of the content using Digest::MD5. def md5lite(content) md5(content[0..511]) end def md5lite?(string) md5?(string) end # Calculate a checksum of the first 500 chars of a file's content using Digest::MD5. def md5lite_file(filename) md5_file(filename, true) end def md5lite_stream(&block) md5_stream(true, &block) end def md5lite_hex_length md5_hex_length end def mtime(content) "" end def mtime?(string) return true if string.is_a? Time !!DateTime.parse(string) rescue false end # Return the :mtime timestamp of a file. def mtime_file(filename) Puppet::FileSystem.stat(filename).mtime end # by definition this doesn't exist # but we still need to execute the block given def mtime_stream(&block) noop_digest = FakeChecksum.new yield noop_digest nil end # Calculate a checksum using Digest::SHA1. def sha1(content) Digest::SHA1.hexdigest(content) end def sha1?(string) string =~ /^\h{40}$/ end # Calculate a checksum of a file's content using Digest::SHA1. def sha1_file(filename, lite = false) digest = Digest::SHA1.new checksum_file(digest, filename, lite) end def sha1_stream(lite = false, &block) digest = Digest::SHA1.new checksum_stream(digest, block, lite) end def sha1_hex_length 40 end # Calculate a checksum of the first 500 chars of the content using Digest::SHA1. def sha1lite(content) sha1(content[0..511]) end def sha1lite?(string) sha1?(string) end # Calculate a checksum of the first 500 chars of a file's content using Digest::SHA1. def sha1lite_file(filename) sha1_file(filename, true) end def sha1lite_stream(&block) sha1_stream(true, &block) end def sha1lite_hex_length sha1_hex_length end def ctime(content) "" end def ctime?(string) return true if string.is_a? Time !!DateTime.parse(string) rescue false end # Return the :ctime of a file. def ctime_file(filename) Puppet::FileSystem.stat(filename).ctime end def ctime_stream(&block) mtime_stream(&block) end def none(content) "" end def none?(string) string.empty? end # Return a "no checksum" def none_file(filename) "" end def none_stream noop_digest = FakeChecksum.new yield noop_digest "" end class DigestLite def initialize(digest, lite = false) @digest = digest @lite = lite @bytes = 0 end # Provide an interface for digests. If lite, only digest the first 512 bytes def <<(str) if @lite if @bytes < 512 buf = str[0, 512 - @bytes] @digest << buf @bytes += buf.length end else @digest << str end end end # Perform an incremental checksum on a file. def checksum_file(digest, filename, lite = false) buffer = lite ? 512 : 4096 File.open(filename, 'rb') do |file| while content = file.read(buffer) # rubocop:disable Lint/AssignmentInCondition digest << content break if lite end end digest.hexdigest end def checksum_stream(digest, block, lite = false) block.call(DigestLite.new(digest, lite)) digest.hexdigest 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/profiler/logging.rb
lib/puppet/util/profiler/logging.rb
# frozen_string_literal: true class Puppet::Util::Profiler::Logging def initialize(logger, identifier) @logger = logger @identifier = identifier @sequence = Sequence.new end def start(description, metric_id) @sequence.next @sequence.down do_start(description, metric_id) end def finish(context, description, metric_id) profile_explanation = do_finish(context, description, metric_id)[:msg] @sequence.up @logger.call("PROFILE [#{@identifier}] #{@sequence} #{description}: #{profile_explanation}") end def shutdown # nothing to do end class Sequence INITIAL = 0 SEPARATOR = '.' def initialize @elements = [INITIAL] end def next @elements[-1] += 1 end def down @elements << INITIAL end def up @elements.pop end def to_s @elements.join(SEPARATOR) 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/profiler/object_counts.rb
lib/puppet/util/profiler/object_counts.rb
# frozen_string_literal: true require_relative '../../../puppet/util/profiler/logging' class Puppet::Util::Profiler::ObjectCounts < Puppet::Util::Profiler::Logging def start ObjectSpace.count_objects end def finish(before) after = ObjectSpace.count_objects diff = before.collect do |type, count| [type, after[type] - count] end diff.sort.collect { |pair| pair.join(': ') }.join(', ') 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/profiler/around_profiler.rb
lib/puppet/util/profiler/around_profiler.rb
# frozen_string_literal: true # A Profiler that can be used to wrap around blocks of code. It is configured # with other profilers and controls them to start before the block is executed # and finish after the block is executed. # # @api private class Puppet::Util::Profiler::AroundProfiler def initialize @profilers = [] end # Reset the profiling system to the original state # # @api private def clear @profilers = [] end # Retrieve the current list of profilers # # @api private def current @profilers end # @param profiler [#profile] A profiler for the current thread # @api private def add_profiler(profiler) @profilers << profiler profiler end # @param profiler [#profile] A profiler to remove from the current thread # @api private def remove_profiler(profiler) @profilers.delete(profiler) end # Profile a block of code and log the time it took to execute. # # This outputs logs entries to the Puppet masters logging destination # providing the time it took, a message describing the profiled code # and a leaf location marking where the profile method was called # in the profiled hierarchy. # # @param message [String] A description of the profiled event # @param metric_id [Array] A list of strings making up the ID of a metric to profile # @param block [Block] The segment of code to profile # @api private def profile(message, metric_id) retval = nil contexts = {} @profilers.each do |profiler| contexts[profiler] = profiler.start(message, metric_id) end begin retval = yield ensure @profilers.each do |profiler| profiler.finish(contexts[profiler], message, metric_id) end end retval 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/profiler/wall_clock.rb
lib/puppet/util/profiler/wall_clock.rb
# frozen_string_literal: true require_relative '../../../puppet/util/profiler/logging' # A profiler implementation that measures the number of seconds a segment of # code takes to execute and provides a callback with a string representation of # the profiling information. # # @api private class Puppet::Util::Profiler::WallClock < Puppet::Util::Profiler::Logging def do_start(description, metric_id) Timer.new end def do_finish(context, description, metric_id) { :time => context.stop, :msg => _("took %{context} seconds") % { context: context } } end class Timer FOUR_DECIMAL_DIGITS = '%0.4f' def initialize @start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) end def stop @time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) - @start @time end def to_s format(FOUR_DECIMAL_DIGITS, @time) 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/profiler/aggregate.rb
lib/puppet/util/profiler/aggregate.rb
# frozen_string_literal: true require_relative '../../../puppet/util/profiler' require_relative '../../../puppet/util/profiler/wall_clock' class Puppet::Util::Profiler::Aggregate < Puppet::Util::Profiler::WallClock def initialize(logger, identifier) super(logger, identifier) @metrics_hash = Metric.new end def shutdown super @logger.call("AGGREGATE PROFILING RESULTS:") @logger.call("----------------------------") print_metrics(@metrics_hash, "") @logger.call("----------------------------") end def do_finish(context, description, metric_id) result = super(context, description, metric_id) update_metric(@metrics_hash, metric_id, result[:time]) result end def update_metric(metrics_hash, metric_id, time) first, *rest = *metric_id if first m = metrics_hash[first] m.increment m.add_time(time) if rest.count > 0 update_metric(m, rest, time) end end end def values @metrics_hash end def print_metrics(metrics_hash, prefix) metrics_hash.sort_by { |_k, v| v.time }.reverse_each do |k, v| @logger.call("#{prefix}#{k}: #{v.time} s (#{v.count} calls)") print_metrics(metrics_hash[k], "#{prefix}#{k} -> ") end end class Metric < Hash def initialize super @count = 0 @time = 0 end attr_reader :count, :time def [](key) unless has_key?(key) self[key] = Metric.new end super(key) end def increment @count += 1 end def add_time(time) @time += time end end class Timer def initialize @start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) end def stop Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) - @start 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/at_fork/solaris.rb
lib/puppet/util/at_fork/solaris.rb
# frozen_string_literal: true require_relative '../../../puppet' require 'fiddle' # Early versions of Fiddle relied on the deprecated DL module and used # classes defined in the namespace of that module instead of classes defined # in the Fiddle's own namespace e.g. DL::Handle instead of Fiddle::Handle. # We don't support those. raise LoadError, _('The loaded Fiddle version is not supported.') unless defined?(Fiddle::Handle) # Solaris implementation of the Puppet::Util::AtFork handler. # The callbacks defined in this implementation ensure the forked process runs # in a different contract than the parent process. This is necessary in order # for the child process to be able to survive termination of the contract its # parent process runs in. This is needed notably for an agent run executed # by a puppet agent service to be able to restart that service without being # killed in the process as a consequence of running in the same contract as # the service, as all processes in the contract are killed when the contract # is terminated during the service restart. class Puppet::Util::AtFork::Solaris private { 'libcontract.so.1' => [ # function name, return value type, parameter types, ... [:ct_ctl_abandon, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_tmpl_activate, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_tmpl_clear, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_tmpl_set_informative, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_tmpl_set_critical, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_pr_tmpl_set_param, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_pr_tmpl_set_fatal, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT], [:ct_status_read, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], [:ct_status_get_id, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP], [:ct_status_free, Fiddle::TYPE_VOID, Fiddle::TYPE_VOIDP] ], }.each do |library, functions| libhandle = Fiddle::Handle.new(library) functions.each do |f| define_method f[0], Fiddle::Function.new(libhandle[f[0].to_s], f[2..], f[1]).method(:call).to_proc end end CTFS_PR_ROOT = File.join('', %w[system contract process]) CTFS_PR_TEMPLATE = File.join(CTFS_PR_ROOT, 'template') CTFS_PR_LATEST = File.join(CTFS_PR_ROOT, 'latest') CT_PR_PGRPONLY = 0x4 CT_PR_EV_HWERR = 0x20 CTD_COMMON = 0 def raise_if_error(&block) unless (e = yield) == 0 e = SystemCallError.new(nil, e) raise e, e.message, caller end end def activate_new_contract_template tmpl = File.new(CTFS_PR_TEMPLATE, File::RDWR) begin tmpl_fd = tmpl.fileno raise_if_error { ct_pr_tmpl_set_param(tmpl_fd, CT_PR_PGRPONLY) } raise_if_error { ct_pr_tmpl_set_fatal(tmpl_fd, CT_PR_EV_HWERR) } raise_if_error { ct_tmpl_set_critical(tmpl_fd, 0) } raise_if_error { ct_tmpl_set_informative(tmpl_fd, CT_PR_EV_HWERR) } raise_if_error { ct_tmpl_activate(tmpl_fd) } rescue tmpl.close raise end @tmpl = tmpl rescue => detail Puppet.log_exception(detail, _('Failed to activate a new process contract template')) end def deactivate_contract_template(parent) return if @tmpl.nil? tmpl = @tmpl @tmpl = nil begin raise_if_error { ct_tmpl_clear(tmpl.fileno) } rescue => detail msg = if parent _('Failed to deactivate process contract template in the parent process') else _('Failed to deactivate process contract template in the child process') end Puppet.log_exception(detail, msg) exit(1) ensure tmpl.close end end def get_latest_child_contract_id stat = File.new(CTFS_PR_LATEST, File::RDONLY) begin stathdl = Fiddle::Pointer.new(0) raise_if_error { ct_status_read(stat.fileno, CTD_COMMON, stathdl.ref) } ctid = ct_status_get_id(stathdl) ct_status_free(stathdl) ensure stat.close end ctid rescue => detail Puppet.log_exception(detail, _('Failed to get latest child process contract id')) nil end def abandon_latest_child_contract ctid = get_latest_child_contract_id return if ctid.nil? begin ctl = File.new(File.join(CTFS_PR_ROOT, ctid.to_s, 'ctl'), File::WRONLY) begin raise_if_error { ct_ctl_abandon(ctl.fileno) } ensure ctl.close end rescue => detail Puppet.log_exception(detail, _('Failed to abandon a child process contract')) end end public def prepare activate_new_contract_template end def parent deactivate_contract_template(true) abandon_latest_child_contract end def child deactivate_contract_template(false) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/at_fork/noop.rb
lib/puppet/util/at_fork/noop.rb
# frozen_string_literal: true # A noop implementation of the Puppet::Util::AtFork handler class Puppet::Util::AtFork::Noop class << self def new # no need to instantiate every time, return the class object itself self end def prepare end def parent end def child 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/command_line/trollop.rb
lib/puppet/util/command_line/trollop.rb
# frozen_string_literal: true ## lib/trollop.rb -- trollop command-line processing library ## Author:: William Morgan (mailto: wmorgan-trollop@masanjin.net) ## Copyright:: Copyright 2007 William Morgan ## License:: the same terms as ruby itself ## ## 2012-03: small changes made by cprice (chris@puppetlabs.com); ## patch submitted for upstream consideration: ## https://gitorious.org/trollop/mainline/merge_requests/9 ## 2012-08: namespace changes made by Jeff McCune (jeff@puppetlabs.com) ## moved Trollop into Puppet::Util::CommandLine to prevent monkey ## patching the upstream trollop library if also loaded. require 'date' module Puppet module Util class CommandLine module Trollop VERSION = "1.16.2" ## Thrown by Parser in the event of a commandline error. Not needed if ## you're using the Trollop::options entry. class CommandlineError < StandardError; end ## Thrown by Parser if the user passes in '-h' or '--help'. Handled ## automatically by Trollop#options. class HelpNeeded < StandardError; end ## Thrown by Parser if the user passes in '-h' or '--version'. Handled ## automatically by Trollop#options. class VersionNeeded < StandardError; end ## Regex for floating point numbers FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?\d+)?$/ ## Regex for parameters PARAM_RE = /^-(-|\.$|[^\d.])/ ## The commandline parser. In typical usage, the methods in this class ## will be handled internally by Trollop::options. In this case, only the ## #opt, #banner and #version, #depends, and #conflicts methods will ## typically be called. ## ## If you want to instantiate this class yourself (for more complicated ## argument-parsing logic), call #parse to actually produce the output hash, ## and consider calling it from within ## Trollop::with_standard_exception_handling. class Parser ## The set of values that indicate a flag option when passed as the ## +:type+ parameter of #opt. FLAG_TYPES = [:flag, :bool, :boolean] ## The set of values that indicate a single-parameter (normal) option when ## passed as the +:type+ parameter of #opt. ## ## A value of +io+ corresponds to a readable IO resource, including ## a filename, URI, or the strings 'stdin' or '-'. SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io, :date] ## The set of values that indicate a multiple-parameter option (i.e., that ## takes multiple space-separated values on the commandline) when passed as ## the +:type+ parameter of #opt. MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios, :dates] ## The complete set of legal values for the +:type+ parameter of #opt. TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES INVALID_SHORT_ARG_REGEX = /[\d-]/ # :nodoc: ## The values from the commandline that were not interpreted by #parse. attr_reader :leftovers ## The complete configuration hashes for each option. (Mainly useful ## for testing.) attr_reader :specs ## A flag that determines whether or not to attempt to automatically generate "short" options if they are not ## explicitly specified. attr_accessor :create_default_short_options ## A flag that determines whether or not to raise an error if the parser is passed one or more ## options that were not registered ahead of time. If 'true', then the parser will simply ## ignore options that it does not recognize. attr_accessor :ignore_invalid_options ## A flag indicating whether or not the parser should attempt to handle "--help" and ## "--version" specially. If 'false', it will treat them just like any other option. attr_accessor :handle_help_and_version ## Initializes the parser, and instance-evaluates any block given. def initialize *a, &b @version = nil @leftovers = [] @specs = {} @long = {} @short = {} @order = [] @constraints = [] @stop_words = [] @stop_on_unknown = false # instance_eval(&b) if b # can't take arguments cloaker(&b).bind_call(self, *a) if b end ## Define an option. +name+ is the option name, a unique identifier ## for the option that you will use internally, which should be a ## symbol or a string. +desc+ is a string description which will be ## displayed in help messages. ## ## Takes the following optional arguments: ## ## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s. ## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+. ## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given. ## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the commandline the value will be +false+. ## [+:required+] If set to +true+, the argument must be provided on the commandline. ## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.) ## ## Note that there are two types of argument multiplicity: an argument ## can take multiple values, e.g. "--arg 1 2 3". An argument can also ## be allowed to occur multiple times, e.g. "--arg 1 --arg 2". ## ## Arguments that take multiple values should have a +:type+ parameter ## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+ ## value of an array of the correct type (e.g. [String]). The ## value of this argument will be an array of the parameters on the ## commandline. ## ## Arguments that can occur multiple times should be marked with ## +:multi+ => +true+. The value of this argument will also be an array. ## In contrast with regular non-multi options, if not specified on ## the commandline, the default value will be [], not nil. ## ## These two attributes can be combined (e.g. +:type+ => +:strings+, ## +:multi+ => +true+), in which case the value of the argument will be ## an array of arrays. ## ## There's one ambiguous case to be aware of: when +:multi+: is true and a ## +:default+ is set to an array (of something), it's ambiguous whether this ## is a multi-value argument as well as a multi-occurrence argument. ## In this case, Trollop assumes that it's not a multi-value argument. ## If you want a multi-value, multi-occurrence argument with a default ## value, you must specify +:type+ as well. def opt name, desc = "", opts = {} raise ArgumentError, _("you already have an argument named '%{name}'") % { name: name } if @specs.member? name ## fill in :type opts[:type] = # normalize case opts[:type] when :boolean, :bool; :flag when :integer; :int when :integers; :ints when :double; :float when :doubles; :floats when Class case opts[:type].name when 'TrueClass', 'FalseClass'; :flag when 'String'; :string when 'Integer'; :int when 'Float'; :float when 'IO'; :io when 'Date'; :date else raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type].class.name } end when nil; nil else raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type] } unless TYPES.include?(opts[:type]) opts[:type] end ## for options with :multi => true, an array default doesn't imply ## a multi-valued argument. for that you have to specify a :type ## as well. (this is how we disambiguate an ambiguous situation; ## see the docs for Parser#opt for details.) disambiguated_default = if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type] opts[:default].first else opts[:default] end type_from_default = case disambiguated_default when Integer; :int when Numeric; :float when TrueClass, FalseClass; :flag when String; :string when IO; :io when Date; :date when Array if opts[:default].empty? raise ArgumentError, _("multiple argument type cannot be deduced from an empty array for '%{value0}'") % { value0: opts[:default][0].class.name } end case opts[:default][0] # the first element determines the types when Integer; :ints when Numeric; :floats when String; :strings when IO; :ios when Date; :dates else raise ArgumentError, _("unsupported multiple argument type '%{value0}'") % { value0: opts[:default][0].class.name } end when nil; nil else raise ArgumentError, _("unsupported argument type '%{value0}'") % { value0: opts[:default].class.name } end raise ArgumentError, _(":type specification and default type don't match (default type is %{type_from_default})") % { type_from_default: type_from_default } if opts[:type] && type_from_default && opts[:type] != type_from_default opts[:type] = opts[:type] || type_from_default || :flag ## fill in :long opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.tr("_", "-") opts[:long] = case opts[:long] when /^--([^-].*)$/ ::Regexp.last_match(1) when /^[^-]/ opts[:long] else raise ArgumentError, _("invalid long option name %{name}") % { name: opts[:long].inspect } end raise ArgumentError, _("long option name %{value0} is already taken; please specify a (different) :long") % { value0: opts[:long].inspect } if @long[opts[:long]] ## fill in :short unless opts[:short] == :none opts[:short] = opts[:short].to_s if opts[:short] end opts[:short] = case opts[:short] when /^-(.)$/; ::Regexp.last_match(1) when nil, :none, /^.$/; opts[:short] else raise ArgumentError, _("invalid short option name '%{name}'") % { name: opts[:short].inspect } end if opts[:short] raise ArgumentError, _("short option name %{value0} is already taken; please specify a (different) :short") % { value0: opts[:short].inspect } if @short[opts[:short]] raise ArgumentError, _("a short option name can't be a number or a dash") if opts[:short] =~ INVALID_SHORT_ARG_REGEX end ## fill in :default for flags opts[:default] = false if opts[:type] == :flag && opts[:default].nil? ## autobox :default for :multi (multi-occurrence) arguments opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array) ## fill in :multi opts[:multi] ||= false opts[:desc] ||= desc @long[opts[:long]] = name @short[opts[:short]] = name if opts[:short] && opts[:short] != :none @specs[name] = opts @order << [:opt, name] end ## Sets the version string. If set, the user can request the version ## on the commandline. Should probably be of the form "<program name> ## <version number>". def version s = nil; @version = s if s; @version end ## Adds text to the help display. Can be interspersed with calls to ## #opt to build a multi-section help page. def banner s; @order << [:text, s] end alias :text :banner ## Marks two (or more!) options as requiring each other. Only handles ## undirected (i.e., mutual) dependencies. Directed dependencies are ## better modeled with Trollop::die. def depends *syms syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: sym } unless @specs[sym] } @constraints << [:depends, syms] end ## Marks two (or more!) options as conflicting. def conflicts *syms syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: sym } unless @specs[sym] } @constraints << [:conflicts, syms] end ## Defines a set of words which cause parsing to terminate when ## encountered, such that any options to the left of the word are ## parsed as usual, and options to the right of the word are left ## intact. ## ## A typical use case would be for subcommand support, where these ## would be set to the list of subcommands. A subsequent Trollop ## invocation would then be used to parse subcommand options, after ## shifting the subcommand off of ARGV. def stop_on *words @stop_words = [*words].flatten end ## Similar to #stop_on, but stops on any unknown word when encountered ## (unless it is a parameter for an argument). This is useful for ## cases where you don't know the set of subcommands ahead of time, ## i.e., without first parsing the global options. def stop_on_unknown @stop_on_unknown = true end ## Parses the commandline. Typically called by Trollop::options, ## but you can call it directly if you need more control. ## ## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions. def parse cmdline = ARGV vals = {} required = {} if handle_help_and_version unless @specs[:version] || @long["version"] opt :version, _("Print version and exit") if @version end opt :help, _("Show this message") unless @specs[:help] || @long["help"] end @specs.each do |sym, opts| required[sym] = true if opts[:required] vals[sym] = opts[:default] vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil end resolve_default_short_options if create_default_short_options ## resolve symbols given_args = {} @leftovers = each_arg cmdline do |arg, params| sym = case arg when /^-([^-])$/ @short[::Regexp.last_match(1)] when /^--no-([^-]\S*)$/ possible_match = @long["[no-]#{::Regexp.last_match(1)}"] if !possible_match partial_match = @long["[no-]#{::Regexp.last_match(1).tr('-', '_')}"] || @long["[no-]#{::Regexp.last_match(1).tr('_', '-')}"] if partial_match Puppet.deprecation_warning _("Partial argument match detected: correct argument is %{partial_match}, got %{arg}. Partial argument matching is deprecated and will be removed in a future release.") % { arg: arg, partial_match: partial_match } end partial_match else possible_match end when /^--([^-]\S*)$/ possible_match = @long[::Regexp.last_match(1)] || @long["[no-]#{::Regexp.last_match(1)}"] if !possible_match partial_match = @long[::Regexp.last_match(1).tr('-', '_')] || @long[::Regexp.last_match(1).tr('_', '-')] || @long["[no-]#{::Regexp.last_match(1).tr('-', '_')}"] || @long["[no-]#{::Regexp.last_match(1).tr('_', '-')}"] if partial_match Puppet.deprecation_warning _("Partial argument match detected: correct argument is %{partial_match}, got %{arg}. Partial argument matching is deprecated and will be removed in a future release.") % { arg: arg, partial_match: partial_match } end partial_match else possible_match end else raise CommandlineError, _("invalid argument syntax: '%{arg}'") % { arg: arg } end unless sym next 0 if ignore_invalid_options raise CommandlineError, _("unknown argument '%{arg}'") % { arg: arg } unless sym end if given_args.include?(sym) && !@specs[sym][:multi] raise CommandlineError, _("option '%{arg}' specified multiple times") % { arg: arg } end given_args[sym] ||= {} given_args[sym][:arg] = arg given_args[sym][:params] ||= [] # The block returns the number of parameters taken. num_params_taken = 0 unless params.nil? if SINGLE_ARG_TYPES.include?(@specs[sym][:type]) given_args[sym][:params] << params[0, 1] # take the first parameter num_params_taken = 1 elsif MULTI_ARG_TYPES.include?(@specs[sym][:type]) given_args[sym][:params] << params # take all the parameters num_params_taken = params.size end end num_params_taken end if handle_help_and_version ## check for version and help args raise VersionNeeded if given_args.include? :version raise HelpNeeded if given_args.include? :help end ## check constraint satisfaction @constraints.each do |type, syms| constraint_sym = syms.find { |sym| given_args[sym] } next unless constraint_sym case type when :depends syms.each { |sym| raise CommandlineError, _("--%{value0} requires --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } unless given_args.include? sym } when :conflicts syms.each { |sym| raise CommandlineError, _("--%{value0} conflicts with --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } if given_args.include?(sym) && (sym != constraint_sym) } end end required.each do |sym, _val| raise CommandlineError, _("option --%{opt} must be specified") % { opt: @specs[sym][:long] } unless given_args.include? sym end ## parse parameters given_args.each do |sym, given_data| arg = given_data[:arg] params = given_data[:params] opts = @specs[sym] raise CommandlineError, _("option '%{arg}' needs a parameter") % { arg: arg } if params.empty? && opts[:type] != :flag vals["#{sym}_given".intern] = true # mark argument as specified on the commandline case opts[:type] when :flag if arg =~ /^--no-/ and sym.to_s =~ /^--\[no-\]/ vals[sym] = opts[:default] else vals[sym] = !opts[:default] end when :int, :ints vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } } when :float, :floats vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } } when :string, :strings vals[sym] = params.map { |pg| pg.map(&:to_s) } when :io, :ios vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } } when :date, :dates vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } } end if SINGLE_ARG_TYPES.include?(opts[:type]) if opts[:multi] # multiple options, each with a single parameter vals[sym] = vals[sym].map { |p| p[0] } else # single parameter vals[sym] = vals[sym][0][0] end elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi] vals[sym] = vals[sym][0] # single option, with multiple parameters end # else: multiple options, with multiple parameters opts[:callback].call(vals[sym]) if opts.has_key?(:callback) end ## modify input in place with only those ## arguments we didn't process cmdline.clear @leftovers.each { |l| cmdline << l } ## allow openstruct-style accessors class << vals def method_missing(m, *args) self[m] || self[m.to_s] end end vals end def parse_date_parameter param, arg # :nodoc: begin time = Chronic.parse(param) rescue NameError # chronic is not available end time ? Date.new(time.year, time.month, time.day) : Date.parse(param) rescue ArgumentError => e raise CommandlineError, _("option '%{arg}' needs a date") % { arg: arg }, e.backtrace end ## Print the help message to +stream+. def educate stream = $stdout width # just calculate it now; otherwise we have to be careful not to # call this unless the cursor's at the beginning of a line. left = {} @specs.each do |name, spec| left[name] = "--#{spec[:long]}" + (spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") + case spec[:type] when :flag; "" when :int; " <i>" when :ints; " <i+>" when :string; " <s>" when :strings; " <s+>" when :float; " <f>" when :floats; " <f+>" when :io; " <filename/uri>" when :ios; " <filename/uri+>" when :date; " <date>" when :dates; " <date+>" end end leftcol_width = left.values.map(&:length).max || 0 rightcol_start = leftcol_width + 6 # spaces unless @order.size > 0 && @order.first.first == :text stream.puts "#{@version}\n" if @version stream.puts _("Options:") end @order.each do |what, opt| if what == :text stream.puts wrap(opt) next end spec = @specs[opt] stream.printf " %#{leftcol_width}s: ", left[opt] desc = spec[:desc] + begin default_s = case spec[:default] when $stdout; "<stdout>" when $stdin; "<stdin>" when $stderr; "<stderr>" when Array spec[:default].join(", ") else spec[:default].to_s end if spec[:default] if spec[:desc] =~ /\.$/ _(" (Default: %{default_s})") % { default_s: default_s } else _(" (default: %{default_s})") % { default_s: default_s } end else "" end end stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start) end end def width # :nodoc: @width ||= if $stdout.tty? begin require 'curses' Curses.init_screen x = Curses.cols Curses.close_screen x rescue Exception 80 end else 80 end end def wrap str, opts = {} # :nodoc: if str == "" [""] else str.split("\n").map { |s| wrap_line s, opts }.flatten end end ## The per-parser version of Trollop::die (see that for documentation). def die arg, msg if msg $stderr.puts _("Error: argument --%{value0} %{msg}.") % { value0: @specs[arg][:long], msg: msg } else $stderr.puts _("Error: %{arg}.") % { arg: arg } end $stderr.puts _("Try --help for help.") exit(-1) end private ## yield successive arg, parameter pairs def each_arg args remains = [] i = 0 until i >= args.length if @stop_words.member? args[i] remains += args[i..] return remains end case args[i] when /^--$/ # arg terminator remains += args[(i + 1)..] return remains when /^--(\S+?)=(.*)$/ # long argument with equals yield "--#{::Regexp.last_match(1)}", [::Regexp.last_match(2)] i += 1 when /^--(\S+)$/ # long argument params = collect_argument_parameters(args, i + 1) if params.empty? # long argument no parameter yield args[i], nil i += 1 else num_params_taken = yield args[i], params unless num_params_taken if @stop_on_unknown remains += args[i + 1..] return remains else remains += params end end i += 1 + num_params_taken end when /^-(\S+)$/ # one or more short arguments shortargs = ::Regexp.last_match(1).split(//) shortargs.each_with_index do |a, j| if j == (shortargs.length - 1) params = collect_argument_parameters(args, i + 1) if params.empty? # argument no parameter yield "-#{a}", nil i += 1 else num_params_taken = yield "-#{a}", params unless num_params_taken if @stop_on_unknown remains += args[i + 1..] return remains else remains += params end end i += 1 + num_params_taken end else yield "-#{a}", nil end end else if @stop_on_unknown remains += args[i..] return remains else remains << args[i] i += 1 end end end remains end def parse_integer_parameter param, arg raise CommandlineError, _("option '%{arg}' needs an integer") % { arg: arg } unless param =~ /^\d+$/ param.to_i end def parse_float_parameter param, arg raise CommandlineError, _("option '%{arg}' needs a floating-point number") % { arg: arg } unless param =~ FLOAT_RE param.to_f end def parse_io_parameter param, arg case param when /^(stdin|-)$/i; $stdin else require 'open-uri' begin URI.parse(param).open rescue SystemCallError => e raise CommandlineError, _("file or url for option '%{arg}' cannot be opened: %{value0}") % { arg: arg, value0: e.message }, e.backtrace end end end def collect_argument_parameters args, start_at params = [] pos = start_at while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos]) params << args[pos] pos += 1 end params end def resolve_default_short_options @order.each do |type, name| next unless type == :opt opts = @specs[name] next if opts[:short] c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) } if c # found a character to use opts[:short] = c @short[c] = name end end end def wrap_line str, opts = {} prefix = opts[:prefix] || 0 width = opts[:width] || (self.width - 1) start = 0 ret = [] until start > str.length nextt = if start + width >= str.length str.length else x = str.rindex(/\s/, start + width) x = str.index(/\s/, start) if x && x < start x || str.length end ret << (ret.empty? ? "" : " " * prefix) + str[start...nextt] start = nextt + 1 end ret end ## instance_eval but with ability to handle block arguments ## thanks to why: http://redhanded.hobix.com/inspect/aBlockCostume.html def cloaker &b (class << self; self; end).class_eval do define_method :cloaker_, &b meth = instance_method :cloaker_ remove_method :cloaker_ meth end end end ## The easy, syntactic-sugary entry method into Trollop. Creates a Parser, ## passes the block to it, then parses +args+ with it, handling any errors or ## requests for help or version information appropriately (and then exiting). ## Modifies +args+ in place. Returns a hash of option values. ## ## The block passed in should contain zero or more calls to +opt+ ## (Parser#opt), zero or more calls to +text+ (Parser#text), and ## probably a call to +version+ (Parser#version). ## ## The returned block contains a value for every option specified with ## +opt+. The value will be the value given on the commandline, or the ## default value if the option was not specified on the commandline. For ## every option specified on the commandline, a key "<option ## name>_given" will also be set in the hash. ## ## Example: ## ## require 'trollop' ## opts = Trollop::options do ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false ## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true ## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4 ## opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil ## end ## ## ## if called with no arguments ## p opts # => { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil } ## ## ## if called with --monkey ## p opts # => {:monkey_given=>true, :monkey=>true, :goat=>true, :num_limbs=>4, :help=>false, :num_thumbs=>nil} ## ## See more examples at http://trollop.rubyforge.org. def options args = ARGV, *a, &b @last_parser = Parser.new(*a, &b) with_standard_exception_handling(@last_parser) { @last_parser.parse args } end ## If Trollop::options doesn't do quite what you want, you can create a Parser ## object and call Parser#parse on it. That method will throw CommandlineError, ## HelpNeeded and VersionNeeded exceptions when necessary; if you want to ## have these handled for you in the standard manner (e.g. show the help ## and then exit upon an HelpNeeded exception), call your code from within ## a block passed to this method. ## ## Note that this method will call System#exit after handling an exception! ## ## Usage example: ## ## require 'trollop' ## p = Trollop::Parser.new do ## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false ## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true ## end ## ## opts = Trollop::with_standard_exception_handling p do ## o = p.parse ARGV ## raise Trollop::HelpNeeded if ARGV.empty? # show help screen ## o ## end ## ## Requires passing in the parser object. def with_standard_exception_handling parser yield rescue CommandlineError => e $stderr.puts _("Error: %{value0}.") % { value0: e.message } $stderr.puts _("Try --help for help.") exit(-1) rescue HelpNeeded parser.educate exit rescue VersionNeeded puts parser.version exit end ## Informs the user that their usage of 'arg' was wrong, as detailed by ## 'msg', and dies. Example: ## ## options do ## opt :volume, :default => 0.0 ## end ## ## die :volume, "too loud" if opts[:volume] > 10.0 ## die :volume, "too soft" if opts[:volume] < 0.1 ## ## In the one-argument case, simply print that message, a notice ## about -h, and die. Example: ## ## options do ## opt :whatever # ... ## end ## ## Trollop::die "need at least one filename" if ARGV.empty? def die arg, msg = nil if @last_parser @last_parser.die arg, msg else
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/util/command_line/puppet_option_parser.rb
lib/puppet/util/command_line/puppet_option_parser.rb
# frozen_string_literal: true require_relative '../../../puppet/util/command_line/trollop' module Puppet module Util class CommandLine class PuppetOptionError < Puppet::Error end class TrollopCommandlineError < Puppet::Util::CommandLine::Trollop::CommandlineError; end # This is a command line option parser. It is intended to have an API that is very similar to # the ruby stdlib 'OptionParser' API, for ease of integration into our existing code... however, # However, we've removed the OptionParser-based implementation and are only maintaining the # it's implemented based on the third-party "trollop" library. This was done because there # are places where the stdlib OptionParser is not flexible enough to meet our needs. class PuppetOptionParser def initialize(usage_msg = nil) require_relative '../../../puppet/util/command_line/trollop' @create_default_short_options = false @parser = Trollop::Parser.new do banner usage_msg end end # This parameter, if set, will tell the underlying option parser not to throw an # exception if we pass it options that weren't explicitly registered. We need this # capability because we need to be able to pass all of the command-line options before # we know which application/face they are going to be running, but the app/face # may specify additional command-line arguments that are valid for that app/face. attr_reader :ignore_invalid_options def ignore_invalid_options=(value) @parser.ignore_invalid_options = value end def on(*args, &block) # The 2nd element is an optional "short" representation. case args.length when 3 long, desc, type = args when 4 long, short, desc, type = args else raise ArgumentError, _("this method only takes 3 or 4 arguments. Given: %{args}") % { args: args.inspect } end options = { :long => long, :short => short, :required => false, :callback => pass_only_last_value_on_to(block), :multi => true, } case type when :REQUIRED options[:type] = :string when :NONE options[:type] = :flag else raise PuppetOptionError, _("Unsupported type: '%{type}'") % { type: type } end @parser.opt long.sub("^--", "").intern, desc, options end def parse(*args) args = args[0] if args.size == 1 and args[0].is_a?(Array) args_copy = args.dup begin @parser.parse args_copy rescue Puppet::Util::CommandLine::Trollop::CommandlineError => err raise PuppetOptionError.new(_("Error parsing arguments"), err) end end def pass_only_last_value_on_to(block) ->(values) { block.call(values.is_a?(Array) ? values.last : values) } end private :pass_only_last_value_on_to 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/watcher/periodic_watcher.rb
lib/puppet/util/watcher/periodic_watcher.rb
# frozen_string_literal: true # Monitor a given watcher for changes on a periodic interval. class Puppet::Util::Watcher::PeriodicWatcher # @param watcher [Puppet::Util::Watcher::ChangeWatcher] a watcher for the value to watch # @param timer [Puppet::Util::Watcher::Timer] A timer to determine when to # recheck the watcher. If the timeout of the timer is negative, then the # watched value is always considered to be changed def initialize(watcher, timer) @watcher = watcher @timer = timer @timer.start end # @return [true, false] If the file has changed since it was last checked. def changed? return true if always_consider_changed? @watcher = examine_watched_info(@watcher) @watcher.changed? end private def always_consider_changed? @timer.timeout < 0 end def examine_watched_info(known) if @timer.expired? @timer.start known.next_reading else known 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/watcher/timer.rb
lib/puppet/util/watcher/timer.rb
# frozen_string_literal: true class Puppet::Util::Watcher::Timer attr_reader :timeout def initialize(timeout) @timeout = timeout end def start @start_time = now end def expired? (now - @start_time) >= @timeout end def now Time.now.to_i 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/watcher/change_watcher.rb
lib/puppet/util/watcher/change_watcher.rb
# frozen_string_literal: true # Watches for changes over time. It only re-examines the values when it is requested to update readings. # @api private class Puppet::Util::Watcher::ChangeWatcher def self.watch(reader) Puppet::Util::Watcher::ChangeWatcher.new(nil, nil, reader).next_reading end def initialize(previous, current, value_reader) @previous = previous @current = current @value_reader = value_reader end def changed? if uncertain? false else @previous != @current end end def uncertain? @previous.nil? || @current.nil? end def change_current_reading_to(new_value) Puppet::Util::Watcher::ChangeWatcher.new(@current, new_value, @value_reader) end def next_reading change_current_reading_to(@value_reader.call) 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/connection.rb
lib/puppet/util/ldap/connection.rb
# frozen_string_literal: true require_relative '../../../puppet/util/ldap' class Puppet::Util::Ldap::Connection attr_accessor :host, :port, :user, :password, :reset, :ssl attr_reader :connection # Return a default connection, using our default settings. def self.instance ssl = if Puppet[:ldaptls] :tls elsif Puppet[:ldapssl] true else false end options = {} options[:ssl] = ssl user = Puppet.settings[:ldapuser] if user && user != "" options[:user] = user pass = Puppet.settings[:ldappassword] if pass && pass != "" options[:password] = pass end end new(Puppet[:ldapserver], Puppet[:ldapport], options) end def close connection.unbind if connection.bound? end def initialize(host, port, user: nil, password: nil, reset: nil, ssl: nil) raise Puppet::Error, _("Could not set up LDAP Connection: Missing ruby/ldap libraries") unless Puppet.features.ldap? @host = host @port = port @user = user @password = password @reset = reset @ssl = ssl end # Create a per-connection unique name. def name [host, port, user, password, ssl].collect(&:to_s).join("/") end # Should we reset the connection? def reset? reset end # Start our ldap connection. def start case ssl when :tls @connection = LDAP::SSLConn.new(host, port, true) when true @connection = LDAP::SSLConn.new(host, port) else @connection = LDAP::Conn.new(host, port) end @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3) @connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON) @connection.simple_bind(user, password) rescue => detail raise Puppet::Error, _("Could not connect to LDAP: %{detail}") % { detail: detail }, detail.backtrace end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false