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
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/envelope.rb
lib/puppet/indirector/envelope.rb
# frozen_string_literal: true require_relative '../../puppet/indirector' # Provide any attributes or functionality needed for indirected # instances. module Puppet::Indirector::Envelope attr_accessor :expiration def expired? expiration and expiration < Time.now end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/plain.rb
lib/puppet/indirector/plain.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' # An empty terminus type, meant to just return empty objects. class Puppet::Indirector::Plain < Puppet::Indirector::Terminus # Just return nothing. def find(request) indirection.model.new(request.key) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/memory.rb
lib/puppet/indirector/memory.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' # Manage a memory-cached list of instances. class Puppet::Indirector::Memory < Puppet::Indirector::Terminus def initialize clear end def clear @instances = {} end def destroy(request) raise ArgumentError, _("Could not find %{request} to destroy") % { request: request.key } unless @instances.include?(request.key) @instances.delete(request.key) end def find(request) @instances[request.key] end def search(request) found_keys = @instances.keys.find_all { |key| key.include?(request.key) } found_keys.collect { |key| @instances[key] } end def head(request) !find(request).nil? end def save(request) @instances[request.key] = request.instance end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/errors.rb
lib/puppet/indirector/errors.rb
# frozen_string_literal: true require_relative '../../puppet/error' module Puppet::Indirector class ValidationError < Puppet::Error; end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/msgpack.rb
lib/puppet/indirector/msgpack.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' require_relative '../../puppet/util' # The base class for MessagePack indirection terminus implementations. # # This should generally be preferred to the PSON base for any future # implementations, since it is ~ 30 times faster class Puppet::Indirector::Msgpack < Puppet::Indirector::Terminus def initialize(*args) unless Puppet.features.msgpack? raise _("MessagePack terminus not supported without msgpack library") end super end def find(request) load_msgpack_from_file(path(request.key), request.key) end def save(request) filename = path(request.key) FileUtils.mkdir_p(File.dirname(filename)) Puppet::FileSystem.replace_file(filename, 0o660) { |f| f.print to_msgpack(request.instance) } rescue TypeError => detail Puppet.log_exception(detail, _("Could not save %{name} %{request}: %{detail}") % { name: name, request: request.key, detail: detail }) end def destroy(request) Puppet::FileSystem.unlink(path(request.key)) rescue => detail unless detail.is_a? Errno::ENOENT raise Puppet::Error, _("Could not destroy %{name} %{request}: %{detail}") % { name: name, request: request.key, detail: detail }, detail.backtrace end 1 # emulate success... end def search(request) Dir.glob(path(request.key)).collect do |file| load_msgpack_from_file(file, request.key) end end # Return the path to a given node's file. def path(name, ext = '.msgpack') if name =~ Puppet::Indirector::BadNameRegexp then Puppet.crit(_("directory traversal detected in %{indirection}: %{name}") % { indirection: self.class, name: name.inspect }) raise ArgumentError, _("invalid key") end base = Puppet.run_mode.server? ? Puppet[:server_datadir] : Puppet[:client_datadir] File.join(base, self.class.indirection_name.to_s, name.to_s + ext) end private def load_msgpack_from_file(file, key) msgpack = nil begin msgpack = Puppet::FileSystem.read(file, :encoding => 'utf-8') rescue Errno::ENOENT return nil rescue => detail # TRANSLATORS "MessagePack" is a program name and should not be translated raise Puppet::Error, _("Could not read MessagePack data for %{indirection} %{key}: %{detail}") % { indirection: indirection.name, key: key, detail: detail }, detail.backtrace end begin from_msgpack(msgpack) rescue => detail raise Puppet::Error, _("Could not parse MessagePack data for %{indirection} %{key}: %{detail}") % { indirection: indirection.name, key: key, detail: detail }, detail.backtrace end end def from_msgpack(text) model.convert_from('msgpack', text) end def to_msgpack(object) object.render('msgpack') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/terminus.rb
lib/puppet/indirector/terminus.rb
# frozen_string_literal: true require_relative '../../puppet/indirector' require_relative '../../puppet/indirector/errors' require_relative '../../puppet/indirector/indirection' require_relative '../../puppet/util/instance_loader' # A simple class that can function as the base class for indirected types. class Puppet::Indirector::Terminus require_relative '../../puppet/util/docs' extend Puppet::Util::Docs class << self include Puppet::Util::InstanceLoader attr_accessor :name, :terminus_type attr_reader :abstract_terminus, :indirection # Are we an abstract terminus type, rather than an instance with an # associated indirection? def abstract_terminus? abstract_terminus end # Convert a constant to a short name. def const2name(const) const.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern end # Look up the indirection if we were only provided a name. def indirection=(name) if name.is_a?(Puppet::Indirector::Indirection) @indirection = name else ind = Puppet::Indirector::Indirection.instance(name) if ind @indirection = ind else raise ArgumentError, _("Could not find indirection instance %{name} for %{terminus}") % { name: name, terminus: self.name } end end end def indirection_name @indirection.name end # Register our subclass with the appropriate indirection. # This follows the convention that our terminus is named after the # indirection. def inherited(subclass) longname = subclass.to_s if longname =~ /#<Class/ raise Puppet::DevError, _("Terminus subclasses must have associated constants") end names = longname.split("::") # Convert everything to a lower-case symbol, converting camelcase to underscore word separation. name = names.pop.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" }.intern subclass.name = name # Short-circuit the abstract types, which are those that directly subclass # the Terminus class. if self == Puppet::Indirector::Terminus subclass.mark_as_abstract_terminus return end # Set the terminus type to be the name of the abstract terminus type. # Yay, class/instance confusion. subclass.terminus_type = self.name # This subclass is specifically associated with an indirection. raise("Invalid name #{longname}") unless names.length > 0 processed_name = names.pop.sub(/^[A-Z]/, &:downcase).gsub(/[A-Z]/) { |i| "_#{i.downcase}" } if processed_name.empty? raise Puppet::DevError, _("Could not discern indirection model from class constant") end # This will throw an exception if the indirection instance cannot be found. # Do this last, because it also registers the terminus type with the indirection, # which needs the above information. subclass.indirection = processed_name.intern # And add this instance to the instance hash. Puppet::Indirector::Terminus.register_terminus_class(subclass) end # Mark that this instance is abstract. def mark_as_abstract_terminus @abstract_terminus = true end def model indirection.model end # Convert a short name to a constant. def name2const(name) name.to_s.capitalize.sub(/_(.)/) { |_i| ::Regexp.last_match(1).upcase } end # Register a class, probably autoloaded. def register_terminus_class(klass) setup_instance_loading klass.indirection_name instance_hash(klass.indirection_name)[klass.name] = klass end # Return a terminus by name, using the autoloader. def terminus_class(indirection_name, terminus_type) setup_instance_loading indirection_name loaded_instance(indirection_name, terminus_type) end # Return all terminus classes for a given indirection. def terminus_classes(indirection_name) setup_instance_loading indirection_name instance_loader(indirection_name).files_to_load(Puppet.lookup(:current_environment)).map do |file| File.basename(file).chomp(".rb").intern end end private def setup_instance_loading(type) instance_load type, "puppet/indirector/#{type}" unless instance_loading?(type) end end def indirection self.class.indirection end def initialize raise Puppet::DevError, _("Cannot create instances of abstract terminus types") if self.class.abstract_terminus? end def model self.class.model end def name self.class.name end def require_environment? true end def allow_remote_requests? true end def terminus_type self.class.terminus_type end def validate(request) if request.instance validate_model(request) validate_key(request) end end def validate_key(request) unless request.key == request.instance.name raise Puppet::Indirector::ValidationError, _("Instance name %{name} does not match requested key %{key}") % { name: request.instance.name.inspect, key: request.key.inspect } end end def validate_model(request) unless model === request.instance raise Puppet::Indirector::ValidationError, _("Invalid instance type %{klass}, expected %{model_type}") % { klass: request.instance.class.inspect, model_type: model.inspect } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/rest.rb
lib/puppet/indirector/rest.rb
# frozen_string_literal: true # Access objects via REST class Puppet::Indirector::REST < Puppet::Indirector::Terminus def find(request) raise NotImplementedError end def head(request) raise NotImplementedError end def search(request) raise NotImplementedError end def destroy(request) raise NotImplementedError end def save(request) raise NotImplementedError end def validate_key(request) # Validation happens on the remote end end private def convert_to_http_error(response) if response.body.to_s.empty? && response.reason returned_message = response.reason elsif response['content-type'].is_a?(String) content_type, body = parse_response(response) if content_type =~ /[pj]son/ returned_message = Puppet::Util::Json.load(body)["message"] else returned_message = response.body end else returned_message = response.body end message = _("Error %{code} on SERVER: %{returned_message}") % { code: response.code, returned_message: returned_message } Net::HTTPError.new(message, Puppet::HTTP::ResponseConverter.to_ruby_response(response)) end # Returns the content_type, stripping any appended charset, and the # body, decompressed if necessary def parse_response(response) if response['content-type'] [response['content-type'].gsub(/\s*;.*$/, ''), response.body] else raise _("No content type in http response; cannot parse") end end def elide(string, length) if Puppet::Util::Log.level == :debug || string.length <= length string else string[0, length - 3] + "..." end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/code.rb
lib/puppet/indirector/code.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' # Do nothing, requiring that the back-end terminus do all # of the work. class Puppet::Indirector::Code < Puppet::Indirector::Terminus end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/yaml.rb
lib/puppet/indirector/yaml.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' require_relative '../../puppet/util/yaml' # The base class for YAML indirection termini. class Puppet::Indirector::Yaml < Puppet::Indirector::Terminus # Read a given name's file in and convert it from YAML. def find(request) file = path(request.key) return nil unless Puppet::FileSystem.exist?(file) begin load_file(file) rescue Puppet::Util::Yaml::YamlLoadError => detail raise Puppet::Error, _("Could not parse YAML data for %{indirection} %{request}: %{detail}") % { indirection: indirection.name, request: request.key, detail: detail }, detail.backtrace end end # Convert our object to YAML and store it to the disk. def save(request) raise ArgumentError, _("You can only save objects that respond to :name") unless request.instance.respond_to?(:name) file = path(request.key) basedir = File.dirname(file) # This is quite likely a bad idea, since we're not managing ownership or modes. Dir.mkdir(basedir) unless Puppet::FileSystem.exist?(basedir) begin Puppet::Util::Yaml.dump(request.instance, file) rescue TypeError => detail Puppet.err _("Could not save %{indirection} %{request}: %{detail}") % { indirection: name, request: request.key, detail: detail } end end # Return the path to a given node's file. def path(name, ext = '.yaml') if name =~ Puppet::Indirector::BadNameRegexp then Puppet.crit(_("directory traversal detected in %{indirection}: %{name}") % { indirection: self.class, name: name.inspect }) raise ArgumentError, _("invalid key") end base = Puppet.run_mode.server? ? Puppet[:yamldir] : Puppet[:clientyamldir] File.join(base, self.class.indirection_name.to_s, name.to_s + ext) end def destroy(request) file_path = path(request.key) Puppet::FileSystem.unlink(file_path) if Puppet::FileSystem.exist?(file_path) end def search(request) Dir.glob(path(request.key, '')).collect do |file| load_file(file) end end protected def load_file(file) Puppet::Util::Yaml.safe_load_file(file, [model, Symbol]) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/json.rb
lib/puppet/indirector/json.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' require_relative '../../puppet/util' # The base class for JSON indirection terminus implementations. # # This should generally be preferred to the YAML base for any future # implementations, since it is faster and can load untrusted data safely. class Puppet::Indirector::JSON < Puppet::Indirector::Terminus def find(request) load_json_from_file(path(request.key), request.key) end def save(request) filename = path(request.key) FileUtils.mkdir_p(File.dirname(filename)) Puppet::FileSystem.replace_file(filename, 0o660) { |f| f.print to_json(request.instance).force_encoding(Encoding::BINARY) } rescue TypeError => detail Puppet.log_exception(detail, _("Could not save %{json} %{request}: %{detail}") % { json: name, request: request.key, detail: detail }) end def destroy(request) Puppet::FileSystem.unlink(path(request.key)) rescue => detail unless detail.is_a? Errno::ENOENT raise Puppet::Error, _("Could not destroy %{json} %{request}: %{detail}") % { json: name, request: request.key, detail: detail }, detail.backtrace end 1 # emulate success... end def search(request) Dir.glob(path(request.key)).collect do |file| load_json_from_file(file, request.key) end end # Return the path to a given node's file. def path(name, ext = '.json') if name =~ Puppet::Indirector::BadNameRegexp then Puppet.crit(_("directory traversal detected in %{json}: %{name}") % { json: self.class, name: name.inspect }) raise ArgumentError, _("invalid key") end base = data_dir File.join(base, self.class.indirection_name.to_s, name.to_s + ext) end private def data_dir Puppet.run_mode.server? ? Puppet[:server_datadir] : Puppet[:client_datadir] end def load_json_from_file(file, key) json = nil begin json = Puppet::FileSystem.read(file, :encoding => Encoding::BINARY) rescue Errno::ENOENT return nil rescue => detail raise Puppet::Error, _("Could not read JSON data for %{name} %{key}: %{detail}") % { name: indirection.name, key: key, detail: detail }, detail.backtrace end begin from_json(json) rescue => detail raise Puppet::Error, _("Could not parse JSON data for %{name} %{key}: %{detail}") % { name: indirection.name, key: key, detail: detail }, detail.backtrace end end def from_json(text) model.convert_from('json', text.force_encoding(Encoding::UTF_8)) end def to_json(object) object.render('json') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/hiera.rb
lib/puppet/indirector/hiera.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' require 'hiera/scope' # This class can't be collapsed into Puppet::Indirector::DataBindings::Hiera # because some community plugins rely on this class directly, see PUP-1843. # This class is deprecated and will be deleted in a future release. # Use `Puppet::DataBinding.indirection.terminus(:hiera)` instead. class Puppet::Indirector::Hiera < Puppet::Indirector::Terminus def initialize(*args) unless Puppet.features.hiera? # TRANSLATORS "Hiera" is the name of a code library and should not be translated raise _("Hiera terminus not supported without hiera library") end super end if defined?(::Psych::SyntaxError) DataBindingExceptions = [::StandardError, ::Psych::SyntaxError] else DataBindingExceptions = [::StandardError] end def find(request) not_found = Object.new options = request.options Puppet.debug { "Performing a hiera indirector lookup of #{request.key} with options #{options.inspect}" } value = hiera.lookup(request.key, not_found, Hiera::Scope.new(options[:variables]), nil, convert_merge(options[:merge])) throw :no_such_key if value.equal?(not_found) value rescue *DataBindingExceptions => detail error = Puppet::DataBinding::LookupError.new("DataBinding 'hiera': #{detail.message}") error.set_backtrace(detail.backtrace) raise error end private # Converts a lookup 'merge' parameter argument into a Hiera 'resolution_type' argument. # # @param merge [String,Hash,nil] The lookup 'merge' argument # @return [Symbol,Hash,nil] The Hiera 'resolution_type' def convert_merge(merge) case merge when nil, 'first' # Nil is OK. Defaults to Hiera :priority nil when Puppet::Pops::MergeStrategy convert_merge(merge.configuration) when 'unique' # Equivalent to Hiera :array :array when 'hash' # Equivalent to Hiera :hash with default :native merge behavior. A Hash must be passed here # to override possible Hiera deep merge config settings. { :behavior => :native } when 'deep' # Equivalent to Hiera :hash with :deeper merge behavior. { :behavior => :deeper } when Hash strategy = merge['strategy'] if strategy == 'deep' result = { :behavior => :deeper } # Remaining entries must have symbolic keys merge.each_pair { |k, v| result[k.to_sym] = v unless k == 'strategy' } result else convert_merge(strategy) end else # TRANSLATORS "merge" is a parameter name and should not be translated raise Puppet::DataBinding::LookupError, _("Unrecognized value for request 'merge' parameter: '%{merge}'") % { merge: merge } end end public def self.hiera_config hiera_config = Puppet.settings[:hiera_config] config = {} if Puppet::FileSystem.exist?(hiera_config) config = Hiera::Config.load(hiera_config) else Puppet.warning _("Config file %{hiera_config} not found, using Hiera defaults") % { hiera_config: hiera_config } end config[:logger] = 'puppet' config end def self.hiera @hiera ||= Hiera.new(:config => hiera_config) end def hiera self.class.hiera end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/exec.rb
lib/puppet/indirector/exec.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' require_relative '../../puppet/util' class Puppet::Indirector::Exec < Puppet::Indirector::Terminus # Look for external node definitions. def find(request) name = request.key external_command = command # Make sure it's an array raise Puppet::DevError, _("Exec commands must be an array") unless external_command.is_a?(Array) # Make sure it's fully qualified. raise ArgumentError, _("You must set the exec parameter to a fully qualified command") unless Puppet::Util.absolute_path?(external_command[0]) # Add our name to it. external_command << name begin output = execute(external_command, :failonfail => true, :combine => false) rescue Puppet::ExecutionFailure => detail raise Puppet::Error, _("Failed to find %{name} via exec: %{detail}") % { name: name, detail: detail }, detail.backtrace end if output =~ /\A\s*\Z/ # all whitespace Puppet.debug { "Empty response for #{name} from #{self.name} terminus" } nil else output end end private # Proxy the execution, so it's easier to test. def execute(command, arguments) Puppet::Util::Execution.execute(command, arguments) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/generic_http.rb
lib/puppet/indirector/generic_http.rb
# frozen_string_literal: true require_relative '../../puppet/file_serving/terminus_helper' class Puppet::Indirector::GenericHttp < Puppet::Indirector::Terminus desc "Retrieve data from a remote HTTP server." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/face.rb
lib/puppet/indirector/face.rb
# frozen_string_literal: true require_relative '../../puppet/face' class Puppet::Indirector::Face < Puppet::Face option "--terminus _" + _("TERMINUS") do summary _("The indirector terminus to use.") description <<-EOT Indirector faces expose indirected subsystems of Puppet. These subsystems are each able to retrieve and alter a specific type of data (with the familiar actions of `find`, `search`, `save`, and `destroy`) from an arbitrary number of pluggable backends. In Puppet parlance, these backends are called terminuses. Almost all indirected subsystems have a `rest` terminus that interacts with the puppet master's data. Most of them have additional terminuses for various local data models, which are in turn used by the indirected subsystem on the puppet master whenever it receives a remote request. The terminus for an action is often determined by context, but occasionally needs to be set explicitly. See the "Notes" section of this face's manpage for more details. EOT before_action do |_action, _args, options| set_terminus(options[:terminus]) end after_action do |_action, _args, _options| indirection.reset_terminus_class end end def self.indirections Puppet::Indirector::Indirection.instances.collect(&:to_s).sort end def self.terminus_classes(indirection) Puppet::Indirector::Terminus.terminus_classes(indirection.to_sym).collect(&:to_s).sort end def call_indirection_method(method, key, options) begin if method == :save # key is really the instance to save result = indirection.__send__(method, key, nil, options) else result = indirection.__send__(method, key, options) end rescue => detail message = _("Could not call '%{method}' on '%{indirection}': %{detail}") % { method: method, indirection: indirection_name, detail: detail } Puppet.log_exception(detail, message) raise RuntimeError, message, detail.backtrace end result end action :destroy do summary _("Delete an object.") arguments _("<key>") when_invoked { |key, _options| call_indirection_method :destroy, key, {} } end action :find do summary _("Retrieve an object by name.") arguments _("[<key>]") when_invoked do |*args| # Default the key to Puppet[:certname] if none is supplied if args.length == 1 key = Puppet[:certname] else key = args.first end call_indirection_method :find, key, {} end end action :save do summary _("API only: create or overwrite an object.") arguments _("<key>") description <<-EOT API only: create or overwrite an object. As the Faces framework does not currently accept data from STDIN, save actions cannot currently be invoked from the command line. EOT when_invoked { |key, _options| call_indirection_method :save, key, {} } end action :search do summary _("Search for an object or retrieve multiple objects.") arguments _("<query>") when_invoked { |key, _options| call_indirection_method :search, key, {} } end # Print the configuration for the current terminus class action :info do summary _("Print the default terminus class for this face.") description <<-EOT Prints the default terminus class for this subcommand. Note that different run modes may have different default termini; when in doubt, specify the run mode with the '--run_mode' option. EOT when_invoked do |_options| if indirection.terminus_class _("Run mode '%{mode}': %{terminus}") % { mode: Puppet.run_mode.name, terminus: indirection.terminus_class } else _("No default terminus class for run mode '%{mode}'") % { mode: Puppet.run_mode.name } end end end attr_accessor :from def indirection_name @indirection_name || name.to_sym end # Here's your opportunity to override the indirection name. By default it # will be the same name as the face. def set_indirection_name(name) @indirection_name = name end # Return an indirection associated with a face, if one exists; # One usually does. def indirection unless @indirection @indirection = Puppet::Indirector::Indirection.instance(indirection_name) @indirection or raise _("Could not find terminus for %{indirection}") % { indirection: indirection_name } end @indirection end def set_terminus(from) indirection.terminus_class = from rescue => detail msg = _("Could not set '%{indirection}' terminus to '%{from}' (%{detail}); valid terminus types are %{types}") % { indirection: indirection.name, from: from, detail: detail, types: self.class.terminus_classes(indirection.name).join(", ") } raise detail, msg, detail.backtrace end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/fact_search.rb
lib/puppet/indirector/fact_search.rb
# frozen_string_literal: true # module containing common methods used by json and yaml facts indirection terminus module Puppet::Indirector::FactSearch def node_matches?(facts, options) options.each do |key, value| type, name, operator = key.to_s.split(".") operator ||= 'eq' return false unless node_matches_option?(type, name, operator, value, facts) end true end def node_matches_option?(type, name, operator, value, facts) case type when "meta" case name when "timestamp" compare_timestamp(operator, facts.timestamp, Time.parse(value)) end when "facts" compare_facts(operator, facts.values[name], value) end end def compare_facts(operator, value1, value2) return false unless value1 case operator when "eq" value1.to_s == value2.to_s when "le" value1.to_f <= value2.to_f when "ge" value1.to_f >= value2.to_f when "lt" value1.to_f < value2.to_f when "gt" value1.to_f > value2.to_f when "ne" value1.to_s != value2.to_s end end def compare_timestamp(operator, value1, value2) case operator when "eq" value1 == value2 when "le" value1 <= value2 when "ge" value1 >= value2 when "lt" value1 < value2 when "gt" value1 > value2 when "ne" value1 != value2 end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_content.rb
lib/puppet/indirector/file_content.rb
# frozen_string_literal: true # A stub class, so our constants work. class Puppet::Indirector::FileContent # :nodoc: end require_relative '../../puppet/file_serving/content'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/indirection.rb
lib/puppet/indirector/indirection.rb
# frozen_string_literal: true require_relative '../../puppet/util/docs' require_relative '../../puppet/util/profiler' require_relative '../../puppet/indirector/envelope' require_relative '../../puppet/indirector/request' require_relative '../../puppet/thread_local' # The class that connects functional classes with their different collection # back-ends. Each indirection has a set of associated terminus classes, # each of which is a subclass of Puppet::Indirector::Terminus. class Puppet::Indirector::Indirection include Puppet::Util::Docs attr_accessor :name, :model attr_reader :termini @@indirections = [] # Find an indirection by name. This is provided so that Terminus classes # can specifically hook up with the indirections they are associated with. def self.instance(name) @@indirections.find { |i| i.name == name } end # Return a list of all known indirections. Used to generate the # reference. def self.instances @@indirections.collect(&:name) end # Find an indirected model by name. This is provided so that Terminus classes # can specifically hook up with the indirections they are associated with. def self.model(name) match = @@indirections.find { |i| i.name == name } return nil unless match match.model end # Create and return our cache terminus. def cache raise Puppet::DevError, _("Tried to cache when no cache class was set") unless cache_class terminus(cache_class) end # Should we use a cache? def cache? cache_class ? true : false end def cache_class @cache_class.value end # Define a terminus class to be used for caching. def cache_class=(class_name) validate_terminus_class(class_name) if class_name @cache_class.value = class_name end # This is only used for testing. def delete @@indirections.delete(self) if @@indirections.include?(self) end # Set the time-to-live for instances created through this indirection. def ttl=(value) # TRANSLATORS "TTL" stands for "time to live" and refers to a duration of time raise ArgumentError, _("Indirection TTL must be an integer") unless value.is_a?(Integer) @ttl = value end # Default to the runinterval for the ttl. def ttl @ttl ||= Puppet[:runinterval] end # Calculate the expiration date for a returned instance. def expiration Time.now + ttl end # Generate the full doc string. def doc text = ''.dup text << scrub(@doc) << "\n\n" if @doc text << "* **Indirected Class**: `#{@indirected_class}`\n"; if terminus_setting text << "* **Terminus Setting**: #{terminus_setting}\n" end text end def initialize(model, name, doc: nil, indirected_class: nil, cache_class: nil, terminus_class: nil, terminus_setting: nil, extend: nil) @model = model @name = name @termini = {} @doc = doc raise(ArgumentError, _("Indirection %{name} is already defined") % { name: @name }) if @@indirections.find { |i| i.name == @name } @@indirections << self @indirected_class = indirected_class self.extend(extend) if extend # Setting these depend on the indirection already being installed so they have to be at the end set_global_setting(:cache_class, cache_class) set_global_setting(:terminus_class, terminus_class) set_global_setting(:terminus_setting, terminus_setting) end # Use this to set indirector settings globally across threads. def set_global_setting(setting, value) case setting when :cache_class validate_terminus_class(value) unless value.nil? @cache_class = Puppet::ThreadLocal.new(value) when :terminus_class validate_terminus_class(value) unless value.nil? @terminus_class = Puppet::ThreadLocal.new(value) when :terminus_setting @terminus_setting = Puppet::ThreadLocal.new(value) else raise(ArgumentError, _("The setting %{setting} is not a valid indirection setting.") % { setting: setting }) end end # Set up our request object. def request(*args) Puppet::Indirector::Request.new(name, *args) end # Return the singleton terminus for this indirection. def terminus(terminus_name = nil) # Get the name of the terminus. raise Puppet::DevError, _("No terminus specified for %{name}; cannot redirect") % { name: name } unless terminus_name ||= terminus_class termini[terminus_name] ||= make_terminus(terminus_name) end # These can be used to select the terminus class. def terminus_setting @terminus_setting.value end def terminus_setting=(setting) @terminus_setting.value = setting end # Determine the terminus class. def terminus_class unless @terminus_class.value setting = terminus_setting if setting self.terminus_class = Puppet.settings[setting] else raise Puppet::DevError, _("No terminus class nor terminus setting was provided for indirection %{name}") % { name: name } end end @terminus_class.value end def reset_terminus_class @terminus_class.value = nil end # Specify the terminus class to use. def terminus_class=(klass) validate_terminus_class(klass) @terminus_class.value = klass end # This is used by terminus_class= and cache=. def validate_terminus_class(terminus_class) unless terminus_class and terminus_class.to_s != "" raise ArgumentError, _("Invalid terminus name %{terminus_class}") % { terminus_class: terminus_class.inspect } end unless Puppet::Indirector::Terminus.terminus_class(name, terminus_class) raise ArgumentError, _("Could not find terminus %{terminus_class} for indirection %{name}") % { terminus_class: terminus_class, name: name } end end # Expire a cached object, if one is cached. Note that we don't actually # remove it, we expire it and write it back out to disk. This way people # can still use the expired object if they want. def expire(key, options = {}) request = request(:expire, key, nil, options) return nil unless cache? && !request.ignore_cache_save? instance = cache.find(request(:find, key, nil, options)) return nil unless instance Puppet.info _("Expiring the %{cache} cache of %{instance}") % { cache: name, instance: instance.name } # Set an expiration date in the past instance.expiration = Time.now - 60 cache.save(request(:save, nil, instance, options)) end def allow_remote_requests? terminus.allow_remote_requests? end # Search for an instance in the appropriate terminus, caching the # results if caching is configured.. def find(key, options = {}) request = request(:find, key, nil, options) terminus = prepare(request) result = find_in_cache(request) if !result.nil? result elsif request.ignore_terminus? nil else # Otherwise, return the result from the terminus, caching if # appropriate. result = terminus.find(request) unless result.nil? result.expiration ||= expiration if result.respond_to?(:expiration) if cache? && !request.ignore_cache_save? Puppet.info _("Caching %{indirection} for %{request}") % { indirection: name, request: request.key } begin cache.save request(:save, key, result, options) rescue => detail Puppet.log_exception(detail) raise detail end end filtered = result if terminus.respond_to?(:filter) Puppet::Util::Profiler.profile(_("Filtered result for %{indirection} %{request}") % { indirection: name, request: request.key }, [:indirector, :filter, name, request.key]) do filtered = terminus.filter(result) rescue Puppet::Error => detail Puppet.log_exception(detail) raise detail end end filtered end end end # Search for an instance in the appropriate terminus, and return a # boolean indicating whether the instance was found. def head(key, options = {}) request = request(:head, key, nil, options) terminus = prepare(request) # Look in the cache first, then in the terminus. Force the result # to be a boolean. !!(find_in_cache(request) || terminus.head(request)) end def find_in_cache(request) # See if our instance is in the cache and up to date. cached = cache.find(request) if cache? && !request.ignore_cache? return nil unless cached if cached.expired? Puppet.info _("Not using expired %{indirection} for %{request} from cache; expired at %{expiration}") % { indirection: name, request: request.key, expiration: cached.expiration } return nil end Puppet.debug { "Using cached #{name} for #{request.key}" } cached rescue => detail Puppet.log_exception(detail, _("Cached %{indirection} for %{request} failed: %{detail}") % { indirection: name, request: request.key, detail: detail }) nil end # Remove something via the terminus. def destroy(key, options = {}) request = request(:destroy, key, nil, options) terminus = prepare(request) result = terminus.destroy(request) if cache? and cache.find(request(:find, key, nil, options)) # Reuse the existing request, since it's equivalent. cache.destroy(request) end result end # Search for more than one instance. Should always return an array. def search(key, options = {}) request = request(:search, key, nil, options) terminus = prepare(request) result = terminus.search(request) if result raise Puppet::DevError, _("Search results from terminus %{terminus_name} are not an array") % { terminus_name: terminus.name } unless result.is_a?(Array) result.each do |instance| next unless instance.respond_to? :expiration instance.expiration ||= expiration end result end end # Save the instance in the appropriate terminus. This method is # normally an instance method on the indirected class. def save(instance, key = nil, options = {}) request = request(:save, key, instance, options) terminus = prepare(request) result = terminus.save(request) unless request.ignore_terminus? # If caching is enabled, save our document there cache.save(request) if cache? && !request.ignore_cache_save? result end private # Check authorization if there's a hook available; fail if there is one # and it returns false. def check_authorization(request, terminus) # At this point, we're assuming authorization makes no sense without # client information. return unless request.node # This is only to authorize via a terminus-specific authorization hook. return unless terminus.respond_to?(:authorized?) unless terminus.authorized?(request) msg = if request.options.empty? _("Not authorized to call %{method} on %{description}") % { method: request.method, description: request.description } else _("Not authorized to call %{method} on %{description} with %{option}") % { method: request.method, description: request.description, option: request.options.inspect } end raise ArgumentError, msg end end # Pick the appropriate terminus, check the request's authorization, and return it. # @param [Puppet::Indirector::Request] request instance # @return [Puppet::Indirector::Terminus] terminus instance (usually a subclass # of Puppet::Indirector::Terminus) for this request def prepare(request) # Pick our terminus. terminus_name = terminus_class dest_terminus = terminus(terminus_name) check_authorization(request, dest_terminus) dest_terminus.validate(request) dest_terminus end # Create a new terminus instance. def make_terminus(terminus_class) # Load our terminus class. klass = Puppet::Indirector::Terminus.terminus_class(name, terminus_class) unless klass raise ArgumentError, _("Could not find terminus %{terminus_class} for indirection %{indirection}") % { terminus_class: terminus_class, indirection: name } end klass.new end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/none.rb
lib/puppet/indirector/none.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/terminus' # A none terminus type, meant to always return nil class Puppet::Indirector::None < Puppet::Indirector::Terminus def find(request) nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/request.rb
lib/puppet/indirector/request.rb
# frozen_string_literal: true require 'cgi' require 'uri' require_relative '../../puppet/indirector' require_relative '../../puppet/util/psych_support' require_relative '../../puppet/util/warnings' # This class encapsulates all of the information you need to make an # Indirection call, and as a result also handles REST calls. It's somewhat # analogous to an HTTP Request object, except tuned for our Indirector. class Puppet::Indirector::Request include Puppet::Util::PsychSupport include Puppet::Util::Warnings attr_accessor :key, :method, :options, :instance, :node, :ip, :authenticated, :ignore_cache, :ignore_cache_save, :ignore_terminus attr_accessor :server, :port, :uri, :protocol attr_reader :indirection_name # trusted_information is specifically left out because we can't serialize it # and keep it "trusted" OPTION_ATTRIBUTES = [:ip, :node, :authenticated, :ignore_terminus, :ignore_cache, :ignore_cache_save, :instance, :environment] # Is this an authenticated request? def authenticated? # Double negative, so we just get true or false !!authenticated end def environment # If environment has not been set directly, we should use the application's # current environment @environment ||= Puppet.lookup(:current_environment) end def environment=(env) @environment = if env.is_a?(Puppet::Node::Environment) env else Puppet.lookup(:environments).get!(env) end end # LAK:NOTE This is a messy interface to the cache, and it's only # used by the Configurer class. I decided it was better to implement # it now and refactor later, when we have a better design, than # to spend another month coming up with a design now that might # not be any better. def ignore_cache? ignore_cache end def ignore_cache_save? ignore_cache_save end def ignore_terminus? ignore_terminus end def initialize(indirection_name, method, key, instance, options = {}) @instance = instance options ||= {} self.indirection_name = indirection_name self.method = method options = options.each_with_object({}) { |ary, hash| hash[ary[0].to_sym] = ary[1]; } set_attributes(options) @options = options if key # If the request key is a URI, then we need to treat it specially, # because it rewrites the key. We could otherwise strip server/port/etc # info out in the REST class, but it seemed bad design for the REST # class to rewrite the key. if key.to_s =~ %r{^\w+:/} and !Puppet::Util.absolute_path?(key.to_s) # it's a URI set_uri_key(key) else @key = key end end @key = @instance.name if !@key and @instance end # Look up the indirection based on the name provided. def indirection Puppet::Indirector::Indirection.instance(indirection_name) end def indirection_name=(name) @indirection_name = name.to_sym end def model ind = indirection raise ArgumentError, _("Could not find indirection '%{indirection}'") % { indirection: indirection_name } unless ind ind.model end # Are we trying to interact with multiple resources, or just one? def plural? method == :search end def initialize_from_hash(hash) @indirection_name = hash['indirection_name'].to_sym @method = hash['method'].to_sym @key = hash['key'] @instance = hash['instance'] @options = hash['options'] end def to_data_hash { 'indirection_name' => @indirection_name.to_s, 'method' => @method.to_s, 'key' => @key, 'instance' => @instance, 'options' => @options } end def to_hash result = options.dup OPTION_ATTRIBUTES.each do |attribute| value = send(attribute) if value result[attribute] = value end end result end def description uri || "/#{indirection_name}/#{key}" end def remote? node or ip end private def set_attributes(options) OPTION_ATTRIBUTES.each do |attribute| if options.include?(attribute.to_sym) send(attribute.to_s + "=", options[attribute]) options.delete(attribute) end end end # Parse the key as a URI, setting attributes appropriately. def set_uri_key(key) @uri = key begin # calling uri_encode for UTF-8 characters will % escape them and keep them UTF-8 uri = URI.parse(Puppet::Util.uri_encode(key)) rescue => detail raise ArgumentError, _("Could not understand URL %{key}: %{detail}") % { key: key, detail: detail }, detail.backtrace end # Just short-circuit these to full paths if uri.scheme == "file" @key = Puppet::Util.uri_to_path(uri) return end @server = uri.host if uri.host && !uri.host.empty? # If the URI class can look up the scheme, it will provide a port, # otherwise it will default to '0'. if uri.port.to_i == 0 and uri.scheme == "puppet" @port = Puppet.settings[:serverport].to_i else @port = uri.port.to_i end # filebucket:// is only used internally to pass request details # from Dipper objects to the indirector. The wire always uses HTTPS. if uri.scheme == 'filebucket' @protocol = 'https' else @protocol = uri.scheme end @key = Puppet::Util.uri_unescape(uri.path.sub(%r{^/}, '')) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_metadata.rb
lib/puppet/indirector/file_metadata.rb
# frozen_string_literal: true # A stub class, so our constants work. class Puppet::Indirector::FileMetadata # :nodoc: end require_relative '../../puppet/file_serving/metadata'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_server.rb
lib/puppet/indirector/file_server.rb
# frozen_string_literal: true require_relative '../../puppet/file_serving/configuration' require_relative '../../puppet/file_serving/fileset' require_relative '../../puppet/file_serving/terminus_helper' require_relative '../../puppet/indirector/terminus' # Look files up using the file server. class Puppet::Indirector::FileServer < Puppet::Indirector::Terminus include Puppet::FileServing::TerminusHelper # Is the client authorized to perform this action? def authorized?(request) return false unless [:find, :search].include?(request.method) mount, _ = configuration.split_path(request) # If we're not serving this mount, then access is denied. return false unless mount true end # Find our key using the fileserver. def find(request) mount, relative_path = configuration.split_path(request) return nil unless mount # The mount checks to see if the file exists, and returns nil # if not. path = mount.find(relative_path, request) return nil unless path path2instance(request, path) end # Search for files. This returns an array rather than a single # file. def search(request) mount, relative_path = configuration.split_path(request) paths = mount.search(relative_path, request) if mount unless paths Puppet.info _("Could not find filesystem info for file '%{request}' in environment %{env}") % { request: request.key, env: request.environment } return nil end path2instances(request, *paths) end private # Our fileserver configuration, if needed. def configuration Puppet::FileServing::Configuration.configuration end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/catalog/store_configs.rb
lib/puppet/indirector/catalog/store_configs.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/store_configs' require_relative '../../../puppet/resource/catalog' class Puppet::Resource::Catalog::StoreConfigs < Puppet::Indirector::StoreConfigs desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/catalog/compiler.rb
lib/puppet/indirector/catalog/compiler.rb
# frozen_string_literal: true require_relative '../../../puppet/environments' require_relative '../../../puppet/node' require_relative '../../../puppet/node/server_facts' require_relative '../../../puppet/resource/catalog' require_relative '../../../puppet/indirector/code' require_relative '../../../puppet/util/profiler' require_relative '../../../puppet/util/checksums' require 'yaml' require 'uri' class Puppet::Resource::Catalog::Compiler < Puppet::Indirector::Code desc "Compiles catalogs on demand using Puppet's compiler." include Puppet::Util include Puppet::Util::Checksums attr_accessor :code # @param request [Puppet::Indirector::Request] an indirection request # (possibly) containing facts # @return [Puppet::Node::Facts] facts object corresponding to facts in request def extract_facts_from_request(request) text_facts = request.options[:facts] return unless text_facts format = request.options[:facts_format] unless format raise ArgumentError, _("Facts but no fact format provided for %{request}") % { request: request.key } end Puppet::Util::Profiler.profile(_("Found facts"), [:compiler, :find_facts]) do facts = text_facts.is_a?(Puppet::Node::Facts) ? text_facts : convert_wire_facts(text_facts, format) unless facts.name == request.key raise Puppet::Error, _("Catalog for %{request} was requested with fact definition for the wrong node (%{fact_name}).") % { request: request.key.inspect, fact_name: facts.name.inspect } end return facts end end def save_facts_from_request(facts, request) Puppet::Node::Facts.indirection.save(facts, nil, :environment => request.environment, :transaction_uuid => request.options[:transaction_uuid]) end # Compile a node's catalog. def find(request) facts = extract_facts_from_request(request) save_facts_from_request(facts, request) unless facts.nil? node = node_from_request(facts, request) node.trusted_data = Puppet.lookup(:trusted_information) { Puppet::Context::TrustedInformation.local(node) }.to_h if node.environment # If the requested environment name doesn't match the server specified environment # name, as determined by the node terminus, and the request wants us to check for an # environment mismatch, then return an empty catalog with the server-specified # enviroment. if request.remote? && request.options[:check_environment] # The "environment" may be same while environment objects differ. This # is most likely because the environment cache was flushed between the request # processing and node lookup. Environment overrides `==` but requires the # name and modulepath to be the same. When using versioned environment dirs the # same "environment" can have different modulepaths so simply compare names here. if node.environment.name != request.environment.name Puppet.warning _("Requested environment '%{request_env}' did not match server specified environment '%{server_env}'") % { request_env: request.environment.name, server_env: node.environment.name } return Puppet::Resource::Catalog.new(node.name, node.environment) end end node.environment.with_text_domain do envs = Puppet.lookup(:environments) envs.guard(node.environment.name) begin compile(node, request.options) ensure envs.unguard(node.environment.name) end end else compile(node, request.options) end end # filter-out a catalog to remove exported resources def filter(catalog) return catalog.filter(&:virtual?) if catalog.respond_to?(:filter) catalog end def initialize Puppet::Util::Profiler.profile(_("Setup server facts for compiling"), [:compiler, :init_server_facts]) do set_server_facts end end # Is our compiler part of a network, or are we just local? def networked? Puppet.run_mode.server? end def require_environment? false end private # @param facts [String] facts in a wire format for decoding # @param format [String] a content-type string # @return [Puppet::Node::Facts] facts object deserialized from supplied string # @api private def convert_wire_facts(facts, format) case format when 'pson' # We unescape here because the corresponding code in Puppet::Configurer::FactHandler encodes with Puppet::Util.uri_query_encode # PSON is deprecated, but continue to accept from older agents Puppet::Node::Facts.convert_from('pson', CGI.unescape(facts)) when 'application/json' Puppet::Node::Facts.convert_from('json', CGI.unescape(facts)) else raise ArgumentError, _("Unsupported facts format") end end # Add any extra data necessary to the node. def add_node_data(node) # Merge in our server-side facts, so they can be used during compilation. node.add_server_facts(@server_facts) end # Determine which checksum to use; if agent_checksum_type is not nil, # use the first entry in it that is also in known_checksum_types. # If no match is found, return nil. def common_checksum_type(agent_checksum_type) if agent_checksum_type agent_checksum_types = agent_checksum_type.split('.').map(&:to_sym) checksum_type = agent_checksum_types.drop_while do |type| !known_checksum_types.include? type end.first end checksum_type end def get_content_uri(metadata, source, environment_path) # The static file content server doesn't know how to expand mountpoints, so # we need to do that ourselves from the actual system path of the source file. # This does that, while preserving any user-specified server or port. source_path = Pathname.new(metadata.full_path) path = source_path.relative_path_from(environment_path).to_s source_as_uri = URI.parse(Puppet::Util.uri_encode(source)) server = source_as_uri.host port = ":#{source_as_uri.port}" if source_as_uri.port "puppet://#{server}#{port}/#{path}" end # Helper method to decide if a file resource's metadata can be inlined. # Also used to profile/log reasons for not inlining. def inlineable?(resource, sources) if resource[:ensure] == 'absent' # TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining) Puppet::Util::Profiler.profile(_("Not inlining absent resource"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :absent]) { false } elsif sources.empty? # TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining) Puppet::Util::Profiler.profile(_("Not inlining resource without sources"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :no_sources]) { false } elsif !(sources.all? { |source| source =~ /^puppet:/ }) # TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining) Puppet::Util::Profiler.profile(_("Not inlining unsupported source scheme"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :unsupported_scheme]) { false } else true end end # Return true if metadata is inlineable, meaning the request's source is # for the 'modules' mount and the resolved path is of the form: # $codedir/environments/$environment/*/*/files/** def inlineable_metadata?(metadata, source, environment_path) source_as_uri = URI.parse(Puppet::Util.uri_encode(source)) location = Puppet::Module::FILETYPES['files'] !!(source_as_uri.path =~ %r{^/modules/} && metadata.full_path =~ %r{#{environment_path}/[^/]+/[^/]+/#{location}/.+}) end # Helper method to log file resources that could not be inlined because they # fall outside of an environment. def log_file_outside_environment # TRANSLATORS Inlining refers to adding additional metadata (in this case we are not inlining) Puppet::Util::Profiler.profile(_("Not inlining file outside environment"), [:compiler, :static_compile_inlining, :skipped_file_metadata, :file_outside_environment]) { true } end # Helper method to log file resources that were successfully inlined. def log_metadata_inlining # TRANSLATORS Inlining refers to adding additional metadata Puppet::Util::Profiler.profile(_("Inlining file metadata"), [:compiler, :static_compile_inlining, :inlined_file_metadata]) { true } end # Inline file metadata for static catalogs # Initially restricted to files sourced from codedir via puppet:/// uri. def inline_metadata(catalog, checksum_type) environment_path = Pathname.new File.join(Puppet[:environmentpath], catalog.environment) environment_path = Puppet::Environments::Directories.real_path(environment_path) list_of_resources = catalog.resources.find_all { |res| res.type == "File" } # TODO: get property/parameter defaults if entries are nil in the resource # For now they're hard-coded to match the File type. list_of_resources.each do |resource| sources = [resource[:source]].flatten.compact next unless inlineable?(resource, sources) # both need to handle multiple sources if resource[:recurse] == true || resource[:recurse] == 'true' || resource[:recurse] == 'remote' # Construct a hash mapping sources to arrays (list of files found recursively) of metadata options = { :environment => catalog.environment_instance, :links => resource[:links] ? resource[:links].to_sym : :manage, :checksum_type => resource[:checksum] ? resource[:checksum].to_sym : checksum_type.to_sym, :source_permissions => resource[:source_permissions] ? resource[:source_permissions].to_sym : :ignore, :recurse => true, :recurselimit => resource[:recurselimit], :max_files => resource[:max_files], :ignore => resource[:ignore], } sources_in_environment = true source_to_metadatas = {} sources.each do |source| source = Puppet::Type.type(:file).attrclass(:source).normalize(source) list_of_data = Puppet::FileServing::Metadata.indirection.search(source, options) next unless list_of_data basedir_meta = list_of_data.find { |meta| meta.relative_path == '.' } devfail "FileServing::Metadata search should always return the root search path" if basedir_meta.nil? unless inlineable_metadata?(basedir_meta, source, environment_path) # If any source is not in the environment path, skip inlining this resource. log_file_outside_environment sources_in_environment = false break end base_content_uri = get_content_uri(basedir_meta, source, environment_path) list_of_data.each do |metadata| if metadata.relative_path == '.' metadata.content_uri = base_content_uri else metadata.content_uri = "#{base_content_uri}/#{metadata.relative_path}" end end source_to_metadatas[source] = list_of_data # Optimize for returning less data if sourceselect is first if resource[:sourceselect] == 'first' || resource[:sourceselect].nil? break end end if sources_in_environment && !source_to_metadatas.empty? log_metadata_inlining catalog.recursive_metadata[resource.title] = source_to_metadatas end else options = { :environment => catalog.environment_instance, :links => resource[:links] ? resource[:links].to_sym : :manage, :checksum_type => resource[:checksum] ? resource[:checksum].to_sym : checksum_type.to_sym, :source_permissions => resource[:source_permissions] ? resource[:source_permissions].to_sym : :ignore } metadata = nil sources.each do |source| source = Puppet::Type.type(:file).attrclass(:source).normalize(source) data = Puppet::FileServing::Metadata.indirection.find(source, options) next unless data metadata = data metadata.source = source break end raise _("Could not get metadata for %{resource}") % { resource: resource[:source] } unless metadata if inlineable_metadata?(metadata, metadata.source, environment_path) metadata.content_uri = get_content_uri(metadata, metadata.source, environment_path) log_metadata_inlining # If the file is in the environment directory, we can safely inline catalog.metadata[resource.title] = metadata else # Log a profiler event that we skipped this file because it is not in an environment. log_file_outside_environment end end end end # Compile the actual catalog. def compile(node, options) if node.environment && node.environment.static_catalogs? && options[:static_catalog] && options[:code_id] # Check for errors before compiling the catalog checksum_type = common_checksum_type(options[:checksum_type]) raise Puppet::Error, _("Unable to find a common checksum type between agent '%{agent_type}' and master '%{master_type}'.") % { agent_type: options[:checksum_type], master_type: known_checksum_types } unless checksum_type end escaped_node_name = node.name.gsub(/%/, '%%') if checksum_type if node.environment escaped_node_environment = node.environment.to_s.gsub(/%/, '%%') benchmark_str = _("Compiled static catalog for %{node} in environment %{environment} in %%{seconds} seconds") % { node: escaped_node_name, environment: escaped_node_environment } profile_str = _("Compiled static catalog for %{node} in environment %{environment}") % { node: node.name, environment: node.environment } else benchmark_str = _("Compiled static catalog for %{node} in %%{seconds} seconds") % { node: escaped_node_name } profile_str = _("Compiled static catalog for %{node}") % { node: node.name } end elsif node.environment escaped_node_environment = node.environment.to_s.gsub(/%/, '%%') benchmark_str = _("Compiled catalog for %{node} in environment %{environment} in %%{seconds} seconds") % { node: escaped_node_name, environment: escaped_node_environment } profile_str = _("Compiled catalog for %{node} in environment %{environment}") % { node: node.name, environment: node.environment } else benchmark_str = _("Compiled catalog for %{node} in %%{seconds} seconds") % { node: escaped_node_name } profile_str = _("Compiled catalog for %{node}") % { node: node.name } end config = nil benchmark(:notice, benchmark_str) do compile_type = checksum_type ? :static_compile : :compile Puppet::Util::Profiler.profile(profile_str, [:compiler, compile_type, node.environment, node.name]) do begin config = Puppet::Parser::Compiler.compile(node, options[:code_id]) rescue Puppet::Error => detail Puppet.err(detail.to_s) if networked? raise ensure Puppet::Type.clear_misses unless Puppet[:always_retry_plugins] end if checksum_type && config.is_a?(model) escaped_node_name = node.name.gsub(/%/, '%%') if node.environment escaped_node_environment = node.environment.to_s.gsub(/%/, '%%') # TRANSLATORS Inlined refers to adding additional metadata benchmark_str = _("Inlined resource metadata into static catalog for %{node} in environment %{environment} in %%{seconds} seconds") % { node: escaped_node_name, environment: escaped_node_environment } # TRANSLATORS Inlined refers to adding additional metadata profile_str = _("Inlined resource metadata into static catalog for %{node} in environment %{environment}") % { node: node.name, environment: node.environment } else # TRANSLATORS Inlined refers to adding additional metadata benchmark_str = _("Inlined resource metadata into static catalog for %{node} in %%{seconds} seconds") % { node: escaped_node_name } # TRANSLATORS Inlined refers to adding additional metadata profile_str = _("Inlined resource metadata into static catalog for %{node}") % { node: node.name } end benchmark(:notice, benchmark_str) do Puppet::Util::Profiler.profile(profile_str, [:compiler, :static_compile_postprocessing, node.environment, node.name]) do inline_metadata(config, checksum_type) end end end end end config end # Use indirection to find the node associated with a given request def find_node(name, environment, transaction_uuid, configured_environment, facts) Puppet::Util::Profiler.profile(_("Found node information"), [:compiler, :find_node]) do node = nil begin node = Puppet::Node.indirection.find(name, :environment => environment, :transaction_uuid => transaction_uuid, :configured_environment => configured_environment, :facts => facts) rescue => detail message = _("Failed when searching for node %{name}: %{detail}") % { name: name, detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end # Add any external data to the node. if node add_node_data(node) end node end end # Extract the node from the request, or use the request # to find the node. def node_from_request(facts, request) node = request.options[:use_node] if node if request.remote? raise Puppet::Error, _("Invalid option use_node for a remote request") else return node end end # We rely on our authorization system to determine whether the connected # node is allowed to compile the catalog's node referenced by key. # By default the REST authorization system makes sure only the connected node # can compile his catalog. # This allows for instance monitoring systems or puppet-load to check several # node's catalog with only one certificate and a modification to auth.conf # If no key is provided we can only compile the currently connected node. name = request.key || request.node node = find_node(name, request.environment, request.options[:transaction_uuid], request.options[:configured_environment], facts) if node return node end raise ArgumentError, _("Could not find node '%{name}'; cannot compile") % { name: name } end # Initialize our server fact hash; we add these to each client, and they # won't change while we're running, so it's safe to cache the values. # # See also set_server_facts in Puppet::Server::Compiler in puppetserver. def set_server_facts @server_facts = Puppet::Node::ServerFacts.load end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/catalog/msgpack.rb
lib/puppet/indirector/catalog/msgpack.rb
# frozen_string_literal: true require_relative '../../../puppet/resource/catalog' require_relative '../../../puppet/indirector/msgpack' class Puppet::Resource::Catalog::Msgpack < Puppet::Indirector::Msgpack desc "Store catalogs as flat files, serialized using MessagePack." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/catalog/rest.rb
lib/puppet/indirector/catalog/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/resource/catalog' require_relative '../../../puppet/indirector/rest' class Puppet::Resource::Catalog::Rest < Puppet::Indirector::REST desc "Find resource catalogs over HTTP via REST." def find(request) checksum_type = if request.options[:checksum_type] request.options[:checksum_type].split('.') else Puppet[:supported_checksum_types] end session = Puppet.lookup(:http_session) api = session.route_to(:puppet) unless Puppet.settings[:skip_logging_catalog_request_destination] ip_address = begin " (#{Resolv.getaddress(api.url.host)})" rescue Resolv::ResolvError nil end Puppet.notice("Requesting catalog from #{api.url.host}:#{api.url.port}#{ip_address}") end _, catalog = api.post_catalog( request.key, facts: request.options[:facts_for_catalog], environment: request.environment.to_s, configured_environment: request.options[:configured_environment], check_environment: request.options[:check_environment], transaction_uuid: request.options[:transaction_uuid], job_uuid: request.options[:job_id], static_catalog: request.options[:static_catalog], checksum_type: checksum_type ) catalog rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 return nil unless request.options[:fail_on_404] _, body = parse_response(e.response) msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body } raise Puppet::Error, msg else raise convert_to_http_error(e.response) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/catalog/yaml.rb
lib/puppet/indirector/catalog/yaml.rb
# frozen_string_literal: true require_relative '../../../puppet/resource/catalog' require_relative '../../../puppet/indirector/yaml' class Puppet::Resource::Catalog::Yaml < Puppet::Indirector::Yaml desc "Store catalogs as flat files, serialized using YAML." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/catalog/json.rb
lib/puppet/indirector/catalog/json.rb
# frozen_string_literal: true require_relative '../../../puppet/resource/catalog' require_relative '../../../puppet/indirector/json' class Puppet::Resource::Catalog::Json < Puppet::Indirector::JSON desc "Store catalogs as flat files, serialized using JSON." def from_json(text) utf8 = text.force_encoding(Encoding::UTF_8) if utf8.valid_encoding? model.convert_from(json_format, utf8) else Puppet.info(_("Unable to deserialize catalog from json, retrying with pson")) model.convert_from('pson', text.force_encoding(Encoding::BINARY)) end end def to_json(object) object.render(json_format) rescue Puppet::Network::FormatHandler::FormatError => err if Puppet[:allow_pson_serialization] Puppet.info(_("Unable to serialize catalog to json, retrying with pson. PSON is deprecated and will be removed in a future release")) Puppet.log_exception(err, err.message, level: :debug) object.render('pson').force_encoding(Encoding::BINARY) else Puppet.info(_("Unable to serialize catalog to json, no other acceptable format")) Puppet.log_exception(err, err.message, level: :err) end end private def json_format if Puppet[:rich_data] 'rich_data_json' else 'json' end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/resource/store_configs.rb
lib/puppet/indirector/resource/store_configs.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/store_configs' require_relative '../../../puppet/indirector/resource/validator' class Puppet::Resource::StoreConfigs < Puppet::Indirector::StoreConfigs include Puppet::Resource::Validator desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' def allow_remote_requests? false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/resource/validator.rb
lib/puppet/indirector/resource/validator.rb
# frozen_string_literal: true module Puppet::Resource::Validator def validate_key(request) type, title = request.key.split('/', 2) unless type.casecmp(request.instance.type).zero? and title == request.instance.title raise Puppet::Indirector::ValidationError, _("Resource instance does not match request key") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/resource/ral.rb
lib/puppet/indirector/resource/ral.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/resource/validator' class Puppet::Resource::Ral < Puppet::Indirector::Code include Puppet::Resource::Validator desc "Manipulate resources with the resource abstraction layer. Only used internally." def allow_remote_requests? false end def find(request) # find by name res = type(request).instances.find { |o| o.name == resource_name(request) } res ||= type(request).new(:name => resource_name(request), :audit => type(request).properties.collect(&:name)) res.to_resource end def search(request) conditions = request.options.dup conditions[:name] = resource_name(request) if resource_name(request) type(request).instances.map(&:to_resource).find_all do |res| conditions.all? do |property, value| # even though `res` is an instance of Puppet::Resource, calling # `res[:name]` on it returns nil, and for some reason it is necessary # to invoke the Puppet::Resource#copy_as_resource copy constructor... res.copy_as_resource[property].to_s == value.to_s end end.sort_by(&:title) end def save(request) # In RAL-land, to "save" means to actually try to change machine state res = request.instance ral_res = res.to_ral catalog = Puppet::Resource::Catalog.new(nil, request.environment) catalog.add_resource ral_res transaction = catalog.apply [ral_res.to_resource, transaction.report] end private # {type,resource}_name: the resource name may contain slashes: # File["/etc/hosts"]. To handle, assume the type name does # _not_ have any slashes in it, and split only on the first. def type_name(request) request.key.split('/', 2)[0] end def resource_name(request) name = request.key.split('/', 2)[1] name unless name == "" end def type(request) Puppet::Type.type(type_name(request)) or raise Puppet::Error, _("Could not find type %{request_type}") % { request_type: type_name(request) } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/store_configs.rb
lib/puppet/indirector/node/store_configs.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/store_configs' require_relative '../../../puppet/node' class Puppet::Node::StoreConfigs < Puppet::Indirector::StoreConfigs desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/plain.rb
lib/puppet/indirector/node/plain.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/plain' class Puppet::Node::Plain < Puppet::Indirector::Plain desc "Always return an empty node object. Assumes you keep track of nodes in flat file manifests. You should use it when you don't have some other, functional source you want to use, as the compiler will not work without a valid node terminus. Note that class is responsible for merging the node's facts into the node instance before it is returned." # Just return an empty node. def find(request) node = super node.environment = request.environment facts = request.options[:facts].is_a?(Puppet::Node::Facts) ? request.options[:facts] : nil node.fact_merge(facts) node end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/memory.rb
lib/puppet/indirector/node/memory.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/memory' class Puppet::Node::Memory < Puppet::Indirector::Memory desc "Keep track of nodes in memory but nowhere else. This is used for one-time compiles, such as what the stand-alone `puppet` does. To use this terminus, you must load it with the data you want it to contain; it is only useful for developers and should generally not be chosen by a normal user." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/msgpack.rb
lib/puppet/indirector/node/msgpack.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/msgpack' class Puppet::Node::Msgpack < Puppet::Indirector::Msgpack desc "Store node information as flat files, serialized using MessagePack, or deserialize stored MessagePack nodes." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/rest.rb
lib/puppet/indirector/node/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/rest' class Puppet::Node::Rest < Puppet::Indirector::REST desc "Get a node via REST. Puppet agent uses this to allow the puppet master to override its environment." def find(request) session = Puppet.lookup(:http_session) api = session.route_to(:puppet) _, node = api.get_node( request.key, environment: request.environment.to_s, configured_environment: request.options[:configured_environment], transaction_uuid: request.options[:transaction_uuid] ) node rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 return nil unless request.options[:fail_on_404] _, body = parse_response(e.response) msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body } raise Puppet::Error, msg else raise convert_to_http_error(e.response) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/yaml.rb
lib/puppet/indirector/node/yaml.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/yaml' class Puppet::Node::Yaml < Puppet::Indirector::Yaml desc "Store node information as flat files, serialized using YAML, or deserialize stored YAML nodes." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/json.rb
lib/puppet/indirector/node/json.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/json' class Puppet::Node::Json < Puppet::Indirector::JSON desc "Store node information as flat files, serialized using JSON, or deserialize stored JSON nodes." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/node/exec.rb
lib/puppet/indirector/node/exec.rb
# frozen_string_literal: true require_relative '../../../puppet/node' require_relative '../../../puppet/indirector/exec' class Puppet::Node::Exec < Puppet::Indirector::Exec desc "Call an external program to get node information. See the [External Nodes](https://puppet.com/docs/puppet/latest/lang_write_functions_in_puppet.html) page for more information." include Puppet::Util def command command = Puppet[:external_nodes] raise ArgumentError, _("You must set the 'external_nodes' parameter to use the external node terminus") unless command != _("none") command.split end # Look for external node definitions. def find(request) output = super or return nil # Translate the output to ruby. result = translate(request.key, output) facts = request.options[:facts].is_a?(Puppet::Node::Facts) ? request.options[:facts] : nil # Set the requested environment if it wasn't overridden # If we don't do this it gets set to the local default result[:environment] ||= request.environment create_node(request.key, result, facts) end private # Proxy the execution, so it's easier to test. def execute(command, arguments) Puppet::Util::Execution.execute(command, arguments) end # Turn our outputted objects into a Puppet::Node instance. def create_node(name, result, facts = nil) node = Puppet::Node.new(name) [:parameters, :classes, :environment].each do |param| value = result[param] if value node.send(param.to_s + "=", value) end end node.fact_merge(facts) node end # Translate the yaml string into Ruby objects. def translate(name, output) Puppet::Util::Yaml.safe_load(output, [Symbol]).each_with_object({}) do |data, hash| case data[0] when String hash[data[0].intern] = data[1] when Symbol hash[data[0]] = data[1] else raise Puppet::Error, _("key is a %{klass}, not a string or symbol") % { klass: data[0].class } end end rescue => detail raise Puppet::Error, _("Could not load external node results for %{name}: %{detail}") % { name: name, detail: detail }, detail.backtrace end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_content/selector.rb
lib/puppet/indirector/file_content/selector.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/content' require_relative '../../../puppet/indirector/file_content' require_relative '../../../puppet/indirector/code' require_relative '../../../puppet/file_serving/terminus_selector' class Puppet::Indirector::FileContent::Selector < Puppet::Indirector::Code desc "Select the terminus based on the request" include Puppet::FileServing::TerminusSelector def get_terminus(request) indirection.terminus(select(request)) end def find(request) get_terminus(request).find(request) end def search(request) get_terminus(request).search(request) end def authorized?(request) terminus = get_terminus(request) if terminus.respond_to?(:authorized?) terminus.authorized?(request) else true end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_content/rest.rb
lib/puppet/indirector/file_content/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/content' require_relative '../../../puppet/indirector/file_content' require_relative '../../../puppet/indirector/rest' class Puppet::Indirector::FileContent::Rest < Puppet::Indirector::REST desc "Retrieve file contents via a REST HTTP interface." def find(request) content = StringIO.new content.binmode url = URI.parse(Puppet::Util.uri_encode(request.uri)) session = Puppet.lookup(:http_session) api = session.route_to(:fileserver, url: url) api.get_file_content( path: Puppet::Util.uri_unescape(url.path), environment: request.environment.to_s ) do |data| content << data end Puppet::FileServing::Content.from_binary(content.string) rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 return nil unless request.options[:fail_on_404] _, body = parse_response(e.response) msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body } raise Puppet::Error, msg else raise convert_to_http_error(e.response) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_content/file.rb
lib/puppet/indirector/file_content/file.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/content' require_relative '../../../puppet/indirector/file_content' require_relative '../../../puppet/indirector/direct_file_server' class Puppet::Indirector::FileContent::File < Puppet::Indirector::DirectFileServer desc "Retrieve file contents from disk." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_content/file_server.rb
lib/puppet/indirector/file_content/file_server.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/content' require_relative '../../../puppet/indirector/file_content' require_relative '../../../puppet/indirector/file_server' class Puppet::Indirector::FileContent::FileServer < Puppet::Indirector::FileServer desc "Retrieve file contents using Puppet's fileserver." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/report/msgpack.rb
lib/puppet/indirector/report/msgpack.rb
# frozen_string_literal: true require_relative '../../../puppet/transaction/report' require_relative '../../../puppet/indirector/msgpack' class Puppet::Transaction::Report::Msgpack < Puppet::Indirector::Msgpack desc "Store last report as a flat file, serialized using MessagePack." # Force report to be saved there def path(name, ext = '.msgpack') Puppet[:lastrunreport] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/report/processor.rb
lib/puppet/indirector/report/processor.rb
# frozen_string_literal: true require_relative '../../../puppet/transaction/report' require_relative '../../../puppet/indirector/code' require_relative '../../../puppet/reports' class Puppet::Transaction::Report::Processor < Puppet::Indirector::Code desc "Puppet's report processor. Processes the report with each of the report types listed in the 'reports' setting." def initialize Puppet.settings.use(:main, :reporting, :metrics) end def save(request) process(request.instance) end def destroy(request) processors do |mod| mod.destroy(request.key) if mod.respond_to?(:destroy) end end private # Process the report with each of the configured report types. # LAK:NOTE This isn't necessarily the best design, but it's backward # compatible and that's good enough for now. def process(report) Puppet.debug { "Received report to process from #{report.host}" } processors do |mod| Puppet.debug { "Processing report from #{report.host} with processor #{mod}" } # We have to use a dup because we're including a module in the # report. newrep = report.dup begin newrep.extend(mod) newrep.process rescue => detail Puppet.log_exception(detail, _("Report %{report} failed: %{detail}") % { report: name, detail: detail }) end end end # Handle the parsing of the reports attribute. def reports Puppet[:reports].gsub(/(^\s+)|(\s+$)/, '').split(/\s*,\s*/) end def processors(&blk) return [] if Puppet[:reports] == "none" reports.each do |name| mod = Puppet::Reports.report(name) if mod yield(mod) else Puppet.warning _("No report named '%{name}'") % { name: name } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/report/rest.rb
lib/puppet/indirector/report/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/rest' require 'semantic_puppet' class Puppet::Transaction::Report::Rest < Puppet::Indirector::REST desc "Get server report over HTTP via REST." def save(request) session = Puppet.lookup(:http_session) api = session.route_to(:report) response = api.put_report( request.key, request.instance, environment: request.environment.to_s ) content_type, body = parse_response(response) deserialize_save(content_type, body) rescue Puppet::HTTP::ResponseError => e return nil if e.response.code == 404 raise convert_to_http_error(e.response) end private def deserialize_save(content_type, body) format = Puppet::Network::FormatHandler.format_for(content_type) format.intern(Array, body) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/report/yaml.rb
lib/puppet/indirector/report/yaml.rb
# frozen_string_literal: true require_relative '../../../puppet/transaction/report' require_relative '../../../puppet/indirector/yaml' class Puppet::Transaction::Report::Yaml < Puppet::Indirector::Yaml include Puppet::Util::SymbolicFileMode desc "Store last report as a flat file, serialized using YAML." # Force report to be saved there def path(name, ext = '.yaml') Puppet[:lastrunreport] end def save(request) filename = path(request.key) mode = Puppet.settings.setting(:lastrunreport).mode unless valid_symbolic_mode?(mode) raise Puppet::DevError, _("replace_file mode: %{mode} is invalid") % { mode: mode } end mode = symbolic_mode_to_int(normalize_symbolic_mode(mode)) FileUtils.mkdir_p(File.dirname(filename)) begin Puppet::FileSystem.replace_file(filename, mode) do |fh| fh.print YAML.dump(request.instance) end rescue TypeError => detail Puppet.err _("Could not save %{indirection} %{request}: %{detail}") % { indirection: name, request: request.key, detail: detail } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/report/json.rb
lib/puppet/indirector/report/json.rb
# frozen_string_literal: true require_relative '../../../puppet/transaction/report' require_relative '../../../puppet/indirector/json' class Puppet::Transaction::Report::Json < Puppet::Indirector::JSON include Puppet::Util::SymbolicFileMode desc "Store last report as a flat file, serialized using JSON." # Force report to be saved there def path(name, ext = '.json') Puppet[:lastrunreport] end def save(request) filename = path(request.key) mode = Puppet.settings.setting(:lastrunreport).mode unless valid_symbolic_mode?(mode) raise Puppet::DevError, _("replace_file mode: %{mode} is invalid") % { mode: mode } end mode = symbolic_mode_to_int(normalize_symbolic_mode(mode)) FileUtils.mkdir_p(File.dirname(filename)) begin Puppet::FileSystem.replace_file(filename, mode) do |fh| fh.print JSON.dump(request.instance) end rescue TypeError => detail Puppet.err _("Could not save %{indirection} %{request}: %{detail}") % { indirection: name, request: request.key, detail: detail } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_metadata/selector.rb
lib/puppet/indirector/file_metadata/selector.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/metadata' require_relative '../../../puppet/indirector/file_metadata' require_relative '../../../puppet/indirector/code' require_relative '../../../puppet/file_serving/terminus_selector' class Puppet::Indirector::FileMetadata::Selector < Puppet::Indirector::Code desc "Select the terminus based on the request" include Puppet::FileServing::TerminusSelector def get_terminus(request) indirection.terminus(select(request)) end def find(request) get_terminus(request).find(request) end def search(request) get_terminus(request).search(request) end def authorized?(request) terminus = get_terminus(request) if terminus.respond_to?(:authorized?) terminus.authorized?(request) else true end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_metadata/rest.rb
lib/puppet/indirector/file_metadata/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/metadata' require_relative '../../../puppet/indirector/file_metadata' require_relative '../../../puppet/indirector/rest' class Puppet::Indirector::FileMetadata::Rest < Puppet::Indirector::REST desc "Retrieve file metadata via a REST HTTP interface." def find(request) url = URI.parse(Puppet::Util.uri_encode(request.uri)) session = Puppet.lookup(:http_session) api = session.route_to(:fileserver, url: url) _, file_metadata = api.get_file_metadata( path: Puppet::Util.uri_unescape(url.path), environment: request.environment.to_s, links: request.options[:links], checksum_type: request.options[:checksum_type], source_permissions: request.options[:source_permissions] ) file_metadata rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 return nil unless request.options[:fail_on_404] _, body = parse_response(e.response) msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body } raise Puppet::Error, msg else raise convert_to_http_error(e.response) end end def search(request) url = URI.parse(Puppet::Util.uri_encode(request.uri)) session = Puppet.lookup(:http_session) api = session.route_to(:fileserver, url: url) _, file_metadatas = api.get_file_metadatas( path: Puppet::Util.uri_unescape(url.path), environment: request.environment.to_s, recurse: request.options[:recurse], recurselimit: request.options[:recurselimit], max_files: request.options[:max_files], ignore: request.options[:ignore], links: request.options[:links], checksum_type: request.options[:checksum_type], source_permissions: request.options[:source_permissions] ) file_metadatas rescue Puppet::HTTP::ResponseError => e # since it's search, return empty array instead of nil return [] if e.response.code == 404 raise convert_to_http_error(e.response) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_metadata/file.rb
lib/puppet/indirector/file_metadata/file.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/metadata' require_relative '../../../puppet/indirector/file_metadata' require_relative '../../../puppet/indirector/direct_file_server' class Puppet::Indirector::FileMetadata::File < Puppet::Indirector::DirectFileServer desc "Retrieve file metadata directly from the local filesystem." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_metadata/http.rb
lib/puppet/indirector/file_metadata/http.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/http_metadata' require_relative '../../../puppet/indirector/generic_http' require_relative '../../../puppet/indirector/file_metadata' require 'net/http' class Puppet::Indirector::FileMetadata::Http < Puppet::Indirector::GenericHttp desc "Retrieve file metadata from a remote HTTP server." include Puppet::FileServing::TerminusHelper def find(request) checksum_type = request.options[:checksum_type] # See URL encoding comment in Puppet::Type::File::ParamSource#chunk_file_from_source uri = URI(request.uri) client = Puppet.runtime[:http] head = client.head(uri, options: { include_system_store: true }) return create_httpmetadata(head, checksum_type) if head.success? case head.code when 403, 405 # AMZ presigned URL and puppetserver may return 403 # instead of 405. Fallback to partial get get = partial_get(client, uri) return create_httpmetadata(get, checksum_type) if get.success? end nil end def search(request) raise Puppet::Error, _("cannot lookup multiple files") end private def partial_get(client, uri) client.get(uri, headers: { 'Range' => 'bytes=0-0' }, options: { include_system_store: true }) end def create_httpmetadata(http_request, checksum_type) metadata = Puppet::FileServing::HttpMetadata.new(http_request) metadata.checksum_type = checksum_type if checksum_type metadata.collect metadata end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_metadata/file_server.rb
lib/puppet/indirector/file_metadata/file_server.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/metadata' require_relative '../../../puppet/indirector/file_metadata' require_relative '../../../puppet/indirector/file_server' class Puppet::Indirector::FileMetadata::FileServer < Puppet::Indirector::FileServer desc "Retrieve file metadata using Puppet's fileserver." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/data_binding/hiera.rb
lib/puppet/indirector/data_binding/hiera.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/hiera' require 'hiera/scope' class Puppet::DataBinding::Hiera < Puppet::Indirector::Hiera desc "Retrieve data using Hiera." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/data_binding/none.rb
lib/puppet/indirector/data_binding/none.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/none' class Puppet::DataBinding::None < Puppet::Indirector::None desc "A Dummy terminus that always throws :no_such_key for data lookups." def find(request) throw :no_such_key end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/store_configs.rb
lib/puppet/indirector/facts/store_configs.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/store_configs' class Puppet::Node::Facts::StoreConfigs < Puppet::Indirector::StoreConfigs desc 'Part of the "storeconfigs" feature. Should not be directly set by end users.' def allow_remote_requests? false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/memory.rb
lib/puppet/indirector/facts/memory.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/memory' class Puppet::Node::Facts::Memory < Puppet::Indirector::Memory desc "Keep track of facts in memory but nowhere else. This is used for one-time compiles, such as what the stand-alone `puppet` does. To use this terminus, you must load it with the data you want it to contain." end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/rest.rb
lib/puppet/indirector/facts/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/rest' class Puppet::Node::Facts::Rest < Puppet::Indirector::REST desc "Find and save facts about nodes over HTTP via REST." def find(request) session = Puppet.lookup(:http_session) api = session.route_to(:puppet) _, facts = api.get_facts( request.key, environment: request.environment.to_s ) facts rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 return nil unless request.options[:fail_on_404] _, body = parse_response(e.response) msg = _("Find %{uri} resulted in 404 with the message: %{body}") % { uri: elide(e.response.url.path, 100), body: body } raise Puppet::Error, msg else raise convert_to_http_error(e.response) end end def save(request) raise ArgumentError, _("PUT does not accept options") unless request.options.empty? session = Puppet.lookup(:http_session) api = session.route_to(:puppet) api.put_facts( request.key, facts: request.instance, environment: request.environment.to_s ) # preserve existing behavior nil rescue Puppet::HTTP::ResponseError => e # always raise even if fail_on_404 is false raise convert_to_http_error(e.response) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/yaml.rb
lib/puppet/indirector/facts/yaml.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/yaml' require_relative '../../../puppet/indirector/fact_search' class Puppet::Node::Facts::Yaml < Puppet::Indirector::Yaml desc "Store client facts as flat files, serialized using YAML, or return deserialized facts from disk." include Puppet::Indirector::FactSearch def search(request) node_names = [] Dir.glob(yaml_dir_path).each do |file| facts = load_file(file) if facts && node_matches?(facts, request.options) node_names << facts.name end end node_names end private # Return the path to a given node's file. def yaml_dir_path base = Puppet.run_mode.server? ? Puppet[:yamldir] : Puppet[:clientyamldir] File.join(base, 'facts', '*.yaml') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/json.rb
lib/puppet/indirector/facts/json.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/json' require_relative '../../../puppet/indirector/fact_search' class Puppet::Node::Facts::Json < Puppet::Indirector::JSON desc "Store client facts as flat files, serialized using JSON, or return deserialized facts from disk." include Puppet::Indirector::FactSearch def search(request) node_names = [] Dir.glob(json_dir_path).each do |file| facts = load_json_from_file(file, '') if facts && node_matches?(facts, request.options) node_names << facts.name end end node_names end private def json_dir_path path("*") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/network_device.rb
lib/puppet/indirector/facts/network_device.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/code' class Puppet::Node::Facts::NetworkDevice < Puppet::Indirector::Code desc "Retrieve facts from a network device." def allow_remote_requests? false end # Look a device's facts up through the current device. def find(request) result = Puppet::Node::Facts.new(request.key, Puppet::Util::NetworkDevice.current.facts) result.add_local_facts result.sanitize result end def destroy(facts) raise Puppet::DevError, _("You cannot destroy facts in the code store; it is only used for getting facts from a remote device") end def save(facts) raise Puppet::DevError, _("You cannot save facts to the code store; it is only used for getting facts from a remote device") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/facts/facter.rb
lib/puppet/indirector/facts/facter.rb
# frozen_string_literal: true require_relative '../../../puppet/node/facts' require_relative '../../../puppet/indirector/code' class Puppet::Node::Facts::Facter < Puppet::Indirector::Code desc "Retrieve facts from Facter. This provides a somewhat abstract interface between Puppet and Facter. It's only `somewhat` abstract because it always returns the local host's facts, regardless of what you attempt to find." def allow_remote_requests? false end def destroy(facts) raise Puppet::DevError, _('You cannot destroy facts in the code store; it is only used for getting facts from Facter') end def save(facts) raise Puppet::DevError, _('You cannot save facts to the code store; it is only used for getting facts from Facter') end # Lookup a host's facts up in Facter. def find(request) Puppet.runtime[:facter].reset # Note: we need to setup puppet's external search paths before adding the puppetversion # fact. This is because in Facter 2.x, the first `Puppet.runtime[:facter].add` causes Facter to create # its directory loaders which cannot be changed, meaning other external facts won't # be resolved. (PUP-4607) self.class.setup_external_search_paths(request) self.class.setup_search_paths(request) # Initialize core Puppet facts, such as puppetversion Puppet.initialize_facts result = if request.options[:resolve_options] raise(Puppet::Error, _("puppet facts show requires version 4.0.40 or greater of Facter.")) unless Facter.respond_to?(:resolve) find_with_options(request) elsif Puppet[:include_legacy_facts] # to_hash returns both structured and legacy facts Puppet::Node::Facts.new(request.key, Puppet.runtime[:facter].to_hash) else # resolve does not return legacy facts unless requested facts = Puppet.runtime[:facter].resolve('') # some versions of Facter 4 return a Facter::FactCollection instead of # a Hash, breaking API compatibility, so force a hash using `to_h` Puppet::Node::Facts.new(request.key, facts.to_h) end result.add_local_facts unless request.options[:resolve_options] result.sanitize result end def self.setup_search_paths(request) # Add any per-module fact directories to facter's search path dirs = request.environment.modulepath.collect do |dir| %w[lib plugins].map do |subdirectory| Dir.glob("#{dir}/*/#{subdirectory}/facter") end end.flatten + Puppet[:factpath].split(File::PATH_SEPARATOR) dirs = dirs.select do |dir| next false unless FileTest.directory?(dir) # Even through we no longer directly load facts in the terminus, # print out each .rb in the facts directory as module # developers may find that information useful for debugging purposes if Puppet::Util::Log.sendlevel?(:info) Puppet.info _("Loading facts") Dir.glob("#{dir}/*.rb").each do |file| Puppet.debug { "Loading facts from #{file}" } end end true end dirs << request.options[:custom_dir] if request.options[:custom_dir] Puppet.runtime[:facter].search(*dirs) end def self.setup_external_search_paths(request) # Add any per-module external fact directories to facter's external search path dirs = [] request.environment.modules.each do |m| next unless m.has_external_facts? dir = m.plugin_fact_directory Puppet.debug { "Loading external facts from #{dir}" } dirs << dir end # Add system external fact directory if it exists if FileTest.directory?(Puppet[:pluginfactdest]) dir = Puppet[:pluginfactdest] Puppet.debug { "Loading external facts from #{dir}" } dirs << dir end dirs << request.options[:external_dir] if request.options[:external_dir] Puppet.runtime[:facter].search_external dirs end private def find_with_options(request) options = request.options options_for_facter = ''.dup options_for_facter += options[:user_query].join(' ') options_for_facter += " --config #{options[:config_file]}" if options[:config_file] options_for_facter += " --show-legacy" if options[:show_legacy] options_for_facter += " --no-block" if options[:no_block] == false options_for_facter += " --no-cache" if options[:no_cache] == false options_for_facter += " --timing" if options[:timing] Puppet::Node::Facts.new(request.key, Puppet.runtime[:facter].resolve(options_for_facter)) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_bucket_file/selector.rb
lib/puppet/indirector/file_bucket_file/selector.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/code' module Puppet::FileBucketFile class Selector < Puppet::Indirector::Code desc "Select the terminus based on the request" def select(request) if request.protocol == 'https' :rest else :file end end def get_terminus(request) indirection.terminus(select(request)) end def head(request) get_terminus(request).head(request) end def find(request) get_terminus(request).find(request) end def save(request) get_terminus(request).save(request) end def search(request) get_terminus(request).search(request) end def destroy(request) get_terminus(request).destroy(request) end def authorized?(request) terminus = get_terminus(request) if terminus.respond_to?(:authorized?) terminus.authorized?(request) else true end end def validate_key(request) get_terminus(request).validate(request) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_bucket_file/rest.rb
lib/puppet/indirector/file_bucket_file/rest.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/rest' require_relative '../../../puppet/file_bucket/file' module Puppet::FileBucketFile class Rest < Puppet::Indirector::REST desc "This is a REST based mechanism to send/retrieve file to/from the filebucket" def head(request) session = Puppet.lookup(:http_session) api = session.route_to(:puppet) api.head_filebucket_file( request.key, environment: request.environment.to_s, bucket_path: request.options[:bucket_path] ) rescue Puppet::HTTP::ResponseError => e return nil if e.response.code == 404 raise convert_to_http_error(e.response) end def find(request) session = Puppet.lookup(:http_session) api = session.route_to(:puppet) _, filebucket_file = api.get_filebucket_file( request.key, environment: request.environment.to_s, bucket_path: request.options[:bucket_path], diff_with: request.options[:diff_with], list_all: request.options[:list_all], fromdate: request.options[:fromdate], todate: request.options[:todate] ) filebucket_file rescue Puppet::HTTP::ResponseError => e raise convert_to_http_error(e.response) end def save(request) session = Puppet.lookup(:http_session) api = session.route_to(:puppet) api.put_filebucket_file( request.key, body: request.instance.render, environment: request.environment.to_s ) rescue Puppet::HTTP::ResponseError => e raise convert_to_http_error(e.response) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/file_bucket_file/file.rb
lib/puppet/indirector/file_bucket_file/file.rb
# frozen_string_literal: true require_relative '../../../puppet/indirector/code' require_relative '../../../puppet/file_bucket/file' require_relative '../../../puppet/util/checksums' require_relative '../../../puppet/util/diff' require 'fileutils' module Puppet::FileBucketFile class File < Puppet::Indirector::Code include Puppet::Util::Checksums include Puppet::Util::Diff desc "Store files in a directory set based on their checksums." def find(request) request.options[:bucket_path] ||= Puppet[:bucketdir] # If filebucket mode is 'list' if request.options[:list_all] return nil unless ::File.exist?(request.options[:bucket_path]) return list(request) end checksum, files_original_path = request_to_checksum_and_path(request) contents_file = path_for(request.options[:bucket_path], checksum, 'contents') paths_file = path_for(request.options[:bucket_path], checksum, 'paths') if Puppet::FileSystem.exist?(contents_file) && matches(paths_file, files_original_path) if request.options[:diff_with] other_contents_file = path_for(request.options[:bucket_path], request.options[:diff_with], 'contents') raise _("could not find diff_with %{diff}") % { diff: request.options[:diff_with] } unless Puppet::FileSystem.exist?(other_contents_file) raise _("Unable to diff on this platform") unless Puppet[:diff] != "" diff(Puppet::FileSystem.path_string(contents_file), Puppet::FileSystem.path_string(other_contents_file)) else # TRANSLATORS "FileBucket" should not be translated Puppet.info _("FileBucket read %{checksum}") % { checksum: checksum } model.new(Puppet::FileSystem.binread(contents_file)) end else nil end end def list(request) if request.remote? raise Puppet::Error, _("Listing remote file buckets is not allowed") end fromdate = request.options[:fromdate] || "0:0:0 1-1-1970" todate = request.options[:todate] || Time.now.strftime("%F %T") begin to = Time.parse(todate) rescue ArgumentError raise Puppet::Error, _("Error while parsing 'todate'") end begin from = Time.parse(fromdate) rescue ArgumentError raise Puppet::Error, _("Error while parsing 'fromdate'") end # Setting hash's default value to [], needed by the following loop bucket = Hash.new { [] } msg = ''.dup # Get all files with mtime between 'from' and 'to' Pathname.new(request.options[:bucket_path]).find { |item| next unless item.file? and item.basename.to_s == "paths" filenames = item.read.strip.split("\n") filestat = Time.parse(item.stat.mtime.to_s) next unless from <= filestat and filestat <= to filenames.each do |filename| bucket[filename] += [[item.stat.mtime, item.parent.basename]] end } # Sort the results bucket.each { |_filename, contents| contents.sort_by! do |item| # NOTE: Ruby 2.4 may reshuffle item order even if the keys in sequence are sorted already item[0] end } # Build the output message. Sorted by names then by dates bucket.sort.each { |filename, contents| contents.each { |mtime, chksum| date = mtime.strftime("%F %T") msg += "#{chksum} #{date} #{filename}\n" } } model.new(msg) end def head(request) checksum, files_original_path = request_to_checksum_and_path(request) contents_file = path_for(request.options[:bucket_path], checksum, 'contents') paths_file = path_for(request.options[:bucket_path], checksum, 'paths') Puppet::FileSystem.exist?(contents_file) && matches(paths_file, files_original_path) end def save(request) instance = request.instance _, files_original_path = request_to_checksum_and_path(request) contents_file = path_for(instance.bucket_path, instance.checksum_data, 'contents') paths_file = path_for(instance.bucket_path, instance.checksum_data, 'paths') save_to_disk(instance, files_original_path, contents_file, paths_file) # don't echo the request content back to the agent model.new('') end def validate_key(request) # There are no ACLs on filebucket files so validating key is not important end private # @param paths_file [Object] Opaque file path # @param files_original_path [String] # def matches(paths_file, files_original_path) # Puppet will have already written the paths_file in the systems encoding # given its possible that request.options[:bucket_path] or Puppet[:bucketdir] # contained characters in an encoding that are not represented the # same way when the bytes are decoded as UTF-8, continue using system encoding Puppet::FileSystem.open(paths_file, 0o640, 'a+:external') do |f| path_match(f, files_original_path) end end def path_match(file_handle, files_original_path) return true unless files_original_path # if no path was provided, it's a match file_handle.rewind file_handle.each_line do |line| return true if line.chomp == files_original_path end false end # @param bucket_file [Puppet::FileBucket::File] IO object representing # content to back up # @param files_original_path [String] Path to original source file on disk # @param contents_file [Pathname] Opaque file path to intended backup # location # @param paths_file [Pathname] Opaque file path to file containing source # file paths on disk # @return [void] # @raise [Puppet::FileBucket::BucketError] on possible sum collision between # existing and new backup # @api private def save_to_disk(bucket_file, files_original_path, contents_file, paths_file) Puppet::Util.withumask(0o007) do unless Puppet::FileSystem.dir_exist?(paths_file) Puppet::FileSystem.dir_mkpath(paths_file) end # Puppet will have already written the paths_file in the systems encoding # given its possible that request.options[:bucket_path] or Puppet[:bucketdir] # contained characters in an encoding that are not represented the # same way when the bytes are decoded as UTF-8, continue using system encoding Puppet::FileSystem.exclusive_open(paths_file, 0o640, 'a+:external') do |f| if Puppet::FileSystem.exist?(contents_file) if verify_identical_file(contents_file, bucket_file) # TRANSLATORS "FileBucket" should not be translated Puppet.info _("FileBucket got a duplicate file %{file_checksum}") % { file_checksum: bucket_file.checksum } # Don't touch the contents file on Windows, since we can't update the # mtime of read-only files there. unless Puppet::Util::Platform.windows? Puppet::FileSystem.touch(contents_file) end elsif contents_file_matches_checksum?(contents_file, bucket_file.checksum_data, bucket_file.checksum_type) # If the contents or sizes don't match, but the checksum does, # then we've found a conflict (potential hash collision). # Unlikely, but quite bad. Don't remove the file in case it's # needed, but ask the user to validate. # Note: Don't print the full path to the bucket file in the # exception to avoid disclosing file system layout on server. # TRANSLATORS "FileBucket" should not be translated Puppet.err(_("Unable to verify existing FileBucket backup at '%{path}'.") % { path: contents_file.to_path }) raise Puppet::FileBucket::BucketError, _("Existing backup and new file have different content but same checksum, %{value}. Verify existing backup and remove if incorrect.") % { value: bucket_file.checksum } else # PUP-1334 If the contents_file exists but does not match its # checksum, our backup has been corrupted. Warn about overwriting # it, and proceed with new backup. Puppet.warning(_("Existing backup does not match its expected sum, %{sum}. Overwriting corrupted backup.") % { sum: bucket_file.checksum }) copy_bucket_file_to_contents_file(contents_file, bucket_file) end else copy_bucket_file_to_contents_file(contents_file, bucket_file) end unless path_match(f, files_original_path) f.seek(0, IO::SEEK_END) f.puts(files_original_path) end end end end def request_to_checksum_and_path(request) checksum_type, checksum, path = request.key.split(%r{/}, 3) if path == '' # Treat "md5/<checksum>/" like "md5/<checksum>" path = nil end raise ArgumentError, _("Unsupported checksum type %{checksum_type}") % { checksum_type: checksum_type.inspect } if checksum_type != Puppet[:digest_algorithm] expected = method(checksum_type + "_hex_length").call raise _("Invalid checksum %{checksum}") % { checksum: checksum.inspect } if checksum !~ /^[0-9a-f]{#{expected}}$/ [checksum, path] end # @return [Object] Opaque path as constructed by the Puppet::FileSystem # def path_for(bucket_path, digest, subfile = nil) bucket_path ||= Puppet[:bucketdir] dir = ::File.join(digest[0..7].split("")) basedir = ::File.join(bucket_path, dir, digest) Puppet::FileSystem.pathname(subfile ? ::File.join(basedir, subfile) : basedir) end # @param contents_file [Pathname] Opaque file path to intended backup # location # @param bucket_file [Puppet::FileBucket::File] IO object representing # content to back up # @return [Boolean] whether the data in contents_file is of the same size # and content as that in the bucket_file # @api private def verify_identical_file(contents_file, bucket_file) (bucket_file.to_binary.bytesize == Puppet::FileSystem.size(contents_file)) && (bucket_file.stream() { |s| Puppet::FileSystem.compare_stream(contents_file, s) }) end # @param contents_file [Pathname] Opaque file path to intended backup # location # @param expected_checksum_data [String] expected value of checksum of type # checksum_type # @param checksum_type [String] type of check sum of checksum_data, ie "md5" # @return [Boolean] whether the checksum of the contents_file matches the # supplied checksum # @api private def contents_file_matches_checksum?(contents_file, expected_checksum_data, checksum_type) contents_file_checksum_data = Puppet::Util::Checksums.method(:"#{checksum_type}_file").call(contents_file.to_path) contents_file_checksum_data == expected_checksum_data end # @param contents_file [Pathname] Opaque file path to intended backup # location # @param bucket_file [Puppet::FileBucket::File] IO object representing # content to back up # @return [void] # @api private def copy_bucket_file_to_contents_file(contents_file, bucket_file) Puppet::FileSystem.replace_file(contents_file, 0o440) do |of| # PUP-1044 writes all of the contents bucket_file.stream() do |src| FileUtils.copy_stream(src, of) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/issues.rb
lib/puppet/pops/issues.rb
# frozen_string_literal: true # Defines classes to deal with issues, and message formatting and defines constants with Issues. # @api public # module Puppet::Pops module Issues # Describes an issue, and can produce a message for an occurrence of the issue. # class Issue # The issue code # @return [Symbol] attr_reader :issue_code # A block producing the message # @return [Proc] attr_reader :message_block # Names that must be bound in an occurrence of the issue to be able to produce a message. # These are the names in addition to requirements stipulated by the Issue formatter contract; i.e. :label`, # and `:semantic`. # attr_reader :arg_names # If this issue can have its severity lowered to :warning, :deprecation, or :ignored attr_writer :demotable # Configures the Issue with required arguments (bound by occurrence), and a block producing a message. def initialize issue_code, *args, &block @issue_code = issue_code @message_block = block @arg_names = args @demotable = true end # Returns true if it is allowed to demote this issue def demotable? @demotable end # Formats a message for an occurrence of the issue with argument bindings passed in a hash. # The hash must contain a LabelProvider bound to the key `label` and the semantic model element # bound to the key `semantic`. All required arguments as specified by `arg_names` must be bound # in the given `hash`. # @api public # def format(hash = {}) # Create a Message Data where all hash keys become methods for convenient interpolation # in issue text. msgdata = MessageData.new(*arg_names) begin # Evaluate the message block in the msg data's binding msgdata.format(hash, &message_block) rescue StandardError => e raise RuntimeError, _("Error while reporting issue: %{code}. %{message}") % { code: issue_code, message: e.message }, caller end end end # Provides a binding of arguments passed to Issue.format to method names available # in the issue's message producing block. # @api private # class MessageData def initialize *argnames singleton = class << self; self end argnames.each do |name| singleton.send(:define_method, name) do @data[name] end end end def format(hash, &block) @data = hash instance_eval(&block) end # Obtains the label provider given as a key `:label` in the hash passed to #format. The label provider is # return if no arguments are given. If given an argument, returns the result of calling #label on the label # provider. # # @param args [Object] one object to obtain a label for or zero arguments to obtain the label provider # @return [LabelProvider,String] the label provider or label depending on if an argument is given or not # @raise [Puppet::Error] if no label provider is found def label(*args) args.empty? ? label_provider : label_provider.label(args[0]) end # Returns the label provider given as key `:label` in the hash passed to #format. # @return [LabelProvider] the label provider # @raise [Puppet::Error] if no label provider is found def label_provider label_provider = @data[:label] # TRANSLATORS ":label" is a keyword and should not be translated raise Puppet::Error, _('Label provider key :label must be set to produce the text of the message!') unless label_provider label_provider end # Returns the label provider given as a key in the hash passed to #format. # def semantic # TRANSLATORS ":semantic" is a keyword and should not be translated raise Puppet::Error, _('Label provider key :semantic must be set to produce the text of the message!') unless @data[:semantic] @data[:semantic] end end # Defines an issue with the given `issue_code`, additional required parameters, and a block producing a message. # The block is evaluated in the context of a MessageData which provides convenient access to all required arguments # via accessor methods. In addition to accessors for specified arguments, these are also available: # * `label` - a `LabelProvider` that provides human understandable names for model elements and production of article (a/an/the). # * `semantic` - the model element for which the issue is reported # # @param issue_code [Symbol] the issue code for the issue used as an identifier, should be the same as the constant # the issue is bound to. # @param args [Symbol] required arguments that must be passed when formatting the message, may be empty # @param block [Proc] a block producing the message string, evaluated in a MessageData scope. The produced string # should not end with a period as additional information may be appended. # # @see MessageData # @api public # def self.issue(issue_code, *args, &block) Issue.new(issue_code, *args, &block) end # Creates a non demotable issue. # @see Issue.issue # def self.hard_issue(issue_code, *args, &block) result = Issue.new(issue_code, *args, &block) result.demotable = false result end # @comment Here follows definitions of issues. The intent is to provide a list from which yardoc can be generated # containing more detailed information / explanation of the issue. # These issues are set as constants, but it is unfortunately not possible for the created object to easily know which # name it is bound to. Instead the constant has to be repeated. (Alternatively, it could be done by instead calling # #const_set on the module, but the extra work required to get yardoc output vs. the extra effort to repeat the name # twice makes it not worth it (if doable at all, since there is no tag to artificially construct a constant, and # the parse tag does not produce any result for a constant assignment). # This is allowed (3.1) and has not yet been deprecated. # @todo configuration # NAME_WITH_HYPHEN = issue :NAME_WITH_HYPHEN, :name do _("%{issue} may not have a name containing a hyphen. The name '%{name}' is not legal") % { issue: label.a_an_uc(semantic), name: name } end # When a variable name contains a hyphen and these are illegal. # It is possible to control if a hyphen is legal in a name or not using the setting TODO # @todo describe the setting # @api public # @todo configuration if this is error or warning # VAR_WITH_HYPHEN = issue :VAR_WITH_HYPHEN, :name do _("A variable name may not contain a hyphen. The name '%{name}' is not legal") % { name: name } end # A class, definition, or node may only appear at top level or inside other classes # @todo Is this really true for nodes? Can they be inside classes? Isn't that too late? # @api public # NOT_TOP_LEVEL = hard_issue :NOT_TOP_LEVEL do _("Classes, definitions, and nodes may only appear at toplevel or inside other classes") end NOT_ABSOLUTE_TOP_LEVEL = hard_issue :NOT_ABSOLUTE_TOP_LEVEL do _("%{value} may only appear at toplevel") % { value: label.a_an_uc(semantic) } end CROSS_SCOPE_ASSIGNMENT = hard_issue :CROSS_SCOPE_ASSIGNMENT, :name do _("Illegal attempt to assign to '%{name}'. Cannot assign to variables in other namespaces") % { name: name } end # Assignment can only be made to certain types of left hand expressions such as variables. ILLEGAL_ASSIGNMENT = hard_issue :ILLEGAL_ASSIGNMENT do _("Illegal attempt to assign to '%{value}'. Not an assignable reference") % { value: label.a_an(semantic) } end # Variables are immutable, cannot reassign in the same assignment scope ILLEGAL_REASSIGNMENT = hard_issue :ILLEGAL_REASSIGNMENT, :name do if Validation::Checker4_0::RESERVED_PARAMETERS[name] _("Cannot reassign built in (or already assigned) variable '$%{var}'") % { var: name } else _("Cannot reassign variable '$%{var}'") % { var: name } end end # Variables facts and trusted ILLEGAL_RESERVED_ASSIGNMENT = hard_issue :ILLEGAL_RESERVED_ASSIGNMENT, :name do _("Attempt to assign to a reserved variable name: '$%{var}'") % { var: name } end # Assignment cannot be made to numeric match result variables ILLEGAL_NUMERIC_ASSIGNMENT = issue :ILLEGAL_NUMERIC_ASSIGNMENT, :varname do _("Illegal attempt to assign to the numeric match result variable '$%{var}'. Numeric variables are not assignable") % { var: varname } end # Assignment can only be made to certain types of left hand expressions such as variables. ILLEGAL_ASSIGNMENT_CONTEXT = hard_issue :ILLEGAL_ASSIGNMENT_CONTEXT do _("Assignment not allowed here") end # parameters cannot have numeric names, clashes with match result variables ILLEGAL_NUMERIC_PARAMETER = issue :ILLEGAL_NUMERIC_PARAMETER, :name do _("The numeric parameter name '$%{name}' cannot be used (clashes with numeric match result variables)") % { name: name } end ILLEGAL_NONLITERAL_PARAMETER_TYPE = issue :ILLEGAL_NONLITERAL_PARAMETER_TYPE, :name, :type_class do _("The parameter '$%{name}' must be a literal type, not %{type_class}") % { name: name, type_class: label.a_an(type_class) } end # In certain versions of Puppet it may be allowed to assign to a not already assigned key # in an array or a hash. This is an optional validation that may be turned on to prevent accidental # mutation. # ILLEGAL_INDEXED_ASSIGNMENT = issue :ILLEGAL_INDEXED_ASSIGNMENT do _("Illegal attempt to assign via [index/key]. Not an assignable reference") end # When indexed assignment ($x[]=) is allowed, the leftmost expression must be # a variable expression. # ILLEGAL_ASSIGNMENT_VIA_INDEX = hard_issue :ILLEGAL_ASSIGNMENT_VIA_INDEX do _("Illegal attempt to assign to %{value} via [index/key]. Not an assignable reference") % { value: label.a_an(semantic) } end ILLEGAL_MULTI_ASSIGNMENT_SIZE = hard_issue :ILLEGAL_MULTI_ASSIGNMENT_SIZE, :expected, :actual do _("Mismatched number of assignable entries and values, expected %{expected}, got %{actual}") % { expected: expected, actual: actual } end MISSING_MULTI_ASSIGNMENT_KEY = hard_issue :MISSING_MULTI_ASSIGNMENT_KEY, :key do _("No value for required key '%{key}' in assignment to variables from hash") % { key: key } end MISSING_MULTI_ASSIGNMENT_VARIABLE = hard_issue :MISSING_MULTI_ASSIGNMENT_VARIABLE, :name do _("No value for required variable '$%{name}' in assignment to variables from class reference") % { name: name } end APPENDS_DELETES_NO_LONGER_SUPPORTED = hard_issue :APPENDS_DELETES_NO_LONGER_SUPPORTED, :operator do _("The operator '%{operator}' is no longer supported. See http://links.puppet.com/remove-plus-equals") % { operator: operator } end # For unsupported operators (e.g. += and -= in puppet 4). # UNSUPPORTED_OPERATOR = hard_issue :UNSUPPORTED_OPERATOR, :operator do _("The operator '%{operator}' is not supported.") % { operator: operator } end # For operators that are not supported in specific contexts (e.g. '* =>' in # resource defaults) # UNSUPPORTED_OPERATOR_IN_CONTEXT = hard_issue :UNSUPPORTED_OPERATOR_IN_CONTEXT, :operator do _("The operator '%{operator}' in %{value} is not supported.") % { operator: operator, value: label.a_an(semantic) } end # For non applicable operators (e.g. << on Hash). # OPERATOR_NOT_APPLICABLE = hard_issue :OPERATOR_NOT_APPLICABLE, :operator, :left_value do _("Operator '%{operator}' is not applicable to %{left}.") % { operator: operator, left: label.a_an(left_value) } end OPERATOR_NOT_APPLICABLE_WHEN = hard_issue :OPERATOR_NOT_APPLICABLE_WHEN, :operator, :left_value, :right_value do _("Operator '%{operator}' is not applicable to %{left} when right side is %{right}.") % { operator: operator, left: label.a_an(left_value), right: label.a_an(right_value) } end COMPARISON_NOT_POSSIBLE = hard_issue :COMPARISON_NOT_POSSIBLE, :operator, :left_value, :right_value, :detail do _("Comparison of: %{left} %{operator} %{right}, is not possible. Caused by '%{detail}'.") % { left: label(left_value), operator: operator, right: label(right_value), detail: detail } end MATCH_NOT_REGEXP = hard_issue :MATCH_NOT_REGEXP, :detail do _("Can not convert right match operand to a regular expression. Caused by '%{detail}'.") % { detail: detail } end MATCH_NOT_STRING = hard_issue :MATCH_NOT_STRING, :left_value do _("Left match operand must result in a String value. Got %{left}.") % { left: label.a_an(left_value) } end # Some expressions/statements may not produce a value (known as right-value, or rvalue). # This may vary between puppet versions. # NOT_RVALUE = issue :NOT_RVALUE do _("Invalid use of expression. %{value} does not produce a value") % { value: label.a_an_uc(semantic) } end # Appending to attributes is only allowed in certain types of resource expressions. # ILLEGAL_ATTRIBUTE_APPEND = hard_issue :ILLEGAL_ATTRIBUTE_APPEND, :name, :parent do _("Illegal +> operation on attribute %{attr}. This operator can not be used in %{expression}") % { attr: name, expression: label.a_an(parent) } end ILLEGAL_NAME = hard_issue :ILLEGAL_NAME, :name do _("Illegal name. The given name '%{name}' does not conform to the naming rule /^((::)?[a-z_]\\w*)(::[a-z]\\w*)*$/") % { name: name } end ILLEGAL_SINGLE_TYPE_MAPPING = hard_issue :ILLEGAL_TYPE_MAPPING, :expression do _("Illegal type mapping. Expected a Type on the left side, got %{expression}") % { expression: label.a_an_uc(semantic) } end ILLEGAL_REGEXP_TYPE_MAPPING = hard_issue :ILLEGAL_TYPE_MAPPING, :expression do _("Illegal type mapping. Expected a Tuple[Regexp,String] on the left side, got %{expression}") % { expression: label.a_an_uc(semantic) } end ILLEGAL_PARAM_NAME = hard_issue :ILLEGAL_PARAM_NAME, :name do _("Illegal parameter name. The given name '%{name}' does not conform to the naming rule /^[a-z_]\\w*$/") % { name: name } end ILLEGAL_VAR_NAME = hard_issue :ILLEGAL_VAR_NAME, :name do _("Illegal variable name, The given name '%{name}' does not conform to the naming rule /^((::)?[a-z]\\w*)*((::)?[a-z_]\\w*)$/") % { name: name } end ILLEGAL_NUMERIC_VAR_NAME = hard_issue :ILLEGAL_NUMERIC_VAR_NAME, :name do _("Illegal numeric variable name, The given name '%{name}' must be a decimal value if it starts with a digit 0-9") % { name: name } end # In case a model is constructed programmatically, it must create valid type references. # ILLEGAL_CLASSREF = hard_issue :ILLEGAL_CLASSREF, :name do _("Illegal type reference. The given name '%{name}' does not conform to the naming rule") % { name: name } end # This is a runtime issue - storeconfigs must be on in order to collect exported. This issue should be # set to :ignore when just checking syntax. # @todo should be a :warning by default # RT_NO_STORECONFIGS = issue :RT_NO_STORECONFIGS do _("You cannot collect exported resources without storeconfigs being set; the collection will be ignored") end # This is a runtime issue - storeconfigs must be on in order to export a resource. This issue should be # set to :ignore when just checking syntax. # @todo should be a :warning by default # RT_NO_STORECONFIGS_EXPORT = issue :RT_NO_STORECONFIGS_EXPORT do _("You cannot collect exported resources without storeconfigs being set; the export is ignored") end # A hostname may only contain letters, digits, '_', '-', and '.'. # ILLEGAL_HOSTNAME_CHARS = hard_issue :ILLEGAL_HOSTNAME_CHARS, :hostname do _("The hostname '%{hostname}' contains illegal characters (only letters, digits, '_', '-', and '.' are allowed)") % { hostname: hostname } end # A hostname may only contain letters, digits, '_', '-', and '.'. # ILLEGAL_HOSTNAME_INTERPOLATION = hard_issue :ILLEGAL_HOSTNAME_INTERPOLATION do _("An interpolated expression is not allowed in a hostname of a node") end # Issues when an expression is used where it is not legal. # E.g. an arithmetic expression where a hostname is expected. # ILLEGAL_EXPRESSION = hard_issue :ILLEGAL_EXPRESSION, :feature, :container do _("Illegal expression. %{expression} is unacceptable as %{feature} in %{container}") % { expression: label.a_an_uc(semantic), feature: feature, container: label.a_an(container) } end # Issues when a variable is not a NAME # ILLEGAL_VARIABLE_EXPRESSION = hard_issue :ILLEGAL_VARIABLE_EXPRESSION do _("Illegal variable expression. %{expression} did not produce a variable name (String or Numeric).") % { expression: label.a_an_uc(semantic) } end # Issues when an expression is used illegally in a query. # query only supports == and !=, and not <, > etc. # ILLEGAL_QUERY_EXPRESSION = hard_issue :ILLEGAL_QUERY_EXPRESSION do _("Illegal query expression. %{expression} cannot be used in a query") % { expression: label.a_an_uc(semantic) } end # If an attempt is made to make a resource default virtual or exported. # NOT_VIRTUALIZEABLE = hard_issue :NOT_VIRTUALIZEABLE do _("Resource Defaults are not virtualizable") end CLASS_NOT_VIRTUALIZABLE = issue :CLASS_NOT_VIRTUALIZABLE do _("Classes are not virtualizable") end # When an attempt is made to use multiple keys (to produce a range in Ruby - e.g. $arr[2,-1]). # This is not supported in 3x, but it allowed in 4x. # UNSUPPORTED_RANGE = issue :UNSUPPORTED_RANGE, :count do _("Attempt to use unsupported range in %{expression}, %{count} values given for max 1") % { expression: label.a_an(semantic), count: count } end # Issues when expressions that are not implemented or activated in the current version are used. # UNSUPPORTED_EXPRESSION = issue :UNSUPPORTED_EXPRESSION do _("Expressions of type %{expression} are not supported in this version of Puppet") % { expression: label.a_an(semantic) } end ILLEGAL_RELATIONSHIP_OPERAND_TYPE = issue :ILLEGAL_RELATIONSHIP_OPERAND_TYPE, :operand do _("Illegal relationship operand, can not form a relationship with %{expression}. A Catalog type is required.") % { expression: label.a_an(operand) } end NOT_CATALOG_TYPE = issue :NOT_CATALOG_TYPE, :type do _("Illegal relationship operand, can not form a relationship with something of type %{expression_type}. A Catalog type is required.") % { expression_type: type } end BAD_STRING_SLICE_ARITY = issue :BAD_STRING_SLICE_ARITY, :actual do _("String supports [] with one or two arguments. Got %{actual}") % { actual: actual } end BAD_STRING_SLICE_TYPE = issue :BAD_STRING_SLICE_TYPE, :actual do _("String-Type [] requires all arguments to be integers (or default). Got %{actual}") % { actual: actual } end BAD_ARRAY_SLICE_ARITY = issue :BAD_ARRAY_SLICE_ARITY, :actual do _("Array supports [] with one or two arguments. Got %{actual}") % { actual: actual } end BAD_HASH_SLICE_ARITY = issue :BAD_HASH_SLICE_ARITY, :actual do _("Hash supports [] with one or more arguments. Got %{actual}") % { actual: actual } end BAD_INTEGER_SLICE_ARITY = issue :BAD_INTEGER_SLICE_ARITY, :actual do _("Integer-Type supports [] with one or two arguments (from, to). Got %{actual}") % { actual: actual } end BAD_INTEGER_SLICE_TYPE = issue :BAD_INTEGER_SLICE_TYPE, :actual do _("Integer-Type [] requires all arguments to be integers (or default). Got %{actual}") % { actual: actual } end BAD_COLLECTION_SLICE_TYPE = issue :BAD_COLLECTION_SLICE_TYPE, :actual do _("A Type's size constraint arguments must be a single Integer type, or 1-2 integers (or default). Got %{actual}") % { actual: label.a_an(actual) } end BAD_FLOAT_SLICE_ARITY = issue :BAD_INTEGER_SLICE_ARITY, :actual do _("Float-Type supports [] with one or two arguments (from, to). Got %{actual}") % { actual: actual } end BAD_FLOAT_SLICE_TYPE = issue :BAD_INTEGER_SLICE_TYPE, :actual do _("Float-Type [] requires all arguments to be floats, or integers (or default). Got %{actual}") % { actual: actual } end BAD_SLICE_KEY_TYPE = issue :BAD_SLICE_KEY_TYPE, :left_value, :expected_classes, :actual do if expected_classes.size > 1 _("%{expression}[] cannot use %{actual} where one of the following is expected: %{expected}") % { expression: label.a_an_uc(left_value), actual: actual, expected: expected_classes.join(', ') } else _("%{expression}[] cannot use %{actual} where %{expected} is expected") % { expression: label.a_an_uc(left_value), actual: actual, expected: expected_classes[0] } end end BAD_STRING_SLICE_KEY_TYPE = issue :BAD_STRING_SLICE_KEY_TYPE, :left_value, :actual_type do _("A substring operation does not accept %{label_article} %{actual_type} as a character index. Expected an Integer") % { label_article: label.article(actual_type), actual_type: actual_type } end BAD_NOT_UNDEF_SLICE_TYPE = issue :BAD_NOT_UNDEF_SLICE_TYPE, :base_type, :actual do _("%{expression}[] argument must be a Type or a String. Got %{actual}") % { expression: base_type, actual: actual } end BAD_TYPE_SLICE_TYPE = issue :BAD_TYPE_SLICE_TYPE, :base_type, :actual do _("%{base_type}[] arguments must be types. Got %{actual}") % { base_type: base_type, actual: actual } end BAD_TYPE_SLICE_ARITY = issue :BAD_TYPE_SLICE_ARITY, :base_type, :min, :max, :actual do base_type_label = base_type.is_a?(String) ? base_type : label.a_an_uc(base_type) if max == -1 || max == Float::INFINITY _("%{base_type_label}[] accepts %{min} or more arguments. Got %{actual}") % { base_type_label: base_type_label, min: min, actual: actual } elsif max && max != min _("%{base_type_label}[] accepts %{min} to %{max} arguments. Got %{actual}") % { base_type_label: base_type_label, min: min, max: max, actual: actual } else _("%{base_type_label}[] accepts %{min} %{label}. Got %{actual}") % { base_type_label: base_type_label, min: min, label: label.plural_s(min, _('argument')), actual: actual } end end BAD_TYPE_SPECIALIZATION = hard_issue :BAD_TYPE_SPECIALIZATION, :type, :message do _("Error creating type specialization of %{base_type}, %{message}") % { base_type: label.a_an(type), message: message } end ILLEGAL_TYPE_SPECIALIZATION = issue :ILLEGAL_TYPE_SPECIALIZATION, :kind do _("Cannot specialize an already specialized %{kind} type") % { kind: kind } end ILLEGAL_RESOURCE_SPECIALIZATION = issue :ILLEGAL_RESOURCE_SPECIALIZATION, :actual do _("First argument to Resource[] must be a resource type or a String. Got %{actual}.") % { actual: actual } end EMPTY_RESOURCE_SPECIALIZATION = issue :EMPTY_RESOURCE_SPECIALIZATION do _("Arguments to Resource[] are all empty/undefined") end ILLEGAL_HOSTCLASS_NAME = hard_issue :ILLEGAL_HOSTCLASS_NAME, :name do _("Illegal Class name in class reference. %{expression} cannot be used where a String is expected") % { expression: label.a_an_uc(name) } end ILLEGAL_DEFINITION_NAME = hard_issue :ILLEGAL_DEFINITION_NAME, :name do _("Unacceptable name. The name '%{name}' is unacceptable as the name of %{value}") % { name: name, value: label.a_an(semantic) } end ILLEGAL_DEFINITION_LOCATION = issue :ILLEGAL_DEFINITION_LOCATION, :name, :file do _("Unacceptable location. The name '%{name}' is unacceptable in file '%{file}'") % { name: name, file: file } end ILLEGAL_TOP_CONSTRUCT_LOCATION = issue :ILLEGAL_TOP_CONSTRUCT_LOCATION do if semantic.is_a?(Puppet::Pops::Model::NamedDefinition) _("The %{value} '%{name}' is unacceptable as a top level construct in this location") % { name: semantic.name, value: label(semantic) } else _("This %{value} is unacceptable as a top level construct in this location") % { value: label(semantic) } end end CAPTURES_REST_NOT_LAST = hard_issue :CAPTURES_REST_NOT_LAST, :param_name do _("Parameter $%{param} is not last, and has 'captures rest'") % { param: param_name } end CAPTURES_REST_NOT_SUPPORTED = hard_issue :CAPTURES_REST_NOT_SUPPORTED, :container, :param_name do _("Parameter $%{param} has 'captures rest' - not supported in %{container}") % { param: param_name, container: label.a_an(container) } end REQUIRED_PARAMETER_AFTER_OPTIONAL = hard_issue :REQUIRED_PARAMETER_AFTER_OPTIONAL, :param_name do _("Parameter $%{param} is required but appears after optional parameters") % { param: param_name } end MISSING_REQUIRED_PARAMETER = hard_issue :MISSING_REQUIRED_PARAMETER, :param_name do _("Parameter $%{param} is required but no value was given") % { param: param_name } end NOT_NUMERIC = issue :NOT_NUMERIC, :value do _("The value '%{value}' cannot be converted to Numeric.") % { value: value } end NUMERIC_COERCION = issue :NUMERIC_COERCION, :before, :after do _("The string '%{before}' was automatically coerced to the numerical value %{after}") % { before: before, after: after } end UNKNOWN_FUNCTION = issue :UNKNOWN_FUNCTION, :name do _("Unknown function: '%{name}'.") % { name: name } end UNKNOWN_VARIABLE = issue :UNKNOWN_VARIABLE, :name do _("Unknown variable: '%{name}'.") % { name: name } end RUNTIME_ERROR = issue :RUNTIME_ERROR, :detail do _("Error while evaluating %{expression}, %{detail}") % { expression: label.a_an(semantic), detail: detail } end UNKNOWN_RESOURCE_TYPE = issue :UNKNOWN_RESOURCE_TYPE, :type_name do _("Resource type not found: %{res_type}") % { res_type: type_name } end ILLEGAL_RESOURCE_TYPE = hard_issue :ILLEGAL_RESOURCE_TYPE, :actual do _("Illegal Resource Type expression, expected result to be a type name, or untitled Resource, got %{actual}") % { actual: actual } end DUPLICATE_TITLE = issue :DUPLICATE_TITLE, :title do _("The title '%{title}' has already been used in this resource expression") % { title: title } end DUPLICATE_ATTRIBUTE = issue :DUPLICATE_ATTRIBUE, :attribute do _("The attribute '%{attribute}' has already been set") % { attribute: attribute } end MISSING_TITLE = hard_issue :MISSING_TITLE do _("Missing title. The title expression resulted in undef") end MISSING_TITLE_AT = hard_issue :MISSING_TITLE_AT, :index do _("Missing title at index %{index}. The title expression resulted in an undef title") % { index: index } end ILLEGAL_TITLE_TYPE_AT = hard_issue :ILLEGAL_TITLE_TYPE_AT, :index, :actual do _("Illegal title type at index %{index}. Expected String, got %{actual}") % { index: index, actual: actual } end EMPTY_STRING_TITLE_AT = hard_issue :EMPTY_STRING_TITLE_AT, :index do _("Empty string title at %{index}. Title strings must have a length greater than zero.") % { index: index } end UNKNOWN_RESOURCE = issue :UNKNOWN_RESOURCE, :type_name, :title do _("Resource not found: %{type_name}['%{title}']") % { type_name: type_name, title: title } end UNKNOWN_RESOURCE_PARAMETER = issue :UNKNOWN_RESOURCE_PARAMETER, :type_name, :title, :param_name do _("The resource %{type_name}['%{title}'] does not have a parameter called '%{param}'") % { type_name: type_name.capitalize, title: title, param: param_name } end DIV_BY_ZERO = hard_issue :DIV_BY_ZERO do _("Division by 0") end RESULT_IS_INFINITY = hard_issue :RESULT_IS_INFINITY, :operator do _("The result of the %{operator} expression is Infinity") % { operator: operator } end # TODO_HEREDOC EMPTY_HEREDOC_SYNTAX_SEGMENT = issue :EMPTY_HEREDOC_SYNTAX_SEGMENT, :syntax do _("Heredoc syntax specification has empty segment between '+' : '%{syntax}'") % { syntax: syntax } end ILLEGAL_EPP_PARAMETERS = issue :ILLEGAL_EPP_PARAMETERS do _("Ambiguous EPP parameter expression. Probably missing '<%-' before parameters to remove leading whitespace") end DISCONTINUED_IMPORT = hard_issue :DISCONTINUED_IMPORT do # TRANSLATORS "import" is a function name and should not be translated _("Use of 'import' has been discontinued in favor of a manifest directory. See http://links.puppet.com/puppet-import-deprecation") end IDEM_EXPRESSION_NOT_LAST = issue :IDEM_EXPRESSION_NOT_LAST do _("This %{expression} has no effect. A value was produced and then forgotten (one or more preceding expressions may have the wrong form)") % { expression: label.label(semantic) } end RESOURCE_WITHOUT_TITLE = issue :RESOURCE_WITHOUT_TITLE, :name do _("This expression is invalid. Did you try declaring a '%{name}' resource without a title?") % { name: name } end IDEM_NOT_ALLOWED_LAST = hard_issue :IDEM_NOT_ALLOWED_LAST, :container do _("This %{expression} has no effect. %{container} can not end with a value-producing expression without other effect") % { expression: label.label(semantic), container: label.a_an_uc(container) } end RESERVED_WORD = hard_issue :RESERVED_WORD, :word do _("Use of reserved word: %{word}, must be quoted if intended to be a String value") % { word: word } end FUTURE_RESERVED_WORD = issue :FUTURE_RESERVED_WORD, :word do _("Use of future reserved word: '%{word}'") % { word: word } end RESERVED_TYPE_NAME = hard_issue :RESERVED_TYPE_NAME, :name do _("The name: '%{name}' is already defined by Puppet and can not be used as the name of %{expression}.") % { name: name, expression: label.a_an(semantic) } end UNMATCHED_SELECTOR = hard_issue :UNMATCHED_SELECTOR, :param_value do _("No matching entry for selector parameter with value '%{param}'") % { param: param_value } end ILLEGAL_NODE_INHERITANCE = issue :ILLEGAL_NODE_INHERITANCE do _("Node inheritance is not supported in Puppet >= 4.0.0. See http://links.puppet.com/puppet-node-inheritance-deprecation") end ILLEGAL_OVERRIDDEN_TYPE = issue :ILLEGAL_OVERRIDDEN_TYPE, :actual do _("Resource Override can only operate on resources, got: %{actual}") % { actual: label.label(actual) } end DUPLICATE_PARAMETER = hard_issue :DUPLICATE_PARAMETER, :param_name do _("The parameter '%{param}' is declared more than once in the parameter list") % { param: param_name } end DUPLICATE_KEY = issue :DUPLICATE_KEY, :key do _("The key '%{key}' is declared more than once") % { key: key } end DUPLICATE_DEFAULT = hard_issue :DUPLICATE_DEFAULT, :container do _("This %{container} already has a 'default' entry - this is a duplicate") % { container: label.label(container) } end RESERVED_PARAMETER = hard_issue :RESERVED_PARAMETER, :container, :param_name do _("The parameter $%{param} redefines a built in parameter in %{container}") % { param: param_name, container: label.the(container) } end TYPE_MISMATCH = hard_issue :TYPE_MISMATCH, :expected, :actual do _("Expected value of type %{expected}, got %{actual}") % { expected: expected, actual: actual } end MULTIPLE_ATTRIBUTES_UNFOLD = hard_issue :MULTIPLE_ATTRIBUTES_UNFOLD do _("Unfolding of attributes from Hash can only be used once per resource body") end ILLEGAL_CATALOG_RELATED_EXPRESSION = hard_issue :ILLEGAL_CATALOG_RELATED_EXPRESSION do _("This %{expression} appears in a context where catalog related expressions are not allowed") % { expression: label.label(semantic) } end SYNTAX_ERROR = hard_issue :SYNTAX_ERROR, :where do _("Syntax error at %{location}") % { location: where } end ILLEGAL_CLASS_REFERENCE = hard_issue :ILLEGAL_CLASS_REFERENCE do _('Illegal class reference') end ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE = hard_issue :ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE do _('Illegal fully qualified class reference') end ILLEGAL_FULLY_QUALIFIED_NAME = hard_issue :ILLEGAL_FULLY_QUALIFIED_NAME do _('Illegal fully qualified name') end ILLEGAL_NAME_OR_BARE_WORD = hard_issue :ILLEGAL_NAME_OR_BARE_WORD do _('Illegal name or bare word') end ILLEGAL_NUMBER = hard_issue :ILLEGAL_NUMBER, :value do _("Illegal number '%{value}'") % { value: value } end ILLEGAL_UNICODE_ESCAPE = issue :ILLEGAL_UNICODE_ESCAPE do _("Unicode escape '\\u' was not followed by 4 hex digits or 1-6 hex digits in {} or was > 10ffff") end INVALID_HEX_NUMBER = hard_issue :INVALID_HEX_NUMBER, :value do _("Not a valid hex number %{value}") % { value: value } end INVALID_OCTAL_NUMBER = hard_issue :INVALID_OCTAL_NUMBER, :value do _("Not a valid octal number %{value}") % { value: value } end INVALID_DECIMAL_NUMBER = hard_issue :INVALID_DECIMAL_NUMBER, :value do _("Not a valid decimal number %{value}") % { value: value } end NO_INPUT_TO_LEXER = hard_issue :NO_INPUT_TO_LEXER do _("Internal Error: No string or file given to lexer to process.") end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/visitable.rb
lib/puppet/pops/visitable.rb
# frozen_string_literal: true # Visitable is a mix-in module that makes a class visitable by a Visitor module Puppet::Pops::Visitable def accept(visitor, *arguments) visitor.visit(self, *arguments) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/pcore.rb
lib/puppet/pops/pcore.rb
# frozen_string_literal: true require 'uri' module Puppet::Pops module Pcore include Types::PuppetObject TYPE_URI_RX = Types::TypeFactory.regexp(URI::DEFAULT_PARSER.make_regexp) TYPE_URI = Types::TypeFactory.pattern(TYPE_URI_RX) TYPE_URI_ALIAS = Types::PTypeAliasType.new('Pcore::URI', nil, TYPE_URI) TYPE_SIMPLE_TYPE_NAME = Types::TypeFactory.pattern(/\A[A-Z]\w*\z/) TYPE_QUALIFIED_REFERENCE = Types::TypeFactory.pattern(/\A[A-Z]\w*(?:::[A-Z]\w*)*\z/) TYPE_MEMBER_NAME = Types::PPatternType.new([Types::PRegexpType.new(Patterns::PARAM_NAME)]) KEY_PCORE_URI = 'pcore_uri' KEY_PCORE_VERSION = 'pcore_version' PCORE_URI = 'http://puppet.com/2016.1/pcore' PCORE_VERSION = SemanticPuppet::Version.new(1, 0, 0) PARSABLE_PCORE_VERSIONS = SemanticPuppet::VersionRange.parse('1.x') RUNTIME_NAME_AUTHORITY = 'http://puppet.com/2016.1/runtime' def self._pcore_type @type end def self.annotate(instance, annotations_hash) annotations_hash.each_pair do |type, init_hash| type.implementation_class.annotate(instance) { init_hash } end instance end def self.init_env(loader) if Puppet[:tasks] add_object_type('Task', <<-PUPPET, loader) { attributes => { # Fully qualified name of the task name => { type => Pattern[/\\A[a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)*\\z/] }, # List of file references referenced by metadata and their paths on disk. # If there are no implementations listed in metadata, the first file is always # the task executable. files => { type => Array[Struct[name => String, path => String]] }, # Task metadata metadata => { type => Hash[String, Any] }, # Map parameter names to their parsed data type parameters => { type => Optional[Hash[Pattern[/\\A[a-z][a-z0-9_]*\\z/], Type]], value => undef }, } } PUPPET end end def self.init(loader, ir) add_alias('Pcore::URI_RX', TYPE_URI_RX, loader) add_type(TYPE_URI_ALIAS, loader) add_alias('Pcore::SimpleTypeName', TYPE_SIMPLE_TYPE_NAME, loader) add_alias('Pcore::MemberName', TYPE_MEMBER_NAME, loader) add_alias('Pcore::TypeName', TYPE_QUALIFIED_REFERENCE, loader) add_alias('Pcore::QRef', TYPE_QUALIFIED_REFERENCE, loader) Types::TypedModelObject.register_ptypes(loader, ir) @type = create_object_type(loader, ir, Pcore, 'Pcore', nil) ir.register_implementation_namespace('Pcore', 'Puppet::Pops::Pcore') ir.register_implementation_namespace('Puppet::AST', 'Puppet::Pops::Model') ir.register_implementation('Puppet::AST::Locator', 'Puppet::Pops::Parser::Locator::Locator19') Resource.register_ptypes(loader, ir) Lookup::Context.register_ptype(loader, ir); Lookup::DataProvider.register_types(loader) add_object_type('Deferred', <<-PUPPET, loader) { attributes => { # Fully qualified name of the function name => { type => Pattern[/\\A[$]?[a-z][a-z0-9_]*(?:::[a-z][a-z0-9_]*)*\\z/] }, arguments => { type => Optional[Array[Any]], value => undef}, } } PUPPET end # Create and register a new `Object` type in the Puppet Type System and map it to an implementation class # # @param loader [Loader::Loader] The loader where the new type will be registered # @param ir [ImplementationRegistry] The implementation registry that maps this class to the new type # @param impl_class [Class] The class that is the implementation of the type # @param type_name [String] The fully qualified name of the new type # @param parent_name [String,nil] The fully qualified name of the parent type # @param attributes_hash [Hash{String => Object}] A hash of attribute definitions for the new type # @param functions_hash [Hash{String => Object}] A hash of function definitions for the new type # @param equality [Array<String>] An array with names of attributes that participate in equality comparison # @return [PObjectType] the created type. Not yet resolved # # @api private def self.create_object_type(loader, ir, impl_class, type_name, parent_name, attributes_hash = EMPTY_HASH, functions_hash = EMPTY_HASH, equality = nil) init_hash = {} init_hash[Types::KEY_PARENT] = Types::PTypeReferenceType.new(parent_name) unless parent_name.nil? init_hash[Types::KEY_ATTRIBUTES] = attributes_hash unless attributes_hash.empty? init_hash[Types::KEY_FUNCTIONS] = functions_hash unless functions_hash.empty? init_hash[Types::KEY_EQUALITY] = equality unless equality.nil? ir.register_implementation(type_name, impl_class) add_type(Types::PObjectType.new(type_name, init_hash), loader) end def self.add_object_type(name, body, loader) add_type(Types::PObjectType.new(name, Parser::EvaluatingParser.new.parse_string(body).body), loader) end def self.add_alias(name, type, loader, name_authority = RUNTIME_NAME_AUTHORITY) add_type(Types::PTypeAliasType.new(name, nil, type), loader, name_authority) end def self.add_type(type, loader, name_authority = RUNTIME_NAME_AUTHORITY) loader.set_entry(Loader::TypedName.new(:type, type.name, name_authority), type) type end def self.register_implementations(impls, name_authority = RUNTIME_NAME_AUTHORITY) Loaders.loaders.register_implementations(impls, name_authority) end def self.register_aliases(aliases, name_authority = RUNTIME_NAME_AUTHORITY, loader = Loaders.loaders.private_environment_loader) aliases.each do |name, type_string| add_type(Types::PTypeAliasType.new(name, Types::TypeFactory.type_reference(type_string), nil), loader, name_authority) end aliases.each_key.map { |name| loader.load(:type, name).resolve(loader) } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization.rb
lib/puppet/pops/serialization.rb
# frozen_string_literal: true module Puppet::Pops module Serialization def self.not_implemented(impl, method_name) raise NotImplementedError, "The class #{impl.class.name} should have implemented the method #{method_name}()" end class SerializationError < Puppet::Error end PCORE_TYPE_KEY = '__ptype' # Key used when the value can be represented as, and recreated from, a single string that can # be passed to a `from_string` method or an array of values that can be passed to the default # initializer method. PCORE_VALUE_KEY = '__pvalue' # Type key used for hashes that contain keys that are not of type String PCORE_TYPE_HASH = 'Hash' # Type key used for symbols PCORE_TYPE_SENSITIVE = 'Sensitive' PCORE_TYPE_BINARY = 'Binary' # Type key used for symbols PCORE_TYPE_SYMBOL = 'Symbol' # Type key used for Default PCORE_TYPE_DEFAULT = 'Default' # Type key used for document local references PCORE_LOCAL_REF_SYMBOL = 'LocalRef' end end require_relative 'serialization/json_path' require_relative 'serialization/from_data_converter' require_relative 'serialization/to_data_converter' require_relative 'serialization/to_stringified_converter' require_relative 'serialization/serializer' require_relative 'serialization/deserializer' require_relative 'serialization/json' require_relative 'serialization/time_factory' require_relative 'serialization/object'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/adaptable.rb
lib/puppet/pops/adaptable.rb
# frozen_string_literal: true # Adaptable is a mix-in module that adds adaptability to a class. # This means that an adapter can # associate itself with an instance of the class and store additional data/have behavior. # # This mechanism should be used when there is a desire to keep implementation concerns separate. # In Ruby it is always possible to open and modify a class or instance to teach it new tricks, but it # is however not possible to do this for two different versions of some service at the same time. # The Adaptable pattern is also good when only a few of the objects of some class needs to have extra # information (again possible in Ruby by adding instance variables dynamically). In fact, the implementation # of Adaptable does just that; it adds an instance variable named after the adapter class and keeps an # instance of this class in this slot. # # @note the implementation details; the fact that an instance variable is used to keep the adapter # instance data should not # be exploited as the implementation of _being adaptable_ may change in the future. # @api private # module Puppet::Pops module Adaptable # Base class for an Adapter. # # A typical adapter just defines some accessors. # # A more advanced adapter may need to setup the adapter based on the object it is adapting. # @example Making Duck adaptable # class Duck # include Puppet::Pops::Adaptable # end # @example Giving a Duck a nick name # class NickNameAdapter < Puppet::Pops::Adaptable::Adapter # attr_accessor :nick_name # end # d = Duck.new # NickNameAdapter.adapt(d).nick_name = "Daffy" # NickNameAdapter.get(d).nick_name # => "Daffy" # # @example Giving a Duck a more elaborate nick name # class NickNameAdapter < Puppet::Pops::Adaptable::Adapter # attr_accessor :nick_name, :object # def initialize o # @object = o # @nick_name = "Yo" # end # def nick_name # "#{@nick_name}, the #{o.class.name}" # end # def NickNameAdapter.create_adapter(o) # x = new o # x # end # end # d = Duck.new # n = NickNameAdapter.adapt(d) # n.nick_name # => "Yo, the Duck" # n.nick_name = "Daffy" # n.nick_name # => "Daffy, the Duck" # @example Using a block to set values # NickNameAdapter.adapt(o) { |a| a.nick_name = "Buddy!" } # NickNameAdapter.adapt(o) { |a, o| a.nick_name = "You're the best #{o.class.name} I met."} # class Adapter # Returns an existing adapter for the given object, or nil, if the object is not # adapted. # # @param o [Adaptable] object to get adapter from # @return [Adapter<self>] an adapter of the same class as the receiver of #get # @return [nil] if the given object o has not been adapted by the receiving adapter # @raise [ArgumentError] if the object is not adaptable # def self.get(o) attr_name = self_attr_name o.instance_variable_get(attr_name) end # Returns an existing adapter for the given object, or creates a new adapter if the # object has not been adapted, or the adapter has been cleared. # # @example Using a block to set values # NickNameAdapter.adapt(o) { |a| a.nick_name = "Buddy!" } # NickNameAdapter.adapt(o) { |a, o| a.nick_name = "Your the best #{o.class.name} I met."} # @overload adapt(o) # @overload adapt(o, {|adapter| block}) # @overload adapt(o, {|adapter, o| block}) # @param o [Adaptable] object to add adapter to # @yieldparam adapter [Adapter<self>] the created adapter # @yieldparam o [Adaptable] optional, the given adaptable # @param block [Proc] optional, evaluated in the context of the adapter (existing or new) # @return [Adapter<self>] an adapter of the same class as the receiver of the call # @raise [ArgumentError] if the given object o is not adaptable # def self.adapt(o, &block) attr_name = self_attr_name value = o.instance_variable_get(attr_name) adapter = value || associate_adapter(create_adapter(o), o) if block_given? if block.arity == 1 block.call(adapter) else block.call(adapter, o) end end adapter end # Creates a new adapter, associates it with the given object and returns the adapter. # # @example Using a block to set values # NickNameAdapter.adapt_new(o) { |a| a.nick_name = "Buddy!" } # NickNameAdapter.adapt_new(o) { |a, o| a.nick_name = "Your the best #{o.class.name} I met."} # This is used when a fresh adapter is wanted instead of possible returning an # existing adapter as in the case of {Adapter.adapt}. # @overload adapt_new(o) # @overload adapt_new(o, {|adapter| block}) # @overload adapt_new(o, {|adapter, o| block}) # @yieldparam adapter [Adapter<self>] the created adapter # @yieldparam o [Adaptable] optional, the given adaptable # @param o [Adaptable] object to add adapter to # @param block [Proc] optional, evaluated in the context of the new adapter # @return [Adapter<self>] an adapter of the same class as the receiver of the call # @raise [ArgumentError] if the given object o is not adaptable # def self.adapt_new(o, &block) adapter = associate_adapter(create_adapter(o), o) if block_given? if block.arity == 1 block.call(adapter) else block.call(adapter, o) end end adapter end # Clears the adapter set in the given object o. Returns any set adapter or nil. # @param o [Adaptable] the object where the adapter should be cleared # @return [Adapter] if an adapter was set # @return [nil] if the adapter has not been set # def self.clear(o) attr_name = self_attr_name if o.instance_variable_defined?(attr_name) o.send(:remove_instance_variable, attr_name) else nil end end # This base version creates an instance of the class (i.e. an instance of the concrete subclass # of Adapter). A Specialization may want to create an adapter instance specialized for the given target # object. # @param o [Adaptable] The object to adapt. This implementation ignores this variable, but a # specialization may want to initialize itself differently depending on the object it is adapting. # @return [Adapter<self>] instance of the subclass of Adapter receiving the call # def self.create_adapter(o) new end # Associates the given adapter with the given target object # @param adapter [Adapter] the adapter to associate with the given object _o_ # @param o [Adaptable] the object to adapt # @return [adapter] the given adapter # def self.associate_adapter(adapter, o) o.instance_variable_set(self_attr_name, adapter) adapter end # Returns a suitable instance variable name given a class name. # The returned string is the fully qualified name of a class with '::' replaced by '_' since # '::' is not allowed in an instance variable name. # @param name [String] the fully qualified name of a class # @return [String] the name with all '::' replaced by '_' # @api private # def self.instance_var_name(name) name.split(DOUBLE_COLON).join(USCORE) end # Returns the name of the class, or the name of the type if the class represents an Object type # @return [String] the name of the class or type def self.type_name name end # Returns a suitable instance variable name for the _name_ of this instance. The name is created by calling # Adapter#instance_var_name and then cached. # @return [String] the instance variable name for _name_ # @api private # rubocop:disable Naming/MemoizedInstanceVariableName def self.self_attr_name @attr_name_sym ||= :"@#{instance_var_name(type_name)}" end # rubocop:enable Naming/MemoizedInstanceVariableName end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/puppet_stack.rb
lib/puppet/pops/puppet_stack.rb
# frozen_string_literal: true require_relative '../../puppet/thread_local' module Puppet module Pops # Utility class for keeping track of the "Puppet stack", ie the file # and line numbers of Puppet Code that created the current context. # # To use this make a call with: # # ```rb # Puppet::Pops::PuppetStack.stack(file, line, receiver, message, args) # ``` # # To get the stack call: # # ```rb # Puppet::Pops::PuppetStack.stacktrace # ``` # # or # # ```rb # Puppet::Pops::PuppetStack.top_of_stack # ``` # # To support testing, a given file that is an empty string, or nil # as well as a nil line number are supported. Such stack frames # will be represented with the text `unknown` and `0´ respectively. module PuppetStack @stack = Puppet::ThreadLocal.new { Array.new } def self.stack(file, line, obj, message, args, &block) file = 'unknown' if file.nil? || file == '' line = 0 if line.nil? result = nil @stack.value.unshift([file, line]) begin if block_given? result = obj.send(message, *args, &block) else result = obj.send(message, *args) end ensure @stack.value.shift() end result end def self.stacktrace @stack.value.dup end # Returns an Array with the top of the puppet stack, or an empty # Array if there was no such entry. def self.top_of_stack @stack.value.first || [] end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/patterns.rb
lib/puppet/pops/patterns.rb
# frozen_string_literal: true # The Patterns module contains common regular expression patters for the Puppet DSL language module Puppet::Pops::Patterns # NUMERIC matches hex, octal, decimal, and floating point and captures several parts # 0 = entire matched number, leading and trailing whitespace and sign included # 1 = sign, +, - or nothing # 2 = entire numeric part # 3 = hexadecimal number # 4 = non hex integer portion, possibly with leading 0 (octal) # 5 = floating point part, starts with ".", decimals and optional exponent # # Thus, a hex number has group 3 value, an octal value has group 4 (if it starts with 0), and no group 3 # and a floating point value has group 4 and group 5. # NUMERIC = /\A[[:blank:]]*([-+]?)[[:blank:]]*((0[xX][0-9A-Fa-f]+)|(0?\d+)((?:\.\d+)?(?:[eE]-?\d+)?))[[:blank:]]*\z/ # Special expression that tests if there is whitespace between sign and number. The expression is used # to strip such whitespace when normal Float or Integer conversion fails. WS_BETWEEN_SIGN_AND_NUMBER = /\A([+-])[[:blank:]]+(.*)\z/ # ILLEGAL_P3_1_HOSTNAME matches if a hostname contains illegal characters. # This check does not prevent pathological names like 'a....b', '.....', "---". etc. ILLEGAL_HOSTNAME_CHARS = /[^-\w.]/ # NAME matches a name the same way as the lexer. NAME = /\A((::)?[a-z]\w*)(::[a-z]\w*)*\z/ # CLASSREF_EXT matches a class reference the same way as the lexer - i.e. the external source form # where each part must start with a capital letter A-Z. # CLASSREF_EXT = /\A((::){0,1}[A-Z]\w*)+\z/ # Same as CLASSREF_EXT but cannot start with '::' # CLASSREF_EXT_DECL = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/ # CLASSREF matches a class reference the way it is represented internally in the # model (i.e. in lower case). # CLASSREF = /\A((::){0,1}[a-z]\w*)+\z/ # Same as CLASSREF but cannot start with '::' # CLASSREF_DECL = /\A[a-z]\w*(?:::[a-z]\w*)*\z/ # DOLLAR_VAR matches a variable name including the initial $ character DOLLAR_VAR = /\$(::)?(\w+::)*\w+/ # VAR_NAME matches the name part of a variable (The $ character is not included) # Note, that only the final segment may start with an underscore. # Note, regexp sensitive to backtracking VAR_NAME = /\A(?:::)?(?:[a-z]\w*::)*[a-z_]\w*\z/ # PARAM_NAME matches the name part of a parameter (The $ character is not included) PARAM_NAME = /\A[a-z_]\w*\z/ # A Numeric var name must be the decimal number 0, or a decimal number not starting with 0 NUMERIC_VAR_NAME = /\A(?:0|(?:[1-9][0-9]*))\z/ end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/label_provider.rb
lib/puppet/pops/label_provider.rb
# frozen_string_literal: true # Provides a label for an object. # This simple implementation calls #to_s on the given object, and handles articles 'a/an/the'. # module Puppet::Pops::LabelProvider VOWELS = %w[a e i o u y] SKIPPED_CHARACTERS = %w[" '] A = "a" AN = "an" # Provides a label for the given object by calling `to_s` on the object. # The intent is for this method to be overridden in concrete label providers. def label o o.to_s end # Produces a label for the given text with indefinite article (a/an) def a_an o text = label(o) "#{article(text)} #{text}" end # Produces a label for the given text with indefinite article (A/An) def a_an_uc o text = label(o) "#{article(text).capitalize} #{text}" end # Produces a label for the given text with *definite article* (the). def the o "the #{label(o)}" end # Produces a label for the given text with *definite article* (The). def the_uc o "The #{label(o)}" end # Appends 's' to (optional) text if count != 1 else an empty string def plural_s(count, text = '') count == 1 ? text : "#{text}s" end # Combines several strings using commas and a final conjunction def combine_strings(strings, conjunction = 'or') case strings.size when 0 '' when 1 strings[0] when 2 "#{strings[0]} #{conjunction} #{strings[1]}" else "#{strings[0...-1].join(', ')}, #{conjunction} #{strings.last}" end end # Produces an *indefinite article* (a/an) for the given text ('a' if # it starts with a vowel) This is obviously flawed in the general # sense as may labels have punctuation at the start and this method # does not translate punctuation to English words. Also, if a vowel is # pronounced as a consonant, the article should not be "an". # def article s article_for_letter(first_letter_of(s)) end private def first_letter_of(string) char = string[0, 1] if SKIPPED_CHARACTERS.include? char char = string[1, 1] end if char == "" raise Puppet::DevError, _("<%{string}> does not appear to contain a word") % { string: string } end char end def article_for_letter(letter) downcased = letter.downcase if VOWELS.include? downcased AN else A end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/utils.rb
lib/puppet/pops/utils.rb
# frozen_string_literal: true # Provides utility methods module Puppet::Pops module Utils # Can the given o be converted to numeric? (or is numeric already) # Accepts a leading '::' # Returns a boolean if the value is numeric # If testing if value can be converted it is more efficient to call {#to_n} or {#to_n_with_radix} directly # and check if value is nil. def self.is_numeric?(o) case o when Numeric true else !!Patterns::NUMERIC.match(relativize_name(o.to_s)) end end # Convert a match from Patterns::NUMERIC to floating point value if # possible def self.match_to_fp(match) if match[5].to_s.length > 0 # Use default radix (default is decimal == 10) for floats # Do not convert a value that is 0 raised to 10^somevalue to float - the value is always 0 # i.e. 0000.0e1, 0e1, 0.0000e1 if Integer(match[4]) == 0 && match[5] =~ /\A\.?0*[eE].*\z/ nil else fp_value = Float(match[2]) if fp_value != Float::INFINITY match[1] == '-' ? -fp_value : fp_value else nil end end end end # To Numeric with radix, or nil if not a number. # If the value is already Numeric it is returned verbatim with a radix of 10. # @param o [String, Number] a string containing a number in octal, hex, integer (decimal) or floating point form # with optional sign +/- # @return [Array<Number, Integer>, nil] array with converted number and radix, or nil if not possible to convert # @api public # def self.to_n_with_radix o case o when String match = Patterns::NUMERIC.match(relativize_name(o)) if !match nil elsif match[5].to_s.length > 0 fp_value = match_to_fp(match) fp_value.nil? ? nil : [fp_value, 10] else # Set radix (default is decimal == 10) radix = 10 if match[3].to_s.length > 0 radix = 16 elsif match[4].to_s.length > 1 && match[4][0, 1] == '0' radix = 8 end # Ruby 1.8.7 does not have a second argument to Kernel method that creates an # integer from a string, it relies on the prefix 0x, 0X, 0 (and unsupported in puppet binary 'b') # We have the correct string here, match[2] is safe to parse without passing on radix match[1] == '-' ? [-Integer(match[2]), radix] : [Integer(match[2]), radix] end when Numeric # Impossible to calculate radix, assume decimal [o, 10] else nil end rescue ArgumentError nil end # To Numeric (or already numeric) # Returns nil if value is not numeric, else an Integer or Float. A String may have an optional sign. # # A leading '::' is accepted (and ignored) # def self.to_n o case o when String match = Patterns::NUMERIC.match(relativize_name(o)) if !match nil elsif match[5].to_s.length > 0 match_to_fp(match) else match[1] == '-' ? -Integer(match[2]) : Integer(match[2]) end when Numeric o else nil end rescue ArgumentError nil end # is the name absolute (i.e. starts with ::) def self.is_absolute? name name.start_with? "::" end def self.name_to_segments name name.split("::") end def self.relativize_name name is_absolute?(name) ? name[2..] : name end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loaders.rb
lib/puppet/pops/loaders.rb
# frozen_string_literal: true module Puppet::Pops # This is the container for all Loader instances. Each Loader instance has a `loader_name` by which it can be uniquely # identified within this container. # A Loader can be private or public. In general, code will have access to the private loader associated with the # location of the code. It will be parented by a loader that in turn have access to other public loaders that # can load only such entries that have been publicly available. The split between public and private is not # yet enforced in Puppet. # # The name of a private loader should always end with ' private' # class Loaders class LoaderError < Puppet::Error; end # Commented out the :static_loader and :puppet_system_loader # because of rubocop offenses with duplicated definitions of # these generated methods, but keeping them here for visibility # on how the loaders are stacked. # attr_reader :static_loader # attr_reader :puppet_system_loader attr_reader :puppet_cache_loader attr_reader :public_environment_loader attr_reader :private_environment_loader attr_reader :environment def self.new(environment, for_agent = false, load_from_pcore = true) environment.lock.synchronize do obj = environment.loaders if obj.nil? obj = allocate obj.send(:initialize, environment, for_agent, load_from_pcore) end obj end end def initialize(environment, for_agent, load_from_pcore = true) # Protect against environment havoc raise ArgumentError, _("Attempt to redefine already initialized loaders for environment") unless environment.loaders.nil? environment.loaders = self @environment = environment @loaders_by_name = {} add_loader_by_name(self.class.static_loader) # Create the set of loaders # 1. Puppet, loads from the "running" puppet - i.e. bundled functions, types, extension points and extensions # These cannot be cached since a loaded instance will be bound to its closure scope which holds on to # a compiler and all loaded types. Subsequent request would find remains of the environment that loaded # the content. PUP-4461. # @puppet_system_loader = create_puppet_system_loader() # 2. Cache loader(optional) - i.e. what puppet stores on disk via pluginsync; gate behind the for_agent flag. # 3. Environment loader - i.e. what is bound across the environment, may change for each setup # TODO: loaders need to work when also running in an agent doing catalog application. There is no # concept of environment the same way as when running as a master (except when doing apply). # The creation mechanisms should probably differ between the two. @private_environment_loader = if for_agent @puppet_cache_loader = create_puppet_cache_loader create_environment_loader(environment, @puppet_cache_loader, load_from_pcore) else create_environment_loader(environment, @puppet_system_loader, load_from_pcore) end Pcore.init_env(@private_environment_loader) # 4. module loaders are set up from the create_environment_loader, they register themselves end # Called after loader has been added to Puppet Context as :loaders so that dynamic types can # be pre-loaded with a fully configured loader system def pre_load @puppet_system_loader.load(:type, 'error') end # Clears the cached static and puppet_system loaders (to enable testing) # def self.clear @@static_loader = nil Puppet::Pops::Types::TypeFactory.clear Model.class_variable_set(:@@pcore_ast_initialized, false) Model.register_pcore_types end # Calls {#loaders} to obtain the {{Loaders}} instance and then uses it to find the appropriate loader # for the given `module_name`, or for the environment in case `module_name` is `nil` or empty. # # @param module_name [String,nil] the name of the module # @return [Loader::Loader] the found loader # @raise [Puppet::ParseError] if no loader can be found # @api private def self.find_loader(module_name) loaders.find_loader(module_name) end def self.static_implementation_registry if !class_variable_defined?(:@@static_implementation_registry) || @@static_implementation_registry.nil? ir = Types::ImplementationRegistry.new Types::TypeParser.type_map.values.each { |t| ir.register_implementation(t.simple_name, t.class.name) } @@static_implementation_registry = ir end @@static_implementation_registry end def self.static_loader # The static loader can only be changed after a reboot if !class_variable_defined?(:@@static_loader) || @@static_loader.nil? @@static_loader = Loader::StaticLoader.new() @@static_loader.register_aliases Pcore.init(@@static_loader, static_implementation_registry) end @@static_loader end def self.implementation_registry loaders = Puppet.lookup(:loaders) { nil } loaders.nil? ? nil : loaders.implementation_registry end def register_implementations(obj_classes, name_authority) self.class.register_implementations_with_loader(obj_classes, name_authority, @private_environment_loader) end # Register implementations using the global static loader def self.register_static_implementations(obj_classes) register_implementations_with_loader(obj_classes, Pcore::RUNTIME_NAME_AUTHORITY, static_loader) end def self.register_implementations_with_loader(obj_classes, name_authority, loader) types = obj_classes.map do |obj_class| type = obj_class._pcore_type typed_name = Loader::TypedName.new(:type, type.name, name_authority) entry = loader.loaded_entry(typed_name) loader.set_entry(typed_name, type) if entry.nil? || entry.value.nil? type end # Resolve lazy so that all types can cross reference each other types.each { |type| type.resolve(loader) } end # Register the given type with the Runtime3TypeLoader. The registration will not happen unless # the type system has been initialized. # # @param name [String,Symbol] the name of the entity being set # @param origin [URI] the origin or the source where the type is defined # @api private def self.register_runtime3_type(name, origin) loaders = Puppet.lookup(:loaders) { nil } return nil if loaders.nil? rt3_loader = loaders.runtime3_type_loader return nil if rt3_loader.nil? name = name.to_s caps_name = Types::TypeFormatter.singleton.capitalize_segments(name) typed_name = Loader::TypedName.new(:type, name) rt3_loader.set_entry(typed_name, Types::PResourceType.new(caps_name), origin) nil end # Finds a loader to use when deserializing a catalog and then subsequenlty use user # defined types found in that catalog. # def self.catalog_loader loaders = Puppet.lookup(:loaders) { nil } if loaders.nil? loaders = Loaders.new(Puppet.lookup(:current_environment), true) Puppet.push_context(:loaders => loaders) end loaders.find_loader(nil) end # Finds the `Loaders` instance by looking up the :loaders in the global Puppet context # # @return [Loaders] the loaders instance # @raise [Puppet::ParseError] if loader has been bound to the global context # @api private def self.loaders loaders = Puppet.lookup(:loaders) { nil } raise Puppet::ParseError, _("Internal Error: Puppet Context ':loaders' missing") if loaders.nil? loaders end # Lookup a loader by its unique name. # # @param [String] loader_name the name of the loader to lookup # @return [Loader] the found loader # @raise [Puppet::ParserError] if no loader is found def [](loader_name) loader = @loaders_by_name[loader_name] if loader.nil? # Unable to find the module private loader. Try resolving the module loader = private_loader_for_module(loader_name[0..-9]) if loader_name.end_with?(' private') raise Puppet::ParseError, _("Unable to find loader named '%{loader_name}'") % { loader_name: loader_name } if loader.nil? end loader end # Finds the appropriate loader for the given `module_name`, or for the environment in case `module_name` # is `nil` or empty. # # @param module_name [String,nil] the name of the module # @return [Loader::Loader] the found loader # @raise [Puppet::ParseError] if no loader can be found # @api private def find_loader(module_name) if module_name.nil? || EMPTY_STRING == module_name # Use the public environment loader public_environment_loader else # TODO : Later check if definition is private, and then add it to private_loader_for_module # loader = public_loader_for_module(module_name) if loader.nil? raise Puppet::ParseError, _("Internal Error: did not find public loader for module: '%{module_name}'") % { module_name: module_name } end loader end end def implementation_registry # Environment specific implementation registry @implementation_registry ||= Types::ImplementationRegistry.new(self.class.static_implementation_registry) end def static_loader self.class.static_loader end def puppet_system_loader @puppet_system_loader end def runtime3_type_loader @runtime3_type_loader end def public_loader_for_module(module_name) md = @module_resolver[module_name] || (return nil) # Note, this loader is not resolved until there is interest in the visibility of entities from the # perspective of something contained in the module. (Many request may pass through a module loader # without it loading anything. # See {#private_loader_for_module}, and not in {#configure_loaders_for_modules} md.public_loader end def private_loader_for_module(module_name) md = @module_resolver[module_name] || (return nil) # Since there is interest in the visibility from the perspective of entities contained in the # module, it must be resolved (to provide this visibility). # See {#configure_loaders_for_modules} unless md.resolved? @module_resolver.resolve(md) end md.private_loader end def add_loader_by_name(loader) name = loader.loader_name if @loaders_by_name.include?(name) raise Puppet::ParseError, _("Internal Error: Attempt to redefine loader named '%{name}'") % { name: name } end @loaders_by_name[name] = loader end # Load the main manifest for the given environment # # There are two sources that can be used for the initial parse: # # 1. The value of `Puppet[:code]`: Puppet can take a string from # its settings and parse that as a manifest. This is used by various # Puppet applications to read in a manifest and pass it to the # environment as a side effect. This is attempted first. # 2. The contents of the environment's +manifest+ attribute: Puppet will # try to load the environment manifest. The manifest must be a file. # # @return [Model::Program] The manifest parsed into a model object def load_main_manifest parser = Parser::EvaluatingParser.singleton parsed_code = Puppet[:code] program = if parsed_code != "" parser.parse_string(parsed_code, 'unknown-source-location') else file = @environment.manifest # if the manifest file is a reference to a directory, parse and # combine all .pp files in that directory if file == Puppet::Node::Environment::NO_MANIFEST nil elsif File.directory?(file) raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints directory '#{file}'. It must be a file" elsif File.exist?(file) parser.parse_file(file) else raise Puppet::Error, "manifest of environment '#{@environment.name}' appoints '#{file}'. It does not exist" end end instantiate_definitions(program, public_environment_loader) unless program.nil? program rescue Puppet::ParseErrorWithIssue => detail detail.environment = @environment.name raise rescue => detail msg = _('Could not parse for environment %{env}: %{detail}') % { env: @environment, detail: detail } error = Puppet::Error.new(msg) error.set_backtrace(detail.backtrace) raise error end # Add 4.x definitions found in the given program to the given loader. def instantiate_definitions(program, loader) program.definitions.each { |d| instantiate_definition(d, loader) } nil end # Add given 4.x definition to the given loader. def instantiate_definition(definition, loader) case definition when Model::PlanDefinition instantiate_PlanDefinition(definition, loader) when Model::FunctionDefinition instantiate_FunctionDefinition(definition, loader) when Model::TypeAlias instantiate_TypeAlias(definition, loader) when Model::TypeMapping instantiate_TypeMapping(definition, loader) else raise Puppet::ParseError, "Internal Error: Unknown type of definition - got '#{definition.class}'" end end private def instantiate_PlanDefinition(plan_definition, loader) typed_name, f = Loader::PuppetPlanInstantiator.create_from_model(plan_definition, loader) loader.set_entry(typed_name, f, plan_definition.locator.to_uri(plan_definition)) nil end def instantiate_FunctionDefinition(function_definition, loader) # Instantiate Function, and store it in the loader typed_name, f = Loader::PuppetFunctionInstantiator.create_from_model(function_definition, loader) loader.set_entry(typed_name, f, function_definition.locator.to_uri(function_definition)) nil end def instantiate_TypeAlias(type_alias, loader) # Bind the type alias to the loader using the alias Puppet::Pops::Loader::TypeDefinitionInstantiator.create_from_model(type_alias, loader) nil end def instantiate_TypeMapping(type_mapping, loader) tf = Types::TypeParser.singleton lhs = tf.interpret(type_mapping.type_expr, loader) rhs = tf.interpret_any(type_mapping.mapping_expr, loader) implementation_registry.register_type_mapping(lhs, rhs) nil end def create_puppet_system_loader Loader::ModuleLoaders.system_loader_from(static_loader, self) end def create_puppet_cache_loader Loader::ModuleLoaders.cached_loader_from(puppet_system_loader, self) end def create_environment_loader(environment, parent_loader, load_from_pcore = true) # This defines where to start parsing/evaluating - the "initial import" (to use 3x terminology) # Is either a reference to a single .pp file, or a directory of manifests. If the environment becomes # a module and can hold functions, types etc. then these are available across all other modules without # them declaring this dependency - it is however valuable to be able to treat it the same way # bindings and other such system related configuration. # This is further complicated by the many options available: # - The environment may not have a directory, the code comes from one appointed 'manifest' (site.pp) # - The environment may have a directory and also point to a 'manifest' # - The code to run may be set in settings (code) # Further complication is that there is nothing specifying what the visibility is into # available modules. (3x is everyone sees everything). # Puppet binder currently reads confdir/bindings - that is bad, it should be using the new environment support. # env_conf is setup from the environment_dir value passed into Puppet::Environments::Directories.new env_conf = Puppet.lookup(:environments).get_conf(environment.name) env_path = env_conf.nil? || !env_conf.is_a?(Puppet::Settings::EnvironmentConf) ? nil : env_conf.path_to_env if Puppet[:tasks] loader = Loader::ModuleLoaders.environment_loader_from(parent_loader, self, env_path) else # Create the 3.x resource type loader static_loader.runtime_3_init # Create pcore resource type loader, if applicable pcore_resource_type_loader = if load_from_pcore && env_path Loader::ModuleLoaders.pcore_resource_type_loader_from(parent_loader, self, env_path) else nil end @runtime3_type_loader = add_loader_by_name(Loader::Runtime3TypeLoader.new(parent_loader, self, environment, pcore_resource_type_loader)) if env_path.nil? # Not a real directory environment, cannot work as a module TODO: Drop when legacy env are dropped? loader = add_loader_by_name(Loader::SimpleEnvironmentLoader.new(@runtime3_type_loader, Loader::ENVIRONMENT, environment)) else # View the environment as a module to allow loading from it - this module is always called 'environment' loader = Loader::ModuleLoaders.environment_loader_from(@runtime3_type_loader, self, env_path) end end # An environment has a module path even if it has a null loader configure_loaders_for_modules(loader, environment) # modules should see this loader @public_environment_loader = loader # Code in the environment gets to see all modules (since there is no metadata for the environment) # but since this is not given to the module loaders, they can not load global code (since they can not # have prior knowledge about this loader = add_loader_by_name(Loader::DependencyLoader.new(loader, Loader::ENVIRONMENT_PRIVATE, @module_resolver.all_module_loaders(), environment)) # The module loader gets the private loader via a lazy operation to look up the module's private loader. # This does not work for an environment since it is not resolved the same way. # TODO: The EnvironmentLoader could be a specialized loader instead of using a ModuleLoader to do the work. # This is subject to future design - an Environment may move more in the direction of a Module. @public_environment_loader.private_loader = loader loader end def configure_loaders_for_modules(parent_loader, environment) @module_resolver = mr = ModuleResolver.new(self) environment.modules.each do |puppet_module| # Create data about this module md = LoaderModuleData.new(puppet_module) mr[puppet_module.name] = md md.public_loader = Loader::ModuleLoaders.module_loader_from(parent_loader, self, md.name, md.path) end # NOTE: Do not resolve all modules here - this is wasteful if only a subset of modules / functions are used # The resolution is triggered by asking for a module's private loader, since this means there is interest # in the visibility from that perspective. # If later, it is wanted that all resolutions should be made up-front (to capture errors eagerly, this # can be introduced (better for production), but may be irritating in development mode. end # =LoaderModuleData # Information about a Module and its loaders. # TODO: should have reference to real model element containing all module data; this is faking it # TODO: Should use Puppet::Module to get the metadata (as a hash) - a somewhat blunt instrument, but that is # what is available with a reasonable API. # class LoaderModuleData attr_accessor :public_loader attr_accessor :private_loader attr_accessor :resolutions # The Puppet::Module this LoaderModuleData represents in the loader configuration attr_reader :puppet_module # @param puppet_module [Puppet::Module] the module instance for the module being represented # def initialize(puppet_module) @puppet_module = puppet_module @resolutions = [] @public_loader = nil @private_loader = nil end def name @puppet_module.name end def version @puppet_module.version end def path @puppet_module.path end def resolved? !@private_loader.nil? end def restrict_to_dependencies? @puppet_module.has_metadata? end def unmet_dependencies? @puppet_module.unmet_dependencies.any? end def dependency_names @puppet_module.dependencies_as_modules.collect(&:name) end end # Resolves module loaders - resolution of model dependencies is done by Puppet::Module # class ModuleResolver def initialize(loaders) @loaders = loaders @index = {} @all_module_loaders = nil end def [](name) @index[name] end def []=(name, module_data) @index[name] = module_data end def all_module_loaders @all_module_loaders ||= @index.values.map(&:public_loader) end def resolve(module_data) if module_data.resolved? nil else module_data.private_loader = if module_data.restrict_to_dependencies? create_loader_with_dependencies_first(module_data) else create_loader_with_all_modules_visible(module_data) end end end private def create_loader_with_all_modules_visible(from_module_data) @loaders.add_loader_by_name(Loader::DependencyLoader.new(from_module_data.public_loader, "#{from_module_data.name} private", all_module_loaders(), @loaders.environment)) end def create_loader_with_dependencies_first(from_module_data) dependency_loaders = from_module_data.dependency_names.collect { |name| @index[name].public_loader } visible_loaders = dependency_loaders + (all_module_loaders() - dependency_loaders) @loaders.add_loader_by_name(Loader::DependencyLoader.new(from_module_data.public_loader, "#{from_module_data.name} private", visible_loaders, @loaders.environment)) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/merge_strategy.rb
lib/puppet/pops/merge_strategy.rb
# frozen_string_literal: true require 'deep_merge/core' module Puppet::Pops # Merges to objects into one based on an implemented strategy. # class MergeStrategy NOT_FOUND = Object.new.freeze def self.strategies @@strategies ||= {} end private_class_method :strategies # Finds the merge strategy for the given _merge_, creates an instance of it and returns that instance. # # @param merge [MergeStrategy,String,Hash<String,Object>,nil] The merge strategy. Can be a string or symbol denoting the key # identifier or a hash with options where the key 'strategy' denotes the key # @return [MergeStrategy] The matching merge strategy # def self.strategy(merge) return DefaultMergeStrategy::INSTANCE unless merge return merge if merge.is_a?(MergeStrategy) if merge.is_a?(Hash) merge_strategy = merge['strategy'] if merge_strategy.nil? # TRANSLATORS 'merge' is a variable name and 'strategy' is a key and should not be translated raise ArgumentError, _("The hash given as 'merge' must contain the name of a strategy in string form for the key 'strategy'") end merge_options = merge.size == 1 ? EMPTY_HASH : merge else merge_strategy = merge merge_options = EMPTY_HASH end merge_strategy = merge_strategy.to_sym if merge_strategy.is_a?(String) strategy_class = strategies[merge_strategy] raise ArgumentError, _("Unknown merge strategy: '%{strategy}'") % { strategy: merge_strategy } if strategy_class.nil? merge_options == EMPTY_HASH ? strategy_class::INSTANCE : strategy_class.new(merge_options) end # Returns the list of merge strategy keys known to this class # # @return [Array<Symbol>] List of strategy keys # def self.strategy_keys strategies.keys - [:default, :unconstrained_deep, :reverse_deep] end # Adds a new merge strategy to the map of strategies known to this class # # @param strategy_class [Class<MergeStrategy>] The class of the added strategy # def self.add_strategy(strategy_class) unless MergeStrategy > strategy_class # TRANSLATORS 'MergeStrategies.add_strategy' is a method, 'stratgey_class' is a variable and 'MergeStrategy' is a class name and should not be translated raise ArgumentError, _("MergeStrategies.add_strategy 'strategy_class' must be a 'MergeStrategy' class. Got %{strategy_class}") % { strategy_class: strategy_class } end strategies[strategy_class.key] = strategy_class nil end # Finds a merge strategy that corresponds to the given _merge_ argument and delegates the task of merging the elements of _e1_ and _e2_ to it. # # @param e1 [Object] The first element # @param e2 [Object] The second element # @return [Object] The result of the merge # def self.merge(e1, e2, merge) strategy(merge).merge(e1, e2) end def self.key raise NotImplementedError, "Subclass must implement 'key'" end # Create a new instance of this strategy configured with the given _options_ # @param merge_options [Hash<String,Object>] Merge options def initialize(options) assert_type('The merge options', self.class.options_t, options) unless options.empty? @options = options end # Merges the elements of _e1_ and _e2_ according to the rules of this strategy and options given when this # instance was created # # @param e1 [Object] The first element # @param e2 [Object] The second element # @return [Object] The result of the merge # def merge(e1, e2) checked_merge( assert_type('The first element of the merge', value_t, e1), assert_type('The second element of the merge', value_t, e2) ) end # TODO: API 5.0 Remove this method # @deprecated def merge_lookup(lookup_variants) lookup(lookup_variants, Lookup::Invocation.current) end # Merges the result of yielding the given _lookup_variants_ to a given block. # # @param lookup_variants [Array] The variants to pass as second argument to the given block # @return [Object] the merged value. # @yield [} ] # @yieldparam variant [Object] each variant given in the _lookup_variants_ array. # @yieldreturn [Object] the value to merge with other values # @throws :no_such_key if the lookup was unsuccessful # # Merges the result of yielding the given _lookup_variants_ to a given block. # # @param lookup_variants [Array] The variants to pass as second argument to the given block # @return [Object] the merged value. # @yield [} ] # @yieldparam variant [Object] each variant given in the _lookup_variants_ array. # @yieldreturn [Object] the value to merge with other values # @throws :no_such_key if the lookup was unsuccessful # def lookup(lookup_variants, lookup_invocation) case lookup_variants.size when 0 throw :no_such_key when 1 merge_single(yield(lookup_variants[0])) else lookup_invocation.with(:merge, self) do result = lookup_variants.reduce(NOT_FOUND) do |memo, lookup_variant| not_found = true value = catch(:no_such_key) do v = yield(lookup_variant) not_found = false v end if not_found memo else memo.equal?(NOT_FOUND) ? convert_value(value) : merge(memo, value) end end throw :no_such_key if result == NOT_FOUND lookup_invocation.report_result(result) end end end # Converts a single value to the type expected when merging two elements # @param value [Object] the value to convert # @return [Object] the converted value def convert_value(value) value end # Applies the merge strategy on a single element. Only applicable for `unique` # @param value [Object] the value to merge with nothing # @return [Object] the merged value def merge_single(value) value end def options @options end def configuration if @options.nil? || @options.empty? self.class.key.to_s else @options.include?('strategy') ? @options : { 'strategy' => self.class.key.to_s }.merge(@options) end end protected class << self # Returns the type used to validate the options hash # # @return [Types::PStructType] the puppet type # def options_t @options_t ||= Types::TypeParser.singleton.parse("Struct[{strategy=>Optional[Pattern[/#{key}/]]}]") end end # Returns the type used to validate the options hash # # @return [Types::PAnyType] the puppet type # def value_t raise NotImplementedError, "Subclass must implement 'value_t'" end def checked_merge(e1, e2) raise NotImplementedError, "Subclass must implement 'checked_merge(e1,e2)'" end def assert_type(param, type, value) Types::TypeAsserter.assert_instance_of(param, type, value) end end # Simple strategy that returns the first value found. It never merges any values. # class FirstFoundStrategy < MergeStrategy INSTANCE = new(EMPTY_HASH) def self.key :first end # Returns the first value found # # @param lookup_variants [Array] The variants to pass as second argument to the given block # @return [Object] the merged value # @throws :no_such_key unless the lookup was successful # def lookup(lookup_variants, _) # First found does not continue when a root key was found and a subkey wasn't since that would # simulate a hash merge lookup_variants.each { |lookup_variant| catch(:no_such_key) { return yield(lookup_variant) } } throw :no_such_key end protected def value_t @value_t ||= Types::PAnyType::DEFAULT end MergeStrategy.add_strategy(self) end # Same as {FirstFoundStrategy} but used when no strategy has been explicitly given class DefaultMergeStrategy < FirstFoundStrategy INSTANCE = new(EMPTY_HASH) def self.key :default end MergeStrategy.add_strategy(self) end # Produces a new hash by merging hash e1 with hash e2 in such a way that the values of duplicate keys # will be those of e1 # class HashMergeStrategy < MergeStrategy INSTANCE = new(EMPTY_HASH) def self.key :hash end # @param e1 [Hash<String,Object>] The hash that will act as the source of the merge # @param e2 [Hash<String,Object>] The hash that will act as the receiver for the merge # @return [Hash<String,Object]] The merged hash # @see Hash#merge def checked_merge(e1, e2) e2.merge(e1) end protected def value_t @value_t ||= Types::TypeParser.singleton.parse('Hash[String,Data]') end MergeStrategy.add_strategy(self) end # Merges two values that must be either scalar or arrays into a unique set of values. # # Scalar values will be converted into a one element arrays and array values will be flattened # prior to forming the unique set. The order of the elements is preserved with e1 being the # first contributor of elements and e2 the second. # class UniqueMergeStrategy < MergeStrategy INSTANCE = new(EMPTY_HASH) def self.key :unique end # @param e1 [Array<Object>] The first array # @param e2 [Array<Object>] The second array # @return [Array<Object>] The unique set of elements # def checked_merge(e1, e2) convert_value(e1) | convert_value(e2) end def convert_value(e) e.is_a?(Array) ? e.flatten : [e] end # If _value_ is an array, then return the result of calling `uniq` on that array. Otherwise, # the argument is returned. # @param value [Object] the value to merge with nothing # @return [Object] the merged value def merge_single(value) value.is_a?(Array) ? value.uniq : value end protected def value_t @value_t ||= Types::TypeParser.singleton.parse('Variant[Scalar,Array[Data]]') end MergeStrategy.add_strategy(self) end # Documentation copied from https://github.com/danielsdeleo/deep_merge/blob/master/lib/deep_merge/core.rb # altered with respect to _preserve_unmergeables_ since this implementation always disables that option. # # The destination is dup'ed before the deep_merge is called to allow frozen objects as values. # # deep_merge method permits merging of arbitrary child elements. The two top level # elements must be hashes. These hashes can contain unlimited (to stack limit) levels # of child elements. These child elements to not have to be of the same types. # Where child elements are of the same type, deep_merge will attempt to merge them together. # Where child elements are not of the same type, deep_merge will skip or optionally overwrite # the destination element with the contents of the source element at that level. # So if you have two hashes like this: # source = {:x => [1,2,3], :y => 2} # dest = {:x => [4,5,'6'], :y => [7,8,9]} # dest.deep_merge!(source) # Results: {:x => [1,2,3,4,5,'6'], :y => 2} # # "deep_merge" will unconditionally overwrite any unmergeables and merge everything else. # # Options: # Options are specified in the last parameter passed, which should be in hash format: # hash.deep_merge!({:x => [1,2]}, {:knockout_prefix => '--'}) # - 'knockout_prefix' Set to string value to signify prefix which deletes elements from existing element. Defaults is _undef_ # - 'sort_merged_arrays' Set to _true_ to sort all arrays that are merged together. Default is _false_ # - 'merge_hash_arrays' Set to _true_ to merge hashes within arrays. Default is _false_ # # Selected Options Details: # :knockout_prefix => The purpose of this is to provide a way to remove elements # from existing Hash by specifying them in a special way in incoming hash # source = {:x => ['--1', '2']} # dest = {:x => ['1', '3']} # dest.ko_deep_merge!(source) # Results: {:x => ['2','3']} # Additionally, if the knockout_prefix is passed alone as a string, it will cause # the entire element to be removed: # source = {:x => '--'} # dest = {:x => [1,2,3]} # dest.ko_deep_merge!(source) # Results: {:x => ""} # # :merge_hash_arrays => merge hashes within arrays # source = {:x => [{:y => 1}]} # dest = {:x => [{:z => 2}]} # dest.deep_merge!(source, {:merge_hash_arrays => true}) # Results: {:x => [{:y => 1, :z => 2}]} # class DeepMergeStrategy < MergeStrategy INSTANCE = new(EMPTY_HASH) def self.key :deep end def checked_merge(e1, e2) dm_options = { :preserve_unmergeables => false } options.each_pair { |k, v| dm_options[k.to_sym] = v unless k == 'strategy' } # e2 (the destination) is deep cloned to avoid that the passed in object mutates DeepMerge.deep_merge!(e1, deep_clone(e2), dm_options) end def deep_clone(value) case value when Hash result = value.clone value.each { |k, v| result[k] = deep_clone(v) } result when Array value.map { |v| deep_clone(v) } else value end end protected class << self # Returns a type that allows all deep_merge options except 'preserve_unmergeables' since we force # the setting of that option to false # # @return [Types::PAnyType] the puppet type used when validating the options hash def options_t @options_t ||= Types::TypeParser.singleton.parse('Struct[{'\ "strategy=>Optional[Pattern[#{key}]],"\ 'knockout_prefix=>Optional[String],'\ 'merge_debug=>Optional[Boolean],'\ 'merge_hash_arrays=>Optional[Boolean],'\ 'sort_merged_arrays=>Optional[Boolean],'\ '}]') end end def value_t @value_t ||= Types::PAnyType::DEFAULT end MergeStrategy.add_strategy(self) end # Same as {DeepMergeStrategy} but without constraint on valid merge options # (needed for backward compatibility with Hiera v3) class UnconstrainedDeepMergeStrategy < DeepMergeStrategy def self.key :unconstrained_deep end # @return [Types::PAnyType] the puppet type used when validating the options hash def self.options_t @options_t ||= Types::TypeParser.singleton.parse('Hash[String[1],Any]') end MergeStrategy.add_strategy(self) end # Same as {UnconstrainedDeepMergeStrategy} but with reverse priority of merged elements. # (needed for backward compatibility with Hiera v3) class ReverseDeepMergeStrategy < UnconstrainedDeepMergeStrategy INSTANCE = new(EMPTY_HASH) def self.key :reverse_deep end def checked_merge(e1, e2) super(e2, e1) end MergeStrategy.add_strategy(self) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/semantic_error.rb
lib/puppet/pops/semantic_error.rb
# frozen_string_literal: true # Error that is used to raise an Issue. See {Puppet::Pops::Issues}. # class Puppet::Pops::SemanticError < RuntimeError attr_accessor :issue attr_accessor :semantic attr_accessor :options # @param issue [Puppet::Pops::Issues::Issue] the issue describing the severity and message # @param semantic [Puppet::Pops::Model::Locatable, nil] the expression causing the failure, or nil if unknown # @param options [Hash] an options hash with Symbol to value mapping - these are the arguments to the issue # def initialize(issue, semantic = nil, options = {}) @issue = issue @semantic = semantic @options = options end def file @options[:file] end def line @options[:line] end def pos @options[:pos] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/pn.rb
lib/puppet/pops/pn.rb
# frozen_string_literal: true module Puppet::Pops module PN KEY_PATTERN = /^[A-Za-z_-][0-9A-Za-z_-]*$/ def pnError(message) raise ArgumentError, message end def as_call(name) Call.new(name, self) end def as_parameters [self] end def ==(o) eql?(o) end def to_s s = ''.dup format(nil, s) s end def with_name(name) Entry.new(name, self) end def double_quote(str, bld) bld << '"' str.each_codepoint do |codepoint| case codepoint when 0x09 bld << '\\t' when 0x0a bld << '\\n' when 0x0d bld << '\\r' when 0x22 bld << '\\"' when 0x5c bld << '\\\\' else if codepoint < 0x20 bld << sprintf('\\o%3.3o', codepoint) elsif codepoint <= 0x7f bld << codepoint else bld << [codepoint].pack('U') end end end bld << '"' end def format_elements(elements, indent, b) elements.each_with_index do |e, i| if indent b << "\n" << indent.current elsif i > 0 b << ' ' end e.format(indent, b) end end class Indent attr_reader :current def initialize(indent = ' ', current = '') @indent = indent @current = current end def increase Indent.new(@indent, @current + @indent) end end class Call include PN attr_reader :name, :elements def initialize(name, *elements) @name = name @elements = elements end def [](idx) @elements[idx] end def as_call(name) Call.new(name, *@elements) end def as_parameters List.new(@elements) end def eql?(o) o.is_a?(Call) && @name == o.name && @elements == o.elements end def format(indent, b) b << '(' << @name if @elements.size > 0 b << ' ' unless indent format_elements(@elements, indent ? indent.increase : nil, b) end b << ')' end def to_data { '^' => [@name] + @elements.map(&:to_data) } end end class Entry attr_reader :key, :value def initialize(key, value) @key = key @value = value end def eql?(o) o.is_a?(Entry) && @key == o.key && @value == o.value end alias == eql? end class List include PN attr_reader :elements def initialize(elements) @elements = elements end def [](idx) @elements[idx] end def as_call(name) Call.new(name, *@elements) end def as_parameters @elements end def eql?(o) o.is_a?(List) && @elements == o.elements end def format(indent, b) b << '[' format_elements(@elements, indent ? indent.increase : nil, b) unless @elements.empty? b << ']' end def to_data @elements.map(&:to_data) end end class Literal include PN attr_reader :value def initialize(value) @value = value end def format(indent, b) if @value.nil? b << 'nil' elsif value.is_a?(String) double_quote(value, b) else b << value.to_s end end def eql?(o) o.is_a?(Literal) && @value == o.value end def to_data @value end end class Map include PN attr_reader :entries def initialize(entries) entries.each { |e| pnError("key #{e.key} does not conform to pattern /#{KEY_PATTERN.source}/)") unless e.key =~ KEY_PATTERN } @entries = entries end def eql?(o) o.is_a?(Map) && @entries == o.entries end def format(indent, b) local_indent = indent ? indent.increase : nil b << '{' @entries.each_with_index do |e, i| if indent b << "\n" << local_indent.current elsif i > 0 b << ' ' end b << ':' << e.key b << ' ' e.value.format(local_indent, b) end b << '}' end def to_data r = [] @entries.each { |e| r << e.key << e.value.to_data } { '#' => r } end end end end require_relative 'model/pn_transformer' require_relative 'parser/pn_parser'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/visitor.rb
lib/puppet/pops/visitor.rb
# frozen_string_literal: true module Puppet::Pops # A Visitor performs delegation to a given receiver based on the configuration of the Visitor. # A new visitor is created with a given receiver, a method prefix, min, and max argument counts. # e.g. # visitor = Visitor.new(self, "visit_from", 1, 1) # will make the visitor call "self.visit_from_CLASS(x)" where CLASS is resolved to the given # objects class, or one of is ancestors, the first class for which there is an implementation of # a method will be selected. # # Raises RuntimeError if there are too few or too many arguments, or if the receiver is not # configured to handle a given visiting object. # class Visitor attr_reader :receiver, :message, :min_args, :max_args, :cache def initialize(receiver, message, min_args = 0, max_args = nil) raise ArgumentError, "min_args must be >= 0" if min_args < 0 raise ArgumentError, "max_args must be >= min_args or nil" if max_args && max_args < min_args @receiver = receiver @message = message @min_args = min_args @max_args = max_args @cache = Hash.new end # Visit the configured receiver def visit(thing, *args) visit_this(@receiver, thing, args) end NO_ARGS = EMPTY_ARRAY # Visit an explicit receiver def visit_this(receiver, thing, args) raise "Visitor Error: Too few arguments passed. min = #{@min_args}" unless args.length >= @min_args if @max_args raise "Visitor Error: Too many arguments passed. max = #{@max_args}" unless args.length <= @max_args end method_name = @cache[thing.class] if method_name return receiver.send(method_name, thing, *args) else thing.class.ancestors().each do |ancestor| name = ancestor.name next if name.nil? method_name = :"#{@message}_#{name.split(DOUBLE_COLON).last}" next unless receiver.respond_to?(method_name, true) @cache[thing.class] = method_name return receiver.send(method_name, thing, *args) end end raise "Visitor Error: the configured receiver (#{receiver.class}) can't handle instance of: #{thing.class}" end # Visit an explicit receiver def visit_this_class(receiver, clazz, args) raise "Visitor Error: Too few arguments passed. min = #{@min_args}" unless args.length >= @min_args if @max_args raise "Visitor Error: Too many arguments passed. max = #{@max_args}" unless args.length <= @max_args end method_name = @cache[clazz] if method_name return receiver.send(method_name, clazz, *args) else clazz.ancestors().each do |ancestor| name = ancestor.name next if name.nil? method_name = :"#{@message}_#{name.split(DOUBLE_COLON).last}" next unless receiver.respond_to?(method_name, true) @cache[clazz] = method_name return receiver.send(method_name, clazz, *args) end end raise "Visitor Error: the configured receiver (#{receiver.class}) can't handle instance of: #{clazz}" end # Visit an explicit receiver with 0 args # (This is ~30% faster than calling the general method) # def visit_this_0(receiver, thing) method_name = @cache[thing.class] if method_name return receiver.send(method_name, thing) end visit_this(receiver, thing, NO_ARGS) end # Visit an explicit receiver with 1 args # (This is ~30% faster than calling the general method) # def visit_this_1(receiver, thing, arg) method_name = @cache[thing.class] if method_name return receiver.send(method_name, thing, arg) end visit_this(receiver, thing, [arg]) end # Visit an explicit receiver with 2 args # (This is ~30% faster than calling the general method) # def visit_this_2(receiver, thing, arg1, arg2) method_name = @cache[thing.class] if method_name return receiver.send(method_name, thing, arg1, arg2) end visit_this(receiver, thing, [arg1, arg2]) end # Visit an explicit receiver with 3 args # (This is ~30% faster than calling the general method) # def visit_this_3(receiver, thing, arg1, arg2, arg3) method_name = @cache[thing.class] if method_name return receiver.send(method_name, thing, arg1, arg2, arg3) end visit_this(receiver, thing, [arg1, arg2, arg3]) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/validation.rb
lib/puppet/pops/validation.rb
# frozen_string_literal: true module Puppet::Pops # A module with base functionality for validation of a model. # # * **Factory** - an abstract factory implementation that makes it easier to create a new validation factory. # * **SeverityProducer** - produces a severity (:error, :warning, :ignore) for a given Issue # * **DiagnosticProducer** - produces a Diagnostic which binds an Issue to an occurrence of that issue # * **Acceptor** - the receiver/sink/collector of computed diagnostics # * **DiagnosticFormatter** - produces human readable output for a Diagnostic # module Validation # This class is an abstract base implementation of a _model validation factory_ that creates a validator instance # and associates it with a fully configured DiagnosticProducer. # # A _validator_ is responsible for validating a model. There may be different versions of validation available # for one and the same model; e.g. different semantics for different puppet versions, or different types of # validation configuration depending on the context/type of validation that should be performed (static, vs. runtime, etc.). # # This class is abstract and must be subclassed. The subclass must implement the methods # {#label_provider} and {#checker}. It is also expected that the subclass will override # the severity_producer and configure the issues that should be reported as errors (i.e. if they should be ignored, produce # a warning, or a deprecation warning). # # @abstract Subclass must implement {#checker}, and {#label_provider} # @api public # class Factory # Produces a validator with the given acceptor as the recipient of produced diagnostics. # The acceptor is where detected issues are received (and typically collected). # # @param acceptor [Acceptor] the acceptor is the receiver of all detected issues # @return [#validate] a validator responding to `validate(model)` # # @api public # def validator(acceptor) checker(diagnostic_producer(acceptor)) end # Produces the diagnostics producer to use given an acceptor of issues. # # @param acceptor [Acceptor] the acceptor is the receiver of all detected issues # @return [DiagnosticProducer] a detector of issues # # @api public # def diagnostic_producer(acceptor) DiagnosticProducer.new(acceptor, severity_producer(), label_provider()) end # Produces the SeverityProducer to use # Subclasses should implement and add specific overrides # # @return [SeverityProducer] a severity producer producing error, warning or ignore per issue # # @api public # def severity_producer SeverityProducer.new end # Produces the checker to use. # # @abstract # # @api public # def checker(diagnostic_producer) raise NoMethodError, "checker" end # Produces the label provider to use. # # @abstract # # @api public # def label_provider raise NoMethodError, "label_provider" end end # Decides on the severity of a given issue. # The produced severity is one of `:error`, `:warning`, or `:ignore`. # By default, a severity of `:error` is produced for all issues. To configure the severity # of an issue call `#severity=(issue, level)`. # # @return [Symbol] a symbol representing the severity `:error`, `:warning`, or `:ignore` # # @api public # class SeverityProducer SEVERITIES = { ignore: true, warning: true, error: true, deprecation: true }.freeze # Creates a new instance where all issues are diagnosed as :error unless overridden. # @param [Symbol] specifies default severity if :error is not wanted as the default # @api public # def initialize(default_severity = :error) # If diagnose is not set, the default is returned by the block @severities = Hash.new default_severity end # Returns the severity of the given issue. # @return [Symbol] severity level :error, :warning, or :ignore # @api public # def severity(issue) assert_issue(issue) @severities[issue] end # @see {#severity} # @api public # def [] issue severity issue end # Override a default severity with the given severity level. # # @param issue [Issues::Issue] the issue for which to set severity # @param level [Symbol] the severity level (:error, :warning, or :ignore). # @api public # def []=(issue, level) unless issue.is_a? Issues::Issue raise Puppet::DevError, _("Attempt to set validation severity for something that is not an Issue. (Got %{issue})") % { issue: issue.class } end unless SEVERITIES[level] raise Puppet::DevError, _("Illegal severity level: %{level} for '%{issue_code}'") % { issue_code: issue.issue_code, level: level } end unless issue.demotable? || level == :error raise Puppet::DevError, _("Attempt to demote the hard issue '%{issue_code}' to %{level}") % { issue_code: issue.issue_code, level: level } end @severities[issue] = level end # Returns `true` if the issue should be reported or not. # @return [Boolean] this implementation returns true for errors and warnings # # @api public # def should_report? issue diagnose = @severities[issue] diagnose == :error || diagnose == :warning || diagnose == :deprecation end # Checks if the given issue is valid. # @api private # def assert_issue issue unless issue.is_a? Issues::Issue raise Puppet::DevError, _("Attempt to get validation severity for something that is not an Issue. (Got %{issue})") % { issue: issue.class } end end end # A producer of diagnostics. # An producer of diagnostics is given each issue occurrence as they are found by a diagnostician/validator. It then produces # a Diagnostic, which it passes on to a configured Acceptor. # # This class exists to aid a diagnostician/validator which will typically first check if a particular issue # will be accepted at all (before checking for an occurrence of the issue; i.e. to perform check avoidance for expensive checks). # A validator passes an instance of Issue, the semantic object (the "culprit"), a hash with arguments, and an optional # exception. The semantic object is used to determine the location of the occurrence of the issue (file/line), and it # sets keys in the given argument hash that may be used in the formatting of the issue message. # class DiagnosticProducer # A producer of severity for a given issue # @return [SeverityProducer] # attr_reader :severity_producer # A producer of labels for objects involved in the issue # @return [LabelProvider] # attr_reader :label_provider # Initializes this producer. # # @param acceptor [Acceptor] a sink/collector of diagnostic results # @param severity_producer [SeverityProducer] the severity producer to use to determine severity of a given issue # @param label_provider [LabelProvider] a provider of model element type to human readable label # def initialize(acceptor, severity_producer, label_provider) @acceptor = acceptor @severity_producer = severity_producer @label_provider = label_provider end def accept(issue, semantic, arguments = {}, except = nil) return unless will_accept? issue # Set label provider unless caller provided a special label provider arguments[:label] ||= @label_provider arguments[:semantic] ||= semantic # A detail message is always provided, but is blank by default. # TODO: this support is questionable, it requires knowledge that :detail is special arguments[:detail] ||= '' # Accept an Error as semantic if it supports methods #file(), #line(), and #pos() if semantic.is_a?(StandardError) unless semantic.respond_to?(:file) && semantic.respond_to?(:line) && semantic.respond_to?(:pos) raise Puppet::DevError, _("Issue %{issue_code}: Cannot pass a %{class_name} as a semantic object when it does not support #pos(), #file() and #line()") % { issue_code: issue.issue_code, class_name: semantic.class } end end source_pos = semantic file = semantic.file unless semantic.nil? severity = @severity_producer.severity(issue) @acceptor.accept(Diagnostic.new(severity, issue, file, source_pos, arguments, except)) end def will_accept? issue @severity_producer.should_report? issue end end class Diagnostic attr_reader :severity attr_reader :issue attr_reader :arguments attr_reader :exception attr_reader :file attr_reader :source_pos def initialize severity, issue, file, source_pos, arguments = {}, exception = nil @severity = severity @issue = issue @file = file @source_pos = source_pos @arguments = arguments # TODO: Currently unused, the intention is to provide more information (stack backtrace, etc.) when # debugging or similar - this to catch internal problems reported as higher level issues. @exception = exception end # Two diagnostics are considered equal if the have the same issue, location and severity # (arguments and exception are ignored) # rubocop:disable Layout def ==(o) self.class == o.class && same_position?(o) && issue.issue_code == o.issue.issue_code && file == o.file && severity == o.severity end alias eql? == # rubocop:enable Layout def hash @hash ||= [file, source_pos.offset, issue.issue_code, severity].hash end # Position is equal if the diagnostic is not located or if referring to the same offset def same_position?(o) source_pos.nil? && o.source_pos.nil? || source_pos.offset == o.source_pos.offset end private :same_position? end # Formats a diagnostic for output. # Produces a diagnostic output typical for a compiler (suitable for interpretation by tools) # The format is: # `file:line:pos: Message`, where pos, line and file are included if available. # class DiagnosticFormatter def format diagnostic "#{format_location(diagnostic)} #{format_severity(diagnostic)}#{format_message(diagnostic)}" end def format_message diagnostic diagnostic.issue.format(diagnostic.arguments) end # This produces "Deprecation notice: " prefix if the diagnostic has :deprecation severity, otherwise "". # The idea is that all other diagnostics are emitted with the methods Puppet.err (or an exception), and # Puppet.warning. # @note Note that it is not a good idea to use Puppet.deprecation_warning as it is for internal deprecation. # def format_severity diagnostic diagnostic.severity == :deprecation ? "Deprecation notice: " : "" end def format_location diagnostic file = diagnostic.file file = (file.is_a?(String) && file.empty?) ? nil : file line = pos = nil if diagnostic.source_pos line = diagnostic.source_pos.line pos = diagnostic.source_pos.pos end if file && line && pos "#{file}:#{line}:#{pos}:" elsif file && line "#{file}:#{line}:" elsif file "#{file}:" else "" end end end # Produces a diagnostic output in the "puppet style", where the location is appended with an "at ..." if the # location is known. # class DiagnosticFormatterPuppetStyle < DiagnosticFormatter def format diagnostic if (location = format_location diagnostic) != "" "#{format_severity(diagnostic)}#{format_message(diagnostic)}#{location}" else format_message(diagnostic) end end # The somewhat (machine) unusable format in current use by puppet. # have to be used here for backwards compatibility. def format_location diagnostic file = diagnostic.file file = (file.is_a?(String) && file.empty?) ? nil : file line = pos = nil if diagnostic.source_pos line = diagnostic.source_pos.line pos = diagnostic.source_pos.pos end if file && line && pos " at #{file}:#{line}:#{pos}" elsif file && line " at #{file}:#{line}" elsif line && pos " at line #{line}:#{pos}" elsif line " at line #{line}" elsif file " in #{file}" else "" end end end # An acceptor of diagnostics. # An acceptor of diagnostics is given each issue as they are found by a diagnostician/validator. An # acceptor can collect all found issues, or decide to collect a few and then report, or give up as the first issue # if found. # This default implementation collects all diagnostics in the order they are produced, and can then # answer questions about what was diagnosed. # class Acceptor # All diagnostic in the order they were issued attr_reader :diagnostics # The number of :warning severity issues + number of :deprecation severity issues attr_reader :warning_count # The number of :error severity issues attr_reader :error_count # Initializes this diagnostics acceptor. # By default, the acceptor is configured with a default severity producer. # @param severity_producer [SeverityProducer] the severity producer to use to determine severity of an issue # # TODO add semantic_label_provider # def initialize @diagnostics = [] @error_count = 0 @warning_count = 0 end # Returns true when errors have been diagnosed. def errors? @error_count > 0 end # Returns true when warnings have been diagnosed. def warnings? @warning_count > 0 end # Returns true when errors and/or warnings have been diagnosed. def errors_or_warnings? errors? || warnings? end # Returns the diagnosed errors in the order they were reported. def errors @diagnostics.select { |d| d.severity == :error } end # Returns the diagnosed warnings in the order they were reported. # (This includes :warning and :deprecation severity) def warnings @diagnostics.select { |d| d.severity == :warning || d.severity == :deprecation } end def errors_and_warnings @diagnostics.select { |d| d.severity != :ignore } end # Returns the ignored diagnostics in the order they were reported (if reported at all) def ignored @diagnostics.select { |d| d.severity == :ignore } end # Add a diagnostic, or all diagnostics from another acceptor to the set of diagnostics # @param diagnostic [Diagnostic, Acceptor] diagnostic(s) that should be accepted def accept(diagnostic) if diagnostic.is_a?(Acceptor) diagnostic.diagnostics.each { |d| _accept(d) } else _accept(diagnostic) end end # Prunes the contain diagnostics by removing those for which the given block returns true. # The internal statistics is updated as a consequence of removing. # @return [Array<Diagnostic, nil] the removed set of diagnostics or nil if nothing was removed # def prune(&block) removed = [] @diagnostics.delete_if do |d| should_remove = yield(d) if should_remove removed << d end should_remove end removed.each do |d| case d.severity when :error @error_count -= 1 when :warning @warning_count -= 1 # there is not ignore_count end end removed.empty? ? nil : removed end private def _accept(diagnostic) @diagnostics << diagnostic case diagnostic.severity when :error @error_count += 1 when :deprecation, :warning @warning_count += 1 end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/adapters.rb
lib/puppet/pops/adapters.rb
# frozen_string_literal: true # The Adapters module contains adapters for Documentation, Origin, SourcePosition, and Loader. # module Puppet::Pops module Adapters class ObjectIdCacheAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :cache def initialize @cache = {} end # Retrieves a mutable hash with all stored values def retrieve(o) @cache[o.__id__] ||= {} end end # A documentation adapter adapts an object with a documentation string. # (The intended use is for a source text parser to extract documentation and store this # in DocumentationAdapter instances). # class DocumentationAdapter < Adaptable::Adapter # @return [String] The documentation associated with an object attr_accessor :documentation end # An empty alternative adapter is used when there is the need to # attach a value to be used if the original is empty. This is used # when a lazy evaluation takes place, and the decision how to handle an # empty case must be delayed. # class EmptyAlternativeAdapter < Adaptable::Adapter # @return [Object] The alternative value associated with an object attr_accessor :empty_alternative end # This class is for backward compatibility only. It's not really an adapter but it is # needed for the puppetlabs-strings gem # @deprecated class SourcePosAdapter def self.adapt(object) new(object) end def initialize(object) @object = object end def file @object.file end def line @object.line end def pos @object.pos end def extract_text @object.locator.extract_text(@object.offset, @object.length) end end # A LoaderAdapter adapts an object with a {Loader}. This is used to make further loading from the # perspective of the adapted object take place in the perspective of this Loader. # # It is typically enough to adapt the root of a model as a search is made towards the root of the model # until a loader is found, but there is no harm in duplicating this information provided a contained # object is adapted with the correct loader. # # @see Utils#find_adapter # @api private class LoaderAdapter < Adaptable::Adapter attr_accessor :loader_name # Finds the loader to use when loading originates from the source position of the given argument. # # @param instance [Model::PopsObject] The model object # @param file [String] the file from where the model was parsed # @param default_loader [Loader] the loader to return if no loader is found for the model # @return [Loader] the found loader or default_loader if it could not be found # def self.loader_for_model_object(model, file = nil, default_loader = nil) loaders = Puppet.lookup(:loaders) { nil } if loaders.nil? default_loader || Loaders.static_loader else loader_name = loader_name_by_source(loaders.environment, model, file) if loader_name.nil? default_loader || loaders[Loader::ENVIRONMENT_PRIVATE] else loaders[loader_name] end end end class PathsAndNameCacheAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :cache, :paths def self.create_adapter(env) adapter = super(env) adapter.paths = env.modulepath.map { |p| Pathname.new(p) } adapter.cache = {} adapter end end # Attempts to find the module that `instance` originates from by looking at it's {SourcePosAdapter} and # compare the `locator.file` found there with the module paths given in the environment found in the # given `scope`. If the file is found to be relative to a path, then the first segment of the relative # path is interpreted as the name of a module. The object that the {SourcePosAdapter} is adapted to # will then be adapted to the private loader for that module and that adapter is returned. # # The method returns `nil` when no module could be found. # # @param environment [Puppet::Node::Environment] the current environment # @param instance [Model::PopsObject] the AST for the code # @param file [String] the path to the file for the code or `nil` # @return [String] the name of the loader associated with the source # @api private def self.loader_name_by_source(environment, instance, file) file = instance.file if file.nil? return nil if file.nil? || EMPTY_STRING == file pn_adapter = PathsAndNameCacheAdapter.adapt(environment) dir = File.dirname(file) pn_adapter.cache.fetch(dir) do |key| mod = find_module_for_dir(environment, pn_adapter.paths, dir) loader_name = mod.nil? ? nil : "#{mod.name} private" pn_adapter.cache[key] = loader_name end end # @api private def self.find_module_for_dir(environment, paths, dir) return nil if dir.nil? file_path = Pathname.new(dir) paths.each do |path| begin relative_path = file_path.relative_path_from(path).to_s.split(File::SEPARATOR) rescue ArgumentError # file_path was not relative to the module_path. That's OK. next end if relative_path.length > 1 mod = environment.module(relative_path[0]) return mod unless mod.nil? end end nil end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/lookup.rb
lib/puppet/pops/lookup.rb
# frozen_string_literal: true # This class is the backing implementation of the Puppet function 'lookup'. # See puppet/functions/lookup.rb for documentation. # module Puppet::Pops module Lookup LOOKUP_OPTIONS = 'lookup_options' GLOBAL = '__global__' # Performs a lookup in the configured scopes and optionally merges the default. # # This is a backing function and all parameters are assumed to have been type checked. # See puppet/functions/lookup.rb for full documentation and all parameter combinations. # # @param name [String|Array<String>] The name or names to lookup # @param type [Types::PAnyType|nil] The expected type of the found value # @param default_value [Object] The value to use as default when no value is found # @param has_default [Boolean] Set to _true_ if _default_value_ is included (_nil_ is a valid _default_value_) # @param merge [MergeStrategy,String,Hash<String,Object>,nil] Merge strategy or hash with strategy and options # @param lookup_invocation [Invocation] Invocation data containing scope, overrides, and defaults # @return [Object] The found value # def self.lookup(name, value_type, default_value, has_default, merge, lookup_invocation) names = name.is_a?(Array) ? name : [name] # find first name that yields a non-nil result and wrap it in a two element array # with name and value. not_found = MergeStrategy::NOT_FOUND override_values = lookup_invocation.override_values result_with_name = [nil, not_found] names.each do |key| value = override_values.include?(key) ? assert_type(["Value found for key '%s' in override hash", key], value_type, override_values[key]) : not_found catch(:no_such_key) { value = search_and_merge(key, lookup_invocation, merge, false) } if value.equal?(not_found) next if value.equal?(not_found) result_with_name = [key, assert_type('Found value', value_type, value)] break end # Use the 'default_values' hash as a last resort if nothing is found if result_with_name[1].equal?(not_found) default_values = lookup_invocation.default_values unless default_values.empty? names.each do |key| value = default_values.include?(key) ? assert_type(["Value found for key '%s' in default values hash", key], value_type, default_values[key]) : not_found next if value.equal?(not_found) result_with_name = [key, value] break end end end answer = result_with_name[1] if answer.equal?(not_found) if block_given? answer = assert_type('Value returned from default block', value_type, yield(name)) elsif has_default answer = assert_type('Default value', value_type, default_value) else lookup_invocation.emit_debug_info(debug_preamble(names)) if Puppet[:debug] fail_lookup(names) end end lookup_invocation.emit_debug_info(debug_preamble(names)) if Puppet[:debug] answer end # @api private def self.debug_preamble(names) if names.size == 1 names = "'#{names[0]}'" else names = names.map { |n| "'#{n}'" }.join(', ') end "Lookup of #{names}" end # @api private def self.search_and_merge(name, lookup_invocation, merge, apl = true) answer = lookup_invocation.lookup_adapter.lookup(name, lookup_invocation, merge) lookup_invocation.emit_debug_info("Automatic Parameter Lookup of '#{name}'") if apl && Puppet[:debug] answer end def self.assert_type(subject, type, value) type ? Types::TypeAsserter.assert_instance_of(subject, type, value) : value end private_class_method :assert_type def self.fail_lookup(names) raise Puppet::DataBinding::LookupError, n_("Function lookup() did not find a value for the name '%{name}'", "Function lookup() did not find a value for any of the names [%{name_list}]", names.size) % { name: names[0], name_list: names.map { |n| "'#{n}'" }.join(', ') } end private_class_method :fail_lookup end end require_relative 'lookup/lookup_adapter' require_relative 'lookup/key_recorder'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/issue_reporter.rb
lib/puppet/pops/issue_reporter.rb
# frozen_string_literal: true module Puppet::Pops class IssueReporter # @param acceptor [Validation::Acceptor] the acceptor containing reported issues # @option options [String] :message (nil) A message text to use as prefix in # a single Error message # @option options [Boolean] :emit_warnings (false) whether warnings should be emitted # @option options [Boolean] :emit_errors (true) whether errors should be # emitted or only the given message # @option options [Exception] :exception_class (Puppet::ParseError) The exception to raise # def self.assert_and_report(acceptor, options) return unless acceptor max_errors = options[:max_errors] || Puppet[:max_errors] max_warnings = options[:max_warnings] || Puppet[:max_warnings] max_deprecations = options[:max_deprecations] || (Puppet[:disable_warnings].include?('deprecations') ? 0 : Puppet[:max_deprecations]) emit_warnings = options[:emit_warnings] || false emit_errors = options[:emit_errors].nil? ? true : !!options[:emit_errors] emit_message = options[:message] emit_exception = options[:exception_class] || Puppet::ParseErrorWithIssue # If there are warnings output them warnings = acceptor.warnings if emit_warnings && warnings.size > 0 formatter = Validation::DiagnosticFormatterPuppetStyle.new emitted_w = 0 emitted_dw = 0 acceptor.warnings.each do |w| if w.severity == :deprecation # Do *not* call Puppet.deprecation_warning it is for internal deprecation, not # deprecation of constructs in manifests! (It is not designed for that purpose even if # used throughout the code base). # log_message(:warning, formatter, w) if emitted_dw < max_deprecations emitted_dw += 1 else log_message(:warning, formatter, w) if emitted_w < max_warnings emitted_w += 1 end break if emitted_w >= max_warnings && emitted_dw >= max_deprecations # but only then end end # If there were errors, report the first found. Use a puppet style formatter. errors = acceptor.errors if errors.size > 0 unless emit_errors raise emit_exception, emit_message end formatter = Validation::DiagnosticFormatterPuppetStyle.new if errors.size == 1 || max_errors <= 1 # raise immediately exception = create_exception(emit_exception, emit_message, formatter, errors[0]) # if an exception was given as cause, use it's backtrace instead of the one indicating "here" if errors[0].exception exception.set_backtrace(errors[0].exception.backtrace) end raise exception end emitted = 0 if emit_message Puppet.err(emit_message) end errors.each do |e| log_message(:err, formatter, e) emitted += 1 break if emitted >= max_errors end giving_up_message = if emit_warnings && warnings.size > 0 _("Language validation logged %{error_count} errors, and %{warning_count} warnings. Giving up") % { error_count: errors.size, warning_count: warnings.size } else _("Language validation logged %{error_count} errors. Giving up") % { error_count: errors.size } end exception = emit_exception.new(giving_up_message) exception.file = errors[0].file raise exception end end def self.format_with_prefix(prefix, message) return message unless prefix [prefix, message].join(' ') end def self.warning(semantic, issue, args) Puppet::Util::Log.create({ :level => :warning, :message => issue.format(args), :arguments => args, :issue_code => issue.issue_code, :file => semantic.file, :line => semantic.line, :pos => semantic.pos, }) end def self.error(exception_class, semantic, issue, args) raise exception_class.new(issue.format(args), semantic.file, semantic.line, semantic.pos, nil, issue.issue_code, args) end def self.create_exception(exception_class, emit_message, formatter, diagnostic) file = diagnostic.file file = (file.is_a?(String) && file.empty?) ? nil : file line = pos = nil if diagnostic.source_pos line = diagnostic.source_pos.line pos = diagnostic.source_pos.pos end exception_class.new(format_with_prefix(emit_message, formatter.format_message(diagnostic)), file, line, pos, nil, diagnostic.issue.issue_code, diagnostic.arguments) end private_class_method :create_exception def self.log_message(severity, formatter, diagnostic) file = diagnostic.file file = (file.is_a?(String) && file.empty?) ? nil : file line = pos = nil if diagnostic.source_pos line = diagnostic.source_pos.line pos = diagnostic.source_pos.pos end Puppet::Util::Log.create({ :level => severity, :message => formatter.format_message(diagnostic), :arguments => diagnostic.arguments, :issue_code => diagnostic.issue.issue_code, :file => file, :line => line, :pos => pos, }) end private_class_method :log_message end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/validation/tasks_checker.rb
lib/puppet/pops/validation/tasks_checker.rb
# frozen_string_literal: true module Puppet::Pops module Validation # Validator that limits the set of allowed expressions to not include catalog related operations # @api private class TasksChecker < Checker4_0 def in_ApplyExpression? top = container(0) step = -1 until container(step) == top return true if container(step).is_a? Puppet::Pops::Model::ApplyBlockExpression step -= 1 end end def check_CollectExpression(o) # Only virtual resource queries are allowed in apply blocks, not exported # resource queries if in_ApplyExpression? if o.query.is_a?(Puppet::Pops::Model::VirtualQuery) super(o) else acceptor.accept(Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING, o, { :klass => o }) end else illegalTasksExpression(o) end end def check_HostClassDefinition(o) illegalTasksExpression(o) end def check_NodeDefinition(o) if in_ApplyExpression? super(o) else illegalTasksExpression(o) end end def check_RelationshipExpression(o) if in_ApplyExpression? super(o) else illegalTasksExpression(o) end end def check_ResourceDefaultsExpression(o) if in_ApplyExpression? super(o) else illegalTasksExpression(o) end end def check_ResourceExpression(o) if in_ApplyExpression? super(o) else illegalTasksExpression(o) end end def check_ResourceOverrideExpression(o) if in_ApplyExpression? super(o) else illegalTasksExpression(o) end end def check_ResourceTypeDefinition(o) illegalTasksExpression(o) end def check_ApplyExpression(o) if in_ApplyExpression? acceptor.accept(Issues::EXPRESSION_NOT_SUPPORTED_WHEN_COMPILING, o, { :klass => o }) end end def illegalTasksExpression(o) acceptor.accept(Issues::EXPRESSION_NOT_SUPPORTED_WHEN_SCRIPTING, o, { :klass => o }) end def resource_without_title?(o) false end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/validation/validator_factory_4_0.rb
lib/puppet/pops/validation/validator_factory_4_0.rb
# frozen_string_literal: true module Puppet::Pops module Validation # Configures validation suitable for 4.0 # class ValidatorFactory_4_0 < Factory # Produces the checker to use def checker diagnostic_producer if Puppet[:tasks] require_relative 'tasks_checker' TasksChecker.new(diagnostic_producer) else Checker4_0.new(diagnostic_producer) end end # Produces the label provider to use def label_provider Model::ModelLabelProvider.new() end # Produces the severity producer to use def severity_producer p = super # Configure each issue that should **not** be an error # # Validate as per the current runtime configuration p[Issues::RT_NO_STORECONFIGS_EXPORT] = Puppet[:storeconfigs] ? :ignore : :warning p[Issues::RT_NO_STORECONFIGS] = Puppet[:storeconfigs] ? :ignore : :warning p[Issues::FUTURE_RESERVED_WORD] = :deprecation p[Issues::DUPLICATE_KEY] = Puppet[:strict] == :off ? :ignore : Puppet[:strict] p[Issues::NAME_WITH_HYPHEN] = :error p[Issues::EMPTY_RESOURCE_SPECIALIZATION] = :ignore p[Issues::CLASS_NOT_VIRTUALIZABLE] = :error p[Issues::ILLEGAL_NONLITERAL_PARAMETER_TYPE] = :deprecation p end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/validation/checker4_0.rb
lib/puppet/pops/validation/checker4_0.rb
# frozen_string_literal: true require_relative '../../../puppet/pops/evaluator/external_syntax_support' module Puppet::Pops module Validation # A Validator validates a model. # # Validation is performed on each model element in isolation. Each method should validate the model element's state # but not validate its referenced/contained elements except to check their validity in their respective role. # The intent is to drive the validation with a tree iterator that visits all elements in a model. # # # TODO: Add validation of multiplicities - this is a general validation that can be checked for all # Model objects via their metamodel. (I.e an extra call to multiplicity check in polymorph check). # This is however mostly valuable when validating model to model transformations, and is therefore T.B.D # class Checker4_0 < Evaluator::LiteralEvaluator include Puppet::Pops::Evaluator::ExternalSyntaxSupport attr_reader :acceptor attr_reader :migration_checker def self.check_visitor # Class instance variable rather than Class variable because methods visited # may be overridden in subclass @check_visitor ||= Visitor.new(nil, 'check', 0, 0) end # Initializes the validator with a diagnostics producer. This object must respond to # `:will_accept?` and `:accept`. # def initialize(diagnostics_producer) super() @@rvalue_visitor ||= Visitor.new(nil, "rvalue", 0, 0) @@hostname_visitor ||= Visitor.new(nil, "hostname", 1, 2) @@assignment_visitor ||= Visitor.new(nil, "assign", 0, 1) @@query_visitor ||= Visitor.new(nil, "query", 0, 0) @@relation_visitor ||= Visitor.new(nil, "relation", 0, 0) @@idem_visitor ||= Visitor.new(nil, "idem", 0, 0) @check_visitor = self.class.check_visitor @acceptor = diagnostics_producer # Use null migration checker unless given in context @migration_checker = (Puppet.lookup(:migration_checker) { Migration::MigrationChecker.new() }) end # Validates the entire model by visiting each model element and calling `check`. # The result is collected (or acted on immediately) by the configured diagnostic provider/acceptor # given when creating this Checker. # def validate(model) # tree iterate the model, and call check for each element @path = [] check(model) internal_check_top_construct_in_module(model) model._pcore_all_contents(@path) { |element| check(element) } end def container(index = -1) @path[index] end # Performs regular validity check def check(o) @check_visitor.visit_this_0(self, o) end # Performs check if this is a vaid hostname expression # @param single_feature_name [String, nil] the name of a single valued hostname feature of the value's container. e.g. 'parent' def hostname(o, semantic) @@hostname_visitor.visit_this_1(self, o, semantic) end # Performs check if this is valid as a query def query(o) @@query_visitor.visit_this_0(self, o) end # Performs check if this is valid as a relationship side def relation(o) @@relation_visitor.visit_this_0(self, o) end # Performs check if this is valid as a rvalue def rvalue(o) @@rvalue_visitor.visit_this_0(self, o) end #---TOP CHECK # Performs check if this is valid as a container of a definition (class, define, node) def top(definition, idx = -1) o = container(idx) idx -= 1 case o when NilClass, Model::ApplyExpression, Model::HostClassDefinition, Model::Program # ok, stop scanning parents when Model::BlockExpression c = container(idx) if !c.is_a?(Model::Program) && (definition.is_a?(Model::FunctionDefinition) || definition.is_a?(Model::TypeAlias) || definition.is_a?(Model::TypeDefinition)) # not ok. These can never be nested in a block acceptor.accept(Issues::NOT_ABSOLUTE_TOP_LEVEL, definition) else # ok, if this is a block representing the body of a class, or is top level top(definition, idx) end when Model::LambdaExpression # A LambdaExpression is a BlockExpression, and this check is needed to prevent the polymorph method for BlockExpression # to accept a lambda. # A lambda can not iteratively create classes, nodes or defines as the lambda does not have a closure. acceptor.accept(Issues::NOT_TOP_LEVEL, definition) else # fail, reached a container that is not top level acceptor.accept(Issues::NOT_TOP_LEVEL, definition) end end # Checks the LHS of an assignment (is it assignable?). # If args[0] is true, assignment via index is checked. # def assign(o, via_index = false) @@assignment_visitor.visit_this_1(self, o, via_index) end # Checks if the expression has side effect ('idem' is latin for 'the same', here meaning that the evaluation state # is known to be unchanged after the expression has been evaluated). The result is not 100% authoritative for # negative answers since analysis of function behavior is not possible. # @return [Boolean] true if expression is known to have no effect on evaluation state # def idem(o) @@idem_visitor.visit_this_0(self, o) end # Returns the last expression in a block, or the expression, if that expression is idem def ends_with_idem(o) if o.is_a?(Model::BlockExpression) last = o.statements[-1] idem(last) ? last : nil else idem(o) ? o : nil end end #---ASSIGNMENT CHECKS def assign_VariableExpression(o, via_index) varname_string = varname_to_s(o.expr) if varname_string =~ Patterns::NUMERIC_VAR_NAME acceptor.accept(Issues::ILLEGAL_NUMERIC_ASSIGNMENT, o, :varname => varname_string) end # Can not assign to something in another namespace (i.e. a '::' in the name is not legal) if acceptor.will_accept? Issues::CROSS_SCOPE_ASSIGNMENT if varname_string =~ /::/ acceptor.accept(Issues::CROSS_SCOPE_ASSIGNMENT, o, :name => varname_string) end end # TODO: Could scan for reassignment of the same variable if done earlier in the same container # Or if assigning to a parameter (more work). end def assign_AccessExpression(o, via_index) # Are indexed assignments allowed at all ? $x[x] = '...' if acceptor.will_accept? Issues::ILLEGAL_INDEXED_ASSIGNMENT acceptor.accept(Issues::ILLEGAL_INDEXED_ASSIGNMENT, o) else # Then the left expression must be assignable-via-index assign(o.left_expr, true) end end def assign_LiteralList(o, via_index) o.values.each { |x| assign(x) } end def assign_Object(o, via_index) # Can not assign to anything else (differentiate if this is via index or not) # i.e. 10 = 'hello' vs. 10['x'] = 'hello' (the root is reported as being in error in both cases) # acceptor.accept(via_index ? Issues::ILLEGAL_ASSIGNMENT_VIA_INDEX : Issues::ILLEGAL_ASSIGNMENT, o) end #---CHECKS def check_Object(o) end def check_Factory(o) check(o.model) end def check_AccessExpression(o) # Only min range is checked, all other checks are RT checks as they depend on the resulting type # of the LHS. if o.keys.size < 1 acceptor.accept(Issues::MISSING_INDEX, o) end end def check_AssignmentExpression(o) case o.operator when '=' assign(o.left_expr) rvalue(o.right_expr) when '+=', '-=' acceptor.accept(Issues::APPENDS_DELETES_NO_LONGER_SUPPORTED, o, { :operator => o.operator }) else acceptor.accept(Issues::UNSUPPORTED_OPERATOR, o, { :operator => o.operator }) end end # Checks that operation with :+> is contained in a ResourceOverride or Collector. # # Parent of an AttributeOperation can be one of: # * CollectExpression # * ResourceOverride # * ResourceBody (ILLEGAL this is a regular resource expression) # * ResourceDefaults (ILLEGAL) # def check_AttributeOperation(o) if o.operator == '+>' # Append operator use is constrained p = container unless p.is_a?(Model::CollectExpression) || p.is_a?(Model::ResourceOverrideExpression) acceptor.accept(Issues::ILLEGAL_ATTRIBUTE_APPEND, o, { :name => o.attribute_name, :parent => p }) end end rvalue(o.value_expr) end def check_AttributesOperation(o) # Append operator use is constrained p = container case p when Model::AbstractResource # do nothing when Model::CollectExpression # do nothing else # protect against just testing a snippet that has no parent, error message will be a bit strange # but it is not for a real program. parent2 = p.nil? ? o : container(-2) unless parent2.is_a?(Model::AbstractResource) acceptor.accept(Issues::UNSUPPORTED_OPERATOR_IN_CONTEXT, parent2, :operator => '* =>') end end rvalue(o.expr) end def check_BinaryExpression(o) rvalue(o.left_expr) rvalue(o.right_expr) end def resource_without_title?(o) if o.instance_of?(Model::BlockExpression) statements = o.statements statements.length == 2 && statements[0].instance_of?(Model::QualifiedName) && statements[1].instance_of?(Model::LiteralHash) else false end end def check_BlockExpression(o) if resource_without_title?(o) acceptor.accept(Issues::RESOURCE_WITHOUT_TITLE, o, :name => o.statements[0].value) else o.statements[0..-2].each do |statement| if idem(statement) acceptor.accept(Issues::IDEM_EXPRESSION_NOT_LAST, statement) break # only flag the first end end end end def check_CallNamedFunctionExpression(o) functor = o.functor_expr if functor.is_a?(Model::QualifiedReference) || functor.is_a?(Model::AccessExpression) && functor.left_expr.is_a?(Model::QualifiedReference) # ok (a call to a type) return nil end case functor when Model::QualifiedName # ok nil when Model::RenderStringExpression # helpful to point out this easy to make Epp error acceptor.accept(Issues::ILLEGAL_EPP_PARAMETERS, o) else acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.functor_expr, { :feature => 'function name', :container => o }) end end def check_EppExpression(o) p = container if p.is_a?(Model::LambdaExpression) internal_check_no_capture(p, o) internal_check_parameter_name_uniqueness(p) end end def check_HeredocExpression(o) # Only syntax check static text in heredoc during validation - dynamic text is validated by the evaluator. expr = o.text_expr if expr.is_a?(Model::LiteralString) assert_external_syntax(nil, expr.value, o.syntax, o.text_expr) end end def check_MethodCallExpression(o) unless o.functor_expr.is_a? Model::QualifiedName acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.functor_expr, :feature => 'function name', :container => o) end end def check_CaseExpression(o) rvalue(o.test) # There can only be one LiteralDefault case option value found_default = false o.options.each do |option| option.values.each do |value| next unless value.is_a?(Model::LiteralDefault) # Flag the second default as 'unreachable' acceptor.accept(Issues::DUPLICATE_DEFAULT, value, :container => o) if found_default found_default = true end end end def check_CaseOption(o) o.values.each { |v| rvalue(v) } end def check_CollectExpression(o) unless o.type_expr.is_a? Model::QualifiedReference acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.type_expr, :feature => 'type name', :container => o) end end # Only used for function names, grammar should not be able to produce something faulty, but # check anyway if model is created programmatically (it will fail in transformation to AST for sure). def check_NamedAccessExpression(o) name = o.right_expr unless name.is_a? Model::QualifiedName acceptor.accept(Issues::ILLEGAL_EXPRESSION, name, :feature => 'function name', :container => container) end end RESERVED_TYPE_NAMES = { 'type' => true, 'any' => true, 'unit' => true, 'scalar' => true, 'boolean' => true, 'numeric' => true, 'integer' => true, 'float' => true, 'collection' => true, 'array' => true, 'hash' => true, 'tuple' => true, 'struct' => true, 'variant' => true, 'optional' => true, 'enum' => true, 'regexp' => true, 'pattern' => true, 'runtime' => true, 'init' => true, 'object' => true, 'sensitive' => true, 'semver' => true, 'semverrange' => true, 'string' => true, 'timestamp' => true, 'timespan' => true, 'typeset' => true, } FUTURE_RESERVED_WORDS = { 'plan' => true } # for 'class', 'define', and function def check_NamedDefinition(o) top(o) if o.name !~ Patterns::CLASSREF_DECL acceptor.accept(Issues::ILLEGAL_DEFINITION_NAME, o, { :name => o.name }) end internal_check_file_namespace(o) internal_check_reserved_type_name(o, o.name) internal_check_future_reserved_word(o, o.name) end def check_TypeAlias(o) top(o) if o.name !~ Patterns::CLASSREF_EXT_DECL acceptor.accept(Issues::ILLEGAL_DEFINITION_NAME, o, { :name => o.name }) end internal_check_reserved_type_name(o, o.name) internal_check_type_ref(o, o.type_expr) end def check_TypeMapping(o) top(o) lhs = o.type_expr lhs_type = 0 # Not Runtime if lhs.is_a?(Model::AccessExpression) left = lhs.left_expr if left.is_a?(Model::QualifiedReference) && left.cased_value == 'Runtime' lhs_type = 1 # Runtime keys = lhs.keys # Must be a literal string or pattern replacement lhs_type = 2 if keys.size == 2 && pattern_with_replacement?(keys[1]) end end if lhs_type == 0 # This is not a TypeMapping. Something other than Runtime[] on LHS acceptor.accept(Issues::UNSUPPORTED_EXPRESSION, o) else rhs = o.mapping_expr if pattern_with_replacement?(rhs) acceptor.accept(Issues::ILLEGAL_SINGLE_TYPE_MAPPING, o) if lhs_type == 1 elsif type_ref?(rhs) acceptor.accept(Issues::ILLEGAL_REGEXP_TYPE_MAPPING, o) if lhs_type == 2 else acceptor.accept(lhs_type == 1 ? Issues::ILLEGAL_SINGLE_TYPE_MAPPING : Issues::ILLEGAL_REGEXP_TYPE_MAPPING, o) end end end def pattern_with_replacement?(o) if o.is_a?(Model::LiteralList) v = o.values v.size == 2 && v[0].is_a?(Model::LiteralRegularExpression) && v[1].is_a?(Model::LiteralString) else false end end def type_ref?(o) o = o.left_expr if o.is_a?(Model::AccessExpression) o.is_a?(Model::QualifiedReference) end def check_TypeDefinition(o) top(o) internal_check_reserved_type_name(o, o.name) # TODO: Check TypeDefinition body. For now, just error out acceptor.accept(Issues::UNSUPPORTED_EXPRESSION, o) end def check_FunctionDefinition(o) check_NamedDefinition(o) internal_check_return_type(o) internal_check_parameter_name_uniqueness(o) end def check_HostClassDefinition(o) check_NamedDefinition(o) internal_check_no_capture(o) internal_check_parameter_name_uniqueness(o) internal_check_reserved_params(o) internal_check_no_idem_last(o) internal_check_parameter_type_literal(o) end def check_ResourceTypeDefinition(o) check_NamedDefinition(o) internal_check_no_capture(o) internal_check_parameter_name_uniqueness(o) internal_check_reserved_params(o) internal_check_no_idem_last(o) end def internal_check_parameter_type_literal(o) o.parameters.each do |p| next unless p.type_expr type = nil catch :not_literal do type = literal(p.type_expr) end acceptor.accept(Issues::ILLEGAL_NONLITERAL_PARAMETER_TYPE, p, { name: p.name, type_class: p.type_expr.class }) if type.nil? end end def internal_check_return_type(o) r = o.return_type internal_check_type_ref(o, r) unless r.nil? end def internal_check_type_ref(o, r) n = r.is_a?(Model::AccessExpression) ? r.left_expr : r if n.is_a? Model::QualifiedReference internal_check_future_reserved_word(r, n.value) else acceptor.accept(Issues::ILLEGAL_EXPRESSION, r, :feature => 'a type reference', :container => o) end end def internal_check_no_idem_last(o) violator = ends_with_idem(o.body) if violator acceptor.accept(Issues::IDEM_NOT_ALLOWED_LAST, violator, { :container => o }) unless resource_without_title?(violator) end end def internal_check_capture_last(o) accepted_index = o.parameters.size() - 1 o.parameters.each_with_index do |p, index| if p.captures_rest && index != accepted_index acceptor.accept(Issues::CAPTURES_REST_NOT_LAST, p, { :param_name => p.name }) end end end def internal_check_no_capture(o, container = o) o.parameters.each do |p| if p.captures_rest acceptor.accept(Issues::CAPTURES_REST_NOT_SUPPORTED, p, { :container => container, :param_name => p.name }) end end end def internal_check_reserved_type_name(o, name) if RESERVED_TYPE_NAMES[name] acceptor.accept(Issues::RESERVED_TYPE_NAME, o, { :name => name }) end end def internal_check_future_reserved_word(o, name) if FUTURE_RESERVED_WORDS[name] acceptor.accept(Issues::FUTURE_RESERVED_WORD, o, { :word => name }) end end NO_NAMESPACE = :no_namespace NO_PATH = :no_path BAD_MODULE_FILE = :bad_module_file def internal_check_file_namespace(o) file = o.locator.file return if file.nil? || file == '' # e.g. puppet apply -e '...' file_namespace = namespace_for_file(file) return if file_namespace == NO_NAMESPACE # Downcasing here because check is case-insensitive if file_namespace == BAD_MODULE_FILE || !o.name.downcase.start_with?(file_namespace) acceptor.accept(Issues::ILLEGAL_DEFINITION_LOCATION, o, { :name => o.name, :file => file }) end end def internal_check_top_construct_in_module(prog) return unless prog.is_a?(Model::Program) && !prog.body.nil? # Check that this is a module autoloaded file file = prog.locator.file return if file.nil? return if namespace_for_file(file) == NO_NAMESPACE body = prog.body return if prog.body.is_a?(Model::Nop) # Ignore empty or comment-only files if body.is_a?(Model::BlockExpression) body.statements.each { |s| acceptor.accept(Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION, s) unless valid_top_construct?(s) } else acceptor.accept(Issues::ILLEGAL_TOP_CONSTRUCT_LOCATION, body) unless valid_top_construct?(body) end end def valid_top_construct?(o) o.is_a?(Model::Definition) && !o.is_a?(Model::NodeDefinition) end # @api private class Puppet::Util::FileNamespaceAdapter < Puppet::Pops::Adaptable::Adapter attr_accessor :file_to_namespace def self.create_adapter(env) adapter = super(env) adapter.file_to_namespace = {} adapter end end def namespace_for_file(file) env = Puppet.lookup(:current_environment) return NO_NAMESPACE if env.nil? adapter = Puppet::Util::FileNamespaceAdapter.adapt(env) file_namespace = adapter.file_to_namespace[file] return file_namespace unless file_namespace.nil? # No cache entry, so we do the calculation path = Pathname.new(file) return adapter.file_to_namespace[file] = NO_NAMESPACE if path.extname != ".pp" path = path.expand_path return adapter.file_to_namespace[file] = NO_NAMESPACE if initial_manifest?(path, env.manifest) # All auto-loaded files from modules come from a module search path dir relative_path = get_module_relative_path(path, env.full_modulepath) return adapter.file_to_namespace[file] = NO_NAMESPACE if relative_path == NO_PATH # If a file comes from a module, but isn't in the right place, always error names = dir_to_names(relative_path) adapter.file_to_namespace[file] = (names == BAD_MODULE_FILE ? BAD_MODULE_FILE : names.join("::").freeze) end def initial_manifest?(path, manifest_setting) return false if manifest_setting.nil? || manifest_setting == :no_manifest string_path = path.to_s string_path == manifest_setting || string_path.start_with?(manifest_setting) end # Get the path of +file_path+ relative to the first directory in # +modulepath_directories+ that is an ancestor of +file_path+. Return NO_PATH # if none is found. def get_module_relative_path(file_path, modulepath_directories) clean_file = file_path.cleanpath.to_s parent_path = modulepath_directories.find { |path_dir| is_parent_dir_of?(path_dir, clean_file) } return NO_PATH if parent_path.nil? file_path.relative_path_from(Pathname.new(parent_path)) end private :get_module_relative_path def is_parent_dir_of?(parent_dir, child_dir) parent_dir_path = Pathname.new(parent_dir) clean_parent = parent_dir_path.cleanpath.to_s + File::SEPARATOR child_dir.start_with?(clean_parent) end private :is_parent_dir_of? def dir_to_names(relative_path) # Downcasing here because check is case-insensitive path_components = relative_path.to_s.downcase.split(File::SEPARATOR) # Example definition dir: manifests in this path: # <module name>/manifests/<module subdir>/<classfile>.pp dir = path_components[1] # How can we get this result? # If it is not an initial manifest, it must come from a module, # and from the manifests dir there. This may never get used... return BAD_MODULE_FILE unless dir == 'manifests' || dir == 'functions' || dir == 'types' || dir == 'plans' names = path_components[2..-2] # Directories inside module names.unshift(path_components[0]) # Name of the module itself # Do not include name of module init file at top level of module # e.g. <module name>/manifests/init.pp filename = path_components[-1] unless path_components.length == 3 && filename == 'init.pp' names.push(filename[0..-4]) # Remove .pp from filename end names end RESERVED_PARAMETERS = { 'name' => true, 'title' => true, } def internal_check_reserved_params(o) o.parameters.each do |p| if RESERVED_PARAMETERS[p.name] acceptor.accept(Issues::RESERVED_PARAMETER, p, { :container => o, :param_name => p.name }) end end end def internal_check_parameter_name_uniqueness(o) unique = Set.new o.parameters.each do |p| acceptor.accept(Issues::DUPLICATE_PARAMETER, p, { :param_name => p.name }) unless unique.add?(p.name) end end def check_IfExpression(o) rvalue(o.test) end def check_KeyedEntry(o) rvalue(o.key) rvalue(o.value) # In case there are additional things to forbid than non-rvalues # acceptor.accept(Issues::ILLEGAL_EXPRESSION, o.key, :feature => 'hash key', :container => container) end def check_LambdaExpression(o) internal_check_capture_last(o) internal_check_return_type(o) end def check_LiteralList(o) o.values.each { |v| rvalue(v) } end def check_LiteralInteger(o) v = o.value if v < MIN_INTEGER || v > MAX_INTEGER acceptor.accept(Issues::NUMERIC_OVERFLOW, o, { :value => v }) end end def check_LiteralHash(o) # the keys of a literal hash may be non-literal expressions. They cannot be checked. unique = Set.new o.entries.each do |entry| catch(:not_literal) do literal_key = literal(entry.key) acceptor.accept(Issues::DUPLICATE_KEY, entry, { :key => literal_key }) if unique.add?(literal_key).nil? end end end def check_NodeDefinition(o) # Check that hostnames are valid hostnames (or regular expressions) hostname(o.host_matches, o) top(o) violator = ends_with_idem(o.body) if violator acceptor.accept(Issues::IDEM_NOT_ALLOWED_LAST, violator, { :container => o }) unless resource_without_title?(violator) end unless o.parent.nil? acceptor.accept(Issues::ILLEGAL_NODE_INHERITANCE, o.parent) end end # No checking takes place - all expressions using a QualifiedName need to check. This because the # rules are slightly different depending on the container (A variable allows a numeric start, but not # other names). This means that (if the lexer/parser so chooses) a QualifiedName # can be anything when it represents a Bare Word and evaluates to a String. # def check_QualifiedName(o) end # Checks that the value is a valid UpperCaseWord (a CLASSREF), and optionally if it contains a hypen. # DOH: QualifiedReferences are created with LOWER CASE NAMES at parse time def check_QualifiedReference(o) # Is this a valid qualified name? if o.cased_value !~ Patterns::CLASSREF_EXT acceptor.accept(Issues::ILLEGAL_CLASSREF, o, { :name => o.cased_value }) end end def check_QueryExpression(o) query(o.expr) if o.expr # is optional end def relation_Object(o) rvalue(o) end def relation_CollectExpression(o); end def relation_RelationshipExpression(o); end def check_Parameter(o) if o.name =~ /^(?:0x)?[0-9]+$/ acceptor.accept(Issues::ILLEGAL_NUMERIC_PARAMETER, o, :name => o.name) end unless o.name =~ Patterns::PARAM_NAME acceptor.accept(Issues::ILLEGAL_PARAM_NAME, o, :name => o.name) end return unless o.value internal_check_illegal_assignment(o.value) end def internal_check_illegal_assignment(o) if o.is_a?(Model::AssignmentExpression) acceptor.accept(Issues::ILLEGAL_ASSIGNMENT_CONTEXT, o) else # recursively check all contents unless it's a lambda expression. A lambda may contain # local assignments o._pcore_contents { |model| internal_check_illegal_assignment(model) } unless o.is_a?(Model::LambdaExpression) end end # relationship_side: resource # | resourceref # | collection # | variable # | quotedtext # | selector # | casestatement # | hasharrayaccesses def check_RelationshipExpression(o) relation(o.left_expr) relation(o.right_expr) end def check_ResourceExpression(o) # The expression for type name cannot be statically checked - this is instead done at runtime # to enable better error message of the result of the expression rather than the static instruction. # (This can be revised as there are static constructs that are illegal, but require updating many # tests that expect the detailed reporting). type_name_expr = o.type_name if o.form && o.form != 'regular' && type_name_expr.is_a?(Model::QualifiedName) && type_name_expr.value == 'class' acceptor.accept(Issues::CLASS_NOT_VIRTUALIZABLE, o) end end def check_ResourceBody(o) seenUnfolding = false o.operations.each do |ao| if ao.is_a?(Model::AttributesOperation) if seenUnfolding acceptor.accept(Issues::MULTIPLE_ATTRIBUTES_UNFOLD, ao) else seenUnfolding = true end end end end def check_ResourceDefaultsExpression(o) if o.form != 'regular' acceptor.accept(Issues::NOT_VIRTUALIZEABLE, o) end end def check_ResourceOverrideExpression(o) if o.form != 'regular' acceptor.accept(Issues::NOT_VIRTUALIZEABLE, o) end end def check_ReservedWord(o) if o.future acceptor.accept(Issues::FUTURE_RESERVED_WORD, o, :word => o.word) else acceptor.accept(Issues::RESERVED_WORD, o, :word => o.word) end end def check_SelectorExpression(o) rvalue(o.left_expr) # There can only be one LiteralDefault case option value defaults = o.selectors.select { |v| v.matching_expr.is_a?(Model::LiteralDefault) } unless defaults.size <= 1 # Flag the second default as 'unreachable' acceptor.accept(Issues::DUPLICATE_DEFAULT, defaults[1].matching_expr, :container => o) end end def check_SelectorEntry(o) rvalue(o.matching_expr) end def check_UnaryExpression(o) rvalue(o.expr) end def check_UnlessExpression(o) rvalue(o.test) # TODO: Unless may not have an else part that is an IfExpression (grammar denies this though) end # Checks that variable is either strictly 0, or a non 0 starting decimal number, or a valid VAR_NAME def check_VariableExpression(o) # The expression must be a qualified name or an integer name_expr = o.expr return if name_expr.is_a?(Model::LiteralInteger) if !name_expr.is_a?(Model::QualifiedName) acceptor.accept(Issues::ILLEGAL_EXPRESSION, o, :feature => 'name', :container => o) else # name must be either a decimal string value, or a valid NAME name = o.expr.value if name[0, 1] =~ /[0-9]/ unless name =~ Patterns::NUMERIC_VAR_NAME acceptor.accept(Issues::ILLEGAL_NUMERIC_VAR_NAME, o, :name => name) end else unless name =~ Patterns::VAR_NAME acceptor.accept(Issues::ILLEGAL_VAR_NAME, o, :name => name) end end end end #--- HOSTNAME CHECKS # Transforms Array of host matching expressions into a (Ruby) array of AST::HostName def hostname_Array(o, semantic) o.each { |x| hostname(x, semantic) } end def hostname_String(o, semantic) # The 3.x checker only checks for illegal characters - if matching /[^-\w.]/ the name is invalid, # but this allows pathological names like "a..b......c", "----" # TODO: Investigate if more illegal hostnames should be flagged. # if o =~ Patterns::ILLEGAL_HOSTNAME_CHARS acceptor.accept(Issues::ILLEGAL_HOSTNAME_CHARS, semantic, :hostname => o) end end def hostname_LiteralValue(o, semantic) hostname_String(o.value.to_s, o) end def hostname_ConcatenatedString(o, semantic) # Puppet 3.1. only accepts a concatenated string without interpolated expressions the_expr = o.segments.index { |s| s.is_a?(Model::TextExpression) } if the_expr acceptor.accept(Issues::ILLEGAL_HOSTNAME_INTERPOLATION, o.segments[the_expr].expr) elsif o.segments.size() != 1 # corner case, bad model, concatenation of several plain strings acceptor.accept(Issues::ILLEGAL_HOSTNAME_INTERPOLATION, o) else # corner case, may be ok, but lexer may have replaced with plain string, this is # here if it does not hostname_String(o.segments[0], o.segments[0]) end end def hostname_QualifiedName(o, semantic) hostname_String(o.value.to_s, o) end def hostname_QualifiedReference(o, semantic) hostname_String(o.value.to_s, o) end def hostname_LiteralNumber(o, semantic) # always ok end def hostname_LiteralDefault(o, semantic) # always ok end def hostname_LiteralRegularExpression(o, semantic) # always ok end def hostname_Object(o, semantic) acceptor.accept(Issues::ILLEGAL_EXPRESSION, o, { :feature => 'hostname', :container => semantic }) end #---QUERY CHECKS # Anything not explicitly allowed is flagged as error. def query_Object(o) acceptor.accept(Issues::ILLEGAL_QUERY_EXPRESSION, o) end # Puppet AST only allows == and != # def query_ComparisonExpression(o) acceptor.accept(Issues::ILLEGAL_QUERY_EXPRESSION, o) unless ['==', '!='].include? o.operator end # Allows AND, OR, and checks if left/right are allowed in query. def query_BooleanExpression(o) query o.left_expr query o.right_expr end def query_ParenthesizedExpression(o) query(o.expr) end def query_VariableExpression(o); end def query_QualifiedName(o); end def query_LiteralNumber(o); end def query_LiteralString(o); end def query_LiteralBoolean(o); end #---RVALUE CHECKS # By default, all expressions are reported as being rvalues # Implement specific rvalue checks for those that are not. # def rvalue_Expression(o); end def rvalue_CollectExpression(o) acceptor.accept(Issues::NOT_RVALUE, o) end def rvalue_Definition(o) acceptor.accept(Issues::NOT_RVALUE, o) end def rvalue_NodeDefinition(o) acceptor.accept(Issues::NOT_RVALUE, o) end def rvalue_UnaryExpression(o) rvalue o.expr end #--IDEM CHECK def idem_Object(o) false end def idem_Nop(o) true end def idem_NilClass(o) true end def idem_Literal(o) true end def idem_LiteralList(o) true end def idem_LiteralHash(o) true end def idem_Factory(o) idem(o.model) end def idem_AccessExpression(o) true end def idem_BinaryExpression(o) true end def idem_MatchExpression(o) false # can have side effect of setting $n match variables end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/resource/param.rb
lib/puppet/pops/resource/param.rb
# frozen_string_literal: true # An implementation of the interface Puppet::Resource # that adapts the 3.x compiler and catalog expectations on # a resource instance. This instance is backed by a # pcore representation of the resource type an instance of this # ruby class. # # This class must inherit from Puppet::Resource because of the # class expectations in existing logic. # # This implementation does not support # * setting 'strict' - strictness (must refer to an existing type) is always true # * does not support the indirector # # module Puppet::Pops module Resource class Param # This make this class instantiable from Puppet include Puppet::Pops::Types::PuppetObject def self.register_ptype(loader, ir) @ptype = Pcore.create_object_type(loader, ir, self, 'Puppet::Resource::Param', nil, { Types::KEY_TYPE => Types::PTypeType::DEFAULT, Types::KEY_NAME => Types::PStringType::NON_EMPTY, 'name_var' => { Types::KEY_TYPE => Types::PBooleanType::DEFAULT, Types::KEY_VALUE => false } }, EMPTY_HASH, [Types::KEY_NAME]) end attr_reader :name attr_reader :type attr_reader :name_var def initialize(type, name, name_var = false) @type = type @name = name @name_var = name_var end def to_s name end def self._pcore_type @ptype end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/resource/resource_type_impl.rb
lib/puppet/pops/resource/resource_type_impl.rb
# frozen_string_literal: true require_relative 'param' module Puppet::Pops module Resource def self.register_ptypes(loader, ir) types = [Param, ResourceTypeImpl].map do |c| c.register_ptype(loader, ir) end types.each { |t| t.resolve(loader) } end class ResourceTypeImpl # Make instances of this class directly creatable from the Puppet Language # as object. # include Puppet::Pops::Types::PuppetObject # Instances of ResourceTypeImpl can be used as the type of a Puppet::Parser::Resource/Puppet::Resource when compiling # include Puppet::CompilableResourceType # Returns the Puppet Type for this instance. def self._pcore_type @ptype end def self.register_ptype(loader, ir) param_ref = Types::PTypeReferenceType.new('Puppet::Resource::Param') @ptype = Pcore.create_object_type(loader, ir, self, 'Puppet::Resource::ResourceType3', nil, { Types::KEY_NAME => Types::PStringType::NON_EMPTY, 'properties' => { Types::KEY_TYPE => Types::PArrayType.new(param_ref), Types::KEY_VALUE => EMPTY_ARRAY }, 'parameters' => { Types::KEY_TYPE => Types::PArrayType.new(param_ref), Types::KEY_VALUE => EMPTY_ARRAY }, 'title_patterns_hash' => { Types::KEY_TYPE => Types::POptionalType.new( Types::PHashType.new(Types::PRegexpType::DEFAULT, Types::PArrayType.new(Types::PStringType::NON_EMPTY)) ), Types::KEY_VALUE => nil }, 'isomorphic' => { Types::KEY_TYPE => Types::PBooleanType::DEFAULT, Types::KEY_VALUE => true }, 'capability' => { Types::KEY_TYPE => Types::PBooleanType::DEFAULT, Types::KEY_VALUE => false }, }, EMPTY_HASH, [Types::KEY_NAME]) end def eql?(other) other.is_a?(Puppet::CompilableResourceType) && @name == other.name end alias == eql? # Compares this type against the given _other_ (type) and returns -1, 0, or +1 depending on the order. # @param other [Object] the object to compare against (produces nil, if not kind of Type} # @return [-1, 0, +1, nil] produces -1 if this type is before the given _other_ type, 0 if equals, and 1 if after. # Returns nil, if the given _other_ is not a kind of Type. # @see Comparable # def <=>(other) # Order is only maintained against other types, not arbitrary objects. # The natural order is based on the reference name used when comparing return nil unless other.is_a?(Puppet::CompilableResourceType) # against other type instances. ref <=> other.ref end METAPARAMS = [ :noop, :schedule, :audit, :loglevel, :alias, :tag, :require, :subscribe, :before, :notify, :stage ].freeze # Speed up lookup METAPARAMSET = Set.new(METAPARAMS).freeze attr_reader :name attr_reader :properties attr_reader :parameters attr_reader :title_patterns_hash attr_reader :title_patterns def initialize(name, properties = EMPTY_ARRAY, parameters = EMPTY_ARRAY, title_patterns_hash = nil, isomorphic = true, capability = false) @name = name @properties = properties @parameters = parameters @title_patterns_hash = title_patterns_hash @isomorphic = isomorphic # ignore capability parameter # Compute attributes hash # Compute key_names (possibly compound key if there are multiple name vars). @attributes = {} @key_attributes = [] # Name to kind of attribute @attr_types = {} # Add all meta params METAPARAMS.each { |p| @attr_types[p] = :meta } @property_set = Set.new(properties.map do |p| symname = p.name.to_sym @attributes[symname] = p @key_attributes << symname if p.name_var @attr_types[symname] = :property symname end).freeze @param_set = Set.new(parameters.map do |p| symname = p.name.to_sym @attributes[symname] = p @key_attributes << symname if p.name_var @attr_types[symname] = :param symname end).freeze # API for title patterns is [ [regexp, [ [ [sym, <lambda>], [sym, <lambda>] ] ] ] ] # Where lambdas are optional. This resource type impl does not support lambdas # Note that the pcore file has a simpler hashmap that is post processed here # since the structure must have Symbol instances for names which the .pp representation # does not deliver. # @title_patterns = case @key_attributes.length when 0 # TechDebt: The case of specifying title patterns when having no name vars is unspecified behavior in puppet # Here it is silently ignored. nil when 1 if @title_patterns_hash.nil? [[/(.*)/m, [[@key_attributes.first]]]] else # TechDebt: The case of having one namevar and an empty title patterns is unspecified behavior in puppet. # Here, it may lead to an empty map which may or may not trigger the wanted/expected behavior. # @title_patterns_hash.map { |k, v| [k, v.map { |n| [n.to_sym] }] } end else if @title_patterns_hash.nil? || @title_patterns_hash.empty? # TechDebt: While title patterns must be specified when more than one is used, they do not have # to match/set them all since some namevars can be omitted (to support the use case in # the 'package' type where 'provider' attribute is handled as part of the key without being # set from the title. # raise Puppet::DevError, _("you must specify title patterns when there are two or more key attributes") end @title_patterns_hash.nil? ? [] : @title_patterns_hash.map { |k, v| [k, v.map { |n| [n.to_sym] }] } end end # Override CompilableResource inclusion def is_3x_ruby_plugin? false end # Answers if the parameter name is a parameter/attribute of this type # This is part of the Puppet::Type API # Check if used when compiling (it is triggered in an apply) # def valid_parameter?(name) @attributes.include?(name) || METAPARAMSET.include?(name) end # The type implementation of finish does a lot of things # * iterates over all parameters and calls post_compile on them if the parameter impl responds to post_compile # * validates the relationship parameters # # This implementation does nothing - it is assumed that the catalog is already validated # via the relationship validator (done late in the game). def finish # Do nothing. end # This is called on a resource type # it performs tagging if it is a Class or Node. # It also ensure the parent type is in the catalog, but that is weird since # resource types cannot really inherit def instantiate_resource(scope, resource) # Do nothing because nothing is needed when compiling. # This is what the Puppet::Type implementation does # None of this should be needed # # Make sure our parent class has been evaluated, if we have one. # if parent && !scope.catalog.resource(resource.type, parent) # parent_type(scope).ensure_in_catalog(scope) # end # This will never happen # if ['Class', 'Node'].include? resource.type # scope.catalog.tag(*resource.tags) # end end # Being isomorphic in puppet means that the resource is managing a state # (as opposed to a resource like Exec that is a function, possibly with side effect. # In a Ruby implementation of a resource type, @isomorphic = false is used to turn # off isomorphism, it is true by default. # This is part of the Puppet::Type API. # def isomorphic? @isomorphic end # Produces the names of the attributes that make out the unique id of a resource # def key_attributes @key_attributes end # Gives a type a chance to issue deprecations for parameters. # @param title [String] the title of the resource of this type # @param attributes [Array<Param>] the set parameters in the resource instance def deprecate_params(title, attributes) # TODO: Current API somewhat unclear, if done at type level, or per # Param. end ################################################## # NEVER CALLED COMPILE SIDE FOR A COMPILATION ################################################## # Answers :property, :param or :meta depending on the type of the attribute # According to original version, this is called millions of times # and a cache is required. # @param name [Symbol] def attrtype(name) raise NotImplementedError, "attrtype() - returns the kind (:meta, :param, or :property) of the parameter" # @attr_types[name] end # Returns the implementation of a param/property/attribute - i.e. a Param class def attrclass(name) raise NotImplementedError, "attrclass() - returns the (param) class of the parameter" end # PROBABLY NOT USED WHEN COMPILING # Returns the names of all attributes in a defined order: # * all key attributes (the composite id) # * :provider if it is specified # * all properties # * all parameters # * meta parameters # def allattrs raise NotImplementedError, "allattrs() - return all attribute names in order - probably not used master side" # key_attributes | (parameters & [:provider]) | properties.collect { |property| property.name } | parameters | metaparams end # Sets "applies to host" def apply_to raise NotImplementedError, "apply_to() - probably used when selecting a provider (device/host support)" end def apply_to_host raise NotImplementedError, "apply_to_host() - probably used when selecting a provider (device/host support)" end def apply_to_device raise NotImplementedError, "apply_to_device() - probably used when selecting a provider (device/host support)" end def apply_to_all raise NotImplementedError, "apply_to_all() - probably used when selecting a provider (device/host support)" end def can_apply_to_target(target) raise NotImplementedError, "can_apply_to_target() - probably used when selecting a provider (device/host support)" end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/puppet_plan_instantiator.rb
lib/puppet/pops/loader/puppet_plan_instantiator.rb
# frozen_string_literal: true module Puppet::Pops module Loader # The PuppetPlanInstantiator instantiates a Puppet::Functions::PuppetFunction given a Puppet Programming language # source that when called evaluates the Puppet logic it contains. # class PuppetPlanInstantiator # Produces an instance of the Function class with the given typed_name, or fails with an error if the # given puppet source does not produce this instance when evaluated. # # @param loader [Loader] The loader the function is associated with # @param typed_name [TypedName] the type / name of the function to load # @param source_ref [URI, String] a reference to the source / origin of the puppet code to evaluate # @param pp_code_string [String] puppet code in a string # # @return [Functions::Function] - an instantiated function with global scope closure associated with the given loader # def self.create(loader, typed_name, source_ref, pp_code_string) parser = Parser::EvaluatingParser.new() # parse and validate result = parser.parse_string(pp_code_string, source_ref) # The parser attaches all definitions, including those nested in apply # blocks, to the Program object. Node definitions in apply blocks are # perfectly legal and don't count as the file containing multiple # definitions for this purpose. By this point, we've already validated that # there are no node definitions *outside* apply blocks, so we simply ignore # them here. definitions = result.definitions.reject { |definition| definition.is_a?(Puppet::Pops::Model::NodeDefinition) } # Only one plan is allowed (and no other definitions) case definitions.size when 0 raise ArgumentError, _("The code loaded from %{source_ref} does not define the plan '%{plan_name}' - it is empty.") % { source_ref: source_ref, plan_name: typed_name.name } when 1 # ok else raise ArgumentError, _("The code loaded from %{source_ref} must contain only the plan '%{plan_name}' - it has additional definitions.") % { source_ref: source_ref, plan_name: typed_name.name } end the_plan_definition = definitions[0] unless the_plan_definition.is_a?(Model::PlanDefinition) raise ArgumentError, _("The code loaded from %{source_ref} does not define the plan '%{plan_name}' - no plan found.") % { source_ref: source_ref, plan_name: typed_name.name } end unless the_plan_definition.name == typed_name.name expected = typed_name.name actual = the_plan_definition.name raise ArgumentError, _("The code loaded from %{source_ref} produced plan with the wrong name, expected %{expected}, actual %{actual}") % { source_ref: source_ref, expected: expected, actual: actual } end unless result.body == the_plan_definition raise ArgumentError, _("The code loaded from %{source} contains additional logic - can only contain the plan %{plan_name}") % { source: source_ref, plan_name: typed_name.name } end # Adapt the function definition with loader - this is used from logic contained in it body to find the # loader to use when making calls to the new function API. Such logic have a hard time finding the closure (where # the loader is known - hence this mechanism private_loader = loader.private_loader Adapters::LoaderAdapter.adapt(the_plan_definition).loader_name = private_loader.loader_name # Cannot bind loaded functions to global scope, that must be done without binding that scope as # loaders survive a compilation. closure_scope = nil created = create_function_class(the_plan_definition) # create the function instance - it needs closure (scope), and loader (i.e. where it should start searching for things # when calling functions etc. # It should be bound to global scope created.new(closure_scope, private_loader) end # Creates Function class and instantiates it based on a FunctionDefinition model # @return [Array<TypedName, Functions.Function>] - array of # typed name, and an instantiated function with global scope closure associated with the given loader # def self.create_from_model(plan_definition, loader) created = create_function_class(plan_definition) typed_name = TypedName.new(:plan, plan_definition.name) [typed_name, created.new(nil, loader)] end def self.create_function_class(plan_definition) # Create a 4x function wrapper around a named closure Puppet::Functions.create_function(plan_definition.name, Puppet::Functions::PuppetFunction) do # TODO: should not create a new evaluator per function init_dispatch(Evaluator::Closure::Named.new( plan_definition.name, Evaluator::EvaluatorImpl.new(), plan_definition )) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/static_loader.rb
lib/puppet/pops/loader/static_loader.rb
# frozen_string_literal: true # Static Loader contains constants, basic data types and other types required for the system # to boot. # module Puppet::Pops module Loader class StaticLoader < Loader BUILTIN_TYPE_NAMES = %w[ Component Exec File Filebucket Group Node Notify Package Resources Schedule Service Stage Tidy User Whit ].freeze BUILTIN_TYPE_NAMES_LC = Set.new(BUILTIN_TYPE_NAMES.map(&:downcase)).freeze BUILTIN_ALIASES = { 'Data' => 'Variant[ScalarData,Undef,Hash[String,Data],Array[Data]]', 'RichDataKey' => 'Variant[String,Numeric]', 'RichData' => 'Variant[Scalar,SemVerRange,Binary,Sensitive,Type,TypeSet,URI,Object,Undef,Default,Hash[RichDataKey,RichData],Array[RichData]]', # Backward compatible aliases. 'Puppet::LookupKey' => 'RichDataKey', 'Puppet::LookupValue' => 'RichData' }.freeze attr_reader :loaded def initialize @loaded = {} @runtime_3_initialized = false create_built_in_types end def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY) # Static loader only contains runtime types return EMPTY_ARRAY unless type == :type && name_authority == Pcore::RUNTIME_NAME_AUTHORITY typed_names = @loaded.keys block_given? ? typed_names.select { |tn| yield(tn) } : typed_names end def load_typed(typed_name) load_constant(typed_name) end def get_entry(typed_name) load_constant(typed_name) end def set_entry(typed_name, value, origin = nil) @loaded[typed_name] = Loader::NamedEntry.new(typed_name, value, origin) end def find(name) # There is nothing to search for, everything this loader knows about is already available nil end def parent nil # at top of the hierarchy end def to_s "(StaticLoader)" end def loaded_entry(typed_name, check_dependencies = false) @loaded[typed_name] end def runtime_3_init unless @runtime_3_initialized @runtime_3_initialized = true create_resource_type_references end nil end def register_aliases aliases = BUILTIN_ALIASES.map { |name, string| add_type(name, Types::PTypeAliasType.new(name, Types::TypeFactory.type_reference(string), nil)) } aliases.each { |type| type.resolve(self) } end private def load_constant(typed_name) @loaded[typed_name] end def create_built_in_types origin_uri = URI("puppet:Puppet-Type-System/Static-Loader") type_map = Puppet::Pops::Types::TypeParser.type_map type_map.each do |name, type| set_entry(TypedName.new(:type, name), type, origin_uri) end end def create_resource_type_references # These needs to be done quickly and we do not want to scan the file system for these # We are also not interested in their definition only that they exist. # These types are in all environments. # BUILTIN_TYPE_NAMES.each { |name| create_resource_type_reference(name) } end def add_type(name, type) set_entry(TypedName.new(:type, name), type) type end def create_resource_type_reference(name) add_type(name, Types::TypeFactory.resource(name)) end def synchronize(&block) yield end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/dependency_loader.rb
lib/puppet/pops/loader/dependency_loader.rb
# frozen_string_literal: true # =DependencyLoader # This loader provides visibility into a set of other loaders. It is used as a child of a ModuleLoader (or other # loader) to make its direct dependencies visible for loading from contexts that have access to this dependency loader. # Access is typically given to logic that resides inside of the module, but not to those that just depend on the module. # # It is instantiated with a name, and with a set of dependency_loaders. # # @api private # class Puppet::Pops::Loader::DependencyLoader < Puppet::Pops::Loader::BaseLoader # Creates a DependencyLoader for one parent loader # # @param parent_loader [Puppet::Pops::Loader] typically a module loader for the root # @param name [String] the name of the dependency-loader (used for debugging and tracing only) # @param dependency_loaders [Array<Puppet::Pops::Loader>] array of loaders for modules this module depends on # def initialize(parent_loader, name, dependency_loaders, environment) super(parent_loader, name, environment) @dependency_loaders = dependency_loaders end def discover(type, error_collector = nil, name_authority = Puppet::Pops::Pcore::RUNTIME_NAME_AUTHORITY, &block) result = [] @dependency_loaders.each { |loader| result.concat(loader.discover(type, error_collector, name_authority, &block)) } result.concat(super) result end # Finds name in a loader this loader depends on / can see # def find(typed_name) if typed_name.qualified? l = index()[typed_name.name_parts[0]] if l l.load_typed(typed_name) else # no module entered as dependency with name matching first segment of wanted name nil end else # a non name-spaced name, have to search since it can be anywhere. # (Note: superclass caches the result in this loader as it would have to repeat this search for every # lookup otherwise). loaded = @dependency_loaders.reduce(nil) do |previous, loader| break previous unless previous.nil? loader.load_typed(typed_name) end if loaded promote_entry(loaded) end loaded end end # @api public # def loaded_entry(typed_name, check_dependencies = false) super || (check_dependencies ? loaded_entry_in_dependency(typed_name, check_dependencies) : nil) end def to_s "(DependencyLoader '#{@loader_name}' [" + @dependency_loaders.map(&:to_s).join(' ,') + "])" end private def loaded_entry_in_dependency(typed_name, check_dependencies) if typed_name.qualified? l = index[typed_name.name_parts[0]] if l l.loaded_entry(typed_name) else # no module entered as dependency with name matching first segment of wanted name nil end else # a non name-spaced name, have to search since it can be anywhere. # (Note: superclass caches the result in this loader as it would have to repeat this search for every # lookup otherwise). @dependency_loaders.reduce(nil) do |previous, loader| break previous unless previous.nil? loader.loaded_entry(typed_name, check_dependencies) end end end # An index of module_name to module loader used to speed up lookup of qualified names def index @index ||= @dependency_loaders.each_with_object({}) { |loader, index| index[loader.module_name] = loader; } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/puppet_function_instantiator.rb
lib/puppet/pops/loader/puppet_function_instantiator.rb
# frozen_string_literal: true module Puppet::Pops module Loader # The PuppetFunctionInstantiator instantiates a Puppet::Functions::PuppetFunction given a Puppet Programming language # source that when called evaluates the Puppet logic it contains. # class PuppetFunctionInstantiator # Produces an instance of the Function class with the given typed_name, or fails with an error if the # given puppet source does not produce this instance when evaluated. # # @param loader [Loader] The loader the function is associated with # @param typed_name [TypedName] the type / name of the function to load # @param source_ref [URI, String] a reference to the source / origin of the puppet code to evaluate # @param pp_code_string [String] puppet code in a string # # @return [Functions::Function] - an instantiated function with global scope closure associated with the given loader # def self.create(loader, typed_name, source_ref, pp_code_string) parser = Parser::EvaluatingParser.new() # parse and validate result = parser.parse_string(pp_code_string, source_ref) # Only one function is allowed (and no other definitions) case result.definitions.size when 0 raise ArgumentError, _("The code loaded from %{source_ref} does not define the function '%{func_name}' - it is empty.") % { source_ref: source_ref, func_name: typed_name.name } when 1 # ok else raise ArgumentError, _("The code loaded from %{source_ref} must contain only the function '%{type_name}' - it has additional definitions.") % { source_ref: source_ref, type_name: typed_name.name } end the_function_definition = result.definitions[0] unless the_function_definition.is_a?(Model::FunctionDefinition) raise ArgumentError, _("The code loaded from %{source_ref} does not define the function '%{type_name}' - no function found.") % { source_ref: source_ref, type_name: typed_name.name } end unless the_function_definition.name == typed_name.name expected = typed_name.name actual = the_function_definition.name raise ArgumentError, _("The code loaded from %{source_ref} produced function with the wrong name, expected %{expected}, actual %{actual}") % { source_ref: source_ref, expected: expected, actual: actual } end unless result.body == the_function_definition raise ArgumentError, _("The code loaded from %{source} contains additional logic - can only contain the function %{name}") % { source: source_ref, name: typed_name.name } end # Adapt the function definition with loader - this is used from logic contained in it body to find the # loader to use when making calls to the new function API. Such logic have a hard time finding the closure (where # the loader is known - hence this mechanism private_loader = loader.private_loader Adapters::LoaderAdapter.adapt(the_function_definition).loader_name = private_loader.loader_name # Cannot bind loaded functions to global scope, that must be done without binding that scope as # loaders survive a compilation. closure_scope = nil # Puppet.lookup(:global_scope) { {} } created = create_function_class(the_function_definition) # create the function instance - it needs closure (scope), and loader (i.e. where it should start searching for things # when calling functions etc. # It should be bound to global scope created.new(closure_scope, private_loader) end # Creates Function class and instantiates it based on a FunctionDefinition model # @return [Array<TypedName, Functions.Function>] - array of # typed name, and an instantiated function with global scope closure associated with the given loader # def self.create_from_model(function_definition, loader) created = create_function_class(function_definition) typed_name = TypedName.new(:function, function_definition.name) [typed_name, created.new(nil, loader)] end def self.create_function_class(function_definition) # Create a 4x function wrapper around a named closure Puppet::Functions.create_function(function_definition.name, Puppet::Functions::PuppetFunction) do # TODO: should not create a new evaluator per function init_dispatch(Evaluator::Closure::Named.new( function_definition.name, Evaluator::EvaluatorImpl.new(), function_definition )) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/module_loaders.rb
lib/puppet/pops/loader/module_loaders.rb
# frozen_string_literal: true module Puppet::Pops module Loader # =ModuleLoaders # A ModuleLoader loads items from a single module. # The ModuleLoaders (ruby) module contains various such loaders. There is currently one concrete # implementation, ModuleLoaders::FileBased that loads content from the file system. # Other implementations can be created - if they are based on name to path mapping where the path # is relative to a root path, they can derive the base behavior from the ModuleLoaders::AbstractPathBasedModuleLoader class. # # Examples of such extensions could be a zip/jar/compressed file base loader. # # Notably, a ModuleLoader does not configure itself - it is given the information it needs (the root, its name etc.) # Logic higher up in the loader hierarchy of things makes decisions based on the "shape of modules", and "available # modules" to determine which module loader to use for each individual module. (There could be differences in # internal layout etc.) # # A module loader is also not aware of the mapping of name to relative paths. # # @api private # module ModuleLoaders # Wildcard module name for module loaders, makes loading possible from any namespace. NAMESPACE_WILDCARD = '*' # This is exactly the same as the #system_loader_from method, but the argument for path is changed to # location where pluginsync stores functions. It also accepts definitions in any namespace since pluginsync # places all of them in the same directory. # def self.cached_loader_from(parent_loader, loaders) LibRootedFileBased.new(parent_loader, loaders, NAMESPACE_WILDCARD, Puppet[:libdir], 'cached_puppet_lib', [:func_4x, :func_3x, :datatype]) end def self.system_loader_from(parent_loader, loaders) # Puppet system may be installed in a fixed location via RPM, installed as a Gem, via source etc. # The only way to find this across the different ways puppet can be installed is # to search up the path from this source file's __FILE__ location until it finds the base of # puppet. # puppet_lib = File.realpath(File.join(File.dirname(__FILE__), '../../..')) LibRootedFileBased.new(parent_loader, loaders, nil, puppet_lib, # may or may not have a 'lib' above 'puppet' 'puppet_system', [:func_4x, :func_3x, :datatype]) # only load ruby functions and types from "puppet" end def self.environment_loader_from(parent_loader, loaders, env_path) if env_path.nil? || env_path.empty? EmptyLoader.new(parent_loader, ENVIRONMENT, loaders.environment) else FileBased.new(parent_loader, loaders, ENVIRONMENT, env_path, ENVIRONMENT) end end def self.module_loader_from(parent_loader, loaders, module_name, module_path) ModuleLoaders::FileBased.new(parent_loader, loaders, module_name, module_path, module_name) end def self.pcore_resource_type_loader_from(parent_loader, loaders, environment_path) ModuleLoaders::FileBased.new(parent_loader, loaders, nil, environment_path, 'pcore_resource_types') end class EmptyLoader < BaseLoader def find(typed_name) nil end def private_loader @private_loader ||= self end def private_loader=(loader) @private_loader = loader end end class AbstractPathBasedModuleLoader < BaseLoader # The name of the module, or nil, if this is a global "component", or "any module" if set to the `NAMESPACE_WILDCARD` (*) attr_reader :module_name # The path to the location of the module/component - semantics determined by subclass attr_reader :path # A map of type to smart-paths that help with minimizing the number of paths to scan attr_reader :smart_paths # A Module Loader has a private loader, it is lazily obtained on request to provide the visibility # for entities contained in the module. Since a ModuleLoader also represents an environment and it is # created a different way, this loader can be set explicitly by the loaders bootstrap logic. # # @api private attr_writer :private_loader # Initialize a kind of ModuleLoader for one module # @param parent_loader [Loader] loader with higher priority # @param loaders [Loaders] the container for this loader # @param module_name [String] the name of the module (non qualified name), may be nil for a global "component" # @param path [String] the path to the root of the module (semantics defined by subclass) # @param loader_name [String] a name that is used for human identification (useful when module_name is nil) # def initialize(parent_loader, loaders, module_name, path, loader_name, loadables) super(parent_loader, loader_name, loaders.environment) raise ArgumentError, 'path based loader cannot be instantiated without a path' if path.nil? || path.empty? @module_name = module_name @path = path @smart_paths = LoaderPaths::SmartPaths.new(self) @loaders = loaders @loadables = loadables unless (loadables - LOADABLE_KINDS).empty? # TRANSLATORS 'loadables' is a variable containing loadable modules and should not be translated raise ArgumentError, _('given loadables are not of supported loadable kind') end loaders.add_loader_by_name(self) end def loadables @loadables end def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY, &block) global = global? if name_authority == Pcore::RUNTIME_NAME_AUTHORITY smart_paths.effective_paths(type).each do |sp| relative_paths(sp).each do |rp| tp = sp.typed_name(type, name_authority, rp, global ? nil : @module_name) next unless sp.valid_name?(tp) begin load_typed(tp) unless block_given? && !block.yield(tp) rescue StandardError => e if error_collector.nil? Puppet.warn_once(:unloadable_entity, tp.to_s, e.message) else err = Puppet::DataTypes::Error.new( Issues::LOADER_FAILURE.format(:type => type), 'PUPPET_LOADER_FAILURE', { 'original_error' => e.message }, Issues::LOADER_FAILURE.issue_code ) error_collector << err unless error_collector.include?(err) end end end end end super end # Finds typed/named entity in this module # @param typed_name [TypedName] the type/name to find # @return [Loader::NamedEntry, nil found/created entry, or nil if not found # def find(typed_name) # This loader is tailored to only find entries in the current runtime return nil unless typed_name.name_authority == Pcore::RUNTIME_NAME_AUTHORITY # Assume it is a global name, and that all parts of the name should be used when looking up name_parts = typed_name.name_parts # Certain types and names can be disqualified up front if name_parts.size > 1 # The name is in a name space. # Then entity cannot possible be in this module unless the name starts with the module name. # Note: # * If "module" represents a "global component", the module_name is nil and cannot match which is # ok since such a "module" cannot have namespaced content). # * If this loader is allowed to have namespaced content, the module_name can be set to NAMESPACE_WILDCARD `*` # return nil unless name_parts[0] == module_name || module_name == NAMESPACE_WILDCARD else # The name is in the global name space. case typed_name.type when :function, :resource_type, :resource_type_pp # Can be defined in module using a global name. No action required when :plan unless global? # Global name must be the name of the module return nil unless name_parts[0] == module_name # Look for the special 'init' plan. origin, smart_path = find_existing_path(init_plan_name) return smart_path.nil? ? nil : instantiate(smart_path, typed_name, origin) end when :task unless global? # Global name must be the name of the module return nil unless name_parts[0] == module_name # Look for the special 'init' Task origin, smart_path = find_existing_path(init_task_name) return smart_path.nil? ? nil : instantiate(smart_path, typed_name, origin) end when :type unless global? # Global name must be the name of the module unless name_parts[0] == module_name || module_name == NAMESPACE_WILDCARD # Check for ruby defined data type in global namespace before giving up origin, smart_path = find_existing_path(typed_name) return smart_path.is_a?(LoaderPaths::DataTypePath) ? instantiate(smart_path, typed_name, origin) : nil end # Look for the special 'init_typeset' TypeSet origin, smart_path = find_existing_path(init_typeset_name) return nil if smart_path.nil? value = smart_path.instantiator.create(self, typed_name, origin, get_contents(origin)) if value.is_a?(Types::PTypeSetType) # cache the entry and return it return set_entry(typed_name, value, origin) end # TRANSLATORS 'TypeSet' should not be translated raise ArgumentError, _("The code loaded from %{origin} does not define the TypeSet '%{module_name}'") % { origin: origin, module_name: name_parts[0].capitalize } end else # anything else cannot possibly be in this module # TODO: should not be allowed anyway... may have to revisit this decision return nil end end # Get the paths that actually exist in this module (they are lazily processed once and cached). # The result is an array (that may be empty). # Find the file to instantiate, and instantiate the entity if file is found origin, smart_path = find_existing_path(typed_name) return instantiate(smart_path, typed_name, origin) unless smart_path.nil? return nil unless typed_name.type == :type && typed_name.qualified? # Search for TypeSet using parent name ts_name = typed_name.parent while ts_name # Do not traverse parents here. This search must be confined to this loader tse = get_entry(ts_name) tse = find(ts_name) if tse.nil? || tse.value.nil? if tse && (ts = tse.value).is_a?(Types::PTypeSetType) # The TypeSet might be unresolved at this point. If so, it must be resolved using # this loader. That in turn, adds all contained types to this loader. ts.resolve(self) te = get_entry(typed_name) return te unless te.nil? end ts_name = ts_name.parent end nil end def instantiate(smart_path, typed_name, origin) if origin.is_a?(Array) value = smart_path.instantiator.create(self, typed_name, origin) else value = smart_path.instantiator.create(self, typed_name, origin, get_contents(origin)) end # cache the entry and return it set_entry(typed_name, value, origin) end # Abstract method that subclasses override that checks if it is meaningful to search using a generic smart path. # This optimization is performed to not be tricked into searching an empty directory over and over again. # The implementation may perform a deep search for file content other than directories and cache this in # and index. It is guaranteed that a call to meaningful_to_search? takes place before checking any other # path with relative_path_exists?. # # This optimization exists because many modules have been created from a template and they have # empty directories for functions, types, etc. (It is also the place to create a cached index of the content). # # @param smart_path [String] a path relative to the module's root # @return [Boolean] true if there is content in the directory appointed by the relative path # def meaningful_to_search?(smart_path) raise NotImplementedError end # Abstract method that subclasses override to answer if the given relative path exists, and if so returns that path # # @param resolved_path [String] a path resolved by a smart path against the loader's root (if it has one) # @return [String, nil] the found path or nil if no such path was found # def existing_path(resolved_path) raise NotImplementedError end # Abstract method that subclasses override to return an array of paths that may be associated with the resolved path. # # @param resolved_path [String] a path, without extension, resolved by a smart path against the loader's root (if it has one) # @return [Array<String>] # def candidate_paths(resolved_path) raise NotImplementedError end # Abstract method that subclasses override to produce the content of the effective path. # It should either succeed and return a String or fail with an exception. # # @param effective_path [String] a path as resolved by a smart path # @return [String] the content of the file # def get_contents(effective_path) raise NotImplementedError end # Abstract method that subclasses override to produce a source reference String used to identify the # system resource (resource in the URI sense). # # @param relative_path [String] a path relative to the module's root # @return [String] a reference to the source file (in file system, zip file, or elsewhere). # def get_source_ref(relative_path) raise NotImplementedError end # Answers the question if this loader represents a global component (true for resource type loader and environment loader) # # @return [Boolean] `true` if this loader represents a global component # def global? module_name.nil? || module_name == NAMESPACE_WILDCARD || module_name == ENVIRONMENT end # Answers `true` if the loader used by this instance is rooted beneath 'lib'. This is # typically true for the system_loader. It will have a path relative to the parent # of 'puppet' instead of the parent of 'lib/puppet' since the 'lib' directory of puppet # is renamed during install. This is significant for loaders that load ruby code. # # @return [Boolean] a boolean answering if the loader is rooted beneath 'lib'. def lib_root? false end # Produces the private loader for the module. If this module is not already resolved, this will trigger resolution # def private_loader # The system loader has a nil module_name and it does not have a private_loader as there are no functions # that can only by called by puppet runtime - if so, it acts as the private loader directly. @private_loader ||= (global? ? self : @loaders.private_loader_for_module(module_name)) end # Return all paths that matches the given smart path. The returned paths are # relative to the `#generic_path` of the given smart path. # # @param smart_path [SmartPath] the path to find relative paths for # @return [Array<String>] found paths def relative_paths(smart_path) raise NotImplementedError end private # @return [TypedName] the fake typed name that maps to the init_typeset path for this module def init_typeset_name @init_typeset_name ||= TypedName.new(:type, "#{module_name}::init_typeset") end # @return [TypedName] the fake typed name that maps to the path of an init[arbitrary extension] # file that represents a task named after the module def init_task_name @init_task_name ||= TypedName.new(:task, "#{module_name}::init") end # @return [TypedName] the fake typed name that maps to the path of an init.pp file that represents # a plan named after the module def init_plan_name @init_plan_name ||= TypedName.new(:plan, "#{module_name}::init") end # Find an existing path or paths for the given `typed_name`. Return `nil` if no path is found # @param typed_name [TypedName] the `typed_name` to find a path for # @return [Array,nil] `nil`or a two element array where the first element is an effective path or array of paths # (depending on the `SmartPath`) and the second element is the `SmartPath` that produced the effective path or # paths. A path is a String def find_existing_path(typed_name) is_global = global? smart_paths.effective_paths(typed_name.type).each do |sp| next unless sp.valid_name?(typed_name) origin = sp.effective_path(typed_name, is_global ? 0 : 1) unless origin.nil? if sp.fuzzy_matching? # If there are multiple *specific* paths for the file, find # whichever ones exist. Otherwise, find all paths that *might* be # related to origin if origin.is_a?(Array) origins = origin.filter_map { |ori| existing_path(ori) } else origins = candidate_paths(origin) end return [origins, sp] unless origins.empty? else existing = existing_path(origin) return [origin, sp] unless existing.nil? end end end nil end end # @api private # class FileBased < AbstractPathBasedModuleLoader attr_reader :smart_paths attr_reader :path_index # Create a kind of ModuleLoader for one module (Puppet Module, or module like) # # @param parent_loader [Loader] typically the loader for the environment or root # @param module_name [String] the name of the module (non qualified name), may be nil for "modules" only containing globals # @param path [String] the path to the root of the module (semantics defined by subclass) # @param loader_name [String] a name that identifies the loader # def initialize(parent_loader, loaders, module_name, path, loader_name, loadables = LOADABLE_KINDS) super @path_index = Set.new end def existing_path(effective_path) # Optimized, checks index instead of visiting file system @path_index.include?(effective_path) ? effective_path : nil end def candidate_paths(effective_path) basename = File.basename(effective_path, '.*') dirname = File.dirname(effective_path) files = @path_index.select do |path| File.dirname(path) == dirname end # At least one file has to match what we're loading, or it certainly doesn't exist if files.any? { |file| File.basename(file, '.*') == basename } files else [] end end def meaningful_to_search?(smart_path) !add_to_index(smart_path).empty? end def to_s "(ModuleLoader::FileBased '#{loader_name}' '#{module_name}')" end def add_to_index(smart_path) found = Dir.glob(File.join(smart_path.generic_path, '**', "*#{smart_path.extension}")) # The reason for not always rejecting directories here is performance (avoid extra stat calls). The # false positives (directories with a matching extension) is an error in any case and will be caught # later. found = found.reject { |file_name| File.directory?(file_name) } if smart_path.extension.empty? @path_index.merge(found) found end def get_contents(effective_path) Puppet::FileSystem.read(effective_path, :encoding => 'utf-8') end # Return all paths that matches the given smart path. The returned paths are # relative to the `#generic_path` of the given smart path. # # This method relies on the cache and does not perform any file system access # # @param smart_path [SmartPath] the path to find relative paths for # @return [Array<String>] found paths def relative_paths(smart_path) root = smart_path.generic_path found = [] @path_index.each do |path| found << Pathname(path).relative_path_from(Pathname(root)).to_s if smart_path.valid_path?(path) end found end end # Specialization used by the system_loader which is limited to see what's beneath 'lib' and hence # cannot be rooted in its parent. The 'lib' directory is renamed during install so any attempt # to traverse into it from above would fail. # # @api private # class LibRootedFileBased < FileBased def lib_root? true end end # Loads from a gem specified as a URI, gem://gemname/optional/path/in/gem, or just a String gemname. # The source reference (shown in errors etc.) is the expanded path of the gem as this is believed to be more # helpful - given the location it should be quite obvious which gem it is, without the location, the user would # need to go on a hunt for where the file actually is located. # # TODO: How does this get instantiated? Does the gemname refelect the name of the module (the namespace) # or is that specified a different way? Can a gem be the container of multiple modules? # # @api private # class GemBased < FileBased include GemSupport attr_reader :gem_ref # Create a kind of ModuleLoader for one module # The parameters are: # * parent_loader - typically the loader for the root # * module_name - the name of the module (non qualified name) # * gem_ref - [URI, String] gem reference to the root of the module (URI, gem://gemname/optional/path/in/gem), or # just the gem's name as a String. # def initialize(parent_loader, loaders, module_name, gem_ref, loader_name, loadables = LOADABLE_KINDS) @gem_ref = gem_ref super parent_loader, loaders, module_name, gem_dir(gem_ref), loader_name, loadables end def to_s "(ModuleLoader::GemBased '#{loader_name}' '#{@gem_ref}' [#{module_name}])" end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/generic_plan_instantiator.rb
lib/puppet/pops/loader/generic_plan_instantiator.rb
# frozen_string_literal: true module Puppet::Pops module Loader # The GenericPlanInstantiator dispatches to either PuppetPlanInstantiator or a # yaml_plan_instantiator injected through the Puppet context, depending on # the type of the plan. # class GenericPlanInstantiator def self.create(loader, typed_name, source_refs) if source_refs.length > 1 raise ArgumentError, _("Found multiple files for plan '%{plan_name}' but only one is allowed") % { plan_name: typed_name.name } end source_ref = source_refs[0] code_string = Puppet::FileSystem.read(source_ref, :encoding => 'utf-8') instantiator = if source_ref.end_with?('.pp') Puppet::Pops::Loader::PuppetPlanInstantiator else Puppet.lookup(:yaml_plan_instantiator) do raise Puppet::DevError, _("No instantiator is available to load plan from %{source_ref}") % { source_ref: source_ref } end end instantiator.create(loader, typed_name, source_ref, code_string) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/ruby_data_type_instantiator.rb
lib/puppet/pops/loader/ruby_data_type_instantiator.rb
# frozen_string_literal: true # The RubyTypeInstantiator instantiates a data type from the ruby source # that calls Puppet::DataTypes.create_type. # class Puppet::Pops::Loader::RubyDataTypeInstantiator # Produces an instance of class derived from PAnyType class with the given typed_name, or fails with an error if the # given ruby source does not produce this instance when evaluated. # # @param loader [Puppet::Pops::Loader::Loader] The loader the type is associated with # @param typed_name [Puppet::Pops::Loader::TypedName] the type / name of the type to load # @param source_ref [URI, String] a reference to the source / origin of the ruby code to evaluate # @param ruby_code_string [String] ruby code in a string # # @return [Puppet::Pops::Types::PAnyType] - an instantiated data type associated with the given loader # def self.create(loader, typed_name, source_ref, ruby_code_string) unless ruby_code_string.is_a?(String) && ruby_code_string =~ /Puppet::DataTypes\.create_type/ raise ArgumentError, _("The code loaded from %{source_ref} does not seem to be a Puppet 5x API data type - no create_type call.") % { source_ref: source_ref } end # make the private loader available in a binding to allow it to be passed on loader_for_type = loader.private_loader here = get_binding(loader_for_type) created = eval(ruby_code_string, here, source_ref, 1) # rubocop:disable Security/Eval unless created.is_a?(Puppet::Pops::Types::PAnyType) raise ArgumentError, _("The code loaded from %{source_ref} did not produce a data type when evaluated. Got '%{klass}'") % { source_ref: source_ref, klass: created.class } end unless created.name.casecmp(typed_name.name) == 0 raise ArgumentError, _("The code loaded from %{source_ref} produced mis-matched name, expected '%{type_name}', got %{created_name}") % { source_ref: source_ref, type_name: typed_name.name, created_name: created.name } end created end # Produces a binding where the given loader is bound as a local variable (loader_injected_arg). This variable can be used in loaded # ruby code - e.g. to call Puppet::Function.create_loaded_function(:name, loader,...) # def self.get_binding(loader_injected_arg) binding end private_class_method :get_binding end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/puppet_resource_type_impl_instantiator.rb
lib/puppet/pops/loader/puppet_resource_type_impl_instantiator.rb
# frozen_string_literal: true module Puppet::Pops module Loader # The PuppetResourceTypeImplInstantiator instantiates a Puppet::Pops::ResourceTypeImpl object. # given a Puppet Programming language source that when called evaluates the Puppet logic it contains. # class PuppetResourceTypeImplInstantiator # Produces an instance of Puppet::Pops::ResourceTypeImpl, or fails with an error if the # given puppet source does not produce such an instance when evaluated. # # @param loader [Loader] The loader the function is associated with # @param typed_name [TypedName] the type / name of the resource type impl to load # @param source_ref [URI, String] a reference to the source / origin of the puppet code to evaluate # @param pp_code_string [String] puppet code in a string # # @return [Puppet::Pops::ResourceTypeImpl] - an instantiated ResourceTypeImpl # def self.create(loader, typed_name, source_ref, pp_code_string) parser = Parser::EvaluatingParser.new() # parse and validate model = parser.parse_string(pp_code_string, source_ref) statements = if model.is_a?(Model::Program) if model.body.is_a?(Model::BlockExpression) model.body.statements else [model.body] end else EMPTY_ARRAY end statements = statements.reject { |s| s.is_a?(Model::Nop) } if statements.empty? raise ArgumentError, _("The code loaded from %{source_ref} does not create the resource type '%{type_name}' - it is empty") % { source_ref: source_ref, type_name: typed_name.name } end rname = Resource::ResourceTypeImpl._pcore_type.name unless statements.find do |s| if s.is_a?(Model::CallMethodExpression) functor_expr = s.functor_expr functor_expr.is_a?(Model::NamedAccessExpression) && functor_expr.left_expr.is_a?(Model::QualifiedReference) && functor_expr.left_expr.cased_value == rname && functor_expr.right_expr.is_a?(Model::QualifiedName) && functor_expr.right_expr.value == 'new' else false end end raise ArgumentError, _("The code loaded from %{source_ref} does not create the resource type '%{type_name}' - no call to %{rname}.new found.") % { source_ref: source_ref, type_name: typed_name.name, rname: rname } end unless statements.size == 1 raise ArgumentError, _("The code loaded from %{source_ref} must contain only the creation of resource type '%{type_name}' - it has additional logic.") % { source_ref: source_ref, type_name: typed_name.name } end closure_scope = Puppet.lookup(:global_scope) { {} } resource_type_impl = parser.evaluate(closure_scope, model) unless resource_type_impl.is_a?(Puppet::Pops::Resource::ResourceTypeImpl) got = resource_type.class raise ArgumentError, _("The code loaded from %{source_ref} does not define the resource type '%{type_name}' - got '%{got}'.") % { source_ref: source_ref, type_name: typed_name.name, got: got } end unless resource_type_impl.name == typed_name.name expected = typed_name.name actual = resource_type_impl.name raise ArgumentError, _("The code loaded from %{source_ref} produced resource type with the wrong name, expected '%{expected}', actual '%{actual}'") % { source_ref: source_ref, expected: expected, actual: actual } end # Adapt the resource type definition with loader - this is used from logic contained in it body to find the # loader to use when making calls to the new function API. Such logic have a hard time finding the closure (where # the loader is known - hence this mechanism Adapters::LoaderAdapter.adapt(resource_type_impl).loader_name = loader.loader_name resource_type_impl end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/loader.rb
lib/puppet/pops/loader/loader.rb
# frozen_string_literal: true # Loader # === # A Loader is responsible for loading "entities" ("instantiable and executable objects in the puppet language" which # are type, hostclass, definition, function, and bindings. # # The main method for users of a Loader is the `load` or `load_typed methods`, which returns a previously loaded entity # of a given type/name, and searches and loads the entity if not already loaded. # # private entities # --- # TODO: handle loading of entities that are private. Suggest that all calls pass an origin_loader (the loader # where request originated (or symbol :public). A module loader has one (or possibly a list) of what is # considered to represent private loader - i.e. the dependency loader for a module. If an entity is private # it should be stored with this status, and an error should be raised if the origin_loader is not on the list # of accepted "private" loaders. # The private loaders can not be given at creation time (they are parented by the loader in question). Another # alternative is to check if the origin_loader is a child loader, but this requires bidirectional links # between loaders or a search if loader with private entity is a parent of the origin_loader). # # @api public # module Puppet::Pops module Loader ENVIRONMENT = 'environment' ENVIRONMENT_PRIVATE = 'environment private' class Loader attr_reader :environment, :loader_name # Describes the kinds of things that loaders can load LOADABLE_KINDS = [:func_4x, :func_4xpp, :func_3x, :datatype, :type_pp, :resource_type_pp, :plan, :task].freeze # @param [String] name the name of the loader. Must be unique among all loaders maintained by a {Loader} instance def initialize(loader_name, environment) @loader_name = loader_name.freeze @environment = environment end # Search all places where this loader would find values of a given type and return a list the # found values for which the given block returns true. All found entries will be returned if no # block is given. # # Errors that occur function discovery will either be logged as warnings or collected by the optional # `error_collector` array. When provided, it will receive {Puppet::DataTypes::Error} instances describing # each error in detail and no warnings will be logged. # # @param type [Symbol] the type of values to search for # @param error_collector [Array<Puppet::DataTypes::Error>] an optional array that will receive errors during load # @param name_authority [String] the name authority, defaults to the pcore runtime # @yield [typed_name] optional block to filter the results # @yieldparam [TypedName] typed_name the typed name of a found entry # @yieldreturn [Boolean] `true` to keep the entry, `false` to discard it. # @return [Array<TypedName>] the list of names of discovered values def discover(type, error_collector = nil, name_authority = Pcore::RUNTIME_NAME_AUTHORITY, &block) EMPTY_ARRAY end # Produces the value associated with the given name if already loaded, or available for loading # by this loader, one of its parents, or other loaders visible to this loader. # This is the method an external party should use to "get" the named element. # # An implementor of this method should first check if the given name is already loaded by self, or a parent # loader, and if so return that result. If not, it should call `find` to perform the loading. # # @param type [:Symbol] the type to load # @param name [String, Symbol] the name of the entity to load # @return [Object, nil] the value or nil if not found # # @api public # def load(type, name) synchronize do result = load_typed(TypedName.new(type, name.to_s)) if result result.value end end end # Loads the given typed name, and returns a NamedEntry if found, else returns nil. # This the same a `load`, but returns a NamedEntry with origin/value information. # # @param typed_name [TypedName] - the type, name combination to lookup # @return [NamedEntry, nil] the entry containing the loaded value, or nil if not found # # @api public # def load_typed(typed_name) raise NotImplementedError, "Class #{self.class.name} must implement method #load_typed" end # Returns an already loaded entry if one exists, or nil. This does not trigger loading # of the given type/name. # # @param typed_name [TypedName] - the type, name combination to lookup # @param check_dependencies [Boolean] - if dependencies should be checked in addition to here and parent # @return [NamedEntry, nil] the entry containing the loaded value, or nil if not found # @api public # def loaded_entry(typed_name, check_dependencies = false) raise NotImplementedError, "Class #{self.class.name} must implement method #loaded_entry" end # Produces the value associated with the given name if defined **in this loader**, or nil if not defined. # This lookup does not trigger any loading, or search of the given name. # An implementor of this method may not search or look up in any other loader, and it may not # define the name. # # @param typed_name [TypedName] - the type, name combination to lookup # # @api private # def [](typed_name) found = get_entry(typed_name) if found found.value else nil end end # Searches for the given name in this loader's context (parents should already have searched their context(s) without # producing a result when this method is called). # An implementation of find typically caches the result. # # @param typed_name [TypedName] the type, name combination to lookup # @return [NamedEntry, nil] the entry for the loaded entry, or nil if not found # # @api private # def find(typed_name) raise NotImplementedError, "Class #{self.class.name} must implement method #find" end # Returns the parent of the loader, or nil, if this is the top most loader. This implementation returns nil. def parent nil end # Produces the private loader for loaders that have a one (the visibility given to loaded entities). # For loaders that does not provide a private loader, self is returned. # # @api private def private_loader self end # Lock around a block # This exists so some subclasses that are set up statically and don't actually # load can override it def synchronize(&block) @environment.lock.synchronize(&block) end # Binds a value to a name. The name should not start with '::', but may contain multiple segments. # # @param type [:Symbol] the type of the entity being set # @param name [String, Symbol] the name of the entity being set # @param origin [URI, #uri, String] the origin of the set entity, a URI, or provider of URI, or URI in string form # @return [NamedEntry, nil] the created entry # # @api private # def set_entry(type, name, value, origin = nil) raise NotImplementedError end # Produces a NamedEntry if a value is bound to the given name, or nil if nothing is bound. # # @param typed_name [TypedName] the type, name combination to lookup # @return [NamedEntry, nil] the value bound in an entry # # @api private # def get_entry(typed_name) raise NotImplementedError end # A loader is by default a loader for all kinds of loadables. An implementation may override # if it cannot load all kinds. # # @api private def loadables LOADABLE_KINDS end # A loader may want to implement its own version with more detailed information. def to_s loader_name end # Loaders may contain references to the environment they load items within. # Consequently, calling Kernel#inspect may return strings that are large # enough to cause OutOfMemoryErrors on some platforms. # # We do not call alias_method here as that would copy the content of to_s # at this point to inspect (ie children would print out `loader_name` # rather than their version of to_s if they chose to implement it). def inspect to_s end # An entry for one entity loaded by the loader. # class NamedEntry attr_reader :typed_name attr_reader :value attr_reader :origin def initialize(typed_name, value, origin) @typed_name = typed_name @value = value @origin = origin freeze() end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/simple_environment_loader.rb
lib/puppet/pops/loader/simple_environment_loader.rb
# frozen_string_literal: true # SimpleEnvironmentLoader # === # This loader does not load anything and it is populated by the bootstrapping logic that loads # the site.pp or equivalent for an environment. It does not restrict the names of what it may contain, # and what is loaded here overrides any child loaders (modules). # class Puppet::Pops::Loader::SimpleEnvironmentLoader < Puppet::Pops::Loader::BaseLoader attr_accessor :private_loader # Never finds anything, everything "loaded" is set externally def find(typed_name) nil end def to_s "(SimpleEnvironmentLoader '#{loader_name}')" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/task_instantiator.rb
lib/puppet/pops/loader/task_instantiator.rb
# frozen_string_literal: true # The TypeDefinitionInstantiator instantiates a type alias or a type definition # require_relative '../../../puppet/module/task' module Puppet::Pops module Loader class TaskInstantiator def self.create(loader, typed_name, source_refs) name = typed_name.name basename = typed_name.name_parts[1] || 'init' dirname = File.dirname(source_refs[0]) metadata_files, executables = source_refs.partition { |source_ref| source_ref.end_with?('.json') } metadata_file = metadata_files.find { |source_ref| File.basename(source_ref, '.json') == basename } metadata = Puppet::Module::Task.read_metadata(metadata_file) || {} files = Puppet::Module::Task.find_files(name, dirname, metadata, executables) task = { 'name' => name, 'metadata' => metadata, 'files' => files } begin unless metadata['parameters'].is_a?(Hash) || metadata['parameters'].nil? msg = _('Failed to load metadata for task %{name}: \'parameters\' must be a hash') % { name: name } raise Puppet::ParseError.new(msg, metadata_file) end task['parameters'] = convert_types(metadata['parameters']) Types::TypeFactory.task.from_hash(task) rescue Types::TypeAssertionError => ex # Not strictly a parser error but from the users perspective, the file content didn't parse properly. The # ParserError also conveys file info (even though line is unknown) msg = _('Failed to load metadata for task %{name}: %{reason}') % { name: name, reason: ex.message } raise Puppet::ParseError.new(msg, metadata_file) end end def self.convert_types(args) args.transform_values do |v| v['type'].nil? ? Types::TypeFactory.data : Types::TypeParser.singleton.parse(v['type']) end if args end private_class_method :convert_types end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/loader_paths.rb
lib/puppet/pops/loader/loader_paths.rb
# frozen_string_literal: true # LoaderPaths # === # The central loader knowledge about paths, what they represent and how to instantiate from them. # Contains helpers (*smart paths*) to deal with lazy resolution of paths. # # TODO: Currently only supports loading of functions (2 kinds) # module Puppet::Pops module Loader module LoaderPaths # Returns an array of SmartPath, each instantiated with a reference to the given loader (for root path resolution # and existence checks). The smart paths in the array appear in precedence order. The returned array may be # mutated. # def self.relative_paths_for_type(type, loader) result = [] case type when :function # Only include support for the loadable items the loader states it can contain if loader.loadables.include?(:func_4x) result << FunctionPath4x.new(loader) end if loader.loadables.include?(:func_4xpp) result << FunctionPathPP.new(loader) end if loader.loadables.include?(:func_3x) result << FunctionPath3x.new(loader) end when :plan result << PlanPath.new(loader) when :task result << TaskPath.new(loader) if Puppet[:tasks] && loader.loadables.include?(:task) when :type result << DataTypePath.new(loader) if loader.loadables.include?(:datatype) result << TypePathPP.new(loader) if loader.loadables.include?(:type_pp) when :resource_type_pp result << ResourceTypeImplPP.new(loader) if loader.loadables.include?(:resource_type_pp) else # unknown types, simply produce an empty result; no paths to check, nothing to find... move along... [] end result end # # DO NOT REMOVE YET. needed later? when there is the need to decamel a classname # def de_camel(fq_name) # fq_name.to_s.gsub(/::/, '/'). # gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). # gsub(/([a-z\d])([A-Z])/,'\1_\2'). # tr("-", "_"). # downcase # end class SmartPath # Creates SmartPath for the given loader (loader knows how to check for existence etc.) def initialize(loader) @loader = loader end # Generic path, in the sense of "if there are any entities of this kind to load, where are they?" def generic_path return @generic_path unless @generic_path.nil? the_root_path = root_path # @loader.path @generic_path = (the_root_path.nil? ? relative_path : File.join(the_root_path, relative_path)) end def fuzzy_matching? false end def root_path @loader.path end def lib_root? @loader.lib_root? end # Effective path is the generic path + the name part(s) + extension. # def effective_path(typed_name, start_index_in_name) "#{File.join(generic_path, typed_name.name_parts)}#{extension}" end def typed_name(type, name_authority, relative_path, module_name) # Module name is assumed to be included in the path and therefore not added here n = ''.dup unless extension.empty? # Remove extension relative_path = relative_path[0..-(extension.length + 1)] end relative_path.split('/').each do |segment| n << '::' if n.size > 0 n << segment end TypedName.new(type, n, name_authority) end def valid_path?(path) path.end_with?(extension) && path.start_with?(generic_path) end def valid_name?(typed_name) true end def relative_path raise NotImplementedError end def instantiator raise NotImplementedError end end class RubySmartPath < SmartPath EXTENSION = '.rb' def extension EXTENSION end # Duplication of extension information, but avoids one call def effective_path(typed_name, start_index_in_name) "#{File.join(generic_path, typed_name.name_parts)}.rb" end end # A PuppetSmartPath is rooted at the loader's directory one level up from what the loader specifies as it # path (which is a reference to its 'lib' directory. # class PuppetSmartPath < SmartPath EXTENSION = '.pp' def extension EXTENSION end # Duplication of extension information, but avoids one call def effective_path(typed_name, start_index_in_name) # Puppet name to path always skips the name-space as that is part of the generic path # i.e. <module>/mymodule/functions/foo.pp is the function mymodule::foo parts = typed_name.name_parts if start_index_in_name > 0 return nil if start_index_in_name >= parts.size parts = parts[start_index_in_name..] end "#{File.join(generic_path, parts)}#{extension}" end def typed_name(type, name_authority, relative_path, module_name) n = ''.dup n << module_name unless module_name.nil? unless extension.empty? # Remove extension relative_path = relative_path[0..-(extension.length + 1)] end relative_path.split('/').each do |segment| n << '::' if n.size > 0 n << segment end TypedName.new(type, n, name_authority) end end class FunctionPath4x < RubySmartPath SYSTEM_FUNCTION_PATH_4X = File.join('puppet', 'functions').freeze FUNCTION_PATH_4X = File.join('lib', SYSTEM_FUNCTION_PATH_4X).freeze def relative_path lib_root? ? SYSTEM_FUNCTION_PATH_4X : FUNCTION_PATH_4X end def instantiator RubyFunctionInstantiator end end class FunctionPath3x < RubySmartPath SYSTEM_FUNCTION_PATH_3X = File.join('puppet', 'parser', 'functions').freeze FUNCTION_PATH_3X = File.join('lib', SYSTEM_FUNCTION_PATH_3X).freeze def relative_path lib_root? ? SYSTEM_FUNCTION_PATH_3X : FUNCTION_PATH_3X end def instantiator RubyLegacyFunctionInstantiator end end class FunctionPathPP < PuppetSmartPath FUNCTION_PATH_PP = 'functions' def relative_path FUNCTION_PATH_PP end def instantiator PuppetFunctionInstantiator end end class DataTypePath < RubySmartPath SYSTEM_TYPE_PATH = File.join('puppet', 'datatypes').freeze TYPE_PATH = File.join('lib', SYSTEM_TYPE_PATH).freeze def relative_path lib_root? ? SYSTEM_TYPE_PATH : TYPE_PATH end def instantiator RubyDataTypeInstantiator end end class TypePathPP < PuppetSmartPath TYPE_PATH_PP = 'types' def relative_path TYPE_PATH_PP end def instantiator TypeDefinitionInstantiator end end # TaskPath is like PuppetSmartPath but it does not use an extension and may # match more than one path with one name class TaskPath < PuppetSmartPath TASKS_PATH = 'tasks' FORBIDDEN_EXTENSIONS = %w[.conf .md].freeze def extension EMPTY_STRING end def fuzzy_matching? true end def relative_path TASKS_PATH end def typed_name(type, name_authority, relative_path, module_name) n = ''.dup n << module_name unless module_name.nil? # Remove the file extension, defined as everything after the *last* dot. relative_path = relative_path.sub(%r{\.[^/.]*\z}, '') if relative_path == 'init' && !(module_name.nil? || module_name.empty?) TypedName.new(type, module_name, name_authority) else relative_path.split('/').each do |segment| n << '::' if n.size > 0 n << segment end TypedName.new(type, n, name_authority) end end def instantiator require_relative 'task_instantiator' TaskInstantiator end def valid_name?(typed_name) # TODO: Remove when PE has proper namespace handling typed_name.name_parts.size <= 2 end def valid_path?(path) path.start_with?(generic_path) && is_task_name?(File.basename(path, '.*')) && !FORBIDDEN_EXTENSIONS.any? { |ext| path.end_with?(ext) } end def is_task_name?(name) !!(name =~ /^[a-z][a-z0-9_]*$/) end end class ResourceTypeImplPP < PuppetSmartPath RESOURCE_TYPES_PATH_PP = '.resource_types' def relative_path RESOURCE_TYPES_PATH_PP end def root_path @loader.path end def instantiator PuppetResourceTypeImplInstantiator end # The effect paths for resource type impl is the full name # since resource types are not name spaced. # This overrides the default PuppetSmartPath. # def effective_path(typed_name, start_index_in_name) # Resource type to name does not skip the name-space # i.e. <module>/mymodule/resource_types/foo.pp is the resource type foo "#{File.join(generic_path, typed_name.name_parts)}.pp" end end class PlanPath < PuppetSmartPath PLAN_PATH = File.join('plans') PP_EXT = '.pp' YAML_EXT = '.yaml' def initialize(loader) super if Puppet.lookup(:yaml_plan_instantiator) { nil } @extensions = [PP_EXT, YAML_EXT] else @extensions = [PP_EXT] end @init_filenames = @extensions.map { |ext| "init#{ext}" } end def extension EMPTY_STRING end def relative_path PLAN_PATH end def instantiator Puppet::Pops::Loader::GenericPlanInstantiator end def fuzzy_matching? true end def valid_path?(path) @extensions.any? { |ext| path.end_with?(ext) } && path.start_with?(generic_path) end def typed_name(type, name_authority, relative_path, module_name) if @init_filenames.include?(relative_path) && !(module_name.nil? || module_name.empty?) TypedName.new(type, module_name, name_authority) else n = ''.dup n << module_name unless module_name.nil? ext = @extensions.find { |extension| relative_path.end_with?(extension) } relative_path = relative_path[0..-(ext.length + 1)] relative_path.split('/').each do |segment| n << '::' if n.size > 0 n << segment end TypedName.new(type, n, name_authority) end end def effective_path(typed_name, start_index_in_name) # Puppet name to path always skips the name-space as that is part of the generic path # i.e. <module>/mymodule/functions/foo.pp is the function mymodule::foo parts = typed_name.name_parts if start_index_in_name > 0 return nil if start_index_in_name >= parts.size parts = parts[start_index_in_name..] end basename = File.join(generic_path, parts) @extensions.map { |ext| "#{basename}#{ext}" } end end # SmartPaths # === # Holds effective SmartPath instances per type # class SmartPaths def initialize(path_based_loader) @loader = path_based_loader @smart_paths = {} end # Ensures that the paths for the type have been probed and pruned to what is existing relative to # the given root. # # @param type [Symbol] the entity type to load # @return [Array<SmartPath>] array of effective paths for type (may be empty) # def effective_paths(type) smart_paths = @smart_paths loader = @loader effective_paths = smart_paths[type] unless effective_paths # type not yet processed, does the various directories for the type exist ? # Get the relative dirs for the type paths_for_type = LoaderPaths.relative_paths_for_type(type, loader) # Check which directories exist in the loader's content/index effective_paths = smart_paths[type] = paths_for_type.select { |sp| loader.meaningful_to_search?(sp) } end effective_paths end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/loader/gem_support.rb
lib/puppet/pops/loader/gem_support.rb
# frozen_string_literal: true # GemSupport offers methods to find a gem's location by name or gem://gemname URI. # # TODO: The Puppet 3x, uses Puppet::Util::RubyGems to do this, and obtain paths, and avoids using ::Gems # when ::Bundler is in effect. A quick check what happens on Ruby 1.8.7 and Ruby 1.9.3 with current # version of bundler seems to work just fine without jumping through any hoops. Hopefully the Puppet::Utils::RubyGems is # just dealing with arcane things prior to RubyGems 1.8 that are not needed any more. To verify there is # the need to set up a scenario where additional bundles than what Bundler allows for a given configuration are available # and then trying to access those. # module Puppet::Pops::Loader::GemSupport # Produces the root directory of a gem given as an URI (gem://gemname/optional/path), or just the # gemname as a string. # def gem_dir(uri_or_string) case uri_or_string when URI gem_dir_from_uri(uri_or_string) when String gem_dir_from_name(uri_or_string) end end # Produces the root directory of a gem given as an uri, where hostname is the gemname, and an optional # path is appended to the root of the gem (i.e. if the reference is given to a sub-location within a gem. # TODO: FIND by name raises exception Gem::LoadError with list of all gems on the path # def gem_dir_from_uri(uri) spec = Gem::Specification.find_by_name(uri.hostname) unless spec raise ArgumentError, _("Gem not found %{uri}") % { uri: uri } end # if path given append that, else append given subdir if uri.path.empty? spec.gem_dir else File.join(spec.full_gem_path, uri.path) end end # Produces the root directory of a gem given as a string with the gem's name. # TODO: FIND by name raises exception Gem::LoadError with list of all gems on the path # def gem_dir_from_name(gem_name) spec = Gem::Specification.find_by_name(gem_name) unless spec raise ArgumentError, _("Gem not found '%{gem_name}'") % { gem_name: gem_name } end spec.full_gem_path end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false